From ecee3b5b50397b5d7138d79545c9b65ff5cfb4c8 Mon Sep 17 00:00:00 2001 From: Sharang Parnerkar <30073382+mighty840@users.noreply.github.com> Date: Mon, 28 Sep 2026 22:27:45 +0200 Subject: [PATCH 1/2] fix(dashboard): an expired sign-in sends you to the login instead of failing every page On staging every page said "konnten nicht geladen werden" while the data was intact: the agent rejected each request with an expired token, because the dashboard's token refresh was refused by Keycloak (invalid_grant) and it kept sending the stale token. - One refresh at a time per session. A page's parallel requests all refreshed with the same refresh token, and Keycloak, which rotates it, rejects every one after the first. A request that waited uses the token the other one got. - A refused refresh ends the sign-in: the session's user is removed and the server function answers session_expired. The app shell checks the sign-in every minute and on such an answer goes to the login; the auth check itself counts an unrefreshable sign-in as signed out. - A failure that is not about the sign-in shows its reason and a retry on the targets page, instead of a bare "could not be loaded". Co-Authored-By: Claude Opus 5.5 (1M context) Claude-Session: https://claude.ai/code/session_01EYKjxacrr6K88DruUmP48p --- compliance-dashboard/Cargo.toml | 2 +- compliance-dashboard/assets/main.css | 14 ++ .../src/components/app_shell.rs | 18 ++ compliance-dashboard/src/i18n/texts.rs | 4 + .../src/infrastructure/agent_client.rs | 172 +++++++++++++----- .../src/infrastructure/auth_check.rs | 39 +++- compliance-dashboard/src/pages/targets.rs | 26 ++- 7 files changed, 222 insertions(+), 53 deletions(-) diff --git a/compliance-dashboard/Cargo.toml b/compliance-dashboard/Cargo.toml index d4de885..1fbeb1e 100644 --- a/compliance-dashboard/Cargo.toml +++ b/compliance-dashboard/Cargo.toml @@ -54,7 +54,7 @@ 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"] } +web-sys = { version = "0.3", optional = true, features = ["Blob", "BlobPropertyBag", "HtmlAnchorElement", "Url", "Document", "Element", "Window", "Storage", "MediaQueryList", "Location"] } js-sys = { version = "0.3", optional = true } wasm-bindgen = { version = "0.2", optional = true } gloo-timers = { version = "0.3", features = ["futures"], optional = true } diff --git a/compliance-dashboard/assets/main.css b/compliance-dashboard/assets/main.css index 00ea04b..cd6bf1c 100644 --- a/compliance-dashboard/assets/main.css +++ b/compliance-dashboard/assets/main.css @@ -5058,3 +5058,17 @@ tbody tr:last-child td { flex: 1; min-width: 180px; } + +/* ── A list that could not be loaded: what happened, and a way to retry ── */ +.load-failed { + display: grid; + gap: 8px; + justify-items: start; +} + +.load-failed-reason { + font-family: var(--font-mono); + font-size: 12px; + color: var(--text-tertiary); + overflow-wrap: anywhere; +} diff --git a/compliance-dashboard/src/components/app_shell.rs b/compliance-dashboard/src/components/app_shell.rs index dc539c7..764f641 100644 --- a/compliance-dashboard/src/components/app_shell.rs +++ b/compliance-dashboard/src/components/app_shell.rs @@ -8,6 +8,10 @@ use crate::components::toast::{ToastContainer, Toasts}; use crate::infrastructure::auth_check::check_auth; use crate::infrastructure::platform::fetch_platform_info; +/// How often an open page checks that the sign-in is still valid. +#[cfg(feature = "web")] +const SIGN_IN_CHECK_MS: u32 = 60_000; + #[component] pub fn AppShell() -> Element { use_context_provider(Toasts::new); @@ -21,6 +25,20 @@ pub fn AppShell() -> Element { let auth = use_server_future(check_auth)?; let platform_now = platform().and_then(Result::ok).unwrap_or_default(); use_context_provider(|| Signal::new(platform_now)); + // A sign-in can run out while a page stays open: check now and then, and + // send the browser to the login rather than letting every page fail. + use_future(move || async move { + #[cfg(feature = "web")] + loop { + gloo_timers::future::TimeoutFuture::new(SIGN_IN_CHECK_MS).await; + if let Ok(info) = check_auth().await { + if !info.authenticated { + crate::infrastructure::auth_check::go_to_login(); + break; + } + } + } + }); match auth() { Some(Ok(info)) if info.authenticated => { diff --git a/compliance-dashboard/src/i18n/texts.rs b/compliance-dashboard/src/i18n/texts.rs index 60e3d2d..fa05e22 100644 --- a/compliance-dashboard/src/i18n/texts.rs +++ b/compliance-dashboard/src/i18n/texts.rs @@ -9,6 +9,10 @@ use super::Text; pub mod common { use super::Text; + pub const RETRY: Text = Text { + de: "Erneut versuchen", + en: "Try again", + }; pub const LOADING: Text = Text { de: "Wird geladen …", en: "Loading...", diff --git a/compliance-dashboard/src/infrastructure/agent_client.rs b/compliance-dashboard/src/infrastructure/agent_client.rs index 9ec5e1c..eb0b9c4 100644 --- a/compliance-dashboard/src/infrastructure/agent_client.rs +++ b/compliance-dashboard/src/infrastructure/agent_client.rs @@ -116,10 +116,94 @@ pub async fn agent_get(path: &str) -> Result>>>, +> = std::sync::LazyLock::new(Default::default); + +/// The refresh lock of the session `key`, dropping locks no request holds. +fn refresh_lock(key: &str) -> std::sync::Arc> { + let mut locks = REFRESH_LOCKS + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + locks.retain(|k, lock| k == key || std::sync::Arc::strong_count(lock) > 1); + locks.entry(key.to_string()).or_default().clone() +} + +/// The signed-in user with an access token that is still valid, refreshing +/// it when it is about to expire. `Ok(None)` when no one is signed in, or when +/// Keycloak refused the refresh: the sign-in has run out, and the session's +/// user is removed so the next check sends the browser to the login. +/// +/// # Errors +/// +/// The session could not be read. +pub(crate) async fn current_user( + state: &ServerState, + session: &tower_sessions::Session, +) -> Result, ServerFnError> { + let read = || async { + session + .get::(LOGGED_IN_USER_SESS_KEY) + .await + .map_err(|e| ServerFnError::new(format!("session read failed: {e}"))) + }; + let Some(user) = read().await? else { + return Ok(None); + }; + if !token_needs_refresh(&user.access_token) { + return Ok(Some(user)); + } + + let key = session.id().map(|id| id.to_string()).unwrap_or_default(); + let lock = refresh_lock(&key); + let _held = lock.lock().await; + // Another request of this session may have refreshed while this one + // waited: use its token. + let Some(mut user) = read().await? else { + return Ok(None); + }; + if !token_needs_refresh(&user.access_token) { + return Ok(Some(user)); + } + match refresh_tokens(state, &user.refresh_token).await { + Ok((access, refresh)) => { + user.access_token = access; + if let Some(refresh) = refresh { + user.refresh_token = refresh; + } + if let Err(e) = session.insert(LOGGED_IN_USER_SESS_KEY, &user).await { + tracing::warn!("Failed to persist refreshed tokens: {e}"); + } + Ok(Some(user)) + } + Err(RefreshError::Rejected(reason)) => { + tracing::info!("Sign-in expired, refresh rejected: {reason}"); + if let Err(e) = session + .remove::(LOGGED_IN_USER_SESS_KEY) + .await + { + tracing::warn!("Failed to clear the expired sign-in: {e}"); + } + Ok(None) + } + Err(RefreshError::Unreachable(reason)) => { + // Keycloak could not be asked: the stale token may still pass, + // and the next request tries again. + tracing::warn!("Token refresh failed: {reason}; sending current token anyway"); + Ok(Some(user)) + } + } +} + +/// Attach the signed-in user's bearer token when Keycloak is configured. +/// +/// # Errors +/// +/// [`super::auth_check::SESSION_EXPIRED`] when the sign-in has run out; the session could not be +/// read. async fn attach_token( req: reqwest::RequestBuilder, state: &ServerState, @@ -128,36 +212,10 @@ async fn attach_token( return Ok(req); } let session: tower_sessions::Session = FullstackContext::extract().await?; - let user: Option = session - .get(LOGGED_IN_USER_SESS_KEY) - .await - .map_err(|e| ServerFnError::new(format!("session read failed: {e}")))?; - let Some(mut user) = user else { - return Ok(req); - }; - - if token_needs_refresh(&user.access_token) { - tracing::debug!("Access token expired or near-expiring; refreshing"); - match refresh_tokens(state, &user.refresh_token).await { - Ok((new_access, new_refresh)) => { - user.access_token = new_access; - if let Some(rt) = new_refresh { - user.refresh_token = rt; - } - if let Err(e) = session.insert(LOGGED_IN_USER_SESS_KEY, &user).await { - tracing::warn!("Failed to persist refreshed tokens: {e}"); - } - } - Err(e) => { - tracing::warn!("Token refresh failed: {e}; sending current token anyway"); - // Fall through — the agent will 401 and the UI will - // prompt re-login. Better than failing the request at - // the dashboard layer with no helpful UX cue. - } - } + match current_user(state, &session).await? { + Some(user) => Ok(req.bearer_auth(user.access_token)), + None => Err(ServerFnError::new(super::auth_check::SESSION_EXPIRED)), } - - Ok(req.bearer_auth(user.access_token)) } /// Decode the JWT's payload (no signature verification — the agent @@ -181,18 +239,30 @@ fn token_needs_refresh(jwt: &str) -> bool { claims.exp - REFRESH_SKEW_SECS <= now } +/// Why a refresh gave no new token. +#[derive(Debug)] +enum RefreshError { + /// Keycloak refused it (the refresh token expired or was revoked): the + /// sign-in is over. + Rejected(String), + /// Keycloak could not be asked, or answered with something unreadable. + Unreachable(String), +} + /// Exchange a refresh_token for a new access_token. Returns the new /// access_token and (optionally) the new refresh_token KC issued. /// KC may rotate refresh_tokens on use; we honor whatever it sends. async fn refresh_tokens( state: &ServerState, refresh_token: &str, -) -> Result<(String, Option), String> { +) -> Result<(String, Option), RefreshError> { let kc = state .keycloak - .ok_or_else(|| "Keycloak not configured".to_string())?; + .ok_or_else(|| RefreshError::Unreachable("Keycloak not configured".to_string()))?; if refresh_token.is_empty() { - return Err("no refresh_token in session".to_string()); + return Err(RefreshError::Rejected( + "no refresh_token in session".to_string(), + )); } #[derive(serde::Deserialize)] @@ -210,18 +280,23 @@ async fn refresh_tokens( ]) .send() .await - .map_err(|e| format!("refresh request failed: {e}"))?; + .map_err(|e| RefreshError::Unreachable(format!("refresh request failed: {e}")))?; - if !resp.status().is_success() { - let status = resp.status(); + let status = resp.status(); + if status.is_client_error() { let body = resp.text().await.unwrap_or_default(); - return Err(format!("refresh rejected ({status}): {body}")); + return Err(RefreshError::Rejected(format!("{status}: {body}"))); + } + if !status.is_success() { + return Err(RefreshError::Unreachable(format!( + "refresh answered {status}" + ))); } let r: TokenResp = resp .json() .await - .map_err(|e| format!("refresh response parse failed: {e}"))?; + .map_err(|e| RefreshError::Unreachable(format!("refresh response parse failed: {e}")))?; Ok((r.access_token, r.refresh_token)) } @@ -229,6 +304,21 @@ async fn refresh_tokens( mod tests { use super::*; + #[test] + fn a_session_has_one_refresh_lock_and_unused_ones_go() { + let a = refresh_lock("session-a"); + assert!(std::sync::Arc::ptr_eq(&a, &refresh_lock("session-a"))); + drop(a); + let _b = refresh_lock("session-b"); + let locks = REFRESH_LOCKS + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + assert!( + !locks.contains_key("session-a"), + "a lock no one holds is dropped" + ); + } + #[test] fn a_refusal_says_what_the_agent_said() { let status = reqwest::StatusCode::BAD_REQUEST; diff --git a/compliance-dashboard/src/infrastructure/auth_check.rs b/compliance-dashboard/src/infrastructure/auth_check.rs index 338b9ee..cd7551e 100644 --- a/compliance-dashboard/src/infrastructure/auth_check.rs +++ b/compliance-dashboard/src/infrastructure/auth_check.rs @@ -1,6 +1,24 @@ use compliance_core::models::auth::AuthInfo; use dioxus::prelude::*; +/// What a server function answers when the user's sign-in has run out: the +/// Keycloak session is gone, so only a new login helps. +pub const SESSION_EXPIRED: &str = "session_expired"; + +/// Whether `error` says the sign-in has run out. +pub fn is_session_expired(error: &ServerFnError) -> bool { + error.to_string().contains(SESSION_EXPIRED) +} + +/// Send the browser to the login, which returns to the app afterwards (the +/// browser only; a no-op when rendering on the server). +pub fn go_to_login() { + #[cfg(feature = "web")] + if let Some(window) = web_sys::window() { + let _ = window.location().set_href("/auth"); + } +} + /// Check the current user's authentication state. /// /// Reads the tower-sessions session on the server and returns an @@ -8,7 +26,6 @@ use dioxus::prelude::*; /// exists, `authenticated` is `false` and all other fields are empty. #[server(endpoint = "check-auth")] pub async fn check_auth() -> Result { - use super::auth::LOGGED_IN_USER_SESS_KEY; use super::server_state::ServerState; use super::user_state::{portal_link, UserStateInner}; use dioxus_fullstack::FullstackContext; @@ -28,10 +45,9 @@ pub async fn check_auth() -> Result { let session: tower_sessions::Session = FullstackContext::extract().await?; - let user_state: Option = session - .get(LOGGED_IN_USER_SESS_KEY) - .await - .map_err(|e| ServerFnError::new(format!("session read failed: {e}")))?; + // A sign-in whose token can no longer be refreshed counts as signed out. + let user_state: Option = + super::agent_client::current_user(&state, &session).await?; match user_state { Some(u) => Ok(AuthInfo { @@ -49,3 +65,16 @@ pub async fn check_auth() -> Result { }), } } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn an_expired_sign_in_is_recognised_in_a_server_error() { + assert!(is_session_expired(&ServerFnError::new(SESSION_EXPIRED))); + assert!(!is_session_expired(&ServerFnError::new( + "name already in use (400)" + ))); + } +} diff --git a/compliance-dashboard/src/pages/targets.rs b/compliance-dashboard/src/pages/targets.rs index 3c95bbc..bae8bda 100644 --- a/compliance-dashboard/src/pages/targets.rs +++ b/compliance-dashboard/src/pages/targets.rs @@ -14,6 +14,7 @@ use crate::components::scan_runs::status_badge; use crate::components::toast::{ToastType, Toasts}; use crate::i18n::texts::{common, kinds, scans as scan_texts, targets as tx}; use crate::i18n::{format_ago, use_lang, Lang}; +use crate::infrastructure::auth_check::{go_to_login, is_session_expired}; use crate::infrastructure::evidence::fetch_compliance_summary; use crate::infrastructure::onboarding::{fetch_targets, trigger_target_scan}; use compliance_core::models::{ScanRun, ScanRunStatus}; @@ -65,7 +66,16 @@ pub fn TargetsPage() -> Element { let mut toasts = use_context::(); let navigator = use_navigator(); let mut scanning_ids = use_signal(Vec::::new); - let mut targets = use_resource(move || async move { fetch_targets().await.ok() }); + // A failure keeps its reason, to show it; an expired sign-in goes to the + // login instead. + let mut targets = use_resource(move || async move { + fetch_targets().await.map_err(|e| { + if is_session_expired(&e) { + go_to_login(); + } + e.to_string() + }) + }); let summary = use_resource(move || async move { fetch_compliance_summary().await.ok() }); let lang = use_lang()(); // While a scan runs, its status and finding count change: keep the list @@ -77,7 +87,7 @@ pub fn TargetsPage() -> Element { let running = targets .peek() .as_ref() - .and_then(|t| t.as_ref()) + .and_then(|t| t.as_ref().ok()) .is_some_and(|t| crate::infrastructure::onboarding::any_scan_running(&t.data)); if running { targets.restart(); @@ -108,7 +118,7 @@ pub fn TargetsPage() -> Element { .and_then(|r| r.counts) }; match &targets_snapshot { - Some(Some(resp)) if resp.data.is_empty() => rsx! { + Some(Ok(resp)) if resp.data.is_empty() => rsx! { div { class: "card targets-empty", p { {tx::EMPTY.get(lang)} } div { class: "targets-empty-actions", @@ -123,7 +133,7 @@ pub fn TargetsPage() -> Element { p { class: "targets-empty-hint", {tx::DEMO_HINT.get(lang)} } } }, - Some(Some(resp)) => rsx! { + Some(Ok(resp)) => rsx! { div { class: "card", div { class: "table-wrapper", table { class: "targets-table", @@ -219,8 +229,12 @@ pub fn TargetsPage() -> Element { } } }, - Some(None) => rsx! { - div { class: "card", p { {tx::LOAD_FAILED.get(lang)} } } + Some(Err(reason)) => rsx! { + div { class: "card load-failed", + p { {tx::LOAD_FAILED.get(lang)} } + p { class: "load-failed-reason", "{reason}" } + button { class: "btn btn-secondary", onclick: move |_| targets.restart(), {common::RETRY.get(lang)} } + } }, None => rsx! { div { class: "loading", {common::LOADING.get(lang)} } -- 2.54.1 From 1a28a80d835037c501a07a6c4babaf10dfdb221e Mon Sep 17 00:00:00 2001 From: Sharang Parnerkar <30073382+mighty840@users.noreply.github.com> Date: Mon, 28 Sep 2026 22:32:35 +0200 Subject: [PATCH 2/2] fix(dashboard): the evidence pack downloads a ZIP or says why not The download was a plain link. When the agent refused (an expired token, the Mongo outage), the route answered with the app's own page, and the browser saved that as .html: an empty white page. The button now fetches the pack in the page: a ZIP is saved under the server's file name; anything else shows "Das Nachweispaket konnte nicht erstellt werden" (with the server's reason when it gave one in words), and an expired sign-in goes to the login. The file picker's own button uses the dashboard's button style. Co-Authored-By: Claude Opus 5.5 (1M context) Claude-Session: https://claude.ai/code/session_01EYKjxacrr6K88DruUmP48p --- Cargo.lock | 1 + compliance-dashboard/Cargo.toml | 6 +- compliance-dashboard/assets/main.css | 23 ++++ .../src/components/evidence_button.rs | 123 ++++++++++++++++++ compliance-dashboard/src/components/mod.rs | 1 + compliance-dashboard/src/i18n/texts.rs | 8 ++ compliance-dashboard/src/pages/compliance.rs | 12 +- compliance-dashboard/src/pages/target.rs | 12 +- 8 files changed, 168 insertions(+), 18 deletions(-) create mode 100644 compliance-dashboard/src/components/evidence_button.rs 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), -- 2.54.1