CI / Check (push) Skipped
CI / Agent integration (push) Skipped
CI / Detect Changes (push) Successful in 4s
CI / Deploy Docs (push) Skipped
CI / Deploy MCP (push) Successful in 3m18s
CI / Deploy Dashboard (push) Successful in 7m22s
CI / Deploy Agent (push) Successful in 9m43s
The findings page of one target (/findings?target=...) now opens with two
charts of its open findings: a bar per finding type stacked by severity
(one red scale, every segment a button), and a tree map of the folders
they are in (area = open findings, colour = the most severe). A click
opens the list narrowed to that type and severity, or to that folder; the
filter goes into the URL, a breadcrumb names it and leads back to the
charts. A "Tabelle" toggle shows the same numbers as tables.
- core: finding_breakdown (the shared DTO and the pure counting function;
open = Open, Triaged, NeedsReview as for tracker issues)
- agent: GET /api/v1/targets/{id}/finding-breakdown; the findings list
takes an anchored literal `path` folder filter and `status=undecided`
- dashboard: FindingsPage takes scan_type, severity and path from the
query (Route::findings(target) builds the plain list link)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
435 lines
15 KiB
Rust
435 lines
15 KiB
Rust
//! 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<String>,
|
|
}
|
|
|
|
/// 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<TypeBreakdown>,
|
|
/// The folders with open findings, most findings first.
|
|
pub folders: Vec<FolderBreakdown>,
|
|
/// 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<Item = &str> {
|
|
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<TypeBreakdown> = 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<String, (u64, Severity)> =
|
|
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<FolderBreakdown> = 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<ScanType> {
|
|
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);
|
|
}
|
|
}
|