feat(scan): record which components each scan added, updated or removed (#974) (#975)
CI / Check (push) Skipped
CI / Agent integration (push) Skipped
CI / Detect Changes (push) Successful in 4s
CI / Deploy MCP (push) Successful in 58s
CI / Deploy Docs (push) Successful in 1m29s
CI / Deploy Dashboard (push) Successful in 6m12s
CI / Deploy Agent (push) Successful in 8m13s
CI / Check (push) Skipped
CI / Agent integration (push) Skipped
CI / Detect Changes (push) Successful in 4s
CI / Deploy MCP (push) Successful in 58s
CI / Deploy Docs (push) Successful in 1m29s
CI / Deploy Dashboard (push) Successful in 6m12s
CI / Deploy Agent (push) Successful in 8m13s
Before a stage replaces its part of a target's SBOM (the code SBOM, the CODESYS libraries, the firmware components), the entries it replaces are compared with the new ones and the changes are added to the scan run (`component_changes`, at most 5000; `None` on runs from before). A component is its package manager and name; one version before and one after is an update, otherwise each new version an addition and each gone one a removal. The Verlauf API joins them with the scan's CVEs: a new CVE goes with the component now at its version, a gone one with the component that was at its version, and what no change explains is an advisory row. The scan's drill-down shows the mockup's table (neu / aktualisiert / entfernt / neue Advisory, version before → after, CVEs +n −m) above the CVE list; scans from before say the components were not recorded. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit was merged in pull request #975.
This commit is contained in:
1 parent
31886d226c
commit
f5697ff21d
11 files changed
+784
-22
No files matched your search
@@ -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();
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -9,6 +9,7 @@
|
||||
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;
|
||||
@@ -30,17 +31,20 @@ async fn mongo_reachable() -> bool {
|
||||
.is_ok()
|
||||
}
|
||||
|
||||
/// Store a run of the target that started `start` and ended `end`.
|
||||
/// 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
|
||||
@@ -102,9 +106,24 @@ async fn each_scan_shows_the_cves_it_found_new_and_gone() {
|
||||
// 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))).await;
|
||||
run(&db, ScanRunStatus::Failed, hour(24), Some(hour(25))).await;
|
||||
run(&db, ScanRunStatus::Completed, hour(48), Some(hour(49))).await;
|
||||
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;
|
||||
@@ -126,6 +145,26 @@ async fn each_scan_shows_the_cves_it_found_new_and_gone() {
|
||||
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.
|
||||
|
||||
@@ -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")
|
||||
]
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
pub mod build_info;
|
||||
pub mod component_changes;
|
||||
pub mod config;
|
||||
pub mod control_check;
|
||||
pub mod csaf_docs;
|
||||
|
||||
@@ -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,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -15,9 +15,13 @@
|
||||
//! (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};
|
||||
|
||||
@@ -66,6 +70,108 @@ pub struct ScanChange {
|
||||
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
|
||||
@@ -113,6 +219,12 @@ pub fn changes(
|
||||
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(),
|
||||
@@ -122,6 +234,7 @@ pub fn changes(
|
||||
baseline,
|
||||
new_cves,
|
||||
gone_cves,
|
||||
components,
|
||||
});
|
||||
}
|
||||
out
|
||||
@@ -211,6 +324,61 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[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))];
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
|
||||
use chrono::{DateTime, Utc};
|
||||
use compliance_core::models::ScanRunStatus;
|
||||
use compliance_core::scan_changes::{CveChange, ScanChange};
|
||||
use compliance_core::scan_changes::{ComponentRow, ComponentRowKind, CveChange, ScanChange};
|
||||
use dioxus::prelude::*;
|
||||
|
||||
use crate::app::Route;
|
||||
@@ -185,7 +185,13 @@ fn ScanDetail(target_id: String, change: ScanChange, back: Route) -> Element {
|
||||
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() {
|
||||
@@ -228,7 +234,76 @@ fn ScanDetail(target_id: String, change: ScanChange, back: Route) -> Element {
|
||||
{tx::new_findings(change.new_findings, lang)}
|
||||
}
|
||||
}
|
||||
p { class: "target-muted sh-note", {tx::COMPONENTS_NOTE.get(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}" }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -245,6 +320,63 @@ mod tests {
|
||||
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();
|
||||
|
||||
@@ -6821,10 +6821,42 @@ pub mod scan_history {
|
||||
en: "The history could not be loaded.",
|
||||
};
|
||||
pub const COMPONENTS_NOTE: Text = Text {
|
||||
de: "Welche Komponenten ein Scan hinzugefügt, aktualisiert oder entfernt hat, \
|
||||
speichert Prüfwerk noch nicht; die CVEs oben zeigen, wo sich etwas bewegt hat.",
|
||||
en: "Prüfwerk does not store yet which components a scan added, updated or removed; \
|
||||
the CVEs above show where something moved.",
|
||||
de: "Welche Komponenten dieser Scan hinzugefügt, aktualisiert oder entfernt hat, ist \
|
||||
nicht erfasst: Er lief, bevor Prüfwerk das festhielt.",
|
||||
en: "Which components this scan added, updated or removed was not recorded: it ran \
|
||||
before Prüfwerk kept track of it.",
|
||||
};
|
||||
pub const COMPONENTS_TITLE: Text = Text {
|
||||
de: "Komponenten",
|
||||
en: "Components",
|
||||
};
|
||||
pub const NO_COMPONENT_CHANGE: Text = Text {
|
||||
de: "Keine Komponente hinzugefügt, aktualisiert oder entfernt.",
|
||||
en: "No component added, updated or removed.",
|
||||
};
|
||||
pub const ADDED: Text = Text {
|
||||
de: "neu",
|
||||
en: "added",
|
||||
};
|
||||
pub const UPDATED: Text = Text {
|
||||
de: "aktualisiert",
|
||||
en: "updated",
|
||||
};
|
||||
pub const REMOVED: Text = Text {
|
||||
de: "entfernt",
|
||||
en: "removed",
|
||||
};
|
||||
pub const NEW_ADVISORY: Text = Text {
|
||||
de: "neue Advisory",
|
||||
en: "new advisory",
|
||||
};
|
||||
pub const ADVISORY_GONE: Text = Text {
|
||||
de: "Advisory entfällt",
|
||||
en: "advisory withdrawn",
|
||||
};
|
||||
pub const ADVISORIES_CHANGED: Text = Text {
|
||||
de: "Advisories geändert",
|
||||
en: "advisories changed",
|
||||
};
|
||||
|
||||
/// The drill's heading: `Scan vom 10.11.`.
|
||||
|
||||
@@ -229,7 +229,7 @@ opens the same view.
|
||||
| **Komponenten** (Components) | The updates that remove the most CVEs, and the components per ecosystem | The update's CVEs, or the **Stückliste** filtered to the ecosystem |
|
||||
| **Lizenzen** (Licences) | The components per licence group | The licences of that group and the components using each |
|
||||
| **CRA Annex I** | The 40 requirements as tiles, coloured by state and marked: **!** findings assigned, **?** not checked, **~** partly checked, **OK** checked without findings, **–** not checkable in code | The requirement with its state, the findings against it and the reason |
|
||||
| **Verlauf** (History) | Per scan, the CVEs it found new above the line and those it found gone below it, and the scan's status | What the scan changed: each CVE new or gone, with component, version and severity |
|
||||
| **Verlauf** (History) | Per scan, the CVEs it found new above the line and those it found gone below it, and the scan's status | What the scan changed: the components it added, updated or removed with the CVEs each brought and took, and each CVE new or gone with component, version and severity |
|
||||
|
||||
The figure beside **CRA Annex I** counts the requirements checked without a
|
||||
finding, of all 40.
|
||||
@@ -240,8 +240,15 @@ gone in the window a complete scan no longer found it. The target's first
|
||||
complete scan is marked **Start**; what it found is the starting point, not a
|
||||
change. A scan that did not complete changes nothing, so CVEs found in the
|
||||
meantime (by the daily CVE check, say) count for the next complete scan.
|
||||
Prüfwerk does not store yet which components each scan added, updated or
|
||||
removed.
|
||||
|
||||
A scan's components are compared with the SBOM stored before it: one version
|
||||
of a component before and another after is **aktualisiert** (updated), a new
|
||||
component or version **neu**, one no longer there **entfernt** (removed). A
|
||||
new CVE goes with the component now at its version, a gone one with the
|
||||
component that was at its version. A CVE that came or went while its
|
||||
component stayed the same reads **neue Advisory** or **Advisory entfällt**.
|
||||
At most 5000 component changes are kept per scan. Scans from before
|
||||
Prüfwerk recorded this show their CVEs only and say so.
|
||||
|
||||
## Editing a Target
|
||||
|
||||
|
||||
Reference in new issue
Block a user