Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f5697ff21d | ||
|
|
31886d226c | ||
|
|
692840df59 | ||
|
|
f5ed826b99 | ||
|
|
5017c6286e | ||
|
|
ad0fde9106 | ||
|
|
d6986d23b1 | ||
|
|
7b7731f46d | ||
|
|
03dd8f8df4 | ||
|
|
f1123e1adb | ||
|
|
6e97a0bf4c | ||
|
|
cd90a26558 | ||
|
|
32cd11bb2f | ||
|
|
88682c6c6a | ||
|
|
f57a1020db | ||
|
|
29e38c8b80 | ||
|
|
ef9c578948 | ||
|
|
589c3b440b | ||
|
|
b9acabb6ba | ||
|
|
d274c68ecb | ||
|
|
29d3c91f5a | ||
|
|
5a11a3b602 |
No files matched your search
Generated
+14
-2
@@ -765,6 +765,7 @@ dependencies = [
|
||||
"tree-sitter-python",
|
||||
"tree-sitter-rust",
|
||||
"tree-sitter-typescript",
|
||||
"tree-sitter-vb-dotnet",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -6495,13 +6496,14 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "tree-sitter"
|
||||
version = "0.24.7"
|
||||
version = "0.25.10"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a5387dffa7ffc7d2dae12b50c6f7aab8ff79d6210147c6613561fc3d474c6f75"
|
||||
checksum = "78f873475d258561b06f1c595d93308a7ed124d9977cb26b148c2084a4a3cc87"
|
||||
dependencies = [
|
||||
"cc",
|
||||
"regex",
|
||||
"regex-syntax",
|
||||
"serde_json",
|
||||
"streaming-iterator",
|
||||
"tree-sitter-language",
|
||||
]
|
||||
@@ -6572,6 +6574,16 @@ dependencies = [
|
||||
"tree-sitter-language",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tree-sitter-vb-dotnet"
|
||||
version = "0.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "180e4a199378505f9305c3d01d6ece8a8d34035f310de1c727693f8a2296025e"
|
||||
dependencies = [
|
||||
"cc",
|
||||
"tree-sitter-language",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "try-lock"
|
||||
version = "0.2.5"
|
||||
|
||||
@@ -176,6 +176,8 @@ The agent exposes a REST API on port 3001:
|
||||
|--------|----------|-------------|
|
||||
| `GET` | `/api/v1/health` | Health check |
|
||||
| `GET` | `/api/v1/stats/overview` | Summary statistics and trends |
|
||||
| `GET` | `/api/v1/cve-history?days=30[&target=][&project=][&per_target=true]` | Open CVEs with a fixed version per day (UTC) by severity, for the tenant, a target or a project, with the open critical/high findings |
|
||||
| `GET` | `/api/v1/targets/{id}/top-updates` | The package updates that close the most of a target's open CVEs with a fix |
|
||||
| `GET` | `/api/v1/targets` | List targets (Prüfobjekte), each with its newest scan run |
|
||||
| `POST` | `/api/v1/targets` | Create a target |
|
||||
| `GET` / `PATCH` / `DELETE` | `/api/v1/targets/{id}` | Read, update (name, type, artifacts, `scan_config` incl. `issue_tracker`) or delete a target |
|
||||
@@ -193,7 +195,7 @@ The agent exposes a REST API on port 3001:
|
||||
| `PATCH` | `/api/v1/findings/bulk-status` | Update the status of several findings |
|
||||
| `GET` | `/api/v1/sbom` | List dependencies |
|
||||
| `GET` | `/api/v1/sbom/export` | Export a target's SBOM (CycloneDX 1.5 or SPDX 2.3) |
|
||||
| `GET` | `/api/v1/issues` | List cross-tracker issues |
|
||||
| `GET` | `/api/v1/issues` | List cross-tracker issues (search `q`, `status=open\|closed`, `repo_id`) |
|
||||
| `GET` | `/api/v1/scan-runs` | Scan execution history |
|
||||
| `GET` | `/api/v1/graph/{repo_id}` | Code knowledge graph |
|
||||
| `POST` | `/api/v1/graph/{repo_id}/build` | Trigger graph build |
|
||||
|
||||
@@ -0,0 +1,218 @@
|
||||
//! The CVE charts of the overview and a target's page (#952): open CVEs
|
||||
//! with a fix per day, and the package updates that close the most of them.
|
||||
//!
|
||||
//! Both read the tenant's own database; the org-role middleware lets every
|
||||
//! role that may read call them, like the other target and CVE reads.
|
||||
|
||||
use axum::extract::{Extension, Path, Query};
|
||||
use axum::http::StatusCode;
|
||||
use axum::Json;
|
||||
use mongodb::bson::{doc, oid::ObjectId, Document};
|
||||
use serde::{Deserialize, Deserializer};
|
||||
|
||||
use compliance_core::cve_history::{
|
||||
top_updates, window, CveHistory, OpenFindings, TopUpdate, DEFAULT_DAYS, MAX_DAYS,
|
||||
};
|
||||
use compliance_core::models::CveAlert;
|
||||
use compliance_core::tenant_ctx::TenantCtx;
|
||||
|
||||
use super::dto::{collect_cursor_async, tenant_db, AgentExt, ApiResponse, ApiResult};
|
||||
use super::health::open_findings_by_severity;
|
||||
use crate::database::Database;
|
||||
|
||||
/// The updates a target's "Wo handeln" table lists.
|
||||
const TOP_UPDATES_SHOWN: usize = 10;
|
||||
|
||||
/// The query of [`cve_history`].
|
||||
#[derive(Debug, Deserialize)]
|
||||
pub struct HistoryQuery {
|
||||
/// Days back from today, `1..=90` (clamped); 30 when not given.
|
||||
#[serde(default = "default_days", deserialize_with = "de_days")]
|
||||
pub days: u32,
|
||||
/// Only this target. Takes precedence over `project`.
|
||||
#[serde(default)]
|
||||
pub target: Option<String>,
|
||||
/// Only the targets of this project (`targets.project_ids`).
|
||||
#[serde(default)]
|
||||
pub project: Option<String>,
|
||||
/// Also each target's own series, for the overview's repo cards.
|
||||
#[serde(default)]
|
||||
pub per_target: bool,
|
||||
}
|
||||
|
||||
fn default_days() -> u32 {
|
||||
DEFAULT_DAYS
|
||||
}
|
||||
|
||||
/// Clamp a caller-supplied number of days to `1..=MAX_DAYS`.
|
||||
fn de_days<'de, D: Deserializer<'de>>(d: D) -> Result<u32, D::Error> {
|
||||
Ok(u32::deserialize(d)?.clamp(1, MAX_DAYS))
|
||||
}
|
||||
|
||||
/// A non-empty, trimmed query value.
|
||||
fn given(value: Option<&str>) -> Option<&str> {
|
||||
value.map(str::trim).filter(|v| !v.is_empty())
|
||||
}
|
||||
|
||||
/// The target ids the query is about: one target, a project's targets, or
|
||||
/// `None` for every target of the tenant.
|
||||
async fn scope(db: &Database, query: &HistoryQuery) -> Result<Option<Vec<String>>, StatusCode> {
|
||||
if let Some(target) = given(query.target.as_deref()) {
|
||||
return Ok(Some(vec![target.to_string()]));
|
||||
}
|
||||
let Some(project) = given(query.project.as_deref()) else {
|
||||
return Ok(None);
|
||||
};
|
||||
let rows: Vec<Document> = collect_cursor_async(
|
||||
db.onboarded_targets()
|
||||
.clone_with_type::<Document>()
|
||||
.find(doc! { "project_ids": project })
|
||||
.projection(doc! { "_id": 1 })
|
||||
.await
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?,
|
||||
)
|
||||
.await;
|
||||
Ok(Some(
|
||||
rows.iter()
|
||||
.filter_map(|row| row.get_object_id("_id").ok().map(|id| id.to_hex()))
|
||||
.collect(),
|
||||
))
|
||||
}
|
||||
|
||||
/// The alerts with a fixed version that may be open at some point after
|
||||
/// `since`, of `targets` (every target with `None`). The long texts are
|
||||
/// left out; the history does not need them.
|
||||
async fn alerts_with_fix(
|
||||
db: &Database,
|
||||
targets: Option<&[String]>,
|
||||
since: chrono::DateTime<chrono::Utc>,
|
||||
) -> Result<Vec<CveAlert>, StatusCode> {
|
||||
let mut filter = doc! {
|
||||
"fixed_versions.0": { "$exists": true },
|
||||
"$or": [
|
||||
{ "resolved_at": null },
|
||||
{ "resolved_at": { "$gte": mongodb::bson::DateTime::from_chrono(since) } },
|
||||
],
|
||||
};
|
||||
if let Some(targets) = targets {
|
||||
filter.insert("repo_id", doc! { "$in": targets });
|
||||
}
|
||||
let cursor = db
|
||||
.cve_alerts()
|
||||
.find(filter)
|
||||
.projection(doc! {
|
||||
"summary": 0, "llm_impact_summary": 0, "advisories": 0, "exploitation": 0,
|
||||
})
|
||||
.await
|
||||
.map_err(|e| {
|
||||
tracing::warn!("CVE history: loading alerts failed: {e}");
|
||||
StatusCode::INTERNAL_SERVER_ERROR
|
||||
})?;
|
||||
Ok(collect_cursor_async(cursor).await)
|
||||
}
|
||||
|
||||
/// `GET /api/v1/cve-history?days=30[&target=<id>][&project=<id>][&per_target=true]`
|
||||
/// — per day (UTC, oldest first, today last) the open CVEs with a fixed
|
||||
/// version, by severity, for the tenant, one target or one project's
|
||||
/// targets; plus the open critical and high findings of the same scope.
|
||||
///
|
||||
/// A CVE counts on day `d` when, at the end of `d`: its alert was found
|
||||
/// (`created_at`), not resolved (`resolved_at` unset or later), not settled
|
||||
/// by a VEX `not_affected` / `fixed` stated by then (`vex.at`), and its
|
||||
/// advisory names a fixed version. One CVE counts once per target (its
|
||||
/// GHSA and CVE alias, or two packages, are one), at its highest severity;
|
||||
/// a tenant's or project's count is the sum over its targets. See
|
||||
/// [`compliance_core::cve_history`] for what the stored state cannot show.
|
||||
#[tracing::instrument(skip_all)]
|
||||
pub async fn cve_history(
|
||||
Extension(agent): AgentExt,
|
||||
tenant: TenantCtx,
|
||||
Query(query): Query<HistoryQuery>,
|
||||
) -> ApiResult<CveHistory> {
|
||||
let db = tenant_db(&agent, &tenant).await?;
|
||||
let now = chrono::Utc::now();
|
||||
let since = window(now, query.days).first().map_or(now, |(_, end)| *end);
|
||||
let targets = scope(&db, &query).await?;
|
||||
let findings_scope = match &targets {
|
||||
Some(ids) => doc! { "repo_id": { "$in": ids } },
|
||||
None => doc! {},
|
||||
};
|
||||
let (alerts, by_severity) = tokio::join!(
|
||||
alerts_with_fix(&db, targets.as_deref(), since),
|
||||
open_findings_by_severity(&db, findings_scope),
|
||||
);
|
||||
let mut history = CveHistory::of(&alerts?, now, query.days);
|
||||
let count = |name: &str| by_severity.get(name).copied().unwrap_or(0);
|
||||
history.open_findings = OpenFindings {
|
||||
critical: count("critical"),
|
||||
high: count("high"),
|
||||
};
|
||||
if !query.per_target {
|
||||
history.targets.clear();
|
||||
}
|
||||
Ok(Json(ApiResponse {
|
||||
data: history,
|
||||
total: None,
|
||||
page: None,
|
||||
}))
|
||||
}
|
||||
|
||||
/// `GET /api/v1/targets/{id}/top-updates` — the package updates that close
|
||||
/// the most of the target's open CVEs with a fix (at most ten): package,
|
||||
/// current version, the highest fixed version its alerts name, and how
|
||||
/// many CVEs (and critical ones) it closes. 404 for a target the tenant
|
||||
/// does not have.
|
||||
#[tracing::instrument(skip_all, fields(target_id = %id))]
|
||||
pub async fn target_top_updates(
|
||||
Extension(agent): AgentExt,
|
||||
tenant: TenantCtx,
|
||||
Path(id): Path<String>,
|
||||
) -> ApiResult<Vec<TopUpdate>> {
|
||||
let oid = ObjectId::parse_str(&id).map_err(|_| StatusCode::BAD_REQUEST)?;
|
||||
let db = tenant_db(&agent, &tenant).await?;
|
||||
db.onboarded_targets()
|
||||
.find_one(doc! { "_id": oid })
|
||||
.await
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?
|
||||
.ok_or(StatusCode::NOT_FOUND)?;
|
||||
let now = chrono::Utc::now();
|
||||
let ids = [id];
|
||||
let alerts = alerts_with_fix(&db, Some(&ids), now).await?;
|
||||
let mut updates = top_updates(&alerts, now);
|
||||
let total = updates.len() as u64;
|
||||
updates.truncate(TOP_UPDATES_SHOWN);
|
||||
Ok(Json(ApiResponse {
|
||||
data: updates,
|
||||
total: Some(total),
|
||||
page: None,
|
||||
}))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn query(text: &str) -> HistoryQuery {
|
||||
let uri: axum::http::Uri = format!("/api/v1/cve-history?{text}").parse().unwrap();
|
||||
Query::<HistoryQuery>::try_from_uri(&uri).unwrap().0
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_days_are_clamped_and_default_to_thirty() {
|
||||
assert_eq!(query("").days, 30);
|
||||
assert_eq!(query("days=0").days, 1);
|
||||
assert_eq!(query("days=100000").days, MAX_DAYS);
|
||||
let q = query("days=7&target=t1&per_target=true");
|
||||
assert_eq!(
|
||||
(q.days, q.target.as_deref(), q.per_target),
|
||||
(7, Some("t1"), true)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_blank_scope_means_every_target() {
|
||||
assert_eq!(given(Some(" ")), None);
|
||||
assert_eq!(given(Some(" p1 ")), Some("p1"));
|
||||
assert_eq!(given(None), None);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
//! A target's CVE alerts counted by severity and VEX status (#957), for the
|
||||
//! grid the dashboard's "CVEs & VEX" view opens with.
|
||||
|
||||
use axum::extract::{Extension, Path};
|
||||
use axum::http::StatusCode;
|
||||
use axum::Json;
|
||||
use mongodb::bson::{doc, Document};
|
||||
use serde::Deserialize;
|
||||
|
||||
use compliance_core::cve_matrix::{CveCell, CveMatrix};
|
||||
use compliance_core::models::VexStatus;
|
||||
use compliance_core::tenant_ctx::TenantCtx;
|
||||
|
||||
use super::dto::{collect_cursor_async, tenant_db, AgentExt, ApiResponse, ApiResult};
|
||||
|
||||
/// The fields of a stored alert the grid reads.
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct MatrixRow {
|
||||
#[serde(default)]
|
||||
severity: Option<String>,
|
||||
#[serde(default)]
|
||||
cvss_score: Option<f64>,
|
||||
#[serde(default)]
|
||||
vex: Option<MatrixVex>,
|
||||
}
|
||||
|
||||
/// The status of an alert's VEX statement; the rest of it is not read.
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct MatrixVex {
|
||||
status: VexStatus,
|
||||
}
|
||||
|
||||
impl MatrixRow {
|
||||
fn cell(&self) -> CveCell {
|
||||
CveCell::of(
|
||||
self.severity.as_deref(),
|
||||
self.cvss_score,
|
||||
self.vex.as_ref().map(|v| v.status),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/// The alerts of target `id` the grid counts: still reported, as in
|
||||
/// [`compliance_core::cve_matrix::counts`]. `null` matches a missing
|
||||
/// `resolved_at` and one stored as `null`.
|
||||
fn still_reported(id: &str) -> Document {
|
||||
doc! { "repo_id": id, "resolved_at": null }
|
||||
}
|
||||
|
||||
/// GET /api/v1/targets/{id}/cve-matrix — the target's still-reported CVE
|
||||
/// alerts counted per severity and VEX status. Scoped to the requester's
|
||||
/// tenant like `GET /api/v1/targets/{id}/cves`; the org-role middleware
|
||||
/// lets every reading role in.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// 500 when the tenant's database or the alerts cannot be read.
|
||||
#[tracing::instrument(skip_all, fields(target_id = %id))]
|
||||
pub async fn target_cve_matrix(
|
||||
Extension(agent): AgentExt,
|
||||
tenant: TenantCtx,
|
||||
Path(id): Path<String>,
|
||||
) -> ApiResult<CveMatrix> {
|
||||
let db = tenant_db(&agent, &tenant).await?;
|
||||
// Only the three fields the bucketing reads, not the summaries and
|
||||
// references of every alert. A row that does not decode is skipped with
|
||||
// a warning, as the CVE list skips it.
|
||||
let cursor = db
|
||||
.cve_alerts()
|
||||
.clone_with_type::<MatrixRow>()
|
||||
.find(still_reported(&id))
|
||||
.projection(doc! { "_id": 0, "severity": 1, "cvss_score": 1, "vex.status": 1 })
|
||||
.await
|
||||
.map_err(|e| {
|
||||
tracing::warn!("CVE matrix not read: {e}");
|
||||
StatusCode::INTERNAL_SERVER_ERROR
|
||||
})?;
|
||||
let rows: Vec<MatrixRow> = collect_cursor_async(cursor).await;
|
||||
let matrix = CveMatrix::from_cells(rows.iter().map(MatrixRow::cell));
|
||||
Ok(Json(ApiResponse {
|
||||
total: Some(matrix.total()),
|
||||
data: matrix,
|
||||
page: None,
|
||||
}))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use compliance_core::cve_matrix::{CveSeverity, VexColumn};
|
||||
|
||||
#[test]
|
||||
fn only_alerts_still_reported_are_read() {
|
||||
let filter = still_reported("t1");
|
||||
assert_eq!(filter.get_str("repo_id").ok(), Some("t1"));
|
||||
assert_eq!(filter.get("resolved_at"), Some(&mongodb::bson::Bson::Null));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_projected_row_is_bucketed_like_the_alert() {
|
||||
let row: MatrixRow = mongodb::bson::from_document(doc! {
|
||||
"severity": "MODERATE",
|
||||
"vex": { "status": "not_affected" },
|
||||
})
|
||||
.expect("a projected alert");
|
||||
let cell = row.cell();
|
||||
assert_eq!(cell.severity, CveSeverity::Medium);
|
||||
assert_eq!(cell.vex, VexColumn::NotAffected);
|
||||
|
||||
let bare: MatrixRow = mongodb::bson::from_document(doc! { "severity": null })
|
||||
.expect("an alert without severity or statement");
|
||||
assert_eq!(bare.cell(), CveCell::of(None, None, None));
|
||||
}
|
||||
}
|
||||
@@ -69,6 +69,10 @@ pub struct FindingsFilter {
|
||||
/// groups listing a place in it.
|
||||
#[serde(default)]
|
||||
pub variant: Option<String>,
|
||||
/// Only the findings in one folder, as the folder chart names it
|
||||
/// ([`path_regex`]).
|
||||
#[serde(default)]
|
||||
pub path: Option<String>,
|
||||
#[serde(default)]
|
||||
pub sort_by: Option<String>,
|
||||
#[serde(default)]
|
||||
@@ -88,6 +92,65 @@ impl FindingsFilter {
|
||||
}
|
||||
}
|
||||
|
||||
/// Open or closed, as the tickets list filters them.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum TicketState {
|
||||
/// Open or in progress.
|
||||
Open,
|
||||
/// Closed or resolved.
|
||||
Closed,
|
||||
}
|
||||
|
||||
impl TicketState {
|
||||
/// The stored statuses (`in_progress`) this state stands for.
|
||||
pub fn statuses(self) -> Vec<String> {
|
||||
let closed = self == Self::Closed;
|
||||
compliance_core::models::IssueStatus::ALL
|
||||
.iter()
|
||||
.filter(|s| s.is_closed() == closed)
|
||||
.map(ToString::to_string)
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
|
||||
/// The query of the tickets list (`GET /api/v1/issues`).
|
||||
#[derive(Deserialize)]
|
||||
pub struct IssuesFilter {
|
||||
/// A word of the title or the ticket number (`913`, `#913`, `PROJ-913`).
|
||||
#[serde(default)]
|
||||
pub q: Option<String>,
|
||||
/// Only open or only closed tickets; an unknown value is refused (400).
|
||||
#[serde(default)]
|
||||
pub status: Option<TicketState>,
|
||||
/// Only the tickets of one target: of its findings and its CVEs.
|
||||
#[serde(default)]
|
||||
pub repo_id: Option<String>,
|
||||
#[serde(default = "default_page", deserialize_with = "de_page")]
|
||||
pub page: u64,
|
||||
#[serde(default = "default_limit", deserialize_with = "de_limit")]
|
||||
pub limit: i64,
|
||||
}
|
||||
|
||||
impl IssuesFilter {
|
||||
/// Documents to skip for this page. Bounded by construction.
|
||||
pub fn skip(&self) -> u64 {
|
||||
self.page
|
||||
.saturating_sub(1)
|
||||
.saturating_mul(self.limit as u64)
|
||||
}
|
||||
|
||||
/// The search term, trimmed; `None` when there is none.
|
||||
pub fn search(&self) -> Option<&str> {
|
||||
self.q.as_deref().map(str::trim).filter(|q| !q.is_empty())
|
||||
}
|
||||
|
||||
/// The target to filter by; `None` for all.
|
||||
pub fn target(&self) -> Option<&str> {
|
||||
self.repo_id.as_deref().filter(|id| !id.is_empty())
|
||||
}
|
||||
}
|
||||
|
||||
/// Fields a caller may sort findings by.
|
||||
///
|
||||
/// `sort_by` went into the sort document verbatim, so a caller could sort on
|
||||
@@ -136,6 +199,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<String> {
|
||||
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<T: Serialize> {
|
||||
pub data: T,
|
||||
@@ -412,6 +504,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();
|
||||
@@ -478,6 +605,55 @@ mod tests {
|
||||
assert_eq!(f.severity.as_deref(), Some(""));
|
||||
}
|
||||
|
||||
// ── IssuesFilter ─────────────────────────────────────────────
|
||||
|
||||
#[test]
|
||||
fn issues_filter_defaults_and_clamps() {
|
||||
let f: IssuesFilter = serde_json::from_str("{}").unwrap();
|
||||
assert_eq!(f.search(), None);
|
||||
assert_eq!(f.status, None);
|
||||
assert_eq!(f.target(), None);
|
||||
assert_eq!((f.page, f.limit), (1, 50));
|
||||
|
||||
let f: IssuesFilter = serde_json::from_str(r#"{"limit":5000,"page":0}"#).unwrap();
|
||||
assert_eq!(f.limit, MAX_PAGE_SIZE);
|
||||
assert_eq!(f.skip(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn issues_filter_ignores_blank_search_and_target() {
|
||||
let f: IssuesFilter = serde_json::from_str(r#"{"q":" ","repo_id":""}"#).unwrap();
|
||||
assert_eq!(f.search(), None);
|
||||
assert_eq!(f.target(), None);
|
||||
|
||||
let f: IssuesFilter = serde_json::from_str(r##"{"q":" #913 ","repo_id":"t1"}"##).unwrap();
|
||||
assert_eq!(f.search(), Some("#913"));
|
||||
assert_eq!(f.target(), Some("t1"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn issues_filter_status_is_open_or_closed_only() {
|
||||
let f: IssuesFilter = serde_json::from_str(r#"{"status":"closed"}"#).unwrap();
|
||||
assert_eq!(f.status, Some(TicketState::Closed));
|
||||
assert!(serde_json::from_str::<IssuesFilter>(r#"{"status":"$ne"}"#).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ticket_states_cover_every_stored_status_once() {
|
||||
assert_eq!(TicketState::Open.statuses(), ["open", "in_progress"]);
|
||||
assert_eq!(TicketState::Closed.statuses(), ["closed", "resolved"]);
|
||||
// The names are the stored ones.
|
||||
for name in TicketState::Open
|
||||
.statuses()
|
||||
.into_iter()
|
||||
.chain(TicketState::Closed.statuses())
|
||||
{
|
||||
let status: compliance_core::models::IssueStatus =
|
||||
serde_json::from_value(json!(name)).unwrap();
|
||||
assert_eq!(status.to_string(), name);
|
||||
}
|
||||
}
|
||||
|
||||
// ── ApiResponse ──────────────────────────────────────────────
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -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<String> = 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<String>,
|
||||
) -> ApiResult<FindingBreakdown> {
|
||||
let db = tenant_db(&agent, &tenant).await?;
|
||||
// Only the three fields the counts need cross the wire.
|
||||
let rows: Vec<BreakdownRow> = match db
|
||||
.findings()
|
||||
.clone_with_type::<BreakdownRow>()
|
||||
.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"] },
|
||||
}
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -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<String>,
|
||||
}
|
||||
|
||||
/// 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<String>,
|
||||
}
|
||||
|
||||
/// 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<Vec<Finding>, 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<GroupsQuery>,
|
||||
) -> ApiResult<Vec<FindingGroup>> {
|
||||
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<Document, StatusCode> {
|
||||
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<DecideGroupRequest>,
|
||||
) -> Result<Json<serde_json::Value>, 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::<DecideGroupRequest>(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::<DecideGroupRequest>(bad).is_err());
|
||||
let mut bad_scope = wire;
|
||||
bad_scope["key"]["scope"] = "everywhere".into();
|
||||
assert!(serde_json::from_value::<DecideGroupRequest>(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));
|
||||
}
|
||||
}
|
||||
@@ -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<String> = 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";
|
||||
|
||||
@@ -214,7 +229,7 @@ impl<'a> Actor<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
fn status_update(
|
||||
pub(crate) fn status_update(
|
||||
status: &FindingStatus,
|
||||
reason: Option<&str>,
|
||||
actor: &Actor<'_>,
|
||||
@@ -231,6 +246,7 @@ fn status_update(
|
||||
at: chrono::Utc::now(),
|
||||
reason: reason.map(String::from),
|
||||
scan: None,
|
||||
tracker: None,
|
||||
};
|
||||
let status = mongodb::bson::to_bson(status).map_err(|_| StatusCode::BAD_REQUEST)?;
|
||||
let change = mongodb::bson::to_bson(&change).map_err(|_| StatusCode::BAD_REQUEST)?;
|
||||
@@ -299,18 +315,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<mongodb::bson::oid::ObjectId>,
|
||||
update: mongodb::bson::Document,
|
||||
) -> Result<u64, StatusCode> {
|
||||
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))]
|
||||
@@ -342,6 +382,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!(
|
||||
|
||||
@@ -57,14 +57,19 @@ fn health_answer(mongo_reachable: bool) -> (axum::http::StatusCode, Json<serde_j
|
||||
/// positive, not an accepted risk and not ignored.
|
||||
pub(crate) const OPEN_STATUSES: [&str; 3] = ["open", "triaged", "needs_review"];
|
||||
|
||||
/// How many open findings there are of each severity, by severity name.
|
||||
async fn open_findings_by_severity(
|
||||
/// How many open findings there are of each severity, by severity name;
|
||||
/// only those matching `scope` (e.g. `{"repo_id": …}`), every one with an
|
||||
/// empty document.
|
||||
pub(crate) async fn open_findings_by_severity(
|
||||
db: &crate::database::Database,
|
||||
scope: mongodb::bson::Document,
|
||||
) -> std::collections::HashMap<String, u64> {
|
||||
use futures_util::TryStreamExt;
|
||||
|
||||
let mut matching = scope;
|
||||
matching.insert("status", doc! { "$in": OPEN_STATUSES.to_vec() });
|
||||
let pipeline = vec![
|
||||
doc! { "$match": { "status": { "$in": OPEN_STATUSES.to_vec() } } },
|
||||
doc! { "$match": matching },
|
||||
doc! { "$group": { "_id": "$severity", "n": { "$sum": 1 } } },
|
||||
];
|
||||
let rows: Vec<mongodb::bson::Document> = match db.findings().aggregate(pipeline).await {
|
||||
@@ -116,7 +121,7 @@ pub async fn stats_overview(
|
||||
.await
|
||||
.unwrap_or(0)
|
||||
},
|
||||
open_findings_by_severity(db),
|
||||
open_findings_by_severity(db, doc! {}),
|
||||
);
|
||||
let severity = |name: &str| by_severity.get(name).copied().unwrap_or(0);
|
||||
let total_findings = by_severity.values().sum();
|
||||
|
||||
@@ -0,0 +1,554 @@
|
||||
//! The "Heute" inbox (#950): the workspace's open decisions as cards in four
|
||||
//! urgency buckets, decisions on a whole card, undo, and putting a card off
|
||||
//! until a date ("Wiedervorlage").
|
||||
//!
|
||||
//! The bucket rules and the cards are [`compliance_core::models::inbox`]'s;
|
||||
//! this module loads what they are made of and applies decisions through
|
||||
//! the existing endpoints' code: a finding's status as
|
||||
//! `PATCH /api/v1/findings/bulk-status` sets it, a CVE alert's VEX statement
|
||||
//! as `PATCH /api/v1/cves/{id}/vex` does. Writes are role-gated by the org
|
||||
//! role middleware like every other write.
|
||||
|
||||
use std::collections::{BTreeMap, HashMap};
|
||||
|
||||
use axum::extract::{Extension, Path, Query};
|
||||
use axum::http::StatusCode;
|
||||
use axum::Json;
|
||||
use chrono::{DateTime, Utc};
|
||||
use futures_util::StreamExt;
|
||||
use mongodb::bson::{doc, oid::ObjectId, Bson, Document};
|
||||
use serde::Deserialize;
|
||||
|
||||
use compliance_core::models::inbox::{
|
||||
alert_undecided, apply_snoozes, cve_cards, finding_cards, view, Bucket, BucketRules, CardKey,
|
||||
DecideRequest, DecideResponse, InboxAction, InboxCard, InboxFinding, InboxSnooze, InboxView,
|
||||
OneCardPerFinding, PreviousState, Progress, Reason, SnoozeRequest, SnoozeResponse, UndoRequest,
|
||||
ViewRequest, DECIDED_STATUSES, DECIDING_VEX, UNDECIDED_STATUSES,
|
||||
};
|
||||
use compliance_core::models::{CveAlert, FindingStatus, VexStatus};
|
||||
use compliance_core::tenant_ctx::TenantCtx;
|
||||
|
||||
use super::dto::{
|
||||
collect_cursor_async, tenant_db, AgentExt, ApiResponse, ApiResult, BulkUpdateStatusRequest,
|
||||
};
|
||||
use super::findings::{bulk_update_finding_status, Actor};
|
||||
use super::vex::{set_cve_vex, VexRequest};
|
||||
use crate::database::Database;
|
||||
|
||||
/// Cards listed when the request names no limit.
|
||||
const DEFAULT_LIMIT: usize = 100;
|
||||
/// The most cards one request lists; the counts always cover all.
|
||||
const MAX_LIMIT: usize = 500;
|
||||
|
||||
/// A refusal with its reason, the shape `PATCH /api/v1/cves/{id}/vex` answers
|
||||
/// with, so the dashboard shows why.
|
||||
type Refusal = (StatusCode, Json<serde_json::Value>);
|
||||
|
||||
fn refuse(code: StatusCode, error: &str) -> Refusal {
|
||||
(code, Json(serde_json::json!({ "error": error })))
|
||||
}
|
||||
|
||||
/// A database error as a refusal, logged.
|
||||
fn store_error(e: mongodb::error::Error) -> Refusal {
|
||||
tracing::warn!("inbox: database error: {e}");
|
||||
refuse(StatusCode::INTERNAL_SERVER_ERROR, "store")
|
||||
}
|
||||
|
||||
/// The query of [`get_inbox`].
|
||||
#[derive(Debug, Deserialize)]
|
||||
pub struct InboxQuery {
|
||||
/// Only this target's cards, counts and Erstbewertung.
|
||||
#[serde(default)]
|
||||
pub target: Option<String>,
|
||||
/// The bucket whose cards to list (default `today`).
|
||||
#[serde(default)]
|
||||
pub bucket: Option<Bucket>,
|
||||
/// The most cards to list (default 100, at most 500).
|
||||
#[serde(default)]
|
||||
pub limit: Option<usize>,
|
||||
}
|
||||
|
||||
/// The bucket rules as configured: the CVE issues' EPSS threshold
|
||||
/// (`CVE_ISSUE_EPSS_PERCENTILE`, default 0.95), at `now`.
|
||||
fn rules(now: DateTime<Utc>) -> BucketRules {
|
||||
BucketRules {
|
||||
epss_percentile: crate::pipeline::cve_issues::epss_percentile(
|
||||
std::env::var("CVE_ISSUE_EPSS_PERCENTILE").ok().as_deref(),
|
||||
),
|
||||
now,
|
||||
}
|
||||
}
|
||||
|
||||
/// `values` as a BSON array for an `$in`.
|
||||
fn bson_list<T: serde::Serialize>(values: &[T]) -> Bson {
|
||||
mongodb::bson::to_bson(values).unwrap_or_else(|_| Bson::Array(Vec::new()))
|
||||
}
|
||||
|
||||
/// The findings waiting for a decision ([`UNDECIDED_STATUSES`]) matching
|
||||
/// `filter`, with only the fields the inbox reads.
|
||||
async fn open_findings(
|
||||
db: &Database,
|
||||
mut filter: Document,
|
||||
) -> Result<Vec<InboxFinding>, mongodb::error::Error> {
|
||||
filter.insert("status", doc! { "$in": bson_list(&UNDECIDED_STATUSES) });
|
||||
let projection: Document = InboxFinding::FIELDS
|
||||
.iter()
|
||||
.map(|field| ((*field).to_string(), Bson::Int32(1)))
|
||||
.collect();
|
||||
let cursor = db
|
||||
.findings()
|
||||
.clone_with_type::<InboxFinding>()
|
||||
.find(filter)
|
||||
.projection(projection)
|
||||
.await?;
|
||||
Ok(collect_cursor_async(cursor).await)
|
||||
}
|
||||
|
||||
/// The CVE alerts waiting for a decision ([`alert_undecided`]) matching
|
||||
/// `filter`.
|
||||
async fn open_alerts(
|
||||
db: &Database,
|
||||
mut filter: Document,
|
||||
) -> Result<Vec<CveAlert>, mongodb::error::Error> {
|
||||
filter.insert("resolved_at", Bson::Null);
|
||||
filter.insert(
|
||||
"$or",
|
||||
vec![
|
||||
doc! { "vex": Bson::Null },
|
||||
doc! { "vex.status": VexStatus::UnderInvestigation.as_str() },
|
||||
],
|
||||
);
|
||||
let cursor = db.cve_alerts().find(filter).await?;
|
||||
let alerts: Vec<CveAlert> = collect_cursor_async(cursor).await;
|
||||
Ok(alerts.into_iter().filter(alert_undecided).collect())
|
||||
}
|
||||
|
||||
/// The snooze of each card key.
|
||||
async fn snoozes(db: &Database) -> Result<HashMap<String, InboxSnooze>, mongodb::error::Error> {
|
||||
let cursor = db.inbox_snoozes().find(doc! {}).await?;
|
||||
let snoozes: Vec<InboxSnooze> = collect_cursor_async(cursor).await;
|
||||
Ok(snoozes.into_iter().map(|s| (s.key.clone(), s)).collect())
|
||||
}
|
||||
|
||||
/// The targets' names by id.
|
||||
async fn target_names(db: &Database) -> Result<HashMap<String, String>, mongodb::error::Error> {
|
||||
let mut cursor = db
|
||||
.onboarded_targets()
|
||||
.clone_with_type::<Document>()
|
||||
.find(doc! {})
|
||||
.projection(doc! { "name": 1 })
|
||||
.await?;
|
||||
let mut names = HashMap::new();
|
||||
while let Some(target) = cursor.next().await {
|
||||
let target = target?;
|
||||
if let (Ok(id), Ok(name)) = (target.get_object_id("_id"), target.get_str("name")) {
|
||||
names.insert(id.to_hex(), name.to_string());
|
||||
}
|
||||
}
|
||||
Ok(names)
|
||||
}
|
||||
|
||||
/// The Erstbewertung of `scope` (the workspace, or one target): the open
|
||||
/// items already loaded, plus the decided ones counted in the database. See
|
||||
/// [`Progress`] for what counts as decided.
|
||||
async fn progress(
|
||||
db: &Database,
|
||||
target: Option<&str>,
|
||||
findings: &[InboxFinding],
|
||||
alerts: &[CveAlert],
|
||||
) -> Result<Progress, mongodb::error::Error> {
|
||||
let in_scope = |repo_id: &str| target.is_none_or(|t| t == repo_id);
|
||||
let scope = || target.map_or_else(Document::new, |t| doc! { "repo_id": t });
|
||||
let mut decided_findings = scope();
|
||||
decided_findings.insert("status", doc! { "$in": bson_list(&DECIDED_STATUSES) });
|
||||
let mut decided_alerts = scope();
|
||||
decided_alerts.insert("resolved_at", Bson::Null);
|
||||
decided_alerts.insert("vex.status", doc! { "$in": bson_list(&DECIDING_VEX) });
|
||||
let decided = db.findings().count_documents(decided_findings).await?
|
||||
+ db.cve_alerts().count_documents(decided_alerts).await?;
|
||||
let open = findings.iter().filter(|f| in_scope(&f.repo_id)).count()
|
||||
+ alerts.iter().filter(|a| in_scope(&a.repo_id)).count();
|
||||
Ok(Progress {
|
||||
decided,
|
||||
total: decided + open as u64,
|
||||
})
|
||||
}
|
||||
|
||||
/// GET /api/v1/inbox[?target=<id>&bucket=<bucket>&limit=<n>] — the bucket
|
||||
/// counts, the Erstbewertung, the targets with cards, and the cards of one
|
||||
/// bucket (default `today`), most urgent first.
|
||||
///
|
||||
/// Cards: one per finding, one per target, package and version for CVE
|
||||
/// alerts. Cards put off until a date are left out until then and come back
|
||||
/// under `later`.
|
||||
#[tracing::instrument(skip_all, fields(target = ?query.target, bucket = ?query.bucket))]
|
||||
pub async fn get_inbox(
|
||||
Extension(agent): AgentExt,
|
||||
tenant: TenantCtx,
|
||||
Query(query): Query<InboxQuery>,
|
||||
) -> ApiResult<InboxView> {
|
||||
let db = tenant_db(&agent, &tenant).await?;
|
||||
let failed = |e: mongodb::error::Error| {
|
||||
tracing::warn!("inbox: failed to load: {e}");
|
||||
StatusCode::INTERNAL_SERVER_ERROR
|
||||
};
|
||||
let now = Utc::now();
|
||||
let findings = open_findings(&db, Document::new()).await.map_err(failed)?;
|
||||
let alerts = open_alerts(&db, Document::new()).await.map_err(failed)?;
|
||||
let snoozes = snoozes(&db).await.map_err(failed)?;
|
||||
let names = target_names(&db).await.map_err(failed)?;
|
||||
let target = query.target.as_deref().filter(|t| !t.is_empty());
|
||||
let progress = progress(&db, target, &findings, &alerts)
|
||||
.await
|
||||
.map_err(failed)?;
|
||||
|
||||
let mut cards = finding_cards(&findings, &OneCardPerFinding);
|
||||
cards.extend(cve_cards(&alerts, &rules(now)));
|
||||
let request = ViewRequest {
|
||||
target,
|
||||
bucket: query.bucket.unwrap_or_default(),
|
||||
limit: query.limit.unwrap_or(DEFAULT_LIMIT).min(MAX_LIMIT),
|
||||
};
|
||||
let view = view(
|
||||
apply_snoozes(cards, &snoozes, now),
|
||||
&names,
|
||||
progress,
|
||||
request,
|
||||
);
|
||||
Ok(Json(ApiResponse {
|
||||
data: view,
|
||||
total: None,
|
||||
page: None,
|
||||
}))
|
||||
}
|
||||
|
||||
/// The card `key` names as it stands now, with what each item is, or why
|
||||
/// there is none: 400 for a malformed key, 409 when nothing on it waits for
|
||||
/// a decision any more.
|
||||
async fn resolve_card(
|
||||
db: &Database,
|
||||
key: &str,
|
||||
) -> Result<(InboxCard, Vec<PreviousState>), Refusal> {
|
||||
let gone = || {
|
||||
refuse(
|
||||
StatusCode::CONFLICT,
|
||||
"nothing on this card waits for a decision",
|
||||
)
|
||||
};
|
||||
match CardKey::parse(key).ok_or_else(|| refuse(StatusCode::BAD_REQUEST, "bad key"))? {
|
||||
CardKey::Finding { id } => {
|
||||
let oid =
|
||||
ObjectId::parse_str(&id).map_err(|_| refuse(StatusCode::BAD_REQUEST, "bad key"))?;
|
||||
let findings = open_findings(db, doc! { "_id": oid })
|
||||
.await
|
||||
.map_err(store_error)?;
|
||||
let card = finding_cards(&findings, &OneCardPerFinding)
|
||||
.into_iter()
|
||||
.find(|c| c.key == key)
|
||||
.ok_or_else(gone)?;
|
||||
let previous = findings
|
||||
.into_iter()
|
||||
.map(|f| PreviousState::Finding {
|
||||
id: f.id.to_hex(),
|
||||
status: f.status,
|
||||
})
|
||||
.collect();
|
||||
Ok((card, previous))
|
||||
}
|
||||
CardKey::CvePackage { target_id } => {
|
||||
let alerts = open_alerts(db, doc! { "repo_id": &target_id })
|
||||
.await
|
||||
.map_err(store_error)?;
|
||||
let card = cve_cards(&alerts, &rules(Utc::now()))
|
||||
.into_iter()
|
||||
.find(|c| c.key == key)
|
||||
.ok_or_else(gone)?;
|
||||
let previous = alerts
|
||||
.into_iter()
|
||||
.filter_map(|a| {
|
||||
let id = a.id?.to_hex();
|
||||
card.item_ids.contains(&id).then(|| PreviousState::Cve {
|
||||
id,
|
||||
vex: a.vex.map(|v| v.status),
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
Ok((card, previous))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Set `status` on the findings `ids` the way
|
||||
/// `PATCH /api/v1/findings/bulk-status` does: recorded in their history with
|
||||
/// who and why, and their tracker issues closed or reopened.
|
||||
async fn set_finding_status(
|
||||
agent: &AgentExt,
|
||||
tenant: &TenantCtx,
|
||||
ids: Vec<String>,
|
||||
status: FindingStatus,
|
||||
reason: Option<String>,
|
||||
) -> Result<(), Refusal> {
|
||||
let request = BulkUpdateStatusRequest {
|
||||
ids,
|
||||
status,
|
||||
reason,
|
||||
};
|
||||
bulk_update_finding_status(agent.clone(), tenant.clone(), Json(request))
|
||||
.await
|
||||
.map(|_| ())
|
||||
.map_err(|code| match code {
|
||||
StatusCode::UNPROCESSABLE_ENTITY => refuse(code, "a reason is required"),
|
||||
other => refuse(other, "status"),
|
||||
})
|
||||
}
|
||||
|
||||
/// State `request()` on the alerts `ids` the way `PATCH /api/v1/cves/{id}/vex`
|
||||
/// does; the first refusal (a missing justification) stops before anything
|
||||
/// is stored, as every alert gets the same statement.
|
||||
async fn set_vex(
|
||||
agent: &AgentExt,
|
||||
tenant: &TenantCtx,
|
||||
ids: &[String],
|
||||
request: impl Fn() -> VexRequest,
|
||||
) -> Result<(), Refusal> {
|
||||
for id in ids {
|
||||
// The answer (the stored statement) is not needed here.
|
||||
let _stored = set_cve_vex(
|
||||
agent.clone(),
|
||||
tenant.clone(),
|
||||
Path(id.clone()),
|
||||
Json(request()),
|
||||
)
|
||||
.await?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// POST /api/v1/inbox/decide `{key, action, reason?, justification?,
|
||||
/// statement?}` — apply `action` to every item of card `key`, through the
|
||||
/// findings' and the VEX endpoints' code, and answer what each item was
|
||||
/// before (for `POST /api/v1/inbox/undo`). The card's resubmission, if any,
|
||||
/// is dropped. 409 when nothing on the card waits any more, 422 for an action
|
||||
/// the card does not offer or without the reason, justification or statement
|
||||
/// it needs.
|
||||
#[tracing::instrument(skip_all, fields(key = %req.key, action = ?req.action))]
|
||||
pub async fn decide(
|
||||
agent: AgentExt,
|
||||
tenant: TenantCtx,
|
||||
Json(req): Json<DecideRequest>,
|
||||
) -> Result<Json<DecideResponse>, Refusal> {
|
||||
let db = tenant_db(&agent, &tenant)
|
||||
.await
|
||||
.map_err(|code| refuse(code, "tenant"))?;
|
||||
let (card, previous) = resolve_card(&db, &req.key).await?;
|
||||
if !card.actions.contains(&req.action) {
|
||||
return Err(refuse(
|
||||
StatusCode::UNPROCESSABLE_ENTITY,
|
||||
"the card does not offer this action",
|
||||
));
|
||||
}
|
||||
let text = |s: &Option<String>| {
|
||||
s.as_deref()
|
||||
.map(str::trim)
|
||||
.filter(|t| !t.is_empty())
|
||||
.map(String::from)
|
||||
};
|
||||
let vex = |status, justification, impact_statement, action_statement| {
|
||||
move || VexRequest {
|
||||
status,
|
||||
justification,
|
||||
impact_statement: Option::clone(&impact_statement),
|
||||
action_statement: Option::clone(&action_statement),
|
||||
}
|
||||
};
|
||||
let ids = card.item_ids;
|
||||
match req.action {
|
||||
InboxAction::FalsePositive => {
|
||||
set_finding_status(&agent, &tenant, ids, FindingStatus::FalsePositive, None).await?;
|
||||
}
|
||||
InboxAction::AcceptedRisk => {
|
||||
let reason = text(&req.reason);
|
||||
set_finding_status(&agent, &tenant, ids, FindingStatus::AcceptedRisk, reason).await?;
|
||||
}
|
||||
InboxAction::Confirm => {
|
||||
set_finding_status(&agent, &tenant, ids, FindingStatus::Triaged, None).await?;
|
||||
}
|
||||
InboxAction::NotAffected => {
|
||||
let statement = vex(
|
||||
VexStatus::NotAffected,
|
||||
req.justification,
|
||||
text(&req.statement),
|
||||
None,
|
||||
);
|
||||
set_vex(&agent, &tenant, &ids, statement).await?;
|
||||
}
|
||||
InboxAction::Affected => {
|
||||
let statement = vex(VexStatus::Affected, None, None, text(&req.statement));
|
||||
set_vex(&agent, &tenant, &ids, statement).await?;
|
||||
}
|
||||
}
|
||||
db.inbox_snoozes()
|
||||
.delete_one(doc! { "key": &req.key })
|
||||
.await
|
||||
.map_err(store_error)?;
|
||||
Ok(Json(DecideResponse {
|
||||
key: req.key,
|
||||
action: req.action,
|
||||
previous,
|
||||
}))
|
||||
}
|
||||
|
||||
/// Whether the items of `previous` are those of card `key`: the finding the
|
||||
/// key names, or alerts of the key's package version.
|
||||
async fn belongs_to(db: &Database, key: &str, previous: &[PreviousState]) -> Result<bool, Refusal> {
|
||||
match CardKey::parse(key).ok_or_else(|| refuse(StatusCode::BAD_REQUEST, "bad key"))? {
|
||||
CardKey::Finding { id } => Ok(previous
|
||||
.iter()
|
||||
.all(|p| matches!(p, PreviousState::Finding { id: item, .. } if *item == id))),
|
||||
CardKey::CvePackage { .. } => {
|
||||
let mut oids = Vec::with_capacity(previous.len());
|
||||
for state in previous {
|
||||
let PreviousState::Cve { id, .. } = state else {
|
||||
return Ok(false);
|
||||
};
|
||||
oids.push(
|
||||
ObjectId::parse_str(id)
|
||||
.map_err(|_| refuse(StatusCode::BAD_REQUEST, "bad id"))?,
|
||||
);
|
||||
}
|
||||
let cursor = db
|
||||
.cve_alerts()
|
||||
.find(doc! { "_id": { "$in": &oids } })
|
||||
.await
|
||||
.map_err(store_error)?;
|
||||
let alerts: Vec<CveAlert> = collect_cursor_async(cursor).await;
|
||||
Ok(alerts.len() == oids.len()
|
||||
&& alerts.iter().all(|a| {
|
||||
CardKey::cve_package(&a.repo_id, &a.affected_package, &a.affected_version)
|
||||
== key
|
||||
}))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// POST /api/v1/inbox/undo `{key, previous}` — put the items of a decision
|
||||
/// on card `key` back, through the same code the decision went through: a
|
||||
/// finding gets its previous status (a new entry in its history, which keeps
|
||||
/// the decision on record), an alert `under_investigation` (also when it had
|
||||
/// no statement before; both leave it open). 422 when an item does not
|
||||
/// belong to the card or its previous state was not an open one.
|
||||
#[tracing::instrument(skip_all, fields(key = %req.key))]
|
||||
pub async fn undo(
|
||||
agent: AgentExt,
|
||||
tenant: TenantCtx,
|
||||
Json(req): Json<UndoRequest>,
|
||||
) -> Result<Json<serde_json::Value>, Refusal> {
|
||||
let db = tenant_db(&agent, &tenant)
|
||||
.await
|
||||
.map_err(|code| refuse(code, "tenant"))?;
|
||||
if req.previous.is_empty() || !belongs_to(&db, &req.key, &req.previous).await? {
|
||||
return Err(refuse(
|
||||
StatusCode::UNPROCESSABLE_ENTITY,
|
||||
"the items do not belong to the card",
|
||||
));
|
||||
}
|
||||
let mut by_status: BTreeMap<FindingStatus, Vec<String>> = BTreeMap::new();
|
||||
let mut alerts = Vec::new();
|
||||
for state in req.previous {
|
||||
match state {
|
||||
PreviousState::Finding { id, status } if UNDECIDED_STATUSES.contains(&status) => {
|
||||
by_status.entry(status).or_default().push(id);
|
||||
}
|
||||
PreviousState::Cve {
|
||||
id,
|
||||
vex: None | Some(VexStatus::UnderInvestigation),
|
||||
} => {
|
||||
alerts.push(id);
|
||||
}
|
||||
PreviousState::Finding { .. } | PreviousState::Cve { .. } => {
|
||||
return Err(refuse(
|
||||
StatusCode::UNPROCESSABLE_ENTITY,
|
||||
"only an open state can be restored",
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
for (status, ids) in by_status {
|
||||
set_finding_status(&agent, &tenant, ids, status, None).await?;
|
||||
}
|
||||
set_vex(&agent, &tenant, &alerts, || VexRequest {
|
||||
status: VexStatus::UnderInvestigation,
|
||||
justification: None,
|
||||
impact_statement: None,
|
||||
action_statement: None,
|
||||
})
|
||||
.await?;
|
||||
Ok(Json(serde_json::json!({ "status": "restored" })))
|
||||
}
|
||||
|
||||
/// POST /api/v1/inbox/snooze `{key, for}` — put card `key` off: one week, one
|
||||
/// month, or until a date (`{"kind": "date", "date": "2026-12-01"}`). It is
|
||||
/// hidden until then and comes back in its own bucket, or earlier when a new
|
||||
/// CVE or a KEV entry joins it: the snooze records the card's items and
|
||||
/// whether it was KEV. A second snooze replaces the first. 400 for a
|
||||
/// malformed key, 409 when nothing on the card waits for a decision, 422 for
|
||||
/// a date that is not in the future.
|
||||
#[tracing::instrument(skip_all, fields(key = %req.key))]
|
||||
pub async fn snooze(
|
||||
Extension(agent): AgentExt,
|
||||
tenant: TenantCtx,
|
||||
Json(req): Json<SnoozeRequest>,
|
||||
) -> Result<Json<SnoozeResponse>, Refusal> {
|
||||
if CardKey::parse(&req.key).is_none() {
|
||||
return Err(refuse(StatusCode::BAD_REQUEST, "bad key"));
|
||||
}
|
||||
let now = Utc::now();
|
||||
let until = req
|
||||
.snooze_for
|
||||
.until(now)
|
||||
.map_err(|e| refuse(StatusCode::UNPROCESSABLE_ENTITY, &e.to_string()))?;
|
||||
let db = tenant_db(&agent, &tenant)
|
||||
.await
|
||||
.map_err(|code| refuse(code, "tenant"))?;
|
||||
let (card, _) = resolve_card(&db, &req.key).await?;
|
||||
let actor = Actor::of(&tenant.0);
|
||||
let record = InboxSnooze {
|
||||
key: req.key.clone(),
|
||||
until,
|
||||
by: actor.id.to_string(),
|
||||
by_name: actor.name,
|
||||
at: now,
|
||||
kev: card.reasons.contains(&Reason::Kev),
|
||||
items: card.item_ids,
|
||||
};
|
||||
db.inbox_snoozes()
|
||||
.replace_one(doc! { "key": &req.key }, &record)
|
||||
.upsert(true)
|
||||
.await
|
||||
.map_err(store_error)?;
|
||||
Ok(Json(SnoozeResponse {
|
||||
key: req.key,
|
||||
until,
|
||||
}))
|
||||
}
|
||||
|
||||
/// DELETE /api/v1/inbox/snooze/{key} — take card `key`'s resubmission back
|
||||
/// (the undo of a snooze); nothing to take back is no error.
|
||||
#[tracing::instrument(skip_all, fields(key = %key))]
|
||||
pub async fn unsnooze(
|
||||
Extension(agent): AgentExt,
|
||||
tenant: TenantCtx,
|
||||
Path(key): Path<String>,
|
||||
) -> Result<Json<serde_json::Value>, Refusal> {
|
||||
if CardKey::parse(&key).is_none() {
|
||||
return Err(refuse(StatusCode::BAD_REQUEST, "bad key"));
|
||||
}
|
||||
let db = tenant_db(&agent, &tenant)
|
||||
.await
|
||||
.map_err(|code| refuse(code, "tenant"))?;
|
||||
db.inbox_snoozes()
|
||||
.delete_one(doc! { "key": &key })
|
||||
.await
|
||||
.map_err(store_error)?;
|
||||
Ok(Json(serde_json::json!({ "status": "deleted" })))
|
||||
}
|
||||
@@ -1,32 +1,42 @@
|
||||
use axum::extract::{Extension, Query};
|
||||
use axum::Json;
|
||||
use mongodb::bson::doc;
|
||||
use mongodb::bson::{doc, Bson, Document};
|
||||
|
||||
use super::dto::*;
|
||||
use compliance_core::models::issue::cve_issue_prefix;
|
||||
use compliance_core::models::TrackerIssue;
|
||||
use compliance_core::tenant_ctx::TenantCtx;
|
||||
|
||||
#[tracing::instrument(skip_all)]
|
||||
/// The tenant's tickets, newest first, searched and filtered by `filter`.
|
||||
///
|
||||
/// A ticket stores no target, only the finding it is about: the target filter
|
||||
/// first looks up the ids of the target's findings that have a ticket.
|
||||
#[tracing::instrument(skip_all, fields(repo_id = ?filter.repo_id, status = ?filter.status))]
|
||||
pub async fn list_issues(
|
||||
Extension(agent): AgentExt,
|
||||
tenant: TenantCtx,
|
||||
Query(params): Query<PaginationParams>,
|
||||
Query(filter): Query<IssuesFilter>,
|
||||
) -> ApiResult<Vec<TrackerIssue>> {
|
||||
let db = tenant_db(&agent, &tenant).await?;
|
||||
let db = &db;
|
||||
let skip = params.skip();
|
||||
let finding_ids = match filter.target() {
|
||||
Some(repo_id) => Some(ticketed_finding_ids(db, repo_id).await),
|
||||
None => None,
|
||||
};
|
||||
let query = issues_query(&filter, finding_ids.as_deref());
|
||||
let skip = filter.skip();
|
||||
let total = db
|
||||
.tracker_issues()
|
||||
.count_documents(doc! {})
|
||||
.count_documents(query.clone())
|
||||
.await
|
||||
.unwrap_or(0);
|
||||
|
||||
let issues = match db
|
||||
.tracker_issues()
|
||||
.find(doc! {})
|
||||
.find(query)
|
||||
.sort(doc! { "created_at": -1 })
|
||||
.skip(skip)
|
||||
.limit(params.limit)
|
||||
.limit(filter.limit)
|
||||
.await
|
||||
{
|
||||
Ok(cursor) => collect_cursor_async(cursor).await,
|
||||
@@ -39,6 +49,198 @@ pub async fn list_issues(
|
||||
Ok(Json(ApiResponse {
|
||||
data: issues,
|
||||
total: Some(total),
|
||||
page: Some(params.page),
|
||||
page: Some(filter.page),
|
||||
}))
|
||||
}
|
||||
|
||||
/// The ids (hex) of the findings of target `repo_id` that have a ticket.
|
||||
///
|
||||
/// Storing a finding's ticket sets the finding's `tracker_issue_url`
|
||||
/// (`pipeline::issue_creation`), so the other findings are left out. A failed
|
||||
/// lookup is logged and leaves only the target's CVE tickets.
|
||||
async fn ticketed_finding_ids(db: &crate::database::Database, repo_id: &str) -> Vec<String> {
|
||||
let filter = doc! { "repo_id": repo_id, "tracker_issue_url": { "$ne": Bson::Null } };
|
||||
match db.findings().distinct("_id", filter).await {
|
||||
Ok(ids) => ids
|
||||
.iter()
|
||||
.filter_map(Bson::as_object_id)
|
||||
.map(|id| id.to_hex())
|
||||
.collect(),
|
||||
Err(e) => {
|
||||
tracing::warn!("Failed to look up the target's findings: {e}");
|
||||
Vec::new()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The Mongo filter of the tickets list.
|
||||
///
|
||||
/// # Arguments
|
||||
///
|
||||
/// * `filter` - the caller's search and filters
|
||||
/// * `finding_ids` - for a target filter, the ids of the target's findings
|
||||
/// with a ticket ([`ticketed_finding_ids`]); `None` without one
|
||||
///
|
||||
/// # Returns
|
||||
///
|
||||
/// `{}` for no filter, else an `$and` of the search (title or ticket number),
|
||||
/// the status and the target.
|
||||
fn issues_query(filter: &IssuesFilter, finding_ids: Option<&[String]>) -> Document {
|
||||
let mut clauses: Vec<Document> = Vec::with_capacity(3);
|
||||
if let Some(term) = filter.search() {
|
||||
let mut either = vec![doc! { "title": { "$regex": literal_regex(term), "$options": "i" } }];
|
||||
// `#913` is ticket 913; `913` also finds the Jira key `PROJ-913`.
|
||||
let number = term.strip_prefix('#').unwrap_or(term).trim();
|
||||
if !number.is_empty() {
|
||||
let exact = format!("(^|-){}$", literal_regex(number));
|
||||
either.push(doc! { "external_id": { "$regex": exact, "$options": "i" } });
|
||||
}
|
||||
clauses.push(doc! { "$or": either });
|
||||
}
|
||||
if let Some(state) = filter.status {
|
||||
clauses.push(doc! { "status": { "$in": state.statuses() } });
|
||||
}
|
||||
if let (Some(repo_id), Some(ids)) = (filter.target(), finding_ids) {
|
||||
// A CVE ticket names its target in its key instead of a finding.
|
||||
let cve = format!("^{}", literal_regex(&cve_issue_prefix(repo_id)));
|
||||
clauses.push(doc! { "$or": [
|
||||
{ "finding_id": { "$in": ids } },
|
||||
{ "finding_id": { "$regex": cve } },
|
||||
] });
|
||||
}
|
||||
if clauses.is_empty() {
|
||||
Document::new()
|
||||
} else {
|
||||
doc! { "$and": clauses }
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[allow(clippy::unwrap_used)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn filter(json: &str) -> IssuesFilter {
|
||||
serde_json::from_str(json).unwrap()
|
||||
}
|
||||
|
||||
/// The clauses of the `$and`, by position.
|
||||
fn clauses(query: &Document) -> Vec<Document> {
|
||||
query
|
||||
.get_array("$and")
|
||||
.unwrap()
|
||||
.iter()
|
||||
.map(|c| c.as_document().unwrap().clone())
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The external-id regex a search for `term` uses.
|
||||
fn number_regex(term: &str) -> String {
|
||||
let query = issues_query(&filter(&format!(r#"{{"q":{term:?}}}"#)), None);
|
||||
let either = clauses(&query)[0].get_array("$or").unwrap().clone();
|
||||
let external = either[1].as_document().unwrap();
|
||||
external
|
||||
.get_document("external_id")
|
||||
.unwrap()
|
||||
.get_str("$regex")
|
||||
.unwrap()
|
||||
.to_string()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_filter_lists_everything() {
|
||||
assert_eq!(issues_query(&filter("{}"), None), Document::new());
|
||||
assert_eq!(
|
||||
issues_query(&filter(r#"{"q":" ","repo_id":""}"#), None),
|
||||
Document::new()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_number_with_or_without_hash_finds_the_ticket() {
|
||||
assert_eq!(number_regex("913"), "(^|-)913$");
|
||||
assert_eq!(number_regex("#913"), "(^|-)913$");
|
||||
let re = regex::RegexBuilder::new(&number_regex("#913"))
|
||||
.case_insensitive(true)
|
||||
.build()
|
||||
.unwrap();
|
||||
assert!(re.is_match("913"));
|
||||
assert!(re.is_match("PROJ-913"));
|
||||
assert!(!re.is_match("1913"));
|
||||
assert!(!re.is_match("9130"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_search_is_a_literal_title_substring() {
|
||||
let query = issues_query(&filter(r#"{"q":"(a+)+$"}"#), None);
|
||||
let either = clauses(&query)[0].get_array("$or").unwrap().clone();
|
||||
let title = either[0]
|
||||
.as_document()
|
||||
.unwrap()
|
||||
.get_document("title")
|
||||
.unwrap();
|
||||
assert_eq!(title.get_str("$regex").unwrap(), r"\(a\+\)\+\$");
|
||||
assert_eq!(title.get_str("$options").unwrap(), "i");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_lone_hash_searches_the_title_only() {
|
||||
let query = issues_query(&filter(r##"{"q":"#"}"##), None);
|
||||
assert_eq!(clauses(&query)[0].get_array("$or").unwrap().len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_status_filter_takes_both_stored_statuses() {
|
||||
let query = issues_query(&filter(r#"{"status":"open"}"#), None);
|
||||
assert_eq!(
|
||||
clauses(&query)[0],
|
||||
doc! { "status": { "$in": ["open", "in_progress"] } }
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_target_filter_takes_its_findings_and_its_cves() {
|
||||
let ids = vec!["65a1b2c3d4e5f60718293a4b".to_string()];
|
||||
let query = issues_query(&filter(r#"{"repo_id":"t1"}"#), Some(&ids));
|
||||
assert_eq!(
|
||||
clauses(&query)[0],
|
||||
doc! { "$or": [
|
||||
{ "finding_id": { "$in": ["65a1b2c3d4e5f60718293a4b"] } },
|
||||
{ "finding_id": { "$regex": "^cve:t1:" } },
|
||||
] }
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_target_without_ticketed_findings_still_has_its_cves() {
|
||||
let query = issues_query(&filter(r#"{"repo_id":"t.1"}"#), Some(&[]));
|
||||
let either = clauses(&query)[0].get_array("$or").unwrap().clone();
|
||||
let cve = either[1]
|
||||
.as_document()
|
||||
.unwrap()
|
||||
.get_document("finding_id")
|
||||
.unwrap();
|
||||
// The id is matched literally.
|
||||
assert_eq!(cve.get_str("$regex").unwrap(), r"^cve:t\.1:");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn search_status_and_target_all_apply() {
|
||||
// Search and target are both an `$or`: neither may replace the other.
|
||||
let query = issues_query(
|
||||
&filter(r#"{"q":"913","status":"closed","repo_id":"t1"}"#),
|
||||
Some(&[]),
|
||||
);
|
||||
let all = clauses(&query);
|
||||
assert_eq!(all.len(), 3);
|
||||
assert!(all[0].get_array("$or").unwrap()[0]
|
||||
.as_document()
|
||||
.unwrap()
|
||||
.contains_key("title"));
|
||||
assert!(all[1].contains_key("status"));
|
||||
assert!(all[2].get_array("$or").unwrap()[0]
|
||||
.as_document()
|
||||
.unwrap()
|
||||
.contains_key("finding_id"));
|
||||
}
|
||||
}
|
||||
@@ -1,14 +1,19 @@
|
||||
pub mod admin;
|
||||
pub mod chat;
|
||||
pub mod cve_history;
|
||||
pub mod cve_matrix;
|
||||
pub mod dast;
|
||||
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;
|
||||
pub mod health;
|
||||
pub mod help_chat;
|
||||
pub mod inbox;
|
||||
pub mod issues;
|
||||
pub mod licenses;
|
||||
pub mod manual_findings;
|
||||
@@ -23,6 +28,8 @@ pub mod platform;
|
||||
pub mod projects;
|
||||
pub use pentest_handlers as pentest;
|
||||
pub mod sbom;
|
||||
pub mod sbom_ecosystems;
|
||||
pub mod scan_changes;
|
||||
pub mod scans;
|
||||
pub mod support;
|
||||
pub mod target_input;
|
||||
|
||||
@@ -640,6 +640,10 @@ fn git_source_json(
|
||||
"webhook_secret".into(),
|
||||
new_secret.map_or(serde_json::Value::Null, Into::into),
|
||||
);
|
||||
obj.insert(
|
||||
"webhook_events".into(),
|
||||
crate::git_source::WEBHOOK_EVENTS.as_slice().into(),
|
||||
);
|
||||
}
|
||||
v
|
||||
}
|
||||
|
||||
@@ -31,7 +31,7 @@ pub async fn sbom_filters(
|
||||
.unwrap_or_default()
|
||||
.into_iter()
|
||||
.filter_map(|v| v.as_str().map(|s| s.to_string()))
|
||||
.filter(|s| !s.is_empty() && s != "unknown" && s != "file")
|
||||
.filter(|s| compliance_core::sbom_ecosystems::is_filterable_manager(s))
|
||||
.collect();
|
||||
|
||||
let licenses: Vec<String> = db
|
||||
|
||||
@@ -0,0 +1,131 @@
|
||||
//! GET /api/v1/targets/{id}/sbom-ecosystems: a target's SBOM components per
|
||||
//! ecosystem, and how many of them have a known vulnerability (#957).
|
||||
|
||||
use axum::extract::{Extension, Path};
|
||||
use axum::http::StatusCode;
|
||||
use axum::Json;
|
||||
use futures_util::TryStreamExt;
|
||||
use mongodb::bson::{doc, Document};
|
||||
use serde::Deserialize;
|
||||
|
||||
use super::dto::{tenant_db, AgentExt, ApiResponse, ApiResult};
|
||||
use compliance_core::sbom_ecosystems::{rank, EcosystemCount};
|
||||
use compliance_core::tenant_ctx::TenantCtx;
|
||||
|
||||
/// One row of [`pipeline`]: a package manager with its counts. `_id` is
|
||||
/// `None` for components stored without one.
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct EcosystemRow {
|
||||
#[serde(rename = "_id")]
|
||||
package_manager: Option<String>,
|
||||
components: u64,
|
||||
with_cve: u64,
|
||||
}
|
||||
|
||||
impl From<EcosystemRow> for EcosystemCount {
|
||||
fn from(row: EcosystemRow) -> Self {
|
||||
Self {
|
||||
package_manager: row.package_manager.unwrap_or_default(),
|
||||
components: row.components,
|
||||
with_cve: row.with_cve,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The aggregation counting the components of target `repo_id` per package
|
||||
/// manager in the database, so only one row per ecosystem leaves it (never
|
||||
/// the components with their vulnerability lists, #67).
|
||||
fn pipeline(repo_id: &str) -> Vec<Document> {
|
||||
vec![
|
||||
doc! { "$match": { "repo_id": repo_id } },
|
||||
doc! { "$group": {
|
||||
"_id": "$package_manager",
|
||||
"components": { "$sum": 1 },
|
||||
// A component stored without the list counts as without a CVE.
|
||||
"with_cve": { "$sum": { "$cond": [
|
||||
{ "$gt": [{ "$size": { "$ifNull": ["$known_vulnerabilities", []] } }, 0] },
|
||||
1,
|
||||
0,
|
||||
] } },
|
||||
} },
|
||||
]
|
||||
}
|
||||
|
||||
/// GET /api/v1/targets/{id}/sbom-ecosystems — the SBOM components of target
|
||||
/// `id` per ecosystem the component table can filter by, the largest first.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// `500` when the aggregation fails, so the dashboard says so instead of
|
||||
/// showing an empty chart.
|
||||
#[tracing::instrument(skip_all, fields(target_id = %id))]
|
||||
pub async fn list_sbom_ecosystems(
|
||||
Extension(agent): AgentExt,
|
||||
tenant: TenantCtx,
|
||||
Path(id): Path<String>,
|
||||
) -> ApiResult<Vec<EcosystemCount>> {
|
||||
let db = tenant_db(&agent, &tenant).await?;
|
||||
let fail = |e: mongodb::error::Error| {
|
||||
tracing::warn!("Failed to count the SBOM ecosystems: {e}");
|
||||
StatusCode::INTERNAL_SERVER_ERROR
|
||||
};
|
||||
let rows: Vec<Document> = db
|
||||
.sbom_entries()
|
||||
.aggregate(pipeline(&id))
|
||||
.await
|
||||
.map_err(fail)?
|
||||
.try_collect()
|
||||
.await
|
||||
.map_err(fail)?;
|
||||
let counts = rows
|
||||
.into_iter()
|
||||
.filter_map(|row| mongodb::bson::from_document::<EcosystemRow>(row).ok())
|
||||
.map(EcosystemCount::from)
|
||||
.collect();
|
||||
let ecosystems = rank(counts);
|
||||
Ok(Json(ApiResponse {
|
||||
total: Some(ecosystems.len() as u64),
|
||||
data: ecosystems,
|
||||
page: None,
|
||||
}))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn the_pipeline_counts_one_target_per_package_manager() {
|
||||
let stages = pipeline("t1");
|
||||
assert_eq!(stages.len(), 2);
|
||||
assert_eq!(stages[0], doc! { "$match": { "repo_id": "t1" } });
|
||||
let group = stages[1].get_document("$group").expect("a $group stage");
|
||||
assert_eq!(group.get_str("_id").ok(), Some("$package_manager"));
|
||||
assert_eq!(
|
||||
group.get_document("components").ok(),
|
||||
Some(&doc! { "$sum": 1 })
|
||||
);
|
||||
assert!(group.contains_key("with_cve"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_row_reads_as_its_count_whatever_integer_width_mongo_sums_in() {
|
||||
let row: EcosystemRow = mongodb::bson::from_document(
|
||||
doc! { "_id": "npm", "components": 412_i32, "with_cve": 7_i64 },
|
||||
)
|
||||
.expect("a row");
|
||||
assert_eq!(
|
||||
EcosystemCount::from(row),
|
||||
EcosystemCount {
|
||||
package_manager: "npm".into(),
|
||||
components: 412,
|
||||
with_cve: 7,
|
||||
}
|
||||
);
|
||||
let nameless: EcosystemRow = mongodb::bson::from_document(
|
||||
doc! { "_id": null, "components": 2_i32, "with_cve": 0_i32 },
|
||||
)
|
||||
.expect("a row without a package manager");
|
||||
assert_eq!(EcosystemCount::from(nameless).package_manager, "");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,141 @@
|
||||
//! A target's "Verlauf" (#957): what each of its last scans changed, the
|
||||
//! CVE alerts found new and those found gone ([`compliance_core::scan_changes`]).
|
||||
//!
|
||||
//! Reads the tenant's own database; the org-role middleware lets every role
|
||||
//! that may read call it, like the other target reads.
|
||||
|
||||
use axum::extract::{Extension, Path, Query};
|
||||
use axum::http::StatusCode;
|
||||
use axum::Json;
|
||||
use mongodb::bson::{doc, oid::ObjectId, DateTime as BsonDateTime, Document};
|
||||
use serde::{Deserialize, Deserializer};
|
||||
|
||||
use compliance_core::models::{CveAlert, ScanRun};
|
||||
use compliance_core::scan_changes::{changes, ScanChange, DEFAULT_SCANS, MAX_SCANS};
|
||||
use compliance_core::tenant_ctx::TenantCtx;
|
||||
|
||||
use super::dto::{collect_cursor_async, tenant_db, AgentExt, ApiResponse, ApiResult};
|
||||
|
||||
/// The query of [`target_scan_changes`].
|
||||
#[derive(Debug, Deserialize)]
|
||||
pub struct ChangesQuery {
|
||||
/// The last scans to show, `1..=50` (clamped); 20 when not given.
|
||||
#[serde(default = "default_limit", deserialize_with = "de_limit")]
|
||||
pub limit: usize,
|
||||
}
|
||||
|
||||
fn default_limit() -> usize {
|
||||
DEFAULT_SCANS
|
||||
}
|
||||
|
||||
/// Clamp a caller-supplied number of scans to `1..=MAX_SCANS`.
|
||||
fn de_limit<'de, D: Deserializer<'de>>(d: D) -> Result<usize, D::Error> {
|
||||
Ok(usize::deserialize(d)?.clamp(1, MAX_SCANS))
|
||||
}
|
||||
|
||||
/// Log a database error and answer 500.
|
||||
fn db_error(what: &str) -> impl FnOnce(mongodb::error::Error) -> StatusCode + '_ {
|
||||
move |e| {
|
||||
tracing::warn!("scan changes: {what} failed: {e}");
|
||||
StatusCode::INTERNAL_SERVER_ERROR
|
||||
}
|
||||
}
|
||||
|
||||
/// `GET /api/v1/targets/{id}/scan-changes[?limit=20]` — the target's last
|
||||
/// scans, oldest first, each with the CVE alerts found new and gone since
|
||||
/// the completed scan before it (most severe first), its status and its new
|
||||
/// findings. The target's first completed scan is marked `baseline`. 404
|
||||
/// for a target the tenant does not have.
|
||||
#[tracing::instrument(skip_all, fields(target_id = %id))]
|
||||
pub async fn target_scan_changes(
|
||||
Extension(agent): AgentExt,
|
||||
tenant: TenantCtx,
|
||||
Path(id): Path<String>,
|
||||
Query(query): Query<ChangesQuery>,
|
||||
) -> ApiResult<Vec<ScanChange>> {
|
||||
let oid = ObjectId::parse_str(&id).map_err(|_| StatusCode::BAD_REQUEST)?;
|
||||
let db = tenant_db(&agent, &tenant).await?;
|
||||
// Only whether it exists: its id is all that is read.
|
||||
db.onboarded_targets()
|
||||
.clone_with_type::<Document>()
|
||||
.find_one(doc! { "_id": oid })
|
||||
.projection(doc! { "_id": 1 })
|
||||
.await
|
||||
.map_err(db_error("reading the target"))?
|
||||
.ok_or(StatusCode::NOT_FOUND)?;
|
||||
|
||||
let runs: Vec<ScanRun> = collect_cursor_async(
|
||||
db.scan_runs()
|
||||
.find(doc! { "repo_id": &id })
|
||||
.sort(doc! { "started_at": -1 })
|
||||
.limit(i64::try_from(query.limit).unwrap_or(i64::MAX))
|
||||
.await
|
||||
.map_err(db_error("listing the runs"))?,
|
||||
)
|
||||
.await;
|
||||
// Where the window of the oldest shown scan starts: the end of the
|
||||
// completed scan before it, if there is one.
|
||||
let since = match runs.iter().map(|r| r.started_at).min() {
|
||||
Some(oldest) => db
|
||||
.scan_runs()
|
||||
.find_one(doc! {
|
||||
"repo_id": &id,
|
||||
"status": "completed",
|
||||
"started_at": { "$lt": BsonDateTime::from_chrono(oldest) },
|
||||
})
|
||||
.sort(doc! { "started_at": -1 })
|
||||
.await
|
||||
.map_err(db_error("finding the scan before"))?
|
||||
.and_then(|run| run.completed_at),
|
||||
None => None,
|
||||
};
|
||||
|
||||
let mut filter = doc! { "repo_id": &id };
|
||||
if let Some(since) = since {
|
||||
let since = BsonDateTime::from_chrono(since);
|
||||
filter.insert(
|
||||
"$or",
|
||||
vec![
|
||||
doc! { "created_at": { "$gt": since } },
|
||||
doc! { "resolved_at": { "$gt": since } },
|
||||
],
|
||||
);
|
||||
}
|
||||
let alerts: Vec<CveAlert> = collect_cursor_async(
|
||||
db.cve_alerts()
|
||||
.find(filter)
|
||||
.projection(doc! {
|
||||
"summary": 0, "llm_impact_summary": 0, "advisories": 0, "exploitation": 0,
|
||||
})
|
||||
.await
|
||||
.map_err(db_error("loading the alerts"))?,
|
||||
)
|
||||
.await;
|
||||
|
||||
let data = changes(&runs, since, &alerts);
|
||||
Ok(Json(ApiResponse {
|
||||
total: Some(data.len() as u64),
|
||||
data,
|
||||
page: None,
|
||||
}))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn query(text: &str) -> ChangesQuery {
|
||||
let uri: axum::http::Uri = format!("/x?{text}").parse().unwrap_or_default();
|
||||
Query::<ChangesQuery>::try_from_uri(&uri)
|
||||
.map(|q| q.0)
|
||||
.unwrap_or(ChangesQuery { limit: 0 })
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_limit_is_clamped_and_defaults_to_twenty() {
|
||||
assert_eq!(query("").limit, DEFAULT_SCANS);
|
||||
assert_eq!(query("limit=0").limit, 1);
|
||||
assert_eq!(query("limit=999").limit, MAX_SCANS);
|
||||
assert_eq!(query("limit=5").limit, 5);
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
//! VEX for a target's CVE alerts (#498): list them, state their status, and
|
||||
//! export the statements as OpenVEX or CycloneDX VEX.
|
||||
//! VEX for a target's CVE alerts (#498): list them, state their status (one
|
||||
//! alert, or every open alert of a component at once, #949), and export the
|
||||
//! statements as OpenVEX or CycloneDX VEX.
|
||||
|
||||
use axum::extract::{Extension, Path, Query};
|
||||
use axum::http::{header, HeaderValue, StatusCode};
|
||||
@@ -9,6 +10,7 @@ use mongodb::bson::{doc, oid::ObjectId};
|
||||
use serde::Deserialize;
|
||||
|
||||
use compliance_core::csaf_docs;
|
||||
use compliance_core::cve_groups::{self, CveGroup, PackageKey};
|
||||
use compliance_core::enisa_docs::{self, EnisaInput, Reportability};
|
||||
use compliance_core::models::{CveAlert, SbomEntry, VexAssessment, VexJustification, VexStatus};
|
||||
use compliance_core::tenant_ctx::TenantCtx;
|
||||
@@ -26,18 +28,8 @@ pub async fn list_target_cves(
|
||||
Path(id): Path<String>,
|
||||
) -> ApiResult<Vec<CveAlert>> {
|
||||
let db = tenant_db(&agent, &tenant).await?;
|
||||
let alerts: Vec<CveAlert> = match db
|
||||
.cve_alerts()
|
||||
.find(doc! { "repo_id": &id })
|
||||
.sort(doc! { "created_at": -1 })
|
||||
.await
|
||||
{
|
||||
Ok(cursor) => collect_cursor_async(cursor).await,
|
||||
Err(e) => {
|
||||
tracing::warn!("Failed to list CVE alerts: {e}");
|
||||
Vec::new()
|
||||
}
|
||||
};
|
||||
// An unreadable list reads as empty here, as it always has.
|
||||
let alerts = target_alerts(&db, &id).await.unwrap_or_default();
|
||||
Ok(Json(ApiResponse {
|
||||
total: Some(alerts.len() as u64),
|
||||
data: alerts,
|
||||
@@ -45,6 +37,23 @@ pub async fn list_target_cves(
|
||||
}))
|
||||
}
|
||||
|
||||
/// The CVE alerts of target `id`, newest first.
|
||||
async fn target_alerts(
|
||||
db: &crate::database::Database,
|
||||
id: &str,
|
||||
) -> Result<Vec<CveAlert>, StatusCode> {
|
||||
let cursor = db
|
||||
.cve_alerts()
|
||||
.find(doc! { "repo_id": id })
|
||||
.sort(doc! { "created_at": -1 })
|
||||
.await
|
||||
.map_err(|e| {
|
||||
tracing::warn!("Failed to list CVE alerts: {e}");
|
||||
StatusCode::INTERNAL_SERVER_ERROR
|
||||
})?;
|
||||
Ok(collect_cursor_async(cursor).await)
|
||||
}
|
||||
|
||||
/// The body of [`set_cve_vex`].
|
||||
#[derive(Debug, Deserialize)]
|
||||
pub struct VexRequest {
|
||||
@@ -57,9 +66,8 @@ pub struct VexRequest {
|
||||
pub action_statement: Option<String>,
|
||||
}
|
||||
|
||||
/// The statement `req` asks for, by the requester of `tenant`.
|
||||
fn statement(req: VexRequest, tenant: &TenantCtx) -> VexAssessment {
|
||||
let actor = Actor::of(&tenant.0);
|
||||
/// The statement `req` asks for, by `actor`.
|
||||
fn statement(req: VexRequest, actor: Actor<'_>) -> VexAssessment {
|
||||
let text = |s: Option<String>| s.map(|t| t.trim().to_string()).filter(|t| !t.is_empty());
|
||||
VexAssessment {
|
||||
status: req.status,
|
||||
@@ -85,7 +93,7 @@ pub async fn set_cve_vex(
|
||||
) -> Result<Json<serde_json::Value>, (StatusCode, Json<serde_json::Value>)> {
|
||||
let fail = |code: StatusCode, error: &str| (code, Json(serde_json::json!({ "error": error })));
|
||||
let oid = ObjectId::parse_str(&id).map_err(|_| fail(StatusCode::BAD_REQUEST, "bad id"))?;
|
||||
let vex = statement(req, &tenant);
|
||||
let vex = statement(req, Actor::of(&tenant.0));
|
||||
vex.validate()
|
||||
.map_err(|e| fail(StatusCode::UNPROCESSABLE_ENTITY, &e.to_string()))?;
|
||||
let db = tenant_db(&agent, &tenant)
|
||||
@@ -104,6 +112,90 @@ pub async fn set_cve_vex(
|
||||
Ok(Json(serde_json::json!({ "status": "updated", "vex": vex })))
|
||||
}
|
||||
|
||||
/// GET /api/v1/targets/{id}/cve-groups — the target's open CVE alerts grouped
|
||||
/// by component (#949): the update that fixes them, their counts per
|
||||
/// severity, KEV and the highest EPSS score, the most severe group first.
|
||||
#[tracing::instrument(skip_all, fields(target_id = %id))]
|
||||
pub async fn list_cve_groups(
|
||||
Extension(agent): AgentExt,
|
||||
tenant: TenantCtx,
|
||||
Path(id): Path<String>,
|
||||
) -> ApiResult<Vec<CveGroup>> {
|
||||
let db = tenant_db(&agent, &tenant).await?;
|
||||
let groups = cve_groups::group_open_alerts(&target_alerts(&db, &id).await?);
|
||||
Ok(Json(ApiResponse {
|
||||
total: Some(groups.len() as u64),
|
||||
data: groups,
|
||||
page: None,
|
||||
}))
|
||||
}
|
||||
|
||||
/// The body of [`set_group_vex`]: the component as [`list_cve_groups`] names
|
||||
/// it, and the statement as [`set_cve_vex`] takes it.
|
||||
#[derive(Debug, Deserialize)]
|
||||
pub struct GroupVexRequest {
|
||||
#[serde(flatten)]
|
||||
pub key: PackageKey,
|
||||
#[serde(flatten)]
|
||||
pub statement: VexRequest,
|
||||
}
|
||||
|
||||
/// PATCH /api/v1/targets/{id}/cve-groups/vex — state one VEX status on every
|
||||
/// open alert of a component (#949): one statement per alert, with the
|
||||
/// validation, author and time of [`set_cve_vex`], so the exports and the
|
||||
/// CVE issues' auto-close treat them as single decisions. Settled alerts
|
||||
/// keep their statements. 422 as for one alert, 404 when the component has
|
||||
/// no open alert.
|
||||
#[tracing::instrument(skip_all, fields(target_id = %id))]
|
||||
pub async fn set_group_vex(
|
||||
Extension(agent): AgentExt,
|
||||
tenant: TenantCtx,
|
||||
Path(id): Path<String>,
|
||||
Json(req): Json<GroupVexRequest>,
|
||||
) -> Result<Json<serde_json::Value>, (StatusCode, Json<serde_json::Value>)> {
|
||||
let fail = |code: StatusCode, error: &str| (code, Json(serde_json::json!({ "error": error })));
|
||||
let vex = statement(req.statement, Actor::of(&tenant.0));
|
||||
vex.validate()
|
||||
.map_err(|e| fail(StatusCode::UNPROCESSABLE_ENTITY, &e.to_string()))?;
|
||||
let db = tenant_db(&agent, &tenant)
|
||||
.await
|
||||
.map_err(|code| fail(code, "tenant"))?;
|
||||
let alerts = target_alerts(&db, &id)
|
||||
.await
|
||||
.map_err(|code| fail(code, "load"))?;
|
||||
let ids = open_alert_ids(&alerts, &req.key);
|
||||
if ids.is_empty() {
|
||||
return Err(fail(
|
||||
StatusCode::NOT_FOUND,
|
||||
"no open alert of this component",
|
||||
));
|
||||
}
|
||||
let vex_bson = mongodb::bson::to_bson(&vex)
|
||||
.map_err(|_| fail(StatusCode::INTERNAL_SERVER_ERROR, "encode"))?;
|
||||
let result = db
|
||||
.cve_alerts()
|
||||
.update_many(
|
||||
doc! { "_id": { "$in": ids }, "repo_id": &id },
|
||||
doc! { "$set": { "vex": vex_bson } },
|
||||
)
|
||||
.await
|
||||
.map_err(|_| fail(StatusCode::INTERNAL_SERVER_ERROR, "store"))?;
|
||||
Ok(Json(serde_json::json!({
|
||||
"status": "updated",
|
||||
"updated": result.matched_count,
|
||||
"vex": vex,
|
||||
})))
|
||||
}
|
||||
|
||||
/// The ids of the open alerts among `alerts` that are about component `key`.
|
||||
fn open_alert_ids(alerts: &[CveAlert], key: &PackageKey) -> Vec<ObjectId> {
|
||||
alerts
|
||||
.iter()
|
||||
.filter(|a| cve_groups::is_open(a) && key.matches(a))
|
||||
.filter_map(|a| a.id)
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The query of [`export_vex`].
|
||||
#[derive(Debug, Deserialize)]
|
||||
pub struct VexExportQuery {
|
||||
@@ -441,6 +533,88 @@ pub async fn export_enisa(
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use compliance_core::models::{CveSource, VexError};
|
||||
|
||||
fn group_request(body: serde_json::Value) -> GroupVexRequest {
|
||||
serde_json::from_value(body).expect("a group request")
|
||||
}
|
||||
|
||||
fn actor() -> Actor<'static> {
|
||||
Actor {
|
||||
id: "u1",
|
||||
name: Some("Ada Admin".into()),
|
||||
support: false,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_group_decision_is_validated_like_a_single_one() {
|
||||
let req = group_request(serde_json::json!({
|
||||
"package": "vite",
|
||||
"version": "5.4.21",
|
||||
"purl": "pkg:npm/vite@5.4.21",
|
||||
"status": "not_affected",
|
||||
"impact_statement": " ",
|
||||
}));
|
||||
assert_eq!(
|
||||
req.key,
|
||||
PackageKey {
|
||||
package: "vite".into(),
|
||||
version: "5.4.21".into(),
|
||||
purl: Some("pkg:npm/vite@5.4.21".into()),
|
||||
}
|
||||
);
|
||||
let vex = statement(req.statement, actor());
|
||||
assert_eq!(vex.validate(), Err(VexError::NotAffectedWithoutReason));
|
||||
|
||||
let req = group_request(serde_json::json!({
|
||||
"package": "vite",
|
||||
"version": "5.4.21",
|
||||
"status": "not_affected",
|
||||
"justification": "vulnerable_code_not_in_execute_path",
|
||||
"impact_statement": " Build tool only. ",
|
||||
}));
|
||||
assert_eq!(req.key.purl, None);
|
||||
let vex = statement(req.statement, actor());
|
||||
assert_eq!(vex.validate(), Ok(()));
|
||||
assert_eq!(vex.impact_statement.as_deref(), Some("Build tool only."));
|
||||
assert_eq!(
|
||||
(vex.by.as_str(), vex.by_name.as_deref(), vex.by_scan),
|
||||
("u1", Some("Ada Admin"), false)
|
||||
);
|
||||
|
||||
let affected = group_request(serde_json::json!({
|
||||
"package": "vite",
|
||||
"version": "5.4.21",
|
||||
"status": "affected",
|
||||
}));
|
||||
assert_eq!(
|
||||
statement(affected.statement, actor()).validate(),
|
||||
Err(VexError::AffectedWithoutAction)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_group_decision_reaches_the_open_alerts_of_its_component_only() {
|
||||
let alert = |cve: &str, version: &str| {
|
||||
let mut a = CveAlert::new(
|
||||
cve.into(),
|
||||
"t1".into(),
|
||||
"vite".into(),
|
||||
version.into(),
|
||||
CveSource::Osv,
|
||||
);
|
||||
a.id = Some(ObjectId::new());
|
||||
a
|
||||
};
|
||||
let open = alert("CVE-2025-0001", "5.4.21");
|
||||
let mut settled = alert("CVE-2025-0002", "5.4.21");
|
||||
settled.resolved_at = Some(chrono::Utc::now());
|
||||
let other_version = alert("CVE-2025-0003", "6.0.0");
|
||||
let alerts = vec![open.clone(), settled, other_version];
|
||||
let key = PackageKey::of(&open);
|
||||
assert_eq!(open_alert_ids(&alerts, &key), [open.id.expect("an id")]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_publisher_namespace_is_a_web_url_or_the_placeholder() {
|
||||
|
||||
@@ -126,11 +126,18 @@ fn routes() -> Vec<(Method, String, bool)> {
|
||||
(Method::GET, format!("/api/v1/findings/{ID}"), false),
|
||||
(Method::PATCH, format!("/api/v1/findings/{ID}/status"), true),
|
||||
(Method::PATCH, "/api/v1/findings/bulk-status".into(), true),
|
||||
(Method::GET, "/api/v1/inbox".into(), false),
|
||||
(Method::POST, "/api/v1/inbox/decide".into(), true),
|
||||
(Method::POST, "/api/v1/inbox/undo".into(), true),
|
||||
(Method::POST, "/api/v1/inbox/snooze".into(), true),
|
||||
(Method::DELETE, format!("/api/v1/inbox/snooze/f-{ID}"), true),
|
||||
(
|
||||
Method::PATCH,
|
||||
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,
|
||||
@@ -142,7 +149,23 @@ 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/cve-history?days=30".into(), false),
|
||||
(
|
||||
Method::GET,
|
||||
format!("/api/v1/targets/{ID}/top-updates"),
|
||||
false,
|
||||
),
|
||||
(
|
||||
Method::GET,
|
||||
format!("/api/v1/targets/{ID}/scan-changes"),
|
||||
false,
|
||||
),
|
||||
(Method::GET, "/api/v1/licenses/conclusions".into(), false),
|
||||
(Method::PUT, "/api/v1/licenses/conclusions".into(), true),
|
||||
(
|
||||
|
||||
@@ -107,16 +107,66 @@ 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),
|
||||
)
|
||||
// The "Heute" inbox (#950): open decisions in urgency buckets.
|
||||
.route("/api/v1/inbox", get(handlers::inbox::get_inbox))
|
||||
.route("/api/v1/inbox/decide", post(handlers::inbox::decide))
|
||||
.route("/api/v1/inbox/undo", post(handlers::inbox::undo))
|
||||
.route("/api/v1/inbox/snooze", post(handlers::inbox::snooze))
|
||||
.route(
|
||||
"/api/v1/inbox/snooze/{key}",
|
||||
delete(handlers::inbox::unsnooze),
|
||||
)
|
||||
// VEX on a target's CVE alerts (#498).
|
||||
.route(
|
||||
"/api/v1/targets/{id}/cves",
|
||||
get(handlers::vex::list_target_cves),
|
||||
)
|
||||
.route(
|
||||
"/api/v1/targets/{id}/cve-matrix",
|
||||
get(handlers::cve_matrix::target_cve_matrix),
|
||||
)
|
||||
// Open CVEs with a fix per day, and the updates closing most (#952).
|
||||
.route(
|
||||
"/api/v1/cve-history",
|
||||
get(handlers::cve_history::cve_history),
|
||||
)
|
||||
.route(
|
||||
"/api/v1/targets/{id}/top-updates",
|
||||
get(handlers::cve_history::target_top_updates),
|
||||
)
|
||||
// What each scan changed, for the target's "Verlauf" (#957).
|
||||
.route(
|
||||
"/api/v1/targets/{id}/scan-changes",
|
||||
get(handlers::scan_changes::target_scan_changes),
|
||||
)
|
||||
.route("/api/v1/targets/{id}/vex", get(handlers::vex::export_vex))
|
||||
.route("/api/v1/targets/{id}/csaf", get(handlers::vex::export_csaf))
|
||||
.route("/api/v1/targets/{id}/enisa", get(handlers::vex::list_enisa))
|
||||
.route("/api/v1/cves/{id}/enisa", get(handlers::vex::export_enisa))
|
||||
.route("/api/v1/cves/{id}/vex", patch(handlers::vex::set_cve_vex))
|
||||
// The open CVE alerts grouped by component, one decision per group (#949).
|
||||
.route(
|
||||
"/api/v1/targets/{id}/cve-groups",
|
||||
get(handlers::vex::list_cve_groups),
|
||||
)
|
||||
.route(
|
||||
"/api/v1/targets/{id}/cve-groups/vex",
|
||||
patch(handlers::vex::set_group_vex),
|
||||
)
|
||||
// The target's SBOM components per ecosystem (#957).
|
||||
.route(
|
||||
"/api/v1/targets/{id}/sbom-ecosystems",
|
||||
get(handlers::sbom_ecosystems::list_sbom_ecosystems),
|
||||
)
|
||||
.route(
|
||||
"/api/v1/targets/{id}/evidence-pack",
|
||||
get(handlers::evidence::evidence_pack),
|
||||
@@ -125,6 +175,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),
|
||||
|
||||
@@ -98,7 +98,9 @@ pub async fn triage_repo_findings(
|
||||
// to decide.
|
||||
TriageOutcome::NeedsReview => {
|
||||
finding.status = FindingStatus::NeedsReview;
|
||||
finding.triage_action = Some("control_not_confirmed".to_string());
|
||||
finding.triage_action = Some(
|
||||
compliance_core::models::finding::TRIAGE_CONTROL_NOT_CONFIRMED.to_string(),
|
||||
);
|
||||
finding.triage_rationale.get_or_insert_with(|| {
|
||||
"The control check did not confirm the CRA requirements this \
|
||||
finding maps to. Please review whether it is a real issue."
|
||||
|
||||
@@ -116,8 +116,8 @@ pub const SURFACES: &[Surface] = &[
|
||||
|
||||
/// Source file extensions worth reading (skip binaries/assets/lockfiles).
|
||||
const CODE_EXTS: &[&str] = &[
|
||||
"py", "js", "ts", "tsx", "jsx", "go", "java", "rb", "php", "rs", "cs", "kt", "c", "h", "cc",
|
||||
"cpp", "hpp",
|
||||
"py", "js", "ts", "tsx", "jsx", "go", "java", "rb", "php", "rs", "cs", "vb", "kt", "c", "h",
|
||||
"cc", "cpp", "hpp",
|
||||
];
|
||||
/// Directories never worth walking.
|
||||
const SKIP_DIRS: &[&str] = &[
|
||||
|
||||
@@ -618,6 +618,19 @@ impl Database {
|
||||
)
|
||||
.await?;
|
||||
|
||||
// inbox_snoozes (#950): one per card key, and the resubmissions due
|
||||
self.inbox_snoozes()
|
||||
.create_index(
|
||||
IndexModel::builder()
|
||||
.keys(doc! { "key": 1 })
|
||||
.options(IndexOptions::builder().unique(true).build())
|
||||
.build(),
|
||||
)
|
||||
.await?;
|
||||
self.inbox_snoozes()
|
||||
.create_index(IndexModel::builder().keys(doc! { "until": 1 }).build())
|
||||
.await?;
|
||||
|
||||
tracing::info!("Database indexes ensured");
|
||||
Ok(())
|
||||
}
|
||||
@@ -785,6 +798,12 @@ impl Database {
|
||||
self.inner.collection("werkbank_jobs")
|
||||
}
|
||||
|
||||
/// The cards of the "Heute" inbox put off until a date (#950).
|
||||
pub fn inbox_snoozes(&self) -> Collection<compliance_core::models::inbox::InboxSnooze> {
|
||||
self.inner
|
||||
.collection(compliance_core::models::inbox::SNOOZES_COLLECTION)
|
||||
}
|
||||
|
||||
#[allow(dead_code)]
|
||||
pub fn raw_collection(&self, name: &str) -> Collection<mongodb::bson::Document> {
|
||||
self.inner.collection(name)
|
||||
|
||||
@@ -12,6 +12,9 @@ pub enum SourceAction {
|
||||
/// A push to the default branch: scan the target, creating it first if
|
||||
/// the `created` delivery was lost.
|
||||
Push(GiteaRepo),
|
||||
/// A person closed or reopened an issue (#953): carry it over to the
|
||||
/// finding or CVE the issue was opened for, if Prüfwerk opened it.
|
||||
Issue(IssueEvent),
|
||||
/// Nothing to do, and why.
|
||||
Ignore(&'static str),
|
||||
}
|
||||
@@ -21,11 +24,40 @@ impl SourceAction {
|
||||
pub fn repo(&self) -> Option<&GiteaRepo> {
|
||||
match self {
|
||||
Self::Created(repo) | Self::Deleted(repo) | Self::Push(repo) => Some(repo),
|
||||
Self::Issue(event) => Some(&event.repo),
|
||||
Self::Ignore(_) => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What happened to an issue.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum IssueChange {
|
||||
Closed,
|
||||
Reopened,
|
||||
}
|
||||
|
||||
/// An issue closed or reopened in a repository of the organisation.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct IssueEvent {
|
||||
pub repo: GiteaRepo,
|
||||
/// The issue number in the repository (`TrackerIssue::external_id`).
|
||||
pub number: i64,
|
||||
pub change: IssueChange,
|
||||
/// The login of the user who closed or reopened it.
|
||||
pub sender: String,
|
||||
}
|
||||
|
||||
/// Whether Prüfwerk itself caused an issue event: the sender is the issue's
|
||||
/// author. Prüfwerk opens its issues as the source's bot user and closes and
|
||||
/// reopens them as that user, so an author acting on their own issue is the
|
||||
/// bot. The bot token cannot read its own user (`read:user` is not among its
|
||||
/// scopes), so the author stands in for it. Gitea logins are
|
||||
/// case-insensitive.
|
||||
pub fn is_own_event(sender: &str, author: &str) -> bool {
|
||||
!sender.is_empty() && sender.eq_ignore_ascii_case(author)
|
||||
}
|
||||
|
||||
/// A branch deletion pushes this as the new head.
|
||||
const ZERO_SHA: &str = "0000000000000000000000000000000000000000";
|
||||
|
||||
@@ -33,19 +65,16 @@ const ZERO_SHA: &str = "0000000000000000000000000000000000000000";
|
||||
/// organisation. Repositories of any other owner are ignored, so a system
|
||||
/// webhook (which sees the whole instance) is safe to use.
|
||||
pub fn route_event(event: &str, payload: &serde_json::Value, org: &str) -> SourceAction {
|
||||
if !super::WEBHOOK_EVENTS.contains(&event) {
|
||||
return SourceAction::Ignore("event not handled");
|
||||
}
|
||||
let Some(repo) = payload
|
||||
.get("repository")
|
||||
.cloned()
|
||||
.and_then(|r| serde_json::from_value::<GiteaRepo>(r).ok())
|
||||
else {
|
||||
return match event {
|
||||
"repository" | "push" => SourceAction::Ignore("payload without a repository"),
|
||||
_ => SourceAction::Ignore("event not handled"),
|
||||
};
|
||||
return SourceAction::Ignore("payload without a repository");
|
||||
};
|
||||
if !matches!(event, "repository" | "push") {
|
||||
return SourceAction::Ignore("event not handled");
|
||||
}
|
||||
if !repo.in_org(org) {
|
||||
return SourceAction::Ignore("repository outside the configured organisation");
|
||||
}
|
||||
@@ -55,6 +84,7 @@ pub fn route_event(event: &str, payload: &serde_json::Value, org: &str) -> Sourc
|
||||
Some("deleted") => SourceAction::Deleted(repo),
|
||||
_ => SourceAction::Ignore("repository action not handled"),
|
||||
},
|
||||
"issues" => route_issue(payload, repo),
|
||||
_ => {
|
||||
let git_ref = payload.get("ref").and_then(|r| r.as_str()).unwrap_or("");
|
||||
let after = payload.get("after").and_then(|a| a.as_str()).unwrap_or("");
|
||||
@@ -69,6 +99,41 @@ pub fn route_event(event: &str, payload: &serde_json::Value, org: &str) -> Sourc
|
||||
}
|
||||
}
|
||||
|
||||
/// Route an `issues` delivery of `repo`: a close or reopen by someone other
|
||||
/// than Prüfwerk's bot user.
|
||||
fn route_issue(payload: &serde_json::Value, repo: GiteaRepo) -> SourceAction {
|
||||
let change = match payload.get("action").and_then(|a| a.as_str()) {
|
||||
Some("closed") => IssueChange::Closed,
|
||||
Some("reopened") => IssueChange::Reopened,
|
||||
_ => return SourceAction::Ignore("issue action not handled"),
|
||||
};
|
||||
let issue = payload.get("issue");
|
||||
let Some(number) = payload
|
||||
.get("number")
|
||||
.or_else(|| issue.and_then(|i| i.get("number")))
|
||||
.and_then(serde_json::Value::as_i64)
|
||||
else {
|
||||
return SourceAction::Ignore("issue without a number");
|
||||
};
|
||||
// `user.login` of the sender and of the issue's author.
|
||||
let login = |user: Option<&serde_json::Value>| {
|
||||
user.and_then(|u| u.get("login"))
|
||||
.and_then(|l| l.as_str())
|
||||
.unwrap_or_default()
|
||||
.to_string()
|
||||
};
|
||||
let sender = login(payload.get("sender"));
|
||||
if is_own_event(&sender, &login(issue.and_then(|i| i.get("user")))) {
|
||||
return SourceAction::Ignore("issue changed by Prüfwerk's bot user");
|
||||
}
|
||||
SourceAction::Issue(IssueEvent {
|
||||
repo,
|
||||
number,
|
||||
change,
|
||||
sender,
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[allow(clippy::expect_used, clippy::unwrap_used)]
|
||||
mod tests {
|
||||
@@ -161,7 +226,7 @@ mod tests {
|
||||
);
|
||||
assert_eq!(
|
||||
route_event("issues", &json!({}), "kunde"),
|
||||
SourceAction::Ignore("event not handled")
|
||||
SourceAction::Ignore("payload without a repository")
|
||||
);
|
||||
assert_eq!(
|
||||
route_event("push", &json!({ "ref": "refs/heads/main" }), "kunde"),
|
||||
@@ -172,4 +237,80 @@ mod tests {
|
||||
SourceAction::Ignore("event not handled")
|
||||
);
|
||||
}
|
||||
|
||||
fn issue_event(action: &str, sender: &str, author: &str) -> serde_json::Value {
|
||||
json!({
|
||||
"action": action, "number": 12,
|
||||
"issue": { "number": 12, "state": "closed", "user": { "login": author } },
|
||||
"sender": { "login": sender },
|
||||
"repository": repository("kunde"),
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_person_closing_or_reopening_an_issue_is_carried_over() {
|
||||
let closed = issue_event("closed", "dev-anna", "pruefwerk");
|
||||
match route_event("issues", &closed, "kunde") {
|
||||
SourceAction::Issue(e) => assert_eq!(
|
||||
(e.repo.id, e.number, e.change, e.sender.as_str()),
|
||||
(42, 12, IssueChange::Closed, "dev-anna")
|
||||
),
|
||||
other => panic!("{other:?}"),
|
||||
}
|
||||
let reopened = issue_event("reopened", "dev-anna", "pruefwerk");
|
||||
assert!(matches!(
|
||||
route_event("issues", &reopened, "kunde"),
|
||||
SourceAction::Issue(IssueEvent {
|
||||
change: IssueChange::Reopened,
|
||||
..
|
||||
})
|
||||
));
|
||||
// The number from the issue when the payload has none on top.
|
||||
let mut p = issue_event("closed", "dev-anna", "pruefwerk");
|
||||
p.as_object_mut().unwrap().remove("number");
|
||||
assert!(matches!(
|
||||
route_event("issues", &p, "kunde"),
|
||||
SourceAction::Issue(IssueEvent { number: 12, .. })
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pruefwerks_own_changes_are_ignored_so_nothing_loops() {
|
||||
// The bot closed or reopened the issue it opened.
|
||||
for action in ["closed", "reopened"] {
|
||||
let p = issue_event(action, "pruefwerk", "pruefwerk");
|
||||
assert_eq!(
|
||||
route_event("issues", &p, "kunde"),
|
||||
SourceAction::Ignore("issue changed by Prüfwerk's bot user")
|
||||
);
|
||||
}
|
||||
assert!(is_own_event("Pruefwerk", "pruefwerk"));
|
||||
assert!(!is_own_event("dev-anna", "pruefwerk"));
|
||||
// A payload without a sender is not taken for the bot's.
|
||||
assert!(!is_own_event("", ""));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn other_issue_events_are_ignored() {
|
||||
for action in ["opened", "edited", "label_updated", "assigned"] {
|
||||
let p = issue_event(action, "dev-anna", "pruefwerk");
|
||||
assert_eq!(
|
||||
route_event("issues", &p, "kunde"),
|
||||
SourceAction::Ignore("issue action not handled")
|
||||
);
|
||||
}
|
||||
let mut p = issue_event("closed", "dev-anna", "pruefwerk");
|
||||
p.as_object_mut().unwrap().remove("number");
|
||||
p["issue"].as_object_mut().unwrap().remove("number");
|
||||
assert_eq!(
|
||||
route_event("issues", &p, "kunde"),
|
||||
SourceAction::Ignore("issue without a number")
|
||||
);
|
||||
let mut p = issue_event("closed", "dev-anna", "pruefwerk");
|
||||
p["repository"] = repository("andere");
|
||||
assert_eq!(
|
||||
route_event("issues", &p, "kunde"),
|
||||
SourceAction::Ignore("repository outside the configured organisation")
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -34,6 +34,10 @@ use gitea::{GiteaRepo, RepoLister, SourceClient};
|
||||
pub const DEFAULT_HOST_PATTERN: &str = r"^[a-z0-9-]+\.code(-stage)?\.breakpilot\.com$";
|
||||
/// Minutes between syncs unless `GIT_SOURCE_SYNC_MINUTES` says otherwise.
|
||||
pub const DEFAULT_SYNC_MINUTES: u64 = 30;
|
||||
/// The Gitea events the organisation or system webhook must send: Prüfwerk
|
||||
/// cannot register or change the webhook itself (the bot has no
|
||||
/// administration rights), so the platform API names them for provisioning.
|
||||
pub const WEBHOOK_EVENTS: [&str; 3] = ["repository", "push", "issues"];
|
||||
/// The webhook path of a tenant's source, below the webhook server's origin.
|
||||
pub fn webhook_path(tenant_id: &str) -> String {
|
||||
format!("/webhook/{tenant_id}/gitea-source")
|
||||
@@ -454,6 +458,11 @@ pub enum Outcome {
|
||||
Ensured { target_id: String, scan: bool },
|
||||
/// The repository's target was archived (`false`: there was none).
|
||||
Archived(bool),
|
||||
/// An issue closed or reopened in Gitea was carried back (#953).
|
||||
Issue {
|
||||
target_id: String,
|
||||
detail: &'static str,
|
||||
},
|
||||
/// Nothing done.
|
||||
Ignored(&'static str),
|
||||
}
|
||||
@@ -495,6 +504,24 @@ pub async fn apply_action(
|
||||
scan: true,
|
||||
})
|
||||
}
|
||||
SourceAction::Issue(event) => {
|
||||
// Only the repository's existing target: an issue event never
|
||||
// creates one.
|
||||
let Some(target_id) = db
|
||||
.onboarded_targets()
|
||||
.find_one(repo_filter(&source.base_url, event.repo.id))
|
||||
.await?
|
||||
.and_then(|t| t.id)
|
||||
else {
|
||||
return Ok(Outcome::Ignored("repository has no target"));
|
||||
};
|
||||
let target_id = target_id.to_hex();
|
||||
let done = crate::pipeline::issue_backsync::apply(db, &target_id, &event).await?;
|
||||
Ok(Outcome::Issue {
|
||||
target_id,
|
||||
detail: done.detail(event.change),
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use std::collections::HashMap;
|
||||
use std::fmt;
|
||||
|
||||
use compliance_core::models::{Exploitation, Finding, FindingStatus, Severity};
|
||||
use compliance_core::models::{Exploitation, Finding, FindingStatus, ReviewReason, Severity};
|
||||
use serde::{Deserialize, Deserializer};
|
||||
use serde_json::Value;
|
||||
|
||||
@@ -72,7 +72,7 @@ const RESPONSE_SAMPLE_CHARS: usize = 500;
|
||||
|
||||
/// `triage_action` of a finding the LLM triage gave no verdict; the reason is
|
||||
/// in `triage_rationale`, which starts with `skipped: <reason>`.
|
||||
pub const SKIPPED_ACTION: &str = "skipped";
|
||||
pub const SKIPPED_ACTION: &str = compliance_core::models::finding::TRIAGE_SKIPPED;
|
||||
|
||||
/// The model the triage asks. A trait so tests can drive the triage with a
|
||||
/// fake model.
|
||||
@@ -823,12 +823,12 @@ fn drop_trailing_comma(json: &mut String) {
|
||||
/// A dismissed or low-confidence finding is kept as
|
||||
/// [`FindingStatus::NeedsReview`], never deleted: the model's rationale goes
|
||||
/// with it, and a person decides.
|
||||
///
|
||||
/// Which of the two it was is read back from the stored verdict
|
||||
/// ([`Finding::review_reason`]), so the decision lives in one place
|
||||
/// ([`ReviewReason::of_verdict`]).
|
||||
fn apply_action(finding: &mut Finding, action: &str, adjusted_confidence: f64) -> Outcome {
|
||||
match action {
|
||||
"dismiss" => {
|
||||
finding.status = FindingStatus::NeedsReview;
|
||||
Outcome::Dismissed
|
||||
}
|
||||
"downgrade" => {
|
||||
finding.severity = downgrade_severity(&finding.severity);
|
||||
finding.status = FindingStatus::Triaged;
|
||||
@@ -839,22 +839,24 @@ fn apply_action(finding: &mut Finding, action: &str, adjusted_confidence: f64) -
|
||||
finding.status = FindingStatus::Triaged;
|
||||
Outcome::Upgraded
|
||||
}
|
||||
// "confirm" or unknown: kept as reported when the model is confident.
|
||||
_ if adjusted_confidence >= CONFIDENCE_THRESHOLD => {
|
||||
finding.status = FindingStatus::Triaged;
|
||||
Outcome::Confirmed
|
||||
}
|
||||
_ => {
|
||||
finding.status = FindingStatus::NeedsReview;
|
||||
Outcome::LowConfidence
|
||||
}
|
||||
// "dismiss", "confirm" or unknown: triaged when the model is sure it
|
||||
// is real, else left to a person.
|
||||
_ => match ReviewReason::of_verdict(action, adjusted_confidence) {
|
||||
Some(reason) => {
|
||||
finding.status = FindingStatus::NeedsReview;
|
||||
match reason {
|
||||
ReviewReason::LikelyFalseAlarm => Outcome::Dismissed,
|
||||
ReviewReason::Unsure => Outcome::LowConfidence,
|
||||
}
|
||||
}
|
||||
None => {
|
||||
finding.status = FindingStatus::Triaged;
|
||||
Outcome::Confirmed
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// Least confidence (after [`adjust_confidence`]) at which a confirmed
|
||||
/// finding counts as triaged; below it the finding needs review.
|
||||
const CONFIDENCE_THRESHOLD: f64 = 3.0;
|
||||
|
||||
/// Read ~50 lines of surrounding code from the file at the finding's location
|
||||
fn read_surrounding_context(finding: &Finding) -> Option<String> {
|
||||
let file_path = finding.file_path.as_deref()?;
|
||||
@@ -1104,6 +1106,51 @@ mod tests {
|
||||
assert_eq!(unsure.status, FindingStatus::NeedsReview);
|
||||
}
|
||||
|
||||
/// A verdict of the model on finding 1.
|
||||
fn model_verdict(action: &str, confidence: f64) -> TriageResult {
|
||||
TriageResult {
|
||||
id: Some("1".into()),
|
||||
action: action.into(),
|
||||
confidence,
|
||||
rationale: "why".into(),
|
||||
remediation: None,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_finding_kept_for_review_says_why() {
|
||||
let mut dismissed = finding();
|
||||
assert_eq!(
|
||||
apply_verdict(&mut dismissed, &model_verdict("dismiss", 9.0)),
|
||||
Outcome::Dismissed
|
||||
);
|
||||
assert_eq!(
|
||||
dismissed.review_reason(),
|
||||
Some(ReviewReason::LikelyFalseAlarm)
|
||||
);
|
||||
assert_eq!(dismissed.triage_rationale.as_deref(), Some("why"));
|
||||
|
||||
let mut unsure = finding();
|
||||
assert_eq!(
|
||||
apply_verdict(&mut unsure, &model_verdict("confirm", 2.0)),
|
||||
Outcome::LowConfidence
|
||||
);
|
||||
assert_eq!(unsure.review_reason(), Some(ReviewReason::Unsure));
|
||||
|
||||
// Test code halves the confidence: a 5 there is unsure.
|
||||
let mut in_tests = finding();
|
||||
in_tests.file_path = Some("src/tests/buffer.c".into());
|
||||
assert_eq!(
|
||||
apply_verdict(&mut in_tests, &model_verdict("confirm", 5.0)),
|
||||
Outcome::LowConfidence
|
||||
);
|
||||
assert_eq!(in_tests.review_reason(), Some(ReviewReason::Unsure));
|
||||
|
||||
let mut confirmed = finding();
|
||||
apply_verdict(&mut confirmed, &model_verdict("confirm", 7.0));
|
||||
assert_eq!(confirmed.review_reason(), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn confirmed_and_rerated_findings_pass() {
|
||||
let mut f = finding();
|
||||
|
||||
@@ -0,0 +1,178 @@
|
||||
//! Recording what a scan changes in the stored SBOM (#974): before a stage
|
||||
//! replaces its part of a target's SBOM, the entries it is about to replace
|
||||
//! are compared with the new ones ([`compliance_core::component_changes`])
|
||||
//! and the changes are added to the scan run.
|
||||
//!
|
||||
//! Each stage owns its part (the code SBOM, the CODESYS libraries, the
|
||||
//! firmware components) and records only that part's changes, so the run
|
||||
//! adds up the changes of all of them. Best effort: a failure is logged and
|
||||
//! the scan goes on, with the run's changes incomplete.
|
||||
|
||||
use futures_util::TryStreamExt;
|
||||
use mongodb::bson::{doc, oid::ObjectId, to_bson, Document};
|
||||
|
||||
use compliance_core::component_changes::{diff, MAX_CHANGES};
|
||||
use compliance_core::models::SbomEntry;
|
||||
|
||||
use crate::database::Database;
|
||||
use crate::error::AgentError;
|
||||
|
||||
/// Add to run `scan_run_id` the changes that replacing target `repo_id`'s
|
||||
/// stored entries matching `scope` with `entries` makes. The run's changes
|
||||
/// start empty, so a run whose stages changed nothing says so.
|
||||
///
|
||||
/// # Arguments
|
||||
///
|
||||
/// * `db` - the tenant database
|
||||
/// * `scan_run_id` - the run (hex id)
|
||||
/// * `repo_id` - the target
|
||||
/// * `scope` - the stage's part of the SBOM, as a filter on the entries
|
||||
/// * `entries` - what the stage stores instead
|
||||
pub(crate) async fn record(
|
||||
db: &Database,
|
||||
scan_run_id: &str,
|
||||
repo_id: &str,
|
||||
scope: Document,
|
||||
entries: &[SbomEntry],
|
||||
) {
|
||||
if let Err(e) = try_record(db, scan_run_id, repo_id, scope, entries).await {
|
||||
tracing::warn!(repo_id, scan_run_id, "component changes not recorded: {e}");
|
||||
}
|
||||
}
|
||||
|
||||
async fn try_record(
|
||||
db: &Database,
|
||||
scan_run_id: &str,
|
||||
repo_id: &str,
|
||||
scope: Document,
|
||||
entries: &[SbomEntry],
|
||||
) -> Result<(), AgentError> {
|
||||
let run = ObjectId::parse_str(scan_run_id).map_err(|e| AgentError::Other(e.to_string()))?;
|
||||
let mut filter = doc! { "repo_id": repo_id };
|
||||
filter.extend(scope);
|
||||
let stored: Vec<Document> = db
|
||||
.sbom_entries()
|
||||
.clone_with_type::<Document>()
|
||||
.find(filter)
|
||||
.projection(doc! { "package_manager": 1, "name": 1, "version": 1, "_id": 0 })
|
||||
.await?
|
||||
.try_collect()
|
||||
.await?;
|
||||
let field = |d: &Document, key: &str| d.get_str(key).unwrap_or_default().to_string();
|
||||
let before: Vec<(String, String, String)> = stored
|
||||
.iter()
|
||||
.map(|d| {
|
||||
(
|
||||
field(d, "package_manager"),
|
||||
field(d, "name"),
|
||||
field(d, "version"),
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
let before: Vec<(&str, &str, &str)> = before
|
||||
.iter()
|
||||
.map(|(m, n, v)| (m.as_str(), n.as_str(), v.as_str()))
|
||||
.collect();
|
||||
let after: Vec<(&str, &str, &str)> = entries
|
||||
.iter()
|
||||
.map(|e| {
|
||||
(
|
||||
e.package_manager.as_str(),
|
||||
e.name.as_str(),
|
||||
e.version.as_str(),
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
let changes = to_bson(&diff(&before, &after)).map_err(|e| AgentError::Other(e.to_string()))?;
|
||||
let max = i64::try_from(MAX_CHANGES).unwrap_or(i64::MAX);
|
||||
// One pipeline update: the run's list so far (none yet: empty) and this
|
||||
// stage's changes, at most the cap.
|
||||
db.scan_runs()
|
||||
.update_one(
|
||||
doc! { "_id": run },
|
||||
vec![doc! { "$set": { "component_changes": { "$slice": [
|
||||
{ "$concatArrays": [{ "$ifNull": ["$component_changes", []] }, changes] },
|
||||
max,
|
||||
] } } }],
|
||||
)
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[allow(clippy::expect_used, clippy::unwrap_used)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use compliance_core::component_changes::ComponentChangeKind;
|
||||
use compliance_core::models::{ScanRun, ScanTrigger};
|
||||
|
||||
fn entry(manager: &str, name: &str, version: &str) -> SbomEntry {
|
||||
SbomEntry::new("t1".into(), name.into(), version.into(), manager.into())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn each_stage_adds_the_changes_of_its_own_part() {
|
||||
let uri = std::env::var("TEST_MONGODB_URI")
|
||||
.unwrap_or_else(|_| "mongodb://root:example@localhost:27017/?authSource=admin".into());
|
||||
let prefix = format!("cchg_{}", &uuid::Uuid::new_v4().simple().to_string()[..10]);
|
||||
let Ok(pool) = crate::database::DatabasePool::connect(&uri, &prefix).await else {
|
||||
eprintln!("SKIP component_changes: no MongoDB reachable at {uri}");
|
||||
return;
|
||||
};
|
||||
let db = pool.for_tenant_id("component-changes").await.unwrap();
|
||||
// Arrange: a stored SBOM with a code and a firmware part.
|
||||
let stored = [
|
||||
entry("npm", "lodash", "4.17.20"),
|
||||
entry("npm", "left-pad", "1.3.0"),
|
||||
entry("firmware", "busybox", "1.36.0"),
|
||||
];
|
||||
db.sbom_entries().insert_many(&stored).await.unwrap();
|
||||
let run_id = db
|
||||
.scan_runs()
|
||||
.insert_one(ScanRun::new("t1".into(), ScanTrigger::Manual))
|
||||
.await
|
||||
.unwrap()
|
||||
.inserted_id
|
||||
.as_object_id()
|
||||
.unwrap()
|
||||
.to_hex();
|
||||
|
||||
// Act: the code stage replaces its part; the firmware stage keeps
|
||||
// its own unchanged.
|
||||
record(
|
||||
&db,
|
||||
&run_id,
|
||||
"t1",
|
||||
doc! { "package_manager": { "$nin": ["firmware"] } },
|
||||
&[entry("npm", "lodash", "4.17.21")],
|
||||
)
|
||||
.await;
|
||||
record(
|
||||
&db,
|
||||
&run_id,
|
||||
"t1",
|
||||
doc! { "package_manager": { "$in": ["firmware"] } },
|
||||
&[entry("firmware", "busybox", "1.36.0")],
|
||||
)
|
||||
.await;
|
||||
|
||||
// Assert
|
||||
let run = db
|
||||
.scan_runs()
|
||||
.find_one(doc! { "_id": ObjectId::parse_str(&run_id).unwrap() })
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
let changes = run.component_changes.expect("recorded");
|
||||
let read: Vec<(ComponentChangeKind, &str)> =
|
||||
changes.iter().map(|c| (c.kind, c.name.as_str())).collect();
|
||||
assert_eq!(
|
||||
read,
|
||||
[
|
||||
(ComponentChangeKind::Removed, "left-pad"),
|
||||
(ComponentChangeKind::Updated, "lodash")
|
||||
]
|
||||
);
|
||||
pool.drop_tenant("component-changes").await.ok();
|
||||
}
|
||||
}
|
||||
@@ -7,6 +7,12 @@
|
||||
//! updated or removed), the issue is closed with a comment; when it comes back,
|
||||
//! it is reopened.
|
||||
//!
|
||||
//! An issue a person closed in Gitea (#953) stays closed while the scan still
|
||||
//! finds its CVE: closing it was that person's call, and no VEX statement is
|
||||
//! made from it (one needs a justification). Once a complete scan no longer
|
||||
//! finds the CVE, that close is forgotten, so a CVE that comes back reopens
|
||||
//! the issue as usual.
|
||||
//!
|
||||
//! A CVE a VEX statement settles (`not_affected` or `fixed`, by a person, the
|
||||
//! scan or an imported VEX document) gets no issue. Its open issue is closed
|
||||
//! with a comment naming the status and the reason when `ISSUE_AUTOCLOSE` is
|
||||
@@ -24,6 +30,7 @@ use std::collections::{BTreeMap, HashMap};
|
||||
use mongodb::bson::doc;
|
||||
|
||||
use compliance_core::config::IssueAutoclose;
|
||||
use compliance_core::models::issue::cve_issue_prefix;
|
||||
use compliance_core::models::notification::{parse_severity, NotificationSeverity};
|
||||
use compliance_core::models::{CveAlert, IssueStatus, TrackerIssue, VexAssessment, VexStatus};
|
||||
|
||||
@@ -95,7 +102,12 @@ pub(crate) struct CveIssueCounts {
|
||||
/// target, package and CVE, so another version of the same package does not
|
||||
/// open a second issue.
|
||||
fn issue_key(target_id: &str, alert: &CveAlert) -> String {
|
||||
format!("cve:{target_id}:{}:{}", alert.affected_package, alert.cve())
|
||||
format!(
|
||||
"{}{}:{}",
|
||||
cve_issue_prefix(target_id),
|
||||
alert.affected_package,
|
||||
alert.cve()
|
||||
)
|
||||
}
|
||||
|
||||
/// A severity as the `severity:` labels name it.
|
||||
@@ -163,7 +175,7 @@ pub(crate) async fn sync_cve_issues(
|
||||
alerts: &[CveAlert],
|
||||
complete: bool,
|
||||
) -> Result<CveIssueCounts, AgentError> {
|
||||
let prefix = format!("cve:{}:", target.target_id);
|
||||
let prefix = cve_issue_prefix(target.target_id);
|
||||
let mut existing: HashMap<String, TrackerIssue> = HashMap::new();
|
||||
let mut cursor = target
|
||||
.db
|
||||
@@ -189,7 +201,9 @@ pub(crate) async fn sync_cve_issues(
|
||||
.filter(|(_, a)| !a.is_resolved_by_vex() && issue_worthy(a, target.epss_percentile))
|
||||
{
|
||||
match existing.get(key) {
|
||||
Some(issue) if is_closed(&issue.status) => {
|
||||
// A person closed it in Gitea while the CVE is unchanged.
|
||||
Some(issue) if issue.closed_in_tracker.is_some() => {}
|
||||
Some(issue) if issue.status.is_closed() => {
|
||||
let comment = "**Prüfwerk:** Bei der Prüfung erneut gefunden, daher wieder geöffnet.\n\nFound again by the scan, so reopened.";
|
||||
if set_state(target, issue, comment, "open").await {
|
||||
record(target.db, issue, IssueStatus::Open).await?;
|
||||
@@ -210,7 +224,7 @@ pub(crate) async fn sync_cve_issues(
|
||||
.iter()
|
||||
.filter_map(|(key, alert)| {
|
||||
let vex = alert.vex.as_ref().filter(|_| alert.is_resolved_by_vex())?;
|
||||
let issue = existing.get(key).filter(|i| !is_closed(&i.status))?;
|
||||
let issue = existing.get(key).filter(|i| !i.status.is_closed())?;
|
||||
Some((issue, vex))
|
||||
})
|
||||
.collect();
|
||||
@@ -218,7 +232,14 @@ pub(crate) async fn sync_cve_issues(
|
||||
|
||||
if complete {
|
||||
for (key, issue) in &existing {
|
||||
if present.contains_key(key) || is_closed(&issue.status) {
|
||||
if present.contains_key(key) {
|
||||
continue;
|
||||
}
|
||||
if issue.status.is_closed() {
|
||||
// Gone now: if it comes back, it is found again.
|
||||
if issue.closed_in_tracker.is_some() {
|
||||
record(target.db, issue, IssueStatus::Closed).await?;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
let comment = "**Prüfwerk:** Die Prüfung findet diese Schwachstelle nicht mehr: Die Abhängigkeit wurde aktualisiert oder entfernt.\n\nThe scan no longer finds this vulnerability: the dependency was updated or removed.";
|
||||
@@ -311,11 +332,6 @@ fn vex_comment(vex: &VexAssessment) -> String {
|
||||
)
|
||||
}
|
||||
|
||||
/// Whether an issue is closed.
|
||||
fn is_closed(status: &IssueStatus) -> bool {
|
||||
matches!(status, IssueStatus::Closed | IssueStatus::Resolved)
|
||||
}
|
||||
|
||||
/// The Prüfwerk label ids of a Gitea repository, created where missing;
|
||||
/// `None` for other trackers or when Gitea refuses.
|
||||
async fn gitea_label_ids(target: &CveIssueTarget<'_>) -> Option<HashMap<String, i64>> {
|
||||
@@ -498,12 +514,10 @@ async fn record(
|
||||
let Some(id) = issue.id else {
|
||||
return Ok(());
|
||||
};
|
||||
let status = mongodb::bson::to_bson(&status).map_err(|e| AgentError::Other(e.to_string()))?;
|
||||
let update = crate::pipeline::issue_sync::issue_state_update(&status, None)
|
||||
.map_err(|e| AgentError::Other(e.to_string()))?;
|
||||
db.tracker_issues()
|
||||
.update_one(
|
||||
doc! { "_id": id },
|
||||
doc! { "$set": { "status": status, "updated_at": mongodb::bson::DateTime::now() } },
|
||||
)
|
||||
.update_one(doc! { "_id": id }, update)
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
@@ -784,7 +798,9 @@ mod tests {
|
||||
|
||||
// It comes back: reopened, not opened twice.
|
||||
assert_eq!(
|
||||
sync_cve_issues(&target, &[okhttp], true).await.unwrap(),
|
||||
sync_cve_issues(&target, std::slice::from_ref(&okhttp), true)
|
||||
.await
|
||||
.unwrap(),
|
||||
CveIssueCounts {
|
||||
reopened: 1,
|
||||
..Default::default()
|
||||
@@ -792,6 +808,46 @@ mod tests {
|
||||
);
|
||||
assert_eq!(calls.lock().unwrap().last().unwrap(), "state 100: \"open\"");
|
||||
|
||||
// A person closes it in Gitea (#953): the scan that still finds the
|
||||
// CVE leaves it closed and sends nothing.
|
||||
let key = format!("cve:target-1:okhttp:{}", okhttp.cve());
|
||||
db.tracker_issues()
|
||||
.update_one(
|
||||
doc! { "finding_id": &key },
|
||||
doc! { "$set": { "status": "closed", "closed_in_tracker": "dev-anna" } },
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let sent = calls.lock().unwrap().len();
|
||||
assert_eq!(
|
||||
sync_cve_issues(&target, std::slice::from_ref(&okhttp), true)
|
||||
.await
|
||||
.unwrap(),
|
||||
CveIssueCounts::default()
|
||||
);
|
||||
assert_eq!(calls.lock().unwrap().len(), sent);
|
||||
|
||||
// Updated away, the close is forgotten; back again, it reopens.
|
||||
sync_cve_issues(&target, &[], true).await.unwrap();
|
||||
let stored = db
|
||||
.tracker_issues()
|
||||
.find_one(doc! { "finding_id": &key })
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
(stored.status, stored.closed_in_tracker),
|
||||
(IssueStatus::Closed, None)
|
||||
);
|
||||
assert_eq!(calls.lock().unwrap().len(), sent, "already closed");
|
||||
assert_eq!(
|
||||
sync_cve_issues(&target, &[okhttp], true)
|
||||
.await
|
||||
.unwrap()
|
||||
.reopened,
|
||||
1
|
||||
);
|
||||
|
||||
pool.drop_tenant("cve-issues").await.ok();
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,472 @@
|
||||
//! A person closing or reopening a Prüfwerk issue in Gitea, carried back to
|
||||
//! the finding (#953).
|
||||
//!
|
||||
//! * Closed: an undecided finding becomes resolved, recorded as "closed in the
|
||||
//! ticket" with the Gitea user's login. The next scan confirms it (not found:
|
||||
//! it stays resolved) or reopens finding and issue as for any resolved
|
||||
//! finding found again. A finding a person had already decided keeps that
|
||||
//! decision; only the issue's state is recorded.
|
||||
//! * Reopened: a decided finding becomes undecided again (`open`).
|
||||
//! * CVE issues: only the issue's state and who closed it are recorded. No
|
||||
//! VEX statement is set, since one needs a justification; the scan leaves
|
||||
//! the issue closed while the CVE is still there
|
||||
//! ([`crate::pipeline::cve_issues`]).
|
||||
//!
|
||||
//! Nothing here calls the tracker: the issue already is in the state the
|
||||
//! event (or the poll, [`crate::pipeline::issue_poll`]) reports, and the issue record says so, so the status sync
|
||||
//! ([`crate::pipeline::issue_sync`]) has nothing to carry over either.
|
||||
|
||||
use futures_util::TryStreamExt;
|
||||
use mongodb::bson::{doc, oid::ObjectId, to_bson, Bson, Document};
|
||||
|
||||
use compliance_core::models::{
|
||||
FindingStatus, IssueStatus, StatusChange, TrackerChangeKind, TrackerIssue, TrackerType,
|
||||
};
|
||||
|
||||
use crate::database::Database;
|
||||
use crate::error::AgentError;
|
||||
use crate::git_source::events::{IssueChange, IssueEvent};
|
||||
use crate::pipeline::issue_creation::ISSUE_STATUSES;
|
||||
use crate::pipeline::issue_sync::issue_state_update;
|
||||
|
||||
/// What carrying an issue event back did, for the delivery record.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub(crate) enum BackSynced {
|
||||
/// The issue is not one Prüfwerk opened in this repository.
|
||||
NotOurs,
|
||||
/// The finding's status changed.
|
||||
Finding,
|
||||
/// Only the issue's state was recorded: the finding already had a
|
||||
/// matching status (a person had decided it, or it was undecided).
|
||||
IssueOnly,
|
||||
/// A CVE issue's state was recorded.
|
||||
Cve,
|
||||
}
|
||||
|
||||
impl BackSynced {
|
||||
/// The delivery record's detail for this result of `change`.
|
||||
pub(crate) fn detail(self, change: IssueChange) -> &'static str {
|
||||
match (self, change) {
|
||||
(Self::NotOurs, _) => "issue not opened by Prüfwerk",
|
||||
(Self::Finding, IssueChange::Closed) => "finding resolved: issue closed in Gitea",
|
||||
(Self::Finding, IssueChange::Reopened) => "finding reopened: issue reopened in Gitea",
|
||||
(Self::IssueOnly, _) => "issue state recorded; the finding's status already matched",
|
||||
(Self::Cve, _) => "CVE issue state recorded",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The finding statuses `change` moves a finding away from: the undecided
|
||||
/// ones ([`ISSUE_STATUSES`]) for a close, every other for a reopen.
|
||||
fn statuses_changed_by(change: IssueChange) -> Document {
|
||||
let undecided: Vec<String> = ISSUE_STATUSES.iter().map(ToString::to_string).collect();
|
||||
match change {
|
||||
IssueChange::Closed => doc! { "$in": undecided },
|
||||
IssueChange::Reopened => doc! { "$nin": undecided },
|
||||
}
|
||||
}
|
||||
|
||||
/// The status a finding moves to and how its history records `change`.
|
||||
fn new_status(change: IssueChange) -> (FindingStatus, TrackerChangeKind) {
|
||||
match change {
|
||||
IssueChange::Closed => (FindingStatus::Resolved, TrackerChangeKind::ClosedInTracker),
|
||||
IssueChange::Reopened => (FindingStatus::Open, TrackerChangeKind::ReopenedInTracker),
|
||||
}
|
||||
}
|
||||
|
||||
/// Carry `event` back for the managed target `target_id`.
|
||||
///
|
||||
/// # Arguments
|
||||
///
|
||||
/// * `db` - the tenant database
|
||||
/// * `target_id` - the target of the event's repository
|
||||
/// * `event` - the close or reopen, by someone other than Prüfwerk's bot
|
||||
///
|
||||
/// # Returns
|
||||
///
|
||||
/// What was changed.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// A database error.
|
||||
pub(crate) async fn apply(
|
||||
db: &Database,
|
||||
target_id: &str,
|
||||
event: &IssueEvent,
|
||||
) -> Result<BackSynced, AgentError> {
|
||||
apply_change(db, target_id, event.number, event.change, &event.sender).await
|
||||
}
|
||||
|
||||
/// Carry a close or reopen of issue `number` back for target `target_id`,
|
||||
/// however it was learnt: a webhook delivery ([`apply`]) or the poll
|
||||
/// ([`crate::pipeline::issue_poll`]).
|
||||
///
|
||||
/// # Arguments
|
||||
///
|
||||
/// * `db` - the tenant database
|
||||
/// * `target_id` - the target of the issue's repository
|
||||
/// * `number` - the issue number in that repository
|
||||
/// * `change` - closed or reopened
|
||||
/// * `sender` - the login of the person who did it, not Prüfwerk's bot
|
||||
///
|
||||
/// # Returns
|
||||
///
|
||||
/// What was changed.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// A database error.
|
||||
pub(crate) async fn apply_change(
|
||||
db: &Database,
|
||||
target_id: &str,
|
||||
number: i64,
|
||||
change: IssueChange,
|
||||
sender: &str,
|
||||
) -> Result<BackSynced, AgentError> {
|
||||
let Some(issue) = find_issue(db, target_id, number).await? else {
|
||||
return Ok(BackSynced::NotOurs);
|
||||
};
|
||||
let (status, closed_by) = match change {
|
||||
IssueChange::Closed => (IssueStatus::Closed, Some(sender)),
|
||||
IssueChange::Reopened => (IssueStatus::Open, None),
|
||||
};
|
||||
// The issue first: once it reads closed, a status sync running meanwhile
|
||||
// finds nothing to close (and no comment to write) for the finding.
|
||||
if let Some(id) = issue.id {
|
||||
let update =
|
||||
issue_state_update(&status, closed_by).map_err(|e| AgentError::Other(e.to_string()))?;
|
||||
let mut filter = doc! { "_id": id };
|
||||
if closed_by.is_some() {
|
||||
// A record that already reads closed was closed by Prüfwerk (by
|
||||
// a bot user other than the issue's author, after a token
|
||||
// change): there is no person's close to keep.
|
||||
filter.insert("status", doc! { "$nin": ["closed", "resolved"] });
|
||||
}
|
||||
db.tracker_issues().update_one(filter, update).await?;
|
||||
}
|
||||
if issue.finding_id.starts_with("cve:") {
|
||||
return Ok(BackSynced::Cve);
|
||||
}
|
||||
let Ok(finding_id) = ObjectId::parse_str(&issue.finding_id) else {
|
||||
return Ok(BackSynced::IssueOnly);
|
||||
};
|
||||
let (new, kind) = new_status(change);
|
||||
let history = StatusChange::by_tracker(new.clone(), kind, sender);
|
||||
let to_bson_err = |e: mongodb::bson::ser::Error| AgentError::Other(e.to_string());
|
||||
// One conditional update, like the scan's status changes: a decision a
|
||||
// person makes meanwhile is not overwritten.
|
||||
let res = db
|
||||
.findings()
|
||||
.update_one(
|
||||
doc! { "_id": finding_id, "status": statuses_changed_by(change) },
|
||||
doc! {
|
||||
"$set": {
|
||||
"status": to_bson(&new).map_err(to_bson_err)?,
|
||||
"updated_at": mongodb::bson::DateTime::now(),
|
||||
},
|
||||
"$push": { "status_history": to_bson(&history).map_err(to_bson_err)? },
|
||||
},
|
||||
)
|
||||
.await?;
|
||||
Ok(if res.modified_count > 0 {
|
||||
BackSynced::Finding
|
||||
} else {
|
||||
BackSynced::IssueOnly
|
||||
})
|
||||
}
|
||||
|
||||
/// The issue Prüfwerk opened as number `number` in the repository of target
|
||||
/// `target_id`. Issue numbers repeat across repositories, so a record counts
|
||||
/// only if it belongs to the target: a CVE issue by its key, a finding issue
|
||||
/// by its finding.
|
||||
async fn find_issue(
|
||||
db: &Database,
|
||||
target_id: &str,
|
||||
number: i64,
|
||||
) -> Result<Option<TrackerIssue>, AgentError> {
|
||||
let tracker = to_bson(&TrackerType::Gitea).map_err(|e| AgentError::Other(e.to_string()))?;
|
||||
let candidates: Vec<TrackerIssue> = db
|
||||
.tracker_issues()
|
||||
.find(doc! { "external_id": number.to_string(), "tracker_type": tracker })
|
||||
.await?
|
||||
.try_collect()
|
||||
.await?;
|
||||
let cve_prefix = format!("cve:{target_id}:");
|
||||
if let Some(cve) = candidates
|
||||
.iter()
|
||||
.find(|i| i.finding_id.starts_with(&cve_prefix))
|
||||
{
|
||||
return Ok(Some(cve.clone()));
|
||||
}
|
||||
let ids: Vec<Bson> = candidates
|
||||
.iter()
|
||||
.filter_map(|i| ObjectId::parse_str(&i.finding_id).ok())
|
||||
.map(Bson::ObjectId)
|
||||
.collect();
|
||||
if ids.is_empty() {
|
||||
return Ok(None);
|
||||
}
|
||||
let Some(row) = db
|
||||
.findings()
|
||||
.clone_with_type::<Document>()
|
||||
.find_one(doc! { "_id": { "$in": ids }, "repo_id": target_id })
|
||||
.projection(doc! { "_id": 1 })
|
||||
.await?
|
||||
else {
|
||||
return Ok(None);
|
||||
};
|
||||
let Ok(id) = row.get_object_id("_id") else {
|
||||
return Ok(None);
|
||||
};
|
||||
let id = id.to_hex();
|
||||
Ok(candidates.into_iter().find(|i| i.finding_id == id))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[allow(clippy::expect_used, clippy::unwrap_used)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use compliance_core::models::{Finding, ScanType, Severity};
|
||||
|
||||
use crate::git_source::gitea::GiteaRepo;
|
||||
|
||||
#[test]
|
||||
fn a_close_resolves_undecided_findings_and_a_reopen_reopens_decided_ones() {
|
||||
assert_eq!(
|
||||
new_status(IssueChange::Closed),
|
||||
(FindingStatus::Resolved, TrackerChangeKind::ClosedInTracker)
|
||||
);
|
||||
assert_eq!(
|
||||
new_status(IssueChange::Reopened),
|
||||
(FindingStatus::Open, TrackerChangeKind::ReopenedInTracker)
|
||||
);
|
||||
let closed = statuses_changed_by(IssueChange::Closed);
|
||||
let moved: Vec<&str> = closed
|
||||
.get_array("$in")
|
||||
.unwrap()
|
||||
.iter()
|
||||
.filter_map(Bson::as_str)
|
||||
.collect();
|
||||
assert_eq!(moved, ["open", "triaged", "needs_review"]);
|
||||
assert!(statuses_changed_by(IssueChange::Reopened).contains_key("$nin"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_delivery_record_says_what_happened() {
|
||||
assert_eq!(
|
||||
BackSynced::Finding.detail(IssueChange::Closed),
|
||||
"finding resolved: issue closed in Gitea"
|
||||
);
|
||||
assert_eq!(
|
||||
BackSynced::NotOurs.detail(IssueChange::Reopened),
|
||||
"issue not opened by Prüfwerk"
|
||||
);
|
||||
}
|
||||
|
||||
fn event(change: IssueChange) -> IssueEvent {
|
||||
let repo: GiteaRepo = serde_json::from_value(serde_json::json!({
|
||||
"id": 7, "name": "fw", "full_name": "kunde/fw",
|
||||
}))
|
||||
.unwrap();
|
||||
IssueEvent {
|
||||
repo,
|
||||
number: 12,
|
||||
change,
|
||||
sender: "dev-anna".into(),
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn closing_and_reopening_in_gitea_moves_the_finding() {
|
||||
let uri = std::env::var("TEST_MONGODB_URI")
|
||||
.unwrap_or_else(|_| "mongodb://root:example@localhost:27017/?authSource=admin".into());
|
||||
let prefix = format!(
|
||||
"ibsync_{}",
|
||||
&uuid::Uuid::new_v4().simple().to_string()[..10]
|
||||
);
|
||||
let Ok(pool) = crate::database::DatabasePool::connect(&uri, &prefix).await else {
|
||||
eprintln!("SKIP issue_backsync: no MongoDB reachable at {uri}");
|
||||
return;
|
||||
};
|
||||
let db = pool.for_tenant_id("issue-backsync").await.unwrap();
|
||||
let target = ObjectId::new().to_hex();
|
||||
let other_target = ObjectId::new().to_hex();
|
||||
|
||||
// Arrange: issue #12 of this target's finding, and #12 of another
|
||||
// repository's finding (numbers repeat across repositories).
|
||||
let insert = |repo_id: String, status: FindingStatus| {
|
||||
let db = db.clone();
|
||||
async move {
|
||||
let mut f = Finding::new(
|
||||
repo_id,
|
||||
format!("fp-{}", ObjectId::new()),
|
||||
"semgrep".into(),
|
||||
ScanType::Sast,
|
||||
"strcpy".into(),
|
||||
"d".into(),
|
||||
Severity::High,
|
||||
);
|
||||
f.status = status;
|
||||
let id = db
|
||||
.findings()
|
||||
.insert_one(&f)
|
||||
.await
|
||||
.unwrap()
|
||||
.inserted_id
|
||||
.as_object_id()
|
||||
.unwrap();
|
||||
let issue = TrackerIssue::new(
|
||||
id.to_hex(),
|
||||
TrackerType::Gitea,
|
||||
"12".into(),
|
||||
"https://kunde.code.breakpilot.com/kunde/fw/issues/12".into(),
|
||||
"strcpy".into(),
|
||||
);
|
||||
db.tracker_issues().insert_one(&issue).await.unwrap();
|
||||
id
|
||||
}
|
||||
};
|
||||
let other = insert(other_target, FindingStatus::Open).await;
|
||||
let ours = insert(target.clone(), FindingStatus::NeedsReview).await;
|
||||
let finding = |id: ObjectId| {
|
||||
let db = db.clone();
|
||||
async move {
|
||||
db.findings()
|
||||
.find_one(doc! { "_id": id })
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap()
|
||||
}
|
||||
};
|
||||
let issue_of = |id: ObjectId| {
|
||||
let db = db.clone();
|
||||
async move {
|
||||
db.tracker_issues()
|
||||
.find_one(doc! { "finding_id": id.to_hex() })
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap()
|
||||
}
|
||||
};
|
||||
|
||||
// Act: closed in Gitea.
|
||||
let done = apply(&db, &target, &event(IssueChange::Closed))
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
// Assert: resolved, recorded as closed in the ticket by the user.
|
||||
assert_eq!(done, BackSynced::Finding);
|
||||
let f = finding(ours).await;
|
||||
assert_eq!(f.status, FindingStatus::Resolved);
|
||||
let last = f.status_history.last().unwrap();
|
||||
assert_eq!(last.tracker, Some(TrackerChangeKind::ClosedInTracker));
|
||||
assert_eq!(last.by_name.as_deref(), Some("dev-anna"));
|
||||
let issue = issue_of(ours).await;
|
||||
assert_eq!(issue.status, IssueStatus::Closed);
|
||||
assert_eq!(issue.closed_in_tracker.as_deref(), Some("dev-anna"));
|
||||
// The other repository's #12 is untouched.
|
||||
assert_eq!(finding(other).await.status, FindingStatus::Open);
|
||||
assert_eq!(issue_of(other).await.status, IssueStatus::Open);
|
||||
|
||||
// The same delivery again changes nothing more.
|
||||
let again = apply(&db, &target, &event(IssueChange::Closed))
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(again, BackSynced::IssueOnly);
|
||||
assert_eq!(finding(ours).await.status_history.len(), 1);
|
||||
|
||||
// Reopened in Gitea: undecided again, the closer forgotten.
|
||||
let done = apply(&db, &target, &event(IssueChange::Reopened))
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(done, BackSynced::Finding);
|
||||
let f = finding(ours).await;
|
||||
assert_eq!(f.status, FindingStatus::Open);
|
||||
assert_eq!(
|
||||
f.status_history.last().unwrap().tracker,
|
||||
Some(TrackerChangeKind::ReopenedInTracker)
|
||||
);
|
||||
let issue = issue_of(ours).await;
|
||||
assert_eq!(issue.status, IssueStatus::Open);
|
||||
assert!(issue.closed_in_tracker.is_none());
|
||||
|
||||
// A decision a person made in Prüfwerk is kept on a close.
|
||||
db.findings()
|
||||
.update_one(
|
||||
doc! { "_id": ours },
|
||||
doc! { "$set": { "status": "accepted_risk" } },
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
db.tracker_issues()
|
||||
.update_one(
|
||||
doc! { "finding_id": ours.to_hex() },
|
||||
doc! { "$set": { "status": "open" } },
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let done = apply(&db, &target, &event(IssueChange::Closed))
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(done, BackSynced::IssueOnly);
|
||||
assert_eq!(finding(ours).await.status, FindingStatus::AcceptedRisk);
|
||||
assert_eq!(issue_of(ours).await.status, IssueStatus::Closed);
|
||||
|
||||
// An issue Prüfwerk did not open (no record) is not ours.
|
||||
let mut stranger = event(IssueChange::Closed);
|
||||
stranger.number = 99;
|
||||
assert_eq!(
|
||||
apply(&db, &target, &stranger).await.unwrap(),
|
||||
BackSynced::NotOurs
|
||||
);
|
||||
|
||||
// A CVE issue: only the record, with who closed it.
|
||||
let key = format!("cve:{target}:openssl:CVE-2024-0001");
|
||||
let mut cve = TrackerIssue::new(
|
||||
key.clone(),
|
||||
TrackerType::Gitea,
|
||||
"30".into(),
|
||||
"https://kunde.code.breakpilot.com/kunde/fw/issues/30".into(),
|
||||
"[CVE] openssl@3.0.0: CVE-2024-0001".into(),
|
||||
);
|
||||
cve.status = IssueStatus::Open;
|
||||
db.tracker_issues().insert_one(&cve).await.unwrap();
|
||||
let mut closed = event(IssueChange::Closed);
|
||||
closed.number = 30;
|
||||
assert_eq!(apply(&db, &target, &closed).await.unwrap(), BackSynced::Cve);
|
||||
let stored = db
|
||||
.tracker_issues()
|
||||
.find_one(doc! { "finding_id": &key })
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(stored.status, IssueStatus::Closed);
|
||||
assert_eq!(stored.closed_in_tracker.as_deref(), Some("dev-anna"));
|
||||
|
||||
// Prüfwerk closed it already (the event comes from a bot user other
|
||||
// than the issue's author, after a token change): no person's close
|
||||
// is recorded, so a CVE that comes back still reopens it.
|
||||
let key = format!("cve:{target}:zlib:CVE-2024-0002");
|
||||
let mut cve = TrackerIssue::new(
|
||||
key.clone(),
|
||||
TrackerType::Gitea,
|
||||
"31".into(),
|
||||
"https://kunde.code.breakpilot.com/kunde/fw/issues/31".into(),
|
||||
"[CVE] zlib@1.2.0: CVE-2024-0002".into(),
|
||||
);
|
||||
cve.status = IssueStatus::Closed;
|
||||
db.tracker_issues().insert_one(&cve).await.unwrap();
|
||||
closed.number = 31;
|
||||
closed.sender = "pruefwerk-neu".into();
|
||||
apply(&db, &target, &closed).await.unwrap();
|
||||
let stored = db
|
||||
.tracker_issues()
|
||||
.find_one(doc! { "finding_id": &key })
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert!(stored.closed_in_tracker.is_none());
|
||||
|
||||
pool.drop_tenant("issue-backsync").await.ok();
|
||||
}
|
||||
}
|
||||
@@ -298,6 +298,7 @@ mod tests {
|
||||
body: Some(format_issue_body(finding)),
|
||||
html_url: format!("https://gitea.invalid/o/r/issues/{number}"),
|
||||
state: "open".into(),
|
||||
user: None,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -511,9 +511,14 @@ impl IssueSink<'_> {
|
||||
finding: &Finding,
|
||||
title: &str,
|
||||
) -> Result<TrackerIssue, CoreError> {
|
||||
let finding_id = finding
|
||||
.id
|
||||
.as_ref()
|
||||
.map(|id| id.to_hex())
|
||||
.unwrap_or_default();
|
||||
let mut body = format_issue_body(finding);
|
||||
if self.managed {
|
||||
if let Some(link) = finding_link(&self.dashboard, self.repo_id) {
|
||||
if let Some(link) = finding_link(&self.dashboard, &finding_id) {
|
||||
body.push_str(&format!(
|
||||
"\n[Open in Prüfwerk / In Prüfwerk öffnen]({link})"
|
||||
));
|
||||
@@ -540,11 +545,7 @@ impl IssueSink<'_> {
|
||||
.await?
|
||||
}
|
||||
};
|
||||
issue.finding_id = finding
|
||||
.id
|
||||
.as_ref()
|
||||
.map(|id| id.to_hex())
|
||||
.unwrap_or_default();
|
||||
issue.finding_id = finding_id;
|
||||
self.record(finding, &issue).await;
|
||||
Ok(issue)
|
||||
}
|
||||
@@ -706,13 +707,18 @@ fn cra_requirements(control_refs: &[String]) -> Vec<String> {
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The finding list of a target in the Prüfwerk dashboard; `None` unless the
|
||||
/// dashboard's public origin is an https URL.
|
||||
fn finding_link(dashboard: &str, target_id: &str) -> Option<String> {
|
||||
/// A finding's page in the Prüfwerk dashboard (#947), where its status is
|
||||
/// set; a group (#464) has its own id and so its own page. `None` unless the
|
||||
/// dashboard's public origin is an https URL and the finding has an id.
|
||||
///
|
||||
/// # Arguments
|
||||
///
|
||||
/// * `dashboard` - the dashboard's public origin (`DASHBOARD_PUBLIC_URL`)
|
||||
/// * `finding_id` - the finding's id as hex, empty when it has none
|
||||
fn finding_link(dashboard: &str, finding_id: &str) -> Option<String> {
|
||||
let dashboard = dashboard.trim_end_matches('/');
|
||||
dashboard
|
||||
.starts_with("https://")
|
||||
.then(|| format!("{dashboard}/findings?target={target_id}"))
|
||||
(dashboard.starts_with("https://") && !finding_id.is_empty())
|
||||
.then(|| format!("{dashboard}/findings/{finding_id}"))
|
||||
}
|
||||
|
||||
/// The ids of `names` among the ensured labels; a name without an id is left
|
||||
@@ -813,6 +819,7 @@ mod tests {
|
||||
body: body.map(str::to_string),
|
||||
html_url: format!("https://gitea.invalid/o/r/issues/{number}"),
|
||||
state: "open".into(),
|
||||
user: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -924,13 +931,16 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn links_only_to_an_https_dashboard() {
|
||||
fn links_the_finding_page_of_an_https_dashboard() {
|
||||
let id = "6560a1b2c3d4e5f601234567";
|
||||
assert_eq!(
|
||||
finding_link("https://pruefwerk.breakpilot.com/", "t1").as_deref(),
|
||||
Some("https://pruefwerk.breakpilot.com/findings?target=t1")
|
||||
finding_link("https://pruefwerk.breakpilot.com/", id).as_deref(),
|
||||
Some("https://pruefwerk.breakpilot.com/findings/6560a1b2c3d4e5f601234567")
|
||||
);
|
||||
assert_eq!(finding_link("", "t1"), None);
|
||||
assert_eq!(finding_link("http://x", "t1"), None);
|
||||
assert_eq!(finding_link("", id), None);
|
||||
assert_eq!(finding_link("http://x", id), None);
|
||||
// a finding without an id has no page to link
|
||||
assert_eq!(finding_link("https://pruefwerk.breakpilot.com", ""), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -0,0 +1,455 @@
|
||||
//! Issues closed or reopened in Gitea, learnt by polling (#953).
|
||||
//!
|
||||
//! The back-sync ([`super::issue_backsync`]) first came from the managed git
|
||||
//! source's organisation webhook. Most targets have no such webhook: they are
|
||||
//! repositories with a Gitea issue tracker. So at every sync interval the poll
|
||||
//! lists the issues of each target that has Prüfwerk issues (one listing per
|
||||
//! repository, as a scan makes), compares their state with Prüfwerk's records
|
||||
//! and, for each that differs, reads from the issue's timeline who closed or
|
||||
//! reopened it. A person's change is carried back as a webhook delivery is;
|
||||
//! Prüfwerk's own (its bot user opened the issue) is left alone. Where a
|
||||
//! webhook delivered the change already, the records match and the poll has
|
||||
//! nothing to do.
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
use futures_util::TryStreamExt;
|
||||
use mongodb::bson::{doc, Bson};
|
||||
|
||||
use compliance_core::models::issue::cve_issue_prefix;
|
||||
use compliance_core::models::{OnboardedTarget, TrackerIssue, TrackerType};
|
||||
use compliance_core::{AgentConfig, NetGuard};
|
||||
|
||||
use crate::agent::ComplianceAgent;
|
||||
use crate::database::Database;
|
||||
use crate::error::AgentError;
|
||||
use crate::git_source::events::{is_own_event, IssueChange};
|
||||
use crate::pipeline::issue_backsync::{apply_change, BackSynced};
|
||||
use crate::pipeline::issue_creation::build_tracker;
|
||||
use crate::pipeline::repo_view::RepoView;
|
||||
use crate::pipeline::tracker_dispatch::TrackerDispatch;
|
||||
use crate::secrets::SecretBox;
|
||||
use crate::trackers::gitea::GiteaIssue;
|
||||
|
||||
/// What one poll of a tenant did: counts only, for the log.
|
||||
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
|
||||
pub(crate) struct PollSummary {
|
||||
/// Targets whose issues were listed.
|
||||
pub targets: u32,
|
||||
/// Findings resolved or reopened.
|
||||
pub findings: u32,
|
||||
/// Issues whose state was recorded without a finding change (a decision
|
||||
/// a person had made stays; a CVE issue).
|
||||
pub recorded: u32,
|
||||
/// Targets whose tracker could not be read.
|
||||
pub failed: u32,
|
||||
}
|
||||
|
||||
/// What the poll of one target needs, owned by the agent.
|
||||
#[derive(Clone, Copy)]
|
||||
struct PollContext<'a> {
|
||||
db: &'a Database,
|
||||
config: &'a AgentConfig,
|
||||
net_guard: NetGuard,
|
||||
secrets: &'a SecretBox,
|
||||
}
|
||||
|
||||
/// The issues of `listed` whose state differs from Prüfwerk's record of it
|
||||
/// (`records`: number to closed), with the change and the issue's author.
|
||||
/// Issues Prüfwerk has no record of are not its own and left out.
|
||||
fn changes<'a>(
|
||||
records: &HashMap<i64, bool>,
|
||||
listed: &'a [GiteaIssue],
|
||||
) -> Vec<(i64, IssueChange, &'a str)> {
|
||||
listed
|
||||
.iter()
|
||||
.filter_map(
|
||||
|issue| match (records.get(&issue.number)?, issue.is_closed()) {
|
||||
(false, true) => Some((issue.number, IssueChange::Closed, issue.author())),
|
||||
(true, false) => Some((issue.number, IssueChange::Reopened, issue.author())),
|
||||
(true, true) | (false, false) => None,
|
||||
},
|
||||
)
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Prüfwerk's Gitea issues of target `target_id`, by number: whether each
|
||||
/// is closed. A finding's issue is found through the finding (storing an
|
||||
/// issue sets the finding's `tracker_issue_url`), a CVE issue by its key.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// A database error.
|
||||
async fn records(db: &Database, target_id: &str) -> Result<HashMap<i64, bool>, AgentError> {
|
||||
let ticketed = db
|
||||
.findings()
|
||||
.distinct(
|
||||
"_id",
|
||||
doc! { "repo_id": target_id, "tracker_issue_url": { "$ne": Bson::Null } },
|
||||
)
|
||||
.await?;
|
||||
let finding_ids: Vec<String> = ticketed
|
||||
.iter()
|
||||
.filter_map(Bson::as_object_id)
|
||||
.map(|id| id.to_hex())
|
||||
.collect();
|
||||
let cve = format!("^{}", regex::escape(&cve_issue_prefix(target_id)));
|
||||
let issues: Vec<TrackerIssue> = db
|
||||
.tracker_issues()
|
||||
.find(doc! {
|
||||
"tracker_type": TrackerType::Gitea.to_string(),
|
||||
"$or": [
|
||||
{ "finding_id": { "$in": finding_ids } },
|
||||
{ "finding_id": { "$regex": cve } },
|
||||
],
|
||||
})
|
||||
.await?
|
||||
.try_collect()
|
||||
.await?;
|
||||
Ok(issues
|
||||
.iter()
|
||||
.filter_map(|i| Some((i.external_id.parse().ok()?, i.status.is_closed())))
|
||||
.collect())
|
||||
}
|
||||
|
||||
/// Poll the issues of `target` and carry a person's closes and reopens
|
||||
/// back. A target without a Gitea tracker or without Prüfwerk issues is
|
||||
/// skipped without asking Gitea anything.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// The records cannot be read, or Gitea cannot be listed or asked for a
|
||||
/// timeline: the next poll tries again.
|
||||
async fn poll_target(
|
||||
ctx: PollContext<'_>,
|
||||
target: &OnboardedTarget,
|
||||
summary: &mut PollSummary,
|
||||
) -> Result<(), AgentError> {
|
||||
let (Some(id), Some(code)) = (target.id.map(|id| id.to_hex()), target.code_artifact()) else {
|
||||
return Ok(());
|
||||
};
|
||||
let repo = RepoView::from_target(target, code, ctx.secrets);
|
||||
let Some(TrackerDispatch::Gitea(gitea)) = build_tracker(ctx.config, ctx.net_guard, &repo)
|
||||
else {
|
||||
return Ok(());
|
||||
};
|
||||
let (Some(owner), Some(name)) = (repo.tracker_owner.as_deref(), repo.tracker_repo.as_deref())
|
||||
else {
|
||||
return Ok(());
|
||||
};
|
||||
let records = records(ctx.db, &id).await?;
|
||||
if records.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
summary.targets += 1;
|
||||
let listed = gitea.list_issues(owner, name).await?;
|
||||
for (number, change, author) in changes(&records, &listed) {
|
||||
let closed = change == IssueChange::Closed;
|
||||
let Some(by) = gitea
|
||||
.last_state_change_by(owner, name, number, closed)
|
||||
.await?
|
||||
.filter(|by| !is_own_event(by, author))
|
||||
else {
|
||||
// Prüfwerk's own change whose record was not written, or a
|
||||
// timeline without the entry: nothing a person decided.
|
||||
continue;
|
||||
};
|
||||
match apply_change(ctx.db, &id, number, change, &by).await? {
|
||||
BackSynced::Finding => summary.findings += 1,
|
||||
BackSynced::IssueOnly | BackSynced::Cve => summary.recorded += 1,
|
||||
BackSynced::NotOurs => {}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Poll every active target of tenant `tenant_id`, one after the other so a
|
||||
/// small Gitea sees one listing at a time.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Automation is not allowed for the tenant (the same entitlement and
|
||||
/// ladder rules as the webhook), or its targets cannot be read. A target
|
||||
/// that fails is counted in [`PollSummary::failed`] and logged.
|
||||
pub(crate) async fn poll_tenant(
|
||||
agent: &ComplianceAgent,
|
||||
tenant_id: &str,
|
||||
) -> Result<PollSummary, AgentError> {
|
||||
crate::git_source::automation_allowed(agent, tenant_id)
|
||||
.await
|
||||
.map_err(AgentError::Other)?;
|
||||
let db = agent.db_pool.for_tenant_id(tenant_id).await?;
|
||||
let targets: Vec<OnboardedTarget> = db
|
||||
.onboarded_targets()
|
||||
.find(doc! { "archived_at": null })
|
||||
.await?
|
||||
.try_collect()
|
||||
.await?;
|
||||
let ctx = PollContext {
|
||||
db: &db,
|
||||
config: &agent.config,
|
||||
net_guard: agent.net_guard,
|
||||
secrets: &agent.secrets,
|
||||
};
|
||||
let mut summary = PollSummary::default();
|
||||
for target in &targets {
|
||||
if let Err(e) = poll_target(ctx, target, &mut summary).await {
|
||||
summary.failed += 1;
|
||||
let target_id = target.id.map(|id| id.to_hex()).unwrap_or_default();
|
||||
tracing::warn!(tenant_id, target_id, "issue poll failed: {e}");
|
||||
}
|
||||
}
|
||||
Ok(summary)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[allow(clippy::expect_used, clippy::unwrap_used)]
|
||||
mod tests {
|
||||
use axum::extract::{Path, Query};
|
||||
use axum::routing::get;
|
||||
use axum::{Json, Router};
|
||||
use compliance_core::models::{
|
||||
Artifact, Finding, FindingStatus, IssueStatus, IssueTrackerConfig, ScanType, Severity,
|
||||
TargetType, TrackerChangeKind,
|
||||
};
|
||||
use mongodb::bson::oid::ObjectId;
|
||||
|
||||
use super::*;
|
||||
|
||||
/// A fake Gitea: issue #12 closed by a person, #13 closed by the bot
|
||||
/// that opened it, #14 reopened by a person, #15 not Prüfwerk's. Every
|
||||
/// list ends with an empty page, as Gitea's do.
|
||||
async fn fake_gitea() -> String {
|
||||
fn page<T: Into<serde_json::Value>>(
|
||||
q: &HashMap<String, String>,
|
||||
items: T,
|
||||
) -> Json<serde_json::Value> {
|
||||
if q.get("page").map(String::as_str) == Some("1") {
|
||||
Json(items.into())
|
||||
} else {
|
||||
Json(serde_json::json!([]))
|
||||
}
|
||||
}
|
||||
async fn issues(
|
||||
Path((_o, _r)): Path<(String, String)>,
|
||||
Query(q): Query<HashMap<String, String>>,
|
||||
) -> Json<serde_json::Value> {
|
||||
let issue = |n: i64, state: &str| serde_json::json!({ "number": n, "title": "t", "state": state, "user": { "login": "pruefwerk-bot" } });
|
||||
page(
|
||||
&q,
|
||||
serde_json::json!([
|
||||
issue(12, "closed"),
|
||||
issue(13, "closed"),
|
||||
issue(14, "open"),
|
||||
issue(15, "closed")
|
||||
]),
|
||||
)
|
||||
}
|
||||
async fn timeline(
|
||||
Path((_o, _r, n)): Path<(String, String, i64)>,
|
||||
Query(q): Query<HashMap<String, String>>,
|
||||
) -> Json<serde_json::Value> {
|
||||
let event = |kind: &str, login: &str| serde_json::json!({ "type": kind, "user": { "login": login } });
|
||||
let events = match n {
|
||||
12 => serde_json::json!([
|
||||
event("comment", "pruefwerk-bot"),
|
||||
event("close", "dev-anna")
|
||||
]),
|
||||
13 => serde_json::json!([
|
||||
event("close", "dev-anna"),
|
||||
event("reopen", "dev-anna"),
|
||||
event("close", "Pruefwerk-Bot")
|
||||
]),
|
||||
14 => {
|
||||
serde_json::json!([event("close", "pruefwerk-bot"), event("reopen", "dev-ben")])
|
||||
}
|
||||
_ => serde_json::json!([event("close", "dev-anna")]),
|
||||
};
|
||||
page(&q, events)
|
||||
}
|
||||
let app = Router::new()
|
||||
.route("/api/v1/repos/{o}/{r}/issues", get(issues))
|
||||
.route("/api/v1/repos/{o}/{r}/issues/{n}/timeline", get(timeline));
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let addr = listener.local_addr().unwrap();
|
||||
tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
|
||||
format!("http://{addr}")
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_persons_close_or_reopen_in_gitea_is_carried_back_and_the_bots_is_not() {
|
||||
let uri = std::env::var("TEST_MONGODB_URI")
|
||||
.unwrap_or_else(|_| "mongodb://root:example@localhost:27017/?authSource=admin".into());
|
||||
let prefix = format!("ipoll_{}", &uuid::Uuid::new_v4().simple().to_string()[..10]);
|
||||
let Ok(pool) = crate::database::DatabasePool::connect(&uri, &prefix).await else {
|
||||
eprintln!("SKIP issue_poll: no MongoDB reachable at {uri}");
|
||||
return;
|
||||
};
|
||||
let db = pool.for_tenant_id("issue-poll").await.unwrap();
|
||||
let base = fake_gitea().await;
|
||||
|
||||
// Arrange: a target with a Gitea tracker, two open findings with
|
||||
// issues #12 and #13, and the CVE issue #14 (closed by Prüfwerk).
|
||||
let mut target = OnboardedTarget::new("fw".into(), TargetType::BackendService);
|
||||
target
|
||||
.artifacts
|
||||
.push(Artifact::git_repo(format!("{base}/kunde/fw.git"), "main"));
|
||||
target.scan_config.issue_tracker = Some(IssueTrackerConfig {
|
||||
tracker_type: Some(TrackerType::Gitea),
|
||||
owner: Some("kunde".into()),
|
||||
repo: Some("fw".into()),
|
||||
token: Some("bot-token".into()),
|
||||
});
|
||||
let target_id = db
|
||||
.onboarded_targets()
|
||||
.insert_one(&target)
|
||||
.await
|
||||
.unwrap()
|
||||
.inserted_id
|
||||
.as_object_id()
|
||||
.unwrap();
|
||||
target.id = Some(target_id);
|
||||
let target_hex = target_id.to_hex();
|
||||
let with_issue = |number: &str| {
|
||||
let db = db.clone();
|
||||
let target_hex = target_hex.clone();
|
||||
let base = base.clone();
|
||||
let number = number.to_string();
|
||||
async move {
|
||||
let url = format!("{base}/kunde/fw/issues/{number}");
|
||||
let mut f = Finding::new(
|
||||
target_hex,
|
||||
format!("fp-{number}"),
|
||||
"semgrep".into(),
|
||||
ScanType::Sast,
|
||||
"strcpy".into(),
|
||||
"d".into(),
|
||||
Severity::High,
|
||||
);
|
||||
f.tracker_issue_url = Some(url.clone());
|
||||
let id = db
|
||||
.findings()
|
||||
.insert_one(&f)
|
||||
.await
|
||||
.unwrap()
|
||||
.inserted_id
|
||||
.as_object_id()
|
||||
.unwrap();
|
||||
let issue = TrackerIssue::new(
|
||||
id.to_hex(),
|
||||
TrackerType::Gitea,
|
||||
number,
|
||||
url,
|
||||
"strcpy".into(),
|
||||
);
|
||||
db.tracker_issues().insert_one(&issue).await.unwrap();
|
||||
id
|
||||
}
|
||||
};
|
||||
let closed_by_anna = with_issue("12").await;
|
||||
let closed_by_bot = with_issue("13").await;
|
||||
let mut cve = TrackerIssue::new(
|
||||
format!("{}openssl:CVE-2026-1", cve_issue_prefix(&target_hex)),
|
||||
TrackerType::Gitea,
|
||||
"14".into(),
|
||||
format!("{base}/kunde/fw/issues/14"),
|
||||
"CVE-2026-1".into(),
|
||||
);
|
||||
cve.status = IssueStatus::Closed;
|
||||
db.tracker_issues().insert_one(&cve).await.unwrap();
|
||||
let ctx = PollContext {
|
||||
db: &db,
|
||||
config: &AgentConfig::default(),
|
||||
net_guard: NetGuard::allow_private(),
|
||||
secrets: &SecretBox::without_key(),
|
||||
};
|
||||
|
||||
// Act
|
||||
let mut summary = PollSummary::default();
|
||||
poll_target(ctx, &target, &mut summary).await.unwrap();
|
||||
|
||||
// Assert: Anna's close resolved her finding, the bot's left the
|
||||
// other alone, Ben's reopen of the CVE issue is recorded.
|
||||
assert_eq!(
|
||||
summary,
|
||||
PollSummary {
|
||||
targets: 1,
|
||||
findings: 1,
|
||||
recorded: 1,
|
||||
failed: 0
|
||||
}
|
||||
);
|
||||
let finding = |id: ObjectId| {
|
||||
let db = db.clone();
|
||||
async move {
|
||||
db.findings()
|
||||
.find_one(doc! { "_id": id })
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap()
|
||||
}
|
||||
};
|
||||
let resolved = finding(closed_by_anna).await;
|
||||
assert_eq!(resolved.status, FindingStatus::Resolved);
|
||||
let last = resolved.status_history.last().unwrap();
|
||||
assert_eq!(
|
||||
(last.tracker, last.by_name.as_deref()),
|
||||
(Some(TrackerChangeKind::ClosedInTracker), Some("dev-anna"))
|
||||
);
|
||||
assert_eq!(finding(closed_by_bot).await.status, FindingStatus::Open);
|
||||
let issue = |number: &str| {
|
||||
let db = db.clone();
|
||||
let number = number.to_string();
|
||||
async move {
|
||||
db.tracker_issues()
|
||||
.find_one(doc! { "external_id": number })
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap()
|
||||
}
|
||||
};
|
||||
let twelve = issue("12").await;
|
||||
assert_eq!(
|
||||
(twelve.status, twelve.closed_in_tracker.as_deref()),
|
||||
(IssueStatus::Closed, Some("dev-anna"))
|
||||
);
|
||||
assert_eq!(issue("13").await.status, IssueStatus::Open);
|
||||
assert_eq!(issue("14").await.status, IssueStatus::Open);
|
||||
|
||||
// A second poll finds the records matching (the bot's close aside,
|
||||
// which stays a person's to decide): nothing more changes.
|
||||
let mut again = PollSummary::default();
|
||||
poll_target(ctx, &target, &mut again).await.unwrap();
|
||||
assert_eq!((again.findings, again.recorded), (0, 0));
|
||||
|
||||
pool.drop_tenant("issue-poll").await.ok();
|
||||
}
|
||||
|
||||
fn listed(number: i64, state: &str, author: &str) -> GiteaIssue {
|
||||
serde_json::from_value(serde_json::json!({
|
||||
"number": number, "title": "t", "state": state,
|
||||
"user": { "login": author },
|
||||
}))
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_issues_whose_state_differs_from_the_record_are_changes() {
|
||||
let records: HashMap<i64, bool> = [(1, false), (2, true), (3, false), (4, true)].into();
|
||||
let issues = [
|
||||
listed(1, "closed", "bot"),
|
||||
listed(2, "open", "bot"),
|
||||
listed(3, "open", "bot"),
|
||||
listed(4, "closed", "bot"),
|
||||
// Not Prüfwerk's: no record.
|
||||
listed(5, "closed", "dev-anna"),
|
||||
];
|
||||
assert_eq!(
|
||||
changes(&records, &issues),
|
||||
[
|
||||
(1, IssueChange::Closed, "bot"),
|
||||
(2, IssueChange::Reopened, "bot")
|
||||
]
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -170,19 +170,40 @@ impl IssueSync {
|
||||
let Some(id) = issue.id else {
|
||||
return Ok(());
|
||||
};
|
||||
let status = mongodb::bson::to_bson(&status).map_err(|e| e.to_string())?;
|
||||
let update = issue_state_update(&status, None).map_err(|e| e.to_string())?;
|
||||
self.db
|
||||
.tracker_issues()
|
||||
.update_one(
|
||||
doc! { "_id": id },
|
||||
doc! { "$set": { "status": status, "updated_at": mongodb::bson::DateTime::now() } },
|
||||
)
|
||||
.update_one(doc! { "_id": id }, update)
|
||||
.await
|
||||
.map(drop)
|
||||
.map_err(|e| e.to_string())
|
||||
}
|
||||
}
|
||||
|
||||
/// The update that stores an issue's new `status`. `closed_by` is the
|
||||
/// tracker user who closed it there (#953); when Prüfwerk changes the state,
|
||||
/// or the issue is reopened, it is `None` and an earlier closer is cleared.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// The status cannot be written as BSON.
|
||||
pub(crate) fn issue_state_update(
|
||||
status: &IssueStatus,
|
||||
closed_by: Option<&str>,
|
||||
) -> Result<mongodb::bson::Document, mongodb::bson::ser::Error> {
|
||||
let mut set = doc! {
|
||||
"status": mongodb::bson::to_bson(status)?,
|
||||
"updated_at": mongodb::bson::DateTime::now(),
|
||||
};
|
||||
Ok(match closed_by {
|
||||
Some(login) => {
|
||||
set.insert("closed_in_tracker", login);
|
||||
doc! { "$set": set }
|
||||
}
|
||||
None => doc! { "$set": set, "$unset": { "closed_in_tracker": "" } },
|
||||
})
|
||||
}
|
||||
|
||||
/// The `risk:accepted` label id per target (`Finding::repo_id`), once
|
||||
/// resolved; `None` for a target whose repository has no such label.
|
||||
type RiskLabels = HashMap<String, Option<i64>>;
|
||||
@@ -492,6 +513,69 @@ mod tests {
|
||||
assert_eq!(tail, ["state 12: \"closed\"", "labels 12: [42]"]);
|
||||
}
|
||||
|
||||
// Reopened, then a person closes the issue in Gitea (#953): the
|
||||
// back-sync resolves the finding and records the issue closed, so the
|
||||
// sync neither comments nor closes it again.
|
||||
db.findings()
|
||||
.update_one(
|
||||
doc! { "_id": finding_id },
|
||||
doc! { "$set": { "status": "open" } },
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
sync.sync_one(finding_id, &mut RiskLabels::new())
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(issue_status().await, IssueStatus::Open);
|
||||
let event = crate::git_source::events::IssueEvent {
|
||||
repo: serde_json::from_value(serde_json::json!({
|
||||
"id": 7, "name": "fw", "full_name": "kunde/fw",
|
||||
}))
|
||||
.unwrap(),
|
||||
number: 12,
|
||||
change: crate::git_source::events::IssueChange::Closed,
|
||||
sender: "dev-anna".into(),
|
||||
};
|
||||
crate::pipeline::issue_backsync::apply(&db, &target_id.to_hex(), &event)
|
||||
.await
|
||||
.unwrap();
|
||||
let before = calls.lock().unwrap().len();
|
||||
sync.sync_one(finding_id, &mut RiskLabels::new())
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(calls.lock().unwrap().len(), before, "nothing sent to Gitea");
|
||||
assert_eq!(issue_status().await, IssueStatus::Closed);
|
||||
|
||||
// Found again by the next scan: reopened with the usual comment.
|
||||
db.findings()
|
||||
.update_one(
|
||||
doc! { "_id": finding_id },
|
||||
doc! {
|
||||
"$set": { "status": "open" },
|
||||
"$push": { "status_history": mongodb::bson::to_bson(&by_scan(
|
||||
FindingStatus::Open,
|
||||
ScanChangeKind::FoundAgain,
|
||||
)).unwrap() },
|
||||
},
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
sync.sync_one(finding_id, &mut RiskLabels::new())
|
||||
.await
|
||||
.unwrap();
|
||||
{
|
||||
let calls = calls.lock().unwrap();
|
||||
assert!(calls[before].contains("erneut gefunden"));
|
||||
assert_eq!(calls[before + 1], "state 12: \"open\"");
|
||||
}
|
||||
let reopened = db
|
||||
.tracker_issues()
|
||||
.find_one(doc! { "finding_id": finding_id.to_hex() })
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert!(reopened.closed_in_tracker.is_none());
|
||||
|
||||
pool.drop_tenant("issue-sync").await.ok();
|
||||
}
|
||||
|
||||
@@ -526,6 +610,20 @@ mod tests {
|
||||
StatusChange::by_scan(status, kind, "run-1")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_issue_state_keeps_who_closed_it_in_the_tracker_until_it_reopens() {
|
||||
let closed = issue_state_update(&IssueStatus::Closed, Some("dev-anna")).unwrap();
|
||||
let set = closed.get_document("$set").unwrap();
|
||||
assert_eq!(set.get_str("status").unwrap(), "closed");
|
||||
assert_eq!(set.get_str("closed_in_tracker").unwrap(), "dev-anna");
|
||||
assert!(!closed.contains_key("$unset"));
|
||||
let by_pruefwerk = issue_state_update(&IssueStatus::Open, None).unwrap();
|
||||
assert!(by_pruefwerk
|
||||
.get_document("$unset")
|
||||
.unwrap()
|
||||
.contains_key("closed_in_tracker"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn closing_statuses_close_and_open_ones_reopen() {
|
||||
assert_eq!(
|
||||
|
||||
@@ -5,6 +5,7 @@ pub mod change;
|
||||
pub mod clamav;
|
||||
pub mod clone_limit;
|
||||
pub mod code_review;
|
||||
pub(crate) mod component_changes;
|
||||
pub mod cppcheck;
|
||||
pub(crate) mod csaf_feed;
|
||||
pub(crate) mod csaf_match;
|
||||
@@ -26,8 +27,10 @@ pub mod gitleaks;
|
||||
pub(crate) mod graph_build;
|
||||
pub mod grouping;
|
||||
pub mod ios_config;
|
||||
pub(crate) mod issue_backsync;
|
||||
mod issue_catchup;
|
||||
pub(crate) mod issue_creation;
|
||||
pub(crate) mod issue_poll;
|
||||
pub(crate) mod issue_sync;
|
||||
pub mod languages;
|
||||
pub mod license_policy;
|
||||
|
||||
@@ -1088,15 +1088,23 @@ impl PipelineOrchestrator {
|
||||
// nothing, so dependencies removed from a repo used to stay in its SBOM
|
||||
// forever.
|
||||
if !sbom_entries.is_empty() {
|
||||
self.db
|
||||
.sbom_entries()
|
||||
.delete_many(doc! {
|
||||
"repo_id": &repo_id,
|
||||
"package_manager": {
|
||||
"$nin": crate::pipeline::firmware_sbom::FIRMWARE_MANAGERS.to_vec()
|
||||
},
|
||||
})
|
||||
.await?;
|
||||
let scope = doc! {
|
||||
"package_manager": {
|
||||
"$nin": crate::pipeline::firmware_sbom::FIRMWARE_MANAGERS.to_vec()
|
||||
},
|
||||
};
|
||||
// What this replaces, for the target's history (#974).
|
||||
crate::pipeline::component_changes::record(
|
||||
&self.db,
|
||||
scan_run_id,
|
||||
&repo_id,
|
||||
scope.clone(),
|
||||
&sbom_entries,
|
||||
)
|
||||
.await;
|
||||
let mut filter = doc! { "repo_id": &repo_id };
|
||||
filter.extend(scope);
|
||||
self.db.sbom_entries().delete_many(filter).await?;
|
||||
}
|
||||
|
||||
// Persist SBOM entries
|
||||
@@ -2170,6 +2178,14 @@ impl PipelineOrchestrator {
|
||||
if entries.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
crate::pipeline::component_changes::record(
|
||||
&self.db,
|
||||
scan_run_id,
|
||||
target_id,
|
||||
doc! { "package_manager": "codesys" },
|
||||
&entries,
|
||||
)
|
||||
.await;
|
||||
self.db
|
||||
.sbom_entries()
|
||||
.delete_many(doc! { "repo_id": target_id, "package_manager": "codesys" })
|
||||
@@ -2465,6 +2481,16 @@ impl PipelineOrchestrator {
|
||||
}
|
||||
};
|
||||
if !entries.is_empty() {
|
||||
crate::pipeline::component_changes::record(
|
||||
&self.db,
|
||||
scan_run_id,
|
||||
target_id,
|
||||
doc! { "package_manager": {
|
||||
"$in": crate::pipeline::firmware_sbom::FIRMWARE_MANAGERS.to_vec()
|
||||
} },
|
||||
&entries,
|
||||
)
|
||||
.await;
|
||||
// Only the firmware entries: a rescan with no new
|
||||
// commits skips the SBOM stage, so deleting everything
|
||||
// here wiped the Syft entries until the next commit.
|
||||
|
||||
@@ -126,6 +126,34 @@ pub async fn start_scheduler(agent: &ComplianceAgent) -> Result<(), AgentError>
|
||||
.await
|
||||
.map_err(|e| AgentError::Scheduler(format!("Failed to add git sync job: {e}")))?;
|
||||
|
||||
// Issues a person closed or reopened in Gitea (#953), for the targets no
|
||||
// webhook reports them for; at the managed git sync's interval.
|
||||
let poll_agent = agent.clone();
|
||||
let poll_job = Job::new_repeated_async(agent.git_source.sync_interval, move |_uuid, _lock| {
|
||||
let agent = poll_agent.clone();
|
||||
Box::pin(async move {
|
||||
for tenant_id in scheduler_tenants(&agent).await {
|
||||
match crate::pipeline::issue_poll::poll_tenant(&agent, &tenant_id).await {
|
||||
Ok(s) if s.targets > 0 => tracing::info!(
|
||||
tenant_id,
|
||||
targets = s.targets,
|
||||
findings = s.findings,
|
||||
recorded = s.recorded,
|
||||
failed = s.failed,
|
||||
"issue poll done"
|
||||
),
|
||||
Ok(_) => {}
|
||||
Err(e) => tracing::warn!(tenant_id, "issue poll skipped: {e}"),
|
||||
}
|
||||
}
|
||||
})
|
||||
})
|
||||
.map_err(|e| AgentError::Scheduler(format!("Failed to create issue poll job: {e}")))?;
|
||||
sched
|
||||
.add(poll_job)
|
||||
.await
|
||||
.map_err(|e| AgentError::Scheduler(format!("Failed to add issue poll job: {e}")))?;
|
||||
|
||||
sched
|
||||
.start()
|
||||
.await
|
||||
|
||||
@@ -176,6 +176,39 @@ impl GiteaTracker {
|
||||
.await
|
||||
}
|
||||
|
||||
/// The login of whoever last closed (`closed`) or reopened issue `number`,
|
||||
/// from its timeline; `None` if the timeline has no such entry. The issue
|
||||
/// itself does not say who closed it.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// [`CoreError::IssueTracker`] if the timeline cannot be read, or has more
|
||||
/// than `MAX_TIMELINE_PAGES` pages.
|
||||
pub async fn last_state_change_by(
|
||||
&self,
|
||||
owner: &str,
|
||||
repo: &str,
|
||||
number: i64,
|
||||
closed: bool,
|
||||
) -> Result<Option<String>, CoreError> {
|
||||
let kind = if closed { "close" } else { "reopen" };
|
||||
let events: Vec<GiteaTimelineEvent> = self
|
||||
.list_all(
|
||||
"issue timeline",
|
||||
&format!("/repos/{owner}/{repo}/issues/{number}/timeline"),
|
||||
MAX_TIMELINE_PAGES,
|
||||
)
|
||||
.await?;
|
||||
// Oldest first: the last matching entry is the current state's.
|
||||
Ok(events
|
||||
.into_iter()
|
||||
.rev()
|
||||
.find(|e| e.kind == kind)
|
||||
.and_then(|e| e.user)
|
||||
.map(|u| u.login)
|
||||
.filter(|login| !login.is_empty()))
|
||||
}
|
||||
|
||||
/// Make sure the repository has every label in `wanted`, creating the
|
||||
/// missing ones, and return the id of each by name. Needs write access to
|
||||
/// the repository's issues, nothing more.
|
||||
@@ -287,6 +320,25 @@ const LIST_PAGE_SIZE: usize = 50;
|
||||
const MAX_LABEL_PAGES: usize = 20;
|
||||
/// Upper bound on issue pages (10 000 issues).
|
||||
const MAX_ISSUE_PAGES: usize = 200;
|
||||
/// Upper bound on the timeline pages of one issue (1 000 entries).
|
||||
const MAX_TIMELINE_PAGES: usize = 20;
|
||||
|
||||
/// A Gitea user, by login.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, serde::Deserialize)]
|
||||
pub struct GiteaUser {
|
||||
#[serde(default)]
|
||||
pub login: String,
|
||||
}
|
||||
|
||||
/// An entry of an issue's timeline, with what a close or reopen needs:
|
||||
/// `type` is `close`, `reopen`, `comment`, ...
|
||||
#[derive(Debug, Clone, PartialEq, Eq, serde::Deserialize)]
|
||||
struct GiteaTimelineEvent {
|
||||
#[serde(rename = "type", default)]
|
||||
kind: String,
|
||||
#[serde(default)]
|
||||
user: Option<GiteaUser>,
|
||||
}
|
||||
|
||||
/// An issue as Gitea lists it, with what an issue is matched by.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, serde::Deserialize)]
|
||||
@@ -301,6 +353,21 @@ pub struct GiteaIssue {
|
||||
/// `open` or `closed`.
|
||||
#[serde(default)]
|
||||
pub state: String,
|
||||
/// Who opened it: Prüfwerk's issues are opened by its bot user.
|
||||
#[serde(default)]
|
||||
pub user: Option<GiteaUser>,
|
||||
}
|
||||
|
||||
impl GiteaIssue {
|
||||
/// The login of whoever opened the issue, empty if Gitea did not say.
|
||||
pub fn author(&self) -> &str {
|
||||
self.user.as_ref().map_or("", |u| u.login.as_str())
|
||||
}
|
||||
|
||||
/// Whether the issue is closed.
|
||||
pub fn is_closed(&self) -> bool {
|
||||
self.state == "closed"
|
||||
}
|
||||
}
|
||||
|
||||
/// A repository label as Gitea returns it.
|
||||
|
||||
@@ -6,7 +6,9 @@
|
||||
//! source is read through a handle that cannot conjure a tenant database.
|
||||
//!
|
||||
//! A verified delivery that asks for work is answered `202 Accepted` at once;
|
||||
//! the entitlement check, the target and the scan follow in the background,
|
||||
//! the entitlement check, the target and the scan (or, for an issue closed
|
||||
//! or reopened by a person, the finding's new status, #953) follow in the
|
||||
//! background,
|
||||
//! so a slow registry or Keycloak never runs into Gitea's delivery timeout.
|
||||
//! What became of it (handled, refused, failed) is recorded for the target
|
||||
//! page, since Gitea's delivery log only ever sees the `202`.
|
||||
@@ -199,6 +201,9 @@ fn delivery_of(event: &str, result: &Result<Outcome, NotHandled>) -> WebhookDeli
|
||||
Ok(Outcome::Archived(false)) => {
|
||||
(DeliveryResult::Handled, "no active target to archive", None)
|
||||
}
|
||||
Ok(Outcome::Issue { target_id, detail }) => {
|
||||
(DeliveryResult::Handled, *detail, Some(target_id.clone()))
|
||||
}
|
||||
Ok(Outcome::Ignored(why)) => (DeliveryResult::Handled, *why, None),
|
||||
Err(NotHandled::Refused(why)) => (DeliveryResult::Refused, why.as_str(), None),
|
||||
Err(NotHandled::Failed(why)) => (DeliveryResult::Failed, why.as_str(), None),
|
||||
@@ -257,6 +262,20 @@ mod tests {
|
||||
let d = delivery_of("repository", &Ok(ensured(false)));
|
||||
assert_eq!(d.detail, "target ready, nothing to scan yet");
|
||||
|
||||
let issue = Outcome::Issue {
|
||||
target_id: "t1".into(),
|
||||
detail: "finding resolved: issue closed in Gitea",
|
||||
};
|
||||
let d = delivery_of("issues", &Ok(issue));
|
||||
assert_eq!(
|
||||
(d.result, d.detail.as_str(), d.target_id.as_deref()),
|
||||
(
|
||||
DeliveryResult::Handled,
|
||||
"finding resolved: issue closed in Gitea",
|
||||
Some("t1")
|
||||
)
|
||||
);
|
||||
|
||||
let d = delivery_of("repository", &Ok(Outcome::Archived(true)));
|
||||
assert_eq!(
|
||||
(d.result, d.detail.as_str()),
|
||||
|
||||
@@ -483,6 +483,155 @@ async fn platform_api_webhook_and_sync() {
|
||||
h.pool.drop_tenant(TENANT).await.ok();
|
||||
}
|
||||
|
||||
/// An issue a person closes or reopens in Gitea moves its finding (#953);
|
||||
/// the same done by Prüfwerk's bot user is ignored, so nothing loops.
|
||||
#[tokio::test]
|
||||
async fn an_issue_closed_or_reopened_in_gitea_moves_its_finding() {
|
||||
use compliance_core::models::{
|
||||
Finding, FindingStatus, IssueStatus, ScanType, Severity, TrackerChangeKind, TrackerIssue,
|
||||
TrackerType,
|
||||
};
|
||||
|
||||
let Some(h) = start().await else { return };
|
||||
let (status, created) = h
|
||||
.put_source(serde_json::json!({
|
||||
"base_url": "https://kunde.code.breakpilot.com", "org": "kunde",
|
||||
"bot_token": "bot-pat", "enabled": false
|
||||
}))
|
||||
.await;
|
||||
assert_eq!(status, 200, "{created}");
|
||||
assert_eq!(
|
||||
created["webhook_events"],
|
||||
serde_json::json!(["repository", "push", "issues"])
|
||||
);
|
||||
let secret = created["webhook_secret"].as_str().unwrap().to_string();
|
||||
h.db.git_sources()
|
||||
.update_one(doc! {}, doc! { "$set": { "enabled": true } })
|
||||
.await
|
||||
.unwrap();
|
||||
let send = |event: &'static str, body: serde_json::Value| {
|
||||
let sig = sign(&secret, &serde_json::to_vec(&body).unwrap());
|
||||
let h = &h;
|
||||
async move { h.deliver(TENANT, event, &body, Some(sig)).await }
|
||||
};
|
||||
|
||||
// Arrange: the repository's target, a finding and its issue #12.
|
||||
let repo = repo_json(21, "kunde", "fw");
|
||||
assert_eq!(
|
||||
send(
|
||||
"repository",
|
||||
serde_json::json!({ "action": "created", "repository": repo })
|
||||
)
|
||||
.await,
|
||||
202
|
||||
);
|
||||
Harness::eventually("the target", || async { h.target(21).await.is_some() }).await;
|
||||
let target_id = h.target(21).await.unwrap().id.unwrap().to_hex();
|
||||
let mut finding = Finding::new(
|
||||
target_id.clone(),
|
||||
"fp-backsync".into(),
|
||||
"semgrep".into(),
|
||||
ScanType::Sast,
|
||||
"strcpy".into(),
|
||||
"d".into(),
|
||||
Severity::High,
|
||||
);
|
||||
finding.status = FindingStatus::NeedsReview;
|
||||
let finding_id =
|
||||
h.db.findings()
|
||||
.insert_one(&finding)
|
||||
.await
|
||||
.unwrap()
|
||||
.inserted_id
|
||||
.as_object_id()
|
||||
.unwrap();
|
||||
let issue = TrackerIssue::new(
|
||||
finding_id.to_hex(),
|
||||
TrackerType::Gitea,
|
||||
"12".into(),
|
||||
"https://kunde.code.breakpilot.com/kunde/fw/issues/12".into(),
|
||||
"strcpy".into(),
|
||||
);
|
||||
h.db.tracker_issues().insert_one(&issue).await.unwrap();
|
||||
let issue_event = |action: &str, sender: &str| {
|
||||
serde_json::json!({
|
||||
"action": action, "number": 12,
|
||||
"issue": { "number": 12, "user": { "login": "pruefwerk" } },
|
||||
"sender": { "login": sender },
|
||||
"repository": repo,
|
||||
})
|
||||
};
|
||||
let stored = || async {
|
||||
let f =
|
||||
h.db.findings()
|
||||
.find_one(doc! { "_id": finding_id })
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
let i =
|
||||
h.db.tracker_issues()
|
||||
.find_one(doc! { "finding_id": finding_id.to_hex() })
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
(f, i)
|
||||
};
|
||||
|
||||
// Prüfwerk's own close (the bot opened the issue): answered at once,
|
||||
// nothing changes.
|
||||
assert_eq!(
|
||||
send("issues", issue_event("closed", "pruefwerk")).await,
|
||||
200
|
||||
);
|
||||
|
||||
// A person closes it: resolved, as closed in the ticket by them.
|
||||
assert_eq!(send("issues", issue_event("closed", "dev-anna")).await, 202);
|
||||
Harness::eventually("the resolved finding", || async {
|
||||
stored().await.0.status == FindingStatus::Resolved
|
||||
})
|
||||
.await;
|
||||
let (f, i) = stored().await;
|
||||
let change = f.status_history.last().unwrap();
|
||||
assert_eq!(change.tracker, Some(TrackerChangeKind::ClosedInTracker));
|
||||
assert_eq!(change.by_name.as_deref(), Some("dev-anna"));
|
||||
assert_eq!(f.status_history.len(), 1, "the bot's close changed nothing");
|
||||
assert_eq!(
|
||||
(i.status, i.closed_in_tracker.as_deref()),
|
||||
(IssueStatus::Closed, Some("dev-anna"))
|
||||
);
|
||||
let for_target = compliance_agent::webhooks::deliveries::target_filter(&target_id, None);
|
||||
Harness::eventually("the recorded issue delivery", || async {
|
||||
h.db.webhook_deliveries()
|
||||
.count_documents({
|
||||
let mut f = for_target.clone();
|
||||
f.insert("detail", "finding resolved: issue closed in Gitea");
|
||||
f
|
||||
})
|
||||
.await
|
||||
.unwrap()
|
||||
== 1
|
||||
})
|
||||
.await;
|
||||
|
||||
// Reopened: undecided again.
|
||||
assert_eq!(
|
||||
send("issues", issue_event("reopened", "dev-anna")).await,
|
||||
202
|
||||
);
|
||||
Harness::eventually("the reopened finding", || async {
|
||||
stored().await.0.status == FindingStatus::Open
|
||||
})
|
||||
.await;
|
||||
let (f, i) = stored().await;
|
||||
assert_eq!(
|
||||
f.status_history.last().unwrap().tracker,
|
||||
Some(TrackerChangeKind::ReopenedInTracker)
|
||||
);
|
||||
assert_eq!((i.status, i.closed_in_tracker), (IssueStatus::Open, None));
|
||||
|
||||
h.pool.drop_tenant(TENANT).await.ok();
|
||||
}
|
||||
|
||||
/// A deliveries collection written before the indexes were ensured (a plain
|
||||
/// one) is converted to a capped one.
|
||||
#[tokio::test]
|
||||
|
||||
@@ -0,0 +1,386 @@
|
||||
//! The "Heute" inbox (#950) through the real API: cards in their buckets,
|
||||
//! decisions on a card through the findings' and VEX code, undo, and
|
||||
//! resubmission dates.
|
||||
//!
|
||||
//! Runs against a live Mongo (`TEST_MONGODB_URI`) and skips cleanly without
|
||||
//! one.
|
||||
|
||||
#![allow(clippy::expect_used, clippy::unwrap_used)]
|
||||
|
||||
mod common;
|
||||
|
||||
use chrono::{Duration, Utc};
|
||||
use compliance_core::models::inbox::{CardKey, InboxSnooze};
|
||||
use compliance_core::models::{CveAlert, CveSource, Exploitation, KevEntry};
|
||||
use mongodb::bson::{doc, oid::ObjectId, Document};
|
||||
use serde_json::{json, Value};
|
||||
|
||||
use common::TestServer;
|
||||
|
||||
/// A target id and its name.
|
||||
const TARGET: &str = "665f1c2ab0c4d1e2f3a4b5c6";
|
||||
|
||||
/// Whether a Mongo answers at the test URI.
|
||||
async fn mongo_reachable() -> bool {
|
||||
let uri = std::env::var("TEST_MONGODB_URI")
|
||||
.unwrap_or_else(|_| "mongodb://root:example@localhost:27017/?authSource=admin".into());
|
||||
let Ok(client) = mongodb::Client::with_uri_str(&uri).await else {
|
||||
return false;
|
||||
};
|
||||
client
|
||||
.database("admin")
|
||||
.run_command(doc! { "ping": 1 })
|
||||
.await
|
||||
.is_ok()
|
||||
}
|
||||
|
||||
async fn tenant_db(server: &TestServer) -> mongodb::Database {
|
||||
let uri = std::env::var("TEST_MONGODB_URI")
|
||||
.unwrap_or_else(|_| "mongodb://root:example@localhost:27017/?authSource=admin".into());
|
||||
mongodb::Client::with_uri_str(&uri)
|
||||
.await
|
||||
.unwrap()
|
||||
.database(&server.tenant_db_name())
|
||||
}
|
||||
|
||||
/// Store a finding; its id.
|
||||
async fn finding(
|
||||
db: &mongodb::Database,
|
||||
title: &str,
|
||||
scan_type: &str,
|
||||
severity: &str,
|
||||
status: &str,
|
||||
file: &str,
|
||||
) -> String {
|
||||
let id = ObjectId::new();
|
||||
let now = mongodb::bson::DateTime::now();
|
||||
db.collection::<Document>("findings")
|
||||
.insert_one(doc! {
|
||||
"_id": id,
|
||||
"repo_id": TARGET,
|
||||
"fingerprint": format!("fp-{title}"),
|
||||
"scanner": "test",
|
||||
"scan_type": scan_type,
|
||||
"title": title,
|
||||
"description": title,
|
||||
"severity": severity,
|
||||
"status": status,
|
||||
"file_path": file,
|
||||
"line_number": 7,
|
||||
"triage_action": if status == "needs_review" { "dismiss" } else { "confirm" },
|
||||
"status_history": [],
|
||||
"created_at": now,
|
||||
"updated_at": now,
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
id.to_hex()
|
||||
}
|
||||
|
||||
/// Store a CVE alert of log4j-core 2.14.1; its id.
|
||||
async fn alert(db: &mongodb::Database, cve: &str, kev: bool) -> String {
|
||||
let mut a = CveAlert::new(
|
||||
cve.into(),
|
||||
TARGET.into(),
|
||||
"log4j-core".into(),
|
||||
"2.14.1".into(),
|
||||
CveSource::Osv,
|
||||
);
|
||||
let id = ObjectId::new();
|
||||
a.id = Some(id);
|
||||
a.severity = Some("CRITICAL".into());
|
||||
a.fixed_versions = vec!["2.17.1".into()];
|
||||
if kev {
|
||||
a.exploitation = Some(Exploitation {
|
||||
kev: Some(KevEntry {
|
||||
date_added: "2021-12-10".into(),
|
||||
known_ransomware: true,
|
||||
}),
|
||||
..Exploitation::default()
|
||||
});
|
||||
a.exploited_seen_at = Some(Utc::now() - Duration::hours(2));
|
||||
}
|
||||
db.collection::<CveAlert>("cve_alerts")
|
||||
.insert_one(&a)
|
||||
.await
|
||||
.unwrap();
|
||||
id.to_hex()
|
||||
}
|
||||
|
||||
async fn inbox(server: &TestServer, query: &str) -> Value {
|
||||
let resp = server.get(&format!("/api/v1/inbox{query}")).await;
|
||||
assert_eq!(resp.status(), 200);
|
||||
let body: Value = resp.json().await.unwrap();
|
||||
body["data"].clone()
|
||||
}
|
||||
|
||||
fn counts(view: &Value) -> [u64; 4] {
|
||||
let c = &view["counts"];
|
||||
[
|
||||
c["today"].as_u64().unwrap(),
|
||||
c["this_week"].as_u64().unwrap(),
|
||||
c["later"].as_u64().unwrap(),
|
||||
c["likely_false_positive"].as_u64().unwrap(),
|
||||
]
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn the_inbox_buckets_decides_undoes_and_resubmits() {
|
||||
if !mongo_reachable().await {
|
||||
eprintln!("SKIP inbox: no MongoDB reachable");
|
||||
return;
|
||||
}
|
||||
let server = TestServer::start().await;
|
||||
let db = tenant_db(&server).await;
|
||||
db.collection::<Document>("onboarded_targets")
|
||||
.insert_one(doc! { "_id": ObjectId::parse_str(TARGET).unwrap(), "name": "Pumpe", "target_type": "software" })
|
||||
.await
|
||||
.unwrap();
|
||||
let secret = finding(
|
||||
&db,
|
||||
"AWS key",
|
||||
"secretdetection",
|
||||
"medium",
|
||||
"open",
|
||||
"src/config.rs",
|
||||
)
|
||||
.await;
|
||||
let _test_secret = finding(
|
||||
&db,
|
||||
"Test key",
|
||||
"secretdetection",
|
||||
"low",
|
||||
"open",
|
||||
"tests/keys.env",
|
||||
)
|
||||
.await;
|
||||
let high = finding(&db, "SQL injection", "sast", "high", "triaged", "src/db.rs").await;
|
||||
let ai = finding(
|
||||
&db,
|
||||
"Weak hash",
|
||||
"sast",
|
||||
"medium",
|
||||
"needs_review",
|
||||
"src/hash.rs",
|
||||
)
|
||||
.await;
|
||||
finding(
|
||||
&db,
|
||||
"Old decision",
|
||||
"sast",
|
||||
"low",
|
||||
"false_positive",
|
||||
"src/a.rs",
|
||||
)
|
||||
.await;
|
||||
let a1 = alert(&db, "CVE-2021-44228", true).await;
|
||||
let a2 = alert(&db, "CVE-2021-45046", false).await;
|
||||
|
||||
// Today: the secret in code and log4j (KEV); this week: the high finding;
|
||||
// later: the test secret; the AI's: the dismissed one.
|
||||
let all = inbox(&server, "").await;
|
||||
assert_eq!(counts(&all), [2, 1, 1, 1]);
|
||||
assert_eq!(all["progress"], json!({ "decided": 1, "total": 7 }));
|
||||
assert_eq!(
|
||||
all["targets"],
|
||||
json!([{
|
||||
"id": TARGET,
|
||||
"name": "Pumpe",
|
||||
"counts": { "today": 2, "this_week": 1, "later": 1, "likely_false_positive": 1 },
|
||||
}])
|
||||
);
|
||||
let today = all["cards"].as_array().unwrap();
|
||||
let log4j = today
|
||||
.iter()
|
||||
.find(|c| c["kind"] == "cve_package")
|
||||
.unwrap()
|
||||
.clone();
|
||||
let log4j_key = CardKey::cve_package(TARGET, "log4j-core", "2.14.1");
|
||||
assert_eq!(log4j["key"], log4j_key);
|
||||
assert_eq!(log4j["count"], 2);
|
||||
assert_eq!(log4j["fix_version"], "2.17.1");
|
||||
assert_eq!(log4j["reasons"][0]["kind"], "kev");
|
||||
assert!(today
|
||||
.iter()
|
||||
.any(|c| c["item_ids"] == json!([secret]) && c["reasons"][0]["kind"] == "secret_in_code"));
|
||||
let ai_card = inbox(&server, "?bucket=likely_false_positive").await["cards"][0].clone();
|
||||
assert_eq!(ai_card["actions"], json!(["false_positive", "confirm"]));
|
||||
assert_eq!(inbox(&server, "?target=other").await["counts"]["today"], 0);
|
||||
|
||||
// A CVE decision needs its justification; with it, every alert of the
|
||||
// card gets the statement, and undo puts them back to open.
|
||||
let refused = server
|
||||
.post(
|
||||
"/api/v1/inbox/decide",
|
||||
&json!({ "key": log4j_key, "action": "not_affected" }),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(refused.status(), 422);
|
||||
let decided = server
|
||||
.post(
|
||||
"/api/v1/inbox/decide",
|
||||
&json!({
|
||||
"key": log4j_key,
|
||||
"action": "not_affected",
|
||||
"justification": "vulnerable_code_not_in_execute_path",
|
||||
}),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(decided.status(), 200);
|
||||
let decided: Value = decided.json().await.unwrap();
|
||||
let mut previous = decided["previous"].as_array().unwrap().clone();
|
||||
previous.sort_by_key(|p| p["id"].as_str().unwrap().to_string());
|
||||
let mut expected = vec![
|
||||
json!({ "kind": "cve", "id": a1, "vex": null }),
|
||||
json!({ "kind": "cve", "id": a2, "vex": null }),
|
||||
];
|
||||
expected.sort_by_key(|p| p["id"].as_str().unwrap().to_string());
|
||||
assert_eq!(previous, expected);
|
||||
let stored = db
|
||||
.collection::<CveAlert>("cve_alerts")
|
||||
.find_one(doc! { "_id": ObjectId::parse_str(&a1).unwrap() })
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
stored.vex.map(|v| v.status),
|
||||
Some(compliance_core::models::VexStatus::NotAffected)
|
||||
);
|
||||
let after = inbox(&server, "").await;
|
||||
assert_eq!(counts(&after), [1, 1, 1, 1]);
|
||||
assert_eq!(after["progress"], json!({ "decided": 3, "total": 7 }));
|
||||
let again = server
|
||||
.post(
|
||||
"/api/v1/inbox/decide",
|
||||
&json!({ "key": log4j_key, "action": "affected", "statement": "Update" }),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(again.status(), 409, "nothing left to decide");
|
||||
let undone = server
|
||||
.post(
|
||||
"/api/v1/inbox/undo",
|
||||
&json!({ "key": log4j_key, "previous": decided["previous"] }),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(undone.status(), 200);
|
||||
assert_eq!(counts(&inbox(&server, "").await), [2, 1, 1, 1]);
|
||||
|
||||
// A finding's risk needs a reason; the status change is recorded as the
|
||||
// findings endpoint records it, and undo restores the previous status.
|
||||
let high_key = CardKey::finding(&high);
|
||||
let no_reason = server
|
||||
.post(
|
||||
"/api/v1/inbox/decide",
|
||||
&json!({ "key": high_key, "action": "accepted_risk" }),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(no_reason.status(), 422);
|
||||
let not_offered = server
|
||||
.post(
|
||||
"/api/v1/inbox/decide",
|
||||
&json!({ "key": high_key, "action": "confirm" }),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(not_offered.status(), 422);
|
||||
let accepted: Value = server
|
||||
.post(
|
||||
"/api/v1/inbox/decide",
|
||||
&json!({ "key": high_key, "action": "accepted_risk", "reason": "isolated network" }),
|
||||
)
|
||||
.await
|
||||
.json()
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
accepted["previous"],
|
||||
json!([{ "kind": "finding", "id": high, "status": "triaged" }])
|
||||
);
|
||||
let stored = db
|
||||
.collection::<Document>("findings")
|
||||
.find_one(doc! { "_id": ObjectId::parse_str(&high).unwrap() })
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(stored.get_str("status").ok(), Some("accepted_risk"));
|
||||
let history = stored.get_array("status_history").unwrap();
|
||||
assert_eq!(
|
||||
history[0].as_document().unwrap().get_str("reason").ok(),
|
||||
Some("isolated network")
|
||||
);
|
||||
assert_eq!(counts(&inbox(&server, "").await), [2, 0, 1, 1]);
|
||||
let undone = server
|
||||
.post(
|
||||
"/api/v1/inbox/undo",
|
||||
&json!({ "key": high_key, "previous": accepted["previous"] }),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(undone.status(), 200);
|
||||
assert_eq!(counts(&inbox(&server, "").await), [2, 1, 1, 1]);
|
||||
// Undo only touches the card's own items.
|
||||
let foreign = server
|
||||
.post(
|
||||
"/api/v1/inbox/undo",
|
||||
&json!({ "key": high_key, "previous": [{ "kind": "finding", "id": ai, "status": "open" }] }),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(foreign.status(), 422);
|
||||
|
||||
// The AI was right: the dismissed finding is a false positive.
|
||||
let confirmed = server
|
||||
.post(
|
||||
"/api/v1/inbox/decide",
|
||||
&json!({ "key": CardKey::finding(&ai), "action": "false_positive" }),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(confirmed.status(), 200);
|
||||
assert_eq!(counts(&inbox(&server, "").await), [2, 1, 1, 0]);
|
||||
|
||||
// Put off: hidden until the date, then back in its own bucket (today).
|
||||
let secret_key = CardKey::finding(&secret);
|
||||
let past = server
|
||||
.post(
|
||||
"/api/v1/inbox/snooze",
|
||||
&json!({ "key": secret_key, "for": { "kind": "date", "date": "2020-01-01" } }),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(past.status(), 422);
|
||||
let snoozed = server
|
||||
.post(
|
||||
"/api/v1/inbox/snooze",
|
||||
&json!({ "key": secret_key, "for": { "kind": "week" } }),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(snoozed.status(), 200);
|
||||
assert_eq!(counts(&inbox(&server, "").await), [1, 1, 1, 0]);
|
||||
let record = db
|
||||
.collection::<InboxSnooze>("inbox_snoozes")
|
||||
.find_one(doc! { "key": &secret_key })
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(record.by, "dev-user");
|
||||
assert!(record.until > Utc::now() + Duration::days(6));
|
||||
// The card's items are recorded, so a new one would end the snooze early.
|
||||
assert_eq!(record.items, std::slice::from_ref(&secret));
|
||||
db.collection::<Document>("inbox_snoozes")
|
||||
.update_one(
|
||||
doc! { "key": &secret_key },
|
||||
doc! { "$set": { "until": mongodb::bson::DateTime::from_chrono(Utc::now() - Duration::hours(1)) } },
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let due = inbox(&server, "?bucket=today").await;
|
||||
assert_eq!(counts(&due), [2, 1, 1, 0]);
|
||||
assert!(due["cards"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.any(|c| c["key"] == secret_key && c["reasons"][0]["kind"] == "resubmission"));
|
||||
let unsnoozed = server
|
||||
.delete(&format!("/api/v1/inbox/snooze/{secret_key}"))
|
||||
.await;
|
||||
assert_eq!(unsnoozed.status(), 200);
|
||||
assert_eq!(counts(&inbox(&server, "").await), [2, 1, 1, 0]);
|
||||
|
||||
server.cleanup().await;
|
||||
}
|
||||
@@ -563,8 +563,8 @@ async fn collect(agent: &Agent, target_id: &str, run: &Value) -> Collected {
|
||||
}
|
||||
|
||||
/// Wait until each target has a finished scan run that did not exist before
|
||||
/// seeding. Returns the run per target id; targets still running at the
|
||||
/// deadline are left out.
|
||||
/// seeding. Returns the run per target id; targets still queued or running
|
||||
/// at the deadline are left out.
|
||||
async fn wait_for_runs(
|
||||
agent: &Agent,
|
||||
targets: &[String],
|
||||
@@ -580,7 +580,8 @@ async fn wait_for_runs(
|
||||
if done.contains_key(&repo)
|
||||
|| !targets.contains(&repo)
|
||||
|| before.contains(&oid(&run))
|
||||
|| text(&run, "status") == "running"
|
||||
// Still waiting for a slot (t84) or scanning: not finished.
|
||||
|| matches!(text(&run, "status").as_str(), "queued" | "running")
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,187 @@
|
||||
//! A target's "Verlauf" (#957) through the real API: per scan the CVE
|
||||
//! alerts found new and gone since the completed scan before it.
|
||||
//!
|
||||
//! Runs against a live Mongo (`TEST_MONGODB_URI`) and skips cleanly without
|
||||
//! one.
|
||||
|
||||
#![allow(clippy::expect_used, clippy::unwrap_used)]
|
||||
|
||||
mod common;
|
||||
|
||||
use chrono::{DateTime, Duration, Utc};
|
||||
use compliance_core::component_changes::{ComponentChange, ComponentChangeKind};
|
||||
use compliance_core::models::{CveAlert, CveSource, ScanRun, ScanRunStatus, ScanTrigger};
|
||||
use mongodb::bson::{doc, oid::ObjectId, Document};
|
||||
use serde_json::Value;
|
||||
|
||||
use common::TestServer;
|
||||
|
||||
const TARGET: &str = "665f1c2ab0c4d1e2f3a4b5c7";
|
||||
|
||||
async fn mongo_reachable() -> bool {
|
||||
let uri = std::env::var("TEST_MONGODB_URI")
|
||||
.unwrap_or_else(|_| "mongodb://root:example@localhost:27017/?authSource=admin".into());
|
||||
let Ok(client) = mongodb::Client::with_uri_str(&uri).await else {
|
||||
return false;
|
||||
};
|
||||
client
|
||||
.database("admin")
|
||||
.run_command(doc! { "ping": 1 })
|
||||
.await
|
||||
.is_ok()
|
||||
}
|
||||
|
||||
/// Store a run of the target that started `start` and ended `end`, with the
|
||||
/// component changes it recorded.
|
||||
async fn run(
|
||||
db: &mongodb::Database,
|
||||
status: ScanRunStatus,
|
||||
start: DateTime<Utc>,
|
||||
end: Option<DateTime<Utc>>,
|
||||
components: Option<Vec<ComponentChange>>,
|
||||
) {
|
||||
let mut run = ScanRun::new(TARGET.into(), ScanTrigger::Scheduled);
|
||||
run.status = status;
|
||||
run.started_at = start;
|
||||
run.completed_at = end;
|
||||
run.component_changes = components;
|
||||
db.collection::<ScanRun>("scan_runs")
|
||||
.insert_one(&run)
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
/// Store an alert of the target found at `created`, gone at `resolved`.
|
||||
async fn alert(
|
||||
db: &mongodb::Database,
|
||||
cve: &str,
|
||||
created: DateTime<Utc>,
|
||||
resolved: Option<DateTime<Utc>>,
|
||||
) {
|
||||
let mut a = CveAlert::new(
|
||||
cve.into(),
|
||||
TARGET.into(),
|
||||
"openssl".into(),
|
||||
"3.0.9".into(),
|
||||
CveSource::Osv,
|
||||
);
|
||||
a.severity = Some("HIGH".into());
|
||||
a.created_at = created;
|
||||
a.resolved_at = resolved;
|
||||
db.collection::<CveAlert>("cve_alerts")
|
||||
.insert_one(&a)
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
/// The CVE ids of a change's `side` (`new_cves` or `gone_cves`).
|
||||
fn cves(change: &Value, side: &str) -> Vec<String> {
|
||||
change[side]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.map(|c| c["cve"].as_str().unwrap().to_string())
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn each_scan_shows_the_cves_it_found_new_and_gone() {
|
||||
if !mongo_reachable().await {
|
||||
eprintln!("SKIP scan_changes: no MongoDB reachable");
|
||||
return;
|
||||
}
|
||||
let server = TestServer::start().await;
|
||||
let uri = std::env::var("TEST_MONGODB_URI")
|
||||
.unwrap_or_else(|_| "mongodb://root:example@localhost:27017/?authSource=admin".into());
|
||||
let db = mongodb::Client::with_uri_str(&uri)
|
||||
.await
|
||||
.unwrap()
|
||||
.database(&server.tenant_db_name());
|
||||
db.collection::<Document>("onboarded_targets")
|
||||
.insert_one(doc! { "_id": ObjectId::parse_str(TARGET).unwrap(), "name": "Pumpe", "target_type": "software" })
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
// Arrange: three scans, the middle one failed; one CVE from the first
|
||||
// scan goes in the last, one comes with it.
|
||||
let t0 = Utc::now() - Duration::days(3);
|
||||
let hour = |h: i64| t0 + Duration::hours(h);
|
||||
run(&db, ScanRunStatus::Completed, hour(0), Some(hour(1)), None).await;
|
||||
run(&db, ScanRunStatus::Failed, hour(24), Some(hour(25)), None).await;
|
||||
// The last one recorded its components (#974): openssl was updated.
|
||||
let updated = ComponentChange {
|
||||
kind: ComponentChangeKind::Updated,
|
||||
package_manager: "npm".into(),
|
||||
name: "openssl".into(),
|
||||
from: Some("3.0.9".into()),
|
||||
to: Some("3.0.11".into()),
|
||||
};
|
||||
run(
|
||||
&db,
|
||||
ScanRunStatus::Completed,
|
||||
hour(48),
|
||||
Some(hour(49)),
|
||||
Some(vec![updated]),
|
||||
)
|
||||
.await;
|
||||
alert(&db, "CVE-2026-1001", hour(1), Some(hour(49))).await;
|
||||
alert(&db, "CVE-2026-1002", hour(1), None).await;
|
||||
alert(&db, "CVE-2026-1003", hour(49), None).await;
|
||||
|
||||
// Act
|
||||
let resp = server
|
||||
.get(&format!("/api/v1/targets/{TARGET}/scan-changes"))
|
||||
.await;
|
||||
assert_eq!(resp.status(), 200);
|
||||
let body: Value = resp.json().await.unwrap();
|
||||
let changes = body["data"].as_array().unwrap();
|
||||
|
||||
// Assert: oldest first; the first is the baseline, the failed one
|
||||
// changes nothing, the last has one new and one gone.
|
||||
assert_eq!(changes.len(), 3);
|
||||
assert_eq!(changes[0]["baseline"], true);
|
||||
assert!(cves(&changes[0], "new_cves").is_empty());
|
||||
assert_eq!(changes[1]["status"], "failed");
|
||||
assert!(cves(&changes[1], "new_cves").is_empty());
|
||||
assert_eq!(cves(&changes[2], "new_cves"), ["CVE-2026-1003"]);
|
||||
assert_eq!(cves(&changes[2], "gone_cves"), ["CVE-2026-1001"]);
|
||||
// The update took the gone CVE (at 3.0.9). The new one names 3.0.9 too,
|
||||
// which the update left, so no change explains it: an advisory row,
|
||||
// after the change of the same component.
|
||||
assert!(changes[0].get("components").is_none(), "not recorded");
|
||||
let rows = changes[2]["components"].as_array().unwrap();
|
||||
let read: Vec<(&str, &str, u64, u64)> = rows
|
||||
.iter()
|
||||
.map(|r| {
|
||||
(
|
||||
r["kind"].as_str().unwrap(),
|
||||
r["name"].as_str().unwrap(),
|
||||
r["cves_new"].as_u64().unwrap(),
|
||||
r["cves_gone"].as_u64().unwrap(),
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(
|
||||
read,
|
||||
[("updated", "openssl", 0, 1), ("advisory", "openssl", 1, 0)]
|
||||
);
|
||||
|
||||
// With a limit the oldest scans drop out, and the window of the first
|
||||
// shown one starts at the end of the completed scan before it.
|
||||
let resp = server
|
||||
.get(&format!("/api/v1/targets/{TARGET}/scan-changes?limit=1"))
|
||||
.await;
|
||||
let body: Value = resp.json().await.unwrap();
|
||||
let changes = body["data"].as_array().unwrap();
|
||||
assert_eq!(changes.len(), 1);
|
||||
assert_eq!(changes[0]["baseline"], false);
|
||||
assert_eq!(cves(&changes[0], "new_cves"), ["CVE-2026-1003"]);
|
||||
|
||||
// An unknown target is a 404.
|
||||
let resp = server
|
||||
.get("/api/v1/targets/665f1c2ab0c4d1e2f3a4b5ff/scan-changes")
|
||||
.await;
|
||||
assert_eq!(resp.status(), 404);
|
||||
|
||||
server.cleanup().await;
|
||||
}
|
||||
@@ -0,0 +1,172 @@
|
||||
//! What a scan changed in a target's SBOM (#974): the components it added,
|
||||
//! updated and removed, against the SBOM stored before it.
|
||||
//!
|
||||
//! A component is its package manager and name; its versions are compared
|
||||
//! as sets, since a target can hold two copies of a library. One version
|
||||
//! before and one after is an update; otherwise each version that is new is
|
||||
//! an addition and each that is gone a removal.
|
||||
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// The most component changes a scan records; a larger change (a first
|
||||
/// firmware import, a new build system) keeps the first ones in name order.
|
||||
pub const MAX_CHANGES: usize = 5000;
|
||||
|
||||
/// How a component changed.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum ComponentChangeKind {
|
||||
Added,
|
||||
Updated,
|
||||
Removed,
|
||||
}
|
||||
|
||||
/// One component a scan added, updated or removed.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct ComponentChange {
|
||||
pub kind: ComponentChangeKind,
|
||||
pub package_manager: String,
|
||||
pub name: String,
|
||||
/// The version before; `None` for an addition.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub from: Option<String>,
|
||||
/// The version after; `None` for a removal.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub to: Option<String>,
|
||||
}
|
||||
|
||||
/// A component as the comparison sees it: package manager, name, version.
|
||||
pub type ComponentKey<'a> = (&'a str, &'a str, &'a str);
|
||||
|
||||
/// The versions of each component (package manager, name) in `components`.
|
||||
fn by_component<'a>(
|
||||
components: &[ComponentKey<'a>],
|
||||
) -> BTreeMap<(&'a str, &'a str), BTreeSet<&'a str>> {
|
||||
let mut map: BTreeMap<_, BTreeSet<_>> = BTreeMap::new();
|
||||
for (manager, name, version) in components {
|
||||
map.entry((*manager, *name)).or_default().insert(*version);
|
||||
}
|
||||
map
|
||||
}
|
||||
|
||||
/// The changes from `before` to `after`, by component name, at most
|
||||
/// [`MAX_CHANGES`].
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// ```
|
||||
/// use compliance_core::component_changes::{diff, ComponentChangeKind};
|
||||
///
|
||||
/// let before = [("npm", "lodash", "4.17.20")];
|
||||
/// let after = [("npm", "lodash", "4.17.21")];
|
||||
/// let changes = diff(&before, &after);
|
||||
/// assert_eq!(changes[0].kind, ComponentChangeKind::Updated);
|
||||
/// ```
|
||||
pub fn diff(before: &[ComponentKey<'_>], after: &[ComponentKey<'_>]) -> Vec<ComponentChange> {
|
||||
let (old, new) = (by_component(before), by_component(after));
|
||||
let empty = BTreeSet::new();
|
||||
let keys: BTreeSet<_> = old.keys().chain(new.keys()).copied().collect();
|
||||
let mut changes = Vec::new();
|
||||
for (manager, name) in keys {
|
||||
let was = old.get(&(manager, name)).unwrap_or(&empty);
|
||||
let is = new.get(&(manager, name)).unwrap_or(&empty);
|
||||
if was == is {
|
||||
continue;
|
||||
}
|
||||
let change = |kind, from: Option<&str>, to: Option<&str>| ComponentChange {
|
||||
kind,
|
||||
package_manager: manager.to_string(),
|
||||
name: name.to_string(),
|
||||
from: from.map(str::to_string),
|
||||
to: to.map(str::to_string),
|
||||
};
|
||||
if let ([from], [to]) = (
|
||||
was.iter().collect::<Vec<_>>().as_slice(),
|
||||
is.iter().collect::<Vec<_>>().as_slice(),
|
||||
) {
|
||||
changes.push(change(ComponentChangeKind::Updated, Some(from), Some(to)));
|
||||
continue;
|
||||
}
|
||||
for version in was.difference(is) {
|
||||
changes.push(change(ComponentChangeKind::Removed, Some(version), None));
|
||||
}
|
||||
for version in is.difference(was) {
|
||||
changes.push(change(ComponentChangeKind::Added, None, Some(version)));
|
||||
}
|
||||
}
|
||||
changes.truncate(MAX_CHANGES);
|
||||
changes
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn an_sbom_change_reads_as_additions_updates_and_removals() {
|
||||
let before = [
|
||||
("npm", "lodash", "4.17.20"),
|
||||
("npm", "left-pad", "1.3.0"),
|
||||
("cargo", "serde", "1.0.200"),
|
||||
// Two copies, one goes.
|
||||
("npm", "minimist", "1.2.5"),
|
||||
("npm", "minimist", "1.2.8"),
|
||||
];
|
||||
let after = [
|
||||
("npm", "lodash", "4.17.21"),
|
||||
("cargo", "serde", "1.0.200"),
|
||||
("npm", "minimist", "1.2.8"),
|
||||
("npm", "zod", "3.23.0"),
|
||||
];
|
||||
|
||||
let changes = diff(&before, &after);
|
||||
|
||||
let read: Vec<(ComponentChangeKind, &str, Option<&str>, Option<&str>)> = changes
|
||||
.iter()
|
||||
.map(|c| (c.kind, c.name.as_str(), c.from.as_deref(), c.to.as_deref()))
|
||||
.collect();
|
||||
assert_eq!(
|
||||
read,
|
||||
[
|
||||
(
|
||||
ComponentChangeKind::Removed,
|
||||
"left-pad",
|
||||
Some("1.3.0"),
|
||||
None
|
||||
),
|
||||
(
|
||||
ComponentChangeKind::Updated,
|
||||
"lodash",
|
||||
Some("4.17.20"),
|
||||
Some("4.17.21")
|
||||
),
|
||||
(
|
||||
ComponentChangeKind::Removed,
|
||||
"minimist",
|
||||
Some("1.2.5"),
|
||||
None
|
||||
),
|
||||
(ComponentChangeKind::Added, "zod", None, Some("3.23.0")),
|
||||
]
|
||||
);
|
||||
assert!(diff(&after, &after).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_same_name_in_another_package_manager_is_another_component() {
|
||||
let changes = diff(&[("npm", "uuid", "9.0.0")], &[("cargo", "uuid", "9.0.0")]);
|
||||
let kinds: Vec<_> = changes
|
||||
.iter()
|
||||
.map(|c| (c.kind, c.package_manager.as_str()))
|
||||
.collect();
|
||||
assert_eq!(
|
||||
kinds,
|
||||
[
|
||||
(ComponentChangeKind::Added, "cargo"),
|
||||
(ComponentChangeKind::Removed, "npm")
|
||||
]
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,432 @@
|
||||
//! A target's open CVE alerts grouped by the component they are in (#949):
|
||||
//! what one update of the component fixes, so that whoever triages decides
|
||||
//! once per package instead of once per CVE.
|
||||
//!
|
||||
//! Open means not settled: no `not_affected` or `fixed` statement, and not
|
||||
//! found gone by a complete scan (see [`crate::vex_docs::status_of`]).
|
||||
|
||||
use std::cmp::Ordering;
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::models::CveAlert;
|
||||
use crate::version::cmp_dotted;
|
||||
use crate::vex_docs::status_of;
|
||||
|
||||
/// How severe a CVE is, as the groups count it. `Info` is a CVE the
|
||||
/// advisory rates neither by name nor by CVSS score.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum CveSeverity {
|
||||
Info,
|
||||
Low,
|
||||
Medium,
|
||||
High,
|
||||
Critical,
|
||||
}
|
||||
|
||||
impl CveSeverity {
|
||||
/// The severity of `alert`: the advisory's rating (GitHub's `MODERATE`
|
||||
/// is medium), else its CVSS score, else `Info`.
|
||||
pub fn of(alert: &CveAlert) -> Self {
|
||||
let named = alert.severity.as_deref().map(str::to_ascii_lowercase);
|
||||
match named.as_deref() {
|
||||
Some("critical") => Self::Critical,
|
||||
Some("high") => Self::High,
|
||||
Some("moderate" | "medium") => Self::Medium,
|
||||
Some("low") => Self::Low,
|
||||
_ => match alert.cvss_score {
|
||||
Some(score) if score >= 9.0 => Self::Critical,
|
||||
Some(score) if score >= 7.0 => Self::High,
|
||||
Some(score) if score >= 4.0 => Self::Medium,
|
||||
Some(score) if score > 0.0 => Self::Low,
|
||||
_ => Self::Info,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// The severity as the dashboard's badge names it (`high`).
|
||||
pub fn as_str(self) -> &'static str {
|
||||
match self {
|
||||
Self::Info => "info",
|
||||
Self::Low => "low",
|
||||
Self::Medium => "medium",
|
||||
Self::High => "high",
|
||||
Self::Critical => "critical",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// How many CVEs of a group have each severity.
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct SeverityCounts {
|
||||
pub critical: usize,
|
||||
pub high: usize,
|
||||
pub medium: usize,
|
||||
pub low: usize,
|
||||
pub info: usize,
|
||||
}
|
||||
|
||||
impl SeverityCounts {
|
||||
fn add(&mut self, severity: CveSeverity) {
|
||||
let count = match severity {
|
||||
CveSeverity::Critical => &mut self.critical,
|
||||
CveSeverity::High => &mut self.high,
|
||||
CveSeverity::Medium => &mut self.medium,
|
||||
CveSeverity::Low => &mut self.low,
|
||||
CveSeverity::Info => &mut self.info,
|
||||
};
|
||||
*count += 1;
|
||||
}
|
||||
|
||||
/// Each severity with its count, most severe first.
|
||||
pub fn by_severity(&self) -> [(CveSeverity, usize); 5] {
|
||||
[
|
||||
(CveSeverity::Critical, self.critical),
|
||||
(CveSeverity::High, self.high),
|
||||
(CveSeverity::Medium, self.medium),
|
||||
(CveSeverity::Low, self.low),
|
||||
(CveSeverity::Info, self.info),
|
||||
]
|
||||
}
|
||||
|
||||
/// The most severe severity counted, `Info` when none is.
|
||||
pub fn max(&self) -> CveSeverity {
|
||||
self.by_severity()
|
||||
.into_iter()
|
||||
.find(|(_, count)| *count > 0)
|
||||
.map_or(CveSeverity::Info, |(severity, _)| severity)
|
||||
}
|
||||
}
|
||||
|
||||
/// The component a group is about, as its alerts name it.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
|
||||
pub struct PackageKey {
|
||||
pub package: String,
|
||||
pub version: String,
|
||||
/// The component's purl (`pkg:npm/vite@5.4.21`), when the alerts carry
|
||||
/// one.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub purl: Option<String>,
|
||||
}
|
||||
|
||||
impl PackageKey {
|
||||
/// The key of the component `alert` is about.
|
||||
pub fn of(alert: &CveAlert) -> Self {
|
||||
Self {
|
||||
package: alert.affected_package.clone(),
|
||||
version: alert.affected_version.clone(),
|
||||
purl: alert.purl.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `alert` is about this component.
|
||||
pub fn matches(&self, alert: &CveAlert) -> bool {
|
||||
self.package == alert.affected_package
|
||||
&& self.version == alert.affected_version
|
||||
&& self.purl == alert.purl
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `alert` still asks for a decision: neither stated `not_affected`
|
||||
/// or `fixed`, nor found gone by a complete scan.
|
||||
pub fn is_open(alert: &CveAlert) -> bool {
|
||||
!status_of(alert).resolves()
|
||||
}
|
||||
|
||||
/// The open CVE alerts of one component.
|
||||
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
||||
pub struct CveGroup {
|
||||
#[serde(flatten)]
|
||||
pub key: PackageKey,
|
||||
/// The highest version above the component's own that the advisories
|
||||
/// name as fixed: the update that fixes every CVE naming a fix.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub fix_version: Option<String>,
|
||||
/// How many of the CVEs name a fixed version, and so are fixed by
|
||||
/// updating to `fix_version`.
|
||||
pub fixable: usize,
|
||||
/// The CVEs per severity; a CVE in several alerts (a GitHub advisory
|
||||
/// and the NVD entry it aliases) counts once, at its highest severity.
|
||||
pub counts: SeverityCounts,
|
||||
/// Whether any of them is in CISA's KEV catalog.
|
||||
pub kev: bool,
|
||||
/// The highest EPSS score among them, 0 to 1.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub epss_max: Option<f64>,
|
||||
/// The CVE ids, each once, sorted.
|
||||
pub cve_ids: Vec<String>,
|
||||
/// The alerts (hex object ids) a group decision states VEX on.
|
||||
pub alert_ids: Vec<String>,
|
||||
}
|
||||
|
||||
/// What [`group_open_alerts`] gathers per CVE: its highest severity and
|
||||
/// whether an advisory names a fix above the component's version.
|
||||
#[derive(Default)]
|
||||
struct CveTally {
|
||||
severity: Option<CveSeverity>,
|
||||
fixable: bool,
|
||||
}
|
||||
|
||||
/// The open alerts of `alerts` grouped by component, the most severe group
|
||||
/// first (then the one with more CVEs, then by name and version).
|
||||
pub fn group_open_alerts(alerts: &[CveAlert]) -> Vec<CveGroup> {
|
||||
let mut by_component: BTreeMap<PackageKey, Vec<&CveAlert>> = BTreeMap::new();
|
||||
for alert in alerts.iter().filter(|a| is_open(a)) {
|
||||
by_component
|
||||
.entry(PackageKey::of(alert))
|
||||
.or_default()
|
||||
.push(alert);
|
||||
}
|
||||
let mut groups: Vec<CveGroup> = by_component
|
||||
.into_iter()
|
||||
.map(|(key, members)| group(key, &members))
|
||||
.collect();
|
||||
groups.sort_by(|a, b| {
|
||||
b.counts
|
||||
.max()
|
||||
.cmp(&a.counts.max())
|
||||
.then_with(|| b.cve_ids.len().cmp(&a.cve_ids.len()))
|
||||
.then_with(|| a.key.cmp(&b.key))
|
||||
});
|
||||
groups
|
||||
}
|
||||
|
||||
/// The group of component `key` from its open alerts `members`.
|
||||
fn group(key: PackageKey, members: &[&CveAlert]) -> CveGroup {
|
||||
let above_current = |v: &&String| cmp_dotted(v, &key.version) == Ordering::Greater;
|
||||
let mut tallies: BTreeMap<&str, CveTally> = BTreeMap::new();
|
||||
let mut fix_version: Option<&String> = None;
|
||||
let mut kev = false;
|
||||
let mut epss_max: Option<f64> = None;
|
||||
for alert in members {
|
||||
let tally = tallies.entry(alert.cve()).or_default();
|
||||
tally.severity = tally.severity.max(Some(CveSeverity::of(alert)));
|
||||
for fixed in alert.fixed_versions.iter().filter(above_current) {
|
||||
tally.fixable = true;
|
||||
if fix_version.is_none_or(|best| cmp_dotted(fixed, best) == Ordering::Greater) {
|
||||
fix_version = Some(fixed);
|
||||
}
|
||||
}
|
||||
if let Some(exploitation) = &alert.exploitation {
|
||||
kev |= exploitation.kev.is_some();
|
||||
if let Some(epss) = &exploitation.epss {
|
||||
epss_max = Some(epss_max.map_or(epss.score, |m| m.max(epss.score)));
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut counts = SeverityCounts::default();
|
||||
for tally in tallies.values() {
|
||||
counts.add(tally.severity.unwrap_or(CveSeverity::Info));
|
||||
}
|
||||
CveGroup {
|
||||
fix_version: fix_version.cloned(),
|
||||
fixable: tallies.values().filter(|t| t.fixable).count(),
|
||||
counts,
|
||||
kev,
|
||||
epss_max,
|
||||
cve_ids: tallies.keys().map(|id| (*id).to_string()).collect(),
|
||||
alert_ids: members
|
||||
.iter()
|
||||
.filter_map(|a| a.id.map(|o| o.to_hex()))
|
||||
.collect(),
|
||||
key,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::models::vex::{VexAssessment, VexStatus};
|
||||
use crate::models::{CveSource, EpssScore, Exploitation, KevEntry};
|
||||
|
||||
fn alert(id: &str, package: &str, version: &str, severity: Option<&str>) -> CveAlert {
|
||||
let mut a = CveAlert::new(
|
||||
id.into(),
|
||||
"t1".into(),
|
||||
package.into(),
|
||||
version.into(),
|
||||
CveSource::Osv,
|
||||
);
|
||||
a.id = Some(bson::oid::ObjectId::new());
|
||||
a.purl = Some(format!("pkg:npm/{package}@{version}"));
|
||||
a.severity = severity.map(String::from);
|
||||
a
|
||||
}
|
||||
|
||||
fn fixed_in(mut a: CveAlert, versions: &[&str]) -> CveAlert {
|
||||
a.fixed_versions = versions.iter().map(|v| v.to_string()).collect();
|
||||
a
|
||||
}
|
||||
|
||||
fn stated(mut a: CveAlert, status: VexStatus) -> CveAlert {
|
||||
a.vex = Some(VexAssessment {
|
||||
status,
|
||||
justification: None,
|
||||
impact_statement: Some("Build tool only.".into()),
|
||||
action_statement: None,
|
||||
by: "u1".into(),
|
||||
by_name: None,
|
||||
at: chrono::Utc::now(),
|
||||
by_scan: false,
|
||||
});
|
||||
a
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn severities_come_from_the_rating_then_the_cvss_score() {
|
||||
let mut a = alert("CVE-2024-0001", "vite", "5.4.21", Some("MODERATE"));
|
||||
assert_eq!(CveSeverity::of(&a), CveSeverity::Medium);
|
||||
a.severity = None;
|
||||
assert_eq!(CveSeverity::of(&a), CveSeverity::Info);
|
||||
a.cvss_score = Some(9.8);
|
||||
assert_eq!(CveSeverity::of(&a), CveSeverity::Critical);
|
||||
a.cvss_score = Some(0.0);
|
||||
assert_eq!(CveSeverity::of(&a), CveSeverity::Info);
|
||||
a.severity = Some("High".into());
|
||||
assert_eq!(CveSeverity::of(&a), CveSeverity::High);
|
||||
assert_eq!(
|
||||
serde_json::to_value(CveSeverity::Critical).ok(),
|
||||
Some(serde_json::json!("critical"))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn open_alerts_group_by_component_with_the_highest_fix() {
|
||||
let alerts = vec![
|
||||
fixed_in(
|
||||
alert("CVE-2025-0001", "vite", "5.4.21", Some("HIGH")),
|
||||
&["5.4.22", "6.3.6"],
|
||||
),
|
||||
fixed_in(
|
||||
alert("CVE-2025-0002", "vite", "5.4.21", Some("LOW")),
|
||||
&["8.3.3"],
|
||||
),
|
||||
fixed_in(alert("CVE-2025-0003", "vite", "5.4.21", None), &["8.10.0"]),
|
||||
// A fix below the component's version fixes nothing here.
|
||||
fixed_in(alert("CVE-2025-0004", "vite", "5.4.21", None), &["4.0.0"]),
|
||||
alert("CVE-2025-0005", "vite", "6.0.0", Some("CRITICAL")),
|
||||
alert("CVE-2025-0006", "lodash", "4.17.20", Some("HIGH")),
|
||||
];
|
||||
let groups = group_open_alerts(&alerts);
|
||||
let keys: Vec<(&str, &str)> = groups
|
||||
.iter()
|
||||
.map(|g| (g.key.package.as_str(), g.key.version.as_str()))
|
||||
.collect();
|
||||
// Most severe first; among the two `high` groups, more CVEs first.
|
||||
assert_eq!(
|
||||
keys,
|
||||
[("vite", "6.0.0"), ("vite", "5.4.21"), ("lodash", "4.17.20")]
|
||||
);
|
||||
let vite = &groups[1];
|
||||
assert_eq!(vite.fix_version.as_deref(), Some("8.10.0"));
|
||||
assert_eq!(vite.fixable, 3);
|
||||
assert_eq!(
|
||||
vite.counts,
|
||||
SeverityCounts {
|
||||
high: 1,
|
||||
low: 1,
|
||||
info: 2,
|
||||
..SeverityCounts::default()
|
||||
}
|
||||
);
|
||||
assert_eq!(
|
||||
vite.cve_ids,
|
||||
[
|
||||
"CVE-2025-0001",
|
||||
"CVE-2025-0002",
|
||||
"CVE-2025-0003",
|
||||
"CVE-2025-0004"
|
||||
]
|
||||
);
|
||||
assert_eq!(vite.alert_ids.len(), 4);
|
||||
assert_eq!(groups[2].fix_version, None);
|
||||
assert_eq!(groups[2].fixable, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn settled_alerts_are_left_out_and_a_cve_counts_once() {
|
||||
let mut gone = alert("CVE-2025-0003", "vite", "5.4.21", Some("HIGH"));
|
||||
gone.resolved_at = Some(chrono::Utc::now());
|
||||
let mut ghsa = alert("GHSA-aaaa-bbbb-cccc", "vite", "5.4.21", Some("LOW"));
|
||||
ghsa.aliases = vec!["CVE-2025-0001".into()];
|
||||
let alerts = vec![
|
||||
alert("CVE-2025-0001", "vite", "5.4.21", Some("MEDIUM")),
|
||||
ghsa,
|
||||
stated(
|
||||
alert("CVE-2025-0002", "vite", "5.4.21", Some("CRITICAL")),
|
||||
VexStatus::NotAffected,
|
||||
),
|
||||
gone,
|
||||
// Affected and under investigation still ask for a decision.
|
||||
stated(
|
||||
alert("CVE-2025-0004", "vite", "5.4.21", None),
|
||||
VexStatus::Affected,
|
||||
),
|
||||
];
|
||||
let groups = group_open_alerts(&alerts);
|
||||
assert_eq!(groups.len(), 1);
|
||||
let vite = &groups[0];
|
||||
assert_eq!(vite.cve_ids, ["CVE-2025-0001", "CVE-2025-0004"]);
|
||||
assert_eq!(vite.alert_ids.len(), 3);
|
||||
assert_eq!(
|
||||
vite.counts,
|
||||
SeverityCounts {
|
||||
medium: 1,
|
||||
info: 1,
|
||||
..SeverityCounts::default()
|
||||
}
|
||||
);
|
||||
assert!(group_open_alerts(&alerts[2..4]).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_group_has_the_worst_exploitation_of_its_cves() {
|
||||
let mut kev = alert("CVE-2025-0001", "vite", "5.4.21", Some("LOW"));
|
||||
kev.exploitation = Some(Exploitation {
|
||||
kev: Some(KevEntry::default()),
|
||||
epss: Some(EpssScore {
|
||||
score: 0.2,
|
||||
percentile: 0.9,
|
||||
date: String::new(),
|
||||
}),
|
||||
ssvc_exploitation: None,
|
||||
});
|
||||
let mut likely = alert("CVE-2025-0002", "vite", "5.4.21", Some("LOW"));
|
||||
likely.exploitation = Some(Exploitation {
|
||||
epss: Some(EpssScore {
|
||||
score: 0.7,
|
||||
percentile: 0.99,
|
||||
date: String::new(),
|
||||
}),
|
||||
..Exploitation::default()
|
||||
});
|
||||
let groups = group_open_alerts(&[kev, likely]);
|
||||
assert!(groups[0].kev);
|
||||
assert_eq!(groups[0].epss_max, Some(0.7));
|
||||
let quiet = group_open_alerts(&[alert("CVE-2025-0003", "vite", "5.4.21", None)]);
|
||||
assert!(!quiet[0].kev);
|
||||
assert_eq!(quiet[0].epss_max, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_key_matches_the_alerts_of_its_component_only() {
|
||||
let a = alert("CVE-2025-0001", "vite", "5.4.21", None);
|
||||
let key = PackageKey::of(&a);
|
||||
assert!(key.matches(&a));
|
||||
let mut other_version = a.clone();
|
||||
other_version.affected_version = "5.4.22".into();
|
||||
assert!(!key.matches(&other_version));
|
||||
let mut without_purl = a.clone();
|
||||
without_purl.purl = None;
|
||||
assert!(!key.matches(&without_purl));
|
||||
// The group's JSON names the component at the top level, as the
|
||||
// group decision's body does.
|
||||
let groups = group_open_alerts(&[a]);
|
||||
let json = serde_json::to_value(&groups[0]).unwrap_or_default();
|
||||
assert_eq!(json["package"], "vite");
|
||||
assert_eq!(json["purl"], "pkg:npm/vite@5.4.21");
|
||||
assert_eq!(json["counts"]["info"], 1);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,429 @@
|
||||
//! Open CVE alerts over time, and the package updates that close the most
|
||||
//! of them (#952): what the overview's and a target's CVE charts show.
|
||||
//!
|
||||
//! Computed from the stored alerts alone, no snapshots: an alert counts on
|
||||
//! day `d` (UTC) when, at the end of `d`,
|
||||
//!
|
||||
//! * it had been found (`created_at`),
|
||||
//! * it was not resolved yet (`resolved_at` unset or later),
|
||||
//! * no VEX statement had settled it (`not_affected` or `fixed` stated at
|
||||
//! `vex.at` or earlier), and
|
||||
//! * its advisory names a fixed version (`fixed_versions` not empty).
|
||||
//!
|
||||
//! The unit is one CVE in one target: the same CVE in two packages of a
|
||||
//! target (a GHSA and its CVE alias, two copies of a library) counts once,
|
||||
//! at its highest severity; in two targets it counts twice. A tenant's or a
|
||||
//! project's series is the sum of its targets' series.
|
||||
//!
|
||||
//! Only the current state of an alert is stored, so two things are not
|
||||
//! seen in the past: an alert reported again after it was resolved loses
|
||||
//! its `resolved_at` (it shows as open through the gap), and a withdrawn
|
||||
//! VEX statement is overwritten (the alert shows as open throughout).
|
||||
|
||||
use std::cmp::Ordering;
|
||||
use std::collections::{BTreeMap, HashMap, HashSet};
|
||||
|
||||
use chrono::{DateTime, Days, NaiveDate, Utc};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::models::notification::{parse_severity, NotificationSeverity};
|
||||
use crate::models::CveAlert;
|
||||
use crate::version::cmp_dotted;
|
||||
|
||||
/// The days a history covers unless asked otherwise.
|
||||
pub const DEFAULT_DAYS: u32 = 30;
|
||||
/// The most days a history may cover.
|
||||
pub const MAX_DAYS: u32 = 90;
|
||||
|
||||
/// One day of a history: the open CVEs with a fixed version, by severity.
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct CveDay {
|
||||
/// The day (UTC).
|
||||
pub date: NaiveDate,
|
||||
pub critical: u32,
|
||||
pub high: u32,
|
||||
pub medium: u32,
|
||||
pub low: u32,
|
||||
}
|
||||
|
||||
impl CveDay {
|
||||
/// The critical and high ones: what the charts show.
|
||||
pub fn urgent(&self) -> u32 {
|
||||
self.critical + self.high
|
||||
}
|
||||
|
||||
/// Count one CVE of `severity`.
|
||||
fn count(&mut self, severity: &NotificationSeverity) {
|
||||
match severity {
|
||||
NotificationSeverity::Critical => self.critical += 1,
|
||||
NotificationSeverity::High => self.high += 1,
|
||||
NotificationSeverity::Medium => self.medium += 1,
|
||||
NotificationSeverity::Low => self.low += 1,
|
||||
}
|
||||
}
|
||||
|
||||
/// Add another series' counts of the same day.
|
||||
fn add(&mut self, other: &Self) {
|
||||
self.critical += other.critical;
|
||||
self.high += other.high;
|
||||
self.medium += other.medium;
|
||||
self.low += other.low;
|
||||
}
|
||||
}
|
||||
|
||||
/// Open findings of the same scope, the dashboards' other two tiles.
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct OpenFindings {
|
||||
pub critical: u64,
|
||||
pub high: u64,
|
||||
}
|
||||
|
||||
/// The answer of `GET /api/v1/cve-history`.
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct CveHistory {
|
||||
/// Oldest day first, today last.
|
||||
pub days: Vec<CveDay>,
|
||||
#[serde(default)]
|
||||
pub open_findings: OpenFindings,
|
||||
/// Each target's own series (same days), when asked for; a target
|
||||
/// without alerts in the window is left out.
|
||||
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
|
||||
pub targets: BTreeMap<String, Vec<CveDay>>,
|
||||
}
|
||||
|
||||
/// The days of a window of `days` days ending today (at least one), each
|
||||
/// with the instant it ends: the next day's midnight, UTC.
|
||||
pub fn window(now: DateTime<Utc>, days: u32) -> Vec<(NaiveDate, DateTime<Utc>)> {
|
||||
let today = now.date_naive();
|
||||
(0..days.max(1))
|
||||
.rev()
|
||||
.filter_map(|back| {
|
||||
let date = today.checked_sub_days(Days::new(u64::from(back)))?;
|
||||
let end = date.checked_add_days(Days::new(1))?.and_hms_opt(0, 0, 0)?;
|
||||
Some((date, end.and_utc()))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Whether `alert` was open just before `end`: found before it, not
|
||||
/// resolved and not settled by VEX by then. The fixed version is not
|
||||
/// checked here.
|
||||
pub fn open_before(alert: &CveAlert, end: DateTime<Utc>) -> bool {
|
||||
alert.created_at < end
|
||||
&& alert.resolved_at.is_none_or(|resolved| resolved >= end)
|
||||
&& !alert
|
||||
.vex
|
||||
.as_ref()
|
||||
.is_some_and(|vex| vex.status.resolves() && vex.at < end)
|
||||
}
|
||||
|
||||
/// The alerts with a fixed version, by target and CVE id, each with its
|
||||
/// severity class.
|
||||
fn by_target_and_cve(
|
||||
alerts: &[CveAlert],
|
||||
) -> HashMap<(&str, &str), Vec<(&CveAlert, NotificationSeverity)>> {
|
||||
let mut groups: HashMap<(&str, &str), Vec<_>> = HashMap::new();
|
||||
for alert in alerts.iter().filter(|a| !a.fixed_versions.is_empty()) {
|
||||
let severity = parse_severity(alert.severity.as_deref(), alert.cvss_score);
|
||||
groups
|
||||
.entry((alert.repo_id.as_str(), alert.cve()))
|
||||
.or_default()
|
||||
.push((alert, severity));
|
||||
}
|
||||
groups
|
||||
}
|
||||
|
||||
impl CveHistory {
|
||||
/// The history of `alerts` over `days` days ending today, with every
|
||||
/// target's series in [`Self::targets`].
|
||||
pub fn of(alerts: &[CveAlert], now: DateTime<Utc>, days: u32) -> Self {
|
||||
let window = window(now, days);
|
||||
let empty: Vec<CveDay> = window
|
||||
.iter()
|
||||
.map(|(date, _)| CveDay {
|
||||
date: *date,
|
||||
..CveDay::default()
|
||||
})
|
||||
.collect();
|
||||
let mut targets: BTreeMap<String, Vec<CveDay>> = BTreeMap::new();
|
||||
for ((repo_id, _), members) in by_target_and_cve(alerts) {
|
||||
let series = targets
|
||||
.entry(repo_id.to_string())
|
||||
.or_insert_with(|| empty.clone());
|
||||
for (day, (_, end)) in series.iter_mut().zip(&window) {
|
||||
let highest = members
|
||||
.iter()
|
||||
.filter(|(alert, _)| open_before(alert, *end))
|
||||
.map(|(_, severity)| severity)
|
||||
.max();
|
||||
if let Some(severity) = highest {
|
||||
day.count(severity);
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut total = empty;
|
||||
for series in targets.values() {
|
||||
for (sum, day) in total.iter_mut().zip(series) {
|
||||
sum.add(day);
|
||||
}
|
||||
}
|
||||
Self {
|
||||
days: total,
|
||||
open_findings: OpenFindings::default(),
|
||||
targets,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A package update and the open CVEs with a fix it closes, for a target's
|
||||
/// "Wo handeln" table.
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct TopUpdate {
|
||||
pub package: String,
|
||||
pub current_version: String,
|
||||
/// The highest version the alerts name as fixed.
|
||||
pub fixed_version: String,
|
||||
/// Open CVEs with a fix in this package and version.
|
||||
pub cves: u32,
|
||||
/// The critical ones among them.
|
||||
pub critical: u32,
|
||||
}
|
||||
|
||||
/// The updates of the packages with open CVEs (open at `now`, with a
|
||||
/// fixed version), the most CVEs closed first, then the most critical,
|
||||
/// then by name.
|
||||
pub fn top_updates(alerts: &[CveAlert], now: DateTime<Utc>) -> Vec<TopUpdate> {
|
||||
let Some((_, end)) = window(now, 1).pop() else {
|
||||
return Vec::new();
|
||||
};
|
||||
type Key<'a> = (&'a str, &'a str);
|
||||
let mut packages: HashMap<Key, (HashSet<&str>, HashSet<&str>, &str)> = HashMap::new();
|
||||
for alert in alerts
|
||||
.iter()
|
||||
.filter(|a| !a.fixed_versions.is_empty() && open_before(a, end))
|
||||
{
|
||||
let key = (
|
||||
alert.affected_package.as_str(),
|
||||
alert.affected_version.as_str(),
|
||||
);
|
||||
let (cves, critical, fixed) = packages.entry(key).or_default();
|
||||
cves.insert(alert.cve());
|
||||
if parse_severity(alert.severity.as_deref(), alert.cvss_score)
|
||||
== NotificationSeverity::Critical
|
||||
{
|
||||
critical.insert(alert.cve());
|
||||
}
|
||||
for version in &alert.fixed_versions {
|
||||
if fixed.is_empty() || cmp_dotted(version, fixed) == Ordering::Greater {
|
||||
*fixed = version;
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut updates: Vec<TopUpdate> = packages
|
||||
.into_iter()
|
||||
.map(|((package, current), (cves, critical, fixed))| TopUpdate {
|
||||
package: package.to_string(),
|
||||
current_version: current.to_string(),
|
||||
fixed_version: fixed.to_string(),
|
||||
cves: u32::try_from(cves.len()).unwrap_or(u32::MAX),
|
||||
critical: u32::try_from(critical.len()).unwrap_or(u32::MAX),
|
||||
})
|
||||
.collect();
|
||||
updates.sort_by(|a, b| {
|
||||
b.cves
|
||||
.cmp(&a.cves)
|
||||
.then_with(|| b.critical.cmp(&a.critical))
|
||||
.then_with(|| a.package.cmp(&b.package))
|
||||
.then_with(|| a.current_version.cmp(&b.current_version))
|
||||
});
|
||||
updates
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::models::vex::{VexAssessment, VexStatus};
|
||||
use crate::models::CveSource;
|
||||
use chrono::TimeZone;
|
||||
|
||||
/// 2026-11-10 14:00 UTC.
|
||||
fn now() -> DateTime<Utc> {
|
||||
Utc.with_ymd_and_hms(2026, 11, 10, 14, 0, 0).unwrap()
|
||||
}
|
||||
|
||||
fn at(day: u32, hour: u32) -> DateTime<Utc> {
|
||||
Utc.with_ymd_and_hms(2026, 11, day, hour, 0, 0).unwrap()
|
||||
}
|
||||
|
||||
fn alert(repo: &str, cve: &str, severity: &str, created: DateTime<Utc>) -> CveAlert {
|
||||
let mut a = CveAlert::new(
|
||||
cve.into(),
|
||||
repo.into(),
|
||||
"log4j-core".into(),
|
||||
"2.14.1".into(),
|
||||
CveSource::Osv,
|
||||
);
|
||||
a.severity = Some(severity.into());
|
||||
a.fixed_versions = vec!["2.17.1".into()];
|
||||
a.created_at = created;
|
||||
a
|
||||
}
|
||||
|
||||
fn settled(status: VexStatus, when: DateTime<Utc>) -> VexAssessment {
|
||||
VexAssessment {
|
||||
status,
|
||||
justification: None,
|
||||
impact_statement: None,
|
||||
action_statement: None,
|
||||
by: "u1".into(),
|
||||
by_name: None,
|
||||
at: when,
|
||||
by_scan: false,
|
||||
}
|
||||
}
|
||||
|
||||
/// The urgent (critical + high) count of each day, oldest first.
|
||||
fn urgent(days: &[CveDay]) -> Vec<u32> {
|
||||
days.iter().map(CveDay::urgent).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_window_ends_today_with_each_days_midnight() {
|
||||
let w = window(now(), 3);
|
||||
let dates: Vec<String> = w.iter().map(|(d, _)| d.to_string()).collect();
|
||||
assert_eq!(dates, ["2026-11-08", "2026-11-09", "2026-11-10"]);
|
||||
assert_eq!(w[2].1, at(11, 0));
|
||||
assert_eq!(window(now(), 0).len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_alert_never_resolved_is_open_from_the_day_it_was_found() {
|
||||
let h = CveHistory::of(
|
||||
&[alert("t1", "CVE-2021-44228", "CRITICAL", at(8, 23))],
|
||||
now(),
|
||||
4,
|
||||
);
|
||||
assert_eq!(urgent(&h.days), [0, 1, 1, 1]);
|
||||
assert_eq!(h.days[3].critical, 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_alert_resolved_on_a_day_no_longer_counts_on_that_day() {
|
||||
let mut found_and_gone = alert("t1", "CVE-2021-44228", "HIGH", at(9, 8));
|
||||
found_and_gone.resolved_at = Some(at(9, 17));
|
||||
let mut gone_later = alert("t1", "CVE-2021-45046", "HIGH", at(8, 8));
|
||||
gone_later.resolved_at = Some(at(10, 9));
|
||||
let h = CveHistory::of(&[found_and_gone, gone_later], now(), 3);
|
||||
assert_eq!(urgent(&h.days), [1, 1, 0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_alert_without_a_fixed_version_is_left_out() {
|
||||
let mut a = alert("t1", "CVE-2021-44228", "CRITICAL", at(8, 8));
|
||||
a.fixed_versions.clear();
|
||||
let h = CveHistory::of(&[a.clone()], now(), 3);
|
||||
assert_eq!(urgent(&h.days), [0, 0, 0]);
|
||||
assert!(h.targets.is_empty());
|
||||
assert!(top_updates(&[a], now()).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn one_cve_counts_once_per_target_at_its_highest_severity() {
|
||||
// The GHSA and its CVE alias, in two packages of one target.
|
||||
let mut ghsa = alert("t1", "GHSA-jfh8-c2jp-5v3q", "HIGH", at(8, 8));
|
||||
ghsa.aliases = vec!["CVE-2021-44228".into()];
|
||||
ghsa.affected_package = "log4j-api".into();
|
||||
let cve = alert("t1", "CVE-2021-44228", "CRITICAL", at(9, 8));
|
||||
// The same CVE in another target counts there too.
|
||||
let other = alert("t2", "CVE-2021-44228", "HIGH", at(8, 8));
|
||||
let h = CveHistory::of(&[ghsa, cve, other], now(), 3);
|
||||
assert_eq!(
|
||||
h.targets["t1"]
|
||||
.iter()
|
||||
.map(|d| (d.critical, d.high))
|
||||
.collect::<Vec<_>>(),
|
||||
[(0, 1), (1, 0), (1, 0)]
|
||||
);
|
||||
assert_eq!(urgent(&h.targets["t2"]), [1, 1, 1]);
|
||||
assert_eq!(urgent(&h.days), [2, 2, 2]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_vex_statement_settles_an_alert_from_when_it_was_made() {
|
||||
let mut not_affected = alert("t1", "CVE-2021-44228", "CRITICAL", at(8, 8));
|
||||
not_affected.vex = Some(settled(VexStatus::NotAffected, at(9, 12)));
|
||||
// Affected does not settle it.
|
||||
let mut affected = alert("t1", "CVE-2021-45046", "HIGH", at(8, 8));
|
||||
affected.vex = Some(settled(VexStatus::Affected, at(8, 9)));
|
||||
let h = CveHistory::of(&[not_affected, affected], now(), 3);
|
||||
assert_eq!(urgent(&h.days), [2, 1, 1]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn medium_and_low_are_counted_apart_from_the_urgent_ones() {
|
||||
let h = CveHistory::of(
|
||||
&[
|
||||
alert("t1", "GHSA-4jrv-ppp4-jm57", "MODERATE", at(10, 8)),
|
||||
alert("t1", "CVE-2020-0001", "LOW", at(10, 8)),
|
||||
],
|
||||
now(),
|
||||
1,
|
||||
);
|
||||
assert_eq!(
|
||||
(h.days[0].medium, h.days[0].low, h.days[0].urgent()),
|
||||
(1, 1, 0)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_update_closing_the_most_cves_comes_first_with_the_highest_fix() {
|
||||
let mut first = alert("t1", "CVE-2021-44228", "CRITICAL", at(8, 8));
|
||||
first.fixed_versions = vec!["2.15.0".into(), "2.12.2".into()];
|
||||
let mut second = alert("t1", "CVE-2021-45046", "CRITICAL", at(8, 8));
|
||||
second.fixed_versions = vec!["2.16.0".into()];
|
||||
// The GHSA of the first CVE: no extra CVE closed.
|
||||
let mut alias = alert("t1", "GHSA-jfh8-c2jp-5v3q", "CRITICAL", at(8, 8));
|
||||
alias.aliases = vec!["CVE-2021-44228".into()];
|
||||
alias.fixed_versions = vec!["2.17.1".into()];
|
||||
let mut gson = alert("t1", "CVE-2022-25647", "HIGH", at(8, 8));
|
||||
gson.affected_package = "gson".into();
|
||||
gson.affected_version = "2.8.8".into();
|
||||
gson.fixed_versions = vec!["2.8.9".into()];
|
||||
// Resolved: closes nothing any more.
|
||||
let mut gone = alert("t1", "CVE-2020-0002", "HIGH", at(8, 8));
|
||||
gone.affected_package = "jackson".into();
|
||||
gone.resolved_at = Some(at(9, 8));
|
||||
let updates = top_updates(&[gson, first, second, alias, gone], now());
|
||||
assert_eq!(
|
||||
updates,
|
||||
[
|
||||
TopUpdate {
|
||||
package: "log4j-core".into(),
|
||||
current_version: "2.14.1".into(),
|
||||
fixed_version: "2.17.1".into(),
|
||||
cves: 2,
|
||||
critical: 2,
|
||||
},
|
||||
TopUpdate {
|
||||
package: "gson".into(),
|
||||
current_version: "2.8.8".into(),
|
||||
fixed_version: "2.8.9".into(),
|
||||
cves: 1,
|
||||
critical: 0,
|
||||
},
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn equal_counts_rank_the_more_critical_update_first() {
|
||||
let high = alert("t1", "CVE-2020-0003", "HIGH", at(8, 8));
|
||||
let mut critical = alert("t1", "CVE-2020-0004", "CRITICAL", at(8, 8));
|
||||
critical.affected_package = "zlib".into();
|
||||
let names: Vec<String> = top_updates(&[high, critical], now())
|
||||
.into_iter()
|
||||
.map(|u| u.package)
|
||||
.collect();
|
||||
assert_eq!(names, ["zlib", "log4j-core"]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,442 @@
|
||||
//! A target's CVE alerts counted by severity and VEX status (#957): the grid
|
||||
//! the dashboard's "CVEs & VEX" view opens with, and the filter its cells
|
||||
//! narrow the CVE list to.
|
||||
//!
|
||||
//! The agent counts with [`CveCell::of`] and the dashboard filters the list
|
||||
//! with [`CveFilter::matches`], which buckets the same way, so a cell's
|
||||
//! number and the length of the list it opens cannot drift apart. Only
|
||||
//! alerts that are still reported count ([`counts`]): one a complete scan no
|
||||
//! longer found (`resolved_at` set) has left the grid.
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::models::{CveAlert, VexStatus};
|
||||
|
||||
/// A row of the grid: the advisory's severity, or `Unknown` when it names
|
||||
/// none.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum CveSeverity {
|
||||
Critical,
|
||||
High,
|
||||
Medium,
|
||||
Low,
|
||||
Unknown,
|
||||
}
|
||||
|
||||
impl CveSeverity {
|
||||
/// Every row, top to bottom.
|
||||
pub const ALL: [Self; 5] = [
|
||||
Self::Critical,
|
||||
Self::High,
|
||||
Self::Medium,
|
||||
Self::Low,
|
||||
Self::Unknown,
|
||||
];
|
||||
|
||||
/// The row of an alert rated `severity` by its advisory (`CRITICAL`,
|
||||
/// `MODERATE`, `low`; case does not matter), else by its CVSS base score
|
||||
/// `cvss`, else `Unknown`.
|
||||
///
|
||||
/// The advisory's word comes first because it is what the CVE list shows
|
||||
/// as the alert's badge; the score only fills in when the word is
|
||||
/// missing or not one of the four.
|
||||
pub fn of(severity: Option<&str>, cvss: Option<f64>) -> Self {
|
||||
let word = severity.map(|s| s.trim().to_ascii_lowercase());
|
||||
match word.as_deref() {
|
||||
Some("critical") => return Self::Critical,
|
||||
Some("high") => return Self::High,
|
||||
Some("medium" | "moderate") => return Self::Medium,
|
||||
Some("low") => return Self::Low,
|
||||
_ => {}
|
||||
}
|
||||
// Guards rather than range patterns on the `f64`, so that a `NaN`
|
||||
// score falls through to `Low` like every other score below 4.
|
||||
match cvss {
|
||||
Some(score) if score >= 9.0 => Self::Critical,
|
||||
Some(score) if score >= 7.0 => Self::High,
|
||||
Some(score) if score >= 4.0 => Self::Medium,
|
||||
Some(_) => Self::Low,
|
||||
None => Self::Unknown,
|
||||
}
|
||||
}
|
||||
|
||||
/// The row's name on the wire and in the dashboard's URL (`high`).
|
||||
pub const fn as_str(self) -> &'static str {
|
||||
match self {
|
||||
Self::Critical => "critical",
|
||||
Self::High => "high",
|
||||
Self::Medium => "medium",
|
||||
Self::Low => "low",
|
||||
Self::Unknown => "unknown",
|
||||
}
|
||||
}
|
||||
|
||||
/// The row named `name` by [`Self::as_str`].
|
||||
pub fn parse(name: &str) -> Option<Self> {
|
||||
Self::ALL.into_iter().find(|s| s.as_str() == name)
|
||||
}
|
||||
|
||||
/// The row's index in [`Self::ALL`].
|
||||
const fn index(self) -> usize {
|
||||
self as usize
|
||||
}
|
||||
}
|
||||
|
||||
/// A column of the grid: the alert's VEX statement, or `Open` while nobody
|
||||
/// (and no scan) has stated one.
|
||||
///
|
||||
/// Unlike [`crate::vex_docs::status_of`], which exports an alert without a
|
||||
/// statement as `under_investigation`, the grid tells the two apart: "open"
|
||||
/// is not looked at yet, "under investigation" is being looked at.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum VexColumn {
|
||||
Open,
|
||||
UnderInvestigation,
|
||||
Affected,
|
||||
NotAffected,
|
||||
Fixed,
|
||||
}
|
||||
|
||||
impl VexColumn {
|
||||
/// Every column, left to right.
|
||||
pub const ALL: [Self; 5] = [
|
||||
Self::Open,
|
||||
Self::UnderInvestigation,
|
||||
Self::Affected,
|
||||
Self::NotAffected,
|
||||
Self::Fixed,
|
||||
];
|
||||
|
||||
/// The column of an alert whose VEX statement has `status`, `None`
|
||||
/// without one.
|
||||
pub const fn of(status: Option<VexStatus>) -> Self {
|
||||
match status {
|
||||
None => Self::Open,
|
||||
Some(VexStatus::UnderInvestigation) => Self::UnderInvestigation,
|
||||
Some(VexStatus::Affected) => Self::Affected,
|
||||
Some(VexStatus::NotAffected) => Self::NotAffected,
|
||||
Some(VexStatus::Fixed) => Self::Fixed,
|
||||
}
|
||||
}
|
||||
|
||||
/// The column's name on the wire and in the dashboard's URL (`open`).
|
||||
pub const fn as_str(self) -> &'static str {
|
||||
match self {
|
||||
Self::Open => "open",
|
||||
Self::UnderInvestigation => "under_investigation",
|
||||
Self::Affected => "affected",
|
||||
Self::NotAffected => "not_affected",
|
||||
Self::Fixed => "fixed",
|
||||
}
|
||||
}
|
||||
|
||||
/// The column named `name` by [`Self::as_str`].
|
||||
pub fn parse(name: &str) -> Option<Self> {
|
||||
Self::ALL.into_iter().find(|v| v.as_str() == name)
|
||||
}
|
||||
|
||||
/// The column's index in [`Self::ALL`].
|
||||
const fn index(self) -> usize {
|
||||
self as usize
|
||||
}
|
||||
}
|
||||
|
||||
/// The cell of the grid an alert is counted in.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
pub struct CveCell {
|
||||
pub severity: CveSeverity,
|
||||
pub vex: VexColumn,
|
||||
}
|
||||
|
||||
impl CveCell {
|
||||
/// The cell of an alert rated `severity` / `cvss` with the VEX status
|
||||
/// `vex` (see [`CveSeverity::of`] and [`VexColumn::of`]).
|
||||
pub fn of(severity: Option<&str>, cvss: Option<f64>, vex: Option<VexStatus>) -> Self {
|
||||
Self {
|
||||
severity: CveSeverity::of(severity, cvss),
|
||||
vex: VexColumn::of(vex),
|
||||
}
|
||||
}
|
||||
|
||||
/// The cell `alert` is counted in.
|
||||
pub fn of_alert(alert: &CveAlert) -> Self {
|
||||
Self::of(
|
||||
alert.severity.as_deref(),
|
||||
alert.cvss_score,
|
||||
alert.vex.as_ref().map(|v| v.status),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `alert` is counted in the grid: still reported by the scans.
|
||||
pub fn counts(alert: &CveAlert) -> bool {
|
||||
alert.resolved_at.is_none()
|
||||
}
|
||||
|
||||
/// One non-empty cell of a [`CveMatrix`].
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct CveMatrixCell {
|
||||
pub severity: CveSeverity,
|
||||
pub vex: VexColumn,
|
||||
pub count: u64,
|
||||
}
|
||||
|
||||
/// A target's still-reported CVE alerts counted per [`CveCell`]. Only the
|
||||
/// non-empty cells are listed, rows top to bottom and columns left to right;
|
||||
/// every other cell counts 0.
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct CveMatrix {
|
||||
pub cells: Vec<CveMatrixCell>,
|
||||
}
|
||||
|
||||
impl CveMatrix {
|
||||
/// Count `cells`, one per alert.
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// ```
|
||||
/// use compliance_core::cve_matrix::{CveCell, CveMatrix, CveSeverity, VexColumn};
|
||||
///
|
||||
/// let high_open = CveCell::of(Some("HIGH"), None, None);
|
||||
/// let matrix = CveMatrix::from_cells([high_open, high_open]);
|
||||
/// assert_eq!(matrix.count(CveSeverity::High, VexColumn::Open), 2);
|
||||
/// ```
|
||||
pub fn from_cells(cells: impl IntoIterator<Item = CveCell>) -> Self {
|
||||
// A fixed 5 x 5 table: one pass, no hashing, and the output order
|
||||
// falls out of the index order.
|
||||
let mut table = [[0u64; VexColumn::ALL.len()]; CveSeverity::ALL.len()];
|
||||
for cell in cells {
|
||||
table[cell.severity.index()][cell.vex.index()] += 1;
|
||||
}
|
||||
let cells = CveSeverity::ALL
|
||||
.into_iter()
|
||||
.flat_map(|severity| {
|
||||
VexColumn::ALL.into_iter().map(move |vex| CveMatrixCell {
|
||||
severity,
|
||||
vex,
|
||||
count: table[severity.index()][vex.index()],
|
||||
})
|
||||
})
|
||||
.filter(|cell| cell.count > 0)
|
||||
.collect();
|
||||
Self { cells }
|
||||
}
|
||||
|
||||
/// How many alerts are in the cell of `severity` and `vex`.
|
||||
pub fn count(&self, severity: CveSeverity, vex: VexColumn) -> u64 {
|
||||
self.cells
|
||||
.iter()
|
||||
.find(|c| c.severity == severity && c.vex == vex)
|
||||
.map_or(0, |c| c.count)
|
||||
}
|
||||
|
||||
/// The largest count of a cell, 0 when there are none.
|
||||
pub fn max(&self) -> u64 {
|
||||
self.cells.iter().map(|c| c.count).max().unwrap_or(0)
|
||||
}
|
||||
|
||||
/// How many alerts are counted in all.
|
||||
pub fn total(&self) -> u64 {
|
||||
self.cells.iter().map(|c| c.count).sum()
|
||||
}
|
||||
|
||||
/// How many alerts nobody has assessed yet: the "open" column.
|
||||
pub fn unassessed(&self) -> u64 {
|
||||
self.cells
|
||||
.iter()
|
||||
.filter(|c| c.vex == VexColumn::Open)
|
||||
.map(|c| c.count)
|
||||
.sum()
|
||||
}
|
||||
|
||||
/// The rows the grid shows: the four severities, and "unknown" only
|
||||
/// when an alert has no severity.
|
||||
pub fn rows(&self) -> Vec<CveSeverity> {
|
||||
let has_unknown = self
|
||||
.cells
|
||||
.iter()
|
||||
.any(|c| c.severity == CveSeverity::Unknown);
|
||||
CveSeverity::ALL
|
||||
.into_iter()
|
||||
.filter(|s| *s != CveSeverity::Unknown || has_unknown)
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
|
||||
/// What a click in the grid narrows the CVE list to: a severity, a VEX
|
||||
/// column, or both; `None` leaves that side open. Either way only alerts the
|
||||
/// grid counts ([`counts`]) pass.
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
|
||||
pub struct CveFilter {
|
||||
pub severity: Option<CveSeverity>,
|
||||
pub vex: Option<VexColumn>,
|
||||
}
|
||||
|
||||
impl CveFilter {
|
||||
/// Whether `alert` is in the narrowed list.
|
||||
pub fn matches(&self, alert: &CveAlert) -> bool {
|
||||
if !counts(alert) {
|
||||
return false;
|
||||
}
|
||||
let cell = CveCell::of_alert(alert);
|
||||
self.severity.is_none_or(|s| s == cell.severity) && self.vex.is_none_or(|v| v == cell.vex)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::models::{CveSource, VexAssessment};
|
||||
|
||||
fn alert(severity: Option<&str>, cvss: Option<f64>, vex: Option<VexStatus>) -> CveAlert {
|
||||
CveAlert {
|
||||
id: None,
|
||||
cve_id: "CVE-2024-0001".to_string(),
|
||||
repo_id: "t1".to_string(),
|
||||
affected_package: "openssl".to_string(),
|
||||
affected_version: "3.0.0".to_string(),
|
||||
purl: None,
|
||||
source: CveSource::Osv,
|
||||
severity: severity.map(String::from),
|
||||
cvss_score: cvss,
|
||||
summary: None,
|
||||
llm_impact_summary: None,
|
||||
references: Vec::new(),
|
||||
aliases: Vec::new(),
|
||||
fixed_versions: Vec::new(),
|
||||
exploitation: None,
|
||||
advisories: Vec::new(),
|
||||
vex: vex.map(|status| VexAssessment {
|
||||
status,
|
||||
justification: None,
|
||||
impact_statement: None,
|
||||
action_statement: None,
|
||||
by: "u1".to_string(),
|
||||
by_name: None,
|
||||
at: chrono::Utc::now(),
|
||||
by_scan: false,
|
||||
}),
|
||||
resolved_at: None,
|
||||
exploited_seen_at: None,
|
||||
created_at: chrono::Utc::now(),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_advisory_word_picks_the_row_in_any_case() {
|
||||
assert_eq!(
|
||||
CveSeverity::of(Some("CRITICAL"), None),
|
||||
CveSeverity::Critical
|
||||
);
|
||||
assert_eq!(CveSeverity::of(Some("high"), None), CveSeverity::High);
|
||||
assert_eq!(CveSeverity::of(Some("MODERATE"), None), CveSeverity::Medium);
|
||||
assert_eq!(CveSeverity::of(Some(" Medium "), None), CveSeverity::Medium);
|
||||
assert_eq!(CveSeverity::of(Some("low"), Some(9.8)), CveSeverity::Low);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_cvss_score_fills_in_a_missing_or_odd_word() {
|
||||
assert_eq!(CveSeverity::of(None, Some(9.0)), CveSeverity::Critical);
|
||||
assert_eq!(
|
||||
CveSeverity::of(Some("important"), Some(8.1)),
|
||||
CveSeverity::High
|
||||
);
|
||||
assert_eq!(CveSeverity::of(None, Some(4.0)), CveSeverity::Medium);
|
||||
assert_eq!(CveSeverity::of(None, Some(3.9)), CveSeverity::Low);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn without_word_or_score_the_severity_is_unknown() {
|
||||
assert_eq!(CveSeverity::of(None, None), CveSeverity::Unknown);
|
||||
assert_eq!(CveSeverity::of(Some("unrated"), None), CveSeverity::Unknown);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_statement_is_open_and_each_status_has_its_column() {
|
||||
assert_eq!(VexColumn::of(None), VexColumn::Open);
|
||||
assert_eq!(
|
||||
VexColumn::of(Some(VexStatus::UnderInvestigation)),
|
||||
VexColumn::UnderInvestigation
|
||||
);
|
||||
assert_eq!(
|
||||
VexColumn::of(Some(VexStatus::Affected)),
|
||||
VexColumn::Affected
|
||||
);
|
||||
assert_eq!(
|
||||
VexColumn::of(Some(VexStatus::NotAffected)),
|
||||
VexColumn::NotAffected
|
||||
);
|
||||
assert_eq!(VexColumn::of(Some(VexStatus::Fixed)), VexColumn::Fixed);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn names_round_trip_and_match_the_wire() {
|
||||
for severity in CveSeverity::ALL {
|
||||
assert_eq!(CveSeverity::parse(severity.as_str()), Some(severity));
|
||||
assert_eq!(
|
||||
serde_json::to_value(severity).ok(),
|
||||
Some(serde_json::Value::from(severity.as_str()))
|
||||
);
|
||||
}
|
||||
for vex in VexColumn::ALL {
|
||||
assert_eq!(VexColumn::parse(vex.as_str()), Some(vex));
|
||||
assert_eq!(
|
||||
serde_json::to_value(vex).ok(),
|
||||
Some(serde_json::Value::from(vex.as_str()))
|
||||
);
|
||||
}
|
||||
assert_eq!(CveSeverity::parse("hoch"), None);
|
||||
assert_eq!(VexColumn::parse(""), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_matrix_counts_each_cell_and_lists_only_non_empty_ones() {
|
||||
let high_open = CveCell::of(Some("HIGH"), None, None);
|
||||
let low_fixed = CveCell::of(Some("LOW"), None, Some(VexStatus::Fixed));
|
||||
let matrix = CveMatrix::from_cells([high_open, low_fixed, high_open]);
|
||||
assert_eq!(matrix.cells.len(), 2);
|
||||
assert_eq!(matrix.cells[0].severity, CveSeverity::High);
|
||||
assert_eq!(matrix.count(CveSeverity::High, VexColumn::Open), 2);
|
||||
assert_eq!(matrix.count(CveSeverity::Low, VexColumn::Fixed), 1);
|
||||
assert_eq!(matrix.count(CveSeverity::Critical, VexColumn::Open), 0);
|
||||
assert_eq!(
|
||||
(matrix.max(), matrix.total(), matrix.unassessed()),
|
||||
(2, 3, 2)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_unknown_row_shows_only_when_an_alert_has_no_severity() {
|
||||
let rated = CveMatrix::from_cells([CveCell::of(Some("high"), None, None)]);
|
||||
assert_eq!(rated.rows().len(), 4);
|
||||
let unrated = CveMatrix::from_cells([CveCell::of(None, None, None)]);
|
||||
assert_eq!(unrated.rows().last(), Some(&CveSeverity::Unknown));
|
||||
assert_eq!(CveMatrix::default().rows().len(), 4);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_filter_passes_its_cell_and_never_a_resolved_alert() {
|
||||
let high_open = alert(Some("HIGH"), None, None);
|
||||
let high_affected = alert(Some("HIGH"), None, Some(VexStatus::Affected));
|
||||
let mut resolved = high_open.clone();
|
||||
resolved.resolved_at = Some(chrono::Utc::now());
|
||||
|
||||
let cell = CveFilter {
|
||||
severity: Some(CveSeverity::High),
|
||||
vex: Some(VexColumn::Open),
|
||||
};
|
||||
assert!(cell.matches(&high_open));
|
||||
assert!(!cell.matches(&high_affected));
|
||||
assert!(!cell.matches(&resolved));
|
||||
|
||||
let all_open = CveFilter {
|
||||
severity: None,
|
||||
vex: Some(VexColumn::Open),
|
||||
};
|
||||
assert!(all_open.matches(&high_open));
|
||||
assert!(CveFilter::default().matches(&high_affected));
|
||||
assert!(!CveFilter::default().matches(&resolved));
|
||||
}
|
||||
}
|
||||
@@ -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<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);
|
||||
}
|
||||
}
|
||||
@@ -1,13 +1,18 @@
|
||||
pub mod build_info;
|
||||
pub mod component_changes;
|
||||
pub mod config;
|
||||
pub mod control_check;
|
||||
pub mod csaf_docs;
|
||||
pub mod csaf_ingest;
|
||||
pub mod cve_groups;
|
||||
pub mod cve_history;
|
||||
pub mod cve_matrix;
|
||||
pub mod db;
|
||||
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;
|
||||
@@ -15,6 +20,8 @@ pub mod models;
|
||||
pub mod net_guard;
|
||||
pub mod purl;
|
||||
pub mod sbom_docs;
|
||||
pub mod sbom_ecosystems;
|
||||
pub mod scan_changes;
|
||||
pub mod scan_matrix;
|
||||
pub mod spdx_license;
|
||||
#[cfg(feature = "telemetry")]
|
||||
|
||||
@@ -93,6 +93,10 @@ pub struct StatusChange {
|
||||
/// which run.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub scan: Option<ScanStatusChange>,
|
||||
/// Set when the finding's issue was closed or reopened in the issue
|
||||
/// tracker (#953); `by_name` is the tracker user who did it.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub tracker: Option<TrackerChangeKind>,
|
||||
}
|
||||
|
||||
impl StatusChange {
|
||||
@@ -118,8 +122,45 @@ impl StatusChange {
|
||||
kind,
|
||||
scan_run_id: scan_run_id.to_string(),
|
||||
}),
|
||||
tracker: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The `by` of every change carried over from the issue tracker.
|
||||
pub const TRACKER_ACTOR: &'static str = "pruefwerk-tracker";
|
||||
|
||||
/// A change carried over from the issue tracker, where the user `login`
|
||||
/// closed or reopened the finding's issue.
|
||||
///
|
||||
/// # Arguments
|
||||
///
|
||||
/// * `status` - the status the finding moves to
|
||||
/// * `kind` - what happened to the issue
|
||||
/// * `login` - the tracker user who did it, shown as who changed it
|
||||
pub fn by_tracker(status: FindingStatus, kind: TrackerChangeKind, login: &str) -> Self {
|
||||
Self {
|
||||
status,
|
||||
by: Self::TRACKER_ACTOR.to_string(),
|
||||
by_name: Some(login.to_string()),
|
||||
support: false,
|
||||
at: Utc::now(),
|
||||
reason: None,
|
||||
scan: None,
|
||||
tracker: Some(kind),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What happened to a finding's issue in the issue tracker that changed the
|
||||
/// finding's status.
|
||||
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum TrackerChangeKind {
|
||||
/// A person closed the issue: the finding counts as resolved until a
|
||||
/// scan finds it again.
|
||||
ClosedInTracker,
|
||||
/// A person reopened the issue: the finding is undecided again.
|
||||
ReopenedInTracker,
|
||||
}
|
||||
|
||||
/// Why a scan changed a finding's status.
|
||||
@@ -305,10 +346,156 @@ impl Finding {
|
||||
}
|
||||
}
|
||||
|
||||
/// `triage_action` of a finding the LLM triage judged a false alarm.
|
||||
pub const TRIAGE_DISMISS: &str = "dismiss";
|
||||
/// `triage_action` of a finding the LLM triage gave no verdict; the reason is
|
||||
/// in `triage_rationale`, which starts with `skipped: <reason>`.
|
||||
pub const TRIAGE_SKIPPED: &str = "skipped";
|
||||
/// `triage_action` of a finding the control check did not confirm against the
|
||||
/// CRA requirements it maps to.
|
||||
pub const TRIAGE_CONTROL_NOT_CONFIRMED: &str = "control_not_confirmed";
|
||||
/// Least confidence (0-10, as stored in `confidence`) at which the LLM triage
|
||||
/// takes a confirmed finding as triaged; below it the finding needs review.
|
||||
pub const TRIAGE_CONFIDENCE_THRESHOLD: f64 = 3.0;
|
||||
|
||||
/// Why the LLM triage left a finding to a person ([`FindingStatus::NeedsReview`]).
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum ReviewReason {
|
||||
/// The model dismissed the finding as a likely false alarm.
|
||||
LikelyFalseAlarm,
|
||||
/// The model confirmed the finding, but with too little confidence.
|
||||
Unsure,
|
||||
}
|
||||
|
||||
impl ReviewReason {
|
||||
/// Why a verdict of the model leaves a finding to a person; `None` when
|
||||
/// the verdict decides it (confirmed, downgraded or upgraded).
|
||||
///
|
||||
/// # Arguments
|
||||
///
|
||||
/// * `action` - the model's action (`confirm`, `dismiss`, ...); an unknown
|
||||
/// one counts as `confirm`
|
||||
/// * `confidence` - the model's confidence, as stored in `confidence`
|
||||
pub fn of_verdict(action: &str, confidence: f64) -> Option<Self> {
|
||||
match action {
|
||||
TRIAGE_DISMISS => Some(Self::LikelyFalseAlarm),
|
||||
"downgrade" | "upgrade" => None,
|
||||
_ if confidence < TRIAGE_CONFIDENCE_THRESHOLD => Some(Self::Unsure),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Finding {
|
||||
/// Why the LLM triage left this finding to a person, read from its stored
|
||||
/// verdict (`triage_action`, `confidence`); `None` unless it needs review
|
||||
/// because of that verdict (also when the triage skipped it or the control
|
||||
/// check put it there).
|
||||
pub fn review_reason(&self) -> Option<ReviewReason> {
|
||||
if self.status != FindingStatus::NeedsReview {
|
||||
return None;
|
||||
}
|
||||
match self.triage_action.as_deref()? {
|
||||
TRIAGE_SKIPPED | TRIAGE_CONTROL_NOT_CONFIRMED => None,
|
||||
action => ReviewReason::of_verdict(action, self.confidence?),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// A finding as the LLM triage leaves it.
|
||||
fn reviewed(status: FindingStatus, action: &str, confidence: Option<f64>) -> Finding {
|
||||
let mut finding = Finding::new(
|
||||
"repo".to_string(),
|
||||
"fp".to_string(),
|
||||
"semgrep".to_string(),
|
||||
ScanType::Sast,
|
||||
"title".to_string(),
|
||||
"description".to_string(),
|
||||
Severity::High,
|
||||
);
|
||||
finding.status = status;
|
||||
finding.triage_action = Some(action.to_string());
|
||||
finding.confidence = confidence;
|
||||
finding
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_dismissed_finding_needs_review_as_a_likely_false_alarm() {
|
||||
let finding = reviewed(FindingStatus::NeedsReview, TRIAGE_DISMISS, Some(9.0));
|
||||
assert_eq!(
|
||||
finding.review_reason(),
|
||||
Some(ReviewReason::LikelyFalseAlarm)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_confirmation_below_the_threshold_is_unsure() {
|
||||
let unsure = reviewed(FindingStatus::NeedsReview, "confirm", Some(2.9));
|
||||
assert_eq!(unsure.review_reason(), Some(ReviewReason::Unsure));
|
||||
// An unknown action counts as a confirmation, as in the triage.
|
||||
let unknown = reviewed(FindingStatus::NeedsReview, "keep", Some(1.0));
|
||||
assert_eq!(unknown.review_reason(), Some(ReviewReason::Unsure));
|
||||
let sure = reviewed(FindingStatus::NeedsReview, "confirm", Some(3.0));
|
||||
assert_eq!(sure.review_reason(), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_a_finding_that_needs_review_has_a_reason() {
|
||||
let decided = reviewed(FindingStatus::FalsePositive, TRIAGE_DISMISS, Some(9.0));
|
||||
assert_eq!(decided.review_reason(), None);
|
||||
let triaged = reviewed(FindingStatus::Triaged, "confirm", Some(1.0));
|
||||
assert_eq!(triaged.review_reason(), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_finding_the_model_did_not_put_up_for_review_has_no_reason() {
|
||||
let mut untriaged = reviewed(FindingStatus::NeedsReview, "confirm", Some(1.0));
|
||||
untriaged.triage_action = None;
|
||||
assert_eq!(untriaged.review_reason(), None);
|
||||
// The control check keeps the model's confidence: it is not the reason.
|
||||
let control = reviewed(
|
||||
FindingStatus::NeedsReview,
|
||||
TRIAGE_CONTROL_NOT_CONFIRMED,
|
||||
Some(1.0),
|
||||
);
|
||||
assert_eq!(control.review_reason(), None);
|
||||
let skipped = reviewed(FindingStatus::NeedsReview, TRIAGE_SKIPPED, Some(0.5));
|
||||
assert_eq!(skipped.review_reason(), None);
|
||||
let no_confidence = reviewed(FindingStatus::NeedsReview, "confirm", None);
|
||||
assert_eq!(no_confidence.review_reason(), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_change_of_severity_decides_the_finding() {
|
||||
assert_eq!(ReviewReason::of_verdict("downgrade", 0.0), None);
|
||||
assert_eq!(ReviewReason::of_verdict("upgrade", 0.0), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_tracker_change_names_the_tracker_user_and_no_scan() {
|
||||
let change = StatusChange::by_tracker(
|
||||
FindingStatus::Resolved,
|
||||
TrackerChangeKind::ClosedInTracker,
|
||||
"dev-anna",
|
||||
);
|
||||
assert_eq!(change.by, StatusChange::TRACKER_ACTOR);
|
||||
assert_eq!(change.by_name.as_deref(), Some("dev-anna"));
|
||||
let wire = serde_json::to_value(&change).unwrap_or_default();
|
||||
assert_eq!(wire["tracker"], "closed_in_tracker");
|
||||
assert!(wire.get("scan").is_none());
|
||||
// A change stored before #953 has no `tracker` and still reads.
|
||||
let mut old = wire.clone();
|
||||
if let Some(o) = old.as_object_mut() {
|
||||
o.remove("tracker");
|
||||
}
|
||||
let back: Option<StatusChange> = serde_json::from_value(old).ok();
|
||||
assert!(back.is_some_and(|c| c.tracker.is_none()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn needs_review_reads_and_writes_as_needs_review() {
|
||||
let wire = serde_json::to_string(&FindingStatus::NeedsReview).unwrap_or_default();
|
||||
|
||||
@@ -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<String>,
|
||||
}
|
||||
|
||||
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<String>,
|
||||
}
|
||||
|
||||
/// 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<GroupReview>,
|
||||
/// The findings, by file and line.
|
||||
pub members: Vec<Finding>,
|
||||
}
|
||||
|
||||
impl FindingGroup {
|
||||
/// The group of `members` (at least one) under `key`.
|
||||
fn new(key: GroupKey, mut members: Vec<Finding>) -> 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<ObjectId> {
|
||||
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<AiReview> {
|
||||
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<GroupReview> {
|
||||
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<Option<String>, Vec<Finding>>;
|
||||
|
||||
/// 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<Item = Finding>) -> Vec<FindingGroup> {
|
||||
let mut groups = Vec::new();
|
||||
let mut by_rule: HashMap<RuleInTarget, ByFile> = 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<String> = files_per_dir
|
||||
.into_iter()
|
||||
.filter(|(_, files)| *files >= DIRECTORY_MIN_FILES)
|
||||
.map(|(dir, _)| dir.to_string())
|
||||
.collect();
|
||||
|
||||
let mut by_dir: BTreeMap<String, Vec<Finding>> = 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<Item = Finding>, key: &GroupKey) -> Vec<ObjectId> {
|
||||
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::<GroupKey>(wire).ok().as_ref(),
|
||||
Some(&key)
|
||||
);
|
||||
assert_ne!(
|
||||
key.id(),
|
||||
GroupKey {
|
||||
scope: GroupScope::File,
|
||||
..key.clone()
|
||||
}
|
||||
.id()
|
||||
);
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -41,6 +41,49 @@ impl std::fmt::Display for IssueStatus {
|
||||
}
|
||||
}
|
||||
|
||||
impl IssueStatus {
|
||||
/// Every status, open ones first.
|
||||
pub const ALL: [Self; 4] = [Self::Open, Self::InProgress, Self::Closed, Self::Resolved];
|
||||
|
||||
/// Whether the ticket is done (closed or resolved); the other two are
|
||||
/// open.
|
||||
pub fn is_closed(&self) -> bool {
|
||||
match self {
|
||||
Self::Closed | Self::Resolved => true,
|
||||
Self::Open | Self::InProgress => false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What a ticket is about, as its `finding_id` says.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum IssueSubject<'a> {
|
||||
/// One finding, by its id (the hex of its `ObjectId`).
|
||||
Finding(&'a str),
|
||||
/// A known vulnerability in one target's components, by the target id.
|
||||
Cve {
|
||||
/// The target (repository) the CVE was found in.
|
||||
target_id: &'a str,
|
||||
},
|
||||
}
|
||||
|
||||
/// What the `finding_id` of a CVE ticket starts with.
|
||||
const CVE_KEY: &str = "cve:";
|
||||
|
||||
/// The start of the `finding_id` of every CVE ticket of one target. The whole
|
||||
/// key is `cve:{target_id}:{package}:{cve}`: one ticket per target, package
|
||||
/// and CVE.
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// ```
|
||||
/// use compliance_core::models::issue::cve_issue_prefix;
|
||||
/// assert_eq!(cve_issue_prefix("abc"), "cve:abc:");
|
||||
/// ```
|
||||
pub fn cve_issue_prefix(target_id: &str) -> String {
|
||||
format!("{CVE_KEY}{target_id}:")
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct TrackerIssue {
|
||||
#[serde(rename = "_id", skip_serializing_if = "Option::is_none")]
|
||||
@@ -51,6 +94,10 @@ pub struct TrackerIssue {
|
||||
pub external_url: String,
|
||||
pub title: String,
|
||||
pub status: IssueStatus,
|
||||
/// The tracker user who closed the issue there (#953), while it stays
|
||||
/// closed: a person's decision the scan does not undo on its own.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub closed_in_tracker: Option<String>,
|
||||
#[serde(with = "super::serde_helpers::bson_datetime")]
|
||||
pub created_at: DateTime<Utc>,
|
||||
#[serde(with = "super::serde_helpers::bson_datetime")]
|
||||
@@ -74,8 +121,75 @@ impl TrackerIssue {
|
||||
external_url,
|
||||
title,
|
||||
status: IssueStatus::Open,
|
||||
closed_in_tracker: None,
|
||||
created_at: now,
|
||||
updated_at: now,
|
||||
}
|
||||
}
|
||||
|
||||
/// What the ticket is about: its finding, or for a CVE ticket the target
|
||||
/// the CVE is in. `None` when `finding_id` is neither (empty, for an
|
||||
/// issue whose finding had no id).
|
||||
pub fn subject(&self) -> Option<IssueSubject<'_>> {
|
||||
if let Some(rest) = self.finding_id.strip_prefix(CVE_KEY) {
|
||||
// `rest` is `{target_id}:{package}:{cve}`; `split` always yields
|
||||
// a first piece, so only an empty one is refused.
|
||||
return rest
|
||||
.split(':')
|
||||
.next()
|
||||
.filter(|id| !id.is_empty())
|
||||
.map(|target_id| IssueSubject::Cve { target_id });
|
||||
}
|
||||
let id = self.finding_id.as_str();
|
||||
(id.len() == 24 && id.bytes().all(|b| b.is_ascii_hexdigit()))
|
||||
.then_some(IssueSubject::Finding(id))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn issue(finding_id: &str) -> TrackerIssue {
|
||||
TrackerIssue::new(
|
||||
finding_id.to_string(),
|
||||
TrackerType::Gitea,
|
||||
"913".into(),
|
||||
"https://gitea.invalid/o/r/issues/913".into(),
|
||||
"[high] semgrep: hardcoded key".into(),
|
||||
)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_finding_ticket_is_about_its_finding() {
|
||||
let id = "65a1b2c3d4e5f60718293a4b";
|
||||
assert_eq!(issue(id).subject(), Some(IssueSubject::Finding(id)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_cve_ticket_is_about_its_target() {
|
||||
let key = format!("{}openssl:CVE-2024-0001", cve_issue_prefix("tgt1"));
|
||||
assert_eq!(
|
||||
issue(&key).subject(),
|
||||
Some(IssueSubject::Cve { target_id: "tgt1" })
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_ticket_without_a_usable_id_is_about_nothing() {
|
||||
assert_eq!(issue("").subject(), None);
|
||||
assert_eq!(issue("cve::pkg:CVE-1").subject(), None);
|
||||
assert_eq!(issue("not-an-object-id").subject(), None);
|
||||
// The right length, but not hex.
|
||||
assert_eq!(issue("zzzzzzzzzzzzzzzzzzzzzzzz").subject(), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn closed_and_resolved_are_closed() {
|
||||
let closed: Vec<IssueStatus> = IssueStatus::ALL
|
||||
.into_iter()
|
||||
.filter(IssueStatus::is_closed)
|
||||
.collect();
|
||||
assert_eq!(closed, [IssueStatus::Closed, IssueStatus::Resolved]);
|
||||
}
|
||||
}
|
||||
@@ -351,6 +351,93 @@ pub fn apply(entries: &mut [SbomEntry], conclusions: &[LicenseConclusion]) {
|
||||
}
|
||||
}
|
||||
|
||||
/// The four groups the licence chart of a target shows (#957), coarser than
|
||||
/// [`LicenseCategory`]. Declared in chart order, from least to most to
|
||||
/// look at; the order is also the index into [`LicenseGroupCounts`].
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
||||
pub enum LicenseGroup {
|
||||
/// Public domain, permissive and own code.
|
||||
Permissive,
|
||||
/// LGPL, MPL, EPL, CDDL and the like.
|
||||
WeakCopyleft,
|
||||
/// GPL, and network copyleft (AGPL).
|
||||
StrongCopyleft,
|
||||
/// No licence, one SPDX cannot read, or a proprietary one: a person has
|
||||
/// to look at it.
|
||||
Unknown,
|
||||
}
|
||||
|
||||
impl LicenseGroup {
|
||||
/// Every group, in chart order.
|
||||
pub const ALL: [Self; 4] = [
|
||||
Self::Permissive,
|
||||
Self::WeakCopyleft,
|
||||
Self::StrongCopyleft,
|
||||
Self::Unknown,
|
||||
];
|
||||
}
|
||||
|
||||
impl LicenseCategory {
|
||||
/// The chart group of this category. A proprietary licence is neither
|
||||
/// open source nor copyleft, so it is grouped with the unknown ones: its
|
||||
/// terms are a contract a person has to read.
|
||||
pub fn group(self) -> LicenseGroup {
|
||||
match self {
|
||||
Self::PublicDomain | Self::Permissive | Self::OwnCode => LicenseGroup::Permissive,
|
||||
Self::WeakCopyleft => LicenseGroup::WeakCopyleft,
|
||||
Self::StrongCopyleft | Self::NetworkCopyleft => LicenseGroup::StrongCopyleft,
|
||||
Self::Proprietary | Self::Unclear => LicenseGroup::Unknown,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// How many components fall into each [`LicenseGroup`].
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// ```
|
||||
/// use compliance_core::models::license::{LicenseGroup, LicenseGroupCounts};
|
||||
/// use compliance_core::models::LicenseCategory;
|
||||
///
|
||||
/// let counts: LicenseGroupCounts = [
|
||||
/// (LicenseCategory::Permissive, 3),
|
||||
/// (LicenseCategory::PublicDomain, 1),
|
||||
/// (LicenseCategory::NetworkCopyleft, 2),
|
||||
/// ]
|
||||
/// .into_iter()
|
||||
/// .collect();
|
||||
/// assert_eq!(counts.get(LicenseGroup::Permissive), 4);
|
||||
/// assert_eq!(counts.get(LicenseGroup::StrongCopyleft), 2);
|
||||
/// assert_eq!(counts.total(), 6);
|
||||
/// ```
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
|
||||
pub struct LicenseGroupCounts([u64; 4]);
|
||||
|
||||
impl LicenseGroupCounts {
|
||||
/// The components in `group`.
|
||||
pub fn get(self, group: LicenseGroup) -> u64 {
|
||||
// A field-less enum casts to its position (`Permissive` is 0).
|
||||
self.0[group as usize]
|
||||
}
|
||||
|
||||
/// The components in every group.
|
||||
pub fn total(self) -> u64 {
|
||||
self.0.iter().sum()
|
||||
}
|
||||
}
|
||||
|
||||
/// Counts from `(category, components)` pairs, such as the rows of the
|
||||
/// licence summary.
|
||||
impl FromIterator<(LicenseCategory, u64)> for LicenseGroupCounts {
|
||||
fn from_iter<I: IntoIterator<Item = (LicenseCategory, u64)>>(rows: I) -> Self {
|
||||
let mut counts = Self::default();
|
||||
for (category, count) in rows {
|
||||
counts.0[category.group() as usize] += count;
|
||||
}
|
||||
counts
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -481,4 +568,98 @@ mod tests {
|
||||
assert!(LicenseCategory::WeakCopyleft.is_copyleft());
|
||||
assert!(!LicenseCategory::Proprietary.is_copyleft());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_category_falls_into_one_chart_group() {
|
||||
use LicenseCategory as C;
|
||||
use LicenseGroup as G;
|
||||
for (category, group) in [
|
||||
(C::PublicDomain, G::Permissive),
|
||||
(C::Permissive, G::Permissive),
|
||||
(C::OwnCode, G::Permissive),
|
||||
(C::WeakCopyleft, G::WeakCopyleft),
|
||||
(C::StrongCopyleft, G::StrongCopyleft),
|
||||
(C::NetworkCopyleft, G::StrongCopyleft),
|
||||
(C::Proprietary, G::Unknown),
|
||||
(C::Unclear, G::Unknown),
|
||||
] {
|
||||
assert_eq!(category.group(), group, "{category:?}");
|
||||
}
|
||||
// Every group is reached, and copyleft groups hold only copyleft.
|
||||
for group in LicenseGroup::ALL {
|
||||
let members: Vec<_> = LicenseCategory::ALL
|
||||
.into_iter()
|
||||
.filter(|c| c.group() == group)
|
||||
.collect();
|
||||
assert!(!members.is_empty(), "{group:?} is empty");
|
||||
let copyleft = matches!(group, G::WeakCopyleft | G::StrongCopyleft);
|
||||
assert!(members.iter().all(|c| c.is_copyleft() == copyleft));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn licence_expressions_fall_into_the_group_of_their_category() {
|
||||
use crate::spdx_license::category;
|
||||
use LicenseGroup as G;
|
||||
for (license, group) in [
|
||||
("MIT", G::Permissive),
|
||||
("Apache-2.0", G::Permissive),
|
||||
("BSD-3-Clause", G::Permissive),
|
||||
("CC0-1.0", G::Permissive),
|
||||
("The Apache Software License, Version 2.0", G::Permissive),
|
||||
("LGPL-2.1-or-later", G::WeakCopyleft),
|
||||
("MPL-2.0", G::WeakCopyleft),
|
||||
("EPL-2.0", G::WeakCopyleft),
|
||||
("CDDL-1.0", G::WeakCopyleft),
|
||||
("GPL-3.0-only", G::StrongCopyleft),
|
||||
("GPL-2.0+", G::StrongCopyleft),
|
||||
("AGPL-3.0-or-later", G::StrongCopyleft),
|
||||
// `OR`: the most permissive choice counts.
|
||||
("MIT OR GPL-3.0-only", G::Permissive),
|
||||
("(LGPL-2.1-only OR GPL-2.0-only)", G::WeakCopyleft),
|
||||
// `AND`: the most restrictive term counts.
|
||||
("MIT AND GPL-2.0-only", G::StrongCopyleft),
|
||||
("Apache-2.0 AND MPL-2.0", G::WeakCopyleft),
|
||||
// An exception after `WITH` keeps the licence's category (the
|
||||
// licence policy, #570, reads it the same way).
|
||||
(
|
||||
"GPL-2.0-only WITH Classpath-exception-2.0",
|
||||
G::StrongCopyleft,
|
||||
),
|
||||
("Apache-2.0 WITH LLVM-exception", G::Permissive),
|
||||
// Nothing a person could rely on.
|
||||
("", G::Unknown),
|
||||
("NOASSERTION", G::Unknown),
|
||||
("NONE", G::Unknown),
|
||||
("LicenseRef-Pump-EULA", G::Unknown),
|
||||
("Custom Pump License", G::Unknown),
|
||||
("MIT AND LicenseRef-Pump-EULA", G::Unknown),
|
||||
] {
|
||||
assert_eq!(category(license).group(), group, "{license}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn group_counts_add_up_the_rows_of_each_group() {
|
||||
use LicenseCategory as C;
|
||||
let counts: LicenseGroupCounts = [
|
||||
(C::Permissive, 10),
|
||||
(C::OwnCode, 2),
|
||||
(C::WeakCopyleft, 3),
|
||||
(C::StrongCopyleft, 40),
|
||||
(C::NetworkCopyleft, 9),
|
||||
(C::Unclear, 5),
|
||||
(C::Proprietary, 1),
|
||||
]
|
||||
.into_iter()
|
||||
.collect();
|
||||
assert_eq!(counts.get(LicenseGroup::Permissive), 12);
|
||||
assert_eq!(counts.get(LicenseGroup::WeakCopyleft), 3);
|
||||
assert_eq!(counts.get(LicenseGroup::StrongCopyleft), 49);
|
||||
assert_eq!(counts.get(LicenseGroup::Unknown), 6);
|
||||
assert_eq!(counts.total(), 70);
|
||||
let empty: LicenseGroupCounts = std::iter::empty().collect();
|
||||
assert_eq!(empty, LicenseGroupCounts::default());
|
||||
assert_eq!(empty.total(), 0);
|
||||
}
|
||||
}
|
||||
@@ -6,8 +6,10 @@ 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 inbox;
|
||||
pub mod issue;
|
||||
pub mod license;
|
||||
pub mod license_policy;
|
||||
@@ -45,13 +47,14 @@ pub use exclude_paths::{
|
||||
normalise_exclude_paths, ExcludePathError, MAX_EXCLUDE_PATHS, MAX_EXCLUDE_PATH_LEN,
|
||||
};
|
||||
pub use finding::{
|
||||
Finding, FindingStatus, Occurrence, ScanChangeKind, ScanStatusChange, Severity, StatusChange,
|
||||
Finding, FindingStatus, Occurrence, ReviewReason, ScanChangeKind, ScanStatusChange, Severity,
|
||||
StatusChange, TrackerChangeKind,
|
||||
};
|
||||
pub use git_source::{GitSource, GitSourceView, SourceRepo, GIT_SOURCE_ID};
|
||||
pub use graph::{
|
||||
CodeEdge, CodeEdgeKind, CodeNode, CodeNodeKind, GraphBuildRun, GraphBuildStatus, ImpactAnalysis,
|
||||
};
|
||||
pub use issue::{IssueStatus, TrackerIssue, TrackerType};
|
||||
pub use issue::{IssueStatus, IssueSubject, TrackerIssue, TrackerType};
|
||||
pub use license::{LicenseCategory, LicenseConclusion, LicenseUsage};
|
||||
pub use license_policy::{
|
||||
LegalReview, LicensePolicy, LicenseVerdict, PolicyAction, ReviewDecision,
|
||||
|
||||
@@ -227,6 +227,11 @@ pub struct ScanRun {
|
||||
/// and for a run that did not count.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub charge: Option<super::metering::RunCharge>,
|
||||
/// The components the run added, updated or removed in the stored SBOM
|
||||
/// (#974); `None` when it was not recorded (runs from before, and runs
|
||||
/// that did not replace the SBOM).
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub component_changes: Option<Vec<crate::component_changes::ComponentChange>>,
|
||||
}
|
||||
|
||||
/// Why a stage was skipped, or what a run note is about
|
||||
@@ -466,6 +471,7 @@ impl ScanRun {
|
||||
chargeable: false,
|
||||
charged_as: None,
|
||||
charge: None,
|
||||
component_changes: None,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,109 @@
|
||||
//! A target's SBOM components counted per ecosystem (package manager), and
|
||||
//! how many of them carry a known vulnerability (#957): the "Komponenten nach
|
||||
//! Ökosystem" chart, each bar opening the component table filtered to it.
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// The components of one ecosystem in a target's SBOM.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct EcosystemCount {
|
||||
/// The package manager as the SBOM names it (`npm`, `cargo`), the value
|
||||
/// the component table's package-manager filter takes.
|
||||
pub package_manager: String,
|
||||
/// How many components it has.
|
||||
pub components: u64,
|
||||
/// How many of them have at least one known vulnerability.
|
||||
pub with_cve: u64,
|
||||
}
|
||||
|
||||
/// Whether `package_manager` names an ecosystem the component table can be
|
||||
/// filtered by: not empty, and neither `unknown` nor `file` (a component
|
||||
/// found as a file, not from a manifest).
|
||||
pub fn is_filterable_manager(package_manager: &str) -> bool {
|
||||
!package_manager.is_empty() && package_manager != "unknown" && package_manager != "file"
|
||||
}
|
||||
|
||||
/// The filterable ecosystems of `counts`, the one with the most components
|
||||
/// first (then by name, so equal counts keep a stable order).
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// ```
|
||||
/// use compliance_core::sbom_ecosystems::{rank, EcosystemCount};
|
||||
///
|
||||
/// let count = |pm: &str, components| EcosystemCount {
|
||||
/// package_manager: pm.into(),
|
||||
/// components,
|
||||
/// with_cve: 0,
|
||||
/// };
|
||||
/// let ranked = rank(vec![count("cargo", 3), count("file", 9), count("npm", 12)]);
|
||||
/// assert_eq!(ranked, [count("npm", 12), count("cargo", 3)]);
|
||||
/// ```
|
||||
pub fn rank(counts: Vec<EcosystemCount>) -> Vec<EcosystemCount> {
|
||||
let mut ranked: Vec<EcosystemCount> = counts
|
||||
.into_iter()
|
||||
.filter(|c| is_filterable_manager(&c.package_manager))
|
||||
.collect();
|
||||
// `sort_unstable_by` is fine: the name breaks every tie, as one
|
||||
// aggregation yields each package manager once.
|
||||
ranked.sort_unstable_by(|a, b| {
|
||||
b.components
|
||||
.cmp(&a.components)
|
||||
.then_with(|| a.package_manager.cmp(&b.package_manager))
|
||||
});
|
||||
ranked
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn count(package_manager: &str, components: u64, with_cve: u64) -> EcosystemCount {
|
||||
EcosystemCount {
|
||||
package_manager: package_manager.into(),
|
||||
components,
|
||||
with_cve,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_largest_ecosystem_comes_first_then_by_name() {
|
||||
let ranked = rank(vec![
|
||||
count("pip", 4, 0),
|
||||
count("npm", 412, 7),
|
||||
count("cargo", 4, 1),
|
||||
]);
|
||||
assert_eq!(
|
||||
ranked,
|
||||
[
|
||||
count("npm", 412, 7),
|
||||
count("cargo", 4, 1),
|
||||
count("pip", 4, 0)
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn what_the_table_cannot_filter_by_is_left_out() {
|
||||
assert!(rank(vec![
|
||||
count("", 2, 0),
|
||||
count("unknown", 5, 1),
|
||||
count("file", 3, 0)
|
||||
])
|
||||
.is_empty());
|
||||
assert!(is_filterable_manager("nuget"));
|
||||
assert!(!is_filterable_manager("file"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_count_names_its_fields_on_the_wire() {
|
||||
assert_eq!(
|
||||
serde_json::to_value(count("npm", 12, 3)).ok(),
|
||||
Some(serde_json::json!({
|
||||
"package_manager": "npm",
|
||||
"components": 12,
|
||||
"with_cve": 3,
|
||||
}))
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,394 @@
|
||||
//! What each scan of a target changed: the CVE alerts it found new and those
|
||||
//! it found gone (#957, the "Verlauf" view).
|
||||
//!
|
||||
//! Computed from the stored alerts and runs alone, no snapshots. A completed
|
||||
//! scan's window runs from the end of the completed scan before it to its own
|
||||
//! end; an alert counts as new in the window its `created_at` falls in, and
|
||||
//! as gone in the window its `resolved_at` falls in. A target's first
|
||||
//! completed scan is its baseline: what it found is the whole SBOM, not a
|
||||
//! change. A scan that did not complete (queued, running, failed,
|
||||
//! interrupted) changes nothing: what came in meanwhile belongs to the next
|
||||
//! completed scan.
|
||||
//!
|
||||
//! Only an alert's current state is stored, so an alert reported again after
|
||||
//! it was resolved loses its `resolved_at` and is not seen as gone back then
|
||||
//! (as in [`crate::cve_history`]). Alerts the daily CVE monitor adds between
|
||||
//! two scans count for the next scan, which is when its report shows them.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use chrono::{DateTime, Utc};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::component_changes::{ComponentChange, ComponentChangeKind};
|
||||
|
||||
use crate::models::notification::{parse_severity, NotificationSeverity};
|
||||
use crate::models::{CveAlert, ScanRun, ScanRunStatus};
|
||||
|
||||
/// The scans a history shows unless asked otherwise.
|
||||
pub const DEFAULT_SCANS: usize = 20;
|
||||
/// The most scans a history may show.
|
||||
pub const MAX_SCANS: usize = 50;
|
||||
|
||||
/// One CVE alert a scan found new or gone.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct CveChange {
|
||||
/// The CVE id (or the advisory's, when it has no CVE alias).
|
||||
pub cve: String,
|
||||
pub package: String,
|
||||
pub version: String,
|
||||
pub severity: NotificationSeverity,
|
||||
}
|
||||
|
||||
impl CveChange {
|
||||
fn of(alert: &CveAlert) -> Self {
|
||||
Self {
|
||||
cve: alert.cve().to_string(),
|
||||
package: alert.affected_package.clone(),
|
||||
version: alert.affected_version.clone(),
|
||||
severity: parse_severity(alert.severity.as_deref(), alert.cvss_score),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What one scan changed.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct ScanChange {
|
||||
/// The run's id (hex).
|
||||
pub run_id: String,
|
||||
pub status: ScanRunStatus,
|
||||
pub started_at: DateTime<Utc>,
|
||||
#[serde(default)]
|
||||
pub completed_at: Option<DateTime<Utc>>,
|
||||
/// New findings the scan stored.
|
||||
#[serde(default)]
|
||||
pub new_findings: u32,
|
||||
/// The target's first completed scan: no changes, it set the start.
|
||||
#[serde(default)]
|
||||
pub baseline: bool,
|
||||
/// The CVE alerts found new in the scan's window, most severe first.
|
||||
pub new_cves: Vec<CveChange>,
|
||||
/// The CVE alerts found gone in the scan's window, most severe first.
|
||||
pub gone_cves: Vec<CveChange>,
|
||||
/// The components the scan changed, each with the CVEs it brought and
|
||||
/// took, and the advisories that changed for components it left alone
|
||||
/// (#974); `None` when the run did not record its component changes.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub components: Option<Vec<ComponentRow>>,
|
||||
}
|
||||
|
||||
/// A line of what a scan changed in its components.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum ComponentRowKind {
|
||||
Added,
|
||||
Updated,
|
||||
Removed,
|
||||
/// The component did not change; advisories about it did.
|
||||
Advisory,
|
||||
}
|
||||
|
||||
/// One component a scan changed, or whose advisories changed, with the
|
||||
/// CVEs that came and went with it.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct ComponentRow {
|
||||
pub kind: ComponentRowKind,
|
||||
pub name: String,
|
||||
/// The version before; `None` for an addition.
|
||||
#[serde(default)]
|
||||
pub from: Option<String>,
|
||||
/// The version after; `None` for a removal.
|
||||
#[serde(default)]
|
||||
pub to: Option<String>,
|
||||
pub cves_new: u32,
|
||||
pub cves_gone: u32,
|
||||
}
|
||||
|
||||
/// The rows of a scan that changed `changes` and saw `new` and `gone` CVEs:
|
||||
/// a new CVE goes with the component now at its version, a gone one with
|
||||
/// the component that was at its version; what no change explains is an
|
||||
/// advisory row per component and version. Rows with CVEs first, then by
|
||||
/// name.
|
||||
fn component_rows(
|
||||
changes: &[ComponentChange],
|
||||
new: &[CveChange],
|
||||
gone: &[CveChange],
|
||||
) -> Vec<ComponentRow> {
|
||||
let count = |cves: &[CveChange], name: &str, version: Option<&str>| {
|
||||
version.map_or(0, |v| {
|
||||
cves.iter()
|
||||
.filter(|c| c.package == name && c.version == v)
|
||||
.count() as u32
|
||||
})
|
||||
};
|
||||
let mut rows: Vec<ComponentRow> = changes
|
||||
.iter()
|
||||
.map(|c| ComponentRow {
|
||||
kind: match c.kind {
|
||||
ComponentChangeKind::Added => ComponentRowKind::Added,
|
||||
ComponentChangeKind::Updated => ComponentRowKind::Updated,
|
||||
ComponentChangeKind::Removed => ComponentRowKind::Removed,
|
||||
},
|
||||
name: c.name.clone(),
|
||||
from: c.from.clone(),
|
||||
to: c.to.clone(),
|
||||
cves_new: count(new, &c.name, c.to.as_deref()),
|
||||
cves_gone: count(gone, &c.name, c.from.as_deref()),
|
||||
})
|
||||
.collect();
|
||||
let explained = |cve: &CveChange, after: bool| {
|
||||
changes.iter().any(|c| {
|
||||
let version = if after { &c.to } else { &c.from };
|
||||
c.name == cve.package && version.as_deref() == Some(cve.version.as_str())
|
||||
})
|
||||
};
|
||||
let mut advisories: BTreeMap<(&str, &str), (u32, u32)> = BTreeMap::new();
|
||||
for cve in new.iter().filter(|c| !explained(c, true)) {
|
||||
advisories
|
||||
.entry((cve.package.as_str(), cve.version.as_str()))
|
||||
.or_default()
|
||||
.0 += 1;
|
||||
}
|
||||
for cve in gone.iter().filter(|c| !explained(c, false)) {
|
||||
advisories
|
||||
.entry((cve.package.as_str(), cve.version.as_str()))
|
||||
.or_default()
|
||||
.1 += 1;
|
||||
}
|
||||
rows.extend(
|
||||
advisories
|
||||
.into_iter()
|
||||
.map(|((name, version), (cves_new, cves_gone))| ComponentRow {
|
||||
kind: ComponentRowKind::Advisory,
|
||||
name: name.to_string(),
|
||||
from: Some(version.to_string()),
|
||||
to: Some(version.to_string()),
|
||||
cves_new,
|
||||
cves_gone,
|
||||
}),
|
||||
);
|
||||
rows.sort_by(|a, b| {
|
||||
let quiet = |r: &ComponentRow| r.cves_new + r.cves_gone == 0;
|
||||
quiet(a).cmp(&quiet(b)).then_with(|| a.name.cmp(&b.name))
|
||||
});
|
||||
rows
|
||||
}
|
||||
|
||||
/// The changes of `runs` (one target's, any order) from `alerts` (the same
|
||||
/// target's), oldest scan first.
|
||||
///
|
||||
/// # Arguments
|
||||
///
|
||||
/// * `runs` - the scans to show
|
||||
/// * `since` - when the completed scan before them ended; `None` when they
|
||||
/// go back to the target's first scan
|
||||
/// * `alerts` - the target's CVE alerts (at least those created or resolved
|
||||
/// after `since`)
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// ```
|
||||
/// use compliance_core::scan_changes::changes;
|
||||
///
|
||||
/// assert!(changes(&[], None, &[]).is_empty());
|
||||
/// ```
|
||||
pub fn changes(
|
||||
runs: &[ScanRun],
|
||||
since: Option<DateTime<Utc>>,
|
||||
alerts: &[CveAlert],
|
||||
) -> Vec<ScanChange> {
|
||||
let mut sorted: Vec<&ScanRun> = runs.iter().collect();
|
||||
sorted.sort_by_key(|r| r.started_at);
|
||||
let mut start = since;
|
||||
let mut out = Vec::with_capacity(sorted.len());
|
||||
for run in sorted {
|
||||
let end = run
|
||||
.completed_at
|
||||
.filter(|_| run.status == ScanRunStatus::Completed);
|
||||
let (new_cves, gone_cves) = match (start, end) {
|
||||
(Some(from), Some(to)) => {
|
||||
let within = |at: DateTime<Utc>| from < at && at <= to;
|
||||
(
|
||||
ranked(alerts.iter().filter(|a| within(a.created_at))),
|
||||
ranked(alerts.iter().filter(|a| a.resolved_at.is_some_and(&within))),
|
||||
)
|
||||
}
|
||||
_ => (Vec::new(), Vec::new()),
|
||||
};
|
||||
let baseline = end.is_some() && start.is_none();
|
||||
if end.is_some() {
|
||||
start = end;
|
||||
}
|
||||
// The baseline's changes are its whole SBOM, not a change.
|
||||
let components = run
|
||||
.component_changes
|
||||
.as_deref()
|
||||
.filter(|_| !baseline)
|
||||
.map(|changes| component_rows(changes, &new_cves, &gone_cves));
|
||||
out.push(ScanChange {
|
||||
run_id: run.id.map(|id| id.to_hex()).unwrap_or_default(),
|
||||
status: run.status.clone(),
|
||||
started_at: run.started_at,
|
||||
completed_at: run.completed_at,
|
||||
new_findings: run.new_findings_count,
|
||||
baseline,
|
||||
new_cves,
|
||||
gone_cves,
|
||||
components,
|
||||
});
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// `alerts` as changes, the most severe first, then by package and CVE.
|
||||
fn ranked<'a>(alerts: impl Iterator<Item = &'a CveAlert>) -> Vec<CveChange> {
|
||||
let mut list: Vec<CveChange> = alerts.map(CveChange::of).collect();
|
||||
list.sort_by(|a, b| {
|
||||
b.severity
|
||||
.cmp(&a.severity)
|
||||
.then_with(|| a.package.cmp(&b.package))
|
||||
.then_with(|| a.cve.cmp(&b.cve))
|
||||
});
|
||||
list
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[allow(clippy::unwrap_used)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::models::{CveSource, ScanTrigger};
|
||||
|
||||
fn at(hour: u32) -> DateTime<Utc> {
|
||||
format!("2026-11-10T{hour:02}:00:00Z").parse().unwrap()
|
||||
}
|
||||
|
||||
fn run(started: u32, status: ScanRunStatus, completed: Option<u32>) -> ScanRun {
|
||||
let mut run = ScanRun::new("t1".into(), ScanTrigger::Scheduled);
|
||||
run.id = Some(bson::oid::ObjectId::new());
|
||||
run.status = status;
|
||||
run.started_at = at(started);
|
||||
run.completed_at = completed.map(at);
|
||||
run
|
||||
}
|
||||
|
||||
fn alert(cve: &str, severity: &str, created: u32, resolved: Option<u32>) -> CveAlert {
|
||||
let mut a = CveAlert::new(
|
||||
cve.into(),
|
||||
"t1".into(),
|
||||
"openssl".into(),
|
||||
"3.0.9".into(),
|
||||
CveSource::Osv,
|
||||
);
|
||||
a.severity = Some(severity.into());
|
||||
a.created_at = at(created);
|
||||
a.resolved_at = resolved.map(at);
|
||||
a
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn each_completed_scan_gets_what_came_and_went_since_the_one_before() {
|
||||
let runs = [
|
||||
run(1, ScanRunStatus::Completed, Some(2)),
|
||||
run(3, ScanRunStatus::Failed, Some(4)),
|
||||
run(5, ScanRunStatus::Completed, Some(6)),
|
||||
run(7, ScanRunStatus::Running, None),
|
||||
];
|
||||
let alerts = [
|
||||
// Found by the first scan: its baseline, not a change.
|
||||
alert("CVE-2026-0001", "high", 2, Some(6)),
|
||||
// Added by the monitor while the failed scan ran: the next
|
||||
// completed scan reports it.
|
||||
alert("CVE-2026-0002", "critical", 4, None),
|
||||
alert("CVE-2026-0003", "low", 6, None),
|
||||
];
|
||||
|
||||
let changes = changes(&runs, None, &alerts);
|
||||
|
||||
// The first scan is the baseline; the failed and the running scan
|
||||
// change nothing.
|
||||
let baselines: Vec<bool> = changes.iter().map(|c| c.baseline).collect();
|
||||
assert_eq!(baselines, [true, false, false, false]);
|
||||
assert!(changes[0].new_cves.is_empty());
|
||||
assert!(changes[1].new_cves.is_empty() && changes[3].new_cves.is_empty());
|
||||
let new: Vec<&str> = changes[2].new_cves.iter().map(|c| c.cve.as_str()).collect();
|
||||
assert_eq!(new, ["CVE-2026-0002", "CVE-2026-0003"], "most severe first");
|
||||
let gone: Vec<&str> = changes[2]
|
||||
.gone_cves
|
||||
.iter()
|
||||
.map(|c| c.cve.as_str())
|
||||
.collect();
|
||||
assert_eq!(gone, ["CVE-2026-0001"]);
|
||||
assert_eq!(
|
||||
changes[2].new_cves[0].severity,
|
||||
NotificationSeverity::Critical
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_scans_cves_go_with_the_components_it_changed_the_rest_are_advisories() {
|
||||
let change = |kind, name: &str, from: Option<&str>, to: Option<&str>| ComponentChange {
|
||||
kind,
|
||||
package_manager: "npm".into(),
|
||||
name: name.into(),
|
||||
from: from.map(String::from),
|
||||
to: to.map(String::from),
|
||||
};
|
||||
let cve = |id: &str, package: &str, version: &str| CveChange {
|
||||
cve: id.into(),
|
||||
package: package.into(),
|
||||
version: version.into(),
|
||||
severity: NotificationSeverity::High,
|
||||
};
|
||||
let changes = [
|
||||
change(
|
||||
ComponentChangeKind::Updated,
|
||||
"openssl",
|
||||
Some("3.0.9"),
|
||||
Some("3.0.11"),
|
||||
),
|
||||
change(ComponentChangeKind::Added, "libxml2", None, Some("2.11.4")),
|
||||
change(ComponentChangeKind::Removed, "libpng", Some("1.6.39"), None),
|
||||
change(ComponentChangeKind::Added, "quiet", None, Some("1.0.0")),
|
||||
];
|
||||
let new = [
|
||||
cve("CVE-1", "openssl", "3.0.11"),
|
||||
cve("CVE-2", "libxml2", "2.11.4"),
|
||||
cve("CVE-3", "busybox", "1.36.0"),
|
||||
];
|
||||
let gone = [
|
||||
cve("CVE-4", "openssl", "3.0.9"),
|
||||
cve("CVE-5", "libpng", "1.6.39"),
|
||||
];
|
||||
|
||||
let rows = component_rows(&changes, &new, &gone);
|
||||
|
||||
let read: Vec<(ComponentRowKind, &str, u32, u32)> = rows
|
||||
.iter()
|
||||
.map(|r| (r.kind.clone(), r.name.as_str(), r.cves_new, r.cves_gone))
|
||||
.collect();
|
||||
assert_eq!(
|
||||
read,
|
||||
[
|
||||
(ComponentRowKind::Advisory, "busybox", 1, 0),
|
||||
(ComponentRowKind::Removed, "libpng", 0, 1),
|
||||
(ComponentRowKind::Added, "libxml2", 1, 0),
|
||||
(ComponentRowKind::Updated, "openssl", 1, 1),
|
||||
// Changes without CVEs last.
|
||||
(ComponentRowKind::Added, "quiet", 0, 0),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_history_that_starts_later_takes_its_window_from_the_scan_before() {
|
||||
let runs = [run(5, ScanRunStatus::Completed, Some(6))];
|
||||
let alerts = [
|
||||
alert("CVE-2026-0001", "high", 2, None),
|
||||
alert("CVE-2026-0002", "high", 4, None),
|
||||
];
|
||||
let changes = changes(&runs, Some(at(3)), &alerts);
|
||||
assert!(!changes[0].baseline);
|
||||
let new: Vec<&str> = changes[0].new_cves.iter().map(|c| c.cve.as_str()).collect();
|
||||
assert_eq!(new, ["CVE-2026-0002"]);
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,6 +1,9 @@
|
||||
use dioxus::prelude::*;
|
||||
|
||||
use compliance_core::models::inbox::Bucket;
|
||||
|
||||
use crate::components::app_shell::AppShell;
|
||||
use crate::pages::target_views::RepoView;
|
||||
use crate::pages::*;
|
||||
|
||||
#[derive(Debug, Clone, Routable, PartialEq)]
|
||||
@@ -8,24 +11,56 @@ use crate::pages::*;
|
||||
#[allow(clippy::enum_variant_names)]
|
||||
pub enum Route {
|
||||
#[layout(AppShell)]
|
||||
#[route("/")]
|
||||
// The landing page: the open decisions (#950). `?target=<id>` opens
|
||||
// one target's, `&bucket=` one bucket (`today`, `this_week`, ...).
|
||||
#[route("/?:target&:bucket")]
|
||||
HeutePage { target: String, bucket: String },
|
||||
#[route("/overview")]
|
||||
OverviewPage {},
|
||||
#[route("/targets")]
|
||||
TargetsPage {},
|
||||
#[route("/targets/:id")]
|
||||
TargetPage { id: String },
|
||||
// The target's views (#957), one tab each (`findings`, `cves`,
|
||||
// `components`, `licences`, `cra`, `history`; see `RepoView`). On the
|
||||
// CVE tab `?cve_severity=high&cve_vex=open` opens the CVE list
|
||||
// narrowed to that cell of the grid (`all` leaves a side open,
|
||||
// neither shows the grid); on the CRA tab `?control=cra-ai-3` one
|
||||
// requirement; on the history tab `?scan=<run id>` one scan.
|
||||
#[route("/targets/:id/views/:view?:cve_severity&:cve_vex&:control&:scan")]
|
||||
TargetViewsPage {
|
||||
id: String,
|
||||
view: String,
|
||||
cve_severity: Option<String>,
|
||||
cve_vex: Option<String>,
|
||||
control: Option<String>,
|
||||
scan: Option<String>,
|
||||
},
|
||||
#[route("/targets/:id/compliance")]
|
||||
CompliancePage { id: String },
|
||||
#[route("/onboard")]
|
||||
OnboardingPage {},
|
||||
// `?target=<id>` opens the list filtered to one target.
|
||||
#[route("/findings?:target")]
|
||||
FindingsPage { target: String },
|
||||
// `?target=<id>` 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<String>,
|
||||
severity: Option<String>,
|
||||
path: Option<String>,
|
||||
target: String,
|
||||
},
|
||||
#[route("/findings/:id")]
|
||||
FindingDetailPage { id: String },
|
||||
// `?target=<id>` opens the list filtered to one target.
|
||||
#[route("/sbom?:target")]
|
||||
SbomPage { target: String },
|
||||
// The SBOM page with its component table filtered to one ecosystem,
|
||||
// opened from the components view (#957).
|
||||
#[route("/sbom/ecosystem/:ecosystem?:target", SbomPage)]
|
||||
SbomEcosystemPage { ecosystem: String, target: String },
|
||||
#[route("/issues")]
|
||||
IssuesPage {},
|
||||
// The code graph opens from its card on the target page.
|
||||
@@ -56,6 +91,45 @@ pub enum Route {
|
||||
McpTokensPage {},
|
||||
}
|
||||
|
||||
impl Route {
|
||||
/// The page (the dashboard) of target `id`.
|
||||
pub fn target(id: String) -> Self {
|
||||
Self::TargetPage { id }
|
||||
}
|
||||
|
||||
/// The tab `view` of target `id`'s views; the CVE tab shows its grid.
|
||||
pub fn target_view(id: String, view: RepoView) -> Self {
|
||||
Self::TargetViewsPage {
|
||||
id,
|
||||
view: view.slug().to_string(),
|
||||
cve_severity: None,
|
||||
cve_vex: None,
|
||||
control: None,
|
||||
scan: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Heute for target `target` (every target when empty), opened on
|
||||
/// `bucket` (the most urgent one when `None`).
|
||||
pub fn heute(target: String, bucket: Option<Bucket>) -> Self {
|
||||
Self::HeutePage {
|
||||
target,
|
||||
bucket: bucket.map(|b| b.as_str().to_string()).unwrap_or_default(),
|
||||
}
|
||||
}
|
||||
|
||||
/// 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");
|
||||
@@ -78,9 +152,29 @@ pub fn App() -> Element {
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::Route;
|
||||
use std::str::FromStr;
|
||||
|
||||
use compliance_core::models::inbox::Bucket;
|
||||
|
||||
use super::Route;
|
||||
use crate::pages::target_views::RepoView;
|
||||
|
||||
#[test]
|
||||
fn heute_is_the_landing_page_and_the_overview_stays_reachable() {
|
||||
assert_eq!(
|
||||
Route::from_str("/").ok(),
|
||||
Some(Route::heute(String::new(), None))
|
||||
);
|
||||
let one = Route::heute("t1".to_string(), Some(Bucket::ThisWeek));
|
||||
assert_eq!(one.to_string(), "/?target=t1&bucket=this_week");
|
||||
assert_eq!(Route::from_str(&one.to_string()).ok(), Some(one));
|
||||
assert!(matches!(
|
||||
Route::from_str("/overview"),
|
||||
Ok(Route::OverviewPage {})
|
||||
));
|
||||
assert_eq!(Route::OverviewPage {}.to_string(), "/overview");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_sbom_page_carries_its_target_in_the_query() {
|
||||
let filtered = Route::SbomPage {
|
||||
@@ -99,4 +193,138 @@ mod tests {
|
||||
Ok(Route::SbomPage { target }) if target.is_empty()
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_ecosystem_of_the_sbom_page_is_in_its_url() {
|
||||
let filtered = Route::SbomEcosystemPage {
|
||||
ecosystem: "npm".to_string(),
|
||||
target: "665f1c2ab0c4d1e2f3a4b5c6".to_string(),
|
||||
};
|
||||
assert_eq!(
|
||||
filtered.to_string(),
|
||||
"/sbom/ecosystem/npm?target=665f1c2ab0c4d1e2f3a4b5c6"
|
||||
);
|
||||
assert!(matches!(
|
||||
Route::from_str("/sbom/ecosystem/cargo?target=665f"),
|
||||
Ok(Route::SbomEcosystemPage { ecosystem, target })
|
||||
if ecosystem == "cargo" && target == "665f"
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_target_view_carries_its_tab_and_the_cve_cell_in_the_url() {
|
||||
let cell = Route::TargetViewsPage {
|
||||
id: "t1".to_string(),
|
||||
view: "cves".to_string(),
|
||||
cve_severity: Some("high".to_string()),
|
||||
cve_vex: Some("open".to_string()),
|
||||
control: None,
|
||||
scan: None,
|
||||
};
|
||||
// The router writes a `&` after each argument that is set.
|
||||
assert_eq!(
|
||||
cell.to_string(),
|
||||
"/targets/t1/views/cves?cve_severity=high&cve_vex=open&"
|
||||
);
|
||||
assert_eq!(Route::from_str(&cell.to_string()).ok(), Some(cell));
|
||||
|
||||
// A CRA requirement and a scan read back the same way.
|
||||
for (view, control, scan) in [
|
||||
("cra", Some("cra-ai-3"), None),
|
||||
("history", None, Some("665f1c2ab0c4d1e2f3a4b5c6")),
|
||||
] {
|
||||
let route = Route::TargetViewsPage {
|
||||
id: "t1".to_string(),
|
||||
view: view.to_string(),
|
||||
cve_severity: None,
|
||||
cve_vex: None,
|
||||
control: control.map(String::from),
|
||||
scan: scan.map(String::from),
|
||||
};
|
||||
assert_eq!(Route::from_str(&route.to_string()).ok(), Some(route));
|
||||
}
|
||||
|
||||
let column = Route::TargetViewsPage {
|
||||
id: "t1".to_string(),
|
||||
view: "cves".to_string(),
|
||||
cve_severity: None,
|
||||
cve_vex: Some("open".to_string()),
|
||||
control: None,
|
||||
scan: None,
|
||||
};
|
||||
assert_eq!(Route::from_str(&column.to_string()).ok(), Some(column));
|
||||
|
||||
// The router writes the `?` of a two-argument query even when both
|
||||
// are absent; harmless, and it reads back as the grid.
|
||||
let grid = Route::target_view("t1".to_string(), RepoView::Cves);
|
||||
assert_eq!(grid.to_string(), "/targets/t1/views/cves?");
|
||||
assert_eq!(Route::from_str("/targets/t1/views/cves").ok(), Some(grid));
|
||||
|
||||
assert_eq!(Route::target("t1".to_string()).to_string(), "/targets/t1");
|
||||
assert_eq!(
|
||||
Route::from_str("/targets/t1").ok(),
|
||||
Some(Route::target("t1".to_string()))
|
||||
);
|
||||
assert!(matches!(
|
||||
Route::from_str("/targets/t1/compliance"),
|
||||
Ok(Route::CompliancePage { id }) if id == "t1"
|
||||
));
|
||||
}
|
||||
|
||||
#[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()))
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,451 @@
|
||||
//! The "Komponenten" view of one target (#957), at the top of the SBOM
|
||||
//! page's component tab: which update removes the most CVEs (from the CVE
|
||||
//! groups of #949) and the components per ecosystem, as horizontal bars.
|
||||
//! An update bar opens that component's CVE group card in place; an
|
||||
//! ecosystem bar filters the component table below to it. "Tabelle" shows
|
||||
//! the same numbers as plain tables.
|
||||
|
||||
use std::collections::HashSet;
|
||||
|
||||
use dioxus::prelude::*;
|
||||
|
||||
use compliance_core::cve_groups::{CveGroup, PackageKey};
|
||||
use compliance_core::models::CveAlert;
|
||||
use compliance_core::sbom_ecosystems::EcosystemCount;
|
||||
|
||||
use crate::components::severity_badge::SeverityBadge;
|
||||
use crate::components::vex_panel::CveGroupCard;
|
||||
use crate::i18n::texts::{common, component_overview as tx};
|
||||
use crate::i18n::{format_count, use_lang};
|
||||
use crate::infrastructure::sbom_ecosystems::fetch_sbom_ecosystems;
|
||||
use crate::infrastructure::vex::{fetch_cve_groups, fetch_enisa_candidates, fetch_target_cves};
|
||||
use crate::pages::sbom::pm_display_name;
|
||||
|
||||
/// How many update bars show before "Alle anzeigen".
|
||||
const TOP_UPDATES: usize = 10;
|
||||
|
||||
/// The CVE groups an update helps with, the one removing the most CVEs
|
||||
/// first (then the most severe, then by component). The groups and their
|
||||
/// counts are #949's; this only filters and orders them.
|
||||
pub fn rank_updates(groups: &[CveGroup]) -> Vec<&CveGroup> {
|
||||
let mut ranked: Vec<&CveGroup> = groups
|
||||
.iter()
|
||||
.filter(|g| g.fix_version.is_some() && g.fixable > 0)
|
||||
.collect();
|
||||
ranked.sort_unstable_by(|a, b| {
|
||||
b.fixable
|
||||
.cmp(&a.fixable)
|
||||
.then_with(|| b.counts.max().cmp(&a.counts.max()))
|
||||
.then_with(|| a.key.cmp(&b.key))
|
||||
});
|
||||
ranked
|
||||
}
|
||||
|
||||
/// An update's label: `openssl 3.0.11 → 3.0.15`.
|
||||
fn update_label(group: &CveGroup) -> String {
|
||||
let fix = group.fix_version.as_deref().unwrap_or_default();
|
||||
format!("{} {} → {fix}", group.key.package, group.key.version)
|
||||
}
|
||||
|
||||
/// The width of a bar of `value` against the largest one, `max`, as a CSS
|
||||
/// percentage (at least a sliver, so a small bar stays visible).
|
||||
fn bar_width(value: u64, max: u64) -> String {
|
||||
// Lossy `as f64` is fine: counts this large do not exist, and the result
|
||||
// is a CSS width.
|
||||
let percent = if max == 0 {
|
||||
0.0
|
||||
} else {
|
||||
value as f64 * 100.0 / max as f64
|
||||
};
|
||||
format!("width: {:.1}%", percent.max(2.0))
|
||||
}
|
||||
|
||||
/// The "Komponenten" overview of target `target_id`. `ecosystem` is the
|
||||
/// component table's package-manager filter; `on_ecosystem` sets it (an
|
||||
/// empty name clears it).
|
||||
#[component]
|
||||
pub fn ComponentOverview(
|
||||
target_id: ReadSignal<String>,
|
||||
ecosystem: String,
|
||||
on_ecosystem: EventHandler<String>,
|
||||
) -> Element {
|
||||
let lang = use_lang()();
|
||||
let mut groups = use_resource(move || async move { fetch_cve_groups(target_id()).await.ok() });
|
||||
let ecosystems =
|
||||
use_resource(move || async move { fetch_sbom_ecosystems(target_id()).await.ok() });
|
||||
let mut as_table = use_signal(|| false);
|
||||
let mut opened = use_signal(|| Option::<PackageKey>::None);
|
||||
// Another target picked on the page closes the open group card.
|
||||
use_effect(move || {
|
||||
target_id();
|
||||
opened.set(None);
|
||||
});
|
||||
|
||||
if let Some(key) = opened() {
|
||||
let open_group = groups
|
||||
.read()
|
||||
.as_ref()
|
||||
.and_then(|found| found.as_ref())
|
||||
.and_then(|found| found.iter().find(|g| g.key == key).cloned());
|
||||
return rsx! {
|
||||
div { class: "co-view",
|
||||
Breadcrumb {
|
||||
selection: format!("{} {}", key.package, key.version),
|
||||
on_back: move |()| opened.set(None),
|
||||
}
|
||||
match open_group {
|
||||
Some(group) => rsx! {
|
||||
OpenGroup {
|
||||
target_id,
|
||||
group,
|
||||
on_saved: move |()| groups.restart(),
|
||||
}
|
||||
},
|
||||
None if groups.read().is_none() => rsx! {
|
||||
div { class: "loading", {common::LOADING.get(lang)} }
|
||||
},
|
||||
None => rsx! { p { class: "target-muted", {tx::GROUP_SETTLED.get(lang)} } },
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
if !ecosystem.is_empty() {
|
||||
return rsx! {
|
||||
div { class: "co-view",
|
||||
Breadcrumb {
|
||||
selection: pm_display_name(&ecosystem).to_string(),
|
||||
on_back: move |()| on_ecosystem.call(String::new()),
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
rsx! {
|
||||
div { class: "co-view",
|
||||
div { class: "co-toggle", role: "group",
|
||||
for (table, label) in [(false, tx::VIEW_CHART), (true, tx::VIEW_TABLE)] {
|
||||
button {
|
||||
class: if as_table() == table { "co-toggle-btn active" } else { "co-toggle-btn" },
|
||||
"aria-pressed": if as_table() == table { "true" } else { "false" },
|
||||
onclick: move |_| as_table.set(table),
|
||||
{label.get(lang)}
|
||||
}
|
||||
}
|
||||
}
|
||||
div { class: "co-charts",
|
||||
section { class: "card co-chart",
|
||||
h3 { class: "co-chart-title", {tx::UPDATES_TITLE.get(lang)} }
|
||||
p { class: "co-chart-hint", {tx::UPDATES_HINT.get(lang)} }
|
||||
match &*groups.read() {
|
||||
None => rsx! { div { class: "loading", {common::LOADING.get(lang)} } },
|
||||
Some(None) => rsx! { p { class: "target-muted", {tx::LOAD_FAILED.get(lang)} } },
|
||||
Some(Some(found)) => rsx! {
|
||||
UpdateBars {
|
||||
groups: found.clone(),
|
||||
as_table: as_table(),
|
||||
on_open: move |key: PackageKey| opened.set(Some(key)),
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
section { class: "card co-chart",
|
||||
h3 { class: "co-chart-title", {tx::ECOSYSTEMS_TITLE.get(lang)} }
|
||||
p { class: "co-chart-hint", {tx::ECOSYSTEMS_HINT.get(lang)} }
|
||||
match &*ecosystems.read() {
|
||||
None => rsx! { div { class: "loading", {common::LOADING.get(lang)} } },
|
||||
Some(None) => rsx! { p { class: "target-muted", {tx::LOAD_FAILED.get(lang)} } },
|
||||
Some(Some(found)) if found.is_empty() => rsx! {
|
||||
p { class: "target-muted", {tx::NO_ECOSYSTEMS.get(lang)} }
|
||||
},
|
||||
Some(Some(found)) => rsx! {
|
||||
EcosystemBars { ecosystems: found.clone(), as_table: as_table(), on_ecosystem }
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// "Komponenten › `selection`" with the way back to the charts.
|
||||
#[component]
|
||||
fn Breadcrumb(selection: String, on_back: EventHandler<()>) -> Element {
|
||||
let lang = use_lang()();
|
||||
rsx! {
|
||||
nav { class: "co-breadcrumb", "aria-label": tx::BREADCRUMB.get(lang),
|
||||
span { class: "co-breadcrumb-root", {tx::BREADCRUMB.get(lang)} }
|
||||
span { class: "co-breadcrumb-sep", "aria-hidden": "true", "›" }
|
||||
strong { "{selection}" }
|
||||
button {
|
||||
class: "btn btn-ghost btn-sm co-back",
|
||||
onclick: move |_| on_back.call(()),
|
||||
{tx::BACK.get(lang)}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The update bars (or their table) of `groups`, the top 10 until "Alle
|
||||
/// anzeigen"; `on_open` receives the component of a clicked bar.
|
||||
#[component]
|
||||
fn UpdateBars(groups: Vec<CveGroup>, as_table: bool, on_open: EventHandler<PackageKey>) -> Element {
|
||||
let lang = use_lang()();
|
||||
let mut show_all = use_signal(|| false);
|
||||
let ranked = rank_updates(&groups);
|
||||
if ranked.is_empty() {
|
||||
return rsx! { p { class: "target-muted", {tx::NO_UPDATES.get(lang)} } };
|
||||
}
|
||||
let total = ranked.len();
|
||||
let shown = if show_all() {
|
||||
total
|
||||
} else {
|
||||
total.min(TOP_UPDATES)
|
||||
};
|
||||
let max = ranked.first().map_or(0, |g| g.fixable as u64);
|
||||
rsx! {
|
||||
if as_table {
|
||||
div { class: "table-wrapper",
|
||||
table { class: "co-table",
|
||||
thead {
|
||||
tr {
|
||||
th { {tx::COL_UPDATE.get(lang)} }
|
||||
th { class: "co-num", {tx::COL_REMOVES.get(lang)} }
|
||||
th { {tx::COL_SEVERITY.get(lang)} }
|
||||
}
|
||||
}
|
||||
tbody {
|
||||
for group in ranked.iter().take(shown) {
|
||||
{
|
||||
let label = update_label(group);
|
||||
let key = group.key.clone();
|
||||
rsx! {
|
||||
tr {
|
||||
td {
|
||||
button {
|
||||
class: "co-link",
|
||||
"aria-label": tx::update_action(&label, group.fixable, lang),
|
||||
onclick: move |_| on_open.call(key.clone()),
|
||||
"{label}"
|
||||
}
|
||||
}
|
||||
td { class: "co-num", {tx::removes(group.fixable)} }
|
||||
td { SeverityBadge { severity: group.counts.max().as_str().to_string() } }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
ol { class: "co-bars",
|
||||
for group in ranked.iter().take(shown) {
|
||||
{
|
||||
let label = update_label(group);
|
||||
let action = tx::update_action(&label, group.fixable, lang);
|
||||
let key = group.key.clone();
|
||||
rsx! {
|
||||
li {
|
||||
button {
|
||||
class: "co-bar",
|
||||
"aria-label": "{action}",
|
||||
title: "{action}",
|
||||
onclick: move |_| on_open.call(key.clone()),
|
||||
span { class: "co-bar-label", "{label}" }
|
||||
span { class: "co-bar-track",
|
||||
span { class: "co-bar-fill", style: bar_width(group.fixable as u64, max) }
|
||||
}
|
||||
span { class: "co-bar-value", {tx::removes(group.fixable)} }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if total > TOP_UPDATES {
|
||||
button {
|
||||
class: "btn btn-ghost btn-sm co-more",
|
||||
"aria-expanded": if show_all() { "true" } else { "false" },
|
||||
onclick: move |_| show_all.toggle(),
|
||||
if show_all() { {tx::TOP_ONLY.get(lang)} } else { {tx::show_all(total, lang)} }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The ecosystem bars (or their table) of `ecosystems`; a click sends the
|
||||
/// package manager to `on_ecosystem`.
|
||||
#[component]
|
||||
fn EcosystemBars(
|
||||
ecosystems: Vec<EcosystemCount>,
|
||||
as_table: bool,
|
||||
on_ecosystem: EventHandler<String>,
|
||||
) -> Element {
|
||||
let lang = use_lang()();
|
||||
let max = ecosystems.iter().map(|e| e.components).max().unwrap_or(0);
|
||||
rsx! {
|
||||
if as_table {
|
||||
div { class: "table-wrapper",
|
||||
table { class: "co-table",
|
||||
thead {
|
||||
tr {
|
||||
th { {tx::COL_ECOSYSTEM.get(lang)} }
|
||||
th { class: "co-num", {tx::COL_COMPONENTS.get(lang)} }
|
||||
th { class: "co-num", {tx::COL_WITH_CVE.get(lang)} }
|
||||
}
|
||||
}
|
||||
tbody {
|
||||
for count in ecosystems.iter() {
|
||||
{
|
||||
let name = pm_display_name(&count.package_manager);
|
||||
let action = tx::ecosystem_action(name, count.components, count.with_cve, lang);
|
||||
let manager = count.package_manager.clone();
|
||||
rsx! {
|
||||
tr {
|
||||
td {
|
||||
button {
|
||||
class: "co-link",
|
||||
"aria-label": "{action}",
|
||||
onclick: move |_| on_ecosystem.call(manager.clone()),
|
||||
"{name}"
|
||||
}
|
||||
}
|
||||
td { class: "co-num", {format_count(count.components, lang)} }
|
||||
td { class: "co-num", {format_count(count.with_cve, lang)} }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
ol { class: "co-bars",
|
||||
for count in ecosystems.iter() {
|
||||
{
|
||||
let name = pm_display_name(&count.package_manager);
|
||||
let action = tx::ecosystem_action(name, count.components, count.with_cve, lang);
|
||||
let manager = count.package_manager.clone();
|
||||
rsx! {
|
||||
li {
|
||||
button {
|
||||
class: "co-bar",
|
||||
"aria-label": "{action}",
|
||||
title: "{action}",
|
||||
onclick: move |_| on_ecosystem.call(manager.clone()),
|
||||
span { class: "co-bar-label", "{name}" }
|
||||
span { class: "co-bar-track",
|
||||
span { class: "co-bar-fill", style: bar_width(count.components, max) }
|
||||
}
|
||||
span { class: "co-bar-value",
|
||||
{tx::ecosystem_value(count.components, count.with_cve, lang)}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The CVE group card of #949 for `group`, with its alerts and the CRA
|
||||
/// Article 14 candidates it needs, loaded when it opens.
|
||||
#[component]
|
||||
fn OpenGroup(
|
||||
target_id: ReadSignal<String>,
|
||||
group: CveGroup,
|
||||
on_saved: EventHandler<()>,
|
||||
) -> Element {
|
||||
let lang = use_lang()();
|
||||
let mut alerts = use_resource(move || async move { fetch_target_cves(target_id()).await.ok() });
|
||||
let mut enisa = use_resource(move || async move {
|
||||
fetch_enisa_candidates(target_id())
|
||||
.await
|
||||
.unwrap_or_default()
|
||||
});
|
||||
let ids: HashSet<&str> = group.alert_ids.iter().map(String::as_str).collect();
|
||||
let members: Option<Vec<CveAlert>> = alerts.read().as_ref().map(|loaded| {
|
||||
loaded
|
||||
.iter()
|
||||
.flatten()
|
||||
.filter(|a| a.id.is_some_and(|id| ids.contains(id.to_hex().as_str())))
|
||||
.cloned()
|
||||
.collect()
|
||||
});
|
||||
let candidates = enisa.read().clone().unwrap_or_default();
|
||||
match members {
|
||||
None => rsx! { div { class: "loading", {common::LOADING.get(lang)} } },
|
||||
Some(members) => rsx! {
|
||||
CveGroupCard {
|
||||
target_id: target_id(),
|
||||
group,
|
||||
alerts: members,
|
||||
candidates,
|
||||
on_saved: move |()| {
|
||||
alerts.restart();
|
||||
enisa.restart();
|
||||
on_saved.call(());
|
||||
},
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use compliance_core::cve_groups::SeverityCounts;
|
||||
|
||||
fn group(package: &str, fixable: usize, fix: Option<&str>, counts: SeverityCounts) -> CveGroup {
|
||||
CveGroup {
|
||||
key: PackageKey {
|
||||
package: package.into(),
|
||||
version: "1.0.0".into(),
|
||||
purl: None,
|
||||
},
|
||||
fix_version: fix.map(String::from),
|
||||
fixable,
|
||||
counts,
|
||||
kev: false,
|
||||
epss_max: None,
|
||||
cve_ids: Vec::new(),
|
||||
alert_ids: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn updates_rank_by_the_cves_they_remove_then_by_severity() {
|
||||
let high = SeverityCounts {
|
||||
high: 1,
|
||||
..SeverityCounts::default()
|
||||
};
|
||||
let low = SeverityCounts {
|
||||
low: 1,
|
||||
..SeverityCounts::default()
|
||||
};
|
||||
let groups = vec![
|
||||
group("lodash", 1, Some("4.17.21"), low),
|
||||
group("vite", 3, Some("8.3.3"), low),
|
||||
group("openssl", 1, Some("3.0.15"), high),
|
||||
// No fix named: no update to rank.
|
||||
group("left-pad", 0, None, high),
|
||||
];
|
||||
let ranked: Vec<&str> = rank_updates(&groups)
|
||||
.iter()
|
||||
.map(|g| g.key.package.as_str())
|
||||
.collect();
|
||||
assert_eq!(ranked, ["vite", "openssl", "lodash"]);
|
||||
assert_eq!(update_label(&groups[1]), "vite 1.0.0 → 8.3.3");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_bar_is_as_wide_as_its_share_of_the_largest() {
|
||||
assert_eq!(bar_width(3, 3), "width: 100.0%");
|
||||
assert_eq!(bar_width(1, 4), "width: 25.0%");
|
||||
assert_eq!(bar_width(1, 1000), "width: 2.0%");
|
||||
assert_eq!(bar_width(0, 0), "width: 2.0%");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,191 @@
|
||||
//! The CRA Annex I view of a target (#957): its 40 requirements as tiles,
|
||||
//! coloured by state and marked with a sign, so the state is never told by
|
||||
//! colour alone. A tile opens the requirement with what its state rests on.
|
||||
|
||||
use dioxus::prelude::*;
|
||||
|
||||
use crate::app::Route;
|
||||
use crate::i18n::texts::{common, cra_tiles as tx};
|
||||
use crate::i18n::use_lang;
|
||||
use crate::infrastructure::evidence::fetch_compliance;
|
||||
use crate::pages::compliance::{ControlRow, STATES};
|
||||
use crate::pages::target_views::RepoView;
|
||||
|
||||
/// A tile's sign and CSS tone for a control `state` (as the API names it).
|
||||
fn mark(state: &str) -> (&'static str, &'static str) {
|
||||
match state {
|
||||
"not_satisfied" => ("!", "ct-bad"),
|
||||
"not_assessed" => ("?", "ct-open"),
|
||||
"partial" => ("~", "ct-partial"),
|
||||
"no_violation_found" => ("OK", "ct-ok"),
|
||||
_ => ("–", "ct-process"),
|
||||
}
|
||||
}
|
||||
|
||||
/// The short name a tile shows for control `id`: `cra-ai-7` is `AI-07`;
|
||||
/// another id stays as it is.
|
||||
fn short_id(id: &str) -> String {
|
||||
id.strip_prefix("cra-ai-")
|
||||
.and_then(|n| n.parse::<u32>().ok())
|
||||
.map_or_else(|| id.to_string(), |n| format!("AI-{n:02}"))
|
||||
}
|
||||
|
||||
/// `controls` in tile order: by the number of their id, others last.
|
||||
fn in_tile_order(mut controls: Vec<serde_json::Value>) -> Vec<serde_json::Value> {
|
||||
let number = |c: &serde_json::Value| {
|
||||
c["control"]
|
||||
.as_str()
|
||||
.and_then(|id| id.strip_prefix("cra-ai-"))
|
||||
.and_then(|n| n.parse::<u32>().ok())
|
||||
.unwrap_or(u32::MAX)
|
||||
};
|
||||
controls.sort_by_key(number);
|
||||
controls
|
||||
}
|
||||
|
||||
/// The tiles of target `target_id`, or, with `control` (from the URL) set,
|
||||
/// that requirement with its state, findings and reasons.
|
||||
#[component]
|
||||
pub fn CraTiles(target_id: String, control: Option<String>) -> Element {
|
||||
let lang = use_lang()();
|
||||
let id = target_id.clone();
|
||||
let view = use_resource(move || {
|
||||
let id = id.clone();
|
||||
async move { fetch_compliance(id).await.ok() }
|
||||
});
|
||||
let Some(loaded) = view.read().clone() else {
|
||||
return rsx! { div { class: "loading", {common::LOADING.get(lang)} } };
|
||||
};
|
||||
let Some(data) = loaded else {
|
||||
return rsx! { div { class: "card", p { {tx::LOAD_FAILED.get(lang)} } } };
|
||||
};
|
||||
let controls = in_tile_order(data["controls"].as_array().cloned().unwrap_or_default());
|
||||
let to_tile = |control: Option<String>| Route::TargetViewsPage {
|
||||
id: target_id.clone(),
|
||||
view: RepoView::Cra.slug().to_string(),
|
||||
cve_severity: None,
|
||||
cve_vex: None,
|
||||
control,
|
||||
scan: None,
|
||||
};
|
||||
|
||||
if let Some(wanted) = control {
|
||||
let back = to_tile(None);
|
||||
let Some(chosen) = controls
|
||||
.iter()
|
||||
.find(|c| c["control"].as_str() == Some(wanted.as_str()))
|
||||
.cloned()
|
||||
else {
|
||||
return rsx! {
|
||||
div { class: "card",
|
||||
p { {tx::UNKNOWN.get(lang)} }
|
||||
Link { class: "repo-view-list", to: back, {tx::BACK.get(lang)} }
|
||||
}
|
||||
};
|
||||
};
|
||||
let state = chosen["state"].as_str().unwrap_or_default().to_string();
|
||||
let (label, badge) = STATES
|
||||
.iter()
|
||||
.find(|(s, _, _)| *s == state)
|
||||
.map_or(("", "badge"), |(_, label, badge)| (label.get(lang), *badge));
|
||||
return rsx! {
|
||||
nav { class: "ct-crumbs", "aria-label": tx::BREADCRUMB.get(lang),
|
||||
Link { to: back.clone(), "CRA" }
|
||||
span { "aria-hidden": "true", " › " }
|
||||
strong { "{short_id(&wanted)} {chosen[\"title\"].as_str().unwrap_or_default()}" }
|
||||
Link { class: "btn btn-sm btn-ghost ct-back", to: back, {tx::BACK.get(lang)} }
|
||||
}
|
||||
section { class: "card ct-detail",
|
||||
p { span { class: "{badge}", "{label}" } }
|
||||
ul { class: "cra-controls",
|
||||
ControlRow { control: chosen, lang, show_reason: true }
|
||||
}
|
||||
Link {
|
||||
class: "repo-view-list",
|
||||
to: Route::CompliancePage { id: target_id.clone() },
|
||||
{tx::ALL_REQUIREMENTS.get(lang)}
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
rsx! {
|
||||
section { class: "card ct-card", "aria-label": tx::TITLE.get(lang),
|
||||
div { class: "ct-head",
|
||||
h3 { class: "ct-title", {tx::title(controls.len(), lang)} }
|
||||
div { class: "ct-legend",
|
||||
for (state, label, _) in STATES {
|
||||
{
|
||||
let (sign, tone) = mark(state);
|
||||
let n = controls.iter().filter(|c| c["state"].as_str() == Some(state)).count();
|
||||
rsx! {
|
||||
span { key: "{state}", class: "ct-legend-item",
|
||||
span { class: "ct-swatch {tone}", "aria-hidden": "true", "{sign}" }
|
||||
"{label.get(lang)} ({n})"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
div { class: "ct-grid",
|
||||
for c in controls.iter() {
|
||||
{
|
||||
let id = c["control"].as_str().unwrap_or_default().to_string();
|
||||
let state = c["state"].as_str().unwrap_or_default();
|
||||
let (sign, tone) = mark(state);
|
||||
let state_label = STATES
|
||||
.iter()
|
||||
.find(|(s, _, _)| *s == state)
|
||||
.map_or("", |(_, label, _)| label.get(lang));
|
||||
let tip = format!(
|
||||
"{}: {} ({state_label})",
|
||||
short_id(&id),
|
||||
c["title"].as_str().unwrap_or_default()
|
||||
);
|
||||
rsx! {
|
||||
Link {
|
||||
key: "{id}",
|
||||
class: "ct-tile {tone}",
|
||||
title: "{tip}",
|
||||
"aria-label": "{tip}",
|
||||
to: to_tile(Some(id.clone())),
|
||||
span { class: "ct-tile-id", "{short_id(&id)}" }
|
||||
span { class: "ct-tile-mark", "{sign}" }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
p { class: "ct-hint", {tx::HINT.get(lang)} }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn a_tile_names_its_requirement_short_and_in_number_order() {
|
||||
assert_eq!(short_id("cra-ai-7"), "AI-07");
|
||||
assert_eq!(short_id("cra-ai-40"), "AI-40");
|
||||
assert_eq!(short_id("custom"), "custom");
|
||||
let ordered = in_tile_order(vec![
|
||||
serde_json::json!({ "control": "cra-ai-10" }),
|
||||
serde_json::json!({ "control": "other" }),
|
||||
serde_json::json!({ "control": "cra-ai-2" }),
|
||||
]);
|
||||
let ids: Vec<&str> = ordered
|
||||
.iter()
|
||||
.filter_map(|c| c["control"].as_str())
|
||||
.collect();
|
||||
assert_eq!(ids, ["cra-ai-2", "cra-ai-10", "other"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_state_has_its_own_sign() {
|
||||
let signs: Vec<&str> = STATES.iter().map(|(s, _, _)| mark(s).0).collect();
|
||||
assert_eq!(signs, ["!", "?", "~", "OK", "–"]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,424 @@
|
||||
//! The "CVEs & VEX" view on a target (#957): a grid of severity against VEX
|
||||
//! status with a count per cell, shaded on one blue scale, and behind each
|
||||
//! count the target's CVE list narrowed to that cell. The choice lives in
|
||||
//! the page's URL (`?cve_severity=high&cve_vex=open`), so a narrowed list
|
||||
//! can be linked and the browser's back button returns to the grid.
|
||||
|
||||
use dioxus::prelude::*;
|
||||
use dioxus_free_icons::icons::bs_icons::BsArrowLeft;
|
||||
use dioxus_free_icons::Icon;
|
||||
|
||||
use compliance_core::cve_matrix::{CveFilter, CveMatrix, CveSeverity, VexColumn};
|
||||
|
||||
use crate::app::Route;
|
||||
use crate::components::vex_panel::VexPanel;
|
||||
use crate::i18n::texts::{common, cve_matrix as tx, vex as vex_tx};
|
||||
use crate::i18n::{use_lang, Lang};
|
||||
use crate::infrastructure::cve_matrix::fetch_cve_matrix;
|
||||
use crate::pages::target_views::RepoView;
|
||||
|
||||
/// The query value for "every severity and status": the whole list.
|
||||
const ALL: &str = "all";
|
||||
|
||||
/// The steps of the blue scale above 0 (`.cve-shade-1` to `.cve-shade-5`).
|
||||
const SHADES: u64 = 5;
|
||||
|
||||
/// What the target page's CVE query asks for.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
enum Selection {
|
||||
/// No CVE query: the grid.
|
||||
Grid,
|
||||
/// The list narrowed to a cell, row or column of the grid.
|
||||
List(Option<CveFilter>),
|
||||
}
|
||||
|
||||
/// The selection of the query values `severity` and `vex`. An absent or
|
||||
/// unknown value leaves its side open; when both sides are open the list
|
||||
/// is the whole one as it always was (resolved alerts included), `None`.
|
||||
fn selection(severity: Option<&str>, vex: Option<&str>) -> Selection {
|
||||
if severity.is_none() && vex.is_none() {
|
||||
return Selection::Grid;
|
||||
}
|
||||
let filter = CveFilter {
|
||||
severity: severity.and_then(CveSeverity::parse),
|
||||
vex: vex.and_then(VexColumn::parse),
|
||||
};
|
||||
Selection::List((filter != CveFilter::default()).then_some(filter))
|
||||
}
|
||||
|
||||
/// The target page of `target_id` with its CVE list narrowed to `filter`,
|
||||
/// or the whole list for `None`.
|
||||
fn list_route(target_id: &str, filter: Option<CveFilter>) -> Route {
|
||||
let filter = filter.unwrap_or_default();
|
||||
let severity = filter.severity.map(|s| s.as_str().to_string());
|
||||
// Neither side named would mean the grid; `all` asks for the list.
|
||||
let vex = filter
|
||||
.vex
|
||||
.map(VexColumn::as_str)
|
||||
.or(severity.is_none().then_some(ALL))
|
||||
.map(String::from);
|
||||
Route::TargetViewsPage {
|
||||
id: target_id.to_string(),
|
||||
view: RepoView::Cves.slug().to_string(),
|
||||
cve_severity: severity,
|
||||
cve_vex: vex,
|
||||
control: None,
|
||||
scan: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The step of the blue scale for `count` in a grid whose largest cell is
|
||||
/// `max`: 0 for an empty cell, else 1 to [`SHADES`] in proportion, rounded
|
||||
/// up so that a single CVE is never shaded like none.
|
||||
fn shade(count: u64, max: u64) -> u64 {
|
||||
if count == 0 || max == 0 {
|
||||
return 0;
|
||||
}
|
||||
// Integer ceiling of SHADES * count / max, no floats.
|
||||
(SHADES * count).div_ceil(max).min(SHADES)
|
||||
}
|
||||
|
||||
/// What the breadcrumb names the selection: "hoch · offen", "offen", "alle".
|
||||
fn crumb(filter: Option<CveFilter>, lang: Lang) -> String {
|
||||
let filter = filter.unwrap_or_default();
|
||||
let parts: Vec<&str> = [
|
||||
filter.severity.map(|s| tx::severity(s).get(lang)),
|
||||
filter.vex.map(|v| tx::vex(v).get(lang)),
|
||||
]
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.collect();
|
||||
if parts.is_empty() {
|
||||
tx::ALL.get(lang).to_string()
|
||||
} else {
|
||||
parts.join(" · ")
|
||||
}
|
||||
}
|
||||
|
||||
/// What a cell says to a screen reader and on hover: "hoch, offen: 12".
|
||||
fn cell_label(severity: CveSeverity, vex: VexColumn, count: u64, lang: Lang) -> String {
|
||||
format!(
|
||||
"{}, {}: {count}",
|
||||
tx::severity(severity).get(lang),
|
||||
tx::vex(vex).get(lang)
|
||||
)
|
||||
}
|
||||
|
||||
/// The "Schwachstellen und VEX" card body of target `target_id`: the grid,
|
||||
/// or the CVE list narrowed to the cell the query `cve_severity` /
|
||||
/// `cve_vex` names.
|
||||
#[component]
|
||||
pub fn CveView(
|
||||
target_id: String,
|
||||
cve_severity: Option<String>,
|
||||
cve_vex: Option<String>,
|
||||
) -> Element {
|
||||
let lang = use_lang()();
|
||||
match selection(cve_severity.as_deref(), cve_vex.as_deref()) {
|
||||
Selection::Grid => rsx! { CveGrid { target_id } },
|
||||
Selection::List(filter) => rsx! {
|
||||
nav { class: "cve-crumbs", "aria-label": tx::CVES.get(lang),
|
||||
Link { class: "btn btn-ghost btn-back", to: Route::target_view(target_id.clone(), RepoView::Cves),
|
||||
Icon { icon: BsArrowLeft, width: 16, height: 16 }
|
||||
{tx::BACK.get(lang)}
|
||||
}
|
||||
span { class: "cve-crumb-trail",
|
||||
Link { to: Route::target_view(target_id.clone(), RepoView::Cves), {tx::CVES.get(lang)} }
|
||||
span { "aria-hidden": "true", " › " }
|
||||
span { "aria-current": "page", "{crumb(filter, lang)}" }
|
||||
}
|
||||
}
|
||||
VexPanel { target_id, filter }
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// The grid (or, toggled, the table) of target `target_id`'s counts. Mounted
|
||||
/// afresh on every return from the list, so statements made there show.
|
||||
#[component]
|
||||
fn CveGrid(target_id: String) -> Element {
|
||||
let lang = use_lang()();
|
||||
let navigator = use_navigator();
|
||||
let id_for_load = target_id.clone();
|
||||
let matrix = use_resource(move || {
|
||||
let id = id_for_load.clone();
|
||||
async move { fetch_cve_matrix(id).await.ok() }
|
||||
});
|
||||
let mut as_table = use_signal(|| false);
|
||||
|
||||
let guard = matrix.read();
|
||||
let matrix = match &*guard {
|
||||
None => return rsx! { div { class: "loading", {common::LOADING.get(lang)} } },
|
||||
Some(None) => return rsx! { p { class: "target-muted", {vex_tx::LOAD_FAILED.get(lang)} } },
|
||||
Some(Some(m)) => m,
|
||||
};
|
||||
let unassessed = matrix.unassessed();
|
||||
let open_route = list_route(
|
||||
&target_id,
|
||||
Some(CveFilter {
|
||||
severity: None,
|
||||
vex: Some(VexColumn::Open),
|
||||
}),
|
||||
);
|
||||
let all_route = list_route(&target_id, None);
|
||||
|
||||
rsx! {
|
||||
div { class: "cve-matrix-head",
|
||||
p { class: "target-muted", {tx::HINT.get(lang)} }
|
||||
if matrix.total() > 0 {
|
||||
div { class: "cve-view-toggle", role: "group", "aria-label": tx::VIEW.get(lang),
|
||||
button {
|
||||
class: "btn btn-sm",
|
||||
"aria-pressed": "{!as_table()}",
|
||||
onclick: move |_| as_table.set(false),
|
||||
{tx::CHART.get(lang)}
|
||||
}
|
||||
button {
|
||||
class: "btn btn-sm",
|
||||
"aria-pressed": "{as_table()}",
|
||||
onclick: move |_| as_table.set(true),
|
||||
{tx::TABLE.get(lang)}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if matrix.total() == 0 {
|
||||
p { class: "target-muted", {vex_tx::NONE.get(lang)} }
|
||||
} else if as_table() {
|
||||
CveTable { target_id: target_id.clone(), matrix: matrix.clone() }
|
||||
} else {
|
||||
CveChart { target_id: target_id.clone(), matrix: matrix.clone() }
|
||||
}
|
||||
div { class: "cve-matrix-foot",
|
||||
if matrix.total() > 0 {
|
||||
button {
|
||||
class: "cve-unassessed",
|
||||
disabled: unassessed == 0,
|
||||
onclick: move |_| { navigator.push(open_route.clone()); },
|
||||
span { {tx::UNASSESSED.get(lang)} ": " }
|
||||
strong { "{unassessed}" }
|
||||
}
|
||||
}
|
||||
button {
|
||||
class: "btn btn-ghost btn-sm",
|
||||
onclick: move |_| { navigator.push(all_route.clone()); },
|
||||
{tx::LIST_AND_EXPORTS.get(lang)}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The grid itself: a row per severity, a column per VEX status, each cell
|
||||
/// a button into the narrowed list.
|
||||
#[component]
|
||||
fn CveChart(target_id: String, matrix: CveMatrix) -> Element {
|
||||
let lang = use_lang()();
|
||||
let max = matrix.max();
|
||||
rsx! {
|
||||
div { class: "cve-grid-wrap",
|
||||
div { class: "cve-grid",
|
||||
span {}
|
||||
for vex in VexColumn::ALL {
|
||||
span { class: "cve-grid-col", {tx::vex(vex).get(lang)} }
|
||||
}
|
||||
for severity in matrix.rows() {
|
||||
span { class: "cve-grid-row", {tx::severity(severity).get(lang)} }
|
||||
for vex in VexColumn::ALL {
|
||||
CveCellButton {
|
||||
target_id: target_id.clone(),
|
||||
severity,
|
||||
vex,
|
||||
count: matrix.count(severity, vex),
|
||||
max,
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
div { class: "cve-scale", "aria-hidden": "true",
|
||||
span { {tx::FEW.get(lang)} }
|
||||
for step in 1..=SHADES {
|
||||
span { class: "cve-scale-step cve-shade-{step}" }
|
||||
}
|
||||
span { {tx::MANY.get(lang)} }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One cell of the grid. An empty cell is disabled: it would open an empty
|
||||
/// list.
|
||||
#[component]
|
||||
fn CveCellButton(
|
||||
target_id: String,
|
||||
severity: CveSeverity,
|
||||
vex: VexColumn,
|
||||
count: u64,
|
||||
max: u64,
|
||||
) -> Element {
|
||||
let lang = use_lang()();
|
||||
let navigator = use_navigator();
|
||||
let label = cell_label(severity, vex, count, lang);
|
||||
let step = shade(count, max);
|
||||
rsx! {
|
||||
button {
|
||||
class: "cve-cell cve-shade-{step}",
|
||||
"aria-label": "{label}",
|
||||
title: "{label}",
|
||||
disabled: count == 0,
|
||||
onclick: move |_| {
|
||||
navigator.push(list_route(&target_id, Some(CveFilter {
|
||||
severity: Some(severity),
|
||||
vex: Some(vex),
|
||||
})));
|
||||
},
|
||||
"{count}"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The same counts as a plain table, for screen readers and for reading
|
||||
/// exact numbers; a count links to the narrowed list as in the grid.
|
||||
#[component]
|
||||
fn CveTable(target_id: String, matrix: CveMatrix) -> Element {
|
||||
let lang = use_lang()();
|
||||
rsx! {
|
||||
div { class: "table-wrapper",
|
||||
table { class: "cve-table",
|
||||
caption { class: "sr-only", {tx::CAPTION.get(lang)} }
|
||||
thead {
|
||||
tr {
|
||||
th { scope: "col", {tx::SEVERITY.get(lang)} }
|
||||
for vex in VexColumn::ALL {
|
||||
th { scope: "col", {tx::vex(vex).get(lang)} }
|
||||
}
|
||||
}
|
||||
}
|
||||
tbody {
|
||||
for severity in matrix.rows() {
|
||||
tr {
|
||||
th { scope: "row", {tx::severity(severity).get(lang)} }
|
||||
for vex in VexColumn::ALL {
|
||||
{
|
||||
let count = matrix.count(severity, vex);
|
||||
let to = list_route(&target_id, Some(CveFilter {
|
||||
severity: Some(severity),
|
||||
vex: Some(vex),
|
||||
}));
|
||||
rsx! {
|
||||
td {
|
||||
if count > 0 {
|
||||
Link {
|
||||
to,
|
||||
"aria-label": cell_label(severity, vex, count, lang),
|
||||
"{count}"
|
||||
}
|
||||
} else {
|
||||
"0"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn no_query_shows_the_grid_and_any_query_the_list() {
|
||||
assert_eq!(selection(None, None), Selection::Grid);
|
||||
assert_eq!(
|
||||
selection(Some("high"), Some("open")),
|
||||
Selection::List(Some(CveFilter {
|
||||
severity: Some(CveSeverity::High),
|
||||
vex: Some(VexColumn::Open),
|
||||
}))
|
||||
);
|
||||
assert_eq!(
|
||||
selection(None, Some("open")),
|
||||
Selection::List(Some(CveFilter {
|
||||
severity: None,
|
||||
vex: Some(VexColumn::Open),
|
||||
}))
|
||||
);
|
||||
assert_eq!(selection(None, Some(ALL)), Selection::List(None));
|
||||
assert_eq!(selection(Some("bogus"), None), Selection::List(None));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_route_reads_back_as_its_selection() {
|
||||
let filters = [
|
||||
None,
|
||||
Some(CveFilter {
|
||||
severity: Some(CveSeverity::Unknown),
|
||||
vex: Some(VexColumn::NotAffected),
|
||||
}),
|
||||
Some(CveFilter {
|
||||
severity: None,
|
||||
vex: Some(VexColumn::Open),
|
||||
}),
|
||||
Some(CveFilter {
|
||||
severity: Some(CveSeverity::Low),
|
||||
vex: None,
|
||||
}),
|
||||
];
|
||||
for filter in filters {
|
||||
let Route::TargetViewsPage {
|
||||
id,
|
||||
view,
|
||||
cve_severity,
|
||||
cve_vex,
|
||||
..
|
||||
} = list_route("t1", filter)
|
||||
else {
|
||||
panic!("not the target page");
|
||||
};
|
||||
assert_eq!((id.as_str(), view.as_str()), ("t1", "cves"));
|
||||
assert_eq!(
|
||||
selection(cve_severity.as_deref(), cve_vex.as_deref()),
|
||||
Selection::List(filter)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_shade_rises_with_the_count_and_one_cve_is_never_blank() {
|
||||
assert_eq!(shade(0, 10), 0);
|
||||
assert_eq!(shade(0, 0), 0);
|
||||
assert_eq!(shade(1, 100), 1);
|
||||
assert_eq!(shade(10, 10), SHADES);
|
||||
assert_eq!(shade(5, 10), 3);
|
||||
assert_eq!(shade(7, 7), SHADES);
|
||||
assert_eq!((shade(40, 100), shade(41, 100)), (2, 3));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn labels_name_row_column_and_count() {
|
||||
assert_eq!(
|
||||
cell_label(CveSeverity::High, VexColumn::Open, 12, Lang::De),
|
||||
"hoch, offen: 12"
|
||||
);
|
||||
assert_eq!(
|
||||
cell_label(CveSeverity::Critical, VexColumn::NotAffected, 0, Lang::En),
|
||||
"critical, not affected: 0"
|
||||
);
|
||||
let cell = Some(CveFilter {
|
||||
severity: Some(CveSeverity::High),
|
||||
vex: Some(VexColumn::Open),
|
||||
});
|
||||
assert_eq!(crumb(cell, Lang::De), "hoch · offen");
|
||||
let column = Some(CveFilter {
|
||||
severity: None,
|
||||
vex: Some(VexColumn::UnderInvestigation),
|
||||
});
|
||||
assert_eq!(crumb(column, Lang::De), "in Prüfung");
|
||||
assert_eq!(crumb(None, Lang::De), "alle");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,286 @@
|
||||
//! The CVE trend (#952): the KPI tiles and the stacked bar chart of the last
|
||||
//! 30 days, the sparkline of a project or target, and a target's "Wo
|
||||
//! handeln" table. Used by the overview and the target page. Plain HTML,
|
||||
//! CSS and SVG; no chart library.
|
||||
|
||||
use compliance_core::cve_history::{CveDay, CveHistory};
|
||||
use dioxus::prelude::*;
|
||||
use dioxus_free_icons::icons::bs_icons::BsArrowRight;
|
||||
use dioxus_free_icons::Icon;
|
||||
|
||||
use crate::app::Route;
|
||||
use crate::i18n::texts::{common, cve_trend as tx};
|
||||
use crate::i18n::use_lang;
|
||||
use crate::infrastructure::cve_history::{fetch_cve_history, fetch_top_updates};
|
||||
|
||||
/// The y axis' top for a highest bar of `max`: the smallest of 2, 4, 6, 8
|
||||
/// and 10 times a power of ten that is not below it. Always even, so the
|
||||
/// middle label is a whole number.
|
||||
pub fn axis_top(max: u32) -> u32 {
|
||||
let mut scale: u64 = 1;
|
||||
loop {
|
||||
for step in [2u64, 4, 6, 8, 10] {
|
||||
let top = step * scale;
|
||||
if top >= u64::from(max) {
|
||||
return u32::try_from(top).unwrap_or(u32::MAX);
|
||||
}
|
||||
}
|
||||
scale *= 10;
|
||||
}
|
||||
}
|
||||
|
||||
/// The points of a sparkline of `values` in a `width` × `height` box: the
|
||||
/// first value at the left edge, the last at the right, 0 one unit above
|
||||
/// the bottom and the highest value one unit below the top.
|
||||
pub fn sparkline_points(values: &[u32], width: f32, height: f32) -> String {
|
||||
let max = values.iter().copied().max().unwrap_or(0).max(1) as f32;
|
||||
let step = if values.len() > 1 {
|
||||
width / (values.len() - 1) as f32
|
||||
} else {
|
||||
0.0
|
||||
};
|
||||
let usable = (height - 2.0).max(0.0);
|
||||
values
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, v)| {
|
||||
let x = i as f32 * step;
|
||||
let y = height - 1.0 - (*v as f32 / max) * usable;
|
||||
format!("{x:.1},{y:.1}")
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
.join(" ")
|
||||
}
|
||||
|
||||
/// The change from the first to the last day of `days` of the count `of`.
|
||||
pub fn change(days: &[CveDay], of: fn(&CveDay) -> u32) -> i64 {
|
||||
match (days.first(), days.last()) {
|
||||
(Some(first), Some(last)) => i64::from(of(last)) - i64::from(of(first)),
|
||||
_ => 0,
|
||||
}
|
||||
}
|
||||
|
||||
/// A bar's height in percent of the axis' `top`.
|
||||
fn percent(n: u32, top: u32) -> f32 {
|
||||
n as f32 * 100.0 / top.max(1) as f32
|
||||
}
|
||||
|
||||
/// The four tiles and the bar chart of one scope (the tenant, or the target
|
||||
/// `target`; empty for the tenant). Each tile opens the list behind it,
|
||||
/// filtered to the target.
|
||||
#[component]
|
||||
pub fn CveDashboard(history: CveHistory, target: String) -> Element {
|
||||
let lang = use_lang()();
|
||||
let days = &history.days;
|
||||
let today = days.last().copied().unwrap_or_default();
|
||||
let span = days.len();
|
||||
let critical_change = tx::change(change(days, |d| d.critical), span, lang);
|
||||
let high_change = tx::change(change(days, |d| d.high), span, lang);
|
||||
let findings = history.open_findings;
|
||||
rsx! {
|
||||
div { class: "ov-figures",
|
||||
Link { to: Route::SbomPage { target: target.clone() }, class: "ov-figure",
|
||||
span { class: "ov-figure-label", {tx::CVE_CRITICAL.get(lang)} }
|
||||
span { class: "ov-figure-value cve-kpi-critical", "{today.critical}" }
|
||||
span { class: "ov-figure-sub", "{critical_change}" }
|
||||
}
|
||||
Link { to: Route::SbomPage { target: target.clone() }, class: "ov-figure",
|
||||
span { class: "ov-figure-label", {tx::CVE_HIGH.get(lang)} }
|
||||
span { class: "ov-figure-value cve-kpi-high", "{today.high}" }
|
||||
span { class: "ov-figure-sub", "{high_change}" }
|
||||
}
|
||||
Link { to: Route::findings(target.clone()), class: "ov-figure",
|
||||
span { class: "ov-figure-label", {tx::FINDINGS_CRITICAL.get(lang)} }
|
||||
span { class: "ov-figure-value", "{findings.critical}" }
|
||||
span { class: "ov-figure-sub", {tx::OPEN_NOW.get(lang)} }
|
||||
}
|
||||
Link { to: Route::findings(target), class: "ov-figure",
|
||||
span { class: "ov-figure-label", {tx::FINDINGS_HIGH.get(lang)} }
|
||||
span { class: "ov-figure-value", "{findings.high}" }
|
||||
span { class: "ov-figure-sub", {tx::OPEN_NOW.get(lang)} }
|
||||
}
|
||||
}
|
||||
section { class: "card cve-chart-card",
|
||||
div { class: "cve-chart-head",
|
||||
div {
|
||||
h3 { {tx::CHART_TITLE.get(lang)} }
|
||||
p { {tx::CHART_HINT.get(lang)} }
|
||||
}
|
||||
ul { class: "cve-legend",
|
||||
li { span { class: "cve-dot cve-critical" } {common::CRITICAL.get(lang)} }
|
||||
li { span { class: "cve-dot cve-high" } {common::HIGH.get(lang)} }
|
||||
}
|
||||
}
|
||||
CveBars { days: history.days.clone() }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The stacked bars of `days`: critical at the bottom, high on top, one bar
|
||||
/// a day with its counts as the tooltip; the axis reads 0, middle and top.
|
||||
#[component]
|
||||
pub fn CveBars(days: Vec<CveDay>) -> Element {
|
||||
let lang = use_lang()();
|
||||
let top = axis_top(days.iter().map(CveDay::urgent).max().unwrap_or(0));
|
||||
let mid = top / 2;
|
||||
let first = days.first().map(|d| d.date.format("%d.%m.").to_string());
|
||||
let last = days.last().map(|d| d.date.format("%d.%m.").to_string());
|
||||
rsx! {
|
||||
div { class: "cve-chart",
|
||||
div { class: "cve-chart-axis", "aria-hidden": "true",
|
||||
span { "{top}" }
|
||||
span { "{mid}" }
|
||||
span { "0" }
|
||||
}
|
||||
div { class: "cve-chart-bars", role: "img", "aria-label": tx::CHART_LABEL.get(lang),
|
||||
for day in days {
|
||||
div {
|
||||
key: "{day.date}",
|
||||
class: "cve-bar",
|
||||
title: tx::bar_title(day.date, day.critical, day.high, lang),
|
||||
span { class: "cve-bar-high", style: "height: {percent(day.high, top)}%;" }
|
||||
span { class: "cve-bar-critical", style: "height: {percent(day.critical, top)}%;" }
|
||||
}
|
||||
}
|
||||
}
|
||||
div { class: "cve-chart-dates", "aria-hidden": "true",
|
||||
span { {first.unwrap_or_default()} }
|
||||
span { {last.unwrap_or_default()} }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A small line of `values` (oldest first), in the text colour around it.
|
||||
#[component]
|
||||
pub fn Sparkline(values: Vec<u32>, label: String) -> Element {
|
||||
let points = sparkline_points(&values, 100.0, 24.0);
|
||||
rsx! {
|
||||
svg {
|
||||
class: "cve-spark",
|
||||
view_box: "0 0 100 24",
|
||||
preserve_aspect_ratio: "none",
|
||||
role: "img",
|
||||
"aria-label": "{label}",
|
||||
polyline {
|
||||
points: "{points}",
|
||||
fill: "none",
|
||||
stroke: "currentColor",
|
||||
stroke_width: "1.5",
|
||||
stroke_linejoin: "round",
|
||||
vector_effect: "non-scaling-stroke",
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The top of a target's page: its tiles and chart, and the package updates
|
||||
/// that close the most of its open CVEs with a fix.
|
||||
#[component]
|
||||
pub fn TargetCveDashboard(target_id: String) -> Element {
|
||||
let lang = use_lang()();
|
||||
let id = use_signal(|| target_id.clone());
|
||||
let history = use_resource(move || async move { fetch_cve_history(id(), false).await.ok() });
|
||||
let updates = use_resource(move || async move { fetch_top_updates(id()).await.ok() });
|
||||
rsx! {
|
||||
match history.read().clone() {
|
||||
Some(Some(history)) => rsx! { CveDashboard { history, target: target_id.clone() } },
|
||||
Some(None) => rsx! { div { class: "card", p { class: "target-muted", {tx::LOAD_FAILED.get(lang)} } } },
|
||||
None => rsx! { div { class: "loading", {common::LOADING.get(lang)} } },
|
||||
}
|
||||
section { class: "card cve-act",
|
||||
div { class: "target-card-head",
|
||||
div {
|
||||
h3 { {tx::WHERE_TO_ACT.get(lang)} }
|
||||
p { class: "target-muted", {tx::WHERE_TO_ACT_HINT.get(lang)} }
|
||||
}
|
||||
Link { to: Route::SbomPage { target: target_id.clone() }, class: "target-card-link",
|
||||
{tx::ALL_CVES.get(lang)}
|
||||
Icon { icon: BsArrowRight, width: 14, height: 14 }
|
||||
}
|
||||
}
|
||||
match &*updates.read() {
|
||||
Some(Some(list)) if list.is_empty() => rsx! { p { class: "target-muted", {tx::NO_UPDATES.get(lang)} } },
|
||||
Some(Some(list)) => rsx! {
|
||||
div { class: "table-wrapper",
|
||||
table { class: "cve-act-table",
|
||||
thead {
|
||||
tr {
|
||||
th { {tx::COL_PACKAGE.get(lang)} }
|
||||
th { {tx::COL_CURRENT.get(lang)} }
|
||||
th { {tx::COL_FIXED.get(lang)} }
|
||||
th { class: "num", {tx::COL_CVES.get(lang)} }
|
||||
}
|
||||
}
|
||||
tbody {
|
||||
for update in list.iter() {
|
||||
tr { key: "{update.package}@{update.current_version}",
|
||||
td { code { "{update.package}" } }
|
||||
td { code { "{update.current_version}" } }
|
||||
td { code { "{update.fixed_version}" } }
|
||||
td { class: "num",
|
||||
strong { "{update.cves}" }
|
||||
if update.critical > 0 {
|
||||
span { class: "cve-act-critical", {tx::of_them_critical(update.critical, lang)} }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
Some(None) => rsx! { p { class: "target-muted", {tx::LOAD_FAILED.get(lang)} } },
|
||||
None => rsx! { div { class: "loading", {common::LOADING.get(lang)} } },
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn day(critical: u32, high: u32) -> CveDay {
|
||||
CveDay {
|
||||
critical,
|
||||
high,
|
||||
..CveDay::default()
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_axis_top_is_even_and_not_below_the_highest_bar() {
|
||||
assert_eq!(axis_top(0), 2);
|
||||
assert_eq!(axis_top(1), 2);
|
||||
assert_eq!(axis_top(3), 4);
|
||||
assert_eq!(axis_top(7), 8);
|
||||
assert_eq!(axis_top(11), 20);
|
||||
assert_eq!(axis_top(41), 60);
|
||||
assert_eq!(axis_top(1000), 1000);
|
||||
assert_eq!(axis_top(u32::MAX), u32::MAX);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_sparkline_spans_the_box_from_bottom_to_top() {
|
||||
assert_eq!(
|
||||
sparkline_points(&[0, 5, 10], 100.0, 24.0),
|
||||
"0.0,23.0 50.0,12.0 100.0,1.0"
|
||||
);
|
||||
// All zero: a flat line at the bottom, no division by zero.
|
||||
assert_eq!(
|
||||
sparkline_points(&[0, 0], 100.0, 24.0),
|
||||
"0.0,23.0 100.0,23.0"
|
||||
);
|
||||
assert_eq!(sparkline_points(&[3], 100.0, 24.0), "0.0,1.0");
|
||||
assert_eq!(sparkline_points(&[], 100.0, 24.0), "");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_change_is_the_last_day_against_the_first() {
|
||||
let days = [day(4, 1), day(9, 9), day(2, 6)];
|
||||
assert_eq!(change(&days, |d| d.critical), -2);
|
||||
assert_eq!(change(&days, |d| d.high), 5);
|
||||
assert_eq!(change(&[], |d| d.high), 0);
|
||||
}
|
||||
}
|
||||
@@ -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 {
|
||||
|
||||
@@ -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<T: serde::de::DeserializeOwned>(value: &str) -> Option<T> {
|
||||
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::<ScanType>(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::<Severity>(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::<Vec<_>>()
|
||||
.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<String>,
|
||||
severity: Option<String>,
|
||||
path: Option<String>,
|
||||
) -> 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"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -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<String>,
|
||||
targets: Resource<Option<TargetsResponse>>,
|
||||
) -> Element {
|
||||
let lang = use_lang()();
|
||||
let can_write = crate::components::no_access::use_can_write();
|
||||
let mut toasts = use_context::<Toasts>();
|
||||
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::<String>::new);
|
||||
// The group whose risk is being accepted, waiting for the reason.
|
||||
let mut reasoning = use_signal(|| None::<String>);
|
||||
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<String>| {
|
||||
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<String, String> {
|
||||
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")
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,157 @@
|
||||
//! The licences view of one target (#957): its components as one bar split
|
||||
//! into four licence groups, with a card per group below it. A click on a
|
||||
//! segment or a card narrows the licence table of the tab to that group; a
|
||||
//! breadcrumb leads back to the chart. A "Tabelle" toggle shows the same
|
||||
//! numbers as a plain table.
|
||||
|
||||
use dioxus::prelude::*;
|
||||
|
||||
use compliance_core::models::license::{LicenseGroup, LicenseGroupCounts};
|
||||
|
||||
use crate::i18n::texts::licence_overview as tx;
|
||||
use crate::i18n::{format_count, use_lang};
|
||||
|
||||
/// The class that gives a group its colour (`--lo-color`).
|
||||
fn group_class(group: LicenseGroup) -> &'static str {
|
||||
match group {
|
||||
LicenseGroup::Permissive => "lo-permissive",
|
||||
LicenseGroup::WeakCopyleft => "lo-weak",
|
||||
LicenseGroup::StrongCopyleft => "lo-strong",
|
||||
LicenseGroup::Unknown => "lo-unknown",
|
||||
}
|
||||
}
|
||||
|
||||
/// The chart of `counts`, or, once a group is `selected`, the breadcrumb of
|
||||
/// that group with the way back. Nothing while there are no components.
|
||||
///
|
||||
/// # Arguments
|
||||
///
|
||||
/// * `counts` - the target's components per licence group
|
||||
/// * `selected` - the group the licence table is narrowed to; written on a
|
||||
/// click, cleared by the way back
|
||||
#[component]
|
||||
pub fn LicenceOverview(
|
||||
counts: LicenseGroupCounts,
|
||||
mut selected: Signal<Option<LicenseGroup>>,
|
||||
) -> Element {
|
||||
let lang = use_lang()();
|
||||
let mut as_table = use_signal(|| false);
|
||||
|
||||
if let Some(group) = selected() {
|
||||
return rsx! {
|
||||
nav { class: "lo-crumbs", "aria-label": tx::BREADCRUMB.get(lang),
|
||||
button {
|
||||
class: "lo-crumb-link",
|
||||
onclick: move |_| selected.set(None),
|
||||
{tx::BREADCRUMB_ROOT.get(lang)}
|
||||
}
|
||||
span { class: "lo-crumb-sep", "aria-hidden": "true", "›" }
|
||||
span { class: "lo-crumb-current", "aria-current": "page",
|
||||
{tx::group(group).get(lang)}
|
||||
}
|
||||
button {
|
||||
class: "btn btn-sm btn-ghost lo-back",
|
||||
onclick: move |_| selected.set(None),
|
||||
{tx::BACK.get(lang)}
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
if counts.total() == 0 {
|
||||
return rsx! {};
|
||||
}
|
||||
|
||||
rsx! {
|
||||
div { class: "card lo-card",
|
||||
div { class: "lo-head",
|
||||
h3 { class: "lo-title", {tx::TITLE.get(lang)} }
|
||||
// A toggle: the label stays, the pressed state changes.
|
||||
button {
|
||||
class: "btn btn-sm btn-ghost lo-toggle",
|
||||
"aria-pressed": "{as_table()}",
|
||||
onclick: move |_| as_table.toggle(),
|
||||
{tx::TABLE.get(lang)}
|
||||
}
|
||||
}
|
||||
p { class: "lo-hint", {tx::HINT.get(lang)} }
|
||||
if as_table() {
|
||||
div { class: "table-wrapper",
|
||||
table {
|
||||
thead {
|
||||
tr {
|
||||
th { {tx::GROUP.get(lang)} }
|
||||
th { {tx::COMPONENTS.get(lang)} }
|
||||
th { {tx::NOTE.get(lang)} }
|
||||
}
|
||||
}
|
||||
tbody {
|
||||
for group in LicenseGroup::ALL {
|
||||
tr { key: "{group_class(group)}",
|
||||
td {
|
||||
button {
|
||||
class: "lo-table-link",
|
||||
onclick: move |_| selected.set(Some(group)),
|
||||
{tx::group(group).get(lang)}
|
||||
}
|
||||
}
|
||||
td { class: "lo-num", {format_count(counts.get(group), lang)} }
|
||||
td { {tx::note(group).get(lang)} }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
div { class: "lo-bar", role: "group", "aria-label": tx::TITLE.get(lang),
|
||||
// An empty group has no segment; its card still says 0.
|
||||
for group in LicenseGroup::ALL.into_iter().filter(|g| counts.get(*g) > 0) {
|
||||
button {
|
||||
key: "{group_class(group)}",
|
||||
class: "lo-seg {group_class(group)}",
|
||||
style: "flex-grow: {counts.get(group)};",
|
||||
title: tx::segment_label(group, counts.get(group), lang),
|
||||
"aria-label": tx::segment_label(group, counts.get(group), lang),
|
||||
onclick: move |_| selected.set(Some(group)),
|
||||
}
|
||||
}
|
||||
}
|
||||
div { class: "lo-groups",
|
||||
for group in LicenseGroup::ALL {
|
||||
button {
|
||||
key: "{group_class(group)}",
|
||||
class: "lo-group {group_class(group)}",
|
||||
onclick: move |_| selected.set(Some(group)),
|
||||
span { class: "lo-group-name",
|
||||
span { class: "lo-swatch", "aria-hidden": "true" }
|
||||
{tx::group(group).get(lang)}
|
||||
}
|
||||
span { class: "lo-group-count",
|
||||
strong { {format_count(counts.get(group), lang)} }
|
||||
" "
|
||||
{tx::COMPONENTS.get(lang)}
|
||||
}
|
||||
span { class: "lo-group-note", {tx::note(group).get(lang)} }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn every_group_has_a_colour_class_of_its_own() {
|
||||
let classes: std::collections::HashSet<_> =
|
||||
LicenseGroup::ALL.into_iter().map(group_class).collect();
|
||||
assert_eq!(classes.len(), LicenseGroup::ALL.len());
|
||||
let css = include_str!("../../assets/main.css");
|
||||
for class in classes {
|
||||
assert!(css.contains(&format!(".{class} {{ --lo-color:")), "{class}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -4,14 +4,21 @@ pub mod attack_chain;
|
||||
pub mod billing_swap;
|
||||
pub mod code_inspector;
|
||||
pub mod code_snippet;
|
||||
pub mod component_overview;
|
||||
pub mod copy_button;
|
||||
pub mod cra_bar;
|
||||
pub mod cra_tiles;
|
||||
pub mod cve_matrix;
|
||||
pub mod cve_trend;
|
||||
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;
|
||||
pub mod licence_overview;
|
||||
pub mod license_editor;
|
||||
pub mod license_review;
|
||||
pub mod manual_findings;
|
||||
@@ -23,6 +30,7 @@ pub mod pagination;
|
||||
pub mod pentest_wizard;
|
||||
pub mod projects;
|
||||
pub mod scan_coverage;
|
||||
pub mod scan_history;
|
||||
pub mod scan_runs;
|
||||
pub mod severity_badge;
|
||||
pub mod sidebar;
|
||||
|
||||
@@ -0,0 +1,386 @@
|
||||
//! The "Verlauf" view of a target (#957): per scan, the CVE alerts it found
|
||||
//! new above the line and those it found gone below it, with the run's
|
||||
//! status. A scan opens the list of what it changed.
|
||||
|
||||
use chrono::{DateTime, Utc};
|
||||
use compliance_core::models::ScanRunStatus;
|
||||
use compliance_core::scan_changes::{ComponentRow, ComponentRowKind, CveChange, ScanChange};
|
||||
use dioxus::prelude::*;
|
||||
|
||||
use crate::app::Route;
|
||||
use crate::components::scan_runs::status_badge;
|
||||
use crate::components::severity_badge::SeverityBadge;
|
||||
use crate::i18n::texts::{common, scan_history as tx};
|
||||
use crate::i18n::{use_lang, Lang};
|
||||
use crate::infrastructure::scan_changes::fetch_scan_changes;
|
||||
use crate::pages::target_views::RepoView;
|
||||
|
||||
/// The height of the taller bar side, in pixels.
|
||||
const BAR_HEIGHT: u64 = 80;
|
||||
|
||||
/// A bar's height for `count` when the largest count is `max`: at least
|
||||
/// 2 px for any change, so a single CVE is never drawn as none.
|
||||
fn bar_px(count: usize, max: usize) -> u64 {
|
||||
if count == 0 || max == 0 {
|
||||
return 0;
|
||||
}
|
||||
(count as u64 * BAR_HEIGHT).div_ceil(max as u64).max(2)
|
||||
}
|
||||
|
||||
/// A scan's day as the chart labels it: `10.11.` / `11/10`.
|
||||
fn day(at: &DateTime<Utc>, lang: Lang) -> String {
|
||||
match lang {
|
||||
Lang::De => at.format("%d.%m.").to_string(),
|
||||
Lang::En => at.format("%m/%d").to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The view of target `target_id`: the chart (or its table), or, with
|
||||
/// `scan` (a run id, from the URL) set, what that scan changed.
|
||||
#[component]
|
||||
pub fn ScanHistory(target_id: String, scan: Option<String>) -> Element {
|
||||
let lang = use_lang()();
|
||||
let mut as_table = use_signal(|| false);
|
||||
let id = target_id.clone();
|
||||
let history = use_resource(move || {
|
||||
let id = id.clone();
|
||||
async move { fetch_scan_changes(id).await.ok() }
|
||||
});
|
||||
let Some(loaded) = history.read().clone() else {
|
||||
return rsx! { div { class: "loading", {common::LOADING.get(lang)} } };
|
||||
};
|
||||
let Some(changes) = loaded else {
|
||||
return rsx! { div { class: "card", p { {tx::LOAD_FAILED.get(lang)} } } };
|
||||
};
|
||||
let to_scan = |scan: Option<String>| Route::TargetViewsPage {
|
||||
id: target_id.clone(),
|
||||
view: RepoView::History.slug().to_string(),
|
||||
cve_severity: None,
|
||||
cve_vex: None,
|
||||
control: None,
|
||||
scan,
|
||||
};
|
||||
if changes.is_empty() {
|
||||
return rsx! { div { class: "card", p { class: "target-muted", {tx::NO_SCANS.get(lang)} } } };
|
||||
}
|
||||
|
||||
if let Some(run_id) = scan {
|
||||
let back = to_scan(None);
|
||||
return match changes.into_iter().find(|c| c.run_id == run_id) {
|
||||
Some(change) => rsx! {
|
||||
ScanDetail { target_id: target_id.clone(), change, back }
|
||||
},
|
||||
None => rsx! {
|
||||
div { class: "card",
|
||||
p { {tx::UNKNOWN.get(lang)} }
|
||||
Link { class: "repo-view-list", to: back, {tx::BACK.get(lang)} }
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
let max = changes
|
||||
.iter()
|
||||
.map(|c| c.new_cves.len().max(c.gone_cves.len()))
|
||||
.max()
|
||||
.unwrap_or(0);
|
||||
rsx! {
|
||||
section { class: "card sh-card", "aria-label": tx::TITLE.get(lang),
|
||||
div { class: "sh-head",
|
||||
h3 { class: "sh-title", {tx::TITLE.get(lang)} }
|
||||
div { class: "sh-legend",
|
||||
span { span { class: "sh-swatch sh-new", "aria-hidden": "true" } {tx::NEW.get(lang)} }
|
||||
span { span { class: "sh-swatch sh-gone", "aria-hidden": "true" } {tx::GONE.get(lang)} }
|
||||
}
|
||||
// A toggle: the label stays, the pressed state changes.
|
||||
button {
|
||||
class: "btn btn-sm btn-ghost sh-toggle",
|
||||
"aria-pressed": "{as_table()}",
|
||||
onclick: move |_| as_table.toggle(),
|
||||
{tx::TABLE.get(lang)}
|
||||
}
|
||||
}
|
||||
if as_table() {
|
||||
div { class: "table-wrapper",
|
||||
table {
|
||||
thead {
|
||||
tr {
|
||||
th { {tx::SCAN.get(lang)} }
|
||||
th { {tx::STATUS.get(lang)} }
|
||||
th { class: "co-num", {tx::NEW.get(lang)} }
|
||||
th { class: "co-num", {tx::GONE.get(lang)} }
|
||||
}
|
||||
}
|
||||
tbody {
|
||||
for c in changes.iter().rev() {
|
||||
tr { key: "{c.run_id}",
|
||||
td {
|
||||
Link { to: to_scan(Some(c.run_id.clone())), "{day(&c.started_at, lang)}" }
|
||||
}
|
||||
td { {status_badge(&c.status).1.get(lang)} }
|
||||
td { class: "co-num", "{c.new_cves.len()}" }
|
||||
td { class: "co-num", "{c.gone_cves.len()}" }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
div { class: "sh-chart", role: "list",
|
||||
for c in changes.iter() {
|
||||
{
|
||||
let tip = tx::tip(&day(&c.started_at, lang), c, status_badge(&c.status).1.get(lang), lang);
|
||||
let up = bar_px(c.new_cves.len(), max);
|
||||
let down = bar_px(c.gone_cves.len(), max);
|
||||
let (badge, _) = status_badge(&c.status);
|
||||
let label = if c.baseline {
|
||||
tx::BASELINE.get(lang)
|
||||
} else {
|
||||
status_badge(&c.status).1.get(lang)
|
||||
};
|
||||
rsx! {
|
||||
Link {
|
||||
key: "{c.run_id}",
|
||||
class: "sh-scan",
|
||||
role: "listitem",
|
||||
title: "{tip}",
|
||||
"aria-label": "{tip}",
|
||||
to: to_scan(Some(c.run_id.clone())),
|
||||
span { class: "sh-up", span { class: "sh-bar sh-new", style: "height: {up}px;" } }
|
||||
span { class: "sh-axis", "aria-hidden": "true" }
|
||||
span { class: "sh-down", span { class: "sh-bar sh-gone", style: "height: {down}px;" } }
|
||||
span { class: "sh-day", "{day(&c.started_at, lang)}" }
|
||||
if c.baseline || c.status != ScanRunStatus::Completed {
|
||||
span { class: "{badge} sh-status", "{label}" }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
p { class: "sh-hint", {tx::HINT.get(lang)} }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What scan `change` of target `target_id` changed: its CVEs found new and
|
||||
/// gone, most severe first, and its new findings; `back` returns to the
|
||||
/// chart.
|
||||
#[component]
|
||||
fn ScanDetail(target_id: String, change: ScanChange, back: Route) -> Element {
|
||||
let lang = use_lang()();
|
||||
let rows: Vec<(bool, CveChange)> = change
|
||||
.new_cves
|
||||
.iter()
|
||||
.cloned()
|
||||
.map(|c| (true, c))
|
||||
.chain(change.gone_cves.iter().cloned().map(|c| (false, c)))
|
||||
.collect();
|
||||
rsx! {
|
||||
nav { class: "ct-crumbs", "aria-label": tx::BREADCRUMB.get(lang),
|
||||
Link { to: back.clone(), {tx::ROOT.get(lang)} }
|
||||
span { "aria-hidden": "true", " › " }
|
||||
strong { {tx::scan_of(&day(&change.started_at, lang), lang)} }
|
||||
span { class: "target-muted", " · {tx::summary(change.new_cves.len(), change.gone_cves.len(), lang)}" }
|
||||
Link { class: "btn btn-sm btn-ghost ct-back", to: back, {tx::BACK.get(lang)} }
|
||||
}
|
||||
if let Some(components) = change.components.clone().filter(|_| !change.baseline) {
|
||||
ComponentTable { components }
|
||||
}
|
||||
section { class: "card",
|
||||
if change.components.is_some() && !change.baseline {
|
||||
h3 { class: "sh-title", "CVEs" }
|
||||
}
|
||||
if change.baseline {
|
||||
p { class: "target-muted", {tx::BASELINE_HINT.get(lang)} }
|
||||
} else if rows.is_empty() {
|
||||
p { class: "target-muted", {tx::NO_CHANGE.get(lang)} }
|
||||
} else {
|
||||
div { class: "table-wrapper",
|
||||
table {
|
||||
thead {
|
||||
tr {
|
||||
th { {tx::CHANGE.get(lang)} }
|
||||
th { "CVE" }
|
||||
th { {tx::COMPONENT.get(lang)} }
|
||||
th { {tx::VERSION.get(lang)} }
|
||||
th { {tx::SEVERITY.get(lang)} }
|
||||
}
|
||||
}
|
||||
tbody {
|
||||
for (i, (new, c)) in rows.into_iter().enumerate() {
|
||||
tr { key: "{i}",
|
||||
td { if new { {tx::NEW_ONE.get(lang)} } else { {tx::GONE_ONE.get(lang)} } }
|
||||
td { code { "{c.cve}" } }
|
||||
td { "{c.package}" }
|
||||
td { code { "{c.version}" } }
|
||||
td {
|
||||
SeverityBadge {
|
||||
severity: serde_json::to_value(&c.severity)
|
||||
.ok()
|
||||
.and_then(|v| v.as_str().map(String::from))
|
||||
.unwrap_or_default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if change.new_findings > 0 {
|
||||
Link { class: "repo-view-list", to: Route::findings(target_id.clone()),
|
||||
{tx::new_findings(change.new_findings, lang)}
|
||||
}
|
||||
}
|
||||
if change.components.is_none() && !change.baseline {
|
||||
p { class: "target-muted sh-note", {tx::COMPONENTS_NOTE.get(lang)} }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// How a component row reads: its change, its version, its CVEs.
|
||||
fn row_text(row: &ComponentRow, lang: Lang) -> (&'static str, String, String) {
|
||||
let change = match row.kind {
|
||||
ComponentRowKind::Added => tx::ADDED,
|
||||
ComponentRowKind::Updated => tx::UPDATED,
|
||||
ComponentRowKind::Removed => tx::REMOVED,
|
||||
ComponentRowKind::Advisory if row.cves_gone == 0 => tx::NEW_ADVISORY,
|
||||
ComponentRowKind::Advisory if row.cves_new == 0 => tx::ADVISORY_GONE,
|
||||
ComponentRowKind::Advisory => tx::ADVISORIES_CHANGED,
|
||||
}
|
||||
.get(lang);
|
||||
let version = match (&row.from, &row.to) {
|
||||
(Some(from), Some(to)) if from != to => format!("{from} → {to}"),
|
||||
(_, Some(v)) | (Some(v), None) => v.clone(),
|
||||
(None, None) => String::new(),
|
||||
};
|
||||
let cves = match (row.cves_new, row.cves_gone) {
|
||||
(0, 0) => "–".to_string(),
|
||||
(n, 0) => format!("+{n}"),
|
||||
(0, g) => format!("−{g}"),
|
||||
(n, g) => format!("+{n}, −{g}"),
|
||||
};
|
||||
(change, version, cves)
|
||||
}
|
||||
|
||||
/// The components a scan changed, with the CVEs each brought and took.
|
||||
#[component]
|
||||
fn ComponentTable(components: Vec<ComponentRow>) -> Element {
|
||||
let lang = use_lang()();
|
||||
rsx! {
|
||||
section { class: "card",
|
||||
h3 { class: "sh-title", {tx::COMPONENTS_TITLE.get(lang)} }
|
||||
if components.is_empty() {
|
||||
p { class: "target-muted", {tx::NO_COMPONENT_CHANGE.get(lang)} }
|
||||
} else {
|
||||
div { class: "table-wrapper",
|
||||
table {
|
||||
thead {
|
||||
tr {
|
||||
th { {tx::CHANGE.get(lang)} }
|
||||
th { {tx::COMPONENT.get(lang)} }
|
||||
th { {tx::VERSION.get(lang)} }
|
||||
th { class: "co-num", "CVEs" }
|
||||
}
|
||||
}
|
||||
tbody {
|
||||
for (i, row) in components.iter().enumerate() {
|
||||
{
|
||||
let (change, version, cves) = row_text(row, lang);
|
||||
rsx! {
|
||||
tr { key: "{i}",
|
||||
td { "{change}" }
|
||||
td { "{row.name}" }
|
||||
td { code { "{version}" } }
|
||||
td { class: "co-num", "{cves}" }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn bars_scale_to_the_largest_change_and_one_cve_shows() {
|
||||
assert_eq!(bar_px(0, 9), 0);
|
||||
assert_eq!(bar_px(9, 9), BAR_HEIGHT);
|
||||
assert_eq!(bar_px(1, 1000), 2);
|
||||
assert_eq!(bar_px(3, 0), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_component_row_reads_as_its_change_version_and_cves() {
|
||||
let row = |kind, from: Option<&str>, to: Option<&str>, new, gone| ComponentRow {
|
||||
kind,
|
||||
name: "openssl".into(),
|
||||
from: from.map(String::from),
|
||||
to: to.map(String::from),
|
||||
cves_new: new,
|
||||
cves_gone: gone,
|
||||
};
|
||||
let read = |r: ComponentRow| row_text(&r, Lang::De);
|
||||
assert_eq!(
|
||||
read(row(
|
||||
ComponentRowKind::Updated,
|
||||
Some("3.0.9"),
|
||||
Some("3.0.11"),
|
||||
3,
|
||||
1
|
||||
)),
|
||||
(
|
||||
"aktualisiert",
|
||||
"3.0.9 → 3.0.11".to_string(),
|
||||
"+3, −1".to_string()
|
||||
)
|
||||
);
|
||||
assert_eq!(
|
||||
read(row(ComponentRowKind::Removed, Some("1.6.39"), None, 0, 1)),
|
||||
("entfernt", "1.6.39".to_string(), "−1".to_string())
|
||||
);
|
||||
assert_eq!(
|
||||
read(row(ComponentRowKind::Added, None, Some("2.11.4"), 0, 0)).2,
|
||||
"–"
|
||||
);
|
||||
assert_eq!(
|
||||
read(row(
|
||||
ComponentRowKind::Advisory,
|
||||
Some("1.36.0"),
|
||||
Some("1.36.0"),
|
||||
1,
|
||||
0
|
||||
))
|
||||
.0,
|
||||
"neue Advisory"
|
||||
);
|
||||
assert_eq!(
|
||||
read(row(
|
||||
ComponentRowKind::Advisory,
|
||||
Some("1.36.0"),
|
||||
Some("1.36.0"),
|
||||
0,
|
||||
2
|
||||
))
|
||||
.0,
|
||||
"Advisory entfällt"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_scans_day_reads_as_in_each_language() {
|
||||
let at: DateTime<Utc> = "2026-11-10T08:00:00Z".parse().unwrap_or_default();
|
||||
assert_eq!(day(&at, Lang::De), "10.11.");
|
||||
assert_eq!(day(&at, Lang::En), "11/10");
|
||||
}
|
||||
}
|
||||
@@ -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)}
|
||||
}
|
||||
|
||||
@@ -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,
|
||||
@@ -102,6 +100,16 @@ pub fn Sidebar() -> Element {
|
||||
runtime_only: true,
|
||||
write_only: false,
|
||||
},
|
||||
// The MCP endpoint also serves a source-only deployment, where the
|
||||
// overview's MCP-Server card (and with it the only other link to
|
||||
// the tokens) is hidden.
|
||||
NavItem {
|
||||
label: nav::MCP_TOKENS,
|
||||
route: Route::McpTokensPage {},
|
||||
icon: rsx! { Icon { icon: BsKey, width: 18, height: 18 } },
|
||||
runtime_only: false,
|
||||
write_only: false,
|
||||
},
|
||||
];
|
||||
|
||||
// Both links are set per deployment (`DOCS_URL`, `PORTAL_URL`). The
|
||||
@@ -158,11 +166,17 @@ pub fn Sidebar() -> Element {
|
||||
}
|
||||
}
|
||||
div { class: "sidebar-nav",
|
||||
TodayNavItem {
|
||||
collapsed: collapsed(),
|
||||
active: matches!(current_route, Route::HeutePage { .. }),
|
||||
on_navigate: move |_| mobile_open.set(false),
|
||||
}
|
||||
for item in nav_items.into_iter().filter(|i| can_write || !i.write_only) {
|
||||
{
|
||||
let is_active = match (¤t_route, &item.route) {
|
||||
(Route::FindingDetailPage { .. } | Route::FindingsPage { .. }, Route::FindingsPage { .. }) => true,
|
||||
(Route::SbomPage { .. }, Route::SbomPage { .. }) => true,
|
||||
(Route::SbomEcosystemPage { .. }, Route::SbomPage { .. }) => true,
|
||||
(Route::CompliancePage { .. }, Route::TargetsPage {}) => true,
|
||||
(Route::DastTargetsPage {}, Route::DastOverviewPage {}) => true,
|
||||
(Route::DastFindingsPage {}, Route::DastOverviewPage {}) => true,
|
||||
@@ -281,6 +295,41 @@ pub fn Sidebar() -> Element {
|
||||
}
|
||||
}
|
||||
|
||||
/// The sidebar's "Heute" entry with the workspace's "Heute handeln" count
|
||||
/// (#950): fetched once, then kept current by the page.
|
||||
#[component]
|
||||
fn TodayNavItem(collapsed: bool, active: bool, on_navigate: EventHandler<()>) -> Element {
|
||||
use crate::infrastructure::inbox::fetch_inbox;
|
||||
use crate::pages::inbox::TODAY_COUNT;
|
||||
use compliance_core::models::inbox::Bucket;
|
||||
|
||||
let lang = use_lang()();
|
||||
let _count = use_resource(|| async {
|
||||
if TODAY_COUNT.peek().is_none() {
|
||||
if let Ok(view) = fetch_inbox(String::new(), Bucket::Today, Some(0)).await {
|
||||
*TODAY_COUNT.write() = Some(view.counts.today);
|
||||
}
|
||||
}
|
||||
});
|
||||
let label = crate::i18n::texts::inbox::NAV.get(lang);
|
||||
let today = TODAY_COUNT().filter(|n| *n > 0);
|
||||
rsx! {
|
||||
Link {
|
||||
to: Route::heute(String::new(), None),
|
||||
class: if active { "nav-item active" } else { "nav-item" },
|
||||
title: "{label}",
|
||||
onclick: move |_| on_navigate.call(()),
|
||||
Icon { icon: BsInbox, width: 18, height: 18 }
|
||||
if !collapsed {
|
||||
span { "{label}" }
|
||||
}
|
||||
if let Some(today) = today {
|
||||
span { class: "nav-count", "{today}" }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The BreakPilot wordmark, as on breakpilot.com and the portal: the chevron,
|
||||
/// and unless `with_name` is off, "BreakPilot" with "Prüfwerk" beneath.
|
||||
#[component]
|
||||
|
||||
@@ -1,13 +1,18 @@
|
||||
//! On a target: its known vulnerabilities with their VEX status, an editor to
|
||||
//! state whether the product is affected, the OpenVEX and CycloneDX VEX
|
||||
//! downloads and the CSAF 2.0 draft (#498). Read-only roles see the
|
||||
//! statements but not the editor.
|
||||
//! downloads and the CSAF 2.0 draft (#498). By default the open ones are
|
||||
//! grouped by component with one decision per group (#949); "Einzeln" lists
|
||||
//! every alert. Read-only roles see the statements but not the editor.
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
use dioxus::prelude::*;
|
||||
use dioxus_free_icons::icons::bs_icons::BsDownload;
|
||||
use dioxus_free_icons::Icon;
|
||||
|
||||
use compliance_core::models::{CveAlert, VexJustification, VexStatus};
|
||||
use compliance_core::cve_groups::{CveGroup, CveSeverity, PackageKey};
|
||||
use compliance_core::cve_matrix::CveFilter;
|
||||
use compliance_core::models::{CveAlert, VexAssessment, VexJustification, VexStatus};
|
||||
use compliance_core::vex_docs::status_of;
|
||||
|
||||
use crate::components::no_access::use_can_write;
|
||||
@@ -16,9 +21,9 @@ use crate::components::toast::{ToastType, Toasts};
|
||||
use crate::i18n::texts::{common, vex as tx};
|
||||
use crate::i18n::{use_lang, Lang, Text};
|
||||
use crate::infrastructure::vex::{
|
||||
csaf_filename, enisa_filename, fetch_csaf_export, fetch_enisa_candidates, fetch_enisa_draft,
|
||||
fetch_target_cves, fetch_vex_export, save_cve_vex, EnisaCandidateDto, StageDueDto, VexFormat,
|
||||
VexStatementDto,
|
||||
csaf_filename, enisa_filename, fetch_csaf_export, fetch_cve_groups, fetch_enisa_candidates,
|
||||
fetch_enisa_draft, fetch_target_cves, fetch_vex_export, save_cve_vex, save_group_vex,
|
||||
EnisaCandidateDto, StageDueDto, VexFormat, VexStatementDto,
|
||||
};
|
||||
|
||||
/// Every status, in the order the editor offers them.
|
||||
@@ -103,11 +108,11 @@ fn stated_by(alert: &CveAlert, lang: Lang) -> String {
|
||||
}
|
||||
}
|
||||
|
||||
/// The "Schwachstellen und VEX" card body for target `target_id`.
|
||||
/// The "Schwachstellen und VEX" card body for target `target_id`; with
|
||||
/// `filter`, only the alerts of that cell of the CVE grid (#957).
|
||||
#[component]
|
||||
pub fn VexPanel(target_id: String) -> Element {
|
||||
pub fn VexPanel(target_id: String, #[props(default)] filter: Option<CveFilter>) -> Element {
|
||||
let lang = use_lang()();
|
||||
let can_write = use_can_write();
|
||||
let id_for_load = target_id.clone();
|
||||
let mut alerts = use_resource(move || {
|
||||
let id = id_for_load.clone();
|
||||
@@ -120,7 +125,19 @@ pub fn VexPanel(target_id: String) -> Element {
|
||||
let id = id_for_enisa.clone();
|
||||
async move { fetch_enisa_candidates(id).await.unwrap_or_default() }
|
||||
});
|
||||
let mut editing = use_signal(|| Option::<String>::None);
|
||||
// The open alerts grouped by component (#949), one decision per group.
|
||||
let id_for_groups = target_id.clone();
|
||||
let mut groups = use_resource(move || {
|
||||
let id = id_for_groups.clone();
|
||||
async move { fetch_cve_groups(id).await.ok() }
|
||||
});
|
||||
let mut grouped = use_signal(|| true);
|
||||
let on_saved = move |()| {
|
||||
alerts.restart();
|
||||
enisa.restart();
|
||||
groups.restart();
|
||||
};
|
||||
let candidates = enisa.read().clone().unwrap_or_default();
|
||||
|
||||
rsx! {
|
||||
div { class: "vex-head",
|
||||
@@ -136,82 +153,240 @@ pub fn VexPanel(target_id: String) -> Element {
|
||||
None => rsx! { div { class: "loading", {common::LOADING.get(lang)} } },
|
||||
Some(None) => rsx! { p { class: "target-muted", {tx::LOAD_FAILED.get(lang)} } },
|
||||
Some(Some(list)) if list.is_empty() => rsx! { p { class: "target-muted", {tx::NONE.get(lang)} } },
|
||||
// A cell of the CVE grid (#957) opens its alerts one by one: the
|
||||
// package groups (#949) cover all open alerts, not the cell's.
|
||||
Some(Some(list)) if filter.is_some() => rsx! {
|
||||
CveTable {
|
||||
alerts: list
|
||||
.iter()
|
||||
.filter(|a| filter.as_ref().is_none_or(|f| f.matches(a)))
|
||||
.cloned()
|
||||
.collect::<Vec<_>>(),
|
||||
candidates: candidates.clone(),
|
||||
on_saved,
|
||||
}
|
||||
},
|
||||
Some(Some(list)) => rsx! {
|
||||
div { class: "table-wrapper",
|
||||
table { class: "vex-table",
|
||||
thead {
|
||||
tr {
|
||||
th { {tx::CVE.get(lang)} }
|
||||
th { {tx::COMPONENT.get(lang)} }
|
||||
th { {tx::SEVERITY.get(lang)} }
|
||||
th { {tx::STATUS.get(lang)} }
|
||||
th { {tx::STATED_BY.get(lang)} }
|
||||
th {}
|
||||
}
|
||||
div { class: "sbom-tab-bar vex-view-toggle",
|
||||
for (is_grouped, label) in [(true, tx::VIEW_GROUPED), (false, tx::VIEW_SINGLE)] {
|
||||
button {
|
||||
class: if grouped() == is_grouped { "sbom-tab active" } else { "sbom-tab" },
|
||||
"aria-pressed": if grouped() == is_grouped { "true" } else { "false" },
|
||||
onclick: move |_| grouped.set(is_grouped),
|
||||
{label.get(lang)}
|
||||
}
|
||||
tbody {
|
||||
for alert in list.iter() {
|
||||
{
|
||||
let alert_id = alert.id.map(|o| o.to_hex()).unwrap_or_default();
|
||||
let status = status_of(alert);
|
||||
let open = editing.read().as_deref() == Some(alert_id.as_str());
|
||||
let edit_id = alert_id.clone();
|
||||
rsx! {
|
||||
tr { key: "{alert_id}",
|
||||
td {
|
||||
code { "{alert.cve_id}" }
|
||||
// The vendor advisories that name it (#515), linked as
|
||||
// their terms ask; the remediation on hover.
|
||||
for adv in alert.advisories.iter() {
|
||||
a {
|
||||
class: "vex-advisory",
|
||||
href: adv.url.clone().unwrap_or_default(),
|
||||
target: "_blank",
|
||||
rel: "noopener noreferrer",
|
||||
title: adv.remediation.clone().unwrap_or_else(|| adv.title.clone()),
|
||||
"{adv.id}"
|
||||
}
|
||||
}
|
||||
}
|
||||
td { "{alert.affected_package} {alert.affected_version}" }
|
||||
td {
|
||||
if let Some(sev) = alert.severity.as_deref() {
|
||||
SeverityBadge { severity: sev.to_string() }
|
||||
}
|
||||
}
|
||||
td { span { class: status_class(status), {status_text(status).get(lang)} } }
|
||||
td { class: "target-muted", "{stated_by(alert, lang)}" }
|
||||
td {
|
||||
if can_write && !open {
|
||||
button {
|
||||
class: "btn btn-ghost btn-sm",
|
||||
onclick: move |_| editing.set(Some(edit_id.clone())),
|
||||
{tx::EDIT.get(lang)}
|
||||
}
|
||||
}
|
||||
if let Some(candidate) = enisa
|
||||
.read()
|
||||
.as_ref()
|
||||
.and_then(|c| reportable_candidate(c, &alert_id))
|
||||
{
|
||||
EnisaDraftButton { alert_id: alert_id.clone(), candidate }
|
||||
}
|
||||
}
|
||||
}
|
||||
if grouped() {
|
||||
match &*groups.read() {
|
||||
None => rsx! { div { class: "loading", {common::LOADING.get(lang)} } },
|
||||
Some(None) => rsx! { p { class: "target-muted", {tx::LOAD_FAILED.get(lang)} } },
|
||||
Some(Some(found)) if found.is_empty() => rsx! { p { class: "target-muted", {tx::ALL_DECIDED.get(lang)} } },
|
||||
Some(Some(found)) => rsx! {
|
||||
CveGroups {
|
||||
target_id: target_id.clone(),
|
||||
groups: found.clone(),
|
||||
alerts: list.clone(),
|
||||
candidates: candidates.clone(),
|
||||
on_saved,
|
||||
}
|
||||
},
|
||||
}
|
||||
} else {
|
||||
CveTable { alerts: list.clone(), candidates: candidates.clone(), on_saved }
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The group cards of `groups`, each with its rows from `alerts`.
|
||||
#[component]
|
||||
fn CveGroups(
|
||||
target_id: String,
|
||||
groups: Vec<CveGroup>,
|
||||
alerts: Vec<CveAlert>,
|
||||
candidates: Vec<EnisaCandidateDto>,
|
||||
on_saved: EventHandler<()>,
|
||||
) -> Element {
|
||||
let by_id: HashMap<String, &CveAlert> = alerts
|
||||
.iter()
|
||||
.filter_map(|a| a.id.map(|o| (o.to_hex(), a)))
|
||||
.collect();
|
||||
rsx! {
|
||||
div { class: "vex-groups",
|
||||
for group in groups.iter() {
|
||||
{
|
||||
let members: Vec<CveAlert> = group
|
||||
.alert_ids
|
||||
.iter()
|
||||
.filter_map(|id| by_id.get(id).map(|a| (*a).clone()))
|
||||
.collect();
|
||||
let card_key = format!(
|
||||
"{}@{}@{}",
|
||||
group.key.package,
|
||||
group.key.version,
|
||||
group.key.purl.as_deref().unwrap_or_default()
|
||||
);
|
||||
rsx! {
|
||||
CveGroupCard {
|
||||
key: "{card_key}",
|
||||
target_id: target_id.clone(),
|
||||
group: group.clone(),
|
||||
alerts: members,
|
||||
candidates: candidates.clone(),
|
||||
on_saved,
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One component's open CVEs: what updating it fixes, the decision for all of
|
||||
/// them, and the CVEs themselves on demand.
|
||||
#[component]
|
||||
pub fn CveGroupCard(
|
||||
target_id: String,
|
||||
group: CveGroup,
|
||||
alerts: Vec<CveAlert>,
|
||||
candidates: Vec<EnisaCandidateDto>,
|
||||
on_saved: EventHandler<()>,
|
||||
) -> Element {
|
||||
let lang = use_lang()();
|
||||
let can_write = use_can_write();
|
||||
let mut expanded = use_signal(|| false);
|
||||
let mut deciding = use_signal(|| false);
|
||||
let open = group.cve_ids.len();
|
||||
rsx! {
|
||||
div { class: "vex-group",
|
||||
div { class: "vex-group-head",
|
||||
SeverityBadge { severity: group.counts.max().as_str().to_string() }
|
||||
strong { class: "vex-group-title", {tx::group_headline(&group, lang)} }
|
||||
if group.kev {
|
||||
span { class: "badge badge-danger", title: tx::KEV_HINT.get(lang), "KEV" }
|
||||
}
|
||||
if let Some(score) = group.epss_max {
|
||||
span { class: "target-muted", title: tx::EPSS_HINT.get(lang), {tx::epss_label(score, lang)} }
|
||||
}
|
||||
div { class: "vex-group-actions",
|
||||
if can_write && !deciding() {
|
||||
button {
|
||||
class: "btn btn-secondary btn-sm",
|
||||
onclick: move |_| deciding.set(true),
|
||||
{tx::not_affected_all(open, lang)}
|
||||
}
|
||||
}
|
||||
button {
|
||||
class: "btn btn-ghost btn-sm",
|
||||
"aria-expanded": if expanded() { "true" } else { "false" },
|
||||
onclick: move |_| expanded.toggle(),
|
||||
if expanded() { {tx::HIDE_CVES.get(lang)} } else { {tx::SHOW_CVES.get(lang)} }
|
||||
}
|
||||
}
|
||||
}
|
||||
if deciding() {
|
||||
VexEditor {
|
||||
current: None,
|
||||
initial: VexStatus::NotAffected,
|
||||
save: SaveTo::Group { target_id: target_id.clone(), key: group.key.clone() },
|
||||
on_close: move |saved: bool| {
|
||||
deciding.set(false);
|
||||
if saved {
|
||||
on_saved.call(());
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
if expanded() {
|
||||
CveTable { alerts, candidates, on_saved }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The CVE alerts `alerts` as a table, each with its own "Bewerten".
|
||||
#[component]
|
||||
fn CveTable(
|
||||
alerts: Vec<CveAlert>,
|
||||
candidates: Vec<EnisaCandidateDto>,
|
||||
on_saved: EventHandler<()>,
|
||||
) -> Element {
|
||||
let lang = use_lang()();
|
||||
let can_write = use_can_write();
|
||||
let mut editing = use_signal(|| Option::<String>::None);
|
||||
rsx! {
|
||||
div { class: "table-wrapper",
|
||||
table { class: "vex-table",
|
||||
thead {
|
||||
tr {
|
||||
th { {tx::CVE.get(lang)} }
|
||||
th { {tx::COMPONENT.get(lang)} }
|
||||
th { {tx::SEVERITY.get(lang)} }
|
||||
th { {tx::STATUS.get(lang)} }
|
||||
th { {tx::STATED_BY.get(lang)} }
|
||||
th {}
|
||||
}
|
||||
}
|
||||
tbody {
|
||||
for alert in alerts.iter() {
|
||||
{
|
||||
let alert_id = alert.id.map(|o| o.to_hex()).unwrap_or_default();
|
||||
let status = status_of(alert);
|
||||
let open = editing.read().as_deref() == Some(alert_id.as_str());
|
||||
let edit_id = alert_id.clone();
|
||||
let current = alert.vex.clone().filter(|v| !v.by_scan);
|
||||
let initial = current.as_ref().map_or(status, |v| v.status);
|
||||
rsx! {
|
||||
tr { key: "{alert_id}",
|
||||
td {
|
||||
code { "{alert.cve_id}" }
|
||||
// The vendor advisories that name it (#515), linked as
|
||||
// their terms ask; the remediation on hover.
|
||||
for adv in alert.advisories.iter() {
|
||||
a {
|
||||
class: "vex-advisory",
|
||||
href: adv.url.clone().unwrap_or_default(),
|
||||
target: "_blank",
|
||||
rel: "noopener noreferrer",
|
||||
title: adv.remediation.clone().unwrap_or_else(|| adv.title.clone()),
|
||||
"{adv.id}"
|
||||
}
|
||||
}
|
||||
if open {
|
||||
tr { class: "vex-editor-row",
|
||||
td { colspan: "6",
|
||||
VexEditor {
|
||||
alert: alert.clone(),
|
||||
on_close: move |saved: bool| {
|
||||
editing.set(None);
|
||||
if saved {
|
||||
alerts.restart();
|
||||
enisa.restart();
|
||||
}
|
||||
},
|
||||
}
|
||||
td { "{alert.affected_package} {alert.affected_version}" }
|
||||
// The severity the groups count it with (#949): the
|
||||
// advisory's rating, else its CVSS score, else info.
|
||||
td { SeverityBadge { severity: CveSeverity::of(alert).as_str().to_string() } }
|
||||
td { span { class: status_class(status), {status_text(status).get(lang)} } }
|
||||
td { class: "target-muted", "{stated_by(alert, lang)}" }
|
||||
td {
|
||||
if can_write && !open {
|
||||
button {
|
||||
class: "btn btn-ghost btn-sm",
|
||||
onclick: move |_| editing.set(Some(edit_id.clone())),
|
||||
{tx::EDIT.get(lang)}
|
||||
}
|
||||
}
|
||||
if let Some(candidate) = reportable_candidate(&candidates, &alert_id) {
|
||||
EnisaDraftButton { alert_id: alert_id.clone(), candidate }
|
||||
}
|
||||
}
|
||||
}
|
||||
if open {
|
||||
tr { class: "vex-editor-row",
|
||||
td { colspan: "6",
|
||||
VexEditor {
|
||||
current,
|
||||
initial,
|
||||
save: SaveTo::Alert(alert_id.clone()),
|
||||
on_close: move |saved: bool| {
|
||||
editing.set(None);
|
||||
if saved {
|
||||
on_saved.call(());
|
||||
}
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -220,7 +395,7 @@ pub fn VexPanel(target_id: String) -> Element {
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -411,14 +586,38 @@ fn TlpBadge(label: String) -> Element {
|
||||
}
|
||||
}
|
||||
|
||||
/// The statement editor for one alert, starting from its current statement.
|
||||
/// `on_close` gets whether a statement was saved.
|
||||
/// What a [`VexEditor`] states VEX on.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
enum SaveTo {
|
||||
/// One alert, by its id.
|
||||
Alert(String),
|
||||
/// Every open alert of a component in a target (#949).
|
||||
Group { target_id: String, key: PackageKey },
|
||||
}
|
||||
|
||||
impl SaveTo {
|
||||
/// Store `statement`; the agent's refusal is the error.
|
||||
async fn save(self, statement: VexStatementDto) -> Result<(), ServerFnError> {
|
||||
match self {
|
||||
Self::Alert(id) => save_cve_vex(id, statement).await,
|
||||
Self::Group { target_id, key } => save_group_vex(target_id, key, statement).await,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The statement editor, starting from `current` (a person's statement, if
|
||||
/// any) with status `initial`, for one alert or a whole group. `on_close`
|
||||
/// gets whether a statement was saved.
|
||||
#[component]
|
||||
fn VexEditor(alert: CveAlert, on_close: EventHandler<bool>) -> Element {
|
||||
fn VexEditor(
|
||||
current: Option<VexAssessment>,
|
||||
initial: VexStatus,
|
||||
save: SaveTo,
|
||||
on_close: EventHandler<bool>,
|
||||
) -> Element {
|
||||
let lang = use_lang()();
|
||||
let mut toasts = use_context::<Toasts>();
|
||||
let current = alert.vex.clone().filter(|v| !v.by_scan);
|
||||
let mut status = use_signal(|| current.as_ref().map_or(status_of(&alert), |v| v.status));
|
||||
let mut status = use_signal(|| initial);
|
||||
let mut justification = use_signal(|| current.as_ref().and_then(|v| v.justification));
|
||||
let mut impact = use_signal(|| {
|
||||
current
|
||||
@@ -444,7 +643,6 @@ fn VexEditor(alert: CveAlert, on_close: EventHandler<bool>) -> Element {
|
||||
action_statement: filled(action()).filter(|_| status() == VexStatus::Affected),
|
||||
};
|
||||
let blocked = missing(&statement);
|
||||
let alert_id = alert.id.map(|o| o.to_hex()).unwrap_or_default();
|
||||
|
||||
rsx! {
|
||||
div { class: "vex-editor",
|
||||
@@ -491,10 +689,10 @@ fn VexEditor(alert: CveAlert, on_close: EventHandler<bool>) -> Element {
|
||||
class: "btn btn-primary btn-sm",
|
||||
disabled: busy() || blocked.is_some(),
|
||||
onclick: move |_| {
|
||||
let (id, body) = (alert_id.clone(), statement.clone());
|
||||
let (to, body) = (save.clone(), statement.clone());
|
||||
busy.set(true);
|
||||
spawn(async move {
|
||||
match save_cve_vex(id, body).await {
|
||||
match to.save(body).await {
|
||||
Ok(()) => {
|
||||
toasts.push(ToastType::Success, tx::SAVED.get(lang));
|
||||
on_close.call(true);
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,41 @@
|
||||
//! The open CVEs with a fix per day, and the updates that close the most of
|
||||
//! a target's (#952).
|
||||
|
||||
use compliance_core::cve_history::{CveHistory, TopUpdate};
|
||||
use dioxus::prelude::*;
|
||||
|
||||
/// The last 30 days (`GET /api/v1/cve-history`): of one target when
|
||||
/// `target` is not empty, else of the whole tenant; with every target's own
|
||||
/// series when `per_target`.
|
||||
#[server]
|
||||
pub async fn fetch_cve_history(
|
||||
target: String,
|
||||
per_target: bool,
|
||||
) -> Result<CveHistory, ServerFnError> {
|
||||
let mut req = super::agent_client::agent_get("/api/v1/cve-history").await?;
|
||||
if !target.is_empty() {
|
||||
req = req.query(&[("target", target)]);
|
||||
}
|
||||
if per_target {
|
||||
req = req.query(&[("per_target", "true")]);
|
||||
}
|
||||
let resp = req
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| ServerFnError::new(e.to_string()))?;
|
||||
let body: serde_json::Value = super::agent_client::json_or_error(resp).await?;
|
||||
serde_json::from_value(body["data"].clone()).map_err(|e| ServerFnError::new(e.to_string()))
|
||||
}
|
||||
|
||||
/// The updates that close the most of target `id`'s open CVEs with a fix
|
||||
/// (`GET /api/v1/targets/{id}/top-updates`).
|
||||
#[server]
|
||||
pub async fn fetch_top_updates(id: String) -> Result<Vec<TopUpdate>, ServerFnError> {
|
||||
let resp = super::agent_client::agent_get(&format!("/api/v1/targets/{id}/top-updates"))
|
||||
.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()))
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
//! A target's CVE alerts counted by severity and VEX status (#957), from
|
||||
//! the agent's `GET /api/v1/targets/{id}/cve-matrix`.
|
||||
|
||||
use dioxus::prelude::*;
|
||||
|
||||
use compliance_core::cve_matrix::CveMatrix;
|
||||
|
||||
/// The agent's reply (read on the server only).
|
||||
#[cfg(feature = "server")]
|
||||
#[derive(Debug, serde::Deserialize)]
|
||||
struct MatrixResponse {
|
||||
data: CveMatrix,
|
||||
}
|
||||
|
||||
/// The still-reported CVE alerts of target `target_id`, counted per
|
||||
/// severity and VEX status.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// The agent's refusal or an unreachable agent.
|
||||
#[server]
|
||||
pub async fn fetch_cve_matrix(target_id: String) -> Result<CveMatrix, ServerFnError> {
|
||||
let resp = super::agent_client::agent_get(&format!("/api/v1/targets/{target_id}/cve-matrix"))
|
||||
.await?
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| ServerFnError::new(e.to_string()))?;
|
||||
let body: MatrixResponse = super::agent_client::json_or_error(resp).await?;
|
||||
Ok(body.data)
|
||||
}
|
||||
@@ -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<FindingBreakdown, ServerFnError> {
|
||||
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"));
|
||||
}
|
||||
}
|
||||
@@ -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<Vec<FindingGroup>, 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<FindingGroup>,
|
||||
}
|
||||
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<String>,
|
||||
) -> Result<u64, ServerFnError> {
|
||||
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())
|
||||
}
|
||||
@@ -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<FindingsListResponse
|
||||
url::form_urlencoded::byte_serialize(query.variant.as_bytes()).collect::<String>()
|
||||
));
|
||||
}
|
||||
if !query.path.is_empty() {
|
||||
path.push_str(&format!(
|
||||
"&path={}",
|
||||
url::form_urlencoded::byte_serialize(query.path.as_bytes()).collect::<String>()
|
||||
));
|
||||
}
|
||||
if !query.sort_by.is_empty() {
|
||||
path.push_str(&format!("&sort_by={}", query.sort_by));
|
||||
}
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
//! The "Heute" inbox (#950): the cards of a bucket, decisions on a card,
|
||||
//! undo, and resubmission dates. The agent does the work; these only carry
|
||||
//! the session's token there and back.
|
||||
|
||||
use dioxus::prelude::*;
|
||||
|
||||
use compliance_core::models::inbox::{
|
||||
Bucket, DecideRequest, DecideResponse, InboxView, SnoozeRequest, SnoozeResponse, UndoRequest,
|
||||
};
|
||||
|
||||
/// The agent's `{ data }` reply (read on the server only).
|
||||
#[cfg(feature = "server")]
|
||||
#[derive(Debug, serde::Deserialize)]
|
||||
struct ViewResponse {
|
||||
data: InboxView,
|
||||
}
|
||||
|
||||
/// The counts, the Erstbewertung, the targets and the cards of `bucket`, for
|
||||
/// the whole workspace or, with a non-empty `target`, one target; at most
|
||||
/// `limit` cards (the agent's default without one).
|
||||
#[server]
|
||||
pub async fn fetch_inbox(
|
||||
target: String,
|
||||
bucket: Bucket,
|
||||
limit: Option<u32>,
|
||||
) -> Result<InboxView, ServerFnError> {
|
||||
let mut request = super::agent_client::agent_get("/api/v1/inbox")
|
||||
.await?
|
||||
.query(&[("bucket", bucket.as_str())]);
|
||||
if !target.is_empty() {
|
||||
request = request.query(&[("target", target.as_str())]);
|
||||
}
|
||||
if let Some(limit) = limit {
|
||||
request = request.query(&[("limit", limit)]);
|
||||
}
|
||||
let resp = request
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| ServerFnError::new(e.to_string()))?;
|
||||
let body: ViewResponse = super::agent_client::json_or_error(resp).await?;
|
||||
Ok(body.data)
|
||||
}
|
||||
|
||||
/// Apply a decision to every item of a card; what they were before, for
|
||||
/// [`undo_decision`]. The agent's refusal (a missing reason, a card already
|
||||
/// decided, a read-only role) is the error.
|
||||
#[server]
|
||||
pub async fn decide_card(request: DecideRequest) -> Result<DecideResponse, ServerFnError> {
|
||||
let resp = super::agent_client::agent_request(reqwest::Method::POST, "/api/v1/inbox/decide")
|
||||
.await?
|
||||
.json(&request)
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| ServerFnError::new(e.to_string()))?;
|
||||
super::agent_client::json_or_error(resp).await
|
||||
}
|
||||
|
||||
/// Put the items of a decision back.
|
||||
#[server]
|
||||
pub async fn undo_decision(request: UndoRequest) -> Result<(), ServerFnError> {
|
||||
let resp = super::agent_client::agent_request(reqwest::Method::POST, "/api/v1/inbox/undo")
|
||||
.await?
|
||||
.json(&request)
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| ServerFnError::new(e.to_string()))?;
|
||||
super::agent_client::ok_or_error(resp).await
|
||||
}
|
||||
|
||||
/// Put a card off; when it comes back.
|
||||
#[server]
|
||||
pub async fn snooze_card(request: SnoozeRequest) -> Result<SnoozeResponse, ServerFnError> {
|
||||
let resp = super::agent_client::agent_request(reqwest::Method::POST, "/api/v1/inbox/snooze")
|
||||
.await?
|
||||
.json(&request)
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| ServerFnError::new(e.to_string()))?;
|
||||
super::agent_client::json_or_error(resp).await
|
||||
}
|
||||
|
||||
/// Take a card's resubmission back (the undo of [`snooze_card`]).
|
||||
#[server]
|
||||
pub async fn unsnooze_card(key: String) -> Result<(), ServerFnError> {
|
||||
let resp = super::agent_client::agent_request(
|
||||
reqwest::Method::DELETE,
|
||||
&format!("/api/v1/inbox/snooze/{key}"),
|
||||
)
|
||||
.await?
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| ServerFnError::new(e.to_string()))?;
|
||||
super::agent_client::ok_or_error(resp).await
|
||||
}
|
||||
@@ -3,6 +3,9 @@ use serde::{Deserialize, Serialize};
|
||||
|
||||
use compliance_core::models::TrackerIssue;
|
||||
|
||||
/// Tickets per page of the list.
|
||||
pub const PAGE_SIZE: u64 = 20;
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
|
||||
pub struct IssuesListResponse {
|
||||
pub data: Vec<TrackerIssue>,
|
||||
@@ -10,9 +13,41 @@ pub struct IssuesListResponse {
|
||||
pub page: Option<u64>,
|
||||
}
|
||||
|
||||
/// The search and filters of the tickets list; an empty field filters nothing.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq)]
|
||||
pub struct IssuesQuery {
|
||||
pub page: u64,
|
||||
/// A word of the title or the ticket number (`913`, `#913`).
|
||||
pub q: String,
|
||||
/// `open` or `closed`.
|
||||
pub status: String,
|
||||
/// One target's tickets.
|
||||
pub repo_id: String,
|
||||
}
|
||||
|
||||
/// The agent path that lists the tickets `query` asks for, every value
|
||||
/// URL-encoded (`#913` would otherwise end the path).
|
||||
#[cfg(feature = "server")]
|
||||
fn issues_path(query: &IssuesQuery) -> String {
|
||||
let mut params = url::form_urlencoded::Serializer::new(String::new());
|
||||
params
|
||||
.append_pair("page", &query.page.to_string())
|
||||
.append_pair("limit", &PAGE_SIZE.to_string());
|
||||
for (key, value) in [
|
||||
("q", query.q.trim()),
|
||||
("status", query.status.as_str()),
|
||||
("repo_id", query.repo_id.as_str()),
|
||||
] {
|
||||
if !value.is_empty() {
|
||||
params.append_pair(key, value);
|
||||
}
|
||||
}
|
||||
format!("/api/v1/issues?{}", params.finish())
|
||||
}
|
||||
|
||||
#[server]
|
||||
pub async fn fetch_issues(page: u64) -> Result<IssuesListResponse, ServerFnError> {
|
||||
let resp = super::agent_client::agent_get(&format!("/api/v1/issues?page={page}&limit=20"))
|
||||
pub async fn fetch_issues(query: IssuesQuery) -> Result<IssuesListResponse, ServerFnError> {
|
||||
let resp = super::agent_client::agent_get(&issues_path(&query))
|
||||
.await?
|
||||
.send()
|
||||
.await
|
||||
@@ -23,3 +58,32 @@ pub async fn fetch_issues(page: u64) -> Result<IssuesListResponse, ServerFnError
|
||||
.map_err(|e| ServerFnError::new(e.to_string()))?;
|
||||
Ok(body)
|
||||
}
|
||||
|
||||
#[cfg(all(test, feature = "server"))]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn an_empty_query_asks_for_one_page() {
|
||||
let query = IssuesQuery {
|
||||
page: 2,
|
||||
..IssuesQuery::default()
|
||||
};
|
||||
assert_eq!(issues_path(&query), "/api/v1/issues?page=2&limit=20");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_search_and_filters_are_encoded() {
|
||||
let query = IssuesQuery {
|
||||
page: 1,
|
||||
q: " #913 ".into(),
|
||||
status: "open".into(),
|
||||
repo_id: "65a1b2c3d4e5f60718293a4b".into(),
|
||||
};
|
||||
assert_eq!(
|
||||
issues_path(&query),
|
||||
"/api/v1/issues?page=1&limit=20&q=%23913&status=open\
|
||||
&repo_id=65a1b2c3d4e5f60718293a4b"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -2,12 +2,17 @@
|
||||
// the #[server] macro generates client stubs for the web target)
|
||||
pub mod auth_check;
|
||||
pub mod chat;
|
||||
pub mod cve_history;
|
||||
pub mod cve_matrix;
|
||||
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;
|
||||
pub mod inbox;
|
||||
pub mod issues;
|
||||
pub mod manual_findings;
|
||||
pub mod mcp;
|
||||
@@ -20,6 +25,8 @@ pub mod platform;
|
||||
pub mod projects;
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub mod sbom;
|
||||
pub mod sbom_ecosystems;
|
||||
pub mod scan_changes;
|
||||
pub mod scans;
|
||||
pub mod stats;
|
||||
pub mod support;
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
//! The SBOM components of one target per ecosystem (#957), for the
|
||||
//! "Komponenten nach Ökosystem" chart.
|
||||
|
||||
use dioxus::prelude::*;
|
||||
|
||||
use compliance_core::sbom_ecosystems::EcosystemCount;
|
||||
|
||||
/// The agent's `/sbom-ecosystems` reply (read on the server only).
|
||||
#[cfg(feature = "server")]
|
||||
#[derive(Debug, serde::Deserialize)]
|
||||
struct EcosystemsResponse {
|
||||
data: Vec<EcosystemCount>,
|
||||
}
|
||||
|
||||
/// The SBOM components of target `target_id` per ecosystem, the largest
|
||||
/// first (`GET /api/v1/targets/{id}/sbom-ecosystems`).
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// The agent's refusal or an unreachable agent, as a [`ServerFnError`].
|
||||
#[server]
|
||||
pub async fn fetch_sbom_ecosystems(
|
||||
target_id: String,
|
||||
) -> Result<Vec<EcosystemCount>, ServerFnError> {
|
||||
let resp =
|
||||
super::agent_client::agent_get(&format!("/api/v1/targets/{target_id}/sbom-ecosystems"))
|
||||
.await?
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| ServerFnError::new(e.to_string()))?;
|
||||
let body: EcosystemsResponse = super::agent_client::json_or_error(resp).await?;
|
||||
Ok(body.data)
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
//! What each of a target's scans changed, for its "Verlauf" view (#957).
|
||||
|
||||
use compliance_core::scan_changes::ScanChange;
|
||||
use dioxus::prelude::*;
|
||||
|
||||
/// Target `id`'s last scans, oldest first, with the CVE alerts each found
|
||||
/// new and gone (`GET /api/v1/targets/{id}/scan-changes`).
|
||||
#[server]
|
||||
pub async fn fetch_scan_changes(id: String) -> Result<Vec<ScanChange>, ServerFnError> {
|
||||
let resp = super::agent_client::agent_get(&format!("/api/v1/targets/{id}/scan-changes"))
|
||||
.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()))
|
||||
}
|
||||
@@ -5,6 +5,7 @@
|
||||
use dioxus::prelude::*;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use compliance_core::cve_groups::{CveGroup, PackageKey};
|
||||
use compliance_core::models::{CveAlert, VexJustification, VexStatus};
|
||||
|
||||
/// A VEX statement as the editor sends it; the agent adds who and when.
|
||||
@@ -86,6 +87,61 @@ pub async fn save_cve_vex(
|
||||
super::agent_client::ok_or_error(resp).await
|
||||
}
|
||||
|
||||
/// The agent's `/cve-groups` reply (read on the server only).
|
||||
#[cfg(feature = "server")]
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct GroupsResponse {
|
||||
data: Vec<CveGroup>,
|
||||
}
|
||||
|
||||
/// The open CVE alerts of target `target_id` grouped by component (#949),
|
||||
/// the most severe group first.
|
||||
#[server]
|
||||
pub async fn fetch_cve_groups(target_id: String) -> Result<Vec<CveGroup>, ServerFnError> {
|
||||
let resp = super::agent_client::agent_get(&format!("/api/v1/targets/{target_id}/cve-groups"))
|
||||
.await?
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| ServerFnError::new(e.to_string()))?;
|
||||
let body: GroupsResponse = super::agent_client::json_or_error(resp).await?;
|
||||
Ok(body.data)
|
||||
}
|
||||
|
||||
/// The body of a group decision: the component and the statement side by
|
||||
/// side (sent on the server only).
|
||||
#[cfg(feature = "server")]
|
||||
#[derive(Serialize)]
|
||||
struct GroupVexBody<'a> {
|
||||
#[serde(flatten)]
|
||||
key: &'a PackageKey,
|
||||
#[serde(flatten)]
|
||||
statement: &'a VexStatementDto,
|
||||
}
|
||||
|
||||
/// State `statement` on every open alert of component `key` in target
|
||||
/// `target_id`, one statement per alert. The agent refuses as for one alert
|
||||
/// ([`save_cve_vex`]), and with 404 when the component has no open alert.
|
||||
#[server]
|
||||
pub async fn save_group_vex(
|
||||
target_id: String,
|
||||
key: PackageKey,
|
||||
statement: VexStatementDto,
|
||||
) -> Result<(), ServerFnError> {
|
||||
let resp = super::agent_client::agent_request(
|
||||
reqwest::Method::PATCH,
|
||||
&format!("/api/v1/targets/{target_id}/cve-groups/vex"),
|
||||
)
|
||||
.await?
|
||||
.json(&GroupVexBody {
|
||||
key: &key,
|
||||
statement: &statement,
|
||||
})
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| ServerFnError::new(e.to_string()))?;
|
||||
super::agent_client::ok_or_error(resp).await
|
||||
}
|
||||
|
||||
/// The VEX document of target `target_id` in `format`, as text to save.
|
||||
#[server]
|
||||
pub async fn fetch_vex_export(
|
||||
@@ -237,6 +293,36 @@ mod tests {
|
||||
assert_eq!(csaf_filename("not json"), "csaf-vex.json");
|
||||
}
|
||||
|
||||
#[cfg(feature = "server")]
|
||||
#[test]
|
||||
fn a_group_decision_names_the_component_beside_the_statement() {
|
||||
let key = PackageKey {
|
||||
package: "vite".into(),
|
||||
version: "5.4.21".into(),
|
||||
purl: Some("pkg:npm/vite@5.4.21".into()),
|
||||
};
|
||||
let statement = VexStatementDto {
|
||||
status: VexStatus::NotAffected,
|
||||
justification: None,
|
||||
impact_statement: Some("Build tool only.".into()),
|
||||
action_statement: None,
|
||||
};
|
||||
assert_eq!(
|
||||
serde_json::to_value(GroupVexBody {
|
||||
key: &key,
|
||||
statement: &statement,
|
||||
})
|
||||
.ok(),
|
||||
Some(serde_json::json!({
|
||||
"package": "vite",
|
||||
"version": "5.4.21",
|
||||
"purl": "pkg:npm/vite@5.4.21",
|
||||
"status": "not_affected",
|
||||
"impact_statement": "Build tool only.",
|
||||
}))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_statement_leaves_out_what_is_not_given() {
|
||||
let dto = VexStatementDto {
|
||||
|
||||
@@ -16,7 +16,7 @@ use crate::infrastructure::evidence::{fetch_compliance, CraCounts};
|
||||
|
||||
/// The label and badge of each control state, in the order the page lists
|
||||
/// them: violated first, requirements evidenced outside the code last.
|
||||
const STATES: [(&str, Text, &str); 5] = [
|
||||
pub(crate) const STATES: [(&str, Text, &str); 5] = [
|
||||
("not_satisfied", tx::NOT_SATISFIED, "badge badge-critical"),
|
||||
("not_assessed", tx::NOT_ASSESSED, "badge badge-medium"),
|
||||
("partial", tx::PARTIAL, "badge badge-info"),
|
||||
@@ -70,7 +70,7 @@ pub fn CompliancePage(id: String) -> Element {
|
||||
|
||||
rsx! {
|
||||
div { class: "back-nav",
|
||||
Link { to: Route::TargetPage { id: id.clone() }, class: "btn btn-ghost btn-back",
|
||||
Link { to: Route::target(id.clone()), class: "btn btn-ghost btn-back",
|
||||
Icon { icon: BsArrowLeft, width: 16, height: 16 }
|
||||
"{name}"
|
||||
}
|
||||
@@ -166,7 +166,7 @@ pub fn CompliancePage(id: String) -> Element {
|
||||
/// state rests on (the findings against it, or why it was not assessed,
|
||||
/// unless `show_reason` is off because the group states it once).
|
||||
#[component]
|
||||
fn ControlRow(control: serde_json::Value, lang: Lang, show_reason: bool) -> Element {
|
||||
pub(crate) fn ControlRow(control: serde_json::Value, lang: Lang, show_reason: bool) -> Element {
|
||||
let findings = control["findings"].as_array().cloned().unwrap_or_default();
|
||||
// The control map's notes are engineering prose in English; in German
|
||||
// the group's hint says the same.
|
||||
|
||||
@@ -14,7 +14,7 @@ use crate::infrastructure::findings::{location, mask_secrets, wire_name};
|
||||
use crate::infrastructure::graph::fetch_impact;
|
||||
use crate::pages::findings::status_icon;
|
||||
use crate::pages::graph_view::impact_has_content;
|
||||
use compliance_core::models::{FindingStatus, ScanType};
|
||||
use compliance_core::models::{FindingStatus, ReviewReason, ScanType};
|
||||
|
||||
/// What happened to the last save on this page, shown next to what was saved.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
@@ -32,6 +32,7 @@ pub fn FindingDetailPage(id: String) -> Element {
|
||||
let finding_id = id.clone();
|
||||
let mut status_save = use_signal(|| SaveState::Idle);
|
||||
let mut feedback_save = use_signal(|| SaveState::Idle);
|
||||
let mut decision_save = use_signal(|| SaveState::Idle);
|
||||
// Accepting a risk asks for a reason before it is saved.
|
||||
// A status that needs a reason (accepted risk, wrong mapping) asks for it
|
||||
// before it is saved.
|
||||
@@ -84,6 +85,29 @@ pub fn FindingDetailPage(id: String) -> Element {
|
||||
let finding_id_for_status = id.clone();
|
||||
let finding_id_for_risk = id.clone();
|
||||
let finding_id_for_feedback = id.clone();
|
||||
let finding_id_for_decision = id.clone();
|
||||
let review_reason = f.review_reason();
|
||||
// A click that sets `status` (with `reason`) and shows the result
|
||||
// beside the AI's rationale.
|
||||
let decide = move |status: FindingStatus, reason: Option<String>| {
|
||||
let id = finding_id_for_decision.clone();
|
||||
move |_: MouseEvent| {
|
||||
let id = id.clone();
|
||||
let wire = wire_name(&status);
|
||||
let reason = reason.clone();
|
||||
spawn(async move {
|
||||
match crate::infrastructure::findings::update_finding_status(
|
||||
id, wire, reason,
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(()) => decision_save.set(SaveState::Saved),
|
||||
Err(e) => decision_save.set(SaveState::Failed(e.to_string())),
|
||||
}
|
||||
finding.restart();
|
||||
});
|
||||
}
|
||||
};
|
||||
let existing_feedback = f.developer_feedback.clone().unwrap_or_default();
|
||||
let where_found = location(f.file_path.as_deref(), f.line_number);
|
||||
// A committed secret is shown shortened; the evidence keeps it.
|
||||
@@ -129,7 +153,7 @@ pub fn FindingDetailPage(id: String) -> Element {
|
||||
"{} | {} | {}",
|
||||
tx::tool_name(&f.scanner, lang),
|
||||
tx::scan_type(&f.scan_type).get(lang),
|
||||
tx::status(&f.status).get(lang)
|
||||
tx::finding_status(&f).get(lang)
|
||||
),
|
||||
}
|
||||
|
||||
@@ -234,11 +258,36 @@ pub fn FindingDetailPage(id: String) -> Element {
|
||||
div { class: "card-header", {tx::TRIAGE.get(lang)} }
|
||||
div {
|
||||
style: "display: flex; align-items: center; gap: 8px; margin-bottom: 8px;",
|
||||
if let Some(action) = &f.triage_action {
|
||||
if let Some(reason) = review_reason {
|
||||
span { class: "badge badge-info",
|
||||
{status_icon(&f.status)}
|
||||
" {tx::review_reason(reason).get(lang)}"
|
||||
}
|
||||
} else if let Some(action) = &f.triage_action {
|
||||
span { class: "badge badge-info", "{action}" }
|
||||
}
|
||||
}
|
||||
p { style: "color: var(--text-secondary); font-size: 14px;", "{rationale}" }
|
||||
// Confirm or reject the AI's guess in one click.
|
||||
if can_write && review_reason == Some(ReviewReason::LikelyFalseAlarm) {
|
||||
div { class: "flex gap-2", style: "margin-top: 10px;",
|
||||
button {
|
||||
class: "btn btn-primary",
|
||||
title: "{tx::MARK_AS.get(lang)} {tx::status(&FindingStatus::FalsePositive).get(lang)}",
|
||||
onclick: decide(FindingStatus::FalsePositive, Some(rationale.clone())),
|
||||
{status_icon(&FindingStatus::FalsePositive)}
|
||||
" {tx::CONFIRM_FALSE_ALARM.get(lang)}"
|
||||
}
|
||||
button {
|
||||
class: "btn btn-ghost",
|
||||
title: "{tx::MARK_AS.get(lang)} {tx::status(&FindingStatus::Triaged).get(lang)}",
|
||||
onclick: decide(FindingStatus::Triaged, None),
|
||||
{status_icon(&FindingStatus::Triaged)}
|
||||
" {tx::REVIEW_ANYWAY.get(lang)}"
|
||||
}
|
||||
}
|
||||
}
|
||||
SaveNote { state: decision_save() }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -392,6 +441,9 @@ pub fn FindingDetailPage(id: String) -> Element {
|
||||
if let Some(scan) = &change.scan {
|
||||
div { style: "color: var(--text-secondary);", {tx::scan_change(scan.kind).get(lang)} }
|
||||
}
|
||||
if let Some(note) = tracker_note(change, lang) {
|
||||
div { style: "color: var(--text-secondary);", "{note}" }
|
||||
}
|
||||
if let Some(reason) = &change.reason {
|
||||
div { style: "color: var(--text-secondary);", "{tx::REASON.get(lang)}: {reason}" }
|
||||
}
|
||||
@@ -515,6 +567,18 @@ fn changed_by(
|
||||
format!("{} {short}", tx::SOMEONE.get(lang))
|
||||
}
|
||||
|
||||
/// What happened to the finding's issue in the tracker, with the tracker
|
||||
/// user who did it ("Im Ticket geschlossen von dev-anna"); `None` for a
|
||||
/// change made in Prüfwerk.
|
||||
fn tracker_note(
|
||||
change: &compliance_core::models::finding::StatusChange,
|
||||
lang: crate::i18n::Lang,
|
||||
) -> Option<String> {
|
||||
let kind = change.tracker?;
|
||||
let login = change.by_name.as_deref().unwrap_or_default();
|
||||
Some(format!("{} {login}", tx::tracker_change(kind).get(lang)))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -530,6 +594,7 @@ mod tests {
|
||||
at: chrono::Utc::now(),
|
||||
reason: None,
|
||||
scan: None,
|
||||
tracker: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -568,6 +633,31 @@ mod tests {
|
||||
assert_eq!(changed_by(&c, &me(), Lang::En), "Prüfwerk scan");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_change_from_the_ticket_names_the_tracker_user() {
|
||||
use compliance_core::models::TrackerChangeKind;
|
||||
let c = StatusChange::by_tracker(
|
||||
FindingStatus::Resolved,
|
||||
TrackerChangeKind::ClosedInTracker,
|
||||
"dev-anna",
|
||||
);
|
||||
assert_eq!(changed_by(&c, &me(), Lang::De), "dev-anna");
|
||||
assert_eq!(
|
||||
tracker_note(&c, Lang::De).as_deref(),
|
||||
Some("Im Ticket geschlossen von dev-anna")
|
||||
);
|
||||
let c = StatusChange::by_tracker(
|
||||
FindingStatus::Open,
|
||||
TrackerChangeKind::ReopenedInTracker,
|
||||
"dev-anna",
|
||||
);
|
||||
assert_eq!(
|
||||
tracker_note(&c, Lang::En).as_deref(),
|
||||
Some("Reopened in the ticket by dev-anna")
|
||||
);
|
||||
assert!(tracker_note(&change("x", Some("y")), Lang::De).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_old_change_of_someone_else_shows_a_short_id() {
|
||||
let c = change("0b7d51aa-9f1c-4e33-8a1f-2d8c1e0f9a77", None);
|
||||
|
||||
@@ -7,24 +7,60 @@ 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::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, 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;
|
||||
|
||||
#[component]
|
||||
pub fn FindingsPage(target: String) -> Element {
|
||||
pub fn FindingsPage(
|
||||
target: String,
|
||||
scan_type: Option<String>,
|
||||
severity: Option<String>,
|
||||
path: Option<String>,
|
||||
) -> Element {
|
||||
let can_write = crate::components::no_access::use_can_write();
|
||||
let lang = use_lang()();
|
||||
let mut toasts = use_context::<Toasts>();
|
||||
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());
|
||||
// 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()),
|
||||
(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.
|
||||
@@ -51,6 +87,7 @@ pub fn FindingsPage(target: String) -> Element {
|
||||
});
|
||||
|
||||
let mut findings = use_resource(move || {
|
||||
let grouped_view = grouped();
|
||||
let query = crate::infrastructure::findings::FindingsQuery {
|
||||
page: page(),
|
||||
severity: severity_filter(),
|
||||
@@ -59,10 +96,14 @@ 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(),
|
||||
};
|
||||
async move {
|
||||
if grouped_view {
|
||||
return None;
|
||||
}
|
||||
crate::infrastructure::findings::fetch_findings(query)
|
||||
.await
|
||||
.ok()
|
||||
@@ -124,8 +165,27 @@ 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: "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;",
|
||||
@@ -152,31 +212,37 @@ pub fn FindingsPage(target: String) -> Element {
|
||||
}
|
||||
}
|
||||
select {
|
||||
disabled: grouped(),
|
||||
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 {
|
||||
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.
|
||||
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 {
|
||||
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.
|
||||
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()) {
|
||||
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() {
|
||||
@@ -188,7 +254,7 @@ pub fn FindingsPage(target: String) -> Element {
|
||||
|
||||
// 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);",
|
||||
@@ -241,6 +307,7 @@ pub fn FindingsPage(target: String) -> Element {
|
||||
}
|
||||
|
||||
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<String> = resp.data.iter().filter_map(|f| f.id.as_ref().map(|id| id.to_hex())).collect();
|
||||
@@ -394,9 +461,13 @@ pub fn FindingsPage(target: String) -> Element {
|
||||
}
|
||||
}
|
||||
td {
|
||||
span { class: "badge badge-info",
|
||||
// Why the AI left it to a person, its
|
||||
// rationale on hover.
|
||||
span {
|
||||
class: "badge badge-info",
|
||||
title: finding.review_reason().and(finding.triage_rationale.clone()),
|
||||
{status_icon(&finding.status)}
|
||||
" {tx::status(&finding.status).get(lang)}"
|
||||
" {tx::finding_status(finding).get(lang)}"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -500,7 +500,7 @@ fn GraphBack(repo_id: String) -> Element {
|
||||
let lang = use_lang()();
|
||||
rsx! {
|
||||
div { class: "back-nav",
|
||||
Link { to: Route::TargetPage { id: repo_id }, class: "btn btn-ghost btn-back",
|
||||
Link { to: Route::target(repo_id), class: "btn btn-ghost btn-back",
|
||||
Icon { icon: BsArrowLeft, width: 16, height: 16 }
|
||||
{tx::BACK.get(lang)}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,925 @@
|
||||
//! "Heute" (#950), the landing page: the workspace's open decisions in four
|
||||
//! urgency buckets, one card per decision, with the decision, "Später" with
|
||||
//! a resubmission date, and undo, all from here.
|
||||
//!
|
||||
//! Keyboard (on this page only, never while typing): `j`/`k` move between
|
||||
//! cards, `f` false alarm (VEX `not_affected` on a CVE card), `a` risk
|
||||
//! accepted (VEX `affected` on a CVE card), `s` later (one week), `Esc`
|
||||
//! closes an open input.
|
||||
|
||||
use std::collections::HashSet;
|
||||
use std::rc::Rc;
|
||||
|
||||
use chrono::{DateTime, NaiveDate, Utc};
|
||||
use dioxus::prelude::*;
|
||||
|
||||
use compliance_core::models::inbox::{
|
||||
Bucket, CardKind, DecideRequest, InboxAction, InboxCard, InboxView, Reason, SnoozeFor,
|
||||
SnoozeRequest, UndoRequest,
|
||||
};
|
||||
use compliance_core::models::VexJustification;
|
||||
|
||||
use crate::app::Route;
|
||||
use crate::components::no_access::use_can_write;
|
||||
use crate::components::page_header::PageHeader;
|
||||
use crate::components::severity_badge::SeverityBadge;
|
||||
use crate::components::toast::{ToastType, Toasts};
|
||||
use crate::i18n::texts::{common, inbox as tx, vex as vex_tx};
|
||||
use crate::i18n::{use_lang, Lang, Text};
|
||||
use crate::infrastructure::inbox::{
|
||||
decide_card, fetch_inbox, snooze_card, undo_decision, unsnooze_card,
|
||||
};
|
||||
|
||||
/// The workspace's "Heute handeln" cards, for the sidebar: fetched once,
|
||||
/// then kept current by this page.
|
||||
pub static TODAY_COUNT: GlobalSignal<Option<u64>> = Signal::global(|| None);
|
||||
|
||||
/// How long the undo strip stays after a decision.
|
||||
#[cfg(feature = "web")]
|
||||
const UNDO_MS: u32 = 8_000;
|
||||
|
||||
/// The VEX justifications in the "Nicht betroffen" choice, with their labels.
|
||||
const JUSTIFICATIONS: [(VexJustification, Text); 5] = [
|
||||
(
|
||||
VexJustification::ComponentNotPresent,
|
||||
vex_tx::COMPONENT_NOT_PRESENT,
|
||||
),
|
||||
(
|
||||
VexJustification::VulnerableCodeNotPresent,
|
||||
vex_tx::CODE_NOT_PRESENT,
|
||||
),
|
||||
(
|
||||
VexJustification::VulnerableCodeNotInExecutePath,
|
||||
vex_tx::CODE_NOT_IN_EXECUTE_PATH,
|
||||
),
|
||||
(
|
||||
VexJustification::VulnerableCodeCannotBeControlledByAdversary,
|
||||
vex_tx::CODE_NOT_CONTROLLABLE,
|
||||
),
|
||||
(
|
||||
VexJustification::InlineMitigationsAlreadyExist,
|
||||
vex_tx::MITIGATIONS_EXIST,
|
||||
),
|
||||
];
|
||||
|
||||
/// A decision that needs a word first: the reason of an accepted risk, the
|
||||
/// justification of a `not_affected`, the action of an `affected`.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
struct Pending {
|
||||
key: String,
|
||||
action: InboxAction,
|
||||
text: String,
|
||||
justification: Option<VexJustification>,
|
||||
}
|
||||
|
||||
impl Pending {
|
||||
/// Whether it carries what the agent asks for.
|
||||
fn ready(&self) -> bool {
|
||||
let has_text = !self.text.trim().is_empty();
|
||||
match self.action {
|
||||
InboxAction::NotAffected => self.justification.is_some() || has_text,
|
||||
InboxAction::AcceptedRisk | InboxAction::Affected => has_text,
|
||||
InboxAction::FalsePositive | InboxAction::Confirm => true,
|
||||
}
|
||||
}
|
||||
|
||||
/// The request deciding card `key` with it.
|
||||
fn request(&self) -> DecideRequest {
|
||||
let text = Some(self.text.trim().to_string()).filter(|t| !t.is_empty());
|
||||
let (reason, statement) = match self.action {
|
||||
InboxAction::AcceptedRisk => (text, None),
|
||||
InboxAction::NotAffected | InboxAction::Affected => (None, text),
|
||||
InboxAction::FalsePositive | InboxAction::Confirm => (None, None),
|
||||
};
|
||||
DecideRequest {
|
||||
key: self.key.clone(),
|
||||
action: self.action,
|
||||
reason,
|
||||
justification: self
|
||||
.justification
|
||||
.filter(|_| self.action == InboxAction::NotAffected),
|
||||
statement,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What the undo strip takes back.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
enum UndoKind {
|
||||
Decision(UndoRequest),
|
||||
Snooze(String),
|
||||
}
|
||||
|
||||
/// The undo strip's offer; `id` tells a newer offer from the one a timer
|
||||
/// was started for.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
struct UndoOffer {
|
||||
id: u64,
|
||||
kind: UndoKind,
|
||||
message: String,
|
||||
}
|
||||
|
||||
/// The labels of a bucket: name, what goes in it, and what an empty one says.
|
||||
pub(crate) const fn bucket_texts(bucket: Bucket) -> (Text, Text, Text) {
|
||||
match bucket {
|
||||
Bucket::Today => (tx::TODAY, tx::TODAY_HINT, tx::EMPTY_TODAY),
|
||||
Bucket::ThisWeek => (tx::THIS_WEEK, tx::THIS_WEEK_HINT, tx::EMPTY_THIS_WEEK),
|
||||
Bucket::Later => (tx::LATER, tx::LATER_HINT, tx::EMPTY_LATER),
|
||||
Bucket::LikelyFalsePositive => (tx::AI, tx::AI_HINT, tx::EMPTY_AI),
|
||||
}
|
||||
}
|
||||
|
||||
/// The CSS tone of a bucket's tile.
|
||||
pub(crate) const fn bucket_tone(bucket: Bucket) -> &'static str {
|
||||
match bucket {
|
||||
Bucket::Today => "tone-danger",
|
||||
Bucket::ThisWeek => "tone-warning",
|
||||
Bucket::Later => "tone-neutral",
|
||||
Bucket::LikelyFalsePositive => "tone-accent",
|
||||
}
|
||||
}
|
||||
|
||||
/// An action's button label; the AI bucket's false alarm confirms the AI.
|
||||
fn action_label(action: InboxAction, bucket: Bucket) -> Text {
|
||||
match action {
|
||||
InboxAction::FalsePositive if bucket == Bucket::LikelyFalsePositive => {
|
||||
tx::CONFIRM_FALSE_POSITIVE
|
||||
}
|
||||
InboxAction::FalsePositive => tx::FALSE_POSITIVE,
|
||||
InboxAction::AcceptedRisk => tx::ACCEPT_RISK,
|
||||
InboxAction::Confirm => tx::CONFIRM,
|
||||
InboxAction::NotAffected => tx::NOT_AFFECTED,
|
||||
InboxAction::Affected => tx::AFFECTED,
|
||||
}
|
||||
}
|
||||
|
||||
/// The action key `f` or `a` stands for on `card`, if the card offers it:
|
||||
/// false alarm and accepted risk, on a CVE card their VEX counterparts.
|
||||
fn shortcut_action(key: &str, card: &InboxCard) -> Option<InboxAction> {
|
||||
let wanted = match (key, card.kind) {
|
||||
("f", CardKind::Finding) => InboxAction::FalsePositive,
|
||||
("f", CardKind::CvePackage) => InboxAction::NotAffected,
|
||||
("a", CardKind::Finding) => InboxAction::AcceptedRisk,
|
||||
("a", CardKind::CvePackage) => InboxAction::Affected,
|
||||
_ => return None,
|
||||
};
|
||||
card.actions.contains(&wanted).then_some(wanted)
|
||||
}
|
||||
|
||||
/// A day in the reader's convention: `01.12.2026`, `2026-12-01`.
|
||||
fn format_day(time: &DateTime<Utc>, lang: Lang) -> String {
|
||||
match lang {
|
||||
Lang::De => time.format("%d.%m.%Y").to_string(),
|
||||
Lang::En => time.format("%Y-%m-%d").to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
/// A reason as a chip: its text and tone.
|
||||
fn chip(reason: &Reason, lang: Lang) -> (String, &'static str) {
|
||||
match reason {
|
||||
Reason::AiDismissed => (tx::AI_DISMISSED.get(lang).to_string(), "tone-accent"),
|
||||
Reason::Kev => (tx::KEV.get(lang).to_string(), "tone-danger"),
|
||||
Reason::Epss { percentile } => (tx::epss(*percentile, lang), "tone-warning"),
|
||||
Reason::EnisaDeadline {
|
||||
stage: Some(stage),
|
||||
overdue,
|
||||
hours_left,
|
||||
..
|
||||
} => (tx::enisa(stage, *overdue, *hours_left, lang), "tone-danger"),
|
||||
Reason::EnisaDeadline { stage: None, .. } => {
|
||||
(tx::CRA_DUTY.get(lang).to_string(), "tone-danger")
|
||||
}
|
||||
Reason::SecretInCode => (tx::SECRET_IN_CODE.get(lang).to_string(), "tone-danger"),
|
||||
Reason::FixAvailable { version } => (tx::fix(version), "tone-success"),
|
||||
Reason::Resubmission { since } => (
|
||||
tx::resubmission(&format_day(since, lang), lang),
|
||||
"tone-info",
|
||||
),
|
||||
Reason::NewSinceResubmission { since } => (
|
||||
tx::new_since_resubmission(&format_day(since, lang), lang),
|
||||
"tone-danger",
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
/// The page's state and what it does with it; every field is a copyable
|
||||
/// handle, so event handlers take the whole of it.
|
||||
#[derive(Clone, Copy)]
|
||||
struct Inbox {
|
||||
view: Resource<Result<InboxView, ServerFnError>>,
|
||||
hidden: Signal<HashSet<String>>,
|
||||
pending: Signal<Option<Pending>>,
|
||||
undo: Signal<Option<UndoOffer>>,
|
||||
offers: Signal<u64>,
|
||||
busy: Signal<bool>,
|
||||
page: Signal<Option<Rc<MountedData>>>,
|
||||
toasts: Toasts,
|
||||
lang: Lang,
|
||||
}
|
||||
|
||||
impl Inbox {
|
||||
/// Start `action` on `card`: at once, or by asking for its input first.
|
||||
fn begin(mut self, card: &InboxCard, action: InboxAction) {
|
||||
if !action.needs_input() {
|
||||
self.decide(
|
||||
card.title.clone(),
|
||||
Pending {
|
||||
key: card.key.clone(),
|
||||
action,
|
||||
text: String::new(),
|
||||
justification: None,
|
||||
},
|
||||
);
|
||||
return;
|
||||
}
|
||||
let text = match (action, &card.fix_version) {
|
||||
(InboxAction::Affected, Some(version)) => tx::update_to(version, self.lang),
|
||||
_ => String::new(),
|
||||
};
|
||||
self.pending.set(Some(Pending {
|
||||
key: card.key.clone(),
|
||||
action,
|
||||
text,
|
||||
justification: None,
|
||||
}));
|
||||
}
|
||||
|
||||
/// Apply `decision` to the card titled `title`, then offer to undo it.
|
||||
fn decide(mut self, title: String, decision: Pending) {
|
||||
if *self.busy.peek() || !decision.ready() {
|
||||
return;
|
||||
}
|
||||
self.busy.set(true);
|
||||
spawn(async move {
|
||||
match decide_card(decision.request()).await {
|
||||
Ok(answer) => {
|
||||
self.hidden.write().insert(answer.key.clone());
|
||||
self.pending.set(None);
|
||||
let message = format!("{}: {title}", tx::DECIDED.get(self.lang));
|
||||
self.offer(
|
||||
UndoKind::Decision(UndoRequest {
|
||||
key: answer.key,
|
||||
previous: answer.previous,
|
||||
}),
|
||||
message,
|
||||
);
|
||||
self.view.restart();
|
||||
}
|
||||
Err(e) => self.failed(&e),
|
||||
}
|
||||
self.busy.set(false);
|
||||
self.refocus().await;
|
||||
});
|
||||
}
|
||||
|
||||
/// Put `card` off as `choice` says, then offer to undo it.
|
||||
fn snooze(mut self, card: &InboxCard, choice: SnoozeFor) {
|
||||
if *self.busy.peek() {
|
||||
return;
|
||||
}
|
||||
self.busy.set(true);
|
||||
let request = SnoozeRequest {
|
||||
key: card.key.clone(),
|
||||
snooze_for: choice,
|
||||
};
|
||||
spawn(async move {
|
||||
match snooze_card(request).await {
|
||||
Ok(answer) => {
|
||||
self.hidden.write().insert(answer.key.clone());
|
||||
self.pending.set(None);
|
||||
let message = tx::snoozed(&format_day(&answer.until, self.lang), self.lang);
|
||||
self.offer(UndoKind::Snooze(answer.key), message);
|
||||
self.view.restart();
|
||||
}
|
||||
Err(e) => self.failed(&e),
|
||||
}
|
||||
self.busy.set(false);
|
||||
self.refocus().await;
|
||||
});
|
||||
}
|
||||
|
||||
/// Take the offered decision or snooze back.
|
||||
fn undo(mut self) {
|
||||
let Some(offer) = self.undo.write().take() else {
|
||||
return;
|
||||
};
|
||||
spawn(async move {
|
||||
let (key, result) = match offer.kind {
|
||||
UndoKind::Decision(request) => (request.key.clone(), undo_decision(request).await),
|
||||
UndoKind::Snooze(key) => (key.clone(), unsnooze_card(key).await),
|
||||
};
|
||||
match result {
|
||||
Ok(()) => {
|
||||
self.hidden.write().remove(&key);
|
||||
self.toasts.push(ToastType::Info, tx::UNDONE.get(self.lang));
|
||||
self.view.restart();
|
||||
}
|
||||
Err(e) => self.failed(&e),
|
||||
}
|
||||
self.refocus().await;
|
||||
});
|
||||
}
|
||||
|
||||
/// Show the undo strip with `message` for a while.
|
||||
fn offer(mut self, kind: UndoKind, message: String) {
|
||||
let id = *self.offers.peek() + 1;
|
||||
self.offers.set(id);
|
||||
self.undo.set(Some(UndoOffer { id, kind, message }));
|
||||
#[cfg(feature = "web")]
|
||||
{
|
||||
let mut undo = self.undo;
|
||||
spawn(async move {
|
||||
gloo_timers::future::TimeoutFuture::new(UNDO_MS).await;
|
||||
if undo.peek().as_ref().is_some_and(|o| o.id == id) {
|
||||
undo.set(None);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
fn failed(mut self, error: &ServerFnError) {
|
||||
self.toasts.push(
|
||||
ToastType::Error,
|
||||
format!("{}: {error}", tx::FAILED.get(self.lang)),
|
||||
);
|
||||
}
|
||||
|
||||
/// Give the keyboard back to the page (a removed card took the focus
|
||||
/// with it).
|
||||
async fn refocus(self) {
|
||||
let page = self.page.peek().clone();
|
||||
if let Some(page) = page {
|
||||
// Focusing can only fail when the page has gone; nothing to do then.
|
||||
let _focused = page.set_focus(true).await;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Heute: the open decisions of the workspace, or of target `target` (from
|
||||
/// `?target=`, e.g. a target page's button), with the bucket `bucket` open
|
||||
/// (`?bucket=`; the most urgent one when absent or unknown).
|
||||
#[component]
|
||||
pub fn HeutePage(target: String, bucket: String) -> Element {
|
||||
let lang = use_lang()();
|
||||
let can_write = use_can_write();
|
||||
let target = use_signal(|| target.clone());
|
||||
let bucket = use_signal(|| Bucket::parse(&bucket).unwrap_or(Bucket::Today));
|
||||
let mut selected = use_signal(|| 0_usize);
|
||||
let view = use_resource(move || async move { fetch_inbox(target(), bucket(), None).await });
|
||||
let inbox = Inbox {
|
||||
view,
|
||||
hidden: use_signal(HashSet::new),
|
||||
pending: use_signal(|| None),
|
||||
undo: use_signal(|| None),
|
||||
offers: use_signal(|| 0),
|
||||
busy: use_signal(|| false),
|
||||
page: use_signal(|| None),
|
||||
toasts: use_context::<Toasts>(),
|
||||
lang,
|
||||
};
|
||||
|
||||
// The sidebar shows the workspace's count, not one target's.
|
||||
use_effect(move || {
|
||||
if let Some(Ok(view)) = &*view.read() {
|
||||
if target.peek().is_empty() && *bucket.peek() == view.bucket {
|
||||
*TODAY_COUNT.write() = Some(view.counts.today);
|
||||
}
|
||||
}
|
||||
});
|
||||
// Keep the chosen card in sight.
|
||||
use_effect(move || {
|
||||
let _ = selected();
|
||||
let _scrolled = document::eval(
|
||||
"document.querySelector('.inbox-card.is-selected')?.scrollIntoView({block: 'nearest'})",
|
||||
);
|
||||
});
|
||||
|
||||
let current = view.read().clone();
|
||||
let cards: Vec<InboxCard> = match ¤t {
|
||||
Some(Ok(v)) => {
|
||||
let hidden = inbox.hidden.read();
|
||||
v.cards
|
||||
.iter()
|
||||
.filter(|c| !hidden.contains(&c.key))
|
||||
.cloned()
|
||||
.collect()
|
||||
}
|
||||
_ => Vec::new(),
|
||||
};
|
||||
let chosen = selected().min(cards.len().saturating_sub(1));
|
||||
let key_cards = cards.clone();
|
||||
let mut pending = inbox.pending;
|
||||
let onkeydown = move |e: KeyboardEvent| {
|
||||
let modifiers = e.modifiers();
|
||||
if modifiers.ctrl() || modifiers.meta() || modifiers.alt() {
|
||||
return;
|
||||
}
|
||||
let key = match e.key() {
|
||||
Key::Character(c) => c,
|
||||
Key::Escape => {
|
||||
pending.set(None);
|
||||
return;
|
||||
}
|
||||
_ => return,
|
||||
};
|
||||
let card = key_cards.get(chosen);
|
||||
match (key.as_str(), card) {
|
||||
("j", Some(_)) => selected.set((chosen + 1).min(key_cards.len() - 1)),
|
||||
("k", Some(_)) => selected.set(chosen.saturating_sub(1)),
|
||||
("f" | "a", Some(card)) if can_write => {
|
||||
if let Some(action) = shortcut_action(&key, card) {
|
||||
e.prevent_default();
|
||||
inbox.begin(card, action);
|
||||
}
|
||||
}
|
||||
("s", Some(card)) if can_write => {
|
||||
e.prevent_default();
|
||||
inbox.snooze(card, SnoozeFor::Week);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
};
|
||||
|
||||
rsx! {
|
||||
div {
|
||||
class: "inbox-page",
|
||||
tabindex: "0",
|
||||
onkeydown,
|
||||
onmounted: move |e| {
|
||||
let page = e.data();
|
||||
let mut handle = inbox.page;
|
||||
handle.set(Some(page.clone()));
|
||||
spawn(async move {
|
||||
let _focused = page.set_focus(true).await;
|
||||
});
|
||||
},
|
||||
PageHeader {
|
||||
title: tx::TITLE.get(lang).to_string(),
|
||||
description: tx::SUBTITLE.get(lang).to_string(),
|
||||
}
|
||||
match current {
|
||||
None => rsx! { div { class: "loading", {common::LOADING.get(lang)} } },
|
||||
Some(Err(_)) => rsx! {
|
||||
div { class: "card inbox-empty",
|
||||
p { {tx::LOAD_FAILED.get(lang)} }
|
||||
button {
|
||||
class: "btn btn-secondary btn-sm",
|
||||
onclick: move |_| { let mut view = view; view.restart(); },
|
||||
{common::RETRY.get(lang)}
|
||||
}
|
||||
}
|
||||
},
|
||||
Some(Ok(v)) => rsx! {
|
||||
InboxHeader { view: v.clone(), target, bucket, selected, pending }
|
||||
if cards.is_empty() {
|
||||
div { class: "card inbox-empty",
|
||||
p { {bucket_texts(v.bucket).2.get(lang)} }
|
||||
}
|
||||
} else {
|
||||
div { class: "inbox-cards",
|
||||
for (i, card) in cards.into_iter().enumerate() {
|
||||
CardView {
|
||||
key: "{card.key}",
|
||||
target_name: v
|
||||
.targets
|
||||
.iter()
|
||||
.find(|t| t.id == card.target_id)
|
||||
.map_or_else(|| card.target_id.clone(), |t| t.name.clone()),
|
||||
selected: i == chosen,
|
||||
can_write,
|
||||
pending: inbox
|
||||
.pending
|
||||
.read()
|
||||
.clone()
|
||||
.filter(|p| p.key == card.key),
|
||||
on_select: move |_| selected.set(i),
|
||||
on_action: {
|
||||
let card = card.clone();
|
||||
move |action| inbox.begin(&card, action)
|
||||
},
|
||||
on_snooze: {
|
||||
let card = card.clone();
|
||||
move |choice| inbox.snooze(&card, choice)
|
||||
},
|
||||
on_edit: move |next| pending.set(Some(next)),
|
||||
on_submit: {
|
||||
let title = card.title.clone();
|
||||
move |decision| inbox.decide(title.clone(), decision)
|
||||
},
|
||||
on_cancel: move |_| pending.set(None),
|
||||
card,
|
||||
}
|
||||
}
|
||||
}
|
||||
if can_write {
|
||||
p { class: "inbox-shortcuts", {tx::SHORTCUTS.get(lang)} }
|
||||
}
|
||||
}
|
||||
},
|
||||
}
|
||||
if let Some(offer) = (inbox.undo)() {
|
||||
div { class: "inbox-undo", role: "status",
|
||||
span { "{offer.message}" }
|
||||
button {
|
||||
class: "btn btn-sm inbox-undo-btn",
|
||||
onclick: move |_| inbox.undo(),
|
||||
{tx::UNDO.get(lang)}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The Erstbewertung, the target chips and the bucket tiles.
|
||||
#[component]
|
||||
fn InboxHeader(
|
||||
view: InboxView,
|
||||
target: Signal<String>,
|
||||
bucket: Signal<Bucket>,
|
||||
selected: Signal<usize>,
|
||||
pending: Signal<Option<Pending>>,
|
||||
) -> Element {
|
||||
let lang = use_lang()();
|
||||
let progress = view.progress;
|
||||
let percent = progress.percent();
|
||||
let mut choose_bucket = move |b: Bucket| {
|
||||
bucket.set(b);
|
||||
selected.set(0);
|
||||
pending.set(None);
|
||||
};
|
||||
let mut choose_target = move |id: String| {
|
||||
target.set(id);
|
||||
selected.set(0);
|
||||
pending.set(None);
|
||||
};
|
||||
rsx! {
|
||||
section { class: "inbox-progress", title: tx::PROGRESS_HINT.get(lang),
|
||||
div { class: "inbox-progress-head",
|
||||
span { class: "inbox-progress-label", {tx::PROGRESS.get(lang)} }
|
||||
span { class: "inbox-progress-value",
|
||||
{tx::progress_line(progress.decided, progress.total, lang)}
|
||||
}
|
||||
span { class: "inbox-progress-percent", "{percent} %" }
|
||||
}
|
||||
div {
|
||||
class: "inbox-progress-track",
|
||||
role: "progressbar",
|
||||
"aria-valuemin": "0",
|
||||
"aria-valuemax": "100",
|
||||
"aria-valuenow": "{percent}",
|
||||
div { class: "inbox-progress-fill", style: "width: {percent}%" }
|
||||
}
|
||||
}
|
||||
if !view.targets.is_empty() {
|
||||
div { class: "inbox-targets",
|
||||
button {
|
||||
class: if target().is_empty() { "inbox-target is-active" } else { "inbox-target" },
|
||||
onclick: move |_| choose_target(String::new()),
|
||||
{tx::ALL_TARGETS.get(lang)}
|
||||
}
|
||||
for t in view.targets.iter().cloned() {
|
||||
button {
|
||||
key: "{t.id}",
|
||||
class: if target() == t.id { "inbox-target is-active" } else { "inbox-target" },
|
||||
onclick: move |_| choose_target(t.id.clone()),
|
||||
"{t.name}"
|
||||
span { class: "inbox-target-count", "{t.counts.total()}" }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
div { class: "inbox-buckets", role: "tablist",
|
||||
for b in Bucket::ALL {
|
||||
{
|
||||
let (label, hint, _) = bucket_texts(b);
|
||||
let active = view.bucket == b;
|
||||
let tone = bucket_tone(b);
|
||||
let count = view.counts.get(b);
|
||||
rsx! {
|
||||
button {
|
||||
key: "{b.as_str()}",
|
||||
class: if active { "inbox-bucket {tone} is-active" } else { "inbox-bucket {tone}" },
|
||||
role: "tab",
|
||||
"aria-selected": if active { "true" } else { "false" },
|
||||
onclick: move |_| choose_bucket(b),
|
||||
span { class: "inbox-bucket-count", "{count}" }
|
||||
span { class: "inbox-bucket-label", {label.get(lang)} }
|
||||
span { class: "inbox-bucket-hint", {hint.get(lang)} }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One card: what it is, why it is here, and its decisions.
|
||||
#[component]
|
||||
fn CardView(
|
||||
card: InboxCard,
|
||||
target_name: String,
|
||||
selected: bool,
|
||||
can_write: bool,
|
||||
pending: Option<Pending>,
|
||||
on_select: EventHandler<()>,
|
||||
on_action: EventHandler<InboxAction>,
|
||||
on_snooze: EventHandler<SnoozeFor>,
|
||||
on_edit: EventHandler<Pending>,
|
||||
on_submit: EventHandler<Pending>,
|
||||
on_cancel: EventHandler<()>,
|
||||
) -> Element {
|
||||
let lang = use_lang()();
|
||||
let mut date = use_signal(String::new);
|
||||
let details = match card.kind {
|
||||
CardKind::Finding => Route::FindingDetailPage {
|
||||
id: card.item_ids.first().cloned().unwrap_or_default(),
|
||||
},
|
||||
CardKind::CvePackage => Route::target(card.target_id.clone()),
|
||||
};
|
||||
let size = match card.kind {
|
||||
CardKind::CvePackage => Some(tx::cves(card.count)),
|
||||
CardKind::Finding if card.count > 1 => Some(tx::places(card.count, lang)),
|
||||
CardKind::Finding => None,
|
||||
};
|
||||
let chips: Vec<(String, &'static str)> = card.reasons.iter().map(|r| chip(r, lang)).collect();
|
||||
let bucket = card.bucket;
|
||||
rsx! {
|
||||
article {
|
||||
class: if selected { "inbox-card is-selected" } else { "inbox-card" },
|
||||
onclick: move |_| on_select.call(()),
|
||||
div { class: "inbox-card-head",
|
||||
SeverityBadge { severity: card.severity.to_string() }
|
||||
h3 { class: "inbox-card-title", "{card.title}" }
|
||||
}
|
||||
p { class: "inbox-card-sub",
|
||||
span { class: "inbox-card-target", "{target_name}" }
|
||||
if !card.subtitle.is_empty() {
|
||||
code { class: "inbox-card-place", "{card.subtitle}" }
|
||||
}
|
||||
if let Some(size) = size {
|
||||
span { class: "inbox-card-size", "{size}" }
|
||||
}
|
||||
}
|
||||
if !chips.is_empty() {
|
||||
div { class: "inbox-chips",
|
||||
for (label, tone) in chips {
|
||||
span { class: "inbox-chip {tone}", "{label}" }
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(note) = card.note.clone() {
|
||||
p { class: "inbox-card-note",
|
||||
span { class: "inbox-card-note-label", {tx::AI_NOTE.get(lang)} }
|
||||
"{note}"
|
||||
}
|
||||
}
|
||||
if let Some(decision) = pending {
|
||||
DecisionInput { decision, on_edit, on_submit, on_cancel }
|
||||
} else {
|
||||
div { class: "inbox-actions",
|
||||
if can_write {
|
||||
for (i, action) in card.actions.iter().copied().enumerate() {
|
||||
button {
|
||||
key: "{i}",
|
||||
class: if i == 0 { "btn btn-primary btn-sm" } else { "btn btn-secondary btn-sm" },
|
||||
onclick: move |e| {
|
||||
e.stop_propagation();
|
||||
on_action.call(action);
|
||||
},
|
||||
{action_label(action, bucket).get(lang)}
|
||||
}
|
||||
}
|
||||
details {
|
||||
class: "inbox-later",
|
||||
onclick: move |e| e.stop_propagation(),
|
||||
summary { class: "btn btn-ghost btn-sm", {tx::LATER_MENU.get(lang)} " ▾" }
|
||||
div { class: "inbox-later-menu",
|
||||
button {
|
||||
class: "inbox-later-option",
|
||||
onclick: move |_| on_snooze.call(SnoozeFor::Week),
|
||||
{tx::ONE_WEEK.get(lang)}
|
||||
}
|
||||
button {
|
||||
class: "inbox-later-option",
|
||||
onclick: move |_| on_snooze.call(SnoozeFor::Month),
|
||||
{tx::ONE_MONTH.get(lang)}
|
||||
}
|
||||
label { class: "inbox-later-date",
|
||||
span { {tx::ON_DATE.get(lang)} }
|
||||
input {
|
||||
r#type: "date",
|
||||
value: "{date}",
|
||||
oninput: move |e| date.set(e.value()),
|
||||
onkeydown: move |e| e.stop_propagation(),
|
||||
}
|
||||
}
|
||||
button {
|
||||
class: "btn btn-secondary btn-sm",
|
||||
disabled: NaiveDate::parse_from_str(&date(), "%Y-%m-%d").is_err(),
|
||||
onclick: move |_| {
|
||||
if let Ok(day) = NaiveDate::parse_from_str(&date(), "%Y-%m-%d") {
|
||||
on_snooze.call(SnoozeFor::Date { date: day });
|
||||
}
|
||||
},
|
||||
{tx::SET_DATE.get(lang)}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Link {
|
||||
class: "inbox-details",
|
||||
to: details,
|
||||
onclick: move |e: MouseEvent| e.stop_propagation(),
|
||||
{tx::DETAILS.get(lang)}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The input a decision needs before it can be made.
|
||||
#[component]
|
||||
fn DecisionInput(
|
||||
decision: Pending,
|
||||
on_edit: EventHandler<Pending>,
|
||||
on_submit: EventHandler<Pending>,
|
||||
on_cancel: EventHandler<()>,
|
||||
) -> Element {
|
||||
let lang = use_lang()();
|
||||
let placeholder = match decision.action {
|
||||
InboxAction::NotAffected => vex_tx::IMPACT_STATEMENT,
|
||||
InboxAction::Affected => vex_tx::ACTION_STATEMENT,
|
||||
InboxAction::AcceptedRisk | InboxAction::FalsePositive | InboxAction::Confirm => tx::REASON,
|
||||
};
|
||||
let ready = decision.ready();
|
||||
let typed = decision.clone();
|
||||
let chosen = decision.clone();
|
||||
let submitted = decision.clone();
|
||||
let on_key = decision.clone();
|
||||
let justification = decision
|
||||
.justification
|
||||
.map(VexJustification::as_str)
|
||||
.unwrap_or_default();
|
||||
rsx! {
|
||||
div {
|
||||
class: "inbox-input",
|
||||
onclick: move |e| e.stop_propagation(),
|
||||
if decision.action == InboxAction::NotAffected {
|
||||
select {
|
||||
class: "inbox-input-select",
|
||||
value: "{justification}",
|
||||
"aria-label": vex_tx::JUSTIFICATION.get(lang),
|
||||
onkeydown: move |e| e.stop_propagation(),
|
||||
onchange: move |e| {
|
||||
let mut next = chosen.clone();
|
||||
next.justification = JUSTIFICATIONS
|
||||
.iter()
|
||||
.map(|(j, _)| *j)
|
||||
.find(|j| j.as_str() == e.value());
|
||||
on_edit.call(next);
|
||||
},
|
||||
option { value: "", {vex_tx::NO_JUSTIFICATION.get(lang)} }
|
||||
for (j, label) in JUSTIFICATIONS {
|
||||
option { key: "{j.as_str()}", value: j.as_str(), {label.get(lang)} }
|
||||
}
|
||||
}
|
||||
}
|
||||
input {
|
||||
class: "inbox-input-text",
|
||||
r#type: "text",
|
||||
value: "{decision.text}",
|
||||
placeholder: placeholder.get(lang),
|
||||
"aria-label": placeholder.get(lang),
|
||||
onmounted: move |e| async move {
|
||||
// Focusing can only fail when the input has gone.
|
||||
let _focused = e.data().set_focus(true).await;
|
||||
},
|
||||
oninput: move |e| {
|
||||
let mut next = typed.clone();
|
||||
next.text = e.value();
|
||||
on_edit.call(next);
|
||||
},
|
||||
onkeydown: move |e| {
|
||||
e.stop_propagation();
|
||||
match e.key() {
|
||||
Key::Enter if on_key.ready() => on_submit.call(on_key.clone()),
|
||||
Key::Escape => on_cancel.call(()),
|
||||
_ => {}
|
||||
}
|
||||
},
|
||||
}
|
||||
button {
|
||||
class: "btn btn-primary btn-sm",
|
||||
disabled: !ready,
|
||||
onclick: move |_| on_submit.call(submitted.clone()),
|
||||
{tx::DECIDE.get(lang)}
|
||||
}
|
||||
button {
|
||||
class: "btn btn-ghost btn-sm",
|
||||
onclick: move |_| on_cancel.call(()),
|
||||
{tx::CANCEL.get(lang)}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use compliance_core::models::Severity;
|
||||
|
||||
fn card(kind: CardKind, actions: Vec<InboxAction>) -> InboxCard {
|
||||
InboxCard {
|
||||
key: "f-1".into(),
|
||||
kind,
|
||||
bucket: Bucket::Today,
|
||||
target_id: "t1".into(),
|
||||
title: "t".into(),
|
||||
subtitle: String::new(),
|
||||
severity: Severity::High,
|
||||
count: 1,
|
||||
reasons: Vec::new(),
|
||||
item_ids: vec!["1".into()],
|
||||
actions,
|
||||
fix_version: None,
|
||||
note: None,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shortcuts_pick_the_card_s_matching_action() {
|
||||
use InboxAction::*;
|
||||
let finding = card(CardKind::Finding, vec![FalsePositive, AcceptedRisk]);
|
||||
assert_eq!(shortcut_action("f", &finding), Some(FalsePositive));
|
||||
assert_eq!(shortcut_action("a", &finding), Some(AcceptedRisk));
|
||||
assert_eq!(shortcut_action("x", &finding), None);
|
||||
let ai = card(CardKind::Finding, vec![FalsePositive, Confirm]);
|
||||
assert_eq!(shortcut_action("a", &ai), None, "not offered");
|
||||
let cve = card(CardKind::CvePackage, vec![Affected, NotAffected]);
|
||||
assert_eq!(shortcut_action("f", &cve), Some(NotAffected));
|
||||
assert_eq!(shortcut_action("a", &cve), Some(Affected));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_decision_needs_its_input_and_sends_it_in_the_right_field() {
|
||||
let mut risk = Pending {
|
||||
key: "f-1".into(),
|
||||
action: InboxAction::AcceptedRisk,
|
||||
text: " ".into(),
|
||||
justification: None,
|
||||
};
|
||||
assert!(!risk.ready());
|
||||
risk.text = " isolated ".into();
|
||||
assert!(risk.ready());
|
||||
assert_eq!(risk.request().reason.as_deref(), Some("isolated"));
|
||||
assert_eq!(risk.request().statement, None);
|
||||
let mut not_affected = Pending {
|
||||
key: "c-1-2".into(),
|
||||
action: InboxAction::NotAffected,
|
||||
text: String::new(),
|
||||
justification: None,
|
||||
};
|
||||
assert!(!not_affected.ready());
|
||||
not_affected.justification = Some(VexJustification::VulnerableCodeNotPresent);
|
||||
assert!(not_affected.ready());
|
||||
assert_eq!(
|
||||
not_affected.request().justification,
|
||||
Some(VexJustification::VulnerableCodeNotPresent)
|
||||
);
|
||||
let affected = Pending {
|
||||
key: "c-1-2".into(),
|
||||
action: InboxAction::Affected,
|
||||
text: "Update to version 2.17.1.".into(),
|
||||
justification: Some(VexJustification::ComponentNotPresent),
|
||||
};
|
||||
assert_eq!(
|
||||
affected.request().statement.as_deref(),
|
||||
Some("Update to version 2.17.1.")
|
||||
);
|
||||
assert_eq!(affected.request().justification, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn chips_name_their_reason() {
|
||||
let (label, tone) = chip(&Reason::Kev, Lang::De);
|
||||
assert_eq!(label, "Aktiv ausgenutzt (CISA KEV)");
|
||||
assert_eq!(tone, "tone-danger");
|
||||
let (label, _) = chip(
|
||||
&Reason::FixAvailable {
|
||||
version: "2.17.1".into(),
|
||||
},
|
||||
Lang::En,
|
||||
);
|
||||
assert_eq!(label, "Fix: 2.17.1");
|
||||
assert_eq!(
|
||||
action_label(InboxAction::FalsePositive, Bucket::LikelyFalsePositive),
|
||||
tx::CONFIRM_FALSE_POSITIVE
|
||||
);
|
||||
assert_eq!(
|
||||
action_label(InboxAction::FalsePositive, Bucket::Today),
|
||||
tx::FALSE_POSITIVE
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,64 +1,126 @@
|
||||
use dioxus::prelude::*;
|
||||
|
||||
use compliance_core::models::{IssueStatus, IssueSubject, TrackerIssue, TrackerType};
|
||||
|
||||
use crate::app::Route;
|
||||
use crate::components::page_header::PageHeader;
|
||||
use crate::components::pagination::Pagination;
|
||||
use crate::i18n::texts::{common, findings as ftx, issues as tx};
|
||||
use crate::i18n::{use_lang, Text};
|
||||
use crate::infrastructure::issues::{fetch_issues, IssuesQuery, PAGE_SIZE};
|
||||
|
||||
#[component]
|
||||
pub fn IssuesPage() -> Element {
|
||||
let lang = use_lang()();
|
||||
let mut page = use_signal(|| 1u64);
|
||||
let mut search_query = use_signal(String::new);
|
||||
let mut status_filter = use_signal(String::new);
|
||||
let mut repo_filter = use_signal(String::new);
|
||||
|
||||
let repos = use_resource(|| async {
|
||||
crate::infrastructure::onboarding::fetch_targets()
|
||||
.await
|
||||
.ok()
|
||||
});
|
||||
|
||||
let issues = use_resource(move || {
|
||||
let p = page();
|
||||
async move { crate::infrastructure::issues::fetch_issues(p).await.ok() }
|
||||
let query = IssuesQuery {
|
||||
page: page(),
|
||||
q: search_query(),
|
||||
status: status_filter(),
|
||||
repo_id: repo_filter(),
|
||||
};
|
||||
async move { fetch_issues(query).await.ok() }
|
||||
});
|
||||
|
||||
rsx! {
|
||||
PageHeader {
|
||||
title: "Issues",
|
||||
description: "Cross-tracker issue view - GitHub, GitLab, and Jira",
|
||||
title: tx::TITLE.get(lang),
|
||||
description: tx::SUBTITLE.get(lang),
|
||||
}
|
||||
|
||||
div { class: "filter-bar",
|
||||
input {
|
||||
r#type: "text",
|
||||
placeholder: tx::SEARCH.get(lang),
|
||||
style: "min-width: 240px;",
|
||||
oninput: move |e| { search_query.set(e.value()); page.set(1); },
|
||||
}
|
||||
select {
|
||||
onchange: move |e| { repo_filter.set(e.value()); page.set(1); },
|
||||
option { value: "", {ftx::ALL_TARGETS.get(lang)} }
|
||||
if let Some(Some(resp)) = &*repos.read() {
|
||||
for t in &resp.data {
|
||||
{
|
||||
let id = t.get("_id").and_then(|o| o.get("$oid")).and_then(|s| s.as_str()).unwrap_or_default().to_string();
|
||||
let name = t.get("name").and_then(|n| n.as_str()).unwrap_or_default().to_string();
|
||||
rsx! {
|
||||
option { value: "{id}", selected: repo_filter() == id, "{name}" }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
select {
|
||||
onchange: move |e| { status_filter.set(e.value()); page.set(1); },
|
||||
option { value: "", {ftx::ALL_STATUSES.get(lang)} }
|
||||
// Open takes in-progress tickets too, closed the resolved ones.
|
||||
option { value: "open", {tx::status(&IssueStatus::Open).get(lang)} }
|
||||
option { value: "closed", {tx::status(&IssueStatus::Closed).get(lang)} }
|
||||
}
|
||||
}
|
||||
|
||||
match &*issues.read() {
|
||||
Some(Some(resp)) => {
|
||||
let total_pages = resp.total.unwrap_or(0).div_ceil(20).max(1);
|
||||
let total_pages = resp.total.unwrap_or(0).div_ceil(PAGE_SIZE).max(1);
|
||||
rsx! {
|
||||
div { class: "card",
|
||||
div { class: "table-wrapper",
|
||||
table {
|
||||
thead {
|
||||
tr {
|
||||
th { "Tracker" }
|
||||
th { "ID" }
|
||||
th { "Title" }
|
||||
th { "Status" }
|
||||
th { "Created" }
|
||||
th { "Link" }
|
||||
th { {tx::COL_TRACKER.get(lang)} }
|
||||
th { {tx::COL_NUMBER.get(lang)} }
|
||||
th { {ftx::COL_TITLE.get(lang)} }
|
||||
th { {ftx::COL_STATUS.get(lang)} }
|
||||
th { {tx::COL_CREATED.get(lang)} }
|
||||
th { {tx::COL_LINKS.get(lang)} }
|
||||
}
|
||||
}
|
||||
tbody {
|
||||
if resp.data.is_empty() {
|
||||
tr {
|
||||
td { colspan: "6", style: "text-align: center; opacity: 0.6; padding: 24px;",
|
||||
{tx::NONE.get(lang)}
|
||||
}
|
||||
}
|
||||
}
|
||||
for issue in &resp.data {
|
||||
tr {
|
||||
td {
|
||||
span { class: "badge badge-info", "{issue.tracker_type}" }
|
||||
}
|
||||
td {
|
||||
style: "font-family: monospace;",
|
||||
"{issue.external_id}"
|
||||
}
|
||||
td { class: "ticket-tracker", {tracker_name(&issue.tracker_type)} }
|
||||
td { class: "ticket-number", {ticket_number(&issue.external_id)} }
|
||||
td { "{issue.title}" }
|
||||
td {
|
||||
span { class: "badge badge-info", "{issue.status}" }
|
||||
span { class: "badge {status_class(&issue.status)}",
|
||||
{tx::status(&issue.status).get(lang)}
|
||||
}
|
||||
}
|
||||
td {
|
||||
style: "font-size: 12px; color: var(--text-secondary);",
|
||||
td { class: "ticket-created",
|
||||
{issue.created_at.format("%Y-%m-%d %H:%M").to_string()}
|
||||
}
|
||||
td {
|
||||
a {
|
||||
href: "{issue.external_url}",
|
||||
target: "_blank",
|
||||
style: "color: var(--accent); text-decoration: none;",
|
||||
"Open"
|
||||
div { class: "ticket-links",
|
||||
if let Some((to, label)) = ticket_link(issue) {
|
||||
Link { to, {label.get(lang)} }
|
||||
}
|
||||
if !issue.external_url.is_empty() {
|
||||
a {
|
||||
href: "{issue.external_url}",
|
||||
target: "_blank",
|
||||
rel: "noopener noreferrer",
|
||||
{tx::OPEN_TRACKER.get(lang)}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -75,11 +137,113 @@ pub fn IssuesPage() -> Element {
|
||||
}
|
||||
},
|
||||
Some(None) => rsx! {
|
||||
div { class: "card", p { "Failed to load issues." } }
|
||||
div { class: "card", p { {tx::LOAD_FAILED.get(lang)} } }
|
||||
},
|
||||
None => rsx! {
|
||||
div { class: "loading", "Loading issues..." }
|
||||
div { class: "loading", {common::LOADING.get(lang)} }
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Where a ticket leads in Prüfwerk, and the link's text: its finding, or for
|
||||
/// a CVE ticket the target's components and their CVEs. `None` for a ticket
|
||||
/// whose finding is unknown.
|
||||
fn ticket_link(issue: &TrackerIssue) -> Option<(Route, Text)> {
|
||||
Some(match issue.subject()? {
|
||||
IssueSubject::Finding(id) => (
|
||||
Route::FindingDetailPage { id: id.to_string() },
|
||||
tx::OPEN_FINDING,
|
||||
),
|
||||
IssueSubject::Cve { target_id } => (
|
||||
Route::SbomPage {
|
||||
target: target_id.to_string(),
|
||||
},
|
||||
tx::OPEN_CVES,
|
||||
),
|
||||
})
|
||||
}
|
||||
|
||||
/// A ticket's number as its tracker shows it: `#913`, or a Jira key as is.
|
||||
fn ticket_number(external_id: &str) -> String {
|
||||
if !external_id.is_empty() && external_id.bytes().all(|b| b.is_ascii_digit()) {
|
||||
format!("#{external_id}")
|
||||
} else {
|
||||
external_id.to_string()
|
||||
}
|
||||
}
|
||||
|
||||
/// A tracker by its product name.
|
||||
fn tracker_name(tracker: &TrackerType) -> &'static str {
|
||||
match tracker {
|
||||
TrackerType::GitHub => "GitHub",
|
||||
TrackerType::GitLab => "GitLab",
|
||||
TrackerType::Gitea => "Gitea",
|
||||
TrackerType::Jira => "Jira",
|
||||
}
|
||||
}
|
||||
|
||||
/// The badge colour of a ticket status: open blue, in progress amber, done
|
||||
/// green.
|
||||
fn status_class(status: &IssueStatus) -> &'static str {
|
||||
match status {
|
||||
IssueStatus::Open => "badge-info",
|
||||
IssueStatus::InProgress => "badge-medium",
|
||||
IssueStatus::Closed | IssueStatus::Resolved => "badge-success",
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn issue(finding_id: &str) -> TrackerIssue {
|
||||
TrackerIssue::new(
|
||||
finding_id.to_string(),
|
||||
TrackerType::Gitea,
|
||||
"913".into(),
|
||||
"https://gitea.invalid/o/r/issues/913".into(),
|
||||
"[high] semgrep: hardcoded key".into(),
|
||||
)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_finding_ticket_links_to_its_finding() {
|
||||
let id = "65a1b2c3d4e5f60718293a4b";
|
||||
let (to, label) = ticket_link(&issue(id)).expect("a link");
|
||||
assert_eq!(to, Route::FindingDetailPage { id: id.into() });
|
||||
assert_eq!(label, tx::OPEN_FINDING);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_cve_ticket_links_to_its_targets_cves() {
|
||||
let (to, label) = ticket_link(&issue("cve:t1:openssl:CVE-2024-0001")).expect("a link");
|
||||
assert_eq!(
|
||||
to,
|
||||
Route::SbomPage {
|
||||
target: "t1".into()
|
||||
}
|
||||
);
|
||||
assert_eq!(label, tx::OPEN_CVES);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_ticket_without_a_finding_has_no_link() {
|
||||
assert!(ticket_link(&issue("")).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn numbers_read_like_the_tracker() {
|
||||
assert_eq!(ticket_number("913"), "#913");
|
||||
assert_eq!(ticket_number("PROJ-913"), "PROJ-913");
|
||||
assert_eq!(ticket_number(""), "");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn done_tickets_are_green() {
|
||||
for status in IssueStatus::ALL {
|
||||
let green = status_class(&status) == "badge-success";
|
||||
assert_eq!(green, status.is_closed(), "{status}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -10,6 +10,7 @@ pub mod findings;
|
||||
pub mod graph_explorer;
|
||||
pub(crate) mod graph_view;
|
||||
pub mod impact_analysis;
|
||||
pub mod inbox;
|
||||
pub mod issues;
|
||||
pub mod mcp_servers;
|
||||
pub mod mcp_tokens;
|
||||
@@ -19,6 +20,7 @@ pub mod pentest_dashboard;
|
||||
pub mod pentest_session;
|
||||
pub mod sbom;
|
||||
pub mod target;
|
||||
pub mod target_views;
|
||||
pub mod targets;
|
||||
|
||||
pub use chat::ChatPage;
|
||||
@@ -32,6 +34,7 @@ pub use finding_detail::FindingDetailPage;
|
||||
pub use findings::FindingsPage;
|
||||
pub use graph_explorer::GraphExplorerPage;
|
||||
pub use impact_analysis::ImpactAnalysisPage;
|
||||
pub use inbox::HeutePage;
|
||||
pub use issues::IssuesPage;
|
||||
pub use mcp_servers::McpServersPage;
|
||||
pub use mcp_tokens::McpTokensPage;
|
||||
@@ -41,4 +44,5 @@ pub use pentest_dashboard::PentestDashboardPage;
|
||||
pub use pentest_session::PentestSessionPage;
|
||||
pub use sbom::SbomPage;
|
||||
pub use target::TargetPage;
|
||||
pub use target_views::TargetViewsPage;
|
||||
pub use targets::TargetsPage;
|
||||
@@ -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)}
|
||||
}
|
||||
|
||||
@@ -4,46 +4,85 @@ use dioxus_free_icons::Icon;
|
||||
|
||||
use crate::app::Route;
|
||||
use crate::components::cra_bar::CraBar;
|
||||
use crate::components::cve_trend::{CveDashboard, Sparkline};
|
||||
use crate::components::page_header::PageHeader;
|
||||
use crate::components::severity_badge::SeverityBadge;
|
||||
use crate::i18n::texts::{common, overview, scans as scan_texts};
|
||||
use crate::i18n::texts::{common, cve_trend, nav, overview, scans as scan_texts};
|
||||
use crate::i18n::{format_ago, use_lang, Lang};
|
||||
use crate::infrastructure::evidence::{fetch_compliance_summary, ComplianceSummaryRow};
|
||||
use crate::infrastructure::cve_history::fetch_cve_history;
|
||||
use crate::infrastructure::evidence::{fetch_compliance_summary, ComplianceSummaryRow, CraCounts};
|
||||
use crate::infrastructure::findings::{fetch_findings, location, FindingsQuery};
|
||||
use crate::infrastructure::inbox::fetch_inbox;
|
||||
use crate::infrastructure::mcp::fetch_mcp_servers;
|
||||
use crate::infrastructure::onboarding::fetch_targets;
|
||||
use crate::infrastructure::platform::use_source_only;
|
||||
use crate::infrastructure::projects::{fetch_projects, project_ids_of};
|
||||
use crate::infrastructure::stats::fetch_overview_stats;
|
||||
use compliance_core::models::{ScanRun, ScanRunStatus};
|
||||
use crate::pages::inbox::{bucket_texts, bucket_tone};
|
||||
use crate::pages::target_views::RepoView;
|
||||
use compliance_core::cve_history::{CveDay, CveHistory};
|
||||
use compliance_core::models::inbox::{Bucket, InboxCounts, InboxTarget};
|
||||
use compliance_core::models::{Project, ScanRun, ScanRunStatus};
|
||||
|
||||
/// Open findings the "Next up" list shows.
|
||||
const NEXT_UP: usize = 6;
|
||||
/// Targets "CRA status by target" lists; the rest are on the targets page.
|
||||
const TARGETS_SHOWN: usize = 8;
|
||||
/// Target cards a project shows; the rest are on the targets page.
|
||||
const CARDS_PER_PROJECT: usize = 6;
|
||||
|
||||
/// One target's line in "CRA status by target".
|
||||
/// One target's card under its projects.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
struct TargetLine {
|
||||
id: String,
|
||||
name: String,
|
||||
target_type: String,
|
||||
summary: Option<ComplianceSummaryRow>,
|
||||
/// Its CRA Annex I counts, `None` when the agent could not evaluate it.
|
||||
counts: Option<CraCounts>,
|
||||
/// The last scan's status, and when it finished (or started, if running).
|
||||
last_scan: Option<(ScanRunStatus, chrono::DateTime<chrono::Utc>)>,
|
||||
project_ids: Vec<String>,
|
||||
/// Today's open critical and high CVEs with a fix.
|
||||
critical: u32,
|
||||
high: u32,
|
||||
/// Critical plus high per day, oldest first; empty without a history.
|
||||
trend: Vec<u32>,
|
||||
/// Its open decisions per Heute bucket.
|
||||
buckets: InboxCounts,
|
||||
}
|
||||
|
||||
/// The targets joined with their CRA counts, those with the most violated
|
||||
/// requirements first, then by name.
|
||||
impl TargetLine {
|
||||
/// Today's open critical and high CVEs with a fix together.
|
||||
fn urgent(&self) -> u32 {
|
||||
self.critical + self.high
|
||||
}
|
||||
}
|
||||
|
||||
/// The targets joined with their CRA counts, CVE trend and Heute buckets
|
||||
/// (`inbox`, the targets with open decisions): the most open critical and
|
||||
/// high CVEs with a fix first, then the most violated requirements, then by
|
||||
/// name.
|
||||
fn target_lines(
|
||||
targets: &[serde_json::Value],
|
||||
summary: &[ComplianceSummaryRow],
|
||||
history: Option<&CveHistory>,
|
||||
inbox: &[InboxTarget],
|
||||
) -> Vec<TargetLine> {
|
||||
let mut lines: Vec<TargetLine> = targets
|
||||
.iter()
|
||||
.filter_map(|t| {
|
||||
let id = t.get("_id")?.get("$oid")?.as_str()?.to_string();
|
||||
let own = history.and_then(|h| h.targets.get(&id));
|
||||
let today = own.and_then(|s| s.last()).copied().unwrap_or_default();
|
||||
// A target without alerts in the window is flat at zero.
|
||||
let trend = match (own, history) {
|
||||
(Some(series), _) => series.iter().map(CveDay::urgent).collect(),
|
||||
(None, Some(h)) => vec![0; h.days.len()],
|
||||
(None, None) => Vec::new(),
|
||||
};
|
||||
Some(TargetLine {
|
||||
summary: summary.iter().find(|s| s.target_id == id).cloned(),
|
||||
counts: summary
|
||||
.iter()
|
||||
.find(|s| s.target_id == id)
|
||||
.and_then(|s| s.counts),
|
||||
name: t.get("name")?.as_str()?.to_string(),
|
||||
target_type: t
|
||||
.get("target_type")
|
||||
@@ -55,24 +94,87 @@ fn target_lines(
|
||||
.filter(|r| !r.is_null())
|
||||
.and_then(|r| serde_json::from_value::<ScanRun>(r.clone()).ok())
|
||||
.map(|run| (run.status, run.completed_at.unwrap_or(run.started_at))),
|
||||
project_ids: project_ids_of(t),
|
||||
critical: today.critical,
|
||||
high: today.high,
|
||||
trend,
|
||||
buckets: inbox
|
||||
.iter()
|
||||
.find(|i| i.id == id)
|
||||
.map(|i| i.counts)
|
||||
.unwrap_or_default(),
|
||||
id,
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
let violated = |l: &TargetLine| {
|
||||
l.summary
|
||||
.as_ref()
|
||||
.and_then(|s| s.counts)
|
||||
.map_or(0, |c| c.not_satisfied)
|
||||
};
|
||||
let violated = |l: &TargetLine| l.counts.map_or(0, |c| c.not_satisfied);
|
||||
lines.sort_by(|a, b| {
|
||||
violated(b)
|
||||
.cmp(&violated(a))
|
||||
b.urgent()
|
||||
.cmp(&a.urgent())
|
||||
.then_with(|| violated(b).cmp(&violated(a)))
|
||||
.then_with(|| a.name.cmp(&b.name))
|
||||
});
|
||||
lines
|
||||
}
|
||||
|
||||
/// The targets of one project, or (`project` `None`) those in none.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
struct ProjectGroup {
|
||||
project: Option<Project>,
|
||||
lines: Vec<TargetLine>,
|
||||
}
|
||||
|
||||
impl ProjectGroup {
|
||||
/// The project's critical plus high CVEs with a fix per day: the sum of
|
||||
/// its targets' trends.
|
||||
fn trend(&self) -> Vec<u32> {
|
||||
let len = self.lines.iter().map(|l| l.trend.len()).max().unwrap_or(0);
|
||||
let mut sum = vec![0; len];
|
||||
for line in &self.lines {
|
||||
for (total, n) in sum.iter_mut().zip(&line.trend) {
|
||||
*total += n;
|
||||
}
|
||||
}
|
||||
sum
|
||||
}
|
||||
|
||||
/// Today's open critical and high CVEs with a fix of its targets.
|
||||
fn urgent(&self) -> u32 {
|
||||
self.lines.iter().map(TargetLine::urgent).sum()
|
||||
}
|
||||
}
|
||||
|
||||
/// `lines` by project, in the registry's order, each in the order of
|
||||
/// `lines`: a target in several projects under each, those in none (or
|
||||
/// only in deleted ones) last. Projects without targets are left out.
|
||||
fn group_by_project(lines: &[TargetLine], projects: &[Project]) -> Vec<ProjectGroup> {
|
||||
let in_project = |line: &TargetLine, id: &str| line.project_ids.iter().any(|p| p == id);
|
||||
let mut groups: Vec<ProjectGroup> = projects
|
||||
.iter()
|
||||
.map(|p| ProjectGroup {
|
||||
project: Some(p.clone()),
|
||||
lines: lines
|
||||
.iter()
|
||||
.filter(|l| in_project(l, &p.id))
|
||||
.cloned()
|
||||
.collect(),
|
||||
})
|
||||
.filter(|g| !g.lines.is_empty())
|
||||
.collect();
|
||||
let rest: Vec<TargetLine> = lines
|
||||
.iter()
|
||||
.filter(|l| !projects.iter().any(|p| in_project(l, &p.id)))
|
||||
.cloned()
|
||||
.collect();
|
||||
if !rest.is_empty() {
|
||||
groups.push(ProjectGroup {
|
||||
project: None,
|
||||
lines: rest,
|
||||
});
|
||||
}
|
||||
groups
|
||||
}
|
||||
|
||||
#[component]
|
||||
pub fn OverviewPage() -> Element {
|
||||
let lang = use_lang()();
|
||||
@@ -83,6 +185,15 @@ pub fn OverviewPage() -> Element {
|
||||
let stats = use_resource(|| async { fetch_overview_stats().await.ok() });
|
||||
let targets = use_resource(|| async { fetch_targets().await.ok() });
|
||||
let summary = use_resource(|| async { fetch_compliance_summary().await.ok() });
|
||||
let projects = use_resource(|| async { fetch_projects().await.ok() });
|
||||
let history = use_resource(|| async { fetch_cve_history(String::new(), true).await.ok() });
|
||||
// The bucket counts of every target; no cards.
|
||||
let inbox = use_resource(|| async {
|
||||
fetch_inbox(String::new(), Bucket::Today, Some(0))
|
||||
.await
|
||||
.ok()
|
||||
.map(|v| v.targets)
|
||||
});
|
||||
let next_up = use_resource(|| async {
|
||||
fetch_findings(FindingsQuery {
|
||||
page: 1,
|
||||
@@ -113,59 +224,36 @@ pub fn OverviewPage() -> Element {
|
||||
}
|
||||
}
|
||||
},
|
||||
Some(Some(s)) => rsx! {
|
||||
div { class: "ov-figures",
|
||||
Link { to: Route::TargetsPage {}, class: "ov-figure",
|
||||
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",
|
||||
span { class: "ov-figure-label", {overview::OPEN_FINDINGS.get(lang)} }
|
||||
span { class: "ov-figure-value", "{s.total_findings}" }
|
||||
span { class: "ov-figure-sub",
|
||||
span { class: "sev-critical-text", "{s.critical_findings} {overview::CRITICAL_LC.get(lang)}" }
|
||||
" · "
|
||||
span { class: "sev-high-text", "{s.high_findings} {overview::HIGH_LC.get(lang)}" }
|
||||
}
|
||||
}
|
||||
Link { to: Route::SbomPage { target: String::new() }, class: "ov-figure",
|
||||
span { class: "ov-figure-label", {overview::COMPONENTS.get(lang)} }
|
||||
span { class: "ov-figure-value", "{s.total_sbom_entries}" }
|
||||
span { class: "ov-figure-sub", {overview::IN_SBOM.get(lang)} }
|
||||
}
|
||||
Link { to: Route::SbomPage { target: String::new() }, class: "ov-figure",
|
||||
span { class: "ov-figure-label", {overview::KNOWN_VULNS.get(lang)} }
|
||||
span { class: "ov-figure-value", "{s.total_cve_alerts}" }
|
||||
span { class: "ov-figure-sub", {overview::IN_COMPONENTS.get(lang)} }
|
||||
}
|
||||
Some(Some(_)) => rsx! {
|
||||
match history.read().clone() {
|
||||
Some(Some(history)) => rsx! { CveDashboard { history, target: String::new() } },
|
||||
Some(None) => rsx! { div { class: "card", p { class: "ov-muted", {cve_trend::LOAD_FAILED.get(lang)} } } },
|
||||
None => rsx! { div { class: "loading", {common::LOADING.get(lang)} } },
|
||||
}
|
||||
|
||||
div { class: "ov-grid",
|
||||
section { class: "card ov-cra",
|
||||
section { class: "card ov-projects",
|
||||
div { class: "ov-section-head",
|
||||
h3 { {overview::CRA_BY_TARGET.get(lang)} }
|
||||
p { {overview::CRA_BY_TARGET_HINT.get(lang)} }
|
||||
h3 { {cve_trend::BY_PROJECT.get(lang)} }
|
||||
p { {cve_trend::BY_PROJECT_HINT.get(lang)} }
|
||||
}
|
||||
match (&*targets.read(), &*summary.read()) {
|
||||
(Some(Some(t)), Some(rows)) => {
|
||||
let lines = target_lines(&t.data, rows.as_deref().unwrap_or_default());
|
||||
let more = lines.len() > TARGETS_SHOWN;
|
||||
match &*targets.read() {
|
||||
Some(Some(t)) => {
|
||||
let summary = summary.read().clone().flatten().unwrap_or_default();
|
||||
let projects = projects.read().clone().flatten().unwrap_or_default();
|
||||
let inbox = inbox.read().clone().flatten().unwrap_or_default();
|
||||
let lines = target_lines(&t.data, &summary, history.read().as_ref().and_then(|h| h.as_ref()), &inbox);
|
||||
let groups = group_by_project(&lines, &projects);
|
||||
// Without any project, the one group is every target.
|
||||
let only = groups.len() == 1;
|
||||
rsx! {
|
||||
ul { class: "ov-targets",
|
||||
for line in lines.into_iter().take(TARGETS_SHOWN) {
|
||||
TargetRow { line, lang }
|
||||
}
|
||||
}
|
||||
if more {
|
||||
Link { to: Route::TargetsPage {}, class: "ov-more",
|
||||
{overview::ALL_TARGETS.get(lang)}
|
||||
Icon { icon: BsArrowRight, width: 14, height: 14 }
|
||||
}
|
||||
for group in groups {
|
||||
ProjectSection { key: "{group.project.as_ref().map(|p| p.id.as_str()).unwrap_or_default()}", group, only, lang }
|
||||
}
|
||||
}
|
||||
}
|
||||
(Some(None), _) => rsx! { p { class: "ov-muted", {overview::LIST_LOAD_FAILED.get(lang)} } },
|
||||
_ => rsx! { div { class: "loading", {common::LOADING.get(lang)} } },
|
||||
Some(None) => rsx! { p { class: "ov-muted", {overview::LIST_LOAD_FAILED.get(lang)} } },
|
||||
None => rsx! { div { class: "loading", {common::LOADING.get(lang)} } },
|
||||
}
|
||||
}
|
||||
|
||||
@@ -220,7 +308,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 }
|
||||
}
|
||||
@@ -250,10 +338,49 @@ pub fn OverviewPage() -> Element {
|
||||
}
|
||||
}
|
||||
|
||||
/// One target in "CRA status by target": its name, its CRA bar and its last
|
||||
/// scan; the name opens its CRA status.
|
||||
/// One project's head (its name, how many targets and open CVEs with a fix,
|
||||
/// its trend) and its first target cards; `only` when it is the one group,
|
||||
/// then named after the targets rather than "Ohne Projekt".
|
||||
#[component]
|
||||
fn TargetRow(line: TargetLine, lang: Lang) -> Element {
|
||||
fn ProjectSection(group: ProjectGroup, only: bool, lang: Lang) -> Element {
|
||||
let name = match (&group.project, only) {
|
||||
(Some(project), _) => project.name.clone(),
|
||||
(None, true) => overview::TARGETS.get(lang).to_string(),
|
||||
(None, false) => cve_trend::NO_PROJECT.get(lang).to_string(),
|
||||
};
|
||||
let summary = cve_trend::project_summary(group.lines.len(), group.urgent(), lang);
|
||||
let trend = group.trend();
|
||||
let more = group.lines.len().saturating_sub(CARDS_PER_PROJECT);
|
||||
rsx! {
|
||||
div { class: "ov-project",
|
||||
div { class: "ov-project-head",
|
||||
div { class: "ov-project-title",
|
||||
h4 { "{name}" }
|
||||
span { "{summary}" }
|
||||
}
|
||||
if !trend.is_empty() {
|
||||
Sparkline { values: trend, label: "{cve_trend::CHART_TITLE.get(lang)}: {name}" }
|
||||
}
|
||||
}
|
||||
div { class: "repo-cards",
|
||||
for line in group.lines.into_iter().take(CARDS_PER_PROJECT) {
|
||||
RepoCard { key: "{line.id}", line, lang }
|
||||
}
|
||||
}
|
||||
if more > 0 {
|
||||
Link { to: Route::TargetsPage {}, class: "ov-more",
|
||||
{cve_trend::more_targets(more, lang)}
|
||||
Icon { icon: BsArrowRight, width: 14, height: 14 }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One target's card: its open critical and high CVEs with a fix and their
|
||||
/// trend, its CRA bar, its last scan, and the lists behind them.
|
||||
#[component]
|
||||
fn RepoCard(line: TargetLine, lang: Lang) -> Element {
|
||||
let now = chrono::Utc::now();
|
||||
let scanned = line.last_scan.as_ref().map(|(status, when)| {
|
||||
let (badge, label) = crate::components::scan_runs::status_badge(status);
|
||||
@@ -264,26 +391,54 @@ fn TargetRow(line: TargetLine, lang: Lang) -> Element {
|
||||
*status == ScanRunStatus::Completed,
|
||||
)
|
||||
});
|
||||
let split = cve_trend::split(line.critical, line.high, lang);
|
||||
rsx! {
|
||||
li { class: "ov-target",
|
||||
div { class: "ov-target-name",
|
||||
Link { to: Route::CompliancePage { id: line.id.clone() }, "{line.name}" }
|
||||
article { class: "repo-card",
|
||||
div { class: "repo-card-name",
|
||||
Link { to: Route::target(line.id.clone()), "{line.name}" }
|
||||
span { class: "ov-target-type", {crate::i18n::texts::kinds::target_type(&line.target_type, lang)} }
|
||||
}
|
||||
div { class: "ov-target-bar",
|
||||
match line.summary.as_ref().and_then(|s| s.counts) {
|
||||
Some(counts) => rsx! { CraBar { counts, compact: true } },
|
||||
None => rsx! { span { class: "ov-muted", {overview::CRA_UNAVAILABLE.get(lang)} } },
|
||||
Link { to: Route::target_view(line.id.clone(), RepoView::Cves), class: "repo-card-cves", title: "{split}",
|
||||
span { class: "repo-card-n", "{line.urgent()}" }
|
||||
span { class: "repo-card-label",
|
||||
{cve_trend::WITH_FIX.get(lang)}
|
||||
span { class: "repo-card-split", "{split}" }
|
||||
}
|
||||
if !line.trend.is_empty() {
|
||||
Sparkline { values: line.trend.clone(), label: "{cve_trend::CHART_TITLE.get(lang)}: {line.name}" }
|
||||
}
|
||||
}
|
||||
div { class: "ov-target-scan",
|
||||
match scanned {
|
||||
Some((_, _, ago, true)) => rsx! { span { "{ago}" } },
|
||||
Some((badge, status, ago, false)) => rsx! {
|
||||
span { class: "{badge}", "{status}" }
|
||||
span { " {ago}" }
|
||||
},
|
||||
None => rsx! { span { class: "ov-muted", {scan_texts::NEVER_SCANNED.get(lang)} } },
|
||||
Link { to: Route::CompliancePage { id: line.id.clone() }, class: "repo-card-cra",
|
||||
match line.counts {
|
||||
Some(counts) => rsx! { CraBar { counts, compact: true } },
|
||||
None => rsx! { span { class: "ov-target-type", {overview::CRA_UNAVAILABLE.get(lang)} } },
|
||||
}
|
||||
}
|
||||
div { class: "repo-card-buckets",
|
||||
for b in Bucket::ALL {
|
||||
Link {
|
||||
key: "{b.as_str()}",
|
||||
class: "repo-card-bucket {bucket_tone(b)}",
|
||||
to: Route::heute(line.id.clone(), Some(b)),
|
||||
span { class: "repo-card-bucket-n", "{line.buckets.get(b)}" }
|
||||
span { class: "repo-card-bucket-label", {bucket_texts(b).0.get(lang)} }
|
||||
}
|
||||
}
|
||||
}
|
||||
div { class: "repo-card-foot",
|
||||
span { class: "repo-card-scan",
|
||||
match scanned {
|
||||
Some((_, _, ago, true)) => rsx! { "{ago}" },
|
||||
Some((badge, status, ago, false)) => rsx! {
|
||||
span { class: "{badge}", "{status}" }
|
||||
" {ago}"
|
||||
},
|
||||
None => rsx! { {scan_texts::NEVER_SCANNED.get(lang)} },
|
||||
}
|
||||
}
|
||||
span { class: "repo-card-links",
|
||||
Link { to: Route::findings(line.id.clone()), {nav::FINDINGS.get(lang)} }
|
||||
Link { to: Route::SbomPage { target: line.id.clone() }, {nav::SBOM.get(lang)} }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -429,3 +584,124 @@ fn RuntimeSections() -> Element {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use compliance_core::models::ProjectKind;
|
||||
|
||||
fn project(id: &str, name: &str) -> Project {
|
||||
Project {
|
||||
id: id.to_string(),
|
||||
name: name.to_string(),
|
||||
kind: ProjectKind::Product,
|
||||
description: String::new(),
|
||||
}
|
||||
}
|
||||
|
||||
fn target(id: &str, name: &str, projects: &[&str]) -> serde_json::Value {
|
||||
serde_json::json!({ "_id": { "$oid": id }, "name": name, "project_ids": projects })
|
||||
}
|
||||
|
||||
fn day(date: &str, critical: u32, high: u32) -> CveDay {
|
||||
CveDay {
|
||||
date: date.parse().unwrap(),
|
||||
critical,
|
||||
high,
|
||||
..CveDay::default()
|
||||
}
|
||||
}
|
||||
|
||||
fn names(group: &ProjectGroup) -> Vec<&str> {
|
||||
group.lines.iter().map(|l| l.name.as_str()).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn targets_with_open_cves_come_first_with_their_trend() {
|
||||
let history = CveHistory {
|
||||
days: vec![day("2026-11-09", 1, 0), day("2026-11-10", 1, 2)],
|
||||
targets: [(
|
||||
"b".to_string(),
|
||||
vec![day("2026-11-09", 1, 0), day("2026-11-10", 1, 2)],
|
||||
)]
|
||||
.into(),
|
||||
..CveHistory::default()
|
||||
};
|
||||
let targets = [target("a", "alpha", &[]), target("b", "beta", &[])];
|
||||
let lines = target_lines(&targets, &[], Some(&history), &[]);
|
||||
assert_eq!(lines[0].name, "beta");
|
||||
assert_eq!((lines[0].critical, lines[0].high), (1, 2));
|
||||
assert_eq!(lines[0].trend, [1, 3]);
|
||||
// No alerts in the window: flat at zero over the same days.
|
||||
assert_eq!(lines[1].trend, [0, 0]);
|
||||
// Without a history: no trend at all.
|
||||
assert!(target_lines(&targets, &[], None, &[])[0].trend.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_target_carries_its_heute_buckets_and_one_without_decisions_none() {
|
||||
let inbox = [InboxTarget {
|
||||
id: "b".to_string(),
|
||||
name: "beta".to_string(),
|
||||
counts: InboxCounts {
|
||||
today: 3,
|
||||
this_week: 1,
|
||||
later: 0,
|
||||
likely_false_positive: 2,
|
||||
},
|
||||
}];
|
||||
let targets = [target("a", "alpha", &[]), target("b", "beta", &[])];
|
||||
let lines = target_lines(&targets, &[], None, &inbox);
|
||||
let of = |name: &str| lines.iter().find(|l| l.name == name).unwrap().buckets;
|
||||
assert_eq!(of("beta"), inbox[0].counts);
|
||||
assert_eq!(of("alpha"), InboxCounts::default());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn targets_are_grouped_by_project_with_those_in_none_last() {
|
||||
let targets = [
|
||||
target("a", "alpha", &["p1", "p2"]),
|
||||
target("b", "beta", &["p2"]),
|
||||
target("c", "gamma", &["deleted"]),
|
||||
target("d", "delta", &[]),
|
||||
];
|
||||
let lines = target_lines(&targets, &[], None, &[]);
|
||||
let projects = [
|
||||
project("p1", "Lok"),
|
||||
project("p2", "Steuerung"),
|
||||
project("p3", "Leer"),
|
||||
];
|
||||
let groups = group_by_project(&lines, &projects);
|
||||
let heads: Vec<Option<&str>> = groups
|
||||
.iter()
|
||||
.map(|g| g.project.as_ref().map(|p| p.name.as_str()))
|
||||
.collect();
|
||||
// The empty project is left out; a target in two projects is in both.
|
||||
assert_eq!(heads, [Some("Lok"), Some("Steuerung"), None]);
|
||||
assert_eq!(names(&groups[0]), ["alpha"]);
|
||||
assert_eq!(names(&groups[1]), ["alpha", "beta"]);
|
||||
assert_eq!(names(&groups[2]), ["delta", "gamma"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_projects_trend_and_count_are_its_targets_summed() {
|
||||
let line = |name: &str, critical, high, trend: Vec<u32>| TargetLine {
|
||||
id: name.to_string(),
|
||||
name: name.to_string(),
|
||||
target_type: String::new(),
|
||||
counts: None,
|
||||
last_scan: None,
|
||||
project_ids: Vec::new(),
|
||||
critical,
|
||||
high,
|
||||
trend,
|
||||
buckets: InboxCounts::default(),
|
||||
};
|
||||
let group = ProjectGroup {
|
||||
project: Some(project("p1", "Lok")),
|
||||
lines: vec![line("a", 1, 2, vec![1, 3]), line("b", 0, 4, vec![2, 4])],
|
||||
};
|
||||
assert_eq!(group.trend(), [3, 7]);
|
||||
assert_eq!(group.urgent(), 7);
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,8 @@
|
||||
use compliance_core::models::{LicenseConclusion, YOCTO_RECIPE_MANAGER};
|
||||
use dioxus::prelude::*;
|
||||
|
||||
use crate::app::Route;
|
||||
use crate::components::component_overview::ComponentOverview;
|
||||
use crate::components::license_editor::{category_class, confirmed_title, LicenseEditor};
|
||||
use crate::components::license_review::{
|
||||
action_class, reasons_text, review_title, LicenseCheckPanel,
|
||||
@@ -14,21 +16,45 @@ use crate::i18n::{use_lang, Lang};
|
||||
use crate::infrastructure::sbom::*;
|
||||
use compliance_core::models::ReviewDecision;
|
||||
|
||||
/// The SBOM page. `target` filters it to one target; `ecosystem` (from
|
||||
/// `/sbom/ecosystem/:ecosystem`, #957) to one package manager.
|
||||
#[component]
|
||||
pub fn SbomPage(target: String) -> Element {
|
||||
pub fn SbomPage(target: String, #[props(default)] ecosystem: String) -> Element {
|
||||
let lang = use_lang()();
|
||||
let mut toasts = use_context::<Toasts>();
|
||||
// ── Filter signals ──
|
||||
let mut page = use_signal(|| 1u64);
|
||||
// Opened from a target (`?target=<id>`): filtered to it.
|
||||
let mut repo_filter = use_signal(|| target.clone());
|
||||
let mut pm_filter = use_signal(String::new);
|
||||
let mut pm_filter = use_signal(|| ecosystem.clone());
|
||||
let mut search_q = use_signal(String::new);
|
||||
let mut vuln_toggle = use_signal(|| Option::<bool>::None);
|
||||
let mut license_filter = use_signal(String::new);
|
||||
// Only the components an image declares (`Some(true)`), or all.
|
||||
let mut in_image_filter = use_signal(|| Option::<bool>::None);
|
||||
|
||||
// Back and forward between two ecosystems keep this page mounted with
|
||||
// new props: the filter follows the URL.
|
||||
use_effect(use_reactive!(|ecosystem| {
|
||||
if *pm_filter.peek() != ecosystem {
|
||||
pm_filter.set(ecosystem);
|
||||
page.set(1);
|
||||
}
|
||||
}));
|
||||
// A bar of the components view (#957) filters the table to its
|
||||
// ecosystem, and puts it in the URL; an empty one clears the filter.
|
||||
let navigator = use_navigator();
|
||||
let on_ecosystem = move |ecosystem: String| {
|
||||
pm_filter.set(ecosystem.clone());
|
||||
page.set(1);
|
||||
let target = repo_filter();
|
||||
navigator.push(if ecosystem.is_empty() {
|
||||
Route::SbomPage { target }
|
||||
} else {
|
||||
Route::SbomEcosystemPage { ecosystem, target }
|
||||
});
|
||||
};
|
||||
|
||||
// ── Active tab: "packages" | "licenses" | "diff" ──
|
||||
let mut active_tab = use_signal(|| "packages".to_string());
|
||||
|
||||
@@ -94,6 +120,18 @@ pub fn SbomPage(target: String) -> Element {
|
||||
}
|
||||
});
|
||||
|
||||
// ── Licence group the licence table is narrowed to, from its chart (#957) ──
|
||||
let mut licence_group =
|
||||
use_signal(|| Option::<compliance_core::models::license::LicenseGroup>::None);
|
||||
// Another target starts at the chart again.
|
||||
use_effect(move || {
|
||||
repo_filter.read();
|
||||
// `peek` reads without subscribing: only the target re-runs this.
|
||||
if licence_group.peek().is_some() {
|
||||
licence_group.set(None);
|
||||
}
|
||||
});
|
||||
|
||||
// ── License summary ──
|
||||
let mut license_data = use_resource(move || {
|
||||
let repo = repo_filter();
|
||||
@@ -143,6 +181,10 @@ pub fn SbomPage(target: String) -> Element {
|
||||
|
||||
// ═══════════════ PACKAGES TAB ═══════════════
|
||||
if active_tab() == "packages" {
|
||||
// ── The components view of one target (#957) ──
|
||||
if !repo_filter().is_empty() {
|
||||
ComponentOverview { target_id: repo_filter(), ecosystem: pm_filter(), on_ecosystem }
|
||||
}
|
||||
// ── Filter bar ──
|
||||
div { class: "sbom-filter-bar",
|
||||
select {
|
||||
@@ -175,7 +217,7 @@ pub fn SbomPage(target: String) -> Element {
|
||||
{
|
||||
let val = pm.clone();
|
||||
let label = pm_display_name(&val);
|
||||
rsx! { option { value: "{val}", "{label}" } }
|
||||
rsx! { option { value: "{val}", selected: pm_filter() == val, "{label}" } }
|
||||
}
|
||||
}
|
||||
},
|
||||
@@ -581,30 +623,50 @@ pub fn SbomPage(target: String) -> Element {
|
||||
|
||||
// ═══════════════ LICENSE COMPLIANCE TAB ═══════════════
|
||||
if active_tab() == "licenses" {
|
||||
// The chart of one target's licence groups (#957); a click on it
|
||||
// narrows the licence table below to that group.
|
||||
{
|
||||
let repo = repo_filter();
|
||||
let repo_name = match &*repos.read() {
|
||||
Some(Some(resp)) => resp
|
||||
.data
|
||||
.iter()
|
||||
.find(|r| {
|
||||
r.get("_id").and_then(|o| o.get("$oid")).and_then(|s| s.as_str())
|
||||
== Some(repo.as_str())
|
||||
})
|
||||
.and_then(|r| r.get("name").and_then(|n| n.as_str()))
|
||||
.unwrap_or_default()
|
||||
.to_string(),
|
||||
_ => String::new(),
|
||||
let counts = match &*license_data.read() {
|
||||
Some(Some(resp)) if !repo_filter().is_empty() => {
|
||||
Some(resp.data.iter().map(|l| (l.category, l.count)).collect())
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
rsx! {
|
||||
LicenseCheckPanel {
|
||||
key: "{repo}",
|
||||
repo: repo.clone(),
|
||||
repo_name,
|
||||
on_changed: move |_| {
|
||||
license_data.restart();
|
||||
sbom.restart();
|
||||
},
|
||||
if let Some(counts) = counts {
|
||||
crate::components::licence_overview::LicenceOverview {
|
||||
counts,
|
||||
selected: licence_group,
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if licence_group().is_none() {
|
||||
{
|
||||
let repo = repo_filter();
|
||||
let repo_name = match &*repos.read() {
|
||||
Some(Some(resp)) => resp
|
||||
.data
|
||||
.iter()
|
||||
.find(|r| {
|
||||
r.get("_id").and_then(|o| o.get("$oid")).and_then(|s| s.as_str())
|
||||
== Some(repo.as_str())
|
||||
})
|
||||
.and_then(|r| r.get("name").and_then(|n| n.as_str()))
|
||||
.unwrap_or_default()
|
||||
.to_string(),
|
||||
_ => String::new(),
|
||||
};
|
||||
rsx! {
|
||||
LicenseCheckPanel {
|
||||
key: "{repo}",
|
||||
repo: repo.clone(),
|
||||
repo_name,
|
||||
on_changed: move |_| {
|
||||
license_data.restart();
|
||||
sbom.restart();
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -615,9 +677,17 @@ pub fn SbomPage(target: String) -> Element {
|
||||
let copyleft_items: Vec<_> = resp.data.iter().filter(|l| l.category.is_copyleft()).collect();
|
||||
let open = resp.data.iter().find(|l| l.license == "Unknown").map_or(0, |l| l.count);
|
||||
let confirmed: u64 = resp.data.iter().map(|l| l.confirmed).sum();
|
||||
// Behind a click on the chart only the table, narrowed
|
||||
// to the group clicked.
|
||||
let narrowed = licence_group();
|
||||
let shown: Vec<_> = resp
|
||||
.data
|
||||
.iter()
|
||||
.filter(|l| narrowed.is_none_or(|g| l.category.group() == g))
|
||||
.collect();
|
||||
|
||||
rsx! {
|
||||
if open > 0 || confirmed > 0 {
|
||||
if narrowed.is_none() && (open > 0 || confirmed > 0) {
|
||||
div { class: "card license-open-card",
|
||||
if open > 0 {
|
||||
strong { {lx::OPEN_COUNT.get(lang).replace("{n}", &open.to_string())} }
|
||||
@@ -638,7 +708,7 @@ pub fn SbomPage(target: String) -> Element {
|
||||
}
|
||||
}
|
||||
}
|
||||
if has_copyleft {
|
||||
if narrowed.is_none() && has_copyleft {
|
||||
div { class: "license-copyleft-warning",
|
||||
strong { {tx::COPYLEFT_TITLE.get(lang)} }
|
||||
p { {tx::COPYLEFT_BODY.get(lang)} }
|
||||
@@ -654,6 +724,7 @@ pub fn SbomPage(target: String) -> Element {
|
||||
}
|
||||
}
|
||||
|
||||
if narrowed.is_none() {
|
||||
div { class: "card",
|
||||
h3 { style: "margin-bottom: 16px;", {tx::LICENSE_DISTRIBUTION.get(lang)} }
|
||||
if total_pkgs > 0 {
|
||||
@@ -681,6 +752,7 @@ pub fn SbomPage(target: String) -> Element {
|
||||
p { {tx::NO_LICENSE_DATA.get(lang)} }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
div { class: "card",
|
||||
h3 { style: "margin-bottom: 16px;", {tx::ALL_LICENSES_TITLE.get(lang)} }
|
||||
@@ -695,7 +767,7 @@ pub fn SbomPage(target: String) -> Element {
|
||||
}
|
||||
}
|
||||
tbody {
|
||||
for item in &resp.data {
|
||||
for item in &shown {
|
||||
tr {
|
||||
td {
|
||||
span {
|
||||
@@ -911,7 +983,7 @@ pub fn SbomPage(target: String) -> Element {
|
||||
}
|
||||
}
|
||||
|
||||
fn pm_display_name(pm: &str) -> &str {
|
||||
pub(crate) fn pm_display_name(pm: &str) -> &str {
|
||||
match pm {
|
||||
"npm" => "npm",
|
||||
"cargo" => "Cargo",
|
||||
|
||||
@@ -10,6 +10,7 @@ use crate::app::Route;
|
||||
use crate::components::artifact_upload::ArtifactUpload;
|
||||
use crate::components::billing_swap::BillingSwap;
|
||||
use crate::components::cra_bar::CraBar;
|
||||
use crate::components::cve_trend::TargetCveDashboard;
|
||||
use crate::components::evidence_button::EvidencePackButton;
|
||||
use crate::components::layer_pins::LayerPinsCard;
|
||||
use crate::components::manual_findings::ManualFindingsPanel;
|
||||
@@ -19,9 +20,10 @@ use crate::components::scan_coverage::ScanCoverage;
|
||||
use crate::components::scan_runs::ScanRunList;
|
||||
use crate::components::severity_badge::SeverityBadge;
|
||||
use crate::components::toast::{ToastType, Toasts};
|
||||
use crate::components::vex_panel::VexPanel;
|
||||
use crate::components::webhook_deliveries::WebhookDeliveries;
|
||||
use crate::i18n::texts::{common, compliance::language_name, kinds, targets as tx};
|
||||
use crate::i18n::texts::{
|
||||
common, compliance::language_name, kinds, repo_views as rv, targets as tx,
|
||||
};
|
||||
use crate::i18n::use_lang;
|
||||
use crate::infrastructure::evidence::{fetch_compliance, CraCounts};
|
||||
use crate::infrastructure::findings::{fetch_findings, location, FindingsQuery};
|
||||
@@ -32,7 +34,10 @@ use crate::infrastructure::onboarding::{
|
||||
ArchivePassword, ArtifactInputDto, PasswordOutcome,
|
||||
};
|
||||
use crate::infrastructure::platform::{use_source_only, SourceOnlyNote};
|
||||
use crate::infrastructure::projects::{fetch_projects, project_ids_of, set_target_projects};
|
||||
use crate::infrastructure::projects::{
|
||||
fetch_projects, project_ids_of, projects_named, set_target_projects,
|
||||
};
|
||||
use crate::pages::target_views::{RepoCrumbs, RepoView, TodayLink};
|
||||
|
||||
/// Open findings listed on the page; the rest are one click away.
|
||||
const OPEN_SHOWN: usize = 5;
|
||||
@@ -92,6 +97,8 @@ fn editable_artifacts(target: &serde_json::Value) -> Vec<ArtifactInputDto> {
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
/// The page of target `id`: its dashboard, with the way to its views
|
||||
/// ([`crate::pages::target_views`]) and to Heute.
|
||||
#[component]
|
||||
pub fn TargetPage(id: String) -> Element {
|
||||
let lang = use_lang()();
|
||||
@@ -162,8 +169,16 @@ pub fn TargetPage(id: String) -> Element {
|
||||
// The code graph's card, once a scan built one with declarations in it.
|
||||
let graph = graph.read().clone().flatten().filter(|g| g.units > 0);
|
||||
|
||||
let project_names: Vec<String> = match &*projects.read() {
|
||||
Some(Ok(all)) => projects_named(&project_ids_of(&t), all)
|
||||
.into_iter()
|
||||
.map(|p| p.name.clone())
|
||||
.collect(),
|
||||
_ => Vec::new(),
|
||||
};
|
||||
|
||||
rsx! {
|
||||
BackLink {}
|
||||
RepoCrumbs { target_id: id.clone(), name: name.clone(), projects: project_names, view: None }
|
||||
|
||||
header { class: "target-head",
|
||||
div { class: "target-head-text",
|
||||
@@ -187,44 +202,54 @@ pub fn TargetPage(id: String) -> Element {
|
||||
}
|
||||
}
|
||||
div { class: "target-head-actions",
|
||||
if can_write {
|
||||
button {
|
||||
class: "btn btn-primary",
|
||||
disabled: starting(),
|
||||
onclick: move |_| {
|
||||
starting.set(true);
|
||||
spawn(async move {
|
||||
match trigger_target_scan(target_id()).await {
|
||||
Ok(_) => {
|
||||
toasts.push(ToastType::Success, tx::SCAN_STARTED.get(lang));
|
||||
scans_started += 1;
|
||||
}
|
||||
Err(e) => toasts.push(ToastType::Error, e.to_string()),
|
||||
Link {
|
||||
class: "btn btn-secondary",
|
||||
to: Route::target_view(id.clone(), RepoView::Findings),
|
||||
title: rv::ALL_VIEWS_HINT.get(lang),
|
||||
{rv::ALL_VIEWS.get(lang)}
|
||||
Icon { icon: BsArrowRight, width: 14, height: 14 }
|
||||
}
|
||||
TodayLink { target_id: id.clone() }
|
||||
}
|
||||
}
|
||||
div { class: "target-head-tools",
|
||||
if can_write {
|
||||
button {
|
||||
class: "btn btn-ghost",
|
||||
disabled: starting(),
|
||||
onclick: move |_| {
|
||||
starting.set(true);
|
||||
spawn(async move {
|
||||
match trigger_target_scan(target_id()).await {
|
||||
Ok(_) => {
|
||||
toasts.push(ToastType::Success, tx::SCAN_STARTED.get(lang));
|
||||
scans_started += 1;
|
||||
}
|
||||
starting.set(false);
|
||||
status.restart();
|
||||
});
|
||||
},
|
||||
Icon { icon: BsPlayFill, width: 16, height: 16 }
|
||||
{tx::RUN_SCAN.get(lang)}
|
||||
}
|
||||
Err(e) => toasts.push(ToastType::Error, e.to_string()),
|
||||
}
|
||||
starting.set(false);
|
||||
status.restart();
|
||||
});
|
||||
},
|
||||
Icon { icon: BsPlayFill, width: 16, height: 16 }
|
||||
{tx::RUN_SCAN.get(lang)}
|
||||
}
|
||||
EvidencePackButton { target_id: id.clone() }
|
||||
if can_write {
|
||||
button {
|
||||
class: "btn btn-ghost",
|
||||
onclick: move |_| editing.set(true),
|
||||
Icon { icon: BsPencil, width: 14, height: 14 }
|
||||
{tx::EDIT.get(lang)}
|
||||
}
|
||||
}
|
||||
EvidencePackButton { target_id: id.clone() }
|
||||
if can_write {
|
||||
button {
|
||||
class: "btn btn-ghost",
|
||||
onclick: move |_| editing.set(true),
|
||||
Icon { icon: BsPencil, width: 14, height: 14 }
|
||||
{tx::EDIT.get(lang)}
|
||||
}
|
||||
if can_write {
|
||||
button {
|
||||
class: "btn btn-ghost btn-ghost-danger",
|
||||
onclick: move |_| confirm_delete.set(true),
|
||||
Icon { icon: BsTrash, width: 14, height: 14 }
|
||||
{tx::DELETE.get(lang)}
|
||||
}
|
||||
}
|
||||
if can_write {
|
||||
button {
|
||||
class: "btn btn-ghost btn-ghost-danger",
|
||||
onclick: move |_| confirm_delete.set(true),
|
||||
Icon { icon: BsTrash, width: 14, height: 14 }
|
||||
{tx::DELETE.get(lang)}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -239,6 +264,9 @@ pub fn TargetPage(id: String) -> Element {
|
||||
}
|
||||
}
|
||||
|
||||
// Open CVEs with a fix over 30 days, and where to act (#952).
|
||||
TargetCveDashboard { target_id: id.clone() }
|
||||
|
||||
div { class: "target-summary",
|
||||
section { class: "card target-cra",
|
||||
div { class: "target-card-head",
|
||||
@@ -311,7 +339,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 }
|
||||
}
|
||||
@@ -346,11 +374,6 @@ pub fn TargetPage(id: String) -> Element {
|
||||
LayerPinsCard { pins }
|
||||
}
|
||||
|
||||
section { class: "card target-vex",
|
||||
div { class: "target-card-head", h3 { {crate::i18n::texts::vex::TITLE.get(lang)} } }
|
||||
div { class: "target-card-body", VexPanel { target_id: id.clone() } }
|
||||
}
|
||||
|
||||
div { class: "target-columns",
|
||||
section { class: "card",
|
||||
div { class: "target-card-head", h3 { {tx::SCAN_RUNS.get(lang)} } }
|
||||
|
||||
@@ -0,0 +1,373 @@
|
||||
//! A target's views (#957): one tab per view, each opening with a chart; a
|
||||
//! click on the chart leads to the list behind it, already narrowed. Reached
|
||||
//! from the target's dashboard ("Alle Ansichten"); the breadcrumb leads back.
|
||||
|
||||
use compliance_core::models::inbox::Bucket;
|
||||
use compliance_core::models::license::{LicenseGroup, LicenseGroupCounts};
|
||||
use dioxus::prelude::*;
|
||||
use dioxus_free_icons::icons::bs_icons::BsArrowRight;
|
||||
use dioxus_free_icons::Icon;
|
||||
|
||||
use crate::app::Route;
|
||||
use crate::components::component_overview::ComponentOverview;
|
||||
use crate::components::cra_tiles::CraTiles;
|
||||
use crate::components::cve_matrix::CveView;
|
||||
use crate::components::finding_breakdown::FindingBreakdownView;
|
||||
use crate::components::scan_history::ScanHistory;
|
||||
use crate::i18n::texts::{common, repo_views as tx};
|
||||
use crate::i18n::{format_count, use_lang, Lang};
|
||||
use crate::infrastructure::evidence::{fetch_compliance, CraCounts};
|
||||
use crate::infrastructure::findings::{fetch_findings, FindingsQuery};
|
||||
use crate::infrastructure::inbox::fetch_inbox;
|
||||
use crate::infrastructure::onboarding::fetch_target;
|
||||
use crate::infrastructure::projects::{fetch_projects, project_ids_of, projects_named};
|
||||
use crate::infrastructure::sbom::{fetch_license_summary, LicenseSummaryData};
|
||||
|
||||
/// A tab of a target's views, in the order the tabs show.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum RepoView {
|
||||
Findings,
|
||||
Cves,
|
||||
Components,
|
||||
Licences,
|
||||
Cra,
|
||||
History,
|
||||
}
|
||||
|
||||
impl RepoView {
|
||||
/// Every view, in tab order.
|
||||
pub const ALL: [Self; 6] = [
|
||||
Self::Findings,
|
||||
Self::Cves,
|
||||
Self::Components,
|
||||
Self::Licences,
|
||||
Self::Cra,
|
||||
Self::History,
|
||||
];
|
||||
|
||||
/// The view's name in the URL (`/targets/{id}/views/{slug}`).
|
||||
pub const fn slug(self) -> &'static str {
|
||||
match self {
|
||||
Self::Findings => "findings",
|
||||
Self::Cves => "cves",
|
||||
Self::Components => "components",
|
||||
Self::Licences => "licences",
|
||||
Self::Cra => "cra",
|
||||
Self::History => "history",
|
||||
}
|
||||
}
|
||||
|
||||
/// The view named `slug`; an unknown name opens the first tab.
|
||||
pub fn from_slug(slug: &str) -> Self {
|
||||
Self::ALL
|
||||
.into_iter()
|
||||
.find(|v| v.slug() == slug)
|
||||
.unwrap_or(Self::Findings)
|
||||
}
|
||||
|
||||
/// The tab's label.
|
||||
pub fn label(self, lang: Lang) -> &'static str {
|
||||
match self {
|
||||
Self::Findings => tx::FINDINGS,
|
||||
Self::Cves => tx::CVES,
|
||||
Self::Components => tx::COMPONENTS,
|
||||
Self::Licences => tx::LICENCES,
|
||||
Self::Cra => tx::CRA,
|
||||
Self::History => tx::HISTORY,
|
||||
}
|
||||
.get(lang)
|
||||
}
|
||||
}
|
||||
|
||||
/// The figure next to a tab's label: the open findings, and from the
|
||||
/// target's CRA status its CVEs, components and CRA counts; `None` while
|
||||
/// they load or when the view has no figure.
|
||||
fn tab_figure(
|
||||
view: RepoView,
|
||||
status: Option<&serde_json::Value>,
|
||||
open_findings: Option<u64>,
|
||||
lang: Lang,
|
||||
) -> Option<String> {
|
||||
let number = |key: &str| status?.get(key)?.as_u64();
|
||||
match view {
|
||||
RepoView::Findings => open_findings.map(|n| tx::open(n, lang)),
|
||||
RepoView::Cves => number("cve_alerts").map(|n| format_count(n, lang)),
|
||||
RepoView::Components => number("sbom_components").map(|n| format_count(n, lang)),
|
||||
RepoView::Cra => serde_json::from_value::<CraCounts>(status?.get("counts")?.clone())
|
||||
.ok()
|
||||
.map(|c| {
|
||||
let total = c.not_satisfied
|
||||
+ c.not_assessed
|
||||
+ c.partial
|
||||
+ c.no_violation_found
|
||||
+ c.not_code_checkable;
|
||||
format!("{}/{total}", c.no_violation_found)
|
||||
}),
|
||||
RepoView::Licences | RepoView::History => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The breadcrumb of target `target_id`: Überblick › its projects › its
|
||||
/// name, and the open `view` when there is one.
|
||||
#[component]
|
||||
pub fn RepoCrumbs(
|
||||
target_id: String,
|
||||
name: String,
|
||||
projects: Vec<String>,
|
||||
view: Option<RepoView>,
|
||||
) -> Element {
|
||||
let lang = use_lang()();
|
||||
rsx! {
|
||||
nav { class: "repo-crumbs", "aria-label": tx::BREADCRUMB.get(lang),
|
||||
Link { to: Route::OverviewPage {}, {tx::OVERVIEW.get(lang)} }
|
||||
if !projects.is_empty() {
|
||||
span { class: "repo-crumb-sep", "aria-hidden": "true", "›" }
|
||||
span { "{projects.join(\", \")}" }
|
||||
}
|
||||
span { class: "repo-crumb-sep", "aria-hidden": "true", "›" }
|
||||
match view {
|
||||
Some(view) => rsx! {
|
||||
Link { class: "repo-crumb-name", to: Route::target(target_id.clone()), "{name}" }
|
||||
span { class: "repo-crumb-sep", "aria-hidden": "true", "›" }
|
||||
span { "aria-current": "page", {view.label(lang)} }
|
||||
},
|
||||
None => rsx! { span { class: "repo-crumb-name", "aria-current": "page", "{name}" } },
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// "N heute zu entscheiden →": Heute, narrowed to target `target_id`.
|
||||
#[component]
|
||||
pub fn TodayLink(target_id: String) -> Element {
|
||||
let lang = use_lang()();
|
||||
let id = target_id.clone();
|
||||
let view = use_resource(move || {
|
||||
let id = id.clone();
|
||||
async move { fetch_inbox(id, Bucket::Today, Some(0)).await.ok() }
|
||||
});
|
||||
let today = view
|
||||
.read()
|
||||
.as_ref()
|
||||
.and_then(|v| v.as_ref().map(|v| v.counts.today));
|
||||
rsx! {
|
||||
Link {
|
||||
class: if today.unwrap_or(0) > 0 { "btn btn-primary" } else { "btn btn-secondary" },
|
||||
to: Route::heute(target_id, Some(Bucket::Today)),
|
||||
match today {
|
||||
Some(n) => rsx! { {tx::today(n, lang)} },
|
||||
None => rsx! { {tx::TODAY.get(lang)} },
|
||||
}
|
||||
Icon { icon: BsArrowRight, width: 14, height: 14 }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The views of target `id`, tab `view` open. From the URL query:
|
||||
/// `cve_severity` and `cve_vex` are the CVE grid's cell (see [`CveView`]),
|
||||
/// `control` the CRA requirement and `scan` the scan opened.
|
||||
#[component]
|
||||
pub fn TargetViewsPage(
|
||||
id: String,
|
||||
view: String,
|
||||
cve_severity: Option<String>,
|
||||
cve_vex: Option<String>,
|
||||
control: Option<String>,
|
||||
scan: Option<String>,
|
||||
) -> Element {
|
||||
let lang = use_lang()();
|
||||
let current = RepoView::from_slug(&view);
|
||||
// The page stays mounted from tab to tab (only `view` changes); another
|
||||
// target's `id` loads again.
|
||||
let target = use_resource(use_reactive!(
|
||||
|id| async move { fetch_target(id).await.ok() }
|
||||
));
|
||||
let status = use_resource(use_reactive!(|id| async move {
|
||||
fetch_compliance(id).await.ok()
|
||||
}));
|
||||
let open_findings = use_resource(use_reactive!(|id| async move {
|
||||
fetch_findings(FindingsQuery {
|
||||
page: 1,
|
||||
repo_id: id,
|
||||
status: "open".to_string(),
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.ok()
|
||||
.and_then(|r| r.total)
|
||||
}));
|
||||
let projects = use_resource(fetch_projects);
|
||||
|
||||
let target_json = target.read().clone().flatten().map(|r| r.data);
|
||||
let name = target_json
|
||||
.as_ref()
|
||||
.and_then(|t| t.get("name").and_then(|n| n.as_str()))
|
||||
.unwrap_or_default()
|
||||
.to_string();
|
||||
let project_names: Vec<String> = match (&target_json, &*projects.read()) {
|
||||
(Some(t), Some(Ok(all))) => projects_named(&project_ids_of(t), all)
|
||||
.into_iter()
|
||||
.map(|p| p.name.clone())
|
||||
.collect(),
|
||||
_ => Vec::new(),
|
||||
};
|
||||
let status = status.read().clone().flatten();
|
||||
let open_findings = open_findings.read().flatten();
|
||||
|
||||
rsx! {
|
||||
RepoCrumbs { target_id: id.clone(), name: name.clone(), projects: project_names, view: Some(current) }
|
||||
header { class: "repo-head",
|
||||
div { class: "repo-head-text",
|
||||
h2 { class: "repo-head-name", "{name}" }
|
||||
p { class: "repo-head-sub", {tx::SUBTITLE.get(lang)} }
|
||||
}
|
||||
TodayLink { target_id: id.clone() }
|
||||
}
|
||||
nav { class: "repo-tabs", role: "tablist", "aria-label": tx::TABS.get(lang),
|
||||
for v in RepoView::ALL {
|
||||
Link {
|
||||
key: "{v.slug()}",
|
||||
class: if v == current { "repo-tab is-active" } else { "repo-tab" },
|
||||
role: "tab",
|
||||
"aria-selected": if v == current { "true" } else { "false" },
|
||||
to: Route::target_view(id.clone(), v),
|
||||
{v.label(lang)}
|
||||
if let Some(figure) = tab_figure(v, status.as_ref(), open_findings, lang) {
|
||||
span { class: "repo-tab-figure", "{figure}" }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
div { class: "repo-view",
|
||||
match current {
|
||||
RepoView::Findings => rsx! {
|
||||
FindingBreakdownView { target: id.clone(), scan_type: None, severity: None, path: None }
|
||||
Link { class: "repo-view-list", to: Route::findings(id.clone()), {tx::FINDINGS_LIST.get(lang)} }
|
||||
},
|
||||
RepoView::Cves => rsx! {
|
||||
CveView { target_id: id.clone(), cve_severity, cve_vex }
|
||||
},
|
||||
RepoView::Components => rsx! {
|
||||
ComponentsTab { target_id: id.clone() }
|
||||
},
|
||||
RepoView::Licences => rsx! {
|
||||
LicencesTab { target_id: id.clone() }
|
||||
},
|
||||
RepoView::Cra => rsx! {
|
||||
CraTiles { target_id: id.clone(), control }
|
||||
},
|
||||
RepoView::History => rsx! {
|
||||
ScanHistory { target_id: id.clone(), scan }
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The components view: updates ranked by the CVEs they remove, and the
|
||||
/// components per ecosystem; an ecosystem opens the SBOM list filtered to it.
|
||||
#[component]
|
||||
fn ComponentsTab(target_id: String) -> Element {
|
||||
let navigator = use_navigator();
|
||||
let target = target_id.clone();
|
||||
rsx! {
|
||||
ComponentOverview {
|
||||
target_id,
|
||||
ecosystem: String::new(),
|
||||
on_ecosystem: move |ecosystem: String| {
|
||||
navigator.push(Route::SbomEcosystemPage { ecosystem, target: target.clone() });
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The licence view: the bar of the licence groups; a group opens its
|
||||
/// licences, with the components under each.
|
||||
#[component]
|
||||
fn LicencesTab(target_id: String) -> Element {
|
||||
let lang = use_lang()();
|
||||
let selected = use_signal(|| None::<LicenseGroup>);
|
||||
let id = target_id.clone();
|
||||
let summary = use_resource(move || {
|
||||
let id = id.clone();
|
||||
async move { fetch_license_summary(Some(id)).await.ok() }
|
||||
});
|
||||
let Some(Some(summary)) = summary.read().clone() else {
|
||||
return rsx! { div { class: "loading", {common::LOADING.get(lang)} } };
|
||||
};
|
||||
let counts: LicenseGroupCounts = summary.data.iter().map(|l| (l.category, l.count)).collect();
|
||||
if counts.total() == 0 {
|
||||
return rsx! { p { class: "card target-muted", {tx::NO_LICENCES.get(lang)} } };
|
||||
}
|
||||
let group: Option<LicenseGroup> = selected();
|
||||
let licences: Vec<LicenseSummaryData> = summary
|
||||
.data
|
||||
.into_iter()
|
||||
.filter(|l| group.is_some_and(|g| l.category.group() == g))
|
||||
.collect();
|
||||
rsx! {
|
||||
crate::components::licence_overview::LicenceOverview { counts, selected }
|
||||
if group.is_some() {
|
||||
div { class: "card table-wrapper",
|
||||
table {
|
||||
thead {
|
||||
tr {
|
||||
th { {tx::LICENCE.get(lang)} }
|
||||
th { class: "co-num", {tx::COUNT.get(lang)} }
|
||||
th { {tx::USED_BY.get(lang)} }
|
||||
}
|
||||
}
|
||||
tbody {
|
||||
for l in licences {
|
||||
tr { key: "{l.license}",
|
||||
td { "{l.license}" }
|
||||
td { class: "co-num", {format_count(l.count, lang)} }
|
||||
td { class: "repo-licence-packages", "{l.packages.join(\", \")}" }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Link {
|
||||
class: "repo-view-list",
|
||||
to: Route::SbomPage { target: target_id },
|
||||
{tx::LICENCES_LIST.get(lang)}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn every_view_reads_back_from_its_slug_and_an_unknown_one_opens_the_first() {
|
||||
for view in RepoView::ALL {
|
||||
assert_eq!(RepoView::from_slug(view.slug()), view);
|
||||
}
|
||||
assert_eq!(RepoView::from_slug("nope"), RepoView::Findings);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_tabs_show_the_figures_the_status_has() {
|
||||
let status = serde_json::json!({
|
||||
"cve_alerts": 15,
|
||||
"sbom_components": 312,
|
||||
"counts": {
|
||||
"not_satisfied": 6, "not_assessed": 8, "partial": 0,
|
||||
"no_violation_found": 14, "not_code_checkable": 12,
|
||||
},
|
||||
});
|
||||
let figure = |v| tab_figure(v, Some(&status), Some(47), Lang::De);
|
||||
assert_eq!(figure(RepoView::Findings).as_deref(), Some("47 offen"));
|
||||
assert_eq!(figure(RepoView::Cves).as_deref(), Some("15"));
|
||||
assert_eq!(figure(RepoView::Components).as_deref(), Some("312"));
|
||||
// Checked in the code without a finding, of all 40.
|
||||
assert_eq!(figure(RepoView::Cra).as_deref(), Some("14/40"));
|
||||
assert_eq!(figure(RepoView::Licences), None);
|
||||
assert_eq!(figure(RepoView::History), None);
|
||||
assert_eq!(tab_figure(RepoView::Cves, None, None, Lang::De), None);
|
||||
assert_eq!(tab_figure(RepoView::Findings, None, None, Lang::De), None);
|
||||
}
|
||||
}
|
||||
@@ -226,10 +226,10 @@ pub fn TargetsPage() -> Element {
|
||||
rsx! {
|
||||
tr {
|
||||
class: "targets-row",
|
||||
onclick: move |_| { navigator.push(Route::TargetPage { id: id_open.clone() }); },
|
||||
onclick: move |_| { navigator.push(Route::target(id_open.clone())); },
|
||||
td {
|
||||
Link {
|
||||
to: Route::TargetPage { id: id.clone() },
|
||||
to: Route::target(id.clone()),
|
||||
class: "targets-name",
|
||||
onclick: move |e: MouseEvent| e.stop_propagation(),
|
||||
"{name}"
|
||||
@@ -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}"
|
||||
|
||||
@@ -17,13 +17,15 @@ thiserror = { workspace = true }
|
||||
|
||||
|
||||
# Tree-sitter parsing
|
||||
tree-sitter = "0.24"
|
||||
tree-sitter = "0.25"
|
||||
tree-sitter-rust = "0.23"
|
||||
tree-sitter-python = "0.23"
|
||||
tree-sitter-javascript = "0.23"
|
||||
tree-sitter-typescript = "0.23"
|
||||
tree-sitter-c = "0.23"
|
||||
tree-sitter-c-sharp = "=0.23.1"
|
||||
# VB.NET, CodeAnt-AI grammar (MIT), ABI 15: needs tree-sitter 0.25
|
||||
tree-sitter-vb-dotnet = "=0.1.0"
|
||||
|
||||
# Graph algorithms
|
||||
petgraph = "0.7"
|
||||
|
||||
@@ -19,7 +19,7 @@ use super::common::{parse, text, walk, FileGraph};
|
||||
/// Base types whose methods a web framework calls: MVC and API
|
||||
/// controllers, Razor pages, SignalR hubs, Web Forms pages, controls and
|
||||
/// master pages, and ASMX services.
|
||||
const WEB_BASES: [&str; 9] = [
|
||||
pub(super) const WEB_BASES: [&str; 9] = [
|
||||
"Controller",
|
||||
"ControllerBase",
|
||||
"ApiController",
|
||||
@@ -32,7 +32,7 @@ const WEB_BASES: [&str; 9] = [
|
||||
];
|
||||
|
||||
/// Attributes that expose a method over HTTP.
|
||||
const ENDPOINT_ATTRIBUTES: [&str; 10] = [
|
||||
pub(super) const ENDPOINT_ATTRIBUTES: [&str; 10] = [
|
||||
"HttpGet",
|
||||
"HttpPost",
|
||||
"HttpPut",
|
||||
|
||||
@@ -0,0 +1,664 @@
|
||||
//! ASP.NET markup: Razor components and views (`.razor`, `.cshtml`) and Web
|
||||
//! Forms pages, user controls and master pages (`.aspx`, `.ascx`,
|
||||
//! `.master`). Only their code regions hold declarations:
|
||||
//!
|
||||
//! - Razor: `@code { … }` and `@functions { … }` blocks, C# members;
|
||||
//! - Web Forms: `<script runat="server"> … </script>` blocks, members in the
|
||||
//! language the `<%@ Page/Control/Master Language="…" %>` directive names
|
||||
//! (C# when it names none).
|
||||
//!
|
||||
//! Everything else is blanked out, line breaks kept, and each region is
|
||||
//! wrapped in a class named after the file, so the C# or VB parser reads the
|
||||
//! members and every line it reports is the line in the markup file.
|
||||
//! Inline Razor (`@{ … }`, `@if`, `@x.Y()`) and Web Forms render blocks
|
||||
//! (`<% … %>`) mix code with markup and are left out.
|
||||
//!
|
||||
//! The framework calls a markup file's methods from the markup itself
|
||||
//! (`@onclick="Save"`, `OnClick="BtnSave_Click"`, `<%# GetTitle() %>`) and
|
||||
//! through lifecycle hooks (`OnInitialized`, `Page_Load`), so those are
|
||||
//! entry points.
|
||||
|
||||
use std::collections::HashSet;
|
||||
use std::path::Path;
|
||||
|
||||
use compliance_core::error::CoreError;
|
||||
use compliance_core::models::graph::CodeNodeKind;
|
||||
use compliance_core::traits::graph_builder::{LanguageParser, ParseOutput};
|
||||
|
||||
use super::common::FileGraph;
|
||||
use super::csharp::CSharpParser;
|
||||
use super::vb::VbParser;
|
||||
|
||||
/// Methods a Razor component's or Web Forms page's framework calls without
|
||||
/// the markup naming them.
|
||||
const LIFECYCLE_HOOKS: [&str; 22] = [
|
||||
// Blazor components
|
||||
"OnInitialized",
|
||||
"OnInitializedAsync",
|
||||
"OnParametersSet",
|
||||
"OnParametersSetAsync",
|
||||
"OnAfterRender",
|
||||
"OnAfterRenderAsync",
|
||||
"SetParametersAsync",
|
||||
"ShouldRender",
|
||||
"Dispose",
|
||||
"DisposeAsync",
|
||||
// Web Forms, wired by AutoEventWireup
|
||||
"Page_PreInit",
|
||||
"Page_Init",
|
||||
"Page_InitComplete",
|
||||
"Page_PreLoad",
|
||||
"Page_Load",
|
||||
"Page_LoadComplete",
|
||||
"Page_PreRender",
|
||||
"Page_PreRenderComplete",
|
||||
"Page_SaveStateComplete",
|
||||
"Page_Unload",
|
||||
"Page_Error",
|
||||
"Page_DataBind",
|
||||
];
|
||||
|
||||
/// Parses the code regions of ASP.NET markup files.
|
||||
#[derive(Debug, Default)]
|
||||
pub struct MarkupParser;
|
||||
|
||||
/// The language of a markup file's code regions.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
enum CodeLanguage {
|
||||
CSharp,
|
||||
Vb,
|
||||
}
|
||||
|
||||
/// One code region: the markup in `markup_start..code_start` (the
|
||||
/// `@code` keyword, the `<script>` tag) is replaced by `open`, the code in
|
||||
/// `code_start..code_end` is kept, and the markup in `code_end..markup_end`
|
||||
/// (the `</script>` tag) is replaced by `close`.
|
||||
#[derive(Debug)]
|
||||
struct Region {
|
||||
markup_start: usize,
|
||||
code_start: usize,
|
||||
code_end: usize,
|
||||
markup_end: usize,
|
||||
}
|
||||
|
||||
impl MarkupParser {
|
||||
/// An ASP.NET markup parser.
|
||||
pub fn new() -> Self {
|
||||
Self
|
||||
}
|
||||
}
|
||||
|
||||
impl LanguageParser for MarkupParser {
|
||||
fn language(&self) -> &str {
|
||||
"aspnet-markup"
|
||||
}
|
||||
|
||||
fn extensions(&self) -> &[&str] {
|
||||
&["razor", "cshtml", "aspx", "ascx", "master"]
|
||||
}
|
||||
|
||||
fn parse_file(
|
||||
&self,
|
||||
file_path: &Path,
|
||||
source: &str,
|
||||
repo_id: &str,
|
||||
graph_build_id: &str,
|
||||
) -> Result<ParseOutput, CoreError> {
|
||||
let ext = file_path
|
||||
.extension()
|
||||
.and_then(|e| e.to_str())
|
||||
.unwrap_or_default()
|
||||
.to_ascii_lowercase();
|
||||
let razor = matches!(ext.as_str(), "razor" | "cshtml");
|
||||
let (language, inherits, regions) = if razor {
|
||||
(CodeLanguage::CSharp, None, razor_regions(source))
|
||||
} else {
|
||||
let (language, inherits) = web_forms_directive(source);
|
||||
(language, inherits, web_forms_regions(source))
|
||||
};
|
||||
if regions.is_empty() {
|
||||
// Markup only: the file is part of the application all the same.
|
||||
let lines = source.lines().count() as u32;
|
||||
let name = match language {
|
||||
CodeLanguage::CSharp => "csharp",
|
||||
CodeLanguage::Vb => "vb",
|
||||
};
|
||||
return Ok(FileGraph::new(file_path, lines, repo_id, graph_build_id, name).finish());
|
||||
}
|
||||
// A Web Forms page's class is the one its directive names (Visual
|
||||
// Studio names `Default.aspx`'s `_Default`, `Default` being a VB
|
||||
// keyword); a Razor file's is named after the file.
|
||||
let class = inherits.unwrap_or_else(|| class_name(file_path));
|
||||
let (open, close) = match (razor, language) {
|
||||
// The `@code` keyword is followed by the block's own braces.
|
||||
(true, _) => (format!("class {class} "), ""),
|
||||
(false, CodeLanguage::CSharp) => (format!("class {class} {{"), "}"),
|
||||
(false, CodeLanguage::Vb) => (format!("Class {class}"), "End Class"),
|
||||
};
|
||||
let code = blank_markup(source, ®ions, &open, close);
|
||||
let mut output = match language {
|
||||
CodeLanguage::CSharp => {
|
||||
CSharpParser::new().parse_file(file_path, &code, repo_id, graph_build_id)?
|
||||
}
|
||||
CodeLanguage::Vb => {
|
||||
VbParser::new().parse_file(file_path, &code, repo_id, graph_build_id)?
|
||||
}
|
||||
};
|
||||
let referenced = markup_references(source, ®ions);
|
||||
for node in output
|
||||
.nodes
|
||||
.iter_mut()
|
||||
.filter(|n| matches!(n.kind, CodeNodeKind::Method))
|
||||
{
|
||||
let name = node.name.to_ascii_lowercase();
|
||||
if referenced.contains(&name)
|
||||
|| LIFECYCLE_HOOKS
|
||||
.iter()
|
||||
.any(|h| h.eq_ignore_ascii_case(&name))
|
||||
{
|
||||
node.is_entry_point = true;
|
||||
}
|
||||
}
|
||||
Ok(output)
|
||||
}
|
||||
}
|
||||
|
||||
/// The class a markup file compiles to, named after the file: `Counter` for
|
||||
/// `Counter.razor`, `_Layout` for `_Layout.cshtml`, as an identifier.
|
||||
fn class_name(file_path: &Path) -> String {
|
||||
let stem = file_path
|
||||
.file_stem()
|
||||
.and_then(|s| s.to_str())
|
||||
.unwrap_or("Page");
|
||||
let mut name: String = stem
|
||||
.chars()
|
||||
.map(|c| {
|
||||
if c.is_alphanumeric() || c == '_' {
|
||||
c
|
||||
} else {
|
||||
'_'
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
if name.starts_with(|c: char| c.is_ascii_digit()) || name.is_empty() {
|
||||
name.insert(0, '_');
|
||||
}
|
||||
name
|
||||
}
|
||||
|
||||
/// `source` with everything outside `regions` replaced by spaces (line
|
||||
/// breaks kept), each region's opening markup by `open` and its closing
|
||||
/// markup by `close`.
|
||||
fn blank_markup(source: &str, regions: &[Region], open: &str, close: &str) -> String {
|
||||
let mut code = String::with_capacity(source.len());
|
||||
let blank = |code: &mut String, markup: &str| {
|
||||
code.extend(markup.chars().map(|c| if c == '\n' { '\n' } else { ' ' }));
|
||||
};
|
||||
let mut at = 0;
|
||||
for region in regions {
|
||||
blank(&mut code, &source[at..region.markup_start]);
|
||||
code.push_str(open);
|
||||
// The rest of the opening markup, if it spans lines (a `<script>`
|
||||
// tag with its attributes on several), keeps its line breaks.
|
||||
blank(&mut code, &source[region.markup_start..region.code_start]);
|
||||
code.push_str(&source[region.code_start..region.code_end]);
|
||||
code.push_str(close);
|
||||
blank(&mut code, &source[region.code_end..region.markup_end]);
|
||||
at = region.markup_end;
|
||||
}
|
||||
blank(&mut code, &source[at..]);
|
||||
code
|
||||
}
|
||||
|
||||
/// The `@code { … }` and `@functions { … }` blocks of a Razor file, outside
|
||||
/// Razor comments (`@* … *@`). The opening markup is the keyword; the block
|
||||
/// with its braces is the code.
|
||||
fn razor_regions(source: &str) -> Vec<Region> {
|
||||
let bytes = source.as_bytes();
|
||||
let mut regions = Vec::new();
|
||||
let mut at = 0;
|
||||
while at < bytes.len() {
|
||||
if bytes[at..].starts_with(b"@*") {
|
||||
at = find(bytes, at + 2, b"*@").map_or(bytes.len(), |end| end + 2);
|
||||
continue;
|
||||
}
|
||||
if bytes[at] == b'@' && (at == 0 || !is_identifier_byte(bytes[at - 1])) {
|
||||
let keyword = [b"code".as_slice(), b"functions"]
|
||||
.into_iter()
|
||||
.find(|k| bytes[at + 1..].starts_with(k));
|
||||
if let Some(keyword) = keyword {
|
||||
let after = at + 1 + keyword.len();
|
||||
let open = after
|
||||
+ bytes[after..]
|
||||
.iter()
|
||||
.take_while(|b| b.is_ascii_whitespace())
|
||||
.count();
|
||||
if bytes.get(open) == Some(&b'{') {
|
||||
if let Some(close) = matching_brace(bytes, open) {
|
||||
regions.push(Region {
|
||||
markup_start: at,
|
||||
code_start: after,
|
||||
code_end: close + 1,
|
||||
markup_end: close + 1,
|
||||
});
|
||||
at = close + 1;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
at += 1;
|
||||
}
|
||||
regions
|
||||
}
|
||||
|
||||
/// The `<script runat="server">` blocks of a Web Forms file. The opening
|
||||
/// markup is the tag, the closing markup the `</script>` tag.
|
||||
fn web_forms_regions(source: &str) -> Vec<Region> {
|
||||
// ASCII lowercase keeps every byte offset.
|
||||
let lower = source.to_ascii_lowercase();
|
||||
let bytes = lower.as_bytes();
|
||||
let mut regions = Vec::new();
|
||||
let mut at = 0;
|
||||
while let Some(tag) = find(bytes, at, b"<script") {
|
||||
let Some(tag_end) = find(bytes, tag, b">") else {
|
||||
break;
|
||||
};
|
||||
let attributes: String = lower[tag..tag_end]
|
||||
.chars()
|
||||
.filter(|c| !c.is_whitespace())
|
||||
.collect();
|
||||
let server = ["runat=\"server\"", "runat='server'", "runat=server"]
|
||||
.iter()
|
||||
.any(|a| attributes.contains(a));
|
||||
let Some(close) = find(bytes, tag_end, b"</script") else {
|
||||
break;
|
||||
};
|
||||
let close_end = find(bytes, close, b">").map_or(bytes.len(), |end| end + 1);
|
||||
if server {
|
||||
regions.push(Region {
|
||||
markup_start: tag,
|
||||
code_start: tag_end + 1,
|
||||
code_end: close,
|
||||
markup_end: close_end,
|
||||
});
|
||||
}
|
||||
at = close_end;
|
||||
}
|
||||
regions
|
||||
}
|
||||
|
||||
/// The language and class a Web Forms file's directive names: `<%@ Page
|
||||
/// Language="VB" Inherits="Plant._Default" %>` is VB and `_Default`. No
|
||||
/// language, or another one, is C#.
|
||||
fn web_forms_directive(source: &str) -> (CodeLanguage, Option<String>) {
|
||||
// ASCII lowercase keeps every byte offset, so a match in `lower` is the
|
||||
// same range in `source`.
|
||||
let lower = source.to_ascii_lowercase();
|
||||
let bytes = lower.as_bytes();
|
||||
let mut at = 0;
|
||||
while let Some(start) = find(bytes, at, b"<%@") {
|
||||
let end = find(bytes, start, b"%>").unwrap_or(bytes.len());
|
||||
let directive = start + 3..end;
|
||||
let kind = lower[directive.clone()]
|
||||
.split_whitespace()
|
||||
.next()
|
||||
.unwrap_or_default();
|
||||
if matches!(kind, "page" | "control" | "master") {
|
||||
let value = |name: &str| {
|
||||
attribute_value(&lower, &source[directive.clone()], directive.start, name)
|
||||
};
|
||||
let language = match value("language") {
|
||||
Some(v) if v.to_ascii_lowercase().starts_with("vb") => CodeLanguage::Vb,
|
||||
_ => CodeLanguage::CSharp,
|
||||
};
|
||||
// `Plant._Default, Plant` names the class with its assembly.
|
||||
let inherits = value("inherits")
|
||||
.and_then(|v| v.split(',').next())
|
||||
.and_then(|v| v.trim().rsplit('.').next())
|
||||
.filter(|name| !name.is_empty())
|
||||
.map(str::to_string);
|
||||
return (language, inherits);
|
||||
}
|
||||
at = end;
|
||||
}
|
||||
(CodeLanguage::CSharp, None)
|
||||
}
|
||||
|
||||
/// The value of the attribute `name` in a directive, `directive` being its
|
||||
/// text in the original case and `offset` where it starts in `lower`.
|
||||
fn attribute_value<'s>(
|
||||
lower: &str,
|
||||
directive: &'s str,
|
||||
offset: usize,
|
||||
name: &str,
|
||||
) -> Option<&'s str> {
|
||||
let lower_directive = &lower[offset..offset + directive.len()];
|
||||
let mut from = 0;
|
||||
while let Some(found) = lower_directive[from..].find(name) {
|
||||
let at = from + found;
|
||||
from = at + name.len();
|
||||
// A whole attribute name: not the end of a longer one.
|
||||
if at > 0 && is_identifier_byte(lower_directive.as_bytes()[at - 1]) {
|
||||
continue;
|
||||
}
|
||||
let rest = directive[from..].trim_start();
|
||||
let Some(rest) = rest.strip_prefix('=') else {
|
||||
continue;
|
||||
};
|
||||
let rest = rest.trim_start();
|
||||
let (quote, rest) = match rest.chars().next() {
|
||||
Some(q @ ('"' | '\'')) => (Some(q), &rest[1..]),
|
||||
_ => (None, rest),
|
||||
};
|
||||
let end = match quote {
|
||||
Some(q) => rest.find(q),
|
||||
None => rest.find(char::is_whitespace),
|
||||
}
|
||||
.unwrap_or(rest.len());
|
||||
return Some(&rest[..end]);
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Lowercased identifiers the markup outside `regions` refers to: in
|
||||
/// attribute values (`OnClick="BtnSave_Click"`, `@onclick="Save"`), right
|
||||
/// after an `@` (`@Title()`), and in Web Forms code blocks (`<%# Eval(…) %>`).
|
||||
/// Text between tags is not code and doesn't count.
|
||||
fn markup_references(source: &str, regions: &[Region]) -> HashSet<String> {
|
||||
let mut slices = Vec::with_capacity(regions.len() + 1);
|
||||
let mut at = 0;
|
||||
for region in regions {
|
||||
slices.push(&source[at..region.markup_start]);
|
||||
at = region.markup_end;
|
||||
}
|
||||
slices.push(&source[at..]);
|
||||
|
||||
let mut found = HashSet::new();
|
||||
for slice in slices {
|
||||
let bytes = slice.as_bytes();
|
||||
let (mut in_tag, mut quote, mut server_block) = (false, None::<u8>, false);
|
||||
let mut i = 0;
|
||||
while i < bytes.len() {
|
||||
let b = bytes[i];
|
||||
if quote.is_none() && !server_block && bytes[i..].starts_with(b"<%") {
|
||||
server_block = true;
|
||||
} else if server_block && bytes[i..].starts_with(b"%>") {
|
||||
server_block = false;
|
||||
} else if !server_block && quote == Some(b) {
|
||||
quote = None;
|
||||
} else if in_tag && !server_block && quote.is_none() && (b == b'"' || b == b'\'') {
|
||||
quote = Some(b);
|
||||
} else if !server_block && quote.is_none() && b == b'<' {
|
||||
in_tag = bytes
|
||||
.get(i + 1)
|
||||
.is_some_and(|n| n.is_ascii_alphabetic() || *n == b'/');
|
||||
} else if !server_block && quote.is_none() && b == b'>' {
|
||||
in_tag = false;
|
||||
} else if is_identifier_start(b) && (i == 0 || !is_identifier_byte(bytes[i - 1])) {
|
||||
let len = bytes[i..]
|
||||
.iter()
|
||||
.take_while(|&&c| is_identifier_byte(c))
|
||||
.count();
|
||||
let after_at = i > 0 && bytes[i - 1] == b'@';
|
||||
if quote.is_some() || server_block || after_at {
|
||||
found.insert(slice[i..i + len].to_ascii_lowercase());
|
||||
}
|
||||
i += len;
|
||||
continue;
|
||||
}
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
found
|
||||
}
|
||||
|
||||
/// The index of the `}` that closes the `{` at `open`, skipping C# strings,
|
||||
/// characters and comments.
|
||||
fn matching_brace(bytes: &[u8], open: usize) -> Option<usize> {
|
||||
let mut depth = 0usize;
|
||||
let mut i = open;
|
||||
while i < bytes.len() {
|
||||
match bytes[i] {
|
||||
b'{' => depth += 1,
|
||||
b'}' => {
|
||||
depth -= 1;
|
||||
if depth == 0 {
|
||||
return Some(i);
|
||||
}
|
||||
}
|
||||
b'/' if bytes.get(i + 1) == Some(&b'/') => {
|
||||
i = find(bytes, i, b"\n").unwrap_or(bytes.len());
|
||||
continue;
|
||||
}
|
||||
b'/' if bytes.get(i + 1) == Some(&b'*') => {
|
||||
i = find(bytes, i + 2, b"*/").map_or(bytes.len(), |end| end + 2);
|
||||
continue;
|
||||
}
|
||||
b'"' if bytes[i..].starts_with(b"\"\"\"") => {
|
||||
i = find(bytes, i + 3, b"\"\"\"").map_or(bytes.len(), |end| end + 3);
|
||||
continue;
|
||||
}
|
||||
b'"' => {
|
||||
let verbatim = i > 0
|
||||
&& (bytes[i - 1] == b'@'
|
||||
|| (bytes[i - 1] == b'$' && i > 1 && bytes[i - 2] == b'@'));
|
||||
i = string_end(bytes, i + 1, verbatim);
|
||||
continue;
|
||||
}
|
||||
b'\'' => {
|
||||
// `'x'`, `'\''`: skip the escaped character, then to the quote.
|
||||
let start = i + 1 + usize::from(bytes.get(i + 1) == Some(&b'\\'));
|
||||
i = find(bytes, start + 1, b"'").map_or(bytes.len(), |end| end + 1);
|
||||
continue;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
i += 1;
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// The index after the `"` that ends a string starting at `from`: a
|
||||
/// verbatim string (`@"…"`) escapes a quote by doubling it, a regular one
|
||||
/// with a backslash and ends at the line's end at the latest.
|
||||
fn string_end(bytes: &[u8], from: usize, verbatim: bool) -> usize {
|
||||
let mut i = from;
|
||||
while i < bytes.len() {
|
||||
match bytes[i] {
|
||||
b'"' if verbatim && bytes.get(i + 1) == Some(&b'"') => i += 2,
|
||||
b'"' => return i + 1,
|
||||
b'\\' if !verbatim => i += 2,
|
||||
b'\n' if !verbatim => return i,
|
||||
_ => i += 1,
|
||||
}
|
||||
}
|
||||
bytes.len()
|
||||
}
|
||||
|
||||
/// The first index of `needle` in `bytes` at or after `from`.
|
||||
fn find(bytes: &[u8], from: usize, needle: &[u8]) -> Option<usize> {
|
||||
bytes
|
||||
.get(from..)?
|
||||
.windows(needle.len())
|
||||
.position(|w| w == needle)
|
||||
.map(|at| from + at)
|
||||
}
|
||||
|
||||
fn is_identifier_start(b: u8) -> bool {
|
||||
b.is_ascii_alphabetic() || b == b'_'
|
||||
}
|
||||
|
||||
fn is_identifier_byte(b: u8) -> bool {
|
||||
b.is_ascii_alphanumeric() || b == b'_'
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use compliance_core::models::graph::CodeNode;
|
||||
|
||||
const COUNTER: &str = r#"@page "/counter"
|
||||
@* @code { void Commented() { } } *@
|
||||
<h1>Counter: @currentCount</h1>
|
||||
<p>Save your work</p>
|
||||
<button class="btn" @onclick="IncrementCount">Click me</button>
|
||||
|
||||
@code {
|
||||
private int currentCount = 0;
|
||||
private string label = "}";
|
||||
|
||||
protected override void OnInitialized() { Reset(); }
|
||||
|
||||
private void IncrementCount()
|
||||
{
|
||||
// a brace in a comment: }
|
||||
currentCount++;
|
||||
Log(@"C:\path ""quoted"" }");
|
||||
}
|
||||
|
||||
private void Reset() { currentCount = 0; }
|
||||
|
||||
private void Save() { }
|
||||
}
|
||||
"#;
|
||||
|
||||
const DEFAULT_ASPX: &str = r#"<%@ Page Language="VB" AutoEventWireup="true" Inherits="Plant.DefaultPage" %>
|
||||
<html>
|
||||
<body>
|
||||
<script runat="server">
|
||||
Protected Sub Page_Load(sender As Object, e As EventArgs)
|
||||
Bind()
|
||||
End Sub
|
||||
|
||||
Protected Sub BtnSave_Click(sender As Object, e As EventArgs)
|
||||
End Sub
|
||||
|
||||
Private Sub Bind()
|
||||
End Sub
|
||||
</script>
|
||||
<script type="text/javascript">function notServer() { }</script>
|
||||
<form runat="server">
|
||||
<asp:Button ID="BtnSave" runat="server" OnClick="BtnSave_Click" Text="Save" />
|
||||
<%# Title() %>
|
||||
</form>
|
||||
</body>
|
||||
</html>
|
||||
"#;
|
||||
|
||||
fn parse(path: &str, source: &str) -> ParseOutput {
|
||||
MarkupParser::new()
|
||||
.parse_file(Path::new(path), source, "repo", "build")
|
||||
.expect("markup parses")
|
||||
}
|
||||
|
||||
fn node<'a>(out: &'a ParseOutput, qualified: &str) -> &'a CodeNode {
|
||||
out.nodes
|
||||
.iter()
|
||||
.find(|n| n.qualified_name == qualified)
|
||||
.unwrap_or_else(|| panic!("no node {qualified}: {:?}", out.nodes))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_razor_components_code_block_becomes_its_class() {
|
||||
let out = parse("Pages/Counter.razor", COUNTER);
|
||||
let class = node(&out, "Pages/Counter.razor::Counter");
|
||||
assert!(matches!(class.kind, CodeNodeKind::Class));
|
||||
assert_eq!(class.language, "csharp");
|
||||
// Lines are the markup file's lines.
|
||||
let increment = node(&out, "Pages/Counter.razor::Counter.IncrementCount");
|
||||
assert_eq!((increment.start_line, increment.end_line), (13, 18));
|
||||
// Braces in strings and comments don't end the block early.
|
||||
node(&out, "Pages/Counter.razor::Counter.Save");
|
||||
// A commented-out block is not code.
|
||||
assert!(!out.nodes.iter().any(|n| n.name == "Commented"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn methods_the_markup_or_the_framework_calls_are_entry_points() {
|
||||
let out = parse("Pages/Counter.razor", COUNTER);
|
||||
let entry =
|
||||
|name: &str| node(&out, &format!("Pages/Counter.razor::Counter.{name}")).is_entry_point;
|
||||
assert!(entry("IncrementCount"), "wired by @onclick");
|
||||
assert!(entry("OnInitialized"), "a lifecycle hook");
|
||||
assert!(!entry("Reset"), "called from code only");
|
||||
// "Save" is only text between tags.
|
||||
assert!(!entry("Save"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_web_forms_page_in_vb_reads_its_server_script() {
|
||||
let out = parse("Default.aspx", DEFAULT_ASPX);
|
||||
let page = node(&out, "Default.aspx::DefaultPage");
|
||||
assert_eq!(page.language, "vb");
|
||||
let load = node(&out, "Default.aspx::DefaultPage.Page_Load");
|
||||
assert_eq!((load.start_line, load.end_line), (5, 7));
|
||||
assert!(load.is_entry_point, "AutoEventWireup");
|
||||
assert!(
|
||||
node(&out, "Default.aspx::DefaultPage.BtnSave_Click").is_entry_point,
|
||||
"OnClick"
|
||||
);
|
||||
assert!(!node(&out, "Default.aspx::DefaultPage.Bind").is_entry_point);
|
||||
// The client-side script is not server code.
|
||||
assert!(!out.nodes.iter().any(|n| n.name == "notServer"));
|
||||
assert!(out
|
||||
.edges
|
||||
.iter()
|
||||
.any(|e| e.source == "Default.aspx::DefaultPage.Page_Load" && e.target == "Bind"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_web_forms_control_without_a_language_is_csharp() {
|
||||
let source = "<%@ Control %>\n<script runat=server>\n protected void Page_Load(object s, EventArgs e) { Go(); }\n void Go() { }\n</script>\n";
|
||||
let out = parse("Menu.ascx", source);
|
||||
let load = node(&out, "Menu.ascx::Menu.Page_Load");
|
||||
assert_eq!(load.language, "csharp");
|
||||
assert_eq!(load.start_line, 3);
|
||||
assert!(out
|
||||
.edges
|
||||
.iter()
|
||||
.any(|e| e.source == "Menu.ascx::Menu.Page_Load" && e.target == "Go"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_directive_names_the_class_and_language() {
|
||||
let (language, class) = web_forms_directive(
|
||||
"<%@ Master language='vb' Inherits=\"Plant._Site, Plant\" CodeFileBaseClass=\"X\" %>",
|
||||
);
|
||||
assert_eq!(language, CodeLanguage::Vb);
|
||||
assert_eq!(class.as_deref(), Some("_Site"));
|
||||
// `CodeFileBaseClass` doesn't count as `Inherits`, nor a later
|
||||
// directive as the page's.
|
||||
let (language, class) = web_forms_directive(
|
||||
"<%@ Register Src=\"a.ascx\" %><%@ Page CodeFileBaseClass=\"Base\" %>",
|
||||
);
|
||||
assert_eq!(language, CodeLanguage::CSharp);
|
||||
assert_eq!(class, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_view_without_code_is_a_file_only() {
|
||||
let out = parse(
|
||||
"Views/Home/Index.cshtml",
|
||||
"@model HomeVm\n<h1>@Model.Title</h1>\n",
|
||||
);
|
||||
assert_eq!(out.nodes.len(), 1);
|
||||
assert!(matches!(out.nodes[0].kind, CodeNodeKind::File));
|
||||
assert_eq!(out.nodes[0].end_line, 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_registry_hands_markup_files_to_this_parser() {
|
||||
let registry = super::super::registry::ParserRegistry::new();
|
||||
for ext in ["razor", "cshtml", "aspx", "ascx", "master"] {
|
||||
assert!(registry.supports_extension(ext), "{ext}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_class_name_is_an_identifier() {
|
||||
assert_eq!(class_name(Path::new("Pages/Counter.razor")), "Counter");
|
||||
assert_eq!(class_name(Path::new("_Layout.cshtml")), "_Layout");
|
||||
assert_eq!(class_name(Path::new("404-page.aspx")), "_404_page");
|
||||
}
|
||||
}
|
||||
@@ -2,9 +2,11 @@ pub mod c;
|
||||
mod common;
|
||||
pub mod csharp;
|
||||
pub mod javascript;
|
||||
pub mod markup;
|
||||
pub mod python;
|
||||
pub mod registry;
|
||||
pub mod rust_parser;
|
||||
pub mod typescript;
|
||||
pub mod vb;
|
||||
|
||||
pub use common::FileGraph;
|
||||
Loaded 100 of 115 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user