From efb2c8a1ea1c70a90d831699245aab02d29ea659 Mon Sep 17 00:00:00 2001 From: Sharang Parnerkar Date: Wed, 23 Sep 2026 14:03:45 +0000 Subject: [PATCH] feat(dashboard): onboarding starts the first scan and shows its progress (#344) --- .../src/components/scan_runs.rs | 13 +- compliance-dashboard/src/i18n/mod.rs | 31 + compliance-dashboard/src/i18n/texts.rs | 277 ++++++++ .../src/infrastructure/agent_client.rs | 50 ++ .../src/infrastructure/onboarding.rs | 44 +- .../src/infrastructure/platform.rs | 5 +- compliance-dashboard/src/pages/onboarding.rs | 597 +++++++++--------- 7 files changed, 690 insertions(+), 327 deletions(-) diff --git a/compliance-dashboard/src/components/scan_runs.rs b/compliance-dashboard/src/components/scan_runs.rs index d4ef3ea..9a953f2 100644 --- a/compliance-dashboard/src/components/scan_runs.rs +++ b/compliance-dashboard/src/components/scan_runs.rs @@ -14,7 +14,8 @@ use crate::infrastructure::scans::fetch_target_scan_runs; 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. +/// in progress (or none is recorded yet), so the customer sees it move +/// without reloading. #[component] pub fn ScanRunList(target_id: String) -> Element { let lang = use_lang()(); @@ -28,12 +29,16 @@ pub fn ScanRunList(target_id: String) -> Element { #[cfg(feature = "web")] loop { gloo_timers::future::TimeoutFuture::new(POLL_MS).await; - let running = runs + // Also while the history is empty: a scan just started may not + // be recorded yet when the first request lands. + let waiting = runs .peek() .as_ref() .and_then(|r| r.as_ref()) - .is_some_and(|list| list.iter().any(|r| r.status == ScanRunStatus::Running)); - if running { + .is_some_and(|list| { + list.is_empty() || list.iter().any(|r| r.status == ScanRunStatus::Running) + }); + if waiting { runs.restart(); } } diff --git a/compliance-dashboard/src/i18n/mod.rs b/compliance-dashboard/src/i18n/mod.rs index f7ed74c..b2f1c0d 100644 --- a/compliance-dashboard/src/i18n/mod.rs +++ b/compliance-dashboard/src/i18n/mod.rs @@ -70,6 +70,29 @@ impl Text { } } +/// A byte count for people: `12,3 MB` in German, `12.3 MB` in English. +pub fn format_bytes(bytes: u64, lang: Lang) -> String { + const UNITS: [&str; 4] = ["KB", "MB", "GB", "TB"]; + if bytes < 1024 { + return format!("{bytes} B"); + } + // Precision loss is irrelevant at one decimal place. + let mut value = bytes as f64 / 1024.0; + let mut unit = UNITS[0]; + for next in &UNITS[1..] { + if value < 1024.0 { + break; + } + value /= 1024.0; + unit = next; + } + let number = format!("{value:.1}"); + match lang { + Lang::De => format!("{} {unit}", number.replace('.', ",")), + Lang::En => format!("{number} {unit}"), + } +} + /// Provide the language to the whole app. Call once, in the app shell. /// /// Server rendering and the first client render use German so hydration @@ -152,6 +175,14 @@ mod tests { assert_eq!(Lang::from_code("fr"), None); } + #[test] + fn sizes_read_like_the_language() { + assert_eq!(format_bytes(512, Lang::De), "512 B"); + assert_eq!(format_bytes(12_900_000, Lang::De), "12,3 MB"); + assert_eq!(format_bytes(12_900_000, Lang::En), "12.3 MB"); + assert_eq!(format_bytes(3 * 1024 * 1024 * 1024, Lang::En), "3.0 GB"); + } + #[test] fn text_picks_the_language() { let t = Text { diff --git a/compliance-dashboard/src/i18n/texts.rs b/compliance-dashboard/src/i18n/texts.rs index 8e873d7..2cabd9c 100644 --- a/compliance-dashboard/src/i18n/texts.rs +++ b/compliance-dashboard/src/i18n/texts.rs @@ -653,3 +653,280 @@ pub mod kinds { .map_or_else(|| value.replace('_', " "), |(_, t)| t.get(lang).to_string()) } } + +/// The onboarding wizard. +pub mod onboarding { + use super::Text; + + pub const TITLE: Text = Text { + de: "Prüfobjekt anlegen", + en: "Onboard a target", + }; + pub const SUBTITLE: Text = Text { + de: "Beschreiben Sie das Produkt, fügen Sie Code oder Dateien hinzu, und die \ + erste Prüfung startet.", + en: "Describe the product, add its code or files, and the first scan starts.", + }; + pub const STEPS: [Text; 4] = [ + Text { + de: "Typ", + en: "Target type", + }, + Text { + de: "Artefakte", + en: "Artifacts", + }, + Text { + de: "Prüfen", + en: "Review", + }, + Text { + de: "Fertig", + en: "Done", + }, + ]; + pub const ERROR: Text = Text { + de: "Fehler", + en: "Error", + }; + pub const WHAT_KIND: Text = Text { + de: "Um welche Art von Software handelt es sich?", + en: "What kind of software is this?", + }; + pub const NAME: Text = Text { + de: "Name", + en: "Name", + }; + pub const DEMO_PROMPT: Text = Text { + de: "Kein Projekt zur Hand? Beginnen Sie mit dem Demo-Satz:", + en: "No target at hand? Start with the versioned demo set:", + }; + /// One-line descriptions of the target types, in `kinds::TARGET_TYPES` order. + pub const TYPE_HINTS: [Text; 9] = [ + Text { + de: "Frontend + Server", + en: "Front end + server", + }, + Text { + de: "REST, GraphQL, gRPC", + en: "REST, GraphQL, gRPC", + }, + Text { + de: "Windows / macOS / Linux", + en: "Windows / macOS / Linux", + }, + Text { + de: "APK / AAB", + en: "APK / AAB", + }, + Text { + de: "IPA", + en: "IPA", + }, + Text { + de: "Mikrocontroller, kein Betriebssystem", + en: "Microcontroller, no operating system", + }, + Text { + de: "Zephyr, FreeRTOS, …", + en: "Zephyr, FreeRTOS, ...", + }, + Text { + de: "BSP + Image", + en: "BSP + image", + }, + Text { + de: "IEC 61131-3", + en: "IEC 61131-3", + }, + ]; + pub const ATTACH: Text = Text { + de: "Artefakte hinzufügen", + en: "Attach artifacts", + }; + pub const KIND: Text = Text { + de: "Art", + en: "Kind", + }; + pub const FILE: Text = Text { + de: "Datei", + en: "File", + }; + pub const FORMAT: Text = Text { + de: "Format", + en: "Format", + }; + pub const ADD_FILE: Text = Text { + de: "+ Datei hinzufügen", + en: "+ Add file", + }; + pub const REFERENCE: Text = Text { + de: "Referenz (URL / Pfad / Text)", + en: "Reference (URL / path / text)", + }; + pub const BRANCH: Text = Text { + de: "Branch", + en: "Branch", + }; + pub const ADD: Text = Text { + de: "+ Hinzufügen", + en: "+ Add", + }; + pub const SELECTED: Text = Text { + de: "Ausgewählt", + en: "Selected", + }; + pub const REMOVE: Text = Text { + de: "Entfernen", + en: "Remove", + }; + pub const NO_ARTIFACTS: Text = Text { + de: "Noch keine Artefakte. Fügen Sie mindestens eines hinzu.", + en: "No artifacts yet. Add at least one.", + }; + pub const FILE_SUFFIX: Text = Text { + de: "Datei", + en: "file", + }; + pub const PLC_HINT_TITLE: Text = Text { + de: "CODESYS- / SPS-Projekte", + en: "CODESYS / PLC projects", + }; + pub const PLC_HINT: Text = Text { + de: "Fügen Sie ein SPS-Projekt (PLCopen XML / ST oder ein .projectarchive) oder \ + ein Git-Repository mit exportiertem Quellcode hinzu. Für die Analyse der \ + Steuerungslogik genügen PLCopen-XML-Exporte oder .st-Dateien; die \ + Bibliotheks-SBOM braucht das .projectarchive. Die binäre .project-Datei \ + allein lässt sich nicht auswerten.", + en: "Attach a PLC project (PLCopen XML / ST, or a .projectarchive), or a git \ + repository of exported source. Control-logic analysis needs PLCopen XML \ + exports or .st files; the library SBOM needs the .projectarchive. The \ + binary .project file alone cannot be analysed.", + }; + pub const REVIEW: Text = Text { + de: "Prüfen", + en: "Review", + }; + pub const TYPE: Text = Text { + de: "Typ", + en: "Type", + }; + pub const ARTIFACTS: Text = Text { + de: "Artefakte", + en: "Artifacts", + }; + pub const REVIEW_NOTE: Text = Text { + de: "Nach dem Anlegen werden die Dateien hochgeladen und die erste Prüfung \ + startet automatisch.", + en: "After you create it, the files are uploaded and the first scan starts \ + on its own.", + }; + pub const REVIEW_NOTE_SOURCE_ONLY: Text = Text { + de: "DAST, Penetrationstest und Prüfungen am laufenden Gerät sind in dieser \ + Umgebung nicht verfügbar.", + en: "DAST, pentest and live-device probes are not available in this \ + environment.", + }; + pub const BACK: Text = Text { + de: "Zurück", + en: "Back", + }; + pub const NEXT: Text = Text { + de: "Weiter", + en: "Next", + }; + pub const CREATE: Text = Text { + de: "Anlegen und prüfen", + en: "Create and scan", + }; + pub const CREATING: Text = Text { + de: "Wird angelegt …", + en: "Creating...", + }; + pub const UPLOADING: Text = Text { + de: "Wird hochgeladen", + en: "Uploading", + }; + pub const UPLOAD_FAILED: Text = Text { + de: "Hochladen fehlgeschlagen", + en: "Upload failed", + }; + pub const UPLOAD_FAILED_HINT: Text = Text { + de: "Das Prüfobjekt wurde angelegt, aber nicht jede Datei kam an. Die Prüfung \ + wurde daher nicht gestartet. Fügen Sie die Datei unter „Prüfobjekte“ \ + erneut hinzu.", + en: "The target was created, but not every file arrived, so the scan was not \ + started. Add the file again under Targets.", + }; + pub const DONE: Text = Text { + de: "Prüfobjekt angelegt", + en: "Target onboarded", + }; + pub const CREATED: Text = Text { + de: "wurde angelegt.", + en: "was created.", + }; + pub const SUGGESTED: Text = Text { + de: "Erkannter Typ:", + en: "Detected type:", + }; + pub const SCAN_STARTED: Text = Text { + de: "Die erste Prüfung läuft. Der Fortschritt erscheint unten.", + en: "The first scan is running. Its progress appears below.", + }; + pub const SCAN_START_FAILED: Text = Text { + de: "Die Prüfung konnte nicht gestartet werden", + en: "The scan could not be started", + }; + 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 SOURCE_ONLY_SKIPS: Text = Text { + de: "Prüfungen am laufenden Gerät (ICS/SPS-Laufzeit), DAST und Penetrationstest \ + entfallen hier.", + en: "Live-device probes (ICS/PLC runtime), DAST and pentest are skipped here.", + }; + pub const OPTIN_TITLE: Text = Text { + de: "Optionale Prüfungen", + en: "Opt-in scans", + }; + pub const OPTIN_HINT: Text = Text { + de: "Anwendbar, aber standardmäßig aus, da sie ein laufendes Gerät ansprechen. \ + Auswählen und dann die Prüfung starten.", + en: "Applicable but off by default (they touch a live device). Tick them, then \ + run the scan.", + }; + pub const ENABLE: Text = Text { + de: "Aktivieren:", + en: "Enable", + }; + pub const OPTIN_FAILED: Text = Text { + de: "Optionale Prüfungen konnten nicht aktiviert werden", + en: "Failed to enable opt-in scans", + }; + pub const RUN_SCAN: Text = Text { + de: "Prüfung starten", + en: "Run scan", + }; + pub const PROGRESS: Text = Text { + de: "Fortschritt", + en: "Progress", + }; + pub const TO_FINDINGS: Text = Text { + de: "Zu den Befunden", + en: "View findings", + }; + pub const TO_TARGETS: Text = Text { + de: "Zu den Prüfobjekten", + en: "Go to targets", + }; + pub const ANOTHER: Text = Text { + de: "Weiteres Prüfobjekt anlegen", + en: "Onboard another", + }; +} diff --git a/compliance-dashboard/src/infrastructure/agent_client.rs b/compliance-dashboard/src/infrastructure/agent_client.rs index 204037d..c96d9c1 100644 --- a/compliance-dashboard/src/infrastructure/agent_client.rs +++ b/compliance-dashboard/src/infrastructure/agent_client.rs @@ -46,6 +46,42 @@ pub async fn agent_request( Ok(req) } +/// Parse an agent response as JSON. A non-2xx status becomes an error that +/// carries the agent's own `error` message (or the status text), so the user +/// reads why a request was refused instead of a JSON parse error. +/// +/// # Errors +/// +/// The refusal for a non-2xx status, or the parse error for a malformed body. +pub async fn json_or_error( + resp: reqwest::Response, +) -> Result { + let status = resp.status(); + if !status.is_success() { + let body = resp.text().await.unwrap_or_default(); + return Err(ServerFnError::new(refusal_message(status, &body))); + } + resp.json() + .await + .map_err(|e| ServerFnError::new(e.to_string())) +} + +/// The message for a refused request: the agent's `error` field when it sent +/// one, else the status text, with the status code. +fn refusal_message(status: reqwest::StatusCode, body: &str) -> String { + let message = serde_json::from_str::(body) + .ok() + .and_then(|v| v.get("error").and_then(|e| e.as_str()).map(String::from)) + .filter(|m| !m.trim().is_empty()) + .unwrap_or_else(|| { + status + .canonical_reason() + .unwrap_or("request failed") + .to_string() + }); + format!("{message} ({})", status.as_u16()) +} + /// Same as [`agent_request`] but for `GET`. Convenience for the common case. pub async fn agent_get(path: &str) -> Result { agent_request(Method::GET, path).await @@ -163,6 +199,20 @@ async fn refresh_tokens( #[cfg(test)] mod tests { use super::*; + + #[test] + fn a_refusal_says_what_the_agent_said() { + let status = reqwest::StatusCode::BAD_REQUEST; + assert_eq!( + refusal_message(status, r#"{"error":"name already in use"}"#), + "name already in use (400)" + ); + assert_eq!(refusal_message(status, ""), "Bad Request (400)"); + assert_eq!( + refusal_message(reqwest::StatusCode::FORBIDDEN, r#"{"error":""}"#), + "Forbidden (403)" + ); + } use base64::Engine; /// Build a JWT-shaped string (header.payload.sig) with the given diff --git a/compliance-dashboard/src/infrastructure/onboarding.rs b/compliance-dashboard/src/infrastructure/onboarding.rs index ba80289..092f8b9 100644 --- a/compliance-dashboard/src/infrastructure/onboarding.rs +++ b/compliance-dashboard/src/infrastructure/onboarding.rs @@ -181,9 +181,7 @@ pub async fn fetch_targets() -> Result { .send() .await .map_err(|e| ServerFnError::new(e.to_string()))?; - resp.json() - .await - .map_err(|e| ServerFnError::new(e.to_string())) + super::agent_client::json_or_error(resp).await } /// List the demo-target manifest the agent can seed. @@ -201,9 +199,7 @@ pub async fn fetch_demo_seed_targets() -> Result format!("upload rejected by the agent ({code})"), })); } - resp.json() - .await - .map_err(|e| ServerFnError::new(e.to_string())) + super::agent_client::json_or_error(resp).await } /// Update a target's name / type / artifacts (dashboard editor). @@ -333,9 +323,7 @@ pub async fn update_target( .send() .await .map_err(|e| ServerFnError::new(e.to_string()))?; - resp.json() - .await - .map_err(|e| ServerFnError::new(e.to_string())) + super::agent_client::json_or_error(resp).await } /// Enable specific opt-in scans on a target by setting `scan_config.enabled_scans`. @@ -355,9 +343,7 @@ pub async fn enable_target_scans( .send() .await .map_err(|e| ServerFnError::new(e.to_string()))?; - resp.json() - .await - .map_err(|e| ServerFnError::new(e.to_string())) + super::agent_client::json_or_error(resp).await } /// Run kind-based classification on a target. @@ -371,9 +357,7 @@ pub async fn detect_target(id: String) -> Result .send() .await .map_err(|e| ServerFnError::new(e.to_string()))?; - resp.json() - .await - .map_err(|e| ServerFnError::new(e.to_string())) + super::agent_client::json_or_error(resp).await } /// Fetch the scan-applicability matrix for a target. @@ -384,9 +368,7 @@ pub async fn fetch_applicable_scans(id: String) -> Result Result Result bool { /// A small inline note used next to disabled runtime-only controls. #[component] pub fn SourceOnlyNote(#[props(default)] inline: bool) -> Element { + let note = crate::i18n::texts::common::NOT_AVAILABLE_HERE.get(crate::i18n::use_lang()()); let style = if inline { "font-size: 0.8em; color: var(--text-secondary); font-style: italic; margin-left: 8px;" } else { "padding: 10px 14px; border-left: 3px solid var(--border-bright); color: var(--text-secondary); font-size: 0.9em; margin-bottom: 16px;" }; rsx! { - span { class: "source-only-note", style: "{style}", title: "{SOURCE_ONLY_NOTE}", - "{SOURCE_ONLY_NOTE} (source-only mode)" + span { class: "source-only-note", style: "{style}", title: "{note}", + "{note}" } } } diff --git a/compliance-dashboard/src/pages/onboarding.rs b/compliance-dashboard/src/pages/onboarding.rs index 8a2ac21..481dee6 100644 --- a/compliance-dashboard/src/pages/onboarding.rs +++ b/compliance-dashboard/src/pages/onboarding.rs @@ -1,49 +1,23 @@ +//! The onboarding wizard: type and name, artifacts, review, then create. +//! +//! Creating uploads the staged files one by one (the step shows which), and +//! starts the first scan on its own unless an upload failed or the target +//! offers opt-in scans the user may want to tick first. The last step follows +//! that scan live and links on to its findings. + use dioxus::prelude::*; +use crate::app::Route; use crate::components::demo_targets::DemoTargetsButton; use crate::components::page_header::PageHeader; +use crate::components::scan_runs::ScanRunList; +use crate::i18n::texts::{common, kinds, onboarding as tx}; +use crate::i18n::{format_bytes, use_lang}; use crate::infrastructure::onboarding::{ create_target, detect_target, enable_target_scans, fetch_applicable_scans, trigger_target_scan, upload_target_artifact, validate_artifact_ref, validate_target_name, ArtifactInputDto, }; -use crate::infrastructure::platform::{ - stage_tone, use_source_only, SourceOnlyNote, SOURCE_ONLY_NOTE, -}; - -/// (value, label, one-line description) for the 9 target families. -const TARGET_TYPES: &[(&str, &str, &str)] = &[ - ("web_app", "Web Application", "Front end + server"), - ("backend_service", "Backend / API", "REST, GraphQL, gRPC"), - ("desktop_app", "Desktop App", "Windows / macOS / Linux"), - ("android_app", "Android App", "APK / AAB"), - ("ios_app", "iOS App", "IPA"), - ( - "firmware_bare_metal", - "Firmware — bare metal", - "No operating system", - ), - ("firmware_rtos", "Firmware — RTOS", "Zephyr, FreeRTOS, ..."), - ( - "embedded_linux_yocto", - "Embedded Linux / Yocto", - "BSP + image", - ), - ("plc_sps", "PLC / SPS", "IEC 61131-3"), -]; - -/// (value, label) for the artifact kinds a user can attach. -const ARTIFACT_KINDS: &[(&str, &str)] = &[ - ("git_repo", "Git repository"), - ("source_archive", "Source archive (zip, tar, tar.gz)"), - ("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)"), -]; - -const STEP_LABELS: &[&str] = &["Target type", "Artifacts", "Review", "Done"]; +use crate::infrastructure::platform::{stage_tone, use_source_only, SourceOnlyNote}; /// Artifact kinds that only make sense with a runtime (live target / device) /// — disabled when the agent reports `source_only`. @@ -59,7 +33,6 @@ fn is_file_kind(kind: &str) -> bool { ) } -/// A file artifact staged in the wizard, uploaded after the target is created. /// A file staged in the wizard. It holds the browser's file handle, not its /// contents: the file is streamed straight from disk when it is uploaded, so a /// 500 MB firmware image is never copied into WASM memory. @@ -71,99 +44,13 @@ struct PendingFile { file: dioxus::html::FileData, } -/// One row in the applicable-scans list on the success step. -#[component] -fn ScanRow(scan: serde_json::Value) -> Element { - let name = scan - .get("scan") - .and_then(|v| v.as_str()) - .unwrap_or("?") - .to_string(); - let rationale = scan - .get("rationale") - .and_then(|v| v.as_str()) - .unwrap_or("") - .to_string(); - let blocked = scan - .get("blocked_reason") - .and_then(|v| v.as_str()) - .map(String::from); - let default_on = scan - .get("default_on") - .and_then(|v| v.as_bool()) - .unwrap_or(false); - let status = scan - .get("status") - .and_then(|v| v.as_str()) - .map(String::from); - let badge_class = stage_tone(status.as_deref(), blocked.as_deref(), default_on).badge_class(); - rsx! { - div { style: "display: flex; gap: 8px; align-items: center; padding: 6px 0;", - span { class: "{badge_class}", "{name}" } - span { style: "opacity: 0.8;", "{rationale}" } - if let Some(b) = blocked { - span { style: "opacity: 0.6; font-style: italic;", "— {b}" } - } - } - } -} - -fn kind_label(kind: &str) -> &str { - ARTIFACT_KINDS +/// The opt-in scans of an applicable-scans list: applicable and unblocked, +/// but off by default (e.g. the ICS probe). Each entry is (display name, serde +/// scan-type name for the enable call: lowercase, no underscores, matching +/// `ScanType`'s `rename_all = "lowercase"`). +fn optin_scans(scans: &[serde_json::Value]) -> Vec<(String, String)> { + scans .iter() - .find(|(v, _)| *v == kind) - .map(|(_, l)| *l) - .unwrap_or(kind) -} - -fn type_label(value: &str) -> &str { - TARGET_TYPES - .iter() - .find(|(v, _, _)| *v == value) - .map(|(_, l, _)| *l) - .unwrap_or(value) -} - -#[component] -pub fn OnboardingPage() -> Element { - let mut step = use_signal(|| 0usize); - let mut name = use_signal(String::new); - let mut target_type = use_signal(String::new); - let mut description = use_signal(String::new); - let mut artifacts = use_signal(Vec::::new); - - // "Add artifact" mini-form. - let mut new_kind = use_signal(|| "git_repo".to_string()); - let mut new_source = use_signal(String::new); - let mut new_branch = use_signal(|| "main".to_string()); - // File-upload artifacts (PLC project, firmware image, ...). - let mut new_plc_format = use_signal(|| "plcopen_xml".to_string()); - let mut new_file = use_signal(|| Option::<(String, dioxus::html::FileData)>::None); - let mut pending_files = use_signal(Vec::::new); - - // Create + result state. - let mut creating = use_signal(|| false); - let mut error = use_signal(|| Option::::None); - let mut scans = use_signal(Vec::::new); - let mut suggested = use_signal(|| Option::::None); - let mut created_id = use_signal(|| Option::::None); - let mut scan_msg = use_signal(|| Option::::None); - // Opt-in scans (default-off but unblocked) the user ticks to enable before - // running — stored as serde scan-type names (lowercase, no underscores). - let mut enabled_extra = use_signal(Vec::::new); - - let source_only = use_source_only(); - let step_now = step(); - let name_error = validate_target_name(&name()); - let can_advance_type = name_error.is_none() && !target_type().trim().is_empty(); - let has_artifacts = !artifacts().is_empty() || !pending_files().is_empty(); - // Opt-in scans: applicable + unblocked, but default-off (e.g. the ICS probe). - // The user ticks these to enable them before the first run. Each entry is - // (display name for the label, serde scan-type name for the enable call — - // lowercase, no underscores, matching ScanType's rename_all = "lowercase"). - let optin_scans: Vec<(String, String)> = scans() - .iter() - .filter(|_| !source_only) .filter_map(|s| { let unblocked = s.get("blocked_reason").and_then(|v| v.as_str()).is_none(); let default_on = s @@ -178,34 +65,113 @@ pub fn OnboardingPage() -> Element { None } }) - .collect(); + .collect() +} + +/// One row in the applicable-scans list on the last step. +#[component] +fn ScanRow(scan: serde_json::Value) -> Element { + let text = |key: &str| scan.get(key).and_then(|v| v.as_str()).map(String::from); + let name = text("scan").unwrap_or_else(|| "?".to_string()); + let rationale = text("rationale").unwrap_or_default(); + let blocked = text("blocked_reason"); + let default_on = scan + .get("default_on") + .and_then(|v| v.as_bool()) + .unwrap_or(false); + let status = text("status"); + let badge_class = stage_tone(status.as_deref(), blocked.as_deref(), default_on).badge_class(); + rsx! { + div { style: "display: flex; gap: 8px; align-items: center; padding: 6px 0;", + span { class: "{badge_class}", "{name}" } + span { style: "opacity: 0.8;", "{rationale}" } + if let Some(b) = blocked { + span { style: "opacity: 0.6; font-style: italic;", "— {b}" } + } + } + } +} + +/// Where the first scan stands on the last step. +#[derive(Debug, Clone, PartialEq)] +enum FirstScan { + /// Not started: an upload failed, or opt-in scans are offered first. + Waiting, + /// Started; the progress is shown. + Started, + /// The agent refused to start it. + Failed(String), +} + +#[component] +pub fn OnboardingPage() -> Element { + let lang = use_lang()(); + let mut step = use_signal(|| 0usize); + let mut name = use_signal(String::new); + let mut target_type = use_signal(String::new); + let mut artifacts = use_signal(Vec::::new); + + // "Add artifact" mini-form. + let mut new_kind = use_signal(|| "git_repo".to_string()); + let mut new_source = use_signal(String::new); + let mut new_branch = use_signal(|| "main".to_string()); + // File-upload artifacts (PLC project, firmware image, ...). + let mut new_plc_format = use_signal(|| "plcopen_xml".to_string()); + let mut new_file = use_signal(|| Option::<(String, dioxus::html::FileData)>::None); + let mut pending_files = use_signal(Vec::::new); + + // Create + result state. + let mut creating = use_signal(|| false); + // Which file is being uploaded: (1-based index, total, file name). + let mut uploading = use_signal(|| Option::<(usize, usize, String)>::None); + let mut error = use_signal(|| Option::::None); + let mut upload_errors = use_signal(Vec::::new); + let mut scans = use_signal(Vec::::new); + let mut suggested = use_signal(|| Option::::None); + let mut created_id = use_signal(|| Option::::None); + let mut first_scan = use_signal(|| FirstScan::Waiting); + // Opt-in scans the user ticks before running, as serde scan-type names. + let mut enabled_extra = use_signal(Vec::::new); + + let source_only = use_source_only(); + let step_now = step(); + let name_error = validate_target_name(&name()); + let can_advance_type = name_error.is_none() && !target_type().trim().is_empty(); + let has_artifacts = !artifacts().is_empty() || !pending_files().is_empty(); + let optin = if source_only { + Vec::new() + } else { + optin_scans(&scans()) + }; // Live validation of the artifact reference being typed (empty = no error yet). let new_source_error = if new_source().is_empty() { None } else { validate_artifact_ref(&new_kind(), &new_source()) }; + let type_label = move |value: &str| kinds::target_type(value, lang); + let kind_label = move |value: &str| kinds::artifact_kind(value, lang); rsx! { PageHeader { - title: "Onboard a target", - description: "Add a target, attach its artifacts, and see which scans apply.", + title: tx::TITLE.get(lang), + description: tx::SUBTITLE.get(lang), } // Stepper. div { class: "wizard-steps", - for (i, label) in STEP_LABELS.iter().enumerate() { + for (i, label) in tx::STEPS.iter().enumerate() { div { class: if i == step_now { "wizard-step wizard-step-active" } else { "wizard-step" }, span { class: "wizard-step-dot", "{i + 1}" } - span { class: "wizard-step-label", "{label}" } + span { class: "wizard-step-label", {label.get(lang)} } } } } if let Some(err) = error() { div { class: "card", style: "border-color: var(--danger, #d33); margin-bottom: 12px;", - div { class: "card-header", "Error" } + div { class: "card-header", {tx::ERROR.get(lang)} } div { style: "padding: 12px;", "{err}" } } } @@ -213,13 +179,13 @@ pub fn OnboardingPage() -> Element { div { class: "card", // ---- Step 0: target type + name ---- if step_now == 0 { - div { class: "card-header", "What kind of software is this?" } + div { class: "card-header", {tx::WHAT_KIND.get(lang)} } div { style: "padding: 16px;", div { class: "form-group", - label { "Name" } + label { {tx::NAME.get(lang)} } input { r#type: "text", - placeholder: "acme-web", + placeholder: "sensor-node", value: "{name}", oninput: move |e| name.set(e.value()), } @@ -231,12 +197,12 @@ pub fn OnboardingPage() -> Element { } div { style: "display: flex; gap: 10px; align-items: center; flex-wrap: wrap; margin: 4px 0 8px; font-size: 0.9em; color: var(--text-secondary);", - span { "No target at hand? Start with the versioned demo set:" } + span { {tx::DEMO_PROMPT.get(lang)} } DemoTargetsButton { secondary: true } } div { style: "display: grid; grid-template-columns: repeat(auto-fill, minmax(200px, 1fr)); gap: 12px; margin-top: 12px;", - for (value, tlabel, tdesc) in TARGET_TYPES.iter().copied() { + for ((value, tlabel), hint) in kinds::TARGET_TYPES.into_iter().zip(tx::TYPE_HINTS) { div { class: "card", style: if target_type() == value { @@ -245,8 +211,8 @@ pub fn OnboardingPage() -> Element { "padding: 12px; cursor: pointer;" }, onclick: move |_| target_type.set(value.to_string()), - div { style: "font-weight: 600;", "{tlabel}" } - div { style: "font-size: 0.85em; opacity: 0.7;", "{tdesc}" } + div { style: "font-weight: 600;", {tlabel.get(lang)} } + div { style: "font-size: 0.85em; opacity: 0.7;", {hint.get(lang)} } } } } @@ -255,58 +221,35 @@ pub fn OnboardingPage() -> Element { // ---- Step 1: artifacts ---- if step_now == 1 { - div { class: "card-header", "Attach artifacts" } + div { class: "card-header", {tx::ATTACH.get(lang)} } if target_type() == "plc_sps" { div { style: "margin: 12px 16px 0; padding: 12px 14px; border-left: 3px solid var(--accent, #3b82f6); background: var(--surface-2, rgba(59,130,246,0.08)); font-size: 0.88em; line-height: 1.55;", - div { style: "font-weight: 600; margin-bottom: 4px;", "CODESYS / PLC projects" } - "Attach a " - b { "PLC project" } - " (PLCopen XML / ST, or a .projectarchive), or a " - b { "Git repository" } - " of exported source — every scan is then just a pull." - ul { style: "margin: 6px 0 0; padding-left: 18px;", - li { - b { "Control-logic SAST" } - " — commit " - b { "PLCopen XML exports" } - " (Project → Export PLCopenXML) or raw .st; ST and graphical FBD/LD are both analyzed." - } - li { - b { "Library + runtime SBOM" } - " — include the " - b { ".projectarchive" } - "; PLCopen XML alone carries no libraries." - } - li { - "Avoid committing only the binary " - code { ".project" } - " — it can't be parsed and doesn't diff." - } - } + div { style: "font-weight: 600; margin-bottom: 4px;", {tx::PLC_HINT_TITLE.get(lang)} } + {tx::PLC_HINT.get(lang)} } } div { style: "padding: 16px;", div { style: "display: flex; gap: 8px; flex-wrap: wrap; align-items: flex-end;", div { class: "form-group", style: "margin: 0;", - label { "Kind" } + label { {tx::KIND.get(lang)} } select { value: "{new_kind}", oninput: move |e| new_kind.set(e.value()), - for (value, klabel) in ARTIFACT_KINDS.iter().copied() { + for (value, klabel) in kinds::ARTIFACT_KINDS { if source_only && is_runtime_kind(value) { - option { value: "{value}", disabled: true, title: "{SOURCE_ONLY_NOTE}", - "{klabel} — {SOURCE_ONLY_NOTE}" + option { value: "{value}", disabled: true, title: common::NOT_AVAILABLE_HERE.get(lang), + "{klabel.get(lang)} — {common::NOT_AVAILABLE_HERE.get(lang)}" } } else { - option { value: "{value}", "{klabel}" } + option { value: "{value}", {klabel.get(lang)} } } } } } if is_file_kind(&new_kind()) { div { class: "form-group", style: "margin: 0; flex: 1; min-width: 240px;", - label { "File" } + label { {tx::FILE.get(lang)} } input { r#type: "file", onchange: move |evt| { @@ -329,7 +272,7 @@ pub fn OnboardingPage() -> Element { } if new_kind() == "plc_project" { div { class: "form-group", style: "margin: 0;", - label { "Format" } + label { {tx::FORMAT.get(lang)} } select { value: "{new_plc_format}", oninput: move |e| new_plc_format.set(e.value()), @@ -371,11 +314,11 @@ pub fn OnboardingPage() -> Element { new_file.set(None); } }, - "+ Add file" + {tx::ADD_FILE.get(lang)} } } else { div { class: "form-group", style: "margin: 0; flex: 1; min-width: 240px;", - label { "Reference (URL / path / text)" } + label { {tx::REFERENCE.get(lang)} } input { r#type: "text", placeholder: "https://git.example.com/acme.git", @@ -385,7 +328,7 @@ pub fn OnboardingPage() -> Element { } if new_kind() == "git_repo" { div { class: "form-group", style: "margin: 0;", - label { "Branch" } + label { {tx::BRANCH.get(lang)} } input { r#type: "text", value: "{new_branch}", @@ -411,14 +354,14 @@ pub fn OnboardingPage() -> Element { new_source.set(String::new()); } }, - "+ Add" + {tx::ADD.get(lang)} } } } if is_file_kind(&new_kind()) { if let Some((fname, data)) = new_file() { div { style: "font-size: 0.85em; opacity: 0.7; margin-top: 6px;", - "Selected: {fname} ({data.size()} bytes)" + "{tx::SELECTED.get(lang)}: {fname} ({format_bytes(data.size(), lang)})" } } } else if let Some(err) = new_source_error.clone() { @@ -429,13 +372,13 @@ pub fn OnboardingPage() -> Element { div { style: "display: flex; justify-content: space-between; align-items: center; padding: 8px 12px; border: 1px solid var(--border, #333); border-radius: 6px; margin-top: 6px;", span { - span { style: "opacity: 0.7;", "{kind_label(&pf.kind)} (file): " } - "{pf.filename} ({pf.file.size()} bytes)" + span { style: "opacity: 0.7;", "{kind_label(&pf.kind)} ({tx::FILE_SUFFIX.get(lang)}): " } + "{pf.filename} ({format_bytes(pf.file.size(), lang)})" } button { class: "btn btn-ghost-danger btn-sm", onclick: move |_| { pending_files.write().remove(i); }, - "Remove" + {tx::REMOVE.get(lang)} } } } @@ -452,12 +395,12 @@ pub fn OnboardingPage() -> Element { button { class: "btn btn-ghost-danger btn-sm", onclick: move |_| { artifacts.write().remove(i); }, - "Remove" + {tx::REMOVE.get(lang)} } } } } else { - div { style: "opacity: 0.6;", "No artifacts yet. Add at least one." } + div { style: "opacity: 0.6;", {tx::NO_ARTIFACTS.get(lang)} } } } } @@ -465,23 +408,32 @@ pub fn OnboardingPage() -> Element { // ---- Step 2: review + create ---- if step_now == 2 { - div { class: "card-header", "Review" } + div { class: "card-header", {tx::REVIEW.get(lang)} } div { style: "padding: 16px;", div { class: "wizard-summary", - div { strong { "Name: " } "{name()}" } - div { strong { "Type: " } "{type_label(&target_type())}" } - div { strong { "Artifacts:" } } + div { strong { "{tx::NAME.get(lang)}: " } "{name()}" } + div { strong { "{tx::TYPE.get(lang)}: " } "{type_label(&target_type())}" } + div { strong { "{tx::ARTIFACTS.get(lang)}:" } } ul { for a in artifacts() { li { "{kind_label(&a.kind)}: {a.source_ref}" } } + for pf in pending_files() { + li { "{kind_label(&pf.kind)}: {pf.filename} ({format_bytes(pf.file.size(), lang)})" } + } } } div { style: "margin-top: 12px; opacity: 0.7; font-size: 0.9em;", + {tx::REVIEW_NOTE.get(lang)} if source_only { - "The applicable scans (SAST / SBOM / firmware / PLC control logic) are shown after the target is created. DAST, pentest and live-device probes are not available in this environment." - } else { - "The applicable scans (SAST / DAST / firmware / PLC) are shown after the target is created." + " " + {tx::REVIEW_NOTE_SOURCE_ONLY.get(lang)} + } + } + if let Some((index, total, file)) = uploading() { + div { style: "margin-top: 12px; display: flex; gap: 8px; align-items: center;", + span { class: "spinner" } + "{tx::UPLOADING.get(lang)} {index}/{total}: {file}" } } } @@ -489,18 +441,46 @@ pub fn OnboardingPage() -> Element { // ---- Step 3: created ---- if step_now == 3 { - div { class: "card-header", "Target onboarded" } + div { class: "card-header", {tx::DONE.get(lang)} } div { style: "padding: 16px;", p { strong { "{name()}" } - " was created." + " {tx::CREATED.get(lang)}" if let Some(s) = suggested() { - span { " Suggested type from detection: " strong { "{type_label(&s)}" } "." } + span { " {tx::SUGGESTED.get(lang)} " strong { "{type_label(&s)}" } "." } } } - h4 { style: "margin-top: 16px;", "Applicable scans" } + if !upload_errors().is_empty() { + div { class: "card", style: "border-color: var(--danger, #d33); padding: 12px; margin: 12px 0;", + div { style: "font-weight: 600;", {tx::UPLOAD_FAILED.get(lang)} } + ul { style: "margin: 6px 0 6px 18px; padding: 0;", + for e in upload_errors() { + li { "{e}" } + } + } + div { style: "font-size: 0.9em;", {tx::UPLOAD_FAILED_HINT.get(lang)} } + } + } + match first_scan() { + FirstScan::Started => rsx! { + div { style: "margin-top: 8px; color: var(--success, #2a2);", {tx::SCAN_STARTED.get(lang)} } + }, + FirstScan::Failed(e) => rsx! { + div { style: "margin-top: 8px; color: var(--danger, #d33);", + "{tx::SCAN_START_FAILED.get(lang)}: {e}" + } + }, + FirstScan::Waiting => rsx! {}, + } + if first_scan() == FirstScan::Started { + if let Some(id) = created_id() { + h4 { style: "margin-top: 16px;", {tx::PROGRESS.get(lang)} } + ScanRunList { target_id: id } + } + } + h4 { style: "margin-top: 16px;", {tx::APPLICABLE_SCANS.get(lang)} } if scans().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)} } } else { for s in scans() { ScanRow { scan: s } @@ -508,19 +488,18 @@ pub fn OnboardingPage() -> Element { } if source_only { div { style: "margin-top: 12px; font-size: 0.9em;", - "Live-device probes (ICS/PLC runtime), DAST and pentest are skipped here" + {tx::SOURCE_ONLY_SKIPS.get(lang)} SourceOnlyNote { inline: true } } } - if !optin_scans.is_empty() { + if first_scan() != FirstScan::Started && !optin.is_empty() { div { style: "margin-top: 12px; padding: 10px; border: 1px dashed var(--border, #ccc); border-radius: 6px;", - div { style: "font-weight: 600; margin-bottom: 6px;", "Enable opt-in scans" } + div { style: "font-weight: 600; margin-bottom: 6px;", {tx::OPTIN_TITLE.get(lang)} } div { style: "opacity: 0.7; font-size: 0.85em; margin-bottom: 8px;", - "These are applicable but off by default (they touch a live device). Tick to enable before running." + {tx::OPTIN_HINT.get(lang)} } - for pair in optin_scans.clone() { + for (display, serde_name) in optin.clone() { { - let (display, serde_name) = pair; let cb_name = serde_name.clone(); rsx! { label { @@ -538,46 +517,53 @@ pub fn OnboardingPage() -> Element { enabled_extra.set(v); }, } - "Enable {display}" + "{tx::ENABLE.get(lang)} {display}" } } } } } } - if let Some(msg) = scan_msg() { - div { style: "margin-top: 8px; color: var(--success, #2a2);", "{msg}" } - } - div { style: "margin-top: 16px; display: flex; gap: 8px;", - button { - class: "btn btn-primary", - onclick: move |_| { - if let Some(id) = created_id() { - let extra = enabled_extra(); - scan_msg.set(Some("Scan triggered...".to_string())); - spawn(async move { - // Persist any ticked opt-in scans first, so the - // agent's build_scan_plan includes them this run. - if !extra.is_empty() { - if let Err(e) = - enable_target_scans(id.clone(), extra).await - { - scan_msg.set(Some(format!( - "Failed to enable opt-in scans: {e}" - ))); - return; + div { style: "margin-top: 16px; display: flex; gap: 8px; flex-wrap: wrap;", + if first_scan() != FirstScan::Started { + button { + class: "btn btn-primary", + onclick: move |_| { + if let Some(id) = created_id() { + let extra = enabled_extra(); + spawn(async move { + // Persist any ticked opt-in scans first, so the + // agent's build_scan_plan includes them this run. + if !extra.is_empty() { + if let Err(e) = + enable_target_scans(id.clone(), extra).await + { + first_scan.set(FirstScan::Failed(format!( + "{}: {e}", + tx::OPTIN_FAILED.get(lang) + ))); + return; + } } - } - match trigger_target_scan(id).await { - Ok(_) => scan_msg.set(Some( - "Scan started — findings will appear as it runs.".to_string(), - )), - Err(e) => scan_msg.set(Some(format!("Failed to start scan: {e}"))), - } - }); - } - }, - "Run scan" + first_scan.set(match trigger_target_scan(id).await { + Ok(_) => FirstScan::Started, + Err(e) => FirstScan::Failed(e.to_string()), + }); + }); + } + }, + {tx::RUN_SCAN.get(lang)} + } + } + if let Some(id) = created_id() { + Link { + to: Route::FindingsPage { target: id }, + class: "btn btn-secondary", + {tx::TO_FINDINGS.get(lang)} + } + } + Link { to: Route::TargetsPage {}, class: "btn btn-secondary", + {tx::TO_TARGETS.get(lang)} } button { class: "btn btn-secondary", @@ -585,17 +571,18 @@ pub fn OnboardingPage() -> Element { step.set(0); name.set(String::new()); target_type.set(String::new()); - description.set(String::new()); artifacts.write().clear(); pending_files.write().clear(); new_file.set(None); scans.write().clear(); suggested.set(None); created_id.set(None); - scan_msg.set(None); + first_scan.set(FirstScan::Waiting); + upload_errors.write().clear(); + enabled_extra.write().clear(); error.set(None); }, - "Onboard another" + {tx::ANOTHER.get(lang)} } } } @@ -607,16 +594,16 @@ pub fn OnboardingPage() -> Element { div { style: "display: flex; justify-content: space-between; margin-top: 16px;", button { class: "btn btn-back", - disabled: step_now == 0, + disabled: step_now == 0 || creating(), onclick: move |_| { if step() > 0 { step.set(step() - 1); } }, - "Back" + {tx::BACK.get(lang)} } if step_now < 2 { button { class: "btn btn-primary", disabled: (step_now == 0 && !can_advance_type) || (step_now == 1 && !has_artifacts), onclick: move |_| step.set(step() + 1), - "Next" + {tx::NEXT.get(lang)} } } else { button { @@ -625,63 +612,97 @@ pub fn OnboardingPage() -> Element { onclick: move |_| { let n = name(); let tt = target_type(); - let desc = description(); let arts = artifacts(); let files = pending_files(); - let d = if desc.trim().is_empty() { None } else { Some(desc) }; creating.set(true); error.set(None); + upload_errors.write().clear(); spawn(async move { - match create_target(n, tt, d, arts).await { - Ok(resp) => { - let id = resp - .data - .get("_id") - .and_then(|o| o.get("$oid")) - .and_then(|s| s.as_str()) - .map(String::from); - if let Some(id) = id { - created_id.set(Some(id.clone())); - // Upload staged file artifacts now that the target exists. - for pf in files { - let fname = pf.filename.clone(); - if let Err(e) = upload_target_artifact( - id.clone(), - pf.kind, - pf.plc_format, - pf.file.into(), - ) - .await - { - error.set(Some(format!( - "Upload failed for {fname}: {e}" - ))); - } - } - if let Ok(sc) = fetch_applicable_scans(id.clone()).await { - scans.set(sc.data.scans); - } - if let Ok(det) = detect_target(id).await { - suggested.set( - det.data - .get("classification") - .and_then(|c| c.get("suggested")) - .and_then(|s| s.as_str()) - .map(String::from), - ); - } - } - step.set(3); + let id = match create_target(n, tt, None, arts).await { + Ok(resp) => resp + .data + .get("_id") + .and_then(|o| o.get("$oid")) + .and_then(|s| s.as_str()) + .map(String::from), + Err(e) => { + error.set(Some(e.to_string())); + None + } + }; + let Some(id) = id else { + creating.set(false); + return; + }; + created_id.set(Some(id.clone())); + + // Upload the staged files now that the target exists. + let total = files.len(); + for (i, pf) in files.into_iter().enumerate() { + let fname = pf.filename.clone(); + uploading.set(Some((i + 1, total, fname.clone()))); + if let Err(e) = upload_target_artifact( + id.clone(), + pf.kind, + pf.plc_format, + pf.file.into(), + ) + .await + { + upload_errors.write().push(format!("{fname}: {e}")); } - Err(e) => error.set(Some(e.to_string())), } + uploading.set(None); + + let applicable = fetch_applicable_scans(id.clone()) + .await + .map(|sc| sc.data.scans) + .unwrap_or_default(); + if let Ok(det) = detect_target(id.clone()).await { + suggested.set( + det.data + .get("classification") + .and_then(|c| c.get("suggested")) + .and_then(|s| s.as_str()) + .map(String::from), + ); + } + // Start the first scan unless a file is missing or + // the user has opt-in scans to decide on first. + let offers_optin = !source_only && !optin_scans(&applicable).is_empty(); + scans.set(applicable); + if upload_errors.read().is_empty() && !offers_optin { + first_scan.set(match trigger_target_scan(id).await { + Ok(_) => FirstScan::Started, + Err(e) => FirstScan::Failed(e.to_string()), + }); + } + step.set(3); creating.set(false); }); }, - if creating() { "Creating..." } else { "Create target" } + if creating() { {tx::CREATING.get(lang)} } else { {tx::CREATE.get(lang)} } } } } } } } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn only_unblocked_default_off_scans_are_opt_in() { + let scans = vec![ + serde_json::json!({ "scan": "sast", "default_on": true }), + serde_json::json!({ "scan": "ics_probe", "default_on": false }), + serde_json::json!({ "scan": "dast", "default_on": false, "blocked_reason": "no URL" }), + ]; + assert_eq!( + optin_scans(&scans), + vec![("ics_probe".to_string(), "icsprobe".to_string())] + ); + } +}