From dcf889ab53e7faa55d2f3801404b9bf640243af4 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 09:33:31 +0300 Subject: [PATCH] in: live session-revocation logout - Topic::Revoked(user_id) on the store bus; /api/live emits it to the killed user's own connections (may_hear own-id) then ends the stream - set_user_disabled announces Admin+Profile+Revoked (own admin path included) - identity_sync: directory revoked{sub} -> Profile announce (refetch-morph; revoke-except survivors never false-kicked); disabled mirrored both ways - im-client pin -> 5efbd60 (DirectoryEvent::Revoked, member.disabled) - client: revoked frame or /api/me 401 on SSE error -> hard navigate to / - new GET /api/me (204/401, 500 on store failure) --- Cargo.lock | 2 +- Cargo.toml | 2 +- crates/in-core/src/live.rs | 9 +- crates/in-core/src/store/mod.rs | 14 +- crates/in-core/src/store/turso_store.rs | 10 +- crates/in-core/tests/store.rs | 58 ++++++ crates/in-web/src/layout.rs | 16 ++ crates/in-web/src/live.rs | 38 +++- crates/in-web/src/main.rs | 252 +++++++++++++++++++++++- crates/in-web/src/server.rs | 18 +- crates/in-web/tests/http.rs | 160 +++++++++++++++ 11 files changed, 558 insertions(+), 21 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 2ce9f65..3f4aabb 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1929,7 +1929,7 @@ dependencies = [ [[package]] name = "im-client" version = "0.1.0" -source = "git+https://github.com/DizeyLab/im?rev=25140f3#25140f308a711d4090fa75bb29558a3f5335587c" +source = "git+https://github.com/DizeyLab/im?rev=5efbd60963c4473264ed765afeed038d4273d791#5efbd60963c4473264ed765afeed038d4273d791" dependencies = [ "base64 0.23.1", "chacha20poly1305", diff --git a/Cargo.toml b/Cargo.toml index 247f367..90481d8 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -16,7 +16,7 @@ in-client = { path = "crates/in-client" } # pair the OIDC side already holds. The OIDC half stays gated off — this # app's own `in-client` fork keeps the auth routes, and two route sets in # one binary collide. -im-client = { git = "https://github.com/DizeyLab/im", rev = "25140f3", default-features = false } +im-client = { git = "https://github.com/DizeyLab/im", rev = "5efbd60963c4473264ed765afeed038d4273d791", default-features = false } serde = { version = "1.0.229", features = ["derive"] } serde_json = "1.0.151" thiserror = "2.0.20" diff --git a/crates/in-core/src/live.rs b/crates/in-core/src/live.rs index 31bee99..10efbc4 100644 --- a/crates/in-core/src/live.rs +++ b/crates/in-core/src/live.rs @@ -29,6 +29,12 @@ pub enum Topic { /// every signed-in topbar, so every reader may hear that some member /// moved and re-fetch through the ordinary gated route. Profile(String), + /// The person's account was killed user-level — disabled, or deleted. + /// Only the person's own connections may hear it: the frame orders + /// their tabs out at once, a hard redirect a mere refresh cannot + /// promise. Everyone else learns the news as an ordinary + /// [`Topic::Profile`] move. + Revoked(String), /// Users, quotas, disablements — the admin's surface. Admin(String), } @@ -42,6 +48,7 @@ impl Topic { Topic::Trash(_) => "trash", Topic::Shares(_) => "shares", Topic::Profile(_) => "profile", + Topic::Revoked(_) => "revoked", Topic::Admin(_) => "admin", } } @@ -51,7 +58,7 @@ impl Topic { pub fn id(&self) -> &str { match self { Topic::Library(id) | Topic::Trash(id) | Topic::Shares(id) | Topic::Profile(id) - | Topic::Admin(id) => id, + | Topic::Revoked(id) | Topic::Admin(id) => id, } } } diff --git a/crates/in-core/src/store/mod.rs b/crates/in-core/src/store/mod.rs index 4fde714..23e386c 100644 --- a/crates/in-core/src/store/mod.rs +++ b/crates/in-core/src/store/mod.rs @@ -422,9 +422,21 @@ pub trait Store: 'static + Send + Sync { async fn set_user_quota(&self, user_id: &str, quota_bytes: u64) -> Result<()>; /// Disables an account. A disabled account signs in to nothing: the auth - /// layer reads this and treats the person as signed out. + /// layer reads this and treats the person as signed out. The write + /// announces [`Topic::Admin`](crate::live::Topic) for the admins' + /// panels, [`Topic::Profile`](crate::live::Topic) for every signed-in + /// topbar, and [`Topic::Revoked`](crate::live::Topic) for the person's + /// own open tabs, which are ordered out at once. async fn set_user_disabled(&self, user_id: &str, disabled: bool) -> Result<()>; + /// Wakes the live channel for a member whose row did not move: every + /// signed-in reader is told the member's profile surface changed and + /// re-fetches through the ordinary gated route. The identity mirror + /// uses it when im revokes a person's sessions — the row here is + /// untouched and there is nothing to write, but every tab carrying + /// them must find out. Silent when nobody is listening. + fn announce_profile(&self, user_id: &str); + /// Writes the person's display preferences — `theme` ('light'/'dark'), /// `language` ('en'/'tr') and `ui` ('ledger'/'instrument') — read by /// `root_layout` into `data-theme`, `` and `data-ui`. A value diff --git a/crates/in-core/src/store/turso_store.rs b/crates/in-core/src/store/turso_store.rs index 15cd9f5..f95b6b7 100644 --- a/crates/in-core/src/store/turso_store.rs +++ b/crates/in-core/src/store/turso_store.rs @@ -1234,10 +1234,18 @@ impl Store for TursoStore { return Err(StoreError::NotFound); } drop(conn); - self.announce([Topic::Admin(user_id.to_string())]); + self.announce([ + Topic::Admin(user_id.to_string()), + Topic::Profile(user_id.to_string()), + Topic::Revoked(user_id.to_string()), + ]); Ok(()) } + fn announce_profile(&self, user_id: &str) { + self.announce([Topic::Profile(user_id.to_string())]); + } + async fn set_preferences(&self, id: &str, theme: &str, language: &str, ui: &str) -> Result<()> { if theme != "light" && theme != "dark" { return Err(StoreError::Corrupt(format!("theme {theme:?}"))); diff --git a/crates/in-core/tests/store.rs b/crates/in-core/tests/store.rs index 8c668f4..f1270dc 100644 --- a/crates/in-core/tests/store.rs +++ b/crates/in-core/tests/store.rs @@ -167,6 +167,64 @@ async fn quota_and_disablement_round_trip() { )); } +/// Killing an account speaks to three audiences at once: the admins' +/// panels, every signed-in topbar, and — the strictest — the person's +/// own open tabs, whose frame reads as the order to leave. The way back +/// (a re-enable) announces the same three, through the same channel. +#[tokio::test] +async fn a_disablement_announces_the_admin_surface_the_profile_and_the_kill() { + let scratch = Scratch::open().await; + let user = alice(&scratch.store).await; + let mut rx = scratch.store.subscribe(); + + scratch + .store + .set_user_disabled(&user.id, true) + .await + .unwrap(); + let admin = rx.try_recv().unwrap(); + assert_eq!(admin.topic.kind(), "admin"); + assert_eq!(admin.topic.id(), user.id); + let profile = rx.try_recv().unwrap(); + assert_eq!(profile.topic.kind(), "profile"); + let kill = rx.try_recv().unwrap(); + assert_eq!(kill.topic.kind(), "revoked"); + assert_eq!(kill.topic.id(), user.id); + + scratch + .store + .set_user_disabled(&user.id, false) + .await + .unwrap(); + assert_eq!(rx.try_recv().unwrap().topic.kind(), "admin"); + assert_eq!(rx.try_recv().unwrap().topic.kind(), "profile"); + assert_eq!(rx.try_recv().unwrap().topic.kind(), "revoked"); + assert!(matches!( + rx.try_recv(), + Err(tokio::sync::broadcast::error::TryRecvError::Empty) + )); +} + +/// A session revocation at im carries no write here — the local row did +/// not move — yet every tab carrying the person must still hear that +/// their world changed. `announce_profile` is the write-less knock on +/// the same channel: one profile announcement, exactly, and nothing else. +#[tokio::test] +async fn announce_profile_wakes_the_channel_without_a_write() { + let scratch = Scratch::open().await; + let user = alice(&scratch.store).await; + let mut rx = scratch.store.subscribe(); + + scratch.store.announce_profile(&user.id); + let change = rx.try_recv().unwrap(); + assert_eq!(change.topic.kind(), "profile"); + assert_eq!(change.topic.id(), user.id); + assert!(matches!( + rx.try_recv(), + Err(tokio::sync::broadcast::error::TryRecvError::Empty) + )); +} + #[tokio::test] async fn folders_postfix_onto_live_sibling_names() { let scratch = Scratch::open().await; diff --git a/crates/in-web/src/layout.rs b/crates/in-web/src/layout.rs index 12e604a..0a028a8 100644 --- a/crates/in-web/src/layout.rs +++ b/crates/in-web/src/layout.rs @@ -947,6 +947,16 @@ pub async fn search_script<'a>(cx: &'a Cx) -> Result { /// disagree with it — the tick re-fetches, and the server stays the only thing /// that decides what a moment reads as. It runs only on pages carrying a /// `data-tick` element, so a page with no clock-driven text is silent. +/// +/// Two frames are not a refresh at all. A `revoked` topic means this tab's +/// account was killed user-level — disabled, or deleted — and the only right +/// answer is to leave: a hard redirect to the root, no morph, because a dead +/// session has nothing worth keeping on screen. And when the stream itself +/// errors — the window rolling over, a restart, a reconnect refused — the +/// script probes `/api/me` once: a 401 says the session behind this tab is +/// gone no matter what the page still shows, and the tab leaves the same +/// way. Every other error keeps the `EventSource`'s own reconnect, which +/// wants no help. pub async fn live_script<'a>(cx: &'a Cx) -> Result { const JS: &str = "\ (function () { \ @@ -975,8 +985,14 @@ pub async fn live_script<'a>(cx: &'a Cx) -> Result { src.onmessage = function (e) { \ var frame; \ try { frame = JSON.parse(e.data); } catch (err) { return; } \ + if (frame && frame.topic === 'revoked') { window.location.href = '/'; return; } \ if (frame && wanted(frame.topic)) { schedule(); } \ }; \ + src.onerror = function () { \ + fetch('/api/me').then(function (r) { \ + if (r.status === 401) { window.location.href = '/'; } \ + }).catch(function () { }); \ + }; \ } catch (err) { } \ setInterval(function () { \ if (document.querySelector('[data-tick]')) { refresh(); } \ diff --git a/crates/in-web/src/live.rs b/crates/in-web/src/live.rs index bf601b4..ca8739f 100644 --- a/crates/in-web/src/live.rs +++ b/crates/in-web/src/live.rs @@ -52,7 +52,10 @@ pub struct Shutdown(pub tokio::sync::watch::Receiver); /// Every topic carries its owner's id, and a reader hears only their own — /// one person's drive never names itself on another person's connection. The /// one exception is the admin surface, which an admin hears about: someone -/// who can act on every account may be told every account moved. +/// who can act on every account may be told every account moved. A +/// [`Topic::Revoked`] is the strictest of all — the killed person's own +/// connections and nobody else's, not even an admin's, since a hard +/// redirect is an order nobody should receive secondhand. fn may_hear(topic: &Topic, me: &str, admin: bool) -> bool { if topic.id() == me { return true; @@ -81,6 +84,12 @@ struct Frame<'a> { /// everything you are showing". const RESYNC: &str = r#"{"topic":"resync"}"#; +/// A frame ordering the reader's own tab out: their account was killed +/// user-level — disabled, or deleted. Like the resync frame it is a bare +/// topic with nothing else on it, and it is the one frame after which the +/// stream ends. +const REVOKED: &str = r#"{"topic":"revoked"}"#; + #[route(GET "/api/live")] async fn live(cx: &Cx) -> topcoat::Result { let Ok(user) = require_user(cx).await else { @@ -97,9 +106,14 @@ async fn live(cx: &Cx) -> topcoat::Result { .0; let events = futures_util::stream::unfold( - (rx, admin, me, deadline, stopping), - |(mut rx, admin, me, deadline, mut stopping)| async move { + (rx, false, admin, me, deadline, stopping), + |(mut rx, sealing, admin, me, deadline, mut stopping)| async move { loop { + // A stream whose last word was the revoked frame ends + // here: the account behind it is gone. + if sealing { + return None; + } // Already going down: say nothing and 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()) { @@ -141,6 +155,17 @@ async fn live(cx: &Cx) -> topcoat::Result { if !may_hear(&topic, &me, admin) { continue; } + // The one news that ends the stream: the reader's + // own account was killed user-level. The bare frame + // orders the tab out, and the stream closes behind + // it — a dead account's connection has no further + // business staying open. + if let Topic::Revoked(_) = topic { + return Some(( + Ok(Event::new().data(REVOKED)), + (rx, true, admin, me, deadline, stopping), + )); + } let frame = Frame { topic: topic.kind(), id: topic.id(), @@ -149,12 +174,15 @@ async fn live(cx: &Cx) -> topcoat::Result { match Event::new().json_data(&frame) { Ok(event) => event, Err(problem) => { - return Some((Err(problem), (rx, admin, me, deadline, stopping))); + return Some(( + Err(problem), + (rx, sealing, admin, me, deadline, stopping), + )); } } } }; - return Some((Ok(frame), (rx, admin, me, deadline, stopping))); + return Some((Ok(frame), (rx, sealing, admin, me, deadline, stopping))); } }, ); diff --git a/crates/in-web/src/main.rs b/crates/in-web/src/main.rs index 2119385..3f74150 100644 --- a/crates/in-web/src/main.rs +++ b/crates/in-web/src/main.rs @@ -365,15 +365,19 @@ async fn shutdown_signal() { const IDENTITY_BACKOFF_CAP: std::time::Duration = std::time::Duration::from_secs(30); /// Mirrors one member's identity into the local row: the JIT upsert that -/// keeps address, name, admin flag and photo stamp following im. The store -/// announces a `profile` change itself when a mirrored field moved, so the -/// only job left here is the write and its one log line when it fails. +/// keeps address, name, admin flag and photo stamp following im — and the +/// disablement flag with it, both directions, for the row is im's word on +/// the person and a re-enable must land here as surely as a kill. The +/// store announces a `profile` change itself when a mirrored field moved, +/// and a flipped disablement announces the admin surface, the profile and +/// the person's own tabs all at once, so the only job left here is the +/// write and its one log line when it fails. async fn mirror_member( store: &Arc, member: &im_client::directory::DirectoryMember, default_quota_bytes: u64, ) { - if let Err(problem) = store + let user = match store .provision_user( &member.sub, &member.email, @@ -384,7 +388,19 @@ async fn mirror_member( ) .await { - eprintln!("in: directory mirror of {}: {problem}", member.sub); + Ok(user) => user, + Err(problem) => { + eprintln!("in: directory mirror of {}: {problem}", member.sub); + return; + } + }; + if user.disabled != member.disabled + && let Err(problem) = store.set_user_disabled(&user.id, member.disabled).await + { + eprintln!( + "in: directory disablement mirror of {}: {problem}", + member.sub + ); } } @@ -420,11 +436,14 @@ async fn identity_sync( health.connected(); while let Some(event) = stream.next().await { match event { - Ok(im_client::directory::DirectoryEvent::Profile(member)) => { - mirror_member(&store, &member, default_quota_bytes).await; - // Every event is proof the feed is alive; - // the card's age line reads this. - health.note_event(); + Ok(event) => { + apply_directory_event( + &store, + &health, + event, + default_quota_bytes, + ) + .await; } // A network failure ends the stream; the full // pass below re-lists before the redial. @@ -456,6 +475,50 @@ async fn identity_sync( } } +/// One event off the directory stream, applied to the local mirror. The +/// seam exists so the tests can drive a constructed event through the +/// same door identity_sync's stream loop uses — the loop itself only +/// knows how to read the wire. +async fn apply_directory_event( + store: &Arc, + health: &in_web::server::DirectoryHealth, + event: im_client::directory::DirectoryEvent, + default_quota_bytes: u64, +) { + match event { + im_client::directory::DirectoryEvent::Profile(member) => { + mirror_member(store, &member, default_quota_bytes).await; + } + // Sessions died at im; no local row moved. Wake the person + // through the profile topic — their tabs refetch, meet the dead + // introspection, and morph to the sign-in card. + im_client::directory::DirectoryEvent::Revoked { sub } => { + announce_revocation(store, &sub).await; + } + } + // Every event is proof the feed is alive; the card's age line reads + // this. + health.note_event(); +} + +/// The session-targeted half of a directory revocation: im revoked the +/// person's sessions and no local row moved, but every tab carrying them +/// must find out. The row is woken through the ordinary profile +/// announcement — the one topic every signed-in reader may hear — so the +/// revoked person's own tabs refetch, meet a dead introspection, and +/// morph to the sign-in card: the whole of what a session-level logout +/// looks like from here. No hard redirect: which of the person's +/// sessions died is im's knowledge alone, and a surviving tab must not +/// be ordered out for its sibling's death. +async fn announce_revocation(store: &Arc, sub: &str) { + match store.user_by_oidc_sub(sub).await { + Ok(Some(user)) => store.announce_profile(&user.id), + // Nobody local carries this subject: nobody here to wake. + Ok(None) => {} + Err(problem) => eprintln!("in: revocation wake for {sub}: {problem}"), + } +} + /// How often the suite list is re-fetched from im. Short enough that a /// service the admin adds over there shows up here before anyone goes /// looking for its wordmark, long enough that the two are not talking @@ -510,3 +573,172 @@ async fn family_sync( tokio::time::sleep(std::time::Duration::from_secs(FAMILY_SECONDS)).await; } } + +#[cfg(test)] +mod tests { + use super::*; + use in_core::store::Store; + + /// A revoked session at im wakes the person's row by its local id: + /// one profile announcement, heard by every signed-in reader, with + /// the person's own tabs morphing to the sign-in card on the refetch. + /// A subject that never signed in here wakes nobody. + #[tokio::test] + async fn a_revoked_session_wakes_the_persons_row_through_the_profile_topic() { + let dir = std::env::temp_dir().join(format!("in-revoke-{}", ulid::Ulid::generate())); + std::fs::create_dir_all(&dir).unwrap(); + let store: Arc = Arc::new( + in_core::store::TursoStore::open( + dir.join("in.db").to_str().unwrap(), + Some(&dir.join("storage")), + ) + .await + .unwrap(), + ); + let user = store + .provision_user("sub-gone", "gone@in.test", "Gone", None, 0, 1024) + .await + .unwrap(); + let mut rx = store.subscribe(); + + announce_revocation(&store, "sub-gone").await; + + let change = rx.try_recv().unwrap(); + assert_eq!(change.topic.kind(), "profile"); + assert_eq!(change.topic.id(), user.id); + assert!(matches!( + rx.try_recv(), + Err(tokio::sync::broadcast::error::TryRecvError::Empty) + )); + + announce_revocation(&store, "sub-unknown").await; + assert!(matches!( + rx.try_recv(), + Err(tokio::sync::broadcast::error::TryRecvError::Empty) + )); + + drop(store); + let _ = std::fs::remove_dir_all(&dir); + } + + /// One roster member as the wire carries it. + fn member(sub: &str, disabled: bool) -> im_client::directory::DirectoryMember { + im_client::directory::DirectoryMember { + sub: sub.to_string(), + email: format!("{sub}@in.test"), + name: "Member".to_string(), + admin: false, + photo_version: 0, + timezone: "UTC+03:00".to_string(), + disabled, + } + } + + async fn scratch() -> (std::path::PathBuf, Arc) { + let dir = std::env::temp_dir().join(format!("in-event-{}", ulid::Ulid::generate())); + std::fs::create_dir_all(&dir).unwrap(); + let store: Arc = Arc::new( + in_core::store::TursoStore::open( + dir.join("in.db").to_str().unwrap(), + Some(&dir.join("storage")), + ) + .await + .unwrap(), + ); + (dir, store) + } + + /// A `revoked` frame off the stream — im's word that the subject's + /// sessions died — wakes the person's row by its local id through + /// the profile topic, and stamps the connection card's freshness. + #[tokio::test] + async fn a_stream_revocation_announces_through_the_profile_topic() { + let (dir, store) = scratch().await; + let health = in_web::server::DirectoryHealth::new(); + let user = store + .provision_user("sub-gone", "gone@in.test", "Gone", None, 0, 1024) + .await + .unwrap(); + let mut rx = store.subscribe(); + + apply_directory_event( + &store, + &health, + im_client::directory::DirectoryEvent::Revoked { + sub: "sub-gone".to_string(), + }, + 1024, + ) + .await; + + let change = rx.try_recv().unwrap(); + assert_eq!(change.topic.kind(), "profile"); + assert_eq!(change.topic.id(), user.id); + assert!(matches!( + rx.try_recv(), + Err(tokio::sync::broadcast::error::TryRecvError::Empty) + )); + assert!(health.last_event_age_secs().is_some()); + + drop(store); + let _ = std::fs::remove_dir_all(&dir); + } + + /// The member's disablement flag follows im in both directions: a + /// `profile` frame carrying `disabled` flips the local row and — the + /// part the tabs wait for — the store announces the kill (and, on + /// the way back, the reopening) on all three surfaces at once. + #[tokio::test] + async fn a_members_disabled_flag_mirrors_both_ways() { + let (dir, store) = scratch().await; + let health = in_web::server::DirectoryHealth::new(); + let mut rx = store.subscribe(); + + // First sight: the mirror inserts the row, present and enabled. + apply_directory_event( + &store, + &health, + im_client::directory::DirectoryEvent::Profile(member("sub-m", false)), + 1024, + ) + .await; + let user = store.user_by_oidc_sub("sub-m").await.unwrap().unwrap(); + assert!(!user.disabled); + // A fresh row announces the admin surface and the profile — the + // two reads that keep the later phases' queues clean. + assert_eq!(rx.try_recv().unwrap().topic.kind(), "admin"); + assert_eq!(rx.try_recv().unwrap().topic.kind(), "profile"); + // im switches the member off: the row follows, and the revoked + // frame rides to the person's own tabs. + apply_directory_event( + &store, + &health, + im_client::directory::DirectoryEvent::Profile(member("sub-m", true)), + 1024, + ) + .await; + let killed = store.user_by_oidc_sub("sub-m").await.unwrap().unwrap(); + assert!(killed.disabled); + assert_eq!(rx.try_recv().unwrap().topic.kind(), "admin"); + assert_eq!(rx.try_recv().unwrap().topic.kind(), "profile"); + assert_eq!(rx.try_recv().unwrap().topic.kind(), "revoked"); + + // im lets them back in: the same channel carries the reopening. + apply_directory_event( + &store, + &health, + im_client::directory::DirectoryEvent::Profile(member("sub-m", false)), + 1024, + ) + .await; + let back = store.user_by_oidc_sub("sub-m").await.unwrap().unwrap(); + assert!(!back.disabled); + assert_eq!(rx.try_recv().unwrap().topic.kind(), "admin"); + assert_eq!(rx.try_recv().unwrap().topic.kind(), "profile"); + assert_eq!(rx.try_recv().unwrap().topic.kind(), "revoked"); + assert!(health.last_event_age_secs().is_some()); + + drop(store); + let _ = std::fs::remove_dir_all(&dir); + } +} diff --git a/crates/in-web/src/server.rs b/crates/in-web/src/server.rs index 2104ff3..1d1de38 100644 --- a/crates/in-web/src/server.rs +++ b/crates/in-web/src/server.rs @@ -20,7 +20,7 @@ use sha2::Digest; use topcoat::asset::AssetBundle; use topcoat::context::{Cx, app_context, memoize}; use topcoat::router::request::headers; -use topcoat::router::{Body, HeaderValue, Next, StatusCode, header, response::Response, to_bytes}; +use topcoat::router::{Body, HeaderValue, Next, StatusCode, header, response::{IntoResponse, Response}, route, to_bytes}; /// The whole application context, put into the router by `main.rs`. One /// struct rather than three separate contexts so a route needing two of them @@ -301,6 +301,22 @@ pub async fn require_user(cx: &Cx) -> Result { } } +/// The sign-in probe the live channel's error path polls: 204 while this +/// browser carries a live session, 401 the moment it does not — no HTML, +/// no body, nothing but the answer. It exists for the one question an open +/// tab can ask mid-flight ("am I still signed in?") without dragging a +/// page render behind it. A store failure answers 500 rather than 401: +/// the probe's whole contract is that only a real sign-out draws the 401, +/// and a broken database must never fake one. +#[route(GET "/api/me")] +pub async fn me(cx: &Cx) -> topcoat::Result { + match current_user(cx).await { + Ok(Some(_)) => (StatusCode::NO_CONTENT, "").into_response(cx), + Ok(None) => (StatusCode::UNAUTHORIZED, "").into_response(cx), + Err(_) => (StatusCode::INTERNAL_SERVER_ERROR, "").into_response(cx), + } +} + /// The admin behind this request. Anyone else is refused *here*, not /// merely hidden from in the UI. pub async fn require_admin(cx: &Cx) -> Result { diff --git a/crates/in-web/tests/http.rs b/crates/in-web/tests/http.rs index e58ff85..84229c9 100644 --- a/crates/in-web/tests/http.rs +++ b/crates/in-web/tests/http.rs @@ -10,6 +10,7 @@ //! New HTTP tests belong in this file rather than a new `tests/*.rs`: one //! test binary links and runs once. use http::{HeaderValue, Request, StatusCode, header}; +use http_body_util::BodyExt; use in_core::{Config, OidcConfig}; use std::collections::HashMap; use std::path::PathBuf; @@ -6040,3 +6041,162 @@ async fn the_family_limit_lands_on_the_account() { let holder = app.store.user(&user_id).await.unwrap().unwrap(); assert_eq!(holder.quota_bytes, 1024 * 1024); } + +/// How long one wait for a live frame may run before the test fails +/// loudly. A stream that never speaks is a hang, not an answer. +const FRAME_PATIENCE: std::time::Duration = std::time::Duration::from_secs(5); + +/// One open `/api/live` connection, held the way a browser holds it: the +/// frames are read as they arrive, and the end of the body is itself +/// news — a stream the server closed behind its last word. +struct LiveStream { + status: StatusCode, + content_type: Option, + body: Body, + /// Bytes read but not yet through a blank-line frame boundary; an + /// SSE event may straddle two body chunks. + buffer: String, +} + +impl LiveStream { + /// The next complete SSE frame, or `None` when the stream ended. A + /// frame that never arrives fails the test rather than outlasting it. + async fn next_frame(&mut self) -> Option { + loop { + if let Some(at) = self.buffer.find("\n\n") { + return Some(self.buffer.drain(..at + 2).collect::()); + } + let polled = tokio::time::timeout(FRAME_PATIENCE, self.body.frame()) + .await + .expect("no frame arrived in time"); + // `None` is the body running out — the stream's end, which is + // the caller's news. Anything else is a frame to buffer. + let Some(polled) = polled else { + return None; + }; + let frame = polled.expect("the live body failed"); + let chunk = frame.into_data().expect("a frame with no data"); + self.buffer.push_str(&String::from_utf8_lossy(&chunk)); + } + } +} + +impl TestApp { + /// Opens the signed-in live stream and keeps it, unread — the frame + /// reader works on the body [`LiveStream`] holds. + async fn open_live(&self, cookie: &str) -> LiveStream { + let response = self + .router + .handle( + Request::builder() + .method("GET") + .uri("/api/live") + .header(header::COOKIE, HeaderValue::from_str(cookie).unwrap()) + .body(Body::empty()) + .unwrap(), + ) + .await; + let status = response.status(); + let content_type = response + .headers() + .get(header::CONTENT_TYPE) + .and_then(|value| value.to_str().ok()) + .map(str::to_string); + LiveStream { + status, + content_type, + body: response.into_body(), + buffer: String::new(), + } + } +} + +/// The sign-in probe the live channel's error path polls: 204 while the +/// session stands, 401 the moment it does not. A locally disabled +/// account reads as signed out even though im's introspection would +/// still vouch for the very same cookie — the local flag outranks it. +#[tokio::test] +async fn the_me_probe_answers_204_while_signed_in_and_401_the_moment_not() { + let app = TestApp::build().await; + let out = app.get("/api/me", None).await; + assert_eq!(out.status, StatusCode::UNAUTHORIZED); + assert!(out.bytes.is_empty(), "no body: {:?}", out.text()); + + let cookie = app.sign_in("sub-probe", "probe@in.test", "Probe").await; + let in_answer = app.get("/api/me", Some(&cookie)).await; + assert_eq!(in_answer.status, StatusCode::NO_CONTENT); + assert!(in_answer.bytes.is_empty(), "no body on 204 either"); + + let user = app.store.user_by_oidc_sub("sub-probe").await.unwrap().unwrap(); + app.store.set_user_disabled(&user.id, true).await.unwrap(); + let disabled = app.get("/api/me", Some(&cookie)).await; + assert_eq!(disabled.status, StatusCode::UNAUTHORIZED); +} + +/// A user-level kill — the disabled flag mirrored from im — rides the +/// ordinary topic bus, but its frame goes to exactly one listener: the +/// killed account's own open tabs, each answered with the bare revoked +/// frame and then an ended stream. Everybody else hears an ordinary +/// profile move and keeps their stream. +#[tokio::test] +async fn a_user_level_kill_orders_its_own_tabs_out_and_nobody_else() { + let app = TestApp::build().await; + let alice_cookie = app.sign_in("sub-alice", "alice@in.test", "Alice").await; + let bob_cookie = app.sign_in("sub-bob", "bob@in.test", "Bob").await; + let mut alice = app.open_live(&alice_cookie).await; + let mut bob = app.open_live(&bob_cookie).await; + assert_eq!(alice.status, StatusCode::OK); + assert_eq!( + alice.content_type.as_deref(), + Some("text/event-stream"), + "the live channel is an event stream" + ); + + // The kill: im's mirror flips the local flag; the store announces. + let alice_id = app + .store + .user_by_oidc_sub("sub-alice") + .await + .unwrap() + .unwrap() + .id; + app.store.set_user_disabled(&alice_id, true).await.unwrap(); + + // Bob hears the profile move — and only that. The revoked frame is + // an order no bystander ever receives. + let heard = bob.next_frame().await.unwrap(); + assert!( + heard.contains("\"topic\":\"profile\""), + "bob heard: {heard}" + ); + + // Alice hears her own kill as the bare frame, and the stream ends + // behind it — nothing on a dead account's connection lingers. + loop { + let heard = alice.next_frame().await.unwrap(); + if heard.contains("\"topic\":\"revoked\"") { + break; + } + } + assert!( + alice.next_frame().await.is_none(), + "the killed tab's stream must end behind the revoked frame" + ); + + // Bob's stream survived Alice's kill: his own kill reaches it. + let bob_id = app + .store + .user_by_oidc_sub("sub-bob") + .await + .unwrap() + .unwrap() + .id; + app.store.set_user_disabled(&bob_id, true).await.unwrap(); + loop { + let heard = bob.next_frame().await.unwrap(); + if heard.contains("\"topic\":\"revoked\"") { + break; + } + } + assert!(bob.next_frame().await.is_none(), "bob's stream ends too"); +}