diff --git a/Cargo.lock b/Cargo.lock index 3cf91a4..98deeff 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -777,6 +777,7 @@ dependencies = [ "url", "uuid", "wasm-bindgen", + "wasm-bindgen-futures", "web-sys", ] diff --git a/compliance-dashboard/Cargo.toml b/compliance-dashboard/Cargo.toml index 1fbeb1e..5809113 100644 --- a/compliance-dashboard/Cargo.toml +++ b/compliance-dashboard/Cargo.toml @@ -12,7 +12,7 @@ path = "../bin/main.rs" workspace = true [features] -web = ["dioxus/web", "dioxus/router", "dioxus/fullstack", "dep:web-sys", "dep:js-sys", "dep:wasm-bindgen", "dep:gloo-timers"] +web = ["dioxus/web", "dioxus/router", "dioxus/fullstack", "dep:web-sys", "dep:js-sys", "dep:wasm-bindgen", "dep:wasm-bindgen-futures", "dep:gloo-timers"] server = [ "dioxus/server", "dioxus/router", @@ -54,9 +54,11 @@ thiserror = { workspace = true } # Web-only reqwest = { workspace = true, optional = true } -web-sys = { version = "0.3", optional = true, features = ["Blob", "BlobPropertyBag", "HtmlAnchorElement", "Url", "Document", "Element", "Window", "Storage", "MediaQueryList", "Location"] } +web-sys = { version = "0.3", optional = true, features = ["Blob", "BlobPropertyBag", "HtmlAnchorElement", "Url", "Document", "Element", "Window", "Storage", "MediaQueryList", "Location", "Request", "RequestInit", "Response", "Headers"] } js-sys = { version = "0.3", optional = true } wasm-bindgen = { version = "0.2", optional = true } +# Awaiting the browser's fetch for downloads that must report failures. +wasm-bindgen-futures = { version = "0.4", optional = true } gloo-timers = { version = "0.3", features = ["futures"], optional = true } # Server-only diff --git a/compliance-dashboard/assets/main.css b/compliance-dashboard/assets/main.css index cd6bf1c..93ec91b 100644 --- a/compliance-dashboard/assets/main.css +++ b/compliance-dashboard/assets/main.css @@ -5072,3 +5072,26 @@ tbody tr:last-child td { color: var(--text-tertiary); overflow-wrap: anywhere; } + + +/* The file picker's own button, in the dashboard's button style. */ +input[type="file"]::file-selector-button { + margin-right: 10px; + padding: 5px 12px; + font: 500 12.5px var(--font-body); + color: var(--text-primary); + background: var(--bg-elevated); + border: 1px solid var(--border-bright); + border-radius: var(--radius-sm); + cursor: pointer; + transition: border-color 0.15s var(--ease-out); +} + +input[type="file"]::file-selector-button:hover { + border-color: var(--accent); +} + +input[type="file"] { + font-size: 12.5px; + color: var(--text-tertiary); +} diff --git a/compliance-dashboard/src/components/evidence_button.rs b/compliance-dashboard/src/components/evidence_button.rs new file mode 100644 index 0000000..a70c0fe --- /dev/null +++ b/compliance-dashboard/src/components/evidence_button.rs @@ -0,0 +1,123 @@ +//! Download a target's evidence pack from inside the page, so a failure +//! shows as a message instead of saving the app's own page as a file. + +use dioxus::prelude::*; +use dioxus_free_icons::icons::bs_icons::BsDownload; +use dioxus_free_icons::Icon; + +use crate::components::toast::{ToastType, Toasts}; +use crate::i18n::texts::targets as tx; +use crate::i18n::use_lang; +use crate::infrastructure::evidence::evidence_pack_url; + +/// Why a download did not produce a ZIP. Only the browser build downloads. +#[derive(Debug, Clone, PartialEq)] +#[cfg_attr(not(feature = "web"), allow(dead_code))] +enum DownloadError { + /// The sign-in has run out. + SignedOut, + /// Anything else, with what the server said when it said it in words. + Failed(Option), +} + +/// The "Nachweispaket herunterladen" button for target `target_id`. +#[component] +pub fn EvidencePackButton(target_id: String) -> Element { + let lang = use_lang()(); + let mut toasts = use_context::(); + let mut busy = use_signal(|| false); + rsx! { + button { + class: "btn btn-secondary", + title: tx::EVIDENCE_HINT.get(lang), + disabled: busy(), + onclick: move |_| { + let url = evidence_pack_url(&target_id); + busy.set(true); + spawn(async move { + match download_zip(&url).await { + Ok(()) => {} + Err(DownloadError::SignedOut) => { + crate::infrastructure::auth_check::go_to_login(); + } + Err(DownloadError::Failed(detail)) => { + let text = match detail { + Some(d) => format!("{}: {d}", tx::EVIDENCE_FAILED.get(lang)), + None => tx::EVIDENCE_FAILED.get(lang).to_string(), + }; + toasts.push(ToastType::Error, text); + } + } + busy.set(false); + }); + }, + Icon { icon: BsDownload, width: 14, height: 14 } + if busy() { {tx::EVIDENCE_BUILDING.get(lang)} } else { {tx::EVIDENCE_PACK.get(lang)} } + } + } +} + +/// Fetch `url` and save the response as a file, but only when it is a ZIP. +#[cfg(feature = "web")] +async fn download_zip(url: &str) -> Result<(), DownloadError> { + use wasm_bindgen::JsCast; + use wasm_bindgen_futures::JsFuture; + + let failed = || DownloadError::Failed(None); + let window = web_sys::window().ok_or_else(failed)?; + let response: web_sys::Response = JsFuture::from(window.fetch_with_str(url)) + .await + .ok() + .and_then(|r| r.dyn_into().ok()) + .ok_or_else(failed)?; + let headers = response.headers(); + let header = |name: &str| headers.get(name).ok().flatten().unwrap_or_default(); + let is_zip = header("content-type").starts_with("application/zip"); + if !response.ok() || !is_zip { + // Only a plain-text answer is worth showing; a page is not. + let text = if header("content-type").starts_with("text/plain") { + match response.text() { + Ok(p) => JsFuture::from(p).await.ok().and_then(|t| t.as_string()), + Err(_) => None, + } + } else { + None + }; + let text = text.filter(|t| !t.trim().is_empty()); + if response.status() == 401 + || text + .as_deref() + .is_some_and(|t| t.contains(crate::infrastructure::auth_check::SESSION_EXPIRED)) + { + return Err(DownloadError::SignedOut); + } + return Err(DownloadError::Failed(text)); + } + let filename = header("content-disposition") + .split("filename=") + .nth(1) + .map(|f| f.trim_matches('"').to_string()) + .unwrap_or_else(|| "pruefwerk-evidence.zip".to_string()); + let blob: web_sys::Blob = JsFuture::from(response.blob().map_err(|_| failed())?) + .await + .ok() + .and_then(|b| b.dyn_into().ok()) + .ok_or_else(failed)?; + let object_url = web_sys::Url::create_object_url_with_blob(&blob).map_err(|_| failed())?; + let anchor: web_sys::HtmlAnchorElement = window + .document() + .and_then(|d| d.create_element("a").ok()) + .and_then(|e| e.dyn_into().ok()) + .ok_or_else(failed)?; + anchor.set_href(&object_url); + anchor.set_download(&filename); + anchor.click(); + let _ = web_sys::Url::revoke_object_url(&object_url); + Ok(()) +} + +/// Server rendering: downloads only happen in the browser. +#[cfg(not(feature = "web"))] +async fn download_zip(_url: &str) -> Result<(), DownloadError> { + Ok(()) +} diff --git a/compliance-dashboard/src/components/mod.rs b/compliance-dashboard/src/components/mod.rs index eb32580..1624191 100644 --- a/compliance-dashboard/src/components/mod.rs +++ b/compliance-dashboard/src/components/mod.rs @@ -6,6 +6,7 @@ pub mod code_snippet; pub mod copy_button; pub mod cra_bar; pub mod demo_targets; +pub mod evidence_button; pub mod file_tree; pub mod help_chat; pub mod lang_toggle; diff --git a/compliance-dashboard/src/i18n/texts.rs b/compliance-dashboard/src/i18n/texts.rs index fa05e22..21bce13 100644 --- a/compliance-dashboard/src/i18n/texts.rs +++ b/compliance-dashboard/src/i18n/texts.rs @@ -873,6 +873,14 @@ pub mod targets { de: "Hochgeladen. Starten Sie die Prüfung, um die Datei zu prüfen.", en: "Uploaded. Start a scan to check the file.", }; + pub const EVIDENCE_BUILDING: Text = Text { + de: "Wird erstellt …", + en: "Building...", + }; + pub const EVIDENCE_FAILED: Text = Text { + de: "Das Nachweispaket konnte nicht erstellt werden", + en: "The evidence pack could not be built", + }; } /// Target types and artifact kinds, keyed by their API value. diff --git a/compliance-dashboard/src/pages/compliance.rs b/compliance-dashboard/src/pages/compliance.rs index 18d4bd4..1aeaa31 100644 --- a/compliance-dashboard/src/pages/compliance.rs +++ b/compliance-dashboard/src/pages/compliance.rs @@ -4,14 +4,15 @@ use dioxus::prelude::*; -use dioxus_free_icons::icons::bs_icons::{BsArrowLeft, BsDownload}; +use dioxus_free_icons::icons::bs_icons::BsArrowLeft; use dioxus_free_icons::Icon; use crate::app::Route; use crate::components::cra_bar::CraBar; -use crate::i18n::texts::{common, compliance as tx, findings as ftx, targets as ttx}; +use crate::components::evidence_button::EvidencePackButton; +use crate::i18n::texts::{common, compliance as tx, findings as ftx}; use crate::i18n::{use_lang, Lang, Text}; -use crate::infrastructure::evidence::{evidence_pack_url, fetch_compliance, CraCounts}; +use crate::infrastructure::evidence::{fetch_compliance, CraCounts}; /// The label and badge of each control state, in the order the page lists /// them: violated first, requirements evidenced outside the code last. @@ -79,10 +80,7 @@ pub fn CompliancePage(id: String) -> Element { p { class: "target-head-meta", {tx::SUBTITLE.get(lang)} } } div { class: "target-head-actions", - a { class: "btn btn-secondary", href: evidence_pack_url(&id), download: "", - Icon { icon: BsDownload, width: 14, height: 14 } - {ttx::EVIDENCE_PACK.get(lang)} - } + EvidencePackButton { target_id: id.clone() } } } diff --git a/compliance-dashboard/src/pages/target.rs b/compliance-dashboard/src/pages/target.rs index 9776024..8d5b1f3 100644 --- a/compliance-dashboard/src/pages/target.rs +++ b/compliance-dashboard/src/pages/target.rs @@ -9,6 +9,7 @@ use dioxus_free_icons::Icon; use crate::app::Route; use crate::components::artifact_upload::ArtifactUpload; use crate::components::cra_bar::CraBar; +use crate::components::evidence_button::EvidencePackButton; use crate::components::manual_findings::ManualFindingsPanel; use crate::components::scan_coverage::ScanCoverage; use crate::components::scan_runs::ScanRunList; @@ -16,7 +17,7 @@ use crate::components::severity_badge::SeverityBadge; use crate::components::toast::{ToastType, Toasts}; use crate::i18n::texts::{common, kinds, targets as tx}; use crate::i18n::use_lang; -use crate::infrastructure::evidence::{evidence_pack_url, fetch_compliance, CraCounts}; +use crate::infrastructure::evidence::{fetch_compliance, CraCounts}; use crate::infrastructure::findings::{fetch_findings, location, FindingsQuery}; use crate::infrastructure::onboarding::{ delete_target, fetch_applicable_scans, fetch_target, is_file_kind, set_archive_password, @@ -160,14 +161,7 @@ pub fn TargetPage(id: String) -> Element { Icon { icon: BsPlayFill, width: 16, height: 16 } {tx::RUN_SCAN.get(lang)} } - a { - class: "btn btn-secondary", - href: evidence_pack_url(&id), - download: "", - title: tx::EVIDENCE_HINT.get(lang), - Icon { icon: BsDownload, width: 14, height: 14 } - {tx::EVIDENCE_PACK.get(lang)} - } + EvidencePackButton { target_id: id.clone() } button { class: "btn btn-ghost", onclick: move |_| editing.set(true),