diff --git a/compliance-agent/src/api/handlers/evidence.rs b/compliance-agent/src/api/handlers/evidence.rs new file mode 100644 index 0000000..cefed39 --- /dev/null +++ b/compliance-agent/src/api/handlers/evidence.rs @@ -0,0 +1,114 @@ +//! `GET /api/v1/targets/{id}/evidence-pack`: the target's evidence as a ZIP +//! (see [`crate::evidence`]), for the dashboard's download and for +//! breakpilot's document service to pull. + +use axum::extract::{Extension, Path}; +use axum::http::{header, HeaderValue, StatusCode}; +use axum::response::IntoResponse; +use mongodb::bson::{doc, oid::ObjectId}; + +use compliance_core::tenant_ctx::TenantCtx; + +use super::dto::{collect_cursor_async, tenant_db, AgentExt}; +use super::sbom::MAX_EXPORT_COMPONENTS; +use crate::evidence::{build_pack, EvidenceInputs}; + +/// Most findings one pack is built from in memory. +const MAX_PACK_FINDINGS: u64 = 50_000; + +/// GET /api/v1/targets/{id}/evidence-pack — 404 for an unknown target, 413 +/// when it is too large to build in memory. +#[tracing::instrument(skip_all, fields(target_id = %id))] +pub async fn evidence_pack( + Extension(agent): AgentExt, + tenant: TenantCtx, + Path(id): Path, +) -> Result { + let oid = ObjectId::parse_str(&id).map_err(|_| StatusCode::BAD_REQUEST)?; + let db = tenant_db(&agent, &tenant).await?; + let target = db + .onboarded_targets() + .find_one(doc! { "_id": oid }) + .await + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)? + .ok_or(StatusCode::NOT_FOUND)?; + + let by_target = doc! { "repo_id": &id }; + let findings_count = db + .findings() + .count_documents(by_target.clone()) + .await + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; + let sbom_count = db + .sbom_entries() + .count_documents(by_target.clone()) + .await + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; + if findings_count > MAX_PACK_FINDINGS || sbom_count > MAX_EXPORT_COMPONENTS { + return Err(StatusCode::PAYLOAD_TOO_LARGE); + } + + let load_err = |e: mongodb::error::Error| { + tracing::warn!("evidence pack: {e}"); + StatusCode::INTERNAL_SERVER_ERROR + }; + let inputs = EvidenceInputs { + findings: collect_cursor_async( + db.findings() + .find(by_target.clone()) + .await + .map_err(load_err)?, + ) + .await, + sbom: collect_cursor_async( + db.sbom_entries() + .find(by_target.clone()) + .await + .map_err(load_err)?, + ) + .await, + cves: collect_cursor_async( + db.cve_alerts() + .find(by_target.clone()) + .await + .map_err(load_err)?, + ) + .await, + last_run: db + .scan_runs() + .find_one(by_target) + .sort(doc! { "started_at": -1 }) + .await + .map_err(load_err)?, + target, + }; + + let now = chrono::Utc::now(); + let (zip, _files) = tokio::task::spawn_blocking(move || build_pack(&inputs, now)) + .await + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)? + .map_err(|e| { + tracing::warn!("evidence pack: {e}"); + StatusCode::INTERNAL_SERVER_ERROR + })?; + + agent.emit_usage( + &tenant.0.tenant_id, + "evidence_pack.generated", + format!("evidence:{}:{id}:{}", tenant.0.tenant_id, now.timestamp()), + serde_json::json!({ "target_id": id }), + ); + let filename = format!("pruefwerk-evidence-{id}-{}.zip", now.format("%Y%m%d")); + let disposition = HeaderValue::from_str(&format!("attachment; filename=\"{filename}\"")) + .unwrap_or_else(|_| HeaderValue::from_static("attachment")); + Ok(( + [ + ( + header::CONTENT_TYPE, + HeaderValue::from_static("application/zip"), + ), + (header::CONTENT_DISPOSITION, disposition), + ], + zip, + )) +} diff --git a/compliance-agent/src/api/handlers/mod.rs b/compliance-agent/src/api/handlers/mod.rs index fd55beb..25f47d8 100644 --- a/compliance-agent/src/api/handlers/mod.rs +++ b/compliance-agent/src/api/handlers/mod.rs @@ -3,6 +3,7 @@ pub mod chat; pub mod dast; pub mod demo_seed; pub mod dto; +pub mod evidence; pub mod findings; pub mod graph; pub mod health; diff --git a/compliance-agent/src/api/handlers/sbom.rs b/compliance-agent/src/api/handlers/sbom.rs index 77b09e7..f3f2b04 100644 --- a/compliance-agent/src/api/handlers/sbom.rs +++ b/compliance-agent/src/api/handlers/sbom.rs @@ -11,7 +11,7 @@ use compliance_core::tenant_ctx::TenantCtx; /// Components above which an export is refused instead of built (#67). An /// SBOM is a compliance document, so it is never truncated: a repository this /// large gets a clear error, not a partial file. -const MAX_EXPORT_COMPONENTS: u64 = 100_000; +pub(crate) const MAX_EXPORT_COMPONENTS: u64 = 100_000; /// Package names listed per license in the summary; `count` stays exact. const MAX_LICENSE_PACKAGES: i64 = 100; @@ -165,77 +165,11 @@ pub async fn export_sbom( } }; + let subject = format!("repo-{}", params.repo_id); let body = if params.format == "spdx" { - // SPDX 2.3 format - let packages: Vec = entries - .iter() - .enumerate() - .map(|(i, e)| { - serde_json::json!({ - "SPDXID": format!("SPDXRef-Package-{i}"), - "name": e.name, - "versionInfo": e.version, - "downloadLocation": "NOASSERTION", - "licenseConcluded": e.license.as_deref().unwrap_or("NOASSERTION"), - "externalRefs": e.purl.as_ref().map(|p| vec![serde_json::json!({ - "referenceCategory": "PACKAGE-MANAGER", - "referenceType": "purl", - "referenceLocator": p, - })]).unwrap_or_default(), - }) - }) - .collect(); - - serde_json::json!({ - "spdxVersion": "SPDX-2.3", - "dataLicense": "CC0-1.0", - "SPDXID": "SPDXRef-DOCUMENT", - "name": format!("sbom-{}", params.repo_id), - "documentNamespace": format!("https://compliance-scanner/sbom/{}", params.repo_id), - "packages": packages, - }) + crate::evidence::sbom_docs::spdx(&entries, ¶ms.repo_id) } else { - // CycloneDX 1.5 format - let components: Vec = entries - .iter() - .map(|e| { - let mut comp = serde_json::json!({ - "type": "library", - "name": e.name, - "version": e.version, - "group": e.package_manager, - }); - if let Some(purl) = &e.purl { - comp["purl"] = serde_json::Value::String(purl.clone()); - } - if let Some(license) = &e.license { - comp["licenses"] = serde_json::json!([{ "license": { "id": license } }]); - } - if !e.known_vulnerabilities.is_empty() { - comp["vulnerabilities"] = serde_json::json!( - e.known_vulnerabilities.iter().map(|v| serde_json::json!({ - "id": v.id, - "source": { "name": v.source }, - "ratings": v.severity.as_ref().map(|s| vec![serde_json::json!({"severity": s})]).unwrap_or_default(), - })).collect::>() - ); - } - comp - }) - .collect(); - - serde_json::json!({ - "bomFormat": "CycloneDX", - "specVersion": "1.5", - "version": 1, - "metadata": { - "component": { - "type": "application", - "name": format!("repo-{}", params.repo_id), - } - }, - "components": components, - }) + crate::evidence::sbom_docs::cyclonedx(&entries, &subject) }; let json_str = diff --git a/compliance-agent/src/api/routes.rs b/compliance-agent/src/api/routes.rs index a498748..b73e20a 100644 --- a/compliance-agent/src/api/routes.rs +++ b/compliance-agent/src/api/routes.rs @@ -70,6 +70,10 @@ pub fn build_router() -> Router { "/api/v1/findings/{id}/feedback", patch(handlers::update_finding_feedback), ) + .route( + "/api/v1/targets/{id}/evidence-pack", + get(handlers::evidence::evidence_pack), + ) // Findings from a manual DAST run or penetration test. .route( "/api/v1/targets/{id}/findings", diff --git a/compliance-agent/src/evidence/mod.rs b/compliance-agent/src/evidence/mod.rs new file mode 100644 index 0000000..a673409 --- /dev/null +++ b/compliance-agent/src/evidence/mod.rs @@ -0,0 +1,296 @@ +//! The evidence pack: everything Prüfwerk knows about one target, as files a +//! conformity process can keep (#285). +//! +//! It is served on request (API, MCP) and pulled by breakpilot's document +//! service, which writes the reports; Prüfwerk renders no PDF. Each file's +//! sha256 is in `manifest.json`, with the scan run, the tool versions and the +//! hash of the control catalog that produced the CRA mapping, so a report +//! built from the pack can say exactly what it rests on. + +pub mod sbom_docs; + +use std::io::Write; + +use chrono::{DateTime, Utc}; +use serde::Serialize; +use sha2::{Digest, Sha256}; + +use compliance_core::models::oscal_assessment::assess; +use compliance_core::models::{CveAlert, Finding, OnboardedTarget, SbomEntry, ScanRun}; + +use crate::error::AgentError; + +/// Where the image records the versions of the tools it ships. +const TOOL_VERSIONS_PATH: &str = "/opt/pruefwerk/tool-versions.json"; + +/// What the pack is built from. +pub struct EvidenceInputs { + pub target: OnboardedTarget, + pub findings: Vec, + pub sbom: Vec, + pub cves: Vec, + /// The newest scan run, if the target was ever scanned. + pub last_run: Option, +} + +/// One file of the pack, as `manifest.json` lists it. +#[derive(Debug, Serialize, PartialEq, Eq)] +pub struct ManifestFile { + pub name: String, + pub sha256: String, + pub bytes: usize, +} + +/// `manifest.json`. +#[derive(Debug, Serialize)] +struct Manifest { + product: &'static str, + version: &'static str, + generated_at: DateTime, + target: serde_json::Value, + last_scan_run: Option, + /// The tools in the image that produced the findings, when known. + tool_versions: Option, + control_catalog: serde_json::Value, + counts: serde_json::Value, + files: Vec, +} + +/// The pack as a ZIP, and the manifest's file list. +/// +/// # Errors +/// +/// When a document cannot be serialised or the archive cannot be written. +pub fn build_pack( + inputs: &EvidenceInputs, + at: DateTime, +) -> Result<(Vec, Vec), AgentError> { + let subject = inputs.target.name.as_str(); + let files: Vec<(&str, Vec)> = vec![ + ( + "oscal-assessment-results.json", + json(&assess(&inputs.findings, at))?, + ), + ( + "sbom.cdx.json", + json(&sbom_docs::cyclonedx(&inputs.sbom, subject))?, + ), + ( + "sbom.spdx.json", + json(&sbom_docs::spdx(&inputs.sbom, subject))?, + ), + ("findings.json", json(&inputs.findings)?), + ("findings.csv", findings_csv(&inputs.findings).into_bytes()), + ("cve-alerts.json", json(&inputs.cves)?), + ]; + let listed: Vec = files + .iter() + .map(|(name, bytes)| ManifestFile { + name: (*name).to_string(), + sha256: hex::encode(Sha256::digest(bytes)), + bytes: bytes.len(), + }) + .collect(); + + let catalog = control_map::ControlMap::cra_source(); + let manifest = Manifest { + product: "Prüfwerk", + version: env!("CARGO_PKG_VERSION"), + generated_at: at, + target: serde_json::json!({ + "id": inputs.target.id.map(|id| id.to_hex()), + "name": inputs.target.name, + "type": inputs.target.target_type.to_string(), + }), + last_scan_run: inputs.last_run.as_ref().map(|run| { + serde_json::json!({ + "id": run.id.map(|id| id.to_hex()), + "status": run.status, + "started_at": run.started_at, + "completed_at": run.completed_at, + "skipped_stages": run.skipped_stages, + }) + }), + tool_versions: std::fs::read(TOOL_VERSIONS_PATH) + .ok() + .and_then(|b| serde_json::from_slice(&b).ok()), + control_catalog: serde_json::json!({ + "framework": "CRA Annex I", + "map_sha256": hex::encode(Sha256::digest(catalog.as_bytes())), + }), + counts: serde_json::json!({ + "findings": inputs.findings.len(), + "sbom_components": inputs.sbom.len(), + "cve_alerts": inputs.cves.len(), + }), + files: listed, + }; + let manifest_bytes = json(&manifest)?; + + let mut zip = zip::ZipWriter::new(std::io::Cursor::new(Vec::new())); + let options: zip::write::SimpleFileOptions = Default::default(); + for (name, bytes) in files + .iter() + .map(|(n, b)| (*n, b.as_slice())) + .chain(std::iter::once(( + "manifest.json", + manifest_bytes.as_slice(), + ))) + { + zip.start_file(name, options) + .map_err(|e| AgentError::Other(e.to_string()))?; + zip.write_all(bytes)?; + } + let archive = zip + .finish() + .map_err(|e| AgentError::Other(e.to_string()))? + .into_inner(); + Ok((archive, manifest.files)) +} + +/// `value` as pretty-printed JSON. +fn json(value: &T) -> Result, AgentError> { + serde_json::to_vec_pretty(value).map_err(|e| AgentError::Other(e.to_string())) +} + +/// The findings as CSV, one row each, for a spreadsheet. +fn findings_csv(findings: &[Finding]) -> String { + let mut out = + String::from("id,severity,status,type,scanner,rule_id,cwe,location,title,cra_controls\n"); + for f in findings { + let location = match (&f.file_path, f.line_number) { + (Some(file), Some(line)) => format!("{file}:{line}"), + (Some(file), None) => file.clone(), + _ => String::new(), + }; + let row = [ + f.id.map(|id| id.to_hex()).unwrap_or_default(), + f.severity.to_string(), + f.status.to_string(), + f.scan_type.to_string(), + f.scanner.clone(), + f.rule_id.clone().unwrap_or_default(), + f.cwe.clone().unwrap_or_default(), + location, + f.title.clone(), + f.control_refs.join(" "), + ]; + let cells: Vec = row.iter().map(|c| csv_cell(c)).collect(); + out.push_str(&cells.join(",")); + out.push('\n'); + } + out +} + +/// A CSV cell, quoted when it holds a comma, quote or line break. A leading +/// `=`, `+`, `-` or `@` is prefixed with `'` so a spreadsheet does not run a +/// finding's text as a formula. +fn csv_cell(value: &str) -> String { + let value = if value.starts_with(['=', '+', '-', '@']) { + format!("'{value}") + } else { + value.to_string() + }; + if value.contains([',', '"', '\n', '\r']) { + format!("\"{}\"", value.replace('"', "\"\"")) + } else { + value + } +} + +#[cfg(test)] +#[allow(clippy::expect_used)] +mod tests { + use super::*; + use compliance_core::models::{ScanType, Severity, TargetType}; + use std::io::Read; + + fn inputs() -> EvidenceInputs { + let mut finding = Finding::new( + "t1".into(), + "fp".into(), + "semgrep".into(), + ScanType::Sast, + "Hard-coded credential, \"admin\"".into(), + "d".into(), + Severity::High, + ); + finding.cwe = Some("CWE-798".into()); + finding.file_path = Some("Core/Src/comms.c".into()); + finding.line_number = Some(9); + finding.control_refs = vec!["cra-ai-8".into()]; + EvidenceInputs { + target: OnboardedTarget::new("sensor-node".into(), TargetType::FirmwareBareMetal), + findings: vec![finding], + sbom: vec![SbomEntry::new( + "t1".into(), + "FreeRTOS".into(), + "10.3.1".into(), + "embedded".into(), + )], + cves: vec![], + last_run: None, + } + } + + #[test] + fn the_pack_holds_every_file_and_the_manifest_hashes_match() { + let (zip_bytes, listed) = build_pack(&inputs(), Utc::now()).expect("pack"); + let mut archive = + zip::ZipArchive::new(std::io::Cursor::new(zip_bytes)).expect("a valid zip"); + let mut names: Vec = archive.file_names().map(String::from).collect(); + names.sort(); + assert_eq!( + names, + [ + "cve-alerts.json", + "findings.csv", + "findings.json", + "manifest.json", + "oscal-assessment-results.json", + "sbom.cdx.json", + "sbom.spdx.json", + ] + ); + for file in &listed { + let mut bytes = Vec::new(); + archive + .by_name(&file.name) + .expect("listed file present") + .read_to_end(&mut bytes) + .expect("read"); + assert_eq!( + hex::encode(Sha256::digest(&bytes)), + file.sha256, + "{}", + file.name + ); + } + let mut manifest = String::new(); + archive + .by_name("manifest.json") + .expect("manifest") + .read_to_string(&mut manifest) + .expect("read"); + let manifest: serde_json::Value = serde_json::from_str(&manifest).expect("json"); + assert_eq!(manifest["counts"]["findings"], 1); + assert_eq!( + manifest["control_catalog"]["map_sha256"] + .as_str() + .map(str::len), + Some(64) + ); + } + + #[test] + fn csv_cells_are_quoted_and_formulas_defused() { + let csv = findings_csv(&inputs().findings); + assert!( + csv.contains("\"Hard-coded credential, \"\"admin\"\"\""), + "{csv}" + ); + assert!(csv.contains("Core/Src/comms.c:9")); + assert_eq!(csv_cell("=HYPERLINK(1)"), "'=HYPERLINK(1)"); + assert_eq!(csv_cell("plain"), "plain"); + } +} diff --git a/compliance-agent/src/evidence/sbom_docs.rs b/compliance-agent/src/evidence/sbom_docs.rs new file mode 100644 index 0000000..0f526ea --- /dev/null +++ b/compliance-agent/src/evidence/sbom_docs.rs @@ -0,0 +1,102 @@ +//! SBOM documents in the two exchange formats: CycloneDX 1.5 and SPDX 2.3. +//! Shared by the SBOM export and the evidence pack, so both say the same. + +use compliance_core::models::SbomEntry; + +/// A CycloneDX 1.5 document for `entries`, named after `subject`. +pub fn cyclonedx(entries: &[SbomEntry], subject: &str) -> serde_json::Value { + let components: Vec = entries + .iter() + .map(|e| { + let mut comp = serde_json::json!({ + "type": "library", + "name": e.name, + "version": e.version, + "group": e.package_manager, + }); + if let Some(purl) = &e.purl { + comp["purl"] = serde_json::Value::String(purl.clone()); + } + if let Some(license) = &e.license { + comp["licenses"] = serde_json::json!([{ "license": { "id": license } }]); + } + if !e.known_vulnerabilities.is_empty() { + comp["vulnerabilities"] = serde_json::json!(e + .known_vulnerabilities + .iter() + .map(|v| serde_json::json!({ + "id": v.id, + "source": { "name": v.source }, + "ratings": v + .severity + .as_ref() + .map(|s| vec![serde_json::json!({ "severity": s })]) + .unwrap_or_default(), + })) + .collect::>()); + } + comp + }) + .collect(); + + serde_json::json!({ + "bomFormat": "CycloneDX", + "specVersion": "1.5", + "version": 1, + "metadata": { + "component": { "type": "application", "name": subject } + }, + "components": components, + }) +} + +/// An SPDX 2.3 document for `entries`, named after `subject`. +pub fn spdx(entries: &[SbomEntry], subject: &str) -> serde_json::Value { + let packages: Vec = entries + .iter() + .enumerate() + .map(|(i, e)| { + serde_json::json!({ + "SPDXID": format!("SPDXRef-Package-{i}"), + "name": e.name, + "versionInfo": e.version, + "downloadLocation": "NOASSERTION", + "licenseConcluded": e.license.as_deref().unwrap_or("NOASSERTION"), + "externalRefs": e.purl.as_ref().map(|p| vec![serde_json::json!({ + "referenceCategory": "PACKAGE-MANAGER", + "referenceType": "purl", + "referenceLocator": p, + })]).unwrap_or_default(), + }) + }) + .collect(); + + serde_json::json!({ + "spdxVersion": "SPDX-2.3", + "dataLicense": "CC0-1.0", + "SPDXID": "SPDXRef-DOCUMENT", + "name": format!("sbom-{subject}"), + "documentNamespace": format!("https://compliance-scanner/sbom/{subject}"), + "packages": packages, + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn both_formats_list_every_component() { + let mut e = SbomEntry::new("t".into(), "lwIP".into(), "2.1.2".into(), "embedded".into()); + e.license = Some("BSD-3-Clause".into()); + let cdx = cyclonedx(std::slice::from_ref(&e), "t"); + assert_eq!(cdx["bomFormat"], "CycloneDX"); + assert_eq!( + cdx["components"][0]["licenses"][0]["license"]["id"], + "BSD-3-Clause" + ); + let spdx = spdx(&[e], "t"); + assert_eq!(spdx["spdxVersion"], "SPDX-2.3"); + assert_eq!(spdx["packages"][0]["versionInfo"], "2.1.2"); + } +} diff --git a/compliance-agent/src/lib.rs b/compliance-agent/src/lib.rs index c27245d..b68b797 100644 --- a/compliance-agent/src/lib.rs +++ b/compliance-agent/src/lib.rs @@ -8,6 +8,7 @@ pub mod controls; pub mod database; pub mod demo_seed; pub mod error; +pub mod evidence; pub mod fixtures; pub mod import; pub mod ingest; diff --git a/compliance-agent/tests/evidence.rs b/compliance-agent/tests/evidence.rs new file mode 100644 index 0000000..6bc0af6 --- /dev/null +++ b/compliance-agent/tests/evidence.rs @@ -0,0 +1,75 @@ +//! The evidence pack of a target, served as a ZIP (#285). +//! +//! Drives the real API against a live Mongo (`TEST_MONGODB_URI`). + +#![allow(clippy::expect_used, clippy::unwrap_used)] + +mod common; + +use std::io::Read; + +use common::TestServer; + +#[tokio::test] +async fn a_target_s_evidence_pack_holds_its_findings_and_hashes() { + let server = TestServer::start().await; + + // Arrange: a target with one finding from a penetration test. + let created: serde_json::Value = server + .post( + "/api/v1/targets", + &serde_json::json!({ "name": "gateway", "target_type": "firmware_rtos" }), + ) + .await + .json() + .await + .unwrap(); + let id = created["data"]["_id"]["$oid"].as_str().unwrap().to_string(); + let added = server + .post( + &format!("/api/v1/targets/{id}/findings"), + &serde_json::json!({ + "kind": "pentest", "title": "Telnet with a default password", + "severity": "critical", "cwe": "798", "location": "tcp://192.0.2.10:23", + }), + ) + .await; + assert_eq!(added.status().as_u16(), 201); + + // Act + let resp = server + .get(&format!("/api/v1/targets/{id}/evidence-pack")) + .await; + let missing = server + .get("/api/v1/targets/000000000000000000000000/evidence-pack") + .await; + + // Assert + assert_eq!(resp.status().as_u16(), 200); + assert_eq!( + resp.headers()["content-type"].to_str().unwrap(), + "application/zip" + ); + let bytes = resp.bytes().await.unwrap(); + let mut zip = zip::ZipArchive::new(std::io::Cursor::new(bytes.to_vec())).unwrap(); + let mut read = |name: &str| { + let mut text = String::new(); + zip.by_name(name) + .unwrap_or_else(|_| panic!("{name} in the pack")) + .read_to_string(&mut text) + .unwrap(); + text + }; + let manifest: serde_json::Value = serde_json::from_str(&read("manifest.json")).unwrap(); + assert_eq!(manifest["target"]["name"], "gateway"); + assert_eq!(manifest["counts"]["findings"], 1); + let oscal = read("oscal-assessment-results.json"); + assert!( + oscal.contains("cra-ai-8"), + "the finding's CRA control is assessed" + ); + assert!(read("findings.csv").contains("tcp://192.0.2.10:23")); + assert_eq!(missing.status().as_u16(), 404); + + server.cleanup().await; +} diff --git a/compliance-dashboard/src/i18n/texts.rs b/compliance-dashboard/src/i18n/texts.rs index 49318bb..33803e1 100644 --- a/compliance-dashboard/src/i18n/texts.rs +++ b/compliance-dashboard/src/i18n/texts.rs @@ -527,6 +527,16 @@ pub mod targets { de: "Token wird beim Speichern entfernt", en: "token is removed on save", }; + pub const EVIDENCE_PACK: Text = Text { + de: "Nachweispaket herunterladen", + en: "Download evidence pack", + }; + pub const EVIDENCE_HINT: Text = Text { + de: "ZIP mit OSCAL-Bewertung (CRA Anhang I), SBOM (CycloneDX, SPDX), Befunden \ + (JSON, CSV), CVE-Warnungen und einem Manifest mit SHA-256-Prüfsummen.", + en: "ZIP with the OSCAL assessment (CRA Annex I), SBOM (CycloneDX, SPDX), \ + findings (JSON, CSV), CVE alerts and a manifest with SHA-256 checksums.", + }; } /// Target types and artifact kinds, keyed by their API value. diff --git a/compliance-dashboard/src/infrastructure/agent_client.rs b/compliance-dashboard/src/infrastructure/agent_client.rs index 9c7616b..9ec5e1c 100644 --- a/compliance-dashboard/src/infrastructure/agent_client.rs +++ b/compliance-dashboard/src/infrastructure/agent_client.rs @@ -66,6 +66,21 @@ pub async fn json_or_error( .map_err(|e| ServerFnError::new(e.to_string())) } +/// The response itself when the agent accepted the request, else the refusal +/// (as for [`json_or_error`]); for a body the caller streams on. +/// +/// # Errors +/// +/// The refusal for a non-2xx status. +pub async fn ok_response(resp: reqwest::Response) -> Result { + let status = resp.status(); + if status.is_success() { + return Ok(resp); + } + let body = resp.text().await.unwrap_or_default(); + Err(ServerFnError::new(refusal_message(status, &body))) +} + /// Check an agent response whose body the caller does not need. /// /// # Errors diff --git a/compliance-dashboard/src/infrastructure/evidence.rs b/compliance-dashboard/src/infrastructure/evidence.rs new file mode 100644 index 0000000..2f5f749 --- /dev/null +++ b/compliance-dashboard/src/infrastructure/evidence.rs @@ -0,0 +1,44 @@ +//! The evidence pack download: the agent's ZIP streamed through to the +//! browser, never held here whole. + +use dioxus::prelude::*; + +/// Where the browser downloads a target's evidence pack. +pub fn evidence_pack_url(target_id: &str) -> String { + format!("/api/evidence-pack/{target_id}") +} + +/// `GET /api/evidence-pack/{id}`: the target's evidence pack as a ZIP. +#[get("/api/evidence-pack/{id}")] +pub async fn download_evidence_pack( + id: String, +) -> Result { + let resp = super::agent_client::agent_get(&format!("/api/v1/targets/{id}/evidence-pack")) + .await? + .send() + .await + .map_err(|e| ServerFnError::new(e.to_string()))?; + let resp = super::agent_client::ok_response(resp).await?; + let name = format!( + "pruefwerk-evidence-{id}-{}.zip", + chrono::Utc::now().format("%Y%m%d") + ); + let size = resp.content_length(); + let body = axum::body::Body::from_stream(resp.bytes_stream()).into_data_stream(); + Ok(dioxus::fullstack::FileStream::from_raw( + name, + size, + "application/zip".to_string(), + body, + )) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_download_url_names_the_target() { + assert_eq!(evidence_pack_url("65f0"), "/api/evidence-pack/65f0"); + } +} diff --git a/compliance-dashboard/src/infrastructure/mod.rs b/compliance-dashboard/src/infrastructure/mod.rs index 66cda84..e25af2c 100644 --- a/compliance-dashboard/src/infrastructure/mod.rs +++ b/compliance-dashboard/src/infrastructure/mod.rs @@ -3,6 +3,7 @@ pub mod auth_check; pub mod chat; pub mod dast; +pub mod evidence; pub mod findings; pub mod graph; pub mod help_chat; diff --git a/compliance-dashboard/src/pages/targets.rs b/compliance-dashboard/src/pages/targets.rs index 5454c51..089eec3 100644 --- a/compliance-dashboard/src/pages/targets.rs +++ b/compliance-dashboard/src/pages/targets.rs @@ -558,6 +558,15 @@ pub fn TargetsPage() -> Element { tr { td { colspan: "6", div { style: "padding: 12px 8px;", + div { style: "margin-bottom: 12px; display: flex; gap: 8px; align-items: center; flex-wrap: wrap;", + a { + class: "btn btn-secondary", + href: crate::infrastructure::evidence::evidence_pack_url(&id), + download: "", + {tx::EVIDENCE_PACK.get(lang)} + } + span { style: "opacity: 0.7; font-size: 0.85em;", {tx::EVIDENCE_HINT.get(lang)} } + } h4 { style: "margin: 0 0 6px;", {scan_texts::HISTORY.get(lang)} } ScanRunList { target_id: id.clone() } h4 { style: "margin: 12px 0 6px;", {tx::ARTIFACTS.get(lang)} } diff --git a/control-map/src/lib.rs b/control-map/src/lib.rs index 65320a9..fe564c7 100644 --- a/control-map/src/lib.rs +++ b/control-map/src/lib.rs @@ -75,6 +75,12 @@ fn rule_id_matches(bound: &str, actual: &str) -> bool { } impl ControlMap { + /// The built-in CRA control map as authored, for hashing into evidence: + /// the hash identifies exactly which mapping produced a report. + pub fn cra_source() -> &'static str { + CRA_MAP_JSON + } + /// Load the built-in CRA control map (the embedded, authored LUT). pub fn cra() -> Result { Ok(serde_json::from_str(CRA_MAP_JSON)?)