feat(compliance): per-target CRA Annex I status (#283) #354

Merged
sharang merged 1 commits from feat/compliance-view into main 2026-09-23 16:03:24 +00:00
12 changed files with 548 additions and 15 deletions

No files matched your search

+54 -15
View File
@@ -5,27 +5,24 @@
use axum::extract::{Extension, Path};
use axum::http::{header, HeaderValue, StatusCode};
use axum::response::IntoResponse;
use axum::Json;
use mongodb::bson::{doc, oid::ObjectId};
use compliance_core::tenant_ctx::TenantCtx;
use super::dto::{collect_cursor_async, tenant_db, AgentExt};
use super::sbom::MAX_EXPORT_COMPONENTS;
use crate::evidence::{build_pack, EvidenceInputs};
use crate::database::Database;
use crate::evidence::compliance::ControlState;
use crate::evidence::{build_pack, compliance_of, EvidenceInputs};
/// Most findings one pack is built from in memory.
const MAX_PACK_FINDINGS: u64 = 50_000;
/// GET /api/v1/targets/{id}/evidence-pack — 404 for an unknown target, 413
/// when it is too large to build in memory.
#[tracing::instrument(skip_all, fields(target_id = %id))]
pub async fn evidence_pack(
Extension(agent): AgentExt,
tenant: TenantCtx,
Path(id): Path<String>,
) -> Result<impl IntoResponse, StatusCode> {
let oid = ObjectId::parse_str(&id).map_err(|_| StatusCode::BAD_REQUEST)?;
let db = tenant_db(&agent, &tenant).await?;
/// Everything stored about target `id`: 404 for an unknown target, 413 when it
/// is too large to build in memory.
async fn load_inputs(db: &Database, id: &str) -> Result<EvidenceInputs, StatusCode> {
let oid = ObjectId::parse_str(id).map_err(|_| StatusCode::BAD_REQUEST)?;
let target = db
.onboarded_targets()
.find_one(doc! { "_id": oid })
@@ -33,7 +30,7 @@ pub async fn evidence_pack(
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?
.ok_or(StatusCode::NOT_FOUND)?;
let by_target = doc! { "repo_id": &id };
let by_target = doc! { "repo_id": id };
let findings_count = db
.findings()
.count_documents(by_target.clone())
@@ -49,10 +46,10 @@ pub async fn evidence_pack(
}
let load_err = |e: mongodb::error::Error| {
tracing::warn!("evidence pack: {e}");
tracing::warn!("evidence: {e}");
StatusCode::INTERNAL_SERVER_ERROR
};
let inputs = EvidenceInputs {
Ok(EvidenceInputs {
findings: collect_cursor_async(
db.findings()
.find(by_target.clone())
@@ -81,7 +78,49 @@ pub async fn evidence_pack(
.await
.map_err(load_err)?,
target,
};
})
}
/// GET /api/v1/targets/{id}/compliance — the target's state against every CRA
/// Annex I control, with the findings against each and the last scan.
#[tracing::instrument(skip_all, fields(target_id = %id))]
pub async fn compliance_view(
Extension(agent): AgentExt,
tenant: TenantCtx,
Path(id): Path<String>,
) -> Result<Json<serde_json::Value>, StatusCode> {
let db = tenant_db(&agent, &tenant).await?;
let inputs = load_inputs(&db, &id).await?;
let controls = compliance_of(&inputs);
let count = |state: ControlState| controls.iter().filter(|c| c.state == state).count();
Ok(Json(serde_json::json!({
"data": {
"target_id": id,
"target_name": inputs.target.name,
"counts": {
"not_satisfied": count(ControlState::NotSatisfied),
"no_violation_found": count(ControlState::NoViolationFound),
"not_assessed": count(ControlState::NotAssessed),
"not_code_checkable": count(ControlState::NotCodeCheckable),
},
"last_scan": inputs.last_run,
"sbom_components": inputs.sbom.len(),
"cve_alerts": inputs.cves.len(),
"controls": controls,
}
})))
}
/// GET /api/v1/targets/{id}/evidence-pack — 404 for an unknown target, 413
/// when it is too large to build in memory.
#[tracing::instrument(skip_all, fields(target_id = %id))]
pub async fn evidence_pack(
Extension(agent): AgentExt,
tenant: TenantCtx,
Path(id): Path<String>,
) -> Result<impl IntoResponse, StatusCode> {
let db = tenant_db(&agent, &tenant).await?;
let inputs = load_inputs(&db, &id).await?;
let now = chrono::Utc::now();
let (zip, _files) = tokio::task::spawn_blocking(move || build_pack(&inputs, now))
+4
View File
@@ -74,6 +74,10 @@ pub fn build_router() -> Router {
"/api/v1/targets/{id}/evidence-pack",
get(handlers::evidence::evidence_pack),
)
.route(
"/api/v1/targets/{id}/compliance",
get(handlers::evidence::compliance_view),
)
// Findings from a manual DAST run or penetration test.
.route(
"/api/v1/targets/{id}/findings",
+188
View File
@@ -0,0 +1,188 @@
//! Where a target stands against each CRA Annex I requirement (#283).
//!
//! Every control of the map gets exactly one state, so nothing is silently
//! missing: violated (with the findings that say so), no violation found,
//! not assessed yet, or not checkable in code at all (a design property,
//! which the breakpilot-compliance process covers).
use serde::Serialize;
use compliance_core::models::{Finding, FindingStatus};
use control_map::{ControlMap, Coverage};
/// A control's state for one target.
#[derive(Debug, Clone, Copy, Serialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum ControlState {
/// Open findings are evidence against it.
NotSatisfied,
/// Checkable in code, scanned, and nothing is against it.
NoViolationFound,
/// Checkable in code, but no scan has completed yet, or no tool checks it.
NotAssessed,
/// A design property no code scan can decide (breakpilot-compliance).
NotCodeCheckable,
}
/// A finding as the compliance view lists it.
#[derive(Debug, Clone, Serialize, PartialEq)]
pub struct FindingRef {
pub id: String,
pub title: String,
pub severity: String,
pub status: String,
pub location: Option<String>,
}
/// One control and the target's state against it.
#[derive(Debug, Clone, Serialize, PartialEq)]
pub struct ControlStatus {
pub control: String,
pub title: String,
pub state: ControlState,
/// Why a control is not code-checkable, from the map.
pub note: Option<String>,
pub findings: Vec<FindingRef>,
}
/// Whether a finding still counts against its controls: a false positive
/// and a resolved finding do not; an accepted risk still does.
fn counts(finding: &Finding) -> bool {
!matches!(
finding.status,
FindingStatus::FalsePositive | FindingStatus::Resolved
)
}
/// The state of every control in `map` for a target with `findings`.
/// `scanned` is whether a scan of the target has completed.
pub fn control_statuses(
map: &ControlMap,
findings: &[Finding],
scanned: bool,
) -> Vec<ControlStatus> {
map.controls
.iter()
.map(|entry| {
let against: Vec<FindingRef> = findings
.iter()
.filter(|f| counts(f) && f.control_refs.contains(&entry.control))
.map(|f| FindingRef {
id: f.id.map(|id| id.to_hex()).unwrap_or_default(),
title: f.title.clone(),
severity: f.severity.to_string(),
status: f.status.to_string(),
location: match (&f.file_path, f.line_number) {
(Some(file), Some(line)) => Some(format!("{file}:{line}")),
(Some(file), None) => Some(file.clone()),
_ => None,
},
})
.collect();
let state = if !against.is_empty() {
ControlState::NotSatisfied
} else {
match entry.status {
Coverage::NotCodeCheckable => ControlState::NotCodeCheckable,
Coverage::Covered if scanned => ControlState::NoViolationFound,
// Unscanned, or checkable in code but with no tool for it
// yet: nothing can be said either way.
Coverage::Covered | Coverage::NeedsTooling => ControlState::NotAssessed,
}
};
ControlStatus {
control: entry.control.clone(),
title: entry.title.clone(),
state,
note: entry.note.clone(),
findings: against,
}
})
.collect()
}
#[cfg(test)]
#[allow(clippy::expect_used)]
mod tests {
use super::*;
use compliance_core::models::{ScanType, Severity};
fn finding(control: &str, status: FindingStatus) -> Finding {
let mut f = Finding::new(
"t".into(),
format!("fp-{control}-{status}"),
"semgrep".into(),
ScanType::Sast,
"Hard-coded credential".into(),
"d".into(),
Severity::High,
);
f.control_refs = vec![control.into()];
f.file_path = Some("Core/Src/comms.c".into());
f.line_number = Some(9);
f.status = status;
f
}
fn state_of(statuses: &[ControlStatus], control: &str) -> ControlState {
statuses
.iter()
.find(|s| s.control == control)
.map(|s| s.state)
.expect("every control is listed")
}
#[test]
fn every_control_gets_exactly_one_state() {
let map = ControlMap::cra().expect("map");
let statuses = control_statuses(&map, &[], true);
assert_eq!(statuses.len(), map.controls.len());
assert_eq!(
state_of(&statuses, "cra-ai-8"),
ControlState::NoViolationFound
);
assert_eq!(
state_of(&statuses, "cra-ai-2"),
ControlState::NotCodeCheckable
);
}
#[test]
fn open_findings_violate_and_closed_ones_do_not() {
let map = ControlMap::cra().expect("map");
let findings = [
finding("cra-ai-8", FindingStatus::AcceptedRisk),
finding("cra-ai-13", FindingStatus::FalsePositive),
finding("cra-ai-16", FindingStatus::Resolved),
];
let statuses = control_statuses(&map, &findings, true);
assert_eq!(state_of(&statuses, "cra-ai-8"), ControlState::NotSatisfied);
assert_eq!(
state_of(&statuses, "cra-ai-13"),
ControlState::NoViolationFound
);
assert_eq!(
state_of(&statuses, "cra-ai-16"),
ControlState::NoViolationFound
);
let violated = statuses
.iter()
.find(|s| s.control == "cra-ai-8")
.expect("listed");
assert_eq!(
violated.findings[0].location.as_deref(),
Some("Core/Src/comms.c:9")
);
assert_eq!(violated.findings[0].status, "accepted_risk");
}
#[test]
fn nothing_is_passed_before_a_scan() {
let map = ControlMap::cra().expect("map");
let statuses = control_statuses(&map, &[], false);
assert_eq!(state_of(&statuses, "cra-ai-8"), ControlState::NotAssessed);
assert!(statuses
.iter()
.all(|s| s.state != ControlState::NoViolationFound));
}
}
+20
View File
@@ -7,6 +7,8 @@
//! hash of the control catalog that produced the CRA mapping, so a report
//! built from the pack can say exactly what it rests on.
pub mod compliance;
use std::io::Write;
use chrono::{DateTime, Utc};
@@ -81,6 +83,7 @@ pub fn build_pack(
("findings.json", json(&inputs.findings)?),
("findings.csv", findings_csv(&inputs.findings).into_bytes()),
("cve-alerts.json", json(&inputs.cves)?),
("cra-compliance.json", json(&compliance_of(inputs))?),
];
let listed: Vec<ManifestFile> = files
.iter()
@@ -147,6 +150,22 @@ pub fn build_pack(
Ok((archive, manifest.files))
}
/// Whether a scan of the target has completed, so a control without
/// findings can be called free of violations.
pub fn scanned(inputs: &EvidenceInputs) -> bool {
inputs
.last_run
.as_ref()
.is_some_and(|run| run.completed_at.is_some())
}
/// The target's state against every CRA Annex I control.
pub fn compliance_of(inputs: &EvidenceInputs) -> Vec<compliance::ControlStatus> {
control_map::ControlMap::cra()
.map(|map| compliance::control_statuses(&map, &inputs.findings, scanned(inputs)))
.unwrap_or_default()
}
/// `value` as pretty-printed JSON.
fn json<T: Serialize>(value: &T) -> Result<Vec<u8>, AgentError> {
serde_json::to_vec_pretty(value).map_err(|e| AgentError::Other(e.to_string()))
@@ -242,6 +261,7 @@ mod tests {
assert_eq!(
names,
[
"cra-compliance.json",
"cve-alerts.json",
"findings.csv",
"findings.json",
+19
View File
@@ -71,5 +71,24 @@ async fn a_target_s_evidence_pack_holds_its_findings_and_hashes() {
assert!(read("findings.csv").contains("tcp://192.0.2.10:23"));
assert_eq!(missing.status().as_u16(), 404);
// The compliance view: every control listed; the credential finding
// violates cra-ai-8; never scanned, so nothing else counts as passed.
let view: serde_json::Value = server
.get(&format!("/api/v1/targets/{id}/compliance"))
.await
.json()
.await
.unwrap();
let controls = view["data"]["controls"].as_array().unwrap();
assert_eq!(controls.len(), 40);
let cra8 = controls
.iter()
.find(|c| c["control"] == "cra-ai-8")
.unwrap();
assert_eq!(cra8["state"], "not_satisfied");
assert_eq!(cra8["findings"][0]["location"], "tcp://192.0.2.10:23");
assert_eq!(view["data"]["counts"]["no_violation_found"], 0);
assert_eq!(view["data"]["counts"]["not_code_checkable"], 19);
server.cleanup().await;
}
+2
View File
@@ -12,6 +12,8 @@ pub enum Route {
OverviewPage {},
#[route("/targets")]
TargetsPage {},
#[route("/targets/:id/compliance")]
CompliancePage { id: String },
#[route("/onboard")]
OnboardingPage {},
// `?target=<id>` opens the list filtered to one target.
@@ -109,6 +109,7 @@ pub fn Sidebar() -> Element {
{
let is_active = match (&current_route, &item.route) {
(Route::FindingDetailPage { .. } | Route::FindingsPage { .. }, Route::FindingsPage { .. }) => true,
(Route::CompliancePage { .. }, Route::TargetsPage {}) => true,
(Route::DastTargetsPage {}, Route::DastOverviewPage {}) => true,
(Route::DastFindingsPage {}, Route::DastOverviewPage {}) => true,
(Route::DastFindingDetailPage { .. }, Route::DastOverviewPage {}) => true,
+70
View File
@@ -1587,3 +1587,73 @@ pub mod manual {
en: "Working...",
};
}
/// The CRA compliance view of a target.
pub mod compliance {
use super::Text;
pub const TITLE: Text = Text {
de: "CRA-Status",
en: "CRA status",
};
pub const SUBTITLE: Text = Text {
de: "Stand gegen die grundlegenden Anforderungen des Cyber Resilience Act (Anhang I)",
en: "Standing against the Cyber Resilience Act's essential requirements (Annex I)",
};
pub const OPEN: Text = Text {
de: "CRA-Status anzeigen",
en: "Show CRA status",
};
pub const NOT_SATISFIED: Text = Text {
de: "Nicht erfüllt",
en: "Not satisfied",
};
pub const NO_VIOLATION: Text = Text {
de: "Kein Verstoß gefunden",
en: "No violation found",
};
pub const NOT_ASSESSED: Text = Text {
de: "Noch nicht bewertet",
en: "Not assessed yet",
};
pub const NOT_CODE_CHECKABLE: Text = Text {
de: "Nicht im Code prüfbar",
en: "Not checkable in code",
};
pub const NOT_CODE_CHECKABLE_HINT: Text = Text {
de: "Eigenschaft des Designs oder Prozesses; wird im breakpilot-Compliance-Prozess nachgewiesen.",
en: "A design or process property; evidenced in the breakpilot compliance process.",
};
pub const NOT_ASSESSED_HINT: Text = Text {
de: "Noch keine abgeschlossene Prüfung. Nach der ersten Prüfung steht hier das Ergebnis.",
en: "No scan has completed yet. The result appears after the first scan.",
};
pub const CONTROL: Text = Text {
de: "Anforderung",
en: "Requirement",
};
pub const STATE: Text = Text {
de: "Stand",
en: "State",
};
pub const EVIDENCE: Text = Text {
de: "Befunde",
en: "Findings",
};
pub const DEPENDENCIES: Text = Text {
de: "Komponenten (SBOM)",
en: "Components (SBOM)",
};
pub const CVES: Text = Text {
de: "CVE-Warnungen",
en: "CVE alerts",
};
pub const LAST_SCAN: Text = Text {
de: "Letzte Prüfung",
en: "Last scan",
};
pub const LOAD_FAILED: Text = Text {
de: "Der CRA-Status konnte nicht geladen werden.",
en: "The CRA status could not be loaded.",
};
}
@@ -33,6 +33,19 @@ pub async fn download_evidence_pack(
))
}
/// The target's state against every CRA Annex I control
/// (`GET /api/v1/targets/{id}/compliance`), as the agent sends it.
#[server]
pub async fn fetch_compliance(id: String) -> Result<serde_json::Value, ServerFnError> {
let resp = super::agent_client::agent_get(&format!("/api/v1/targets/{id}/compliance"))
.await?
.send()
.await
.map_err(|e| ServerFnError::new(e.to_string()))?;
let body: serde_json::Value = super::agent_client::json_or_error(resp).await?;
Ok(body["data"].clone())
}
#[cfg(test)]
mod tests {
use super::*;
@@ -0,0 +1,170 @@
//! A target's standing against the CRA Annex I requirements: every control
//! with one state, the findings against the violated ones, and what the
//! evidence rests on (SBOM, CVE alerts, the last scan).
use dioxus::prelude::*;
use crate::app::Route;
use crate::components::page_header::PageHeader;
use crate::components::stat_card::StatCard;
use crate::i18n::texts::{common, compliance as tx, findings as ftx, targets as ttx};
use crate::i18n::{use_lang, Text};
use crate::infrastructure::evidence::{evidence_pack_url, fetch_compliance};
/// The label and badge of a control state, in the order the page lists them.
const STATES: [(&str, Text, &str); 4] = [
("not_satisfied", tx::NOT_SATISFIED, "badge badge-critical"),
("not_assessed", tx::NOT_ASSESSED, "badge badge-medium"),
(
"no_violation_found",
tx::NO_VIOLATION,
"badge badge-success",
),
(
"not_code_checkable",
tx::NOT_CODE_CHECKABLE,
"badge badge-neutral",
),
];
/// Where a state sorts, and how it is shown; an unknown state sorts last and
/// shows as it is.
fn state_info(state: &str) -> (usize, Option<(Text, &'static str)>) {
STATES
.iter()
.position(|(s, _, _)| *s == state)
.map_or((STATES.len(), None), |i| {
(i, Some((STATES[i].1, STATES[i].2)))
})
}
#[component]
pub fn CompliancePage(id: String) -> Element {
let lang = use_lang()();
let target_id = use_signal(|| id.clone());
let view = use_resource(move || async move { fetch_compliance(target_id()).await.ok() });
let snapshot = view.read().clone();
let Some(loaded) = snapshot else {
return rsx! { div { class: "loading", {common::LOADING.get(lang)} } };
};
let Some(data) = loaded else {
return rsx! { div { class: "card", p { {tx::LOAD_FAILED.get(lang)} } } };
};
let name = data["target_name"].as_str().unwrap_or_default().to_string();
let count = |key: &str| data["counts"][key].as_u64().unwrap_or(0).to_string();
let mut controls: Vec<serde_json::Value> =
data["controls"].as_array().cloned().unwrap_or_default();
controls.sort_by_key(|c| state_info(c["state"].as_str().unwrap_or_default()).0);
// The last scan's status in words, as on the targets page.
let last_scan = serde_json::from_value::<compliance_core::models::ScanRunStatus>(
data["last_scan"]["status"].clone(),
)
.ok()
.map(|s| crate::components::scan_runs::status_badge(&s).1.get(lang));
rsx! {
PageHeader {
title: format!("{} · {name}", tx::TITLE.get(lang)),
description: tx::SUBTITLE.get(lang),
}
div { style: "margin-bottom: 16px; display: flex; gap: 8px; flex-wrap: wrap;",
Link { to: Route::TargetsPage {}, class: "btn btn-secondary", "← {ttx::TITLE.get(lang)}" }
a { class: "btn btn-secondary", href: evidence_pack_url(&id), download: "",
{ttx::EVIDENCE_PACK.get(lang)}
}
}
div { class: "stat-cards",
StatCard { label: tx::NOT_SATISFIED.get(lang), value: count("not_satisfied"), color: "var(--danger)" }
StatCard { label: tx::NOT_ASSESSED.get(lang), value: count("not_assessed"), color: "var(--warning)" }
StatCard { label: tx::NO_VIOLATION.get(lang), value: count("no_violation_found"), color: "var(--success)" }
StatCard { label: tx::NOT_CODE_CHECKABLE.get(lang), value: count("not_code_checkable") }
StatCard { label: tx::DEPENDENCIES.get(lang), value: data["sbom_components"].to_string() }
StatCard { label: tx::CVES.get(lang), value: data["cve_alerts"].to_string() }
}
if let Some(status) = last_scan {
p { style: "opacity: 0.75; font-size: 0.9em;", "{tx::LAST_SCAN.get(lang)}: {status}" }
} else {
p { style: "opacity: 0.75; font-size: 0.9em;", {tx::NOT_ASSESSED_HINT.get(lang)} }
}
div { class: "card",
div { class: "table-wrapper",
table {
thead {
tr {
th { {tx::CONTROL.get(lang)} }
th { {tx::STATE.get(lang)} }
th { {tx::EVIDENCE.get(lang)} }
}
}
tbody {
for control in controls {
{
let state = control["state"].as_str().unwrap_or_default().to_string();
let shown = state_info(&state).1;
let findings = control["findings"].as_array().cloned().unwrap_or_default();
let note = control["note"].as_str().map(String::from);
rsx! {
tr {
td {
div { style: "font-family: monospace; font-size: 0.85em; opacity: 0.7;", "{control[\"control\"].as_str().unwrap_or_default()}" }
div { "{control[\"title\"].as_str().unwrap_or_default()}" }
}
td {
match shown {
Some((label, badge)) => rsx! { span { class: "{badge}", {label.get(lang)} } },
None => rsx! { span { "{state}" } },
}
}
td { style: "font-size: 0.9em;",
if state == "not_code_checkable" {
div { style: "opacity: 0.75;", {tx::NOT_CODE_CHECKABLE_HINT.get(lang)} }
if let Some(note) = note {
div { style: "opacity: 0.6; font-size: 0.9em;", "{note}" }
}
}
for f in findings {
{
let fid = f["id"].as_str().unwrap_or_default().to_string();
let status = f["status"].as_str().unwrap_or_default().to_string();
let status_label = serde_json::from_value::<compliance_core::models::FindingStatus>(
serde_json::Value::String(status.clone()),
)
.map_or(status.clone(), |s| ftx::status(&s).get(lang).to_string());
rsx! {
div { style: "margin-bottom: 4px;",
Link { to: Route::FindingDetailPage { id: fid }, "{f[\"title\"].as_str().unwrap_or_default()}" }
if let Some(loc) = f["location"].as_str() {
span { style: "font-family: monospace; opacity: 0.75;", " · {loc}" }
}
span { style: "opacity: 0.6;", " · {status_label}" }
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn violated_controls_come_first() {
assert!(state_info("not_satisfied").0 < state_info("no_violation_found").0);
assert_eq!(state_info("brand_new").0, STATES.len());
assert!(state_info("brand_new").1.is_none());
}
}
+2
View File
@@ -1,5 +1,6 @@
pub mod chat;
pub mod chat_index;
pub mod compliance;
pub mod dast_finding_detail;
pub mod dast_findings;
pub mod dast_overview;
@@ -21,6 +22,7 @@ pub mod targets;
pub use chat::ChatPage;
pub use chat_index::ChatIndexPage;
pub use compliance::CompliancePage;
pub use dast_finding_detail::DastFindingDetailPage;
pub use dast_findings::DastFindingsPage;
pub use dast_overview::DastOverviewPage;
@@ -559,6 +559,11 @@ pub fn TargetsPage() -> Element {
td { colspan: "6",
div { style: "padding: 12px 8px;",
div { style: "margin-bottom: 12px; display: flex; gap: 8px; align-items: center; flex-wrap: wrap;",
Link {
to: crate::app::Route::CompliancePage { id: id.clone() },
class: "btn btn-primary",
{crate::i18n::texts::compliance::OPEN.get(lang)}
}
a {
class: "btn btn-secondary",
href: crate::infrastructure::evidence::evidence_pack_url(&id),