forge
Explore
Log in

Don't you dare go Hollow

iz

Clone
★ 0

0 watching0 forksRustAGPL-3.0567.3 KiB3950aceTahinli27 days ago34 commits

directory.rs535 lines, 19.2 KiBHistoryRawDownload
1//! The members mirror (docs/contracts.md section 3): a full read of `im`'s people directory at boot,
2//! then its change stream, applied to the local `members` table. The worker keeps running until the
3//! stop flag is set.
4//!
5//! Pages never call `im` to show a name or an avatar; they read this mirror. A member who is disabled
6//! or deleted loses their local sessions here, and the same check also runs at every request in the
7//! store, so either path alone is enough (contracts.md 2.5).
8//!
9//! The stream cursor is kept in `settings`. A `resync` event, or a cursor that `im` no longer knows,
10//! starts a full read again. A broken connection is retried with exponential backoff from one second
11//! to one minute, with jitter, so a restart of `im` does not bring every client back in the same
12//! instant.
13
14use std::collections::HashSet;
15use std::time::Duration;
16
17use futures_util::StreamExt;
18use iz_core::authz::Role;
19use iz_core::store::Store;
20use iz_core::store::members::DirectoryMember;
21use serde_json::Value;
22use tokio::sync::watch;
23
24use crate::oidc::{ImError, ImResult, OidcClient, read_limited};
25use crate::state::AppState;
26
27/// The setting that holds the stream cursor.
28pub const CURSOR_SETTING: &str = "directory_cursor";
29/// The setting that holds the role of a member the directory adds (`member` by default).
30pub const DEFAULT_ROLE_SETTING: &str = "default_role";
31/// The shortest wait before a reconnect. Reason: contracts.md 2.2 style backoff, first step.
32const BACKOFF_MIN: Duration = Duration::from_secs(1);
33/// The longest wait before a reconnect. Reason: a family board can wait a minute for `im`.
34const BACKOFF_MAX: Duration = Duration::from_secs(60);
35/// Silence after which the stream is considered dead. `im` sends a keep-alive every 30 seconds.
36const IDLE_LIMIT: Duration = Duration::from_secs(90);
37/// Largest directory listing read at once, in bytes. Reason: a family has a few dozen members, so
38/// this is far above a real listing and still bounds memory.
39const ROSTER_MAX_BYTES: usize = 8 * 1024 * 1024;
40/// Largest stream event accepted, in bytes. Reason: a member record is a few hundred bytes.
41const MAX_EVENT_BYTES: usize = 64 * 1024;
42/// Largest photo fetched from `im`, in bytes. Reason: avatars are small; this bounds the cache.
43pub const PHOTO_MAX_BYTES: usize = 5 * 1024 * 1024;
44/// The image types a photo may be served as. Anything else from `im` is not shown.
45pub const PHOTO_TYPES: [&str; 4] = ["image/png", "image/jpeg", "image/gif", "image/webp"];
46
47/// What can stop the mirror: the directory or the local store.
48#[derive(Debug, thiserror::Error)]
49pub enum MirrorError {
50 /// `im` failed to answer. The worker retries.
51 #[error(transparent)]
52 Im(#[from] ImError),
53 /// The local database failed. The worker retries.
54 #[error(transparent)]
55 Store(#[from] iz_core::Error),
56}
57
58/// A member record as `im` sends it (contracts.md 3.1). Unknown fields are ignored.
59#[derive(serde::Deserialize)]
60struct WireMember {
61 sub: String,
62 email: String,
63 name: String,
64 #[serde(default)]
65 admin: bool,
66 #[serde(default)]
67 disabled: bool,
68 #[serde(default)]
69 locale: Option<String>,
70 #[serde(default = "utc")]
71 zoneinfo: String,
72 #[serde(default)]
73 picture_version: i64,
74 /// The directory's change time (RFC 3339). Empty when `im` does not send one.
75 #[serde(default)]
76 updated_at: String,
77}
78
79fn utc() -> String {
80 "UTC".to_owned()
81}
82
83/// The listing of `im`'s directory (contracts.md 3.2). Members are kept as raw values so that one
84/// bad record does not stop the rest.
85#[derive(serde::Deserialize)]
86struct Roster {
87 members: Vec<Value>,
88 cursor: String,
89}
90
91/// How one connection of the stream ended.
92enum Ended {
93 /// The stop flag was set.
94 Stopped,
95 /// `im` asked for a full read again.
96 Resync,
97 /// The stream closed, went idle, or `im` closed it after 50 minutes. Reconnect with the cursor.
98 /// `delivered` says whether the connection carried any event.
99 Closed { delivered: bool },
100}
101
102/// Starts the mirror. Does nothing when OIDC is not configured.
103pub fn spawn(state: AppState, stop: watch::Receiver<bool>) {
104 let Some(oidc) = state.oidc.clone() else {
105 return;
106 };
107 tokio::spawn(run(state, oidc, stop));
108}
109
110async fn run(state: AppState, oidc: std::sync::Arc<OidcClient>, mut stop: watch::Receiver<bool>) {
111 let mut backoff = BACKOFF_MIN;
112 // A full read is needed at the start, after a resync, and after a failure. A plain reconnect
113 // resumes from the stored cursor, so it does not read the whole listing again.
114 let mut full = true;
115 loop {
116 match mirror_once(&state, &oidc, &mut stop, full).await {
117 Ok(Ended::Stopped) => return,
118 Ok(Ended::Resync) => {
119 tracing::info!("directory: the stream asked for a full read");
120 backoff = BACKOFF_MIN;
121 full = true;
122 }
123 Ok(Ended::Closed { delivered }) => {
124 tracing::info!("directory: the stream closed; reconnecting");
125 // A connection that carried events resets the wait. A silent one keeps growing it, so
126 // an `im` that closes streams at once is not polled every second.
127 if delivered {
128 backoff = BACKOFF_MIN;
129 }
130 full = false;
131 }
132 Err(error) => {
133 tracing::warn!(error = %error, retry_in = ?backoff, "directory: the mirror failed");
134 full = true;
135 }
136 }
137 if wait_or_stop(jittered(backoff), &mut stop).await {
138 return;
139 }
140 backoff = (backoff * 2).min(BACKOFF_MAX);
141 }
142}
143
144/// An optional full read, then one stream connection.
145async fn mirror_once(
146 state: &AppState,
147 oidc: &OidcClient,
148 stop: &mut watch::Receiver<bool>,
149 full: bool,
150) -> std::result::Result<Ended, MirrorError> {
151 if full {
152 full_read(state, oidc).await?;
153 }
154 stream(state, oidc, stop).await
155}
156
157/// Reads the whole directory and applies it. Members that the listing no longer has were deleted in
158/// `im`, so they are marked deleted here too.
159async fn full_read(state: &AppState, oidc: &OidcClient) -> std::result::Result<(), MirrorError> {
160 let token = oidc.service_token().await?;
161 let url = format!("{}/api/v1/directory", oidc.issuer());
162 let response = oidc
163 .http()
164 .get(url)
165 .bearer_auth(token)
166 .send()
167 .await
168 .map_err(|e| ImError::Unavailable(e.to_string()))?;
169 if !response.status().is_success() {
170 return Err(ImError::BadResponse(format!(
171 "the directory answered {}",
172 response.status().as_u16()
173 ))
174 .into());
175 }
176 let roster: Roster = decode_json_limited(response, ROSTER_MAX_BYTES).await?;
177 let default_role = default_role(&state.store).await?;
178 let mut listed = HashSet::new();
179 for raw in roster.members {
180 let Some(member) = parse_member(raw) else {
181 tracing::warn!("directory: skipping a member record that does not parse");
182 continue;
183 };
184 listed.insert(member.sub.clone());
185 apply(state, &member, default_role).await?;
186 }
187 for local in state.store.list_members().await? {
188 if !listed.contains(&local.sub) && !local.disabled {
189 tracing::info!(sub = %local.sub, "directory: member is gone from the listing; marking deleted");
190 state.store.mark_deleted(&local.sub).await?;
191 state.store.delete_sessions_by_sub(&local.sub).await?;
192 }
193 }
194 state
195 .store
196 .set_setting(CURSOR_SETTING, &roster.cursor)
197 .await?;
198 Ok(())
199}
200
201/// Decodes a listing, with the same size limit as the other reads.
202async fn decode_json_limited<T: serde::de::DeserializeOwned>(
203 response: reqwest::Response,
204 limit: usize,
205) -> ImResult<T> {
206 let body = read_limited(response, limit).await?;
207 serde_json::from_slice(&body)
208 .map_err(|e| ImError::BadResponse(format!("the directory listing: {e}")))
209}
210
211/// Opens the change stream from the stored cursor and applies events until the stream ends.
212async fn stream(
213 state: &AppState,
214 oidc: &OidcClient,
215 stop: &mut watch::Receiver<bool>,
216) -> std::result::Result<Ended, MirrorError> {
217 let token = oidc.service_token().await?;
218 let url = format!("{}/api/v1/directory/stream", oidc.issuer());
219 let mut request = oidc
220 .stream_http()
221 .get(url)
222 .bearer_auth(token)
223 .header(reqwest::header::ACCEPT, "text/event-stream");
224 if let Some(cursor) = state.store.get_setting(CURSOR_SETTING).await? {
225 request = request.header("Last-Event-ID", cursor);
226 }
227 let response = request
228 .send()
229 .await
230 .map_err(|e| ImError::Unavailable(e.to_string()))?;
231 if !response.status().is_success() {
232 return Err(ImError::BadResponse(format!(
233 "the stream answered {}",
234 response.status().as_u16()
235 ))
236 .into());
237 }
238 let mut chunks = response.bytes_stream();
239 let mut parser = SseParser::default();
240 let mut delivered = false;
241 loop {
242 let next = tokio::select! {
243 _ = stop.wait_for(|stopped| *stopped) => return Ok(Ended::Stopped),
244 next = tokio::time::timeout(IDLE_LIMIT, chunks.next()) => next,
245 };
246 let chunk = match next {
247 // Silence for longer than the limit: reconnect.
248 Err(_elapsed) => return Ok(Ended::Closed { delivered }),
249 Ok(None) => return Ok(Ended::Closed { delivered }),
250 Ok(Some(Err(error))) => return Err(ImError::Unavailable(error.to_string()).into()),
251 Ok(Some(Ok(bytes))) => bytes,
252 };
253 let events = parser.feed(&chunk).map_err(ImError::BadResponse)?;
254 delivered |= !events.is_empty();
255 for event in events {
256 match event.name.as_str() {
257 "member" => match serde_json::from_str::<Value>(&event.data)
258 .ok()
259 .and_then(parse_member)
260 {
261 Some(member) => {
262 let default_role = default_role(&state.store).await?;
263 apply(state, &member, default_role).await?;
264 }
265 None => {
266 tracing::warn!("directory: skipping a member event that does not parse")
267 }
268 },
269 "deleted" => match serde_json::from_str::<Value>(&event.data)
270 .ok()
271 .and_then(|v| v.get("sub").and_then(Value::as_str).map(str::to_owned))
272 {
273 Some(sub) => {
274 remove(state, &sub).await?;
275 }
276 None => tracing::warn!("directory: skipping a deleted event without a sub"),
277 },
278 "resync" => return Ok(Ended::Resync),
279 _ => {}
280 }
281 if let Some(id) = &event.id {
282 state.store.set_setting(CURSOR_SETTING, id).await?;
283 }
284 }
285 }
286}
287
288/// Applies one member record. A disabled member loses their sessions. A record the store refuses
289/// (for example a time zone it does not know) is logged and skipped, so one bad record never stops
290/// the mirror.
291async fn apply(
292 state: &AppState,
293 member: &DirectoryMember,
294 default_role: Role,
295) -> std::result::Result<(), MirrorError> {
296 match state
297 .store
298 .apply_directory_member(member, default_role)
299 .await
300 {
301 Ok(stored) => {
302 if stored.disabled {
303 state.store.delete_sessions_by_sub(&stored.sub).await?;
304 }
305 Ok(())
306 }
307 Err(iz_core::Error::Invalid(reason)) => {
308 tracing::warn!(sub = %member.sub, reason, "directory: skipping a member the store refuses");
309 Ok(())
310 }
311 Err(error) => Err(error.into()),
312 }
313}
314
315/// Marks a deleted member and ends their sessions.
316async fn remove(state: &AppState, sub: &str) -> std::result::Result<(), MirrorError> {
317 match state.store.mark_deleted(sub).await {
318 Ok(()) | Err(iz_core::Error::NotFound) => {}
319 Err(error) => return Err(error.into()),
320 }
321 state.store.delete_sessions_by_sub(sub).await?;
322 Ok(())
323}
324
325/// The role for a member the directory adds: the `default_role` setting, else `member`.
326pub async fn default_role(store: &Store) -> iz_core::Result<Role> {
327 Ok(store
328 .get_setting(DEFAULT_ROLE_SETTING)
329 .await?
330 .as_deref()
331 .and_then(Role::parse)
332 .unwrap_or(Role::Member))
333}
334
335/// Converts a raw member record into the store's form, or `None` when it does not parse.
336fn parse_member(raw: Value) -> Option<DirectoryMember> {
337 let wire: WireMember = serde_json::from_value(raw).ok()?;
338 Some(DirectoryMember {
339 sub: wire.sub,
340 email: wire.email,
341 name: wire.name,
342 im_admin: wire.admin,
343 disabled: wire.disabled,
344 locale: wire.locale,
345 zoneinfo: wire.zoneinfo,
346 picture_version: wire.picture_version,
347 updated_at: wire.updated_at,
348 })
349}
350
351/// Waits for `wait`, or returns `true` early when the stop flag is set.
352async fn wait_or_stop(wait: Duration, stop: &mut watch::Receiver<bool>) -> bool {
353 tokio::select! {
354 _ = stop.wait_for(|stopped| *stopped) => true,
355 () = tokio::time::sleep(wait) => false,
356 }
357}
358
359/// A wait between half and all of `backoff`. The jitter spreads the reconnects of several clients.
360fn jittered(backoff: Duration) -> Duration {
361 let mut bytes = [0u8; 8];
362 rand::fill(&mut bytes);
363 let fraction = (u64::from_le_bytes(bytes) % 1000) as f64 / 1000.0;
364 backoff.mul_f64(0.5 + fraction * 0.5)
365}
366
367/// One event of a server-sent event stream.
368#[derive(Debug, PartialEq, Eq)]
369pub struct SseEvent {
370 /// The `event:` name, `message` when none was sent.
371 pub name: String,
372 /// The `data:` lines joined with newlines.
373 pub data: String,
374 /// The `id:` of the event, which is the cursor to resume from.
375 pub id: Option<String>,
376}
377
378/// Reads a server-sent event stream (the HTML living standard, event stream section) from raw
379/// chunks. A line may be split across chunks; a blank line ends an event.
380#[derive(Default)]
381pub struct SseParser {
382 pending: Vec<u8>,
383 name: Option<String>,
384 data: Option<String>,
385 id: Option<String>,
386}
387
388impl SseParser {
389 /// Feeds one chunk and returns the events it completes. An over-long line is an error, so a
390 /// hostile stream cannot grow the buffer without bound.
391 pub fn feed(&mut self, chunk: &[u8]) -> std::result::Result<Vec<SseEvent>, String> {
392 self.pending.extend_from_slice(chunk);
393 let mut events = Vec::new();
394 while let Some(end) = self.pending.iter().position(|&b| b == b'\n') {
395 let line: Vec<u8> = self.pending.drain(..=end).collect();
396 let line = String::from_utf8_lossy(&line[..line.len() - 1]).into_owned();
397 let line = line.strip_suffix('\r').unwrap_or(&line).to_owned();
398 if line.is_empty() {
399 if let Some(event) = self.dispatch() {
400 events.push(event);
401 }
402 continue;
403 }
404 if line.starts_with(':') {
405 continue;
406 }
407 let (field, value) = match line.split_once(':') {
408 Some((field, value)) => (field, value.strip_prefix(' ').unwrap_or(value)),
409 None => (line.as_str(), ""),
410 };
411 match field {
412 "event" => self.name = Some(value.to_owned()),
413 "id" if !value.contains('\0') => self.id = Some(value.to_owned()),
414 "data" => {
415 let data = self.data.get_or_insert_with(String::new);
416 if !data.is_empty() {
417 data.push('\n');
418 }
419 data.push_str(value);
420 if data.len() > MAX_EVENT_BYTES {
421 return Err("a stream event is too large".into());
422 }
423 }
424 _ => {}
425 }
426 }
427 if self.pending.len() > MAX_EVENT_BYTES {
428 return Err("a stream line is too large".into());
429 }
430 Ok(events)
431 }
432
433 /// Ends the current event. An event with no data is dropped, as the standard says.
434 fn dispatch(&mut self) -> Option<SseEvent> {
435 let name = self.name.take();
436 let id = self.id.clone();
437 let data = self.data.take()?;
438 Some(SseEvent {
439 name: name.unwrap_or_else(|| "message".to_owned()),
440 data,
441 id,
442 })
443 }
444}
445
446/// Fetches the photo of `sub` at `version` from `im` with the service token. `None` when `im` has no
447/// photo, or the photo has a type iz does not serve. The answer must carry the ETag of that version:
448/// otherwise `im` has a newer photo, and it must not be cached under the older version.
449pub async fn fetch_photo(
450 oidc: &OidcClient,
451 sub: &str,
452 version: i64,
453) -> ImResult<Option<(String, Vec<u8>)>> {
454 let token = oidc.service_token().await?;
455 let url = format!("{}/api/v1/people/{sub}/photo?v={version}", oidc.issuer());
456 let response = oidc
457 .http()
458 .get(url)
459 .bearer_auth(token)
460 .send()
461 .await
462 .map_err(|e| ImError::Unavailable(e.to_string()))?;
463 match response.status() {
464 status if status == reqwest::StatusCode::NOT_FOUND => return Ok(None),
465 status if !status.is_success() => {
466 return Err(ImError::BadResponse(format!(
467 "the photo answered {}",
468 status.as_u16()
469 )));
470 }
471 _ => {}
472 }
473 let mime = response
474 .headers()
475 .get(reqwest::header::CONTENT_TYPE)
476 .and_then(|value| value.to_str().ok())
477 .map(|value| {
478 value
479 .split(';')
480 .next()
481 .unwrap_or_default()
482 .trim()
483 .to_ascii_lowercase()
484 })
485 .unwrap_or_default();
486 if !PHOTO_TYPES.contains(&mime.as_str()) {
487 return Ok(None);
488 }
489 let etag = format!("\"p{version}\"");
490 let answered = response
491 .headers()
492 .get(reqwest::header::ETAG)
493 .and_then(|value| value.to_str().ok());
494 if answered != Some(etag.as_str()) {
495 return Ok(None);
496 }
497 let bytes = read_limited(response, PHOTO_MAX_BYTES).await?;
498 Ok(Some((mime, bytes)))
499}
500
501#[cfg(test)]
502mod tests {
503 use super::*;
504
505 #[test]
506 fn sse_events_split_across_chunks_and_resume_ids() {
507 let mut parser = SseParser::default();
508 assert!(
509 parser
510 .feed(b": keep-alive\n\nevent: mem")
511 .unwrap()
512 .is_empty()
513 );
514 let events = parser
515 .feed(b"ber\nid: 01CURSOR\ndata: {\"sub\":\"a\"}\ndata: more\r\n\r\n")
516 .unwrap();
517 assert_eq!(
518 events,
519 vec![SseEvent {
520 name: "member".into(),
521 data: "{\"sub\":\"a\"}\nmore".into(),
522 id: Some("01CURSOR".into()),
523 }]
524 );
525 // An event with no data is dropped.
526 assert!(parser.feed(b"event: resync\n\n").unwrap().is_empty());
527 }
528
529 #[test]
530 fn sse_refuses_an_unbounded_line() {
531 let mut parser = SseParser::default();
532 let long = vec![b'x'; MAX_EVENT_BYTES + 1];
533 assert!(parser.feed(&long).is_err());
534 }
535}