From f4152e1951a04a198d6c73c815bbd6d4d2a4a069 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] iz: live session-revocation logout - Topic::Revoked(local_id); /api/live names the killed user's own connections then ends the stream; enable publishes Members only - iz-owned /directory/live parser (pin untouched): unknown kinds skipped, CRLF-straddle safe (cr_ended), revoked{sub} -> Members announce, disabled reconciled both directions - client: revoked frame or /api/me 401 on SSE error -> hard navigate to / - new GET /api/me (204/401) --- crates/iz-core/src/live.rs | 8 + crates/iz-core/src/store/mod.rs | 12 + crates/iz-core/src/store/turso_store.rs | 119 ++++--- crates/iz-core/tests/store.rs | 10 +- crates/iz-web/src/directory.rs | 433 +++++++++++++++++++++++- crates/iz-web/src/layout.rs | 14 + crates/iz-web/src/live.rs | 36 +- crates/iz-web/src/main.rs | 21 +- crates/iz-web/src/server.rs | 19 +- crates/iz-web/tests/http.rs | 175 ++++++++++ 10 files changed, 779 insertions(+), 68 deletions(-) diff --git a/crates/iz-core/src/live.rs b/crates/iz-core/src/live.rs index 033f748..f7c8c7b 100644 --- a/crates/iz-core/src/live.rs +++ b/crates/iz-core/src/live.rs @@ -24,6 +24,12 @@ pub enum Topic { Task(String), /// Users, roles, invites, sessions, photos, profile. Members, + /// One account was killed at the provider — disabled, or gone. The id + /// is the local row's, and the frame names it to exactly one reader: + /// the connection whose own id it is. A session revocation does not + /// ride here — which session died is the provider's knowledge, and a + /// tab whose other session survived must not be sent away. + Revoked(String), /// The mail queue: `mail_send` rows. Queue, /// Mail rules and the decisions they made. @@ -45,6 +51,7 @@ impl Topic { Topic::Board => "board", Topic::Task(_) => "task", Topic::Members => "members", + Topic::Revoked(_) => "revoked", Topic::Queue => "queue", Topic::Rules => "rules", Topic::Tags => "tags", @@ -57,6 +64,7 @@ impl Topic { pub fn id(&self) -> Option<&str> { match self { Topic::Task(id) => Some(id), + Topic::Revoked(id) => Some(id), _ => None, } } diff --git a/crates/iz-core/src/store/mod.rs b/crates/iz-core/src/store/mod.rs index 4018a71..160e42e 100644 --- a/crates/iz-core/src/store/mod.rs +++ b/crates/iz-core/src/store/mod.rs @@ -756,6 +756,13 @@ pub trait Store: BoardReads + DetailReads + 'static { /// role-gated route. Sending to zero subscribers is normal and silent, /// and a slow subscriber's overflow is the client's cue to resync. fn subscribe(&self) -> tokio::sync::broadcast::Receiver; + + /// Announces topics with no write behind them — the door for facts that + /// arrive from outside this database, such as a revoked session heard on + /// im's directory stream. This only wakes the subscribers, exactly as a + /// committed write would; which connection is told remains the live + /// channel's own role decision. + fn announce(&self, topics: &[crate::live::Topic]); // -- workspace --------------------------------------------------------- /// The account that claimed the workspace, if it has been claimed. @@ -888,6 +895,11 @@ pub trait Store: BoardReads + DetailReads + 'static { /// an address has an account. async fn user_by_email(&self, workspace_id: &str, email: &str) -> Result>; + /// Lookup by provider subject — the key im's directory stream names when + /// it announces a revoked or disabled member. `None` is a subject this + /// workspace has never provisioned. + async fn user_by_sub(&self, sub: &str) -> Result>; + async fn users(&self, workspace_id: &str) -> Result>; async fn count_users(&self, workspace_id: &str) -> Result; diff --git a/crates/iz-core/src/store/turso_store.rs b/crates/iz-core/src/store/turso_store.rs index 05cf83c..45bbc4a 100644 --- a/crates/iz-core/src/store/turso_store.rs +++ b/crates/iz-core/src/store/turso_store.rs @@ -74,7 +74,7 @@ impl TursoStore { /// of a server nobody is looking at. It is dropped on purpose: an /// announcement nobody is waiting for is not a problem, and logging it /// would fill the log with the sound of an idle app. - fn announce(&self, topics: impl IntoIterator) { + fn publish(&self, topics: impl IntoIterator) { for topic in topics { let _ = self.live.send(Change { topic, @@ -1403,6 +1403,10 @@ impl Store for TursoStore { self.live.subscribe() } + fn announce(&self, topics: &[crate::live::Topic]) { + self.publish(topics.iter().cloned()) + } + async fn provision_user( &self, sub: &str, @@ -1592,7 +1596,7 @@ impl Store for TursoStore { // provider-side rename or role flip, an owner claim. Anything louder // would re-render every members-watching tab on every request. if changed { - self.announce([Topic::Members]); + self.publish([Topic::Members]); } self.user(&id).await?.ok_or(StoreError::NotFound) } @@ -1752,7 +1756,7 @@ impl Store for TursoStore { tx.commit().await.map_err(backend)?; drop(conn); if sync != MemberSync::Untouched { - self.announce([Topic::Members]); + self.publish([Topic::Members]); } Ok(sync) } @@ -1820,7 +1824,7 @@ impl Store for TursoStore { Err(e) => return Err(backend(e)), } drop(conn); - self.announce([Topic::Members]); + self.publish([Topic::Members]); self.user(&id).await?.ok_or(StoreError::NotFound) } @@ -1879,7 +1883,7 @@ impl Store for TursoStore { .await .map_err(backend)?; drop(conn); - self.announce([Topic::Settings]); + self.publish([Topic::Settings]); Ok(()) } @@ -1898,7 +1902,7 @@ impl Store for TursoStore { .await .map_err(backend)?; drop(conn); - self.announce([Topic::Settings]); + self.publish([Topic::Settings]); Ok(()) } @@ -1917,7 +1921,7 @@ impl Store for TursoStore { .await .map_err(backend)?; drop(conn); - self.announce([Topic::Settings]); + self.publish([Topic::Settings]); Ok(()) } @@ -1951,7 +1955,7 @@ impl Store for TursoStore { .await .map_err(backend)?; drop(conn); - self.announce([Topic::Settings]); + self.publish([Topic::Settings]); Ok(()) } @@ -2003,7 +2007,7 @@ impl Store for TursoStore { .await .map_err(backend)?; drop(conn); - self.announce([Topic::Settings]); + self.publish([Topic::Settings]); Ok(()) } @@ -2026,6 +2030,14 @@ impl Store for TursoStore { } } + async fn user_by_sub(&self, sub: &str) -> Result> { + let sql = format!("SELECT {USER_COLUMNS} FROM user WHERE oidc_sub = ?1"); + match self.one_row(&sql, params![sub]).await? { + Some(row) => Ok(Some(user_from(&row)?)), + None => Ok(None), + } + } + async fn users(&self, workspace_id: &str) -> Result> { let conn = self.conn.lock().await; let sql = format!( @@ -2115,7 +2127,7 @@ impl Store for TursoStore { Err(StoreError::NotFound) } else { drop(conn); - self.announce([Topic::Members]); + self.publish([Topic::Members]); Ok(()) } } @@ -2164,7 +2176,7 @@ impl Store for TursoStore { } tx.commit().await.map_err(backend)?; drop(conn); - self.announce(topics); + self.publish(topics); Ok(()) } @@ -2181,7 +2193,16 @@ impl Store for TursoStore { Err(StoreError::NotFound) } else { drop(conn); - self.announce([Topic::Members]); + // The member list moves either way. The kill naming is one + // directional: only a disable names the account's own open tabs + // so they can leave — an enable is a homecoming, and a frame + // saying "you were revoked" as the door reopens would send + // somebody away at the wrong moment. + if disabled { + self.publish([Topic::Members, Topic::Revoked(user_id.to_string())]); + } else { + self.publish([Topic::Members]); + } Ok(()) } } @@ -2205,7 +2226,7 @@ impl Store for TursoStore { .await .map_err(backend)?; drop(conn); - self.announce([Topic::Board]); + self.publish([Topic::Board]); Ok(Column { id, name: name.to_string(), @@ -2393,7 +2414,7 @@ impl Store for TursoStore { if reminded { topics.push(Topic::Queue); } - self.announce(topics); + self.publish(topics); let (task_key, position) = written; Ok(TaskCreated { row: TaskRow { @@ -2495,7 +2516,7 @@ impl Store for TursoStore { match outcome { Ok(Ok(())) => { tx.commit().await.map_err(backend)?; - self.announce([Topic::Board, Topic::Task(task_id.to_string())]); + self.publish([Topic::Board, Topic::Task(task_id.to_string())]); Ok(()) } Ok(Err(refused)) => { @@ -2575,7 +2596,7 @@ impl Store for TursoStore { if reminded { topics.push(Topic::Queue); } - self.announce(topics); + self.publish(topics); } Ok(()) } @@ -2615,7 +2636,7 @@ impl Store for TursoStore { if reminded { topics.push(Topic::Queue); } - self.announce(topics); + self.publish(topics); } Ok(()) } @@ -2721,7 +2742,7 @@ impl Store for TursoStore { Ok(true) => { tx.commit().await.map_err(backend)?; // An edge is visible from both endpoints and on the board. - self.announce([ + self.publish([ Topic::Board, Topic::Task(blocked_task_id.to_string()), Topic::Task(blocking_task_id.to_string()), @@ -2756,7 +2777,7 @@ impl Store for TursoStore { .map_err(backend)?; drop(conn); if n > 0 { - self.announce([ + self.publish([ Topic::Board, Topic::Task(blocked_task_id.to_string()), Topic::Task(blocking_task_id.to_string()), @@ -2811,7 +2832,7 @@ impl Store for TursoStore { } tx.commit().await.map_err(backend)?; - self.announce([Topic::Task(task_id.to_string()), Topic::Activity]); + self.publish([Topic::Task(task_id.to_string()), Topic::Activity]); Ok(CommentWritten { comment_id, activity_id, @@ -2852,7 +2873,7 @@ impl Store for TursoStore { return Err(backend(e)); } drop(conn); - self.announce([Topic::Task(new.task_id.to_string())]); + self.publish([Topic::Task(new.task_id.to_string())]); Ok(id) } @@ -2932,7 +2953,7 @@ impl Store for TursoStore { // the boot sweep collects. let _ = std::fs::remove_file(attachment_file(&self.storage, id)); if let Some(task_id) = owner { - self.announce([Topic::Task(task_id)]); + self.publish([Topic::Task(task_id)]); } } Ok(gone > 0) @@ -2951,7 +2972,7 @@ impl Store for TursoStore { .await .map_err(backend)?; drop(conn); - self.announce([Topic::Settings]); + self.publish([Topic::Settings]); Ok(()) } @@ -2986,7 +3007,7 @@ impl Store for TursoStore { .await .map_err(backend)?; drop(conn); - self.announce([Topic::Task(new.task_id.to_string())]); + self.publish([Topic::Task(new.task_id.to_string())]); Ok(new.id) } @@ -3033,7 +3054,7 @@ impl Store for TursoStore { // orphaned bytes the boot sweep collects. let _ = std::fs::remove_file(attachment_file(&self.storage, id)); if let Some(task_id) = owner { - self.announce([Topic::Task(task_id)]); + self.publish([Topic::Task(task_id)]); } } Ok(moved > 0) @@ -3055,7 +3076,7 @@ impl Store for TursoStore { } async fn announce_storage(&self) -> Result<()> { - self.announce([Topic::Settings]); + self.publish([Topic::Settings]); Ok(()) } @@ -3171,7 +3192,7 @@ impl Store for TursoStore { if reminded { topics.push(Topic::Queue); } - self.announce(topics); + self.publish(topics); Ok(ids) } Ok(None) => { @@ -3374,7 +3395,7 @@ impl Store for TursoStore { if reminded { topics.push(Topic::Queue); } - self.announce(topics); + self.publish(topics); Ok(Moved::Recorded(Transition { id: transition_id, task_id: task_id.to_string(), @@ -3578,7 +3599,7 @@ impl Store for TursoStore { if reminded { topics.push(Topic::Queue); } - self.announce(topics); + self.publish(topics); Ok(deletion) } Ok(None) => { @@ -3694,7 +3715,7 @@ impl Store for TursoStore { .map_err(backend)?; drop(conn); // Task-scoped: the task's own trail and the workspace feed both grew. - self.announce([Topic::Activity, Topic::Task(task_id.to_string())]); + self.publish([Topic::Activity, Topic::Task(task_id.to_string())]); Ok(id) } @@ -3716,7 +3737,7 @@ impl Store for TursoStore { .map_err(backend)?; drop(conn); // Workspace-wide, belonging to no task — the feed only. - self.announce([Topic::Activity]); + self.publish([Topic::Activity]); Ok(id) } @@ -3754,7 +3775,7 @@ impl Store for TursoStore { ) .await .map_err(backend)?; - self.announce([Topic::Rules]); + self.publish([Topic::Rules]); let sql = format!("SELECT {RULE_COLUMNS} FROM mail_rule WHERE id = ?1"); match self.one_row(&sql, params![id]).await? { Some(row) => rule_from(&row), @@ -3804,7 +3825,7 @@ impl Store for TursoStore { return Err(StoreError::NotFound); } drop(conn); - self.announce([Topic::Rules]); + self.publish([Topic::Rules]); Ok(()) } @@ -3898,7 +3919,7 @@ impl Store for TursoStore { return Err(StoreError::NotFound); } drop(conn); - self.announce([Topic::Rules]); + self.publish([Topic::Rules]); Ok(()) } @@ -3915,7 +3936,7 @@ impl Store for TursoStore { } drop(conn); // The rule's queued mail cascaded away with it, so the queue moved too. - self.announce([Topic::Rules, Topic::Queue]); + self.publish([Topic::Rules, Topic::Queue]); Ok(()) } @@ -3979,7 +4000,7 @@ impl Store for TursoStore { return Ok(None); } // A mail joined the queue, so the queue panel is out of date. - self.announce([Topic::Queue]); + self.publish([Topic::Queue]); let sql = format!("SELECT {SEND_COLUMNS} FROM mail_send WHERE id = ?1"); match self.one_row(&sql, params![id]).await? { Some(row) => send_from(&row).map(ClaimedSend::taken).map(Some), @@ -4009,7 +4030,7 @@ impl Store for TursoStore { .map_err(backend)?; // Two surfaces at once: the invite is a queued mail, and an invited // person shows up in the members list before they ever sign in. - self.announce([Topic::Queue, Topic::Members]); + self.publish([Topic::Queue, Topic::Members]); let sql = format!("SELECT {SEND_COLUMNS} FROM mail_send WHERE id = ?1"); match self.one_row(&sql, params![id]).await? { Some(row) => send_from(&row), @@ -4037,7 +4058,7 @@ impl Store for TursoStore { ) .await .map_err(backend)?; - self.announce([Topic::Queue]); + self.publish([Topic::Queue]); let sql = format!("SELECT {SEND_COLUMNS} FROM mail_send WHERE id = ?1"); match self.one_row(&sql, params![id]).await? { Some(row) => send_from(&row), @@ -4064,7 +4085,7 @@ impl Store for TursoStore { // whose subscribers may turn round and read this store, and holding // the single connection while they do is how that deadlocks. drop(conn); - self.announce([Topic::Queue]); + self.publish([Topic::Queue]); Ok(()) } @@ -4103,7 +4124,7 @@ impl Store for TursoStore { drop(conn); // The attempt counter and the next-try time both just moved, and the // queue panel renders both. - self.announce([Topic::Queue]); + self.publish([Topic::Queue]); Ok(()) } @@ -4131,7 +4152,7 @@ impl Store for TursoStore { return Err(StoreError::NotFound); } drop(conn); - self.announce([Topic::Queue]); + self.publish([Topic::Queue]); Ok(()) } @@ -4261,7 +4282,7 @@ impl Store for TursoStore { .await .map_err(backend)?; drop(conn); - self.announce([Topic::Queue]); + self.publish([Topic::Queue]); Ok(()) } @@ -4297,7 +4318,7 @@ impl Store for TursoStore { .map_err(backend)?; drop(conn); // A decision is what the rules page's decisions tab renders. - self.announce([Topic::Rules]); + self.publish([Topic::Rules]); Ok(()) } @@ -4721,7 +4742,7 @@ impl Store for TursoStore { .map_err(backend)?; } drop(conn); - self.announce([Topic::Queue]); + self.publish([Topic::Queue]); Ok(()) } @@ -4840,7 +4861,7 @@ impl Store for TursoStore { }; tx.commit().await.map_err(backend)?; - self.announce([Topic::Board, Topic::Tags]); + self.publish([Topic::Board, Topic::Tags]); Ok(Tag { id, board_id: board_id.to_string(), @@ -4869,7 +4890,7 @@ impl Store for TursoStore { return Err(StoreError::NotFound); } drop(conn); - self.announce([Topic::Board, Topic::Tags]); + self.publish([Topic::Board, Topic::Tags]); Ok(()) } @@ -4941,7 +4962,7 @@ impl Store for TursoStore { } } tx.commit().await.map_err(backend)?; - self.announce([Topic::Board, Topic::Tags]); + self.publish([Topic::Board, Topic::Tags]); Ok(()) } @@ -5003,7 +5024,7 @@ impl Store for TursoStore { } } tx.commit().await.map_err(backend)?; - self.announce([Topic::Board, Topic::Tags]); + self.publish([Topic::Board, Topic::Tags]); Ok(()) } @@ -5032,7 +5053,7 @@ impl Store for TursoStore { return Err(StoreError::NotFound); } drop(conn); - self.announce([Topic::Board, Topic::Task(task_id.to_string()), Topic::Tags]); + self.publish([Topic::Board, Topic::Task(task_id.to_string()), Topic::Tags]); Ok(()) } } diff --git a/crates/iz-core/tests/store.rs b/crates/iz-core/tests/store.rs index b870b24..a81291c 100644 --- a/crates/iz-core/tests/store.rs +++ b/crates/iz-core/tests/store.rs @@ -5593,7 +5593,11 @@ fn every_writing_method_announces_or_is_named_here() { || chunk.contains("INSERT OR ") || chunk.contains("UPDATE ") || chunk.contains("DELETE FROM"); - if writes && !chunk.contains("announce(") && !SILENT_ON_PURPOSE.contains(&name) { + if writes + && !chunk.contains("publish(") + && !chunk.contains("announce(") + && !SILENT_ON_PURPOSE.contains(&name) + { silent.push(name.to_string()); } } @@ -5602,8 +5606,8 @@ fn every_writing_method_announces_or_is_named_here() { silent.is_empty(), "these methods change rows without announcing it, so the screens \ showing those rows will go stale until someone reloads by hand: {silent:?}. \ - Either call `self.announce(..)` after the write commits, or add the \ - method to SILENT_ON_PURPOSE with the reason." + Either call `self.publish(..)` (or the trait's `self.announce(..)`) after \ + the write commits, or add the method to SILENT_ON_PURPOSE with the reason." ); } diff --git a/crates/iz-web/src/directory.rs b/crates/iz-web/src/directory.rs index ad38b10..7b39cb3 100644 --- a/crates/iz-web/src/directory.rs +++ b/crates/iz-web/src/directory.rs @@ -1,5 +1,9 @@ -//! How the identity mirror stands against im — the facts the Settings -//! Connection card renders. The mirror task writes; the page reads. +//! How the identity mirror stands against im. Two halves: the facts the +//! Settings Connection card renders (the mirror task writes, the page +//! reads), and the live connection itself — held and parsed here rather +//! than through the pinned `im-client`, whose frame reader drops every +//! event kind it was not built for, and the feed now carries kinds this +//! app must hear. //! //! Deliberately dumb: one mutex over four plain fields, because the card //! renders once per view and the stream updates a few times a minute. The @@ -7,10 +11,14 @@ //! comes near this struct, so the render path cannot leak what it was never //! given. +use std::collections::VecDeque; use std::sync::Arc; use std::time::{Duration, Instant}; +use iz_core::Topic; +use iz_core::store::Store; use parking_lot::Mutex; +use serde::Deserialize; use topcoat::context::{Cx, try_app_context}; /// The mirror's health, shared between the stream task and the renderer. @@ -97,3 +105,424 @@ pub fn age_text(age: Option) -> String { None => String::new(), } } + +/// Where the live half of the mirror connects. The same issuer and Basic +/// pair the roster client holds, kept apart from it because the stream is +/// read here, frame by frame, rather than through the pinned `im-client` — +/// whose parser drops every event kind it was not built for, and this feed +/// now carries kinds this app must hear. +#[derive(Clone)] +pub struct StreamSource { + http: reqwest::Client, + issuer: String, + client_id: String, + client_secret: String, +} + +impl StreamSource { + pub fn new( + issuer: impl Into, + client_id: impl Into, + client_secret: impl Into, + ) -> Self { + Self { + http: reqwest::Client::new(), + issuer: issuer.into(), + client_id: client_id.into(), + client_secret: client_secret.into(), + } + } + + /// `GET /directory/live`, the connection held with no timeout: a change + /// feed is *supposed* to sit idle, and its liveness is im's keep-alive + /// comment. + pub async fn open_stream(&self) -> Result { + let response = self + .http + .get(format!("{}/directory/live", self.issuer)) + .basic_auth(&self.client_id, Some(&self.client_secret)) + .send() + .await + .map_err(|e| e.to_string())? + .error_for_status() + .map_err(|e| e.to_string())?; + Ok(DirectoryStream { + response, + reader: FrameReader::default(), + }) + } +} + +/// One member's row exactly as the stream carries it: the roster's shape +/// plus the `disabled` fact the roster itself never shows — im's +/// `/directory` lists nobody disabled, so the flag travels only here. +/// Unknown fields are ignored, so an im newer than this build can grow the +/// row without a breaking change. +#[derive(Debug, Clone, PartialEq, Deserialize)] +pub struct StreamMember { + pub sub: String, + pub email: String, + pub name: String, + #[serde(default)] + pub admin: bool, + #[serde(default)] + pub photo_version: u64, + #[serde(default = "default_timezone")] + pub timezone: String, + #[serde(default)] + pub disabled: bool, +} + +/// The timezone im starts every account on, and the one a mirrored row +/// predating the field reads as. +fn default_timezone() -> String { + "UTC+03:00".to_string() +} + +/// One event off im's `/directory/live`, parsed here rather than in the +/// pinned client because the consumer owes the wire more than the pin +/// knows: a `revoked` frame says a session died in im, and a `profile` +/// frame may now carry `disabled`. +#[derive(Debug, Clone, PartialEq)] +pub enum StreamFrame { + /// The named member's row as it now stands. + Profile(StreamMember), + /// At least one of the member's sessions was revoked. Which one is + /// im's knowledge alone; the consumer treats the fact workspace-wide. + Revoked { sub: String }, +} + +/// An open `/directory/live` connection. `next` mirrors the pinned +/// client's shape: `Some(Err)` on a wire failure — then the stream is +/// over — and `None` when im closed a healthy one. Either way the caller +/// re-lists and redials. +pub struct DirectoryStream { + response: reqwest::Response, + reader: FrameReader, +} + +impl DirectoryStream { + pub async fn next(&mut self) -> Option> { + loop { + if let Some(frame) = self.reader.ready.pop_front() { + return Some(Ok(frame)); + } + match self.response.chunk().await { + Ok(Some(bytes)) => self.reader.feed(&bytes), + Ok(None) => return None, + Err(e) => return Some(Err(e.to_string())), + } + } + } +} + +/// The hand-rolled `text/event-stream` reader. Frames accumulate field by +/// field and dispatch on the blank line, per the SSE grammar; the fields +/// this feed carries are `event`, `data`, and comments, but the parser +/// honors the whole shape — including `data` split over several lines, +/// which the spec joins with `\n`. +#[derive(Default)] +struct FrameReader { + /// Bytes read but not yet through a line terminator. + pending: Vec, + /// The previous read ended on a bare `\r`, so the next read's leading + /// `\n` — if that is what comes — completes that terminator rather + /// than opening a blank line. + cr_ended: bool, + /// The current frame's `event:` field, if it named one. + event: Option, + /// The current frame's `data:`, joined back into one string. + data: String, + /// Frames completed and waiting to be read. + ready: VecDeque, +} + +impl FrameReader { + /// Feeds the next bytes from the wire and queues every frame they + /// completed. Bytes trailing their terminator wait for the rest — a + /// field or a UTF-8 character may straddle two reads. + fn feed(&mut self, bytes: &[u8]) { + // The previous read stopped on a bare `\r`. A `\r\n` split across + // two reads is ONE terminator: the pair's `\n` arriving here + // completes the old one instead of opening a blank line and + // dispatching a frame that has not ended. + let bytes = if self.cr_ended { + self.cr_ended = false; + if bytes.first() == Some(&b'\n') { + &bytes[1..] + } else { + bytes + } + } else { + bytes + }; + self.pending.extend_from_slice(bytes); + let Some(at) = self + .pending + .iter() + .rposition(|&b| b == b'\n' || b == b'\r') + .map(|at| at + 1) + else { + return; + }; + let block: Vec = self.pending.drain(..at).collect(); + self.cr_ended = block.last() == Some(&b'\r'); + for line in split_lines(&block) { + if line.is_empty() { + // The blank line dispatches whatever accumulated. + if let Some(frame) = self.take() { + self.ready.push_back(frame); + } + } else if line[0] == b':' { + // A comment — im's keep-alives and retry hint live here. + } else { + let (name, value) = match line.iter().position(|&b| b == b':') { + Some(at) => (&line[..at], &line[at + 1..]), + None => (&line[..], &b""[..]), + }; + // One optional space after the colon is not part of the + // value. + let value = value.strip_prefix(b" ").unwrap_or(value); + match name { + b"event" => self.event = Some(String::from_utf8_lossy(value).into_owned()), + b"data" => { + if !self.data.is_empty() { + self.data.push('\n'); + } + self.data.push_str(&String::from_utf8_lossy(value)); + } + // `id` and `retry` mean nothing to a change feed. + _ => {} + } + } + } + } + + /// Ends the current frame and decides what it was. A frame whose kind + /// this build does not know is skipped, not fatal: im may grow the + /// feed, and one strange frame must not end a healthy connection. A + /// known kind whose payload will not parse is logged and dropped for + /// the same reason. + fn take(&mut self) -> Option { + let data = std::mem::take(&mut self.data); + let event = self.event.take(); + match event.as_deref() { + // A frame with no kind at all is an older im's bare member + // announcement; it parses exactly as it always did. + None | Some("profile") => match serde_json::from_str::(&data) { + Ok(member) => Some(StreamFrame::Profile(member)), + Err(problem) => { + eprintln!("directory stream: unreadable profile frame ({problem})"); + None + } + }, + Some("revoked") => match serde_json::from_str::(&data) { + Ok(frame) => Some(StreamFrame::Revoked { sub: frame.sub }), + Err(problem) => { + eprintln!("directory stream: unreadable revoked frame ({problem})"); + None + } + }, + // A kind from an im newer than this build. + Some(_) => None, + } + } +} + +/// The `{"sub": ...}` payload a `revoked` frame carries. +#[derive(Deserialize)] +struct RevokedFrame { + sub: String, +} + +/// Splits a block that ends at a line terminator into lines, accepting the +/// three SSE terminators: `\n`, `\r\n`, and a bare `\r`. A blank line is a +/// frame's dispatch, so it is kept — only the terminator run itself +/// disappears. +fn split_lines(block: &[u8]) -> Vec> { + let mut lines = Vec::new(); + let mut start = 0usize; + let mut at = 0usize; + while at < block.len() { + if block[at] == b'\n' || block[at] == b'\r' { + lines.push(block[start..at].to_vec()); + if block[at] == b'\r' && block.get(at + 1) == Some(&b'\n') { + at += 1; + } + at += 1; + start = at; + } else { + at += 1; + } + } + if start < block.len() { + lines.push(block[start..].to_vec()); + } + lines +} + +/// Carries one consumed frame into the local mirror — the one door both +/// the stream task and the tests use, so a frame means the same thing no +/// matter who fed it. +/// +/// * A profile syncs the row the way the roster pass does, and im owns the +/// account's life: a profile whose `disabled` disagrees with the local +/// row flips it through the same store path an admin's hand uses — +/// `true` is a user-level kill whose store announcement names the +/// account's own open tabs, `false` is the homecoming that signs the +/// row back in. +/// * A revoked frame is a session fact — which session died is im's +/// knowledge alone, and a tab whose *other* session survived must not be +/// sent away — so it only announces the member surface. Every tab's +/// refetch re-introspects per request, and that is what sorts out who is +/// still signed in. +pub async fn apply_frame(store: &Arc, frame: StreamFrame) { + match frame { + StreamFrame::Profile(member) => { + if let Err(problem) = store + .sync_member( + &member.sub, + &member.email, + &member.name, + member.admin, + member.photo_version, + &member.timezone, + ) + .await + { + eprintln!("directory stream: {}: {problem}", member.email); + } + match store.user_by_sub(&member.sub).await { + Ok(Some(user)) if user.disabled != member.disabled => { + if let Err(problem) = store.set_user_disabled(&user.id, member.disabled).await + { + eprintln!("directory stream: {}: {problem}", member.email); + } + } + Ok(_) => {} + Err(problem) => { + eprintln!("directory stream: {}: {problem}", member.email); + } + } + } + StreamFrame::Revoked { .. } => { + store.announce(&[Topic::Members]); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn frames(wire: &str) -> Vec { + let mut reader = FrameReader::default(); + reader.feed(wire.as_bytes()); + reader.ready.drain(..).collect() + } + + fn member(sub: &str, email: &str, name: &str, disabled: bool) -> StreamMember { + StreamMember { + sub: sub.into(), + email: email.into(), + name: name.into(), + admin: false, + photo_version: 0, + timezone: "UTC+03:00".into(), + disabled, + } + } + + /// A kind this build has never heard of is skipped where it stands — + /// the frames on either side of it still land, and the reader is alive + /// for the next bytes. + #[test] + fn an_unknown_event_kind_is_skipped_and_the_stream_lives_on() { + let wire = concat!( + ": keep-alive\n", + "event: profile\n", + "data: {\"sub\":\"s1\",\"email\":\"a@iz.sh\",\"name\":\"A\"}\n", + "\n", + "event: logrollover\n", + "data: {\"whatever\":true}\n", + "\n", + "event: revoked\n", + "data: {\"sub\":\"s1\"}\n", + "\n", + "event: profile\n", + "data: {\"sub\":\"s2\",\"email\":\"b@iz.sh\",\"name\":\"B\",\"disabled\":true}\n", + "\n", + ); + assert_eq!( + frames(wire), + vec![ + StreamFrame::Profile(member("s1", "a@iz.sh", "A", false)), + StreamFrame::Revoked { sub: "s1".into() }, + StreamFrame::Profile(member("s2", "b@iz.sh", "B", true)), + ] + ); + } + + /// im predating the `event:` field altogether announces bare member + /// frames; unknown fields on a known frame are ignored, so a newer im + /// may grow the row without a breaking change. + #[test] + fn a_bare_frame_from_an_older_im_still_parses() { + let wire = concat!( + "data: {\"sub\":\"s1\",\"email\":\"a@iz.sh\",\"name\":\"A\",\"voltage\":9}\n", + "\n", + ); + let seen = frames(wire); + assert_eq!( + seen, + vec![StreamFrame::Profile(member("s1", "a@iz.sh", "A", false))] + ); + } + + /// A frame cut in the middle of its JSON is held until its rest + /// arrives; nothing is lost and nothing is dispatched early. + #[test] + fn a_frame_straddling_two_reads_is_not_lost() { + let mut reader = FrameReader::default(); + reader.feed(b"event: revoked\ndata: {\"su"); + assert!(reader.ready.is_empty()); + reader.feed(b"b\":\"s9\"}\n\n"); + assert_eq!( + reader.ready.drain(..).collect::>(), + vec![StreamFrame::Revoked { sub: "s9".into() }] + ); + } + + /// A `\r\n` pair split across two reads stays one terminator: the + /// trailing `\r` of a read must not let the next read's leading `\n` + /// arrive as a blank line and dispatch a frame that has not ended. + /// The cut here is exactly at the terminator of the one data line; + /// the blank line that follows in the next read is what dispatches. + #[test] + fn a_crlf_pair_split_across_reads_is_one_terminator() { + let mut reader = FrameReader::default(); + reader.feed(b"data: {\"sub\":\"s1\",\"email\":\"a@iz.sh\",\"name\":\"A\"}\r"); + assert!(reader.ready.is_empty(), "a cut terminator dispatched early"); + reader.feed(b"\n\r\n"); + assert_eq!( + reader.ready.drain(..).collect::>(), + vec![StreamFrame::Profile(member("s1", "a@iz.sh", "A", false))] + ); + } + + /// The same hold with a named kind: the `\r` after `event: revoked` is + /// a field line's end, not the frame's — draining it would let the + /// next read open with a blank line and burn the frame on an empty + /// payload, losing the revocation for good. + #[test] + fn a_trailing_cr_after_the_event_field_does_not_burn_the_frame() { + let mut reader = FrameReader::default(); + reader.feed(b"event: revoked\r"); + assert!(reader.ready.is_empty()); + reader.feed(b"\ndata: {\"sub\":\"s9\"}\r\n\r\n"); + assert_eq!( + reader.ready.drain(..).collect::>(), + vec![StreamFrame::Revoked { sub: "s9".into() }] + ); + } +} diff --git a/crates/iz-web/src/layout.rs b/crates/iz-web/src/layout.rs index 43943a8..200a001 100644 --- a/crates/iz-web/src/layout.rs +++ b/crates/iz-web/src/layout.rs @@ -896,6 +896,14 @@ pub async fn soft_nav_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. +/// The channel also carries one goodbye: a `revoked` frame means this +/// tab's account was killed at the provider, and the answer is a hard +/// redirect to the front door, not a morph. A dropped stream is the other +/// way a tab learns it may be alone: the error path asks `/api/me`, and a +/// `401` there is the same redirect. A merely restarting server answers +/// 204, so a signed-in tab loses nothing — the `EventSource` reconnects +/// on its own. +/// pub async fn live_script<'a>(cx: &'a Cx) -> Result { const JS: &str = "\ (function () { \ @@ -925,8 +933,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', { cache: 'no-store' }).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/iz-web/src/live.rs b/crates/iz-web/src/live.rs index 223f2b8..7fbdf5e 100644 --- a/crates/iz-web/src/live.rs +++ b/crates/iz-web/src/live.rs @@ -47,18 +47,24 @@ impl Default for LiveWindow { #[derive(Clone)] pub struct Shutdown(pub tokio::sync::watch::Receiver); -/// Whether a reader of this role may be told that this surface moved. +/// Whether a reader may be told that this surface moved. /// /// The board, a task and the member list are what every signed-in person /// already sees. The queue, the rules, the settings and the activity log are /// admin screens, and CLAUDE.md's rule — a role that cannot act on a surface /// does not see it — reaches the channel too: a member is not told the queue /// moved, because being told is itself knowing something about the queue. -fn may_hear(topic: &Topic, admin: bool) -> bool { +/// +/// The one topic that is neither surface nor role is [`Topic::Revoked`]: the +/// account it names was killed at the provider, and the only reader it may be +/// named to is the reader it names — hearing it says nothing about anybody +/// else. +fn may_hear(topic: &Topic, reader_id: &str, admin: bool) -> bool { match topic { // Tags ride with the board: every member sees a card's tag, so being // told the tags moved tells them nothing they cannot already read. Topic::Board | Topic::Task(_) | Topic::Members | Topic::Tags => true, + Topic::Revoked(id) => id == reader_id, Topic::Queue | Topic::Rules | Topic::Settings | Topic::Activity => admin, } } @@ -92,9 +98,15 @@ async fn live(cx: &Cx) -> topcoat::Result { let deadline = Instant::now() + try_app_context::(cx).copied().unwrap_or_default().0; let events = futures_util::stream::unfold( - (rx, admin, deadline, stopping), - |(mut rx, admin, deadline, mut stopping)| async move { + (rx, admin, deadline, stopping, user.id.clone(), false), + |(mut rx, admin, deadline, mut stopping, reader_id, mut done)| async move { loop { + // The goodbye frame went out with the last pass: the account + // this reader signed in as was named killed, and there is + // nothing left to say. + if done { + 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()) { @@ -130,21 +142,31 @@ async fn live(cx: &Cx) -> topcoat::Result { // after. The stream stays open — a slow moment is not a fault. Ok(Some(Err(RecvError::Lagged(_)))) => Event::new().data(RESYNC), Ok(Some(Ok(Change { topic, seq }))) => { - if !may_hear(&topic, admin) { + if !may_hear(&topic, &reader_id, admin) { // Not merely unsent: never named. A member's // connection carries no evidence the queue exists. continue; } + // The reader's own account was named: this frame is + // the goodbye, and the stream ends right behind it — + // the tab leaves for the front door rather than + // morphing a workspace it can no longer read. + if matches!(topic, Topic::Revoked(_)) { + done = true; + } let frame = Frame { topic: topic.kind(), id: topic.id(), seq }; match Event::new().json_data(&frame) { Ok(event) => event, Err(problem) => { - return Some((Err(problem), (rx, admin, deadline, stopping))); + return Some(( + Err(problem), + (rx, admin, deadline, stopping, reader_id, done), + )); } } } }; - return Some((Ok(frame), (rx, admin, deadline, stopping))); + return Some((Ok(frame), (rx, admin, deadline, stopping, reader_id, done))); } }, ); diff --git a/crates/iz-web/src/main.rs b/crates/iz-web/src/main.rs index aa5e8c2..f8466fe 100644 --- a/crates/iz-web/src/main.rs +++ b/crates/iz-web/src/main.rs @@ -189,6 +189,11 @@ async fn main() { tokio::spawn(directory_stream( store.clone(), directory.clone(), + iz_web::directory::StreamSource::new( + config.oidc.issuer.clone(), + config.oidc.client_id.clone(), + config.oidc.client_secret.clone(), + ), health.clone(), )); // The storage mirror's watchdog: follows the family to wherever in @@ -487,7 +492,10 @@ async fn apply_member( } /// The live half of the mirror: im's `/directory/live`, one event per -/// changed member. Forever, in this shape: a full pass, then the stream; +/// changed member — plus the `revoked` kind the pinned client's parser +/// drops, which is why the connection and its frames are +/// [`iz_web::directory`]'s and only the roster pass still rides the +/// pinned client. Forever, in this shape: a full pass, then the stream; /// whenever the stream ends — im restarting, or its fifty-minute window /// closing — wait out a backoff that doubles from one second to thirty, /// replay a full pass (the resync that heals whatever the dead stream @@ -499,20 +507,21 @@ async fn apply_member( async fn directory_stream( store: Arc, directory: im_client::directory::DirectoryClient, + source: iz_web::directory::StreamSource, health: iz_web::directory::DirectoryHealth, ) { let mut backoff = std::time::Duration::from_secs(1); loop { mirror_directory(&store, &directory, &health).await; - match directory.open_stream().await { + match source.open_stream().await { Ok(mut stream) => { health.connected(); backoff = std::time::Duration::from_secs(1); - while let Some(event) = stream.next().await { - match event { - Ok(im_client::directory::DirectoryEvent::Profile(member)) => { + while let Some(frame) = stream.next().await { + match frame { + Ok(frame) => { health.event(); - apply_member(&store, &member).await; + iz_web::directory::apply_frame(&store, frame).await; } Err(problem) => { eprintln!("directory stream: {problem}; re-listing"); diff --git a/crates/iz-web/src/server.rs b/crates/iz-web/src/server.rs index 48ab422..4b586b5 100644 --- a/crates/iz-web/src/server.rs +++ b/crates/iz-web/src/server.rs @@ -20,7 +20,10 @@ use topcoat::asset::AssetBundle; use topcoat::context::{Cx, app_context, memoize, try_app_context}; use topcoat::cookie::{Cookies, cookies}; use topcoat::router::request::headers; -use topcoat::router::{Body, HeaderValue, Next, StatusCode, header, response::Response, to_bytes}; +use topcoat::router::{ + route, Body, HeaderValue, Next, StatusCode, header, response::IntoResponse, response::Response, + to_bytes, +}; /// The workspace store, put into context by the router. pub fn store(cx: &Cx) -> Arc { @@ -328,6 +331,20 @@ pub async fn require_writer(cx: &Cx) -> Result { } } +/// The lightweight am-I-signed-in probe the live script's error path asks: +/// `204` with no body when the caller carries a live session, `401` when +/// anything about the caller — no cookie, a revoked or disabled one, a +/// store that cannot answer — says otherwise. It exists so a dropped live +/// stream can tell "the server restarted" from "I was signed out" without +/// fetching a page of HTML to learn it. +#[route(GET "/api/me")] +async fn me(cx: &Cx) -> topcoat::Result { + match current_user(cx).await { + Ok(Some(_)) => StatusCode::NO_CONTENT.into_response(cx), + _ => (StatusCode::UNAUTHORIZED, "").into_response(cx), + } +} + impl From for Refusal { fn from(error: StoreError) -> Self { eprintln!("store error: {error}"); diff --git a/crates/iz-web/tests/http.rs b/crates/iz-web/tests/http.rs index 44817f7..ad3155c 100644 --- a/crates/iz-web/tests/http.rs +++ b/crates/iz-web/tests/http.rs @@ -28,6 +28,7 @@ use http::{HeaderValue, Request, StatusCode, header}; use iz_core::Role; use iz_core::board::Moved; use iz_core::store::{Audience, MailOutcome, SendKind, SendState, Store, Trigger, TursoStore}; +use iz_web::directory::{StreamFrame, StreamMember, apply_frame}; use iz_web::server::Mail; use topcoat::asset::{AssetBundle, RouterBuilderAssetExt}; use topcoat::cookie::RouterBuilderCookieExt; @@ -7532,6 +7533,180 @@ async fn a_queued_mails_next_try_is_marked_for_the_tick() { ); } +/// The lightweight probe the live script's error path asks. A live session +/// gets a bodyless yes; no cookie, or a session im no longer vouches for, +/// gets a plain 401 — so a dropped stream can be told apart from a signed- +/// out tab without fetching a page of HTML to learn it. +#[tokio::test] +async fn the_me_probe_answers_yes_only_to_a_live_session() { + let app = App::open().await; + let boss = admin(&app).await; + + let live = app.get("/api/me", Some(&boss)).await; + assert_eq!(live.status, StatusCode::NO_CONTENT); + assert!(live.bytes.is_empty(), "the probe answered a body"); + + let stranger = app.get("/api/me", None).await; + assert_eq!(stranger.status, StatusCode::UNAUTHORIZED); + + // The session revoked in im: once the fake stops vouching for the + // token, the probe refuses with no page to fetch first. + app.fake.tokens.lock().clear(); + let revoked = app.get("/api/me", Some(&boss)).await; + assert_eq!(revoked.status, StatusCode::UNAUTHORIZED); +} + +/// A session revocation heard off the directory stream is told to the whole +/// workspace — which session died is im's knowledge alone, so no connection +/// is named and no tab is sent away; every tab's own refetch, which +/// re-introspects per request, is what sorts out who is still signed in. +/// A tab whose other session survived therefore keeps its place. +#[tokio::test] +async fn a_session_revocation_announces_the_member_surface_to_everyone() { + let app = App::open().await; + let boss = admin(&app).await; + let bo = invited(&app, &boss, "bo@iz.sh", "Bo", Role::Member).await; + + let member_feed = app.live_open(Some(&bo)).await; + let admin_feed = app.live_open(Some(&boss)).await; + + apply_frame( + &app.store, + StreamFrame::Revoked { + sub: "im-bo@iz.sh".into(), + }, + ) + .await; + + let heard_by_admin = + live_until(admin_feed, "members", std::time::Duration::from_secs(10)).await; + assert!( + heard_by_admin.contains("members"), + "no members announcement: {heard_by_admin}" + ); + let heard_by_member = live_until( + member_feed, + "members", + std::time::Duration::from_millis(500), + ) + .await; + assert!( + heard_by_member.contains("members"), + "the member was not told the member surface moved: {heard_by_member}" + ); + assert!( + !heard_by_admin.contains("revoked") && !heard_by_member.contains("revoked"), + "a session revocation named a connection: {heard_by_admin} / {heard_by_member}" + ); +} + +/// A profile arriving `disabled` is a user-level kill: the local row is +/// disabled through the same store path an admin's hand uses, the +/// account's own tab is named with the `revoked` topic — and only that +/// tab — and the row's next probe reads as signed out, exactly as any +/// refetch would find it. +#[tokio::test] +async fn a_disabled_member_is_named_once_and_signed_out_everywhere() { + let app = App::open().await; + let boss = admin(&app).await; + let bo = invited(&app, &boss, "bo@iz.sh", "Bo", Role::Member).await; + + let member_feed = app.live_open(Some(&bo)).await; + let admin_feed = app.live_open(Some(&boss)).await; + + apply_frame( + &app.store, + StreamFrame::Profile(StreamMember { + sub: "im-bo@iz.sh".into(), + email: "bo@iz.sh".into(), + name: "Bo".into(), + admin: false, + photo_version: 0, + timezone: "UTC+03:00".into(), + disabled: true, + }), + ) + .await; + + // The account's own connection is named — the goodbye frame the client + // answers with a hard redirect. + let goodbye = live_until(member_feed, "revoked", std::time::Duration::from_secs(10)).await; + assert!( + goodbye.contains("revoked"), + "the disabled member's tab was not named: {goodbye}" + ); + + // The workspace heard the member surface move; nobody else was named. + let heard_by_admin = + live_until(admin_feed, "members", std::time::Duration::from_secs(10)).await; + assert!( + heard_by_admin.contains("members"), + "no members announcement: {heard_by_admin}" + ); + assert!( + !heard_by_admin.contains("revoked"), + "an uninvolved tab was named: {heard_by_admin}" + ); + + // The row itself, and the seam every refetch would hit. + let user = app + .store + .user_by_sub("im-bo@iz.sh") + .await + .unwrap() + .expect("the disabled member had no local row"); + assert!(user.disabled); + assert_eq!( + app.get("/api/me", Some(&bo)).await.status, + StatusCode::UNAUTHORIZED + ); +} + +/// im owns the account's life both ways: the same stream that kills the +/// row brings it back. A disable lands, then a re-enable — the local flag +/// follows each, and the member's own probe reads signed-in again, with +/// no revoked naming on the way back in. +#[tokio::test] +async fn a_reenabled_member_is_signed_back_in() { + let app = App::open().await; + let _boss = admin(&app).await; + let bo = member(&app, "bo@iz.sh", "Bo").await; + + let disabled = StreamMember { + sub: "im-bo@iz.sh".into(), + email: "bo@iz.sh".into(), + name: "Bo".into(), + admin: false, + photo_version: 0, + timezone: "UTC+03:00".into(), + disabled: true, + }; + apply_frame(&app.store, StreamFrame::Profile(disabled.clone())).await; + assert!( + app.store + .user_by_sub("im-bo@iz.sh") + .await + .unwrap() + .expect("no local row") + .disabled, + "the stream did not disable the row" + ); + + let enabled = StreamMember { disabled: false, ..disabled }; + apply_frame(&app.store, StreamFrame::Profile(enabled)).await; + assert!( + !app + .store + .user_by_sub("im-bo@iz.sh") + .await + .unwrap() + .expect("no local row") + .disabled, + "the stream did not re-enable the row" + ); + assert_eq!(app.get("/api/me", Some(&bo)).await.status, StatusCode::NO_CONTENT); +} + /// A live update changes only what actually changed. It morphs the fetched /// document onto the live one instead of replacing the body, which is what /// leaves an open dropdown open, a caret where it was and a half-typed comment