From 7cfea4dad232a7b7025f5a04a11cc3faa8453a4e Mon Sep 17 00:00:00 2001 From: Sharang Parnerkar <30073382+mighty840@users.noreply.github.com> Date: Wed, 4 Nov 2026 09:52:44 +0100 Subject: [PATCH] feat(plc): say when a native CODESYS project is not analysed (#165) A CODESYS project in its native format (the binary .project, also inside an uploaded .projectarchive) yields no POUs, and the scan said nothing: a target with only a native project read as clean control logic. - plc::native_projects lists a .project that is not a PLCopen XML export and a readable .projectarchive (a corrupt one keeps its own ArchiveUnreadable note). - The PLC scan records them as a skipped stage (plc_native_project, SkipCode::NativePlcProject, DE/EN) with the way out: export the POUs as PLCopen XML and add the export. - A .project is parsed only when it looks like XML. - The two CODESYS archive baselines of the nightly gain the stage; docs in guide/plc and guide/scanning. Co-Authored-By: Claude Opus 5.5 --- compliance-agent/src/pipeline/orchestrator.rs | 21 ++++ compliance-agent/src/pipeline/plc/mod.rs | 118 ++++++++++++++++++ compliance-core/src/models/scan.rs | 5 + compliance-dashboard/src/i18n/texts.rs | 10 ++ docs/guide/plc.md | 3 + docs/guide/scanning.md | 1 + .../baselines/plc-codesys-proemion.json | 4 +- .../baselines/plc-codesys-synthetic.json | 4 +- 8 files changed, 164 insertions(+), 2 deletions(-) diff --git a/compliance-agent/src/pipeline/orchestrator.rs b/compliance-agent/src/pipeline/orchestrator.rs index 74c34ea..2f22ea1 100644 --- a/compliance-agent/src/pipeline/orchestrator.rs +++ b/compliance-agent/src/pipeline/orchestrator.rs @@ -1437,10 +1437,14 @@ impl PipelineOrchestrator { let mut analysed = Vec::with_capacity(sources.len()); let mut all_sbom: Vec = Vec::new(); let mut sbom_seen = std::collections::BTreeSet::new(); + // CODESYS projects in their native format: their control logic is not + // read, and the run says so (#165). + let mut native = std::collections::BTreeSet::new(); for a in &sources { let Some(path) = ingest_set.get(&a.id).and_then(|ia| ia.working_path.clone()) else { continue; }; + native.extend(crate::pipeline::plc::native_projects(&path)); analysed.push(( path.clone(), crate::pipeline::plc::analyze_tree(&path, target_id), @@ -1481,6 +1485,23 @@ impl PipelineOrchestrator { } } } + if !native.is_empty() { + let list = native.into_iter().collect::>().join(", "); + self.skip_stage( + scan_run_id, + SkippedStage::new( + "plc_native_project", + SkipCode::NativePlcProject, + format!( + "CODESYS projects in their native format are not analysed for control \ + logic: {list}; export the POUs as PLCopen XML (Project > Export \ + PLCopenXML) and add the export to the target" + ), + ) + .about(list), + ) + .await; + } let all_findings = self.map_plc_findings(scan_run_id, analysed).await; tracing::info!( target_id, diff --git a/compliance-agent/src/pipeline/plc/mod.rs b/compliance-agent/src/pipeline/plc/mod.rs index e58e766..0707484 100644 --- a/compliance-agent/src/pipeline/plc/mod.rs +++ b/compliance-agent/src/pipeline/plc/mod.rs @@ -3,6 +3,10 @@ //! Parses Structured Text (raw `.st`/`.scl`/`.exp` files and PLCopen-XML //! projects) into an AST and runs semantic control-logic security rules over it. //! Implements [`ScanType::PlcControlLogic`]. +//! +//! A CODESYS project in its native format (the binary `.project`, also inside +//! a `.projectarchive`) cannot be read; [`native_projects`] lists them so the +//! scan says so instead of finding nothing in silence (#165). pub mod ast; pub mod lexer; @@ -65,6 +69,11 @@ pub(crate) fn analyze_tree(root: &Path, repo_id: &str) -> Vec { let Ok(content) = std::fs::read_to_string(path) else { continue; }; + // A `.project` is read only as a PLCopen export; CODESYS's native one + // is binary ([`native_projects`] reports it). + if ext == "project" && !looks_like_xml(&content) { + continue; + } let pous = if is_xml { plcopen::parse_plcopen(&content) } else { @@ -104,6 +113,67 @@ pub(crate) fn analyze_tree(root: &Path, repo_id: &str) -> Vec { findings } +/// Whether `content` starts as an XML document (after a byte-order mark and +/// white space). +fn looks_like_xml(content: &str) -> bool { + content + .trim_start_matches('\u{feff}') + .trim_start() + .starts_with('<') +} + +/// The CODESYS projects under `root` in their native format, which the +/// control-logic analysis cannot read: a `.project` that is not a PLCopen XML +/// export, and a readable `.projectarchive` (a zip around one). Paths are +/// relative to `root`, `/`-separated, sorted; `.git` is skipped. A +/// `.projectarchive` that does not open is left out: the SBOM stage reports +/// it as unreadable. +/// +/// # Arguments +/// +/// * `root` - the tree, or a single uploaded file +/// +/// # Returns +/// +/// The native project files, e.g. `["LineControl.project"]`. +pub fn native_projects(root: &Path) -> Vec { + let mut found = Vec::new(); + let walker = walkdir::WalkDir::new(root) + .into_iter() + .filter_entry(|e| e.file_name() != ".git"); + for entry in walker.filter_map(Result::ok) { + if !entry.file_type().is_file() { + continue; + } + let path = entry.path(); + let ext = path + .extension() + .and_then(|e| e.to_str()) + .unwrap_or("") + .to_ascii_lowercase(); + let native = match ext.as_str() { + "project" => !std::fs::read(path) + .ok() + .and_then(|bytes| String::from_utf8(bytes).ok()) + .is_some_and(|text| looks_like_xml(&text)), + "projectarchive" => sbom::check_archive(path).is_ok(), + _ => false, + }; + if native { + let rel = path.strip_prefix(root).unwrap_or(path); + let rel = if rel.as_os_str().is_empty() { + // `root` is the file itself. + path.file_name().map(Path::new).unwrap_or(path) + } else { + rel + }; + found.push(rel.to_string_lossy().replace('\\', "/")); + } + } + found.sort(); + found +} + #[cfg(test)] mod tests { use super::*; @@ -231,4 +301,52 @@ mod tests { ); } } + + /// A scratch directory, removed on drop. + struct Scratch(PathBuf); + impl Drop for Scratch { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } + } + + #[test] + fn native_codesys_projects_are_listed_and_exports_are_not() { + let root = + Scratch(std::env::temp_dir().join(format!("cs-plc-native-{}", uuid::Uuid::new_v4()))); + let write = |rel: &str, bytes: &[u8]| { + let path = root.0.join(rel); + std::fs::create_dir_all(path.parent().expect("parent")).expect("mkdir"); + std::fs::write(path, bytes).expect("write"); + }; + // A binary native project, and one that is text but not XML. + write("App/Line.project", b"\x00\x01CODESYS\xff"); + write("Other.project", b"fixture"); + // A PLCopen export saved as `.project` is read, not reported. + write( + "Export.project", + b"\xef\xbb\xbf ", + ); + // A readable archive is native; a corrupt one is left to the SBOM stage. + let fixtures = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../fixtures/nightly/plc"); + std::fs::copy( + fixtures.join("line_control.projectarchive"), + root.0.join("Line.projectarchive"), + ) + .expect("copy archive"); + write("Broken.projectarchive", b"not a zip"); + write(".git/x.project", b"\x00"); + + assert_eq!( + native_projects(&root.0), + ["App/Line.project", "Line.projectarchive", "Other.project"] + ); + // An uploaded file on its own is named by its file name. + assert_eq!( + native_projects(&root.0.join("Other.project")), + ["Other.project"] + ); + // The binary project yields no POUs and no error. + assert!(analyze_tree(&root.0, "t").is_empty()); + } } diff --git a/compliance-core/src/models/scan.rs b/compliance-core/src/models/scan.rs index e2cab25..ca587aa 100644 --- a/compliance-core/src/models/scan.rs +++ b/compliance-core/src/models/scan.rs @@ -217,6 +217,10 @@ pub enum SkipCode { NotAnalysedYet, /// A PLC project archive that could not be read; `subject` is its name. ArchiveUnreadable, + /// CODESYS projects in their native (binary) format, whose control logic + /// is not analysed until they are exported as PLCopen XML; `subject` + /// lists them. + NativePlcProject, /// An uploaded or linked artifact that could not be read; `subject` is /// its name. ArtifactNotIngested, @@ -283,6 +287,7 @@ impl SkipCode { | Self::DependenciesUnlocked | Self::NotAnalysedYet | Self::ArchiveUnreadable + | Self::NativePlcProject | Self::ArtifactNotIngested | Self::ArchivePasswordRequired | Self::ArchivePasswordWrong diff --git a/compliance-dashboard/src/i18n/texts.rs b/compliance-dashboard/src/i18n/texts.rs index 2f3f2dd..39ee5ef 100644 --- a/compliance-dashboard/src/i18n/texts.rs +++ b/compliance-dashboard/src/i18n/texts.rs @@ -475,6 +475,10 @@ pub mod scans { de: "Git-LFS-Dateien", en: "Git LFS files", }, + "plc_native_project" => Text { + de: "SPS-Projekt (natives Format)", + en: "PLC project (native format)", + }, "sast_vendor_code" => Text { de: "Herstellercode (HAL, CMSIS, Drittanbieter)", en: "Vendor code (HAL, CMSIS, third party)", @@ -608,6 +612,12 @@ pub mod scans { (SkipCode::ExcludedPaths, Lang::En) => format!( "Excluded in the target's settings, left out of the whole scan (code analysis, SBOM, CVEs): {subject}" ), + (SkipCode::NativePlcProject, Lang::De) => format!( + "CODESYS-Projekt im nativen Format, Steuerungslogik nicht geprüft: {subject}. Die POUs als PLCopen XML exportieren (Projekt → PLCopenXML exportieren) und den Export zum Prüfobjekt hinzufügen." + ), + (SkipCode::NativePlcProject, Lang::En) => format!( + "CODESYS project in its native format, control logic not analysed: {subject}. Export the POUs as PLCopen XML (Project → Export PLCopenXML) and add the export to the target." + ), (SkipCode::ToolFailed, Lang::De) => format!( "{subject} wurde nicht fertig; was es prüft, gilt als nicht bewertet." ), diff --git a/docs/guide/plc.md b/docs/guide/plc.md index 7704eae..7ee4434 100644 --- a/docs/guide/plc.md +++ b/docs/guide/plc.md @@ -124,6 +124,9 @@ my-plc-project/ - Alternatively commit raw `.st` / `.exp` / `.scl` files — also analyzed. - **Do not** commit only the binary `.project` — it cannot be parsed (and does not diff). If you want the library SBOM, commit the **`.projectarchive`** as well. + A native `.project` or `.projectarchive` without an export is listed on the + scan run under **SPS-Projekt (natives Format)**, so a missing export never + reads as clean control logic. - CODESYS's built-in Git integration, which stores an exported representation, works too — as long as the committed form is PLCopen XML / textual. diff --git a/docs/guide/scanning.md b/docs/guide/scanning.md index f078a89..a0bb427 100644 --- a/docs/guide/scanning.md +++ b/docs/guide/scanning.md @@ -168,6 +168,7 @@ as a clean result: the CRA requirements it checks show as **Nicht geprüft**. | **Abhängigkeiten (SBOM)** | *(manifest)* ohne Lockfile: Die Versionen der Abhängigkeiten und ihre CVEs sind nicht bekannt. | Commit the lockfile (see below). | | e.g. **Firmware-Binäranalyse**, **Container-Analyse**, **Mobile-App-Analyse** | e.g. Firmware-Images werden noch nicht entpackt … | Nothing analyses these files yet; scan the source code instead. | | **SPS-Bibliotheken (SBOM)** | *(file)* ist kein lesbares CODESYS-Projektarchiv. | Export the archive again with *File → Project Archive*, with the referenced libraries ticked. | +| **SPS-Projekt (natives Format)** | CODESYS-Projekt im nativen Format, Steuerungslogik nicht geprüft: *(files)* … | Export the POUs as PLCopen XML (*Project → Export PLCopenXML*) and add the export to the target; see [PLC / SPS](/guide/plc). | | **Einlesen der Dateien** | *(file)* konnte nicht gelesen werden. | Check the file and upload it again under **Bearbeiten**. | | **Archiv-Passwort fehlt (beim Prüfobjekt unter „Bearbeiten“ eingeben)** | *(file)* ist passwortgeschützt. | Enter the password under **Bearbeiten**. | | **Archiv-Passwort falsch (beim Prüfobjekt unter „Bearbeiten“ ändern)** | Das gespeicherte Passwort öffnet *(file)* nicht. | Change the password under **Bearbeiten**. | diff --git a/fixtures/nightly/baselines/plc-codesys-proemion.json b/fixtures/nightly/baselines/plc-codesys-proemion.json index a7495cb..6da054c 100644 --- a/fixtures/nightly/baselines/plc-codesys-proemion.json +++ b/fixtures/nightly/baselines/plc-codesys-proemion.json @@ -1,6 +1,8 @@ { "scan_status": "completed", - "skipped_stages": [], + "skipped_stages": [ + "plc_native_project" + ], "sbom": [ "codesys:3SLicense@3.5.20.0", "codesys:Base Interfaces@3.5.17.0", diff --git a/fixtures/nightly/baselines/plc-codesys-synthetic.json b/fixtures/nightly/baselines/plc-codesys-synthetic.json index 5fc718a..6a4b3ad 100644 --- a/fixtures/nightly/baselines/plc-codesys-synthetic.json +++ b/fixtures/nightly/baselines/plc-codesys-synthetic.json @@ -1,6 +1,8 @@ { "scan_status": "completed", - "skipped_stages": [], + "skipped_stages": [ + "plc_native_project" + ], "sbom": [ "codesys:3SLicense@3.5.16.0", "codesys:CODESYS Control for Linux SL@3.5.16.0",