fix(dashboard): an expired sign-in goes to the login, and the evidence pack says why it failed #418
No files matched your search
Generated
+1
@@ -777,6 +777,7 @@ dependencies = [
|
||||
"url",
|
||||
"uuid",
|
||||
"wasm-bindgen",
|
||||
"wasm-bindgen-futures",
|
||||
"web-sys",
|
||||
]
|
||||
|
||||
|
||||
@@ -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"] }
|
||||
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
|
||||
|
||||
@@ -5058,3 +5058,40 @@ 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;
|
||||
}
|
||||
|
||||
|
||||
/* 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);
|
||||
}
|
||||
@@ -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 => {
|
||||
|
||||
@@ -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<String>),
|
||||
}
|
||||
|
||||
/// 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::<Toasts>();
|
||||
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(())
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
@@ -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...",
|
||||
@@ -869,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.
|
||||
|
||||
@@ -116,10 +116,94 @@ pub async fn agent_get(path: &str) -> Result<reqwest::RequestBuilder, ServerFnEr
|
||||
agent_request(Method::GET, path).await
|
||||
}
|
||||
|
||||
/// Attach the session's bearer token if Keycloak is configured AND the
|
||||
/// session has a logged-in user. Refresh the token proactively if it's
|
||||
/// expired or about to expire. Persists refreshed tokens back into the
|
||||
/// session.
|
||||
/// One refresh at a time per session: the requests a page makes at once
|
||||
/// would otherwise all refresh with the same refresh token, and Keycloak,
|
||||
/// which rotates it, rejects every one after the first (`invalid_grant`).
|
||||
static REFRESH_LOCKS: std::sync::LazyLock<
|
||||
std::sync::Mutex<std::collections::HashMap<String, std::sync::Arc<tokio::sync::Mutex<()>>>>,
|
||||
> = 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<tokio::sync::Mutex<()>> {
|
||||
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<Option<UserStateInner>, ServerFnError> {
|
||||
let read = || async {
|
||||
session
|
||||
.get::<UserStateInner>(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::<UserStateInner>(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<UserStateInner> = 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>), String> {
|
||||
) -> Result<(String, Option<String>), 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;
|
||||
|
||||
@@ -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<AuthInfo, ServerFnError> {
|
||||
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<AuthInfo, ServerFnError> {
|
||||
|
||||
let session: tower_sessions::Session = FullstackContext::extract().await?;
|
||||
|
||||
let user_state: Option<UserStateInner> = 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<UserStateInner> =
|
||||
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<AuthInfo, ServerFnError> {
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
#[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)"
|
||||
)));
|
||||
}
|
||||
}
|
||||
@@ -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() }
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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),
|
||||
|
||||
@@ -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::<Toasts>();
|
||||
let navigator = use_navigator();
|
||||
let mut scanning_ids = use_signal(Vec::<String>::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)} }
|
||||
|
||||
Reference in new issue
Block a user