817 lines
33 KiB
Rust
817 lines
33 KiB
Rust
//! 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 `<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 {
|
|
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<serde_json::Value> {
|
|
let mut props = vec![serde_json::json!({
|
|
"name": "pruefwerk:license:category",
|
|
"value": c.category.as_str(),
|
|
})];
|
|
let mut push = |name: &str, value: Option<String>| {
|
|
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<String> {
|
|
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<serde_json::Value> {
|
|
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<serde_json::Value> {
|
|
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<String> {
|
|
let notes: Vec<String> = 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<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,
|
|
});
|
|
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<String> {
|
|
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<serde_json::Value> = 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<String>,
|
|
}
|
|
|
|
/// 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);
|
|
// One vulnerability per CVE (or advisory without one), affecting every
|
|
// component it was found in, by whichever scanner and id.
|
|
let mut vulns: Vec<SbomVulnerability<'_>> = 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();
|
|
}
|
|
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<serde_json::Value> = 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<serde_json::Value> = 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};
|
|
|
|
#[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<SbomEntry> = [
|
|
"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());
|
|
}
|
|
}
|