Files
pruefwerk/compliance-core/src/models/scan.rs
T
sharang fce9edfbeb
CI / Check (push) Skipped
CI / Detect Changes (push) Successful in 3s
CI / Deploy Docs (push) Skipped
CI / Deploy MCP (push) Successful in 4m20s
CI / Deploy Dashboard (push) Successful in 6m6s
CI / Deploy Agent (push) Successful in 8m25s
feat(scans): show sub-steps of "Projekt erkennen" and clone once per scan (#421)
2026-09-28 21:40:00 +00:00

360 lines
13 KiB
Rust

use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use super::repository::ScanTrigger;
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum ScanType {
Sast,
Sbom,
Cve,
Gdpr,
OAuth,
Graph,
Dast,
SecretDetection,
Lint,
CodeReview,
/// Static analysis of a firmware image (unpack + component CVE).
FirmwareStatic,
/// Control-logic security analysis of PLC / SPS programs.
PlcControlLogic,
/// Static analysis of a mobile package (APK / AAB / IPA).
MobileStatic,
/// Static analysis of a container image.
ContainerScan,
/// Dynamic probing of a running PLC/SPS device over industrial protocols
/// (Modbus/TCP, OPC UA, …) for exposed/unauthenticated control access.
IcsProbe,
/// A penetration test done by a person; its findings are entered or
/// imported by hand.
Pentest,
}
impl std::fmt::Display for ScanType {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Sast => write!(f, "sast"),
Self::Sbom => write!(f, "sbom"),
Self::Cve => write!(f, "cve"),
Self::Gdpr => write!(f, "gdpr"),
Self::OAuth => write!(f, "oauth"),
Self::Graph => write!(f, "graph"),
Self::Dast => write!(f, "dast"),
Self::SecretDetection => write!(f, "secret_detection"),
Self::Lint => write!(f, "lint"),
Self::CodeReview => write!(f, "code_review"),
Self::FirmwareStatic => write!(f, "firmware_static"),
Self::PlcControlLogic => write!(f, "plc_control_logic"),
Self::MobileStatic => write!(f, "mobile_static"),
Self::ContainerScan => write!(f, "container_scan"),
Self::IcsProbe => write!(f, "ics_probe"),
Self::Pentest => write!(f, "pentest"),
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum ScanRunStatus {
Running,
Completed,
/// The scan itself hit an error on the target (clone, tool, pipeline).
Failed,
/// The agent stopped (redeploy, crash, out-of-memory kill) while this scan
/// was running. Set at the next startup for runs left `running`. Distinct
/// from `Failed` on purpose: nothing about the customer's code caused it.
Interrupted,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum ScanPhase {
ChangeDetection,
ArtifactIngest,
Classification,
Sast,
SbomGeneration,
CveScanning,
PatternScanning,
SecretDetection,
LintScanning,
CodeReview,
GraphBuilding,
FirmwareStatic,
PlcAnalysis,
MobileStatic,
ContainerScan,
LlmTriage,
/// Control refs stamped on findings from the CRA control-map table.
ControlTriage,
/// The LLM pass that maps findings to master controls.
SemanticControlMapping,
/// Control checks grounded in the code (text control to code finding).
GroundedControlChecks,
IssueCreation,
DastScanning,
/// An ephemeral soft-PLC started to probe the control logic.
PlcProvision,
IcsProbe,
Completed,
}
/// A step inside a phase that can take minutes on its own, so a long wait
/// shows what the scan is doing. Only the first phase has steps today: a
/// repository with many submodules can take ten minutes before any analysis.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum ScanStep {
/// Cloning the repository, or fetching what changed since the last scan.
CloneRepository,
/// Checking out the repository's submodules (an RTOS, a HAL, a stack).
FetchSubmodules,
/// Unpacking an uploaded archive.
UnpackArchive,
/// Working out what kind of project it is (firmware, backend, PLC, ...).
DetectProjectType,
/// Reading the firmware build to list its components.
AnalyseFirmware,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ScanRun {
#[serde(rename = "_id", skip_serializing_if = "Option::is_none")]
pub id: Option<bson::oid::ObjectId>,
pub repo_id: String,
pub trigger: ScanTrigger,
pub commit_sha: Option<String>,
pub status: ScanRunStatus,
pub current_phase: ScanPhase,
/// Where inside `current_phase` the run is; cleared when the phase changes.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub current_step: Option<ScanStep>,
pub phases_completed: Vec<ScanPhase>,
pub new_findings_count: u32,
/// Why a failed run failed, in plain English; never a raw error or a
/// server path (those go to the log).
pub error_message: Option<String>,
/// Why a failed run failed, as a stable code for the dashboard to word;
/// absent on runs recorded before it existed.
#[serde(default)]
pub error_code: Option<RunErrorCode>,
#[serde(with = "super::serde_helpers::bson_datetime")]
pub started_at: DateTime<Utc>,
#[serde(default, with = "super::serde_helpers::opt_bson_datetime")]
pub completed_at: Option<DateTime<Utc>>,
/// Stages the pipeline deliberately did not run (e.g. a deployment
/// feature flag turned them off). Distinct from `error_message`: a
/// skipped stage is not a failure.
#[serde(default)]
pub skipped_stages: Vec<SkippedStage>,
/// The source languages the static analysis found outside vendor code
/// (`"c"`, `"python"`, …). A control counts as checked only if one of its
/// rules covers one of them. Empty in runs from before it was recorded.
#[serde(default)]
pub languages: Vec<String>,
/// The phases this run will go through, in order, recorded when it starts,
/// so the dashboard can show what is done and what is still to come. Empty
/// in runs from before it was recorded.
#[serde(default)]
pub planned_phases: Vec<ScanPhase>,
}
/// Why a stage was skipped, stable for the dashboard to word in the reader's
/// language. The stage's `reason` next to it is English prose for API
/// readers; neither ever carries a server path or a raw error (those go to
/// the log).
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum SkipCode {
/// The deployment does not run this stage (e.g. DAST where only source
/// code is examined).
FeatureDisabled,
/// Git submodules could not be checked out; `subject` names them.
SubmodulesNotFetched,
/// Vendor and third-party directories left out of SAST; `subject` lists
/// them.
VendorCode,
/// An analysis tool did not complete; `subject` names it.
ToolFailed,
/// A package manifest without a lockfile; `subject` is the manifest.
DependenciesUnlocked,
/// An attached artifact no stage analyses yet (a firmware or container
/// image, a mobile package).
NotAnalysedYet,
/// A PLC project archive that could not be read; `subject` is its name.
ArchiveUnreadable,
/// An uploaded or linked artifact that could not be read; `subject` is
/// its name.
ArtifactNotIngested,
/// A password-protected archive without a password; `subject` is its name.
ArchivePasswordRequired,
/// An archive whose stored password is wrong; `subject` is its name.
ArchivePasswordWrong,
/// The firmware SBOM could not be built.
FirmwareSbomFailed,
/// No supported firmware build system was found in the sources.
FirmwareBuildUnknown,
/// A firmware build was detected, but no components resolve without
/// building it; `subject` is the build system.
FirmwareUnresolved,
/// Some components were not matched against known vulnerabilities;
/// `subject` names the lookup, and the components where known.
CveLookupIncomplete,
/// A scheduled or webhook scan found no new commits since the last scan,
/// so nothing was scanned again.
NoNewCommits,
}
/// Why a scan run failed, stable for the dashboard to word.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum RunErrorCode {
/// The repository could not be cloned or fetched (address, access, network).
RepositoryUnreachable,
/// A password-protected archive without a password.
ArchivePasswordRequired,
/// An archive whose stored password is wrong.
ArchivePasswordWrong,
/// The agent restarted while the run was going.
Interrupted,
/// Anything else; the details are in the agent's log.
Internal,
}
/// A pipeline stage that was planned but intentionally not executed.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct SkippedStage {
/// Stage id (`dast`, `pentest`, `ics_probe`, `plc_runtime`, …).
pub stage: String,
/// Always `skipped` — present so the entry reads like a stage result.
pub status: String,
/// Why it was skipped, in English (`feature disabled`, …).
pub reason: String,
/// Why, as a stable code; absent on runs recorded before codes existed.
#[serde(default)]
pub code: Option<SkipCode>,
/// What it concerns, safe to show: a file or tool name, directories.
#[serde(default)]
pub subject: Option<String>,
}
impl SkippedStage {
/// The reason recorded when a deployment feature flag disables a stage.
pub const FEATURE_DISABLED: &'static str = "feature disabled";
/// A skipped `stage`, why (`code`), and the English `reason`.
pub fn new(stage: impl Into<String>, code: SkipCode, reason: impl Into<String>) -> Self {
Self {
stage: stage.into(),
status: "skipped".to_string(),
reason: reason.into(),
code: Some(code),
subject: None,
}
}
/// The same, naming what it concerns.
pub fn about(mut self, subject: impl Into<String>) -> Self {
self.subject = Some(subject.into());
self
}
pub fn feature_disabled(stage: impl Into<String>) -> Self {
Self::new(stage, SkipCode::FeatureDisabled, Self::FEATURE_DISABLED)
}
}
impl ScanRun {
pub fn new(repo_id: String, trigger: ScanTrigger) -> Self {
Self {
id: None,
repo_id,
trigger,
commit_sha: None,
status: ScanRunStatus::Running,
current_phase: ScanPhase::ChangeDetection,
current_step: None,
phases_completed: Vec::new(),
new_findings_count: 0,
error_message: None,
error_code: None,
started_at: Utc::now(),
completed_at: None,
skipped_stages: Vec::new(),
languages: Vec::new(),
planned_phases: Vec::new(),
}
}
}
#[cfg(test)]
mod skipped_stage_tests {
use super::{ScanRun, ScanStep, ScanTrigger, SkippedStage};
#[test]
fn feature_disabled_reads_like_a_stage_result() {
let s = SkippedStage::feature_disabled("dast");
assert_eq!(s.stage, "dast");
assert_eq!(s.status, "skipped");
assert_eq!(s.reason, SkippedStage::FEATURE_DISABLED);
let j = serde_json::to_value(&s).expect("serialize");
assert_eq!(j["stage"], "dast");
assert_eq!(j["status"], "skipped");
assert_eq!(j["code"], "feature_disabled");
}
/// Runs recorded before codes existed still read.
#[test]
fn a_stage_without_a_code_still_reads() {
let s: SkippedStage = serde_json::from_value(serde_json::json!({
"stage": "sast", "status": "skipped", "reason": "semgrep did not complete",
}))
.expect("deserialize");
assert_eq!((s.code, s.subject), (None, None));
}
/// A new run carries no step; one recorded mid-phase reads back, and runs
/// from before steps existed still read.
#[test]
fn the_current_step_is_optional() {
let run = ScanRun::new("repo".into(), ScanTrigger::Manual);
let mut j = serde_json::to_value(&run).expect("serialize");
assert!(j.get("current_step").is_none());
let old: ScanRun = serde_json::from_value(j.clone()).expect("deserialize");
assert_eq!(old.current_step, None);
j["current_step"] = serde_json::json!("fetch_submodules");
let run: ScanRun = serde_json::from_value(j).expect("deserialize");
assert_eq!(run.current_step, Some(ScanStep::FetchSubmodules));
}
/// Every phase the pipeline records must deserialize, or the run drops
/// out of `GET /scan-runs` (found by the nightly harness, #188).
#[test]
fn runs_with_every_recorded_phase_deserialize() {
let run = ScanRun::new("repo".into(), ScanTrigger::Manual);
let mut j = serde_json::to_value(&run).expect("serialize");
j["phases_completed"] = serde_json::json!([
"control_triage",
"semantic_control_mapping",
"grounded_control_checks",
"plc_provision"
]);
j["current_phase"] = serde_json::json!("grounded_control_checks");
let back: ScanRun = serde_json::from_value(j).expect("known phases");
assert_eq!(back.phases_completed.len(), 4);
}
#[test]
fn scan_runs_without_the_field_deserialize_as_nothing_skipped() {
let run = ScanRun::new("repo".into(), ScanTrigger::Manual);
let mut j = serde_json::to_value(&run).expect("serialize");
j.as_object_mut().expect("object").remove("skipped_stages");
let back: ScanRun = serde_json::from_value(j).expect("older document");
assert!(back.skipped_stages.is_empty());
}
}