From 506e5257c027340471613f4c1cf355a4ff423e0c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Wed, 9 Sep 2026 02:19:00 +0300 Subject: [PATCH] =?UTF-8?q?the=20face=20is=20the=20directory's=20fact:=20i?= =?UTF-8?q?m's=20photo=5Fversion=20rides=20the=20roster=20onto=20the=20use?= =?UTF-8?q?r=20row=20(migration=200006,=20reconcile=20map,=20born-linked?= =?UTF-8?q?=20inserts),=20a=20/directory/live=20stream=20task=20in=20iz-we?= =?UTF-8?q?b=20applies=20each=20Profile=20event=20through=20the=20same=20s?= =?UTF-8?q?ync=5Fmember=20the=20300s=20watchdog=20beat=20keeps=20as=20heal?= =?UTF-8?q?er,=20im-client=20(pinned,=20OIDC=20half=20off)=20supplies=20th?= =?UTF-8?q?e=20shared=20DirectoryClient=20the=20avatar=20route=20and=20the?= =?UTF-8?q?=20mirror=20both=20use,=20and=20the=20avatar=20proxy=20drops=20?= =?UTF-8?q?its=20own-id=20gate=20=E2=80=94=20any=20member's=20face=20serve?= =?UTF-8?q?s=20to=20any=20signed-in=20member,=20ETagged=20p{row=20version}?= =?UTF-8?q?,=20a=20matching=20=3Fv=3D=20cached=20immutable=20for=20a=20yea?= =?UTF-8?q?r=20while=20every=20other=20spelling=20revalidates=20=E2=80=94?= =?UTF-8?q?=20and=20every=20avatar=20URL=20now=20carries=20the=20stamp,=20?= =?UTF-8?q?so=20an=20im-side=20upload=20lands=20as=20a=20members=20announc?= =?UTF-8?q?e,=20a=20morph,=20and=20a=20new=20src=20on=20open=20boards=20wi?= =?UTF-8?q?th=20no=20reload?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Cargo.lock | 22 +++ Cargo.toml | 1 + crates/iz-client/src/lib.rs | 62 --------- .../iz-core/migrations/0006_photo_version.sql | 7 + crates/iz-core/src/board.rs | 8 +- crates/iz-core/src/store/mod.rs | 19 ++- crates/iz-core/src/store/reconcile.rs | 16 ++- crates/iz-core/src/store/schema.rs | 1 + crates/iz-core/src/store/turso_store.rs | 57 +++++--- crates/iz-core/tests/store.rs | 72 ++++++++-- crates/iz-web/Cargo.toml | 1 + crates/iz-web/src/avatar.rs | 93 +++++++------ crates/iz-web/src/board.rs | 2 +- crates/iz-web/src/detail.rs | 11 +- crates/iz-web/src/layout.rs | 24 ++-- crates/iz-web/src/main.rs | 128 ++++++++++++++---- crates/iz-web/src/people.rs | 2 +- crates/iz-web/src/settings.rs | 7 +- crates/iz-web/tests/http.rs | 122 +++++++++++++---- 19 files changed, 442 insertions(+), 213 deletions(-) create mode 100644 crates/iz-core/migrations/0006_photo_version.sql diff --git a/Cargo.lock b/Cargo.lock index 3781476..a46bda3 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1768,6 +1768,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 = "indexmap" version = "2.14.0" @@ -1904,6 +1925,7 @@ dependencies = [ "grass", "http", "http-body-util", + "im-client", "iz-client", "iz-core", "lettre", diff --git a/Cargo.toml b/Cargo.toml index 6ce18a8..786ab2e 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -11,6 +11,7 @@ repository = "https://github.com/DizeyLab/iz" [workspace.dependencies] iz-core = { path = "crates/iz-core", default-features = false } iz-client = { path = "crates/iz-client" } +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/iz-client/src/lib.rs b/crates/iz-client/src/lib.rs index 8ffed42..ba8453b 100644 --- a/crates/iz-client/src/lib.rs +++ b/crates/iz-client/src/lib.rs @@ -150,48 +150,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 member rows needs. -#[derive(Debug, Clone, serde::Deserialize)] -pub struct DirectoryMember { - pub sub: String, - pub email: String, - pub name: String, - #[serde(default)] - pub admin: bool, -} - /// One entry of im's family list: the wordmark key, the human name, and /// where the app lives — exactly what the topbar switcher renders. /// `Serialize` because the app that fetched it mirrors it into its own @@ -204,26 +162,6 @@ pub struct FamilyService { } impl IzClient { - /// The family phonebook: every non-disabled user im knows, fetched as - /// the app (`Authorization: Basic` with the client pair, the same - /// credentials the photo route takes). `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 beat. - pub async fn directory(&self) -> Option> { - let reply = self - .http - .get(format!("{}/directory", self.config.issuer)) - .basic_auth(&self.config.client_id, Some(&self.config.client_secret)) - .send() - .await - .ok()?; - if !reply.status().is_success() { - return None; - } - reply.json().await.ok() - } - /// The family list: every app im's admin panel serves, fetched as the /// app (`Authorization: Basic` with the client pair, the same /// credentials the directory takes). `None` on anything that is not a diff --git a/crates/iz-core/migrations/0006_photo_version.sql b/crates/iz-core/migrations/0006_photo_version.sql new file mode 100644 index 0000000..648c1b5 --- /dev/null +++ b/crates/iz-core/migrations/0006_photo_version.sql @@ -0,0 +1,7 @@ +-- The face wears a version now. im counts every change to a member's photo, +-- and the count rides the directory: a sync that sees a new number knows the +-- face changed without fetching it, and an avatar URL stamped with the number +-- a page rendered can be cached hard — the browser only refetches when the +-- stamp it holds is no longer the stamp the row carries. Rows from before +-- this column start at zero, the count of a member im has never photographed. +ALTER TABLE user ADD COLUMN photo_version INTEGER NOT NULL DEFAULT 0; diff --git a/crates/iz-core/src/board.rs b/crates/iz-core/src/board.rs index f3c449d..4ac10c9 100644 --- a/crates/iz-core/src/board.rs +++ b/crates/iz-core/src/board.rs @@ -95,10 +95,10 @@ pub enum Moved { pub struct Person { pub id: String, pub display_name: String, - /// Whether a local photo exists — always false since SSO: avatars come - /// from the provider, and the board keeps the field so the shape the - /// pages read does not churn under them. - pub has_photo: bool, + /// How many times the provider has re-photographed this person: the + /// `?v=` an avatar URL carries, so a browser may cache the bytes hard + /// and still refetch the day the face changes. Zero: no photo there. + pub photo_version: u64, } impl Person { diff --git a/crates/iz-core/src/store/mod.rs b/crates/iz-core/src/store/mod.rs index 9c385d7..eed96f0 100644 --- a/crates/iz-core/src/store/mod.rs +++ b/crates/iz-core/src/store/mod.rs @@ -200,6 +200,11 @@ pub struct User { pub language: String, /// Display-only, as [`Self::timezone`]. pub ui: String, + /// How many times the person's photo has changed at the provider: the + /// `?v=` stamp an avatar URL carries, so a page can be served for months + /// and the browser still refetches the day the face changes. Zero: no + /// photo, or a provider too old to count. + pub photo_version: u64, } /// The profile page's totals for one person: what is on their plate, what @@ -784,18 +789,20 @@ pub trait Store: BoardReads + DetailReads + 'static { /// gets a row born linked — assignable, mailable and avatar-able before /// their first visit. An unclaimed row with a matching address is /// claimed (sub stamped, id/role/preferences/history kept), a known row - /// follows the provider's address, name and admin flag, and a row that - /// already agrees is left alone. Unlike [`Store::provision_user`] this - /// is not a sign-in: `last_signed_in_at` is never stamped, and an empty - /// database grows no workspace (the first sign-in builds it; the next - /// beat mirrors everyone). The admin flag claims an unclaimed owner the - /// same way provision does. Says what happened through [`MemberSync`]. + /// follows the provider's address, name, admin flag and photo version, + /// and a row that already agrees is left alone. Unlike + /// [`Store::provision_user`] this is not a sign-in: `last_signed_in_at` + /// is never stamped, and an empty database grows no workspace (the first + /// sign-in builds it; the next beat mirrors everyone). The admin flag + /// claims an unclaimed owner the same way provision does. Says what + /// happened through [`MemberSync`]. async fn sync_member( &self, sub: &str, email: &str, display_name: &str, im_admin: bool, + photo_version: u64, ) -> Result; async fn user(&self, id: &str) -> Result>; diff --git a/crates/iz-core/src/store/reconcile.rs b/crates/iz-core/src/store/reconcile.rs index 7c337f9..f1053f1 100644 --- a/crates/iz-core/src/store/reconcile.rs +++ b/crates/iz-core/src/store/reconcile.rs @@ -270,6 +270,7 @@ fn build_maps( old_has_clock: bool, old_has_reminder: bool, old_has_tag: bool, + old_has_photo_version: bool, ) -> Vec { let mut maps = Vec::new(); @@ -363,6 +364,17 @@ fn build_maps( ("language", "old.language".into()), ("ui", "old.ui".into()), ("created_at", "old.created_at".into()), + ( + // A database from before faces wore versions starts every + // member at zero — im's count of "never photographed" — and + // the next directory pass stamps the real one. + "photo_version", + if old_has_photo_version { + "old.photo_version".into() + } else { + "0".to_string() + }, + ), ("last_signed_in_at", "old.last_signed_in_at".into()), ], }); @@ -747,12 +759,14 @@ async fn copy_data(old_conn: &Connection, new_conn: &Connection, path: &str) -> let has_reminder = old_has_column(old_conn, "workspace", "reminder_minutes").await?; let has_tag = old_has_column(old_conn, "tag", "id").await?; let has_setting = old_has_column(old_conn, "setting", "key").await?; + let has_photo_version = old_has_column(old_conn, "user", "photo_version").await?; let maps = build_maps( has_smtp_check, has_batch_window, has_clock, has_reminder, has_tag, + has_photo_version, ); validate_maps(new_conn, &maps).await?; @@ -1059,7 +1073,7 @@ mod tests { let conn = db.connect().unwrap(); conn.execute_batch(&schema_sql()).await.unwrap(); - let maps = build_maps(false, false, false, false, false); + let maps = build_maps(false, false, false, false, false, false); validate_maps(&conn, &maps) .await .expect("the full map set was refused against the declared schema"); diff --git a/crates/iz-core/src/store/schema.rs b/crates/iz-core/src/store/schema.rs index 53cac8c..00c2f9f 100644 --- a/crates/iz-core/src/store/schema.rs +++ b/crates/iz-core/src/store/schema.rs @@ -19,6 +19,7 @@ pub(crate) const MIGRATIONS: &[&str] = &[ include_str!("../../migrations/0003_sso.sql"), include_str!("../../migrations/0004_no_photo_limit.sql"), include_str!("../../migrations/0005_settings.sql"), + include_str!("../../migrations/0006_photo_version.sql"), ]; /// The whole declared schema — every migration applied in order — as one diff --git a/crates/iz-core/src/store/turso_store.rs b/crates/iz-core/src/store/turso_store.rs index 3b69509..e45bc70 100644 --- a/crates/iz-core/src/store/turso_store.rs +++ b/crates/iz-core/src/store/turso_store.rs @@ -1232,11 +1232,12 @@ fn user_from(row: &Row) -> Result { theme: text(row, 10)?, language: text(row, 11)?, ui: text(row, 12)?, + photo_version: row.get::(13).map_err(backend)?.max(0) as u64, }) } const USER_COLUMNS: &str = "id, workspace_id, oidc_sub, email, display_name, role, disabled, \ - created_at, last_signed_in_at, timezone, theme, language, ui"; + created_at, last_signed_in_at, timezone, theme, language, ui, photo_version"; /// Addresses are matched case-insensitively; the display form is kept as typed. fn fold_email(email: &str) -> String { @@ -1463,6 +1464,7 @@ impl Store for TursoStore { email: &str, display_name: &str, im_admin: bool, + photo_version: u64, ) -> Result { let email = fold_email(email); // IMMEDIATE like provision_user: a beat racing a first sign-in over @@ -1485,12 +1487,23 @@ impl Store for TursoStore { let role = synced_role(user.role, im_admin); // A sync is not a sign-in: last_signed_in_at is the person's own // fact, and the directory says nothing about it. - if user.email == email && user.display_name == display_name && role == user.role { + if user.email == email + && user.display_name == display_name + && role == user.role + && user.photo_version == photo_version + { Some((user.id, MemberSync::Untouched)) } else { tx.execute( - "UPDATE user SET email = ?1, display_name = ?2, role = ?3 WHERE id = ?4", - params![email.clone(), display_name, role.as_str(), user.id.clone()], + "UPDATE user SET email = ?1, display_name = ?2, role = ?3, \ + photo_version = ?4 WHERE id = ?5", + params![ + email.clone(), + display_name, + role.as_str(), + photo_version as i64, + user.id.clone() + ], ) .await .map_err(backend)?; @@ -1511,13 +1524,14 @@ impl Store for TursoStore { if let Some(user) = seen { let role = synced_role(user.role, im_admin); tx.execute( - "UPDATE user SET oidc_sub = ?1, email = ?2, display_name = ?3, role = ?4 \ - WHERE id = ?5", + "UPDATE user SET oidc_sub = ?1, email = ?2, display_name = ?3, role = ?4, \ + photo_version = ?5 WHERE id = ?6", params![ sub, email.clone(), display_name, role.as_str(), + photo_version as i64, user.id.clone() ], ) @@ -1547,8 +1561,8 @@ impl Store for TursoStore { let role = if im_admin { Role::Admin } else { Role::Member }; tx.execute( "INSERT INTO user (id, workspace_id, oidc_sub, email, display_name, \ - role, disabled, created_at, last_signed_in_at) \ - VALUES (?1, ?2, ?3, ?4, ?5, ?6, 0, ?7, NULL)", + role, disabled, created_at, last_signed_in_at, photo_version) \ + VALUES (?1, ?2, ?3, ?4, ?5, ?6, 0, ?7, NULL, ?8)", params![ id.clone(), workspace_id, @@ -1556,7 +1570,8 @@ impl Store for TursoStore { email.clone(), display_name, role.as_str(), - now.clone() + now.clone(), + photo_version as i64 ], ) .await @@ -4807,7 +4822,7 @@ impl DetailReads for TursoStore { let conn = self.conn.lock().await; let mut rows = conn .query( - "SELECT u.id, u.display_name, 0 FROM task_assignee a \ + "SELECT u.id, u.display_name, u.photo_version FROM task_assignee a \ JOIN user u ON u.id = a.user_id \ WHERE a.task_id = ?1 ORDER BY u.display_name", params![task_id], @@ -4819,7 +4834,7 @@ impl DetailReads for TursoStore { out.push(Person { id: text(&row, 0)?, display_name: text(&row, 1)?, - has_photo: row.get::(2).map_err(backend)? != 0, + photo_version: row.get::(2).map_err(backend)?.max(0) as u64, }); } Ok(out) @@ -4831,7 +4846,7 @@ impl DetailReads for TursoStore { // so neither leaves the server for this screen. let mut rows = conn .query( - "SELECT id, display_name, 0 FROM user \ + "SELECT id, display_name, photo_version FROM user \ WHERE workspace_id = ?1 AND role <> ?2 ORDER BY display_name", params![workspace_id, Role::Viewer.as_str()], ) @@ -4842,7 +4857,7 @@ impl DetailReads for TursoStore { out.push(Person { id: text(&row, 0)?, display_name: text(&row, 1)?, - has_photo: row.get::(2).map_err(backend)? != 0, + photo_version: row.get::(2).map_err(backend)?.max(0) as u64, }); } Ok(out) @@ -4890,7 +4905,7 @@ impl DetailReads for TursoStore { let conn = self.conn.lock().await; let mut rows = conn .query( - "SELECT c.id, c.body, c.created_at, u.id, u.display_name, 0 \ + "SELECT c.id, c.body, c.created_at, u.id, u.display_name, u.photo_version \ FROM comment c JOIN user u ON u.id = c.author_id \ WHERE c.task_id = ?1 ORDER BY c.created_at, c.rowid", params![task_id], @@ -4906,7 +4921,7 @@ impl DetailReads for TursoStore { author: Person { id: text(&row, 3)?, display_name: text(&row, 4)?, - has_photo: row.get::(5).map_err(backend)? != 0, + photo_version: row.get::(5).map_err(backend)?.max(0) as u64, }, }); } @@ -4946,7 +4961,7 @@ impl DetailReads for TursoStore { let mut rows = conn .query( "SELECT a.id, a.kind, a.detail, a.created_at, u.id, u.display_name, \ - 0 \ + u.photo_version \ FROM activity a LEFT JOIN user u ON u.id = a.actor_id \ WHERE a.task_id = ?1 ORDER BY a.created_at DESC, a.rowid DESC", params![task_id], @@ -4959,7 +4974,7 @@ impl DetailReads for TursoStore { Some(id) => Some(Person { id, display_name: text(&row, 5)?, - has_photo: row.get::(6).map_err(backend)? != 0, + photo_version: row.get::(6).map_err(backend)?.max(0) as u64, }), None => None, }; @@ -4983,7 +4998,7 @@ impl DetailReads for TursoStore { let mut rows = conn .query( "SELECT t.id, t.task_key, t.title, t.column_id, t.done_at, t.parent_id, \ - u.id, u.display_name, 0 \ + u.id, u.display_name, u.photo_version \ FROM task t \ LEFT JOIN task_assignee a ON a.task_id = t.id \ LEFT JOIN user u ON u.id = a.user_id \ @@ -5007,7 +5022,7 @@ impl DetailReads for TursoStore { Some(user_id) => Some(Person { id: user_id, display_name: text(&row, 7)?, - has_photo: row.get::(8).map_err(backend)? != 0, + photo_version: row.get::(8).map_err(backend)?.max(0) as u64, }), None => None, }; @@ -5116,7 +5131,7 @@ impl BoardReads for TursoStore { let conn = self.conn.lock().await; let mut rows = conn .query( - "SELECT a.task_id, u.id, u.display_name, 0 \ + "SELECT a.task_id, u.id, u.display_name, u.photo_version \ FROM task_assignee a \ JOIN task t ON t.id = a.task_id \ JOIN user u ON u.id = a.user_id \ @@ -5133,7 +5148,7 @@ impl BoardReads for TursoStore { Person { id: text(&row, 1)?, display_name: text(&row, 2)?, - has_photo: row.get::(3).map_err(backend)? != 0, + photo_version: row.get::(3).map_err(backend)?.max(0) as u64, }, )); } diff --git a/crates/iz-core/tests/store.rs b/crates/iz-core/tests/store.rs index 8f6b931..f4659f5 100644 --- a/crates/iz-core/tests/store.rs +++ b/crates/iz-core/tests/store.rs @@ -1803,7 +1803,7 @@ fn initials_fall_back_to_two_letters() { let person = |name: &str| Person { id: "u".into(), display_name: name.into(), - has_photo: false, + photo_version: 0, }; assert_eq!(person("Mel Duarte").initials(), "MD"); assert_eq!(person("Ada").initials(), "A"); @@ -8407,8 +8407,7 @@ async fn set_user_disabled_round_trips() { async fn a_synced_member_is_born_linked_and_never_signed_in() { let (scratch, workspace, _admin) = workspace_with_admin().await; let sync = scratch - .store - .sync_member("sub-mert", "mert@iz.sh", "Mert", false) + .store.sync_member("sub-mert", "mert@iz.sh", "Mert", false, 0) .await .unwrap(); assert_eq!(sync, iz_core::store::MemberSync::Inserted); @@ -8423,8 +8422,7 @@ async fn a_synced_member_is_born_linked_and_never_signed_in() { assert!(row.last_signed_in_at.is_none()); // An im admin the workspace has never met is Admin from the first beat. scratch - .store - .sync_member("sub-boss", "boss@iz.sh", "Boss", true) + .store.sync_member("sub-boss", "boss@iz.sh", "Boss", true, 0) .await .unwrap(); let boss = scratch @@ -8445,8 +8443,7 @@ async fn a_sync_claims_an_unclaimed_row_without_touching_its_sign_in_fact() { .await .unwrap(); let sync = scratch - .store - .sync_member("sub-mert", "MERT@iz.sh", "Mert Yılmaz", false) + .store.sync_member("sub-mert", "MERT@iz.sh", "Mert Yılmaz", false, 0) .await .unwrap(); assert_eq!(sync, iz_core::store::MemberSync::Claimed); @@ -8467,8 +8464,7 @@ async fn a_sync_follows_provider_drift_but_not_the_sign_in_fact() { let before = scratch.store.user(&admin_id).await.unwrap().unwrap(); let seen = before.last_signed_in_at.clone(); let sync = scratch - .store - .sync_member("sub-ada", "ada@iz.sh", "Ada Lovelace", true) + .store.sync_member("sub-ada", "ada@iz.sh", "Ada Lovelace", true, 0) .await .unwrap(); assert_eq!(sync, iz_core::store::MemberSync::Refreshed); @@ -8477,8 +8473,7 @@ async fn a_sync_follows_provider_drift_but_not_the_sign_in_fact() { assert_eq!(after.last_signed_in_at, seen); // Losing the flag in the directory drops an Admin to Member. scratch - .store - .sync_member("sub-ada", "ada@iz.sh", "Ada Lovelace", false) + .store.sync_member("sub-ada", "ada@iz.sh", "Ada Lovelace", false, 0) .await .unwrap(); let demoted = scratch.store.user(&admin_id).await.unwrap().unwrap(); @@ -8490,8 +8485,7 @@ async fn an_agreeing_sync_is_untouched_and_silent() { let (scratch, _, _) = workspace_with_admin().await; let mut rx = scratch.store.subscribe(); let sync = scratch - .store - .sync_member("sub-ada", "ada@iz.sh", "Ada", true) + .store.sync_member("sub-ada", "ada@iz.sh", "Ada", true, 0) .await .unwrap(); assert_eq!(sync, iz_core::store::MemberSync::Untouched); @@ -8502,14 +8496,62 @@ async fn an_agreeing_sync_is_untouched_and_silent() { async fn a_sync_without_a_workspace_skips_and_writes_nothing() { let scratch = Scratch::open().await; let sync = scratch - .store - .sync_member("sub-mert", "mert@iz.sh", "Mert", false) + .store.sync_member("sub-mert", "mert@iz.sh", "Mert", false, 0) .await .unwrap(); assert_eq!(sync, iz_core::store::MemberSync::Skipped); assert!(scratch.store.workspace().await.unwrap().is_none()); } +/// The face's version is the row's fact like the name: a sync that hears of +/// a new photo stamps it and says Refreshed (so the live channel hears), +/// one that already agrees says Untouched, and a row born from the +/// directory carries the version it was told before the first visit. +#[tokio::test] +async fn a_photo_version_bump_refreshes_and_announces() { + let (scratch, workspace, _admin) = workspace_with_admin().await; + let mut rx = scratch.store.subscribe(); + let sync = scratch + .store + .sync_member("sub-mert", "mert@iz.sh", "Mert", false, 2) + .await + .unwrap(); + assert_eq!(sync, iz_core::store::MemberSync::Inserted); + let row = scratch + .store + .user_by_email(&workspace, "mert@iz.sh") + .await + .unwrap() + .unwrap(); + assert_eq!(row.photo_version, 2); + assert_eq!(announced(&mut rx), vec!["members".to_string()]); + + // The same version again: the row agrees, and silence is the answer. + let again = scratch + .store + .sync_member("sub-mert", "mert@iz.sh", "Mert", false, 2) + .await + .unwrap(); + assert_eq!(again, iz_core::store::MemberSync::Untouched); + assert!(announced(&mut rx).is_empty()); + + // im counted another upload: the stamp moves and the move is news. + let bumped = scratch + .store + .sync_member("sub-mert", "mert@iz.sh", "Mert", false, 3) + .await + .unwrap(); + assert_eq!(bumped, iz_core::store::MemberSync::Refreshed); + let moved = scratch + .store + .user_by_email(&workspace, "mert@iz.sh") + .await + .unwrap() + .unwrap(); + assert_eq!(moved.photo_version, 3); + assert_eq!(announced(&mut rx), vec!["members".to_string()]); +} + /// The app-level setting drawer: a key never set reads as absent, one set /// reads back, and setting it again replaces rather than duplicates — the /// family mirror rewrites its key every beat, and two rows for one key diff --git a/crates/iz-web/Cargo.toml b/crates/iz-web/Cargo.toml index 176dc4f..cf168e1 100644 --- a/crates/iz-web/Cargo.toml +++ b/crates/iz-web/Cargo.toml @@ -20,6 +20,7 @@ topcoat = { version = "0.6.2", default-features = false, features = [ "sse", ] } iz-client = { workspace = true } +im-client = { workspace = true } iz-core = { workspace = true, features = ["server"] } serde.workspace = true serde_json.workspace = true diff --git a/crates/iz-web/src/avatar.rs b/crates/iz-web/src/avatar.rs index b0ca4d1..88983d4 100644 --- a/crates/iz-web/src/avatar.rs +++ b/crates/iz-web/src/avatar.rs @@ -1,16 +1,21 @@ -//! The signed-in person's face, proxied from im. +//! Every workspace 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 +//! this workspace — not just the caller, whose own face is the common case. +//! The URL carries the member's `photo_version` as `?v=`, so a page may be +//! cached for months and the browser still refetches the day the face +//! changes: a matching `?v` is served `private, max-age=31536000, immutable`, +//! any other spelling revalidates, and the `ETag` names the row's version so +//! a revalidation ends in a bodyless 304. A browser without a session is +//! refused outright; an id outside the workspace, or im unreachable, is the +//! same 404 — the `` hides itself and the initials beneath stand in. -use topcoat::context::Cx; +use im_client::directory::DirectoryClient; +use topcoat::context::{Cx, try_app_context}; use topcoat::router::request::headers as request_headers; use topcoat::router::{HeaderMap, HeaderValue, StatusCode, header, path_param, route}; -use crate::server::require_user; +use crate::server::{require_user, store}; path_param!(user_id); @@ -18,45 +23,64 @@ 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 shared directory client `main.rs` registers on the router from the +/// `[oidc]` config: one HTTP pool, the app's Basic pair on every call. +pub fn directory(cx: &Cx) -> &DirectoryClient { + try_app_context::(cx) + .expect("the directory client was registered on the router") +} + +fn stamped_version(cx: &Cx) -> Option { + let query = topcoat::router::request::uri(cx).query().unwrap_or(""); + query + .split('&') + .filter_map(|pair| pair.split_once('=')) + .find(|(key, _)| *key == "v") + .and_then(|(_, value)| value.parse::().ok()) +} + +/// `GET /avatar/{user_id}`: im's photo for the named member, or the same +/// not-found an unknown id would see — never a `403`, which would confirm +/// the id belongs to somebody. #[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 { + let _viewer = match require_user(cx).await { Ok(user) => user, // 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())), }; - // 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 { + let row = store(cx).user(target).await?; + let Some(row) = row else { return Ok(not_found()); - } - let Some(sub) = user.oidc_sub.clone() else { + }; + let Some(sub) = row.oidc_sub.clone() else { return Ok(not_found()); }; - let Some((bytes, mime)) = iz_client::photo_for(cx, &sub).await else { + let Ok((bytes, mime)) = directory(cx).photo(&sub).await else { return Ok(not_found()); }; - let etag = format!("\"{:x}\"", fnv1a(&bytes)); + // The row's version IS the version this URL names: the directory keeps + // it current (live stream, and the beat behind it), so a stale face + // means a stale row, never a lie about freshness. + let etag = format!("\"p{}\"", row.photo_version); let mut headers = HeaderMap::new(); - headers.insert( - header::ETAG, - HeaderValue::from_str(&etag).unwrap_or(HeaderValue::from_static("\"0\"")), - ); - // 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. `private` because the route is - // gated and a shared proxy must not answer a stranger from another - // account's entry. + headers.insert(header::ETAG, HeaderValue::from_str(&etag).unwrap()); + // A `?v` that agrees with the row means this exact face is pinned to a + // URL that changes the day the face does, so the browser may keep it + // for a year. Every other spelling — including no stamp at all — + // revalidates. `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"), + HeaderValue::from_static(if stamped_version(cx) == Some(row.photo_version) { + "private, max-age=31536000, immutable" + } else { + "private, no-cache" + }), ); headers.insert( header::CONTENT_TYPE, @@ -71,14 +95,3 @@ async fn avatar(cx: &Cx) -> topcoat::Result<(StatusCode, HeaderMap, Vec)> { } Ok((StatusCode::OK, headers, bytes)) } - -/// A cheap, non-cryptographic hash — good enough for an `ETag` on bytes only -/// im ever writes. -fn fnv1a(bytes: &[u8]) -> u64 { - let mut hash: u64 = 0xcbf29ce484222325; - for &b in bytes { - hash ^= b as u64; - hash = hash.wrapping_mul(0x100000001b3); - } - hash -} diff --git a/crates/iz-web/src/board.rs b/crates/iz-web/src/board.rs index 52c3462..e61ba44 100644 --- a/crates/iz-web/src/board.rs +++ b/crates/iz-web/src/board.rs @@ -422,7 +422,7 @@ async fn render_card( let subtasks_open = card.holds_on_subtasks(); let mut assignees = Vec::new(); for person in card.assignees.iter() { - assignees.push(crate::layout::avatar(cx, &person.id, &person.display_name, "").await?); + assignees.push(crate::layout::avatar(cx, &person.id, &person.display_name, person.photo_version, "").await?); } let has_assignees = !card.assignees.is_empty(); let task_id = card.id.clone(); diff --git a/crates/iz-web/src/detail.rs b/crates/iz-web/src/detail.rs index a810e5c..e8052e0 100644 --- a/crates/iz-web/src/detail.rs +++ b/crates/iz-web/src/detail.rs @@ -51,6 +51,8 @@ pub struct Me { pub email: String, pub role: iz_core::Role, pub language: String, + /// The face's version, for the topbar avatar's `?v=` stamp. + pub photo_version: u64, } impl From<&User> for Me { @@ -61,6 +63,7 @@ impl From<&User> for Me { email: user.email.clone(), role: user.role, language: user.language.clone(), + photo_version: user.photo_version, } } } @@ -1556,7 +1559,7 @@ async fn assignee_chip( cx => - (crate::layout::avatar(cx, &person.id, &person.display_name, "avatar-sm").await?) + (crate::layout::avatar(cx, &person.id, &person.display_name, person.photo_version, "avatar-sm").await?) (person.display_name.clone()) if may_write { @@ -1588,7 +1591,7 @@ async fn assignee_picker(cx: &Cx, task_id: &str, people: &[Person], lang: Lang) @@ -1668,7 +1671,7 @@ async fn subtask_row( let release_title = t(lang, Key::ReleaseThisPart); let mut faces = Vec::new(); for person in &part.assignees { - faces.push(crate::layout::avatar(cx, &person.id, &person.display_name, "").await?); + faces.push(crate::layout::avatar(cx, &person.id, &person.display_name, person.photo_version, "").await?); } view! { cx => @@ -1844,7 +1847,7 @@ async fn comment_row(cx: &Cx, comment: &Comment, zone: UtcOffset) -> Result { cx =>
- (crate::layout::avatar(cx, &comment.author.id, &comment.author.display_name, "avatar-lg").await?) + (crate::layout::avatar(cx, &comment.author.id, &comment.author.display_name, comment.author.photo_version, "avatar-lg").await?)
diff --git a/crates/iz-web/src/layout.rs b/crates/iz-web/src/layout.rs index 352df36..6425f38 100644 --- a/crates/iz-web/src/layout.rs +++ b/crates/iz-web/src/layout.rs @@ -69,19 +69,27 @@ pub(crate) async fn wordmark(cx: &Cx) -> Result { /// A person as a circle (or, on the Instrument skin, a square): the initials, /// toned by the id so every account has its own colour, with the im photo -/// over it when im has one. Whether im has one is not known cheaply — the -/// photo is the app's credentialed fetch, not the browser's — so the `` -/// always renders and hides itself on error (see `avatar_script`), leaving -/// the initials beneath as the fallback. Shared by the board, the modal and +/// over it when im has one. The URL carries the row's `photo_version` as +/// `?v=`, so a changed face is a changed URL: a browser may cache the old +/// answer for a year and still see the new one the day the row moves — the +/// live refresh morphs the attribute and the img follows. The `` always +/// renders and hides itself on error (see `avatar_script`), leaving the +/// initials beneath as the fallback. Shared by the board, the modal and /// every topbar user menu. -pub(crate) async fn avatar(cx: &Cx, id: &str, display_name: &str, extra: &str) -> Result { +pub(crate) async fn avatar( + cx: &Cx, + id: &str, + display_name: &str, + photo_version: u64, + extra: &str, +) -> Result { let tone = id .bytes() .fold(0u32, |acc, b| acc.wrapping_mul(31).wrapping_add(b as u32)) % 5; let class = format!("avatar avatar-tone-{tone} {extra}"); let initials = initials_of(display_name); - let src = format!("/avatar/{id}"); + let src = format!("/avatar/{id}?v={photo_version}"); view! { cx => @@ -149,7 +157,7 @@ pub async fn user_menu(cx: &Cx, me: &crate::detail::Me, lang: Lang) -> Result { cx =>
@@ -158,7 +166,6 @@ pub async fn user_menu(cx: &Cx, me: &crate::detail::Me, lang: Lang) -> Result {
(t(lang, role_key))
(t(lang, Key::Profile)) (t(lang, Key::NavSettings)) - (t(lang, Key::SignOut))
(avatar_script(cx).await?) @@ -869,6 +876,7 @@ pub async fn live_script(cx: &Cx) -> Result { if (path === '/tags') { return topic === 'tags' || topic === 'members'; } \ if (path === '/settings') { return topic === 'settings' || topic === 'members'; } \ if (path === '/people/') { return topic === 'members'; } \ + return topic === 'members'; \ } \ try { \ var src = new EventSource('/api/live'); \ diff --git a/crates/iz-web/src/main.rs b/crates/iz-web/src/main.rs index b71f298..1a0798a 100644 --- a/crates/iz-web/src/main.rs +++ b/crates/iz-web/src/main.rs @@ -131,6 +131,15 @@ async fn main() { cookie_name: "iz_session".to_string(), cookie_key, }; + // The shared identity directory: the same issuer and Basic pair the OIDC + // side holds, pointed at im's roster. One HTTP pool inside, cheap to + // clone — the avatar route reaches it through the router context below, + // and the two mirror tasks carry their own handles. + let directory = im_client::directory::DirectoryClient::new( + config.oidc.issuer.clone(), + config.oidc.client_id.clone(), + config.oidc.client_secret.clone(), + ); // The engine is always built, because a sender can appear at any moment: // an admin fills the panel in and the next sweep sends what was held. It // holds one connection pool, rebuilt only when the settings behind it @@ -142,19 +151,24 @@ async fn main() { )); tokio::spawn(sweep(engine.clone(), store.clone())); - // The member list mirrors im's directory: people are assignable and - // mailable before their first visit, and the provider's renames and - // admin flips follow on their own. Runs beside the sweep, first pass - // right away so a fresh deploy sees everyone at boot. + // The member list mirrors im's directory two ways. The live stream is + // the fast path — a photo uploaded, a rename, a disable in im lands + // within a moment and announces, so every open board swaps the face + // without a reload. The beat stays as the watchdog: one full pass + // every five minutes heals whatever a dead stream hid, and keeps the + // family list fresh, which the stream does not carry. First passes + // run right away, so a fresh deploy sees everyone at boot. // The address the app files itself under is `base_url` alone: a bound // address is no fallback here — a loopback bind is nothing anyone else // can reach, and filing it would overwrite the real one in every // switcher. tokio::spawn(directory_sync( store.clone(), + directory.clone(), iz_client::IzClient::new(oidc.clone()), config.base_url.clone(), )); + tokio::spawn(directory_stream(store.clone(), directory.clone())); // Told when the process is stopping, so the live streams end instead of // being waited out. See `iz_web::live::Shutdown`. let (stop, stopping) = tokio::sync::watch::channel(false); @@ -171,6 +185,7 @@ async fn main() { oidc, ) .app_context(store.clone()) + .app_context(directory) .app_context(iz_client::LogoutBack(Arc::new(iz_web::server::logout_back))) .app_context(config.clone()) .app_context(iz_web::live::LiveWindow(std::time::Duration::from_secs( @@ -321,13 +336,15 @@ async fn sweep(engine: std::sync::Arc, store: Arc, + directory: im_client::directory::DirectoryClient, client: iz_client::IzClient, configured_url: String, ) { @@ -336,19 +353,7 @@ async fn directory_sync( // said once and the mirror goes on without it. let mut said_no_address = false; loop { - match client.directory().await { - Some(members) => { - for member in members { - if let Err(problem) = store - .sync_member(&member.sub, &member.email, &member.name, member.admin) - .await - { - eprintln!("directory sync: {}: {problem}", member.email); - } - } - } - None => eprintln!("directory sync: im did not answer; keeping the rows there are"), - } + mirror_directory(&store, &directory).await; // Before asking for the family, this app files itself in it, so a // deployment appears in everyone's switcher without an admin // typing its address. Resolved per beat in the order a sign-out @@ -393,6 +398,80 @@ async fn directory_sync( } } +/// One full pass of im's roster through the member rows: every entry +/// through [`iz_core::store::Store::sync_member`], which announces only +/// the rows that actually changed. +async fn mirror_directory( + store: &Arc, + directory: &im_client::directory::DirectoryClient, +) { + match directory.directory().await { + Ok(members) => { + for member in members { + apply_member(store, &member).await; + } + } + Err(problem) => { + eprintln!("directory sync: im did not answer ({problem}); keeping the rows there are") + } + } +} + +async fn apply_member( + store: &Arc, + member: &im_client::directory::DirectoryMember, +) { + if let Err(problem) = store + .sync_member( + &member.sub, + &member.email, + &member.name, + member.admin, + member.photo_version, + ) + .await + { + eprintln!("directory sync: {}: {problem}", member.email); + } +} + +/// The live half of the mirror: im's `/directory/live`, one event per +/// changed member. Forever, in this shape: a full pass, then the stream; +/// whenever the stream ends — im restarting, or its fifty-minute window +/// closing — wait out a backoff that doubles from one second to thirty, +/// replay a full pass (the resync that heals whatever the dead stream +/// carried or dropped), and redial. A stream error inside the body is the +/// same exit as a clean close: the pass below is what converges. +async fn directory_stream( + store: Arc, + directory: im_client::directory::DirectoryClient, +) { + let mut backoff = std::time::Duration::from_secs(1); + loop { + mirror_directory(&store, &directory).await; + match directory.open_stream().await { + Ok(mut stream) => { + backoff = std::time::Duration::from_secs(1); + while let Some(event) = stream.next().await { + match event { + Ok(im_client::directory::DirectoryEvent::Profile(member)) => { + apply_member(&store, &member).await; + } + Err(problem) => { + eprintln!("directory stream: {problem}; re-listing"); + break; + } + } + } + } + Err(problem) => { + eprintln!("directory stream: im did not answer ({problem})"); + } + } + tokio::time::sleep(backoff).await; + backoff = (backoff * 2).min(std::time::Duration::from_secs(30)); + } +} /// Waits for something to happen to the mail queue specifically. /// /// The channel carries every topic, and the sweep cares about one. Filtering @@ -403,7 +482,6 @@ async fn directory_sync( /// /// Lagging means announcements were dropped — a reason to look, not to stop. async fn queue_touched(rx: &mut tokio::sync::broadcast::Receiver) -> bool { - use tokio::sync::broadcast::error::RecvError; loop { match rx.recv().await { Ok(change) => { @@ -411,8 +489,8 @@ async fn queue_touched(rx: &mut tokio::sync::broadcast::Receiver return true, - Err(RecvError::Closed) => return false, + Err(tokio::sync::broadcast::error::RecvError::Lagged(_)) => return true, + Err(tokio::sync::broadcast::error::RecvError::Closed) => return false, } } } diff --git a/crates/iz-web/src/people.rs b/crates/iz-web/src/people.rs index 0926f1a..34e26ac 100644 --- a/crates/iz-web/src/people.rs +++ b/crates/iz-web/src/people.rs @@ -117,7 +117,7 @@ async fn people_page(cx: &Cx) -> Result {
- (crate::layout::avatar(cx, &person.id, &person.display_name, "avatar-xl").await?) + (crate::layout::avatar(cx, &person.id, &person.display_name, person.photo_version, "avatar-xl").await?)

(person.display_name.clone())

diff --git a/crates/iz-web/src/settings.rs b/crates/iz-web/src/settings.rs index 09eb42d..323caa4 100644 --- a/crates/iz-web/src/settings.rs +++ b/crates/iz-web/src/settings.rs @@ -938,6 +938,8 @@ struct Member { email: String, role: iz_core::Role, disabled: bool, + /// The face's version, for the row's avatar `?v=` stamp. + photo_version: u64, /// The day they last signed in, as the list writes it, or nothing. last_signed_in: Option, is_you: bool, @@ -955,6 +957,7 @@ async fn members_now(cx: &Cx, asking: &User) -> Result> { .into_iter() .map(|user| Member { disabled: user.disabled, + photo_version: user.photo_version, last_signed_in: user .last_signed_in_at .map(|at| iz_core::board::day_label(at.to_offset(zone).date())), @@ -1272,7 +1275,7 @@ async fn settings_page(cx: &Cx) -> Result {
- (crate::layout::avatar(cx, &user.id, &user.display_name, "avatar-lg").await?) + (crate::layout::avatar(cx, &user.id, &user.display_name, user.photo_version, "avatar-lg").await?)
(user.display_name.clone())
(user.email.clone())
@@ -1604,7 +1607,7 @@ async fn settings_page(cx: &Cx) -> Result { - (crate::layout::avatar(cx, &member.id, &member.display_name, "avatar-sm").await?) + (crate::layout::avatar(cx, &member.id, &member.display_name, member.photo_version, "avatar-sm").await?) (member.display_name.clone()) if member.is_you { (t(lang, Key::You)) diff --git a/crates/iz-web/tests/http.rs b/crates/iz-web/tests/http.rs index cbc2bd6..8d5cf05 100644 --- a/crates/iz-web/tests/http.rs +++ b/crates/iz-web/tests/http.rs @@ -349,6 +349,11 @@ impl App { client.clone(), ) .app_context(store.clone()) + .app_context(im_client::directory::DirectoryClient::new( + fake.url(), + "iz-test", + "s3cr3t", + )) .app_context(iz_client::LogoutBack(Arc::new( iz_web::server::logout_back, ))) @@ -432,6 +437,11 @@ impl App { client.clone(), ) .app_context(store.clone()) + .app_context(im_client::directory::DirectoryClient::new( + fake.url(), + "iz-test", + "s3cr3t", + )) .app_context(iz_client::LogoutBack(Arc::new( iz_web::server::logout_back, ))) @@ -708,6 +718,11 @@ impl App { .get(header::ETAG) .and_then(|value| value.to_str().ok()) .map(str::to_string); + let cache_control = response + .headers() + .get(header::CACHE_CONTROL) + .and_then(|value| value.to_str().ok()) + .map(str::to_string); let location = response .headers() .get(header::LOCATION) @@ -724,6 +739,7 @@ impl App { content_range, accept_ranges, etag, + cache_control, location, bytes, } @@ -745,6 +761,7 @@ struct Raw { content_range: Option, accept_ranges: Option, etag: Option, + cache_control: Option, /// Where a 303 sends the browser — the sign-out handoff's whole point. location: Option, bytes: Vec, @@ -4945,8 +4962,7 @@ async fn a_synced_member_is_listed_and_assignable_before_their_first_sign_in() { .unwrap(); let sync = app - .store - .sync_member("sub-mert", "mert@iz.sh", "Mert", false) + .store.sync_member("sub-mert", "mert@iz.sh", "Mert", false, 0) .await .unwrap(); assert_eq!(sync, iz_core::store::MemberSync::Inserted); @@ -5164,10 +5180,12 @@ async fn the_sign_in_card_links_the_login_and_names_a_failed_round_trip() { // Avatar: the signed-in person's face, proxied from im // --------------------------------------------------------------------------- -/// One's own avatar proxies im's photo bytes with the app's credential. -/// Catches a proxy that drops the auth or mangles the bytes. +/// A member's avatar proxies im's photo bytes with the app's credential. +/// Catches a proxy that drops the auth or mangles the bytes, and pins the +/// versioned caching: the row's `photo_version` is the ETag and the `?v=` +/// stamp a page renders. #[tokio::test] -async fn ones_own_avatar_proxies_the_im_photo() { +async fn a_members_avatar_proxies_the_im_photo() { let app = App::open().await; let admin = admin(&app).await; let admin_id = user_id(&app, "ada@iz.sh").await; @@ -5177,46 +5195,99 @@ async fn ones_own_avatar_proxies_the_im_photo() { assert_eq!(photo.status, StatusCode::OK); assert_eq!(photo.content_type.as_deref(), Some("image/png")); assert_eq!(photo.bytes, PNG); + // The row has met no photo yet: version zero, and the ETag says so. + assert_eq!(photo.etag.as_deref(), Some("\"p0\"")); + // No stamp on the URL: revalidate, never cache hard — the URL a page + // renders always carries the stamp, so this is only the stray fetch. + assert_eq!(photo.cache_control.as_deref(), Some("private, no-cache")); - let etag = photo.etag.clone().expect("no ETag on the served avatar"); let cached = app - .get_with_if_none_match(&format!("/avatar/{admin_id}"), Some(&admin), &etag) + .get_with_if_none_match(&format!("/avatar/{admin_id}"), Some(&admin), "\"p0\"") .await; assert_eq!(cached.status, StatusCode::NOT_MODIFIED); assert!(cached.bytes.is_empty()); } -/// Another account's id reads exactly like no photo — never a glimpse across -/// the fence. Catches a proxy that serves any id to any session. +/// The stamp the row carries pins the face: `?v=` agreeing with the row is +/// cacheable for a year because the URL itself changes when the face does, +/// any other spelling revalidates, and a sync that hears of a new photo +/// moves both the stamp and the ETag together. #[tokio::test] -async fn another_accounts_avatar_is_not_found() { +async fn a_matching_version_stamp_is_immutable_and_a_new_one_moves_it() { let app = App::open().await; let admin_cookie = admin(&app).await; - let admin_id = user_id(&app, "ada@iz.sh").await; let member = invited(&app, &admin_cookie, "emre@iz.sh", "Emre", Role::Member).await; - app.fake.set_photo("im-ada", PNG.to_vec(), "image/png"); + let member_id = user_id(&app, "emre@iz.sh").await; + // The directory pass finds the row by its sub — the same subject the + // sign-in provisions — and reports the face's third revision. + app.store + .sync_member("im-emre@iz.sh", "emre@iz.sh", "Emre", false, 3) + .await + .unwrap(); + app.fake.set_photo("im-emre@iz.sh", PNG.to_vec(), "image/png"); - let photo = app.get(&format!("/avatar/{admin_id}"), Some(&member)).await; - assert_eq!(photo.status, StatusCode::NOT_FOUND); + let stamped = app + .get(&format!("/avatar/{member_id}?v=3"), Some(&member)) + .await; + assert_eq!(stamped.status, StatusCode::OK); + assert_eq!( + stamped.cache_control.as_deref(), + Some("private, max-age=31536000, immutable") + ); + assert_eq!(stamped.etag.as_deref(), Some("\"p3\"")); + + // Any other spelling — a stale stamp, junk, none — may not be pinned. + for query in ["?v=2", "?v=junk", ""] { + let stray = app + .get(&format!("/avatar/{member_id}{query}"), Some(&member)) + .await; + assert_eq!(stray.cache_control.as_deref(), Some("private, no-cache")); + } + + // im's count moves; the next sync (the stream's event, or the beat) + // carries it onto the row, and the old stamp stops being true. + app.store + .sync_member("sub-emre", "emre@iz.sh", "Emre", false, 4) + .await + .unwrap(); + let moved = app + .get(&format!("/avatar/{member_id}?v=4"), Some(&member)) + .await; + assert_eq!(moved.etag.as_deref(), Some("\"p4\"")); + assert_eq!( + moved.cache_control.as_deref(), + Some("private, max-age=31536000, immutable") + ); + let stale = app + .get(&format!("/avatar/{member_id}?v=3"), Some(&member)) + .await; + assert_eq!(stale.cache_control.as_deref(), Some("private, no-cache")); } -/// Without a session the avatar names the fix: 401, the way the live channel -/// refuses. Catches a proxy that 404s strangers into probing ids. +/// Any member's face serves to any signed-in member — the board shows +/// assignees' faces, so the bytes must be reachable — while a browser +/// without a session is refused outright, the way the live channel is. #[tokio::test] -async fn the_avatar_refuses_a_signed_out_browser() { +async fn another_members_avatar_serves_but_a_signed_out_browser_does_not() { let app = App::open().await; - let _ = admin(&app).await; + let admin_cookie = admin(&app).await; let admin_id = user_id(&app, "ada@iz.sh").await; + let member = invited(&app, &admin_cookie, "emre@iz.sh", "Emre", Role::Member).await; app.fake.set_photo("im-ada", PNG.to_vec(), "image/png"); - let photo = app.get(&format!("/avatar/{admin_id}"), None).await; - assert_eq!(photo.status, StatusCode::UNAUTHORIZED); + let photo = app.get(&format!("/avatar/{admin_id}"), Some(&member)).await; + assert_eq!(photo.status, StatusCode::OK); + assert_eq!(photo.bytes, PNG); + + let refused = app.get(&format!("/avatar/{admin_id}"), None).await; + assert_eq!(refused.status, StatusCode::UNAUTHORIZED); } -/// im has no photo for this account: 404, and the page falls back to -/// initials. Catches a proxy that fails the page around a missing face. +/// A row that has not met the provider — invited, never signed in, never +/// synced — has no face to fetch, and an id nobody holds reads the same. +/// Catches a proxy that fails the page around a missing face. #[tokio::test] -async fn the_avatar_is_not_found_without_an_im_photo() { +async fn the_avatar_is_not_found_without_a_linked_row() { let app = App::open().await; let admin_cookie = admin(&app).await; let member = invited(&app, &admin_cookie, "emre@iz.sh", "Emre", Role::Member).await; @@ -5226,6 +5297,11 @@ async fn the_avatar_is_not_found_without_an_im_photo() { .get(&format!("/avatar/{member_id}"), Some(&member)) .await; assert_eq!(photo.status, StatusCode::NOT_FOUND); + + let stranger = app + .get(&format!("/avatar/{}", Ulid::new()), Some(&member)) + .await; + assert_eq!(stranger.status, StatusCode::NOT_FOUND); } /// Every page with avatars carries the fallback script: the board's topbar