feat(scans): show sub-steps of "Projekt erkennen" and clone once per scan (#421)
This commit was merged in pull request #421.
This commit is contained in:
1 parent
d4bfb4dc2a
commit
fce9edfbeb
11 files changed
+193
-16
No files matched your search
@@ -213,7 +213,7 @@ pub async fn build_embeddings(
|
||||
creds,
|
||||
agent_clone.net_guard,
|
||||
);
|
||||
let repo_path = match git_ops.clone_or_fetch(&view.git_url, &view.name) {
|
||||
let repo_path = match git_ops.clone_or_fetch(&view.git_url, &view.checkout) {
|
||||
Ok(p) => p,
|
||||
Err(e) => {
|
||||
tracing::error!("Failed to clone repo for embedding build: {e}");
|
||||
|
||||
@@ -325,7 +325,7 @@ pub async fn get_file_content(
|
||||
let db = tenant_db(&agent, &tenant).await?;
|
||||
let db = &db;
|
||||
|
||||
// Look up the repository to get repo name
|
||||
// Look up the repository to find its checkout
|
||||
let repo = db
|
||||
.onboarded_targets()
|
||||
.find_one(doc! { "_id": mongodb::bson::oid::ObjectId::parse_str(&repo_id).ok() })
|
||||
@@ -333,11 +333,16 @@ pub async fn get_file_content(
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?
|
||||
.ok_or(StatusCode::NOT_FOUND)?;
|
||||
|
||||
// The checkout is per tenant — read only from the caller's own.
|
||||
// The checkout is per tenant — read only from the caller's own. It is
|
||||
// named after the code artifact, as ingest clones it.
|
||||
let checkout = repo
|
||||
.code_artifact()
|
||||
.map(|code| code.id.as_str())
|
||||
.ok_or(StatusCode::NOT_FOUND)?;
|
||||
let repo_dir = crate::pipeline::git::clone_dir(
|
||||
std::path::Path::new(&agent.config.git_clone_base_path),
|
||||
&tenant.0.tenant_id,
|
||||
&repo.name,
|
||||
checkout,
|
||||
);
|
||||
let file_path = repo_dir.join(¶ms.path);
|
||||
|
||||
@@ -421,7 +426,7 @@ pub async fn trigger_build(
|
||||
creds,
|
||||
agent_clone.net_guard,
|
||||
);
|
||||
let repo_path = match git_ops.clone_or_fetch(&view.git_url, &view.name) {
|
||||
let repo_path = match git_ops.clone_or_fetch(&view.git_url, &view.checkout) {
|
||||
Ok(p) => p,
|
||||
Err(e) => {
|
||||
tracing::error!("Failed to clone repo for graph build: {e}");
|
||||
|
||||
@@ -13,7 +13,7 @@ use std::collections::HashMap;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use compliance_core::models::{
|
||||
Artifact, ArtifactKind, DetectedFact, OnboardedTarget, SkipCode, SkippedStage,
|
||||
Artifact, ArtifactKind, DetectedFact, OnboardedTarget, ScanStep, SkipCode, SkippedStage,
|
||||
};
|
||||
use compliance_core::{AgentConfig, NetGuard};
|
||||
|
||||
@@ -37,6 +37,9 @@ pub struct IngestContext<'a> {
|
||||
pub net_guard: NetGuard,
|
||||
/// Opens the artifacts' sealed credentials (#260).
|
||||
pub secrets: SecretBox,
|
||||
/// Where to report each long step as it starts, so a running scan shows
|
||||
/// it; `None` when nobody is watching.
|
||||
pub progress: Option<tokio::sync::mpsc::UnboundedSender<ScanStep>>,
|
||||
}
|
||||
|
||||
impl<'a> IngestContext<'a> {
|
||||
@@ -49,6 +52,22 @@ impl<'a> IngestContext<'a> {
|
||||
target_id,
|
||||
net_guard: NetGuard::from_env(config.app_env),
|
||||
secrets: SecretBox::from_config(config),
|
||||
progress: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Report each long step to `progress` as it starts.
|
||||
#[must_use]
|
||||
pub fn with_progress(mut self, progress: tokio::sync::mpsc::UnboundedSender<ScanStep>) -> Self {
|
||||
self.progress = Some(progress);
|
||||
self
|
||||
}
|
||||
|
||||
/// Tell the watcher, if any, that `step` has started. A watcher that
|
||||
/// has gone away is not an error: the ingest itself carries on.
|
||||
fn report(&self, step: ScanStep) {
|
||||
if let Some(progress) = &self.progress {
|
||||
let _ = progress.send(step);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -71,6 +90,7 @@ pub struct IngestedArtifact {
|
||||
}
|
||||
|
||||
/// All ingested artifacts for a target, keyed by artifact id.
|
||||
#[derive(Default)]
|
||||
pub struct IngestSet {
|
||||
/// The ingested artifacts, keyed by [`Artifact::id`].
|
||||
pub by_artifact: HashMap<String, IngestedArtifact>,
|
||||
@@ -209,9 +229,11 @@ fn ingest_git(
|
||||
.map_err(|e| AgentError::Other(e.to_string()))?;
|
||||
let creds = credentials_for(artifact, &ctx.secrets);
|
||||
let git_ops = GitOps::new(ctx.git_clone_base, ctx.tenant_id, creds, ctx.net_guard);
|
||||
ctx.report(ScanStep::CloneRepository);
|
||||
let repo_path = git_ops.clone_or_fetch(&artifact.source_ref, &artifact.id)?;
|
||||
// Classification needs the submodules too: a build system or RTOS may
|
||||
// live in one.
|
||||
ctx.report(ScanStep::FetchSubmodules);
|
||||
let facts = git_ops
|
||||
.update_submodules(&repo_path, &artifact.source_ref)
|
||||
.into_iter()
|
||||
@@ -258,6 +280,7 @@ fn ingest_blob(
|
||||
let password = archive_password(artifact, &ctx.secrets);
|
||||
match archive::ArchiveFormat::sniff(&stored)? {
|
||||
Some(format) => {
|
||||
ctx.report(ScanStep::UnpackArchive);
|
||||
match archive::extract(
|
||||
format,
|
||||
&stored,
|
||||
@@ -468,6 +491,7 @@ mod tests {
|
||||
target_id,
|
||||
net_guard: NetGuard::public_only(),
|
||||
secrets: SecretBox::without_key(),
|
||||
progress: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -646,6 +670,21 @@ mod tests {
|
||||
const ZIPCRYPTO: &[u8] = include_bytes!("../../tests/fixtures/archives/zipcrypto.zip");
|
||||
const SEVEN_ZIP: &[u8] = include_bytes!("../../tests/fixtures/archives/sample.7z");
|
||||
|
||||
#[test]
|
||||
fn unpacking_an_archive_is_reported_as_a_step() {
|
||||
let scratch = Scratch::new();
|
||||
let store = scratch.0.join("store");
|
||||
let (progress, mut steps) = tokio::sync::mpsc::unbounded_channel();
|
||||
let ctx = ctx_for(&store, "t-step").with_progress(progress);
|
||||
let artifact = uploaded_archive(&scratch.0.join("uploads"), "fw.zip", ZIPCRYPTO);
|
||||
|
||||
// The password is missing, but the unpacking was started.
|
||||
let _ = ingest_artifact(&artifact, &ctx);
|
||||
|
||||
assert_eq!(steps.try_recv().ok(), Some(ScanStep::UnpackArchive));
|
||||
assert!(steps.try_recv().is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_password_protected_archive_opens_with_its_stored_password() {
|
||||
let scratch = Scratch::new();
|
||||
|
||||
@@ -86,7 +86,7 @@ impl PipelineOrchestrator {
|
||||
creds,
|
||||
self.net_guard,
|
||||
);
|
||||
let repo_path = git_ops.clone_or_fetch(&repo.git_url, &repo.name)?;
|
||||
let repo_path = git_ops.clone_or_fetch(&repo.git_url, &repo.checkout)?;
|
||||
|
||||
// A scheduled or webhook scan of an unchanged repository has nothing
|
||||
// new to find; one a person started always runs (after an update of
|
||||
@@ -1282,9 +1282,7 @@ impl PipelineOrchestrator {
|
||||
) -> std::collections::HashMap<String, std::path::PathBuf> {
|
||||
self.update_phase(scan_run_id, ScanPhase::Classification)
|
||||
.await;
|
||||
let ctx =
|
||||
crate::ingest::IngestContext::from_config(&self.config, &self.tenant_id, target_id);
|
||||
let ingest_set = crate::ingest::ingest_all(target, &ctx);
|
||||
let ingest_set = self.ingest_with_steps(target, target_id, scan_run_id).await;
|
||||
// Each artifact that could not be read is recorded with its reason; a
|
||||
// missing or wrong archive password under its own stage, so the
|
||||
// dashboard can ask for it. The others are still classified and scanned.
|
||||
@@ -1294,6 +1292,8 @@ impl PipelineOrchestrator {
|
||||
}
|
||||
let working_paths = ingest_set.working_paths();
|
||||
let mut detected_firmware = false;
|
||||
self.update_step(scan_run_id, ScanStep::DetectProjectType)
|
||||
.await;
|
||||
match crate::classify::classify_target(
|
||||
target,
|
||||
&working_paths,
|
||||
@@ -1338,6 +1338,8 @@ impl PipelineOrchestrator {
|
||||
{
|
||||
if let Some(code) = target.code_artifact() {
|
||||
if let Some(path) = working_paths.get(&code.id) {
|
||||
self.update_step(scan_run_id, ScanStep::AnalyseFirmware)
|
||||
.await;
|
||||
let entries = match crate::pipeline::firmware_sbom::firmware_sbom_entries(
|
||||
path,
|
||||
target_id,
|
||||
@@ -1502,7 +1504,7 @@ impl PipelineOrchestrator {
|
||||
let repo_path = crate::pipeline::git::clone_dir(
|
||||
std::path::Path::new(&self.config.git_clone_base_path),
|
||||
&self.tenant_id,
|
||||
&repo.name,
|
||||
&repo.checkout,
|
||||
);
|
||||
if let Ok(sha) = GitOps::get_head_sha(&repo_path) {
|
||||
self.db
|
||||
@@ -1612,12 +1614,62 @@ impl PipelineOrchestrator {
|
||||
doc! { "_id": oid },
|
||||
doc! {
|
||||
"$set": { "current_phase": phase.clone() },
|
||||
"$unset": { "current_step": "" },
|
||||
"$push": { "phases_completed": phase },
|
||||
},
|
||||
)
|
||||
.await;
|
||||
}
|
||||
}
|
||||
|
||||
/// Record the step inside the current phase the run has reached.
|
||||
async fn update_step(&self, scan_run_id: &str, step: ScanStep) {
|
||||
let (Ok(step), Ok(oid)) = (
|
||||
mongodb::bson::to_bson(&step),
|
||||
mongodb::bson::oid::ObjectId::parse_str(scan_run_id),
|
||||
) else {
|
||||
return;
|
||||
};
|
||||
let _ = self
|
||||
.db
|
||||
.scan_runs()
|
||||
.update_one(
|
||||
doc! { "_id": oid },
|
||||
doc! { "$set": { "current_step": step } },
|
||||
)
|
||||
.await;
|
||||
}
|
||||
|
||||
/// Ingest `target`'s artifacts off the async runtime (a clone with its
|
||||
/// submodules can take minutes), recording each long step on the run as
|
||||
/// it starts.
|
||||
async fn ingest_with_steps(
|
||||
&self,
|
||||
target: &OnboardedTarget,
|
||||
target_id: &str,
|
||||
scan_run_id: &str,
|
||||
) -> crate::ingest::IngestSet {
|
||||
let (progress, mut steps) = tokio::sync::mpsc::unbounded_channel();
|
||||
// `spawn_blocking` needs owned data: the closure may outlive this
|
||||
// borrow as far as the compiler can tell.
|
||||
let config = self.config.clone();
|
||||
let tenant_id = self.tenant_id.clone();
|
||||
let target_id = target_id.to_string();
|
||||
let target = target.clone();
|
||||
let ingest = tokio::task::spawn_blocking(move || {
|
||||
let ctx = crate::ingest::IngestContext::from_config(&config, &tenant_id, &target_id)
|
||||
.with_progress(progress);
|
||||
crate::ingest::ingest_all(&target, &ctx)
|
||||
});
|
||||
// Ends when the ingest finishes and drops its sender.
|
||||
while let Some(step) = steps.recv().await {
|
||||
self.update_step(scan_run_id, step).await;
|
||||
}
|
||||
ingest.await.unwrap_or_else(|e| {
|
||||
tracing::error!(error = %e, "Unified pipeline: ingest task failed");
|
||||
crate::ingest::IngestSet::default()
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// The phases [`PipelineOrchestrator::run_target_pipeline`] goes through for
|
||||
@@ -1782,5 +1834,7 @@ mod tests {
|
||||
assert_eq!(repo.tracker_type, Some(TrackerType::Gitea));
|
||||
assert_eq!(repo.tracker_owner.as_deref(), Some("acme"));
|
||||
assert_eq!(repo.findings_count, 3);
|
||||
// The scan reads the clone ingest made, not a second one.
|
||||
assert_eq!(repo.checkout, code.id);
|
||||
}
|
||||
}
|
||||
@@ -43,7 +43,7 @@ impl PipelineOrchestrator {
|
||||
creds,
|
||||
self.net_guard,
|
||||
);
|
||||
let repo_path = git_ops.clone_or_fetch(&repo.git_url, &repo.name)?;
|
||||
let repo_path = git_ops.clone_or_fetch(&repo.git_url, &repo.checkout)?;
|
||||
|
||||
// Get diff between base and head
|
||||
let diff_files = GitOps::get_diff_content(&repo_path, base_sha, head_sha)?;
|
||||
|
||||
@@ -19,6 +19,10 @@ pub struct RepoView {
|
||||
/// The onboarded target's id (used as `repo_id` across findings/sbom/etc.).
|
||||
pub id: Option<mongodb::bson::oid::ObjectId>,
|
||||
pub name: String,
|
||||
/// The directory name of the target's clone: the code artifact's id,
|
||||
/// where ingest clones it. Every reader uses this one checkout, so a
|
||||
/// repository with gigabytes of submodules is fetched once per scan.
|
||||
pub checkout: String,
|
||||
pub git_url: String,
|
||||
pub default_branch: String,
|
||||
pub local_path: Option<String>,
|
||||
@@ -44,6 +48,7 @@ impl RepoView {
|
||||
let mut view = Self {
|
||||
id: target.id,
|
||||
name: target.name.clone(),
|
||||
checkout: code.id.clone(),
|
||||
git_url: code.source_ref.clone(),
|
||||
default_branch: "main".to_string(),
|
||||
local_path: None,
|
||||
|
||||
@@ -38,7 +38,8 @@ pub fn target_paths(
|
||||
paths.push(artifacts.join("uploads").join(&target_id));
|
||||
paths.push(artifacts.join("work").join(&target_id));
|
||||
}
|
||||
// The scan clones under the target's name, ingest under the artifact id.
|
||||
// Clones live under the artifact id; scans before that also cloned
|
||||
// under the target's name.
|
||||
paths.push(clone_dir(clones, tenant_id, &target.name));
|
||||
for artifact in &target.artifacts {
|
||||
match artifact.kind {
|
||||
|
||||
@@ -53,7 +53,9 @@ pub use pentest::{
|
||||
};
|
||||
pub use repository::ScanTrigger;
|
||||
pub use sbom::{SbomEntry, VulnRef};
|
||||
pub use scan::{RunErrorCode, ScanPhase, ScanRun, ScanRunStatus, ScanType, SkipCode, SkippedStage};
|
||||
pub use scan::{
|
||||
RunErrorCode, ScanPhase, ScanRun, ScanRunStatus, ScanStep, ScanType, SkipCode, SkippedStage,
|
||||
};
|
||||
pub use werkbank::{
|
||||
CompleteRequest, CompleteResponse, DastCollect, Executor, HeartbeatAck, HeartbeatRequest,
|
||||
InputRef, Job, JobCollect, JobRecord, JobResult, JobRuntime, JobStatus, JobType, LeaseRequest,
|
||||
|
||||
@@ -101,6 +101,24 @@ pub enum ScanPhase {
|
||||
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")]
|
||||
@@ -110,6 +128,9 @@ pub struct ScanRun {
|
||||
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
|
||||
@@ -254,6 +275,7 @@ impl ScanRun {
|
||||
commit_sha: None,
|
||||
status: ScanRunStatus::Running,
|
||||
current_phase: ScanPhase::ChangeDetection,
|
||||
current_step: None,
|
||||
phases_completed: Vec::new(),
|
||||
new_findings_count: 0,
|
||||
error_message: None,
|
||||
@@ -269,7 +291,7 @@ impl ScanRun {
|
||||
|
||||
#[cfg(test)]
|
||||
mod skipped_stage_tests {
|
||||
use super::{ScanRun, ScanTrigger, SkippedStage};
|
||||
use super::{ScanRun, ScanStep, ScanTrigger, SkippedStage};
|
||||
|
||||
#[test]
|
||||
fn feature_disabled_reads_like_a_stage_result() {
|
||||
@@ -293,6 +315,22 @@ mod skipped_stage_tests {
|
||||
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]
|
||||
|
||||
@@ -5095,3 +5095,7 @@ input[type="file"] {
|
||||
font-size: 12.5px;
|
||||
color: var(--text-tertiary);
|
||||
}
|
||||
|
||||
.scan-sub-step {
|
||||
font-weight: 400;
|
||||
}
|
||||
@@ -8,7 +8,7 @@ use std::collections::HashSet;
|
||||
|
||||
use dioxus::prelude::*;
|
||||
|
||||
use compliance_core::models::{ScanPhase, ScanRun, ScanRunStatus};
|
||||
use compliance_core::models::{ScanPhase, ScanRun, ScanRunStatus, ScanStep};
|
||||
|
||||
use crate::app::Route;
|
||||
use crate::i18n::texts::{common, scans};
|
||||
@@ -125,6 +125,9 @@ fn scan_run_card(run: &ScanRun, lang: Lang) -> Element {
|
||||
if running {
|
||||
span { style: "font-size: 0.9em;",
|
||||
{scans::PHASE.get(lang)} ": " strong { {phase(&run.current_phase).get(lang)} }
|
||||
if let Some(current) = run.current_step {
|
||||
" · {step(current).get(lang)}"
|
||||
}
|
||||
}
|
||||
Elapsed { started_at: run.started_at }
|
||||
span { style: "font-size: 0.9em;",
|
||||
@@ -207,6 +210,7 @@ fn steps(run: &ScanRun) -> Vec<(ScanPhase, StepState)> {
|
||||
/// A running scan's stepper: a progress bar and its phases.
|
||||
fn stepper(run: &ScanRun, lang: Lang) -> Element {
|
||||
let steps = steps(run);
|
||||
let sub_step = run.current_step.map(|s| step(s).get(lang));
|
||||
let done = steps.iter().filter(|(_, s)| *s == StepState::Done).count();
|
||||
let total = steps.len().max(1);
|
||||
let percent = done * 100 / total;
|
||||
@@ -228,6 +232,11 @@ fn stepper(run: &ScanRun, lang: Lang) -> Element {
|
||||
span { class: "spinner scan-step-spinner" }
|
||||
}
|
||||
{phase(&p).get(lang)}
|
||||
if state == StepState::Current {
|
||||
if let Some(sub_step) = sub_step {
|
||||
span { class: "scan-sub-step", " · {sub_step}" }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -359,6 +368,19 @@ fn stage_name(id: &str, lang: Lang) -> String {
|
||||
scans::stage(id).map_or_else(|| id.to_string(), |t| t.get(lang).to_string())
|
||||
}
|
||||
|
||||
/// Where inside its phase a running scan is, in words. Exhaustive, as
|
||||
/// [`phase`] is.
|
||||
pub fn step(step: ScanStep) -> Text {
|
||||
let (de, en) = match step {
|
||||
ScanStep::CloneRepository => ("Repository klonen", "Cloning the repository"),
|
||||
ScanStep::FetchSubmodules => ("Submodule holen", "Fetching submodules"),
|
||||
ScanStep::UnpackArchive => ("Archiv entpacken", "Unpacking the archive"),
|
||||
ScanStep::DetectProjectType => ("Projekttyp bestimmen", "Detecting the project type"),
|
||||
ScanStep::AnalyseFirmware => ("Firmware analysieren", "Analysing the firmware"),
|
||||
};
|
||||
Text { de, en }
|
||||
}
|
||||
|
||||
/// The step a running scan is at, in words. Exhaustive on purpose: a new
|
||||
/// phase does not compile until it has a name in both languages.
|
||||
pub fn phase(phase: &ScanPhase) -> Text {
|
||||
@@ -426,6 +448,13 @@ mod tests {
|
||||
assert_eq!(steps(&run).len(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn steps_have_words_in_both_languages() {
|
||||
let text = step(ScanStep::FetchSubmodules);
|
||||
assert_eq!(text.get(Lang::De), "Submodule holen");
|
||||
assert_eq!(text.get(Lang::En), "Fetching submodules");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unknown_stages_are_shown_by_id() {
|
||||
assert_eq!(
|
||||
|
||||
Reference in new issue
Block a user