From 93c9446490e7acdc6f49777936198cfe4a9b55d6 Mon Sep 17 00:00:00 2001 From: Sharang Parnerkar <30073382+mighty840@users.noreply.github.com> Date: Tue, 10 Nov 2026 12:13:15 +0100 Subject: [PATCH] feat(findings): group findings by rule and file, decide a group at once (#951) Undecided findings are grouped on read, by target, tool, rule and file, and by directory when a rule fires in three or more files of one directory. A stored #464 group stays a group of its own. Nothing about groups is stored. - compliance-core: models::finding_group with the pure group_findings and members_of, for the findings list and later the Heute inbox. - GET /api/v1/finding-groups[?target=] lists the groups; POST /api/v1/finding-groups/decide gives every undecided member the same status through the bulk path (status history, issue sync), so VEX and the evidence pack see ordinary per-finding changes. - Findings list: Gruppiert / Einzeln toggle (default grouped) with group cards, the AI's reason, the places, and Fehlalarm / Risiko akzeptiert for all places of a group. Co-Authored-By: Claude Opus 5.5 --- .../src/api/handlers/finding_groups.rs | 278 ++++++++ compliance-agent/src/api/handlers/findings.rs | 40 +- compliance-agent/src/api/handlers/mod.rs | 1 + .../src/api/role_gate/router_tests.rs | 2 + compliance-agent/src/api/routes.rs | 9 + compliance-core/src/models/finding_group.rs | 602 ++++++++++++++++++ compliance-core/src/models/mod.rs | 1 + compliance-dashboard/assets/main.css | 150 +++++ .../src/components/finding_groups.rs | 303 +++++++++ compliance-dashboard/src/components/mod.rs | 1 + compliance-dashboard/src/i18n/texts.rs | 191 ++++++ .../src/infrastructure/finding_groups.rs | 61 ++ .../src/infrastructure/mod.rs | 1 + compliance-dashboard/src/pages/findings.rs | 37 +- 14 files changed, 1667 insertions(+), 10 deletions(-) create mode 100644 compliance-agent/src/api/handlers/finding_groups.rs create mode 100644 compliance-core/src/models/finding_group.rs create mode 100644 compliance-dashboard/src/components/finding_groups.rs create mode 100644 compliance-dashboard/src/infrastructure/finding_groups.rs diff --git a/compliance-agent/src/api/handlers/finding_groups.rs b/compliance-agent/src/api/handlers/finding_groups.rs new file mode 100644 index 0000000..70736cf --- /dev/null +++ b/compliance-agent/src/api/handlers/finding_groups.rs @@ -0,0 +1,278 @@ +//! Open findings grouped by rule and file, and one decision for a whole +//! group (#951). +//! +//! The grouping is [`compliance_core::models::finding_group`], a pure +//! function over the findings; nothing about groups is stored. A group +//! decision is a status change of every member through the same path as a +//! bulk change ([`super::findings::apply_status`]), so the status history, +//! the issue sync, the evidence pack and VEX see ordinary per-finding +//! changes. + +use axum::extract::{Extension, Query}; +use axum::http::StatusCode; +use axum::Json; +use mongodb::bson::{doc, Document}; +use serde::Deserialize; + +use super::dto::{collect_cursor_async, tenant_db, AgentExt, ApiResponse, ApiResult}; +use super::findings::{apply_status, status_update, Actor}; +use super::health::OPEN_STATUSES; +use compliance_core::models::finding_group::{group_findings, members_of, FindingGroup, GroupKey}; +use compliance_core::models::{Finding, FindingStatus}; +use compliance_core::tenant_ctx::TenantCtx; + +/// The query of [`list_finding_groups`]. +#[derive(Debug, Deserialize)] +pub struct GroupsQuery { + /// Only one target's findings (`Finding::repo_id`). + #[serde(default)] + pub target: Option, +} + +/// The body of [`decide_finding_group`]. +#[derive(Debug, Deserialize)] +pub struct DecideGroupRequest { + /// The group, as [`list_finding_groups`] named it. + pub key: GroupKey, + /// The decision for every member. + pub status: FindingStatus, + /// Why; required for an accepted risk or a wrong mapping. + #[serde(default)] + pub reason: Option, +} + +/// The fields a group never shows, left out of the read: the code, the fix +/// and the history are on each finding's own page. +fn light_projection() -> Document { + doc! { + "code_snippet": 0, + "suggested_fix": 0, + "remediation": 0, + "status_history": 0, + "legacy_fingerprints": 0, + } +} + +/// The undecided findings `filter` narrows down to. +async fn undecided_findings( + db: &crate::database::Database, + mut filter: Document, +) -> Result, StatusCode> { + filter.insert("status", doc! { "$in": OPEN_STATUSES.to_vec() }); + let cursor = db + .findings() + .find(filter) + .projection(light_projection()) + .await + .map_err(|e| { + tracing::warn!("Failed to fetch findings to group: {e}"); + StatusCode::INTERNAL_SERVER_ERROR + })?; + Ok(collect_cursor_async(cursor).await) +} + +/// GET /api/v1/finding-groups[?target=] — the undecided findings, grouped +/// by rule and file (see [`compliance_core::models::finding_group`]), most +/// severe first. +#[tracing::instrument(skip_all, fields(target = ?query.target))] +pub async fn list_finding_groups( + Extension(agent): AgentExt, + tenant: TenantCtx, + Query(query): Query, +) -> ApiResult> { + let db = tenant_db(&agent, &tenant).await?; + let filter = query + .target + .filter(|t| !t.is_empty()) + .map_or_else(Document::new, |target| doc! { "repo_id": target }); + let groups = group_findings(undecided_findings(&db, filter).await?); + Ok(Json(ApiResponse { + total: Some(groups.len() as u64), + data: groups, + page: None, + })) +} + +/// Whether a person may give a whole group `status`: a decision, not a +/// return to an undecided state (the members are undecided already, and +/// "needs review" is the AI's to set). +fn is_group_decision(status: &FindingStatus) -> bool { + match status { + FindingStatus::FalsePositive + | FindingStatus::AcceptedRisk + | FindingStatus::WrongMapping + | FindingStatus::Ignored + | FindingStatus::Resolved => true, + FindingStatus::Open | FindingStatus::Triaged | FindingStatus::NeedsReview => false, + } +} + +/// The status change `req` asks of every member, by `actor`. +/// +/// # Errors +/// +/// 422 when the status is not a decision, or needs a reason and comes +/// without one. +fn decision_update(req: &DecideGroupRequest, actor: &Actor<'_>) -> Result { + if !is_group_decision(&req.status) { + return Err(StatusCode::UNPROCESSABLE_ENTITY); + } + status_update(&req.status, req.reason.as_deref(), actor) +} + +/// The findings that may belong to the group `key`: its rule in its target. +/// The grouping then picks the members from them. +fn candidates_filter(key: &GroupKey) -> Document { + doc! { + "repo_id": &key.repo_id, + "scanner": &key.scanner, + "$or": [ + { "rule_id": &key.rule }, + // A finding without a rule id is grouped by its title. + { "rule_id": { "$in": [null, ""] }, "title": &key.rule }, + ], + } +} + +/// POST /api/v1/finding-groups/decide — give every undecided member of a +/// group the same status, as if each were changed on its own. +/// +/// The members are found again from the key, so a member someone decided +/// in the meantime keeps that decision. 404 when the group has no undecided +/// member (any more), 422 as [`decision_update`]. +#[tracing::instrument(skip_all, fields(rule = %req.key.rule, scope = ?req.key.scope))] +pub async fn decide_finding_group( + Extension(agent): AgentExt, + tenant: TenantCtx, + Json(req): Json, +) -> Result, StatusCode> { + let update = decision_update(&req, &Actor::of(&tenant.0))?; + let db = tenant_db(&agent, &tenant).await?; + let candidates = undecided_findings(&db, candidates_filter(&req.key)).await?; + let oids = members_of(candidates, &req.key); + if oids.is_empty() { + return Err(StatusCode::NOT_FOUND); + } + let filter = doc! { + "_id": { "$in": oids.clone() }, + "status": { "$in": OPEN_STATUSES.to_vec() }, + }; + let members = oids.len(); + let modified_count = apply_status(&agent, db, filter, oids, update).await?; + Ok(Json(serde_json::json!({ + "status": "updated", + "members": members, + "modified_count": modified_count, + }))) +} + +#[cfg(test)] +mod tests { + use super::*; + use compliance_core::models::finding_group::GroupScope; + + fn key() -> GroupKey { + GroupKey { + repo_id: "repo-1".into(), + scanner: "gdpr-patterns".into(), + rule: "pii-logged".into(), + scope: GroupScope::File, + place: Some("src/patterns.rs".into()), + } + } + + fn request(status: FindingStatus, reason: Option<&str>) -> DecideGroupRequest { + DecideGroupRequest { + key: key(), + status, + reason: reason.map(String::from), + } + } + + fn user() -> Actor<'static> { + Actor { + id: "u-1", + name: None, + support: false, + } + } + + #[test] + fn a_group_takes_only_decisions() { + for status in [ + FindingStatus::Open, + FindingStatus::Triaged, + FindingStatus::NeedsReview, + ] { + assert_eq!( + decision_update(&request(status.clone(), Some("why")), &user()).err(), + Some(StatusCode::UNPROCESSABLE_ENTITY), + "{status}" + ); + } + for status in [ + FindingStatus::FalsePositive, + FindingStatus::Ignored, + FindingStatus::Resolved, + ] { + assert!( + decision_update(&request(status.clone(), None), &user()).is_ok(), + "{status}" + ); + } + } + + #[test] + fn an_accepted_risk_for_a_group_needs_a_reason() { + assert_eq!( + decision_update(&request(FindingStatus::AcceptedRisk, None), &user()).err(), + Some(StatusCode::UNPROCESSABLE_ENTITY) + ); + assert_eq!( + decision_update(&request(FindingStatus::AcceptedRisk, Some(" ")), &user()).err(), + Some(StatusCode::UNPROCESSABLE_ENTITY) + ); + let update = decision_update( + &request(FindingStatus::AcceptedRisk, Some("isolated network")), + &user(), + ) + .unwrap_or_default(); + let change = update + .get_document("$push") + .and_then(|p| p.get_document("status_history")) + .cloned() + .unwrap_or_default(); + assert_eq!(change.get_str("reason").ok(), Some("isolated network")); + assert_eq!(change.get_str("by").ok(), Some("u-1")); + } + + #[test] + fn a_request_reads_the_key_and_refuses_an_unknown_status() { + let wire = serde_json::json!({ + "key": { + "repo_id": "repo-1", + "scanner": "gdpr-patterns", + "rule": "pii-logged", + "scope": "file", + "place": "src/patterns.rs", + }, + "status": "false_positive", + }); + let req = serde_json::from_value::(wire.clone()); + assert_eq!(req.ok().map(|r| r.key), Some(key())); + let mut bad = wire.clone(); + bad["status"] = "wontfix".into(); + assert!(serde_json::from_value::(bad).is_err()); + let mut bad_scope = wire; + bad_scope["key"]["scope"] = "everywhere".into(); + assert!(serde_json::from_value::(bad_scope).is_err()); + } + + #[test] + fn the_candidates_are_the_rule_in_the_target() { + let filter = candidates_filter(&key()); + assert_eq!(filter.get_str("repo_id").ok(), Some("repo-1")); + assert_eq!(filter.get_str("scanner").ok(), Some("gdpr-patterns")); + assert_eq!(filter.get_array("$or").map(Vec::len).ok(), Some(2)); + } +} diff --git a/compliance-agent/src/api/handlers/findings.rs b/compliance-agent/src/api/handlers/findings.rs index 1e02189..a331b87 100644 --- a/compliance-agent/src/api/handlers/findings.rs +++ b/compliance-agent/src/api/handlers/findings.rs @@ -229,7 +229,7 @@ impl<'a> Actor<'a> { } } -fn status_update( +pub(crate) fn status_update( status: &FindingStatus, reason: Option<&str>, actor: &Actor<'_>, @@ -314,18 +314,42 @@ pub async fn bulk_update_finding_status( let update = status_update(&req.status, req.reason.as_deref(), &Actor::of(&tenant.0))?; let db = tenant_db(&agent, &tenant).await?; - let result = db - .findings() - .update_many(doc! { "_id": { "$in": oids.clone() } }, update) - .await - .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; - issue_sync(&agent, db).spawn(oids); + let filter = doc! { "_id": { "$in": oids.clone() } }; + let modified_count = apply_status(&agent, db, filter, oids, update).await?; Ok(Json( - serde_json::json!({ "status": "updated", "modified_count": result.modified_count }), + serde_json::json!({ "status": "updated", "modified_count": modified_count }), )) } +/// Apply the status change `update` (from [`status_update`]) to the findings +/// `filter` matches, then carry the new status over to the issues of `oids` +/// (the findings the filter is about) in the background: the one path every +/// change of many findings takes, a bulk change or a group decision (#951). +/// +/// # Returns +/// +/// How many findings changed. +/// +/// # Errors +/// +/// 500 when the database refuses the update. +pub(crate) async fn apply_status( + agent: &crate::agent::ComplianceAgent, + db: crate::database::Database, + filter: mongodb::bson::Document, + oids: Vec, + update: mongodb::bson::Document, +) -> Result { + let result = db + .findings() + .update_many(filter, update) + .await + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; + issue_sync(agent, db).spawn(oids); + Ok(result.modified_count) +} + /// PATCH /api/v1/findings/{id}/feedback — store the developer's feedback on a /// finding. 404 when there is no such finding. #[tracing::instrument(skip_all, fields(finding_id = %id))] diff --git a/compliance-agent/src/api/handlers/mod.rs b/compliance-agent/src/api/handlers/mod.rs index 0b5c924..f5ef4f7 100644 --- a/compliance-agent/src/api/handlers/mod.rs +++ b/compliance-agent/src/api/handlers/mod.rs @@ -6,6 +6,7 @@ pub mod demo_seed; pub mod dto; pub mod evidence; pub mod finding_breakdown; +pub mod finding_groups; 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 c22e6e0..aa94ba5 100644 --- a/compliance-agent/src/api/role_gate/router_tests.rs +++ b/compliance-agent/src/api/role_gate/router_tests.rs @@ -131,6 +131,8 @@ fn routes() -> Vec<(Method, String, bool)> { format!("/api/v1/findings/{ID}/feedback"), true, ), + (Method::GET, "/api/v1/finding-groups".into(), false), + (Method::POST, "/api/v1/finding-groups/decide".into(), true), (Method::POST, format!("/api/v1/targets/{ID}/findings"), true), ( Method::POST, diff --git a/compliance-agent/src/api/routes.rs b/compliance-agent/src/api/routes.rs index 92af1ac..784a326 100644 --- a/compliance-agent/src/api/routes.rs +++ b/compliance-agent/src/api/routes.rs @@ -107,6 +107,15 @@ pub fn build_router() -> Router { "/api/v1/findings/{id}/feedback", patch(handlers::update_finding_feedback), ) + // Undecided findings grouped by rule and file; one decision per group (#951). + .route( + "/api/v1/finding-groups", + get(handlers::finding_groups::list_finding_groups), + ) + .route( + "/api/v1/finding-groups/decide", + post(handlers::finding_groups::decide_finding_group), + ) // VEX on a target's CVE alerts (#498). .route( "/api/v1/targets/{id}/cves", diff --git a/compliance-core/src/models/finding_group.rs b/compliance-core/src/models/finding_group.rs new file mode 100644 index 0000000..b3d84d2 --- /dev/null +++ b/compliance-core/src/models/finding_group.rs @@ -0,0 +1,602 @@ +//! Open findings grouped by rule and place, so that one decision covers +//! every place a rule fired in a file (#951). +//! +//! This is a read-side view: nothing is stored. The grouping (#464) that +//! turns a rule firing all over a repository into one stored finding stays +//! as it is; such a finding is shown here as a group of its own and never +//! merged with others. +//! +//! The rules: +//! +//! * Only undecided findings (open, triaged, needs review) are grouped; a +//! decided one already has its decision. +//! * Findings of one scanner's rule in one file of a target are one group. +//! * When a rule fires in [`DIRECTORY_MIN_FILES`] or more files of one +//! directory, those files are one group for the directory (the files +//! directly in it, not in its subdirectories). +//! * A stored #464 group is a group of its own. + +use std::collections::{BTreeMap, HashMap, HashSet}; + +use bson::oid::ObjectId; +use serde::{Deserialize, Serialize}; + +use super::finding::{Finding, FindingStatus, Severity}; + +/// From how many files of one directory a rule's findings are one group +/// for the directory instead of one per file. +pub const DIRECTORY_MIN_FILES: usize = 3; + +/// What a group spans. +#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord, Hash)] +#[serde(rename_all = "snake_case")] +pub enum GroupScope { + /// The places of a rule in one file. + File, + /// The places of a rule in the files of one directory. + Directory, + /// A finding the scan already grouped for the whole repository (#464). + Repository, +} + +/// What identifies a group, from the view to the decision: the decision +/// finds the group's members again from it, so it applies to what is open +/// then, not to what a stale view showed. +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub struct GroupKey { + /// The target (`Finding::repo_id`). + pub repo_id: String, + /// The tool that reported it; rule ids are per tool. + pub scanner: String, + /// The rule id, or the title for a finding without one. + pub rule: String, + pub scope: GroupScope, + /// The file ([`GroupScope::File`]), the directory, `""` for the top + /// level ([`GroupScope::Directory`]), or the stored group's fingerprint + /// ([`GroupScope::Repository`]). `None` for findings without a file + /// (a dependency, a web endpoint). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub place: Option, +} + +impl GroupKey { + /// The key as one string, for telling groups apart in a view. + pub fn id(&self) -> String { + let scope = match self.scope { + GroupScope::File => "file", + GroupScope::Directory => "dir", + GroupScope::Repository => "repo", + }; + format!( + "{}|{}|{}|{scope}|{}", + self.repo_id, + self.scanner, + self.rule, + self.place.as_deref().unwrap_or_default() + ) + } +} + +/// What the automated review said about a group's members. +#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)] +pub struct GroupReview { + /// Members the AI dismissed: likely a false alarm. + pub likely_false_alarm: usize, + /// Members the AI was unsure about. + pub unsure: usize, + /// The AI's reason for the first of them (a dismissal first). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub rationale: Option, +} + +/// Undecided findings of one rule in one place, decided together. +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct FindingGroup { + pub key: GroupKey, + /// The title of the first member, as the tool wrote it. + pub title: String, + /// The highest severity among the members. + pub severity: Severity, + /// How many places the members stand for: one each, or every place of + /// a stored #464 group. + pub places: usize, + /// Set when the AI flagged members for review. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub review: Option, + /// The findings, by file and line. + pub members: Vec, +} + +impl FindingGroup { + /// The group of `members` (at least one) under `key`. + fn new(key: GroupKey, mut members: Vec) -> Self { + // `Option` sorts `None` first; members without a line lead. + members.sort_by(|a, b| { + (a.file_path.as_deref(), a.line_number).cmp(&(b.file_path.as_deref(), b.line_number)) + }); + let severity = members + .iter() + .map(|f| f.severity.clone()) + .max() + .unwrap_or(Severity::Info); + let places = members.iter().map(|f| f.occurrences.len().max(1)).sum(); + Self { + title: members.first().map(|f| f.title.clone()).unwrap_or_default(), + review: review_of(&members), + key, + severity, + places, + members, + } + } + + /// The ids of the members. + pub fn member_ids(&self) -> Vec { + self.members.iter().filter_map(|f| f.id).collect() + } +} + +/// Whether no person has decided about a finding with `status` yet. +pub fn is_undecided(status: &FindingStatus) -> bool { + match status { + FindingStatus::Open | FindingStatus::Triaged | FindingStatus::NeedsReview => true, + FindingStatus::FalsePositive + | FindingStatus::Resolved + | FindingStatus::Ignored + | FindingStatus::AcceptedRisk + | FindingStatus::WrongMapping => false, + } +} + +/// What the AI's review said about one finding. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum AiReview { + /// It dismissed the finding. + LikelyFalseAlarm, + /// It was not confident either way. + Unsure, +} + +/// The AI's review of `finding`, when it left the finding for a person. +/// +/// Mirrors the predicate PR #958 adds as `Finding::review_reason()`; switch +/// to that once it is merged. +fn ai_review(finding: &Finding) -> Option { + if finding.status != FindingStatus::NeedsReview { + return None; + } + Some(match finding.triage_action.as_deref() { + Some("dismiss") => AiReview::LikelyFalseAlarm, + _ => AiReview::Unsure, + }) +} + +/// What the AI said about `members`, `None` when it flagged none of them. +fn review_of(members: &[Finding]) -> Option { + let mut review = GroupReview::default(); + let mut unsure_rationale = None; + for finding in members { + let rationale = finding + .triage_rationale + .as_deref() + .map(str::trim) + .filter(|r| !r.is_empty()); + match ai_review(finding) { + Some(AiReview::LikelyFalseAlarm) => { + review.likely_false_alarm += 1; + review.rationale = review.rationale.or_else(|| rationale.map(String::from)); + } + Some(AiReview::Unsure) => { + review.unsure += 1; + unsure_rationale = unsure_rationale.or(rationale); + } + None => {} + } + } + if review.likely_false_alarm + review.unsure == 0 { + return None; + } + review.rationale = review + .rationale + .or_else(|| unsure_rationale.map(String::from)); + Some(review) +} + +/// The rule a finding is grouped by: its id, or its title without one. +fn rule_of(finding: &Finding) -> String { + finding + .rule_id + .as_deref() + .filter(|r| !r.is_empty()) + .unwrap_or(&finding.title) + .to_string() +} + +/// The directory of a repo-relative `path`, `""` at the top level. +fn parent_dir(path: &str) -> &str { + path.rfind(['/', '\\']).map_or("", |i| &path[..i]) +} + +/// A rule of one tool in one target: (target, scanner, rule). +type RuleInTarget = (String, String, String); + +/// Findings by their file (`None`: without one). +type ByFile = BTreeMap, Vec>; + +/// Group the undecided ones among `findings` (see the module docs); decided +/// findings are left out. +/// +/// # Returns +/// +/// The groups, most severe first, then the ones with the most places. +/// +/// # Examples +/// +/// ``` +/// use compliance_core::models::finding_group::group_findings; +/// use compliance_core::models::{Finding, ScanType, Severity}; +/// +/// let at = |line| { +/// let mut f = Finding::new( +/// "repo".into(), format!("fp-{line}"), "gdpr-patterns".into(), +/// ScanType::Sast, "PII data potentially logged".into(), "".into(), +/// Severity::Medium, +/// ); +/// f.rule_id = Some("pii-logged".into()); +/// f.file_path = Some("src/patterns.rs".into()); +/// f.line_number = Some(line); +/// f +/// }; +/// let groups = group_findings(vec![at(299), at(302)]); +/// assert_eq!(groups.len(), 1); +/// assert_eq!(groups[0].places, 2); +/// ``` +pub fn group_findings(findings: impl IntoIterator) -> Vec { + let mut groups = Vec::new(); + let mut by_rule: HashMap = HashMap::new(); + for finding in findings.into_iter().filter(|f| is_undecided(&f.status)) { + let rule = rule_of(&finding); + if !finding.occurrences.is_empty() { + let key = GroupKey { + repo_id: finding.repo_id.clone(), + scanner: finding.scanner.clone(), + rule, + scope: GroupScope::Repository, + place: Some(finding.fingerprint.clone()), + }; + groups.push(FindingGroup::new(key, vec![finding])); + continue; + } + let file = finding.file_path.clone().filter(|p| !p.is_empty()); + by_rule + .entry((finding.repo_id.clone(), finding.scanner.clone(), rule)) + .or_default() + .entry(file) + .or_default() + .push(finding); + } + + for ((repo_id, scanner, rule), by_file) in by_rule { + let key = |scope, place| GroupKey { + repo_id: repo_id.clone(), + scanner: scanner.clone(), + rule: rule.clone(), + scope, + place, + }; + let mut files_per_dir: HashMap<&str, usize> = HashMap::new(); + for file in by_file.keys().flatten() { + *files_per_dir.entry(parent_dir(file)).or_default() += 1; + } + let wide_dirs: HashSet = files_per_dir + .into_iter() + .filter(|(_, files)| *files >= DIRECTORY_MIN_FILES) + .map(|(dir, _)| dir.to_string()) + .collect(); + + let mut by_dir: BTreeMap> = BTreeMap::new(); + for (file, members) in by_file { + match file { + Some(file) if wide_dirs.contains(parent_dir(&file)) => by_dir + .entry(parent_dir(&file).to_string()) + .or_default() + .extend(members), + file => groups.push(FindingGroup::new(key(GroupScope::File, file), members)), + } + } + groups.extend(by_dir.into_iter().map(|(dir, members)| { + FindingGroup::new(key(GroupScope::Directory, Some(dir)), members) + })); + } + + groups.sort_by(|a, b| { + b.severity + .cmp(&a.severity) + .then(b.places.cmp(&a.places)) + .then_with(|| a.key.cmp(&b.key)) + }); + groups +} + +/// The ids of the undecided findings among `findings` that make up the +/// group `key`; empty when there is no such group (any more). +pub fn members_of(findings: impl IntoIterator, key: &GroupKey) -> Vec { + group_findings(findings) + .into_iter() + .find(|g| g.key == *key) + .map(|g| g.member_ids()) + .unwrap_or_default() +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::models::{Occurrence, ScanType}; + + fn finding(rule: &str, file: &str, line: u32) -> Finding { + let mut f = Finding::new( + "repo-1".into(), + format!("fp-{file}-{line}"), + "gdpr-patterns".into(), + ScanType::Sast, + "PII data potentially logged".into(), + "d".into(), + Severity::Medium, + ); + f.id = Some(ObjectId::new()); + f.rule_id = Some(rule.into()); + f.file_path = Some(file.into()); + f.line_number = Some(line); + f + } + + fn scopes(groups: &[FindingGroup]) -> Vec<(GroupScope, Option<&str>, usize)> { + groups + .iter() + .map(|g| (g.key.scope, g.key.place.as_deref(), g.members.len())) + .collect() + } + + #[test] + fn one_rule_in_one_file_is_one_group() { + let groups = group_findings(vec![ + finding("pii-logged", "src/patterns.rs", 302), + finding("pii-logged", "src/patterns.rs", 299), + finding("pii-logged", "src/patterns.rs", 301), + ]); + assert_eq!( + scopes(&groups), + [(GroupScope::File, Some("src/patterns.rs"), 3)] + ); + assert_eq!(groups[0].places, 3); + let lines: Vec<_> = groups[0].members.iter().map(|f| f.line_number).collect(); + assert_eq!(lines, [Some(299), Some(301), Some(302)]); + } + + #[test] + fn other_files_and_other_rules_are_other_groups() { + let groups = group_findings(vec![ + finding("pii-logged", "src/a.rs", 1), + finding("pii-logged", "lib/b.rs", 1), + finding("other-rule", "src/a.rs", 2), + ]); + assert_eq!(groups.len(), 3); + assert!(groups.iter().all(|g| g.key.scope == GroupScope::File)); + } + + #[test] + fn the_same_rule_id_of_another_tool_is_another_group() { + let mut other = finding("pii-logged", "src/a.rs", 2); + other.scanner = "semgrep".into(); + let groups = group_findings(vec![finding("pii-logged", "src/a.rs", 1), other]); + assert_eq!(groups.len(), 2); + } + + #[test] + fn many_files_of_one_directory_are_one_group() { + let groups = group_findings(vec![ + finding("pii-logged", "src/api/a.rs", 1), + finding("pii-logged", "src/api/a.rs", 9), + finding("pii-logged", "src/api/b.rs", 1), + finding("pii-logged", "src/api/c.rs", 1), + // A subdirectory and another directory stay apart. + finding("pii-logged", "src/api/v2/d.rs", 1), + finding("pii-logged", "src/e.rs", 1), + ]); + let mut found = scopes(&groups); + found.sort(); + assert_eq!( + found, + [ + (GroupScope::File, Some("src/api/v2/d.rs"), 1), + (GroupScope::File, Some("src/e.rs"), 1), + (GroupScope::Directory, Some("src/api"), 4), + ] + ); + } + + #[test] + fn fewer_files_than_the_directory_needs_stay_one_group_per_file() { + let groups = group_findings(vec![ + finding("pii-logged", "src/a.rs", 1), + finding("pii-logged", "src/b.rs", 1), + ]); + assert_eq!(groups.len(), DIRECTORY_MIN_FILES - 1); + assert!(groups.iter().all(|g| g.key.scope == GroupScope::File)); + } + + #[test] + fn top_level_files_group_under_the_empty_directory() { + let groups = group_findings(vec![ + finding("pii-logged", "a.rs", 1), + finding("pii-logged", "b.rs", 1), + finding("pii-logged", "c.rs", 1), + ]); + assert_eq!(scopes(&groups), [(GroupScope::Directory, Some(""), 3)]); + } + + #[test] + fn decided_findings_are_left_out() { + let mut decided = finding("pii-logged", "src/a.rs", 2); + decided.status = FindingStatus::FalsePositive; + let mut accepted = finding("pii-logged", "src/a.rs", 3); + accepted.status = FindingStatus::AcceptedRisk; + let mut triaged = finding("pii-logged", "src/a.rs", 4); + triaged.status = FindingStatus::Triaged; + let groups = group_findings(vec![ + finding("pii-logged", "src/a.rs", 1), + decided, + accepted, + triaged, + ]); + assert_eq!(scopes(&groups), [(GroupScope::File, Some("src/a.rs"), 2)]); + assert!(group_findings(vec![{ + let mut f = finding("r", "x.rs", 1); + f.status = FindingStatus::Resolved; + f + }]) + .is_empty()); + } + + #[test] + fn a_stored_group_stays_a_group_of_its_own() { + let mut stored = finding("pii-logged", "src/a.rs", 1); + stored.fingerprint = "group-fp".into(); + stored.occurrences = (1..=7) + .map(|line| Occurrence { + file: "src/a.rs".into(), + line: Some(line), + variant: None, + decision: None, + }) + .collect(); + let groups = group_findings(vec![stored, finding("pii-logged", "src/a.rs", 20)]); + assert_eq!( + scopes(&groups), + [ + (GroupScope::Repository, Some("group-fp"), 1), + (GroupScope::File, Some("src/a.rs"), 1), + ] + ); + assert_eq!(groups[0].places, 7); + } + + #[test] + fn findings_without_a_file_or_rule_still_group() { + let mut no_file = finding("CVE-2024-1", "", 0); + no_file.file_path = None; + let mut no_file_2 = no_file.clone(); + no_file_2.id = Some(ObjectId::new()); + let mut no_rule = finding("", "src/a.rs", 1); + no_rule.rule_id = None; + let groups = group_findings(vec![no_file, no_file_2, no_rule]); + let mut found: Vec<_> = groups + .iter() + .map(|g| (g.key.rule.as_str(), g.key.place.as_deref(), g.members.len())) + .collect(); + found.sort(); + assert_eq!( + found, + [ + ("CVE-2024-1", None, 2), + ("PII data potentially logged", Some("src/a.rs"), 1), + ] + ); + } + + #[test] + fn the_most_severe_group_leads() { + let mut critical = finding("hardcoded-key", "src/z.rs", 1); + critical.severity = Severity::Critical; + let groups = group_findings(vec![ + finding("pii-logged", "src/a.rs", 1), + finding("pii-logged", "src/a.rs", 2), + critical, + ]); + assert_eq!(groups[0].severity, Severity::Critical); + assert_eq!(groups[1].places, 2); + } + + #[test] + fn the_group_carries_the_ais_reason() { + let mut dismissed = finding("pii-logged", "src/a.rs", 1); + dismissed.status = FindingStatus::NeedsReview; + dismissed.triage_action = Some("dismiss".into()); + dismissed.triage_rationale = Some(" Only a user id, no PII. ".into()); + let mut unsure = finding("pii-logged", "src/a.rs", 2); + unsure.status = FindingStatus::NeedsReview; + unsure.triage_action = Some("confirm".into()); + unsure.triage_rationale = Some("Unclear".into()); + let groups = group_findings(vec![ + unsure, + dismissed, + finding("pii-logged", "src/a.rs", 3), + ]); + assert_eq!( + groups[0].review, + Some(GroupReview { + likely_false_alarm: 1, + unsure: 1, + rationale: Some("Only a user id, no PII.".into()), + }) + ); + assert_eq!( + group_findings(vec![finding("r", "a.rs", 1)])[0].review, + None + ); + } + + #[test] + fn the_members_of_a_key_are_found_again() { + let one = finding("pii-logged", "src/a.rs", 1); + let two = finding("pii-logged", "src/a.rs", 2); + let other = finding("pii-logged", "src/b.rs", 1); + let ids = [one.id, two.id]; + let all = vec![one, two, other]; + let key = GroupKey { + repo_id: "repo-1".into(), + scanner: "gdpr-patterns".into(), + rule: "pii-logged".into(), + scope: GroupScope::File, + place: Some("src/a.rs".into()), + }; + let mut found: Vec<_> = members_of(all.clone(), &key) + .into_iter() + .map(Some) + .collect(); + found.sort(); + let mut expected = ids.to_vec(); + expected.sort(); + assert_eq!(found, expected); + let gone = GroupKey { + place: Some("src/c.rs".into()), + ..key + }; + assert!(members_of(all, &gone).is_empty()); + } + + #[test] + fn a_key_reads_and_writes_by_its_names() { + let key = GroupKey { + repo_id: "r".into(), + scanner: "s".into(), + rule: "x".into(), + scope: GroupScope::Directory, + place: Some("src".into()), + }; + let wire = serde_json::to_value(&key).unwrap_or_default(); + assert_eq!(wire["scope"], "directory"); + assert_eq!( + serde_json::from_value::(wire).ok().as_ref(), + Some(&key) + ); + assert_ne!( + key.id(), + GroupKey { + scope: GroupScope::File, + ..key.clone() + } + .id() + ); + } +} diff --git a/compliance-core/src/models/mod.rs b/compliance-core/src/models/mod.rs index 6229fd4..99a5f0c 100644 --- a/compliance-core/src/models/mod.rs +++ b/compliance-core/src/models/mod.rs @@ -6,6 +6,7 @@ pub mod dast; pub mod embedding; pub mod exclude_paths; pub mod finding; +pub mod finding_group; pub mod git_source; pub mod graph; pub mod issue; diff --git a/compliance-dashboard/assets/main.css b/compliance-dashboard/assets/main.css index b2f5fe4..229e420 100644 --- a/compliance-dashboard/assets/main.css +++ b/compliance-dashboard/assets/main.css @@ -6675,3 +6675,153 @@ input[type="file"] { .fb-back { margin-left: auto; } + +/* Findings grouped by rule and file (#951) */ +.view-switch { + display: inline-flex; + margin-bottom: 12px; + padding: 2px; + border: 1px solid var(--border); + border-radius: var(--radius); + background: var(--bg-elevated); +} + +.view-switch-btn { + padding: 4px 12px; + border: 0; + border-radius: var(--radius-sm); + background: transparent; + color: var(--text-secondary); + font: 500 12.5px var(--font-body); + cursor: pointer; +} + +.view-switch-btn.active { + background: var(--bg-card); + color: var(--text-primary); + box-shadow: 0 1px 2px rgb(20 22 43 / 0.08); +} + +.fgroup-hint { + margin: 0 0 12px; + font-size: 13px; + color: var(--text-tertiary); +} + +.fgroup-list { + display: flex; + flex-direction: column; + gap: 10px; +} + +.fgroup { + padding: 14px 16px; +} + +.fgroup-empty { + padding: 24px; + text-align: center; + color: var(--text-tertiary); +} + +.fgroup-head { + display: flex; + align-items: flex-start; + gap: 12px; +} + +.fgroup-heading { + min-width: 0; +} + +.fgroup-title { + font-weight: 500; + color: var(--text-primary); + overflow-wrap: anywhere; +} + +.fgroup-places { + font-weight: 400; + color: var(--text-secondary); +} + +.fgroup-meta { + display: flex; + flex-wrap: wrap; + gap: 4px 12px; + margin-top: 3px; + font-size: 11.5px; + color: var(--text-tertiary); +} + +.fgroup-rule { + font-family: var(--font-mono); + overflow-wrap: anywhere; +} + +.fgroup-ai { + margin-top: 10px; + padding: 8px 10px; + border-left: 3px solid var(--info); + border-radius: var(--radius-sm); + background: var(--info-bg); + font-size: 13px; + color: var(--text-secondary); +} + +.fgroup-ai-verdict { + display: block; + font-weight: 500; + color: var(--text-primary); +} + +.fgroup-ai-reason { + display: block; + margin-top: 2px; +} + +.fgroup-actions, +.fgroup-reason-actions { + display: flex; + flex-wrap: wrap; + gap: 8px; + margin-top: 10px; +} + +.fgroup-reason label { + display: block; + margin-top: 10px; + font-size: 13px; + color: var(--text-secondary); +} + +.fgroup-reason textarea { + display: block; + width: 100%; + min-height: 60px; + margin-top: 6px; +} + +.fgroup-members { + margin: 10px 0 0; + padding: 8px 0 0; + border-top: 1px solid var(--border); + list-style: none; +} + +.fgroup-members li { + display: flex; + justify-content: space-between; + gap: 12px; + padding: 3px 0; +} + +.fgroup-members .finding-location { + min-width: 0; +} + +.fgroup-member-status { + flex-shrink: 0; + font-size: 12px; + color: var(--text-tertiary); +} diff --git a/compliance-dashboard/src/components/finding_groups.rs b/compliance-dashboard/src/components/finding_groups.rs new file mode 100644 index 0000000..3fc246a --- /dev/null +++ b/compliance-dashboard/src/components/finding_groups.rs @@ -0,0 +1,303 @@ +//! The grouped view of the findings list (#951): the undecided findings as +//! one card per rule and file, each decided at once. + +use std::collections::{HashMap, HashSet}; + +use dioxus::prelude::*; + +use compliance_core::models::finding_group::{FindingGroup, GroupKey, GroupScope}; +use compliance_core::models::FindingStatus; + +use crate::app::Route; +use crate::components::severity_badge::SeverityBadge; +use crate::components::toast::{ToastType, Toasts}; +use crate::i18n::texts::{common, finding_groups as tx, findings as ftx}; +use crate::i18n::{use_lang, Lang}; +use crate::infrastructure::finding_groups::{decide_finding_group, fetch_finding_groups}; +use crate::infrastructure::findings::location; +use crate::infrastructure::onboarding::TargetsResponse; + +/// The grouped findings of `target` (all targets when empty), with the +/// group decisions for users who may write. +/// +/// # Arguments +/// +/// * `target` - the target filter of the list +/// * `targets` - the targets the list already loaded, to name each group's +/// target when the list shows all of them +#[component] +pub fn FindingGroups( + target: Signal, + targets: Resource>, +) -> Element { + let lang = use_lang()(); + let can_write = crate::components::no_access::use_can_write(); + let mut toasts = use_context::(); + let mut groups = use_resource(move || { + let target = target(); + async move { fetch_finding_groups(target).await } + }); + // The groups whose places are shown, by `GroupKey::id`. + let mut expanded = use_signal(HashSet::::new); + // The group whose risk is being accepted, waiting for the reason. + let mut reasoning = use_signal(|| None::); + let mut reason = use_signal(String::new); + let mut busy = use_signal(|| false); + + // Signals are `Copy`, so this closure is too and every card can hold it. + let mut decide = move |key: GroupKey, status: FindingStatus, why: Option| { + busy.set(true); + spawn(async move { + match decide_finding_group(key, status, why).await { + Ok(changed) => { + toasts.push(ToastType::Success, tx::decided(changed, lang)); + reasoning.set(None); + reason.set(String::new()); + } + Err(e) => toasts.push( + ToastType::Error, + format!("{}: {e}", tx::DECIDE_FAILED.get(lang)), + ), + } + busy.set(false); + groups.restart(); + }); + }; + + let names = target().is_empty().then(|| { + targets + .read() + .as_ref() + .and_then(|r| r.as_ref()) + .map(target_names) + .unwrap_or_default() + }); + + rsx! { + p { class: "fgroup-hint", {tx::HINT.get(lang)} } + match &*groups.read() { + Some(Ok(list)) if list.is_empty() => rsx! { + div { class: "card fgroup-empty", {tx::NONE.get(lang)} } + }, + Some(Ok(list)) => rsx! { + div { class: "fgroup-list", + for group in list.iter() { + { + let id = group.key.id(); + let is_open = expanded.read().contains(&id); + let awaiting_reason = reasoning.read().as_deref() == Some(id.as_str()); + let key_fp = group.key.clone(); + let key_risk = group.key.clone(); + let id_toggle = id.clone(); + let id_reason = id.clone(); + let target_name = names + .as_ref() + .and_then(|n| n.get(&group.key.repo_id)) + .cloned(); + rsx! { + div { class: "card fgroup", key: "{id}", + div { class: "fgroup-head", + SeverityBadge { severity: group.severity.to_string() } + div { class: "fgroup-heading", + div { class: "fgroup-title", + "{group.title}" + span { class: "fgroup-places", + // The whole path; a stored group's place is its fingerprint. + title: group.key.place.clone().filter(|_| group.key.scope != GroupScope::Repository).unwrap_or_default(), + " — {places_label(group, lang)}" + } + } + div { class: "fgroup-meta", + span { title: "{group.key.scanner}", + {ftx::tool_name(&group.key.scanner, lang)} + } + span { class: "fgroup-rule", "{group.key.rule}" } + if let Some(name) = target_name { + span { class: "finding-target", "{name}" } + } + } + } + } + if let Some(review) = &group.review { + div { class: "fgroup-ai", + span { class: "fgroup-ai-verdict", + {tx::ai_review(review.likely_false_alarm, review.unsure, group.members.len(), lang)} + } + if let Some(rationale) = &review.rationale { + span { class: "fgroup-ai-reason", title: tx::AI_REASON.get(lang), "{rationale}" } + } + } + } + div { class: "fgroup-actions", + button { + class: "btn btn-sm btn-ghost", + "aria-expanded": "{is_open}", + onclick: move |_| { + let mut open = expanded.write(); + if !open.remove(&id_toggle) { + open.insert(id_toggle.clone()); + } + }, + if is_open { {tx::HIDE_PLACES.get(lang)} } else { {tx::SHOW_PLACES.get(lang)} } + } + // Deciding is a change: read-only roles only look. + if can_write { + button { + class: "btn btn-sm", + disabled: busy(), + onclick: move |_| decide(key_fp.clone(), FindingStatus::FalsePositive, None), + {tx::false_alarm_all(group.members.len(), lang)} + } + button { + class: "btn btn-sm", + disabled: busy(), + onclick: move |_| { + reason.set(String::new()); + reasoning.set(Some(id_reason.clone())); + }, + {tx::accept_risk_all(group.members.len(), lang)} + } + } + } + if can_write && awaiting_reason { + div { class: "fgroup-reason", + label { + span { {ftx::ACCEPT_RISK_HINT.get(lang)} } + textarea { + value: "{reason}", + oninput: move |e| reason.set(e.value()), + } + } + div { class: "fgroup-reason-actions", + button { + class: "btn btn-sm btn-primary", + disabled: busy() || reason().trim().is_empty(), + onclick: move |_| decide(key_risk.clone(), FindingStatus::AcceptedRisk, Some(reason())), + {ftx::ACCEPT_RISK.get(lang)} + } + button { + class: "btn btn-sm btn-ghost", + onclick: move |_| reasoning.set(None), + {tx::CANCEL.get(lang)} + } + } + } + } + if is_open { + ul { class: "fgroup-members", + for member in group.members.iter() { + { + let member_id = member.id.map(|id| id.to_hex()).unwrap_or_default(); + rsx! { + li { key: "{member_id}", + Link { + to: Route::FindingDetailPage { id: member_id.clone() }, + class: "finding-location", + {location(member.file_path.as_deref(), member.line_number).unwrap_or_else(|| member.title.clone())} + } + span { class: "fgroup-member-status", {ftx::status(&member.status).get(lang)} } + } + } + } + } + } + } + } + } + } + } + } + }, + Some(Err(_)) => rsx! { + div { class: "card", p { {tx::LOAD_FAILED.get(lang)} } } + }, + None => rsx! { + div { class: "loading", {common::LOADING.get(lang)} } + }, + } + } +} + +/// Where a group's places are, in words: "12 Stellen in patterns.rs". +fn places_label(group: &FindingGroup, lang: Lang) -> String { + let place = group.key.place.as_deref(); + match group.key.scope { + GroupScope::File => { + // The file name; the card's tooltip has the whole path. + let file = place.map(|p| p.rsplit(['/', '\\']).next().unwrap_or(p)); + tx::places_in(group.places, file, false, lang) + } + GroupScope::Directory => tx::places_in(group.places, place, true, lang), + GroupScope::Repository => tx::places_in_repository(group.places, lang), + } +} + +/// The targets' names by id. +fn target_names(targets: &TargetsResponse) -> HashMap { + targets + .data + .iter() + .filter_map(|t| { + let id = t.get("_id")?.get("$oid")?.as_str()?.to_string(); + let name = t.get("name")?.as_str()?.to_string(); + Some((id, name)) + }) + .collect() +} + +#[cfg(test)] +mod tests { + use super::*; + use compliance_core::models::finding_group::group_findings; + use compliance_core::models::{Finding, ScanType, Severity}; + + fn at(file: &str, line: u32) -> Finding { + let mut f = Finding::new( + "repo".into(), + format!("fp-{file}-{line}"), + "gdpr-patterns".into(), + ScanType::Sast, + "PII data potentially logged".into(), + "d".into(), + Severity::Medium, + ); + f.rule_id = Some("pii-logged".into()); + f.file_path = Some(file.into()); + f.line_number = Some(line); + f + } + + #[test] + fn a_file_group_is_named_by_its_file() { + let groups = group_findings(vec![ + at("src/pipeline/patterns.rs", 299), + at("src/pipeline/patterns.rs", 302), + ]); + assert_eq!( + places_label(&groups[0], Lang::De), + "2 Stellen in patterns.rs" + ); + } + + #[test] + fn a_directory_group_is_named_by_its_directory() { + let groups = group_findings(vec![ + at("src/a.rs", 1), + at("src/b.rs", 1), + at("src/c.rs", 1), + ]); + assert_eq!(places_label(&groups[0], Lang::En), "3 places in src/"); + } + + #[test] + fn target_names_come_from_the_target_list() { + let targets = TargetsResponse { + data: vec![serde_json::json!({ "_id": { "$oid": "t1" }, "name": "Firmware" })], + total: Some(1), + }; + assert_eq!( + target_names(&targets).get("t1").map(String::as_str), + Some("Firmware") + ); + } +} diff --git a/compliance-dashboard/src/components/mod.rs b/compliance-dashboard/src/components/mod.rs index 61ff07d..ed14e01 100644 --- a/compliance-dashboard/src/components/mod.rs +++ b/compliance-dashboard/src/components/mod.rs @@ -12,6 +12,7 @@ pub mod demo_targets; pub mod evidence_button; pub mod file_tree; pub mod finding_breakdown; +pub mod finding_groups; pub mod help_chat; pub mod lang_toggle; pub mod layer_pins; diff --git a/compliance-dashboard/src/i18n/texts.rs b/compliance-dashboard/src/i18n/texts.rs index fd94e81..ceef4b0 100644 --- a/compliance-dashboard/src/i18n/texts.rs +++ b/compliance-dashboard/src/i18n/texts.rs @@ -2385,6 +2385,197 @@ pub mod findings { }; } +/// The findings grouped by rule and file (#951). +pub mod finding_groups { + use super::super::Lang; + use super::Text; + + pub const VIEW: Text = Text { + de: "Ansicht", + en: "View", + }; + pub const GROUPED: Text = Text { + de: "Gruppiert", + en: "Grouped", + }; + pub const SINGLE: Text = Text { + de: "Einzeln", + en: "Single", + }; + pub const HINT: Text = Text { + de: "Offene Befunde, gebündelt nach Regel und Datei. Eine Entscheidung gilt \ + für jede Stelle der Gruppe. Hier gilt nur der Prüfobjekt-Filter.", + en: "Open findings, bundled by rule and file. One decision applies to every \ + place in the group. Only the target filter applies here.", + }; + pub const NONE: Text = Text { + de: "Keine offenen Befunde.", + en: "No open findings.", + }; + pub const LOAD_FAILED: Text = Text { + de: "Die Gruppen konnten nicht geladen werden.", + en: "The groups could not be loaded.", + }; + pub const SHOW_PLACES: Text = Text { + de: "Stellen zeigen", + en: "Show places", + }; + pub const HIDE_PLACES: Text = Text { + de: "Stellen ausblenden", + en: "Hide places", + }; + pub const AI_REASON: Text = Text { + de: "Begründung der KI", + en: "The AI's reason", + }; + pub const DECIDE_FAILED: Text = Text { + de: "Entscheidung nicht gespeichert", + en: "Decision not saved", + }; + pub const CANCEL: Text = Text { + de: "Abbrechen", + en: "Cancel", + }; + + /// How many places a group has, and where: "12 Stellen in patterns.rs", + /// "3 Stellen in src/api/". + /// + /// # Arguments + /// + /// * `places` - how many places + /// * `place` - the file name or directory; `None` for findings without + /// a file + /// * `directory` - whether `place` is a directory (`""` is the top level) + /// * `lang` - the reader's language + pub fn places_in(places: usize, place: Option<&str>, directory: bool, lang: Lang) -> String { + let count = match (lang, places) { + (Lang::De, 1) => "1 Stelle".to_string(), + (Lang::De, n) => format!("{n} Stellen"), + (Lang::En, 1) => "1 place".to_string(), + (Lang::En, n) => format!("{n} places"), + }; + match (place, directory, lang) { + (Some(""), true, Lang::De) => format!("{count} im obersten Verzeichnis"), + (Some(""), true, Lang::En) => format!("{count} at the top level"), + (Some(dir), true, _) => format!("{count} in {dir}/"), + (Some(file), false, _) => format!("{count} in {file}"), + (None, _, _) => count, + } + } + + /// The same, for a group the scan made for the whole repository: + /// "40 Stellen im ganzen Repository". + pub fn places_in_repository(places: usize, lang: Lang) -> String { + let count = places_in(places, None, false, lang); + match lang { + Lang::De => format!("{count} im ganzen Repository"), + Lang::En => format!("{count} across the repository"), + } + } + + /// What the AI said about a group of `members` findings: "KI: wohl + /// Fehlalarm (3 von 12)" when it dismissed some, else "KI: unsicher". + pub fn ai_review( + likely_false_alarm: usize, + unsure: usize, + members: usize, + lang: Lang, + ) -> String { + let (verdict, flagged) = match (likely_false_alarm, lang) { + (0, Lang::De) => ("KI: unsicher", unsure), + (0, Lang::En) => ("AI: unsure", unsure), + (n, Lang::De) => ("KI: wohl Fehlalarm", n), + (n, Lang::En) => ("AI: likely a false alarm", n), + }; + if flagged == members { + return verdict.to_string(); + } + match lang { + Lang::De => format!("{verdict} ({flagged} von {members})"), + Lang::En => format!("{verdict} ({flagged} of {members})"), + } + } + + /// The button that marks every member a false alarm. + pub fn false_alarm_all(members: usize, lang: Lang) -> String { + match (lang, members) { + (Lang::De, 1) => "Fehlalarm".to_string(), + (Lang::En, 1) => "False alarm".to_string(), + (Lang::De, n) => format!("Fehlalarm (alle {n})"), + (Lang::En, n) => format!("False alarm (all {n})"), + } + } + + /// The button that accepts the risk of every member. + pub fn accept_risk_all(members: usize, lang: Lang) -> String { + match (lang, members) { + (Lang::De, 1) => "Risiko akzeptiert".to_string(), + (Lang::En, 1) => "Risk accepted".to_string(), + (Lang::De, n) => format!("Risiko akzeptiert (alle {n})"), + (Lang::En, n) => format!("Risk accepted (all {n})"), + } + } + + /// The notice after a decision. + pub fn decided(changed: u64, lang: Lang) -> String { + match (lang, changed) { + (Lang::De, 1) => "1 Befund entschieden".to_string(), + (Lang::En, 1) => "1 finding decided".to_string(), + (Lang::De, n) => format!("{n} Befunde entschieden"), + (Lang::En, n) => format!("{n} findings decided"), + } + } + + #[cfg(test)] + mod tests { + use super::*; + + #[test] + fn the_place_count_reads_like_the_language() { + assert_eq!( + places_in(12, Some("patterns.rs"), false, Lang::De), + "12 Stellen in patterns.rs" + ); + assert_eq!( + places_in(1, Some("patterns.rs"), false, Lang::En), + "1 place in patterns.rs" + ); + assert_eq!( + places_in(3, Some("src/api"), true, Lang::De), + "3 Stellen in src/api/" + ); + assert_eq!( + places_in(3, Some(""), true, Lang::En), + "3 places at the top level" + ); + assert_eq!(places_in(2, None, false, Lang::De), "2 Stellen"); + assert_eq!( + places_in_repository(40, Lang::De), + "40 Stellen im ganzen Repository" + ); + } + + #[test] + fn the_ais_verdict_says_how_many_it_covers() { + assert_eq!(ai_review(12, 0, 12, Lang::De), "KI: wohl Fehlalarm"); + assert_eq!( + ai_review(3, 1, 12, Lang::De), + "KI: wohl Fehlalarm (3 von 12)" + ); + assert_eq!(ai_review(0, 2, 5, Lang::En), "AI: unsure (2 of 5)"); + } + + #[test] + fn the_group_buttons_name_how_many_they_decide() { + assert_eq!(false_alarm_all(12, Lang::De), "Fehlalarm (alle 12)"); + assert_eq!(false_alarm_all(1, Lang::De), "Fehlalarm"); + assert_eq!(accept_risk_all(4, Lang::En), "Risk accepted (all 4)"); + assert_eq!(decided(1, Lang::De), "1 Befund entschieden"); + assert_eq!(decided(7, Lang::En), "7 findings decided"); + } + } +} + /// The SBOM page. pub mod sbom { use super::Text; diff --git a/compliance-dashboard/src/infrastructure/finding_groups.rs b/compliance-dashboard/src/infrastructure/finding_groups.rs new file mode 100644 index 0000000..03b6486 --- /dev/null +++ b/compliance-dashboard/src/infrastructure/finding_groups.rs @@ -0,0 +1,61 @@ +//! Findings grouped by rule and file, and one decision per group (#951). + +use dioxus::prelude::*; + +use compliance_core::models::finding_group::{FindingGroup, GroupKey}; +use compliance_core::models::FindingStatus; + +/// The undecided findings grouped by rule and file, of one target when +/// `target` is set, most severe first. +/// +/// # Errors +/// +/// The agent could not be reached or refused the request. +#[server] +pub async fn fetch_finding_groups(target: String) -> Result, ServerFnError> { + let mut path = "/api/v1/finding-groups".to_string(); + if !target.is_empty() { + path.push_str("?target="); + path.extend(url::form_urlencoded::byte_serialize(target.as_bytes())); + } + let resp = super::agent_client::agent_get(&path) + .await? + .send() + .await + .map_err(|e| ServerFnError::new(e.to_string()))?; + /// The agent's answer; only the groups are needed. + #[derive(serde::Deserialize)] + struct Groups { + data: Vec, + } + let body: Groups = super::agent_client::json_or_error(resp).await?; + Ok(body.data) +} + +/// Give every undecided member of the group `key` the status `status`, with +/// `reason` (required for an accepted risk). +/// +/// # Returns +/// +/// How many findings changed. +/// +/// # Errors +/// +/// The agent refused it: no write access, no reason where one is needed, or +/// the group has no undecided member any more. +#[server] +pub async fn decide_finding_group( + key: GroupKey, + status: FindingStatus, + reason: Option, +) -> Result { + let resp = + super::agent_client::agent_request(reqwest::Method::POST, "/api/v1/finding-groups/decide") + .await? + .json(&serde_json::json!({ "key": key, "status": status, "reason": reason })) + .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["modified_count"].as_u64().unwrap_or_default()) +} diff --git a/compliance-dashboard/src/infrastructure/mod.rs b/compliance-dashboard/src/infrastructure/mod.rs index 71ac7ff..1bd5314 100644 --- a/compliance-dashboard/src/infrastructure/mod.rs +++ b/compliance-dashboard/src/infrastructure/mod.rs @@ -7,6 +7,7 @@ pub mod dast; pub mod download; pub mod evidence; pub mod finding_breakdown; +pub mod finding_groups; 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 55372b3..df6414d 100644 --- a/compliance-dashboard/src/pages/findings.rs +++ b/compliance-dashboard/src/pages/findings.rs @@ -8,11 +8,14 @@ use dioxus_free_icons::Icon; use crate::app::Route; use crate::components::finding_breakdown::{list_status, FindingBreakdownView}; +use crate::components::finding_groups::FindingGroups; 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, finding_breakdown as breakdown_tx, findings as tx}; +use crate::i18n::texts::{ + common, finding_breakdown as breakdown_tx, finding_groups as gtx, 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; @@ -35,10 +38,16 @@ pub fn FindingsPage( 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()); + // Grouped by rule and file (#951), or one row per finding. A chart filter + // in the URL (#957) narrows the single list, which the groups ignore. + let mut grouped = use_signal(|| scan_type.is_none() && severity.is_none() && path.is_none()); // 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()); + if scan_type.is_some() || severity.is_some() || path.is_some() { + grouped.set(false); + } for (mut filter, value) in [ (repo_filter, target), (type_filter, scan_type.unwrap_or_default()), @@ -78,6 +87,7 @@ pub fn FindingsPage( }); let mut findings = use_resource(move || { + let grouped_view = grouped(); let query = crate::infrastructure::findings::FindingsQuery { page: page(), severity: severity_filter(), @@ -91,6 +101,9 @@ pub fn FindingsPage( sort_order: sort_order(), }; async move { + if grouped_view { + return None; + } crate::infrastructure::findings::fetch_findings(query) .await .ok() @@ -155,9 +168,24 @@ pub fn FindingsPage( // 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: "view-switch", role: "group", "aria-label": gtx::VIEW.get(lang), + button { + class: if grouped() { "view-switch-btn active" } else { "view-switch-btn" }, + "aria-pressed": "{grouped()}", + onclick: move |_| grouped.set(true), + {gtx::GROUPED.get(lang)} + } + button { + class: if grouped() { "view-switch-btn" } else { "view-switch-btn active" }, + "aria-pressed": "{!grouped()}", + onclick: move |_| grouped.set(false), + {gtx::SINGLE.get(lang)} + } + } div { class: "filter-bar", input { + disabled: grouped(), r#type: "text", placeholder: tx::SEARCH.get(lang), style: "min-width: 200px;", @@ -184,6 +212,7 @@ pub fn FindingsPage( } } select { + disabled: grouped(), onchange: move |e| { severity_filter.set(e.value()); page.set(1); }, option { value: "", {tx::ALL_SEVERITIES.get(lang)} } option { value: "critical", selected: severity_filter() == "critical", {common::CRITICAL.get(lang)} } @@ -193,6 +222,7 @@ pub fn FindingsPage( option { value: "info", selected: severity_filter() == "info", {tx::INFO.get(lang)} } } select { + disabled: grouped(), 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. @@ -201,6 +231,7 @@ pub fn FindingsPage( } } select { + disabled: grouped(), 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. @@ -211,6 +242,7 @@ pub fn FindingsPage( } if let Some(names) = variants.read().as_ref().filter(|v| !v.is_empty()) { select { + disabled: grouped(), onchange: move |e| { variant_filter.set(e.value()); page.set(1); }, option { value: "", {tx::ALL_VARIANTS.get(lang)} } for name in names.iter() { @@ -222,7 +254,7 @@ pub fn FindingsPage( // Bulk action bar // Triage is a change: read-only roles get no bulk actions. - if can_write && !selected_ids().is_empty() { + if can_write && !grouped() && !selected_ids().is_empty() { div { class: "card", style: "display: flex; align-items: center; gap: 12px; padding: 12px 16px; margin-bottom: 16px; background: rgba(56, 189, 248, 0.08); border-color: rgba(56, 189, 248, 0.2);", @@ -275,6 +307,7 @@ pub fn FindingsPage( } match &*findings.read() { + _ if grouped() => rsx! { FindingGroups { target: repo_filter, targets: repos } }, Some(Some(resp)) => { let total_pages = resp.total.unwrap_or(0).div_ceil(20).max(1); let all_ids: Vec = resp.data.iter().filter_map(|f| f.id.as_ref().map(|id| id.to_hex())).collect(); -- 2.54.1