diff --git a/compliance-agent/src/api/handlers/onboarding.rs b/compliance-agent/src/api/handlers/onboarding.rs index 148b7d7..6d2d6e5 100644 --- a/compliance-agent/src/api/handlers/onboarding.rs +++ b/compliance-agent/src/api/handlers/onboarding.rs @@ -649,6 +649,14 @@ pub async fn upload_artifact( // add-artifact endpoint, not upload. let mut artifact = uploaded_artifact(kind, plc_format, &filename, &upload.path, upload.size) .ok_or(StatusCode::BAD_REQUEST)?; + // What a scheduled scan compares to tell this upload from the files its + // last scan read (#465): without it, no upload was ever known unchanged. + let path = upload.path.clone(); + let (sha, _) = tokio::task::spawn_blocking(move || crate::ingest::blob::hash_file(&path)) + .await + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)? + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; + artifact.content_hash = Some(sha); if kind != ArtifactKind::FirmwareImage { match archive_check(upload.path.clone()).await? { // 7z and rar are never unpacked: say so now, not after a scan. diff --git a/compliance-agent/src/pipeline/change.rs b/compliance-agent/src/pipeline/change.rs index 75be80f..5d431f2 100644 --- a/compliance-agent/src/pipeline/change.rs +++ b/compliance-agent/src/pipeline/change.rs @@ -9,10 +9,11 @@ //! its own). The CVE monitor matches the stored SBOM against new advisories //! independently of these scans. -use compliance_core::models::{ArtifactKind, OnboardedTarget}; +use compliance_core::models::{Artifact, ArtifactKind, OnboardedTarget}; use sha2::{Digest, Sha256}; use crate::api::handlers::platform::{BUILD_COMMIT, BUILD_VERSION}; +use crate::ingest::IngestSet; /// The agent build that runs a scan, as stored in /// [`compliance_core::models::LastScan::build`]. @@ -26,10 +27,7 @@ pub fn build_id() -> String { /// unchanged upload from a changed one, and it is scanned. pub fn upload_inputs(target: &OnboardedTarget) -> Option { let mut parts: Vec<(&str, &str)> = Vec::new(); - for artifact in &target.artifacts { - if matches!(artifact.kind, ArtifactKind::GitRepo | ArtifactKind::LiveUrl) { - continue; - } + for artifact in target.artifacts.iter().filter(|a| is_upload(a)) { parts.push((artifact.id.as_str(), artifact.content_hash.as_deref()?)); } if parts.is_empty() { @@ -46,6 +44,61 @@ pub fn upload_inputs(target: &OnboardedTarget) -> Option { Some(hex::encode(hasher.finalize())) } +/// Whether unchanged uploads let a scheduled scan be skipped: on unless +/// `UPLOAD_CHANGE_SKIP` is `false`, `0` or `off`, which scans a target with +/// uploaded files on every schedule. +pub fn upload_skip_enabled() -> bool { + switch_on(std::env::var("UPLOAD_CHANGE_SKIP").ok().as_deref()) +} + +/// Whether a switch's value leaves it on (the default). +fn switch_on(value: Option<&str>) -> bool { + !matches!( + value.map(|v| v.trim().to_ascii_lowercase()).as_deref(), + Some("false" | "0" | "off") + ) +} + +/// Whether the uploads of a git `target` let a scheduled scan that finds no +/// new commits be skipped: it has none, or (with [`upload_skip_enabled`]) +/// they are the same as at its last completed scan. A file uploaded to a git +/// target since then means the scan runs. +pub fn uploads_allow_git_skip(target: &OnboardedTarget) -> bool { + if !target.artifacts.iter().any(is_upload) { + return true; + } + upload_skip_enabled() && uploads_match(target) +} + +/// Whether the uploads of `target` are the ones its last completed scan read. +fn uploads_match(target: &OnboardedTarget) -> bool { + target + .last_scan + .as_ref() + .is_some_and(|last| last.inputs.is_some() && last.inputs == upload_inputs(target)) +} + +/// Whether `artifact` is a file uploaded to the target (not a git repository +/// or a live URL, which are fetched or probed). +fn is_upload(artifact: &Artifact) -> bool { + !matches!(artifact.kind, ArtifactKind::GitRepo | ArtifactKind::LiveUrl) +} + +/// The sha256 that ingest computed for each upload of `target` that records +/// none, as (artifact id, sha256). Uploads before the upload recorded it have +/// none, so they never counted as unchanged; storing it makes them comparable. +pub fn unrecorded_hashes(target: &OnboardedTarget, ingested: &IngestSet) -> Vec<(String, String)> { + target + .artifacts + .iter() + .filter(|a| is_upload(a) && a.content_hash.is_none()) + .filter_map(|a| { + let sha = ingested.get(&a.id)?.content_hash.clone()?; + Some((a.id.clone(), sha)) + }) + .collect() +} + /// Whether a scheduled scan of `target`, which has no git repository, would /// read the same uploaded files with the same build as its last completed /// scan. @@ -56,7 +109,7 @@ pub fn upload_unchanged(target: &OnboardedTarget) -> bool { let Some(last) = &target.last_scan else { return false; }; - last.build == build_id() && last.inputs.is_some() && last.inputs == upload_inputs(target) + last.build == build_id() && uploads_match(target) } #[cfg(test)] @@ -94,6 +147,58 @@ mod tests { assert!(!upload_unchanged(&t)); } + #[test] + fn the_skip_switch_is_on_unless_turned_off() { + assert!(switch_on(None)); + assert!(switch_on(Some("true"))); + assert!(!switch_on(Some("false"))); + assert!(!switch_on(Some(" OFF "))); + } + + #[test] + fn a_git_target_with_a_changed_upload_is_not_skipped() { + let mut repo = Artifact::git_repo("https://git.example/x.git", "main"); + repo.id = "g".into(); + let only_git = target(vec![repo.clone()]); + assert!(uploads_allow_git_skip(&only_git), "nothing uploaded"); + + let mut t = target(vec![repo, upload("a", Some("h1"))]); + t.last_scan = Some(LastScan { + build: build_id(), + inputs: upload_inputs(&t), + }); + assert!(uploads_match(&t)); + t.artifacts.push(upload("b", Some("h2"))); + assert!(!uploads_match(&t), "a new upload since the last scan"); + assert!(!uploads_allow_git_skip(&t)); + } + + #[test] + fn only_uploads_without_a_hash_take_the_one_ingest_computed() { + let mut repo = Artifact::git_repo("https://git.example/x.git", "main"); + repo.id = "g".into(); + let t = target(vec![upload("old", None), upload("new", Some("h2")), repo]); + let mut ingested = IngestSet::default(); + for (id, sha) in [("old", "h1"), ("new", "h2"), ("g", "head")] { + ingested.by_artifact.insert( + id.into(), + crate::ingest::IngestedArtifact { + artifact_id: id.into(), + kind: ArtifactKind::SourceArchive, + working_path: None, + content_hash: Some(sha.into()), + size_bytes: None, + facts: Vec::new(), + }, + ); + } + + assert_eq!( + unrecorded_hashes(&t, &ingested), + [("old".to_string(), "h1".to_string())] + ); + } + #[test] fn a_new_build_a_live_url_or_an_unhashed_upload_scans_again() { let mut t = target(vec![upload("a", Some("h1"))]); diff --git a/compliance-agent/src/pipeline/orchestrator.rs b/compliance-agent/src/pipeline/orchestrator.rs index 002bcb3..ca2cd52 100644 --- a/compliance-agent/src/pipeline/orchestrator.rs +++ b/compliance-agent/src/pipeline/orchestrator.rs @@ -161,9 +161,10 @@ impl PipelineOrchestrator { // A scheduled or webhook scan of an unchanged repository has nothing // new to find; one a person started always runs (after a changed - // setting it can find something else), and a new Prüfwerk build scans - // once (#465). + // setting it can find something else), a new Prüfwerk build scans + // once (#465), and so does a file uploaded to the target since. if !trigger.started_by_person() + && repo.uploads_allow_skip && repo.last_scanned_build.as_deref() == Some(crate::pipeline::change::build_id().as_str()) && !GitOps::has_new_commits(&repo_path, repo.last_scanned_commit.as_deref())? @@ -1079,6 +1080,7 @@ impl PipelineOrchestrator { .any(|a| a.kind == ArtifactKind::GitRepo); if !trigger.started_by_person() && !has_git + && crate::pipeline::change::upload_skip_enabled() && crate::pipeline::change::upload_unchanged(target) { tracing::info!(target_id = %target_id, "Uploaded files unchanged, skipping scan"); @@ -1173,6 +1175,31 @@ impl PipelineOrchestrator { match target.code_artifact() { Some(code) if code.kind == ArtifactKind::GitRepo => { + // The code scan reads the repository; a source archive also + // uploaded to the target is not read, and the run says so. + for archive in target + .artifacts + .iter() + .filter(|a| a.kind == ArtifactKind::SourceArchive) + { + let name = archive + .display_name + .as_deref() + .unwrap_or(&archive.source_ref); + self.skip_stage( + scan_run_id, + SkippedStage::new( + "source_archive", + SkipCode::NotAnalysedYet, + format!( + "the code scan reads the target's git repository; the uploaded \ + archive {name} is not scanned (upload it as a target of its own)" + ), + ) + .about(name.to_string()), + ) + .await; + } let repo = RepoView::from_target(target, code, &self.secrets); let n = self.run_pipeline(&repo, scan_run_id, trigger).await?; self.finalize_target(target, &repo, n).await?; @@ -1745,6 +1772,7 @@ impl PipelineOrchestrator { self.skip_stage(scan_run_id, failure.skipped()).await; } let working_paths = ingest_set.working_paths(); + self.record_upload_hashes(target, &ingest_set).await; let mut detected_firmware = false; self.update_step(scan_run_id, ScanStep::DetectProjectType) .await; @@ -1864,6 +1892,31 @@ impl PipelineOrchestrator { working_paths } + /// Store on each upload that has none the sha256 ingest computed, so the + /// next scheduled scan can tell whether it changed (#465). Best-effort. + async fn record_upload_hashes( + &self, + target: &OnboardedTarget, + ingest_set: &crate::ingest::IngestSet, + ) { + let Some(oid) = target.id else { + return; + }; + for (artifact_id, sha) in crate::pipeline::change::unrecorded_hashes(target, ingest_set) { + if let Err(e) = self + .db + .onboarded_targets() + .update_one( + doc! { "_id": oid, "artifacts.id": &artifact_id }, + doc! { "$set": { "artifacts.$.content_hash": sha } }, + ) + .await + { + tracing::warn!(artifact_id, error = %e, "upload hash not stored"); + } + } + } + /// DAST after the code scan, for a target the matrix plans it for. Gated on /// the plan: a firmware or embedded target has no web surface, and recording /// DAST as skipped there would imply it otherwise would have run. diff --git a/compliance-agent/src/pipeline/repo_view.rs b/compliance-agent/src/pipeline/repo_view.rs index c0a9afc..955dc6e 100644 --- a/compliance-agent/src/pipeline/repo_view.rs +++ b/compliance-agent/src/pipeline/repo_view.rs @@ -42,6 +42,9 @@ pub struct RepoView { /// Created by a managed git source (#439): its Gitea issues get the /// Prüfwerk/CRA labels and a link into Prüfwerk. pub managed: bool, + /// Whether the target's uploaded files let a scheduled scan without new + /// commits be skipped ([`crate::pipeline::change::uploads_allow_git_skip`]). + pub uploads_allow_skip: bool, } impl RepoView { @@ -70,6 +73,7 @@ impl RepoView { last_scanned_build: target.last_scan.as_ref().map(|l| l.build.clone()), findings_count: target.findings_count, managed: target.source_repo.is_some(), + uploads_allow_skip: crate::pipeline::change::uploads_allow_git_skip(target), }; if let Some(git) = &code.git { view.default_branch = git.default_branch.clone(); diff --git a/compliance-agent/src/scan_gate.rs b/compliance-agent/src/scan_gate.rs index ff646bc..3de8b15 100644 --- a/compliance-agent/src/scan_gate.rs +++ b/compliance-agent/src/scan_gate.rs @@ -71,6 +71,16 @@ impl ScanGate { o.insert(Some(trigger)); Admission::Coalesced } + // A person's request takes over a pending scheduled or webhook + // follow-up: that one may skip as unchanged (#465), theirs always + // scans, e.g. right after they uploaded new files. + Entry::Occupied(mut o) + if trigger.started_by_person() + && o.get().as_ref().is_some_and(|p| !p.started_by_person()) => + { + o.insert(Some(trigger)); + Admission::Coalesced + } Entry::Occupied(_) => Admission::Dropped, } } @@ -161,6 +171,24 @@ mod tests { assert_eq!(gate.admit(&key, ScanTrigger::Manual), Admission::Run); } + #[test] + fn a_persons_request_takes_over_a_pending_scheduled_follow_up() { + let gate = ScanGate::new(1); + let key = ScanGate::key("acme", "t1"); + assert_eq!(gate.admit(&key, ScanTrigger::Scheduled), Admission::Run); + assert_eq!( + gate.admit(&key, ScanTrigger::Scheduled), + Admission::Coalesced + ); + + // Clicked after uploading new files: the follow-up scans in full. + assert_eq!(gate.admit(&key, ScanTrigger::Manual), Admission::Coalesced); + assert_eq!(gate.admit(&key, ScanTrigger::Webhook), Admission::Dropped); + assert_eq!(gate.admit(&key, ScanTrigger::Support), Admission::Dropped); + + assert_eq!(gate.finish(&key), Some(ScanTrigger::Manual)); + } + #[test] fn targets_and_tenants_are_independent() { let gate = ScanGate::new(2); diff --git a/compliance-agent/tests/upload_change.rs b/compliance-agent/tests/upload_change.rs new file mode 100644 index 0000000..5710c66 --- /dev/null +++ b/compliance-agent/tests/upload_change.rs @@ -0,0 +1,93 @@ +//! Change detection over uploads (#465): a scheduled scan skips a target only +//! while the files uploaded to it are byte for byte the ones its last +//! completed scan read. Drives the real upload API against a live Mongo +//! (`TEST_MONGODB_URI`). + +#![allow(clippy::expect_used, clippy::unwrap_used)] + +mod common; + +use common::TestServer; +use compliance_agent::pipeline::change::{build_id, upload_inputs, upload_unchanged}; +use compliance_core::models::{Artifact, LastScan, OnboardedTarget, TargetType}; +use sha2::{Digest, Sha256}; + +async fn create_target(server: &TestServer) -> String { + let created: serde_json::Value = server + .post( + "/api/v1/targets", + &serde_json::json!({ "name": "line", "target_type": "backend_service" }), + ) + .await + .json() + .await + .unwrap(); + created["data"]["_id"]["$oid"].as_str().unwrap().to_string() +} + +/// Upload `bytes` as a source archive and return the target's artifacts. +async fn upload(server: &TestServer, id: &str, bytes: &[u8]) -> Vec { + let form = reqwest::multipart::Form::new() + .text("kind", "source_archive") + .part( + "file", + reqwest::multipart::Part::bytes(bytes.to_vec()).file_name("release.zip"), + ); + let target: serde_json::Value = server + .client + .post(format!( + "{}/api/v1/targets/{id}/artifacts/upload", + server.base_url + )) + .multipart(form) + .send() + .await + .unwrap() + .json() + .await + .unwrap(); + serde_json::from_value(target["data"]["artifacts"].clone()).unwrap() +} + +/// The target as the next scan reads it, after a completed scan of `scanned`. +fn after_scan_of(scanned: &[Artifact], now: Vec) -> OnboardedTarget { + let mut read = OnboardedTarget::new("line".into(), TargetType::BackendService); + read.artifacts = scanned.to_vec(); + let mut target = OnboardedTarget::new("line".into(), TargetType::BackendService); + target.artifacts = now; + target.last_scan = Some(LastScan { + build: build_id(), + inputs: upload_inputs(&read), + }); + target +} + +#[tokio::test] +async fn a_new_upload_to_a_scanned_target_is_scanned_again() { + let server = TestServer::start().await; + let id = create_target(&server).await; + + // Arrange: upload A, and a completed scan of it. + let first = upload(&server, &id, b"release 1.0").await; + assert_eq!( + first[0].content_hash.as_deref(), + Some(hex::encode(Sha256::digest(b"release 1.0")).as_str()), + "the upload records the sha256 of its bytes" + ); + assert!( + upload_unchanged(&after_scan_of(&first, first.clone())), + "nothing new uploaded: a scheduled scan may skip" + ); + + // Act: upload B to the same target. + let second = upload(&server, &id, b"release 1.1").await; + + // Assert: the next scheduled scan runs in full. + assert_eq!(second.len(), 2); + assert!(!upload_unchanged(&after_scan_of(&first, second.clone()))); + // A is replaced by B (A removed): still a change. + let only_b: Vec = second[1..].to_vec(); + assert!(!upload_unchanged(&after_scan_of(&first, only_b))); + + server.cleanup().await; +} diff --git a/compliance-dashboard/src/i18n/texts.rs b/compliance-dashboard/src/i18n/texts.rs index ee5c1d5..e260420 100644 --- a/compliance-dashboard/src/i18n/texts.rs +++ b/compliance-dashboard/src/i18n/texts.rs @@ -3131,6 +3131,12 @@ pub mod coverage { de: "braucht ein weiteres Artefakt", en: "needs another artifact", }; + pub const UPLOAD_BESIDE_GIT: Text = Text { + de: "Der Code-Scan liest das Git-Repository des Prüfobjekts; ein dazu hochgeladenes \ + Archiv wird nicht geprüft. Laden Sie es als eigenes Prüfobjekt hoch", + en: "the code scan reads the target's git repository; an archive uploaded to it is \ + not scanned. Upload it as a target of its own", + }; pub const IMAGE_NOT_ANALYSED: Text = Text { de: "Firmware-Images werden noch nicht entpackt: Prüfen Sie stattdessen die \ Firmware-Quellen", @@ -3156,7 +3162,9 @@ pub mod coverage { let r = raw.to_ascii_lowercase(); // Missing artifacts name the kind as `no artifact provided`; // scans no stage runs yet explain themselves in prose. - let text = if r.contains("http(s) live url") { + let text = if r.contains("uploaded archive") { + UPLOAD_BESIDE_GIT + } else if r.contains("http(s) live url") { NEEDS_WEB_URL } else if r.contains("firmware_image") { NEEDS_FIRMWARE @@ -3203,6 +3211,11 @@ mod coverage_tests { ), ("no live_url artifact provided", coverage::NEEDS_DEVICE), ("no git_repo artifact provided", coverage::NEEDS_CODE), + ( + "the code scan reads the target's git repository; the uploaded archive app.zip \ + is not scanned (upload it as a target of its own)", + coverage::UPLOAD_BESIDE_GIT, + ), ( "firmware images are not unpacked or analysed yet: scan the firmware sources \ instead", diff --git a/docs/guide/scanning.md b/docs/guide/scanning.md index 696401a..e9ead21 100644 --- a/docs/guide/scanning.md +++ b/docs/guide/scanning.md @@ -76,8 +76,15 @@ Targets are scanned automatically on a recurring schedule: by default every 6 hours, with a daily check of known components for newly published CVEs. Your administrator controls these schedules. A scheduled scan of a git repository with no new commits since the last scan, or of uploaded files that are the -same as at the last scan, does not scan again; the run says so under -**Nicht ausgeführt** and counts as no scan. After an update of Prüfwerk every +same as at the last scan (compared by their SHA-256, so any newly uploaded +file, even one with the same name, is scanned), does not scan again; the run +says so under +**Nicht ausgeführt** and counts as no scan. A git target to which a file was +uploaded since its last scan is scanned, even without new commits; its code +scan reads the repository, so an archive uploaded to a git target is listed +under **Nicht ausgeführt** as not scanned: upload it as a target of its own. +The administrator can turn the skipping of unchanged uploads off with +`UPLOAD_CHANGE_SKIP=false`. After an update of Prüfwerk every target is scanned once more, since new rules can find more in the same code. **Prüfung starten** always scans in full, also when a restart of Prüfwerk interrupted it and it is started again. The daily CVE check of the known