fix(scan): uploads carry their sha256, so change detection compares the bytes
CI / Check (push) Skipped
CI / Detect Changes (pull_request) Skipped
CI / Deploy Agent (pull_request) Skipped
CI / Deploy Dashboard (pull_request) Skipped
CI / Deploy Docs (pull_request) Skipped
CI / Deploy MCP (pull_request) Skipped
CI / Check (pull_request) Failing after 6m55s

#465's change key for uploaded files is a digest of each upload's
artifact id and content_hash, but nothing ever stored content_hash on an
uploaded artifact (ingest hashed the blob and dropped it). So the key
never described the files actually uploaded.

- the upload handler stores the sha256 of the uploaded bytes on the
  artifact
- a scan stores the sha256 ingest computed on older uploads that have
  none, so existing targets become comparable (a scheduled run skips from the third scan on)
- a person's scan request takes over a pending scheduled/webhook
  follow-up in the scan gate instead of being dropped, so "Prüfung
  starten" right after an upload always scans in full

Unchanged scheduled rescans still skip (identical uploads, same build).

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EYKjxacrr6K88DruUmP48p
This commit is contained in:
Sharang ParnerkarandClaude Opus 5.5 committed 2026-10-08 23:22:05 +02:00
1 parent e1bf9e861c
commit 1602acd233
6 files changed
+208 -6

No files matched your search

@@ -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.
+50 -5
View File
@@ -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<String> {
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,27 @@ pub fn upload_inputs(target: &OnboardedTarget) -> Option<String> {
Some(hex::encode(hasher.finalize()))
}
/// 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.
@@ -94,6 +113,32 @@ mod tests {
assert!(!upload_unchanged(&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"))]);
@@ -1723,6 +1723,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;
@@ -1842,6 +1843,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.
+28
View File
@@ -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);
+93
View File
@@ -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<Artifact> {
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<Artifact>) -> 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<Artifact> = second[1..].to_vec();
assert!(!upload_unchanged(&after_scan_of(&first, only_b)));
server.cleanup().await;
}
+3 -1
View File
@@ -76,7 +76,9 @@ 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
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. 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