From 1274ea055137815ece054d10dad8f1edd272a926 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Wed, 28 Oct 2026 10:35:50 +0300 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20feat:=20machine=20APIs:=20directory?= =?UTF-8?q?,=20directory=20stream=20with=20cursors,=20photo,=20family;=20s?= =?UTF-8?q?weeper=20spawned=20at=20boot?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Cargo.lock | 1 + crates/im-core/src/model.rs | 15 ++ crates/im-core/src/store/directory.rs | 125 ++++++++- crates/im-core/src/store/mod.rs | 6 +- crates/im-core/src/store/oidc.rs | 23 ++ crates/im-core/src/store/services.rs | 43 ++++ crates/im-core/src/store/users.rs | 152 +++++++---- crates/im-web/Cargo.toml | 1 + crates/im-web/src/api/directory.rs | 356 ++++++++++++++++++++++++++ crates/im-web/src/api/family.rs | 39 +++ crates/im-web/src/api/machine_auth.rs | 113 ++++++++ crates/im-web/src/api/mod.rs | 53 ++++ crates/im-web/src/api/photo.rs | 157 ++++++++++++ crates/im-web/src/api/tests.rs | 172 +++++++++++++ crates/im-web/src/boot.rs | 17 ++ crates/im-web/src/main.rs | 2 + crates/im-web/src/oidc/userinfo.rs | 2 +- crates/im-web/src/state.rs | 6 + crates/im-web/src/sweeper.rs | 66 +++++ 19 files changed, 1286 insertions(+), 63 deletions(-) create mode 100644 crates/im-core/src/store/services.rs create mode 100644 crates/im-web/src/api/directory.rs create mode 100644 crates/im-web/src/api/family.rs create mode 100644 crates/im-web/src/api/machine_auth.rs create mode 100644 crates/im-web/src/api/mod.rs create mode 100644 crates/im-web/src/api/photo.rs create mode 100644 crates/im-web/src/api/tests.rs create mode 100644 crates/im-web/src/sweeper.rs diff --git a/Cargo.lock b/Cargo.lock index 947bcf2..e371ca6 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1872,6 +1872,7 @@ dependencies = [ "topcoat", "tracing", "tracing-subscriber", + "ulid", ] [[package]] diff --git a/crates/im-core/src/model.rs b/crates/im-core/src/model.rs index 92d0da9..3ad9d45 100644 --- a/crates/im-core/src/model.rs +++ b/crates/im-core/src/model.rs @@ -299,3 +299,18 @@ pub struct KeyRecord { /// When the key stops signing. It stays published for a while after this time. pub retires_at: Option, } + +/// One row of the service switcher (contracts.md 4). +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Service { + /// Family key, such as `in`. + pub key: String, + /// Display name. + pub name: String, + /// Public origin. + pub url: String, + /// The last health probe's answer, `None` before the first probe. + pub healthy: Option, + /// When the last probe ran. + pub checked_at: Option, +} diff --git a/crates/im-core/src/store/directory.rs b/crates/im-core/src/store/directory.rs index 3ee27f2..dc1a99f 100644 --- a/crates/im-core/src/store/directory.rs +++ b/crates/im-core/src/store/directory.rs @@ -1,14 +1,18 @@ //! The change feed of the people directory: one row per change a machine client may need to see. //! -//! The rows are written in the same transaction as the change they describe, so a change is -//! never visible without its row, and a row never describes a change that did not happen. Rows are -//! read by the directory stream (contracts.md 3.2), which is built in a later step; until then they -//! only accumulate. The sweeper prunes rows older than 30 days. +//! The rows are written in the same transaction as the change they describe, so a change is never +//! visible without its row, and a row never describes a change that did not happen. The directory +//! stream (contracts.md 3.2) reads them with [`Store::directory_changes_after`]; the sweeper prunes +//! rows older than 30 days. Every committed change also wakes the receivers of +//! [`Store::directory_watch`], so a stream waits instead of polling. +use tokio::sync::watch; use turso::Connection; -use crate::error::Result; -use crate::store::db_err; +use crate::error::{Error, Result}; +use crate::model::User; +use crate::store::users::{USER_COLS, map_user}; +use crate::store::{Store, col_int, col_opt_int, col_text, db_err, fetch_all, fetch_opt}; use crate::time::now_stamp; /// What a directory row says happened to a person. @@ -28,6 +32,26 @@ impl ChangeKind { ChangeKind::Deleted => "deleted", } } + + /// The kind of a stored text, or `None` for anything the schema does not allow. + pub fn parse(text: &str) -> Option { + match text { + "member" => Some(ChangeKind::Member), + "deleted" => Some(ChangeKind::Deleted), + _ => None, + } + } +} + +/// One row of the change feed. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Change { + /// The sequence number: the cursor of the stream. + pub seq: i64, + /// The person the change is about. + pub sub: String, + /// What happened to the person. + pub kind: ChangeKind, } /// Appends one change row. Runs inside the caller's transaction, so it commits with the change. @@ -40,3 +64,92 @@ pub(crate) async fn record_change(conn: &Connection, sub: &str, kind: ChangeKind .map_err(db_err)?; Ok(()) } + +impl Store { + /// A receiver that changes every time a directory change commits. A stream subscribes before it + /// reads the feed, so a change made in between still wakes it. + pub fn directory_watch(&self) -> watch::Receiver { + self.inner.directory.subscribe() + } + + /// Wakes every directory receiver. Called after a transaction that wrote directory rows commits. + pub(crate) fn announce_directory(&self) { + self.inner + .directory + .send_modify(|generation| *generation = generation.wrapping_add(1)); + } + + /// The newest sequence number, or 0 when the feed is empty. + pub async fn directory_head(&self) -> Result { + let conn = self.read_conn().await; + head_of(&conn).await + } + + /// The oldest sequence number still kept, or `None` when the feed is empty. + pub async fn directory_oldest(&self) -> Result> { + let conn = self.read_conn().await; + fetch_opt(&conn, "SELECT MIN(seq) FROM directory_changes", (), |row| { + col_opt_int(row, 0) + }) + .await + .map(Option::flatten) + } + + /// The rows after `after`, oldest first, at most `limit` of them. + pub async fn directory_changes_after(&self, after: i64, limit: i64) -> Result> { + let conn = self.read_conn().await; + fetch_all( + &conn, + "SELECT seq, sub, kind FROM directory_changes WHERE seq > ?1 ORDER BY seq LIMIT ?2", + (after, limit), + |row| { + let kind = col_text(row, 2)?; + Ok(Change { + seq: col_int(row, 0)?, + sub: col_text(row, 1)?, + kind: ChangeKind::parse(&kind) + .ok_or_else(|| Error::Database("unknown directory change kind".into()))?, + }) + }, + ) + .await + } + + /// Every account, with the head of the feed read in the same step. The writer is held for both + /// reads, so no change can land between them: the cursor is exactly the state of the members. + pub async fn directory_snapshot(&self) -> Result<(i64, Vec)> { + let conn = self.inner.conn.lock().await; + let head = head_of(&conn).await?; + let users = fetch_all( + &conn, + &format!("SELECT {USER_COLS} FROM users ORDER BY created_at, id"), + (), + map_user, + ) + .await?; + Ok((head, users)) + } + + /// Deletes the rows written before `cutoff`. Returns how many were removed. + pub async fn prune_directory_changes(&self, cutoff: &str) -> Result { + let conn = self.inner.conn.lock().await; + conn.execute( + "DELETE FROM directory_changes WHERE at < ?1", + (cutoff.to_string(),), + ) + .await + .map_err(db_err) + } +} + +/// The newest sequence number on `conn`, or 0. +async fn head_of(conn: &Connection) -> Result { + fetch_opt( + conn, + "SELECT COALESCE(MAX(seq), 0) FROM directory_changes", + (), + |row| col_int(row, 0), + ) + .await + .map(|head| head.unwrap_or(0)) +} diff --git a/crates/im-core/src/store/mod.rs b/crates/im-core/src/store/mod.rs index 57497f8..3870e6b 100644 --- a/crates/im-core/src/store/mod.rs +++ b/crates/im-core/src/store/mod.rs @@ -13,6 +13,7 @@ pub mod directory; pub mod keys; pub mod migrate; pub mod oidc; +pub mod services; pub mod sessions; pub mod snapshot; pub mod users; @@ -22,7 +23,7 @@ use std::sync::Arc; use std::sync::atomic::{AtomicUsize, Ordering}; use std::time::Duration; -use tokio::sync::{Mutex, MutexGuard}; +use tokio::sync::{Mutex, MutexGuard, watch}; use turso::transaction::Transaction; use turso::{Builder, Connection, Database, IntoParams, Row, Value}; @@ -54,6 +55,8 @@ struct Inner { readers: Vec>, /// Round-robin start index for `read_conn`. next_reader: AtomicUsize, + /// Counts the committed changes of the people directory. A stream waits on a receiver of it. + directory: watch::Sender, } impl Store { @@ -81,6 +84,7 @@ impl Store { conn: Mutex::new(conn), readers, next_reader: AtomicUsize::new(0), + directory: watch::channel(0).0, }), }) } diff --git a/crates/im-core/src/store/oidc.rs b/crates/im-core/src/store/oidc.rs index eae9c08..58d15a2 100644 --- a/crates/im-core/src/store/oidc.rs +++ b/crates/im-core/src/store/oidc.rs @@ -124,6 +124,29 @@ async fn insert_refresh(conn: &Connection, new: &NewRefreshToken<'_>, now: &str) impl Store { /// Stores a new authorization code. + /// Deletes the authorization codes that expired before `cutoff`. Run by the sweeper, which keeps + /// codes for a day past their expiry so that a reused code is still recognised as reuse. + pub async fn sweep_auth_codes(&self, cutoff: &str) -> Result { + let conn = self.inner.conn.lock().await; + conn.execute( + "DELETE FROM auth_codes WHERE expires_at < ?1", + (cutoff.to_string(),), + ) + .await + .map_err(db_err) + } + + /// Deletes the refresh tokens that expired before `now`. Run by the sweeper. + pub async fn sweep_refresh_tokens(&self, now: &str) -> Result { + let conn = self.inner.conn.lock().await; + conn.execute( + "DELETE FROM refresh_tokens WHERE expires_at < ?1", + (now.to_string(),), + ) + .await + .map_err(db_err) + } + pub async fn insert_auth_code(&self, new: &NewAuthCode<'_>) -> Result<()> { let conn = self.inner.conn.lock().await; conn.execute( diff --git a/crates/im-core/src/store/services.rs b/crates/im-core/src/store/services.rs new file mode 100644 index 0000000..44cd240 --- /dev/null +++ b/crates/im-core/src/store/services.rs @@ -0,0 +1,43 @@ +//! The service switcher list (contracts.md 4): one row per family app, plus im's own row. +//! +//! im's row is kept at boot from `base_url`, so it cannot drift from the configuration. The other rows +//! are written by the admin pages, which are not built yet. + +use crate::error::Result; +use crate::model::Service; +use crate::store::{Store, col_opt_int, col_opt_text, col_text, db_err, fetch_all}; + +impl Store { + /// Every service, in the admin's order. + pub async fn list_services(&self) -> Result> { + let conn = self.read_conn().await; + fetch_all( + &conn, + "SELECT key, name, url, healthy, checked_at FROM services ORDER BY position, key", + (), + |row| { + Ok(Service { + key: col_text(row, 0)?, + name: col_text(row, 1)?, + url: col_text(row, 2)?, + healthy: col_opt_int(row, 3)?.map(|value| value != 0), + checked_at: col_opt_text(row, 4)?, + }) + }, + ) + .await + } + + /// Creates or updates im's own row (key `im`). Its position and client stay as they are. + pub async fn upsert_home_service(&self, name: &str, url: &str) -> Result<()> { + let conn = self.inner.conn.lock().await; + conn.execute( + "INSERT INTO services (key, name, url, position, client_id) VALUES ('im', ?1, ?2, 0, NULL) \ + ON CONFLICT(key) DO UPDATE SET name = excluded.name, url = excluded.url", + (name.to_string(), url.to_string()), + ) + .await + .map_err(db_err)?; + Ok(()) + } +} diff --git a/crates/im-core/src/store/users.rs b/crates/im-core/src/store/users.rs index 59089de..061edb6 100644 --- a/crates/im-core/src/store/users.rs +++ b/crates/im-core/src/store/users.rs @@ -24,12 +24,12 @@ use crate::store::{ use crate::time::now_stamp; /// The columns of a user row, in the order [`map_user`] reads them. -const USER_COLS: &str = "id, email, name, password_hash, is_admin, disabled_at, \ +pub(crate) const USER_COLS: &str = "id, email, name, password_hash, is_admin, disabled_at, \ totp_secret_sealed, totp_enabled_at, totp_last_step, locale, zoneinfo, theme, \ photo_mime, picture_version, created_at, updated_at, locale_auto"; /// Maps a row selected with [`USER_COLS`]. -fn map_user(row: &Row) -> Result { +pub(crate) fn map_user(row: &Row) -> Result { Ok(User { id: col_text(row, 0)?, email: col_text(row, 1)?, @@ -100,26 +100,36 @@ impl Store { let id = new_id(); let now = now_stamp(); let conn = self.inner.conn.lock().await; - let changed = conn - .execute( - "INSERT INTO users (id, email, email_folded, name, password_hash, is_admin, \ - created_at, updated_at) \ - SELECT ?1, ?2, ?2, ?3, ?4, 1, ?5, ?5 \ - WHERE NOT EXISTS (SELECT 1 FROM users)", - ( - id.clone(), - email.to_string(), - name.to_string(), - password_hash.to_string(), - now, - ), - ) - .await - .map_err(insert_error)?; + let tx = conn.unchecked_transaction().await.map_err(db_err)?; + let outcome: Result = async { + let changed = tx + .execute( + "INSERT INTO users (id, email, email_folded, name, password_hash, is_admin, \ + created_at, updated_at) \ + SELECT ?1, ?2, ?2, ?3, ?4, 1, ?5, ?5 \ + WHERE NOT EXISTS (SELECT 1 FROM users)", + ( + id.clone(), + email.to_string(), + name.to_string(), + password_hash.to_string(), + now, + ), + ) + .await + .map_err(insert_error)?; + if changed == 1 { + record_change(&tx, &id, ChangeKind::Member).await?; + } + Ok(changed == 1) + } + .await; + let created = finish(tx, outcome).await?; drop(conn); - if changed == 0 { + if !created { return Err(Error::Conflict("setup is already complete".into())); } + self.announce_directory(); self.user_by_id(&id).await?.ok_or(Error::NotFound) } @@ -135,21 +145,28 @@ impl Store { let id = new_id(); let now = now_stamp(); let conn = self.inner.conn.lock().await; - conn.execute( - "INSERT INTO users (id, email, email_folded, name, password_hash, is_admin, \ - created_at, updated_at) VALUES (?1, ?2, ?2, ?3, ?4, ?5, ?6, ?6)", - ( - id.clone(), - email.to_string(), - name.to_string(), - password_hash.to_string(), - i64::from(is_admin), - now, - ), - ) - .await - .map_err(insert_error)?; + let tx = conn.unchecked_transaction().await.map_err(db_err)?; + let outcome: Result<()> = async { + tx.execute( + "INSERT INTO users (id, email, email_folded, name, password_hash, is_admin, \ + created_at, updated_at) VALUES (?1, ?2, ?2, ?3, ?4, ?5, ?6, ?6)", + ( + id.clone(), + email.to_string(), + name.to_string(), + password_hash.to_string(), + i64::from(is_admin), + now, + ), + ) + .await + .map_err(insert_error)?; + record_change(&tx, &id, ChangeKind::Member).await + } + .await; + finish(tx, outcome).await?; drop(conn); + self.announce_directory(); self.user_by_id(&id).await?.ok_or(Error::NotFound) } @@ -196,7 +213,11 @@ impl Store { record_change(&tx, id, ChangeKind::Member).await } .await; - finish(tx, outcome).await + let result = finish(tx, outcome).await; + if result.is_ok() { + self.announce_directory(); + } + result } /// Changes the language, time zone and theme. `locale_auto` true means the language follows the @@ -211,25 +232,34 @@ impl Store { theme: &str, ) -> Result<()> { let conn = self.inner.conn.lock().await; - let changed = conn - .execute( - "UPDATE users SET locale = ?2, locale_auto = ?3, zoneinfo = ?4, theme = ?5, \ - updated_at = ?6 WHERE id = ?1", - ( - id.to_string(), - locale.to_string(), - i64::from(locale_auto), - zoneinfo.to_string(), - theme.to_string(), - now_stamp(), - ), - ) - .await - .map_err(db_err)?; - if changed == 0 { - return Err(Error::NotFound); + let tx = conn.unchecked_transaction().await.map_err(db_err)?; + let outcome: Result<()> = async { + let changed = tx + .execute( + "UPDATE users SET locale = ?2, locale_auto = ?3, zoneinfo = ?4, theme = ?5, \ + updated_at = ?6 WHERE id = ?1", + ( + id.to_string(), + locale.to_string(), + i64::from(locale_auto), + zoneinfo.to_string(), + theme.to_string(), + now_stamp(), + ), + ) + .await + .map_err(db_err)?; + if changed == 0 { + return Err(Error::NotFound); + } + record_change(&tx, id, ChangeKind::Member).await } - Ok(()) + .await; + let result = finish(tx, outcome).await; + if result.is_ok() { + self.announce_directory(); + } + result } /// Records that a photo was stored: sets its MIME type, bumps `picture_version` so caches see a @@ -253,7 +283,11 @@ impl Store { record_change(&tx, id, ChangeKind::Member).await } .await; - finish(tx, outcome).await + let result = finish(tx, outcome).await; + if result.is_ok() { + self.announce_directory(); + } + result } /// Records that the photo was removed. Returns false, and writes nothing, when there was no @@ -277,7 +311,11 @@ impl Store { Ok(true) } .await; - finish(tx, outcome).await + let result = finish(tx, outcome).await; + if matches!(result, Ok(true)) { + self.announce_directory(); + } + result } /// Stores a new argon2id hash. The caller has checked the policy and the current password. @@ -335,7 +373,11 @@ impl Store { Ok(true) } .await; - finish(tx, outcome).await + let result = finish(tx, outcome).await; + if matches!(result, Ok(true)) { + self.announce_directory(); + } + result } /// Holds a sealed TOTP secret while its enrolment waits for a confirming code. Replaces an diff --git a/crates/im-web/Cargo.toml b/crates/im-web/Cargo.toml index cc1af9d..1b9c977 100644 --- a/crates/im-web/Cargo.toml +++ b/crates/im-web/Cargo.toml @@ -23,6 +23,7 @@ tokio = { workspace = true, features = ["net", "signal", "time", "io-util"] } topcoat.workspace = true tracing.workspace = true tracing-subscriber = { workspace = true, features = ["env-filter"] } +ulid.workspace = true [dev-dependencies] tempfile.workspace = true diff --git a/crates/im-web/src/api/directory.rs b/crates/im-web/src/api/directory.rs new file mode 100644 index 0000000..1ae4754 --- /dev/null +++ b/crates/im-web/src/api/directory.rs @@ -0,0 +1,356 @@ +//! The people directory of `im` (`docs/contracts.md` section 3): the full listing, and the change stream +//! that follows it. +//! +//! The listing and its cursor are read in one step (`Store::directory_snapshot`), so the cursor is exactly +//! the state of the members. The stream resumes from `Last-Event-ID` (or `?cursor=`). A cursor that is not +//! a non-negative integer, that is ahead of the feed, or that is older than the oldest kept row gets one +//! `resync` event and the stream closes: the client then reads the listing again. Otherwise every row after +//! the cursor is sent (`member` with the current record, or `deleted`), and the stream then waits on the +//! feed's watch channel. It ends when the token expires (or after 50 minutes), when the calling client is +//! disabled or removed, or when the client's stream is cut at the per-client cap (four at once, 429 beyond). + +use std::collections::{HashMap, VecDeque}; +use std::sync::{Arc, Mutex, PoisonError}; +use std::time::Duration; + +use futures_util::{Stream, stream}; +use http::header::HeaderValue; +use im_core::model::User; +use im_core::store::Store; +use im_core::store::directory::{Change, ChangeKind}; +use im_core::time::unix_now; +use serde_json::{Value, json}; +use tokio::sync::watch; +use tokio::time::{Instant, Interval}; +use topcoat::Result; +use topcoat::context::{Cx, app_context}; +use topcoat::router::content::sse::{Event, KeepAlive, Sse, last_event_id}; +use topcoat::router::request::uri; +use topcoat::router::response::{IntoResponse, Response}; +use topcoat::router::{StatusCode, route}; + +use super::machine_auth::{DIRECTORY_READ, Machine, require}; +use super::{api_error, json_response}; +use crate::oidc::parse_pairs; +use crate::state::AppState; + +/// Most streams one client may hold open at once. A further one is refused with `429`. +pub const MAX_STREAMS_PER_CLIENT: usize = 4; + +/// Longest a stream lives, in seconds of wall time, whatever the token's expiry says (contracts 3.2). +pub const STREAM_MAX_LIFE: Duration = Duration::from_secs(50 * 60); + +/// Silence after which a keep-alive comment is sent (contracts 3.2 says every 30 s; 25 s keeps a margin). +pub const KEEP_ALIVE: Duration = Duration::from_secs(25); + +/// Rows read from the feed in one batch. +const BATCH: i64 = 200; + +/// How long a `Retry-After` the refused client is given, in seconds. +const RETRY_AFTER_SECS: &str = "5"; + +/// The open streams of each client. Shared by every request, so the cap holds across connections. +#[derive(Default)] +pub struct StreamSlots { + open: Mutex>, +} + +/// One open stream of a client. Dropping it frees the slot, so a stream that ends for any reason gives its +/// slot back. +pub struct SlotGuard { + slots: Arc, + client_id: String, +} + +impl StreamSlots { + /// Takes a slot for `client_id`, or `None` when the client already holds the maximum. + pub fn acquire(this: &Arc, client_id: &str) -> Option { + let mut open = this.open.lock().unwrap_or_else(PoisonError::into_inner); + let count = open.entry(client_id.to_owned()).or_insert(0); + if *count >= MAX_STREAMS_PER_CLIENT { + return None; + } + *count += 1; + Some(SlotGuard { + slots: Arc::clone(this), + client_id: client_id.to_owned(), + }) + } +} + +impl Drop for SlotGuard { + fn drop(&mut self) { + let mut open = self + .slots + .open + .lock() + .unwrap_or_else(PoisonError::into_inner); + if let Some(count) = open.get_mut(&self.client_id) { + *count = count.saturating_sub(1); + if *count == 0 { + open.remove(&self.client_id); + } + } + } +} + +/// The wire form of one member (contracts 3.1). +pub fn member_json(user: &User) -> Value { + json!({ + "sub": user.id, + "email": user.email, + "name": user.name, + "admin": user.is_admin, + "disabled": user.is_disabled(), + "locale": user.locale, + "zoneinfo": user.zoneinfo, + "picture_version": user.picture_version, + "updated_at": user.updated_at, + }) +} + +/// `GET /api/v1/directory`: every account, disabled ones included, and the cursor of this state. +#[route(GET "/api/v1/directory")] +async fn directory(cx: &Cx) -> Result { + let app = app_context::(cx); + let machine = match require(app, cx, DIRECTORY_READ).await? { + Ok(machine) => machine, + Err(refusal) => return Ok(refusal), + }; + tracing::debug!(caller = %machine.caller, "directory: listing"); + let (head, users) = app.store.directory_snapshot().await?; + let members: Vec = users.iter().map(member_json).collect(); + Ok(json_response( + StatusCode::OK, + &json!({"members": members, "cursor": head.to_string()}), + )) +} + +/// `GET /api/v1/directory/stream`: the change stream, as `text/event-stream`. +#[route(GET "/api/v1/directory/stream")] +async fn directory_stream(cx: &Cx) -> Result { + let app = app_context::(cx); + let machine = match require(app, cx, DIRECTORY_READ).await? { + Ok(machine) => machine, + Err(refusal) => return Ok(refusal), + }; + let Some(slot) = StreamSlots::acquire(&app.stream_slots, &machine.client_id) else { + let mut response = api_error( + StatusCode::TOO_MANY_REQUESTS, + "rate_limited", + "This client already has the maximum number of directory streams open.", + None, + ); + response + .headers_mut() + .insert("retry-after", HeaderValue::from_static(RETRY_AFTER_SECS)); + return Ok(response); + }; + // Subscribed before the feed is read, so a change made in between still wakes the stream. + let wake = app.store.directory_watch(); + let head = app.store.directory_head().await?; + let oldest = app.store.directory_oldest().await?; + let requested = requested_cursor(cx); + let Some(start) = resume_point(requested.as_deref(), head, oldest) else { + return sse(cx, stream::iter(vec![Ok(resync_event())])); + }; + let deadline = Instant::now() + stream_life(&machine); + let follow = Follow { + stop: app.stop.clone(), + store: app.store.clone(), + client_id: machine.client_id.clone(), + cursor: start, + wake, + check: tokio::time::interval_at(Instant::now() + KEEP_ALIVE, KEEP_ALIVE), + deadline, + pending: VecDeque::new(), + _slot: slot, + }; + sse(cx, follow_events(follow)) +} + +/// The state of one stream between two events. +struct Follow { + /// Set when the process stops: the stream then ends, so the server can drain. + stop: watch::Receiver, + store: Store, + client_id: String, + /// The last sequence number sent. + cursor: i64, + /// Woken by every committed directory change. + wake: watch::Receiver, + /// Checks, every [`KEEP_ALIVE`], that the calling client is still enabled. + check: Interval, + /// The stream ends at this time (the token's expiry or the 50-minute cap). + deadline: Instant, + /// Events read but not yet sent. + pending: VecDeque, + /// Holds the client's slot for as long as the stream lives. + _slot: SlotGuard, +} + +/// The events of a stream from its cursor on. It ends on a store failure, a disabled client, the +/// deadline, or a closed feed; the browser or consumer reconnects with its last cursor. +fn follow_events(follow: Follow) -> impl Stream> + Send + 'static { + stream::unfold(follow, |mut follow| async move { + loop { + if let Some(event) = follow.pending.pop_front() { + return Some((Ok(event), follow)); + } + match follow + .store + .directory_changes_after(follow.cursor, BATCH) + .await + { + Ok(changes) if !changes.is_empty() => { + for change in changes { + match change_event(&follow.store, &change).await { + Ok(event) => follow.pending.push_back(event), + Err(error) => { + tracing::error!(error = %error, "directory stream: a change could not be read"); + return None; + } + } + follow.cursor = change.seq; + } + continue; + } + Ok(_) => {} + Err(error) => { + tracing::error!(error = %error, "directory stream: the feed could not be read"); + return None; + } + } + tokio::select! { + changed = follow.wake.changed() => { + if changed.is_err() { + return None; + } + } + _ = follow.check.tick() => { + match follow.store.client_by_id(&follow.client_id).await { + Ok(Some(client)) if !client.is_disabled() => {} + _ => return None, + } + } + () = stopped(&mut follow.stop) => return None, + () = tokio::time::sleep_until(follow.deadline) => return None, + } + } + }) +} + +/// Resolves when the stop flag is set. A flag whose sender is gone never resolves, so a stream is not +/// ended by a test state that has no server behind it. +async fn stopped(stop: &mut watch::Receiver) { + if stop.wait_for(|stopped| *stopped).await.is_err() { + std::future::pending::<()>().await; + } +} + +/// The event of one change row, with the row's sequence number as its id. A member row is sent with the +/// person's current record; if the person is gone by then, the event is `deleted`. +async fn change_event(store: &Store, change: &Change) -> im_core::Result { + let user = match change.kind { + ChangeKind::Member => store.user_by_id(&change.sub).await?, + ChangeKind::Deleted => None, + }; + let event = match user { + Some(user) => Event::new() + .event("member") + .data(member_json(&user).to_string()), + None => Event::new() + .event("deleted") + .data(json!({"sub": change.sub}).to_string()), + }; + Ok(event.id(change.seq.to_string())) +} + +/// The one `resync` event: the cursor is unusable, so the consumer reads the listing again. +fn resync_event() -> Event { + Event::new().event("resync").data("{}") +} + +/// The cursor the client asked to resume from: `Last-Event-ID`, else `?cursor=`. A repeated `cursor` +/// parameter is treated as garbage, which means resync. +fn requested_cursor(cx: &Cx) -> Option { + if let Some(id) = last_event_id(cx).filter(|id| !id.is_empty()) { + return Some(id.to_owned()); + } + let query = uri(cx).query()?; + let pairs = parse_pairs(query.as_bytes())?; + match crate::oidc::single(&pairs, "cursor") { + crate::oidc::Single::Absent => None, + crate::oidc::Single::One(value) => Some(value.to_owned()), + crate::oidc::Single::Repeated => Some(String::new()), + } +} + +/// Where a stream starts, or `None` when it must resync. No cursor starts at the head (the consumer reads +/// the listing first). A cursor must be digits only, not ahead of the head, and not older than the oldest +/// kept row: the rows between it and that row were pruned, so they cannot be replayed. +pub fn resume_point(requested: Option<&str>, head: i64, oldest: Option) -> Option { + let Some(text) = requested else { + return Some(head); + }; + if text.is_empty() || !text.bytes().all(|byte| byte.is_ascii_digit()) { + return None; + } + let cursor: i64 = text.parse().ok()?; + if cursor > head { + return None; + } + if let Some(oldest) = oldest + && cursor.saturating_add(1) < oldest + { + return None; + } + Some(cursor) +} + +/// How long a stream of this caller may live: until the token expires, and at most [`STREAM_MAX_LIFE`]. +fn stream_life(machine: &Machine) -> Duration { + let until_expiry = u64::try_from(machine.expires_at - unix_now()).unwrap_or(0); + Duration::from_secs(until_expiry).min(STREAM_MAX_LIFE) +} + +/// The response of a stream: the events, with a keep-alive comment while idle. `X-Accel-Buffering: no` +/// stops a reverse proxy from holding the events back. +fn sse( + cx: &Cx, + events: impl Stream> + Send + 'static, +) -> Result { + let mut response = Sse::new(events) + .keep_alive(KeepAlive::new().interval(KEEP_ALIVE).text("keepalive")) + .into_response(cx)?; + response + .headers_mut() + .insert("x-accel-buffering", HeaderValue::from_static("no")); + Ok(response) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_cursor_resumes_only_inside_the_kept_range() { + // No cursor: start at the head. + assert_eq!(resume_point(None, 7, Some(3)), Some(7)); + // Inside the range, and at the head. + assert_eq!(resume_point(Some("5"), 7, Some(3)), Some(5)); + assert_eq!(resume_point(Some("7"), 7, Some(3)), Some(7)); + // Ahead of the head, negative, empty, signed or not a number: resync. + assert_eq!(resume_point(Some("8"), 7, Some(3)), None); + assert_eq!(resume_point(Some("-1"), 7, Some(3)), None); + assert_eq!(resume_point(Some("+1"), 7, Some(3)), None); + assert_eq!(resume_point(Some(""), 7, Some(3)), None); + assert_eq!(resume_point(Some("abc"), 7, Some(3)), None); + // Rows 1 and 2 were pruned, so row 3 is the oldest kept. A cursor of 1 still needs row 2: resync. + // A cursor of 2 needs only rows from 3 on: fine. + assert_eq!(resume_point(Some("1"), 7, Some(3)), None); + assert_eq!(resume_point(Some("2"), 7, Some(3)), Some(2)); + // Empty feed: cursor 0 is at the head. + assert_eq!(resume_point(Some("0"), 0, None), Some(0)); + } +} diff --git a/crates/im-web/src/api/family.rs b/crates/im-web/src/api/family.rs new file mode 100644 index 0000000..a567057 --- /dev/null +++ b/crates/im-web/src/api/family.rs @@ -0,0 +1,39 @@ +//! `GET /api/v1/family` (`docs/contracts.md` section 4): the switcher list, in the admin's order. +//! +//! The rows are the `services` table: each family app with its public origin, and im's own row. A row's +//! `healthy` is `null` until the first probe. Any caller with the directory scope may read the list. + +use im_core::model::Service; +use serde_json::{Value, json}; +use topcoat::Result; +use topcoat::context::{Cx, app_context}; +use topcoat::router::StatusCode; +use topcoat::router::response::Response; +use topcoat::router::route; + +use super::machine_auth::{DIRECTORY_READ, require}; +use crate::oidc::json_response; +use crate::state::AppState; + +/// `GET /api/v1/family`. +#[route(GET "/api/v1/family")] +async fn family(cx: &Cx) -> Result { + let app = app_context::(cx); + if let Err(refusal) = require(app, cx, DIRECTORY_READ).await? { + return Ok(refusal); + } + let services = app.store.list_services().await?; + let list: Vec = services.iter().map(service_json).collect(); + Ok(json_response(StatusCode::OK, &json!({"services": list}))) +} + +/// The wire form of one switcher row. +fn service_json(service: &Service) -> Value { + json!({ + "key": service.key, + "name": service.name, + "url": service.url, + "healthy": service.healthy, + "checked_at": service.checked_at, + }) +} diff --git a/crates/im-web/src/api/machine_auth.rs b/crates/im-web/src/api/machine_auth.rs new file mode 100644 index 0000000..326704a --- /dev/null +++ b/crates/im-web/src/api/machine_auth.rs @@ -0,0 +1,113 @@ +//! Checks the client-credentials tokens that family services present to `im` (contracts 2.6). +//! +//! `im` verifies its own tokens: the signature against the published keys, `iss` exactly, `aud` exactly +//! the string `im` (an array is refused, because `im` never issues one), `exp` and `iat`. Then the token +//! must be a machine token: `sub` is `client:`, `svc` names a family key, and it carries no `sid`. +//! The client it names must still exist, be enabled, and be registered under that family key. A user's +//! access token and an ID token fail one of these checks, so they never open a machine route. + +use http::header::AUTHORIZATION; +use im_core::jwt::{self, PublishedKey}; +use im_core::oauth::is_valid_family_key; +use im_core::time::unix_now; +use serde_json::Value; +use topcoat::Result; +use topcoat::context::Cx; +use topcoat::router::StatusCode; +use topcoat::router::request::headers; +use topcoat::router::response::Response; + +use super::{SCOPE_CHALLENGE, TOKEN_CHALLENGE, api_error}; +use crate::oidc::userinfo::bearer; +use crate::oidc::{issuer, signing}; +use crate::state::AppState; + +/// The scope of the people directory, its stream and the photos (contracts 2.6 and 3). +pub const DIRECTORY_READ: &str = "directory.read"; + +/// The audience every directory, photo and family route requires. +pub const MACHINE_AUDIENCE: &str = "im"; + +/// A verified machine caller. +#[derive(Debug, Clone)] +pub struct Machine { + /// The client the token was issued to (`azp`). + pub client_id: String, + /// The family key of the caller (`svc`). + pub caller: String, + /// When the token expires, in Unix seconds. A stream ends no later than this. + pub expires_at: i64, +} + +/// Verifies the bearer token of the request for `scope`. The outer `Result` is a server failure; the +/// inner one is the refusal, ready to send as the answer. +pub async fn require( + app: &AppState, + cx: &Cx, + scope: &str, +) -> Result> { + let Some(token) = bearer(headers(cx).get(AUTHORIZATION)) else { + return Ok(Err(refused())); + }; + let published = signing::published_keys(&app.store).await?; + let keys: Vec = published + .iter() + .filter_map(|key| PublishedKey::new(key.kid.clone(), &key.public_raw)) + .collect(); + let Ok(claims) = jwt::verify(&keys, token) else { + return Ok(Err(refused())); + }; + // The audience must be exactly the string `im`. `check_claims` also checks it, and the exp and iat. + if jwt::single_audience(&claims) != Some(MACHINE_AUDIENCE) { + return Ok(Err(refused())); + } + if jwt::check_claims(&claims, issuer(app), MACHINE_AUDIENCE, unix_now()).is_err() { + return Ok(Err(refused())); + } + let text = |name: &str| claims.get(name).and_then(Value::as_str); + let (Some(client_id), Some(sub), Some(caller), Some(expires_at)) = ( + text("azp"), + text("sub"), + text("svc"), + claims.get("exp").and_then(Value::as_i64), + ) else { + return Ok(Err(refused())); + }; + // A person's token carries a session (`sid`) and a person's id as `sub`; neither is a machine token. + if sub != format!("client:{client_id}") + || claims.contains_key("sid") + || !is_valid_family_key(caller) + { + return Ok(Err(refused())); + } + let Some(client) = app.store.client_by_id(client_id).await? else { + return Ok(Err(refused())); + }; + if client.is_disabled() || client.service_key.as_deref() != Some(caller) { + return Ok(Err(refused())); + } + let granted = text("scope").unwrap_or_default(); + if !granted.split_whitespace().any(|word| word == scope) { + return Ok(Err(api_error( + StatusCode::FORBIDDEN, + "insufficient_scope", + "The token does not grant the scope this route needs.", + Some(SCOPE_CHALLENGE), + ))); + } + Ok(Ok(Machine { + client_id: client.id, + caller: caller.to_owned(), + expires_at, + })) +} + +/// `401 invalid_token`. One answer for every reason, so the reason is not disclosed. +fn refused() -> Response { + api_error( + StatusCode::UNAUTHORIZED, + "invalid_token", + "The access token is missing, invalid, expired, or not issued for this service.", + Some(TOKEN_CHALLENGE), + ) +} diff --git a/crates/im-web/src/api/mod.rs b/crates/im-web/src/api/mod.rs new file mode 100644 index 0000000..57413e9 --- /dev/null +++ b/crates/im-web/src/api/mod.rs @@ -0,0 +1,53 @@ +//! The machine API of `im` (`docs/contracts.md` sections 3 and 4): the people directory and its change +//! stream, the profile photos, and the service switcher list. +//! +//! Every route here needs a client-credentials token that `im` issued to a family service, with the +//! audience `im` and the scope the route needs (`machine_auth.rs`). Errors are JSON with a real status +//! (contracts section 7): `{"error": ..., "message": ...}`. + +pub mod directory; +pub mod family; +pub mod machine_auth; +pub mod photo; + +#[cfg(test)] +mod tests; + +use http::header::WWW_AUTHENTICATE; +use serde_json::json; +use topcoat::router::response::Response; +use topcoat::router::{HeaderValue, StatusCode}; + +use crate::oidc::json_response; + +/// The `WWW-Authenticate` challenge of a token that is missing or not valid for this service. +pub const TOKEN_CHALLENGE: &str = "Bearer error=\"invalid_token\""; + +/// The `WWW-Authenticate` challenge of a valid token that lacks the scope a route needs. +pub const SCOPE_CHALLENGE: &str = "Bearer error=\"insufficient_scope\""; + +/// A machine error: the status, the stable word, a message for logs, and the challenge of a 401 or 403. +pub fn api_error( + status: StatusCode, + error: &str, + message: &str, + challenge: Option<&'static str>, +) -> Response { + let mut response = json_response(status, &json!({"error": error, "message": message})); + if let Some(challenge) = challenge { + response + .headers_mut() + .insert(WWW_AUTHENTICATE, HeaderValue::from_static(challenge)); + } + response +} + +/// `404 not_found` for a route that has no such thing. +pub fn not_found() -> Response { + api_error( + StatusCode::NOT_FOUND, + "not_found", + "There is nothing at this address.", + None, + ) +} diff --git a/crates/im-web/src/api/photo.rs b/crates/im-web/src/api/photo.rs new file mode 100644 index 0000000..e699738 --- /dev/null +++ b/crates/im-web/src/api/photo.rs @@ -0,0 +1,157 @@ +//! `GET /api/v1/people/{sub}/photo` (`docs/contracts.md` section 3.2): a person's profile photo, as bytes. +//! +//! The `sub` must be a ULID, else `404`. A person with no photo, an unknown or deleted person, and a photo +//! whose stored type is not on the allowlist are all `404`, so the answer does not say which it was. There +//! is no initials picture for a machine. The bytes go with `nosniff` and a `"p"` ETag. With +//! `?v=` equal to the current version the answer may be cached for a year (the URL names the version); +//! otherwise it may be kept but must be checked again. `If-None-Match` gets a `304`. + +use http::header::{CACHE_CONTROL, CONTENT_TYPE, ETAG, IF_NONE_MATCH, X_CONTENT_TYPE_OPTIONS}; +use im_core::photo::read_photo; +use topcoat::Result; +use topcoat::context::{Cx, app_context}; +use topcoat::router::request::{headers, uri}; +use topcoat::router::response::Response; +use topcoat::router::{Body, HeaderValue, StatusCode, raw_path_params, route}; + +use super::machine_auth::{DIRECTORY_READ, require}; +use super::{api_error, not_found}; +use crate::oidc::{Single, parse_pairs, single}; +use crate::state::AppState; + +/// The image types a photo may be served as. Anything else stored is not served. +pub const ALLOWED_TYPES: [&str; 4] = ["image/png", "image/jpeg", "image/webp", "image/gif"]; + +/// Caching when `?v=` names the current version: the URL is unique to this picture. +const IMMUTABLE_CACHE: &str = "private, max-age=31536000, immutable"; + +/// Caching otherwise: keep it, but ask again before use. +const REVALIDATE_CACHE: &str = "private, no-cache"; + +/// `GET /api/v1/people/{sub}/photo`. +#[route(GET "/api/v1/people/{sub}/photo")] +async fn photo(cx: &Cx) -> Result { + let app = app_context::(cx); + let machine = match require(app, cx, DIRECTORY_READ).await? { + Ok(machine) => machine, + Err(refusal) => return Ok(refusal), + }; + tracing::debug!(caller = %machine.caller, "photo: request"); + let Some(sub) = path_sub(cx) else { + return Ok(not_found()); + }; + if !is_ulid(&sub) { + return Ok(not_found()); + } + let Some(person) = app.store.user_by_id(&sub).await? else { + return Ok(not_found()); + }; + let Some(mime) = person.photo_mime.as_deref().and_then(allowed_type) else { + return Ok(not_found()); + }; + let etag = format!("\"p{}\"", person.picture_version); + let cache = if requested_version(cx) == Some(person.picture_version) { + IMMUTABLE_CACHE + } else { + REVALIDATE_CACHE + }; + if none_match(cx, &etag) { + return Ok(answer( + StatusCode::NOT_MODIFIED, + &etag, + mime, + cache, + Vec::new(), + )); + } + let dir = app.config.data_dir.clone(); + let read_sub = sub.clone(); + let stored = match tokio::task::spawn_blocking(move || read_photo(&dir, &read_sub)).await { + Ok(Ok(stored)) => stored, + Ok(Err(error)) => { + tracing::error!(error = %error, "photo: the stored picture could not be read"); + return Ok(api_error( + StatusCode::INTERNAL_SERVER_ERROR, + "internal", + "The photo could not be read.", + None, + )); + } + Err(error) => { + tracing::error!(error = %error, "photo: the read task failed"); + return Ok(api_error( + StatusCode::INTERNAL_SERVER_ERROR, + "internal", + "The photo could not be read.", + None, + )); + } + }; + match stored { + Some(bytes) => Ok(answer(StatusCode::OK, &etag, mime, cache, bytes)), + // The row names a photo whose file is gone: there is no picture to send. + None => Ok(not_found()), + } +} + +/// The `{sub}` of the matched route, or `None`. +fn path_sub(cx: &Cx) -> Option { + raw_path_params(cx) + .find(|(name, _)| *name == "sub") + .map(|(_, value)| value.as_str().to_owned()) +} + +/// The `v` query parameter as a version, when it is exactly one integer. +fn requested_version(cx: &Cx) -> Option { + let query = uri(cx).query()?; + let pairs = parse_pairs(query.as_bytes())?; + match single(&pairs, "v") { + Single::One(value) => value.parse().ok(), + _ => None, + } +} + +/// True when `If-None-Match` names `etag`. +fn none_match(cx: &Cx, etag: &str) -> bool { + headers(cx) + .get_all(IF_NONE_MATCH) + .iter() + .filter_map(|value| value.to_str().ok()) + .flat_map(|value| value.split(',')) + .any(|tag| tag.trim() == etag) +} + +/// The stored type, when it is on the allowlist. +fn allowed_type(stored: &str) -> Option<&'static str> { + ALLOWED_TYPES.into_iter().find(|allowed| *allowed == stored) +} + +/// A user id is a ULID: 26 characters of Crockford base32, the first at most `7`. Anything else (a path +/// fragment, an encoded slash, a dot segment) is refused before it reaches the disk. +pub fn is_ulid(sub: &str) -> bool { + sub.len() == 26 && ulid::Ulid::from_string(sub).is_ok() +} + +/// One photo answer with its headers. +fn answer( + status: StatusCode, + etag: &str, + mime: &str, + cache: &'static str, + body: Vec, +) -> Response { + let mut response = Response::new(Body::from(body)); + *response.status_mut() = status; + let headers = response.headers_mut(); + headers.insert( + CONTENT_TYPE, + HeaderValue::from_str(mime).unwrap_or(HeaderValue::from_static("application/octet-stream")), + ); + headers.insert(CACHE_CONTROL, HeaderValue::from_static(cache)); + headers.insert( + ETAG, + HeaderValue::from_str(etag).unwrap_or(HeaderValue::from_static("\"\"")), + ); + headers.insert(X_CONTENT_TYPE_OPTIONS, HeaderValue::from_static("nosniff")); + response +} diff --git a/crates/im-web/src/api/tests.rs b/crates/im-web/src/api/tests.rs new file mode 100644 index 0000000..ab62a9c --- /dev/null +++ b/crates/im-web/src/api/tests.rs @@ -0,0 +1,172 @@ +//! The machine API through the router: who may call it, the stream's resume rule, and the photo path. + +use http::header::{AUTHORIZATION, WWW_AUTHENTICATE}; +use im_core::model::Client; +use im_core::store::clients::NewClient; +use im_core::store::new_id; +use im_core::time::unix_now; +use im_core::token::{generate_token, hash_token}; +use serde_json::{Value, json}; +use topcoat::router::{Body, StatusCode, to_bytes}; + +use crate::boot::{router, test_state}; +use crate::oidc::signing; +use crate::state::AppState; + +/// A family client (`in`) that may ask for the directory scope, and a secret it is not given here. +struct Fixture { + _dir: tempfile::TempDir, + state: AppState, + client: Client, +} + +async fn fixture() -> Fixture { + let (dir, state) = test_state().await; + signing::maintain(&state.store, &state.key) + .await + .expect("signing key"); + let client = state + .store + .create_client(&NewClient { + name: "Files", + secret_hash: &hash_token(&generate_token()), + redirect_uris: &[], + post_logout_redirect_uris: &[], + backchannel_logout_uri: None, + allowed_scopes: "directory.read files.service", + service_key: Some("in"), + }) + .await + .expect("client"); + Fixture { + _dir: dir, + state, + client, + } +} + +/// The claims of a client-credentials token that `im` would issue to `client` for `aud` and `scope`. +fn machine_claims(state: &AppState, client: &Client, aud: &str, scope: &str) -> Value { + let now = unix_now(); + json!({ + "iss": state.config.base_url, + "sub": format!("client:{}", client.id), + "azp": client.id, + "aud": aud, + "scope": scope, + "svc": "in", + "iat": now, + "exp": now + 600, + "jti": generate_token(), + }) +} + +/// Signs `claims` with the instance's own key. +async fn mint(state: &AppState, claims: &Value) -> String { + signing::sign(&state.store, &state.key, claims) + .await + .expect("token") +} + +/// Sends a GET with a bearer token through the whole router: status, headers and body text. +async fn get(state: &AppState, path: &str, token: &str) -> (StatusCode, http::HeaderMap, String) { + let request = http::Request::get(path) + .header(AUTHORIZATION, format!("Bearer {token}")) + .body(Body::empty()) + .expect("request"); + let response = router(state.clone()).handle(request).await; + let status = response.status(); + let headers = response.headers().clone(); + let bytes = to_bytes(response.into_body(), 1024 * 1024) + .await + .expect("body"); + ( + status, + headers, + String::from_utf8_lossy(&bytes).into_owned(), + ) +} + +#[tokio::test] +async fn a_user_access_token_is_refused_on_the_directory() { + let f = fixture().await; + // A person's access token: their id as `sub`, a session as `sid`, and no `svc`. + let claims = json!({ + "iss": f.state.config.base_url, + "sub": new_id(), + "aud": "im", + "azp": f.client.id, + "scope": "openid profile", + "sid": new_id(), + "iat": unix_now(), + "exp": unix_now() + 600, + }); + let token = mint(&f.state, &claims).await; + let (status, headers, _) = get(&f.state, "/api/v1/directory", &token).await; + assert_eq!(status, StatusCode::UNAUTHORIZED); + assert_eq!(headers[WWW_AUTHENTICATE], "Bearer error=\"invalid_token\""); +} + +#[tokio::test] +async fn a_token_for_another_audience_is_refused() { + let f = fixture().await; + let claims = machine_claims(&f.state, &f.client, "in", "directory.read"); + let token = mint(&f.state, &claims).await; + let (status, _, _) = get(&f.state, "/api/v1/directory", &token).await; + assert_eq!(status, StatusCode::UNAUTHORIZED); +} + +#[tokio::test] +async fn a_token_without_the_directory_scope_gets_403() { + let f = fixture().await; + let claims = machine_claims(&f.state, &f.client, "im", "files.service"); + let token = mint(&f.state, &claims).await; + let (status, headers, body) = get(&f.state, "/api/v1/directory", &token).await; + assert_eq!(status, StatusCode::FORBIDDEN); + assert_eq!( + headers[WWW_AUTHENTICATE], + "Bearer error=\"insufficient_scope\"" + ); + assert!(body.contains("insufficient_scope"), "{body}"); +} + +#[tokio::test] +async fn a_cursor_from_the_future_gets_a_resync_and_the_stream_ends() { + let f = fixture().await; + let claims = machine_claims(&f.state, &f.client, "im", "directory.read"); + let token = mint(&f.state, &claims).await; + let (status, _, body) = get(&f.state, "/api/v1/directory/stream?cursor=999", &token).await; + assert_eq!(status, StatusCode::OK); + assert!(body.contains("event: resync"), "{body}"); + assert!(!body.contains("event: member"), "{body}"); +} + +#[tokio::test] +async fn a_photo_path_with_an_encoded_slash_is_not_found() { + let f = fixture().await; + let claims = machine_claims(&f.state, &f.client, "im", "directory.read"); + let token = mint(&f.state, &claims).await; + let (status, _, _) = get( + &f.state, + "/api/v1/people/..%2f..%2fetc%2fpasswd/photo", + &token, + ) + .await; + assert_eq!(status, StatusCode::NOT_FOUND); +} + +#[tokio::test] +async fn a_token_of_a_disabled_client_is_refused() { + let f = fixture().await; + let claims = machine_claims(&f.state, &f.client, "im", "directory.read"); + let token = mint(&f.state, &claims).await; + assert!( + f.state + .store + .disable_client(&f.client.id) + .await + .expect("disable") + ); + let (status, _, _) = get(&f.state, "/api/v1/directory", &token).await; + assert_eq!(status, StatusCode::UNAUTHORIZED); +} diff --git a/crates/im-web/src/boot.rs b/crates/im-web/src/boot.rs index fadcc46..7f41288 100644 --- a/crates/im-web/src/boot.rs +++ b/crates/im-web/src/boot.rs @@ -20,6 +20,7 @@ use tokio::sync::watch; use topcoat::cookie::RouterBuilderCookieExt; use topcoat::router::{BodyLimit, Router, RouterBuilderDiscoverExt, RouterService}; +use crate::api::directory::StreamSlots; use crate::backchannel; use crate::live::LiveHub; use crate::oidc::signing; @@ -27,6 +28,7 @@ use crate::pages::not_found::NotFoundLayer; use crate::pages::profile::PHOTO_ROUTE; use crate::security::{self, SecurityHeaders}; use crate::state::AppState; +use crate::sweeper; use crate::throttle::Throttle; /// Name of the instance key file inside the data directory. @@ -76,6 +78,10 @@ pub async fn serve(config_path: &Path) -> im_core::Result<()> { // One stop flag. The signal task sets it; the server watches it and then drains. let (stop_tx, stop_rx) = watch::channel(false); + let state = AppState { + stop: stop_rx.clone(), + ..state + }; tokio::spawn(async move { shutdown_signal().await; tracing::info!("shutdown signal received"); @@ -88,6 +94,7 @@ pub async fn serve(config_path: &Path) -> im_core::Result<()> { state.config.base_url.clone(), stop_rx.clone(), ); + let sweeper_task = sweeper::spawn(state.store.clone(), stop_rx.clone()); topcoat::serve_until( listener, @@ -97,6 +104,7 @@ pub async fn serve(config_path: &Path) -> im_core::Result<()> { .await?; let _ = signing_worker.await; let _ = backchannel_worker.await; + let _ = sweeper_task.await; tracing::info!("im stopped"); Ok(()) } @@ -119,12 +127,19 @@ pub(crate) async fn open_state(config: Config) -> im_core::Result { let key = secret::load_or_create_key(&data_dir.join(KEY_FILE))?; let store = Store::open(&config.database).await?; signing::maintain(&store, &key).await?; + // im is in its own switcher list. The row follows the configured origin at every boot. + store + .upsert_home_service("Account", &config.base_url) + .await?; Ok(AppState { config: Arc::new(config), store, key: Arc::new(key), live: Arc::new(LiveHub::default()), throttle: Arc::new(Throttle::default()), + stream_slots: Arc::new(StreamSlots::default()), + // Replaced by the stop flag of `serve` before any listener starts. The CLI never serves. + stop: watch::channel(false).1, }) } @@ -205,6 +220,8 @@ mod tests { key: Arc::new(key), live: Arc::new(LiveHub::default()), throttle: Arc::new(Throttle::default()), + stream_slots: Arc::new(StreamSlots::default()), + stop: watch::channel(false).1, }; (dir, state) } diff --git a/crates/im-web/src/main.rs b/crates/im-web/src/main.rs index 3c20f6f..bcf3b97 100644 --- a/crates/im-web/src/main.rs +++ b/crates/im-web/src/main.rs @@ -4,6 +4,7 @@ //! OpenID Connect clients (`cli.rs`). `im admin ...` is the operator command line, which is not built yet. The configuration file is the `--config` path, //! then `IM_CONFIG`, then `config/im.toml`. Exit status 0 is success, 1 a failure, 2 a usage error. +mod api; mod assets; mod audit; mod auth; @@ -18,6 +19,7 @@ mod oidc; mod pages; mod security; mod state; +mod sweeper; mod throttle; mod views; diff --git a/crates/im-web/src/oidc/userinfo.rs b/crates/im-web/src/oidc/userinfo.rs index dc7b818..ec55a41 100644 --- a/crates/im-web/src/oidc/userinfo.rs +++ b/crates/im-web/src/oidc/userinfo.rs @@ -85,7 +85,7 @@ async fn userinfo(cx: &Cx) -> Result { } /// The token of a `Bearer` authorization header, or `None`. -fn bearer(value: Option<&HeaderValue>) -> Option<&str> { +pub(crate) fn bearer(value: Option<&HeaderValue>) -> Option<&str> { let (scheme, token) = value?.to_str().ok()?.split_once(' ')?; (scheme.eq_ignore_ascii_case("bearer") && !token.is_empty()).then_some(token) } diff --git a/crates/im-web/src/state.rs b/crates/im-web/src/state.rs index 7df15e9..00a51ac 100644 --- a/crates/im-web/src/state.rs +++ b/crates/im-web/src/state.rs @@ -4,7 +4,9 @@ use std::sync::Arc; use im_core::config::Config; use im_core::store::Store; +use tokio::sync::watch; +use crate::api::directory::StreamSlots; use crate::live::LiveHub; use crate::throttle::Throttle; @@ -21,4 +23,8 @@ pub struct AppState { pub live: Arc, /// Failed sign-in and second-factor counters. pub throttle: Arc, + /// The open directory streams of each machine client. + pub stream_slots: Arc, + /// Set when the process is stopping. Long-lived streams end when it is, so the server can drain. + pub stop: watch::Receiver, } diff --git a/crates/im-web/src/sweeper.rs b/crates/im-web/src/sweeper.rs new file mode 100644 index 0000000..e3729be --- /dev/null +++ b/crates/im-web/src/sweeper.rs @@ -0,0 +1,66 @@ +//! The sweeper (architecture section 8): once at boot and then hourly, it removes what has expired. +//! +//! - browser sessions past their expiry, with their back-channel logout jobs queued first; +//! - authorization codes that expired more than a day ago (a day is kept so that a reused code is still +//! recognised as reuse, which revokes the tokens it issued); +//! - refresh tokens past their expiry; +//! - directory change rows older than 30 days (a cursor older than the oldest row gets `resync`). +//! +//! Each step runs on its own: one failing step is logged and does not stop the others. + +use std::time::Duration; + +use im_core::store::Store; +use im_core::time::{now_stamp, stamp_before, stamp_minus}; +use tokio::sync::watch; + +/// The time between two sweeps. +const EVERY: Duration = Duration::from_secs(60 * 60); + +/// How long a directory change row is kept (contracts 3.2 and architecture section 3). +const DIRECTORY_KEEP: Duration = Duration::from_secs(30 * 24 * 60 * 60); + +/// How long an expired authorization code is kept, so a reuse is still seen as reuse. +const CODE_KEEP: Duration = Duration::from_secs(24 * 60 * 60); + +/// Starts the sweeper. It runs until `stop` is set. +pub fn spawn(store: Store, mut stop: watch::Receiver) -> tokio::task::JoinHandle<()> { + tokio::spawn(async move { + loop { + sweep_once(&store).await; + tokio::select! { + () = tokio::time::sleep(EVERY) => {} + _ = stop.wait_for(|stopped| *stopped) => return, + } + } + }) +} + +/// One pass over every table. Failures are logged per step. +pub async fn sweep_once(store: &Store) { + let now = now_stamp(); + match store.sweep_expired_sessions().await { + Ok(0) => {} + Ok(count) => tracing::info!(count, "sweeper: expired sessions removed"), + Err(error) => tracing::error!(error = %error, "sweeper: sessions"), + } + let codes_before = stamp_minus(&now, CODE_KEEP).unwrap_or_else(|| now.clone()); + match store.sweep_auth_codes(&codes_before).await { + Ok(0) => {} + Ok(count) => tracing::info!(count, "sweeper: expired authorization codes removed"), + Err(error) => tracing::error!(error = %error, "sweeper: authorization codes"), + } + match store.sweep_refresh_tokens(&now).await { + Ok(0) => {} + Ok(count) => tracing::info!(count, "sweeper: expired refresh tokens removed"), + Err(error) => tracing::error!(error = %error, "sweeper: refresh tokens"), + } + match store + .prune_directory_changes(&stamp_before(DIRECTORY_KEEP)) + .await + { + Ok(0) => {} + Ok(count) => tracing::info!(count, "sweeper: old directory changes removed"), + Err(error) => tracing::error!(error = %error, "sweeper: directory changes"), + } +}