fix(dashboard): an expired sign-in sends you to the login instead of failing every page
CI / Check (push) Skipped
CI / Detect Changes (pull_request) Skipped
CI / Deploy Agent (pull_request) Skipped
CI / Deploy Dashboard (pull_request) Skipped
CI / Deploy Docs (pull_request) Skipped
CI / Deploy MCP (pull_request) Skipped
CI / Check (pull_request) Canceled after 4m51s

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) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EYKjxacrr6K88DruUmP48p
This commit is contained in:
Sharang ParnerkarandClaude Opus 5.5 committed 2026-09-28 22:27:45 +02:00
1 parent 8972db0594
commit ecee3b5b50
7 files changed
+222 -53

No files matched your search

+1 -1
View File
@@ -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 }
+14
View File
@@ -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;
}
@@ -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 => {
+4
View File
@@ -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...",
@@ -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)"
)));
}
}
+20 -6
View File
@@ -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)} }