//! The members mirror (docs/contracts.md section 3): a full read of `im`'s people directory at boot, //! then its change stream, applied to the local `members` table. The worker keeps running until the //! stop flag is set. //! //! Pages never call `im` to show a name or an avatar; they read this mirror. A member who is disabled //! or deleted loses their local sessions here, and the same check also runs at every request in the //! store, so either path alone is enough (contracts.md 2.5). //! //! The stream cursor is kept in `settings`. A `resync` event, or a cursor that `im` no longer knows, //! starts a full read again. A broken connection is retried with exponential backoff from one second //! to one minute, with jitter, so a restart of `im` does not bring every client back in the same //! instant. use std::collections::HashSet; use std::time::Duration; use futures_util::StreamExt; use iz_core::authz::Role; use iz_core::store::Store; use iz_core::store::members::DirectoryMember; use serde_json::Value; use tokio::sync::watch; use crate::oidc::{ImError, ImResult, OidcClient, read_limited}; use crate::state::AppState; /// The setting that holds the stream cursor. pub const CURSOR_SETTING: &str = "directory_cursor"; /// The setting that holds the role of a member the directory adds (`member` by default). pub const DEFAULT_ROLE_SETTING: &str = "default_role"; /// The shortest wait before a reconnect. Reason: contracts.md 2.2 style backoff, first step. const BACKOFF_MIN: Duration = Duration::from_secs(1); /// The longest wait before a reconnect. Reason: a family board can wait a minute for `im`. const BACKOFF_MAX: Duration = Duration::from_secs(60); /// Silence after which the stream is considered dead. `im` sends a keep-alive every 30 seconds. const IDLE_LIMIT: Duration = Duration::from_secs(90); /// Largest directory listing read at once, in bytes. Reason: a family has a few dozen members, so /// this is far above a real listing and still bounds memory. const ROSTER_MAX_BYTES: usize = 8 * 1024 * 1024; /// Largest stream event accepted, in bytes. Reason: a member record is a few hundred bytes. const MAX_EVENT_BYTES: usize = 64 * 1024; /// Largest photo fetched from `im`, in bytes. Reason: avatars are small; this bounds the cache. pub const PHOTO_MAX_BYTES: usize = 5 * 1024 * 1024; /// The image types a photo may be served as. Anything else from `im` is not shown. pub const PHOTO_TYPES: [&str; 4] = ["image/png", "image/jpeg", "image/gif", "image/webp"]; /// What can stop the mirror: the directory or the local store. #[derive(Debug, thiserror::Error)] pub enum MirrorError { /// `im` failed to answer. The worker retries. #[error(transparent)] Im(#[from] ImError), /// The local database failed. The worker retries. #[error(transparent)] Store(#[from] iz_core::Error), } /// A member record as `im` sends it (contracts.md 3.1). Unknown fields are ignored. #[derive(serde::Deserialize)] struct WireMember { sub: String, email: String, name: String, #[serde(default)] admin: bool, #[serde(default)] disabled: bool, #[serde(default)] locale: Option, #[serde(default = "utc")] zoneinfo: String, #[serde(default)] picture_version: i64, /// The directory's change time (RFC 3339). Empty when `im` does not send one. #[serde(default)] updated_at: String, } fn utc() -> String { "UTC".to_owned() } /// The listing of `im`'s directory (contracts.md 3.2). Members are kept as raw values so that one /// bad record does not stop the rest. #[derive(serde::Deserialize)] struct Roster { members: Vec, cursor: String, } /// How one connection of the stream ended. enum Ended { /// The stop flag was set. Stopped, /// `im` asked for a full read again. Resync, /// The stream closed, went idle, or `im` closed it after 50 minutes. Reconnect with the cursor. /// `delivered` says whether the connection carried any event. Closed { delivered: bool }, } /// Starts the mirror. Does nothing when OIDC is not configured. pub fn spawn(state: AppState, stop: watch::Receiver) { let Some(oidc) = state.oidc.clone() else { return; }; tokio::spawn(run(state, oidc, stop)); } async fn run(state: AppState, oidc: std::sync::Arc, mut stop: watch::Receiver) { let mut backoff = BACKOFF_MIN; // A full read is needed at the start, after a resync, and after a failure. A plain reconnect // resumes from the stored cursor, so it does not read the whole listing again. let mut full = true; loop { match mirror_once(&state, &oidc, &mut stop, full).await { Ok(Ended::Stopped) => return, Ok(Ended::Resync) => { tracing::info!("directory: the stream asked for a full read"); backoff = BACKOFF_MIN; full = true; } Ok(Ended::Closed { delivered }) => { tracing::info!("directory: the stream closed; reconnecting"); // A connection that carried events resets the wait. A silent one keeps growing it, so // an `im` that closes streams at once is not polled every second. if delivered { backoff = BACKOFF_MIN; } full = false; } Err(error) => { tracing::warn!(error = %error, retry_in = ?backoff, "directory: the mirror failed"); full = true; } } if wait_or_stop(jittered(backoff), &mut stop).await { return; } backoff = (backoff * 2).min(BACKOFF_MAX); } } /// An optional full read, then one stream connection. async fn mirror_once( state: &AppState, oidc: &OidcClient, stop: &mut watch::Receiver, full: bool, ) -> std::result::Result { if full { full_read(state, oidc).await?; } stream(state, oidc, stop).await } /// Reads the whole directory and applies it. Members that the listing no longer has were deleted in /// `im`, so they are marked deleted here too. async fn full_read(state: &AppState, oidc: &OidcClient) -> std::result::Result<(), MirrorError> { let token = oidc.service_token().await?; let url = format!("{}/api/v1/directory", oidc.issuer()); let response = oidc .http() .get(url) .bearer_auth(token) .send() .await .map_err(|e| ImError::Unavailable(e.to_string()))?; if !response.status().is_success() { return Err(ImError::BadResponse(format!( "the directory answered {}", response.status().as_u16() )) .into()); } let roster: Roster = decode_json_limited(response, ROSTER_MAX_BYTES).await?; let default_role = default_role(&state.store).await?; let mut listed = HashSet::new(); for raw in roster.members { let Some(member) = parse_member(raw) else { tracing::warn!("directory: skipping a member record that does not parse"); continue; }; listed.insert(member.sub.clone()); apply(state, &member, default_role).await?; } for local in state.store.list_members().await? { if !listed.contains(&local.sub) && !local.disabled { tracing::info!(sub = %local.sub, "directory: member is gone from the listing; marking deleted"); state.store.mark_deleted(&local.sub).await?; state.store.delete_sessions_by_sub(&local.sub).await?; } } state .store .set_setting(CURSOR_SETTING, &roster.cursor) .await?; Ok(()) } /// Decodes a listing, with the same size limit as the other reads. async fn decode_json_limited( response: reqwest::Response, limit: usize, ) -> ImResult { let body = read_limited(response, limit).await?; serde_json::from_slice(&body) .map_err(|e| ImError::BadResponse(format!("the directory listing: {e}"))) } /// Opens the change stream from the stored cursor and applies events until the stream ends. async fn stream( state: &AppState, oidc: &OidcClient, stop: &mut watch::Receiver, ) -> std::result::Result { let token = oidc.service_token().await?; let url = format!("{}/api/v1/directory/stream", oidc.issuer()); let mut request = oidc .stream_http() .get(url) .bearer_auth(token) .header(reqwest::header::ACCEPT, "text/event-stream"); if let Some(cursor) = state.store.get_setting(CURSOR_SETTING).await? { request = request.header("Last-Event-ID", cursor); } let response = request .send() .await .map_err(|e| ImError::Unavailable(e.to_string()))?; if !response.status().is_success() { return Err(ImError::BadResponse(format!( "the stream answered {}", response.status().as_u16() )) .into()); } let mut chunks = response.bytes_stream(); let mut parser = SseParser::default(); let mut delivered = false; loop { let next = tokio::select! { _ = stop.wait_for(|stopped| *stopped) => return Ok(Ended::Stopped), next = tokio::time::timeout(IDLE_LIMIT, chunks.next()) => next, }; let chunk = match next { // Silence for longer than the limit: reconnect. Err(_elapsed) => return Ok(Ended::Closed { delivered }), Ok(None) => return Ok(Ended::Closed { delivered }), Ok(Some(Err(error))) => return Err(ImError::Unavailable(error.to_string()).into()), Ok(Some(Ok(bytes))) => bytes, }; let events = parser.feed(&chunk).map_err(ImError::BadResponse)?; delivered |= !events.is_empty(); for event in events { match event.name.as_str() { "member" => match serde_json::from_str::(&event.data) .ok() .and_then(parse_member) { Some(member) => { let default_role = default_role(&state.store).await?; apply(state, &member, default_role).await?; } None => { tracing::warn!("directory: skipping a member event that does not parse") } }, "deleted" => match serde_json::from_str::(&event.data) .ok() .and_then(|v| v.get("sub").and_then(Value::as_str).map(str::to_owned)) { Some(sub) => { remove(state, &sub).await?; } None => tracing::warn!("directory: skipping a deleted event without a sub"), }, "resync" => return Ok(Ended::Resync), _ => {} } if let Some(id) = &event.id { state.store.set_setting(CURSOR_SETTING, id).await?; } } } } /// Applies one member record. A disabled member loses their sessions. A record the store refuses /// (for example a time zone it does not know) is logged and skipped, so one bad record never stops /// the mirror. async fn apply( state: &AppState, member: &DirectoryMember, default_role: Role, ) -> std::result::Result<(), MirrorError> { match state .store .apply_directory_member(member, default_role) .await { Ok(stored) => { if stored.disabled { state.store.delete_sessions_by_sub(&stored.sub).await?; } Ok(()) } Err(iz_core::Error::Invalid(reason)) => { tracing::warn!(sub = %member.sub, reason, "directory: skipping a member the store refuses"); Ok(()) } Err(error) => Err(error.into()), } } /// Marks a deleted member and ends their sessions. async fn remove(state: &AppState, sub: &str) -> std::result::Result<(), MirrorError> { match state.store.mark_deleted(sub).await { Ok(()) | Err(iz_core::Error::NotFound) => {} Err(error) => return Err(error.into()), } state.store.delete_sessions_by_sub(sub).await?; Ok(()) } /// The role for a member the directory adds: the `default_role` setting, else `member`. pub async fn default_role(store: &Store) -> iz_core::Result { Ok(store .get_setting(DEFAULT_ROLE_SETTING) .await? .as_deref() .and_then(Role::parse) .unwrap_or(Role::Member)) } /// Converts a raw member record into the store's form, or `None` when it does not parse. fn parse_member(raw: Value) -> Option { let wire: WireMember = serde_json::from_value(raw).ok()?; Some(DirectoryMember { sub: wire.sub, email: wire.email, name: wire.name, im_admin: wire.admin, disabled: wire.disabled, locale: wire.locale, zoneinfo: wire.zoneinfo, picture_version: wire.picture_version, updated_at: wire.updated_at, }) } /// Waits for `wait`, or returns `true` early when the stop flag is set. async fn wait_or_stop(wait: Duration, stop: &mut watch::Receiver) -> bool { tokio::select! { _ = stop.wait_for(|stopped| *stopped) => true, () = tokio::time::sleep(wait) => false, } } /// A wait between half and all of `backoff`. The jitter spreads the reconnects of several clients. fn jittered(backoff: Duration) -> Duration { let mut bytes = [0u8; 8]; rand::fill(&mut bytes); let fraction = (u64::from_le_bytes(bytes) % 1000) as f64 / 1000.0; backoff.mul_f64(0.5 + fraction * 0.5) } /// One event of a server-sent event stream. #[derive(Debug, PartialEq, Eq)] pub struct SseEvent { /// The `event:` name, `message` when none was sent. pub name: String, /// The `data:` lines joined with newlines. pub data: String, /// The `id:` of the event, which is the cursor to resume from. pub id: Option, } /// Reads a server-sent event stream (the HTML living standard, event stream section) from raw /// chunks. A line may be split across chunks; a blank line ends an event. #[derive(Default)] pub struct SseParser { pending: Vec, name: Option, data: Option, id: Option, } impl SseParser { /// Feeds one chunk and returns the events it completes. An over-long line is an error, so a /// hostile stream cannot grow the buffer without bound. pub fn feed(&mut self, chunk: &[u8]) -> std::result::Result, String> { self.pending.extend_from_slice(chunk); let mut events = Vec::new(); while let Some(end) = self.pending.iter().position(|&b| b == b'\n') { let line: Vec = self.pending.drain(..=end).collect(); let line = String::from_utf8_lossy(&line[..line.len() - 1]).into_owned(); let line = line.strip_suffix('\r').unwrap_or(&line).to_owned(); if line.is_empty() { if let Some(event) = self.dispatch() { events.push(event); } continue; } if line.starts_with(':') { continue; } let (field, value) = match line.split_once(':') { Some((field, value)) => (field, value.strip_prefix(' ').unwrap_or(value)), None => (line.as_str(), ""), }; match field { "event" => self.name = Some(value.to_owned()), "id" if !value.contains('\0') => self.id = Some(value.to_owned()), "data" => { let data = self.data.get_or_insert_with(String::new); if !data.is_empty() { data.push('\n'); } data.push_str(value); if data.len() > MAX_EVENT_BYTES { return Err("a stream event is too large".into()); } } _ => {} } } if self.pending.len() > MAX_EVENT_BYTES { return Err("a stream line is too large".into()); } Ok(events) } /// Ends the current event. An event with no data is dropped, as the standard says. fn dispatch(&mut self) -> Option { let name = self.name.take(); let id = self.id.clone(); let data = self.data.take()?; Some(SseEvent { name: name.unwrap_or_else(|| "message".to_owned()), data, id, }) } } /// Fetches the photo of `sub` at `version` from `im` with the service token. `None` when `im` has no /// photo, or the photo has a type iz does not serve. The answer must carry the ETag of that version: /// otherwise `im` has a newer photo, and it must not be cached under the older version. pub async fn fetch_photo( oidc: &OidcClient, sub: &str, version: i64, ) -> ImResult)>> { let token = oidc.service_token().await?; let url = format!("{}/api/v1/people/{sub}/photo?v={version}", oidc.issuer()); let response = oidc .http() .get(url) .bearer_auth(token) .send() .await .map_err(|e| ImError::Unavailable(e.to_string()))?; match response.status() { status if status == reqwest::StatusCode::NOT_FOUND => return Ok(None), status if !status.is_success() => { return Err(ImError::BadResponse(format!( "the photo answered {}", status.as_u16() ))); } _ => {} } let mime = response .headers() .get(reqwest::header::CONTENT_TYPE) .and_then(|value| value.to_str().ok()) .map(|value| { value .split(';') .next() .unwrap_or_default() .trim() .to_ascii_lowercase() }) .unwrap_or_default(); if !PHOTO_TYPES.contains(&mime.as_str()) { return Ok(None); } let etag = format!("\"p{version}\""); let answered = response .headers() .get(reqwest::header::ETAG) .and_then(|value| value.to_str().ok()); if answered != Some(etag.as_str()) { return Ok(None); } let bytes = read_limited(response, PHOTO_MAX_BYTES).await?; Ok(Some((mime, bytes))) } #[cfg(test)] mod tests { use super::*; #[test] fn sse_events_split_across_chunks_and_resume_ids() { let mut parser = SseParser::default(); assert!( parser .feed(b": keep-alive\n\nevent: mem") .unwrap() .is_empty() ); let events = parser .feed(b"ber\nid: 01CURSOR\ndata: {\"sub\":\"a\"}\ndata: more\r\n\r\n") .unwrap(); assert_eq!( events, vec![SseEvent { name: "member".into(), data: "{\"sub\":\"a\"}\nmore".into(), id: Some("01CURSOR".into()), }] ); // An event with no data is dropped. assert!(parser.feed(b"event: resync\n\n").unwrap().is_empty()); } #[test] fn sse_refuses_an_unbounded_line() { let mut parser = SseParser::default(); let long = vec![b'x'; MAX_EVENT_BYTES + 1]; assert!(parser.feed(&long).is_err()); } }