diff --git a/Cargo.lock b/Cargo.lock index 7ac27f5..170cfa1 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1874,6 +1874,27 @@ dependencies = [ "icu_properties", ] +[[package]] +name = "im-client" +version = "0.1.0" +source = "git+https://github.com/DizeyLab/im?rev=f7b2081#f7b208171820ca309b10043c6e86de12b81f3826" +dependencies = [ + "base64 0.22.1", + "chacha20poly1305", + "rand 0.10.2", + "reqwest", + "rsa", + "serde", + "serde_json", + "sha2 0.10.9", + "sha2 0.11.0", + "subtle", + "thiserror", + "time", + "tokio", + "topcoat", +] + [[package]] name = "image" version = "0.25.10" @@ -1967,6 +1988,7 @@ dependencies = [ "http", "http-body", "http-body-util", + "im-client", "in-client", "in-core", "serde", diff --git a/Cargo.toml b/Cargo.toml index 5bde1e4..ee57fd4 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -11,6 +11,12 @@ repository = "https://github.com/DizeyLab/in" [workspace.dependencies] in-core = { path = "crates/in-core", default-features = false } in-client = { path = "crates/in-client" } +# The identity-directory SDK, split out of im: the directory list, the +# photo proxy and the live change feed, authenticated with the same client +# pair the OIDC side already holds. The OIDC half stays gated off — this +# app's own `in-client` fork keeps the auth routes, and two route sets in +# one binary collide. +im-client = { git = "https://github.com/DizeyLab/im", rev = "f7b2081", default-features = false } serde = { version = "1.0.229", features = ["derive"] } serde_json = "1.0.145" thiserror = "2.0.20" diff --git a/crates/in-client/src/lib.rs b/crates/in-client/src/lib.rs index 7b0812e..9209c1b 100644 --- a/crates/in-client/src/lib.rs +++ b/crates/in-client/src/lib.rs @@ -151,71 +151,6 @@ pub async fn current_user(cx: &Cx) -> Option { } } -/// The person's profile photo from im, if im has one. `None` on 404 and on -/// anything else that is not the bytes — a dropped connection, a body that -/// will not read, a reply without a mime — because a missing face must never -/// fail the page around it: the caller renders its initials instead. -/// -/// Authenticated as the app, not the browser: `Authorization: Basic -/// base64(client_id ":" client_secret)` against im's `/photo/{user_id}`, -/// the same credentials the introspection round-trip posts with. -pub async fn photo_for(cx: &Cx, user_id: &str) -> Option<(Vec, String)> { - let state = client(cx); - let reply = state - .http - .get(format!("{}/photo/{user_id}", state.config.issuer)) - .basic_auth(&state.config.client_id, Some(&state.config.client_secret)) - .send() - .await - .ok()?; - if !reply.status().is_success() { - return None; - } - let mime = reply - .headers() - .get(reqwest::header::CONTENT_TYPE)? - .to_str() - .ok()? - .to_string(); - let bytes = reply.bytes().await.ok()?.to_vec(); - Some((bytes, mime)) -} - -/// One entry of im's directory: the stable subject, the address, the -/// display name, and whether im calls the person an admin — exactly what -/// mirroring the directory into local user rows needs. -#[derive(Debug, Clone, Deserialize)] -pub struct DirectoryMember { - pub sub: String, - pub email: String, - pub name: String, - pub admin: bool, -} - -/// im's family phonebook: every person im knows, fetched as the app -/// (`Authorization: Basic base64(client_id ":" client_secret)`, the same -/// credentials the photo route and the introspection round-trip take) from -/// `{issuer}/directory`. Only a registered app gets an answer at all. -/// -/// `None` on anything that is not a readable list — a refused pair, a -/// dropped connection, a body that is not the array — because a missed -/// beat must never look like an empty directory: the caller keeps the -/// rows it has and asks again next time. -pub async fn directory(cx: &Cx) -> Option> { - let state = client(cx); - let reply = state - .http - .get(format!("{}/directory", state.config.issuer)) - .basic_auth(&state.config.client_id, Some(&state.config.client_secret)) - .send() - .await - .ok()?; - if !reply.status().is_success() { - return None; - } - reply.json().await.ok() -} - /// One entry of im's family list: the word the switcher renders, the /// human label for its title, and the service's base URL — the shape im's /// `/family` answers with. @@ -355,6 +290,9 @@ async fn introspect(state: &InClient, token: &str) -> Introspected { sub: sub.to_string(), email: email.to_string(), name: name.to_string(), + // Additive on im's answer: an im predating the field reads as + // "no photo stamp known", which only softens caching. + photo_version: answer["photo_version"].as_u64().unwrap_or(0), }, exp, ) @@ -366,6 +304,10 @@ pub struct User { pub sub: String, pub email: String, pub name: String, + /// How many times the person's photo has changed in im — the `?v=` the + /// app's avatar route caches by. Mirrored out of introspection; `0` + /// reads as "no stamp known". + pub photo_version: u64, } // --------------------------------------------------------------------------- diff --git a/crates/in-core/migrations/0006_photo_version.sql b/crates/in-core/migrations/0006_photo_version.sql new file mode 100644 index 0000000..e611f44 --- /dev/null +++ b/crates/in-core/migrations/0006_photo_version.sql @@ -0,0 +1,12 @@ +-- The stamp that lets a proxied face be cached hard and still arrive fresh. +-- +-- `user.photo_version` counts how many times the person's photo has changed +-- in im — the identity directory's word, mirrored here by the same passes +-- that mirror email, name and admin. The avatar route turns it into the +-- `ETag` and the `/avatar/{id}?v=` stamp, so a changed photo is a changed +-- URL and a browser never pins an old face behind a year of `immutable`. +-- `0` is "no photo known"; the DEFAULT is the backfill, SQLite filling every +-- existing row with it as the column is added. Databases already carrying +-- the column never see this file applied piecemeal — they reach the declared +-- shape through `in reconcile`, whose copy map backfills the same value. +ALTER TABLE user ADD COLUMN photo_version INTEGER NOT NULL DEFAULT 0; diff --git a/crates/in-core/src/live.rs b/crates/in-core/src/live.rs index 69717f1..31bee99 100644 --- a/crates/in-core/src/live.rs +++ b/crates/in-core/src/live.rs @@ -24,6 +24,11 @@ pub enum Topic { Trash(String), /// Shares: links created or revoked, per-person grants added or removed. Shares(String), + /// A member's identity as im tells it — address, display name, admin + /// flag, photo version. Not per-user data: a person's face renders in + /// every signed-in topbar, so every reader may hear that some member + /// moved and re-fetch through the ordinary gated route. + Profile(String), /// Users, quotas, disablements — the admin's surface. Admin(String), } @@ -36,6 +41,7 @@ impl Topic { Topic::Library(_) => "library", Topic::Trash(_) => "trash", Topic::Shares(_) => "shares", + Topic::Profile(_) => "profile", Topic::Admin(_) => "admin", } } @@ -44,7 +50,8 @@ impl Topic { /// is its own id — or, for [`Topic::Admin`], when it is an admin. pub fn id(&self) -> &str { match self { - Topic::Library(id) | Topic::Trash(id) | Topic::Shares(id) | Topic::Admin(id) => id, + Topic::Library(id) | Topic::Trash(id) | Topic::Shares(id) | Topic::Profile(id) + | Topic::Admin(id) => id, } } } diff --git a/crates/in-core/src/store/mod.rs b/crates/in-core/src/store/mod.rs index 2e41921..6865b10 100644 --- a/crates/in-core/src/store/mod.rs +++ b/crates/in-core/src/store/mod.rs @@ -88,6 +88,11 @@ pub struct User { pub email: String, pub display_name: String, pub admin: bool, + /// How many times the person's photo has changed in im — the stamp the + /// avatar route turns into its `ETag` and `?v=`. Mirrored from the + /// identity directory by the same passes that mirror address and name; + /// `0` reads as "no photo known". + pub photo_version: u64, pub disabled: bool, /// The person's ceiling, in bytes. Set at provisioning, changed by an /// admin afterwards. @@ -375,14 +380,22 @@ pub trait Store: 'static + Send + Sync { /// Every account, oldest first — the admin's settings screen. async fn users(&self) -> Result>; - /// JIT upsert on OIDC login: unknown sub inserts (first user ever gets + /// JIT upsert on OIDC login and on every identity-directory sight: + /// unknown sub inserts (first-ever row with no provider word gets /// admin=1, quota = default_quota_bytes), known sub refreshes - /// email/display_name and stamps last_seen_at. Returns the row. + /// email/display_name/photo_version and stamps last_seen_at. `admin` + /// is the provider's word when the caller carries one — `Some` from the + /// directory and its stream, `None` from a claims-only introspection — + /// and absent it, the row's flag stands. A change to any mirrored + /// field announces [`Topic::Profile`](crate::live::Topic); a fresh row + /// also announces [`Topic::Admin`](crate::live::Topic). Returns the row. async fn provision_user( &self, sub: &str, email: &str, display_name: &str, + admin: Option, + photo_version: u64, default_quota_bytes: u64, ) -> Result; diff --git a/crates/in-core/src/store/reconcile.rs b/crates/in-core/src/store/reconcile.rs index c6be40b..40b11b9 100644 --- a/crates/in-core/src/store/reconcile.rs +++ b/crates/in-core/src/store/reconcile.rs @@ -204,7 +204,7 @@ struct TableMap { /// Builds the explicit column map. Unchanged tables map every column to its /// old self; the user table carries the migration-specific expressions for -/// `ui`, `theme` and `language`, and the file table one for +/// `ui`, `theme`, `language` and `photo_version`, and the file table one for /// `download_count`: a database old enough to predate a column starts on the /// schema's own default rather than on an empty string, which no writer /// would ever store and no reader would ever honour. The share-link table @@ -218,6 +218,7 @@ fn build_maps( old_has_language: bool, old_has_download_count: bool, old_has_password_hash: bool, + old_has_photo_version: bool, ) -> Vec { vec![ TableMap { @@ -249,6 +250,11 @@ fn build_maps( } else { ("language", "'en'".into()) }); + columns.push(if old_has_photo_version { + ("photo_version", "old.photo_version".into()) + } else { + ("photo_version", "0".into()) + }); columns }, }, @@ -424,12 +430,14 @@ async fn copy_data(old_conn: &Connection, new_conn: &Connection, path: &str) -> let old_has_language = old_has_column(old_conn, "user", "language").await?; let old_has_download_count = old_has_column(old_conn, "file", "download_count").await?; let old_has_password_hash = old_has_column(old_conn, "share_link", "password_hash").await?; + let old_has_photo_version = old_has_column(old_conn, "user", "photo_version").await?; let maps = build_maps( old_has_ui, old_has_theme, old_has_language, old_has_download_count, old_has_password_hash, + old_has_photo_version, ); validate_maps(new_conn, &maps).await?; diff --git a/crates/in-core/src/store/schema.rs b/crates/in-core/src/store/schema.rs index b3763ad..c09a480 100644 --- a/crates/in-core/src/store/schema.rs +++ b/crates/in-core/src/store/schema.rs @@ -19,6 +19,7 @@ pub(crate) const MIGRATIONS: &[&str] = &[ include_str!("../../migrations/0003_preferences.sql"), include_str!("../../migrations/0004_downloads_settings.sql"), include_str!("../../migrations/0005_link_password.sql"), + include_str!("../../migrations/0006_photo_version.sql"), ]; /// The whole declared schema — every migration applied in order — as one diff --git a/crates/in-core/src/store/turso_store.rs b/crates/in-core/src/store/turso_store.rs index 64f0348..6870920 100644 --- a/crates/in-core/src/store/turso_store.rs +++ b/crates/in-core/src/store/turso_store.rs @@ -36,7 +36,7 @@ const UPLOADS_DIR: &str = "uploads"; /// row wears `failed` rather than pinning memory the size of the file. const THUMB_SOURCE_CAP: u64 = 64 * 1024 * 1024; -const USER_COLUMNS: &str = "id, oidc_sub, email, display_name, admin, disabled, quota_bytes, used_bytes, ui, created_at, last_seen_at, theme, language"; +const USER_COLUMNS: &str = "id, oidc_sub, email, display_name, admin, disabled, quota_bytes, used_bytes, ui, created_at, last_seen_at, theme, language, photo_version"; const FOLDER_COLUMNS: &str = "id, owner_id, parent_id, name, created_at, deleted_at"; const FILE_COLUMNS: &str = "id, owner_id, folder_id, name, mime, size_bytes, thumb_state, created_at, updated_at, deleted_at, download_count"; const LINK_COLUMNS: &str = "id, token_hash, kind, target_id, created_by, can_download, created_at, expires_at, revoked_at, password_hash"; @@ -962,6 +962,7 @@ fn user_from(row: &Row) -> Result { language: text(row, 12)?, created_at: parse_stamp(&text(row, 9)?)?, last_seen_at: opt_stamp(row, 10)?, + photo_version: row.get::(13).map_err(backend)?.max(0) as u64, }) } @@ -1081,6 +1082,8 @@ impl Store for TursoStore { sub: &str, email: &str, display_name: &str, + admin: Option, + photo_version: u64, default_quota_bytes: u64, ) -> Result { let email = fold_email(email); @@ -1095,15 +1098,25 @@ impl Store for TursoStore { let sql = format!("SELECT {USER_COLUMNS} FROM user WHERE oidc_sub = ?1"); let mut rows = tx.query(&sql, params![sub]).await.map_err(backend)?; if let Some(row) = rows.next().await.map_err(backend)? { - let user = user_from(&row)?; + let known = user_from(&row)?; drop(rows); - // A returning person: the provider may have a new address or a - // new name for them, and the row follows the provider — but the - // admin flag and the quota are ours, and this write touches - // neither. + // A returning person: the row follows the provider — address, + // name, photo stamp, and the admin flag when this sight carries + // the directory's word on it. The quota is ours and this write + // touches neither it nor a flag nobody spoke about. + let admin_changed = admin.is_some_and(|flag| flag != known.admin); tx.execute( - "UPDATE user SET email = ?1, display_name = ?2, last_seen_at = ?3 WHERE id = ?4", - params![email, display_name, now_text()?, user.id], + "UPDATE user SET email = ?1, display_name = ?2, photo_version = ?3, \ + admin = CASE WHEN ?4 IS NULL THEN admin ELSE ?4 END, last_seen_at = ?5 \ + WHERE id = ?6", + params![ + email, + display_name, + photo_version as i64, + admin.map(|flag| if flag { 1 } else { 0 }), + now_text()?, + known.id + ], ) .await .map_err(backend)?; @@ -1116,6 +1129,16 @@ impl Store for TursoStore { let user = user_from(&row)?; drop(back); tx.commit().await.map_err(backend)?; + // A mirrored field moved: every signed-in topbar may want the + // new face or name. A mere last-seen stamp announces nothing — + // a quiet return is not news. + if user.email != known.email + || user.display_name != known.display_name + || user.photo_version != known.photo_version + || admin_changed + { + self.announce([Topic::Profile(user.id.clone())]); + } return Ok(user); } drop(rows); @@ -1128,16 +1151,19 @@ impl Store for TursoStore { None => 0, }; drop(count); - // The first account ever provisioned is the admin: there is no one - // else to make one, and a deployment with no admin is a deployment - // nobody can administer. - let admin = n == 0; + // The provider's word on the person is the admin flag when it has + // one; a sight with no directory behind it falls back to the + // bootstrap rule — the first account ever provisioned is the admin, + // because a deployment with no admin is a deployment nobody can + // administer. + let admin = admin.unwrap_or(n == 0); let id = Ulid::new().to_string(); let now = now_text()?; tx.execute( "INSERT INTO user (id, oidc_sub, email, display_name, admin, disabled, \ - quota_bytes, used_bytes, ui, theme, language, created_at, last_seen_at) \ - VALUES (?1, ?2, ?3, ?4, ?5, 0, ?6, 0, 'instrument', 'dark', 'en', ?7, ?7)", + quota_bytes, used_bytes, ui, theme, language, created_at, last_seen_at, \ + photo_version) \ + VALUES (?1, ?2, ?3, ?4, ?5, 0, ?6, 0, 'instrument', 'dark', 'en', ?7, ?7, ?8)", params![ id.clone(), sub, @@ -1145,7 +1171,8 @@ impl Store for TursoStore { display_name, if admin { 1 } else { 0 }, default_quota_bytes as i64, - now + now, + photo_version as i64 ], ) .await @@ -1165,10 +1192,12 @@ impl Store for TursoStore { let user = user_from(&row)?; drop(back); tx.commit().await.map_err(backend)?; - self.announce([Topic::Admin(user.id.clone())]); + self.announce([ + Topic::Admin(user.id.clone()), + Topic::Profile(user.id.clone()), + ]); Ok(user) } - async fn set_user_quota(&self, user_id: &str, quota_bytes: u64) -> Result<()> { let conn = self.conn.lock().await; let n = conn @@ -3600,13 +3629,7 @@ mod tests { let store = TursoStore::open(dir.path().join("in.db").to_str().unwrap(), Some(&storage)) .await .unwrap(); - let user = store - .provision_user( - "sub-alice", - "alice@example.com", - "Alice", - 1024 * 1024 * 1024, - ) + let user = store.provision_user("sub-alice", "alice@example.com", "Alice", None, 0, 1024 * 1024 * 1024) .await .unwrap(); @@ -3703,13 +3726,7 @@ mod tests { let store = TursoStore::open(dir.path().join("in.db").to_str().unwrap(), Some(&storage)) .await .unwrap(); - let user = store - .provision_user( - "sub-alice", - "alice@example.com", - "Alice", - 1024 * 1024 * 1024, - ) + let user = store.provision_user("sub-alice", "alice@example.com", "Alice", None, 0, 1024 * 1024 * 1024) .await .unwrap(); let file = store @@ -3745,13 +3762,7 @@ mod tests { let store = TursoStore::open(dir.path().join("in.db").to_str().unwrap(), Some(&storage)) .await .unwrap(); - let user = store - .provision_user( - "sub-alice", - "alice@example.com", - "Alice", - 1024 * 1024 * 1024, - ) + let user = store.provision_user("sub-alice", "alice@example.com", "Alice", None, 0, 1024 * 1024 * 1024) .await .unwrap(); let root = store.create_folder(&user.id, None, "root").await.unwrap(); @@ -3816,13 +3827,7 @@ mod tests { let store = TursoStore::open(dir.path().join("in.db").to_str().unwrap(), Some(&storage)) .await .unwrap(); - let user = store - .provision_user( - "sub-alice", - "alice@example.com", - "Alice", - 1024 * 1024 * 1024, - ) + let user = store.provision_user("sub-alice", "alice@example.com", "Alice", None, 0, 1024 * 1024 * 1024) .await .unwrap(); let session = store diff --git a/crates/in-core/tests/store.rs b/crates/in-core/tests/store.rs index 80fad34..a44cebe 100644 --- a/crates/in-core/tests/store.rs +++ b/crates/in-core/tests/store.rs @@ -71,15 +71,13 @@ impl Drop for Scratch { } async fn alice(store: &TursoStore) -> User { - store - .provision_user("sub-alice", "alice@example.com", "Alice", 1024 * 1024 * 1024) + store.provision_user("sub-alice", "alice@example.com", "Alice", None, 0, 1024 * 1024 * 1024) .await .unwrap() } async fn bob(store: &TursoStore) -> User { - store - .provision_user("sub-bob", "bob@example.com", "Bob", 1024 * 1024 * 1024) + store.provision_user("sub-bob", "bob@example.com", "Bob", None, 0, 1024 * 1024 * 1024) .await .unwrap() } @@ -140,8 +138,7 @@ async fn the_first_user_is_admin_and_sign_ins_refresh_the_row() { // A returning person keeps their id, admin flag and quota; the provider's // new address and name win, and the sighting is stamped. let again = scratch - .store - .provision_user("sub-alice", "alice@new.com", "Alice New", 1) + .store.provision_user("sub-alice", "alice@new.com", "Alice New", None, 0, 1) .await .unwrap(); assert_eq!(again.id, first.id); @@ -928,8 +925,7 @@ async fn per_person_shares_gate_visibility() { let user = alice(&scratch.store).await; let friend = bob(&scratch.store).await; let stranger = scratch - .store - .provision_user("sub-caro", "caro@example.com", "Caro", 1024) + .store.provision_user("sub-caro", "caro@example.com", "Caro", None, 0, 1024) .await .unwrap(); let file = scratch.store.insert_file(&user.id, None, "shared", b"data").await.unwrap(); @@ -1288,8 +1284,7 @@ async fn the_sweep_waits_for_a_writer_instead_of_deleting_its_file() { async fn email_lookup_folds_case() { let scratch = Scratch::open().await; let user = scratch - .store - .provision_user("sub-mixed", "Mixed@Example.COM", "Mixed", 1024) + .store.provision_user("sub-mixed", "Mixed@Example.COM", "Mixed", None, 0, 1024) .await .unwrap(); // Stored folded, found however it is asked. @@ -1526,7 +1521,7 @@ async fn add_share_user_needs_the_owner() { let scratch = Scratch::open().await; let user = alice(&scratch.store).await; let friend = bob(&scratch.store).await; - let stranger = scratch.store.provision_user("sub-caro", "caro@example.com", "Caro", 1024).await.unwrap(); + let stranger = scratch.store.provision_user("sub-caro", "caro@example.com", "Caro", None, 0, 1024).await.unwrap(); let file = scratch.store.insert_file(&user.id, None, "mine", b"data").await.unwrap(); // A stranger naming someone else's file is refused — and names no grant. assert!(matches!( @@ -1549,7 +1544,7 @@ async fn shares_for_target_lists_grants_for_the_owner() { let scratch = Scratch::open().await; let user = alice(&scratch.store).await; let friend = bob(&scratch.store).await; - let stranger = scratch.store.provision_user("sub-caro", "caro@example.com", "Caro", 1024).await.unwrap(); + let stranger = scratch.store.provision_user("sub-caro", "caro@example.com", "Caro", None, 0, 1024).await.unwrap(); let file = scratch.store.insert_file(&user.id, None, "mine", b"data").await.unwrap(); // No grants yet. assert!(scratch.store.shares_for_target(&user.id, ShareKind::File, &file.id).await.unwrap().is_empty()); diff --git a/crates/in-web/Cargo.toml b/crates/in-web/Cargo.toml index c6a6e7f..55bcb5a 100644 --- a/crates/in-web/Cargo.toml +++ b/crates/in-web/Cargo.toml @@ -21,6 +21,7 @@ topcoat = { version = "0.6.2", default-features = false, features = [ ] } in-core = { workspace = true, features = ["server"] } in-client.workspace = true +im-client.workspace = true serde.workspace = true serde_json.workspace = true time.workspace = true diff --git a/crates/in-web/src/avatar.rs b/crates/in-web/src/avatar.rs index 15515eb..069af4d 100644 --- a/crates/in-web/src/avatar.rs +++ b/crates/in-web/src/avatar.rs @@ -1,15 +1,25 @@ -//! The signed-in person's face, proxied from im. +//! Every provisioned member's face, proxied from im. //! -//! `GET /avatar/{user_id}` answers with im's photo bytes for the caller's own -//! id — anything else (another id, no photo, im unreachable) is the same 404, -//! and a browser without a session is refused outright. Served with the same -//! fnv1a ETag + immutable cache as im's own photo route, so the topbar's -//! `` revalidates rather than refetches. +//! `GET /avatar/{user_id}` answers with im's photo bytes for any member of +//! the workspace — one's own id or a coworker's: a person's face renders in +//! every signed-in topbar, so the gate is the session, not the id. im is +//! asked with the app's own credentials and always answers an image (a +//! member with no photo gets the default tile), so the only failures left +//! are im unreachable and an id no row names — the same empty answer a +//! browser without a photo shows initials for. A browser without a session +//! is refused outright. +//! +//! Caching is versioned, not content-hashed: the `ETag` is the row's +//! `photo_version` — im's own stamp, mirrored by the directory passes — and +//! a request whose `?v=` already matches the row is stamped +//! `private, max-age=31536000, immutable`, so a changed photo is a changed +//! URL and no browser pins an old face behind a year of cache. Any other +//! spelling of the address revalidates with `private, no-cache`. use topcoat::context::Cx; -use topcoat::router::request::headers as request_headers; +use topcoat::router::request::{headers as request_headers, uri}; use topcoat::router::{HeaderMap, HeaderValue, StatusCode, header, path_param, route}; -use crate::server::require_user; +use crate::server::{app, require_user}; path_param!(user_id); @@ -17,53 +27,68 @@ fn not_found() -> (StatusCode, HeaderMap, Vec) { (StatusCode::NOT_FOUND, HeaderMap::new(), Vec::new()) } -/// `GET /avatar/{user_id}`: im's photo for the caller, or the same not-found -/// a stranger would see — never a `403`, which would confirm the id belongs -/// to somebody else's account. +/// The `?v=` the request carries, if it carries one. +fn stamped_version(cx: &Cx) -> Option<&str> { + uri(cx).query()?.split('&').find_map(|pair| { + let (name, value) = pair.split_once('=')?; + (name == "v").then_some(value) + }) +} + +/// `GET /avatar/{user_id}`: im's photo for any provisioned member, or the +/// same not-found an unknown id gets — never a `403`, which would confirm +/// which ids exist. `?v=` equal to the row's `photo_version` is answered +/// from a year of `immutable`; anything else revalidates. #[route(GET "/avatar/{user_id}")] async fn avatar(cx: &Cx) -> topcoat::Result<(StatusCode, HeaderMap, Vec)> { let target: &str = path_param::(cx); - let user = match require_user(cx).await { - Ok(user) => user, + // The gate is the session: any signed-in browser may fetch any + // provisioned member's face, so the identity itself is not needed here. + if require_user(cx).await.is_err() { // An `` has no page to carry a refusal on; 401 names the fix // the way the live channel's does. - Err(_) => return Ok((StatusCode::UNAUTHORIZED, HeaderMap::new(), Vec::new())), - }; - // v1: one's own face only — anyone else's id reads exactly like no - // photo, so one account's face can never be probed through another's. - if target != user.id { - return Ok(not_found()); + return Ok((StatusCode::UNAUTHORIZED, HeaderMap::new(), Vec::new())); } - let Some((bytes, mime)) = in_client::photo_for(cx, &user.oidc_sub).await else { + // The row, not the caller's session, decides the stamp: any provisioned + // member's face is served, keyed by their own photo version. A store + // error folds into the same not-found as an unknown id — an `` has + // no better way to say either. + let Ok(Some(row)) = app(cx).store.user(target).await else { return Ok(not_found()); }; - let etag = format!("\"{:x}\"", crate::files::fnv1a(&bytes)); + let etag = format!("\"p{}\"", row.photo_version); + let fresh = stamped_version(cx) == Some(row.photo_version.to_string().as_str()); let mut headers = HeaderMap::new(); headers.insert( header::ETAG, - HeaderValue::from_str(&etag).unwrap_or(HeaderValue::from_static("\"0\"")), + HeaderValue::from_str(&etag).unwrap_or(HeaderValue::from_static("\"p0\"")), ); - // The bytes are im's to version and this URL carries no stamp of its - // own, so a changed photo may take up to a year to show — the price of - // proxying without a stamp channel, and the same trade the thumbnail - // route already makes. `private` because the route is gated and a shared - // proxy must not answer a stranger from another account's entry. headers.insert( header::CACHE_CONTROL, - HeaderValue::from_static("private, max-age=31536000, immutable"), - ); - headers.insert( - header::CONTENT_TYPE, - HeaderValue::from_str(&mime).unwrap_or(HeaderValue::from_static("application/octet-stream")), + HeaderValue::from_static(if fresh { + "private, max-age=31536000, immutable" + } else { + "private, no-cache" + }), ); - + // The stamp the browser holds is the row's own word: a match means the + // bytes behind it cannot have changed without the version moving, so im + // is not asked at all. let if_none_match = request_headers(cx) .get(header::IF_NONE_MATCH) .and_then(|value| value.to_str().ok()); if if_none_match == Some(etag.as_str()) { return Ok((StatusCode::NOT_MODIFIED, headers, Vec::new())); } + + let Ok((bytes, mime)) = app(cx).directory.photo(&row.oidc_sub).await else { + return Ok(not_found()); + }; + headers.insert( + header::CONTENT_TYPE, + HeaderValue::from_str(&mime).unwrap_or(HeaderValue::from_static("application/octet-stream")), + ); Ok((StatusCode::OK, headers, bytes)) } diff --git a/crates/in-web/src/layout.rs b/crates/in-web/src/layout.rs index 2909600..55da84f 100644 --- a/crates/in-web/src/layout.rs +++ b/crates/in-web/src/layout.rs @@ -90,7 +90,7 @@ pub(crate) async fn avatar(cx: &Cx, user: &User, extra: &str) -> Result { let class = format!("avatar avatar-tone-{tone} {extra}"); let name = user.display_name.clone(); let initials = initials_of(&user.display_name); - let src = format!("/avatar/{}", user.id); + let src = format!("/avatar/{}?v={}", user.id, user.photo_version); view! { cx => @@ -896,6 +896,7 @@ pub async fn live_script(cx: &Cx) -> Result { } \ function wanted(topic) { \ if (topic === 'resync') { return true; } \ + if (topic === 'profile') { return true; } \ var path = window.location.pathname; \ if (path.indexOf('/settings') === 0) { return topic === 'admin'; } \ if (path.indexOf('/shared') === 0) { return topic === 'shares'; } \ diff --git a/crates/in-web/src/live.rs b/crates/in-web/src/live.rs index f3dc44c..bf601b4 100644 --- a/crates/in-web/src/live.rs +++ b/crates/in-web/src/live.rs @@ -57,6 +57,12 @@ fn may_hear(topic: &Topic, me: &str, admin: bool) -> bool { if topic.id() == me { return true; } + // A member's profile is not per-user data: every signed-in topbar + // renders coworkers' faces and names, so every reader may hear that + // some member moved and re-fetch through the ordinary gated route. + if matches!(topic, Topic::Profile(_)) { + return true; + } matches!(topic, Topic::Admin(_)) && admin } @@ -157,3 +163,25 @@ async fn live(cx: &Cx) -> topcoat::Result { .keep_alive(KeepAlive::new()) .into_response(cx) } + +#[cfg(test)] +mod tests { + use super::*; + use crate::live::Topic; + + #[test] + fn a_profile_change_is_heard_by_every_signed_in_reader() { + // A coworker's face renders in every topbar, so a member's profile + // move is not per-user data: the reader it names and a stranger and + // an admin all hear it. What nobody hears is another person's drive. + let moved = Topic::Profile("member-id".to_string()); + assert!(may_hear(&moved, "member-id", false)); + assert!(may_hear(&moved, "someone-else", false)); + assert!(may_hear(&moved, "someone-else", true)); + assert!(!may_hear( + &Topic::Library("member-id".to_string()), + "someone-else", + false + )); + } +} diff --git a/crates/in-web/src/main.rs b/crates/in-web/src/main.rs index 847cf50..9e7e7c0 100644 --- a/crates/in-web/src/main.rs +++ b/crates/in-web/src/main.rs @@ -213,6 +213,17 @@ async fn main() { logout_back: config.public_origin(), }; + // The same client pair, pointed at im's identity directory: the roster + // the mirror below files, the photo bytes the avatar route proxies, and + // the live feed that makes both arrive without waiting for a beat. + let directory = im_client::directory::DirectoryClient::new( + config.oidc.issuer.clone(), + config.oidc.client_id.clone(), + config.oidc.client_secret.clone(), + ); + let default_quota_bytes = config.default_quota_bytes; + tokio::spawn(identity_sync(store.clone(), directory.clone(), default_quota_bytes)); + // The suite the switcher's wordmarks link to is im's to keep: im's // admin panel owns the list and `/family` serves it to registered // apps. This mirror is refreshed on the beat, first pass right away so @@ -260,6 +271,7 @@ async fn main() { config, shutdown: in_web::live::Shutdown(stopping), link_key: cookie_key, + directory, }) .app_context(in_client::LogoutBack(Arc::new(|cx: &Cx| { Box::pin(async move { Some(in_web::server::share_origin(cx).await) }) @@ -337,6 +349,82 @@ async fn shutdown_signal() { } } +/// The longest wait a run of directory failures earns before trying again. +const IDENTITY_BACKOFF_CAP: std::time::Duration = std::time::Duration::from_secs(30); + +/// Mirrors one member's identity into the local row: the JIT upsert that +/// keeps address, name, admin flag and photo stamp following im. The store +/// announces a `profile` change itself when a mirrored field moved, so the +/// only job left here is the write and its one log line when it fails. +async fn mirror_member( + store: &Arc, + member: &im_client::directory::DirectoryMember, + default_quota_bytes: u64, +) { + if let Err(problem) = store + .provision_user( + &member.sub, + &member.email, + &member.name, + Some(member.admin), + member.photo_version, + default_quota_bytes, + ) + .await + { + eprintln!("in: directory mirror of {}: {problem}", member.sub); + } +} + +/// Keeps the local user rows a live mirror of im's identity directory. +/// +/// The shape is one pass, one stream, repeat: a full `/directory` pass +/// files (or heals) every member row, then `/directory/live` carries each +/// change as it happens. When the stream ends — im restarting, or its +/// window closing — the loop simply runs the full pass again: a lagged +/// reader hears silence, not partial frames, so the re-list is what catches +/// it up, and the redial is the fast path again. A pass that fails backs +/// off a second, then doubles to the cap, resetting on the next answer. +/// Runs the whole life of the process; nothing here is worth keeping alive +/// past shutdown. +async fn identity_sync( + store: Arc, + client: im_client::directory::DirectoryClient, + default_quota_bytes: u64, +) { + let mut backoff = std::time::Duration::from_secs(1); + loop { + match client.directory().await { + Ok(members) => { + backoff = std::time::Duration::from_secs(1); + for member in &members { + mirror_member(&store, member, default_quota_bytes).await; + } + match client.open_stream().await { + Ok(mut stream) => { + while let Some(event) = stream.next().await { + match event { + Ok(im_client::directory::DirectoryEvent::Profile(member)) => { + mirror_member(&store, &member, default_quota_bytes).await; + } + // A network failure ends the stream; the full + // pass below re-lists before the redial. + Err(problem) => { + eprintln!("in: directory stream failed: {problem}"); + break; + } + } + } + } + Err(problem) => eprintln!("in: directory stream refused: {problem}"), + } + } + Err(problem) => eprintln!("in: directory pass failed: {problem}"), + } + tokio::time::sleep(backoff).await; + backoff = (backoff * 2).min(IDENTITY_BACKOFF_CAP); + } +} /// How often the suite list is re-fetched from im. Short enough that a /// service the admin adds over there shows up here before anyone goes /// looking for its wordmark, long enough that the two are not talking diff --git a/crates/in-web/src/server.rs b/crates/in-web/src/server.rs index d317f29..05ee1c6 100644 --- a/crates/in-web/src/server.rs +++ b/crates/in-web/src/server.rs @@ -41,6 +41,10 @@ pub struct App { /// database copy without the key file carries links that open but can /// no longer be re-viewed. pub link_key: in_core::store::secret::Key, + /// im's identity directory — the roster, the photo bytes and the live + /// change feed — authenticated with the same client pair the OIDC side + /// holds. Built once at boot; cheap to clone. + pub directory: im_client::directory::DirectoryClient, } /// The application context this request runs under. @@ -173,6 +177,8 @@ pub async fn current_user(cx: &Cx) -> Result, StoreError> { &claims.sub, &claims.email, &claims.name, + None, + claims.photo_version, app.config.default_quota_bytes, ) .await?;