Files
pruefwerk/compliance-agent/src/classify/mod.rs
T
sharang 750f1d7308
CI / Check (push) Skipped
CI / Detect Changes (push) Successful in 4s
CI / Deploy Docs (push) Successful in 1m15s
CI / Deploy MCP (push) Successful in 4m46s
CI / Deploy Dashboard (push) Successful in 6m40s
CI / Deploy Agent (push) Successful in 8m49s
feat(yocto): layer trees are detected as Embedded Linux / Yocto, and the scan matrix says what runs (#550)
2026-10-09 14:58:09 +00:00

378 lines
13 KiB
Rust

//! Target classification.
//!
//! Runs the classifier registry over a target's artifacts and their ingested
//! working paths, then merges and ranks the verdicts into a [`Classification`].
//! The registry is the heuristic classifier (artifact kinds + source markers)
//! plus the Firmwerk firmware detector (behind a [`FirmwareDetector`] port).
mod dotnet;
mod firmware;
mod language;
pub use firmware::{
FirmwareDetection, FirmwareDetector, FirmwareTarget, FirmwerkNative, MockFirmwareDetector,
};
pub use language::HeuristicClassifier;
use std::collections::HashMap;
use std::path::PathBuf;
use compliance_core::error::CoreError;
use compliance_core::models::{
ArtifactKind, Classification, DetectedFact, OnboardedTarget, TargetType, TargetTypeCandidate,
};
use compliance_core::traits::{ClassificationInput, ClassifierVerdict, TargetClassifier};
use firmware::detection_to_verdict;
/// Classify a target from its artifacts and their ingested working paths, using
/// the heuristic classifier plus the Firmwerk firmware detector. Verdicts are
/// merged (max confidence per target type) and ranked into a [`Classification`].
pub async fn classify_target<D: FirmwareDetector>(
target: &OnboardedTarget,
working_paths: &HashMap<String, PathBuf>,
firmware_detector: &D,
) -> Result<Classification, CoreError> {
let input = ClassificationInput {
artifacts: &target.artifacts,
working_paths,
description: target.description.as_deref(),
};
let mut verdicts = Vec::new();
let mut detected_by = Vec::new();
let heuristic = HeuristicClassifier.classify(&input).await?;
if !heuristic.is_empty() {
detected_by.push("heuristic".to_string());
}
verdicts.extend(heuristic);
// Firmwerk firmware detection over firmware / code working paths.
let mut firmwerk_used = false;
for artifact in &target.artifacts {
if !matches!(
artifact.kind,
ArtifactKind::FirmwareImage | ArtifactKind::GitRepo | ArtifactKind::SourceArchive
) {
continue;
}
let Some(path) = working_paths.get(&artifact.id) else {
continue;
};
if let Some(detection) = firmware_detector.detect(path).await? {
verdicts.push(detection_to_verdict(&detection));
firmwerk_used = true;
}
}
if firmwerk_used {
detected_by.push("firmwerk".to_string());
}
let mut classification = rank(verdicts, detected_by, target.target_type);
// The .NET stack and the app variants at any depth, as facts (#445).
for artifact in &target.artifacts {
if !matches!(
artifact.kind,
ArtifactKind::GitRepo | ArtifactKind::SourceArchive
) {
continue;
}
if let Some(path) = working_paths.get(&artifact.id) {
dotnet::add_facts(&mut classification.facts, path);
// The app's variants (phone and tablet app, flavors, app targets),
// one fact each with what it was recognised from.
for variant in crate::pipeline::variants::app_variants(path).all() {
classification.facts.push(DetectedFact::new(
"app_variant",
variant.name.clone(),
variant.source,
));
}
}
}
Ok(classification)
}
/// Merge verdicts by target type (keeping the max confidence and its rationale),
/// dedupe facts, rank by descending confidence, and assemble a [`Classification`].
/// Falls back to the declared type when no verdict is produced.
fn rank(
verdicts: Vec<ClassifierVerdict>,
detected_by: Vec<String>,
fallback: TargetType,
) -> Classification {
let mut best: HashMap<TargetType, (f32, String)> = HashMap::new();
let mut facts: Vec<DetectedFact> = Vec::new();
for verdict in verdicts {
for fact in verdict.facts {
if !facts
.iter()
.any(|e| e.key == fact.key && e.value == fact.value)
{
facts.push(fact);
}
}
let entry = best
.entry(verdict.target_type)
.or_insert((0.0, String::new()));
if verdict.confidence > entry.0 {
*entry = (verdict.confidence, verdict.rationale);
}
}
let mut candidates: Vec<TargetTypeCandidate> = best
.into_iter()
.map(
|(target_type, (confidence, rationale))| TargetTypeCandidate {
target_type,
confidence,
rationale,
},
)
.collect();
// Descending confidence; ties broken by type name for deterministic ordering.
candidates.sort_by(|a, b| {
b.confidence
.partial_cmp(&a.confidence)
.unwrap_or(std::cmp::Ordering::Equal)
.then_with(|| a.target_type.to_string().cmp(&b.target_type.to_string()))
});
let suggested = candidates
.first()
.map(|c| c.target_type)
.unwrap_or(fallback);
Classification {
suggested,
candidates,
facts,
detected_by,
detected_at: chrono::Utc::now(),
confirmed: false,
}
}
#[cfg(test)]
#[allow(clippy::expect_used, clippy::unwrap_used)]
mod tests {
use super::*;
use compliance_core::models::Artifact;
use std::fs;
use std::path::Path;
struct Scratch(PathBuf);
impl Scratch {
fn new() -> Self {
let p = std::env::temp_dir().join(format!("cs-classify-mod-{}", uuid::Uuid::new_v4()));
fs::create_dir_all(&p).expect("mkdir");
Self(p)
}
}
impl Drop for Scratch {
fn drop(&mut self) {
let _ = fs::remove_dir_all(&self.0);
}
}
fn no_firmware() -> MockFirmwareDetector {
MockFirmwareDetector { detection: None }
}
#[tokio::test]
async fn backend_repo_classifies_as_backend() {
let scratch = Scratch::new();
fs::write(scratch.0.join("go.mod"), "module x").unwrap();
let artifact = Artifact::git_repo("https://git/x", "main");
let mut wp = HashMap::new();
wp.insert(artifact.id.clone(), scratch.0.clone());
let mut target = OnboardedTarget::new("x".to_string(), TargetType::WebApp);
target.artifacts.push(artifact);
let c = classify_target(&target, &wp, &no_firmware())
.await
.expect("classify");
assert_eq!(c.suggested, TargetType::BackendService);
assert!(c.detected_by.contains(&"heuristic".to_string()));
assert!(!c.confirmed);
}
#[tokio::test]
async fn firmware_detector_verdict_ranks_top() {
let scratch = Scratch::new();
fs::write(scratch.0.join("fw.bin"), b"x").unwrap();
let artifact =
Artifact::firmware_image(scratch.0.join("fw.bin").to_string_lossy().to_string());
let mut wp = HashMap::new();
wp.insert(artifact.id.clone(), scratch.0.clone());
let mut target = OnboardedTarget::new("fw".to_string(), TargetType::FirmwareBareMetal);
target.artifacts.push(artifact);
let detector = MockFirmwareDetector {
detection: Some(FirmwareDetection {
provider: "zephyr".to_string(),
confidence: "high".to_string(),
build_system: "zephyr".to_string(),
framework: Some("zephyr".to_string()),
target: FirmwareTarget {
mcu: Some("nrf52840".to_string()),
..Default::default()
},
gaps: vec![],
}),
};
let c = classify_target(&target, &wp, &detector)
.await
.expect("classify");
// Firmwerk's high-confidence RTOS verdict beats the weak firmware prior.
assert_eq!(c.suggested, TargetType::FirmwareRtos);
assert!(c.detected_by.contains(&"firmwerk".to_string()));
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));
}
/// What Firmwerk reports for loose C sources, or for a Makefile.
fn firmwerk_found(provider: &str, confidence: &str) -> MockFirmwareDetector {
MockFirmwareDetector {
detection: Some(FirmwareDetection {
provider: provider.to_string(),
confidence: confidence.to_string(),
build_system: provider.to_string(),
framework: Some("bare-metal".to_string()),
target: FirmwareTarget::default(),
gaps: vec![],
}),
}
}
/// Classify the tree `files` (relative path, content) as one source
/// archive, with `detector` standing in for Firmwerk.
async fn classify_files(
files: &[(&str, &str)],
detector: &MockFirmwareDetector,
) -> Classification {
let scratch = Scratch::new();
for (rel, content) in files {
let path = scratch.0.join(rel);
fs::create_dir_all(path.parent().expect("parent")).expect("mkdir");
fs::write(path, content).expect("write");
}
let artifact = Artifact::source_archive("upload.zip");
let mut wp = HashMap::new();
wp.insert(artifact.id.clone(), scratch.0.clone());
let mut target = OnboardedTarget::new("t".to_string(), TargetType::BackendService);
target.artifacts.push(artifact);
classify_target(&target, &wp, detector)
.await
.expect("classify")
}
#[tokio::test]
async fn the_nightly_yocto_fixture_is_typed_yocto() {
let fixture =
Path::new(env!("CARGO_MANIFEST_DIR")).join("../fixtures/nightly/firmware/yocto-layer");
let artifact = Artifact::source_archive("yocto-layer.zip");
let mut wp = HashMap::new();
wp.insert(artifact.id.clone(), fixture);
let mut target = OnboardedTarget::new("y".to_string(), TargetType::BackendService);
target.artifacts.push(artifact);
let c = classify_target(&target, &wp, &no_firmware())
.await
.expect("classify");
assert_eq!(c.suggested, TargetType::EmbeddedLinuxYocto);
assert!(c
.facts
.iter()
.any(|f| f.key == "build_system" && f.value == "bitbake"));
assert!(c
.facts
.iter()
.any(|f| f.key == "yocto_layer" && f.value == "."));
}
#[tokio::test]
async fn a_plain_c_firmware_repo_stays_bare_metal() {
let c = classify_files(
&[
("Makefile", "CC=arm-none-eabi-gcc\nCFLAGS=-mcpu=cortex-m4"),
("Core/Src/main.c", "int main(void){}"),
// A config file in `conf/` is not a layer.
("conf/board.conf", "BOARD=nucleo"),
],
&firmwerk_found("make", "medium"),
)
.await;
assert_eq!(c.suggested, TargetType::FirmwareBareMetal);
assert!(!c
.candidates
.iter()
.any(|x| x.target_type == TargetType::EmbeddedLinuxYocto));
}
#[tokio::test]
async fn a_layer_shipping_c_sources_is_yocto_not_bare_metal() {
// Firmwerk's source archaeology fires on the recipe's C sources.
let c = classify_files(
&[
("conf/layer.conf", "BBFILE_COLLECTIONS += \"pump\""),
(
"recipes-app/pump/pump_1.0.bb",
"SRC_URI = \"file://pump.c\"",
),
("recipes-app/pump/files/pump.c", "int main(void){}"),
("recipes-app/pump/files/pump.h", "#pragma once"),
],
&firmwerk_found("source-archaeology", "low"),
)
.await;
assert_eq!(c.suggested, TargetType::EmbeddedLinuxYocto);
// The firmware reading stays a lower candidate.
assert!(c
.candidates
.iter()
.any(|x| x.target_type == TargetType::FirmwareBareMetal));
}
#[tokio::test]
async fn no_signal_falls_back_to_declared_type() {
let scratch = Scratch::new();
let _ = Path::new(&scratch.0);
let target = OnboardedTarget::new("empty".to_string(), TargetType::DesktopApp);
let wp = HashMap::new();
let c = classify_target(&target, &wp, &no_firmware())
.await
.expect("classify");
assert_eq!(c.suggested, TargetType::DesktopApp);
assert!(c.candidates.is_empty());
}
}