fix(dashboard): help assistant signs in, scan list follows a started scan, catalog controls readable #423

Merged
sharang merged 1 commits from feat/catalog-controls into main 2026-09-28 21:59:08 +00:00
11 changed files with 281 additions and 33 deletions

No files matched your search

+31 -1
View File
@@ -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<ControlIdsQuery>,
) -> Json<serde_json::Value> {
let ids: Vec<String> = 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 }))
}
+4
View File
@@ -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",
+109
View File
@@ -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<HashMap<String, ControlSummary>> = 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<ControlSummary> {
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<String, ControlSummary> {
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(),
})
);
}
}
+2
View File
@@ -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,
+1 -1
View File
@@ -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<OscalControlsProvider> {
pub(super) fn provider_for(config: &AgentConfig) -> Option<OscalControlsProvider> {
let snapshot_dir = Path::new(&config.breakpilot.snapshot_dir);
if config.breakpilot.base_url.is_none() && !OscalControlsProvider::has_snapshots(snapshot_dir) {
return None;
+14
View File
@@ -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;
}
@@ -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<Signal<u32>>) -> 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::<String>::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();
}
@@ -72,6 +72,32 @@ pub async fn fetch_compliance_summary() -> Result<Vec<ComplianceSummaryRow>, 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<String>,
) -> Result<Vec<CatalogControl>, 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]
@@ -28,17 +28,11 @@ pub async fn send_help_chat_message(
message: String,
history: Vec<HelpChatHistoryMessage>,
) -> Result<HelpChatApiResponse, ServerFnError> {
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)
}
@@ -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<String>) -> 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<CatalogControl> = 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}" }
}
}
}
}
}
}
}
+6 -2
View File
@@ -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)} } }