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, /// Malware signatures (ClamAV) and the committed binaries of a tree /// (#465). Malware, /// The recipe inventory of a Yocto layer tree: the components its BitBake /// recipes build (SBOM) and their known vulnerabilities. RecipeInventory, /// Security lint of a Yocto layer tree's BitBake recipes and image /// configuration. RecipeLint, } 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"), Self::Malware => write!(f, "malware"), Self::RecipeInventory => write!(f, "recipe_inventory"), Self::RecipeLint => write!(f, "recipe_lint"), } } } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] #[serde(rename_all = "snake_case")] pub enum ScanRunStatus { /// Requested and waiting for one of the agent's scan slots (t84). Moves /// to `running` when it gets one. Queued, 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, } impl ScanRunStatus { /// Whether the run has not ended yet: it waits for a slot or runs. pub fn is_open(&self) -> bool { match self { Self::Queued | Self::Running => true, Self::Completed | Self::Failed | Self::Interrupted => false, } } } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] #[serde(rename_all = "snake_case")] pub enum ScanPhase { ChangeDetection, ArtifactIngest, Classification, Sast, SbomGeneration, CveScanning, PatternScanning, SecretDetection, /// ClamAV over the tree, and the committed binaries listed (#465). MalwareScanning, 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, pub repo_id: String, pub trigger: ScanTrigger, pub commit_sha: Option, 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, pub phases_completed: Vec, 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, /// 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, /// When the run started; for a queued run, when it was requested, until /// it starts. #[serde(with = "super::serde_helpers::bson_datetime")] pub started_at: DateTime, /// When a run that waited for a slot was requested (t84); `None` for a /// run that started at once, and in runs from before it was recorded. #[serde( default, skip_serializing_if = "Option::is_none", with = "super::serde_helpers::opt_bson_datetime" )] pub queued_at: Option>, #[serde(default, with = "super::serde_helpers::opt_bson_datetime")] pub completed_at: Option>, /// 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. Runs recorded before `notes` existed /// also hold informational entries here; [`ScanRun::skips`] leaves them /// out. #[serde(default)] pub skipped_stages: Vec, /// Informational entries about stages that ran: code left out of the /// analysis by design, findings suppressed in the sources. Never a gap in /// what was checked. #[serde(default)] pub notes: Vec, /// 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, /// 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, /// How well the target's SBOM meets the BSI TR-03183-2 and NTIA profiles /// at the end of this run (sbomqs, #496); `None` when it was not scored. #[serde(default, skip_serializing_if = "Option::is_none")] pub sbom_quality: Option, /// Why the run ran, for metering (t72): set when it starts for a scan a /// person started, and by change detection otherwise. `None` for a run /// skipped because nothing changed, and in runs from before metering. #[serde(default, skip_serializing_if = "Option::is_none")] pub attribution: Option, /// Whether the run counts toward the customer's usage once it completes /// ([`super::metering::ScanAttribution::chargeable`] for the target's /// billing when it was attributed). #[serde(default)] pub chargeable: bool, /// For a person's request that took over a scheduled, webhook or /// new-content scan still waiting for a slot (t84): that scan's trigger. /// The run has the person's priority and attribution, but it counts only /// as that scan would have: it would have run anyway, just later. #[serde(default, skip_serializing_if = "Option::is_none")] pub charged_as: Option, /// What the run was charged to once it counted; `None` while it runs, /// and for a run that did not count. #[serde(default, skip_serializing_if = "Option::is_none")] pub charge: Option, /// The components the run added, updated or removed in the stored SBOM /// (#974); `None` when it was not recorded (runs from before, and runs /// that did not replace the SBOM). #[serde(default, skip_serializing_if = "Option::is_none")] pub component_changes: Option>, } /// Why a stage was skipped, or what a run note is about /// ([`SkipCode::is_informational`]), 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, /// Packages a build's image SPDX lists in the image without their /// documents, so their recipes are not known; `subject` lists them. BuildPackagesUnresolved, /// Test-data directories (`fixtures/`, `testdata/`) left out of the whole /// scan: code findings, SBOM and CVE match; `subject` lists them. TestData, /// Paths the target's settings exclude (`scan_config.exclude_paths`), /// left out of the whole scan; `subject` lists those that were removed. ExcludedPaths, /// 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, /// 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, /// 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, /// Files kept in Git LFS were not downloaded (binary assets, not /// analysed); `subject` lists the LFS patterns of `.gitattributes`. LfsNotFetched, /// A scheduled or webhook scan found no new commits since the last scan, /// so nothing was scanned again. NoNewCommits, /// A Unity project builds for a mobile platform whose native project /// (Xcode, Gradle) Unity generates at build time, so its settings and /// native code are not in the repository; `subject` names the project and /// platform. PlatformProjectGenerated, /// A scheduled or webhook scan of uploaded files that are the same as at /// the last completed scan, run by the same Prüfwerk version, so nothing /// was scanned again. UploadUnchanged, /// Files too large for the malware scan; `subject` lists them. TooLargeToScan, /// Findings a rule reported that comments in the scanned files suppress /// (`# nooelint` in a Yocto recipe), so they are not shown; `subject` is /// how many. SuppressedInSource, /// Names an image recipe declares it installs that are not recipes or /// package groups in the scanned tree (they come from layers that are not /// in it, such as Poky's); `subject` lists them. NotInTree, /// The Yocto release a layer tree builds could not be read from its /// layer pins or `LAYERSERIES_COMPAT`, so its support period was not /// checked. ReleaseUnknown, /// The month's quota is used up and today's Prüftag on the target has /// had its Prüfungen, so this counted Prüfung did not run (t72). PrueftagLimitReached, /// The month's quota is used up and the Prüftag limit the customer set /// is reached, so this counted Prüfung did not run (t72). PrueftagCapReached, } impl SkipCode { /// Whether an entry with this code only informs about a stage that ran /// (a run note) rather than recording something that did not run, failed /// or is not analysed yet (a skipped stage). pub fn is_informational(self) -> bool { // An exhaustive match, so a new code has to be classified here. match self { Self::VendorCode | Self::TestData | Self::BuildPackagesUnresolved | Self::ExcludedPaths | Self::SuppressedInSource | Self::NotInTree => true, Self::FeatureDisabled | Self::SubmodulesNotFetched | Self::ToolFailed | Self::DependenciesUnlocked | Self::NotAnalysedYet | Self::ArchiveUnreadable | Self::NativePlcProject | Self::ArtifactNotIngested | Self::ArchivePasswordRequired | Self::ArchivePasswordWrong | Self::FirmwareSbomFailed | Self::FirmwareBuildUnknown | Self::FirmwareUnresolved | Self::CveLookupIncomplete | Self::LfsNotFetched | Self::NoNewCommits | Self::PlatformProjectGenerated | Self::UploadUnchanged | Self::TooLargeToScan | Self::ReleaseUnknown | Self::PrueftagLimitReached | Self::PrueftagCapReached => false, } } } /// 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, /// `skipped`, or `note` for an informational entry (a [`RunNote`]) — /// 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, /// What it concerns, safe to show: a file or tool name, directories. #[serde(default)] pub subject: Option, } /// An informational entry of a scan run: the same shape as a skipped stage, /// with status `note` and an informational [`SkipCode`]. pub type RunNote = SkippedStage; impl SkippedStage { /// The reason recorded when a deployment feature flag disables a stage. pub const FEATURE_DISABLED: &'static str = "feature disabled"; /// The status of a stage that did not run. pub const SKIPPED: &'static str = "skipped"; /// The status of an informational entry (a [`RunNote`]). pub const NOTE: &'static str = "note"; /// A skipped `stage`, why (`code`), and the English `reason`; a note /// when `code` is informational. pub fn new(stage: impl Into, code: SkipCode, reason: impl Into) -> Self { let status = if code.is_informational() { Self::NOTE } else { Self::SKIPPED }; Self { stage: stage.into(), status: status.to_string(), reason: reason.into(), code: Some(code), subject: None, } } /// The same, naming what it concerns. pub fn about(mut self, subject: impl Into) -> Self { self.subject = Some(subject.into()); self } pub fn feature_disabled(stage: impl Into) -> Self { Self::new(stage, SkipCode::FeatureDisabled, Self::FEATURE_DISABLED) } /// Whether this entry is a note: its code is informational. Entries /// without a code predate the informational codes, so they are skips. pub fn is_note(&self) -> bool { self.code.is_some_and(SkipCode::is_informational) } } 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(), queued_at: None, completed_at: None, skipped_stages: Vec::new(), notes: Vec::new(), languages: Vec::new(), planned_phases: Vec::new(), sbom_quality: None, attribution: None, chargeable: false, charged_as: None, charge: None, component_changes: None, } } /// A run requested by `trigger` that waits for a scan slot (t84). pub fn queued(repo_id: String, trigger: ScanTrigger) -> Self { let run = Self::new(repo_id, trigger); Self { status: ScanRunStatus::Queued, queued_at: Some(run.started_at), ..run } } } impl ScanRun { /// The stages that did not run, without the informational entries older /// runs recorded among them. pub fn skips(&self) -> impl Iterator { self.skipped_stages.iter().filter(|s| !s.is_note()) } /// The run's notes, including the informational entries older runs /// recorded among the skipped stages. pub fn all_notes(&self) -> impl Iterator { self.notes .iter() .chain(self.skipped_stages.iter().filter(|s| s.is_note())) } /// Move the informational entries older runs recorded among the skipped /// stages into `notes`, as status `note`, so a run read back exports /// both lists the way new runs record them. pub fn split_notes(&mut self) { let (notes, skips) = std::mem::take(&mut self.skipped_stages) .into_iter() .partition::, _>(SkippedStage::is_note); self.skipped_stages = skips; self.notes.extend(notes.into_iter().map(|mut note| { note.status = SkippedStage::NOTE.to_string(); note })); } } #[cfg(test)] mod skipped_stage_tests { use super::{ScanRun, ScanStep, ScanTrigger, SkipCode, SkippedStage}; #[test] fn only_code_exclusions_and_suppressions_are_informational() { let notes = [ SkipCode::VendorCode, SkipCode::SuppressedInSource, SkipCode::NotInTree, ]; let skips = [ SkipCode::FeatureDisabled, SkipCode::SubmodulesNotFetched, SkipCode::ToolFailed, SkipCode::DependenciesUnlocked, SkipCode::NotAnalysedYet, SkipCode::ArchiveUnreadable, SkipCode::ArtifactNotIngested, SkipCode::ArchivePasswordRequired, SkipCode::ArchivePasswordWrong, SkipCode::FirmwareSbomFailed, SkipCode::FirmwareBuildUnknown, SkipCode::FirmwareUnresolved, SkipCode::CveLookupIncomplete, SkipCode::LfsNotFetched, SkipCode::NoNewCommits, SkipCode::PlatformProjectGenerated, SkipCode::UploadUnchanged, SkipCode::TooLargeToScan, SkipCode::PrueftagLimitReached, SkipCode::PrueftagCapReached, ]; assert!(notes.iter().all(|c| c.is_informational())); assert!(skips.iter().all(|c| !c.is_informational())); } #[test] fn an_informational_entry_is_recorded_as_a_note() { let note = SkippedStage::new("sast_vendor_code", SkipCode::VendorCode, "vendor"); assert_eq!(note.status, SkippedStage::NOTE); assert!(note.is_note()); let skip = SkippedStage::new("sast", SkipCode::ToolFailed, "semgrep did not complete"); assert_eq!(skip.status, SkippedStage::SKIPPED); assert!(!skip.is_note()); } /// A run recorded before notes existed, with an informational entry among /// its skipped stages, lists it as a note and keeps the real skips. #[test] fn an_old_run_lists_its_informational_skips_as_notes() { let mut run = ScanRun::new("repo".into(), ScanTrigger::Manual); let mut old = SkippedStage::new("recipe_lint_suppressed", SkipCode::SuppressedInSource, "2"); old.status = SkippedStage::SKIPPED.to_string(); run.skipped_stages = vec![ SkippedStage::feature_disabled("dast"), old, SkippedStage::new("sast", SkipCode::ToolFailed, "semgrep did not complete"), ]; let stages = |it: Vec<&SkippedStage>| -> Vec { it.into_iter().map(|s| s.stage.clone()).collect() }; assert_eq!(stages(run.skips().collect()), ["dast", "sast"]); assert_eq!( stages(run.all_notes().collect()), ["recipe_lint_suppressed"] ); run.split_notes(); assert_eq!( stages(run.skipped_stages.iter().collect()), ["dast", "sast"] ); assert_eq!( stages(run.notes.iter().collect()), ["recipe_lint_suppressed"] ); assert_eq!(run.notes[0].status, SkippedStage::NOTE); let j = serde_json::to_value(&run).expect("serialize"); assert_eq!(j["notes"][0]["code"], "suppressed_in_source"); } #[test] fn scan_runs_without_notes_deserialize_with_none() { 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("notes"); let back: ScanRun = serde_json::from_value(j).expect("older document"); assert!(back.notes.is_empty()); } #[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()); } }