Files
pruefwerk/compliance-core/src/sbom_docs.rs
T
sharang 9bf7aad5b1
CI / Check (push) Skipped
CI / Detect Changes (push) Successful in 4s
CI / Deploy Docs (push) Successful in 1m20s
CI / Deploy Dashboard (push) Successful in 6m25s
CI / Deploy MCP (push) Successful in 3m26s
CI / Deploy Agent (push) Successful in 9m6s
feat(vex): VEX status on CVE alerts, OpenVEX and CycloneDX VEX, a valid CycloneDX SBOM (#498, 1/4) (#502)
2026-10-06 11:56:04 +00:00

227 lines
8.2 KiB
Rust

//! SBOM documents in the two exchange formats: CycloneDX 1.5 and SPDX 2.3.
//! Shared by the agent's SBOM export and evidence pack and by the MCP server,
//! so all of them say the same. The CycloneDX parts are shared with the VEX
//! documents (see [`crate::vex_docs`]), which refer to the same `bom-ref`s.
use crate::models::SbomEntry;
/// The `bom-ref` of a component, which a VEX statement refers to: its purl,
/// or `<package manager>:<name>@<version>` without one.
pub fn component_ref(entry: &SbomEntry) -> String {
entry
.purl
.clone()
.unwrap_or_else(|| format!("{}:{}@{}", entry.package_manager, entry.name, entry.version))
}
/// The identifier of the product (the target) the SBOM and the VEX describe:
/// `pkg:generic/<name>`, the name percent-encoded as a purl requires.
pub fn product_ref(subject: &str) -> String {
let encoded: String = subject
.bytes()
.map(|b| match b {
b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'.' | b'-' | b'_' | b'~' => {
(b as char).to_string()
}
_ => format!("%{b:02X}"),
})
.collect();
format!("pkg:generic/{encoded}")
}
/// The SPDX license ids CycloneDX accepts as `license.id` (its own copy of
/// the SPDX list).
fn spdx_ids() -> &'static std::collections::HashSet<String> {
static IDS: std::sync::LazyLock<std::collections::HashSet<String>> =
std::sync::LazyLock::new(|| {
serde_json::from_str::<serde_json::Value>(include_str!("../schemas/spdx.schema.json"))
.ok()
.and_then(|schema| {
schema["enum"].as_array().map(|ids| {
ids.iter()
.filter_map(|id| id.as_str().map(str::to_string))
.collect()
})
})
.unwrap_or_default()
});
&IDS
}
/// A license as CycloneDX writes it: an SPDX id it knows, an SPDX expression
/// (`MIT OR Apache-2.0`), or a named license.
fn license_choice(license: &str) -> serde_json::Value {
let license = license.trim();
if spdx_ids().contains(license) {
serde_json::json!([{ "license": { "id": license } }])
} else if [" OR ", " AND ", " WITH "]
.iter()
.any(|op| license.contains(op))
{
serde_json::json!([{ "expression": license }])
} else {
serde_json::json!([{ "license": { "name": license } }])
}
}
/// A CycloneDX severity from an advisory's (`HIGH`, `MODERATE`, `critical`).
pub fn cdx_severity(severity: &str) -> &'static str {
match severity.trim().to_ascii_lowercase().as_str() {
"critical" => "critical",
"high" => "high",
"medium" | "moderate" => "medium",
"low" => "low",
"info" | "informational" => "info",
"none" => "none",
_ => "unknown",
}
}
/// The components of a CycloneDX document, each with its `bom-ref`.
pub fn cdx_components(entries: &[SbomEntry]) -> Vec<serde_json::Value> {
let mut seen = std::collections::HashSet::new();
entries
.iter()
.filter(|e| seen.insert(component_ref(e)))
.map(|e| {
let mut comp = serde_json::json!({
"type": "library",
"bom-ref": component_ref(e),
"name": e.name,
"version": e.version,
"group": e.package_manager,
});
if let Some(purl) = &e.purl {
comp["purl"] = serde_json::Value::String(purl.clone());
}
if let Some(license) = e.license.as_deref().filter(|l| !l.trim().is_empty()) {
comp["licenses"] = license_choice(license);
}
comp
})
.collect()
}
/// The frame of a CycloneDX 1.5 document about `subject`: a fresh serial
/// number and the product as `metadata.component`.
pub fn cdx_frame(subject: &str) -> serde_json::Value {
serde_json::json!({
"bomFormat": "CycloneDX",
"specVersion": "1.5",
"serialNumber": format!("urn:uuid:{}", uuid::Uuid::new_v4()),
"version": 1,
"metadata": {
"timestamp": chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Secs, true),
"tools": { "components": [{ "type": "application", "name": "Prüfwerk" }] },
"component": {
"type": "application",
"bom-ref": product_ref(subject),
"name": subject,
}
},
})
}
/// A CycloneDX 1.5 document for `entries`, named after `subject`. The known
/// vulnerabilities of the components are listed at the top level, each
/// naming the components it affects by `bom-ref` (CycloneDX keeps them out of
/// the components).
pub fn cyclonedx(entries: &[SbomEntry], subject: &str) -> serde_json::Value {
let mut doc = cdx_frame(subject);
doc["components"] = serde_json::Value::Array(cdx_components(entries));
// One vulnerability per advisory, affecting every component it was
// found in.
let mut vulns: Vec<(String, String, Option<String>, Vec<String>)> = Vec::new();
for e in entries {
for v in &e.known_vulnerabilities {
let reference = component_ref(e);
match vulns
.iter_mut()
.find(|(id, source, ..)| *id == v.id && *source == v.source)
{
Some((.., refs)) => {
if !refs.contains(&reference) {
refs.push(reference);
}
}
None => vulns.push((
v.id.clone(),
v.source.clone(),
v.severity.clone(),
vec![reference],
)),
}
}
}
if !vulns.is_empty() {
doc["vulnerabilities"] = serde_json::Value::Array(
vulns
.into_iter()
.map(|(id, source, severity, refs)| {
let mut v = serde_json::json!({
"id": id,
"source": { "name": source },
"affects": refs.into_iter().map(|r| serde_json::json!({ "ref": r })).collect::<Vec<_>>(),
});
if let Some(severity) = severity {
v["ratings"] = serde_json::json!([{ "severity": cdx_severity(&severity) }]);
}
v
})
.collect(),
);
}
doc
}
/// An SPDX 2.3 document for `entries`, named after `subject`.
pub fn spdx(entries: &[SbomEntry], subject: &str) -> serde_json::Value {
let packages: Vec<serde_json::Value> = entries
.iter()
.enumerate()
.map(|(i, e)| {
serde_json::json!({
"SPDXID": format!("SPDXRef-Package-{i}"),
"name": e.name,
"versionInfo": e.version,
"downloadLocation": "NOASSERTION",
"licenseConcluded": e.license.as_deref().unwrap_or("NOASSERTION"),
"externalRefs": e.purl.as_ref().map(|p| vec![serde_json::json!({
"referenceCategory": "PACKAGE-MANAGER",
"referenceType": "purl",
"referenceLocator": p,
})]).unwrap_or_default(),
})
})
.collect();
serde_json::json!({
"spdxVersion": "SPDX-2.3",
"dataLicense": "CC0-1.0",
"SPDXID": "SPDXRef-DOCUMENT",
"name": format!("sbom-{subject}"),
"documentNamespace": format!("https://compliance-scanner/sbom/{subject}"),
"packages": packages,
})
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn both_formats_list_every_component() {
let mut e = SbomEntry::new("t".into(), "lwIP".into(), "2.1.2".into(), "embedded".into());
e.license = Some("BSD-3-Clause".into());
let cdx = cyclonedx(std::slice::from_ref(&e), "t");
assert_eq!(cdx["bomFormat"], "CycloneDX");
assert_eq!(
cdx["components"][0]["licenses"][0]["license"]["id"],
"BSD-3-Clause"
);
let spdx = spdx(&[e], "t");
assert_eq!(spdx["spdxVersion"], "SPDX-2.3");
assert_eq!(spdx["packages"][0]["versionInfo"], "2.1.2");
}
}