From c3f9e5380616def2d7900581a878108871838f7e Mon Sep 17 00:00:00 2001 From: Sharang Parnerkar <30073382+mighty840@users.noreply.github.com> Date: Thu, 8 Oct 2026 23:05:26 +0200 Subject: [PATCH] fix(plc): a repository holding only a CODESYS archive is a PLC project A managed git target whose tree is just a .projectarchive was classified "Backend / API" (the classifier knew only .st as PLC evidence), and the CODESYS library/runtime SBOM was collected only on the PLC path, so it got no CODESYS components and no runtime CVEs. - classifier: a committed .projectarchive or CODESYS .project, and an uploaded source archive named *.projectarchive, are PLC evidence (0.85), so a managed target is typed SPS/PLC by its code - code pipeline: every scan tree's .projectarchive files (and an uploaded one, which ingest unpacks) add their CODESYS components to the SBOM and the runtime is matched in NVD with the other NVD lookups, whatever the target type; the code pipeline now owns those entries (a PLC-planned target never reaches it) Co-Authored-By: Claude Opus 5.5 (1M context) Claude-Session: https://claude.ai/code/session_01EYKjxacrr6K88DruUmP48p --- compliance-agent/src/classify/language.rs | 42 +++++++++++++ compliance-agent/src/classify/mod.rs | 26 ++++++++ compliance-agent/src/pipeline/orchestrator.rs | 60 +++++++++++++------ compliance-agent/src/pipeline/plc/sbom.rs | 51 +++++++++++++++- docs/guide/plc.md | 8 +++ 5 files changed, 167 insertions(+), 20 deletions(-) diff --git a/compliance-agent/src/classify/language.rs b/compliance-agent/src/classify/language.rs index da28510..ac2cf63 100644 --- a/compliance-agent/src/classify/language.rs +++ b/compliance-agent/src/classify/language.rs @@ -316,6 +316,11 @@ impl HeuristicClassifier { "firmware image (pending firmwerk detection)", vec![], )), + // A CODESYS project archive uploaded as a plain archive: it is + // unpacked for the scan, so its extension is the evidence. + ArtifactKind::SourceArchive if lower.ends_with(".projectarchive") => out.push( + verdict(TargetType::PlcSps, 0.85, "CODESYS project archive", vec![]), + ), ArtifactKind::LiveUrl if input.artifacts.len() == 1 => { out.push(verdict(TargetType::WebApp, 0.3, "live URL only", vec![])) } @@ -466,6 +471,15 @@ impl HeuristicClassifier { facts_lang("iec-61131-3"), )); } + // A CODESYS project (or its archive) committed to the repository. + if m.has_ext("projectarchive") || m.has_ext("project") { + out.push(verdict( + TargetType::PlcSps, + 0.85, + "CODESYS project files", + facts_lang("iec-61131-3"), + )); + } // Web vs backend from package.json. if m.has_file("package.json") { if package_json_is_frontend(path) { @@ -893,6 +907,34 @@ mod tests { assert!(v.iter().any(|x| x.target_type == TargetType::PlcSps)); } + #[tokio::test] + async fn a_committed_codesys_archive_is_plc_even_beside_a_backend_manifest() { + let only_archive = classify_tree(|root| { + fs::write(root.join("Line.projectarchive"), b"PK").unwrap(); + }) + .await; + assert_eq!(top(&only_archive), TargetType::PlcSps); + + let mixed = classify_tree(|root| { + fs::write(root.join("Pump.project"), b"").unwrap(); + fs::write(root.join("package.json"), "{}").unwrap(); + }) + .await; + assert_eq!(top(&mixed), TargetType::PlcSps); + } + + #[tokio::test] + async fn an_uploaded_codesys_archive_prior_is_plc() { + let artifacts = vec![Artifact::source_archive("Line.projectarchive")]; + let input = ClassificationInput { + artifacts: &artifacts, + working_paths: &HashMap::new(), + description: None, + }; + let v = HeuristicClassifier.classify(&input).await.unwrap(); + assert_eq!(top(&v), TargetType::PlcSps); + } + #[tokio::test] async fn ipa_artifact_prior_is_ios() { let artifacts = vec![Artifact::mobile_package("app.ipa")]; diff --git a/compliance-agent/src/classify/mod.rs b/compliance-agent/src/classify/mod.rs index c0513ad..1cd4803 100644 --- a/compliance-agent/src/classify/mod.rs +++ b/compliance-agent/src/classify/mod.rs @@ -234,6 +234,32 @@ mod tests { assert!(c.facts.iter().any(|f| f.key == "mcu")); } + #[tokio::test] + async fn a_managed_repo_holding_only_a_codesys_archive_is_typed_plc() { + let scratch = Scratch::new(); + let fixture = Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../fixtures/nightly/plc/line_control.projectarchive"); + fs::copy(&fixture, scratch.0.join("line_control.projectarchive")).expect("copy fixture"); + + let artifact = Artifact::git_repo("https://git/plc", "main"); + let mut wp = HashMap::new(); + wp.insert(artifact.id.clone(), scratch.0.clone()); + // A managed target starts with the default type until its code decides. + let mut target = OnboardedTarget::new("plc".to_string(), TargetType::BackendService); + target.source_repo = Some(compliance_core::models::SourceRepo { + base_url: "https://code.example".into(), + repo_id: 1, + full_name: "kunde/plc".into(), + }); + target.artifacts.push(artifact); + + let c = classify_target(&target, &wp, &no_firmware()) + .await + .expect("classify"); + assert_eq!(c.suggested, TargetType::PlcSps); + assert_eq!(target.detected_type(&c), Some(TargetType::PlcSps)); + } + #[tokio::test] async fn no_signal_falls_back_to_declared_type() { let scratch = Scratch::new(); diff --git a/compliance-agent/src/pipeline/orchestrator.rs b/compliance-agent/src/pipeline/orchestrator.rs index 7b5353d..002bcb3 100644 --- a/compliance-agent/src/pipeline/orchestrator.rs +++ b/compliance-agent/src/pipeline/orchestrator.rs @@ -200,17 +200,20 @@ impl PipelineOrchestrator { .await; } - self.scan_tree(&repo_path, repo, scan_run_id).await + self.scan_tree(&repo_path, None, repo, scan_run_id).await } /// The static-analysis stages over a source tree, whatever put it there: a /// git clone, or an uploaded archive that ingest already unpacked. Git-only /// work — change detection and the commit watermark — happens around this, /// never inside it, so an archive gets the same analysis as a repository. + /// `codesys_upload` is an uploaded CODESYS project archive the tree was + /// unpacked from ([`crate::pipeline::plc::sbom::uploaded_archive`]). #[tracing::instrument(skip_all, fields(repo_id = repo.name.as_str()))] async fn scan_tree( &self, tree: &std::path::Path, + codesys_upload: Option<&std::path::Path>, repo: &RepoView, scan_run_id: &str, ) -> Result { @@ -468,7 +471,22 @@ impl PipelineOrchestrator { }) .await .unwrap_or_default(); - for entry in embedded { + // A CODESYS project (committed, or the uploaded archive): its libraries + // and runtime, whatever the target's type. A repository created as + // "Backend / API" that holds only a .projectarchive still gets them. + let tree = repo_path.clone(); + let tree_repo_id = repo_id.clone(); + let upload = codesys_upload.map(std::path::Path::to_path_buf); + let codesys = tokio::task::spawn_blocking(move || { + crate::pipeline::plc::sbom::collect_sbom( + upload.as_deref().unwrap_or(std::path::Path::new("")), + &tree, + &tree_repo_id, + ) + }) + .await + .unwrap_or_default(); + for entry in embedded.into_iter().chain(codesys) { let known = sbom_entries .iter() .any(|e| e.name.eq_ignore_ascii_case(&entry.name) && e.version == entry.version); @@ -560,12 +578,15 @@ impl PipelineOrchestrator { Vec::new() } }; - // OSV has no ecosystem for them: match the embedded libraries in NVD. - // Room for NVD's rate-limit retries on a few libraries. - match tokio::time::timeout( - std::time::Duration::from_secs(300), - cve_scanner.scan_embedded(&repo_id, &mut sbom_entries), - ) + // OSV has no ecosystem for them: match the embedded libraries and a + // CODESYS runtime in NVD. Room for NVD's rate-limit retries on a few. + match tokio::time::timeout(std::time::Duration::from_secs(300), async { + let mut lookup = cve_scanner.scan_embedded(&repo_id, &mut sbom_entries).await; + let codesys = cve_scanner.scan_codesys(&repo_id, &mut sbom_entries).await; + lookup.alerts.extend(codesys.alerts); + lookup.unchecked.extend(codesys.unchecked); + lookup + }) .await { Ok(lookup) => { @@ -582,7 +603,7 @@ impl PipelineOrchestrator { } Err(_) => { cve_complete = false; - tracing::warn!("[{repo_id}] embedded-library CVE match timed out"); + tracing::warn!("[{repo_id}] embedded-library and CODESYS CVE match timed out"); self.record_cve_gap( scan_run_id, "NVD", @@ -843,20 +864,20 @@ impl PipelineOrchestrator { } .spawn(run_findings.status_changed().to_vec()); - // Replace this stage's SBOM entries (not the firmware or CODESYS ones, - // which their own steps own). Entries store the target id as a hex - // string; filtering on the ObjectId matched nothing, so dependencies - // removed from a repo used to stay in its SBOM forever. + // Replace this stage's SBOM entries (not the firmware ones, which their + // own step owns). The CODESYS ones are this stage's too: a PLC target, + // whose control-logic stage owns them, never reaches it. Entries store + // the target id as a hex string; filtering on the ObjectId matched + // nothing, so dependencies removed from a repo used to stay in its SBOM + // forever. if !sbom_entries.is_empty() { - let owned_elsewhere: Vec<&str> = crate::pipeline::firmware_sbom::FIRMWARE_MANAGERS - .into_iter() - .chain(["codesys"]) - .collect(); self.db .sbom_entries() .delete_many(doc! { "repo_id": &repo_id, - "package_manager": { "$nin": owned_elsewhere }, + "package_manager": { + "$nin": crate::pipeline::firmware_sbom::FIRMWARE_MANAGERS.to_vec() + }, }) .await?; } @@ -1167,7 +1188,8 @@ impl PipelineOrchestrator { match working_paths.get(&code.id) { Some(tree) => { let repo = RepoView::from_target(target, code, &self.secrets); - let n = self.scan_tree(tree, &repo, scan_run_id).await?; + 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?; new_count += n; self.dast_after_code_scan(&target_id, &plan, scan_run_id) diff --git a/compliance-agent/src/pipeline/plc/sbom.rs b/compliance-agent/src/pipeline/plc/sbom.rs index b2a4bec..3e87a19 100644 --- a/compliance-agent/src/pipeline/plc/sbom.rs +++ b/compliance-agent/src/pipeline/plc/sbom.rs @@ -13,7 +13,7 @@ use std::collections::BTreeSet; use std::path::{Path, PathBuf}; -use compliance_core::models::SbomEntry; +use compliance_core::models::{Artifact, SbomEntry}; /// Collect the control-application SBOM from every `.projectarchive` reachable for /// a target: the ingested artifact file itself (an uploaded archive), plus any @@ -51,6 +51,21 @@ pub fn collect_sbom(artifact_file: &Path, working_path: &Path, repo_id: &str) -> out } +/// The stored file of an uploaded `artifact` that is a CODESYS project archive. +/// Ingest unpacks it like any archive, so the tree it leaves no longer holds +/// the `.projectarchive` [`collect_sbom`] reads; this is the file itself. +pub fn uploaded_archive(artifact: &Artifact) -> Option<&Path> { + let is_archive = Path::new(&artifact.source_ref) + .extension() + .and_then(|x| x.to_str()) + .is_some_and(|x| x.eq_ignore_ascii_case("projectarchive")); + artifact + .stored_path + .as_deref() + .filter(|_| is_archive) + .map(Path::new) +} + /// Whether `archive` opens as a zip, i.e. could be a CODESYS project archive. /// /// # Errors @@ -266,6 +281,40 @@ mod tests { let _ = std::fs::remove_dir_all(&tmp); } + #[test] + fn the_nightly_codesys_fixture_alone_in_a_tree_yields_its_components() { + let tmp = std::env::temp_dir().join(format!("cs-plc-fixture-{}", uuid::Uuid::new_v4())); + std::fs::create_dir_all(&tmp).expect("mkdir"); + let fixture = Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../fixtures/nightly/plc/line_control.projectarchive"); + std::fs::copy(&fixture, tmp.join("line_control.projectarchive")).expect("copy"); + + let entries = collect_sbom(Path::new(""), &tmp, "t"); + + assert!(entries.len() >= 6, "libraries and runtime: {entries:?}"); + assert!(entries.iter().all(|e| e.package_manager == "codesys")); + assert!(entries + .iter() + .any(|e| e.name.starts_with("CODESYS Control"))); + let _ = std::fs::remove_dir_all(&tmp); + } + + #[test] + fn only_an_uploaded_projectarchive_is_read_as_one() { + let mut upload = Artifact::source_archive("Line.ProjectArchive"); + upload.stored_path = Some("/data/uploads/t/x_Line.ProjectArchive".into()); + assert_eq!( + uploaded_archive(&upload), + Some(Path::new("/data/uploads/t/x_Line.ProjectArchive")) + ); + + let mut zip = Artifact::source_archive("src.zip"); + zip.stored_path = Some("/data/uploads/t/x_src.zip".into()); + assert_eq!(uploaded_archive(&zip), None); + let repo = Artifact::git_repo("https://git.example/plc.projectarchive", "main"); + assert_eq!(uploaded_archive(&repo), None); + } + #[test] fn non_zip_file_yields_no_sbom() { let tmp = std::env::temp_dir().join(format!("cs-plc-sbom-st-{}", uuid::Uuid::new_v4())); diff --git a/docs/guide/plc.md b/docs/guide/plc.md index f65e8eb..5a0b8ea 100644 --- a/docs/guide/plc.md +++ b/docs/guide/plc.md @@ -133,6 +133,14 @@ my-plc-project/ **not** carry the referenced libraries. ::: +A `.projectarchive` (or a CODESYS `.project`) in a repository or an uploaded +archive marks it as a PLC project when Prüfwerk detects the type. A repository +created through the managed git source therefore becomes **SPS / PLC** on its +first scan, and later scans run the control-logic analysis. Whatever the +target's type, the library + runtime SBOM and its CVEs come from every +`.projectarchive` the code holds, so a target kept as **Backend / API** still +lists its CODESYS components. + ## What the scanner finds The control-logic rules are CWE-mapped and include: hardcoded credentials