fix(scan): a failed run says why in plain words, never with a raw error (#414)
CI / Check (push) Skipped
CI / Detect Changes (push) Successful in 3s
CI / Deploy Docs (push) Skipped
CI / Deploy Agent (push) Successful in 4m5s
CI / Deploy Dashboard (push) Successful in 3m9s
CI / Deploy MCP (push) Successful in 2m0s

This commit was merged in pull request #414.
This commit is contained in:
sharang committed 2026-09-26 11:01:04 +00:00
1 parent e09c0d0a9d
commit a35b57ee50
7 files changed
+162 -3

No files matched your search

+56
View File
@@ -1,3 +1,4 @@
use compliance_core::models::RunErrorCode;
use compliance_core::CoreError;
use thiserror::Error;
@@ -45,6 +46,41 @@ pub enum AgentError {
Other(String),
}
impl AgentError {
/// What a scan run that stopped on this error records: a stable code and
/// a plain English sentence, never the error's own text, which can hold
/// server paths and internal details (it goes to the log instead).
pub fn run_failure(&self) -> (RunErrorCode, &'static str) {
match self {
Self::Git(_) => (
RunErrorCode::RepositoryUnreachable,
"the repository could not be cloned or fetched",
),
Self::ArchivePasswordRequired => (
RunErrorCode::ArchivePasswordRequired,
"the archive is password-protected and no password is set",
),
Self::ArchivePasswordWrong => (
RunErrorCode::ArchivePasswordWrong,
"the stored password does not open the archive",
),
Self::Core(_)
| Self::Database(_)
| Self::Http(_)
| Self::Json(_)
| Self::Io(_)
| Self::Scheduler(_)
| Self::Config(_)
| Self::Secret(_)
| Self::Exec(_)
| Self::Other(_) => (
RunErrorCode::Internal,
"the scan stopped because of an internal error",
),
}
}
}
impl From<AgentError> for axum::http::StatusCode {
fn from(err: AgentError) -> Self {
match err {
@@ -53,3 +89,23 @@ impl From<AgentError> for axum::http::StatusCode {
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_failed_run_records_no_raw_error() {
let io = AgentError::Io(std::io::Error::new(
std::io::ErrorKind::NotFound,
"/data/compliance-scanner/artifacts/work/65f0/a1: no such file",
));
let (code, message) = io.run_failure();
assert_eq!(code, RunErrorCode::Internal);
assert!(!message.contains('/'), "{message}");
assert_eq!(
AgentError::ArchivePasswordWrong.run_failure().0,
RunErrorCode::ArchivePasswordWrong
);
}
}
+3
View File
@@ -16,6 +16,7 @@ use chrono::{DateTime, Utc};
use mongodb::bson::{doc, DateTime as BsonDateTime};
use tokio::time::MissedTickBehavior;
use compliance_core::models::RunErrorCode;
use compliance_core::shutdown::Shutdown;
use crate::database::{Database, DatabasePool};
@@ -115,6 +116,8 @@ async fn close_open_runs(db: &Database, now: DateTime<Utc>) -> Result<u64, Agent
doc! { "$set": {
"status": rule.closed_as,
"error_message": INTERRUPTED_MESSAGE,
"error_code": mongodb::bson::to_bson(&RunErrorCode::Interrupted)
.unwrap_or_default(),
"completed_at": completed_at,
} },
)
@@ -613,13 +613,15 @@ impl PipelineOrchestrator {
}
Err(e) => {
tracing::error!(target_id, error = %e, "Unified scan pipeline failed");
let (code, message) = e.run_failure();
self.db
.scan_runs()
.update_one(
doc! { "_id": &insert.inserted_id },
doc! { "$set": {
"status": "failed",
"error_message": e.to_string(),
"error_message": message,
"error_code": mongodb::bson::to_bson(&code).unwrap_or_default(),
"completed_at": mongodb::bson::DateTime::now(),
} },
)
+1 -1
View File
@@ -53,7 +53,7 @@ pub use pentest::{
};
pub use repository::ScanTrigger;
pub use sbom::{SbomEntry, VulnRef};
pub use scan::{ScanPhase, ScanRun, ScanRunStatus, ScanType, SkipCode, SkippedStage};
pub use scan::{RunErrorCode, ScanPhase, ScanRun, ScanRunStatus, ScanType, SkipCode, SkippedStage};
pub use werkbank::{
CompleteRequest, CompleteResponse, DastCollect, Executor, HeartbeatAck, HeartbeatRequest,
InputRef, Job, JobCollect, JobRecord, JobResult, JobRuntime, JobStatus, JobType, LeaseRequest,
+23
View File
@@ -112,7 +112,13 @@ pub struct ScanRun {
pub current_phase: ScanPhase,
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")]
@@ -177,6 +183,22 @@ pub enum SkipCode {
CveLookupIncomplete,
}
/// 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 {
@@ -232,6 +254,7 @@ impl ScanRun {
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(),
@@ -148,7 +148,8 @@ fn scan_run_card(run: &ScanRun, lang: Lang) -> Element {
{scans::INTERRUPTED_HINT.get(lang)}
}
}
if let Some(error) = run.error_message.as_ref() {
// An interrupted run says so in its hint above.
if let Some(error) = scans::run_error(run, lang).filter(|_| run.status != ScanRunStatus::Interrupted) {
div { style: "color: var(--danger); font-size: 0.85em; margin-top: 4px;",
{scans::ERROR.get(lang)} ": {error}"
}
+74
View File
@@ -552,6 +552,59 @@ pub mod scans {
(SkipCode::CveLookupIncomplete, Lang::En) => format!("Not matched: {subject}"),
}
}
/// Why a failed run failed, in the reader's language, from the agent's
/// stable code. A run recorded before codes existed keeps its stored text.
pub fn run_error(
run: &compliance_core::models::ScanRun,
lang: super::super::Lang,
) -> Option<String> {
use super::super::Lang;
use compliance_core::models::RunErrorCode;
let Some(code) = run.error_code else {
return run.error_message.clone();
};
Some(
match (code, lang) {
(RunErrorCode::RepositoryUnreachable, Lang::De) => {
"Das Repository ließ sich nicht klonen. Bitte Adresse und Zugangstoken \
beim Prüfobjekt unter „Bearbeiten“ prüfen."
}
(RunErrorCode::RepositoryUnreachable, Lang::En) => {
"The repository could not be cloned. Check its address and access token \
under the target's Edit."
}
(RunErrorCode::ArchivePasswordRequired, Lang::De) => {
"Das Archiv ist passwortgeschützt. Bitte das Passwort beim Prüfobjekt unter \
„Bearbeiten“ eingeben."
}
(RunErrorCode::ArchivePasswordRequired, Lang::En) => {
"The archive is password-protected. Enter its password under the target's Edit."
}
(RunErrorCode::ArchivePasswordWrong, Lang::De) => {
"Das gespeicherte Passwort öffnet das Archiv nicht."
}
(RunErrorCode::ArchivePasswordWrong, Lang::En) => {
"The stored password does not open the archive."
}
(RunErrorCode::Interrupted, Lang::De) => {
"Durch einen Neustart des Dienstes unterbrochen. Bitte die Prüfung erneut starten."
}
(RunErrorCode::Interrupted, Lang::En) => {
"Interrupted by a service restart. Please start the scan again."
}
(RunErrorCode::Internal, Lang::De) => {
"Die Prüfung wurde wegen eines internen Fehlers abgebrochen. Wir sehen ihn im \
Protokoll; eine erneute Prüfung hilft oft."
}
(RunErrorCode::Internal, Lang::En) => {
"The scan stopped because of an internal error. It is in our log; running \
the scan again often helps."
}
}
.to_string(),
)
}
}
/// The targets page.
@@ -2509,3 +2562,24 @@ mod skipped_reason_tests {
assert_eq!(skipped_reason(&old, Lang::De), "semgrep did not complete");
}
}
#[cfg(test)]
mod run_error_tests {
use super::super::Lang;
use super::scans::run_error;
use compliance_core::models::{RunErrorCode, ScanRun, ScanTrigger};
#[test]
fn a_failed_run_reads_in_the_readers_language() {
let mut run = ScanRun::new("t".into(), ScanTrigger::Manual);
run.error_message = Some("the repository could not be cloned or fetched".into());
run.error_code = Some(RunErrorCode::RepositoryUnreachable);
assert!(run_error(&run, Lang::De).is_some_and(|t| t.starts_with("Das Repository")));
// A run from before codes keeps its stored text.
run.error_code = None;
assert_eq!(
run_error(&run, Lang::En).as_deref(),
Some("the repository could not be cloned or fetched")
);
}
}