Files
pruefwerk/compliance-core/src/csaf_docs.rs
T
sharangandClaude Opus 5.5 87b1e281ed
CI / Check (push) Skipped
CI / Agent integration (push) Skipped
CI / Detect Changes (push) Successful in 3s
CI / Deploy Docs (push) Successful in 1m19s
CI / Deploy MCP (push) Successful in 2m42s
CI / Deploy Dashboard (push) Successful in 6m14s
CI / Deploy Agent (push) Successful in 8m42s
fix(vex): a CVE a scan no longer finds is not stated fixed (#994) (#1015)
A scan never states VEX `fixed`. When a scan stops finding a CVE, its tracker issue stays open and gets one comment; a person closes it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Q9inRcu428A2iNjDHPEAT9
2026-11-27 22:23:03 +00:00

385 lines
14 KiB
Rust

//! A CSAF 2.0 VEX advisory for a target (#498): the same statements as the
//! OpenVEX and CycloneDX VEX documents ([`crate::vex_docs`]) in the format
//! CERTs and the CRA's vulnerability reporting use. Always a draft: the
//! manufacturer checks the publisher and the statements before releasing it.
//!
//! The product tree has the target as product and every affected component
//! as `default_component_of` it; the statuses name the component in the
//! product. A `not_affected` carries its justification as a flag (CSAF's flag
//! labels are OpenVEX's justifications) and its impact statement as a threat;
//! an `affected` its action statement as a remediation.
use chrono::{DateTime, Utc};
use crate::models::{advisory_source, is_cve, VexStatus};
use crate::sbom_docs::product_ref;
use crate::vex_docs::{component_id, rfc3339, statements, status_of, Statement, VexInput};
/// The note every draft carries.
pub const DRAFT_NOTE: &str = "Draft, not published: check publisher and statements before release.";
/// The product id of the target in the product tree.
const PRODUCT_ID: &str = "PRODUCT";
/// The tracking id of the advisory for `subject` on `at`
/// (`pruefwerk-vex-pump-remote-20261006`): lowercase letters, digits and
/// dashes, so the file name CSAF derives from it is the id itself.
pub fn tracking_id(subject: &str, at: DateTime<Utc>) -> String {
let mut slug = String::with_capacity(subject.len());
for c in subject.chars() {
if c.is_ascii_alphanumeric() {
slug.push(c.to_ascii_lowercase());
} else if !slug.ends_with('-') {
slug.push('-');
}
}
format!(
"pruefwerk-vex-{}-{}",
slug.trim_matches('-'),
at.format("%Y%m%d")
)
}
/// The publisher namespace of a draft whose publisher gave none: a URL that
/// cannot resolve (`example.invalid`), so it is plainly to be replaced before
/// release.
pub fn placeholder_namespace(publisher: &str) -> String {
let slug: String = publisher
.chars()
.map(|c| {
if c.is_ascii_alphanumeric() {
c.to_ascii_lowercase()
} else {
'-'
}
})
.collect();
format!("https://example.invalid/{}", slug.trim_matches('-'))
}
/// The file name of an advisory with `tracking_id`, as CSAF 2.0 §5.1 derives
/// it.
pub fn filename(tracking_id: &str) -> String {
let name: String = tracking_id
.to_lowercase()
.chars()
.map(|c| {
if c.is_ascii_alphanumeric() || c == '+' || c == '-' {
c
} else {
'_'
}
})
.collect();
format!("{name}.json")
}
/// The components the alerts are about, each once: `(id, name, purl)`.
fn components(input: &VexInput<'_>) -> Vec<(String, String, String)> {
let mut out: Vec<(String, String, String)> = Vec::new();
for alert in input.alerts {
let purl = component_id(alert, input.sbom);
if out.iter().all(|(.., p)| *p != purl) {
let name = format!("{} {}", alert.affected_package, alert.affected_version);
out.push((format!("C{}", out.len() + 1), name, purl));
}
}
out
}
/// The product id of a component in the product.
fn in_product(component: &str) -> String {
format!("{component}-IN-{PRODUCT_ID}")
}
/// The product tree: the target, its components, and each component as
/// part of the target.
fn product_tree(
input: &VexInput<'_>,
components: &[(String, String, String)],
) -> serde_json::Value {
let mut names = vec![serde_json::json!({
"name": input.subject,
"product_id": PRODUCT_ID,
"product_identification_helper": { "purl": product_ref(input.subject) },
})];
let mut relationships = Vec::with_capacity(components.len());
for (id, name, purl) in components {
let mut product = serde_json::json!({ "name": name, "product_id": id });
if purl.starts_with("pkg:") {
product["product_identification_helper"] = serde_json::json!({ "purl": purl });
}
names.push(product);
relationships.push(serde_json::json!({
"category": "default_component_of",
"product_reference": id,
"relates_to_product_reference": PRODUCT_ID,
"full_product_name": {
"name": format!("{name} in {}", input.subject),
"product_id": in_product(id),
},
}));
}
serde_json::json!({ "full_product_names": names, "relationships": relationships })
}
/// The CSAF `product_status` key of a VEX status.
fn status_key(status: VexStatus) -> &'static str {
match status {
VexStatus::UnderInvestigation => "under_investigation",
VexStatus::Affected => "known_affected",
VexStatus::NotAffected => "known_not_affected",
VexStatus::Fixed => "fixed",
}
}
/// Push `product` onto the list under `key` of the object `parent[field]`,
/// creating both on first use.
fn push_product(parent: &mut serde_json::Value, field: &str, key: &str, product: &str) {
let list = &mut parent[field][key];
match list.as_array_mut() {
Some(list) => list.push(serde_json::json!(product)),
None => *list = serde_json::json!([product]),
}
}
/// One vulnerability of the advisory, from all statements listed under
/// `key` (the CVE, or the advisory's id without one): the CVE in its own
/// field, the other ids (a GitHub advisory) under `ids`.
fn vulnerability(
key: &str,
statements: &[&Statement<'_>],
components: &[(String, String, String)],
input: &VexInput<'_>,
) -> serde_json::Value {
let mut v = serde_json::json!({ "product_status": {} });
let mut ids: Vec<&str> = Vec::new();
if is_cve(key) {
v["cve"] = serde_json::json!(key);
} else {
ids.push(key);
}
for id in statements.iter().flat_map(|st| &st.other_ids) {
if !is_cve(id) && !ids.contains(id) {
ids.push(id);
}
}
if !ids.is_empty() {
v["ids"] = ids
.iter()
.map(|id| serde_json::json!({ "system_name": advisory_source(id).0, "text": id }))
.collect();
}
// The VEX profile requires notes on every vulnerability; without an
// advisory summary they say what is affected.
let text = input
.alerts
.iter()
.filter(|a| a.cve() == key)
.find_map(|a| a.summary.clone())
.unwrap_or_else(|| {
let packages: Vec<String> = statements
.iter()
.map(|st| {
format!(
"{} {}",
st.alert.affected_package, st.alert.affected_version
)
})
.collect();
format!("{key} in {}.", packages.join(", "))
});
v["notes"] = serde_json::json!([{ "category": "description", "text": text }]);
let (mut flags, mut threats, mut remediations) = (Vec::new(), Vec::new(), Vec::new());
// One statement per component, so each product has one status.
for st in statements {
let alert = st.alert;
let Some((id, ..)) = components.iter().find(|(.., p)| *p == st.component) else {
continue;
};
let product = in_product(id);
let status = status_of(alert);
push_product(&mut v, "product_status", status_key(status), &product);
let Some(vex) = alert.statement() else {
continue;
};
match status {
VexStatus::NotAffected => {
if let Some(justification) = vex.justification {
flags.push(serde_json::json!({
"label": justification,
"product_ids": [product],
}));
}
if let Some(text) = vex.impact_statement.as_deref() {
threats.push(serde_json::json!({
"category": "impact",
"details": text,
"product_ids": [product],
}));
}
}
VexStatus::Affected => {
let category = if alert.fixed_versions.is_empty() {
"mitigation"
} else {
"vendor_fix"
};
let details = vex.action_statement.clone().unwrap_or_else(|| {
format!(
"Update {} to {}.",
alert.affected_package,
alert.fixed_versions.join(" or ")
)
});
remediations.push(serde_json::json!({
"category": category,
"details": details,
"product_ids": [product],
}));
}
// Why it is under investigation or fixed (a Yocto recipe's
// CVE_STATUS or patch), as the impact on these products.
VexStatus::UnderInvestigation | VexStatus::Fixed => {
if let Some(text) = vex.impact_statement.as_deref() {
threats.push(serde_json::json!({
"category": "impact",
"details": text,
"product_ids": [product],
}));
}
}
}
}
for (field, list) in [
("flags", flags),
("threats", threats),
("remediations", remediations),
] {
if !list.is_empty() {
v[field] = serde_json::Value::Array(list);
}
}
v
}
/// A CSAF 2.0 VEX advisory (draft) for `input`, published by `input.author`
/// under `namespace` (the publisher's URL), in language `lang` (`de`, `en`:
/// the language its statements were written in). Marked TLP:AMBER until the
/// manufacturer has reviewed it for publication.
pub fn csaf_vex(input: &VexInput<'_>, namespace: &str, lang: &str) -> serde_json::Value {
let now = rfc3339(input.now);
let components = components(input);
let statements = statements(input);
// One vulnerability per CVE (CSAF forbids listing a CVE twice), in the
// order the statements first name it.
let mut keys: Vec<&str> = Vec::new();
for st in &statements {
if !keys.contains(&st.id()) {
keys.push(st.id());
}
}
let vulnerabilities: Vec<serde_json::Value> = keys
.iter()
.map(|key| {
let of_key: Vec<&Statement<'_>> =
statements.iter().filter(|st| st.id() == *key).collect();
vulnerability(key, &of_key, &components, input)
})
.collect();
serde_json::json!({
"document": {
"category": "csaf_vex",
"csaf_version": "2.0",
"lang": lang,
"distribution": { "tlp": { "label": "AMBER" } },
"title": format!("VEX for {} (draft)", input.subject),
"publisher": {
"category": "vendor",
"name": input.author,
"namespace": namespace,
},
"notes": [{ "category": "general", "title": "Draft", "text": DRAFT_NOTE }],
"tracking": {
"id": tracking_id(input.subject, input.now),
"status": "draft",
"version": "1",
"revision_history": [{
"date": now,
"number": "1",
"summary": "Draft generated by Prüfwerk.",
}],
"initial_release_date": now,
"current_release_date": now,
"generator": { "engine": { "name": input.tooling }, "date": now },
},
},
"product_tree": product_tree(input, &components),
"vulnerabilities": vulnerabilities,
})
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn ids_and_file_names_follow_csaf() {
let at = DateTime::parse_from_rfc3339("2026-10-06T12:00:00Z")
.map(|d| d.with_timezone(&Utc))
.unwrap_or_default();
let id = tracking_id("Pump Remote / HMI", at);
assert_eq!(id, "pruefwerk-vex-pump-remote-hmi-20261006");
assert_eq!(filename(&id), "pruefwerk-vex-pump-remote-hmi-20261006.json");
assert_eq!(filename("ACME_SA:2026/01"), "acme_sa_2026_01.json");
assert_eq!(
placeholder_namespace("example-pumps"),
"https://example.invalid/example-pumps"
);
}
#[test]
fn a_scan_note_on_an_open_or_fixed_status_reaches_every_export() {
use crate::models::{CveAlert, CveSource, VexAssessment};
let mut alert = CveAlert::new(
"CVE-2022-48174".into(),
"t".into(),
"busybox".into(),
"1.35.0".into(),
CveSource::Nvd,
);
let note = "Yocto CVE_STATUS \"disputed\" in recipes-core/busybox/busybox_1.35.0.bb";
alert.vex = Some(VexAssessment {
status: VexStatus::UnderInvestigation,
justification: None,
impact_statement: Some(note.into()),
action_statement: None,
by: "pruefwerk-scan".into(),
by_name: None,
at: Utc::now(),
by_scan: true,
});
let alerts = [alert];
let input = VexInput {
subject: "pump",
author: "ws",
tooling: "test",
alerts: &alerts,
sbom: &[],
now: Utc::now(),
};
let openvex = crate::vex_docs::openvex(&input);
let statement = &openvex["statements"][0];
assert_eq!(statement["status"], "under_investigation");
assert_eq!(statement["status_notes"], note);
assert!(
statement.get("impact_statement").is_none(),
"only for not_affected"
);
let csaf = csaf_vex(&input, "https://example.invalid/ws", "en");
assert_eq!(csaf["vulnerabilities"][0]["threats"][0]["details"], note);
}
}