//! SBOM documents in the two exchange formats: CycloneDX 1.6 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. //! //! The CycloneDX document follows BSI TR-03183-2 v2.1 (#508) as far as //! Prüfwerk knows the data: the `bsi:component:*` properties of the registry //! packages, a dependency graph whose completeness is stated, and licences as //! the suppliers declare them. use crate::models::{ advisory_source, is_cve, ComponentHash, LicenseConclusion, SbomEntry, YOCTO_RECIPE_MANAGER, YOCTO_RECIPE_SOURCE, }; use crate::purl::Purl; use crate::spdx_license; /// The `bom-ref` of a component, which a VEX statement refers to: its purl, /// or `:@` 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/`, the name percent-encoded as a purl requires. pub fn product_ref(subject: &str) -> String { format!("pkg:generic/{}", crate::purl::encode(subject)) } /// A license as CycloneDX writes it: an SPDX id, an SPDX expression /// (`MIT OR Apache-2.0`), or a named license. A name or URL of a license /// SPDX lists becomes its id ([`spdx_license::normalise`], BSI TR-03183-2). /// It is the license the supplier declares (registry or lockfile metadata); /// a license a person confirmed is written by [`concluded_choice`] instead. fn license_choice(license: &str) -> serde_json::Value { let license = spdx_license::normalise(license); if spdx_license::canonical_id(&license) == Some(&*license) { serde_json::json!([{ "license": { "id": license, "acknowledgement": "declared" } }]) } else if spdx_license::has_operator(&license) { serde_json::json!([{ "expression": license, "acknowledgement": "declared" }]) } else { serde_json::json!([{ "license": { "name": license, "acknowledgement": "declared" } }]) } } /// The licence a person confirmed, as CycloneDX writes a concluded licence: /// an SPDX id or expression, or a licence of its own by name with its text /// and URL. CycloneDX takes either licences or one expression, never both, /// so the declared licence is then kept as a property /// ([`DECLARED_LICENSE_PROPERTY`]). fn concluded_choice(c: &LicenseConclusion) -> serde_json::Value { if c.is_custom() { let mut license = serde_json::json!({ "name": c.display(), "acknowledgement": "concluded", }); if let Some(text) = &c.license_text { license["text"] = serde_json::json!({ "contentType": "text/plain", "content": text }); } if let Some(url) = &c.license_url { license["url"] = serde_json::Value::String(url.clone()); } serde_json::json!([{ "license": license }]) } else if spdx_license::canonical_id(&c.license) == Some(c.license.as_str()) { serde_json::json!([{ "license": { "id": c.license, "acknowledgement": "concluded" } }]) } else { serde_json::json!([{ "expression": c.license, "acknowledgement": "concluded" }]) } } /// The property holding the licence the scan detected, where a person /// confirmed another one. const DECLARED_LICENSE_PROPERTY: &str = "pruefwerk:license:declared"; /// The properties of a confirmed licence: its category, where the component /// is used, a bought licence's contract and end, where it was found, and who /// confirmed it when. fn conclusion_properties(entry: &SbomEntry, c: &LicenseConclusion) -> Vec { let mut props = vec![serde_json::json!({ "name": "pruefwerk:license:category", "value": c.category.as_str(), })]; let mut push = |name: &str, value: Option| { if let Some(value) = value.filter(|v| !v.trim().is_empty()) { props.push(serde_json::json!({ "name": name, "value": value })); } }; push( DECLARED_LICENSE_PROPERTY, entry.license.clone().filter(|l| l.trim() != c.license), ); push( "pruefwerk:license:usage", c.usage.map(|u| match u { crate::models::LicenseUsage::Shipped => "shipped".to_string(), crate::models::LicenseUsage::BuildOnly => "build_only".to_string(), }), ); push("pruefwerk:license:contract", c.contract_ref.clone()); push( "pruefwerk:license:valid_until", c.valid_until.map(|d| d.to_string()), ); push("pruefwerk:license:evidence", c.evidence.clone()); push( "pruefwerk:license:concluded", Some(format!( "{} {}", c.by_name.as_deref().unwrap_or(&c.by), c.at.to_rfc3339_opts(chrono::SecondsFormat::Secs, true) )), ); if let Some(review) = &c.review { push( "pruefwerk:license:review", Some(format!( "{} by {} {}", review.decision.as_str(), review.by_name.as_deref().unwrap_or(&review.by), review.at.to_rfc3339_opts(chrono::SecondsFormat::Secs, true) )), ); } props } /// The file a registry package is distributed as (`log4j-core-2.14.1.jar`), /// where its purl determines it. `None` for a package type whose file the /// purl does not name (PyPI wheel or sdist, Go modules) and without a version. fn package_filename(purl: &Purl) -> Option { let version = purl.version.as_deref()?; let name = &purl.name; Some(match purl.ty.as_str() { // The registry tarball is named after the unscoped name. "npm" => format!("{name}-{version}.tgz"), "maven" => { let extension = purl.qualifier("type").unwrap_or("jar"); match purl.qualifier("classifier") { Some(classifier) => format!("{name}-{version}-{classifier}.{extension}"), None => format!("{name}-{version}.{extension}"), } } "nuget" => format!("{}.{}.nupkg", name.to_lowercase(), version.to_lowercase()), "cargo" => format!("{name}-{version}.crate"), "gem" => match purl.qualifier("platform") { Some(platform) => format!("{name}-{version}-{platform}.gem"), None => format!("{name}-{version}.gem"), }, "hex" => format!("{name}-{version}.tar"), _ => return None, }) } /// The `bsi:component:*` properties of a registry package: its file, and that /// it is a package archive. A package archive is described like the TR's rpm /// example (Table 7): not executable itself, an archive, structured. fn bsi_properties(purl: &Purl) -> Option { let filename = package_filename(purl)?; Some(serde_json::json!([ { "name": "bsi:component:filename", "value": filename }, { "name": "bsi:component:executable", "value": "non-executable" }, { "name": "bsi:component:archive", "value": "archive" }, { "name": "bsi:component:structured", "value": "structured" }, ])) } /// The property that says where a component comes from when its source /// limits what it proves: a Yocto recipe is in the layer tree, not /// necessarily in the image. const SOURCE_PROPERTY: &str = "pruefwerk:component:source"; /// The property naming the images a component is in and how that is known /// (`declared: pump-image`). const IN_IMAGE_PROPERTY: &str = "pruefwerk:component:in_image"; /// Where `entry` comes from, when the reader must know it to weigh it. fn source_note(entry: &SbomEntry) -> Option<&'static str> { (entry.package_manager == YOCTO_RECIPE_MANAGER).then_some(YOCTO_RECIPE_SOURCE) } /// The CycloneDX properties saying where `entry` comes from and which images /// it is in. fn provenance_properties(entry: &SbomEntry) -> Vec { let source = source_note(entry) .map(|source| serde_json::json!({ "name": SOURCE_PROPERTY, "value": source })); let in_image = entry.in_image.as_ref().map(|in_image| { let value = format!( "{}: {}", in_image.basis.as_str(), in_image.images.join(", ") ); serde_json::json!({ "name": IN_IMAGE_PROPERTY, "value": value }) }); source.into_iter().chain(in_image).collect() } /// The SPDX package comment saying the same: the source, and the images. fn provenance_comment(entry: &SbomEntry) -> Option { let notes: Vec = source_note(entry) .map(str::to_string) .into_iter() .chain(entry.in_image.as_ref().map(|in_image| in_image.describe())) .collect(); (!notes.is_empty()).then(|| notes.join(". ")) } /// 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", } } /// Hashes as CycloneDX writes them. fn cdx_hashes(hashes: &[ComponentHash]) -> serde_json::Value { hashes .iter() .map(|h| serde_json::json!({ "alg": h.alg, "content": h.content })) .collect() } /// The components of a CycloneDX document, each with its `bom-ref`. pub fn cdx_components(entries: &[SbomEntry]) -> Vec { 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, }); if let Some(purl) = &e.purl { comp["purl"] = serde_json::Value::String(purl.clone()); if let Some(parsed) = Purl::parse(purl) { // CycloneDX's group is the namespace (a Maven group id, // an npm scope), not the package manager. if let Some(namespace) = &parsed.namespace { comp["group"] = serde_json::Value::String(namespace.clone()); } if let Some(properties) = bsi_properties(&parsed) { comp["properties"] = properties; } } } if let Some(cpe) = &e.cpe { comp["cpe"] = serde_json::Value::String(cpe.clone()); } let provenance = provenance_properties(e); if !provenance.is_empty() { match comp["properties"].as_array_mut() { Some(properties) => properties.extend(provenance), None => comp["properties"] = serde_json::Value::Array(provenance), } } match &e.concluded { Some(c) => { comp["licenses"] = concluded_choice(c); if !c.copyright.is_empty() { comp["copyright"] = serde_json::Value::String(c.copyright.join("\n")); } let props = conclusion_properties(e, c); match comp["properties"].as_array_mut() { Some(properties) => properties.extend(props), None => comp["properties"] = serde_json::Value::Array(props), } } None => { if let Some(license) = e.license.as_deref().filter(|l| !l.trim().is_empty()) { comp["licenses"] = license_choice(license); } } } if let Some(url) = &e.manufacturer_url { comp["manufacturer"] = serde_json::json!({ "url": [url] }); } if !e.hashes.is_empty() { let hashes = cdx_hashes(&e.hashes); // The file and where it is downloaded from: the TR's hash of // the deployable component and its URI (#508). if let Some(url) = &e.download_url { comp["externalReferences"] = serde_json::json!([{ "type": "distribution", "url": url, "hashes": hashes, }]); } comp["hashes"] = hashes; } comp }) .collect() } /// Who creates Prüfwerk's SBOM documents, as BSI TR-03183-2 asks for the /// "creator of the SBOM": its name and email address (`metadata.manufacturer`). const CREATOR_NAME: &str = "BreakPilot GmbH"; const CREATOR_EMAIL: &str = "kontakt@breakpilot.com"; /// The product's version: when its SBOM data was last compiled, as an /// RFC 3339 date-time. A target has no version of its own, and BSI /// TR-03183-2 names the modification date for a component without one. fn product_version(entries: &[SbomEntry]) -> Option { entries .iter() .map(|e| e.updated_at) .max() .map(|at| at.to_rfc3339_opts(chrono::SecondsFormat::Secs, true)) } /// The frame of a CycloneDX 1.6 document about `subject`, whose components /// are `entries`: a fresh serial number, the creator and the product as /// `metadata.component`. pub fn cdx_frame(subject: &str, entries: &[SbomEntry]) -> serde_json::Value { let mut doc = serde_json::json!({ "bomFormat": "CycloneDX", "specVersion": "1.6", "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" }] }, "manufacturer": { "name": CREATOR_NAME, "contact": [{ "email": CREATOR_EMAIL }], }, "component": { "type": "application", "bom-ref": product_ref(subject), "purl": product_ref(subject), "name": subject, } }, }); if let Some(version) = product_version(entries) { doc["metadata"]["component"]["version"] = serde_json::Value::String(version); } doc } /// The dependency graph of a document whose product contains `components`, /// and its completeness. The SBOM is flat: the product depends on every /// component, directly or through another one, and which of them depend on /// which is not known. So every component gets an empty entry, as CycloneDX /// asks for one without dependencies, and the graph is stated `incomplete`. fn cdx_dependencies(doc: &mut serde_json::Value, components: &[serde_json::Value]) { let product = doc["metadata"]["component"]["bom-ref"].clone(); let refs: Vec = components.iter().map(|c| c["bom-ref"].clone()).collect(); let mut dependencies = Vec::with_capacity(refs.len() + 1); dependencies.push(serde_json::json!({ "ref": product, "dependsOn": refs })); dependencies.extend(refs.iter().map(|r| serde_json::json!({ "ref": r }))); doc["dependencies"] = serde_json::Value::Array(dependencies); doc["compositions"] = serde_json::json!([{ "aggregate": "incomplete", "dependencies": [product], }]); } /// The identification of a CycloneDX vulnerability known as `primary` and /// `others`: `id` and `source` of the primary id (NVD for a CVE, else /// `source`, the scanner that found it), the other ids as `references` to /// their databases. pub fn cdx_vulnerability(primary: &str, others: &[&str], source: &str) -> serde_json::Value { let mut v = if is_cve(primary) { let (name, url) = advisory_source(primary); serde_json::json!({ "id": primary, "source": { "name": name, "url": url } }) } else { serde_json::json!({ "id": primary, "source": { "name": source } }) }; if !others.is_empty() { v["references"] = others .iter() .map(|id| { let (name, url) = advisory_source(id); serde_json::json!({ "id": id, "source": { "name": name, "url": url } }) }) .collect(); } v } /// One vulnerability of a CycloneDX SBOM: its primary id, its other ids, /// the source and severity it was first found with, and the components it /// affects. struct SbomVulnerability<'a> { id: &'a str, others: Vec<&'a str>, source: &'a str, severity: Option<&'a str>, affects: Vec, } /// A CycloneDX 1.6 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). A vulnerability is listed under its CVE when one is /// known, with its GitHub advisory as a reference. pub fn cyclonedx(entries: &[SbomEntry], subject: &str) -> serde_json::Value { let mut doc = cdx_frame(subject, entries); let components = cdx_components(entries); cdx_dependencies(&mut doc, &components); doc["components"] = serde_json::Value::Array(components); cdx_known_vulnerabilities(&mut doc, entries); doc } /// The product a released SBOM describes (#1028): the target a supplier /// workspace releases, the version it publishes, and the workspace's name as /// its supplier. #[derive(Debug, Clone, Copy)] pub struct ReleasedProduct<'a> { /// The target's name. pub name: &'a str, /// The version the supplier publishes, such as `1.4.0`. pub version: &'a str, /// The supplier: the releasing workspace's display name. pub supplier: &'a str, } /// The keys of a component that a released SBOM keeps: what identifies the /// component, its licences and its hashes. Everything else stays with the /// supplier: properties (where it was found, the images it is in, the /// licence review), copyright, references and the manufacturer. A list of /// what is kept, so nothing added to the export later crosses unnoticed. const RELEASED_COMPONENT_KEYS: [&str; 9] = [ "type", "bom-ref", "name", "group", "version", "purl", "cpe", "licenses", "hashes", ]; /// The SBOM a supplier workspace releases to a connected customer workspace /// (#1028): a CycloneDX 1.6 document of `entries` about `product`, holding /// only what identifies each component, its licences and its hashes. /// /// No vulnerabilities, findings or provenance cross: the customer's own scan /// finds the vulnerabilities. A confirmed custom licence keeps its name but /// not its text, which may come from the supplier's own contract. /// /// # Arguments /// /// * `entries` - the SBOM entries of the target's latest scan /// * `product` - the target, the version published and the supplier pub fn released_cyclonedx( entries: &[SbomEntry], product: &ReleasedProduct<'_>, ) -> serde_json::Value { let mut doc = cdx_frame(product.name, entries); doc["metadata"]["component"]["version"] = serde_json::json!(product.version); doc["metadata"]["component"]["supplier"] = serde_json::json!({ "name": product.supplier }); let mut components: Vec = cdx_components(entries) .into_iter() .map(released_component) .collect(); unique_refs(&mut components); cdx_dependencies(&mut doc, &components); doc["components"] = serde_json::Value::Array(components); doc } /// Purl qualifiers that say where a component was fetched from. A released /// SBOM leaves them out: they can name the supplier's own servers (a Yocto /// recipe's `vcs_url`, an internal feed). const ADDRESS_QUALIFIERS: [&str; 3] = ["download_url", "vcs_url", "repository_url"]; /// `purl` without its [`ADDRESS_QUALIFIERS`]; anything that is not a purl /// as it is. fn without_addresses(purl: &str) -> String { if !purl.starts_with("pkg:") { return purl.to_string(); } let (body, subpath) = match purl.split_once('#') { Some((body, subpath)) => (body, Some(subpath)), None => (purl, None), }; let Some((base, qualifiers)) = body.split_once('?') else { return purl.to_string(); }; let kept: Vec<&str> = qualifiers .split('&') .filter(|q| { let key = q.split_once('=').map_or(*q, |(key, _)| key); !ADDRESS_QUALIFIERS.contains(&key) }) .collect(); let mut out = base.to_string(); if !kept.is_empty() { out.push('?'); out.push_str(&kept.join("&")); } if let Some(subpath) = subpath { out.push('#'); out.push_str(subpath); } out } /// Make each component's `bom-ref` unique again: two components can differ /// only in a qualifier [`without_addresses`] removed. A repeated one gets /// ` (2)`, ` (3)`, ... appended. fn unique_refs(components: &mut [serde_json::Value]) { let mut seen: std::collections::HashMap = std::collections::HashMap::new(); for component in components { let Some(reference) = component["bom-ref"].as_str().map(str::to_string) else { continue; }; let count = seen.entry(reference.clone()).or_insert(0); *count += 1; if *count > 1 { component["bom-ref"] = serde_json::json!(format!("{reference} ({count})")); } } } /// `component` with only [`RELEASED_COMPONENT_KEYS`], no licence text and /// no addresses in its purl. fn released_component(mut component: serde_json::Value) -> serde_json::Value { if let Some(fields) = component.as_object_mut() { fields.retain(|key, _| RELEASED_COMPONENT_KEYS.contains(&key.as_str())); for key in ["purl", "bom-ref"] { if let Some(stripped) = fields .get(key) .and_then(|v| v.as_str()) .map(without_addresses) { fields.insert(key.to_string(), serde_json::Value::String(stripped)); } } let licenses = fields .get_mut("licenses") .and_then(serde_json::Value::as_array_mut); for choice in licenses.into_iter().flatten() { if let Some(license) = choice .get_mut("license") .and_then(serde_json::Value::as_object_mut) { license.remove("text"); } } } component } /// The known vulnerabilities of `entries` as the document's /// `vulnerabilities`: one per CVE (or advisory without one), affecting every /// component it was found in, by whichever scanner and id. None, none set. fn cdx_known_vulnerabilities(doc: &mut serde_json::Value, entries: &[SbomEntry]) { let mut vulns: Vec> = Vec::new(); for e in entries { for v in &e.known_vulnerabilities { let id = v.cve(); let i = match vulns.iter().position(|known| known.id == id) { Some(i) => i, None => { vulns.push(SbomVulnerability { id, others: Vec::new(), source: &v.source, severity: None, affects: Vec::new(), }); vulns.len() - 1 } }; let known = &mut vulns[i]; for other in std::iter::once(&v.id).chain(&v.aliases) { if other != id && !known.others.contains(&other.as_str()) { known.others.push(other); } } known.severity = known.severity.or(v.severity.as_deref()); let reference = component_ref(e); if !known.affects.contains(&reference) { known.affects.push(reference); } } } if !vulns.is_empty() { doc["vulnerabilities"] = vulns .into_iter() .map(|known| { let mut v = cdx_vulnerability(known.id, &known.others, known.source); v["affects"] = known .affects .into_iter() .map(|r| serde_json::json!({ "ref": r })) .collect(); if let Some(severity) = known.severity { v["ratings"] = serde_json::json!([{ "severity": cdx_severity(severity) }]); } v }) .collect(); } } /// One part of a machine (#1026): one of its targets, in-house or bought in. #[derive(Debug, Clone, Copy)] pub struct MachinePart<'a> { /// The target's id. Its SBOM entries are the ones with this `repo_id`. pub id: &'a str, /// The target's name. pub name: &'a str, /// Its CycloneDX component type, such as `firmware` or `application`. pub kind: &'static str, /// Who supplies it: the supplier of a bought-in component, the /// manufacturer (the workspace) for one made in-house. pub supplier: &'a str, /// Its version, where the supplier names one; else when its SBOM data /// was last compiled, as for a target's own SBOM. pub version: Option<&'a str>, } impl MachinePart<'_> { /// The part's `bom-ref`: by its target's id, unique in the machine /// whatever the targets are called. pub fn bom_ref(&self) -> String { format!("urn:pruefwerk:target:{}", self.id) } } /// The SBOM of a machine (#1026): the machine `machine` (a product project, /// `project_id`) made of `parts`, each listing the components of `entries` /// with its `repo_id` beneath it. /// /// Every part is a component of the machine with its supplier, so the /// document names who supplies each. A component two parts contain is listed /// once, with both parts depending on it. The machine depends on its parts /// and each part on its components: the top-level dependencies the CRA asks /// for (Annex I, Part II (1)). Which of a part's components depend on which /// is not known, so the graph is stated `incomplete`, as for a target. /// /// # Arguments /// /// * `machine` - the machine's name /// * `project_id` - its project's id, its `bom-ref` /// * `parts` - its parts, in the order they are listed /// * `entries` - the SBOM entries of all parts pub fn machine_cyclonedx( machine: &str, project_id: &str, parts: &[MachinePart<'_>], entries: &[SbomEntry], ) -> serde_json::Value { let machine_ref = format!("urn:pruefwerk:project:{project_id}"); let mut doc = cdx_frame(machine, entries); doc["metadata"]["component"]["type"] = serde_json::json!("device"); doc["metadata"]["component"]["bom-ref"] = serde_json::json!(machine_ref); let mut components: Vec = Vec::with_capacity(parts.len()); let mut dependencies = Vec::with_capacity(parts.len() + 1); dependencies.push(serde_json::json!({ "ref": machine_ref, "dependsOn": parts.iter().map(MachinePart::bom_ref).collect::>(), })); for part in parts { let own: Vec<&SbomEntry> = entries.iter().filter(|e| e.repo_id == part.id).collect(); let version = part.version.map(str::to_string).or_else(|| { own.iter() .map(|e| e.updated_at) .max() .map(|at| at.to_rfc3339_opts(chrono::SecondsFormat::Secs, true)) }); let mut component = serde_json::json!({ "type": part.kind, "bom-ref": part.bom_ref(), "name": part.name, "supplier": { "name": part.supplier }, }); if let Some(version) = version { component["version"] = serde_json::Value::String(version); } components.push(component); let mut refs: Vec = own.iter().map(|e| component_ref(e)).collect(); refs.sort_unstable(); refs.dedup(); dependencies.push(serde_json::json!({ "ref": part.bom_ref(), "dependsOn": refs })); } let parts_of_machine = components.len(); components.extend(cdx_components(entries)); dependencies.extend( components[parts_of_machine..] .iter() .map(|c| serde_json::json!({ "ref": c["bom-ref"] })), ); doc["components"] = serde_json::Value::Array(components); doc["dependencies"] = serde_json::Value::Array(dependencies); doc["compositions"] = serde_json::json!([{ "aggregate": "incomplete", "dependencies": [machine_ref], }]); cdx_known_vulnerabilities(&mut doc, entries); doc } /// An SPDX 2.3 document for `entries`, named after `subject`. pub fn spdx(entries: &[SbomEntry], subject: &str) -> serde_json::Value { // A `LicenseRef-` a package concludes must be defined in the document. let mut extracted: Vec = Vec::new(); let mut defined = std::collections::HashSet::new(); for c in entries.iter().filter_map(|e| e.concluded.as_ref()) { if c.is_custom() && defined.insert(c.license.clone()) { let mut info = serde_json::json!({ "licenseId": c.license, "name": c.display(), // SPDX requires a text; without one, where to find it. "extractedText": c.license_text.clone().unwrap_or_else(|| { c.license_url.clone().unwrap_or_else(|| "NOASSERTION".to_string()) }), }); if let Some(url) = &c.license_url { info["seeAlsos"] = serde_json::json!([url]); } extracted.push(info); } } let packages: Vec = entries .iter() .enumerate() .map(|(i, e)| { // The declared license is what the supplier declares; a license // is concluded only where a person of the workspace confirmed one // (`concluded`). SPDX takes only an expression of listed ids; a // declared license that is none is NOASSERTION, its text kept as // a comment. let raw = e .license .as_deref() .map(str::trim) .filter(|l| !l.is_empty()); let license = raw .map(spdx_license::normalise) .filter(|l| spdx_license::is_spdx_expression(l)); let mut package = serde_json::json!({ "SPDXID": format!("SPDXRef-Package-{i}"), "name": e.name, "versionInfo": e.version, "downloadLocation": "NOASSERTION", // Concluded only where a person confirmed the licence. "licenseConcluded": e.concluded.as_ref().map_or("NOASSERTION", |c| c.license.as_str()), "licenseDeclared": 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(), }); if let (Some(raw), None) = (raw, &license) { package["licenseComments"] = serde_json::Value::String(format!("Declared: {raw}")); } if let Some(c) = &e.concluded { if !c.copyright.is_empty() { package["copyrightText"] = serde_json::Value::String(c.copyright.join("\n")); } let by = c.by_name.as_deref().unwrap_or(&c.by); let mut note = format!( "Concluded by {by} on {} ({})", c.at.format("%Y-%m-%d"), c.category.as_str() ); if let Some(review) = &c.review { note.push_str(&format!( "; legal review: {} by {} on {}", review.decision.as_str(), review.by_name.as_deref().unwrap_or(&review.by), review.at.format("%Y-%m-%d") )); } package["licenseComments"] = serde_json::Value::String( match package["licenseComments"].as_str() { Some(declared) => format!("{declared}. {note}"), None => note, }, ); } if let (Some(cpe), Some(refs)) = (&e.cpe, package["externalRefs"].as_array_mut()) { refs.push(serde_json::json!({ "referenceCategory": "SECURITY", "referenceType": "cpe23Type", "referenceLocator": cpe, })); } if let Some(comment) = provenance_comment(e) { package["comment"] = serde_json::Value::String(comment); } package }) .collect(); let mut doc = 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, }); if !extracted.is_empty() { doc["hasExtractedLicensingInfos"] = serde_json::Value::Array(extracted); } doc } #[cfg(test)] mod tests { use super::*; use crate::models::{InImage, InImageBasis, VulnRef}; #[test] fn a_released_sbom_keeps_what_identifies_each_component_and_nothing_else() { let mut e = SbomEntry::new("t".into(), "pump-sdk".into(), "4.2".into(), "nuget".into()); e.purl = Some("pkg:nuget/pump-sdk@4.2".into()); e.cpe = Some("cpe:2.3:a:example:pump-sdk:4.2:*:*:*:*:*:*:*".into()); e.hashes = vec![ComponentHash { alg: "SHA-256".into(), content: "ab".repeat(32), }]; e.download_url = Some("https://internal.example/feed/pump-sdk.4.2.nupkg".into()); e.manufacturer_url = Some("https://example.com".into()); e.concluded = Some(concluded("LicenseRef-Pump-EULA", Some("Pump EULA"))); e.in_image = Some(InImage { basis: InImageBasis::Declared, images: vec!["pump-image".into()], }); e.known_vulnerabilities = vec![VulnRef { id: "CVE-2026-0001".into(), source: "osv".into(), severity: Some("HIGH".into()), url: None, exploitation: None, aliases: Vec::new(), }]; let product = ReleasedProduct { name: "DR-4 Firmware", version: "1.4.0", supplier: "Test Antriebstechnik", }; let doc = released_cyclonedx(std::slice::from_ref(&e), &product); let meta = &doc["metadata"]["component"]; assert_eq!(meta["name"], "DR-4 Firmware"); assert_eq!(meta["version"], "1.4.0"); assert_eq!(meta["supplier"]["name"], "Test Antriebstechnik"); assert!(doc.get("vulnerabilities").is_none(), "{doc}"); let component = doc["components"][0].as_object().unwrap(); let mut keys: Vec<&str> = component.keys().map(String::as_str).collect(); keys.sort_unstable(); assert_eq!( keys, ["bom-ref", "cpe", "hashes", "licenses", "name", "purl", "type", "version"], "nothing beyond identity, licences and hashes" ); assert_eq!(component["licenses"][0]["license"]["name"], "Pump EULA"); assert!(component["licenses"][0]["license"].get("text").is_none()); let text = doc.to_string(); for leaked in [ "internal.example", "pump-image", "contract 4711", "CVE-2026-0001", ] { assert!(!text.contains(leaked), "{leaked} crossed: {text}"); } // The product still depends on its component. assert_eq!(doc["dependencies"][0]["dependsOn"][0], component["bom-ref"]); } #[test] fn a_released_purl_names_no_address() { let entry = |purl: &str| { let mut e = SbomEntry::new("t".into(), "pump-fw".into(), "1.0".into(), "yocto".into()); e.purl = Some(purl.into()); e }; let entries = [ entry("pkg:generic/pump-fw@1.0?vcs_url=git%2Bhttps%3A%2F%2Fgit.internal.example%2Fpump-fw.git"), entry("pkg:generic/pump-fw@1.0?download_url=http%3A%2F%2Fdl.internal.example%2Fpump.tgz&arch=arm"), ]; let product = ReleasedProduct { name: "DR-4 Firmware", version: "1.4.0", supplier: "Test Antriebstechnik", }; let doc = released_cyclonedx(&entries, &product); assert!(!doc.to_string().contains("internal.example"), "{doc}"); let purls: Vec<&str> = doc["components"] .as_array() .unwrap() .iter() .map(|c| c["purl"].as_str().unwrap()) .collect(); assert_eq!( purls, [ "pkg:generic/pump-fw@1.0", "pkg:generic/pump-fw@1.0?arch=arm" ] ); assert_eq!( without_addresses("pkg:npm/lodash@4.17.21"), "pkg:npm/lodash@4.17.21" ); assert_eq!( without_addresses("pkg:generic/a@1?vcs_url=x#src/lib"), "pkg:generic/a@1#src/lib" ); } #[test] fn released_bom_refs_stay_unique() { let mut components = vec![ serde_json::json!({ "bom-ref": "pkg:generic/a@1" }), serde_json::json!({ "bom-ref": "pkg:generic/a@1" }), serde_json::json!({ "bom-ref": "pkg:generic/b@1" }), ]; unique_refs(&mut components); let refs: Vec<&str> = components .iter() .map(|c| c["bom-ref"].as_str().unwrap()) .collect(); assert_eq!( refs, ["pkg:generic/a@1", "pkg:generic/a@1 (2)", "pkg:generic/b@1"] ); } #[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"); } #[test] fn known_license_names_are_exported_as_spdx_ids() { let entries: Vec = [ "The Apache Software License, Version 2.0", "https://opensource.org/licenses/MIT", "Custom Pump License", "MIT OR Apache-2.0", ] .into_iter() .enumerate() .map(|(i, license)| { let mut e = SbomEntry::new("t".into(), format!("c{i}"), "1".into(), "maven".into()); e.license = Some(license.into()); e }) .collect(); let cdx = cyclonedx(&entries, "t"); let licenses = |i: usize| &cdx["components"][i]["licenses"][0]; assert_eq!(licenses(0)["license"]["id"], "Apache-2.0"); assert!(licenses(0)["license"].get("name").is_none()); assert_eq!(licenses(1)["license"]["id"], "MIT"); assert_eq!(licenses(2)["license"]["name"], "Custom Pump License"); assert!(licenses(2)["license"].get("id").is_none()); assert_eq!(licenses(3)["expression"], "MIT OR Apache-2.0"); let spdx = spdx(&entries, "t"); let package = |i: usize| &spdx["packages"][i]; for i in 0..4 { assert_eq!(package(i)["licenseConcluded"], "NOASSERTION"); } assert_eq!(package(0)["licenseDeclared"], "Apache-2.0"); assert_eq!(package(1)["licenseDeclared"], "MIT"); assert_eq!(package(2)["licenseDeclared"], "NOASSERTION"); assert_eq!( package(2)["licenseComments"], "Declared: Custom Pump License" ); assert_eq!(package(3)["licenseDeclared"], "MIT OR Apache-2.0"); assert!(package(3).get("licenseComments").is_none()); } #[test] fn a_yocto_recipe_says_it_is_not_the_image_sbom_in_both_formats() { let mut recipe = SbomEntry::new( "t".into(), "busybox".into(), "1.35.0".into(), YOCTO_RECIPE_MANAGER.into(), ); recipe.purl = Some("pkg:generic/busybox@1.35.0".into()); recipe.cpe = Some("cpe:2.3:a:*:busybox:1.35.0:*:*:*:*:*:*:*".into()); let other = SbomEntry::new("t".into(), "lwIP".into(), "2.1.2".into(), "embedded".into()); let entries = [recipe, other]; let cdx = cyclonedx(&entries, "t"); let component = &cdx["components"][0]; assert_eq!(component["cpe"], "cpe:2.3:a:*:busybox:1.35.0:*:*:*:*:*:*:*"); assert_eq!( component["properties"], serde_json::json!([{ "name": SOURCE_PROPERTY, "value": YOCTO_RECIPE_SOURCE }]) ); assert!(cdx["components"][1].get("properties").is_none()); let spdx = spdx(&entries, "t"); let package = &spdx["packages"][0]; assert_eq!(package["comment"], YOCTO_RECIPE_SOURCE); assert_eq!(package["externalRefs"][1]["referenceType"], "cpe23Type"); assert!(spdx["packages"][1].get("comment").is_none()); } #[test] fn a_recipe_an_image_installs_says_so_in_both_formats() { let mut recipe = SbomEntry::new( "t".into(), "busybox".into(), "1.35.0".into(), YOCTO_RECIPE_MANAGER.into(), ); recipe.in_image = Some(InImage { basis: InImageBasis::Declared, images: vec!["pump-image".into(), "rescue-image".into()], }); let inventory_only = SbomEntry::new( "t".into(), "pump-fw".into(), "1.0".into(), YOCTO_RECIPE_MANAGER.into(), ); let entries = [recipe, inventory_only]; let cdx = cyclonedx(&entries, "t"); assert_eq!( cdx["components"][0]["properties"], serde_json::json!([ { "name": SOURCE_PROPERTY, "value": YOCTO_RECIPE_SOURCE }, { "name": IN_IMAGE_PROPERTY, "value": "declared: pump-image, rescue-image" }, ]) ); assert_eq!( cdx["components"][1]["properties"], serde_json::json!([{ "name": SOURCE_PROPERTY, "value": YOCTO_RECIPE_SOURCE }]) ); let spdx = spdx(&entries, "t"); assert_eq!( spdx["packages"][0]["comment"], format!( "{YOCTO_RECIPE_SOURCE}. In the image (declared in the recipes, not resolved \ by bitbake): pump-image, rescue-image" ) ); assert_eq!(spdx["packages"][1]["comment"], YOCTO_RECIPE_SOURCE); } fn concluded(license: &str, name: Option<&str>) -> LicenseConclusion { use crate::models::license::{conclusion_id, package_key}; let key = package_key("pump-sdk", "nuget", None); LicenseConclusion { id: conclusion_id(&key, None), package_key: key, name: "pump-sdk".into(), package_manager: "nuget".into(), version: None, license: license.into(), license_name: name.map(String::from), category: crate::models::LicenseCategory::Proprietary, copyright: vec!["© 2019 Example GmbH".into()], license_text: Some("All rights reserved.".into()), license_url: None, evidence: Some("contract 4711".into()), contract_ref: Some("4711".into()), valid_until: chrono::NaiveDate::from_ymd_opt(2027, 12, 31), usage: Some(crate::models::LicenseUsage::Shipped), note: None, by: "u1".into(), by_name: Some("Erika Muster".into()), support: false, at: chrono::Utc::now(), review: None, } } #[test] fn a_confirmed_custom_licence_is_concluded_and_defined() { let mut e = SbomEntry::new("t".into(), "pump-sdk".into(), "3.1".into(), "nuget".into()); e.license = Some("LicenseRef-file".into()); e.concluded = Some(concluded("LicenseRef-Pump-EULA", Some("Pump EULA"))); let cdx = cyclonedx(std::slice::from_ref(&e), "t"); let comp = &cdx["components"][0]; assert_eq!(comp["licenses"][0]["license"]["name"], "Pump EULA"); assert_eq!( comp["licenses"][0]["license"]["acknowledgement"], "concluded" ); assert_eq!( comp["licenses"][0]["license"]["text"]["content"], "All rights reserved." ); assert_eq!(comp["copyright"], "© 2019 Example GmbH"); let props = comp["properties"].as_array().unwrap(); let prop = |n: &str| { props .iter() .find(|p| p["name"] == n) .map(|p| p["value"].clone()) }; assert_eq!( prop("pruefwerk:license:category"), Some("proprietary".into()) ); assert_eq!( prop(DECLARED_LICENSE_PROPERTY), Some("LicenseRef-file".into()) ); assert_eq!( prop("pruefwerk:license:valid_until"), Some("2027-12-31".into()) ); assert_eq!(prop("pruefwerk:license:usage"), Some("shipped".into())); let spdx = spdx(&[e], "t"); let package = &spdx["packages"][0]; assert_eq!(package["licenseConcluded"], "LicenseRef-Pump-EULA"); assert_eq!(package["copyrightText"], "© 2019 Example GmbH"); assert!(package["licenseComments"] .as_str() .unwrap() .contains("Concluded by Erika Muster")); let info = &spdx["hasExtractedLicensingInfos"][0]; assert_eq!(info["licenseId"], "LicenseRef-Pump-EULA"); assert_eq!(info["extractedText"], "All rights reserved."); } #[test] fn a_confirmed_spdx_licence_replaces_the_declared_one() { let mut one = SbomEntry::new("t".into(), "a".into(), "1".into(), "npm".into()); one.concluded = Some(concluded("MIT", None)); let mut two = SbomEntry::new("t".into(), "b".into(), "1".into(), "npm".into()); two.license = Some("MIT".into()); two.concluded = Some(concluded("MIT OR Apache-2.0", None)); let cdx = cyclonedx(&[one.clone(), two.clone()], "t"); assert_eq!(cdx["components"][0]["licenses"][0]["license"]["id"], "MIT"); assert_eq!( cdx["components"][0]["licenses"][0]["license"]["acknowledgement"], "concluded" ); assert_eq!( cdx["components"][1]["licenses"][0]["expression"], "MIT OR Apache-2.0" ); assert_eq!( cdx["components"][1]["licenses"].as_array().unwrap().len(), 1 ); let spdx = spdx(&[one, two], "t"); assert_eq!(spdx["packages"][0]["licenseConcluded"], "MIT"); assert_eq!(spdx["packages"][0]["licenseDeclared"], "NOASSERTION"); assert_eq!(spdx["packages"][1]["licenseConcluded"], "MIT OR Apache-2.0"); assert_eq!(spdx["packages"][1]["licenseDeclared"], "MIT"); assert!(spdx.get("hasExtractedLicensingInfos").is_none()); } }