feat(cve): group CVEs by package with one VEX decision per group (#949) #959

Merged
sharang merged 1 commits from feat/949-cve-groups into main 2026-11-10 14:31:34 +00:00
11 changed files with 1253 additions and 110 deletions

No files matched your search

+192 -18
View File
@@ -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() {
+9
View File
@@ -117,6 +117,15 @@ pub fn build_router() -> Router {
.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),
)
.route(
"/api/v1/targets/{id}/evidence-pack",
get(handlers::evidence::evidence_pack),
+432
View File
@@ -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);
}
}
+1
View File
@@ -3,6 +3,7 @@ pub mod config;
pub mod control_check;
pub mod csaf_docs;
pub mod csaf_ingest;
pub mod cve_groups;
pub mod db;
pub mod encoding;
pub mod enisa_docs;
+42
View File
@@ -5176,6 +5176,48 @@ tbody tr:last-child td {
gap: 8px;
}
/* CVEs grouped by component (#949). */
.vex-view-toggle {
margin-bottom: 12px;
}
.vex-groups {
display: grid;
gap: 10px;
}
.vex-group {
border: 1px solid var(--border);
border-radius: var(--radius-lg);
padding: 10px 12px;
background: var(--bg-card);
}
.vex-group-head {
display: flex;
flex-wrap: wrap;
gap: 8px 10px;
align-items: center;
}
.vex-group-title {
flex: 1 1 320px;
min-width: 0;
font-size: 13.5px;
overflow-wrap: anywhere;
}
.vex-group-actions {
display: flex;
flex-wrap: wrap;
gap: 8px;
margin-left: auto;
}
.vex-group .table-wrapper {
margin-top: 10px;
}
@media (max-width: 1000px) {
.target-summary,
.target-summary:has(.target-graph),
+271 -88
View File
@@ -1,13 +1,17 @@
//! 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::models::{CveAlert, VexAssessment, VexJustification, VexStatus};
use compliance_core::vex_docs::status_of;
use crate::components::no_access::use_can_write;
@@ -16,9 +20,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.
@@ -107,7 +111,6 @@ fn stated_by(alert: &CveAlert, lang: Lang) -> String {
#[component]
pub fn VexPanel(target_id: String) -> 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 +123,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",
@@ -137,81 +152,226 @@ pub fn VexPanel(target_id: String) -> Element {
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)} } },
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]
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 +380,7 @@ pub fn VexPanel(target_id: String) -> Element {
}
}
}
},
}
}
}
}
@@ -411,14 +571,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 +628,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 +674,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);
+184
View File
@@ -2822,6 +2822,8 @@ pub mod manual {
/// The CRA compliance view of a target.
pub mod vex {
use super::Text;
use crate::i18n::Lang;
use compliance_core::cve_groups::{CveGroup, CveSeverity};
pub const TITLE: Text = Text {
de: "Schwachstellen und VEX",
@@ -3026,6 +3028,188 @@ pub mod vex {
de: "Die VEX-Aussage wurde nicht gespeichert",
en: "The VEX statement was not saved",
};
// The CVEs grouped by component (#949).
pub const VIEW_GROUPED: Text = Text {
de: "Gruppiert",
en: "Grouped",
};
pub const VIEW_SINGLE: Text = Text {
de: "Einzeln",
en: "One by one",
};
pub const ALL_DECIDED: Text = Text {
de: "Alle Schwachstellen sind bewertet oder behoben. Unter \"Einzeln\" stehen sie mit \
ihren Aussagen.",
en: "Every vulnerability is assessed or fixed. \"One by one\" lists them with their \
statements.",
};
pub const SHOW_CVES: Text = Text {
de: "CVEs anzeigen",
en: "Show CVEs",
};
pub const HIDE_CVES: Text = Text {
de: "CVEs ausblenden",
en: "Hide CVEs",
};
pub const KEV_HINT: Text = Text {
de: "Im KEV-Katalog der CISA: wird aktiv ausgenutzt",
en: "In CISA's KEV catalog: exploited in the wild",
};
pub const EPSS_HINT: Text = Text {
de: "Höchste EPSS-Wahrscheinlichkeit einer Ausnutzung in den nächsten 30 Tagen (FIRST)",
en: "Highest EPSS probability of exploitation in the next 30 days (FIRST)",
};
/// A severity as a word inside a sentence (`hoch`).
fn severity_word(severity: CveSeverity) -> Text {
match severity {
CveSeverity::Critical => Text {
de: "kritisch",
en: "critical",
},
CveSeverity::High => Text {
de: "hoch",
en: "high",
},
CveSeverity::Medium => Text {
de: "mittel",
en: "medium",
},
CveSeverity::Low => Text {
de: "niedrig",
en: "low",
},
CveSeverity::Info => Text {
de: "info",
en: "info",
},
}
}
/// What one update of a group's component does: `vite 5.4.21 → 8.3.3
/// behebt 9 CVEs (1 hoch, 1 niedrig, 7 info)`; `behebt 7 von 9 CVEs` when
/// some name no fix, `vite 5.4.21: 9 CVEs, kein Fix bekannt (…)` when none
/// does.
pub fn group_headline(group: &CveGroup, lang: Lang) -> String {
let open = group.cve_ids.len();
let cves = if open == 1 { "CVE" } else { "CVEs" };
let counts: Vec<String> = group
.counts
.by_severity()
.into_iter()
.filter(|(_, count)| *count > 0)
.map(|(severity, count)| format!("{count} {}", severity_word(severity).get(lang)))
.collect();
let component = format!("{} {}", group.key.package, group.key.version);
let fixable = group.fixable;
let effect = match (group.fix_version.as_deref(), lang) {
(Some(fix), Lang::De) if fixable == open => {
format!("{component} → {fix} behebt {open} {cves}")
}
(Some(fix), Lang::De) => {
format!("{component} → {fix} behebt {fixable} von {open} {cves}")
}
(Some(fix), Lang::En) if fixable == open => {
format!("{component} → {fix} fixes {open} {cves}")
}
(Some(fix), Lang::En) => {
format!("{component} → {fix} fixes {fixable} of {open} {cves}")
}
(None, Lang::De) => format!("{component}: {open} {cves}, kein Fix bekannt"),
(None, Lang::En) => format!("{component}: {open} {cves}, no fix known"),
};
format!("{effect} ({})", counts.join(", "))
}
/// The group decision's button: `Nicht betroffen (alle 9)`.
pub fn not_affected_all(count: usize, lang: Lang) -> String {
match lang {
Lang::De => format!("Nicht betroffen (alle {count})"),
Lang::En => format!("Not affected (all {count})"),
}
}
/// The highest EPSS score of a group as a whole percentage: `EPSS 70 %`,
/// `EPSS < 1 %` below one percent.
pub fn epss_label(score: f64, lang: Lang) -> String {
let percent = score * 100.0;
let space = match lang {
Lang::De => " ",
Lang::En => "",
};
if percent < 1.0 {
format!("EPSS <{space}1{space}%")
} else {
format!("EPSS {}{space}%", percent.round())
}
}
#[cfg(test)]
mod group_tests {
use super::*;
use compliance_core::cve_groups::{PackageKey, SeverityCounts};
fn vite(fix: Option<&str>, fixable: usize) -> CveGroup {
CveGroup {
key: PackageKey {
package: "vite".into(),
version: "5.4.21".into(),
purl: None,
},
fix_version: fix.map(String::from),
fixable,
counts: SeverityCounts {
high: 1,
low: 1,
info: 7,
..SeverityCounts::default()
},
kev: false,
epss_max: None,
cve_ids: (1..=9).map(|n| format!("CVE-2025-000{n}")).collect(),
alert_ids: Vec::new(),
}
}
#[test]
fn a_group_says_what_one_update_fixes() {
assert_eq!(
group_headline(&vite(Some("8.3.3"), 9), Lang::De),
"vite 5.4.21 → 8.3.3 behebt 9 CVEs (1 hoch, 1 niedrig, 7 info)"
);
assert_eq!(
group_headline(&vite(Some("8.3.3"), 9), Lang::En),
"vite 5.4.21 → 8.3.3 fixes 9 CVEs (1 high, 1 low, 7 info)"
);
assert_eq!(
group_headline(&vite(Some("8.3.3"), 7), Lang::De),
"vite 5.4.21 → 8.3.3 behebt 7 von 9 CVEs (1 hoch, 1 niedrig, 7 info)"
);
assert_eq!(
group_headline(&vite(None, 0), Lang::En),
"vite 5.4.21: 9 CVEs, no fix known (1 high, 1 low, 7 info)"
);
let mut one = vite(Some("5.4.22"), 1);
one.cve_ids.truncate(1);
one.counts = SeverityCounts {
critical: 1,
..SeverityCounts::default()
};
assert_eq!(
group_headline(&one, Lang::De),
"vite 5.4.21 → 5.4.22 behebt 1 CVE (1 kritisch)"
);
}
#[test]
fn the_group_labels_read_like_the_language() {
assert_eq!(not_affected_all(9, Lang::De), "Nicht betroffen (alle 9)");
assert_eq!(not_affected_all(9, Lang::En), "Not affected (all 9)");
assert_eq!(epss_label(0.7012, Lang::De), "EPSS 70 %");
assert_eq!(epss_label(0.004, Lang::De), "EPSS < 1 %");
assert_eq!(epss_label(0.004, Lang::En), "EPSS <1%");
}
}
}
pub mod compliance {
@@ -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 {
+6
View File
@@ -424,6 +424,12 @@ differently:
API: `GET /api/v1/targets/{id}/cves` lists the alerts with their statements,
`PATCH /api/v1/cves/{id}/vex` sets one
(`{"status": "not_affected", "justification": "…", "impact_statement": "…"}`),
`GET /api/v1/targets/{id}/cve-groups` lists the open alerts grouped by component
(`package`, `version`, `purl`, `fix_version`, `fixable`, `counts` per severity,
`kev`, `epss_max`, `cve_ids`, `alert_ids`), and
`PATCH /api/v1/targets/{id}/cve-groups/vex` states one status on every open
alert of a component (the group's `package`, `version` and `purl` beside the
statement's fields; one statement per alert, validated as a single one),
`GET /api/v1/targets/{id}/vex?format=openvex|cyclonedx` downloads the document,
`GET /api/v1/targets/{id}/csaf?namespace=<publisher URL>&lang=de|en` the same
statements as a CSAF 2.0 VEX advisory (a TLP:AMBER draft; see
+14 -2
View File
@@ -11,9 +11,14 @@ vulnerabilities and inform users; VEX is the usual format for it.
## Where
On a target's page, section **Vulnerabilities and VEX**. The table shows each
On a target's page, section **Vulnerabilities and VEX**. The **Grouped** view
(the default) gathers the open vulnerabilities per component and version and
says what an update does, e.g. "vite 5.4.21 → 8.3.3 fixes 9 CVEs (1 high,
1 low, 7 info)": the highest version the advisories name as fixed, and the
vulnerabilities per severity. **KEV** and the highest EPSS score stand beside
it; **Show CVEs** expands the rows. The **One by one** view shows each
vulnerability with its component, severity, status and who made the
statement.
statement, including those already assessed or fixed.
## Statuses
@@ -39,6 +44,13 @@ Justifications for "Not affected":
disabled and a note says what is missing.
3. **Save**. The "Stated by" column shows your name.
For every open vulnerability of a component at once: click **Not affected
(all N)** on the group, give a justification or a statement, **Save**. Each
vulnerability of the group gets the same statement, as if you had assessed it
on its own; the exports and the closing of tickets behave the same. Those
stated "Not affected" or "Fixed" are not in the group and keep their
statements; an "Affected" or "Under investigation" statement is replaced.
Read-only roles see the statements but cannot assess.
## What a scan changes
+16 -2
View File
@@ -13,8 +13,14 @@ Format dafür.
## Wo
Auf der Seite eines Prüfobjekts, Abschnitt **Schwachstellen und VEX**. Die
Tabelle zeigt jede Schwachstelle mit Komponente, Schweregrad, Status und wer
die Aussage gemacht hat.
Ansicht **Gruppiert** (Standard) fasst die offenen Schwachstellen je
Komponente und Version zusammen und sagt, was ein Update bewirkt, z. B.
„vite 5.4.21 → 8.3.3 behebt 9 CVEs (1 hoch, 1 niedrig, 7 info)“: die
höchste Version, die die Advisories als behoben nennen, und die Schwachstellen
je Schweregrad. **KEV** und der höchste EPSS-Wert stehen daneben; **CVEs
anzeigen** klappt die Zeilen auf. Die Ansicht **Einzeln** zeigt jede
Schwachstelle mit Komponente, Schweregrad, Status und wer die Aussage gemacht
hat, auch die bereits bewerteten und behobenen.
## Status
@@ -40,6 +46,14 @@ Begründungen für „Nicht betroffen“:
**Speichern** gesperrt und ein Hinweis sagt, was fehlt.
3. **Speichern**. Die Spalte „Aussage von“ zeigt Ihren Namen.
Für alle offenen Schwachstellen einer Komponente auf einmal: in der Gruppe auf
**Nicht betroffen (alle N)** klicken, Begründung oder Freitext angeben,
**Speichern**. Jede Schwachstelle der Gruppe erhält dieselbe Aussage, als
hätten Sie sie einzeln bewertet; Exporte und das Schließen der Tickets
verhalten sich gleich. Als „Nicht betroffen“ oder „Behoben“ bewertete
Schwachstellen gehören nicht zur Gruppe und behalten ihre Aussage; eine
Aussage „Betroffen“ oder „In Prüfung“ wird ersetzt.
Rollen mit Lesezugriff sehen die Aussagen, können aber nicht bewerten.
## Was die Prüfung ändert