feat(sbom): a supplier's SBOM of a bought-in component is scanned for known CVEs (#1025) #1030
No files matched your search
@@ -733,7 +733,8 @@ pub struct UploadArtifactForm {
|
||||
#[schema(value_type = String, format = Binary)]
|
||||
file: Vec<u8>,
|
||||
/// What the file is, such as `plc_project`, `firmware_image`,
|
||||
/// `source_archive` or `mobile_package`.
|
||||
/// `source_archive`, `mobile_package`, `build_output` or `supplier_sbom`
|
||||
/// (a supplier's CycloneDX or SPDX 2 SBOM of a bought-in component).
|
||||
#[schema(example = "source_archive")]
|
||||
kind: String,
|
||||
/// The PLC project's format, for a PLC project.
|
||||
@@ -742,7 +743,8 @@ pub struct UploadArtifactForm {
|
||||
|
||||
/// Attach an artifact to a target by uploading its file.
|
||||
///
|
||||
/// A PLC project, firmware image, source archive or mobile package.
|
||||
/// A PLC project, firmware image, source archive, mobile package, build
|
||||
/// output or a supplier's SBOM of a bought-in component.
|
||||
///
|
||||
/// The file is **streamed to disk** chunk by chunk as it arrives, never held in
|
||||
/// memory whole (it used to be read into one buffer of up to 512 MiB, per
|
||||
@@ -762,8 +764,9 @@ pub struct UploadArtifactForm {
|
||||
(status = 200, description = "The target with the artifact"),
|
||||
(status = 404, description = "No such target"),
|
||||
(status = 400, description = "Not an id, or a missing or unknown field"),
|
||||
(status = 413, description = "The file is too large"),
|
||||
(status = 413, description = "The file is too large (a supplier SBOM: over 20 MiB)"),
|
||||
(status = 415, description = "An archive format that cannot be unpacked"),
|
||||
(status = 422, description = "A supplier SBOM that cannot be read; `error` says why"),
|
||||
(status = 401, description = "No valid bearer token"),
|
||||
)
|
||||
)]
|
||||
@@ -773,18 +776,17 @@ pub async fn upload_artifact(
|
||||
tenant: TenantCtx,
|
||||
Path(id): Path<String>,
|
||||
mut multipart: Multipart,
|
||||
) -> Result<Json<ApiResponse<OnboardedTarget>>, StatusCode> {
|
||||
) -> Result<Json<ApiResponse<OnboardedTarget>>, UploadRefusal> {
|
||||
let oid = parse_oid(&id)?;
|
||||
let db = tenant_db(&agent, &tenant).await?;
|
||||
if db
|
||||
let Some(stored_target) = db
|
||||
.onboarded_targets()
|
||||
.find_one(doc! { "_id": oid })
|
||||
.await
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?
|
||||
.is_none()
|
||||
{
|
||||
return Err(StatusCode::NOT_FOUND);
|
||||
}
|
||||
else {
|
||||
return Err(StatusCode::NOT_FOUND.into());
|
||||
};
|
||||
|
||||
let mut kind: Option<ArtifactKind> = None;
|
||||
let mut plc_format: Option<PlcFormat> = None;
|
||||
@@ -805,7 +807,7 @@ pub async fn upload_artifact(
|
||||
}
|
||||
"file" => {
|
||||
if stored.is_some() {
|
||||
return Err(StatusCode::BAD_REQUEST);
|
||||
return Err(StatusCode::BAD_REQUEST.into());
|
||||
}
|
||||
if let Some(fname) = field.file_name() {
|
||||
filename = fname.to_string();
|
||||
@@ -821,7 +823,7 @@ pub async fn upload_artifact(
|
||||
}
|
||||
|
||||
let (Some(kind), Some(upload)) = (kind, stored) else {
|
||||
return Err(StatusCode::BAD_REQUEST);
|
||||
return Err(StatusCode::BAD_REQUEST.into());
|
||||
};
|
||||
// Non-file kinds (git repo, live URL, container ref, text) use the JSON
|
||||
// add-artifact endpoint, not upload.
|
||||
@@ -835,10 +837,12 @@ pub async fn upload_artifact(
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||
artifact.content_hash = Some(sha);
|
||||
if kind != ArtifactKind::FirmwareImage {
|
||||
if kind == ArtifactKind::SupplierSbom {
|
||||
check_supplier_sbom(&upload, &filename).await?;
|
||||
} else if kind != ArtifactKind::FirmwareImage {
|
||||
match archive_check(upload.path.clone()).await? {
|
||||
// 7z and rar are never unpacked: say so now, not after a scan.
|
||||
ArchiveCheck::Unsupported => return Err(StatusCode::UNSUPPORTED_MEDIA_TYPE),
|
||||
ArchiveCheck::Unsupported => return Err(StatusCode::UNSUPPORTED_MEDIA_TYPE.into()),
|
||||
// Kept, and marked: the dashboard asks for the password.
|
||||
ArchiveCheck::Encrypted => {
|
||||
artifact
|
||||
@@ -849,6 +853,7 @@ pub async fn upload_artifact(
|
||||
}
|
||||
}
|
||||
|
||||
let artifact_id = artifact.id.clone();
|
||||
let artifact_bson = to_bson(&artifact).map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||
db.onboarded_targets()
|
||||
.update_one(
|
||||
@@ -858,8 +863,96 @@ pub async fn upload_artifact(
|
||||
.await
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||
upload.keep();
|
||||
if kind == ArtifactKind::SupplierSbom {
|
||||
replace_supplier_sboms(&db, oid, &artifact_id, &stored_target.artifacts).await;
|
||||
}
|
||||
|
||||
get_target(Extension(agent), tenant, Path(id)).await
|
||||
Ok(get_target(Extension(agent), tenant, Path(id)).await?)
|
||||
}
|
||||
|
||||
/// Remove the target's supplier SBOMs other than the one just uploaded
|
||||
/// (`kept`): a new version replaces the one before it (#1025), so a scan never
|
||||
/// reads two versions as one. Their files go too, once nothing references
|
||||
/// them. Best-effort, after the new one is stored: if this fails, the next
|
||||
/// scan reads both versions, and nothing is lost.
|
||||
async fn replace_supplier_sboms(
|
||||
db: &crate::database::Database,
|
||||
target: ObjectId,
|
||||
kept: &str,
|
||||
before: &[compliance_core::models::Artifact],
|
||||
) {
|
||||
let pulled = db
|
||||
.onboarded_targets()
|
||||
.update_one(
|
||||
doc! { "_id": target },
|
||||
doc! { "$pull": { "artifacts": { "kind": "supplier_sbom", "id": { "$ne": kept } } } },
|
||||
)
|
||||
.await;
|
||||
if let Err(e) = pulled {
|
||||
tracing::warn!(target_id = %target, error = %e, "replaced supplier SBOM not removed");
|
||||
return;
|
||||
}
|
||||
for old in before
|
||||
.iter()
|
||||
.filter(|a| a.kind == ArtifactKind::SupplierSbom && a.id != kept)
|
||||
.filter_map(|a| a.stored_path.as_deref())
|
||||
{
|
||||
if let Err(e) = std::fs::remove_file(old) {
|
||||
tracing::warn!(target_id = %target, error = %e, "replaced supplier SBOM file left");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Why an upload is refused: its status and, for a supplier SBOM that cannot
|
||||
/// be read, why (as `{"error": …}`, for the dashboard to show).
|
||||
#[derive(Debug)]
|
||||
pub struct UploadRefusal {
|
||||
status: StatusCode,
|
||||
reason: Option<String>,
|
||||
}
|
||||
|
||||
impl From<StatusCode> for UploadRefusal {
|
||||
fn from(status: StatusCode) -> Self {
|
||||
Self {
|
||||
status,
|
||||
reason: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl axum::response::IntoResponse for UploadRefusal {
|
||||
fn into_response(self) -> axum::response::Response {
|
||||
match self.reason {
|
||||
Some(error) => {
|
||||
(self.status, Json(serde_json::json!({ "error": error }))).into_response()
|
||||
}
|
||||
None => self.status.into_response(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Check an uploaded supplier SBOM (#1025) before it is kept: one a scan
|
||||
/// cannot read is refused now, with the reason, not at the next scan.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// 413 past [`crate::pipeline::sbom::supplied::MAX_BYTES`], 422 with the
|
||||
/// reason for one that cannot be read.
|
||||
async fn check_supplier_sbom(upload: &StoredUpload, filename: &str) -> Result<(), UploadRefusal> {
|
||||
use crate::pipeline::sbom::supplied::{self, SuppliedSbomError};
|
||||
let (path, name) = (upload.path.clone(), filename.to_string());
|
||||
let read = tokio::task::spawn_blocking(move || supplied::read(&path, "", &name))
|
||||
.await
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||
match read {
|
||||
Ok(_) => Ok(()),
|
||||
Err(SuppliedSbomError::TooLarge) => Err(StatusCode::PAYLOAD_TOO_LARGE.into()),
|
||||
Err(SuppliedSbomError::Io(_)) => Err(StatusCode::INTERNAL_SERVER_ERROR.into()),
|
||||
Err(e) => Err(UploadRefusal {
|
||||
status: StatusCode::UNPROCESSABLE_ENTITY,
|
||||
reason: Some(e.to_string()),
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
/// The fact an upload records on a password-protected archive.
|
||||
|
||||
@@ -189,8 +189,9 @@ pub fn ingest_artifact(
|
||||
ArtifactKind::SourceArchive | ArtifactKind::MobilePackage | ArtifactKind::PlcProject => {
|
||||
ingest_blob(artifact, ctx, true)
|
||||
}
|
||||
// Stored as uploaded: the SPDX reader opens the archive itself.
|
||||
ArtifactKind::FirmwareImage | ArtifactKind::BuildOutput => {
|
||||
// Stored as uploaded: the SPDX reader opens the archive itself, and a
|
||||
// supplier's SBOM is read as the document it is.
|
||||
ArtifactKind::FirmwareImage | ArtifactKind::BuildOutput | ArtifactKind::SupplierSbom => {
|
||||
ingest_blob(artifact, ctx, false)
|
||||
}
|
||||
ArtifactKind::ContainerImage => Ok(metadata_only(
|
||||
|
||||
@@ -565,6 +565,10 @@ const PURL_TYPES_WITHOUT_OSV: &[&str] = &["pkg:cocoapods/"];
|
||||
/// Whether `entry` belongs to a package manager OSV has no advisories for.
|
||||
fn without_osv_advisories(entry: &SbomEntry) -> bool {
|
||||
entry.package_manager == crate::pipeline::sbom::unity::UNITY_MANAGER
|
||||
// A supplier SBOM's component without a purl (#1025): nothing else
|
||||
// looks it up, so it is not checked rather than free of CVEs.
|
||||
|| (entry.package_manager == crate::pipeline::sbom::supplied::SUPPLIER_MANAGER
|
||||
&& entry.purl.is_none())
|
||||
|| entry
|
||||
.purl
|
||||
.as_deref()
|
||||
@@ -687,6 +691,35 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_supplier_sboms_components_are_matched_like_any_others() {
|
||||
// #1025: the parts of a bought-in component, read from its
|
||||
// supplier's CycloneDX SBOM, go through the same OSV lookup; one
|
||||
// without a purl is reported as not checked, not as free of CVEs.
|
||||
let (url, hits) = fake_osv().await;
|
||||
let scanner = CveScanner::new(NetGuard::allow_private(), None)
|
||||
.unwrap()
|
||||
.with_osv_api(url);
|
||||
let sbom = r#"{"bomFormat": "CycloneDX", "specVersion": "1.5", "components": [
|
||||
{"type": "library", "name": "lodash", "version": "4.17.20",
|
||||
"purl": "pkg:npm/lodash@4.17.20"},
|
||||
{"type": "library", "name": "vendor-blob", "version": "2.0"}
|
||||
]}"#;
|
||||
let mut entries =
|
||||
crate::pipeline::sbom::supplied::parse(sbom.as_bytes(), "t", "pump.cdx.json").unwrap();
|
||||
|
||||
let lookup = scanner.scan_dependencies("t", &mut entries).await.unwrap();
|
||||
|
||||
assert_eq!(hits.load(Ordering::SeqCst), 1);
|
||||
assert_eq!(lookup.alerts.len(), 1);
|
||||
assert_eq!(lookup.alerts[0].affected_package, "lodash");
|
||||
assert_eq!(
|
||||
lookup.alerts[0].purl.as_deref(),
|
||||
Some("pkg:npm/lodash@4.17.20")
|
||||
);
|
||||
assert_eq!(lookup.unchecked, ["vendor-blob 2.0"]);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn yocto_recipes_are_left_to_nvd_not_asked_of_osv() {
|
||||
let (url, hits) = fake_osv().await;
|
||||
|
||||
@@ -634,7 +634,13 @@ impl PipelineOrchestrator {
|
||||
&repo_id,
|
||||
));
|
||||
let yocto_recipes = yocto.recipes;
|
||||
for entry in embedded.into_iter().chain(codesys).chain(yocto_entries) {
|
||||
let supplied = self.read_supplier_sboms(repo, &repo_id).await?;
|
||||
for entry in embedded
|
||||
.into_iter()
|
||||
.chain(codesys)
|
||||
.chain(yocto_entries)
|
||||
.chain(supplied)
|
||||
{
|
||||
let known = sbom_entries
|
||||
.iter()
|
||||
.any(|e| e.name.eq_ignore_ascii_case(&entry.name) && e.version == entry.version);
|
||||
@@ -1798,6 +1804,7 @@ impl PipelineOrchestrator {
|
||||
let mut repo = RepoView::from_target(target, code, &self.secrets);
|
||||
repo.yocto_layers = yocto_layers;
|
||||
repo.build_outputs = build_output_paths(target, &working_paths);
|
||||
repo.supplier_sboms = supplier_sbom_paths(target, &working_paths);
|
||||
let n = self.run_pipeline(&repo, scan_run_id, trigger).await?;
|
||||
self.finalize_target(target, &repo, n).await?;
|
||||
new_count += n;
|
||||
@@ -1815,6 +1822,7 @@ impl PipelineOrchestrator {
|
||||
let mut repo = RepoView::from_target(target, code, &self.secrets);
|
||||
repo.yocto_layers = yocto_layers;
|
||||
repo.build_outputs = build_output_paths(target, &working_paths);
|
||||
repo.supplier_sboms = supplier_sbom_paths(target, &working_paths);
|
||||
let upload = crate::pipeline::plc::sbom::uploaded_archive(code);
|
||||
let n = self.scan_tree(tree, upload, &repo, scan_run_id).await?;
|
||||
self.finalize_target(target, &repo, n).await?;
|
||||
@@ -1837,7 +1845,11 @@ impl PipelineOrchestrator {
|
||||
// Only what a build wrote about its image (an image SPDX archive,
|
||||
// a cve-check report): the same stages run over an empty tree, so
|
||||
// the SBOM, CVEs and VEX come from the build output alone.
|
||||
None if target.has(ArtifactKind::BuildOutput) => {
|
||||
// Or only a supplier's SBOM of a bought-in component (#1025): the
|
||||
// same, with the components read from it.
|
||||
None if target.has(ArtifactKind::BuildOutput)
|
||||
|| target.has(ArtifactKind::SupplierSbom) =>
|
||||
{
|
||||
new_count += self
|
||||
.scan_build_output_only(target, &target_id, &working_paths, scan_run_id)
|
||||
.await?;
|
||||
@@ -3126,10 +3138,11 @@ impl PipelineOrchestrator {
|
||||
/// The recipes, images and package groups of a Yocto layer tree. A parser
|
||||
/// that failed, a tree with no layer, or recipes the parser could not read
|
||||
/// are recorded on the run.
|
||||
/// Scan a target whose only code-like input is its build output: the
|
||||
/// stages run over an empty working directory (nothing to find there),
|
||||
/// with the build outputs read as for a layer tree. The run says that
|
||||
/// there was no source code.
|
||||
/// Scan a target whose only code-like input is its build output or a
|
||||
/// supplier's SBOM: the stages run over an empty working directory
|
||||
/// (nothing to find there), with the build outputs read as for a layer
|
||||
/// tree and the supplier SBOMs as SBOMs. The run says that there was no
|
||||
/// source code.
|
||||
///
|
||||
/// # Returns
|
||||
///
|
||||
@@ -3146,11 +3159,12 @@ impl PipelineOrchestrator {
|
||||
working_paths: &std::collections::HashMap<String, std::path::PathBuf>,
|
||||
scan_run_id: &str,
|
||||
) -> Result<u32, AgentError> {
|
||||
let Some(first) = target
|
||||
.artifacts
|
||||
.iter()
|
||||
.find(|a| a.kind == ArtifactKind::BuildOutput)
|
||||
else {
|
||||
let Some(first) = target.artifacts.iter().find(|a| {
|
||||
matches!(
|
||||
a.kind,
|
||||
ArtifactKind::BuildOutput | ArtifactKind::SupplierSbom
|
||||
)
|
||||
}) else {
|
||||
return Ok(0);
|
||||
};
|
||||
self.skip_stage(
|
||||
@@ -3159,8 +3173,8 @@ impl PipelineOrchestrator {
|
||||
"source_code",
|
||||
SkipCode::NotAnalysedYet,
|
||||
"the target has no source code (a git repository or a source archive): only \
|
||||
its build output is read; code analysis, the recipe inventory and the recipe \
|
||||
lint need the layer tree",
|
||||
its build output or supplier SBOM is read; code analysis, the recipe \
|
||||
inventory and the recipe lint need the code",
|
||||
),
|
||||
)
|
||||
.await;
|
||||
@@ -3176,6 +3190,7 @@ impl PipelineOrchestrator {
|
||||
.map_err(|e| AgentError::Other(format!("build-output work directory: {e}")))?;
|
||||
let mut repo = RepoView::from_target(target, first, &self.secrets);
|
||||
repo.build_outputs = build_output_paths(target, working_paths);
|
||||
repo.supplier_sboms = supplier_sbom_paths(target, working_paths);
|
||||
let scanned = self.scan_tree(&tree, None, &repo, scan_run_id).await;
|
||||
let _ = std::fs::remove_dir_all(&tree);
|
||||
let n = scanned?;
|
||||
@@ -3183,6 +3198,34 @@ impl PipelineOrchestrator {
|
||||
Ok(n)
|
||||
}
|
||||
|
||||
/// The components of the target's supplier SBOMs (#1025), read on a
|
||||
/// blocking thread.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// One that cannot be read fails the scan, with the reason: read as
|
||||
/// empty, it would let a complete CVE check take every known CVE of the
|
||||
/// component for gone.
|
||||
async fn read_supplier_sboms(
|
||||
&self,
|
||||
repo: &RepoView,
|
||||
repo_id: &str,
|
||||
) -> Result<Vec<compliance_core::models::SbomEntry>, AgentError> {
|
||||
let mut entries = Vec::new();
|
||||
for (path, label) in &repo.supplier_sboms {
|
||||
let (file, id, name) = (path.clone(), repo_id.to_string(), label.clone());
|
||||
let read = tokio::task::spawn_blocking(move || {
|
||||
crate::pipeline::sbom::supplied::read(&file, &id, &name)
|
||||
})
|
||||
.await
|
||||
.map_err(|e| AgentError::Other(format!("reading the supplier SBOM {label}: {e}")))?;
|
||||
entries.extend(read.map_err(|e| {
|
||||
AgentError::Other(format!("the supplier SBOM {label} cannot be read: {e}"))
|
||||
})?);
|
||||
}
|
||||
Ok(entries)
|
||||
}
|
||||
|
||||
/// What the target's build outputs say: the images their SPDX archives
|
||||
/// describe ([`crate::pipeline::yocto_spdx`]) and their cve-check reports
|
||||
/// ([`crate::pipeline::yocto_cve_check`]), told apart by content. One
|
||||
@@ -3573,17 +3616,40 @@ fn build_output_paths(
|
||||
target: &OnboardedTarget,
|
||||
working_paths: &std::collections::HashMap<String, std::path::PathBuf>,
|
||||
) -> Vec<std::path::PathBuf> {
|
||||
artifacts_of(target, ArtifactKind::BuildOutput, working_paths)
|
||||
.map(|(_, path)| path)
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The target's supplier SBOMs (#1025) as ingested, each with the name it
|
||||
/// was uploaded under.
|
||||
fn supplier_sbom_paths(
|
||||
target: &OnboardedTarget,
|
||||
working_paths: &std::collections::HashMap<String, std::path::PathBuf>,
|
||||
) -> Vec<(std::path::PathBuf, String)> {
|
||||
artifacts_of(target, ArtifactKind::SupplierSbom, working_paths)
|
||||
.map(|(artifact, path)| (path, artifact.source_ref.clone()))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The target's artifacts of `kind` with the path each was ingested to (or
|
||||
/// stored at, when this run did not ingest it).
|
||||
fn artifacts_of<'a>(
|
||||
target: &'a OnboardedTarget,
|
||||
kind: ArtifactKind,
|
||||
working_paths: &'a std::collections::HashMap<String, std::path::PathBuf>,
|
||||
) -> impl Iterator<Item = (&'a compliance_core::models::Artifact, std::path::PathBuf)> + 'a {
|
||||
target
|
||||
.artifacts
|
||||
.iter()
|
||||
.filter(|a| a.kind == ArtifactKind::BuildOutput)
|
||||
.filter(move |a| a.kind == kind)
|
||||
.filter_map(|a| {
|
||||
working_paths
|
||||
.get(&a.id)
|
||||
.cloned()
|
||||
.or_else(|| a.stored_path.as_deref().map(std::path::PathBuf::from))
|
||||
.map(|path| (a, path))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -60,6 +60,9 @@ pub struct RepoView {
|
||||
/// The target's uploaded build outputs (Yocto image SPDX archives), as
|
||||
/// ingested. Set by the caller; empty from [`Self::from_target`].
|
||||
pub build_outputs: Vec<std::path::PathBuf>,
|
||||
/// The target's supplier SBOMs (#1025) as ingested, each with the name it
|
||||
/// was uploaded under. Set by the caller; empty from [`Self::from_target`].
|
||||
pub supplier_sboms: Vec<(std::path::PathBuf, String)>,
|
||||
}
|
||||
|
||||
impl RepoView {
|
||||
@@ -95,6 +98,7 @@ impl RepoView {
|
||||
yocto_layers: false,
|
||||
exclude_paths: target.scan_config.exclude_paths.clone(),
|
||||
build_outputs: Vec::new(),
|
||||
supplier_sboms: Vec::new(),
|
||||
};
|
||||
if let Some(git) = &code.git {
|
||||
view.default_branch = git.default_branch.clone();
|
||||
|
||||
@@ -16,6 +16,7 @@ pub(crate) use nuget::nuget_components;
|
||||
pub(crate) use nuget_license::{LicenseCache, MongoLicenseCache, NugetRegistry};
|
||||
pub(crate) use nuget_resolve::enabled as nuget_resolution_enabled;
|
||||
pub(crate) use registry_license::RegistryLicenses;
|
||||
pub(crate) mod supplied;
|
||||
mod syft;
|
||||
pub(crate) mod unity;
|
||||
|
||||
|
||||
@@ -0,0 +1,556 @@
|
||||
//! A component's SBOM as its supplier delivered it (#1025): CycloneDX 1.x
|
||||
//! (JSON or XML) or SPDX 2.x JSON, read into SBOM entries for the CVE stage.
|
||||
//!
|
||||
//! The file comes from outside, so it is read defensively: it is capped in
|
||||
//! size and in components, XML is read without a DTD (no entity of any kind
|
||||
//! is resolved), and an SBOM that cannot be read, or lists no component, is
|
||||
//! an error with its reason, never an empty SBOM. An empty one would let a
|
||||
//! complete CVE check take every known CVE of the component for gone.
|
||||
//!
|
||||
//! What is read of each component: its name (with its group), version, purl
|
||||
//! (in the form advisory databases look it up by), CPE and licence. The
|
||||
//! component the document describes (CycloneDX `metadata.component`, SPDX
|
||||
//! `documentDescribes`) is the product itself, not one of its parts, and is
|
||||
//! left out.
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
use compliance_core::models::SbomEntry;
|
||||
|
||||
use super::syft::{canonical_purl, extract_ecosystem_from_purl};
|
||||
|
||||
/// The largest supplier SBOM read, in bytes.
|
||||
pub const MAX_BYTES: u64 = 20 * 1024 * 1024;
|
||||
|
||||
/// The most components one supplier SBOM may list.
|
||||
pub const MAX_COMPONENTS: usize = 100_000;
|
||||
|
||||
/// The package manager of a supplier SBOM's component whose purl names
|
||||
/// none, or that has no purl.
|
||||
pub(crate) const SUPPLIER_MANAGER: &str = "supplier";
|
||||
|
||||
/// Why a supplier SBOM cannot be read.
|
||||
#[derive(Debug, thiserror::Error, PartialEq, Eq)]
|
||||
pub enum SuppliedSbomError {
|
||||
/// Larger than [`MAX_BYTES`].
|
||||
#[error("the SBOM is larger than {} MiB", MAX_BYTES / 1024 / 1024)]
|
||||
TooLarge,
|
||||
/// More components than [`MAX_COMPONENTS`].
|
||||
#[error("the SBOM lists more than {MAX_COMPONENTS} components")]
|
||||
TooManyComponents,
|
||||
/// No component at all: read as empty, it would let a complete CVE check
|
||||
/// take every known CVE of the component for gone.
|
||||
#[error("the SBOM lists no components")]
|
||||
Empty,
|
||||
/// Not a format this reads.
|
||||
#[error(
|
||||
"not a CycloneDX (JSON or XML) or SPDX 2 JSON document{0}; send the SBOM as CycloneDX \
|
||||
1.4-1.6 or SPDX 2.3 JSON"
|
||||
)]
|
||||
UnknownFormat(String),
|
||||
/// The format is recognised, but the document is not well-formed.
|
||||
#[error("the {format} document cannot be read: {reason}")]
|
||||
Malformed {
|
||||
/// The format it was recognised as.
|
||||
format: &'static str,
|
||||
/// What is wrong with it.
|
||||
reason: String,
|
||||
},
|
||||
/// The file cannot be opened or read.
|
||||
#[error("the SBOM file cannot be read: {0}")]
|
||||
Io(String),
|
||||
}
|
||||
|
||||
/// Read the supplier SBOM at `path` into the SBOM entries of target
|
||||
/// `repo_id`. Reads the file; call it on a blocking thread.
|
||||
///
|
||||
/// # Arguments
|
||||
///
|
||||
/// * `path` - the stored upload
|
||||
/// * `repo_id` - the target the entries belong to
|
||||
/// * `label` - what the entries' evidence names the SBOM by (the file name)
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// A [`SuppliedSbomError`] saying why the file is not read.
|
||||
pub fn read(path: &Path, repo_id: &str, label: &str) -> Result<Vec<SbomEntry>, SuppliedSbomError> {
|
||||
let size = std::fs::metadata(path)
|
||||
.map_err(|e| SuppliedSbomError::Io(e.to_string()))?
|
||||
.len();
|
||||
if size > MAX_BYTES {
|
||||
return Err(SuppliedSbomError::TooLarge);
|
||||
}
|
||||
let bytes = std::fs::read(path).map_err(|e| SuppliedSbomError::Io(e.to_string()))?;
|
||||
parse(&bytes, repo_id, label)
|
||||
}
|
||||
|
||||
/// [`read`] for a document already in memory.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// A [`SuppliedSbomError`] saying why the document is not read.
|
||||
pub fn parse(
|
||||
bytes: &[u8],
|
||||
repo_id: &str,
|
||||
label: &str,
|
||||
) -> Result<Vec<SbomEntry>, SuppliedSbomError> {
|
||||
if bytes.len() as u64 > MAX_BYTES {
|
||||
return Err(SuppliedSbomError::TooLarge);
|
||||
}
|
||||
let text = std::str::from_utf8(bytes)
|
||||
.map_err(|_| SuppliedSbomError::UnknownFormat(" (not UTF-8 text)".to_string()))?;
|
||||
let text = text.trim_start_matches('\u{feff}').trim_start();
|
||||
let components = match text.as_bytes().first() {
|
||||
Some(b'<') => cyclonedx_xml(text)?,
|
||||
Some(b'{') => json(text)?,
|
||||
_ => return Err(SuppliedSbomError::UnknownFormat(String::new())),
|
||||
};
|
||||
if components.len() > MAX_COMPONENTS {
|
||||
return Err(SuppliedSbomError::TooManyComponents);
|
||||
}
|
||||
if components.is_empty() {
|
||||
return Err(SuppliedSbomError::Empty);
|
||||
}
|
||||
Ok(components
|
||||
.into_iter()
|
||||
.map(|c| c.entry(repo_id, label))
|
||||
.collect())
|
||||
}
|
||||
|
||||
/// One component as the document names it.
|
||||
#[derive(Debug, Default, PartialEq)]
|
||||
struct Component {
|
||||
group: Option<String>,
|
||||
name: String,
|
||||
version: Option<String>,
|
||||
purl: Option<String>,
|
||||
cpe: Option<String>,
|
||||
license: Option<String>,
|
||||
}
|
||||
|
||||
impl Component {
|
||||
/// The SBOM entry of this component, of target `repo_id`.
|
||||
fn entry(self, repo_id: &str, label: &str) -> SbomEntry {
|
||||
let purl = non_blank(self.purl).map(canonical_purl);
|
||||
let manager = purl
|
||||
.as_deref()
|
||||
.and_then(extract_ecosystem_from_purl)
|
||||
.unwrap_or_else(|| SUPPLIER_MANAGER.to_string());
|
||||
let name = match non_blank(self.group) {
|
||||
Some(group) => format!("{group}/{}", self.name),
|
||||
None => self.name,
|
||||
};
|
||||
let version = non_blank(self.version).unwrap_or_else(|| "unknown".to_string());
|
||||
let mut entry = SbomEntry::new(repo_id.to_string(), name, version, manager);
|
||||
entry.purl = purl;
|
||||
entry.cpe = non_blank(self.cpe);
|
||||
entry.license = non_blank(self.license);
|
||||
entry.evidence = vec![format!("{label} (supplier SBOM)")];
|
||||
entry
|
||||
}
|
||||
}
|
||||
|
||||
/// `value` trimmed, `None` when blank.
|
||||
fn non_blank(value: Option<String>) -> Option<String> {
|
||||
value
|
||||
.map(|v| v.trim().to_string())
|
||||
.filter(|v| !v.is_empty())
|
||||
}
|
||||
|
||||
/// Whether a CycloneDX component of `kind` is a part of the product: files
|
||||
/// and data are not.
|
||||
fn is_part(kind: Option<&str>) -> bool {
|
||||
!matches!(kind, Some("file" | "data"))
|
||||
}
|
||||
|
||||
/// A JSON document: CycloneDX or SPDX 2, told apart by their markers.
|
||||
fn json(text: &str) -> Result<Vec<Component>, SuppliedSbomError> {
|
||||
let doc: serde_json::Value =
|
||||
serde_json::from_str(text).map_err(|e| SuppliedSbomError::Malformed {
|
||||
format: "JSON",
|
||||
reason: e.to_string(),
|
||||
})?;
|
||||
if doc.get("bomFormat").and_then(|v| v.as_str()) == Some("CycloneDX") {
|
||||
let mut out = Vec::new();
|
||||
cyclonedx_json_components(doc.get("components"), &mut out)?;
|
||||
return Ok(out);
|
||||
}
|
||||
match doc.get("spdxVersion").and_then(|v| v.as_str()) {
|
||||
Some(v) if v.starts_with("SPDX-2.") => spdx2(&doc),
|
||||
Some(v) => Err(SuppliedSbomError::UnknownFormat(format!(
|
||||
" ({v} is not read yet)"
|
||||
))),
|
||||
None if doc.get("@context").is_some() => Err(SuppliedSbomError::UnknownFormat(
|
||||
" (SPDX 3.0 is not read yet)".to_string(),
|
||||
)),
|
||||
None => Err(SuppliedSbomError::UnknownFormat(String::new())),
|
||||
}
|
||||
}
|
||||
|
||||
/// The components of a CycloneDX JSON `components` array, nested ones
|
||||
/// included, into `out`.
|
||||
fn cyclonedx_json_components(
|
||||
list: Option<&serde_json::Value>,
|
||||
out: &mut Vec<Component>,
|
||||
) -> Result<(), SuppliedSbomError> {
|
||||
let Some(list) = list.and_then(|v| v.as_array()) else {
|
||||
return Ok(());
|
||||
};
|
||||
for c in list {
|
||||
if out.len() > MAX_COMPONENTS {
|
||||
return Err(SuppliedSbomError::TooManyComponents);
|
||||
}
|
||||
let text = |key: &str| c.get(key).and_then(|v| v.as_str()).map(str::to_string);
|
||||
if is_part(c.get("type").and_then(|v| v.as_str())) {
|
||||
if let Some(name) = text("name").filter(|n| !n.trim().is_empty()) {
|
||||
out.push(Component {
|
||||
group: text("group"),
|
||||
name,
|
||||
version: text("version"),
|
||||
purl: text("purl"),
|
||||
cpe: text("cpe"),
|
||||
license: cyclonedx_json_license(c.get("licenses")),
|
||||
});
|
||||
}
|
||||
}
|
||||
cyclonedx_json_components(c.get("components"), out)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// A CycloneDX JSON `licenses` array as one licence: its expression, else
|
||||
/// the ids or names, all of which apply.
|
||||
fn cyclonedx_json_license(licenses: Option<&serde_json::Value>) -> Option<String> {
|
||||
let list = licenses?.as_array()?;
|
||||
if let Some(expr) = list
|
||||
.iter()
|
||||
.find_map(|l| l.get("expression").and_then(|v| v.as_str()))
|
||||
{
|
||||
return Some(expr.to_string());
|
||||
}
|
||||
let parts: Vec<&str> = list
|
||||
.iter()
|
||||
.filter_map(|l| l.get("license"))
|
||||
.filter_map(|l| {
|
||||
l.get("id")
|
||||
.or_else(|| l.get("name"))
|
||||
.and_then(|v| v.as_str())
|
||||
})
|
||||
.collect();
|
||||
(!parts.is_empty()).then(|| parts.join(" AND "))
|
||||
}
|
||||
|
||||
/// A CycloneDX XML document's components. roxmltree refuses a DTD by
|
||||
/// default, so no entity is ever expanded or fetched.
|
||||
fn cyclonedx_xml(text: &str) -> Result<Vec<Component>, SuppliedSbomError> {
|
||||
let doc = roxmltree::Document::parse(text).map_err(|e| SuppliedSbomError::Malformed {
|
||||
format: "XML",
|
||||
reason: e.to_string(),
|
||||
})?;
|
||||
let root = doc.root_element();
|
||||
let cyclonedx = root.tag_name().name() == "bom"
|
||||
&& root
|
||||
.tag_name()
|
||||
.namespace()
|
||||
.is_some_and(|ns| ns.starts_with("http://cyclonedx.org/schema/bom/"));
|
||||
if !cyclonedx {
|
||||
return Err(SuppliedSbomError::UnknownFormat(
|
||||
" (an XML document, but not a CycloneDX BOM)".to_string(),
|
||||
));
|
||||
}
|
||||
let mut out = Vec::new();
|
||||
if let Some(list) = child(root, "components") {
|
||||
cyclonedx_xml_components(list, &mut out)?;
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// The child element of `node` named `name`.
|
||||
fn child<'a, 'input>(
|
||||
node: roxmltree::Node<'a, 'input>,
|
||||
name: &str,
|
||||
) -> Option<roxmltree::Node<'a, 'input>> {
|
||||
node.children()
|
||||
.find(|n| n.is_element() && n.tag_name().name() == name)
|
||||
}
|
||||
|
||||
/// The text of `node`'s child element `name`.
|
||||
fn child_text(node: roxmltree::Node<'_, '_>, name: &str) -> Option<String> {
|
||||
child(node, name).and_then(|n| n.text()).map(str::to_string)
|
||||
}
|
||||
|
||||
/// The `component` elements of a CycloneDX XML `components` element, nested
|
||||
/// ones included, into `out`.
|
||||
fn cyclonedx_xml_components(
|
||||
list: roxmltree::Node<'_, '_>,
|
||||
out: &mut Vec<Component>,
|
||||
) -> Result<(), SuppliedSbomError> {
|
||||
for c in list
|
||||
.children()
|
||||
.filter(|n| n.is_element() && n.tag_name().name() == "component")
|
||||
{
|
||||
if out.len() > MAX_COMPONENTS {
|
||||
return Err(SuppliedSbomError::TooManyComponents);
|
||||
}
|
||||
if is_part(c.attribute("type")) {
|
||||
if let Some(name) = child_text(c, "name").filter(|n| !n.trim().is_empty()) {
|
||||
out.push(Component {
|
||||
group: child_text(c, "group"),
|
||||
name,
|
||||
version: child_text(c, "version"),
|
||||
purl: child_text(c, "purl"),
|
||||
cpe: child_text(c, "cpe"),
|
||||
license: child(c, "licenses").and_then(cyclonedx_xml_license),
|
||||
});
|
||||
}
|
||||
}
|
||||
if let Some(nested) = child(c, "components") {
|
||||
cyclonedx_xml_components(nested, out)?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// A CycloneDX XML `licenses` element as one licence, as for JSON.
|
||||
fn cyclonedx_xml_license(licenses: roxmltree::Node<'_, '_>) -> Option<String> {
|
||||
if let Some(expr) = child_text(licenses, "expression") {
|
||||
return Some(expr);
|
||||
}
|
||||
let parts: Vec<String> = licenses
|
||||
.children()
|
||||
.filter(|n| n.is_element() && n.tag_name().name() == "license")
|
||||
.filter_map(|l| child_text(l, "id").or_else(|| child_text(l, "name")))
|
||||
.collect();
|
||||
(!parts.is_empty()).then(|| parts.join(" AND "))
|
||||
}
|
||||
|
||||
/// The packages of an SPDX 2 JSON document, but the ones it describes.
|
||||
fn spdx2(doc: &serde_json::Value) -> Result<Vec<Component>, SuppliedSbomError> {
|
||||
let described: Vec<&str> = doc
|
||||
.get("documentDescribes")
|
||||
.and_then(|v| v.as_array())
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter_map(|v| v.as_str())
|
||||
.chain(
|
||||
doc.get("relationships")
|
||||
.and_then(|v| v.as_array())
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter(|r| r.get("relationshipType").and_then(|v| v.as_str()) == Some("DESCRIBES"))
|
||||
.filter_map(|r| r.get("relatedSpdxElement").and_then(|v| v.as_str())),
|
||||
)
|
||||
.collect();
|
||||
let packages = doc
|
||||
.get("packages")
|
||||
.and_then(|v| v.as_array())
|
||||
.ok_or_else(|| SuppliedSbomError::Malformed {
|
||||
format: "SPDX",
|
||||
reason: "it lists no packages".to_string(),
|
||||
})?;
|
||||
if packages.len() > MAX_COMPONENTS + described.len() {
|
||||
return Err(SuppliedSbomError::TooManyComponents);
|
||||
}
|
||||
Ok(packages
|
||||
.iter()
|
||||
.filter(|p| {
|
||||
p.get("SPDXID")
|
||||
.and_then(|v| v.as_str())
|
||||
.is_none_or(|id| !described.contains(&id))
|
||||
})
|
||||
.filter_map(|p| {
|
||||
let text = |key: &str| p.get(key).and_then(|v| v.as_str()).map(str::to_string);
|
||||
let reference = |kind: &str| {
|
||||
p.get("externalRefs")
|
||||
.and_then(|v| v.as_array())
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.find(|r| r.get("referenceType").and_then(|v| v.as_str()) == Some(kind))
|
||||
.and_then(|r| r.get("referenceLocator").and_then(|v| v.as_str()))
|
||||
.map(str::to_string)
|
||||
};
|
||||
let name = text("name").filter(|n| !n.trim().is_empty())?;
|
||||
Some(Component {
|
||||
group: None,
|
||||
name,
|
||||
version: text("versionInfo"),
|
||||
purl: reference("purl"),
|
||||
cpe: reference("cpe23Type").or_else(|| reference("cpe22Type")),
|
||||
license: spdx_license(text("licenseConcluded"))
|
||||
.or_else(|| spdx_license(text("licenseDeclared"))),
|
||||
})
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
|
||||
/// An SPDX licence field, `None` for `NOASSERTION` and `NONE`.
|
||||
fn spdx_license(value: Option<String>) -> Option<String> {
|
||||
value.filter(|v| !matches!(v.trim(), "" | "NOASSERTION" | "NONE"))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
const CDX_JSON: &str = r#"{
|
||||
"bomFormat": "CycloneDX",
|
||||
"specVersion": "1.5",
|
||||
"metadata": { "component": { "type": "device", "name": "Pump controller", "version": "4.2" } },
|
||||
"components": [
|
||||
{
|
||||
"type": "library", "group": "org.apache.logging.log4j", "name": "log4j-core",
|
||||
"version": "2.14.1",
|
||||
"purl": "pkg:maven/org.apache.logging.log4j/log4j-core@2.14.1",
|
||||
"licenses": [ { "license": { "id": "Apache-2.0" } } ],
|
||||
"components": [
|
||||
{ "type": "library", "name": "zlib", "version": "1.2.11",
|
||||
"cpe": "cpe:2.3:a:zlib:zlib:1.2.11:*:*:*:*:*:*:*" }
|
||||
]
|
||||
},
|
||||
{ "type": "file", "name": "README.md" }
|
||||
]
|
||||
}"#;
|
||||
|
||||
#[test]
|
||||
fn a_cyclonedx_json_sbom_lists_its_parts_but_not_the_product() {
|
||||
let entries = parse(CDX_JSON.as_bytes(), "t1", "pump.cdx.json").unwrap();
|
||||
let names: Vec<&str> = entries.iter().map(|e| e.name.as_str()).collect();
|
||||
assert_eq!(names, ["org.apache.logging.log4j/log4j-core", "zlib"]);
|
||||
let log4j = &entries[0];
|
||||
assert_eq!(log4j.version, "2.14.1");
|
||||
assert_eq!(log4j.package_manager, "maven");
|
||||
assert_eq!(
|
||||
log4j.purl.as_deref(),
|
||||
Some("pkg:maven/org.apache.logging.log4j/log4j-core@2.14.1")
|
||||
);
|
||||
assert_eq!(log4j.license.as_deref(), Some("Apache-2.0"));
|
||||
assert_eq!(log4j.evidence, ["pump.cdx.json (supplier SBOM)"]);
|
||||
let zlib = &entries[1];
|
||||
assert_eq!(zlib.package_manager, SUPPLIER_MANAGER);
|
||||
assert!(zlib
|
||||
.cpe
|
||||
.as_deref()
|
||||
.is_some_and(|c| c.starts_with("cpe:2.3:a:zlib")));
|
||||
assert_eq!(zlib.repo_id, "t1");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_cyclonedx_xml_sbom_reads_as_its_json() {
|
||||
let xml = r#"<?xml version="1.0" encoding="UTF-8"?>
|
||||
<bom xmlns="http://cyclonedx.org/schema/bom/1.4" version="1">
|
||||
<metadata><component type="device"><name>Pump controller</name></component></metadata>
|
||||
<components>
|
||||
<component type="library">
|
||||
<group>org.apache.logging.log4j</group><name>log4j-core</name><version>2.14.1</version>
|
||||
<licenses><license><id>Apache-2.0</id></license></licenses>
|
||||
<purl>pkg:maven/org.apache.logging.log4j/log4j-core@2.14.1</purl>
|
||||
<components>
|
||||
<component type="library"><name>zlib</name><version>1.2.11</version>
|
||||
<cpe>cpe:2.3:a:zlib:zlib:1.2.11:*:*:*:*:*:*:*</cpe></component>
|
||||
</components>
|
||||
</component>
|
||||
<component type="file"><name>README.md</name></component>
|
||||
</components>
|
||||
</bom>"#;
|
||||
let from_xml = parse(xml.as_bytes(), "t1", "pump.cdx.json").unwrap();
|
||||
let from_json = parse(CDX_JSON.as_bytes(), "t1", "pump.cdx.json").unwrap();
|
||||
let key = |e: &SbomEntry| {
|
||||
(
|
||||
e.name.clone(),
|
||||
e.version.clone(),
|
||||
e.purl.clone(),
|
||||
e.cpe.clone(),
|
||||
e.license.clone(),
|
||||
)
|
||||
};
|
||||
assert_eq!(
|
||||
from_xml.iter().map(key).collect::<Vec<_>>(),
|
||||
from_json.iter().map(key).collect::<Vec<_>>()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_xml_sbom_with_a_dtd_is_refused() {
|
||||
let xml = r#"<?xml version="1.0"?>
|
||||
<!DOCTYPE bom [ <!ENTITY x SYSTEM "file:///etc/passwd"> ]>
|
||||
<bom xmlns="http://cyclonedx.org/schema/bom/1.4"><components>
|
||||
<component type="library"><name>&x;</name></component></components></bom>"#;
|
||||
assert!(matches!(
|
||||
parse(xml.as_bytes(), "t1", "x.xml"),
|
||||
Err(SuppliedSbomError::Malformed { format: "XML", .. })
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_spdx2_sbom_lists_its_packages_but_the_described_one() {
|
||||
let spdx = r#"{
|
||||
"spdxVersion": "SPDX-2.3",
|
||||
"SPDXID": "SPDXRef-DOCUMENT",
|
||||
"documentDescribes": ["SPDXRef-product"],
|
||||
"packages": [
|
||||
{ "SPDXID": "SPDXRef-product", "name": "Pump controller", "versionInfo": "4.2" },
|
||||
{
|
||||
"SPDXID": "SPDXRef-lodash", "name": "lodash", "versionInfo": "4.17.20",
|
||||
"licenseConcluded": "NOASSERTION", "licenseDeclared": "MIT",
|
||||
"externalRefs": [
|
||||
{ "referenceCategory": "PACKAGE-MANAGER", "referenceType": "purl",
|
||||
"referenceLocator": "pkg:npm/lodash@4.17.20" }
|
||||
]
|
||||
},
|
||||
{
|
||||
"SPDXID": "SPDXRef-openssl", "name": "openssl", "versionInfo": "1.1.1k",
|
||||
"externalRefs": [
|
||||
{ "referenceCategory": "SECURITY", "referenceType": "cpe23Type",
|
||||
"referenceLocator": "cpe:2.3:a:openssl:openssl:1.1.1k:*:*:*:*:*:*:*" }
|
||||
]
|
||||
}
|
||||
]
|
||||
}"#;
|
||||
let entries = parse(spdx.as_bytes(), "t1", "pump.spdx.json").unwrap();
|
||||
let names: Vec<&str> = entries.iter().map(|e| e.name.as_str()).collect();
|
||||
assert_eq!(names, ["lodash", "openssl"]);
|
||||
assert_eq!(entries[0].package_manager, "npm");
|
||||
assert_eq!(entries[0].license.as_deref(), Some("MIT"));
|
||||
assert!(entries[1].purl.is_none());
|
||||
assert!(entries[1].cpe.is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn what_is_not_a_supplier_sbom_is_refused_with_the_reason() {
|
||||
let refused = |text: &str| parse(text.as_bytes(), "t1", "x").unwrap_err();
|
||||
assert!(matches!(
|
||||
refused("name,version\nzlib,1.2"),
|
||||
SuppliedSbomError::UnknownFormat(_)
|
||||
));
|
||||
assert!(matches!(
|
||||
refused(r#"{"a": 1}"#),
|
||||
SuppliedSbomError::UnknownFormat(_)
|
||||
));
|
||||
assert!(matches!(
|
||||
refused(r#"{"@context": "https://spdx.org/rdf/3.0.1/spdx-context.jsonld"}"#),
|
||||
SuppliedSbomError::UnknownFormat(reason) if reason.contains("SPDX 3.0")
|
||||
));
|
||||
assert!(matches!(
|
||||
refused(r#"{"bomFormat": "CycloneDX", "components": ["#),
|
||||
SuppliedSbomError::Malformed { format: "JSON", .. }
|
||||
));
|
||||
assert!(matches!(
|
||||
refused(r#"<project xmlns="http://maven.apache.org/POM/4.0.0"/>"#),
|
||||
SuppliedSbomError::UnknownFormat(_)
|
||||
));
|
||||
let huge = vec![b' '; MAX_BYTES as usize + 1];
|
||||
assert!(matches!(
|
||||
parse(&huge, "t1", "x"),
|
||||
Err(SuppliedSbomError::TooLarge)
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_sbom_without_components_is_refused_not_read_as_empty() {
|
||||
let empty = r#"{"bomFormat": "CycloneDX", "specVersion": "1.5"}"#;
|
||||
assert!(matches!(
|
||||
parse(empty.as_bytes(), "t1", "x"),
|
||||
Err(SuppliedSbomError::Empty)
|
||||
));
|
||||
}
|
||||
}
|
||||
@@ -263,7 +263,7 @@ pub(super) fn canonical_purl(purl: String) -> String {
|
||||
|
||||
/// Extract the ecosystem/package-manager from a PURL string.
|
||||
/// e.g. "pkg:npm/lodash@4.17.21" -> "npm", "pkg:cargo/serde@1.0" -> "cargo"
|
||||
fn extract_ecosystem_from_purl(purl: &str) -> Option<String> {
|
||||
pub(super) fn extract_ecosystem_from_purl(purl: &str) -> Option<String> {
|
||||
let rest = purl.strip_prefix("pkg:")?;
|
||||
let ecosystem = rest.split('/').next()?;
|
||||
if ecosystem.is_empty() {
|
||||
|
||||
@@ -111,6 +111,7 @@ pub fn uploaded_artifact(
|
||||
ArtifactKind::SourceArchive => Artifact::source_archive(filename),
|
||||
ArtifactKind::MobilePackage => Artifact::mobile_package(filename),
|
||||
ArtifactKind::BuildOutput => Artifact::build_output(filename),
|
||||
ArtifactKind::SupplierSbom => Artifact::supplier_sbom(filename),
|
||||
_ => return None,
|
||||
};
|
||||
artifact.stored_path = Some(stored_path.to_string_lossy().to_string());
|
||||
@@ -142,6 +143,7 @@ pub fn reference_artifact(
|
||||
}
|
||||
ArtifactKind::PlaintextDescription => Artifact::plaintext(source_ref),
|
||||
ArtifactKind::BuildOutput => Artifact::build_output(source_ref),
|
||||
ArtifactKind::SupplierSbom => Artifact::supplier_sbom(source_ref),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -287,3 +287,129 @@ async fn the_list_pages_with_a_total_after_the_project_filter() {
|
||||
|
||||
server.cleanup().await;
|
||||
}
|
||||
|
||||
/// Upload `bytes` as a supplier SBOM (#1025) named `name` to target `id`.
|
||||
async fn upload_supplier_sbom(
|
||||
server: &TestServer,
|
||||
id: &str,
|
||||
name: &str,
|
||||
bytes: &[u8],
|
||||
) -> reqwest::Response {
|
||||
let form = reqwest::multipart::Form::new()
|
||||
.text("kind", "supplier_sbom")
|
||||
.part(
|
||||
"file",
|
||||
reqwest::multipart::Part::bytes(bytes.to_vec()).file_name(name.to_string()),
|
||||
);
|
||||
server
|
||||
.client
|
||||
.post(format!(
|
||||
"{}/api/v1/targets/{id}/artifacts/upload",
|
||||
server.base_url
|
||||
))
|
||||
.multipart(form)
|
||||
.send()
|
||||
.await
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_supplier_sbom_is_kept_and_brings_its_scans() {
|
||||
let server = TestServer::start().await;
|
||||
let id = firmware_target(&server, "bought-in-pump").await;
|
||||
let sbom = br#"{"bomFormat": "CycloneDX", "specVersion": "1.5", "components": [
|
||||
{"type": "library", "name": "lodash", "version": "4.17.20", "purl": "pkg:npm/lodash@4.17.20"}
|
||||
]}"#;
|
||||
|
||||
let resp = upload_supplier_sbom(&server, &id, "pump.cdx.json", sbom).await;
|
||||
|
||||
assert_eq!(resp.status(), 200);
|
||||
let body: serde_json::Value = resp.json().await.unwrap();
|
||||
let artifacts = body["data"]["artifacts"].as_array().unwrap();
|
||||
assert_eq!(artifacts.len(), 1);
|
||||
assert_eq!(artifacts[0]["kind"], "supplier_sbom");
|
||||
assert_eq!(stored_uploads(&id).len(), 1);
|
||||
// Its SBOM and CVE scans run, though the target has no code.
|
||||
let resp = server
|
||||
.get(&format!("/api/v1/targets/{id}/applicable-scans"))
|
||||
.await;
|
||||
let body: serde_json::Value = resp.json().await.unwrap();
|
||||
let runs =
|
||||
|scan: &str| {
|
||||
body["data"]["scans"].as_array().unwrap().iter().any(|s| {
|
||||
s["scan"] == scan && s["default_on"] == true && s["blocked_reason"].is_null()
|
||||
})
|
||||
};
|
||||
assert!(runs("sbom") && runs("cve"), "{body}");
|
||||
|
||||
server.cleanup().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_supplier_sbom_that_cannot_be_read_is_refused_with_the_reason() {
|
||||
let server = TestServer::start().await;
|
||||
let id = firmware_target(&server, "bought-in-valve").await;
|
||||
|
||||
for (name, bytes, reason) in [
|
||||
(
|
||||
"valve.csv",
|
||||
&b"name,version\nzlib,1.2.11"[..],
|
||||
"not a CycloneDX",
|
||||
),
|
||||
(
|
||||
"valve.cdx.json",
|
||||
&br#"{"bomFormat": "CycloneDX", "specVersion": "1.5"}"#[..],
|
||||
"lists no components",
|
||||
),
|
||||
] {
|
||||
let resp = upload_supplier_sbom(&server, &id, name, bytes).await;
|
||||
assert_eq!(resp.status(), 422, "{name}");
|
||||
let body: serde_json::Value = resp.json().await.unwrap();
|
||||
assert!(
|
||||
body["error"].as_str().is_some_and(|e| e.contains(reason)),
|
||||
"{name}: {body}"
|
||||
);
|
||||
}
|
||||
assert!(
|
||||
stored_uploads(&id).is_empty(),
|
||||
"a refused SBOM must be deleted"
|
||||
);
|
||||
let resp = server.get(&format!("/api/v1/targets/{id}")).await;
|
||||
let body: serde_json::Value = resp.json().await.unwrap();
|
||||
assert!(body["data"]["artifacts"].as_array().unwrap().is_empty());
|
||||
|
||||
server.cleanup().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_new_supplier_sbom_replaces_the_one_before_it() {
|
||||
let server = TestServer::start().await;
|
||||
let id = firmware_target(&server, "bought-in-drive").await;
|
||||
let version = |v: &str| {
|
||||
format!(
|
||||
r#"{{"bomFormat": "CycloneDX", "specVersion": "1.5", "components": [
|
||||
{{"type": "library", "name": "zlib", "version": "{v}", "purl": "pkg:generic/zlib@{v}"}}
|
||||
]}}"#
|
||||
)
|
||||
};
|
||||
for (name, v) in [
|
||||
("drive-1.cdx.json", "1.2.11"),
|
||||
("drive-2.cdx.json", "1.3.1"),
|
||||
] {
|
||||
let resp = upload_supplier_sbom(&server, &id, name, version(v).as_bytes()).await;
|
||||
assert_eq!(resp.status(), 200, "{name}");
|
||||
}
|
||||
|
||||
let resp = server.get(&format!("/api/v1/targets/{id}")).await;
|
||||
let body: serde_json::Value = resp.json().await.unwrap();
|
||||
let artifacts = body["data"]["artifacts"].as_array().unwrap();
|
||||
assert_eq!(artifacts.len(), 1, "{body}");
|
||||
assert_eq!(artifacts[0]["source_ref"], "drive-2.cdx.json");
|
||||
let files = stored_uploads(&id);
|
||||
assert_eq!(files.len(), 1, "the replaced file must be gone: {files:?}");
|
||||
assert!(std::fs::read_to_string(&files[0])
|
||||
.unwrap()
|
||||
.contains("1.3.1"));
|
||||
|
||||
server.cleanup().await;
|
||||
}
|
||||
@@ -87,6 +87,9 @@ pub enum ArtifactKind {
|
||||
/// What a build wrote about its image: a Yocto image's SPDX archive
|
||||
/// (`<image>.spdx.tar.zst`).
|
||||
BuildOutput,
|
||||
/// A component's SBOM as its supplier delivered it (CycloneDX or SPDX),
|
||||
/// for a component bought in without its source code (#1025).
|
||||
SupplierSbom,
|
||||
}
|
||||
|
||||
impl std::fmt::Display for ArtifactKind {
|
||||
@@ -101,6 +104,7 @@ impl std::fmt::Display for ArtifactKind {
|
||||
Self::PlcProject => write!(f, "plc_project"),
|
||||
Self::PlaintextDescription => write!(f, "plaintext_description"),
|
||||
Self::BuildOutput => write!(f, "build_output"),
|
||||
Self::SupplierSbom => write!(f, "supplier_sbom"),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -337,6 +341,11 @@ impl Artifact {
|
||||
Self::bare(ArtifactKind::BuildOutput, source_ref)
|
||||
}
|
||||
|
||||
/// A supplier's SBOM of a component, uploaded as delivered (#1025).
|
||||
pub fn supplier_sbom(source_ref: impl Into<String>) -> Self {
|
||||
Self::bare(ArtifactKind::SupplierSbom, source_ref)
|
||||
}
|
||||
|
||||
/// A container-image artifact referenced by OCI ref.
|
||||
pub fn container_image(source_ref: impl Into<String>) -> Self {
|
||||
Self::bare(ArtifactKind::ContainerImage, source_ref)
|
||||
|
||||
@@ -62,6 +62,8 @@ pub enum ArtifactRequirement {
|
||||
/// What a build wrote about its image: a Yocto image SPDX archive or its
|
||||
/// cve-check report.
|
||||
BuildOutput,
|
||||
/// A supplier's SBOM of a bought-in component (#1025).
|
||||
SupplierSbom,
|
||||
/// No specific artifact required.
|
||||
Any,
|
||||
}
|
||||
@@ -217,6 +219,20 @@ fn sast_umbrella() -> Vec<ScanRule> {
|
||||
/// simply absent (e.g. DAST is not listed for a PLC target).
|
||||
pub fn rules_for(target_type: TargetType) -> Vec<ScanRule> {
|
||||
let mut rules = target_rules(target_type);
|
||||
// Any target may carry a supplier's SBOM of a component bought in
|
||||
// without its source (#1025): its components and their known CVEs.
|
||||
rules.push(ScanRule::new(
|
||||
ScanType::Sbom,
|
||||
true,
|
||||
"SBOM of the component as its supplier delivered it",
|
||||
ArtifactRequirement::SupplierSbom,
|
||||
));
|
||||
rules.push(ScanRule::new(
|
||||
ScanType::Cve,
|
||||
true,
|
||||
"The supplier SBOM's components against known CVEs and vendor advisories",
|
||||
ArtifactRequirement::SupplierSbom,
|
||||
));
|
||||
// Any target may carry a container image, and nothing scans one; say so
|
||||
// rather than accepting the artifact in silence.
|
||||
rules.push(ScanRule::unavailable(
|
||||
@@ -411,6 +427,7 @@ fn representative_kind(req: ArtifactRequirement) -> Option<ArtifactKind> {
|
||||
ArtifactRequirement::Mobile => Some(ArtifactKind::MobilePackage),
|
||||
ArtifactRequirement::Container => Some(ArtifactKind::ContainerImage),
|
||||
ArtifactRequirement::BuildOutput => Some(ArtifactKind::BuildOutput),
|
||||
ArtifactRequirement::SupplierSbom => Some(ArtifactKind::SupplierSbom),
|
||||
ArtifactRequirement::Any => None,
|
||||
}
|
||||
}
|
||||
@@ -441,6 +458,7 @@ fn requirement_satisfied(req: ArtifactRequirement, target: &OnboardedTarget) ->
|
||||
ArtifactRequirement::Mobile => target.has(ArtifactKind::MobilePackage),
|
||||
ArtifactRequirement::Container => target.has(ArtifactKind::ContainerImage),
|
||||
ArtifactRequirement::BuildOutput => target.has(ArtifactKind::BuildOutput),
|
||||
ArtifactRequirement::SupplierSbom => target.has(ArtifactKind::SupplierSbom),
|
||||
ArtifactRequirement::Any => true,
|
||||
}
|
||||
}
|
||||
@@ -480,6 +498,43 @@ pub fn applicable_scans(target: &OnboardedTarget) -> Vec<ScanOption> {
|
||||
#[cfg(test)]
|
||||
#[allow(clippy::expect_used, clippy::unwrap_used)]
|
||||
mod tests {
|
||||
|
||||
#[test]
|
||||
fn a_supplier_sbom_brings_its_sbom_and_cve_scans_to_every_target_type() {
|
||||
use crate::models::Artifact;
|
||||
for target_type in [
|
||||
TargetType::WebApp,
|
||||
TargetType::BackendService,
|
||||
TargetType::DesktopApp,
|
||||
TargetType::AndroidApp,
|
||||
TargetType::IosApp,
|
||||
TargetType::FirmwareBareMetal,
|
||||
TargetType::FirmwareRtos,
|
||||
TargetType::EmbeddedLinuxYocto,
|
||||
TargetType::PlcSps,
|
||||
] {
|
||||
let mut target = OnboardedTarget::new("component".into(), target_type);
|
||||
target
|
||||
.artifacts
|
||||
.push(Artifact::supplier_sbom("pump.cdx.json"));
|
||||
let runs = |scan: ScanType| {
|
||||
applicable_scans(&target).iter().any(|o| {
|
||||
o.scan == scan
|
||||
&& o.default_on
|
||||
&& o.required_artifact == Some(ArtifactKind::SupplierSbom)
|
||||
})
|
||||
};
|
||||
assert!(
|
||||
runs(ScanType::Sbom),
|
||||
"{target_type:?}: no SBOM from the supplier SBOM"
|
||||
);
|
||||
assert!(
|
||||
runs(ScanType::Cve),
|
||||
"{target_type:?}: no CVE check of the supplier SBOM"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
use super::*;
|
||||
use crate::models::{Artifact, PlcFormat};
|
||||
|
||||
|
||||
@@ -86,6 +86,34 @@ and is not judged.
|
||||
Firmware images, container images and app packages are not unpacked yet; their
|
||||
components come from the source code.
|
||||
|
||||
### A supplier's SBOM
|
||||
|
||||
A component you buy in often comes without its source code, only with its
|
||||
supplier's SBOM. Upload that SBOM to the component's target as a **supplier
|
||||
SBOM** (`supplier_sbom`). A target needs no code for this. Its components are
|
||||
then checked for known vulnerabilities like those read from code: OSV, NVD, the
|
||||
CISA KEV list and EPSS, and the vendor advisories (CSAF) by purl. The results
|
||||
go through the same CVE groups, VEX statements and ENISA drafts.
|
||||
|
||||
- **Formats:** CycloneDX 1.4 to 1.6 (JSON or XML) and SPDX 2.3 JSON. SPDX 3.0
|
||||
is not read yet.
|
||||
- **What is read of each component:** name (with its group), version, purl,
|
||||
CPE and licence. Nested components are read too. The product the document
|
||||
describes (CycloneDX `metadata.component`, SPDX `documentDescribes`) is the
|
||||
component itself and is not listed as one of its parts.
|
||||
- **Components without a purl:** no advisory database can be asked about them.
|
||||
The scan lists them under **Nicht ausgeführt** rather than as free of CVEs.
|
||||
- **Refused at upload, with the reason:**
|
||||
- a file that is no such SBOM
|
||||
- an SBOM that lists no components
|
||||
- one larger than 20 MiB
|
||||
- XML with a DTD, since entities are never resolved
|
||||
|
||||
An SBOM that lists nothing is refused rather than read as empty: read as
|
||||
empty, it would make every known CVE of the component look fixed.
|
||||
- **A new version from the supplier:** upload it to the same target. Each scan
|
||||
reads the target's supplier SBOMs.
|
||||
|
||||
### When the SBOM is empty or incomplete
|
||||
|
||||
An SBOM without components does not mean the software uses no libraries:
|
||||
|
||||
Reference in new issue
Block a user