forge
Explore
Log in

Don't you dare go Hollow

in: live session-revocation logout

Browse files at this commit

dcf889ab53e7faa55d2f3801404b9bf640243af4Ahmet Kaan GümüşParent: d5f952e
- 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.lockmodified+1 -1
@@ -1929,7 +1929,7 @@ dependencies = [
1929 [[package]]1929 [[package]]
1930 name = "im-client"1930 name = "im-client"
1931 version = "0.1.0"1931 version = "0.1.0"
1932-source = "git+https://github.com/DizeyLab/im?rev=25140f3#25140f308a711d4090fa75bb29558a3f5335587c"1932+source = "git+https://github.com/DizeyLab/im?rev=5efbd60963c4473264ed765afeed038d4273d791#5efbd60963c4473264ed765afeed038d4273d791"
1933 dependencies = [1933 dependencies = [
1934 "base64 0.23.1",1934 "base64 0.23.1",
1935 "chacha20poly1305",1935 "chacha20poly1305",
Cargo.tomlmodified+1 -1
@@ -16,7 +16,7 @@ in-client = { path = "crates/in-client" }
16 # pair the OIDC side already holds. The OIDC half stays gated off — this16 # pair the OIDC side already holds. The OIDC half stays gated off — this
17 # app's own `in-client` fork keeps the auth routes, and two route sets in17 # app's own `in-client` fork keeps the auth routes, and two route sets in
18 # one binary collide.18 # one binary collide.
19-im-client = { git = "https://github.com/DizeyLab/im", rev = "25140f3", default-features = false }19+im-client = { git = "https://github.com/DizeyLab/im", rev = "5efbd60963c4473264ed765afeed038d4273d791", default-features = false }
20 serde = { version = "1.0.229", features = ["derive"] }20 serde = { version = "1.0.229", features = ["derive"] }
21 serde_json = "1.0.151"21 serde_json = "1.0.151"
22 thiserror = "2.0.20"22 thiserror = "2.0.20"
crates/in-core/src/live.rsmodified+8 -1
@@ -29,6 +29,12 @@ pub enum Topic {
29 /// every signed-in topbar, so every reader may hear that some member29 /// every signed-in topbar, so every reader may hear that some member
30 /// moved and re-fetch through the ordinary gated route.30 /// moved and re-fetch through the ordinary gated route.
31 Profile(String),31 Profile(String),
32+ /// The person's account was killed user-level — disabled, or deleted.
33+ /// Only the person's own connections may hear it: the frame orders
34+ /// their tabs out at once, a hard redirect a mere refresh cannot
35+ /// promise. Everyone else learns the news as an ordinary
36+ /// [`Topic::Profile`] move.
37+ Revoked(String),
32 /// Users, quotas, disablements — the admin's surface.38 /// Users, quotas, disablements — the admin's surface.
33 Admin(String),39 Admin(String),
34 }40 }
@@ -42,6 +48,7 @@ impl Topic {
42 Topic::Trash(_) => "trash",48 Topic::Trash(_) => "trash",
43 Topic::Shares(_) => "shares",49 Topic::Shares(_) => "shares",
44 Topic::Profile(_) => "profile",50 Topic::Profile(_) => "profile",
51+ Topic::Revoked(_) => "revoked",
45 Topic::Admin(_) => "admin",52 Topic::Admin(_) => "admin",
46 }53 }
47 }54 }
@@ -51,7 +58,7 @@ impl Topic {
51 pub fn id(&self) -> &str {58 pub fn id(&self) -> &str {
52 match self {59 match self {
53 Topic::Library(id) | Topic::Trash(id) | Topic::Shares(id) | Topic::Profile(id)60 Topic::Library(id) | Topic::Trash(id) | Topic::Shares(id) | Topic::Profile(id)
54- | Topic::Admin(id) => id,61+ | Topic::Revoked(id) | Topic::Admin(id) => id,
55 }62 }
56 }63 }
57 }64 }
crates/in-core/src/store/mod.rsmodified+13 -1
@@ -422,9 +422,21 @@ pub trait Store: 'static + Send + Sync {
422 async fn set_user_quota(&self, user_id: &str, quota_bytes: u64) -> Result<()>;422 async fn set_user_quota(&self, user_id: &str, quota_bytes: u64) -> Result<()>;
423 423
424 /// Disables an account. A disabled account signs in to nothing: the auth424 /// Disables an account. A disabled account signs in to nothing: the auth
425- /// layer reads this and treats the person as signed out.425+ /// layer reads this and treats the person as signed out. The write
426+ /// announces [`Topic::Admin`](crate::live::Topic) for the admins'
427+ /// panels, [`Topic::Profile`](crate::live::Topic) for every signed-in
428+ /// topbar, and [`Topic::Revoked`](crate::live::Topic) for the person's
429+ /// own open tabs, which are ordered out at once.
426 async fn set_user_disabled(&self, user_id: &str, disabled: bool) -> Result<()>;430 async fn set_user_disabled(&self, user_id: &str, disabled: bool) -> Result<()>;
427 431
432+ /// Wakes the live channel for a member whose row did not move: every
433+ /// signed-in reader is told the member's profile surface changed and
434+ /// re-fetches through the ordinary gated route. The identity mirror
435+ /// uses it when im revokes a person's sessions — the row here is
436+ /// untouched and there is nothing to write, but every tab carrying
437+ /// them must find out. Silent when nobody is listening.
438+ fn announce_profile(&self, user_id: &str);
439+
428 /// Writes the person's display preferences — `theme` ('light'/'dark'),440 /// Writes the person's display preferences — `theme` ('light'/'dark'),
429 /// `language` ('en'/'tr') and `ui` ('ledger'/'instrument') — read by441 /// `language` ('en'/'tr') and `ui` ('ledger'/'instrument') — read by
430 /// `root_layout` into `data-theme`, `<html lang>` and `data-ui`. A value442 /// `root_layout` into `data-theme`, `<html lang>` and `data-ui`. A value
crates/in-core/src/store/turso_store.rsmodified+9 -1
@@ -1234,10 +1234,18 @@ impl Store for TursoStore {
1234 return Err(StoreError::NotFound);1234 return Err(StoreError::NotFound);
1235 }1235 }
1236 drop(conn);1236 drop(conn);
1237- self.announce([Topic::Admin(user_id.to_string())]);1237+ self.announce([
1238+ Topic::Admin(user_id.to_string()),
1239+ Topic::Profile(user_id.to_string()),
1240+ Topic::Revoked(user_id.to_string()),
1241+ ]);
1238 Ok(())1242 Ok(())
1239 }1243 }
1240 1244
1245+ fn announce_profile(&self, user_id: &str) {
1246+ self.announce([Topic::Profile(user_id.to_string())]);
1247+ }
1248+
1241 async fn set_preferences(&self, id: &str, theme: &str, language: &str, ui: &str) -> Result<()> {1249 async fn set_preferences(&self, id: &str, theme: &str, language: &str, ui: &str) -> Result<()> {
1242 if theme != "light" && theme != "dark" {1250 if theme != "light" && theme != "dark" {
1243 return Err(StoreError::Corrupt(format!("theme {theme:?}")));1251 return Err(StoreError::Corrupt(format!("theme {theme:?}")));
crates/in-core/tests/store.rsmodified+58 -0
@@ -167,6 +167,64 @@ async fn quota_and_disablement_round_trip() {
167 ));167 ));
168 }168 }
169 169
170+/// Killing an account speaks to three audiences at once: the admins'
171+/// panels, every signed-in topbar, and — the strictest — the person's
172+/// own open tabs, whose frame reads as the order to leave. The way back
173+/// (a re-enable) announces the same three, through the same channel.
174+#[tokio::test]
175+async fn a_disablement_announces_the_admin_surface_the_profile_and_the_kill() {
176+ let scratch = Scratch::open().await;
177+ let user = alice(&scratch.store).await;
178+ let mut rx = scratch.store.subscribe();
179+
180+ scratch
181+ .store
182+ .set_user_disabled(&user.id, true)
183+ .await
184+ .unwrap();
185+ let admin = rx.try_recv().unwrap();
186+ assert_eq!(admin.topic.kind(), "admin");
187+ assert_eq!(admin.topic.id(), user.id);
188+ let profile = rx.try_recv().unwrap();
189+ assert_eq!(profile.topic.kind(), "profile");
190+ let kill = rx.try_recv().unwrap();
191+ assert_eq!(kill.topic.kind(), "revoked");
192+ assert_eq!(kill.topic.id(), user.id);
193+
194+ scratch
195+ .store
196+ .set_user_disabled(&user.id, false)
197+ .await
198+ .unwrap();
199+ assert_eq!(rx.try_recv().unwrap().topic.kind(), "admin");
200+ assert_eq!(rx.try_recv().unwrap().topic.kind(), "profile");
201+ assert_eq!(rx.try_recv().unwrap().topic.kind(), "revoked");
202+ assert!(matches!(
203+ rx.try_recv(),
204+ Err(tokio::sync::broadcast::error::TryRecvError::Empty)
205+ ));
206+}
207+
208+/// A session revocation at im carries no write here — the local row did
209+/// not move — yet every tab carrying the person must still hear that
210+/// their world changed. `announce_profile` is the write-less knock on
211+/// the same channel: one profile announcement, exactly, and nothing else.
212+#[tokio::test]
213+async fn announce_profile_wakes_the_channel_without_a_write() {
214+ let scratch = Scratch::open().await;
215+ let user = alice(&scratch.store).await;
216+ let mut rx = scratch.store.subscribe();
217+
218+ scratch.store.announce_profile(&user.id);
219+ let change = rx.try_recv().unwrap();
220+ assert_eq!(change.topic.kind(), "profile");
221+ assert_eq!(change.topic.id(), user.id);
222+ assert!(matches!(
223+ rx.try_recv(),
224+ Err(tokio::sync::broadcast::error::TryRecvError::Empty)
225+ ));
226+}
227+
170 #[tokio::test]228 #[tokio::test]
171 async fn folders_postfix_onto_live_sibling_names() {229 async fn folders_postfix_onto_live_sibling_names() {
172 let scratch = Scratch::open().await;230 let scratch = Scratch::open().await;
crates/in-web/src/layout.rsmodified+16 -0
@@ -947,6 +947,16 @@ pub async fn search_script<'a>(cx: &'a Cx) -> Result<impl View + 'a> {
947 /// disagree with it — the tick re-fetches, and the server stays the only thing947 /// disagree with it — the tick re-fetches, and the server stays the only thing
948 /// that decides what a moment reads as. It runs only on pages carrying a948 /// that decides what a moment reads as. It runs only on pages carrying a
949 /// `data-tick` element, so a page with no clock-driven text is silent.949 /// `data-tick` element, so a page with no clock-driven text is silent.
950+///
951+/// Two frames are not a refresh at all. A `revoked` topic means this tab's
952+/// account was killed user-level — disabled, or deleted — and the only right
953+/// answer is to leave: a hard redirect to the root, no morph, because a dead
954+/// session has nothing worth keeping on screen. And when the stream itself
955+/// errors — the window rolling over, a restart, a reconnect refused — the
956+/// script probes `/api/me` once: a 401 says the session behind this tab is
957+/// gone no matter what the page still shows, and the tab leaves the same
958+/// way. Every other error keeps the `EventSource`'s own reconnect, which
959+/// wants no help.
950 pub async fn live_script<'a>(cx: &'a Cx) -> Result<impl View + 'a> {960 pub async fn live_script<'a>(cx: &'a Cx) -> Result<impl View + 'a> {
951 const JS: &str = "\961 const JS: &str = "\
952 (function () { \962 (function () { \
@@ -975,8 +985,14 @@ pub async fn live_script<'a>(cx: &'a Cx) -> Result<impl View + 'a> {
975 src.onmessage = function (e) { \985 src.onmessage = function (e) { \
976 var frame; \986 var frame; \
977 try { frame = JSON.parse(e.data); } catch (err) { return; } \987 try { frame = JSON.parse(e.data); } catch (err) { return; } \
988+ if (frame && frame.topic === 'revoked') { window.location.href = '/'; return; } \
978 if (frame && wanted(frame.topic)) { schedule(); } \989 if (frame && wanted(frame.topic)) { schedule(); } \
979 }; \990 }; \
991+ src.onerror = function () { \
992+ fetch('/api/me').then(function (r) { \
993+ if (r.status === 401) { window.location.href = '/'; } \
994+ }).catch(function () { }); \
995+ }; \
980 } catch (err) { } \996 } catch (err) { } \
981 setInterval(function () { \997 setInterval(function () { \
982 if (document.querySelector('[data-tick]')) { refresh(); } \998 if (document.querySelector('[data-tick]')) { refresh(); } \
crates/in-web/src/live.rsmodified+33 -5
@@ -52,7 +52,10 @@ pub struct Shutdown(pub tokio::sync::watch::Receiver<bool>);
52 /// Every topic carries its owner's id, and a reader hears only their own —52 /// Every topic carries its owner's id, and a reader hears only their own —
53 /// one person's drive never names itself on another person's connection. The53 /// one person's drive never names itself on another person's connection. The
54 /// one exception is the admin surface, which an admin hears about: someone54 /// one exception is the admin surface, which an admin hears about: someone
55-/// who can act on every account may be told every account moved.55+/// who can act on every account may be told every account moved. A
56+/// [`Topic::Revoked`] is the strictest of all — the killed person's own
57+/// connections and nobody else's, not even an admin's, since a hard
58+/// redirect is an order nobody should receive secondhand.
56 fn may_hear(topic: &Topic, me: &str, admin: bool) -> bool {59 fn may_hear(topic: &Topic, me: &str, admin: bool) -> bool {
57 if topic.id() == me {60 if topic.id() == me {
58 return true;61 return true;
@@ -81,6 +84,12 @@ struct Frame<'a> {
81 /// everything you are showing".84 /// everything you are showing".
82 const RESYNC: &str = r#"{"topic":"resync"}"#;85 const RESYNC: &str = r#"{"topic":"resync"}"#;
83 86
87+/// A frame ordering the reader's own tab out: their account was killed
88+/// user-level — disabled, or deleted. Like the resync frame it is a bare
89+/// topic with nothing else on it, and it is the one frame after which the
90+/// stream ends.
91+const REVOKED: &str = r#"{"topic":"revoked"}"#;
92+
84 #[route(GET "/api/live")]93 #[route(GET "/api/live")]
85 async fn live(cx: &Cx) -> topcoat::Result<Response> {94 async fn live(cx: &Cx) -> topcoat::Result<Response> {
86 let Ok(user) = require_user(cx).await else {95 let Ok(user) = require_user(cx).await else {
@@ -97,9 +106,14 @@ async fn live(cx: &Cx) -> topcoat::Result<Response> {
97 .0;106 .0;
98 107
99 let events = futures_util::stream::unfold(108 let events = futures_util::stream::unfold(
100- (rx, admin, me, deadline, stopping),109+ (rx, false, admin, me, deadline, stopping),
101- |(mut rx, admin, me, deadline, mut stopping)| async move {110+ |(mut rx, sealing, admin, me, deadline, mut stopping)| async move {
102 loop {111 loop {
112+ // A stream whose last word was the revoked frame ends
113+ // here: the account behind it is gone.
114+ if sealing {
115+ return None;
116+ }
103 // Already going down: say nothing and end, so this connection117 // Already going down: say nothing and end, so this connection
104 // is not one the shutdown has to sit and wait out.118 // is not one the shutdown has to sit and wait out.
105 if stopping.as_ref().is_some_and(|watch| *watch.borrow()) {119 if stopping.as_ref().is_some_and(|watch| *watch.borrow()) {
@@ -141,6 +155,17 @@ async fn live(cx: &Cx) -> topcoat::Result<Response> {
141 if !may_hear(&topic, &me, admin) {155 if !may_hear(&topic, &me, admin) {
142 continue;156 continue;
143 }157 }
158+ // The one news that ends the stream: the reader's
159+ // own account was killed user-level. The bare frame
160+ // orders the tab out, and the stream closes behind
161+ // it — a dead account's connection has no further
162+ // business staying open.
163+ if let Topic::Revoked(_) = topic {
164+ return Some((
165+ Ok(Event::new().data(REVOKED)),
166+ (rx, true, admin, me, deadline, stopping),
167+ ));
168+ }
144 let frame = Frame {169 let frame = Frame {
145 topic: topic.kind(),170 topic: topic.kind(),
146 id: topic.id(),171 id: topic.id(),
@@ -149,12 +174,15 @@ async fn live(cx: &Cx) -> topcoat::Result<Response> {
149 match Event::new().json_data(&frame) {174 match Event::new().json_data(&frame) {
150 Ok(event) => event,175 Ok(event) => event,
151 Err(problem) => {176 Err(problem) => {
152- return Some((Err(problem), (rx, admin, me, deadline, stopping)));177+ return Some((
178+ Err(problem),
179+ (rx, sealing, admin, me, deadline, stopping),
180+ ));
153 }181 }
154 }182 }
155 }183 }
156 };184 };
157- return Some((Ok(frame), (rx, admin, me, deadline, stopping)));185+ return Some((Ok(frame), (rx, sealing, admin, me, deadline, stopping)));
158 }186 }
159 },187 },
160 );188 );
crates/in-web/src/main.rsmodified+242 -10
@@ -365,15 +365,19 @@ async fn shutdown_signal() {
365 const IDENTITY_BACKOFF_CAP: std::time::Duration = std::time::Duration::from_secs(30);365 const IDENTITY_BACKOFF_CAP: std::time::Duration = std::time::Duration::from_secs(30);
366 366
367 /// Mirrors one member's identity into the local row: the JIT upsert that367 /// Mirrors one member's identity into the local row: the JIT upsert that
368-/// keeps address, name, admin flag and photo stamp following im. The store368+/// keeps address, name, admin flag and photo stamp following im — and the
369-/// announces a `profile` change itself when a mirrored field moved, so the369+/// disablement flag with it, both directions, for the row is im's word on
370-/// only job left here is the write and its one log line when it fails.370+/// the person and a re-enable must land here as surely as a kill. The
371+/// store announces a `profile` change itself when a mirrored field moved,
372+/// and a flipped disablement announces the admin surface, the profile and
373+/// the person's own tabs all at once, so the only job left here is the
374+/// write and its one log line when it fails.
371 async fn mirror_member(375 async fn mirror_member(
372 store: &Arc<dyn in_core::store::Store>,376 store: &Arc<dyn in_core::store::Store>,
373 member: &im_client::directory::DirectoryMember,377 member: &im_client::directory::DirectoryMember,
374 default_quota_bytes: u64,378 default_quota_bytes: u64,
375 ) {379 ) {
376- if let Err(problem) = store380+ let user = match store
377 .provision_user(381 .provision_user(
378 &member.sub,382 &member.sub,
379 &member.email,383 &member.email,
@@ -384,7 +388,19 @@ async fn mirror_member(
384 )388 )
385 .await389 .await
386 {390 {
387- eprintln!("in: directory mirror of {}: {problem}", member.sub);391+ Ok(user) => user,
392+ Err(problem) => {
393+ eprintln!("in: directory mirror of {}: {problem}", member.sub);
394+ return;
395+ }
396+ };
397+ if user.disabled != member.disabled
398+ && let Err(problem) = store.set_user_disabled(&user.id, member.disabled).await
399+ {
400+ eprintln!(
401+ "in: directory disablement mirror of {}: {problem}",
402+ member.sub
403+ );
388 }404 }
389 }405 }
390 406
@@ -420,11 +436,14 @@ async fn identity_sync(
420 health.connected();436 health.connected();
421 while let Some(event) = stream.next().await {437 while let Some(event) = stream.next().await {
422 match event {438 match event {
423- Ok(im_client::directory::DirectoryEvent::Profile(member)) => {439+ Ok(event) => {
424- mirror_member(&store, &member, default_quota_bytes).await;440+ apply_directory_event(
425- // Every event is proof the feed is alive;441+ &store,
426- // the card's age line reads this.442+ &health,
427- health.note_event();443+ event,
444+ default_quota_bytes,
445+ )
446+ .await;
428 }447 }
429 // A network failure ends the stream; the full448 // A network failure ends the stream; the full
430 // pass below re-lists before the redial.449 // pass below re-lists before the redial.
@@ -456,6 +475,50 @@ async fn identity_sync(
456 }475 }
457 }476 }
458 477
478+/// One event off the directory stream, applied to the local mirror. The
479+/// seam exists so the tests can drive a constructed event through the
480+/// same door identity_sync's stream loop uses — the loop itself only
481+/// knows how to read the wire.
482+async fn apply_directory_event(
483+ store: &Arc<dyn in_core::store::Store>,
484+ health: &in_web::server::DirectoryHealth,
485+ event: im_client::directory::DirectoryEvent,
486+ default_quota_bytes: u64,
487+) {
488+ match event {
489+ im_client::directory::DirectoryEvent::Profile(member) => {
490+ mirror_member(store, &member, default_quota_bytes).await;
491+ }
492+ // Sessions died at im; no local row moved. Wake the person
493+ // through the profile topic — their tabs refetch, meet the dead
494+ // introspection, and morph to the sign-in card.
495+ im_client::directory::DirectoryEvent::Revoked { sub } => {
496+ announce_revocation(store, &sub).await;
497+ }
498+ }
499+ // Every event is proof the feed is alive; the card's age line reads
500+ // this.
501+ health.note_event();
502+}
503+
504+/// The session-targeted half of a directory revocation: im revoked the
505+/// person's sessions and no local row moved, but every tab carrying them
506+/// must find out. The row is woken through the ordinary profile
507+/// announcement — the one topic every signed-in reader may hear — so the
508+/// revoked person's own tabs refetch, meet a dead introspection, and
509+/// morph to the sign-in card: the whole of what a session-level logout
510+/// looks like from here. No hard redirect: which of the person's
511+/// sessions died is im's knowledge alone, and a surviving tab must not
512+/// be ordered out for its sibling's death.
513+async fn announce_revocation(store: &Arc<dyn in_core::store::Store>, sub: &str) {
514+ match store.user_by_oidc_sub(sub).await {
515+ Ok(Some(user)) => store.announce_profile(&user.id),
516+ // Nobody local carries this subject: nobody here to wake.
517+ Ok(None) => {}
518+ Err(problem) => eprintln!("in: revocation wake for {sub}: {problem}"),
519+ }
520+}
521+
459 /// How often the suite list is re-fetched from im. Short enough that a522 /// How often the suite list is re-fetched from im. Short enough that a
460 /// service the admin adds over there shows up here before anyone goes523 /// service the admin adds over there shows up here before anyone goes
461 /// looking for its wordmark, long enough that the two are not talking524 /// looking for its wordmark, long enough that the two are not talking
@@ -510,3 +573,172 @@ async fn family_sync(
510 tokio::time::sleep(std::time::Duration::from_secs(FAMILY_SECONDS)).await;573 tokio::time::sleep(std::time::Duration::from_secs(FAMILY_SECONDS)).await;
511 }574 }
512 }575 }
576+
577+#[cfg(test)]
578+mod tests {
579+ use super::*;
580+ use in_core::store::Store;
581+
582+ /// A revoked session at im wakes the person's row by its local id:
583+ /// one profile announcement, heard by every signed-in reader, with
584+ /// the person's own tabs morphing to the sign-in card on the refetch.
585+ /// A subject that never signed in here wakes nobody.
586+ #[tokio::test]
587+ async fn a_revoked_session_wakes_the_persons_row_through_the_profile_topic() {
588+ let dir = std::env::temp_dir().join(format!("in-revoke-{}", ulid::Ulid::generate()));
589+ std::fs::create_dir_all(&dir).unwrap();
590+ let store: Arc<dyn in_core::store::Store> = Arc::new(
591+ in_core::store::TursoStore::open(
592+ dir.join("in.db").to_str().unwrap(),
593+ Some(&dir.join("storage")),
594+ )
595+ .await
596+ .unwrap(),
597+ );
598+ let user = store
599+ .provision_user("sub-gone", "gone@in.test", "Gone", None, 0, 1024)
600+ .await
601+ .unwrap();
602+ let mut rx = store.subscribe();
603+
604+ announce_revocation(&store, "sub-gone").await;
605+
606+ let change = rx.try_recv().unwrap();
607+ assert_eq!(change.topic.kind(), "profile");
608+ assert_eq!(change.topic.id(), user.id);
609+ assert!(matches!(
610+ rx.try_recv(),
611+ Err(tokio::sync::broadcast::error::TryRecvError::Empty)
612+ ));
613+
614+ announce_revocation(&store, "sub-unknown").await;
615+ assert!(matches!(
616+ rx.try_recv(),
617+ Err(tokio::sync::broadcast::error::TryRecvError::Empty)
618+ ));
619+
620+ drop(store);
621+ let _ = std::fs::remove_dir_all(&dir);
622+ }
623+
624+ /// One roster member as the wire carries it.
625+ fn member(sub: &str, disabled: bool) -> im_client::directory::DirectoryMember {
626+ im_client::directory::DirectoryMember {
627+ sub: sub.to_string(),
628+ email: format!("{sub}@in.test"),
629+ name: "Member".to_string(),
630+ admin: false,
631+ photo_version: 0,
632+ timezone: "UTC+03:00".to_string(),
633+ disabled,
634+ }
635+ }
636+
637+ async fn scratch() -> (std::path::PathBuf, Arc<dyn in_core::store::Store>) {
638+ let dir = std::env::temp_dir().join(format!("in-event-{}", ulid::Ulid::generate()));
639+ std::fs::create_dir_all(&dir).unwrap();
640+ let store: Arc<dyn in_core::store::Store> = Arc::new(
641+ in_core::store::TursoStore::open(
642+ dir.join("in.db").to_str().unwrap(),
643+ Some(&dir.join("storage")),
644+ )
645+ .await
646+ .unwrap(),
647+ );
648+ (dir, store)
649+ }
650+
651+ /// A `revoked` frame off the stream — im's word that the subject's
652+ /// sessions died — wakes the person's row by its local id through
653+ /// the profile topic, and stamps the connection card's freshness.
654+ #[tokio::test]
655+ async fn a_stream_revocation_announces_through_the_profile_topic() {
656+ let (dir, store) = scratch().await;
657+ let health = in_web::server::DirectoryHealth::new();
658+ let user = store
659+ .provision_user("sub-gone", "gone@in.test", "Gone", None, 0, 1024)
660+ .await
661+ .unwrap();
662+ let mut rx = store.subscribe();
663+
664+ apply_directory_event(
665+ &store,
666+ &health,
667+ im_client::directory::DirectoryEvent::Revoked {
668+ sub: "sub-gone".to_string(),
669+ },
670+ 1024,
671+ )
672+ .await;
673+
674+ let change = rx.try_recv().unwrap();
675+ assert_eq!(change.topic.kind(), "profile");
676+ assert_eq!(change.topic.id(), user.id);
677+ assert!(matches!(
678+ rx.try_recv(),
679+ Err(tokio::sync::broadcast::error::TryRecvError::Empty)
680+ ));
681+ assert!(health.last_event_age_secs().is_some());
682+
683+ drop(store);
684+ let _ = std::fs::remove_dir_all(&dir);
685+ }
686+
687+ /// The member's disablement flag follows im in both directions: a
688+ /// `profile` frame carrying `disabled` flips the local row and — the
689+ /// part the tabs wait for — the store announces the kill (and, on
690+ /// the way back, the reopening) on all three surfaces at once.
691+ #[tokio::test]
692+ async fn a_members_disabled_flag_mirrors_both_ways() {
693+ let (dir, store) = scratch().await;
694+ let health = in_web::server::DirectoryHealth::new();
695+ let mut rx = store.subscribe();
696+
697+ // First sight: the mirror inserts the row, present and enabled.
698+ apply_directory_event(
699+ &store,
700+ &health,
701+ im_client::directory::DirectoryEvent::Profile(member("sub-m", false)),
702+ 1024,
703+ )
704+ .await;
705+ let user = store.user_by_oidc_sub("sub-m").await.unwrap().unwrap();
706+ assert!(!user.disabled);
707+ // A fresh row announces the admin surface and the profile — the
708+ // two reads that keep the later phases' queues clean.
709+ assert_eq!(rx.try_recv().unwrap().topic.kind(), "admin");
710+ assert_eq!(rx.try_recv().unwrap().topic.kind(), "profile");
711+ // im switches the member off: the row follows, and the revoked
712+ // frame rides to the person's own tabs.
713+ apply_directory_event(
714+ &store,
715+ &health,
716+ im_client::directory::DirectoryEvent::Profile(member("sub-m", true)),
717+ 1024,
718+ )
719+ .await;
720+ let killed = store.user_by_oidc_sub("sub-m").await.unwrap().unwrap();
721+ assert!(killed.disabled);
722+ assert_eq!(rx.try_recv().unwrap().topic.kind(), "admin");
723+ assert_eq!(rx.try_recv().unwrap().topic.kind(), "profile");
724+ assert_eq!(rx.try_recv().unwrap().topic.kind(), "revoked");
725+
726+ // im lets them back in: the same channel carries the reopening.
727+ apply_directory_event(
728+ &store,
729+ &health,
730+ im_client::directory::DirectoryEvent::Profile(member("sub-m", false)),
731+ 1024,
732+ )
733+ .await;
734+ let back = store.user_by_oidc_sub("sub-m").await.unwrap().unwrap();
735+ assert!(!back.disabled);
736+ assert_eq!(rx.try_recv().unwrap().topic.kind(), "admin");
737+ assert_eq!(rx.try_recv().unwrap().topic.kind(), "profile");
738+ assert_eq!(rx.try_recv().unwrap().topic.kind(), "revoked");
739+ assert!(health.last_event_age_secs().is_some());
740+
741+ drop(store);
742+ let _ = std::fs::remove_dir_all(&dir);
743+ }
744+}
crates/in-web/src/server.rsmodified+17 -1
@@ -20,7 +20,7 @@ use sha2::Digest;
20 use topcoat::asset::AssetBundle;20 use topcoat::asset::AssetBundle;
21 use topcoat::context::{Cx, app_context, memoize};21 use topcoat::context::{Cx, app_context, memoize};
22 use topcoat::router::request::headers;22 use topcoat::router::request::headers;
23-use topcoat::router::{Body, HeaderValue, Next, StatusCode, header, response::Response, to_bytes};23+use topcoat::router::{Body, HeaderValue, Next, StatusCode, header, response::{IntoResponse, Response}, route, to_bytes};
24 24
25 /// The whole application context, put into the router by `main.rs`. One25 /// The whole application context, put into the router by `main.rs`. One
26 /// struct rather than three separate contexts so a route needing two of them26 /// 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<User, Refusal> {
301 }301 }
302 }302 }
303 303
304+/// The sign-in probe the live channel's error path polls: 204 while this
305+/// browser carries a live session, 401 the moment it does not — no HTML,
306+/// no body, nothing but the answer. It exists for the one question an open
307+/// tab can ask mid-flight ("am I still signed in?") without dragging a
308+/// page render behind it. A store failure answers 500 rather than 401:
309+/// the probe's whole contract is that only a real sign-out draws the 401,
310+/// and a broken database must never fake one.
311+#[route(GET "/api/me")]
312+pub async fn me(cx: &Cx) -> topcoat::Result<Response> {
313+ match current_user(cx).await {
314+ Ok(Some(_)) => (StatusCode::NO_CONTENT, "").into_response(cx),
315+ Ok(None) => (StatusCode::UNAUTHORIZED, "").into_response(cx),
316+ Err(_) => (StatusCode::INTERNAL_SERVER_ERROR, "").into_response(cx),
317+ }
318+}
319+
304 /// The admin behind this request. Anyone else is refused *here*, not320 /// The admin behind this request. Anyone else is refused *here*, not
305 /// merely hidden from in the UI.321 /// merely hidden from in the UI.
306 pub async fn require_admin(cx: &Cx) -> Result<User, Refusal> {322 pub async fn require_admin(cx: &Cx) -> Result<User, Refusal> {
crates/in-web/tests/http.rsmodified+160 -0
@@ -10,6 +10,7 @@
10 //! New HTTP tests belong in this file rather than a new `tests/*.rs`: one10 //! New HTTP tests belong in this file rather than a new `tests/*.rs`: one
11 //! test binary links and runs once.11 //! test binary links and runs once.
12 use http::{HeaderValue, Request, StatusCode, header};12 use http::{HeaderValue, Request, StatusCode, header};
13+use http_body_util::BodyExt;
13 use in_core::{Config, OidcConfig};14 use in_core::{Config, OidcConfig};
14 use std::collections::HashMap;15 use std::collections::HashMap;
15 use std::path::PathBuf;16 use std::path::PathBuf;
@@ -6040,3 +6041,162 @@ async fn the_family_limit_lands_on_the_account() {
6040 let holder = app.store.user(&user_id).await.unwrap().unwrap();6041 let holder = app.store.user(&user_id).await.unwrap().unwrap();
6041 assert_eq!(holder.quota_bytes, 1024 * 1024);6042 assert_eq!(holder.quota_bytes, 1024 * 1024);
6042 }6043 }
6044+
6045+/// How long one wait for a live frame may run before the test fails
6046+/// loudly. A stream that never speaks is a hang, not an answer.
6047+const FRAME_PATIENCE: std::time::Duration = std::time::Duration::from_secs(5);
6048+
6049+/// One open `/api/live` connection, held the way a browser holds it: the
6050+/// frames are read as they arrive, and the end of the body is itself
6051+/// news — a stream the server closed behind its last word.
6052+struct LiveStream {
6053+ status: StatusCode,
6054+ content_type: Option<String>,
6055+ body: Body,
6056+ /// Bytes read but not yet through a blank-line frame boundary; an
6057+ /// SSE event may straddle two body chunks.
6058+ buffer: String,
6059+}
6060+
6061+impl LiveStream {
6062+ /// The next complete SSE frame, or `None` when the stream ended. A
6063+ /// frame that never arrives fails the test rather than outlasting it.
6064+ async fn next_frame(&mut self) -> Option<String> {
6065+ loop {
6066+ if let Some(at) = self.buffer.find("\n\n") {
6067+ return Some(self.buffer.drain(..at + 2).collect::<String>());
6068+ }
6069+ let polled = tokio::time::timeout(FRAME_PATIENCE, self.body.frame())
6070+ .await
6071+ .expect("no frame arrived in time");
6072+ // `None` is the body running out — the stream's end, which is
6073+ // the caller's news. Anything else is a frame to buffer.
6074+ let Some(polled) = polled else {
6075+ return None;
6076+ };
6077+ let frame = polled.expect("the live body failed");
6078+ let chunk = frame.into_data().expect("a frame with no data");
6079+ self.buffer.push_str(&String::from_utf8_lossy(&chunk));
6080+ }
6081+ }
6082+}
6083+
6084+impl TestApp {
6085+ /// Opens the signed-in live stream and keeps it, unread — the frame
6086+ /// reader works on the body [`LiveStream`] holds.
6087+ async fn open_live(&self, cookie: &str) -> LiveStream {
6088+ let response = self
6089+ .router
6090+ .handle(
6091+ Request::builder()
6092+ .method("GET")
6093+ .uri("/api/live")
6094+ .header(header::COOKIE, HeaderValue::from_str(cookie).unwrap())
6095+ .body(Body::empty())
6096+ .unwrap(),
6097+ )
6098+ .await;
6099+ let status = response.status();
6100+ let content_type = response
6101+ .headers()
6102+ .get(header::CONTENT_TYPE)
6103+ .and_then(|value| value.to_str().ok())
6104+ .map(str::to_string);
6105+ LiveStream {
6106+ status,
6107+ content_type,
6108+ body: response.into_body(),
6109+ buffer: String::new(),
6110+ }
6111+ }
6112+}
6113+
6114+/// The sign-in probe the live channel's error path polls: 204 while the
6115+/// session stands, 401 the moment it does not. A locally disabled
6116+/// account reads as signed out even though im's introspection would
6117+/// still vouch for the very same cookie — the local flag outranks it.
6118+#[tokio::test]
6119+async fn the_me_probe_answers_204_while_signed_in_and_401_the_moment_not() {
6120+ let app = TestApp::build().await;
6121+ let out = app.get("/api/me", None).await;
6122+ assert_eq!(out.status, StatusCode::UNAUTHORIZED);
6123+ assert!(out.bytes.is_empty(), "no body: {:?}", out.text());
6124+
6125+ let cookie = app.sign_in("sub-probe", "probe@in.test", "Probe").await;
6126+ let in_answer = app.get("/api/me", Some(&cookie)).await;
6127+ assert_eq!(in_answer.status, StatusCode::NO_CONTENT);
6128+ assert!(in_answer.bytes.is_empty(), "no body on 204 either");
6129+
6130+ let user = app.store.user_by_oidc_sub("sub-probe").await.unwrap().unwrap();
6131+ app.store.set_user_disabled(&user.id, true).await.unwrap();
6132+ let disabled = app.get("/api/me", Some(&cookie)).await;
6133+ assert_eq!(disabled.status, StatusCode::UNAUTHORIZED);
6134+}
6135+
6136+/// A user-level kill — the disabled flag mirrored from im — rides the
6137+/// ordinary topic bus, but its frame goes to exactly one listener: the
6138+/// killed account's own open tabs, each answered with the bare revoked
6139+/// frame and then an ended stream. Everybody else hears an ordinary
6140+/// profile move and keeps their stream.
6141+#[tokio::test]
6142+async fn a_user_level_kill_orders_its_own_tabs_out_and_nobody_else() {
6143+ let app = TestApp::build().await;
6144+ let alice_cookie = app.sign_in("sub-alice", "alice@in.test", "Alice").await;
6145+ let bob_cookie = app.sign_in("sub-bob", "bob@in.test", "Bob").await;
6146+ let mut alice = app.open_live(&alice_cookie).await;
6147+ let mut bob = app.open_live(&bob_cookie).await;
6148+ assert_eq!(alice.status, StatusCode::OK);
6149+ assert_eq!(
6150+ alice.content_type.as_deref(),
6151+ Some("text/event-stream"),
6152+ "the live channel is an event stream"
6153+ );
6154+
6155+ // The kill: im's mirror flips the local flag; the store announces.
6156+ let alice_id = app
6157+ .store
6158+ .user_by_oidc_sub("sub-alice")
6159+ .await
6160+ .unwrap()
6161+ .unwrap()
6162+ .id;
6163+ app.store.set_user_disabled(&alice_id, true).await.unwrap();
6164+
6165+ // Bob hears the profile move — and only that. The revoked frame is
6166+ // an order no bystander ever receives.
6167+ let heard = bob.next_frame().await.unwrap();
6168+ assert!(
6169+ heard.contains("\"topic\":\"profile\""),
6170+ "bob heard: {heard}"
6171+ );
6172+
6173+ // Alice hears her own kill as the bare frame, and the stream ends
6174+ // behind it — nothing on a dead account's connection lingers.
6175+ loop {
6176+ let heard = alice.next_frame().await.unwrap();
6177+ if heard.contains("\"topic\":\"revoked\"") {
6178+ break;
6179+ }
6180+ }
6181+ assert!(
6182+ alice.next_frame().await.is_none(),
6183+ "the killed tab's stream must end behind the revoked frame"
6184+ );
6185+
6186+ // Bob's stream survived Alice's kill: his own kill reaches it.
6187+ let bob_id = app
6188+ .store
6189+ .user_by_oidc_sub("sub-bob")
6190+ .await
6191+ .unwrap()
6192+ .unwrap()
6193+ .id;
6194+ app.store.set_user_disabled(&bob_id, true).await.unwrap();
6195+ loop {
6196+ let heard = bob.next_frame().await.unwrap();
6197+ if heard.contains("\"topic\":\"revoked\"") {
6198+ break;
6199+ }
6200+ }
6201+ assert!(bob.next_frame().await.is_none(), "bob's stream ends too");
6202+}