fix(plc): a repository holding only a CODESYS archive is a PLC project (#528)
This commit was merged in pull request #528.
This commit is contained in:
1 parent
ffe31964e6
commit
90c19b5a94
5 files changed
+174
-20
No files matched your search
@@ -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,19 @@ impl HeuristicClassifier {
|
||||
facts_lang("iec-61131-3"),
|
||||
));
|
||||
}
|
||||
// A CODESYS project (or its archive) committed to the repository:
|
||||
// PLC when nothing else is there. Below a backend manifest, so a
|
||||
// code repository that also keeps a PLC project stays a code
|
||||
// target (its CODESYS components are collected either way) and
|
||||
// keeps its code scans.
|
||||
if m.has_ext("projectarchive") || m.has_ext("project") {
|
||||
out.push(verdict(
|
||||
TargetType::PlcSps,
|
||||
0.5,
|
||||
"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 +911,34 @@ mod tests {
|
||||
assert!(v.iter().any(|x| x.target_type == TargetType::PlcSps));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_committed_codesys_archive_is_plc_unless_code_is_beside_it() {
|
||||
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::BackendService);
|
||||
}
|
||||
|
||||
#[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")];
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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<u32, AgentError> {
|
||||
@@ -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)
|
||||
|
||||
@@ -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()));
|
||||
|
||||
@@ -133,6 +133,17 @@ 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 and the
|
||||
repository holds no application code with a build manifest. A repository
|
||||
created through the managed git source with only a CODESYS project therefore
|
||||
becomes **SPS / PLC** on its first scan, and later scans run the control-logic
|
||||
analysis; one that also holds, say, a `package.json` or `pom.xml` stays a code
|
||||
target. 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
|
||||
|
||||
Reference in new issue
Block a user