diff --git a/compliance-agent/src/api/handlers/onboarding.rs b/compliance-agent/src/api/handlers/onboarding.rs index ec3bbe3..2f3861c 100644 --- a/compliance-agent/src/api/handlers/onboarding.rs +++ b/compliance-agent/src/api/handlers/onboarding.rs @@ -930,8 +930,17 @@ pub async fn upload_artifact( .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)? .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; artifact.content_hash = Some(sha); + artifact.ingested_at = Some(chrono::Utc::now()); if kind == ArtifactKind::SupplierSbom { - check_supplier_sbom(&upload, &filename).await?; + let path = upload.path.clone(); + let read = tokio::task::spawn_blocking(move || { + crate::pipeline::sbom::supplied::read_with_statements(&path, "", "") + }) + .await + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; + artifact + .detected + .extend(SupplierSbomSummary::of(read)?.facts()); } 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. @@ -997,11 +1006,11 @@ async fn replace_supplier_sboms( } /// Why an upload is refused: its status and, for a supplier SBOM that cannot -/// be read, why (as `{"error": …}`, for the dashboard to show). +/// be read, why (as `{"error": …, "code": …}`, for the dashboard to show). #[derive(Debug)] pub struct UploadRefusal { status: StatusCode, - reason: Option, + reason: Option<(String, &'static str)>, } impl From for UploadRefusal { @@ -1016,36 +1025,137 @@ impl From for UploadRefusal { 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() - } + Some((error, code)) => ( + self.status, + Json(serde_json::json!({ "error": error, "code": code })), + ) + .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 keys an upload keeps a supplier SBOM's [`SupplierSbomSummary`] +/// under, for the target editor to show. +pub const SBOM_FORMAT_FACT: &str = "sbom_format"; +/// See [`SBOM_FORMAT_FACT`]. +pub const SBOM_COMPONENTS_FACT: &str = "sbom_components"; +/// See [`SBOM_FORMAT_FACT`]. +pub const SBOM_STATEMENTS_FACT: &str = "sbom_statements"; + +/// What a readable supplier SBOM holds (#1025): what the wizard shows when the +/// file is added, and what its upload keeps with the artifact. +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub struct SupplierSbomSummary { + /// The format and its version, such as `CycloneDX 1.5` or `SPDX 2.3`. + pub format: String, + /// The components it lists, nested ones included. + pub components: usize, + /// What the supplier states about its components' vulnerabilities + /// (CycloneDX VEX), one per vulnerability and component. + pub statements: usize, +} + +impl SupplierSbomSummary { + /// The summary of a supplier SBOM as read, or why it is refused: the same + /// verdict for the check and for the upload. + /// + /// # Errors + /// + /// 413 past [`crate::pipeline::sbom::supplied::MAX_BYTES`], 500 when the + /// file cannot be read, 422 with the reason and its code for one that + /// cannot be read as an SBOM. + fn of( + read: Result< + crate::pipeline::sbom::supplied::SuppliedSbom, + crate::pipeline::sbom::supplied::SuppliedSbomError, + >, + ) -> Result { + use crate::pipeline::sbom::supplied::SuppliedSbomError; + match read { + Ok(sbom) => Ok(Self { + format: sbom.format, + components: sbom.entries.len(), + statements: sbom.statements.len(), + }), + Err(SuppliedSbomError::Io(_)) => Err(StatusCode::INTERNAL_SERVER_ERROR.into()), + Err(e) => Err(UploadRefusal { + status: if e == SuppliedSbomError::TooLarge { + StatusCode::PAYLOAD_TOO_LARGE + } else { + StatusCode::UNPROCESSABLE_ENTITY + }, + reason: Some((e.to_string(), e.code())), + }), + } } + + /// The summary as the artifact's facts. + fn facts(&self) -> [DetectedFact; 3] { + [ + DetectedFact::new(SBOM_FORMAT_FACT, self.format.as_str(), "upload"), + DetectedFact::new(SBOM_COMPONENTS_FACT, self.components.to_string(), "upload"), + DetectedFact::new(SBOM_STATEMENTS_FACT, self.statements.to_string(), "upload"), + ] + } +} + +/// The multipart form of a supplier SBOM check. +// Only the API description reads it, as for [`UploadArtifactForm`]. +#[derive(utoipa::ToSchema)] +#[allow(dead_code)] +pub struct CheckSupplierSbomForm { + /// The SBOM file, exactly one. + #[schema(value_type = String, format = Binary)] + file: Vec, +} + +/// Check a supplier SBOM before any target holds it. +/// +/// Reads the file as an upload of kind `supplier_sbom` would, and says what +/// it holds (`data`: `format`, `components`, `statements`) or why it is +/// refused, so the onboarding wizard can refuse a file +/// when it is added, before the target exists (#1025). Nothing is stored. +/// +/// A refusal is `{"error": …, "code": …}`, the code one of `too_large`, +/// `too_many_components`, `empty`, `unknown_format` or `malformed`. +#[utoipa::path( + post, + path = "/api/v1/supplier-sboms/check", + tag = "Targets", + request_body(content = CheckSupplierSbomForm, content_type = "multipart/form-data"), + responses( + (status = 200, description = "What the SBOM holds"), + (status = 400, description = "No file, or more than one"), + (status = 413, description = "The file is over 20 MiB"), + (status = 422, description = "Not a supplier SBOM that can be read; `error` and `code` say why"), + (status = 401, description = "No valid bearer token"), + ) +)] +#[tracing::instrument(skip_all)] +pub async fn check_supplier_sbom( + mut multipart: Multipart, +) -> Result>, UploadRefusal> { + let mut bytes = None; + while let Some(field) = multipart.next_field().await.map_err(|e| e.status())? { + if field.name() == Some("file") { + if bytes.is_some() { + return Err(StatusCode::BAD_REQUEST.into()); + } + bytes = Some(field.bytes().await.map_err(|e| e.status())?); + } + } + let bytes = bytes.ok_or(StatusCode::BAD_REQUEST)?; + let read = tokio::task::spawn_blocking(move || { + crate::pipeline::sbom::supplied::parse_with_statements(&bytes, "", "") + }) + .await + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; + Ok(Json(ApiResponse { + data: SupplierSbomSummary::of(read)?, + total: None, + page: None, + })) } /// The fact an upload records on a password-protected archive. diff --git a/compliance-agent/src/api/routes.rs b/compliance-agent/src/api/routes.rs index 92199b9..fdb99a7 100644 --- a/compliance-agent/src/api/routes.rs +++ b/compliance-agent/src/api/routes.rs @@ -80,6 +80,13 @@ fn described_routes() -> OpenApiRouter { crate::targets::MAX_UPLOAD_BYTES as usize + MULTIPART_OVERHEAD, )), ) + // A supplier SBOM is checked when the wizard adds it, before any + // target holds it: up to its own size limit, never kept. + .routes( + routes!(handlers::onboarding::check_supplier_sbom).layer(DefaultBodyLimit::max( + crate::pipeline::sbom::supplied::MAX_BYTES as usize + MULTIPART_OVERHEAD, + )), + ) .routes(routes!(handlers::onboarding::set_archive_password)) .routes(routes!(handlers::onboarding::applicable_scans_for_target)) .routes(routes!(handlers::onboarding::detect_target)) diff --git a/compliance-agent/src/pipeline/cve.rs b/compliance-agent/src/pipeline/cve.rs index 0297bae..572ce18 100644 --- a/compliance-agent/src/pipeline/cve.rs +++ b/compliance-agent/src/pipeline/cve.rs @@ -705,8 +705,13 @@ mod tests { "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 mut entries = crate::pipeline::sbom::supplied::parse_with_statements( + sbom.as_bytes(), + "t", + "pump.cdx.json", + ) + .unwrap() + .entries; let lookup = scanner.scan_dependencies("t", &mut entries).await.unwrap(); diff --git a/compliance-agent/src/pipeline/sbom/supplied.rs b/compliance-agent/src/pipeline/sbom/supplied.rs index b90b857..4deb972 100644 --- a/compliance-agent/src/pipeline/sbom/supplied.rs +++ b/compliance-agent/src/pipeline/sbom/supplied.rs @@ -86,46 +86,29 @@ pub enum SuppliedSbomError { 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, SuppliedSbomError> { - let size = std::fs::metadata(path) - .map_err(|e| SuppliedSbomError::Io(e.to_string()))? - .len(); - if size > MAX_BYTES { - return Err(SuppliedSbomError::TooLarge); +impl SuppliedSbomError { + /// A stable name of the refusal, for a client to word it in its own + /// language: `too_large`, `too_many_components`, `empty`, + /// `unknown_format`, `malformed` or `io`. + pub fn code(&self) -> &'static str { + match self { + Self::TooLarge => "too_large", + Self::TooManyComponents => "too_many_components", + Self::Empty => "empty", + Self::UnknownFormat(_) => "unknown_format", + Self::Malformed { .. } => "malformed", + Self::Io(_) => "io", + } } - 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, SuppliedSbomError> { - parse_with_statements(bytes, repo_id, label).map(|sbom| sbom.entries) -} - -/// A supplier SBOM as read: its components, and what the supplier states -/// about their vulnerabilities (CycloneDX VEX; #1025). +/// A supplier SBOM as read: its format, its components, and what the +/// supplier states about their vulnerabilities (CycloneDX VEX; #1025). #[derive(Debug)] pub struct SuppliedSbom { + /// The format and its version as the document declares it, such as + /// `CycloneDX 1.5` or `SPDX 2.3`; just the format without a version. + pub format: String, /// The components, as SBOM entries. pub entries: Vec, /// The supplier's statements, one per vulnerability and component. @@ -147,7 +130,14 @@ pub struct SuppliedStatement { pub vex: SupplierVex, } -/// [`read`] with the supplier's statements. +/// Read the supplier SBOM at `path` as 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 /// @@ -167,7 +157,7 @@ pub fn read_with_statements( parse_with_statements(&bytes, repo_id, label) } -/// [`parse`] with the supplier's statements. +/// [`read_with_statements`] for a document already in memory. /// /// # Errors /// @@ -232,6 +222,7 @@ pub fn parse_with_statements( }) .collect(); Ok(SuppliedSbom { + format: doc.format, entries, statements, }) @@ -264,6 +255,8 @@ pub fn attach(statements: &[SuppliedStatement], alerts: &mut [CveAlert]) { /// What a document gives: its components and the supplier's raw statements. #[derive(Debug, Default)] struct Doc { + /// See [`SuppliedSbom::format`]. + format: String, components: Vec, statements: Vec, } @@ -327,6 +320,14 @@ fn is_part(kind: Option<&str>) -> bool { !matches!(kind, Some("file" | "data")) } +/// `format` with its `version`, when the document gives a sensible one. +fn versioned(format: &str, version: Option<&str>) -> String { + match version.map(str::trim) { + Some(v) if !v.is_empty() && v.len() <= 16 => format!("{format} {v}"), + _ => format.to_string(), + } +} + /// A JSON document: CycloneDX or SPDX 2, told apart by their markers. fn json(text: &str) -> Result { let doc: serde_json::Value = @@ -338,12 +339,14 @@ fn json(text: &str) -> Result { let mut components = Vec::new(); cyclonedx_json_components(doc.get("components"), &mut components)?; return Ok(Doc { + format: versioned("CycloneDX", doc.get("specVersion").and_then(|v| v.as_str())), components, statements: cyclonedx_json_statements(doc.get("vulnerabilities")), }); } match doc.get("spdxVersion").and_then(|v| v.as_str()) { Some(v) if v.starts_with("SPDX-2.") => spdx2(&doc).map(|components| Doc { + format: versioned("SPDX", v.strip_prefix("SPDX-")), components, statements: Vec::new(), }), @@ -452,21 +455,21 @@ fn cyclonedx_xml(text: &str) -> Result { 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 { + let version = (root.tag_name().name() == "bom") + .then(|| root.tag_name().namespace()) + .flatten() + .and_then(|ns| ns.strip_prefix("http://cyclonedx.org/schema/bom/")); + let Some(version) = version else { return Err(SuppliedSbomError::UnknownFormat( " (an XML document, but not a CycloneDX BOM)".to_string(), )); - } + }; let mut components = Vec::new(); if let Some(list) = child(root, "components") { cyclonedx_xml_components(list, &mut components)?; } Ok(Doc { + format: versioned("CycloneDX", Some(version)), components, statements: child(root, "vulnerabilities") .map(cyclonedx_xml_statements) @@ -638,6 +641,15 @@ fn spdx_license(value: Option) -> Option { mod tests { use super::*; + /// The entries of the document. + fn parse( + bytes: &[u8], + repo_id: &str, + label: &str, + ) -> Result, SuppliedSbomError> { + parse_with_statements(bytes, repo_id, label).map(|sbom| sbom.entries) + } + const CDX_JSON: &str = r#"{ "bomFormat": "CycloneDX", "specVersion": "1.5", @@ -698,6 +710,13 @@ mod tests { README.md "#; + let format = |text: &str| { + parse_with_statements(text.as_bytes(), "t1", "x") + .unwrap() + .format + }; + assert_eq!(format(xml), "CycloneDX 1.4"); + assert_eq!(format(CDX_JSON), "CycloneDX 1.5"); 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| { @@ -899,7 +918,9 @@ mod tests { } ] }"#; - let entries = parse(spdx.as_bytes(), "t1", "pump.spdx.json").unwrap(); + let sbom = parse_with_statements(spdx.as_bytes(), "t1", "pump.spdx.json").unwrap(); + assert_eq!(sbom.format, "SPDX 2.3"); + let entries = sbom.entries; 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"); @@ -941,9 +962,8 @@ mod tests { #[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) - )); + let refused = parse(empty.as_bytes(), "t1", "x").unwrap_err(); + assert_eq!(refused, SuppliedSbomError::Empty); + assert_eq!(refused.code(), "empty"); } } diff --git a/compliance-agent/tests/integration/api/onboarding.rs b/compliance-agent/tests/integration/api/onboarding.rs index 4a3a542..822b944 100644 --- a/compliance-agent/tests/integration/api/onboarding.rs +++ b/compliance-agent/tests/integration/api/onboarding.rs @@ -328,6 +328,19 @@ async fn a_supplier_sbom_is_kept_and_brings_its_scans() { let artifacts = body["data"]["artifacts"].as_array().unwrap(); assert_eq!(artifacts.len(), 1); assert_eq!(artifacts[0]["kind"], "supplier_sbom"); + assert!(!artifacts[0]["ingested_at"].is_null(), "{body}"); + // What the editor shows of it is kept with it. + let fact = |key: &str| { + artifacts[0]["detected"] + .as_array() + .unwrap() + .iter() + .find(|f| f["key"] == key) + .map(|f| f["value"].clone()) + }; + assert_eq!(fact("sbom_format"), Some(json!("CycloneDX 1.5"))); + assert_eq!(fact("sbom_components"), Some(json!("1"))); + assert_eq!(fact("sbom_statements"), Some(json!("0"))); assert_eq!(stored_uploads(&id).len(), 1); // Its SBOM and CVE scans run, though the target has no code. let resp = server @@ -345,23 +358,86 @@ async fn a_supplier_sbom_is_kept_and_brings_its_scans() { server.cleanup().await; } +/// Files that are no supplier SBOM a scan can read: (name, bytes, part of +/// the reason, its code). +fn unreadable_sboms() -> [(&'static str, &'static [u8], &'static str, &'static str); 2] { + [ + ( + "valve.csv", + b"name,version\nzlib,1.2.11", + "not a CycloneDX", + "unknown_format", + ), + ( + "valve.cdx.json", + br#"{"bomFormat": "CycloneDX", "specVersion": "1.5"}"#, + "lists no components", + "empty", + ), + ] +} + +/// Check `bytes` as a supplier SBOM, before any target holds it. +async fn check_supplier_sbom(server: &TestServer, bytes: &[u8]) -> reqwest::Response { + let form = reqwest::multipart::Form::new().part( + "file", + reqwest::multipart::Part::bytes(bytes.to_vec()).file_name("x.json"), + ); + server + .client + .post(format!("{}/api/v1/supplier-sboms/check", server.base_url)) + .multipart(form) + .send() + .await + .unwrap() +} + +#[tokio::test] +async fn a_supplier_sbom_is_checked_before_a_target_holds_it() { + let server = TestServer::start().await; + let sbom = br#"{"bomFormat": "CycloneDX", "specVersion": "1.6", + "components": [ + {"type": "library", "name": "lodash", "version": "4.17.20", "bom-ref": "l", + "purl": "pkg:npm/lodash@4.17.20"}, + {"type": "library", "name": "zlib", "version": "1.2.11"} + ], + "vulnerabilities": [{"id": "CVE-2021-23337", "affects": [{"ref": "l"}], + "analysis": {"state": "not_affected", "justification": "code_not_reachable"}}] + }"#; + + let resp = check_supplier_sbom(&server, sbom).await; + + assert_eq!(resp.status(), 200); + let body: serde_json::Value = resp.json().await.unwrap(); + assert_eq!( + body["data"], + json!({ "format": "CycloneDX 1.6", "components": 2, "statements": 1 }) + ); + for (name, bytes, _, code) in unreadable_sboms() { + let resp = check_supplier_sbom(&server, bytes).await; + assert_eq!(resp.status(), 422, "{name}"); + let body: serde_json::Value = resp.json().await.unwrap(); + assert_eq!(body["code"], code, "{name}"); + } + // Larger than the 2 MiB of a JSON route, within the SBOM's 20 MiB. + let padded = [ + &br#"{"bomFormat": "CycloneDX", "specVersion": "1.5", "x": ""#[..], + &vec![b'a'; 3 * 1024 * 1024], + br#"", "components": [{"type": "library", "name": "zlib", "version": "1.2.11"}]}"#, + ] + .concat(); + let resp = check_supplier_sbom(&server, &padded).await; + assert_eq!(resp.status(), 200); + + 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", - ), - ] { + for (name, bytes, reason, code) in unreadable_sboms() { 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(); @@ -369,6 +445,7 @@ async fn a_supplier_sbom_that_cannot_be_read_is_refused_with_the_reason() { body["error"].as_str().is_some_and(|e| e.contains(reason)), "{name}: {body}" ); + assert_eq!(body["code"], code, "{name}"); } assert!( stored_uploads(&id).is_empty(), diff --git a/docs/guide/sbom.md b/docs/guide/sbom.md index 6060a72..b2aff93 100644 --- a/docs/guide/sbom.md +++ b/docs/guide/sbom.md @@ -111,6 +111,13 @@ go through the same CVE groups, VEX statements and ENISA drafts. 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. + + The same check runs when the wizard adds the file, before the target + exists (`POST /api/v1/supplier-sboms/check`). It stores nothing and returns + the format, the number of components and the number of supplier + statements, or the refusal with a `code` (`unknown_format`, `malformed`, + `empty`, `too_many_components`, `too_large`). An upload keeps the same + three numbers with the artifact, for the target editor to show. - **A new version from the supplier:** upload it to the same target. It replaces the previous one. - **The supplier and its advisories:** a target can name its supplier: the