Machine APIs: directory, directory stream with cursors, photo, family
Browse files at this commit1274ea055137815ece054d10dad8f1edd272a926Parent: d2aab2b- feat
- machine APIs: directory, directory stream with cursors, photo, family
- sweeper spawned at boot
19 changed files +1286 -63
- Cargo.lock +1 -0
- crates/im-core/src/model.rs +15 -0
- crates/im-core/src/store/directory.rs +119 -6
- crates/im-core/src/store/mod.rs +5 -1
- crates/im-core/src/store/oidc.rs +23 -0
- crates/im-core/src/store/services.rs +43 -0
- crates/im-core/src/store/users.rs +97 -55
- crates/im-web/Cargo.toml +1 -0
- crates/im-web/src/api/directory.rs +356 -0
- crates/im-web/src/api/family.rs +39 -0
- crates/im-web/src/api/machine_auth.rs +113 -0
- crates/im-web/src/api/mod.rs +53 -0
- crates/im-web/src/api/photo.rs +157 -0
- crates/im-web/src/api/tests.rs +172 -0
- crates/im-web/src/boot.rs +17 -0
- crates/im-web/src/main.rs +2 -0
- crates/im-web/src/oidc/userinfo.rs +1 -1
- crates/im-web/src/state.rs +6 -0
- crates/im-web/src/sweeper.rs +66 -0
Cargo.lockmodified+1 -0
| @@ -1872,6 +1872,7 @@ dependencies = [ | |||
| 1872 | "topcoat", | 1872 | "topcoat", |
| 1873 | "tracing", | 1873 | "tracing", |
| 1874 | "tracing-subscriber", | 1874 | "tracing-subscriber", |
| 1875 | + "ulid", | ||
| 1875 | ] | 1876 | ] |
| 1876 | 1877 | ||
| 1877 | [[package]] | 1878 | [[package]] |
crates/im-core/src/model.rsmodified+15 -0
| @@ -299,3 +299,18 @@ pub struct KeyRecord { | |||
| 299 | /// When the key stops signing. It stays published for a while after this time. | 299 | /// When the key stops signing. It stays published for a while after this time. |
| 300 | pub retires_at: Option<String>, | 300 | pub retires_at: Option<String>, |
| 301 | } | 301 | } |
| 302 | + | ||
| 303 | +/// One row of the service switcher (contracts.md 4). | ||
| 304 | +#[derive(Debug, Clone, PartialEq, Eq)] | ||
| 305 | +pub struct Service { | ||
| 306 | + /// Family key, such as `in`. | ||
| 307 | + pub key: String, | ||
| 308 | + /// Display name. | ||
| 309 | + pub name: String, | ||
| 310 | + /// Public origin. | ||
| 311 | + pub url: String, | ||
| 312 | + /// The last health probe's answer, `None` before the first probe. | ||
| 313 | + pub healthy: Option<bool>, | ||
| 314 | + /// When the last probe ran. | ||
| 315 | + pub checked_at: Option<String>, | ||
| 316 | +} | ||
crates/im-core/src/store/directory.rsmodified+119 -6
| @@ -1,14 +1,18 @@ | |||
| 1 | //! The change feed of the people directory: one row per change a machine client may need to see. | 1 | //! The change feed of the people directory: one row per change a machine client may need to see. |
| 2 | //! | 2 | //! |
| 3 | -//! The rows are written in the same transaction as the change they describe, so a change is | 3 | +//! The rows are written in the same transaction as the change they describe, so a change is never |
| 4 | -//! never visible without its row, and a row never describes a change that did not happen. Rows are | 4 | +//! visible without its row, and a row never describes a change that did not happen. The directory |
| 5 | -//! read by the directory stream (contracts.md 3.2), which is built in a later step; until then they | 5 | +//! stream (contracts.md 3.2) reads them with [`Store::directory_changes_after`]; the sweeper prunes |
| 6 | -//! only accumulate. The sweeper prunes rows older than 30 days. | 6 | +//! rows older than 30 days. Every committed change also wakes the receivers of |
| 7 | +//! [`Store::directory_watch`], so a stream waits instead of polling. | ||
| 7 | 8 | ||
| 9 | +use tokio::sync::watch; | ||
| 8 | use turso::Connection; | 10 | use turso::Connection; |
| 9 | 11 | ||
| 10 | -use crate::error::Result; | 12 | +use crate::error::{Error, Result}; |
| 11 | -use crate::store::db_err; | 13 | +use crate::model::User; |
| 14 | +use crate::store::users::{USER_COLS, map_user}; | ||
| 15 | +use crate::store::{Store, col_int, col_opt_int, col_text, db_err, fetch_all, fetch_opt}; | ||
| 12 | use crate::time::now_stamp; | 16 | use crate::time::now_stamp; |
| 13 | 17 | ||
| 14 | /// What a directory row says happened to a person. | 18 | /// What a directory row says happened to a person. |
| @@ -28,6 +32,26 @@ impl ChangeKind { | |||
| 28 | ChangeKind::Deleted => "deleted", | 32 | ChangeKind::Deleted => "deleted", |
| 29 | } | 33 | } |
| 30 | } | 34 | } |
| 35 | + | ||
| 36 | + /// The kind of a stored text, or `None` for anything the schema does not allow. | ||
| 37 | + pub fn parse(text: &str) -> Option<ChangeKind> { | ||
| 38 | + match text { | ||
| 39 | + "member" => Some(ChangeKind::Member), | ||
| 40 | + "deleted" => Some(ChangeKind::Deleted), | ||
| 41 | + _ => None, | ||
| 42 | + } | ||
| 43 | + } | ||
| 44 | +} | ||
| 45 | + | ||
| 46 | +/// One row of the change feed. | ||
| 47 | +#[derive(Debug, Clone, PartialEq, Eq)] | ||
| 48 | +pub struct Change { | ||
| 49 | + /// The sequence number: the cursor of the stream. | ||
| 50 | + pub seq: i64, | ||
| 51 | + /// The person the change is about. | ||
| 52 | + pub sub: String, | ||
| 53 | + /// What happened to the person. | ||
| 54 | + pub kind: ChangeKind, | ||
| 31 | } | 55 | } |
| 32 | 56 | ||
| 33 | /// Appends one change row. Runs inside the caller's transaction, so it commits with the change. | 57 | /// 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 | |||
| 40 | .map_err(db_err)?; | 64 | .map_err(db_err)?; |
| 41 | Ok(()) | 65 | Ok(()) |
| 42 | } | 66 | } |
| 67 | + | ||
| 68 | +impl Store { | ||
| 69 | + /// A receiver that changes every time a directory change commits. A stream subscribes before it | ||
| 70 | + /// reads the feed, so a change made in between still wakes it. | ||
| 71 | + pub fn directory_watch(&self) -> watch::Receiver<u64> { | ||
| 72 | + self.inner.directory.subscribe() | ||
| 73 | + } | ||
| 74 | + | ||
| 75 | + /// Wakes every directory receiver. Called after a transaction that wrote directory rows commits. | ||
| 76 | + pub(crate) fn announce_directory(&self) { | ||
| 77 | + self.inner | ||
| 78 | + .directory | ||
| 79 | + .send_modify(|generation| *generation = generation.wrapping_add(1)); | ||
| 80 | + } | ||
| 81 | + | ||
| 82 | + /// The newest sequence number, or 0 when the feed is empty. | ||
| 83 | + pub async fn directory_head(&self) -> Result<i64> { | ||
| 84 | + let conn = self.read_conn().await; | ||
| 85 | + head_of(&conn).await | ||
| 86 | + } | ||
| 87 | + | ||
| 88 | + /// The oldest sequence number still kept, or `None` when the feed is empty. | ||
| 89 | + pub async fn directory_oldest(&self) -> Result<Option<i64>> { | ||
| 90 | + let conn = self.read_conn().await; | ||
| 91 | + fetch_opt(&conn, "SELECT MIN(seq) FROM directory_changes", (), |row| { | ||
| 92 | + col_opt_int(row, 0) | ||
| 93 | + }) | ||
| 94 | + .await | ||
| 95 | + .map(Option::flatten) | ||
| 96 | + } | ||
| 97 | + | ||
| 98 | + /// The rows after `after`, oldest first, at most `limit` of them. | ||
| 99 | + pub async fn directory_changes_after(&self, after: i64, limit: i64) -> Result<Vec<Change>> { | ||
| 100 | + let conn = self.read_conn().await; | ||
| 101 | + fetch_all( | ||
| 102 | + &conn, | ||
| 103 | + "SELECT seq, sub, kind FROM directory_changes WHERE seq > ?1 ORDER BY seq LIMIT ?2", | ||
| 104 | + (after, limit), | ||
| 105 | + |row| { | ||
| 106 | + let kind = col_text(row, 2)?; | ||
| 107 | + Ok(Change { | ||
| 108 | + seq: col_int(row, 0)?, | ||
| 109 | + sub: col_text(row, 1)?, | ||
| 110 | + kind: ChangeKind::parse(&kind) | ||
| 111 | + .ok_or_else(|| Error::Database("unknown directory change kind".into()))?, | ||
| 112 | + }) | ||
| 113 | + }, | ||
| 114 | + ) | ||
| 115 | + .await | ||
| 116 | + } | ||
| 117 | + | ||
| 118 | + /// Every account, with the head of the feed read in the same step. The writer is held for both | ||
| 119 | + /// reads, so no change can land between them: the cursor is exactly the state of the members. | ||
| 120 | + pub async fn directory_snapshot(&self) -> Result<(i64, Vec<User>)> { | ||
| 121 | + let conn = self.inner.conn.lock().await; | ||
| 122 | + let head = head_of(&conn).await?; | ||
| 123 | + let users = fetch_all( | ||
| 124 | + &conn, | ||
| 125 | + &format!("SELECT {USER_COLS} FROM users ORDER BY created_at, id"), | ||
| 126 | + (), | ||
| 127 | + map_user, | ||
| 128 | + ) | ||
| 129 | + .await?; | ||
| 130 | + Ok((head, users)) | ||
| 131 | + } | ||
| 132 | + | ||
| 133 | + /// Deletes the rows written before `cutoff`. Returns how many were removed. | ||
| 134 | + pub async fn prune_directory_changes(&self, cutoff: &str) -> Result<u64> { | ||
| 135 | + let conn = self.inner.conn.lock().await; | ||
| 136 | + conn.execute( | ||
| 137 | + "DELETE FROM directory_changes WHERE at < ?1", | ||
| 138 | + (cutoff.to_string(),), | ||
| 139 | + ) | ||
| 140 | + .await | ||
| 141 | + .map_err(db_err) | ||
| 142 | + } | ||
| 143 | +} | ||
| 144 | + | ||
| 145 | +/// The newest sequence number on `conn`, or 0. | ||
| 146 | +async fn head_of(conn: &Connection) -> Result<i64> { | ||
| 147 | + fetch_opt( | ||
| 148 | + conn, | ||
| 149 | + "SELECT COALESCE(MAX(seq), 0) FROM directory_changes", | ||
| 150 | + (), | ||
| 151 | + |row| col_int(row, 0), | ||
| 152 | + ) | ||
| 153 | + .await | ||
| 154 | + .map(|head| head.unwrap_or(0)) | ||
| 155 | +} | ||
crates/im-core/src/store/mod.rsmodified+5 -1
| @@ -13,6 +13,7 @@ pub mod directory; | |||
| 13 | pub mod keys; | 13 | pub mod keys; |
| 14 | pub mod migrate; | 14 | pub mod migrate; |
| 15 | pub mod oidc; | 15 | pub mod oidc; |
| 16 | +pub mod services; | ||
| 16 | pub mod sessions; | 17 | pub mod sessions; |
| 17 | pub mod snapshot; | 18 | pub mod snapshot; |
| 18 | pub mod users; | 19 | pub mod users; |
| @@ -22,7 +23,7 @@ use std::sync::Arc; | |||
| 22 | use std::sync::atomic::{AtomicUsize, Ordering}; | 23 | use std::sync::atomic::{AtomicUsize, Ordering}; |
| 23 | use std::time::Duration; | 24 | use std::time::Duration; |
| 24 | 25 | ||
| 25 | -use tokio::sync::{Mutex, MutexGuard}; | 26 | +use tokio::sync::{Mutex, MutexGuard, watch}; |
| 26 | use turso::transaction::Transaction; | 27 | use turso::transaction::Transaction; |
| 27 | use turso::{Builder, Connection, Database, IntoParams, Row, Value}; | 28 | use turso::{Builder, Connection, Database, IntoParams, Row, Value}; |
| 28 | 29 | ||
| @@ -54,6 +55,8 @@ struct Inner { | |||
| 54 | readers: Vec<Mutex<Connection>>, | 55 | readers: Vec<Mutex<Connection>>, |
| 55 | /// Round-robin start index for `read_conn`. | 56 | /// Round-robin start index for `read_conn`. |
| 56 | next_reader: AtomicUsize, | 57 | next_reader: AtomicUsize, |
| 58 | + /// Counts the committed changes of the people directory. A stream waits on a receiver of it. | ||
| 59 | + directory: watch::Sender<u64>, | ||
| 57 | } | 60 | } |
| 58 | 61 | ||
| 59 | impl Store { | 62 | impl Store { |
| @@ -81,6 +84,7 @@ impl Store { | |||
| 81 | conn: Mutex::new(conn), | 84 | conn: Mutex::new(conn), |
| 82 | readers, | 85 | readers, |
| 83 | next_reader: AtomicUsize::new(0), | 86 | next_reader: AtomicUsize::new(0), |
| 87 | + directory: watch::channel(0).0, | ||
| 84 | }), | 88 | }), |
| 85 | }) | 89 | }) |
| 86 | } | 90 | } |
crates/im-core/src/store/oidc.rsmodified+23 -0
| @@ -124,6 +124,29 @@ async fn insert_refresh(conn: &Connection, new: &NewRefreshToken<'_>, now: &str) | |||
| 124 | 124 | ||
| 125 | impl Store { | 125 | impl Store { |
| 126 | /// Stores a new authorization code. | 126 | /// Stores a new authorization code. |
| 127 | + /// Deletes the authorization codes that expired before `cutoff`. Run by the sweeper, which keeps | ||
| 128 | + /// codes for a day past their expiry so that a reused code is still recognised as reuse. | ||
| 129 | + pub async fn sweep_auth_codes(&self, cutoff: &str) -> Result<u64> { | ||
| 130 | + let conn = self.inner.conn.lock().await; | ||
| 131 | + conn.execute( | ||
| 132 | + "DELETE FROM auth_codes WHERE expires_at < ?1", | ||
| 133 | + (cutoff.to_string(),), | ||
| 134 | + ) | ||
| 135 | + .await | ||
| 136 | + .map_err(db_err) | ||
| 137 | + } | ||
| 138 | + | ||
| 139 | + /// Deletes the refresh tokens that expired before `now`. Run by the sweeper. | ||
| 140 | + pub async fn sweep_refresh_tokens(&self, now: &str) -> Result<u64> { | ||
| 141 | + let conn = self.inner.conn.lock().await; | ||
| 142 | + conn.execute( | ||
| 143 | + "DELETE FROM refresh_tokens WHERE expires_at < ?1", | ||
| 144 | + (now.to_string(),), | ||
| 145 | + ) | ||
| 146 | + .await | ||
| 147 | + .map_err(db_err) | ||
| 148 | + } | ||
| 149 | + | ||
| 127 | pub async fn insert_auth_code(&self, new: &NewAuthCode<'_>) -> Result<()> { | 150 | pub async fn insert_auth_code(&self, new: &NewAuthCode<'_>) -> Result<()> { |
| 128 | let conn = self.inner.conn.lock().await; | 151 | let conn = self.inner.conn.lock().await; |
| 129 | conn.execute( | 152 | conn.execute( |
crates/im-core/src/store/services.rsadded+43 -0
| @@ -0,0 +1,43 @@ | |||
| 1 | +//! The service switcher list (contracts.md 4): one row per family app, plus im's own row. | ||
| 2 | +//! | ||
| 3 | +//! im's row is kept at boot from `base_url`, so it cannot drift from the configuration. The other rows | ||
| 4 | +//! are written by the admin pages, which are not built yet. | ||
| 5 | + | ||
| 6 | +use crate::error::Result; | ||
| 7 | +use crate::model::Service; | ||
| 8 | +use crate::store::{Store, col_opt_int, col_opt_text, col_text, db_err, fetch_all}; | ||
| 9 | + | ||
| 10 | +impl Store { | ||
| 11 | + /// Every service, in the admin's order. | ||
| 12 | + pub async fn list_services(&self) -> Result<Vec<Service>> { | ||
| 13 | + let conn = self.read_conn().await; | ||
| 14 | + fetch_all( | ||
| 15 | + &conn, | ||
| 16 | + "SELECT key, name, url, healthy, checked_at FROM services ORDER BY position, key", | ||
| 17 | + (), | ||
| 18 | + |row| { | ||
| 19 | + Ok(Service { | ||
| 20 | + key: col_text(row, 0)?, | ||
| 21 | + name: col_text(row, 1)?, | ||
| 22 | + url: col_text(row, 2)?, | ||
| 23 | + healthy: col_opt_int(row, 3)?.map(|value| value != 0), | ||
| 24 | + checked_at: col_opt_text(row, 4)?, | ||
| 25 | + }) | ||
| 26 | + }, | ||
| 27 | + ) | ||
| 28 | + .await | ||
| 29 | + } | ||
| 30 | + | ||
| 31 | + /// Creates or updates im's own row (key `im`). Its position and client stay as they are. | ||
| 32 | + pub async fn upsert_home_service(&self, name: &str, url: &str) -> Result<()> { | ||
| 33 | + let conn = self.inner.conn.lock().await; | ||
| 34 | + conn.execute( | ||
| 35 | + "INSERT INTO services (key, name, url, position, client_id) VALUES ('im', ?1, ?2, 0, NULL) \ | ||
| 36 | + ON CONFLICT(key) DO UPDATE SET name = excluded.name, url = excluded.url", | ||
| 37 | + (name.to_string(), url.to_string()), | ||
| 38 | + ) | ||
| 39 | + .await | ||
| 40 | + .map_err(db_err)?; | ||
| 41 | + Ok(()) | ||
| 42 | + } | ||
| 43 | +} | ||
crates/im-core/src/store/users.rsmodified+97 -55
| @@ -24,12 +24,12 @@ use crate::store::{ | |||
| 24 | use crate::time::now_stamp; | 24 | use crate::time::now_stamp; |
| 25 | 25 | ||
| 26 | /// The columns of a user row, in the order [`map_user`] reads them. | 26 | /// The columns of a user row, in the order [`map_user`] reads them. |
| 27 | -const USER_COLS: &str = "id, email, name, password_hash, is_admin, disabled_at, \ | 27 | +pub(crate) const USER_COLS: &str = "id, email, name, password_hash, is_admin, disabled_at, \ |
| 28 | totp_secret_sealed, totp_enabled_at, totp_last_step, locale, zoneinfo, theme, \ | 28 | totp_secret_sealed, totp_enabled_at, totp_last_step, locale, zoneinfo, theme, \ |
| 29 | photo_mime, picture_version, created_at, updated_at, locale_auto"; | 29 | photo_mime, picture_version, created_at, updated_at, locale_auto"; |
| 30 | 30 | ||
| 31 | /// Maps a row selected with [`USER_COLS`]. | 31 | /// Maps a row selected with [`USER_COLS`]. |
| 32 | -fn map_user(row: &Row) -> Result<User> { | 32 | +pub(crate) fn map_user(row: &Row) -> Result<User> { |
| 33 | Ok(User { | 33 | Ok(User { |
| 34 | id: col_text(row, 0)?, | 34 | id: col_text(row, 0)?, |
| 35 | email: col_text(row, 1)?, | 35 | email: col_text(row, 1)?, |
| @@ -100,26 +100,36 @@ impl Store { | |||
| 100 | let id = new_id(); | 100 | let id = new_id(); |
| 101 | let now = now_stamp(); | 101 | let now = now_stamp(); |
| 102 | let conn = self.inner.conn.lock().await; | 102 | let conn = self.inner.conn.lock().await; |
| 103 | - let changed = conn | 103 | + let tx = conn.unchecked_transaction().await.map_err(db_err)?; |
| 104 | - .execute( | 104 | + let outcome: Result<bool> = async { |
| 105 | - "INSERT INTO users (id, email, email_folded, name, password_hash, is_admin, \ | 105 | + let changed = tx |
| 106 | - created_at, updated_at) \ | 106 | + .execute( |
| 107 | - SELECT ?1, ?2, ?2, ?3, ?4, 1, ?5, ?5 \ | 107 | + "INSERT INTO users (id, email, email_folded, name, password_hash, is_admin, \ |
| 108 | - WHERE NOT EXISTS (SELECT 1 FROM users)", | 108 | + created_at, updated_at) \ |
| 109 | - ( | 109 | + SELECT ?1, ?2, ?2, ?3, ?4, 1, ?5, ?5 \ |
| 110 | - id.clone(), | 110 | + WHERE NOT EXISTS (SELECT 1 FROM users)", |
| 111 | - email.to_string(), | 111 | + ( |
| 112 | - name.to_string(), | 112 | + id.clone(), |
| 113 | - password_hash.to_string(), | 113 | + email.to_string(), |
| 114 | - now, | 114 | + name.to_string(), |
| 115 | - ), | 115 | + password_hash.to_string(), |
| 116 | - ) | 116 | + now, |
| 117 | - .await | 117 | + ), |
| 118 | - .map_err(insert_error)?; | 118 | + ) |
| 119 | + .await | ||
| 120 | + .map_err(insert_error)?; | ||
| 121 | + if changed == 1 { | ||
| 122 | + record_change(&tx, &id, ChangeKind::Member).await?; | ||
| 123 | + } | ||
| 124 | + Ok(changed == 1) | ||
| 125 | + } | ||
| 126 | + .await; | ||
| 127 | + let created = finish(tx, outcome).await?; | ||
| 119 | drop(conn); | 128 | drop(conn); |
| 120 | - if changed == 0 { | 129 | + if !created { |
| 121 | return Err(Error::Conflict("setup is already complete".into())); | 130 | return Err(Error::Conflict("setup is already complete".into())); |
| 122 | } | 131 | } |
| 132 | + self.announce_directory(); | ||
| 123 | self.user_by_id(&id).await?.ok_or(Error::NotFound) | 133 | self.user_by_id(&id).await?.ok_or(Error::NotFound) |
| 124 | } | 134 | } |
| 125 | 135 | ||
| @@ -135,21 +145,28 @@ impl Store { | |||
| 135 | let id = new_id(); | 145 | let id = new_id(); |
| 136 | let now = now_stamp(); | 146 | let now = now_stamp(); |
| 137 | let conn = self.inner.conn.lock().await; | 147 | let conn = self.inner.conn.lock().await; |
| 138 | - conn.execute( | 148 | + let tx = conn.unchecked_transaction().await.map_err(db_err)?; |
| 139 | - "INSERT INTO users (id, email, email_folded, name, password_hash, is_admin, \ | 149 | + let outcome: Result<()> = async { |
| 140 | - created_at, updated_at) VALUES (?1, ?2, ?2, ?3, ?4, ?5, ?6, ?6)", | 150 | + tx.execute( |
| 141 | - ( | 151 | + "INSERT INTO users (id, email, email_folded, name, password_hash, is_admin, \ |
| 142 | - id.clone(), | 152 | + created_at, updated_at) VALUES (?1, ?2, ?2, ?3, ?4, ?5, ?6, ?6)", |
| 143 | - email.to_string(), | 153 | + ( |
| 144 | - name.to_string(), | 154 | + id.clone(), |
| 145 | - password_hash.to_string(), | 155 | + email.to_string(), |
| 146 | - i64::from(is_admin), | 156 | + name.to_string(), |
| 147 | - now, | 157 | + password_hash.to_string(), |
| 148 | - ), | 158 | + i64::from(is_admin), |
| 149 | - ) | 159 | + now, |
| 150 | - .await | 160 | + ), |
| 151 | - .map_err(insert_error)?; | 161 | + ) |
| 162 | + .await | ||
| 163 | + .map_err(insert_error)?; | ||
| 164 | + record_change(&tx, &id, ChangeKind::Member).await | ||
| 165 | + } | ||
| 166 | + .await; | ||
| 167 | + finish(tx, outcome).await?; | ||
| 152 | drop(conn); | 168 | drop(conn); |
| 169 | + self.announce_directory(); | ||
| 153 | self.user_by_id(&id).await?.ok_or(Error::NotFound) | 170 | self.user_by_id(&id).await?.ok_or(Error::NotFound) |
| 154 | } | 171 | } |
| 155 | 172 | ||
| @@ -196,7 +213,11 @@ impl Store { | |||
| 196 | record_change(&tx, id, ChangeKind::Member).await | 213 | record_change(&tx, id, ChangeKind::Member).await |
| 197 | } | 214 | } |
| 198 | .await; | 215 | .await; |
| 199 | - finish(tx, outcome).await | 216 | + let result = finish(tx, outcome).await; |
| 217 | + if result.is_ok() { | ||
| 218 | + self.announce_directory(); | ||
| 219 | + } | ||
| 220 | + result | ||
| 200 | } | 221 | } |
| 201 | 222 | ||
| 202 | /// Changes the language, time zone and theme. `locale_auto` true means the language follows the | 223 | /// Changes the language, time zone and theme. `locale_auto` true means the language follows the |
| @@ -211,25 +232,34 @@ impl Store { | |||
| 211 | theme: &str, | 232 | theme: &str, |
| 212 | ) -> Result<()> { | 233 | ) -> Result<()> { |
| 213 | let conn = self.inner.conn.lock().await; | 234 | let conn = self.inner.conn.lock().await; |
| 214 | - let changed = conn | 235 | + let tx = conn.unchecked_transaction().await.map_err(db_err)?; |
| 215 | - .execute( | 236 | + let outcome: Result<()> = async { |
| 216 | - "UPDATE users SET locale = ?2, locale_auto = ?3, zoneinfo = ?4, theme = ?5, \ | 237 | + let changed = tx |
| 217 | - updated_at = ?6 WHERE id = ?1", | 238 | + .execute( |
| 218 | - ( | 239 | + "UPDATE users SET locale = ?2, locale_auto = ?3, zoneinfo = ?4, theme = ?5, \ |
| 219 | - id.to_string(), | 240 | + updated_at = ?6 WHERE id = ?1", |
| 220 | - locale.to_string(), | 241 | + ( |
| 221 | - i64::from(locale_auto), | 242 | + id.to_string(), |
| 222 | - zoneinfo.to_string(), | 243 | + locale.to_string(), |
| 223 | - theme.to_string(), | 244 | + i64::from(locale_auto), |
| 224 | - now_stamp(), | 245 | + zoneinfo.to_string(), |
| 225 | - ), | 246 | + theme.to_string(), |
| 226 | - ) | 247 | + now_stamp(), |
| 227 | - .await | 248 | + ), |
| 228 | - .map_err(db_err)?; | 249 | + ) |
| 229 | - if changed == 0 { | 250 | + .await |
| 230 | - return Err(Error::NotFound); | 251 | + .map_err(db_err)?; |
| 252 | + if changed == 0 { | ||
| 253 | + return Err(Error::NotFound); | ||
| 254 | + } | ||
| 255 | + record_change(&tx, id, ChangeKind::Member).await | ||
| 231 | } | 256 | } |
| 232 | - Ok(()) | 257 | + .await; |
| 258 | + let result = finish(tx, outcome).await; | ||
| 259 | + if result.is_ok() { | ||
| 260 | + self.announce_directory(); | ||
| 261 | + } | ||
| 262 | + result | ||
| 233 | } | 263 | } |
| 234 | 264 | ||
| 235 | /// Records that a photo was stored: sets its MIME type, bumps `picture_version` so caches see a | 265 | /// Records that a photo was stored: sets its MIME type, bumps `picture_version` so caches see a |
| @@ -253,7 +283,11 @@ impl Store { | |||
| 253 | record_change(&tx, id, ChangeKind::Member).await | 283 | record_change(&tx, id, ChangeKind::Member).await |
| 254 | } | 284 | } |
| 255 | .await; | 285 | .await; |
| 256 | - finish(tx, outcome).await | 286 | + let result = finish(tx, outcome).await; |
| 287 | + if result.is_ok() { | ||
| 288 | + self.announce_directory(); | ||
| 289 | + } | ||
| 290 | + result | ||
| 257 | } | 291 | } |
| 258 | 292 | ||
| 259 | /// Records that the photo was removed. Returns false, and writes nothing, when there was no | 293 | /// Records that the photo was removed. Returns false, and writes nothing, when there was no |
| @@ -277,7 +311,11 @@ impl Store { | |||
| 277 | Ok(true) | 311 | Ok(true) |
| 278 | } | 312 | } |
| 279 | .await; | 313 | .await; |
| 280 | - finish(tx, outcome).await | 314 | + let result = finish(tx, outcome).await; |
| 315 | + if matches!(result, Ok(true)) { | ||
| 316 | + self.announce_directory(); | ||
| 317 | + } | ||
| 318 | + result | ||
| 281 | } | 319 | } |
| 282 | 320 | ||
| 283 | /// Stores a new argon2id hash. The caller has checked the policy and the current password. | 321 | /// Stores a new argon2id hash. The caller has checked the policy and the current password. |
| @@ -335,7 +373,11 @@ impl Store { | |||
| 335 | Ok(true) | 373 | Ok(true) |
| 336 | } | 374 | } |
| 337 | .await; | 375 | .await; |
| 338 | - finish(tx, outcome).await | 376 | + let result = finish(tx, outcome).await; |
| 377 | + if matches!(result, Ok(true)) { | ||
| 378 | + self.announce_directory(); | ||
| 379 | + } | ||
| 380 | + result | ||
| 339 | } | 381 | } |
| 340 | 382 | ||
| 341 | /// Holds a sealed TOTP secret while its enrolment waits for a confirming code. Replaces an | 383 | /// Holds a sealed TOTP secret while its enrolment waits for a confirming code. Replaces an |
crates/im-web/Cargo.tomlmodified+1 -0
| @@ -23,6 +23,7 @@ tokio = { workspace = true, features = ["net", "signal", "time", "io-util"] } | |||
| 23 | topcoat.workspace = true | 23 | topcoat.workspace = true |
| 24 | tracing.workspace = true | 24 | tracing.workspace = true |
| 25 | tracing-subscriber = { workspace = true, features = ["env-filter"] } | 25 | tracing-subscriber = { workspace = true, features = ["env-filter"] } |
| 26 | +ulid.workspace = true | ||
| 26 | 27 | ||
| 27 | [dev-dependencies] | 28 | [dev-dependencies] |
| 28 | tempfile.workspace = true | 29 | tempfile.workspace = true |
crates/im-web/src/api/directory.rsadded+356 -0
| @@ -0,0 +1,356 @@ | |||
| 1 | +//! The people directory of `im` (`docs/contracts.md` section 3): the full listing, and the change stream | ||
| 2 | +//! that follows it. | ||
| 3 | +//! | ||
| 4 | +//! The listing and its cursor are read in one step (`Store::directory_snapshot`), so the cursor is exactly | ||
| 5 | +//! the state of the members. The stream resumes from `Last-Event-ID` (or `?cursor=`). A cursor that is not | ||
| 6 | +//! a non-negative integer, that is ahead of the feed, or that is older than the oldest kept row gets one | ||
| 7 | +//! `resync` event and the stream closes: the client then reads the listing again. Otherwise every row after | ||
| 8 | +//! the cursor is sent (`member` with the current record, or `deleted`), and the stream then waits on the | ||
| 9 | +//! feed's watch channel. It ends when the token expires (or after 50 minutes), when the calling client is | ||
| 10 | +//! disabled or removed, or when the client's stream is cut at the per-client cap (four at once, 429 beyond). | ||
| 11 | + | ||
| 12 | +use std::collections::{HashMap, VecDeque}; | ||
| 13 | +use std::sync::{Arc, Mutex, PoisonError}; | ||
| 14 | +use std::time::Duration; | ||
| 15 | + | ||
| 16 | +use futures_util::{Stream, stream}; | ||
| 17 | +use http::header::HeaderValue; | ||
| 18 | +use im_core::model::User; | ||
| 19 | +use im_core::store::Store; | ||
| 20 | +use im_core::store::directory::{Change, ChangeKind}; | ||
| 21 | +use im_core::time::unix_now; | ||
| 22 | +use serde_json::{Value, json}; | ||
| 23 | +use tokio::sync::watch; | ||
| 24 | +use tokio::time::{Instant, Interval}; | ||
| 25 | +use topcoat::Result; | ||
| 26 | +use topcoat::context::{Cx, app_context}; | ||
| 27 | +use topcoat::router::content::sse::{Event, KeepAlive, Sse, last_event_id}; | ||
| 28 | +use topcoat::router::request::uri; | ||
| 29 | +use topcoat::router::response::{IntoResponse, Response}; | ||
| 30 | +use topcoat::router::{StatusCode, route}; | ||
| 31 | + | ||
| 32 | +use super::machine_auth::{DIRECTORY_READ, Machine, require}; | ||
| 33 | +use super::{api_error, json_response}; | ||
| 34 | +use crate::oidc::parse_pairs; | ||
| 35 | +use crate::state::AppState; | ||
| 36 | + | ||
| 37 | +/// Most streams one client may hold open at once. A further one is refused with `429`. | ||
| 38 | +pub const MAX_STREAMS_PER_CLIENT: usize = 4; | ||
| 39 | + | ||
| 40 | +/// Longest a stream lives, in seconds of wall time, whatever the token's expiry says (contracts 3.2). | ||
| 41 | +pub const STREAM_MAX_LIFE: Duration = Duration::from_secs(50 * 60); | ||
| 42 | + | ||
| 43 | +/// Silence after which a keep-alive comment is sent (contracts 3.2 says every 30 s; 25 s keeps a margin). | ||
| 44 | +pub const KEEP_ALIVE: Duration = Duration::from_secs(25); | ||
| 45 | + | ||
| 46 | +/// Rows read from the feed in one batch. | ||
| 47 | +const BATCH: i64 = 200; | ||
| 48 | + | ||
| 49 | +/// How long a `Retry-After` the refused client is given, in seconds. | ||
| 50 | +const RETRY_AFTER_SECS: &str = "5"; | ||
| 51 | + | ||
| 52 | +/// The open streams of each client. Shared by every request, so the cap holds across connections. | ||
| 53 | +#[derive(Default)] | ||
| 54 | +pub struct StreamSlots { | ||
| 55 | + open: Mutex<HashMap<String, usize>>, | ||
| 56 | +} | ||
| 57 | + | ||
| 58 | +/// One open stream of a client. Dropping it frees the slot, so a stream that ends for any reason gives its | ||
| 59 | +/// slot back. | ||
| 60 | +pub struct SlotGuard { | ||
| 61 | + slots: Arc<StreamSlots>, | ||
| 62 | + client_id: String, | ||
| 63 | +} | ||
| 64 | + | ||
| 65 | +impl StreamSlots { | ||
| 66 | + /// Takes a slot for `client_id`, or `None` when the client already holds the maximum. | ||
| 67 | + pub fn acquire(this: &Arc<Self>, client_id: &str) -> Option<SlotGuard> { | ||
| 68 | + let mut open = this.open.lock().unwrap_or_else(PoisonError::into_inner); | ||
| 69 | + let count = open.entry(client_id.to_owned()).or_insert(0); | ||
| 70 | + if *count >= MAX_STREAMS_PER_CLIENT { | ||
| 71 | + return None; | ||
| 72 | + } | ||
| 73 | + *count += 1; | ||
| 74 | + Some(SlotGuard { | ||
| 75 | + slots: Arc::clone(this), | ||
| 76 | + client_id: client_id.to_owned(), | ||
| 77 | + }) | ||
| 78 | + } | ||
| 79 | +} | ||
| 80 | + | ||
| 81 | +impl Drop for SlotGuard { | ||
| 82 | + fn drop(&mut self) { | ||
| 83 | + let mut open = self | ||
| 84 | + .slots | ||
| 85 | + .open | ||
| 86 | + .lock() | ||
| 87 | + .unwrap_or_else(PoisonError::into_inner); | ||
| 88 | + if let Some(count) = open.get_mut(&self.client_id) { | ||
| 89 | + *count = count.saturating_sub(1); | ||
| 90 | + if *count == 0 { | ||
| 91 | + open.remove(&self.client_id); | ||
| 92 | + } | ||
| 93 | + } | ||
| 94 | + } | ||
| 95 | +} | ||
| 96 | + | ||
| 97 | +/// The wire form of one member (contracts 3.1). | ||
| 98 | +pub fn member_json(user: &User) -> Value { | ||
| 99 | + json!({ | ||
| 100 | + "sub": user.id, | ||
| 101 | + "email": user.email, | ||
| 102 | + "name": user.name, | ||
| 103 | + "admin": user.is_admin, | ||
| 104 | + "disabled": user.is_disabled(), | ||
| 105 | + "locale": user.locale, | ||
| 106 | + "zoneinfo": user.zoneinfo, | ||
| 107 | + "picture_version": user.picture_version, | ||
| 108 | + "updated_at": user.updated_at, | ||
| 109 | + }) | ||
| 110 | +} | ||
| 111 | + | ||
| 112 | +/// `GET /api/v1/directory`: every account, disabled ones included, and the cursor of this state. | ||
| 113 | +#[route(GET "/api/v1/directory")] | ||
| 114 | +async fn directory(cx: &Cx) -> Result<Response> { | ||
| 115 | + let app = app_context::<AppState>(cx); | ||
| 116 | + let machine = match require(app, cx, DIRECTORY_READ).await? { | ||
| 117 | + Ok(machine) => machine, | ||
| 118 | + Err(refusal) => return Ok(refusal), | ||
| 119 | + }; | ||
| 120 | + tracing::debug!(caller = %machine.caller, "directory: listing"); | ||
| 121 | + let (head, users) = app.store.directory_snapshot().await?; | ||
| 122 | + let members: Vec<Value> = users.iter().map(member_json).collect(); | ||
| 123 | + Ok(json_response( | ||
| 124 | + StatusCode::OK, | ||
| 125 | + &json!({"members": members, "cursor": head.to_string()}), | ||
| 126 | + )) | ||
| 127 | +} | ||
| 128 | + | ||
| 129 | +/// `GET /api/v1/directory/stream`: the change stream, as `text/event-stream`. | ||
| 130 | +#[route(GET "/api/v1/directory/stream")] | ||
| 131 | +async fn directory_stream(cx: &Cx) -> Result<Response> { | ||
| 132 | + let app = app_context::<AppState>(cx); | ||
| 133 | + let machine = match require(app, cx, DIRECTORY_READ).await? { | ||
| 134 | + Ok(machine) => machine, | ||
| 135 | + Err(refusal) => return Ok(refusal), | ||
| 136 | + }; | ||
| 137 | + let Some(slot) = StreamSlots::acquire(&app.stream_slots, &machine.client_id) else { | ||
| 138 | + let mut response = api_error( | ||
| 139 | + StatusCode::TOO_MANY_REQUESTS, | ||
| 140 | + "rate_limited", | ||
| 141 | + "This client already has the maximum number of directory streams open.", | ||
| 142 | + None, | ||
| 143 | + ); | ||
| 144 | + response | ||
| 145 | + .headers_mut() | ||
| 146 | + .insert("retry-after", HeaderValue::from_static(RETRY_AFTER_SECS)); | ||
| 147 | + return Ok(response); | ||
| 148 | + }; | ||
| 149 | + // Subscribed before the feed is read, so a change made in between still wakes the stream. | ||
| 150 | + let wake = app.store.directory_watch(); | ||
| 151 | + let head = app.store.directory_head().await?; | ||
| 152 | + let oldest = app.store.directory_oldest().await?; | ||
| 153 | + let requested = requested_cursor(cx); | ||
| 154 | + let Some(start) = resume_point(requested.as_deref(), head, oldest) else { | ||
| 155 | + return sse(cx, stream::iter(vec![Ok(resync_event())])); | ||
| 156 | + }; | ||
| 157 | + let deadline = Instant::now() + stream_life(&machine); | ||
| 158 | + let follow = Follow { | ||
| 159 | + stop: app.stop.clone(), | ||
| 160 | + store: app.store.clone(), | ||
| 161 | + client_id: machine.client_id.clone(), | ||
| 162 | + cursor: start, | ||
| 163 | + wake, | ||
| 164 | + check: tokio::time::interval_at(Instant::now() + KEEP_ALIVE, KEEP_ALIVE), | ||
| 165 | + deadline, | ||
| 166 | + pending: VecDeque::new(), | ||
| 167 | + _slot: slot, | ||
| 168 | + }; | ||
| 169 | + sse(cx, follow_events(follow)) | ||
| 170 | +} | ||
| 171 | + | ||
| 172 | +/// The state of one stream between two events. | ||
| 173 | +struct Follow { | ||
| 174 | + /// Set when the process stops: the stream then ends, so the server can drain. | ||
| 175 | + stop: watch::Receiver<bool>, | ||
| 176 | + store: Store, | ||
| 177 | + client_id: String, | ||
| 178 | + /// The last sequence number sent. | ||
| 179 | + cursor: i64, | ||
| 180 | + /// Woken by every committed directory change. | ||
| 181 | + wake: watch::Receiver<u64>, | ||
| 182 | + /// Checks, every [`KEEP_ALIVE`], that the calling client is still enabled. | ||
| 183 | + check: Interval, | ||
| 184 | + /// The stream ends at this time (the token's expiry or the 50-minute cap). | ||
| 185 | + deadline: Instant, | ||
| 186 | + /// Events read but not yet sent. | ||
| 187 | + pending: VecDeque<Event>, | ||
| 188 | + /// Holds the client's slot for as long as the stream lives. | ||
| 189 | + _slot: SlotGuard, | ||
| 190 | +} | ||
| 191 | + | ||
| 192 | +/// The events of a stream from its cursor on. It ends on a store failure, a disabled client, the | ||
| 193 | +/// deadline, or a closed feed; the browser or consumer reconnects with its last cursor. | ||
| 194 | +fn follow_events(follow: Follow) -> impl Stream<Item = topcoat::Result<Event>> + Send + 'static { | ||
| 195 | + stream::unfold(follow, |mut follow| async move { | ||
| 196 | + loop { | ||
| 197 | + if let Some(event) = follow.pending.pop_front() { | ||
| 198 | + return Some((Ok(event), follow)); | ||
| 199 | + } | ||
| 200 | + match follow | ||
| 201 | + .store | ||
| 202 | + .directory_changes_after(follow.cursor, BATCH) | ||
| 203 | + .await | ||
| 204 | + { | ||
| 205 | + Ok(changes) if !changes.is_empty() => { | ||
| 206 | + for change in changes { | ||
| 207 | + match change_event(&follow.store, &change).await { | ||
| 208 | + Ok(event) => follow.pending.push_back(event), | ||
| 209 | + Err(error) => { | ||
| 210 | + tracing::error!(error = %error, "directory stream: a change could not be read"); | ||
| 211 | + return None; | ||
| 212 | + } | ||
| 213 | + } | ||
| 214 | + follow.cursor = change.seq; | ||
| 215 | + } | ||
| 216 | + continue; | ||
| 217 | + } | ||
| 218 | + Ok(_) => {} | ||
| 219 | + Err(error) => { | ||
| 220 | + tracing::error!(error = %error, "directory stream: the feed could not be read"); | ||
| 221 | + return None; | ||
| 222 | + } | ||
| 223 | + } | ||
| 224 | + tokio::select! { | ||
| 225 | + changed = follow.wake.changed() => { | ||
| 226 | + if changed.is_err() { | ||
| 227 | + return None; | ||
| 228 | + } | ||
| 229 | + } | ||
| 230 | + _ = follow.check.tick() => { | ||
| 231 | + match follow.store.client_by_id(&follow.client_id).await { | ||
| 232 | + Ok(Some(client)) if !client.is_disabled() => {} | ||
| 233 | + _ => return None, | ||
| 234 | + } | ||
| 235 | + } | ||
| 236 | + () = stopped(&mut follow.stop) => return None, | ||
| 237 | + () = tokio::time::sleep_until(follow.deadline) => return None, | ||
| 238 | + } | ||
| 239 | + } | ||
| 240 | + }) | ||
| 241 | +} | ||
| 242 | + | ||
| 243 | +/// Resolves when the stop flag is set. A flag whose sender is gone never resolves, so a stream is not | ||
| 244 | +/// ended by a test state that has no server behind it. | ||
| 245 | +async fn stopped(stop: &mut watch::Receiver<bool>) { | ||
| 246 | + if stop.wait_for(|stopped| *stopped).await.is_err() { | ||
| 247 | + std::future::pending::<()>().await; | ||
| 248 | + } | ||
| 249 | +} | ||
| 250 | + | ||
| 251 | +/// The event of one change row, with the row's sequence number as its id. A member row is sent with the | ||
| 252 | +/// person's current record; if the person is gone by then, the event is `deleted`. | ||
| 253 | +async fn change_event(store: &Store, change: &Change) -> im_core::Result<Event> { | ||
| 254 | + let user = match change.kind { | ||
| 255 | + ChangeKind::Member => store.user_by_id(&change.sub).await?, | ||
| 256 | + ChangeKind::Deleted => None, | ||
| 257 | + }; | ||
| 258 | + let event = match user { | ||
| 259 | + Some(user) => Event::new() | ||
| 260 | + .event("member") | ||
| 261 | + .data(member_json(&user).to_string()), | ||
| 262 | + None => Event::new() | ||
| 263 | + .event("deleted") | ||
| 264 | + .data(json!({"sub": change.sub}).to_string()), | ||
| 265 | + }; | ||
| 266 | + Ok(event.id(change.seq.to_string())) | ||
| 267 | +} | ||
| 268 | + | ||
| 269 | +/// The one `resync` event: the cursor is unusable, so the consumer reads the listing again. | ||
| 270 | +fn resync_event() -> Event { | ||
| 271 | + Event::new().event("resync").data("{}") | ||
| 272 | +} | ||
| 273 | + | ||
| 274 | +/// The cursor the client asked to resume from: `Last-Event-ID`, else `?cursor=`. A repeated `cursor` | ||
| 275 | +/// parameter is treated as garbage, which means resync. | ||
| 276 | +fn requested_cursor(cx: &Cx) -> Option<String> { | ||
| 277 | + if let Some(id) = last_event_id(cx).filter(|id| !id.is_empty()) { | ||
| 278 | + return Some(id.to_owned()); | ||
| 279 | + } | ||
| 280 | + let query = uri(cx).query()?; | ||
| 281 | + let pairs = parse_pairs(query.as_bytes())?; | ||
| 282 | + match crate::oidc::single(&pairs, "cursor") { | ||
| 283 | + crate::oidc::Single::Absent => None, | ||
| 284 | + crate::oidc::Single::One(value) => Some(value.to_owned()), | ||
| 285 | + crate::oidc::Single::Repeated => Some(String::new()), | ||
| 286 | + } | ||
| 287 | +} | ||
| 288 | + | ||
| 289 | +/// Where a stream starts, or `None` when it must resync. No cursor starts at the head (the consumer reads | ||
| 290 | +/// the listing first). A cursor must be digits only, not ahead of the head, and not older than the oldest | ||
| 291 | +/// kept row: the rows between it and that row were pruned, so they cannot be replayed. | ||
| 292 | +pub fn resume_point(requested: Option<&str>, head: i64, oldest: Option<i64>) -> Option<i64> { | ||
| 293 | + let Some(text) = requested else { | ||
| 294 | + return Some(head); | ||
| 295 | + }; | ||
| 296 | + if text.is_empty() || !text.bytes().all(|byte| byte.is_ascii_digit()) { | ||
| 297 | + return None; | ||
| 298 | + } | ||
| 299 | + let cursor: i64 = text.parse().ok()?; | ||
| 300 | + if cursor > head { | ||
| 301 | + return None; | ||
| 302 | + } | ||
| 303 | + if let Some(oldest) = oldest | ||
| 304 | + && cursor.saturating_add(1) < oldest | ||
| 305 | + { | ||
| 306 | + return None; | ||
| 307 | + } | ||
| 308 | + Some(cursor) | ||
| 309 | +} | ||
| 310 | + | ||
| 311 | +/// How long a stream of this caller may live: until the token expires, and at most [`STREAM_MAX_LIFE`]. | ||
| 312 | +fn stream_life(machine: &Machine) -> Duration { | ||
| 313 | + let until_expiry = u64::try_from(machine.expires_at - unix_now()).unwrap_or(0); | ||
| 314 | + Duration::from_secs(until_expiry).min(STREAM_MAX_LIFE) | ||
| 315 | +} | ||
| 316 | + | ||
| 317 | +/// The response of a stream: the events, with a keep-alive comment while idle. `X-Accel-Buffering: no` | ||
| 318 | +/// stops a reverse proxy from holding the events back. | ||
| 319 | +fn sse( | ||
| 320 | + cx: &Cx, | ||
| 321 | + events: impl Stream<Item = topcoat::Result<Event>> + Send + 'static, | ||
| 322 | +) -> Result<Response> { | ||
| 323 | + let mut response = Sse::new(events) | ||
| 324 | + .keep_alive(KeepAlive::new().interval(KEEP_ALIVE).text("keepalive")) | ||
| 325 | + .into_response(cx)?; | ||
| 326 | + response | ||
| 327 | + .headers_mut() | ||
| 328 | + .insert("x-accel-buffering", HeaderValue::from_static("no")); | ||
| 329 | + Ok(response) | ||
| 330 | +} | ||
| 331 | + | ||
| 332 | +#[cfg(test)] | ||
| 333 | +mod tests { | ||
| 334 | + use super::*; | ||
| 335 | + | ||
| 336 | + #[test] | ||
| 337 | + fn a_cursor_resumes_only_inside_the_kept_range() { | ||
| 338 | + // No cursor: start at the head. | ||
| 339 | + assert_eq!(resume_point(None, 7, Some(3)), Some(7)); | ||
| 340 | + // Inside the range, and at the head. | ||
| 341 | + assert_eq!(resume_point(Some("5"), 7, Some(3)), Some(5)); | ||
| 342 | + assert_eq!(resume_point(Some("7"), 7, Some(3)), Some(7)); | ||
| 343 | + // Ahead of the head, negative, empty, signed or not a number: resync. | ||
| 344 | + assert_eq!(resume_point(Some("8"), 7, Some(3)), None); | ||
| 345 | + assert_eq!(resume_point(Some("-1"), 7, Some(3)), None); | ||
| 346 | + assert_eq!(resume_point(Some("+1"), 7, Some(3)), None); | ||
| 347 | + assert_eq!(resume_point(Some(""), 7, Some(3)), None); | ||
| 348 | + assert_eq!(resume_point(Some("abc"), 7, Some(3)), None); | ||
| 349 | + // Rows 1 and 2 were pruned, so row 3 is the oldest kept. A cursor of 1 still needs row 2: resync. | ||
| 350 | + // A cursor of 2 needs only rows from 3 on: fine. | ||
| 351 | + assert_eq!(resume_point(Some("1"), 7, Some(3)), None); | ||
| 352 | + assert_eq!(resume_point(Some("2"), 7, Some(3)), Some(2)); | ||
| 353 | + // Empty feed: cursor 0 is at the head. | ||
| 354 | + assert_eq!(resume_point(Some("0"), 0, None), Some(0)); | ||
| 355 | + } | ||
| 356 | +} | ||
crates/im-web/src/api/family.rsadded+39 -0
| @@ -0,0 +1,39 @@ | |||
| 1 | +//! `GET /api/v1/family` (`docs/contracts.md` section 4): the switcher list, in the admin's order. | ||
| 2 | +//! | ||
| 3 | +//! The rows are the `services` table: each family app with its public origin, and im's own row. A row's | ||
| 4 | +//! `healthy` is `null` until the first probe. Any caller with the directory scope may read the list. | ||
| 5 | + | ||
| 6 | +use im_core::model::Service; | ||
| 7 | +use serde_json::{Value, json}; | ||
| 8 | +use topcoat::Result; | ||
| 9 | +use topcoat::context::{Cx, app_context}; | ||
| 10 | +use topcoat::router::StatusCode; | ||
| 11 | +use topcoat::router::response::Response; | ||
| 12 | +use topcoat::router::route; | ||
| 13 | + | ||
| 14 | +use super::machine_auth::{DIRECTORY_READ, require}; | ||
| 15 | +use crate::oidc::json_response; | ||
| 16 | +use crate::state::AppState; | ||
| 17 | + | ||
| 18 | +/// `GET /api/v1/family`. | ||
| 19 | +#[route(GET "/api/v1/family")] | ||
| 20 | +async fn family(cx: &Cx) -> Result<Response> { | ||
| 21 | + let app = app_context::<AppState>(cx); | ||
| 22 | + if let Err(refusal) = require(app, cx, DIRECTORY_READ).await? { | ||
| 23 | + return Ok(refusal); | ||
| 24 | + } | ||
| 25 | + let services = app.store.list_services().await?; | ||
| 26 | + let list: Vec<Value> = services.iter().map(service_json).collect(); | ||
| 27 | + Ok(json_response(StatusCode::OK, &json!({"services": list}))) | ||
| 28 | +} | ||
| 29 | + | ||
| 30 | +/// The wire form of one switcher row. | ||
| 31 | +fn service_json(service: &Service) -> Value { | ||
| 32 | + json!({ | ||
| 33 | + "key": service.key, | ||
| 34 | + "name": service.name, | ||
| 35 | + "url": service.url, | ||
| 36 | + "healthy": service.healthy, | ||
| 37 | + "checked_at": service.checked_at, | ||
| 38 | + }) | ||
| 39 | +} | ||
crates/im-web/src/api/machine_auth.rsadded+113 -0
| @@ -0,0 +1,113 @@ | |||
| 1 | +//! Checks the client-credentials tokens that family services present to `im` (contracts 2.6). | ||
| 2 | +//! | ||
| 3 | +//! `im` verifies its own tokens: the signature against the published keys, `iss` exactly, `aud` exactly | ||
| 4 | +//! the string `im` (an array is refused, because `im` never issues one), `exp` and `iat`. Then the token | ||
| 5 | +//! must be a machine token: `sub` is `client:<azp>`, `svc` names a family key, and it carries no `sid`. | ||
| 6 | +//! The client it names must still exist, be enabled, and be registered under that family key. A user's | ||
| 7 | +//! access token and an ID token fail one of these checks, so they never open a machine route. | ||
| 8 | + | ||
| 9 | +use http::header::AUTHORIZATION; | ||
| 10 | +use im_core::jwt::{self, PublishedKey}; | ||
| 11 | +use im_core::oauth::is_valid_family_key; | ||
| 12 | +use im_core::time::unix_now; | ||
| 13 | +use serde_json::Value; | ||
| 14 | +use topcoat::Result; | ||
| 15 | +use topcoat::context::Cx; | ||
| 16 | +use topcoat::router::StatusCode; | ||
| 17 | +use topcoat::router::request::headers; | ||
| 18 | +use topcoat::router::response::Response; | ||
| 19 | + | ||
| 20 | +use super::{SCOPE_CHALLENGE, TOKEN_CHALLENGE, api_error}; | ||
| 21 | +use crate::oidc::userinfo::bearer; | ||
| 22 | +use crate::oidc::{issuer, signing}; | ||
| 23 | +use crate::state::AppState; | ||
| 24 | + | ||
| 25 | +/// The scope of the people directory, its stream and the photos (contracts 2.6 and 3). | ||
| 26 | +pub const DIRECTORY_READ: &str = "directory.read"; | ||
| 27 | + | ||
| 28 | +/// The audience every directory, photo and family route requires. | ||
| 29 | +pub const MACHINE_AUDIENCE: &str = "im"; | ||
| 30 | + | ||
| 31 | +/// A verified machine caller. | ||
| 32 | +#[derive(Debug, Clone)] | ||
| 33 | +pub struct Machine { | ||
| 34 | + /// The client the token was issued to (`azp`). | ||
| 35 | + pub client_id: String, | ||
| 36 | + /// The family key of the caller (`svc`). | ||
| 37 | + pub caller: String, | ||
| 38 | + /// When the token expires, in Unix seconds. A stream ends no later than this. | ||
| 39 | + pub expires_at: i64, | ||
| 40 | +} | ||
| 41 | + | ||
| 42 | +/// Verifies the bearer token of the request for `scope`. The outer `Result` is a server failure; the | ||
| 43 | +/// inner one is the refusal, ready to send as the answer. | ||
| 44 | +pub async fn require( | ||
| 45 | + app: &AppState, | ||
| 46 | + cx: &Cx, | ||
| 47 | + scope: &str, | ||
| 48 | +) -> Result<std::result::Result<Machine, Response>> { | ||
| 49 | + let Some(token) = bearer(headers(cx).get(AUTHORIZATION)) else { | ||
| 50 | + return Ok(Err(refused())); | ||
| 51 | + }; | ||
| 52 | + let published = signing::published_keys(&app.store).await?; | ||
| 53 | + let keys: Vec<PublishedKey> = published | ||
| 54 | + .iter() | ||
| 55 | + .filter_map(|key| PublishedKey::new(key.kid.clone(), &key.public_raw)) | ||
| 56 | + .collect(); | ||
| 57 | + let Ok(claims) = jwt::verify(&keys, token) else { | ||
| 58 | + return Ok(Err(refused())); | ||
| 59 | + }; | ||
| 60 | + // The audience must be exactly the string `im`. `check_claims` also checks it, and the exp and iat. | ||
| 61 | + if jwt::single_audience(&claims) != Some(MACHINE_AUDIENCE) { | ||
| 62 | + return Ok(Err(refused())); | ||
| 63 | + } | ||
| 64 | + if jwt::check_claims(&claims, issuer(app), MACHINE_AUDIENCE, unix_now()).is_err() { | ||
| 65 | + return Ok(Err(refused())); | ||
| 66 | + } | ||
| 67 | + let text = |name: &str| claims.get(name).and_then(Value::as_str); | ||
| 68 | + let (Some(client_id), Some(sub), Some(caller), Some(expires_at)) = ( | ||
| 69 | + text("azp"), | ||
| 70 | + text("sub"), | ||
| 71 | + text("svc"), | ||
| 72 | + claims.get("exp").and_then(Value::as_i64), | ||
| 73 | + ) else { | ||
| 74 | + return Ok(Err(refused())); | ||
| 75 | + }; | ||
| 76 | + // A person's token carries a session (`sid`) and a person's id as `sub`; neither is a machine token. | ||
| 77 | + if sub != format!("client:{client_id}") | ||
| 78 | + || claims.contains_key("sid") | ||
| 79 | + || !is_valid_family_key(caller) | ||
| 80 | + { | ||
| 81 | + return Ok(Err(refused())); | ||
| 82 | + } | ||
| 83 | + let Some(client) = app.store.client_by_id(client_id).await? else { | ||
| 84 | + return Ok(Err(refused())); | ||
| 85 | + }; | ||
| 86 | + if client.is_disabled() || client.service_key.as_deref() != Some(caller) { | ||
| 87 | + return Ok(Err(refused())); | ||
| 88 | + } | ||
| 89 | + let granted = text("scope").unwrap_or_default(); | ||
| 90 | + if !granted.split_whitespace().any(|word| word == scope) { | ||
| 91 | + return Ok(Err(api_error( | ||
| 92 | + StatusCode::FORBIDDEN, | ||
| 93 | + "insufficient_scope", | ||
| 94 | + "The token does not grant the scope this route needs.", | ||
| 95 | + Some(SCOPE_CHALLENGE), | ||
| 96 | + ))); | ||
| 97 | + } | ||
| 98 | + Ok(Ok(Machine { | ||
| 99 | + client_id: client.id, | ||
| 100 | + caller: caller.to_owned(), | ||
| 101 | + expires_at, | ||
| 102 | + })) | ||
| 103 | +} | ||
| 104 | + | ||
| 105 | +/// `401 invalid_token`. One answer for every reason, so the reason is not disclosed. | ||
| 106 | +fn refused() -> Response { | ||
| 107 | + api_error( | ||
| 108 | + StatusCode::UNAUTHORIZED, | ||
| 109 | + "invalid_token", | ||
| 110 | + "The access token is missing, invalid, expired, or not issued for this service.", | ||
| 111 | + Some(TOKEN_CHALLENGE), | ||
| 112 | + ) | ||
| 113 | +} | ||
crates/im-web/src/api/mod.rsadded+53 -0
| @@ -0,0 +1,53 @@ | |||
| 1 | +//! The machine API of `im` (`docs/contracts.md` sections 3 and 4): the people directory and its change | ||
| 2 | +//! stream, the profile photos, and the service switcher list. | ||
| 3 | +//! | ||
| 4 | +//! Every route here needs a client-credentials token that `im` issued to a family service, with the | ||
| 5 | +//! audience `im` and the scope the route needs (`machine_auth.rs`). Errors are JSON with a real status | ||
| 6 | +//! (contracts section 7): `{"error": ..., "message": ...}`. | ||
| 7 | + | ||
| 8 | +pub mod directory; | ||
| 9 | +pub mod family; | ||
| 10 | +pub mod machine_auth; | ||
| 11 | +pub mod photo; | ||
| 12 | + | ||
| 13 | +#[cfg(test)] | ||
| 14 | +mod tests; | ||
| 15 | + | ||
| 16 | +use http::header::WWW_AUTHENTICATE; | ||
| 17 | +use serde_json::json; | ||
| 18 | +use topcoat::router::response::Response; | ||
| 19 | +use topcoat::router::{HeaderValue, StatusCode}; | ||
| 20 | + | ||
| 21 | +use crate::oidc::json_response; | ||
| 22 | + | ||
| 23 | +/// The `WWW-Authenticate` challenge of a token that is missing or not valid for this service. | ||
| 24 | +pub const TOKEN_CHALLENGE: &str = "Bearer error=\"invalid_token\""; | ||
| 25 | + | ||
| 26 | +/// The `WWW-Authenticate` challenge of a valid token that lacks the scope a route needs. | ||
| 27 | +pub const SCOPE_CHALLENGE: &str = "Bearer error=\"insufficient_scope\""; | ||
| 28 | + | ||
| 29 | +/// A machine error: the status, the stable word, a message for logs, and the challenge of a 401 or 403. | ||
| 30 | +pub fn api_error( | ||
| 31 | + status: StatusCode, | ||
| 32 | + error: &str, | ||
| 33 | + message: &str, | ||
| 34 | + challenge: Option<&'static str>, | ||
| 35 | +) -> Response { | ||
| 36 | + let mut response = json_response(status, &json!({"error": error, "message": message})); | ||
| 37 | + if let Some(challenge) = challenge { | ||
| 38 | + response | ||
| 39 | + .headers_mut() | ||
| 40 | + .insert(WWW_AUTHENTICATE, HeaderValue::from_static(challenge)); | ||
| 41 | + } | ||
| 42 | + response | ||
| 43 | +} | ||
| 44 | + | ||
| 45 | +/// `404 not_found` for a route that has no such thing. | ||
| 46 | +pub fn not_found() -> Response { | ||
| 47 | + api_error( | ||
| 48 | + StatusCode::NOT_FOUND, | ||
| 49 | + "not_found", | ||
| 50 | + "There is nothing at this address.", | ||
| 51 | + None, | ||
| 52 | + ) | ||
| 53 | +} | ||
crates/im-web/src/api/photo.rsadded+157 -0
| @@ -0,0 +1,157 @@ | |||
| 1 | +//! `GET /api/v1/people/{sub}/photo` (`docs/contracts.md` section 3.2): a person's profile photo, as bytes. | ||
| 2 | +//! | ||
| 3 | +//! The `sub` must be a ULID, else `404`. A person with no photo, an unknown or deleted person, and a photo | ||
| 4 | +//! whose stored type is not on the allowlist are all `404`, so the answer does not say which it was. There | ||
| 5 | +//! is no initials picture for a machine. The bytes go with `nosniff` and a `"p<picture_version>"` ETag. With | ||
| 6 | +//! `?v=` equal to the current version the answer may be cached for a year (the URL names the version); | ||
| 7 | +//! otherwise it may be kept but must be checked again. `If-None-Match` gets a `304`. | ||
| 8 | + | ||
| 9 | +use http::header::{CACHE_CONTROL, CONTENT_TYPE, ETAG, IF_NONE_MATCH, X_CONTENT_TYPE_OPTIONS}; | ||
| 10 | +use im_core::photo::read_photo; | ||
| 11 | +use topcoat::Result; | ||
| 12 | +use topcoat::context::{Cx, app_context}; | ||
| 13 | +use topcoat::router::request::{headers, uri}; | ||
| 14 | +use topcoat::router::response::Response; | ||
| 15 | +use topcoat::router::{Body, HeaderValue, StatusCode, raw_path_params, route}; | ||
| 16 | + | ||
| 17 | +use super::machine_auth::{DIRECTORY_READ, require}; | ||
| 18 | +use super::{api_error, not_found}; | ||
| 19 | +use crate::oidc::{Single, parse_pairs, single}; | ||
| 20 | +use crate::state::AppState; | ||
| 21 | + | ||
| 22 | +/// The image types a photo may be served as. Anything else stored is not served. | ||
| 23 | +pub const ALLOWED_TYPES: [&str; 4] = ["image/png", "image/jpeg", "image/webp", "image/gif"]; | ||
| 24 | + | ||
| 25 | +/// Caching when `?v=` names the current version: the URL is unique to this picture. | ||
| 26 | +const IMMUTABLE_CACHE: &str = "private, max-age=31536000, immutable"; | ||
| 27 | + | ||
| 28 | +/// Caching otherwise: keep it, but ask again before use. | ||
| 29 | +const REVALIDATE_CACHE: &str = "private, no-cache"; | ||
| 30 | + | ||
| 31 | +/// `GET /api/v1/people/{sub}/photo`. | ||
| 32 | +#[route(GET "/api/v1/people/{sub}/photo")] | ||
| 33 | +async fn photo(cx: &Cx) -> Result<Response> { | ||
| 34 | + let app = app_context::<AppState>(cx); | ||
| 35 | + let machine = match require(app, cx, DIRECTORY_READ).await? { | ||
| 36 | + Ok(machine) => machine, | ||
| 37 | + Err(refusal) => return Ok(refusal), | ||
| 38 | + }; | ||
| 39 | + tracing::debug!(caller = %machine.caller, "photo: request"); | ||
| 40 | + let Some(sub) = path_sub(cx) else { | ||
| 41 | + return Ok(not_found()); | ||
| 42 | + }; | ||
| 43 | + if !is_ulid(&sub) { | ||
| 44 | + return Ok(not_found()); | ||
| 45 | + } | ||
| 46 | + let Some(person) = app.store.user_by_id(&sub).await? else { | ||
| 47 | + return Ok(not_found()); | ||
| 48 | + }; | ||
| 49 | + let Some(mime) = person.photo_mime.as_deref().and_then(allowed_type) else { | ||
| 50 | + return Ok(not_found()); | ||
| 51 | + }; | ||
| 52 | + let etag = format!("\"p{}\"", person.picture_version); | ||
| 53 | + let cache = if requested_version(cx) == Some(person.picture_version) { | ||
| 54 | + IMMUTABLE_CACHE | ||
| 55 | + } else { | ||
| 56 | + REVALIDATE_CACHE | ||
| 57 | + }; | ||
| 58 | + if none_match(cx, &etag) { | ||
| 59 | + return Ok(answer( | ||
| 60 | + StatusCode::NOT_MODIFIED, | ||
| 61 | + &etag, | ||
| 62 | + mime, | ||
| 63 | + cache, | ||
| 64 | + Vec::new(), | ||
| 65 | + )); | ||
| 66 | + } | ||
| 67 | + let dir = app.config.data_dir.clone(); | ||
| 68 | + let read_sub = sub.clone(); | ||
| 69 | + let stored = match tokio::task::spawn_blocking(move || read_photo(&dir, &read_sub)).await { | ||
| 70 | + Ok(Ok(stored)) => stored, | ||
| 71 | + Ok(Err(error)) => { | ||
| 72 | + tracing::error!(error = %error, "photo: the stored picture could not be read"); | ||
| 73 | + return Ok(api_error( | ||
| 74 | + StatusCode::INTERNAL_SERVER_ERROR, | ||
| 75 | + "internal", | ||
| 76 | + "The photo could not be read.", | ||
| 77 | + None, | ||
| 78 | + )); | ||
| 79 | + } | ||
| 80 | + Err(error) => { | ||
| 81 | + tracing::error!(error = %error, "photo: the read task failed"); | ||
| 82 | + return Ok(api_error( | ||
| 83 | + StatusCode::INTERNAL_SERVER_ERROR, | ||
| 84 | + "internal", | ||
| 85 | + "The photo could not be read.", | ||
| 86 | + None, | ||
| 87 | + )); | ||
| 88 | + } | ||
| 89 | + }; | ||
| 90 | + match stored { | ||
| 91 | + Some(bytes) => Ok(answer(StatusCode::OK, &etag, mime, cache, bytes)), | ||
| 92 | + // The row names a photo whose file is gone: there is no picture to send. | ||
| 93 | + None => Ok(not_found()), | ||
| 94 | + } | ||
| 95 | +} | ||
| 96 | + | ||
| 97 | +/// The `{sub}` of the matched route, or `None`. | ||
| 98 | +fn path_sub(cx: &Cx) -> Option<String> { | ||
| 99 | + raw_path_params(cx) | ||
| 100 | + .find(|(name, _)| *name == "sub") | ||
| 101 | + .map(|(_, value)| value.as_str().to_owned()) | ||
| 102 | +} | ||
| 103 | + | ||
| 104 | +/// The `v` query parameter as a version, when it is exactly one integer. | ||
| 105 | +fn requested_version(cx: &Cx) -> Option<i64> { | ||
| 106 | + let query = uri(cx).query()?; | ||
| 107 | + let pairs = parse_pairs(query.as_bytes())?; | ||
| 108 | + match single(&pairs, "v") { | ||
| 109 | + Single::One(value) => value.parse().ok(), | ||
| 110 | + _ => None, | ||
| 111 | + } | ||
| 112 | +} | ||
| 113 | + | ||
| 114 | +/// True when `If-None-Match` names `etag`. | ||
| 115 | +fn none_match(cx: &Cx, etag: &str) -> bool { | ||
| 116 | + headers(cx) | ||
| 117 | + .get_all(IF_NONE_MATCH) | ||
| 118 | + .iter() | ||
| 119 | + .filter_map(|value| value.to_str().ok()) | ||
| 120 | + .flat_map(|value| value.split(',')) | ||
| 121 | + .any(|tag| tag.trim() == etag) | ||
| 122 | +} | ||
| 123 | + | ||
| 124 | +/// The stored type, when it is on the allowlist. | ||
| 125 | +fn allowed_type(stored: &str) -> Option<&'static str> { | ||
| 126 | + ALLOWED_TYPES.into_iter().find(|allowed| *allowed == stored) | ||
| 127 | +} | ||
| 128 | + | ||
| 129 | +/// A user id is a ULID: 26 characters of Crockford base32, the first at most `7`. Anything else (a path | ||
| 130 | +/// fragment, an encoded slash, a dot segment) is refused before it reaches the disk. | ||
| 131 | +pub fn is_ulid(sub: &str) -> bool { | ||
| 132 | + sub.len() == 26 && ulid::Ulid::from_string(sub).is_ok() | ||
| 133 | +} | ||
| 134 | + | ||
| 135 | +/// One photo answer with its headers. | ||
| 136 | +fn answer( | ||
| 137 | + status: StatusCode, | ||
| 138 | + etag: &str, | ||
| 139 | + mime: &str, | ||
| 140 | + cache: &'static str, | ||
| 141 | + body: Vec<u8>, | ||
| 142 | +) -> Response { | ||
| 143 | + let mut response = Response::new(Body::from(body)); | ||
| 144 | + *response.status_mut() = status; | ||
| 145 | + let headers = response.headers_mut(); | ||
| 146 | + headers.insert( | ||
| 147 | + CONTENT_TYPE, | ||
| 148 | + HeaderValue::from_str(mime).unwrap_or(HeaderValue::from_static("application/octet-stream")), | ||
| 149 | + ); | ||
| 150 | + headers.insert(CACHE_CONTROL, HeaderValue::from_static(cache)); | ||
| 151 | + headers.insert( | ||
| 152 | + ETAG, | ||
| 153 | + HeaderValue::from_str(etag).unwrap_or(HeaderValue::from_static("\"\"")), | ||
| 154 | + ); | ||
| 155 | + headers.insert(X_CONTENT_TYPE_OPTIONS, HeaderValue::from_static("nosniff")); | ||
| 156 | + response | ||
| 157 | +} | ||
crates/im-web/src/api/tests.rsadded+172 -0
| @@ -0,0 +1,172 @@ | |||
| 1 | +//! The machine API through the router: who may call it, the stream's resume rule, and the photo path. | ||
| 2 | + | ||
| 3 | +use http::header::{AUTHORIZATION, WWW_AUTHENTICATE}; | ||
| 4 | +use im_core::model::Client; | ||
| 5 | +use im_core::store::clients::NewClient; | ||
| 6 | +use im_core::store::new_id; | ||
| 7 | +use im_core::time::unix_now; | ||
| 8 | +use im_core::token::{generate_token, hash_token}; | ||
| 9 | +use serde_json::{Value, json}; | ||
| 10 | +use topcoat::router::{Body, StatusCode, to_bytes}; | ||
| 11 | + | ||
| 12 | +use crate::boot::{router, test_state}; | ||
| 13 | +use crate::oidc::signing; | ||
| 14 | +use crate::state::AppState; | ||
| 15 | + | ||
| 16 | +/// A family client (`in`) that may ask for the directory scope, and a secret it is not given here. | ||
| 17 | +struct Fixture { | ||
| 18 | + _dir: tempfile::TempDir, | ||
| 19 | + state: AppState, | ||
| 20 | + client: Client, | ||
| 21 | +} | ||
| 22 | + | ||
| 23 | +async fn fixture() -> Fixture { | ||
| 24 | + let (dir, state) = test_state().await; | ||
| 25 | + signing::maintain(&state.store, &state.key) | ||
| 26 | + .await | ||
| 27 | + .expect("signing key"); | ||
| 28 | + let client = state | ||
| 29 | + .store | ||
| 30 | + .create_client(&NewClient { | ||
| 31 | + name: "Files", | ||
| 32 | + secret_hash: &hash_token(&generate_token()), | ||
| 33 | + redirect_uris: &[], | ||
| 34 | + post_logout_redirect_uris: &[], | ||
| 35 | + backchannel_logout_uri: None, | ||
| 36 | + allowed_scopes: "directory.read files.service", | ||
| 37 | + service_key: Some("in"), | ||
| 38 | + }) | ||
| 39 | + .await | ||
| 40 | + .expect("client"); | ||
| 41 | + Fixture { | ||
| 42 | + _dir: dir, | ||
| 43 | + state, | ||
| 44 | + client, | ||
| 45 | + } | ||
| 46 | +} | ||
| 47 | + | ||
| 48 | +/// The claims of a client-credentials token that `im` would issue to `client` for `aud` and `scope`. | ||
| 49 | +fn machine_claims(state: &AppState, client: &Client, aud: &str, scope: &str) -> Value { | ||
| 50 | + let now = unix_now(); | ||
| 51 | + json!({ | ||
| 52 | + "iss": state.config.base_url, | ||
| 53 | + "sub": format!("client:{}", client.id), | ||
| 54 | + "azp": client.id, | ||
| 55 | + "aud": aud, | ||
| 56 | + "scope": scope, | ||
| 57 | + "svc": "in", | ||
| 58 | + "iat": now, | ||
| 59 | + "exp": now + 600, | ||
| 60 | + "jti": generate_token(), | ||
| 61 | + }) | ||
| 62 | +} | ||
| 63 | + | ||
| 64 | +/// Signs `claims` with the instance's own key. | ||
| 65 | +async fn mint(state: &AppState, claims: &Value) -> String { | ||
| 66 | + signing::sign(&state.store, &state.key, claims) | ||
| 67 | + .await | ||
| 68 | + .expect("token") | ||
| 69 | +} | ||
| 70 | + | ||
| 71 | +/// Sends a GET with a bearer token through the whole router: status, headers and body text. | ||
| 72 | +async fn get(state: &AppState, path: &str, token: &str) -> (StatusCode, http::HeaderMap, String) { | ||
| 73 | + let request = http::Request::get(path) | ||
| 74 | + .header(AUTHORIZATION, format!("Bearer {token}")) | ||
| 75 | + .body(Body::empty()) | ||
| 76 | + .expect("request"); | ||
| 77 | + let response = router(state.clone()).handle(request).await; | ||
| 78 | + let status = response.status(); | ||
| 79 | + let headers = response.headers().clone(); | ||
| 80 | + let bytes = to_bytes(response.into_body(), 1024 * 1024) | ||
| 81 | + .await | ||
| 82 | + .expect("body"); | ||
| 83 | + ( | ||
| 84 | + status, | ||
| 85 | + headers, | ||
| 86 | + String::from_utf8_lossy(&bytes).into_owned(), | ||
| 87 | + ) | ||
| 88 | +} | ||
| 89 | + | ||
| 90 | +#[tokio::test] | ||
| 91 | +async fn a_user_access_token_is_refused_on_the_directory() { | ||
| 92 | + let f = fixture().await; | ||
| 93 | + // A person's access token: their id as `sub`, a session as `sid`, and no `svc`. | ||
| 94 | + let claims = json!({ | ||
| 95 | + "iss": f.state.config.base_url, | ||
| 96 | + "sub": new_id(), | ||
| 97 | + "aud": "im", | ||
| 98 | + "azp": f.client.id, | ||
| 99 | + "scope": "openid profile", | ||
| 100 | + "sid": new_id(), | ||
| 101 | + "iat": unix_now(), | ||
| 102 | + "exp": unix_now() + 600, | ||
| 103 | + }); | ||
| 104 | + let token = mint(&f.state, &claims).await; | ||
| 105 | + let (status, headers, _) = get(&f.state, "/api/v1/directory", &token).await; | ||
| 106 | + assert_eq!(status, StatusCode::UNAUTHORIZED); | ||
| 107 | + assert_eq!(headers[WWW_AUTHENTICATE], "Bearer error=\"invalid_token\""); | ||
| 108 | +} | ||
| 109 | + | ||
| 110 | +#[tokio::test] | ||
| 111 | +async fn a_token_for_another_audience_is_refused() { | ||
| 112 | + let f = fixture().await; | ||
| 113 | + let claims = machine_claims(&f.state, &f.client, "in", "directory.read"); | ||
| 114 | + let token = mint(&f.state, &claims).await; | ||
| 115 | + let (status, _, _) = get(&f.state, "/api/v1/directory", &token).await; | ||
| 116 | + assert_eq!(status, StatusCode::UNAUTHORIZED); | ||
| 117 | +} | ||
| 118 | + | ||
| 119 | +#[tokio::test] | ||
| 120 | +async fn a_token_without_the_directory_scope_gets_403() { | ||
| 121 | + let f = fixture().await; | ||
| 122 | + let claims = machine_claims(&f.state, &f.client, "im", "files.service"); | ||
| 123 | + let token = mint(&f.state, &claims).await; | ||
| 124 | + let (status, headers, body) = get(&f.state, "/api/v1/directory", &token).await; | ||
| 125 | + assert_eq!(status, StatusCode::FORBIDDEN); | ||
| 126 | + assert_eq!( | ||
| 127 | + headers[WWW_AUTHENTICATE], | ||
| 128 | + "Bearer error=\"insufficient_scope\"" | ||
| 129 | + ); | ||
| 130 | + assert!(body.contains("insufficient_scope"), "{body}"); | ||
| 131 | +} | ||
| 132 | + | ||
| 133 | +#[tokio::test] | ||
| 134 | +async fn a_cursor_from_the_future_gets_a_resync_and_the_stream_ends() { | ||
| 135 | + let f = fixture().await; | ||
| 136 | + let claims = machine_claims(&f.state, &f.client, "im", "directory.read"); | ||
| 137 | + let token = mint(&f.state, &claims).await; | ||
| 138 | + let (status, _, body) = get(&f.state, "/api/v1/directory/stream?cursor=999", &token).await; | ||
| 139 | + assert_eq!(status, StatusCode::OK); | ||
| 140 | + assert!(body.contains("event: resync"), "{body}"); | ||
| 141 | + assert!(!body.contains("event: member"), "{body}"); | ||
| 142 | +} | ||
| 143 | + | ||
| 144 | +#[tokio::test] | ||
| 145 | +async fn a_photo_path_with_an_encoded_slash_is_not_found() { | ||
| 146 | + let f = fixture().await; | ||
| 147 | + let claims = machine_claims(&f.state, &f.client, "im", "directory.read"); | ||
| 148 | + let token = mint(&f.state, &claims).await; | ||
| 149 | + let (status, _, _) = get( | ||
| 150 | + &f.state, | ||
| 151 | + "/api/v1/people/..%2f..%2fetc%2fpasswd/photo", | ||
| 152 | + &token, | ||
| 153 | + ) | ||
| 154 | + .await; | ||
| 155 | + assert_eq!(status, StatusCode::NOT_FOUND); | ||
| 156 | +} | ||
| 157 | + | ||
| 158 | +#[tokio::test] | ||
| 159 | +async fn a_token_of_a_disabled_client_is_refused() { | ||
| 160 | + let f = fixture().await; | ||
| 161 | + let claims = machine_claims(&f.state, &f.client, "im", "directory.read"); | ||
| 162 | + let token = mint(&f.state, &claims).await; | ||
| 163 | + assert!( | ||
| 164 | + f.state | ||
| 165 | + .store | ||
| 166 | + .disable_client(&f.client.id) | ||
| 167 | + .await | ||
| 168 | + .expect("disable") | ||
| 169 | + ); | ||
| 170 | + let (status, _, _) = get(&f.state, "/api/v1/directory", &token).await; | ||
| 171 | + assert_eq!(status, StatusCode::UNAUTHORIZED); | ||
| 172 | +} | ||
crates/im-web/src/boot.rsmodified+17 -0
| @@ -20,6 +20,7 @@ use tokio::sync::watch; | |||
| 20 | use topcoat::cookie::RouterBuilderCookieExt; | 20 | use topcoat::cookie::RouterBuilderCookieExt; |
| 21 | use topcoat::router::{BodyLimit, Router, RouterBuilderDiscoverExt, RouterService}; | 21 | use topcoat::router::{BodyLimit, Router, RouterBuilderDiscoverExt, RouterService}; |
| 22 | 22 | ||
| 23 | +use crate::api::directory::StreamSlots; | ||
| 23 | use crate::backchannel; | 24 | use crate::backchannel; |
| 24 | use crate::live::LiveHub; | 25 | use crate::live::LiveHub; |
| 25 | use crate::oidc::signing; | 26 | use crate::oidc::signing; |
| @@ -27,6 +28,7 @@ use crate::pages::not_found::NotFoundLayer; | |||
| 27 | use crate::pages::profile::PHOTO_ROUTE; | 28 | use crate::pages::profile::PHOTO_ROUTE; |
| 28 | use crate::security::{self, SecurityHeaders}; | 29 | use crate::security::{self, SecurityHeaders}; |
| 29 | use crate::state::AppState; | 30 | use crate::state::AppState; |
| 31 | +use crate::sweeper; | ||
| 30 | use crate::throttle::Throttle; | 32 | use crate::throttle::Throttle; |
| 31 | 33 | ||
| 32 | /// Name of the instance key file inside the data directory. | 34 | /// Name of the instance key file inside the data directory. |
| @@ -76,6 +78,10 @@ pub async fn serve(config_path: &Path) -> im_core::Result<()> { | |||
| 76 | 78 | ||
| 77 | // One stop flag. The signal task sets it; the server watches it and then drains. | 79 | // One stop flag. The signal task sets it; the server watches it and then drains. |
| 78 | let (stop_tx, stop_rx) = watch::channel(false); | 80 | let (stop_tx, stop_rx) = watch::channel(false); |
| 81 | + let state = AppState { | ||
| 82 | + stop: stop_rx.clone(), | ||
| 83 | + ..state | ||
| 84 | + }; | ||
| 79 | tokio::spawn(async move { | 85 | tokio::spawn(async move { |
| 80 | shutdown_signal().await; | 86 | shutdown_signal().await; |
| 81 | tracing::info!("shutdown signal received"); | 87 | tracing::info!("shutdown signal received"); |
| @@ -88,6 +94,7 @@ pub async fn serve(config_path: &Path) -> im_core::Result<()> { | |||
| 88 | state.config.base_url.clone(), | 94 | state.config.base_url.clone(), |
| 89 | stop_rx.clone(), | 95 | stop_rx.clone(), |
| 90 | ); | 96 | ); |
| 97 | + let sweeper_task = sweeper::spawn(state.store.clone(), stop_rx.clone()); | ||
| 91 | 98 | ||
| 92 | topcoat::serve_until( | 99 | topcoat::serve_until( |
| 93 | listener, | 100 | listener, |
| @@ -97,6 +104,7 @@ pub async fn serve(config_path: &Path) -> im_core::Result<()> { | |||
| 97 | .await?; | 104 | .await?; |
| 98 | let _ = signing_worker.await; | 105 | let _ = signing_worker.await; |
| 99 | let _ = backchannel_worker.await; | 106 | let _ = backchannel_worker.await; |
| 107 | + let _ = sweeper_task.await; | ||
| 100 | tracing::info!("im stopped"); | 108 | tracing::info!("im stopped"); |
| 101 | Ok(()) | 109 | Ok(()) |
| 102 | } | 110 | } |
| @@ -119,12 +127,19 @@ pub(crate) async fn open_state(config: Config) -> im_core::Result<AppState> { | |||
| 119 | let key = secret::load_or_create_key(&data_dir.join(KEY_FILE))?; | 127 | let key = secret::load_or_create_key(&data_dir.join(KEY_FILE))?; |
| 120 | let store = Store::open(&config.database).await?; | 128 | let store = Store::open(&config.database).await?; |
| 121 | signing::maintain(&store, &key).await?; | 129 | signing::maintain(&store, &key).await?; |
| 130 | + // im is in its own switcher list. The row follows the configured origin at every boot. | ||
| 131 | + store | ||
| 132 | + .upsert_home_service("Account", &config.base_url) | ||
| 133 | + .await?; | ||
| 122 | Ok(AppState { | 134 | Ok(AppState { |
| 123 | config: Arc::new(config), | 135 | config: Arc::new(config), |
| 124 | store, | 136 | store, |
| 125 | key: Arc::new(key), | 137 | key: Arc::new(key), |
| 126 | live: Arc::new(LiveHub::default()), | 138 | live: Arc::new(LiveHub::default()), |
| 127 | throttle: Arc::new(Throttle::default()), | 139 | throttle: Arc::new(Throttle::default()), |
| 140 | + stream_slots: Arc::new(StreamSlots::default()), | ||
| 141 | + // Replaced by the stop flag of `serve` before any listener starts. The CLI never serves. | ||
| 142 | + stop: watch::channel(false).1, | ||
| 128 | }) | 143 | }) |
| 129 | } | 144 | } |
| 130 | 145 | ||
| @@ -205,6 +220,8 @@ mod tests { | |||
| 205 | key: Arc::new(key), | 220 | key: Arc::new(key), |
| 206 | live: Arc::new(LiveHub::default()), | 221 | live: Arc::new(LiveHub::default()), |
| 207 | throttle: Arc::new(Throttle::default()), | 222 | throttle: Arc::new(Throttle::default()), |
| 223 | + stream_slots: Arc::new(StreamSlots::default()), | ||
| 224 | + stop: watch::channel(false).1, | ||
| 208 | }; | 225 | }; |
| 209 | (dir, state) | 226 | (dir, state) |
| 210 | } | 227 | } |
crates/im-web/src/main.rsmodified+2 -0
| @@ -4,6 +4,7 @@ | |||
| 4 | //! OpenID Connect clients (`cli.rs`). `im admin ...` is the operator command line, which is not built yet. The configuration file is the `--config` path, | 4 | //! OpenID Connect clients (`cli.rs`). `im admin ...` is the operator command line, which is not built yet. The configuration file is the `--config` path, |
| 5 | //! then `IM_CONFIG`, then `config/im.toml`. Exit status 0 is success, 1 a failure, 2 a usage error. | 5 | //! then `IM_CONFIG`, then `config/im.toml`. Exit status 0 is success, 1 a failure, 2 a usage error. |
| 6 | 6 | ||
| 7 | +mod api; | ||
| 7 | mod assets; | 8 | mod assets; |
| 8 | mod audit; | 9 | mod audit; |
| 9 | mod auth; | 10 | mod auth; |
| @@ -18,6 +19,7 @@ mod oidc; | |||
| 18 | mod pages; | 19 | mod pages; |
| 19 | mod security; | 20 | mod security; |
| 20 | mod state; | 21 | mod state; |
| 22 | +mod sweeper; | ||
| 21 | mod throttle; | 23 | mod throttle; |
| 22 | mod views; | 24 | mod views; |
| 23 | 25 | ||
crates/im-web/src/oidc/userinfo.rsmodified+1 -1
| @@ -85,7 +85,7 @@ async fn userinfo(cx: &Cx) -> Result<Response> { | |||
| 85 | } | 85 | } |
| 86 | 86 | ||
| 87 | /// The token of a `Bearer` authorization header, or `None`. | 87 | /// The token of a `Bearer` authorization header, or `None`. |
| 88 | -fn bearer(value: Option<&HeaderValue>) -> Option<&str> { | 88 | +pub(crate) fn bearer(value: Option<&HeaderValue>) -> Option<&str> { |
| 89 | let (scheme, token) = value?.to_str().ok()?.split_once(' ')?; | 89 | let (scheme, token) = value?.to_str().ok()?.split_once(' ')?; |
| 90 | (scheme.eq_ignore_ascii_case("bearer") && !token.is_empty()).then_some(token) | 90 | (scheme.eq_ignore_ascii_case("bearer") && !token.is_empty()).then_some(token) |
| 91 | } | 91 | } |
crates/im-web/src/state.rsmodified+6 -0
| @@ -4,7 +4,9 @@ use std::sync::Arc; | |||
| 4 | 4 | ||
| 5 | use im_core::config::Config; | 5 | use im_core::config::Config; |
| 6 | use im_core::store::Store; | 6 | use im_core::store::Store; |
| 7 | +use tokio::sync::watch; | ||
| 7 | 8 | ||
| 9 | +use crate::api::directory::StreamSlots; | ||
| 8 | use crate::live::LiveHub; | 10 | use crate::live::LiveHub; |
| 9 | use crate::throttle::Throttle; | 11 | use crate::throttle::Throttle; |
| 10 | 12 | ||
| @@ -21,4 +23,8 @@ pub struct AppState { | |||
| 21 | pub live: Arc<LiveHub>, | 23 | pub live: Arc<LiveHub>, |
| 22 | /// Failed sign-in and second-factor counters. | 24 | /// Failed sign-in and second-factor counters. |
| 23 | pub throttle: Arc<Throttle>, | 25 | pub throttle: Arc<Throttle>, |
| 26 | + /// The open directory streams of each machine client. | ||
| 27 | + pub stream_slots: Arc<StreamSlots>, | ||
| 28 | + /// Set when the process is stopping. Long-lived streams end when it is, so the server can drain. | ||
| 29 | + pub stop: watch::Receiver<bool>, | ||
| 24 | } | 30 | } |
crates/im-web/src/sweeper.rsadded+66 -0
| @@ -0,0 +1,66 @@ | |||
| 1 | +//! The sweeper (architecture section 8): once at boot and then hourly, it removes what has expired. | ||
| 2 | +//! | ||
| 3 | +//! - browser sessions past their expiry, with their back-channel logout jobs queued first; | ||
| 4 | +//! - authorization codes that expired more than a day ago (a day is kept so that a reused code is still | ||
| 5 | +//! recognised as reuse, which revokes the tokens it issued); | ||
| 6 | +//! - refresh tokens past their expiry; | ||
| 7 | +//! - directory change rows older than 30 days (a cursor older than the oldest row gets `resync`). | ||
| 8 | +//! | ||
| 9 | +//! Each step runs on its own: one failing step is logged and does not stop the others. | ||
| 10 | + | ||
| 11 | +use std::time::Duration; | ||
| 12 | + | ||
| 13 | +use im_core::store::Store; | ||
| 14 | +use im_core::time::{now_stamp, stamp_before, stamp_minus}; | ||
| 15 | +use tokio::sync::watch; | ||
| 16 | + | ||
| 17 | +/// The time between two sweeps. | ||
| 18 | +const EVERY: Duration = Duration::from_secs(60 * 60); | ||
| 19 | + | ||
| 20 | +/// How long a directory change row is kept (contracts 3.2 and architecture section 3). | ||
| 21 | +const DIRECTORY_KEEP: Duration = Duration::from_secs(30 * 24 * 60 * 60); | ||
| 22 | + | ||
| 23 | +/// How long an expired authorization code is kept, so a reuse is still seen as reuse. | ||
| 24 | +const CODE_KEEP: Duration = Duration::from_secs(24 * 60 * 60); | ||
| 25 | + | ||
| 26 | +/// Starts the sweeper. It runs until `stop` is set. | ||
| 27 | +pub fn spawn(store: Store, mut stop: watch::Receiver<bool>) -> tokio::task::JoinHandle<()> { | ||
| 28 | + tokio::spawn(async move { | ||
| 29 | + loop { | ||
| 30 | + sweep_once(&store).await; | ||
| 31 | + tokio::select! { | ||
| 32 | + () = tokio::time::sleep(EVERY) => {} | ||
| 33 | + _ = stop.wait_for(|stopped| *stopped) => return, | ||
| 34 | + } | ||
| 35 | + } | ||
| 36 | + }) | ||
| 37 | +} | ||
| 38 | + | ||
| 39 | +/// One pass over every table. Failures are logged per step. | ||
| 40 | +pub async fn sweep_once(store: &Store) { | ||
| 41 | + let now = now_stamp(); | ||
| 42 | + match store.sweep_expired_sessions().await { | ||
| 43 | + Ok(0) => {} | ||
| 44 | + Ok(count) => tracing::info!(count, "sweeper: expired sessions removed"), | ||
| 45 | + Err(error) => tracing::error!(error = %error, "sweeper: sessions"), | ||
| 46 | + } | ||
| 47 | + let codes_before = stamp_minus(&now, CODE_KEEP).unwrap_or_else(|| now.clone()); | ||
| 48 | + match store.sweep_auth_codes(&codes_before).await { | ||
| 49 | + Ok(0) => {} | ||
| 50 | + Ok(count) => tracing::info!(count, "sweeper: expired authorization codes removed"), | ||
| 51 | + Err(error) => tracing::error!(error = %error, "sweeper: authorization codes"), | ||
| 52 | + } | ||
| 53 | + match store.sweep_refresh_tokens(&now).await { | ||
| 54 | + Ok(0) => {} | ||
| 55 | + Ok(count) => tracing::info!(count, "sweeper: expired refresh tokens removed"), | ||
| 56 | + Err(error) => tracing::error!(error = %error, "sweeper: refresh tokens"), | ||
| 57 | + } | ||
| 58 | + match store | ||
| 59 | + .prune_directory_changes(&stamp_before(DIRECTORY_KEEP)) | ||
| 60 | + .await | ||
| 61 | + { | ||
| 62 | + Ok(0) => {} | ||
| 63 | + Ok(count) => tracing::info!(count, "sweeper: old directory changes removed"), | ||
| 64 | + Err(error) => tracing::error!(error = %error, "sweeper: directory changes"), | ||
| 65 | + } | ||
| 66 | +} | ||