feat(dashboard): scan status and history on the targets page (#284)
CI / Check (push) Skipped
CI / Detect Changes (pull_request) Skipped
CI / Deploy Agent (pull_request) Skipped
CI / Deploy Dashboard (pull_request) Skipped
CI / Deploy Docs (pull_request) Skipped
CI / Deploy MCP (pull_request) Skipped
CI / Check (pull_request) Successful in 7m45s

A customer could start a scan but never see whether it ran, where it was,
why it failed or which stages it left out: fetch_scan_runs was unused.

- Agent: GET /api/v1/scan-runs takes ?target_id=; GET /api/v1/targets
  adds each target's newest run as `last_scan` (one aggregation).
- Targets list: a "last scan" column (status, and the step a running
  scan is at); the findings count links to the findings list filtered to
  that target (/findings?target=<id>); starting a scan refreshes the list.
- Target details: the scan history, newest first, with start and finish
  times, new findings, the error of a failed run, and each stage that was
  not run with its reason. It refreshes every 5 s while a scan runs.
- The targets page is in German and English; target types and artifact
  kinds are shared label tables. Phase names are an exhaustive match, so
  a new phase does not compile without both translations.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EYKjxacrr6K88DruUmP48p
This commit is contained in:
Sharang ParnerkarandClaude Opus 5.5 committed 2026-09-23 15:46:17 +02:00
1 parent 5efc267075
commit 466ff01283
11 files changed
+892 -112

No files matched your search

@@ -12,7 +12,7 @@ use mongodb::bson::{doc, oid::ObjectId, to_bson};
use serde::{Deserialize, Serialize};
use compliance_core::models::{
Artifact, ArtifactKind, ComplianceProfile, Credentials, OnboardedTarget, PlcFormat,
Artifact, ArtifactKind, ComplianceProfile, Credentials, OnboardedTarget, PlcFormat, ScanRun,
TargetScanConfig, TargetType,
};
use compliance_core::scan_matrix::{applicable_scans, supports_pentest};
@@ -119,13 +119,14 @@ fn parse_oid(id: &str) -> Result<ObjectId, StatusCode> {
ObjectId::parse_str(id).map_err(|_| StatusCode::BAD_REQUEST)
}
/// GET /api/v1/targets — list onboarded targets (paginated).
/// GET /api/v1/targets — list onboarded targets (paginated), each with its
/// newest scan run.
#[tracing::instrument(skip_all)]
pub async fn list_targets(
Extension(agent): AgentExt,
tenant: TenantCtx,
Query(params): Query<PaginationParams>,
) -> Result<Json<ApiResponse<Vec<OnboardedTarget>>>, StatusCode> {
) -> Result<Json<ApiResponse<Vec<TargetListItem>>>, StatusCode> {
let db = tenant_db(&agent, &tenant).await?;
let skip = params.skip();
let total = db
@@ -146,13 +147,71 @@ pub async fn list_targets(
Vec::new()
}
};
let ids = targets
.iter()
.filter_map(|t| t.id.map(|id| id.to_hex()))
.collect();
let mut last_scans = latest_scan_runs(&db.scan_runs(), ids).await;
let data = targets
.redacted()
.into_iter()
.map(|target| {
let last_scan = target.id.and_then(|id| last_scans.remove(&id.to_hex()));
TargetListItem { target, last_scan }
})
.collect();
Ok(Json(ApiResponse {
data: targets.redacted(),
data,
total: Some(total),
page: Some(params.page),
}))
}
/// A target in the list, with its most recent scan run, so the list can show
/// whether the last scan is running, finished or failed.
#[derive(Serialize)]
pub struct TargetListItem {
/// The target, credentials redacted.
#[serde(flatten)]
pub target: OnboardedTarget,
/// The newest scan run; `None` before the first scan.
pub last_scan: Option<ScanRun>,
}
/// The newest scan run of each target in `target_ids`, in one query.
async fn latest_scan_runs(
runs: &mongodb::Collection<ScanRun>,
target_ids: Vec<String>,
) -> HashMap<String, ScanRun> {
use futures_util::StreamExt;
if target_ids.is_empty() {
return HashMap::new();
}
// Runs store their target's id as `repo_id`.
let pipeline = vec![
doc! { "$match": { "repo_id": { "$in": target_ids } } },
doc! { "$sort": { "started_at": -1 } },
doc! { "$group": { "_id": "$repo_id", "run": { "$first": "$$ROOT" } } },
];
match runs.aggregate(pipeline).await {
Ok(cursor) => {
cursor
.filter_map(|row| async move {
let run = row.ok()?.get_document("run").ok()?.clone();
let run: ScanRun = mongodb::bson::from_document(run).ok()?;
Some((run.repo_id.clone(), run))
})
.collect()
.await
}
Err(e) => {
tracing::warn!("Failed to fetch the targets' last scan runs: {e}");
HashMap::new()
}
}
}
/// POST /api/v1/targets — create an onboarded target.
#[tracing::instrument(skip_all)]
pub async fn create_target(
+51 -3
View File
@@ -1,25 +1,51 @@
use axum::extract::{Extension, Query};
use axum::Json;
use mongodb::bson::doc;
use mongodb::bson::{doc, Document};
use serde::Deserialize;
use super::dto::*;
use compliance_core::models::ScanRun;
use compliance_core::tenant_ctx::TenantCtx;
/// Which scan runs to list.
#[derive(Debug, Default, Deserialize)]
pub struct ScanRunFilter {
/// Only the runs of this target (its id), for the target's scan history.
#[serde(default)]
pub target_id: Option<String>,
}
impl ScanRunFilter {
/// The MongoDB filter: runs store their target's id as `repo_id`.
fn to_document(&self) -> Document {
match self.target_id.as_deref().filter(|id| !id.is_empty()) {
Some(id) => doc! { "repo_id": id },
None => doc! {},
}
}
}
/// GET /api/v1/scan-runs?target_id=&page=&limit= — newest first.
#[tracing::instrument(skip_all)]
pub async fn list_scan_runs(
Extension(agent): AgentExt,
tenant: TenantCtx,
Query(params): Query<PaginationParams>,
Query(filter): Query<ScanRunFilter>,
) -> ApiResult<Vec<ScanRun>> {
let db = tenant_db(&agent, &tenant).await?;
let db = &db;
let skip = params.skip();
let total = db.scan_runs().count_documents(doc! {}).await.unwrap_or(0);
let query = filter.to_document();
let total = db
.scan_runs()
.count_documents(query.clone())
.await
.unwrap_or(0);
let scans = match db
.scan_runs()
.find(doc! {})
.find(query)
.sort(doc! { "started_at": -1 })
.skip(skip)
.limit(params.limit)
@@ -38,3 +64,25 @@ pub async fn list_scan_runs(
page: Some(params.page),
}))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_target_filter_selects_its_runs_only() {
let filter = ScanRunFilter {
target_id: Some("65f0c0ffee".to_string()),
};
assert_eq!(filter.to_document(), doc! { "repo_id": "65f0c0ffee" });
}
#[test]
fn no_or_empty_target_lists_every_run() {
assert_eq!(ScanRunFilter::default().to_document(), doc! {});
let empty = ScanRunFilter {
target_id: Some(String::new()),
};
assert_eq!(empty.to_document(), doc! {});
}
}
+3 -2
View File
@@ -14,8 +14,9 @@ pub enum Route {
TargetsPage {},
#[route("/onboard")]
OnboardingPage {},
#[route("/findings")]
FindingsPage {},
// `?target=<id>` opens the list filtered to one target.
#[route("/findings?:target")]
FindingsPage { target: String },
#[route("/findings/:id")]
FindingDetailPage { id: String },
#[route("/sbom")]
@@ -93,7 +93,7 @@ pub fn DemoTargetsButton(
DemoSeedResults { results: res }
div { class: "modal-actions",
Link { to: Route::TargetsPage {}, class: "btn btn-secondary", "Targets list" }
Link { to: Route::FindingsPage {}, class: "btn btn-secondary", "Findings" }
Link { to: Route::FindingsPage { target: String::new() }, class: "btn btn-secondary", "Findings" }
button { class: "btn btn-primary", onclick: close, "Done" }
}
} else {
@@ -11,6 +11,7 @@ pub mod notification_bell;
pub mod page_header;
pub mod pagination;
pub mod pentest_wizard;
pub mod scan_runs;
pub mod severity_badge;
pub mod sidebar;
pub mod stat_card;
@@ -0,0 +1,201 @@
//! A target's scan history: status, the step a running scan is at, when it
//! started and finished, why it failed, and which stages it did not run.
use dioxus::prelude::*;
use compliance_core::models::{ScanPhase, ScanRun, ScanRunStatus};
use crate::i18n::texts::{common, scans};
use crate::i18n::{use_lang, Lang, Text};
use crate::infrastructure::scans::fetch_target_scan_runs;
/// How often the history refreshes while a scan is running, in milliseconds.
#[cfg(feature = "web")]
const POLL_MS: u32 = 5_000;
/// The scan runs of one target, newest first. Refreshes itself while a run is
/// in progress, so the customer sees it move without reloading.
#[component]
pub fn ScanRunList(target_id: String) -> Element {
let lang = use_lang()();
let id = use_signal(|| target_id.clone());
// Only the browser build restarts it (the polling below).
#[cfg_attr(not(feature = "web"), allow(unused_mut))]
let mut runs = use_resource(move || async move { fetch_target_scan_runs(id()).await.ok() });
use_future(move || async move {
// Only the browser polls; a server render must not leave a loop behind.
#[cfg(feature = "web")]
loop {
gloo_timers::future::TimeoutFuture::new(POLL_MS).await;
let running = runs
.peek()
.as_ref()
.and_then(|r| r.as_ref())
.is_some_and(|list| list.iter().any(|r| r.status == ScanRunStatus::Running));
if running {
runs.restart();
}
}
});
let snapshot = runs.read().clone();
match snapshot {
Some(Some(list)) if list.is_empty() => rsx! {
div { style: "opacity: 0.6;", {scans::NO_RUNS.get(lang)} }
},
Some(Some(list)) => rsx! {
for run in list.iter() {
{scan_run_card(run, lang)}
}
},
Some(None) => rsx! {
div { style: "opacity: 0.6;", {scans::LOAD_FAILED.get(lang)} }
},
None => rsx! {
div { style: "opacity: 0.6;", {common::LOADING.get(lang)} }
},
}
}
/// One run: a status line, then its error and skipped stages, if any.
fn scan_run_card(run: &ScanRun, lang: Lang) -> Element {
let (badge, status) = status_badge(&run.status);
let started = format_time(&run.started_at, lang);
let finished = run.completed_at.as_ref().map(|t| format_time(t, lang));
let running = run.status == ScanRunStatus::Running;
rsx! {
div { style: "border-left: 3px solid var(--border); padding: 6px 10px; margin: 6px 0;",
div { style: "display: flex; gap: 12px; align-items: center; flex-wrap: wrap;",
span { class: "{badge}", {status.get(lang)} }
span { style: "font-size: 0.9em;",
{scans::STARTED.get(lang)} ": {started}"
}
if let Some(finished) = finished {
span { style: "font-size: 0.9em;",
{scans::FINISHED.get(lang)} ": {finished}"
}
}
if running {
span { style: "font-size: 0.9em;",
{scans::PHASE.get(lang)} ": " strong { {phase(&run.current_phase).get(lang)} }
}
} else {
span { style: "font-size: 0.9em;",
{scans::NEW_FINDINGS.get(lang)} ": {run.new_findings_count}"
}
}
}
if run.status == ScanRunStatus::Interrupted {
div { style: "font-size: 0.85em; opacity: 0.8; margin-top: 4px;",
{scans::INTERRUPTED_HINT.get(lang)}
}
}
if let Some(error) = run.error_message.as_ref() {
div { style: "color: var(--danger); font-size: 0.85em; margin-top: 4px;",
{scans::ERROR.get(lang)} ": {error}"
}
}
if !run.skipped_stages.is_empty() {
div { style: "font-size: 0.85em; margin-top: 4px;",
div { style: "opacity: 0.8;", {scans::SKIPPED.get(lang)} ":" }
ul { style: "margin: 2px 0 0 18px; padding: 0;",
for skipped in run.skipped_stages.iter() {
li {
strong { {stage_name(&skipped.stage, lang)} }
" — {skipped.reason}"
}
}
}
}
}
}
}
}
/// The badge class and label for a run status.
pub fn status_badge(status: &ScanRunStatus) -> (&'static str, Text) {
match status {
ScanRunStatus::Running => ("badge badge-info", scans::RUNNING),
ScanRunStatus::Completed => ("badge badge-success", scans::COMPLETED),
ScanRunStatus::Failed => ("badge badge-danger", scans::FAILED),
ScanRunStatus::Interrupted => ("badge badge-medium", scans::INTERRUPTED),
}
}
/// A skipped stage in words, or its id when this dashboard does not know it.
fn stage_name(id: &str, lang: Lang) -> String {
scans::stage(id).map_or_else(|| id.to_string(), |t| t.get(lang).to_string())
}
/// When something happened, in the reader's date convention (UTC).
fn format_time(time: &chrono::DateTime<chrono::Utc>, lang: Lang) -> String {
let pattern = match lang {
Lang::De => "%d.%m.%Y %H:%M UTC",
Lang::En => "%Y-%m-%d %H:%M UTC",
};
time.format(pattern).to_string()
}
/// 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 {
let (de, en) = match phase {
ScanPhase::ChangeDetection => ("Änderungen erkennen", "Detecting changes"),
ScanPhase::ArtifactIngest => ("Dateien einlesen", "Reading the upload"),
ScanPhase::Classification => ("Projekt erkennen", "Classifying the project"),
ScanPhase::Sast => ("Statische Codeanalyse", "Static code analysis"),
ScanPhase::SbomGeneration => ("SBOM erstellen", "Building the SBOM"),
ScanPhase::CveScanning => (
"Bekannte Schwachstellen (CVE)",
"Known vulnerabilities (CVE)",
),
ScanPhase::PatternScanning => ("Datenschutz-Muster", "Privacy patterns"),
ScanPhase::SecretDetection => ("Zugangsdaten im Code", "Secrets in the code"),
ScanPhase::LintScanning => ("Code-Qualität", "Code quality"),
ScanPhase::CodeReview => ("Code-Review", "Code review"),
ScanPhase::GraphBuilding => ("Code-Graph", "Code graph"),
ScanPhase::FirmwareStatic => ("Firmware-Analyse", "Firmware analysis"),
ScanPhase::PlcAnalysis => ("SPS-Analyse", "PLC analysis"),
ScanPhase::MobileStatic => ("Mobile-App-Analyse", "Mobile app analysis"),
ScanPhase::ContainerScan => ("Container-Analyse", "Container analysis"),
ScanPhase::LlmTriage => ("Befunde bewerten", "Triaging findings"),
ScanPhase::ControlTriage => ("CRA-Anforderungen zuordnen", "Mapping CRA requirements"),
ScanPhase::SemanticControlMapping => ("Controls zuordnen", "Mapping controls"),
ScanPhase::GroundedControlChecks => {
("Controls im Code prüfen", "Checking controls in code")
}
ScanPhase::IssueCreation => ("Tickets anlegen", "Creating issues"),
ScanPhase::DastScanning => ("Dynamische Prüfung", "Dynamic testing"),
ScanPhase::PlcProvision => ("SPS-Testumgebung starten", "Starting the PLC test runtime"),
ScanPhase::IcsProbe => ("Industrieprotokolle prüfen", "Probing industrial protocols"),
ScanPhase::Completed => ("Abgeschlossen", "Completed"),
};
Text { de, en }
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn times_follow_the_language() {
let t = chrono::DateTime::parse_from_rfc3339("2026-09-30T08:05:00Z")
.map(|t| t.with_timezone(&chrono::Utc));
let Ok(t) = t else {
panic!("fixed timestamp parses");
};
assert_eq!(format_time(&t, Lang::De), "30.09.2026 08:05 UTC");
assert_eq!(format_time(&t, Lang::En), "2026-09-30 08:05 UTC");
}
#[test]
fn unknown_stages_are_shown_by_id() {
assert_eq!(
stage_name("sast_c_cpp", Lang::De),
"C/C++-Analyse (cppcheck)"
);
assert_eq!(stage_name("brand_new_stage", Lang::De), "brand_new_stage");
}
}
@@ -56,7 +56,9 @@ pub fn Sidebar() -> Element {
},
NavItem {
label: nav::FINDINGS,
route: Route::FindingsPage {},
route: Route::FindingsPage {
target: String::new(),
},
icon: rsx! { Icon { icon: BsShieldExclamation, width: 18, height: 18 } },
runtime_only: false,
},
@@ -106,7 +108,7 @@ pub fn Sidebar() -> Element {
for item in nav_items {
{
let is_active = match (&current_route, &item.route) {
(Route::FindingDetailPage { .. }, Route::FindingsPage {}) => true,
(Route::FindingDetailPage { .. } | Route::FindingsPage { .. }, Route::FindingsPage { .. }) => true,
(Route::DastTargetsPage {}, Route::DastOverviewPage {}) => true,
(Route::DastFindingsPage {}, Route::DastOverviewPage {}) => true,
(Route::DastFindingDetailPage { .. }, Route::DastOverviewPage {}) => true,
+451
View File
@@ -202,3 +202,454 @@ pub mod overview {
en: "Failed to load.",
};
}
/// Scan runs: status, phases and the stages a run did not execute.
pub mod scans {
use super::Text;
pub const HISTORY: Text = Text {
de: "Prüfverlauf",
en: "Scan history",
};
pub const NO_RUNS: Text = Text {
de: "Noch keine Prüfung gelaufen.",
en: "No scan has run yet.",
};
pub const NEVER_SCANNED: Text = Text {
de: "Noch nicht geprüft",
en: "Not scanned yet",
};
pub const RUNNING: Text = Text {
de: "Läuft",
en: "Running",
};
pub const COMPLETED: Text = Text {
de: "Abgeschlossen",
en: "Completed",
};
pub const FAILED: Text = Text {
de: "Fehlgeschlagen",
en: "Failed",
};
pub const INTERRUPTED: Text = Text {
de: "Unterbrochen",
en: "Interrupted",
};
pub const INTERRUPTED_HINT: Text = Text {
de: "Der Dienst wurde während der Prüfung neu gestartet. Starten Sie die \
Prüfung erneut.",
en: "The service restarted during the scan. Please run it again.",
};
pub const STARTED: Text = Text {
de: "Gestartet",
en: "Started",
};
pub const FINISHED: Text = Text {
de: "Beendet",
en: "Finished",
};
pub const PHASE: Text = Text {
de: "Aktueller Schritt",
en: "Current step",
};
pub const NEW_FINDINGS: Text = Text {
de: "Neue Befunde",
en: "New findings",
};
pub const ERROR: Text = Text {
de: "Fehler",
en: "Error",
};
pub const SKIPPED: Text = Text {
de: "Nicht ausgeführt",
en: "Not run",
};
pub const LOAD_FAILED: Text = Text {
de: "Der Prüfverlauf konnte nicht geladen werden.",
en: "The scan history could not be loaded.",
};
/// A stage id the agent records as skipped, in words. `None` for an id
/// this dashboard does not know yet; it is then shown as it is.
pub fn stage(id: &str) -> Option<Text> {
let text = match id {
"ingest" => Text {
de: "Einlesen der Dateien",
en: "Reading the upload",
},
"code_scan" => Text {
de: "Codeanalyse",
en: "Code analysis",
},
"sast" => Text {
de: "Statische Codeanalyse (Semgrep)",
en: "Static analysis (semgrep)",
},
"sast_c_cpp" => Text {
de: "C/C++-Analyse (cppcheck)",
en: "C/C++ analysis (cppcheck)",
},
"sast_vendor_code" => Text {
de: "Herstellercode (HAL, CMSIS, Drittanbieter)",
en: "Vendor code (HAL, CMSIS, third party)",
},
"sbom_dependencies" => Text {
de: "Abhängigkeiten (SBOM)",
en: "Dependencies (SBOM)",
},
"firmware_sbom" => Text {
de: "Firmware-SBOM",
en: "Firmware SBOM",
},
"plc_archive_sbom" => Text {
de: "SPS-Bibliotheken (SBOM)",
en: "PLC libraries (SBOM)",
},
"dast" => Text {
de: "Dynamische Prüfung (DAST)",
en: "Dynamic testing (DAST)",
},
"pentest" => Text {
de: "Penetrationstest",
en: "Penetration test",
},
"ics_probe" => Text {
de: "Industrieprotokolle (ICS)",
en: "Industrial protocols (ICS)",
},
"plc_runtime" => Text {
de: "SPS-Laufzeittest",
en: "PLC runtime test",
},
"firmware_static" => Text {
de: "Firmware-Binäranalyse",
en: "Firmware binary analysis",
},
"mobile_static" => Text {
de: "Mobile-App-Analyse",
en: "Mobile app analysis",
},
"container_scan" => Text {
de: "Container-Analyse",
en: "Container analysis",
},
_ => return None,
};
Some(text)
}
}
/// The targets page.
pub mod targets {
use super::Text;
pub const TITLE: Text = Text {
de: "Prüfobjekte",
en: "Targets",
};
pub const SUBTITLE: Text = Text {
de: "Ihre Prüfobjekte und was ihre Prüfungen gefunden haben.",
en: "Your targets and what their scans found.",
};
pub const ADD: Text = Text {
de: "+ Prüfobjekt anlegen",
en: "+ Add a target",
};
pub const REFRESH: Text = Text {
de: "Aktualisieren",
en: "Refresh",
};
pub const COL_NAME: Text = Text {
de: "Name",
en: "Name",
};
pub const COL_TYPE: Text = Text {
de: "Typ",
en: "Type",
};
pub const COL_DETECTED: Text = Text {
de: "Erkannt",
en: "Detected",
};
pub const COL_LAST_SCAN: Text = Text {
de: "Letzte Prüfung",
en: "Last scan",
};
pub const COL_FINDINGS: Text = Text {
de: "Befunde",
en: "Findings",
};
pub const COL_ACTIONS: Text = Text {
de: "Aktionen",
en: "Actions",
};
pub const SHOW_FINDINGS: Text = Text {
de: "Befunde dieses Prüfobjekts anzeigen",
en: "Show this target's findings",
};
pub const DETAILS: Text = Text {
de: "Details",
en: "Details",
};
pub const EDIT: Text = Text {
de: "Bearbeiten",
en: "Edit target",
};
pub const RUN_SCAN: Text = Text {
de: "Prüfung starten",
en: "Run scan",
};
pub const DELETE: Text = Text {
de: "Löschen",
en: "Delete",
};
pub const SCAN_STARTED: Text = Text {
de: "Prüfung gestartet. Den Fortschritt sehen Sie in den Details.",
en: "Scan started. Follow its progress in the details.",
};
pub const ARTIFACTS: Text = Text {
de: "Artefakte",
en: "Artifacts",
};
pub const NO_ARTIFACTS: Text = Text {
de: "Keine Artefakte.",
en: "No artifacts.",
};
pub const DETECTED_FACTS: Text = Text {
de: "Erkannte Merkmale",
en: "Detected facts",
};
pub const APPLICABLE_SCANS: Text = Text {
de: "Anwendbare Prüfungen",
en: "Applicable scans",
};
pub const NO_SCANS: Text = Text {
de: "Keine Prüfungen möglich (kein Code, keine URL, kein Firmware-Artefakt).",
en: "No scans available (no code / URL / firmware artifact present).",
};
pub const PENTEST_SUPPORTED: Text = Text {
de: "Für diesen Typ ist ein aktiver Penetrationstest möglich.",
en: "Active pentest is supported for this target type.",
};
pub const EMPTY: Text = Text {
de: "Noch keine Prüfobjekte.",
en: "No targets yet.",
};
pub const EMPTY_ACTION: Text = Text {
de: "Erstes Prüfobjekt anlegen",
en: "Onboard your first target",
};
pub const DEMO_HINT: Text = Text {
de: "Der Demo-Satz enthält zwei SPS-Projekte, einen Dienst mit CRA-Schwachstellen \
und ein Zephyr-Firmwarebeispiel.",
en: "The demo set covers two PLC projects, a CRA-vulnerable git service and a \
Zephyr firmware sample.",
};
pub const LOAD_FAILED: Text = Text {
de: "Die Prüfobjekte konnten nicht geladen werden.",
en: "Failed to load targets.",
};
pub const DELETE_TITLE: Text = Text {
de: "Prüfobjekt löschen",
en: "Delete target",
};
pub const DELETE_WARNING: Text = Text {
de: "Damit werden das Prüfobjekt und seine Befunde, SBOM-Einträge, Prüfläufe \
und CVE-Warnungen endgültig entfernt.",
en: "This permanently removes the target and its findings, SBOM entries, scan \
runs, and CVE alerts.",
};
pub const DELETED: Text = Text {
de: "gelöscht",
en: "deleted",
};
pub const CANCEL: Text = Text {
de: "Abbrechen",
en: "Cancel",
};
pub const SAVE: Text = Text {
de: "Speichern",
en: "Save",
};
pub const SAVING: Text = Text {
de: "Wird gespeichert …",
en: "Saving...",
};
pub const UPDATED: Text = Text {
de: "Prüfobjekt gespeichert",
en: "Target updated",
};
pub const EDIT_TITLE: Text = Text {
de: "Prüfobjekt bearbeiten",
en: "Edit target",
};
pub const KIND: Text = Text {
de: "Art",
en: "Kind",
};
pub const REFERENCE: Text = Text {
de: "Referenz",
en: "Reference",
};
pub const BRANCH: Text = Text {
de: "Branch",
en: "Branch",
};
pub const REMOVE: Text = Text {
de: "Entfernen",
en: "Remove",
};
pub const ADD_ARTIFACT: Text = Text {
de: "+ Hinzufügen",
en: "+ Add",
};
}
/// Target types and artifact kinds, keyed by their API value.
pub mod kinds {
use super::Text;
/// The nine target families, in the order the forms offer them.
pub const TARGET_TYPES: [(&str, Text); 9] = [
(
"web_app",
Text {
de: "Webanwendung",
en: "Web application",
},
),
(
"backend_service",
Text {
de: "Backend / API",
en: "Backend / API",
},
),
(
"desktop_app",
Text {
de: "Desktop-Anwendung",
en: "Desktop app",
},
),
(
"android_app",
Text {
de: "Android-App",
en: "Android app",
},
),
(
"ios_app",
Text {
de: "iOS-App",
en: "iOS app",
},
),
(
"firmware_bare_metal",
Text {
de: "Firmware — ohne Betriebssystem",
en: "Firmware — bare metal",
},
),
(
"firmware_rtos",
Text {
de: "Firmware — RTOS",
en: "Firmware — RTOS",
},
),
(
"embedded_linux_yocto",
Text {
de: "Embedded Linux / Yocto",
en: "Embedded Linux / Yocto",
},
),
(
"plc_sps",
Text {
de: "SPS / PLC",
en: "PLC / SPS",
},
),
];
/// The artifact kinds, in the order the forms offer them.
pub const ARTIFACT_KINDS: [(&str, Text); 8] = [
(
"git_repo",
Text {
de: "Git-Repository",
en: "Git repository",
},
),
(
"source_archive",
Text {
de: "Quellcode-Archiv (zip, tar, tar.gz)",
en: "Source archive (zip, tar, tar.gz)",
},
),
(
"firmware_image",
Text {
de: "Firmware-Image",
en: "Firmware image",
},
),
(
"mobile_package",
Text {
de: "Mobile-Paket (APK/IPA)",
en: "Mobile package (APK/IPA)",
},
),
(
"container_image",
Text {
de: "Container-Image",
en: "Container image",
},
),
(
"live_url",
Text {
de: "Live-URL",
en: "Live URL",
},
),
(
"plc_project",
Text {
de: "SPS-Projekt",
en: "PLC project",
},
),
(
"plaintext_description",
Text {
de: "Beschreibung (Text)",
en: "Description (text)",
},
),
];
/// A target type's label; an unknown value is shown with spaces.
pub fn target_type(value: &str, lang: super::super::Lang) -> String {
label(&TARGET_TYPES, value, lang)
}
/// An artifact kind's label; an unknown value is shown with spaces.
pub fn artifact_kind(value: &str, lang: super::super::Lang) -> String {
label(&ARTIFACT_KINDS, value, lang)
}
fn label(table: &[(&str, Text)], value: &str, lang: super::super::Lang) -> String {
table
.iter()
.find(|(v, _)| *v == value)
.map_or_else(|| value.replace('_', " "), |(_, t)| t.get(lang).to_string())
}
}
@@ -23,3 +23,20 @@ pub async fn fetch_scan_runs(page: u64) -> Result<ScansListResponse, ServerFnErr
.map_err(|e| ServerFnError::new(e.to_string()))?;
Ok(body)
}
/// The scan runs of one target, newest first (its scan history).
#[server]
pub async fn fetch_target_scan_runs(target_id: String) -> Result<Vec<ScanRun>, ServerFnError> {
let resp = super::agent_client::agent_get(&format!(
"/api/v1/scan-runs?target_id={target_id}&page=1&limit=10"
))
.await?
.send()
.await
.map_err(|e| ServerFnError::new(e.to_string()))?;
let body: ScansListResponse = resp
.json()
.await
.map_err(|e| ServerFnError::new(e.to_string()))?;
Ok(body.data)
}
+2 -2
View File
@@ -9,12 +9,12 @@ use crate::components::severity_badge::SeverityBadge;
use crate::infrastructure::findings::has_control_refs;
#[component]
pub fn FindingsPage() -> Element {
pub fn FindingsPage(target: String) -> Element {
let mut page = use_signal(|| 1u64);
let mut severity_filter = use_signal(String::new);
let mut type_filter = use_signal(String::new);
let mut status_filter = use_signal(String::new);
let mut repo_filter = use_signal(String::new);
let mut repo_filter = use_signal(|| target.clone());
let mut search_query = use_signal(String::new);
let mut sort_by = use_signal(|| "created_at".to_string());
let mut sort_order = use_signal(|| "desc".to_string());
+98 -98
View File
@@ -11,52 +11,32 @@ use dioxus_free_icons::Icon;
use crate::components::demo_targets::DemoTargetsButton;
use crate::components::page_header::PageHeader;
use crate::components::scan_runs::{status_badge, ScanRunList};
use crate::components::toast::{ToastType, Toasts};
use crate::i18n::texts::{common, kinds, scans as scan_texts, targets as tx};
use crate::i18n::{use_lang, Lang};
use crate::infrastructure::onboarding::{
delete_target, fetch_applicable_scans, fetch_targets, trigger_target_scan, update_target,
validate_artifact_ref, validate_target_name, ArtifactInputDto,
};
use crate::infrastructure::platform::{stage_tone, use_source_only, SourceOnlyNote};
/// The nine target families (value, label) for the edit form's type selector.
const TARGET_TYPES: &[(&str, &str)] = &[
("web_app", "Web Application"),
("backend_service", "Backend / API"),
("desktop_app", "Desktop App"),
("android_app", "Android App"),
("ios_app", "iOS App"),
("firmware_bare_metal", "Firmware — bare metal"),
("firmware_rtos", "Firmware — RTOS"),
("embedded_linux_yocto", "Embedded Linux / Yocto"),
("plc_sps", "PLC / SPS"),
];
/// The artifact kinds (value, label) for the edit form.
const ARTIFACT_KINDS: &[(&str, &str)] = &[
("git_repo", "Git repository"),
("source_archive", "Source archive (zip)"),
("firmware_image", "Firmware image"),
("mobile_package", "Mobile package (APK/IPA)"),
("container_image", "Container image"),
("live_url", "Live URL"),
("plc_project", "PLC project"),
("plaintext_description", "Description (text)"),
];
/// Prettify a snake_case target-type value into a human label.
fn pretty_type(v: &str) -> String {
match v {
"web_app" => "Web Application".into(),
"backend_service" => "Backend / API".into(),
"desktop_app" => "Desktop App".into(),
"android_app" => "Android App".into(),
"ios_app" => "iOS App".into(),
"firmware_bare_metal" => "Firmware — bare metal".into(),
"firmware_rtos" => "Firmware — RTOS".into(),
"embedded_linux_yocto" => "Embedded Linux / Yocto".into(),
"plc_sps" => "PLC / SPS".into(),
other => other.replace('_', " "),
}
/// The last scan's badge class and label (with the step a running scan is
/// at), or `None` before the first scan.
fn last_scan_label(target: &serde_json::Value, lang: Lang) -> Option<(&'static str, String)> {
let run = target.get("last_scan").filter(|r| !r.is_null())?;
let run: compliance_core::models::ScanRun = serde_json::from_value(run.clone()).ok()?;
let (badge, status) = status_badge(&run.status);
let label = if run.status == compliance_core::models::ScanRunStatus::Running {
format!(
"{} · {}",
status.get(lang),
crate::components::scan_runs::phase(&run.current_phase).get(lang)
)
} else {
status.get(lang).to_string()
};
Some((badge, label))
}
fn str_at<'a>(v: &'a serde_json::Value, key: &str) -> &'a str {
@@ -81,6 +61,7 @@ fn TargetScans(id: String) -> Element {
});
let source_only = use_source_only();
let lang = use_lang()();
let snapshot = scans.read().clone();
match &snapshot {
Some(Some(resp)) => {
@@ -89,7 +70,7 @@ fn TargetScans(id: String) -> Element {
rsx! {
div { style: "margin-top: 8px;",
if rows.is_empty() {
div { style: "opacity: 0.6;", "No scans available (no code / URL / firmware artifact present)." }
div { style: "opacity: 0.6;", {tx::NO_SCANS.get(lang)} }
}
for s in rows {
{
@@ -112,19 +93,19 @@ fn TargetScans(id: String) -> Element {
}
if pentest && source_only {
div { style: "margin-top: 6px; opacity: 0.75; font-size: 0.85em;",
"Active pentest is supported for this target type"
{tx::PENTEST_SUPPORTED.get(lang)}
SourceOnlyNote { inline: true }
}
} else if pentest {
div { style: "margin-top: 6px; opacity: 0.75; font-size: 0.85em;",
"Active pentest is supported for this target type."
{tx::PENTEST_SUPPORTED.get(lang)}
}
}
}
}
}
Some(None) => rsx! { div { style: "opacity: 0.6;", "Failed to load applicable scans." } },
None => rsx! { div { style: "opacity: 0.6;", "Loading scans..." } },
Some(None) => rsx! { div { style: "opacity: 0.6;", {tx::LOAD_FAILED.get(lang)} } },
None => rsx! { div { style: "opacity: 0.6;", {common::LOADING.get(lang)} } },
}
}
@@ -147,21 +128,22 @@ pub fn TargetsPage() -> Element {
let mut e_branch = use_signal(|| "main".to_string());
let mut targets = use_resource(move || async move { fetch_targets().await.ok() });
let lang = use_lang()();
rsx! {
PageHeader {
title: "Targets",
description: "Onboarded targets and what their scans found. Add new targets from Onboard.",
title: tx::TITLE.get(lang),
description: tx::SUBTITLE.get(lang),
}
div { style: "margin-bottom: 16px; display: flex; gap: 8px;",
Link { to: crate::app::Route::OnboardingPage {}, class: "btn btn-primary",
"+ Onboard a target"
{tx::ADD.get(lang)}
}
button {
class: "btn btn-secondary",
onclick: move |_| targets.restart(),
"Refresh"
{tx::REFRESH.get(lang)}
}
}
@@ -169,16 +151,14 @@ pub fn TargetsPage() -> Element {
if let Some((del_id, del_name)) = confirm_delete() {
div { class: "modal-overlay",
div { class: "modal-dialog",
h3 { "Delete Target" }
p { "Delete " strong { "{del_name}" } "?" }
p { class: "modal-warning",
"This permanently removes the target and its findings, SBOM entries, scan runs, and CVE alerts."
}
h3 { {tx::DELETE_TITLE.get(lang)} }
p { strong { "{del_name}" } }
p { class: "modal-warning", {tx::DELETE_WARNING.get(lang)} }
div { class: "modal-actions",
button {
class: "btn btn-secondary",
onclick: move |_| confirm_delete.set(None),
"Cancel"
{tx::CANCEL.get(lang)}
}
button {
class: "btn btn-danger",
@@ -189,14 +169,17 @@ pub fn TargetsPage() -> Element {
spawn(async move {
match delete_target(id).await {
Ok(_) => {
toasts.push(ToastType::Success, format!("{name} deleted"));
toasts.push(
ToastType::Success,
format!("{name} {}", tx::DELETED.get(lang)),
);
targets.restart();
}
Err(e) => toasts.push(ToastType::Error, e.to_string()),
}
});
},
"Delete"
{tx::DELETE.get(lang)}
}
}
}
@@ -215,9 +198,9 @@ pub fn TargetsPage() -> Element {
rsx! {
div { class: "modal-overlay",
div { class: "modal-dialog",
h3 { "Edit target" }
h3 { {tx::EDIT_TITLE.get(lang)} }
div { class: "form-group",
label { "Name" }
label { {tx::COL_NAME.get(lang)} }
input {
r#type: "text",
value: "{edit_name}",
@@ -230,42 +213,42 @@ pub fn TargetsPage() -> Element {
}
}
div { class: "form-group",
label { "Type" }
label { {tx::COL_TYPE.get(lang)} }
select {
value: "{edit_type}",
oninput: move |e| edit_type.set(e.value()),
for (v, l) in TARGET_TYPES.iter().copied() {
option { value: "{v}", selected: edit_type() == v, "{l}" }
for (v, l) in kinds::TARGET_TYPES {
option { value: "{v}", selected: edit_type() == v, {l.get(lang)} }
}
}
}
label { style: "font-weight: 600;", "Artifacts" }
label { style: "font-weight: 600;", {tx::ARTIFACTS.get(lang)} }
for (i, a) in edit_arts().iter().enumerate() {
div { style: "display: flex; justify-content: space-between; align-items: center; padding: 4px 0;",
span { style: "font-size: 0.9em;",
span { style: "opacity: 0.7;", "{a.kind}: " }
span { style: "opacity: 0.7;", "{kinds::artifact_kind(&a.kind, lang)}: " }
span { style: "font-family: monospace;", "{a.source_ref}" }
}
button {
class: "btn btn-ghost btn-ghost-danger btn-sm",
onclick: move |_| { edit_arts.write().remove(i); },
"Remove"
{tx::REMOVE.get(lang)}
}
}
}
div { style: "display: flex; gap: 8px; align-items: flex-end; margin-top: 8px;",
div { class: "form-group", style: "margin: 0;",
label { "Kind" }
label { {tx::KIND.get(lang)} }
select {
value: "{e_kind}",
oninput: move |e| e_kind.set(e.value()),
for (v, l) in ARTIFACT_KINDS.iter().copied() {
option { value: "{v}", selected: e_kind() == v, "{l}" }
for (v, l) in kinds::ARTIFACT_KINDS {
option { value: "{v}", selected: e_kind() == v, {l.get(lang)} }
}
}
}
div { class: "form-group", style: "margin: 0; flex: 1;",
label { "Reference" }
label { {tx::REFERENCE.get(lang)} }
input {
r#type: "text",
value: "{e_source}",
@@ -274,7 +257,7 @@ pub fn TargetsPage() -> Element {
}
if e_kind() == "git_repo" {
div { class: "form-group", style: "margin: 0;",
label { "Branch" }
label { {tx::BRANCH.get(lang)} }
input {
r#type: "text",
value: "{e_branch}",
@@ -300,7 +283,7 @@ pub fn TargetsPage() -> Element {
e_source.set(String::new());
}
},
"+ Add"
{tx::ADD_ARTIFACT.get(lang)}
}
}
if let Some(err) = e_source_err.clone() {
@@ -310,7 +293,7 @@ pub fn TargetsPage() -> Element {
button {
class: "btn btn-secondary",
onclick: move |_| edit_id.set(None),
"Cancel"
{tx::CANCEL.get(lang)}
}
button {
class: "btn btn-primary",
@@ -324,7 +307,7 @@ pub fn TargetsPage() -> Element {
spawn(async move {
match update_target(id, Some(nm), Some(tt), Some(arts)).await {
Ok(_) => {
toasts.push(ToastType::Success, "Target updated");
toasts.push(ToastType::Success, tx::UPDATED.get(lang));
targets.restart();
edit_id.set(None);
}
@@ -333,7 +316,7 @@ pub fn TargetsPage() -> Element {
edit_saving.set(false);
});
},
if edit_saving() { "Saving..." } else { "Save" }
if edit_saving() { {tx::SAVING.get(lang)} } else { {tx::SAVE.get(lang)} }
}
}
}
@@ -350,10 +333,10 @@ pub fn TargetsPage() -> Element {
if rows.is_empty() {
rsx! {
div { class: "card", style: "padding: 24px; text-align: center;",
p { style: "opacity: 0.7;", "No targets yet." }
p { style: "opacity: 0.7;", {tx::EMPTY.get(lang)} }
div { style: "display: flex; gap: 8px; justify-content: center; flex-wrap: wrap;",
Link { to: crate::app::Route::OnboardingPage {}, class: "btn btn-primary",
"Onboard your first target"
{tx::EMPTY_ACTION.get(lang)}
}
DemoTargetsButton {
secondary: true,
@@ -361,7 +344,7 @@ pub fn TargetsPage() -> Element {
}
}
p { style: "opacity: 0.6; font-size: 0.85em; margin-top: 10px;",
"The demo set covers two PLC projects, a CRA-vulnerable git service and a Zephyr firmware sample."
{tx::DEMO_HINT.get(lang)}
}
}
}
@@ -372,12 +355,12 @@ pub fn TargetsPage() -> Element {
table {
thead {
tr {
th { "Name" }
th { "Type" }
th { "Detected" }
th { "Artifacts" }
th { "Findings" }
th { "Actions" }
th { {tx::COL_NAME.get(lang)} }
th { {tx::COL_TYPE.get(lang)} }
th { {tx::COL_DETECTED.get(lang)} }
th { {tx::COL_LAST_SCAN.get(lang)} }
th { {tx::COL_FINDINGS.get(lang)} }
th { {tx::COL_ACTIONS.get(lang)} }
}
}
tbody {
@@ -385,12 +368,12 @@ pub fn TargetsPage() -> Element {
{
let id = target_id(&t);
let name = str_at(&t, "name").to_string();
let ttype = pretty_type(str_at(&t, "target_type"));
let ttype = kinds::target_type(str_at(&t, "target_type"), lang);
let suggested = t
.get("classification")
.and_then(|c| c.get("suggested"))
.and_then(|s| s.as_str())
.map(pretty_type);
.map(|s| kinds::target_type(s, lang));
let artifacts = t
.get("artifacts")
.and_then(|a| a.as_array())
@@ -406,6 +389,7 @@ pub fn TargetsPage() -> Element {
.and_then(|f| f.as_array())
.cloned()
.unwrap_or_default();
let last_scan = last_scan_label(&t, lang);
let is_scanning = scanning_ids().contains(&id);
let is_expanded = expanded_ids().contains(&id);
let id_scan = id.clone();
@@ -428,12 +412,23 @@ pub fn TargetsPage() -> Element {
span { style: "opacity: 0.5;", "—" }
}
}
td { "{artifacts.len()}" }
td { "{findings}" }
td {
match last_scan.clone() {
Some((badge, label)) => rsx! { span { class: "{badge}", "{label}" } },
None => rsx! { span { style: "opacity: 0.5;", {scan_texts::NEVER_SCANNED.get(lang)} } },
}
}
td {
Link {
to: crate::app::Route::FindingsPage { target: id.clone() },
title: tx::SHOW_FINDINGS.get(lang),
"{findings}"
}
}
td { style: "display: flex; gap: 4px;",
button {
class: "btn btn-ghost",
title: "Details",
title: tx::DETAILS.get(lang),
onclick: move |_| {
let mut ids = expanded_ids();
if ids.contains(&id_exp) {
@@ -447,7 +442,7 @@ pub fn TargetsPage() -> Element {
}
button {
class: "btn btn-ghost",
title: "Edit target",
title: tx::EDIT.get(lang),
onclick: move |_| {
edit_name.set(name_edit.clone());
edit_type.set(ttype_raw.clone());
@@ -472,7 +467,7 @@ pub fn TargetsPage() -> Element {
}
button {
class: if is_scanning { "btn btn-ghost btn-scanning" } else { "btn btn-ghost" },
title: "Run scan",
title: tx::RUN_SCAN.get(lang),
disabled: is_scanning,
onclick: move |_| {
let id = id_scan.clone();
@@ -481,7 +476,10 @@ pub fn TargetsPage() -> Element {
scanning_ids.set(ids);
spawn(async move {
match trigger_target_scan(id.clone()).await {
Ok(_) => toasts.push(ToastType::Success, "Scan triggered — findings appear as it runs. Use Refresh."),
Ok(_) => {
toasts.push(ToastType::Success, tx::SCAN_STARTED.get(lang));
targets.restart();
}
Err(e) => toasts.push(ToastType::Error, e.to_string()),
}
let mut ids = scanning_ids();
@@ -497,7 +495,7 @@ pub fn TargetsPage() -> Element {
}
button {
class: "btn btn-ghost btn-ghost-danger",
title: "Delete target",
title: tx::DELETE.get(lang),
onclick: move |_| {
confirm_delete.set(Some((id_del.clone(), name_del.clone())));
},
@@ -509,18 +507,20 @@ pub fn TargetsPage() -> Element {
tr {
td { colspan: "6",
div { style: "padding: 12px 8px;",
h4 { style: "margin: 0 0 6px;", "Artifacts" }
h4 { style: "margin: 0 0 6px;", {scan_texts::HISTORY.get(lang)} }
ScanRunList { target_id: id.clone() }
h4 { style: "margin: 12px 0 6px;", {tx::ARTIFACTS.get(lang)} }
if artifacts_detail.is_empty() {
div { style: "opacity: 0.6;", "No artifacts." }
div { style: "opacity: 0.6;", {tx::NO_ARTIFACTS.get(lang)} }
}
for a in artifacts_detail {
div { style: "font-size: 0.9em; padding: 2px 0;",
span { style: "opacity: 0.7;", "{str_at(&a, \"kind\")}: " }
span { style: "opacity: 0.7;", "{kinds::artifact_kind(str_at(&a, \"kind\"), lang)}: " }
span { style: "font-family: monospace;", "{str_at(&a, \"source_ref\")}" }
}
}
if !facts.is_empty() {
h4 { style: "margin: 12px 0 6px;", "Detected facts" }
h4 { style: "margin: 12px 0 6px;", {tx::DETECTED_FACTS.get(lang)} }
for f in facts {
div { style: "font-size: 0.9em; padding: 2px 0;",
span { style: "font-family: monospace;", "{str_at(&f, \"key\")}={str_at(&f, \"value\")}" }
@@ -528,7 +528,7 @@ pub fn TargetsPage() -> Element {
}
}
}
h4 { style: "margin: 12px 0 6px;", "Applicable scans" }
h4 { style: "margin: 12px 0 6px;", {tx::APPLICABLE_SCANS.get(lang)} }
TargetScans { id: id.clone() }
}
}
@@ -545,10 +545,10 @@ pub fn TargetsPage() -> Element {
}
}
Some(None) => rsx! {
div { class: "card", p { "Failed to load targets." } }
div { class: "card", p { {tx::LOAD_FAILED.get(lang)} } }
},
None => rsx! {
div { class: "loading", "Loading targets..." }
div { class: "loading", {common::LOADING.get(lang)} }
},
}
}