From 08994cc7ec0b5209abc4be71e9b02cc4ed00df3f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Fri, 11 Sep 2026 08:54:13 +0300 Subject: [PATCH] im: live session-revocation logout - LiveEvent::Revoked { user_id, session_hash } broadcast from EVERY write path (admin revoke/disable/delete, self revoke, password change revoke-except, reset redeem, sign-out-everywhere) - /live keeps connect-time identity; targeted 'revoked' SSE event only to the killed session's connections; password change spares the asking tab - /directory/live emits revoked {"sub"}; DirectoryMember gains disabled - client: revoked event or /api/me 401 on SSE error -> hard navigate to / - new GET /api/me (204/401) - fix: admin disable never wrote the disabled flag (regression at HEAD) --- crates/im-core/src/sessions.rs | 14 +- crates/im-web/src/admin.rs | 12 + crates/im-web/src/auth.rs | 48 +++- crates/im-web/src/directory.rs | 128 +++++++++- crates/im-web/src/layout.rs | 14 +- crates/im-web/src/live.rs | 442 +++++++++++++++++++++++++++++---- crates/im-web/src/server.rs | 21 +- 7 files changed, 611 insertions(+), 68 deletions(-) diff --git a/crates/im-core/src/sessions.rs b/crates/im-core/src/sessions.rs index 6766535..a00ff06 100644 --- a/crates/im-core/src/sessions.rs +++ b/crates/im-core/src/sessions.rs @@ -298,12 +298,15 @@ pub async fn revoke_user_sessions(store: &Store, user: &UserId) -> Result { /// A password change's revoke: every session dies except the one holding the /// form — the browser that just proved the old password stays signed in, and -/// every other device (and every app token born of them) is out. +/// every other device (and every app token born of them) is out. The dead +/// sessions' token hashes come back, so the caller can address the eviction +/// news: a live connection only leaves when the hash it holds is among +/// these, and the asking browser's never is. pub async fn revoke_user_sessions_except( store: &Store, user: &UserId, keep_token: &str, -) -> Result { +) -> Result> { let keep = hash_token(keep_token); let hashes = { let conn = store.conn.lock().await; @@ -321,7 +324,6 @@ pub async fn revoke_user_sessions_except( } hashes }; - let count = hashes.len() as u64; for hash in &hashes { revoke_session_hash(store, hash).await?; } @@ -343,7 +345,7 @@ pub async fn revoke_user_sessions_except( ) .await .map_err(backend)?; - Ok(count) + Ok(hashes) } #[cfg(test)] @@ -400,10 +402,10 @@ mod tests { .await .unwrap(); - let count = revoke_user_sessions_except(&store, &user_id, mine.expose()) + let revoked = revoke_user_sessions_except(&store, &user_id, mine.expose()) .await .unwrap(); - assert_eq!(count, 1); + assert_eq!(revoked, vec![hash_token(other.expose())]); assert!( resolve_session(&store, mine.expose()) .await diff --git a/crates/im-web/src/admin.rs b/crates/im-web/src/admin.rs index 29b0f87..22ebe89 100644 --- a/crates/im-web/src/admin.rs +++ b/crates/im-web/src/admin.rs @@ -1677,6 +1677,9 @@ async fn delete(cx: &Cx, Form(input): Form) -> Result { .await? .map(|u| u.email); accounts::delete_user(store, &user_id).await?; + // The person is gone; their sessions went with them, and their tabs + // hear it here. + server::note_revoked(cx, user_id.as_str(), None).await; server::log_event(cx, "user_deleted", Some(&me.email), email.as_deref()).await; back(cx, "users", "&ok=deleted") } @@ -1694,6 +1697,8 @@ async fn revoke(cx: &Cx, Form(input): Form) -> Result { let store = &app(cx).store; let user_id = UserId::from(input.user); let sessions = im_core::sessions::revoke_user_sessions(store, &user_id).await?; + // Every session of theirs died; their open tabs each hear it and leave. + server::note_revoked(cx, user_id.as_str(), None).await; let email = accounts::user_by_id(store, &user_id) .await? .map(|u| u.email); @@ -1728,6 +1733,7 @@ async fn session_revoke(cx: &Cx, Form(input): Form) -> Result if !im_core::sessions::revoke_owned_session(&app(cx).store, &user_id, &input.session).await? { return back(cx, "users", "&error=session_unknown"); } + server::note_revoked(cx, user_id.as_str(), Some(&input.session)).await; server::log_event(cx, "session_revoked", Some(&me.email), Some(&input.user)).await; back(cx, "users", "&ok=session_revoked") } @@ -1749,9 +1755,15 @@ async fn set_disabled(cx: &Cx, input: UserAction, disabled: bool) -> Result Redirect { /// tidied. Where the browser goes next is each route's own business. async fn sign_out_everywhere(cx: &Cx) -> Result<()> { if let Some(token) = server::presented_session(cx) { - let email = im_core::sessions::resolve_session(&server::app(cx).store, &token) + let user = im_core::sessions::resolve_session(&server::app(cx).store, &token) .await? - .map(|u| u.email); + .map(|u| (u.id, u.email)); im_core::sessions::revoke_session(&server::app(cx).store, &token).await?; - server::log_event(cx, "logout", email.as_deref(), None).await; + // The eviction news is addressed to the dying session's own + // connection, so its tab leaves at once instead of at the next + // full refetch. + if let Some((id, _)) = &user { + server::note_revoked(cx, id.as_str(), Some(&im_core::accounts::hash_token(&token))) + .await; + } + server::log_event( + cx, + "logout", + user.as_ref().map(|(_, email)| email.as_str()), + None, + ) + .await; } server::clear_session_cookie(cx); Ok(()) @@ -326,6 +340,19 @@ async fn logout_return(cx: &Cx) -> Redirect { see(logout_target(back.as_deref(), &services)) } +/// The signed-in probe behind the live channel's error path: a tab whose +/// stream died asks here whether its session still stands, and the bare +/// status — no HTML, no redirect — is the whole answer. 204 signed in, +/// 401 not. +#[route(GET "/api/me")] +async fn me_probe(cx: &Cx) -> topcoat::Result { + if server::current_user(cx).await.is_some() { + (StatusCode::NO_CONTENT, "").into_response(cx) + } else { + (StatusCode::UNAUTHORIZED, "").into_response(cx) + } +} + #[derive(Deserialize)] pub struct ForgotForm { email: String, @@ -374,6 +401,9 @@ async fn reset(cx: &Cx, Form(input): Form) -> Redirect { let store = &server::app(cx).store; match accounts::redeem_reset(store, &input.token, &input.password).await { Ok(user) => { + // redeem_reset swept every session of theirs inside the core; + // their tabs hear the eviction here. + server::note_revoked(cx, user.id.as_str(), None).await; server::log_event(cx, "password_reset", Some(&user.email), None).await; see("/login?ok=reset".to_string()) } @@ -522,6 +552,9 @@ async fn revoke_session(cx: &Cx, Form(input): Form) -> Redire && im_core::accounts::hash_token(&presented) == input.session { im_core::sessions::revoke_session(store, &presented).await?; + // The news is addressed to this very session; this tab hears its + // own eviction and goes home like any other. + server::note_revoked(cx, user.id.as_str(), Some(&input.session)).await; server::clear_session_cookie(cx); return see("/".to_string()); } @@ -535,6 +568,7 @@ async fn revoke_session(cx: &Cx, Form(input): Form) -> Redire if !im_core::sessions::revoke_owned_session(store, &user.id, &input.session).await? { return see("/?section=sessions&error=session_unknown".to_string()); } + server::note_revoked(cx, user.id.as_str(), Some(&input.session)).await; server::log_event(cx, "session_revoked", Some(&user.email), ip.as_deref()).await; see("/?section=sessions&ok=session_revoked".to_string()) } @@ -623,7 +657,13 @@ async fn password(cx: &Cx, Form(input): Form) -> Redirect { Err(e) => return Err(topcoat::Error::from(std::io::Error::other(e.to_string()))), } if let Some(token) = server::presented_session(cx) { - im_core::sessions::revoke_user_sessions_except(store, &me.id, &token).await?; + let revoked = im_core::sessions::revoke_user_sessions_except(store, &me.id, &token) + .await?; + // Each dead session's own tab hears its eviction; the asking + // browser's hash is never among them, so this tab stays. + for hash in &revoked { + server::note_revoked(cx, me.id.as_str(), Some(hash)).await; + } } server::log_event(cx, "password_changed", Some(&me.email), None).await; see("/?section=password&ok=password".to_string()) diff --git a/crates/im-web/src/directory.rs b/crates/im-web/src/directory.rs index 10196f2..38e3009 100644 --- a/crates/im-web/src/directory.rs +++ b/crates/im-web/src/directory.rs @@ -34,6 +34,11 @@ pub struct DirectoryMember { /// side only serializes — the field is always written — so the serde /// default lives on the SDK's reading half. pub timezone: String, + /// Whether im has switched the member off. Always written; older + /// readers take the serde default — a member whose flag they cannot + /// see reads as present-and-enabled, which it was. + #[serde(default)] + pub disabled: bool, } impl DirectoryMember { @@ -46,6 +51,7 @@ impl DirectoryMember { admin: user.admin, photo_version: user.photo_version, timezone: user.timezone.clone(), + disabled: user.disabled, } } } @@ -80,7 +86,8 @@ async fn directory(cx: &Cx) -> topcoat::Result topcoat::Result { if server::app_client(cx).await.is_none() { @@ -144,6 +151,18 @@ async fn directory_live(cx: &Cx) -> topcoat::Result member, + // A sign-out in motion: every app watching the roster + // hears which subject just lost its sessions, and sends + // its own signed-in tabs of that subject home. Which + // session died is im's own business. + Ok(Some(Ok(server::LiveEvent::Revoked { user_id, .. }))) => { + return Some(( + Ok(Event::new().event("revoked").data( + serde_json::json!({ "sub": user_id }).to_string(), + )), + (rx, deadline, stopping, first), + )); + } }; // A member that will not serialize cannot happen — plain // fields all the way down — but a stream cannot panic on @@ -1532,4 +1551,111 @@ mod tests { .unwrap(); assert_eq!(reloaded.timezone, "UTC-05:00", "nothing half-written"); } + + /// The eviction rides the roster stream too: a revoke announces the + /// subject whose sessions died, and a disable follows with a Profile + /// frame whose `disabled` flag is set — the two cues a sibling needs + /// to send that subject's tabs home and drop them from its copy. + #[tokio::test] + async fn a_revoke_and_a_disable_ride_the_directory_stream() { + /// The next body frame off the stream, as text. Bounded, so a + /// regression fails loudly instead of hanging the suite. + async fn next_chunk( + stream: &mut std::pin::Pin>, + ) -> String { + use futures_util::StreamExt as _; + let chunk = tokio::time::timeout( + std::time::Duration::from_secs(20), + stream.as_mut().next(), + ) + .await + .expect("a frame arrives in time") + .expect("stream stays open") + .expect("frames succeed"); + String::from_utf8_lossy(&chunk).into_owned() + } + + let Setup { + router, + client_id, + secret, + store, + .. + } = setup().await; + let ada = im_core::accounts::user_by_email(&store, "ada@example.com") + .await + .unwrap() + .unwrap(); + let ben = im_core::accounts::user_by_email(&store, "ben@example.com") + .await + .unwrap() + .unwrap(); + let ada_session = + im_core::sessions::create_session(&store, &ada.id, &Default::default()) + .await + .unwrap(); + + // Open the roster stream as an app would, past the reconnection hint. + let response = router + .handle( + http::Request::builder() + .uri("/directory/live") + .header(header::AUTHORIZATION, basic(&client_id, &secret)) + .body(Body::empty()) + .unwrap(), + ) + .await; + let (parts, body) = response.into_parts(); + assert_eq!(parts.status, StatusCode::OK); + let mut stream = Box::pin(body.into_data_stream()); + let mut wire = String::new(); + while !wire.contains("retry: 5000") { + wire.push_str(&next_chunk(&mut stream).await); + } + + // Revoke ben everywhere: the roster names the subject, nothing more. + let admin_cookie = format!("{SESSION_COOKIE}={}", ada_session.expose()); + let (status, location, _) = post_form( + &router, + "/admin/revoke", + &format!("user={}", ben.id), + Some(&admin_cookie), + ) + .await; + assert_eq!(status, StatusCode::SEE_OTHER); + assert_eq!(location.as_deref(), Some("/admin?section=users&ok=revoked")); + wire.clear(); + while !wire.contains("event: revoked") { + wire.push_str(&next_chunk(&mut stream).await); + } + assert!(wire.contains(&format!("\"sub\":\"{}\"", ben.id))); + + // Disable ben: the revoked cue again, then the row itself with the + // flag set — and the roster no longer lists them. + let (status, _, _) = post_form( + &router, + "/admin/disable", + &format!("user={}", ben.id), + Some(&admin_cookie), + ) + .await; + assert_eq!(status, StatusCode::SEE_OTHER); + wire.clear(); + while !wire.contains("\"disabled\":true") { + wire.push_str(&next_chunk(&mut stream).await); + } + assert!(wire.contains("event: profile"), "{wire}"); + + let (status, body) = get(&router, Some(basic(&client_id, &secret))).await; + assert_eq!(status, StatusCode::OK); + let roster: serde_json::Value = serde_json::from_str(&body).unwrap(); + assert!( + !roster + .as_array() + .unwrap() + .iter() + .any(|member| member["sub"] == ben.id.to_string()), + "the disabled member leaves the roster" + ); + } } diff --git a/crates/im-web/src/layout.rs b/crates/im-web/src/layout.rs index 4fba4fd..06de337 100644 --- a/crates/im-web/src/layout.rs +++ b/crates/im-web/src/layout.rs @@ -462,7 +462,9 @@ pub async fn soft_nav_script(cx: &Cx) -> Result { /// moved; the page re-fetches itself through the ordinary route — where the /// ordinary gate answers — and morphs with fields and scroll intact. A /// focused field freezes the refresh mid-typing. Mounted only for a signed-in -/// viewer, so auth screens never reconnect against a 401. +/// viewer, so auth screens never reconnect against a 401. A `revoked` +/// frame — the eviction news, addressed — or a probe answering 401 sends +/// the tab home instead of re-reading. pub async fn live_script(cx: &Cx) -> Result { use topcoat::view::Unescaped; const JS: &str = r#"(function () { @@ -476,6 +478,16 @@ pub async fn live_script(cx: &Cx) -> Result { try { var src = new EventSource('/live'); src.onmessage = function () { schedule(); }; + // A sign-out in motion: this tab's own session was revoked — go home. + src.addEventListener('revoked', function () { location.href = '/'; }); + // A dropped stream reconnects by itself, but one that keeps dying + // against a revoked session is news: the bare probe says whether the + // session still stands. + src.onerror = function () { + fetch('/api/me').then(function (r) { + if (r.status === 401) { location.href = '/'; } + }).catch(function () {}); + }; } catch (err) {} })();"#; Ok(view! { cx => }) diff --git a/crates/im-web/src/live.rs b/crates/im-web/src/live.rs index 198ce92..d6ede1a 100644 --- a/crates/im-web/src/live.rs +++ b/crates/im-web/src/live.rs @@ -1,11 +1,12 @@ //! The live channel: one long-lived connection per open signed-in tab, //! carrying the news that something changed — ported from iz's `live.rs`. //! -//! What travels here is a bare tick and nothing else — never a row, never a -//! name. The client is told only *that* the page moved, and re-fetches it -//! through the ordinary route, where the ordinary gate answers. Every page -//! behind it needs the same session the stream asked for, so there is no -//! per-topic filtering to get wrong. +//! What travels here is a bare tick — "the page moved, re-read it" — and one +//! addressed frame: a `revoked` event whose emptiness is the whole message, +//! sent only to the connection the eviction names. A revoked tab does not +//! re-read (its session would refuse it); it goes home. Everything else +//! stays nameless: the client re-fetches through the ordinary route, where +//! the ordinary gate answers. use std::time::{Duration, Instant}; @@ -39,68 +40,96 @@ pub struct Shutdown(pub tokio::sync::watch::Receiver); #[route(GET "/live")] async fn live(cx: &Cx) -> topcoat::Result { // Resolved once, here, and never again for the life of this connection. - let Ok(_user) = server::current_user(cx).await.ok_or(()) else { + // Both halves stay: the id and the session's token hash are the address + // a `Revoked` announcement is checked against — the eviction news is + // addressed, and this connection reads its own address off it. + let Ok(user) = server::current_user(cx).await.ok_or(()) else { return (StatusCode::UNAUTHORIZED, "").into_response(cx); }; + let me = user.id.to_string(); + let mine = server::presented_session(cx) + .as_deref() + .map(im_core::accounts::hash_token); let rx = server::app(cx).live.subscribe(); let stopping = topcoat::context::try_app_context::(cx).map(|s| s.0.clone()); let deadline = Instant::now() + WINDOW; let events = futures_util::stream::unfold( - (rx, deadline, stopping), - |(mut rx, deadline, mut stopping)| async move { - // Already going down: end, so this connection is not one the - // shutdown has to sit and wait out. - if stopping.as_ref().is_some_and(|watch| *watch.borrow()) { - return None; - } - let left = deadline.saturating_duration_since(Instant::now()); - if left.is_zero() { - return None; - } - // Three things end the wait: an announcement, the window - // running out, and the server being told to stop. The third - // is watched rather than polled, so SIGTERM is felt at once. - let heard = tokio::time::timeout(left, async { - match stopping.as_mut() { - Some(watch) => tokio::select! { - _ = watch.changed() => None, - got = rx.recv() => Some(got), - }, - None => Some(rx.recv().await), + (rx, deadline, stopping, me, mine), + |(mut rx, deadline, mut stopping, me, mine)| async move { + loop { + // Already going down: end, so this connection is not one the + // shutdown has to sit and wait out. + if stopping.as_ref().is_some_and(|watch| *watch.borrow()) { + return None; } - }) - .await; - match heard { - // The window closed, or the server is stopping. Ending - // the stream is the point: the browser reconnects by - // itself and authenticates again. - Err(_) | Ok(None) => return None, - // The broadcaster is gone, which means the process is - // going with it. - Ok(Some(Err(RecvError::Closed))) => return None, - // This reader fell behind and announcements were dropped. - // Which ones is unknowable, so the tick says "re-read - // everything" — the client refetches the whole page, so - // a lagged tick and a plain tick are the same frame. - Ok(Some(Err(RecvError::Lagged(_)))) | Ok(Some(Ok(server::LiveEvent::Tick))) => {} - // One member's row changed. The frame names which one — - // im's own client still just re-fetches the page it is - // on, so the payload is forward-compatibility for a - // future page that can react to its own subject alone. - Ok(Some(Ok(server::LiveEvent::Profile(member)))) => { - return Some(( - Ok::<_, std::convert::Infallible>(Event::new().data( - serde_json::json!({ "kind": "profile", "sub": member.sub }) - .to_string(), - )), - (rx, deadline, stopping), - )); + let left = deadline.saturating_duration_since(Instant::now()); + if left.is_zero() { + return None; + } + // Three things end the wait: an announcement, the window + // running out, and the server being told to stop. The third + // is watched rather than polled, so SIGTERM is felt at once. + let heard = tokio::time::timeout(left, async { + match stopping.as_mut() { + Some(watch) => tokio::select! { + _ = watch.changed() => None, + got = rx.recv() => Some(got), + }, + None => Some(rx.recv().await), + } + }) + .await; + match heard { + // The window closed, or the server is stopping. Ending + // the stream is the point: the browser reconnects by + // itself and authenticates again. + Err(_) | Ok(None) => return None, + // The broadcaster is gone, which means the process is + // going with it. + Ok(Some(Err(RecvError::Closed))) => return None, + // This reader fell behind and announcements were dropped. + // Which ones is unknowable, so the tick says "re-read + // everything" — the client refetches the whole page, so + // a lagged tick and a plain tick are the same frame. + Ok(Some(Err(RecvError::Lagged(_)))) + | Ok(Some(Ok(server::LiveEvent::Tick))) => break, + // One member's row changed. The frame names which one — + // im's own client still just re-fetches the page it is + // on, so the payload is forward-compatibility for a + // future page that can react to its own subject alone. + Ok(Some(Ok(server::LiveEvent::Profile(member)))) => { + return Some(( + Ok::<_, std::convert::Infallible>(Event::new().data( + serde_json::json!({ "kind": "profile", "sub": member.sub }) + .to_string(), + )), + (rx, deadline, stopping, me, mine), + )); + } + // A sign-out in motion: every session of the named user, + // or the one named session. Addressed news — this + // connection answers only when it is the one evicted; + // anyone else's news is silence here. + Ok(Some(Ok(server::LiveEvent::Revoked { + user_id, + session_hash, + }))) => { + let evicted = session_hash + .as_deref() + .is_none_or(|hash| mine.as_deref() == Some(hash)); + if user_id == me && evicted { + return Some(( + Ok(Event::new().event("revoked").data("")), + (rx, deadline, stopping, me, mine), + )); + } + } } } Some(( Ok::<_, std::convert::Infallible>(Event::new().data("{}")), - (rx, deadline, stopping), + (rx, deadline, stopping, me, mine), )) }, ); @@ -109,3 +138,306 @@ async fn live(cx: &Cx) -> topcoat::Result { .keep_alive(KeepAlive::new()) .into_response(cx) } + +#[cfg(test)] +mod tests { + use std::path::Path; + use std::pin::Pin; + use std::sync::Arc; + + use futures_util::StreamExt as _; + use im_core::accounts::{create_invite, create_user_from_invite, hash_token}; + use im_core::model::UserId; + use im_core::sessions::{SessionMeta, create_session, resolve_session}; + use im_core::store::Store; + use topcoat::cookie::RouterBuilderCookieExt as _; + use topcoat::router::{ + Body, BodyDataStream, Router, RouterBuilderDiscoverExt as _, StatusCode, header, to_bytes, + }; + + use crate::config::Config; + use crate::server::{self, SESSION_COOKIE}; + + struct Setup { + router: Router, + store: Arc, + admin_cookie: String, + /// Ben's two sessions, by raw token — each opens its own `/live` + /// connection through its cookie. + ben_tokens: [String; 2], + ben_id: UserId, + } + + async fn setup() -> Setup { + let store = Store::open(Path::new(":memory:")).await.unwrap(); + let admin_invite = create_invite(&store, "ada@example.com", None, true) + .await + .unwrap(); + let admin = create_user_from_invite(&store, admin_invite.expose(), "Ada", "tDLr9!mZQ2xv") + .await + .unwrap(); + let ben_invite = create_invite(&store, "ben@example.com", None, false) + .await + .unwrap(); + let ben = create_user_from_invite(&store, ben_invite.expose(), "Ben", "tDLr9!mZQ2xv") + .await + .unwrap(); + let admin_session = create_session(&store, &admin.id, &SessionMeta::default()) + .await + .unwrap(); + let ben_a = create_session(&store, &ben.id, &SessionMeta::default()) + .await + .unwrap(); + let ben_b = create_session(&store, &ben.id, &SessionMeta::default()) + .await + .unwrap(); + let store = Arc::new(store); + let app = server::App { + store: store.clone(), + config: Config { + database: ":memory:".into(), + listen: "127.0.0.1:7650".parse().unwrap(), + issuer: "http://127.0.0.1:7650".into(), + services: Vec::new(), + }, + live: tokio::sync::broadcast::channel(64).0, + }; + let router = Router::builder() + .discover() + .cookies() + .app_context(app) + .build(); + Setup { + router, + store, + admin_cookie: format!("{SESSION_COOKIE}={}", admin_session.expose()), + ben_tokens: [ben_a.expose().to_string(), ben_b.expose().to_string()], + ben_id: ben.id, + } + } + + fn cookie(token: &str) -> String { + format!("{SESSION_COOKIE}={token}") + } + + /// A form post through the router, answered as (status, Location). + async fn post_form( + router: &Router, + uri: &str, + body: &str, + cookie: Option<&str>, + ) -> (StatusCode, Option) { + let mut builder = http::Request::builder() + .method(http::Method::POST) + .uri(uri) + .header(header::CONTENT_TYPE, "application/x-www-form-urlencoded"); + if let Some(cookie) = cookie { + builder = builder.header(header::COOKIE, cookie); + } + let response = router + .handle(builder.body(Body::from(body.to_string())).unwrap()) + .await; + let (parts, body) = response.into_parts(); + let location = parts + .headers + .get(header::LOCATION) + .and_then(|v| v.to_str().ok()) + .map(str::to_string); + let _ = to_bytes(body, usize::MAX).await.unwrap(); + (parts.status, location) + } + + /// Opens `/live` as a signed-in tab would and pins the body's data + /// stream. A single SSE frame may straddle two body frames, so callers + /// accumulate text and match on substrings. + async fn open_live(router: &Router, cookie: &str) -> Pin> { + let response = router + .handle( + http::Request::builder() + .uri("/live") + .header(header::COOKIE, cookie) + .body(Body::empty()) + .unwrap(), + ) + .await; + let (parts, body) = response.into_parts(); + assert_eq!(parts.status, StatusCode::OK); + Box::pin(body.into_data_stream()) + } + + /// The next body frame off the stream, as text. Bounded, so a + /// regression fails loudly instead of hanging the suite — under the + /// single-threaded test runtime a plain park can miss the producer's + /// wakeup entirely. + async fn next_chunk(stream: &mut Pin>) -> String { + let chunk = tokio::time::timeout(std::time::Duration::from_secs(10), stream.as_mut().next()) + .await + .expect("a frame arrives in time") + .expect("stream stays open") + .expect("frames succeed"); + String::from_utf8_lossy(&chunk).into_owned() + } + + /// Reads frames until `needle` appears, returning everything read. + async fn read_until(stream: &mut Pin>, needle: &str) -> String { + let mut wire = String::new(); + while !wire.contains(needle) { + wire.push_str(&next_chunk(stream).await); + } + wire + } + + /// The heart of the live logout: a revoke reaches the revoked session's + /// own tab as an addressed `revoked` event, while a bystander's tab — + /// on the same bus — hears only the tick the action logs. The + /// bystander's read is the absence proof: frames arrive in send order, + /// and the eviction news is sent before the tick, so a tick with no + /// revoked frame before it means none was addressed here. + #[tokio::test] + async fn a_revoke_reaches_the_revoked_tab_and_not_a_bystanders() { + let setup = setup().await; + let mut ben = open_live(&setup.router, &cookie(&setup.ben_tokens[0])).await; + let mut ada = open_live(&setup.router, &setup.admin_cookie).await; + + let (status, _) = post_form( + &setup.router, + "/admin/revoke", + &format!("user={}", setup.ben_id), + Some(&setup.admin_cookie), + ) + .await; + assert_eq!(status, StatusCode::SEE_OTHER); + + let wire = read_until(&mut ben, "event: revoked").await; + assert!(wire.contains("event: revoked"), "{wire}"); + + let wire = read_until(&mut ada, "data: {}").await; + assert!(!wire.contains("event: revoked"), "{wire}"); + } + + /// A per-session revoke is aimed: the named session's tab hears its + /// eviction, the same person's other tab hears only the tick. + #[tokio::test] + async fn a_session_revoke_spares_the_same_users_other_tab() { + let setup = setup().await; + let mut kept = open_live(&setup.router, &cookie(&setup.ben_tokens[0])).await; + let mut killed = open_live(&setup.router, &cookie(&setup.ben_tokens[1])).await; + + let (status, _) = post_form( + &setup.router, + "/admin/session_revoke", + &format!( + "user={}&session={}", + setup.ben_id, + hash_token(&setup.ben_tokens[1]) + ), + Some(&setup.admin_cookie), + ) + .await; + assert_eq!(status, StatusCode::SEE_OTHER); + + let wire = read_until(&mut killed, "event: revoked").await; + assert!(wire.contains("event: revoked"), "{wire}"); + + let wire = read_until(&mut kept, "data: {}").await; + assert!(!wire.contains("event: revoked"), "{wire}"); + } + + /// The password change's courtesy: the browser that proved the old + /// password keeps its tab — no revoked frame ever names its session — + /// while every other session really dies. + #[tokio::test] + async fn a_password_change_keeps_the_asking_tab_signed_in() { + let setup = setup().await; + let mut asking = open_live(&setup.router, &cookie(&setup.ben_tokens[0])).await; + + let (status, location) = post_form( + &setup.router, + "/password", + "current=tDLr9!mZQ2xv&password=n3w-Hard-Pass!9&password_confirm=n3w-Hard-Pass!9", + Some(&cookie(&setup.ben_tokens[0])), + ) + .await; + assert_eq!(status, StatusCode::SEE_OTHER); + assert_eq!(location.as_deref(), Some("/?section=password&ok=password")); + + let wire = read_until(&mut asking, "data: {}").await; + assert!(!wire.contains("event: revoked"), "{wire}"); + assert!( + resolve_session(&setup.store, &setup.ben_tokens[0]) + .await + .unwrap() + .is_some(), + "the asking session survives" + ); + assert!( + resolve_session(&setup.store, &setup.ben_tokens[1]) + .await + .unwrap() + .is_none(), + "the other session dies" + ); + } + + /// A disable is a sign-out too: the disabled account's tab hears the + /// eviction on the spot. The roster half — the Profile frame carrying + /// `disabled` — is asserted in directory.rs's stream test. + #[tokio::test] + async fn a_disable_reaches_the_disabled_tab() { + let setup = setup().await; + let mut ben = open_live(&setup.router, &cookie(&setup.ben_tokens[0])).await; + + let (status, _) = post_form( + &setup.router, + "/admin/disable", + &format!("user={}", setup.ben_id), + Some(&setup.admin_cookie), + ) + .await; + assert_eq!(status, StatusCode::SEE_OTHER); + + let wire = read_until(&mut ben, "event: revoked").await; + assert!(wire.contains("event: revoked"), "{wire}"); + } + + /// A delete takes the person's sessions with them, and their tabs hear + /// it like any other eviction. + #[tokio::test] + async fn a_delete_reaches_the_deleted_users_tab() { + let setup = setup().await; + let mut ben = open_live(&setup.router, &cookie(&setup.ben_tokens[0])).await; + + let (status, _) = post_form( + &setup.router, + "/admin/delete", + &format!("user={}", setup.ben_id), + Some(&setup.admin_cookie), + ) + .await; + assert_eq!(status, StatusCode::SEE_OTHER); + + let wire = read_until(&mut ben, "event: revoked").await; + assert!(wire.contains("event: revoked"), "{wire}"); + } + + /// The live client's fallback probe: a bare status, no HTML — 204 when + /// the session still stands, 401 when it does not. + #[tokio::test] + async fn the_me_probe_answers_a_bare_status() { + let setup = setup().await; + for (cookie, expected) in [ + (Some(setup.admin_cookie.as_str()), StatusCode::NO_CONTENT), + (None, StatusCode::UNAUTHORIZED), + ] { + let mut builder = http::Request::builder().uri("/api/me"); + if let Some(cookie) = cookie { + builder = builder.header(header::COOKIE, cookie); + } + let response = setup + .router + .handle(builder.body(Body::empty()).unwrap()) + .await; + assert_eq!(response.into_parts().0.status, expected); + } + } +} diff --git a/crates/im-web/src/server.rs b/crates/im-web/src/server.rs index 99a6f75..ca4ea42 100644 --- a/crates/im-web/src/server.rs +++ b/crates/im-web/src/server.rs @@ -39,11 +39,17 @@ pub struct App { /// What travels the live channel. `Tick` is the panel's "something moved — /// re-read"; `Profile` is the directory's own news: this member's row, as it -/// now stands, serialized exactly as `/directory` would have answered it. +/// now stands, serialized exactly as `/directory` would have answered it; +/// `Revoked` is a sign-out in motion: this user's session(s) just died, the +/// one named by hash when the revocation was session-targeted. #[derive(Clone, Debug)] pub enum LiveEvent { Tick, Profile(crate::directory::DirectoryMember), + Revoked { + user_id: String, + session_hash: Option, + }, } /// Announce that the panel's data moved. Sends are lossy on purpose: nobody @@ -65,6 +71,19 @@ pub async fn notify_profile(cx: &Cx, user_id: &im_core::model::UserId) { )); } +/// Announce that `user`'s sessions died — one of them when `session_hash` +/// names a session, all of them when it does not. Every write path that ends +/// sessions speaks here, so the dead sessions' open tabs hear their own +/// eviction on the live channel and leave without waiting out the stream +/// window. Sent right after the write commits and before the tick, so a +/// connection that swallows the tick has already missed nothing. +pub async fn note_revoked(cx: &Cx, user_id: &str, session_hash: Option<&str>) { + let _ = app(cx).live.send(LiveEvent::Revoked { + user_id: user_id.to_string(), + session_hash: session_hash.map(str::to_string), + }); +} + /// Log the event, then tick the live channel — the two travel together so /// the Logs page (and any watching panel) catches up without a reload. pub async fn log_event(cx: &Cx, kind: &str, actor: Option<&str>, detail: Option<&str>) {