diff --git a/compliance-agent/src/api/handlers/dto.rs b/compliance-agent/src/api/handlers/dto.rs index 6fd34ed..198248c 100644 --- a/compliance-agent/src/api/handlers/dto.rs +++ b/compliance-agent/src/api/handlers/dto.rs @@ -69,6 +69,10 @@ pub struct FindingsFilter { /// groups listing a place in it. #[serde(default)] pub variant: Option, + /// Only the findings in one folder, as the folder chart names it + /// ([`path_regex`]). + #[serde(default)] + pub path: Option, #[serde(default)] pub sort_by: Option, #[serde(default)] @@ -136,6 +140,35 @@ pub fn literal_regex(term: &str) -> String { out } +/// The `file_path` regex of a folder filter, anchored and literal; `None` +/// for an empty filter. +/// +/// The keys are those of the folder chart +/// ([`compliance_core::finding_breakdown::FolderBreakdown::path`]): +/// `/` is the files in the root, `src/*` the files directly in `src`, and +/// `src/` (or `src`) everything below `src`. A leading `/` on a stored path +/// is allowed, as the chart ignores it too. +pub fn path_regex(folder: &str) -> Option { + use compliance_core::finding_breakdown::{DIRECT_SUFFIX, ROOT_FOLDER}; + let folder = folder.trim(); + if folder.is_empty() { + return None; + } + if folder == ROOT_FOLDER { + return Some("^/?[^/]+$".to_string()); + } + let (dir, direct) = match folder.strip_suffix(DIRECT_SUFFIX) { + Some(dir) => (dir, true), + None => (folder, false), + }; + let dir = literal_regex(dir.trim_matches('/')); + Some(if direct { + format!("^/?{dir}/[^/]+$") + } else { + format!("^/?{dir}/") + }) +} + #[derive(Serialize)] pub struct ApiResponse { pub data: T, @@ -412,6 +445,41 @@ mod tests { assert_eq!(literal_regex(&long).len(), MAX_SEARCH_LEN); } + #[test] + fn folder_filters_are_anchored_literal_regexes() { + let matches = |folder: &str, path: &str| { + let re = regex::Regex::new(&path_regex(folder).expect("a filter")).expect("valid"); + re.is_match(path) + }; + assert_eq!(path_regex(""), None); + assert_eq!(path_regex(" "), None); + // Everything below a folder, with or without the trailing slash. + assert!(matches("src/", "src/api/a.rs")); + assert!(matches("src", "src/a.rs")); + assert!(!matches("src/", "srcfoo/a.rs")); + assert!(!matches("src/", "lib/src/a.rs")); + assert!(matches("src/api/", "/src/api/a.rs")); + // Only the files directly in a folder. + assert!(matches("src/*", "src/main.rs")); + assert!(!matches("src/*", "src/api/a.rs")); + // The root. + assert!(matches("/", "README.md")); + assert!(matches("/", "/Cargo.toml")); + assert!(!matches("/", "src/main.rs")); + // Metacharacters in a folder name are literal. + assert_eq!(path_regex("a.b/").as_deref(), Some(r"^/?a\.b/")); + assert!(!matches("a.b/", "axb/c.rs")); + assert!(matches("(x)/", "(x)/y.rs")); + } + + #[test] + fn the_findings_filter_takes_a_folder() { + let f: FindingsFilter = serde_json::from_str(r#"{"path":"src/*"}"#).unwrap(); + assert_eq!(f.path.as_deref(), Some("src/*")); + let f: FindingsFilter = serde_json::from_str("{}").unwrap(); + assert_eq!(f.path, None); + } + #[test] fn sbom_filter_clamps_the_same_way() { let f: SbomFilter = serde_json::from_str(r#"{"limit":10000000,"page":0}"#).unwrap(); diff --git a/compliance-agent/src/api/handlers/finding_breakdown.rs b/compliance-agent/src/api/handlers/finding_breakdown.rs new file mode 100644 index 0000000..86ee76a --- /dev/null +++ b/compliance-agent/src/api/handlers/finding_breakdown.rs @@ -0,0 +1,70 @@ +//! `GET /api/v1/targets/{id}/finding-breakdown`: a target's open findings +//! by type and severity, and by folder, for the charts of its findings view +//! (#957). + +use axum::extract::{Extension, Path}; +use mongodb::bson::doc; + +use compliance_core::finding_breakdown::{ + breakdown, BreakdownRow, FindingBreakdown, OPEN_STATUSES, +}; +use compliance_core::tenant_ctx::TenantCtx; + +use super::dto::{collect_cursor_async, tenant_db, AgentExt, ApiResponse, ApiResult}; + +/// The Mongo filter of a target's open (undecided) findings. +fn open_findings_of(target_id: &str) -> mongodb::bson::Document { + let open: Vec = OPEN_STATUSES.iter().map(ToString::to_string).collect(); + doc! { "repo_id": target_id, "status": { "$in": open } } +} + +/// The open findings of target `id`, counted by type and severity and by +/// folder. Tenant-scoped like the findings list, and read-only, so every +/// role that may read findings may read it. A target without open findings +/// (or of another tenant, whose findings are not in this tenant's database) +/// gets an empty breakdown. +#[tracing::instrument(skip_all, fields(target_id = %id))] +pub async fn finding_breakdown( + Extension(agent): AgentExt, + tenant: TenantCtx, + Path(id): Path, +) -> ApiResult { + let db = tenant_db(&agent, &tenant).await?; + // Only the three fields the counts need cross the wire. + let rows: Vec = match db + .findings() + .clone_with_type::() + .find(open_findings_of(&id)) + .projection(doc! { "_id": 0, "scan_type": 1, "severity": 1, "file_path": 1 }) + .await + { + // A document that does not read is skipped (and logged), not fatal. + Ok(cursor) => collect_cursor_async(cursor).await, + Err(e) => { + tracing::warn!("open findings for the breakdown not read: {e}"); + Vec::new() + } + }; + let result = breakdown(&rows); + Ok(axum::Json(ApiResponse { + total: Some(result.total), + data: result, + page: None, + })) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn only_the_targets_undecided_findings_are_counted() { + assert_eq!( + open_findings_of("t1"), + doc! { + "repo_id": "t1", + "status": { "$in": ["open", "triaged", "needs_review"] }, + } + ); + } +} diff --git a/compliance-agent/src/api/handlers/findings.rs b/compliance-agent/src/api/handlers/findings.rs index 573ce59..1e02189 100644 --- a/compliance-agent/src/api/handlers/findings.rs +++ b/compliance-agent/src/api/handlers/findings.rs @@ -29,7 +29,10 @@ pub async fn list_findings( query.insert("scan_type", scan_type); } if let Some(status) = &filter.status { - query.insert("status", status); + query.insert("status", status_filter(status)); + } + if let Some(regex) = filter.path.as_deref().and_then(path_regex) { + query.insert("file_path", doc! { "$regex": regex }); } // Text search across title, description, file_path, rule_id if let Some(q) = &filter.q { @@ -109,6 +112,18 @@ pub async fn list_findings( })) } +/// The match of a `status` filter: one status, or all undecided ones for +/// [`compliance_core::finding_breakdown::OPEN_STATUS_FILTER`]. +fn status_filter(status: &str) -> mongodb::bson::Bson { + use compliance_core::finding_breakdown::{OPEN_STATUSES, OPEN_STATUS_FILTER}; + if status == OPEN_STATUS_FILTER { + let open: Vec = OPEN_STATUSES.iter().map(ToString::to_string).collect(); + mongodb::bson::Bson::Document(doc! { "$in": open }) + } else { + mongodb::bson::Bson::String(status.to_string()) + } +} + /// The temporary field the severity sort ranks on. const SEVERITY_RANK: &str = "_severity_rank"; @@ -342,6 +357,18 @@ pub async fn update_finding_feedback( mod tests { use super::*; + #[test] + fn the_undecided_filter_matches_every_open_status() { + assert_eq!( + status_filter("undecided"), + mongodb::bson::Bson::Document(doc! { "$in": ["open", "triaged", "needs_review"] }) + ); + assert_eq!( + status_filter("resolved"), + mongodb::bson::Bson::String("resolved".into()) + ); + } + #[test] fn an_accepted_risk_needs_a_reason() { assert_eq!( diff --git a/compliance-agent/src/api/handlers/mod.rs b/compliance-agent/src/api/handlers/mod.rs index 344bdc5..8bd9971 100644 --- a/compliance-agent/src/api/handlers/mod.rs +++ b/compliance-agent/src/api/handlers/mod.rs @@ -4,6 +4,7 @@ pub mod dast; pub mod demo_seed; pub mod dto; pub mod evidence; +pub mod finding_breakdown; pub mod findings; pub mod git_source; pub mod graph; diff --git a/compliance-agent/src/api/role_gate/router_tests.rs b/compliance-agent/src/api/role_gate/router_tests.rs index bb63086..c22e6e0 100644 --- a/compliance-agent/src/api/role_gate/router_tests.rs +++ b/compliance-agent/src/api/role_gate/router_tests.rs @@ -142,6 +142,11 @@ fn routes() -> Vec<(Method, String, bool)> { format!("/api/v1/targets/{ID}/evidence-pack"), false, ), + ( + Method::GET, + format!("/api/v1/targets/{ID}/finding-breakdown"), + false, + ), (Method::GET, "/api/v1/sbom/export".into(), false), (Method::GET, "/api/v1/licenses/conclusions".into(), false), (Method::PUT, "/api/v1/licenses/conclusions".into(), true), diff --git a/compliance-agent/src/api/routes.rs b/compliance-agent/src/api/routes.rs index e4c4357..2de9021 100644 --- a/compliance-agent/src/api/routes.rs +++ b/compliance-agent/src/api/routes.rs @@ -125,6 +125,10 @@ pub fn build_router() -> Router { "/api/v1/targets/{id}/compliance", get(handlers::evidence::compliance_view), ) + .route( + "/api/v1/targets/{id}/finding-breakdown", + get(handlers::finding_breakdown::finding_breakdown), + ) .route( "/api/v1/compliance/summary", get(handlers::evidence::compliance_summary), diff --git a/compliance-core/src/finding_breakdown.rs b/compliance-core/src/finding_breakdown.rs new file mode 100644 index 0000000..ec89659 --- /dev/null +++ b/compliance-core/src/finding_breakdown.rs @@ -0,0 +1,434 @@ +//! A target's open findings counted for the charts of its findings view +//! (#957): by finding type and severity, and by folder. +//! +//! "Open" is undecided: [`OPEN_STATUSES`], the statuses a finding still gets +//! a tracker issue at (`pipeline::issue_creation::ISSUE_STATUSES` in the +//! agent). Resolved, false positives, accepted risks and ignored findings are +//! decided and left out. +//! +//! The agent computes a [`FindingBreakdown`] with [`breakdown`] over the open +//! findings' type, severity and path; the dashboard reads the same type. + +use serde::{Deserialize, Serialize}; + +use crate::models::{FindingStatus, ScanType, Severity}; + +/// The statuses of findings nobody has decided about yet. +pub const OPEN_STATUSES: [FindingStatus; 3] = [ + FindingStatus::Open, + FindingStatus::Triaged, + FindingStatus::NeedsReview, +]; + +/// The findings list's `status` filter for all of [`OPEN_STATUSES`], so the +/// list behind a chart shows the findings the chart counts. +pub const OPEN_STATUS_FILTER: &str = "undecided"; + +/// Every severity, most severe first: the order of the stacked segments and +/// the legend. +pub const SEVERITIES: [Severity; 5] = [ + Severity::Critical, + Severity::High, + Severity::Medium, + Severity::Low, + Severity::Info, +]; + +/// The folder key of the findings in the root of the tree (no directory). +pub const ROOT_FOLDER: &str = "/"; + +/// The suffix of a folder key that means "only the files directly in it" +/// (`src/*`), next to `src/` meaning everything below `src`. +pub const DIRECT_SUFFIX: &str = "*"; + +/// The fields of an open finding the breakdown reads (the agent projects +/// the findings to these). +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct BreakdownRow { + /// The finding type, as the findings list filters by it. + pub scan_type: ScanType, + pub severity: Severity, + /// The file the finding is in, relative to the tree; `None` for findings + /// in no file (a CVE in a dependency, a DAST endpoint). + #[serde(default)] + pub file_path: Option, +} + +/// How many findings there are of each severity. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct SeverityCounts { + pub critical: u64, + pub high: u64, + pub medium: u64, + pub low: u64, + pub info: u64, +} + +impl SeverityCounts { + /// The count of `severity`. + pub fn get(&self, severity: &Severity) -> u64 { + match severity { + Severity::Critical => self.critical, + Severity::High => self.high, + Severity::Medium => self.medium, + Severity::Low => self.low, + Severity::Info => self.info, + } + } + + /// Counts one more finding of `severity`. + pub fn add(&mut self, severity: &Severity) { + let count = match severity { + Severity::Critical => &mut self.critical, + Severity::High => &mut self.high, + Severity::Medium => &mut self.medium, + Severity::Low => &mut self.low, + Severity::Info => &mut self.info, + }; + *count += 1; + } + + /// All findings, of any severity. + pub fn total(&self) -> u64 { + self.critical + self.high + self.medium + self.low + self.info + } +} + +/// The open findings of one type. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct TypeBreakdown { + pub scan_type: ScanType, + pub counts: SeverityCounts, +} + +/// The open findings in one folder. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct FolderBreakdown { + /// The folder key, which is also the findings list's `path` filter: + /// `src/` (everything below `src`), `src/*` (only the files directly in + /// `src`), or [`ROOT_FOLDER`] (the files in the root). + pub path: String, + pub count: u64, + /// The most severe of the folder's findings. + pub worst: Severity, +} + +/// A target's open findings by type and severity, and by folder. +#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)] +pub struct FindingBreakdown { + /// The types with open findings, most findings first. + pub by_type: Vec, + /// The folders with open findings, most findings first. + pub folders: Vec, + /// Open findings in no file, which the folders leave out. + pub without_file: u64, + /// All open findings. + pub total: u64, +} + +/// The folders `path` lies in, outermost first (none for a file in the root). +fn folders_of(path: &str) -> impl Iterator { + path.rsplit_once('/') + .map_or("", |(dirs, _file)| dirs) + .split('/') + .filter(|dir| !dir.is_empty()) +} + +/// The folder key `path` is counted under. `split` is the top-level +/// directory shown two levels deep, because it holds most findings. +fn folder_key(path: &str, split: Option<&str>) -> String { + let mut folders = folders_of(path); + match (folders.next(), folders.next()) { + (None, _) => ROOT_FOLDER.to_string(), + (Some(top), None) if split == Some(top) => format!("{top}/{DIRECT_SUFFIX}"), + (Some(top), Some(sub)) if split == Some(top) => format!("{top}/{sub}/"), + (Some(top), _) => format!("{top}/"), + } +} + +/// The top-level directory holding more than half of `paths`, which is then +/// shown two levels deep; `None` when there is none, or it has no subfolder +/// with findings (two levels would show nothing new). +fn dominant_dir<'a>(paths: &[&'a str]) -> Option<&'a str> { + let mut counts: Vec<(&str, usize)> = Vec::new(); + for top in paths.iter().filter_map(|p| folders_of(p).next()) { + match counts.iter_mut().find(|(dir, _)| *dir == top) { + Some((_, count)) => *count += 1, + None => counts.push((top, 1)), + } + } + let (top, _) = counts + .into_iter() + .find(|(_, count)| count * 2 > paths.len())?; + paths + .iter() + .any(|p| { + let mut folders = folders_of(p); + folders.next() == Some(top) && folders.next().is_some() + }) + .then_some(top) +} + +/// The file of `row`, `None` when it is in no file. +fn file_of(row: &BreakdownRow) -> Option<&str> { + row.file_path + .as_deref() + .filter(|p| !p.trim_start_matches('/').is_empty()) +} + +/// Counts the open findings `rows` by type and severity, and by folder. +/// +/// Folders are the top-level directories; when one of them holds more than +/// half of the findings in a file, its subfolders are shown instead +/// (`src/api/`), with the files directly in it as `src/*`. Files in the root +/// count under [`ROOT_FOLDER`]. Most findings come first; ties are ordered +/// by the type's name and by the folder's path, so the order does not depend +/// on the order of `rows`. +/// +/// # Examples +/// +/// ``` +/// use compliance_core::finding_breakdown::{breakdown, BreakdownRow}; +/// use compliance_core::models::{ScanType, Severity}; +/// +/// let row = |file: &str| BreakdownRow { +/// scan_type: ScanType::Sast, +/// severity: Severity::High, +/// file_path: Some(file.to_string()), +/// }; +/// let result = breakdown(&[row("src/a.rs"), row("docs/b.md"), row("README.md")]); +/// assert_eq!(result.total, 3); +/// assert_eq!(result.by_type[0].counts.high, 3); +/// assert_eq!(result.folders.len(), 3); +/// ``` +pub fn breakdown(rows: &[BreakdownRow]) -> FindingBreakdown { + let mut by_type: Vec = Vec::new(); + for row in rows { + match by_type.iter_mut().find(|t| t.scan_type == row.scan_type) { + Some(entry) => entry.counts.add(&row.severity), + None => { + let mut counts = SeverityCounts::default(); + counts.add(&row.severity); + by_type.push(TypeBreakdown { + scan_type: row.scan_type, + counts, + }); + } + } + } + by_type.sort_by_cached_key(|t| (std::cmp::Reverse(t.counts.total()), t.scan_type.to_string())); + + let paths: Vec<&str> = rows.iter().filter_map(file_of).collect(); + let split = dominant_dir(&paths); + // Sorted by path, which the stable sort below keeps for equal counts. + let mut folders: std::collections::BTreeMap = + std::collections::BTreeMap::new(); + let mut without_file = 0; + for row in rows { + let Some(path) = file_of(row) else { + without_file += 1; + continue; + }; + let entry = folders + .entry(folder_key(path, split)) + .or_insert((0, row.severity.clone())); + entry.0 += 1; + if row.severity > entry.1 { + entry.1 = row.severity.clone(); + } + } + let mut folders: Vec = folders + .into_iter() + .map(|(path, (count, worst))| FolderBreakdown { path, count, worst }) + .collect(); + folders.sort_by_key(|f| std::cmp::Reverse(f.count)); + + FindingBreakdown { + by_type, + folders, + without_file, + total: rows.len() as u64, + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn row(scan_type: ScanType, severity: Severity, file: Option<&str>) -> BreakdownRow { + BreakdownRow { + scan_type, + severity, + file_path: file.map(str::to_string), + } + } + + fn sast(severity: Severity, file: &str) -> BreakdownRow { + row(ScanType::Sast, severity, Some(file)) + } + + fn folder_paths(result: &FindingBreakdown) -> Vec<(&str, u64)> { + result + .folders + .iter() + .map(|f| (f.path.as_str(), f.count)) + .collect() + } + + #[test] + fn open_means_undecided() { + assert_eq!( + OPEN_STATUSES, + [ + FindingStatus::Open, + FindingStatus::Triaged, + FindingStatus::NeedsReview + ] + ); + for decided in [ + FindingStatus::Resolved, + FindingStatus::FalsePositive, + FindingStatus::WrongMapping, + FindingStatus::AcceptedRisk, + FindingStatus::Ignored, + ] { + assert!(!OPEN_STATUSES.contains(&decided), "{decided} is decided"); + } + } + + #[test] + fn severities_run_from_critical_to_info() { + let mut sorted = SEVERITIES.to_vec(); + sorted.sort_by(|a, b| b.cmp(a)); + assert_eq!(sorted, SEVERITIES.to_vec()); + assert_eq!(SEVERITIES[0], Severity::Critical); + } + + #[test] + fn types_are_counted_per_severity_most_findings_first() { + let rows = [ + row(ScanType::Gdpr, Severity::Medium, Some("a/x.rs")), + row(ScanType::Sast, Severity::High, Some("a/y.rs")), + row(ScanType::Sast, Severity::Critical, None), + row(ScanType::Sast, Severity::High, None), + ]; + let result = breakdown(&rows); + assert_eq!(result.total, 4); + assert_eq!(result.by_type.len(), 2); + let first = &result.by_type[0]; + assert_eq!(first.scan_type, ScanType::Sast); + assert_eq!(first.counts.high, 2); + assert_eq!(first.counts.critical, 1); + assert_eq!(first.counts.total(), 3); + assert_eq!(result.by_type[1].scan_type, ScanType::Gdpr); + assert_eq!(result.by_type[1].counts.get(&Severity::Medium), 1); + } + + #[test] + fn equal_totals_are_ordered_by_name_whatever_the_row_order() { + let lint = row(ScanType::Lint, Severity::Low, None); + let gdpr = row(ScanType::Gdpr, Severity::Low, None); + let order = |rows: &[BreakdownRow]| -> Vec { + breakdown(rows) + .by_type + .iter() + .map(|t| t.scan_type) + .collect() + }; + let expected = [ScanType::Gdpr, ScanType::Lint]; + assert_eq!(order(&[lint.clone(), gdpr.clone()]), expected); + assert_eq!(order(&[gdpr, lint]), expected); + } + + #[test] + fn folders_are_top_level_with_root_files_as_slash() { + let rows = [ + sast(Severity::Low, "src/api/a.rs"), + sast(Severity::Low, "docs/b.md"), + sast(Severity::Low, "docs/deep/c.md"), + sast(Severity::Low, "README.md"), + sast(Severity::Low, "/Cargo.toml"), + ]; + let result = breakdown(&rows); + assert_eq!(folder_paths(&result), [("/", 2), ("docs/", 2), ("src/", 1)]); + assert_eq!(result.without_file, 0); + } + + #[test] + fn a_folder_with_most_findings_is_shown_two_levels_deep() { + let rows = [ + sast(Severity::Low, "src/api/a.rs"), + sast(Severity::Low, "src/api/v1/b.rs"), + sast(Severity::Low, "src/ui/c.rs"), + sast(Severity::Low, "src/main.rs"), + sast(Severity::Low, "docs/sub/d.md"), + sast(Severity::Low, "e.toml"), + ]; + let result = breakdown(&rows); + assert_eq!( + folder_paths(&result), + [ + ("src/api/", 2), + ("/", 1), + ("docs/", 1), + ("src/*", 1), + ("src/ui/", 1) + ] + ); + } + + #[test] + fn half_is_not_most() { + let rows = [ + sast(Severity::Low, "src/api/a.rs"), + sast(Severity::Low, "docs/b.md"), + ]; + assert_eq!(folder_paths(&breakdown(&rows)), [("docs/", 1), ("src/", 1)]); + } + + #[test] + fn findings_in_no_file_are_not_in_a_folder() { + let rows = [ + row(ScanType::Cve, Severity::High, None), + row(ScanType::Cve, Severity::High, Some("")), + sast(Severity::Low, "lib/a.c"), + ]; + let result = breakdown(&rows); + assert_eq!(result.without_file, 2); + assert_eq!(result.total, 3); + assert_eq!(folder_paths(&result), [("lib/", 1)]); + } + + #[test] + fn a_folder_without_subfolders_is_not_split() { + let rows = [ + sast(Severity::Low, "src/a.rs"), + sast(Severity::Low, "src/b.rs"), + sast(Severity::Low, "docs/c/d.md"), + ]; + assert_eq!(folder_paths(&breakdown(&rows)), [("src/", 2), ("docs/", 1)]); + } + + #[test] + fn a_folder_takes_its_worst_severity() { + let rows = [ + sast(Severity::Low, "a/x.rs"), + sast(Severity::Critical, "a/y.rs"), + sast(Severity::Medium, "a/z.rs"), + sast(Severity::Info, "b/z.rs"), + ]; + let result = breakdown(&rows); + let a = result.folders.iter().find(|f| f.path == "a/"); + assert_eq!(a.map(|f| f.worst.clone()), Some(Severity::Critical)); + } + + #[test] + fn the_breakdown_reads_back_from_json() { + let result = breakdown(&[sast(Severity::High, "src/a.rs")]); + let json = serde_json::to_value(&result).expect("serializes"); + assert_eq!(json["by_type"][0]["scan_type"], "sast"); + assert_eq!(json["folders"][0]["worst"], "high"); + let back: FindingBreakdown = serde_json::from_value(json).expect("deserializes"); + assert_eq!(back, result); + } +} diff --git a/compliance-core/src/lib.rs b/compliance-core/src/lib.rs index 3ccfb96..a7cf48d 100644 --- a/compliance-core/src/lib.rs +++ b/compliance-core/src/lib.rs @@ -8,6 +8,7 @@ pub mod encoding; pub mod enisa_docs; pub mod error; pub mod exec_policy; +pub mod finding_breakdown; #[cfg(feature = "net")] pub mod guarded_net; pub mod license_notices; diff --git a/compliance-dashboard/assets/main.css b/compliance-dashboard/assets/main.css index 1707634..c96441a 100644 --- a/compliance-dashboard/assets/main.css +++ b/compliance-dashboard/assets/main.css @@ -6052,3 +6052,215 @@ input[type="file"] { .license-policy-forbid { border-left: 3px solid var(--danger); } + +/* ── Findings view (#957): open findings by type and by folder ── + One red scale for severity, dark (critical) to light (low); info is a + pale tile with a hairline so it reads on both themes. */ +.fb-card { + margin-bottom: 16px; +} + +.fb-head { + display: flex; + align-items: center; + justify-content: space-between; + gap: 12px; +} + +.fb-toggle[aria-pressed="true"] { + background: var(--accent-muted); + color: var(--accent); +} + +.fb-title { + font-size: 14px; + font-weight: 600; + color: var(--text-primary); +} + +.fb-title-folders { + margin-top: 20px; +} + +.fb-hint { + margin: 4px 0 12px; + font-size: 12px; + color: var(--text-tertiary); +} + +.fb-empty { + color: var(--text-secondary); +} + +.fb-sev-critical { background: #7E2318; color: #fff; } +.fb-sev-high { background: #B3452F; color: #fff; } +.fb-sev-medium { background: #D9765F; color: #14162B; } +.fb-sev-low { background: #E8A08C; color: #14162B; } +.fb-sev-info { background: #EDEFF7; color: #14162B; box-shadow: inset 0 0 0 1px var(--border-strong); } + +.fb-legend { + list-style: none; + display: flex; + flex-wrap: wrap; + gap: 6px 16px; + margin-bottom: 12px; + font-size: 12px; + color: var(--text-secondary); +} + +.fb-legend li { + display: flex; + align-items: center; + gap: 6px; +} + +.fb-swatch { + width: 10px; + height: 10px; + border-radius: 2px; +} + +.fb-bars { + display: grid; + gap: 8px; +} + +.fb-bar-row { + display: grid; + grid-template-columns: minmax(120px, 220px) 1fr; + align-items: center; + gap: 12px; + font-size: 13px; +} + +.fb-bar-label { + color: var(--text-secondary); + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.fb-bar-track { + display: flex; + align-items: center; + gap: 8px; + min-width: 0; +} + +.fb-bar { + display: flex; + gap: 2px; + height: 18px; + min-width: 8px; +} + +.fb-seg { + min-width: 6px; + padding: 0; + border: 0; + border-radius: 2px; + cursor: pointer; +} + +.fb-seg:hover, +.fb-tile:hover { + filter: brightness(0.92); +} + +.fb-seg:focus-visible, +.fb-tile:focus-visible, +.fb-cell-link:focus-visible, +.fb-crumb-link:focus-visible { + outline: 2px solid var(--accent); + outline-offset: 2px; +} + +.fb-bar-total { + font-family: var(--font-mono); + font-size: 12px; + color: var(--text-secondary); + font-variant-numeric: tabular-nums; +} + +.fb-treemap { + display: flex; + flex-wrap: wrap; + gap: 2px; +} + +.fb-tile { + flex-basis: 96px; + min-height: 56px; + display: flex; + flex-direction: column; + justify-content: space-between; + align-items: flex-start; + gap: 4px; + padding: 8px; + border: 0; + border-radius: var(--radius-sm); + text-align: left; + cursor: pointer; + overflow: hidden; +} + +.fb-tile-name { + max-width: 100%; + font-family: var(--font-mono); + font-size: 12px; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.fb-tile-count { + font-size: 16px; + font-weight: 600; + font-variant-numeric: tabular-nums; +} + +.fb-without-file { + margin: 12px 0 0; +} + +.fb-table .fb-num { + text-align: right; + font-variant-numeric: tabular-nums; +} + +.fb-cell-link, +.fb-crumb-link { + padding: 0; + border: 0; + background: none; + color: var(--accent); + font: inherit; + cursor: pointer; +} + +.fb-cell-link:hover, +.fb-crumb-link:hover { + text-decoration: underline; +} + +.fb-crumbs { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 8px; + margin-bottom: 12px; + font-size: 14px; +} + +.fb-crumb-sep { + color: var(--text-faint); +} + +.fb-crumb-current { + color: var(--text-primary); + font-weight: 600; +} + +.fb-back { + margin-left: auto; +} diff --git a/compliance-dashboard/src/app.rs b/compliance-dashboard/src/app.rs index 4add56e..126b7b8 100644 --- a/compliance-dashboard/src/app.rs +++ b/compliance-dashboard/src/app.rs @@ -18,9 +18,18 @@ pub enum Route { CompliancePage { id: String }, #[route("/onboard")] OnboardingPage {}, - // `?target=` opens the list filtered to one target. - #[route("/findings?:target")] - FindingsPage { target: String }, + // `?target=` opens the list filtered to one target; a chart of + // the findings view (#957) adds its type, severity or folder. The + // target comes last: the router writes a `&` after each argument + // that is set, so a link without a chart filter keeps its old form. + // (The macro wants the fields in the order of the arguments.) + #[route("/findings?:scan_type&:severity&:path&:target")] + FindingsPage { + scan_type: Option, + severity: Option, + path: Option, + target: String, + }, #[route("/findings/:id")] FindingDetailPage { id: String }, // `?target=` opens the list filtered to one target. @@ -56,6 +65,19 @@ pub enum Route { McpTokensPage {}, } +impl Route { + /// The findings list of target `target` (of all targets when empty), + /// without a chart's filters. + pub fn findings(target: String) -> Self { + Self::FindingsPage { + target, + scan_type: None, + severity: None, + path: None, + } + } +} + const MAIN_CSS: Asset = asset!("/assets/main.css"); const TAILWIND_CSS: Asset = asset!("/assets/tailwind.css"); const VIS_NETWORK_JS: Asset = asset!("/assets/vis-network.min.js"); @@ -99,4 +121,61 @@ mod tests { Ok(Route::SbomPage { target }) if target.is_empty() )); } + + #[test] + fn the_findings_page_carries_the_chart_filters_in_the_query() { + let id = "665f1c2ab0c4d1e2f3a4b5c6"; + // Without a chart filter the link stays what it was. + assert_eq!( + Route::findings(id.to_string()).to_string(), + format!("/findings?target={id}") + ); + let segment = Route::FindingsPage { + target: id.to_string(), + scan_type: Some("gdpr".to_string()), + severity: Some("medium".to_string()), + path: None, + }; + let url = segment.to_string(); + assert_eq!( + url, + format!("/findings?scan_type=gdpr&severity=medium&target={id}") + ); + assert_eq!(Route::from_str(&url).ok(), Some(segment.clone())); + // The order of the arguments does not matter. + assert_eq!( + Route::from_str(&format!( + "/findings?target={id}&severity=medium&scan_type=gdpr" + )) + .ok(), + Some(segment) + ); + let folder = Route::FindingsPage { + target: id.to_string(), + scan_type: None, + severity: None, + path: Some("src/*".to_string()), + }; + assert_eq!( + folder.to_string(), + format!("/findings?path=src/*&target={id}") + ); + assert_eq!(Route::from_str(&folder.to_string()).ok(), Some(folder)); + let root = Route::FindingsPage { + target: id.to_string(), + scan_type: None, + severity: None, + path: Some("/".to_string()), + }; + assert_eq!(Route::from_str(&root.to_string()).ok(), Some(root)); + // Old links and the bare list still parse. + assert_eq!( + Route::from_str(&format!("/findings?target={id}")).ok(), + Some(Route::findings(id.to_string())) + ); + assert_eq!( + Route::from_str("/findings").ok(), + Some(Route::findings(String::new())) + ); + } } diff --git a/compliance-dashboard/src/components/demo_targets.rs b/compliance-dashboard/src/components/demo_targets.rs index a15dd4f..9411f61 100644 --- a/compliance-dashboard/src/components/demo_targets.rs +++ b/compliance-dashboard/src/components/demo_targets.rs @@ -83,7 +83,7 @@ pub fn DemoTargetsButton( DemoSeedResults { results: res } div { class: "modal-actions", Link { to: Route::TargetsPage {}, class: "btn btn-secondary", {demo::TARGETS_LIST.get(lang)} } - Link { to: Route::FindingsPage { target: String::new() }, class: "btn btn-secondary", {nav::FINDINGS.get(lang)} } + Link { to: Route::findings(String::new()), class: "btn btn-secondary", {nav::FINDINGS.get(lang)} } button { class: "btn btn-primary", onclick: close, {demo::CLOSE.get(lang)} } } } else { diff --git a/compliance-dashboard/src/components/finding_breakdown.rs b/compliance-dashboard/src/components/finding_breakdown.rs new file mode 100644 index 0000000..b1769ff --- /dev/null +++ b/compliance-dashboard/src/components/finding_breakdown.rs @@ -0,0 +1,439 @@ +//! The findings view of one target (#957): its open findings as two +//! clickable charts above the list. One bar per finding type, stacked by +//! severity, and a tree map of the folders they are in. A click opens the +//! list filtered to what was clicked; the filter is in the URL, so the view +//! is linkable, and a breadcrumb leads back to the charts. + +use dioxus::prelude::*; + +use compliance_core::finding_breakdown::{FindingBreakdown, OPEN_STATUS_FILTER, SEVERITIES}; +use compliance_core::models::{ScanType, Severity}; + +use crate::app::Route; +use crate::i18n::texts::{common, finding_breakdown as tx, findings as findings_tx}; +use crate::i18n::{use_lang, Lang}; +use crate::infrastructure::finding_breakdown::{fetch_finding_breakdown, is_target_id}; +use crate::infrastructure::findings::wire_name; + +/// The list behind a segment: target `target`'s findings of one type +/// (`scan_type` as stored, `secretdetection`) and severity. +fn segment_route(target: &str, scan_type: &ScanType, severity: &Severity) -> Route { + Route::FindingsPage { + target: target.to_string(), + scan_type: Some(wire_name(scan_type)), + severity: Some(severity.to_string()), + path: None, + } +} + +/// The list behind a folder tile: target `target`'s findings in `folder`. +fn folder_route(target: &str, folder: &str) -> Route { + Route::FindingsPage { + target: target.to_string(), + scan_type: None, + severity: None, + path: Some(folder.to_string()), + } +} + +/// Whether the URL carries a chart's filter (type, severity or folder). +pub fn has_chart_filter( + scan_type: Option<&str>, + severity: Option<&str>, + path: Option<&str>, +) -> bool { + [scan_type, severity, path] + .into_iter() + .any(|v| v.is_some_and(|v| !v.is_empty())) +} + +/// The status filter the list starts with: behind a chart the undecided +/// findings the chart counted, otherwise all. +pub fn list_status(scan_type: Option<&str>, severity: Option<&str>, path: Option<&str>) -> String { + if has_chart_filter(scan_type, severity, path) { + OPEN_STATUS_FILTER.to_string() + } else { + String::new() + } +} + +/// A value as stored (`gdpr`, `medium`) read back into its type; `None` for +/// anything else. +fn from_wire(value: &str) -> Option { + serde_json::from_value(serde_json::Value::String(value.to_string())).ok() +} + +/// What a breadcrumb names after "Befunde": the type and severity +/// (`Datenschutz · mittel`), or the folder. Unknown values are shown as they +/// are rather than dropped, so the breadcrumb always says what filters. +fn breadcrumb( + scan_type: Option<&str>, + severity: Option<&str>, + path: Option<&str>, + lang: Lang, +) -> String { + let scan_type = scan_type.filter(|s| !s.is_empty()).map(|s| { + from_wire::(s).map_or_else( + || s.to_string(), + |t| findings_tx::scan_type(&t).get(lang).to_string(), + ) + }); + let severity = severity.filter(|s| !s.is_empty()).map(|s| { + from_wire::(s).map_or_else(|| s.to_string(), |sev| tx::severity_lc(&sev, lang)) + }); + let path = path.filter(|p| !p.is_empty()).map(|p| tx::folder(p, lang)); + [scan_type, severity, path] + .into_iter() + .flatten() + .collect::>() + .join(" · ") +} + +/// The charts of target `target`'s open findings, or, once a chart filter +/// (`scan_type`, `severity`, `path` from the URL) is set, the breadcrumb of +/// that filter with the way back. Nothing for no target. +#[component] +pub fn FindingBreakdownView( + target: String, + scan_type: Option, + severity: Option, + path: Option, +) -> Element { + let lang = use_lang()(); + let navigator = use_navigator(); + let mut as_table = use_signal(|| false); + let filtered = has_chart_filter(scan_type.as_deref(), severity.as_deref(), path.as_deref()); + // Fetched for the charts only: behind a click the list is what is shown. + // `None` is "not fetched": loading, not failed. + let breakdown = use_resource(use_reactive!(|target, filtered| async move { + if filtered || !is_target_id(&target) { + return None; + } + Some( + fetch_finding_breakdown(target) + .await + .map_err(|e| e.to_string()), + ) + })); + + if !is_target_id(&target) { + return rsx! {}; + } + + if filtered { + let back = Route::findings(target.clone()); + let crumb = breadcrumb( + scan_type.as_deref(), + severity.as_deref(), + path.as_deref(), + lang, + ); + return rsx! { + nav { class: "fb-crumbs", "aria-label": tx::BREADCRUMB.get(lang), + button { + class: "fb-crumb-link", + onclick: move |_| { navigator.push(back.clone()); }, + {tx::BREADCRUMB_ROOT.get(lang)} + } + span { class: "fb-crumb-sep", "aria-hidden": "true", "›" } + span { class: "fb-crumb-current", "aria-current": "page", "{crumb}" } + button { + class: "btn btn-sm btn-ghost fb-back", + onclick: move |_| { navigator.push(Route::findings(target.clone())); }, + {tx::BACK.get(lang)} + } + } + }; + } + + let data = match &*breakdown.read() { + Some(Some(Ok(data))) => data.clone(), + Some(Some(Err(e))) => { + tracing::warn!("finding breakdown not loaded: {e}"); + return rsx! { + div { class: "card fb-card", p { {tx::LOAD_FAILED.get(lang)} } } + }; + } + _ => { + return rsx! { + div { class: "card fb-card", div { class: "loading", {common::LOADING.get(lang)} } } + }; + } + }; + + if data.total == 0 { + return rsx! { + div { class: "card fb-card", p { class: "fb-empty", {tx::NONE_OPEN.get(lang)} } } + }; + } + + rsx! { + div { class: "card fb-card", + div { class: "fb-head", + h3 { class: "fb-title", {tx::BY_TYPE.get(lang)} } + // A toggle: the label stays, the pressed state changes. + button { + class: "btn btn-sm btn-ghost fb-toggle", + "aria-pressed": "{as_table()}", + onclick: move |_| as_table.toggle(), + {tx::TABLE.get(lang)} + } + } + p { class: "fb-hint", {tx::BY_TYPE_HINT.get(lang)} } + if as_table() { + BreakdownTables { target: target.clone(), data: data.clone() } + } else { + TypeBars { target: target.clone(), data: data.clone() } + h3 { class: "fb-title fb-title-folders", {tx::BY_FOLDER.get(lang)} } + p { class: "fb-hint", {tx::BY_FOLDER_HINT.get(lang)} } + FolderMap { target: target.clone(), data: data.clone() } + } + if data.without_file > 0 { + p { class: "fb-hint fb-without-file", + "{data.without_file} {tx::WITHOUT_FILE.get(lang)}" + } + } + } + } +} + +/// One bar per type, stacked by severity, as long as its share of the +/// largest type; each segment opens the list of its findings. +#[component] +fn TypeBars(target: String, data: FindingBreakdown) -> Element { + let lang = use_lang()(); + let navigator = use_navigator(); + let largest = data.by_type.first().map_or(1, |t| t.counts.total()).max(1); + + rsx! { + ul { class: "fb-legend", "aria-label": tx::LEGEND.get(lang), + for severity in SEVERITIES { + li { + span { class: "fb-swatch fb-sev-{severity}" } + {tx::severity(&severity).get(lang)} + } + } + } + div { class: "fb-bars", + for row in data.by_type.iter() { + { + let type_name = findings_tx::scan_type(&row.scan_type).get(lang); + let total = row.counts.total(); + let width = total * 100 / largest; + rsx! { + div { class: "fb-bar-row", + span { class: "fb-bar-label", "{type_name}" } + div { class: "fb-bar-track", + div { class: "fb-bar", style: "width: {width}%;", + for severity in SEVERITIES { + { + let count = row.counts.get(&severity); + let label = format!("{type_name}, {}: {count}", tx::severity_lc(&severity, lang)); + let to = segment_route(&target, &row.scan_type, &severity); + rsx! { + if count > 0 { + button { + class: "fb-seg fb-sev-{severity}", + style: "flex-grow: {count};", + "aria-label": "{label}", + title: "{label}", + onclick: move |_| { navigator.push(to.clone()); }, + } + } + } + } + } + } + span { class: "fb-bar-total", "{total}" } + } + } + } + } + } + } + } +} + +/// The folders as tiles growing with their open findings, coloured by the +/// most severe; each opens the list of the folder's findings. +#[component] +fn FolderMap(target: String, data: FindingBreakdown) -> Element { + let lang = use_lang()(); + let navigator = use_navigator(); + + rsx! { + div { class: "fb-treemap", + for folder in data.folders.iter() { + { + let name = tx::folder(&folder.path, lang); + let label = format!( + "{name}: {}, {} {}", + folder.count, + tx::WORST_IS.get(lang), + tx::severity_lc(&folder.worst, lang) + ); + let to = folder_route(&target, &folder.path); + rsx! { + button { + class: "fb-tile fb-sev-{folder.worst}", + style: "flex-grow: {folder.count};", + "aria-label": "{label}", + title: "{label}", + onclick: move |_| { navigator.push(to.clone()); }, + span { class: "fb-tile-name", "{name}" } + span { class: "fb-tile-count", "{folder.count}" } + } + } + } + } + } + } +} + +/// The same numbers as plain tables; each non-zero count opens its list. +#[component] +fn BreakdownTables(target: String, data: FindingBreakdown) -> Element { + let lang = use_lang()(); + let navigator = use_navigator(); + + rsx! { + div { class: "table-wrapper", + table { class: "fb-table", + thead { + tr { + th { {tx::COL_TYPE.get(lang)} } + for severity in SEVERITIES { + th { class: "fb-num", {tx::severity(&severity).get(lang)} } + } + th { class: "fb-num", {tx::COL_TOTAL.get(lang)} } + } + } + tbody { + for row in data.by_type.iter() { + { + let type_name = findings_tx::scan_type(&row.scan_type).get(lang); + rsx! { + tr { + td { "{type_name}" } + for severity in SEVERITIES { + { + let count = row.counts.get(&severity); + let label = format!("{type_name}, {}: {count}", tx::severity_lc(&severity, lang)); + let to = segment_route(&target, &row.scan_type, &severity); + rsx! { + td { class: "fb-num", + if count > 0 { + button { + class: "fb-cell-link", + "aria-label": "{label}", + onclick: move |_| { navigator.push(to.clone()); }, + "{count}" + } + } else { + "0" + } + } + } + } + } + td { class: "fb-num", "{row.counts.total()}" } + } + } + } + } + } + } + } + div { class: "table-wrapper", + table { class: "fb-table", + thead { + tr { + th { {tx::COL_FOLDER.get(lang)} } + th { class: "fb-num", {tx::COL_COUNT.get(lang)} } + th { {tx::COL_WORST.get(lang)} } + } + } + tbody { + for folder in data.folders.iter() { + { + let name = tx::folder(&folder.path, lang); + let to = folder_route(&target, &folder.path); + rsx! { + tr { + td { + button { + class: "fb-cell-link", + onclick: move |_| { navigator.push(to.clone()); }, + "{name}" + } + } + td { class: "fb-num", "{folder.count}" } + td { {tx::severity(&folder.worst).get(lang)} } + } + } + } + } + } + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + const ID: &str = "665f1c2ab0c4d1e2f3a4b5c6"; + + #[test] + fn a_segment_opens_its_type_and_severity_as_stored() { + let route = segment_route(ID, &ScanType::SecretDetection, &Severity::Medium); + assert_eq!( + route, + Route::FindingsPage { + target: ID.to_string(), + scan_type: Some("secretdetection".to_string()), + severity: Some("medium".to_string()), + path: None, + } + ); + } + + #[test] + fn a_tile_opens_its_folder() { + assert_eq!( + folder_route(ID, "src/*"), + Route::FindingsPage { + target: ID.to_string(), + scan_type: None, + severity: None, + path: Some("src/*".to_string()), + } + ); + } + + #[test] + fn behind_a_chart_the_list_starts_with_the_open_findings() { + assert!(!has_chart_filter(None, Some(""), None)); + assert_eq!(list_status(None, None, None), ""); + assert_eq!(list_status(Some("gdpr"), Some("medium"), None), "undecided"); + assert_eq!(list_status(None, None, Some("/")), "undecided"); + } + + #[test] + fn the_breadcrumb_names_the_filter() { + assert_eq!( + breadcrumb(Some("gdpr"), Some("medium"), None, Lang::De), + "Datenschutz · mittel" + ); + assert_eq!( + breadcrumb(None, None, Some("src/api/"), Lang::En), + "src/api/" + ); + // An unknown value is still shown. + assert_eq!( + breadcrumb(Some("nonsense"), Some(""), None, Lang::De), + "nonsense" + ); + } +} diff --git a/compliance-dashboard/src/components/mod.rs b/compliance-dashboard/src/components/mod.rs index a20aa3b..69beb7b 100644 --- a/compliance-dashboard/src/components/mod.rs +++ b/compliance-dashboard/src/components/mod.rs @@ -9,6 +9,7 @@ pub mod cra_bar; pub mod demo_targets; pub mod evidence_button; pub mod file_tree; +pub mod finding_breakdown; pub mod help_chat; pub mod lang_toggle; pub mod layer_pins; diff --git a/compliance-dashboard/src/components/scan_runs.rs b/compliance-dashboard/src/components/scan_runs.rs index 0f4583b..d0f377b 100644 --- a/compliance-dashboard/src/components/scan_runs.rs +++ b/compliance-dashboard/src/components/scan_runs.rs @@ -450,7 +450,7 @@ fn RunReveal(target_id: String, run_id: String, count: u32) -> Element { } } Link { - to: Route::FindingsPage { target: target_id.clone() }, + to: Route::findings(target_id.clone()), class: "btn btn-secondary btn-sm", {scans::SHOW_FINDINGS.get(lang)} } diff --git a/compliance-dashboard/src/components/sidebar.rs b/compliance-dashboard/src/components/sidebar.rs index d61e224..cc11400 100644 --- a/compliance-dashboard/src/components/sidebar.rs +++ b/compliance-dashboard/src/components/sidebar.rs @@ -65,9 +65,7 @@ pub fn Sidebar() -> Element { }, NavItem { label: nav::FINDINGS, - route: Route::FindingsPage { - target: String::new(), - }, + route: Route::findings(String::new()), icon: rsx! { Icon { icon: BsShieldExclamation, width: 18, height: 18 } }, runtime_only: false, write_only: false, diff --git a/compliance-dashboard/src/i18n/texts.rs b/compliance-dashboard/src/i18n/texts.rs index 95cc78b..795e8aa 100644 --- a/compliance-dashboard/src/i18n/texts.rs +++ b/compliance-dashboard/src/i18n/texts.rs @@ -4951,3 +4951,157 @@ pub mod graph { } } } + +/// The findings view of one target (#957): its open findings by type and +/// severity, and by folder, as clickable charts. +pub mod finding_breakdown { + use compliance_core::models::Severity; + + use super::{common, Text}; + use crate::i18n::Lang; + + pub const BY_TYPE: Text = Text { + de: "Offene Befunde nach Art", + en: "Open findings by type", + }; + pub const BY_TYPE_HINT: Text = Text { + de: "Offen heißt unentschieden: offen, gesichtet oder zu prüfen. Ein Klick auf ein \ + Segment öffnet die Liste dieser Befunde.", + en: "Open means undecided: open, triaged or needs review. Click a segment to open the \ + list of those findings.", + }; + pub const BY_FOLDER: Text = Text { + de: "Wo die Befunde liegen", + en: "Where the findings are", + }; + pub const BY_FOLDER_HINT: Text = Text { + de: "Fläche: offene Befunde im Ordner. Farbe: der schwerste davon.", + en: "Area: the folder's open findings. Colour: the most severe of them.", + }; + pub const TABLE: Text = Text { + de: "Tabelle", + en: "Table", + }; + pub const BACK: Text = Text { + de: "← Zurück zum Diagramm", + en: "← Back to the chart", + }; + /// The breadcrumb's name, read aloud. + pub const BREADCRUMB: Text = Text { + de: "Navigationspfad", + en: "Breadcrumb", + }; + pub const BREADCRUMB_ROOT: Text = Text { + de: "Befunde", + en: "Findings", + }; + pub const NONE_OPEN: Text = Text { + de: "Keine offenen Befunde.", + en: "No open findings.", + }; + pub const LOAD_FAILED: Text = Text { + de: "Die Übersicht der Befunde konnte nicht geladen werden.", + en: "The findings overview could not be loaded.", + }; + pub const COL_TYPE: Text = Text { + de: "Art", + en: "Type", + }; + pub const COL_FOLDER: Text = Text { + de: "Ordner", + en: "Folder", + }; + pub const COL_COUNT: Text = Text { + de: "Offene Befunde", + en: "Open findings", + }; + pub const COL_TOTAL: Text = Text { + de: "Summe", + en: "Total", + }; + pub const COL_WORST: Text = Text { + de: "Schwerster", + en: "Most severe", + }; + pub const INFO: Text = Text { + de: "Info", + en: "Info", + }; + /// The folder of the files in the root of the tree. + pub const ROOT: Text = Text { + de: "Hauptverzeichnis", + en: "root folder", + }; + /// After a folder whose own files only are meant (`src/*`). + pub const DIRECT: Text = Text { + de: "nur direkt darin", + en: "directly in it only", + }; + /// After the number of open findings in no file. + pub const WITHOUT_FILE: Text = Text { + de: "offene Befunde ohne Datei (z. B. CVEs in Abhängigkeiten) sind hier nicht \ + enthalten.", + en: "open findings in no file (e.g. CVEs in dependencies) are not shown here.", + }; + /// The status filter of the list behind a chart. + pub const UNDECIDED: Text = Text { + de: "Offen (unentschieden)", + en: "Open (undecided)", + }; + pub const LEGEND: Text = Text { + de: "Schweregrade", + en: "Severities", + }; + /// Between a folder and its most severe finding, read aloud. + pub const WORST_IS: Text = Text { + de: "schwerster", + en: "most severe", + }; + + /// A severity in words, capitalised (legend, table head). + pub fn severity(severity: &Severity) -> Text { + match severity { + Severity::Critical => common::CRITICAL, + Severity::High => common::HIGH, + Severity::Medium => common::MEDIUM, + Severity::Low => common::LOW, + Severity::Info => INFO, + } + } + + /// A severity in running text (`Datenschutz, mittel: 9`): lower case. + pub fn severity_lc(severity: &Severity, lang: Lang) -> String { + self::severity(severity).get(lang).to_lowercase() + } + + /// A folder key of the chart (`src/`, `src/*`, `/`) in words. + pub fn folder(path: &str, lang: Lang) -> String { + use compliance_core::finding_breakdown::{DIRECT_SUFFIX, ROOT_FOLDER}; + if path == ROOT_FOLDER { + return format!("/ ({})", ROOT.get(lang)); + } + match path.strip_suffix(DIRECT_SUFFIX) { + Some(dir) => format!("{dir} ({})", DIRECT.get(lang)), + None => path.to_string(), + } + } + + #[cfg(test)] + mod tests { + use super::*; + + #[test] + fn severities_read_in_running_text() { + assert_eq!(severity_lc(&Severity::Medium, Lang::De), "mittel"); + assert_eq!(severity_lc(&Severity::Critical, Lang::En), "critical"); + assert_eq!(severity(&Severity::Info).de, "Info"); + } + + #[test] + fn folders_read_as_words() { + assert_eq!(folder("src/", Lang::De), "src/"); + assert_eq!(folder("src/*", Lang::De), "src/ (nur direkt darin)"); + assert_eq!(folder("/", Lang::En), "/ (root folder)"); + } + } +} diff --git a/compliance-dashboard/src/infrastructure/finding_breakdown.rs b/compliance-dashboard/src/infrastructure/finding_breakdown.rs new file mode 100644 index 0000000..a7aa7f1 --- /dev/null +++ b/compliance-dashboard/src/infrastructure/finding_breakdown.rs @@ -0,0 +1,41 @@ +//! The open findings of one target by type, severity and folder (#957), +//! from `GET /api/v1/targets/{id}/finding-breakdown`. + +use dioxus::prelude::*; + +use compliance_core::finding_breakdown::FindingBreakdown; + +/// Whether `id` looks like a target id (a Mongo object id in hex), so it can +/// go into the agent's URL path as it is. +pub fn is_target_id(id: &str) -> bool { + id.len() == 24 && id.bytes().all(|b| b.is_ascii_hexdigit()) +} + +/// The breakdown of target `target`'s open findings. +#[server] +pub async fn fetch_finding_breakdown(target: String) -> Result { + if !is_target_id(&target) { + return Err(ServerFnError::new("not a target id")); + } + let resp = + super::agent_client::agent_get(&format!("/api/v1/targets/{target}/finding-breakdown")) + .await? + .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())) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn only_object_ids_reach_the_agent_path() { + assert!(is_target_id("665f1c2ab0c4d1e2f3a4b5c6")); + assert!(!is_target_id("")); + assert!(!is_target_id("../findings?x=665f1c2ab0")); + assert!(!is_target_id("665f1c2ab0c4d1e2f3a4b5cz")); + } +} diff --git a/compliance-dashboard/src/infrastructure/findings.rs b/compliance-dashboard/src/infrastructure/findings.rs index 85000d4..85c409e 100644 --- a/compliance-dashboard/src/infrastructure/findings.rs +++ b/compliance-dashboard/src/infrastructure/findings.rs @@ -20,6 +20,8 @@ pub struct FindingsQuery { pub q: String, /// One app variant (`Tablet App`), or empty for all. pub variant: String, + /// One folder of the folder chart (`src/`, `src/*`, `/`), or empty. + pub path: String, pub sort_by: String, pub sort_order: String, } @@ -117,6 +119,12 @@ pub async fn fetch_findings(query: FindingsQuery) -> Result() )); } + if !query.path.is_empty() { + path.push_str(&format!( + "&path={}", + url::form_urlencoded::byte_serialize(query.path.as_bytes()).collect::() + )); + } if !query.sort_by.is_empty() { path.push_str(&format!("&sort_by={}", query.sort_by)); } diff --git a/compliance-dashboard/src/infrastructure/mod.rs b/compliance-dashboard/src/infrastructure/mod.rs index 60a7950..d32d8d0 100644 --- a/compliance-dashboard/src/infrastructure/mod.rs +++ b/compliance-dashboard/src/infrastructure/mod.rs @@ -5,6 +5,7 @@ pub mod chat; pub mod dast; pub mod download; pub mod evidence; +pub mod finding_breakdown; pub mod findings; pub mod graph; pub mod help_chat; diff --git a/compliance-dashboard/src/pages/findings.rs b/compliance-dashboard/src/pages/findings.rs index c8c397e..5fcf825 100644 --- a/compliance-dashboard/src/pages/findings.rs +++ b/compliance-dashboard/src/pages/findings.rs @@ -7,24 +7,51 @@ use dioxus_free_icons::icons::bs_icons::*; use dioxus_free_icons::Icon; use crate::app::Route; +use crate::components::finding_breakdown::{list_status, FindingBreakdownView}; use crate::components::page_header::PageHeader; use crate::components::pagination::Pagination; use crate::components::severity_badge::SeverityBadge; use crate::components::toast::{ToastType, Toasts}; -use crate::i18n::texts::{common, findings as tx}; +use crate::i18n::texts::{common, finding_breakdown as breakdown_tx, findings as tx}; use crate::i18n::use_lang; use crate::infrastructure::findings::{has_control_refs, location, wire_name}; +use compliance_core::finding_breakdown::OPEN_STATUS_FILTER; #[component] -pub fn FindingsPage(target: String) -> Element { +pub fn FindingsPage( + target: String, + scan_type: Option, + severity: Option, + path: Option, +) -> Element { let can_write = crate::components::no_access::use_can_write(); let lang = use_lang()(); let mut toasts = use_context::(); let mut page = use_signal(|| 1u64); - let mut severity_filter = use_signal(String::new); - let mut type_filter = use_signal(String::new); - let mut status_filter = use_signal(String::new); + let mut severity_filter = use_signal(|| severity.clone().unwrap_or_default()); + let mut type_filter = use_signal(|| scan_type.clone().unwrap_or_default()); + let mut status_filter = + use_signal(|| list_status(scan_type.as_deref(), severity.as_deref(), path.as_deref())); let mut repo_filter = use_signal(|| target.clone()); + // A folder of the findings view's tree map; set from the URL only. + let path_filter = use_signal(|| path.clone().unwrap_or_default()); + // The page stays mounted when a chart click or the way back changes the + // URL: its filters then replace the selects' choice. + use_effect(use_reactive!(|target, scan_type, severity, path| { + let status = list_status(scan_type.as_deref(), severity.as_deref(), path.as_deref()); + for (mut filter, value) in [ + (repo_filter, target), + (type_filter, scan_type.unwrap_or_default()), + (severity_filter, severity.unwrap_or_default()), + (path_filter, path.unwrap_or_default()), + (status_filter, status), + ] { + if *filter.peek() != value { + filter.set(value); + page.set(1); + } + } + })); let mut search_query = use_signal(String::new); let mut variant_filter = use_signal(String::new); // Most severe first: what needs attention leads. @@ -59,6 +86,7 @@ pub fn FindingsPage(target: String) -> Element { repo_id: repo_filter(), q: search_query(), variant: variant_filter(), + path: path_filter(), sort_by: sort_by(), sort_order: sort_order(), }; @@ -124,6 +152,10 @@ pub fn FindingsPage(target: String) -> Element { description: tx::SUBTITLE.get(lang), } + // One target: its open findings as charts, or the breadcrumb of the + // chart filter the list below is narrowed to. + FindingBreakdownView { target: repo_filter(), scan_type, severity, path } + div { class: "filter-bar", input { r#type: "text", @@ -154,25 +186,27 @@ pub fn FindingsPage(target: String) -> Element { select { onchange: move |e| { severity_filter.set(e.value()); page.set(1); }, option { value: "", {tx::ALL_SEVERITIES.get(lang)} } - option { value: "critical", {common::CRITICAL.get(lang)} } - option { value: "high", {common::HIGH.get(lang)} } - option { value: "medium", {common::MEDIUM.get(lang)} } - option { value: "low", {common::LOW.get(lang)} } - option { value: "info", {tx::INFO.get(lang)} } + option { value: "critical", selected: severity_filter() == "critical", {common::CRITICAL.get(lang)} } + option { value: "high", selected: severity_filter() == "high", {common::HIGH.get(lang)} } + option { value: "medium", selected: severity_filter() == "medium", {common::MEDIUM.get(lang)} } + option { value: "low", selected: severity_filter() == "low", {common::LOW.get(lang)} } + option { value: "info", selected: severity_filter() == "info", {tx::INFO.get(lang)} } } select { onchange: move |e| { type_filter.set(e.value()); page.set(1); }, option { value: "", {tx::ALL_TYPES.get(lang)} } // The stored names (`secretdetection`), which a filter must match. for scan_type in tx::SCAN_TYPES { - option { value: "{wire_name(&scan_type)}", {tx::scan_type(&scan_type).get(lang)} } + option { value: "{wire_name(&scan_type)}", selected: type_filter() == wire_name(&scan_type), {tx::scan_type(&scan_type).get(lang)} } } } select { onchange: move |e| { status_filter.set(e.value()); page.set(1); }, option { value: "", {tx::ALL_STATUSES.get(lang)} } + // Every undecided status: what the findings view's charts count. + option { value: OPEN_STATUS_FILTER, selected: status_filter() == OPEN_STATUS_FILTER, {breakdown_tx::UNDECIDED.get(lang)} } for status in tx::STATUSES { - option { value: "{wire_name(&status)}", {tx::status(&status).get(lang)} } + option { value: "{wire_name(&status)}", selected: status_filter() == wire_name(&status), {tx::status(&status).get(lang)} } } } if let Some(names) = variants.read().as_ref().filter(|v| !v.is_empty()) { diff --git a/compliance-dashboard/src/pages/onboarding.rs b/compliance-dashboard/src/pages/onboarding.rs index 8ecb63b..64acccd 100644 --- a/compliance-dashboard/src/pages/onboarding.rs +++ b/compliance-dashboard/src/pages/onboarding.rs @@ -603,7 +603,7 @@ pub fn OnboardingPage() -> Element { } if let Some(id) = created_id() { Link { - to: Route::FindingsPage { target: id }, + to: Route::findings(id), class: "btn btn-secondary", {tx::TO_FINDINGS.get(lang)} } diff --git a/compliance-dashboard/src/pages/overview.rs b/compliance-dashboard/src/pages/overview.rs index 5648490..e220b34 100644 --- a/compliance-dashboard/src/pages/overview.rs +++ b/compliance-dashboard/src/pages/overview.rs @@ -119,7 +119,7 @@ pub fn OverviewPage() -> Element { span { class: "ov-figure-label", {overview::TARGETS.get(lang)} } span { class: "ov-figure-value", "{s.total_repositories}" } } - Link { to: Route::FindingsPage { target: String::new() }, class: "ov-figure", + Link { to: Route::findings(String::new()), class: "ov-figure", span { class: "ov-figure-label", {overview::OPEN_FINDINGS.get(lang)} } span { class: "ov-figure-value", "{s.total_findings}" } span { class: "ov-figure-sub", @@ -220,7 +220,7 @@ pub fn OverviewPage() -> Element { } } } - Link { to: Route::FindingsPage { target: String::new() }, class: "ov-more", + Link { to: Route::findings(String::new()), class: "ov-more", {overview::ALL_FINDINGS.get(lang)} Icon { icon: BsArrowRight, width: 14, height: 14 } } diff --git a/compliance-dashboard/src/pages/target.rs b/compliance-dashboard/src/pages/target.rs index e3f7c92..6c6dc85 100644 --- a/compliance-dashboard/src/pages/target.rs +++ b/compliance-dashboard/src/pages/target.rs @@ -311,7 +311,7 @@ pub fn TargetPage(id: String) -> Element { span { class: "target-count", "{r.total.unwrap_or(0)}" } } } - Link { to: Route::FindingsPage { target: id.clone() }, class: "target-card-link", + Link { to: Route::findings(id.clone()), class: "target-card-link", {tx::ALL_FINDINGS.get(lang)} Icon { icon: BsArrowRight, width: 14, height: 14 } } diff --git a/compliance-dashboard/src/pages/targets.rs b/compliance-dashboard/src/pages/targets.rs index 638ff80..abbc05b 100644 --- a/compliance-dashboard/src/pages/targets.rs +++ b/compliance-dashboard/src/pages/targets.rs @@ -262,7 +262,7 @@ pub fn TargetsPage() -> Element { } td { class: "num", Link { - to: Route::FindingsPage { target: id.clone() }, + to: Route::findings(id.clone()), title: tx::SHOW_FINDINGS.get(lang), onclick: move |e: MouseEvent| e.stop_propagation(), "{findings}"