From 364a3eec0d01ae47efecab80993973f31e36684c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Sat, 5 Sep 2026 14:34:37 +0300 Subject: [PATCH] The member list mirrors im's directory: a beat re-reads it at boot and every five minutes, so anyone im knows is assignable and mailable before their first visit --- crates/iz-client/src/lib.rs | 96 +++++++---- crates/iz-core/src/store/mod.rs | 54 +++++-- crates/iz-core/src/store/turso_store.rs | 150 ++++++++++++++++- crates/iz-core/tests/store.rs | 112 ++++++++++++- crates/iz-web/src/main.rs | 37 +++++ crates/iz-web/tests/http.rs | 206 +++++++++++++++++------- 6 files changed, 554 insertions(+), 101 deletions(-) diff --git a/crates/iz-client/src/lib.rs b/crates/iz-client/src/lib.rs index 1fc33b7..e6167ca 100644 --- a/crates/iz-client/src/lib.rs +++ b/crates/iz-client/src/lib.rs @@ -149,6 +149,40 @@ pub async fn photo_for(cx: &Cx, user_id: &str) -> Option<(Vec, String)> { 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, +} + +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() + } +} + /// Path of im's RFC 7662 introspection endpoint, relative to the issuer. const INTROSPECT_PATH: &str = "/introspect"; @@ -573,7 +607,9 @@ async fn exchange_code(state: &IzClient, code: &str, flight: &InFlight) -> Resul let (_user, exp) = match introspect(state, &app_session).await { Introspected::Active(user, exp) => (user, exp), Introspected::Revoked | Introspected::Unanswered => { - return Err(Error::Refused("fresh app session does not introspect".into())); + return Err(Error::Refused( + "fresh app session does not introspect".into(), + )); } }; Ok(Session { app_session, exp }) @@ -709,9 +745,9 @@ mod tests { use super::*; use rsa::signature::{SignatureEncoding, Signer}; use rsa::traits::PublicKeyParts; + use std::sync::{Arc, OnceLock}; use topcoat::cookie::RouterBuilderCookieExt; use topcoat::router::{Body, Router, to_bytes}; - use std::sync::{Arc, OnceLock}; fn keypair() -> (rsa::RsaPrivateKey, rsa::RsaPublicKey) { // 2048-bit generation is slow for a unit test; 1024 is the smallest @@ -847,7 +883,10 @@ mod tests { fn next_allows_plain_local_paths() { assert_eq!(safe_next("/"), "/"); assert_eq!(safe_next("/drive/folder/a"), "/drive/folder/a"); - assert_eq!(safe_next("/?auth_error=exchange_failed"), "/?auth_error=exchange_failed"); + assert_eq!( + safe_next("/?auth_error=exchange_failed"), + "/?auth_error=exchange_failed" + ); } #[test] @@ -879,7 +918,10 @@ mod tests { // `HeaderValue` refuses the injected bytes; the redirect must land // on `/` rather than panic its handler. assert!(HeaderValue::from_str("/\r\nX-evil:1").is_err()); - assert_eq!(location_value("/\r\nX-evil:1"), HeaderValue::from_static("/")); + assert_eq!( + location_value("/\r\nX-evil:1"), + HeaderValue::from_static("/") + ); assert_eq!( location_value("/drive"), HeaderValue::from_str("/drive").unwrap() @@ -1012,8 +1054,7 @@ mod tests { } req.extend_from_slice(&buf[..n]); if let Some(end) = headers_end(&req) { - let head = - String::from_utf8_lossy(&req[..end]).to_string(); + let head = String::from_utf8_lossy(&req[..end]).to_string(); let len = content_length(&head); if req.len() >= end + len { break end; @@ -1023,8 +1064,7 @@ mod tests { return; } }; - let head = - String::from_utf8_lossy(&req[..body_start]).to_string(); + let head = String::from_utf8_lossy(&req[..body_start]).to_string(); let first = head.lines().next().unwrap_or("").to_string(); let len = content_length(&head); req.drain(..body_start + len); @@ -1131,23 +1171,23 @@ mod tests { let _ = canned .jwks .set(serde_json::json!({"keys": [jwk_of(&public, "test")]}).to_string()); - let _ = canned - .token - .set(serde_json::json!({ + let _ = canned.token.set( + serde_json::json!({ "id_token": id_token, "app_session": "tok-1", }) - .to_string()); - let _ = canned - .introspect - .set(serde_json::json!({ + .to_string(), + ); + let _ = canned.introspect.set( + serde_json::json!({ "active": true, "sub": "user-1", "email": "ann@example.com", "name": "Ann", "exp": now + 3600, }) - .to_string()); + .to_string(), + ); let router = test_router(test_config(fake.url())); let callback = TestResponse::of( @@ -1194,23 +1234,23 @@ mod tests { let _ = canned .jwks .set(serde_json::json!({"keys": [jwk_of(&public, "test")]}).to_string()); - let _ = canned - .token - .set(serde_json::json!({ + let _ = canned.token.set( + serde_json::json!({ "id_token": id_token, "app_session": "tok-1", }) - .to_string()); - let _ = canned - .introspect - .set(serde_json::json!({ + .to_string(), + ); + let _ = canned.introspect.set( + serde_json::json!({ "active": true, "sub": "user-1", "email": "ann@example.com", "name": "Ann", "exp": now + 3600, }) - .to_string()); + .to_string(), + ); let router = test_router(test_config(fake.url())); let callback = TestResponse::of( @@ -1317,16 +1357,16 @@ mod tests { async fn current_user_serves_the_introspected_user() { let now = OffsetDateTime::now_utc().unix_timestamp(); let canned = CannedIm::default(); - let _ = canned - .introspect - .set(serde_json::json!({ + let _ = canned.introspect.set( + serde_json::json!({ "active": true, "sub": "user-1", "email": "ann@example.com", "name": "Ann", "exp": now + 3600, }) - .to_string()); + .to_string(), + ); let fake = FakeIm::spawn(canned).await; let router = test_router(test_config(fake.url())); let res = TestResponse::of( diff --git a/crates/iz-core/src/store/mod.rs b/crates/iz-core/src/store/mod.rs index ce6769d..afe9517 100644 --- a/crates/iz-core/src/store/mod.rs +++ b/crates/iz-core/src/store/mod.rs @@ -12,19 +12,19 @@ use crate::Role; use crate::board::{BoardReads, Moved, TaskRow, Transition}; use crate::detail::{ActivityKind, DeletionCost, DetailReads}; -#[cfg(feature = "server")] -pub mod secret; #[cfg(feature = "server")] pub mod reconcile; #[cfg(feature = "server")] -pub mod sniff; -#[cfg(feature = "server")] pub mod schema; +#[cfg(feature = "server")] +pub mod secret; +#[cfg(feature = "server")] +pub mod sniff; pub mod turso_store; -pub use turso_store::TursoStore; #[cfg(feature = "server")] -pub use reconcile::{reconcile, ReconcileOptions}; +pub use reconcile::{ReconcileOptions, reconcile}; +pub use turso_store::TursoStore; #[derive(Debug, Clone, thiserror::Error)] pub enum StoreError { @@ -52,7 +52,6 @@ pub enum StoreError { pub type Result = std::result::Result; - /// A workspace and the settings that ride on it. /// /// The sender is here except for its password, which has no field on purpose: @@ -217,6 +216,22 @@ pub struct UserStats { pub comments: u32, } +/// What one directory sync did to a member row. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum MemberSync { + /// No row carried the person: one was born, linked to their subject. + Inserted, + /// An unclaimed row's address matched: the subject landed on it. + Claimed, + /// The provider's facts (address, name, admin flag) drifted; the row + /// followed, or an unclaimed owner was claimed. + Refreshed, + /// The row already said what the directory says. + Untouched, + /// A new row had no workspace to live in: the first sign-in builds it, + /// and the next beat mirrors everyone. + Skipped, +} /// A task as it is written. The key (`DZ-14`) is not here: the store hands it /// out from the board's counter, so two tasks created at once cannot collide. @@ -664,7 +679,6 @@ pub trait Store: BoardReads + DetailReads + 'static { fn subscribe(&self) -> tokio::sync::broadcast::Receiver; // -- workspace --------------------------------------------------------- - /// The account that claimed the workspace, if it has been claimed. async fn owner(&self) -> Result>; @@ -706,7 +720,6 @@ pub trait Store: BoardReads + DetailReads + 'static { reminder_minutes: u32, ) -> Result<()>; - // -- users ------------------------------------------------------------- /// Upserts the account for a person who just proved who they are to im. @@ -748,6 +761,26 @@ pub trait Store: BoardReads + DetailReads + 'static { role: Role, ) -> Result; + /// Mirrors one entry of im's directory into the member list. + /// + /// The directory vouches the subject, so a person nobody has ever seen + /// 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`]. + async fn sync_member( + &self, + sub: &str, + email: &str, + display_name: &str, + im_admin: bool, + ) -> Result; + async fn user(&self, id: &str) -> Result>; /// Lookup by address. Callers must not turn a `None` into a different @@ -765,7 +798,6 @@ pub trait Store: BoardReads + DetailReads + 'static { /// This is a read, for looking: nothing announces. async fn user_stats(&self, user_id: &str) -> Result; - /// Display-only preferences: stored data stays UTC/neutral, these only /// change how a browser renders it for this one person. async fn set_preferences( @@ -782,8 +814,6 @@ pub trait Store: BoardReads + DetailReads + 'static { /// layer reads this and treats the person as signed out. async fn set_user_disabled(&self, user_id: &str, disabled: bool) -> Result<()>; - - // -- board ------------------------------------------------------------- /// Adds a column to the end of a board. diff --git a/crates/iz-core/src/store/turso_store.rs b/crates/iz-core/src/store/turso_store.rs index 65a03e7..d46cf04 100644 --- a/crates/iz-core/src/store/turso_store.rs +++ b/crates/iz-core/src/store/turso_store.rs @@ -17,9 +17,9 @@ use super::secret; use super::{ ActivityEvent, ActivityFilter, ActivityLine, Attachment, Audience, ClaimedSend, CommentWritten, Deletion, Dir, Event, FeedCursor, FeedPage, Freeing, MailDecision, MailOutcome, MailRule, - MailSend, NewAttachment, NewSender, NewTask, Recipient, Result, SendKind, SendState, - SenderCheck, SenderTest, Store, StoreError, Tag, TaskCreated, Trigger, User, UserStats, - Workspace, + MailSend, MemberSync, NewAttachment, NewSender, NewTask, Recipient, Result, SendKind, + SendState, SenderCheck, SenderTest, Store, StoreError, Tag, TaskCreated, Trigger, User, + UserStats, Workspace, }; use super::{ReconcileOptions, reconcile, schema, sniff}; use crate::Role; @@ -1369,6 +1369,146 @@ impl Store for TursoStore { self.user(&id).await?.ok_or(StoreError::NotFound) } + async fn sync_member( + &self, + sub: &str, + email: &str, + display_name: &str, + im_admin: bool, + ) -> Result { + let email = fold_email(email); + // IMMEDIATE like provision_user: a beat racing a first sign-in over + // the same address must not double the row, and two admin sightings + // must not both claim the owner. + let mut conn = self.tx_conn().await?; + let tx = conn + .transaction_with_behavior(TransactionBehavior::Immediate) + .await + .map_err(backend)?; + let now = now_text()?; + let by_sub = format!("SELECT {USER_COLUMNS} FROM user WHERE oidc_sub = ?1"); + let mut rows = tx.query(&by_sub, params![sub]).await.map_err(backend)?; + let seen = match rows.next().await.map_err(backend)? { + Some(row) => Some(user_from(&row)?), + None => None, + }; + drop(rows); + let outcome = if let Some(user) = seen { + 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 { + 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()], + ) + .await + .map_err(backend)?; + Some((user.id, MemberSync::Refreshed)) + } + } else { + let by_email = + format!("SELECT {USER_COLUMNS} FROM user WHERE email = ?1 COLLATE NOCASE"); + let mut rows = tx + .query(&by_email, params![email.clone()]) + .await + .map_err(backend)?; + let seen = match rows.next().await.map_err(backend)? { + Some(row) => Some(user_from(&row)?), + None => None, + }; + drop(rows); + 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", + params![ + sub, + email.clone(), + display_name, + role.as_str(), + user.id.clone() + ], + ) + .await + .map_err(backend)?; + Some((user.id, MemberSync::Claimed)) + } else { + let known = { + let mut rows = tx + .query("SELECT id FROM workspace LIMIT 1", ()) + .await + .map_err(backend)?; + let known = match rows.next().await.map_err(backend)? { + Some(row) => Some(text(&row, 0)?), + None => None, + }; + drop(rows); + known + }; + match known { + None => None, + Some(workspace_id) => { + // Born linked: the directory vouches the subject, so + // the row never waits unclaimed — assignment, mail + // and the avatar proxy work before the first visit. + let id = Ulid::new().to_string(); + 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)", + params![ + id.clone(), + workspace_id, + sub, + email.clone(), + display_name, + role.as_str(), + now.clone() + ], + ) + .await + .map_err(backend)?; + Some((id, MemberSync::Inserted)) + } + } + } + }; + let Some((id, mut sync)) = outcome else { + // No workspace to put a new row in: the first sign-in builds it, + // and the next beat mirrors everyone. Nothing was written. + drop(tx); + drop(conn); + return Ok(MemberSync::Skipped); + }; + if im_admin { + // Same conditional claim as provision_user: the provider's first + // admin owns the workspace, a later one never steals it. + let claimed = tx + .execute( + "INSERT INTO workspace_owner (singleton, user_id, claimed_at) \ + SELECT 1, ?1, ?2 WHERE NOT EXISTS \ + (SELECT 1 FROM workspace_owner WHERE singleton = 1)", + params![id.clone(), now.clone()], + ) + .await + .map_err(backend)?; + if claimed > 0 && sync == MemberSync::Untouched { + sync = MemberSync::Refreshed; + } + } + tx.commit().await.map_err(backend)?; + drop(conn); + if sync != MemberSync::Untouched { + self.announce([Topic::Members]); + } + Ok(sync) + } + async fn add_member( &self, workspace_id: &str, @@ -1393,7 +1533,9 @@ impl Store for TursoStore { // unique index below means what the case-insensitive check here // says even for rows the password era left unfolded. let seen = { - let sql = format!("SELECT {USER_COLUMNS} FROM user WHERE workspace_id = ?1 AND email = ?2 COLLATE NOCASE"); + let sql = format!( + "SELECT {USER_COLUMNS} FROM user WHERE workspace_id = ?1 AND email = ?2 COLLATE NOCASE" + ); self.one_row(&sql, params![workspace_id, email.clone()]) .await? }; diff --git a/crates/iz-core/tests/store.rs b/crates/iz-core/tests/store.rs index 414e8da..f84b97d 100644 --- a/crates/iz-core/tests/store.rs +++ b/crates/iz-core/tests/store.rs @@ -8069,7 +8069,10 @@ async fn an_added_member_waits_unclaimed_until_their_first_sign_in() { .into_iter() .map(|user| user.email) .collect(); - assert_eq!(names, vec!["ada@iz.sh".to_string(), "mert@iz.sh".to_string()]); + assert_eq!( + names, + vec!["ada@iz.sh".to_string(), "mert@iz.sh".to_string()] + ); } #[tokio::test] @@ -8253,3 +8256,110 @@ async fn set_user_disabled_round_trips() { Err(StoreError::NotFound) )); } + +#[tokio::test] +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) + .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.oidc_sub.as_deref(), Some("sub-mert")); + assert_eq!(row.role, Role::Member); + 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) + .await + .unwrap(); + let boss = scratch + .store + .user_by_email(&workspace, "boss@iz.sh") + .await + .unwrap() + .unwrap(); + assert_eq!(boss.role, Role::Admin); +} + +#[tokio::test] +async fn a_sync_claims_an_unclaimed_row_without_touching_its_sign_in_fact() { + let (scratch, workspace, _admin) = workspace_with_admin().await; + let added = scratch + .store + .add_member(&workspace, "mert@iz.sh", "Mert", Role::Viewer) + .await + .unwrap(); + let sync = scratch + .store + .sync_member("sub-mert", "MERT@iz.sh", "Mert Yılmaz", false) + .await + .unwrap(); + assert_eq!(sync, iz_core::store::MemberSync::Claimed); + let row = scratch.store.user(&added.id).await.unwrap().unwrap(); + assert_eq!(row.oidc_sub.as_deref(), Some("sub-mert")); + assert_eq!(row.display_name, "Mert Yılmaz"); + assert_eq!( + row.role, + Role::Viewer, + "a local role is not the directory's" + ); + assert!(row.last_signed_in_at.is_none(), "a sync is not a sign-in"); +} + +#[tokio::test] +async fn a_sync_follows_provider_drift_but_not_the_sign_in_fact() { + let (scratch, workspace, admin_id) = workspace_with_admin().await; + 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) + .await + .unwrap(); + assert_eq!(sync, iz_core::store::MemberSync::Refreshed); + let after = scratch.store.user(&admin_id).await.unwrap().unwrap(); + assert_eq!(after.display_name, "Ada Lovelace"); + 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) + .await + .unwrap(); + let demoted = scratch.store.user(&admin_id).await.unwrap().unwrap(); + assert_eq!(demoted.role, Role::Member); +} + +#[tokio::test] +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) + .await + .unwrap(); + assert_eq!(sync, iz_core::store::MemberSync::Untouched); + assert!(announced(&mut rx).is_empty()); +} + +#[tokio::test] +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) + .await + .unwrap(); + assert_eq!(sync, iz_core::store::MemberSync::Skipped); + assert!(scratch.store.workspace().await.unwrap().is_none()); +} diff --git a/crates/iz-web/src/main.rs b/crates/iz-web/src/main.rs index 09d35c9..e479ee1 100644 --- a/crates/iz-web/src/main.rs +++ b/crates/iz-web/src/main.rs @@ -137,6 +137,14 @@ 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. + tokio::spawn(directory_sync( + store.clone(), + iz_client::IzClient::new(oidc.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); @@ -296,6 +304,35 @@ async fn sweep(engine: std::sync::Arc, store: Arc, client: iz_client::IzClient) { + 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"), + } + tokio::time::sleep(std::time::Duration::from_secs(DIRECTORY_SECONDS)).await; + } +} + /// Waits for something to happen to the mail queue specifically. /// /// The channel carries every topic, and the sweep cares about one. Filtering diff --git a/crates/iz-web/tests/http.rs b/crates/iz-web/tests/http.rs index fbaaaca..5e45d83 100644 --- a/crates/iz-web/tests/http.rs +++ b/crates/iz-web/tests/http.rs @@ -120,20 +120,21 @@ impl FakeIm { let len = content_length(&head); let body: Vec = req[body_start..body_start + len].to_vec(); req.drain(..body_start + len); - let (status, content_type, payload) = match photo_answer(&pmap, &head, &first) { - Some(photo) => photo, - None => match answer_for(&map, &first, &body) { - Some(answer) => ( - "200 OK", - "application/json".to_string(), - serde_json::to_vec(&answer).unwrap(), - ), - // Anything but the introspection route is - // nothing at all, the way the real im 404s - // unknown paths rather than answering them. - None => ("404 Not Found", "text/plain".to_string(), Vec::new()), - }, - }; + let (status, content_type, payload) = + match photo_answer(&pmap, &head, &first) { + Some(photo) => photo, + None => match answer_for(&map, &first, &body) { + Some(answer) => ( + "200 OK", + "application/json".to_string(), + serde_json::to_vec(&answer).unwrap(), + ), + // Anything but the introspection route is + // nothing at all, the way the real im 404s + // unknown paths rather than answering them. + None => ("404 Not Found", "text/plain".to_string(), Vec::new()), + }, + }; let response = format!( "HTTP/1.1 {status}\r\ncontent-type: {content_type}\r\ncontent-length: {}\r\n\r\n", payload.len() @@ -148,7 +149,11 @@ impl FakeIm { }); } }); - Self { addr, tokens, photos } + Self { + addr, + tokens, + photos, + } } fn url(&self) -> String { @@ -180,7 +185,10 @@ fn photo_answer( return None; } let target = parts.next().unwrap_or(""); - let path = target.split_once('?').map(|(path, _)| path).unwrap_or(target); + let path = target + .split_once('?') + .map(|(path, _)| path) + .unwrap_or(target); let id = path.strip_prefix("/photo/")?; if id.is_empty() || id.contains('/') { return None; @@ -240,7 +248,8 @@ fn answer_for( body: &[u8], ) -> Option { let mut head = request_line.split_whitespace(); - let is_introspect = head.next() == Some("POST") && head.next() == Some(iz_client::introspect_path()); + let is_introspect = + head.next() == Some("POST") && head.next() == Some(iz_client::introspect_path()); if !is_introspect { return None; } @@ -785,7 +794,11 @@ async fn admin(app: &App) -> String { .provision_user(sub, "ada@iz.sh", "Ada Lovelace", true) .await .unwrap(); - assert_eq!(user.role, Role::Admin, "the first im admin did not claim admin"); + assert_eq!( + user.role, + Role::Admin, + "the first im admin did not claim admin" + ); app.mint(sub, "ada@iz.sh", "Ada Lovelace", true) } @@ -1915,7 +1928,6 @@ async fn a_parents_own_part_is_not_offered_as_a_blocker() { ); } - #[tokio::test] async fn the_whole_control_box_opens_its_dropdown() { // A status control is a box holding a dot, the trigger and a chevron. @@ -2281,7 +2293,6 @@ async fn the_soft_swap_rewrites_the_url_before_the_new_pages_scripts_run() { ); } - #[tokio::test] async fn a_member_who_posts_new_limits_anyway_is_refused() { let app = App::open().await; @@ -2814,8 +2825,6 @@ async fn a_non_admin_may_not_set_roles_over_http() { ); } - - // --------------------------------------------------------------------------- // Settings visibility: the sender and the member list are the admin's // --------------------------------------------------------------------------- @@ -4200,7 +4209,12 @@ async fn a_stamp_shifts_with_the_viewers_stored_timezone() { .post( "/api/save_profile", Some(&admin_cookie), - &[("timezone", "UTC+03:00"), ("theme", "light"), ("language", "en"), ("ui", "instrument")], + &[ + ("timezone", "UTC+03:00"), + ("theme", "light"), + ("language", "en"), + ("ui", "instrument"), + ], ) .await; assert!( @@ -4255,7 +4269,12 @@ async fn a_task_modal_stamp_shifts_with_the_viewers_stored_timezone() { .post( "/api/save_profile", Some(&admin_cookie), - &[("timezone", "UTC+03:00"), ("theme", "light"), ("language", "en"), ("ui", "instrument")], + &[ + ("timezone", "UTC+03:00"), + ("theme", "light"), + ("language", "en"), + ("ui", "instrument"), + ], ) .await; assert!( @@ -4292,7 +4311,10 @@ async fn an_unlisted_timezone_is_refused() { "/api/save_profile", Some(&admin_cookie), &[ - ("timezone", "Mars/Olympus_Mons"), ("theme", "light"), ("language", "en"), ("ui", "instrument"), + ("timezone", "Mars/Olympus_Mons"), + ("theme", "light"), + ("language", "en"), + ("ui", "instrument"), ], ) .await; @@ -4312,7 +4334,12 @@ async fn the_dark_theme_is_saved_and_marks_the_page() { .post( "/api/save_profile", Some(&admin_cookie), - &[("timezone", "UTC"), ("theme", "dark"), ("language", "en"), ("ui", "instrument")], + &[ + ("timezone", "UTC"), + ("theme", "dark"), + ("language", "en"), + ("ui", "instrument"), + ], ) .await; assert!( @@ -4339,7 +4366,12 @@ async fn turkish_is_saved_and_the_board_renders_in_turkish() { .post( "/api/save_profile", Some(&admin_cookie), - &[("timezone", "UTC"), ("theme", "light"), ("language", "tr"), ("ui", "instrument")], + &[ + ("timezone", "UTC"), + ("theme", "light"), + ("language", "tr"), + ("ui", "instrument"), + ], ) .await; assert!( @@ -4375,7 +4407,12 @@ async fn an_unlisted_language_is_refused() { .post( "/api/save_profile", Some(&admin_cookie), - &[("timezone", "UTC"), ("theme", "light"), ("language", "fr"), ("ui", "instrument")], + &[ + ("timezone", "UTC"), + ("theme", "light"), + ("language", "fr"), + ("ui", "instrument"), + ], ) .await; assert_eq!( @@ -4393,7 +4430,12 @@ async fn an_unlisted_theme_is_refused() { .post( "/api/save_profile", Some(&admin_cookie), - &[("timezone", "UTC"), ("theme", "neon"), ("language", "en"), ("ui", "instrument")], + &[ + ("timezone", "UTC"), + ("theme", "neon"), + ("language", "en"), + ("ui", "instrument"), + ], ) .await; let location = answer.location.as_deref().unwrap_or_default(); @@ -4412,7 +4454,12 @@ async fn the_ledger_ui_is_saved_and_marks_the_page() { .post( "/api/save_profile", Some(&admin_cookie), - &[("timezone", "UTC"), ("theme", "light"), ("language", "en"), ("ui", "ledger")], + &[ + ("timezone", "UTC"), + ("theme", "light"), + ("language", "en"), + ("ui", "ledger"), + ], ) .await; assert!( @@ -4439,7 +4486,12 @@ async fn an_unlisted_ui_is_refused() { .post( "/api/save_profile", Some(&admin_cookie), - &[("timezone", "UTC"), ("theme", "light"), ("language", "en"), ("ui", "neon")], + &[ + ("timezone", "UTC"), + ("theme", "light"), + ("language", "en"), + ("ui", "neon"), + ], ) .await; let location = answer.location.as_deref().unwrap_or_default(); @@ -4594,7 +4646,11 @@ async fn the_im_admin_flag_makes_an_admin() { .await .unwrap() .expect("no local row after the first login"); - assert_eq!(user.role, Role::Admin, "the im admin flag did not make an admin"); + assert_eq!( + user.role, + Role::Admin, + "the im admin flag did not make an admin" + ); } /// A first SSO login claims the legacy row by address: the `sub` is stamped @@ -4608,10 +4664,7 @@ async fn a_first_sso_login_claims_the_legacy_row_by_address() { .provision_user("im-old", "ada@iz.sh", "Ada Lovelace", false) .await .unwrap(); - app.store - .set_role(&legacy.id, Role::Viewer) - .await - .unwrap(); + app.store.set_role(&legacy.id, Role::Viewer).await.unwrap(); let cookie = app.mint("im-new", "ada@iz.sh", "Ada Lovelace", false); let page = app.get("/", Some(&cookie)).await; @@ -4623,7 +4676,10 @@ async fn a_first_sso_login_claims_the_legacy_row_by_address() { .await .unwrap() .expect("the address has no row after claiming"); - assert_eq!(claimed.id, legacy.id, "the login did not claim the legacy row"); + assert_eq!( + claimed.id, legacy.id, + "the login did not claim the legacy row" + ); assert_eq!( claimed.role, Role::Viewer, @@ -4641,10 +4697,7 @@ async fn a_disabled_member_reads_as_signed_out() { let admin_cookie = admin(&app).await; let member = invited(&app, &admin_cookie, "emre@iz.sh", "Emre", Role::Member).await; let member_id = user_id(&app, "emre@iz.sh").await; - app.store - .set_user_disabled(&member_id, true) - .await - .unwrap(); + app.store.set_user_disabled(&member_id, true).await.unwrap(); let page = app.get("/", Some(&member)).await; let html = String::from_utf8_lossy(&page.bytes); @@ -4730,11 +4783,7 @@ async fn set_role_cannot_make_an_admin() { ); let reloaded = app.store.user(&member_id).await.unwrap().unwrap(); - assert_eq!( - reloaded.role, - Role::Member, - "set_role made an admin anyway" - ); + assert_eq!(reloaded.role, Role::Member, "set_role made an admin anyway"); } /// An admin may add a member who has never signed in, and the row is a @@ -4776,6 +4825,43 @@ async fn an_admin_may_add_a_member_before_their_first_sign_in() { app.store.assign_task(&task, &member_id).await.unwrap(); } +/// A member the directory beat mirrored — born linked, never signed in — +/// is a member like any other: in the picker list and assignable straight +/// away. Catches a sync that writes rows the board cannot see. +#[tokio::test] +async fn a_synced_member_is_listed_and_assignable_before_their_first_sign_in() { + let app = App::open().await; + let admin_cookie = admin(&app).await; + let admin_row = app + .store + .user(&user_id(&app, "ada@iz.sh").await) + .await + .unwrap() + .unwrap(); + + let sync = app + .store + .sync_member("sub-mert", "mert@iz.sh", "Mert", false) + .await + .unwrap(); + assert_eq!(sync, iz_core::store::MemberSync::Inserted); + + let member_id = user_id(&app, "mert@iz.sh").await; + let row = app.store.user(&member_id).await.unwrap().unwrap(); + assert_eq!(row.oidc_sub.as_deref(), Some("sub-mert")); + assert!(row.last_signed_in_at.is_none()); + + let listed = app.store.users(&admin_row.workspace_id).await.unwrap(); + assert!( + listed.iter().any(|user| user.id == member_id), + "the picker's source does not list the synced member" + ); + + let column = first_column(&app).await; + let task = a_task(&app, &admin_cookie, &column, "Onboard Mert").await; + app.store.assign_task(&task, &member_id).await.unwrap(); +} + /// A member who posts to the add route anyway is refused, and no row is /// written. Catches a handler that trusts the form's being hidden. #[tokio::test] @@ -5031,7 +5117,9 @@ async fn the_avatar_is_not_found_without_an_im_photo() { let member = invited(&app, &admin_cookie, "emre@iz.sh", "Emre", Role::Member).await; let member_id = user_id(&app, "emre@iz.sh").await; - let photo = app.get(&format!("/avatar/{member_id}"), Some(&member)).await; + let photo = app + .get(&format!("/avatar/{member_id}"), Some(&member)) + .await; assert_eq!(photo.status, StatusCode::NOT_FOUND); } /// Polls the store until a `Rule` send for `rule_id` addressed to `recipient` @@ -5329,7 +5417,6 @@ async fn user_id(app: &App, email: &str) -> String { .id } - /// The nav shows a page only to a role that can act on it: an admin's board /// carries all four links, a member's carries neither Rules nor Logs. #[tokio::test] @@ -7962,7 +8049,12 @@ async fn a_clock_saved_on_a_task_renders_in_the_viewers_stored_timezone() { .post( "/api/save_profile", Some(&admin_cookie), - &[("timezone", "UTC+03:00"), ("theme", "light"), ("language", "en"), ("ui", "instrument")], + &[ + ("timezone", "UTC+03:00"), + ("theme", "light"), + ("language", "en"), + ("ui", "instrument"), + ], ) .await; assert!( @@ -8321,7 +8413,12 @@ async fn a_card_wears_the_clock_chip_in_the_viewers_zone_instead_of_the_deadline .post( "/api/save_profile", Some(&admin_cookie), - &[("timezone", "UTC+03:00"), ("theme", "light"), ("language", "en"), ("ui", "instrument")], + &[ + ("timezone", "UTC+03:00"), + ("theme", "light"), + ("language", "en"), + ("ui", "instrument"), + ], ) .await; assert!( @@ -9008,7 +9105,6 @@ async fn checking_the_sender_records_an_event() { assert_eq!(lines[0].actor_name.as_deref(), Some("Ada Lovelace")); } - /// A card's dependency summary names both directions with keys: what the card /// blocks and what blocks it, the same list shape either way. #[tokio::test] @@ -9057,11 +9153,9 @@ async fn a_card_lists_both_dependency_directions_as_keys() { )), "the blocker's card did not name what it blocks: {html}" ); - assert!( - html.contains(&format!( - r#"class="card-blocked-by">blocked by {first_key}"# - )), - ); + assert!(html.contains(&format!( + r#"class="card-blocked-by">blocked by {first_key}"# + )),); } /// The board search filters server-side by key and title, composes with the