forge
Explore
Log in

Don't you dare go Hollow

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

Browse files at this commit

364a3eec0d01ae47efecab80993973f31e36684cAhmet Kaan GümüşParent: 8869c7c
crates/iz-client/src/lib.rsmodified+68 -28
@@ -149,6 +149,40 @@ pub async fn photo_for(cx: &Cx, user_id: &str) -> Option<(Vec<u8>, String)> {
149 Some((bytes, mime))149 Some((bytes, mime))
150 }150 }
151 151
152+/// One entry of im's directory: the stable subject, the address, the
153+/// display name, and whether im calls the person an admin — exactly what
154+/// mirroring the directory into local member rows needs.
155+#[derive(Debug, Clone, serde::Deserialize)]
156+pub struct DirectoryMember {
157+ pub sub: String,
158+ pub email: String,
159+ pub name: String,
160+ #[serde(default)]
161+ pub admin: bool,
162+}
163+
164+impl IzClient {
165+ /// The family phonebook: every non-disabled user im knows, fetched as
166+ /// the app (`Authorization: Basic` with the client pair, the same
167+ /// credentials the photo route takes). `None` on anything that is not a
168+ /// readable list — a refused pair, a dropped connection, a body that is
169+ /// not the array — because a missed beat must never look like an empty
170+ /// directory: the caller keeps the rows it has and asks again next beat.
171+ pub async fn directory(&self) -> Option<Vec<DirectoryMember>> {
172+ let reply = self
173+ .http
174+ .get(format!("{}/directory", self.config.issuer))
175+ .basic_auth(&self.config.client_id, Some(&self.config.client_secret))
176+ .send()
177+ .await
178+ .ok()?;
179+ if !reply.status().is_success() {
180+ return None;
181+ }
182+ reply.json().await.ok()
183+ }
184+}
185+
152 /// Path of im's RFC 7662 introspection endpoint, relative to the issuer.186 /// Path of im's RFC 7662 introspection endpoint, relative to the issuer.
153 const INTROSPECT_PATH: &str = "/introspect";187 const INTROSPECT_PATH: &str = "/introspect";
154 188
@@ -573,7 +607,9 @@ async fn exchange_code(state: &IzClient, code: &str, flight: &InFlight) -> Resul
573 let (_user, exp) = match introspect(state, &app_session).await {607 let (_user, exp) = match introspect(state, &app_session).await {
574 Introspected::Active(user, exp) => (user, exp),608 Introspected::Active(user, exp) => (user, exp),
575 Introspected::Revoked | Introspected::Unanswered => {609 Introspected::Revoked | Introspected::Unanswered => {
576- return Err(Error::Refused("fresh app session does not introspect".into()));610+ return Err(Error::Refused(
611+ "fresh app session does not introspect".into(),
612+ ));
577 }613 }
578 };614 };
579 Ok(Session { app_session, exp })615 Ok(Session { app_session, exp })
@@ -709,9 +745,9 @@ mod tests {
709 use super::*;745 use super::*;
710 use rsa::signature::{SignatureEncoding, Signer};746 use rsa::signature::{SignatureEncoding, Signer};
711 use rsa::traits::PublicKeyParts;747 use rsa::traits::PublicKeyParts;
748+ use std::sync::{Arc, OnceLock};
712 use topcoat::cookie::RouterBuilderCookieExt;749 use topcoat::cookie::RouterBuilderCookieExt;
713 use topcoat::router::{Body, Router, to_bytes};750 use topcoat::router::{Body, Router, to_bytes};
714- use std::sync::{Arc, OnceLock};
715 751
716 fn keypair() -> (rsa::RsaPrivateKey, rsa::RsaPublicKey) {752 fn keypair() -> (rsa::RsaPrivateKey, rsa::RsaPublicKey) {
717 // 2048-bit generation is slow for a unit test; 1024 is the smallest753 // 2048-bit generation is slow for a unit test; 1024 is the smallest
@@ -847,7 +883,10 @@ mod tests {
847 fn next_allows_plain_local_paths() {883 fn next_allows_plain_local_paths() {
848 assert_eq!(safe_next("/"), "/");884 assert_eq!(safe_next("/"), "/");
849 assert_eq!(safe_next("/drive/folder/a"), "/drive/folder/a");885 assert_eq!(safe_next("/drive/folder/a"), "/drive/folder/a");
850- assert_eq!(safe_next("/?auth_error=exchange_failed"), "/?auth_error=exchange_failed");886+ assert_eq!(
887+ safe_next("/?auth_error=exchange_failed"),
888+ "/?auth_error=exchange_failed"
889+ );
851 }890 }
852 891
853 #[test]892 #[test]
@@ -879,7 +918,10 @@ mod tests {
879 // `HeaderValue` refuses the injected bytes; the redirect must land918 // `HeaderValue` refuses the injected bytes; the redirect must land
880 // on `/` rather than panic its handler.919 // on `/` rather than panic its handler.
881 assert!(HeaderValue::from_str("/\r\nX-evil:1").is_err());920 assert!(HeaderValue::from_str("/\r\nX-evil:1").is_err());
882- assert_eq!(location_value("/\r\nX-evil:1"), HeaderValue::from_static("/"));921+ assert_eq!(
922+ location_value("/\r\nX-evil:1"),
923+ HeaderValue::from_static("/")
924+ );
883 assert_eq!(925 assert_eq!(
884 location_value("/drive"),926 location_value("/drive"),
885 HeaderValue::from_str("/drive").unwrap()927 HeaderValue::from_str("/drive").unwrap()
@@ -1012,8 +1054,7 @@ mod tests {
1012 }1054 }
1013 req.extend_from_slice(&buf[..n]);1055 req.extend_from_slice(&buf[..n]);
1014 if let Some(end) = headers_end(&req) {1056 if let Some(end) = headers_end(&req) {
1015- let head =1057+ let head = String::from_utf8_lossy(&req[..end]).to_string();
1016- String::from_utf8_lossy(&req[..end]).to_string();
1017 let len = content_length(&head);1058 let len = content_length(&head);
1018 if req.len() >= end + len {1059 if req.len() >= end + len {
1019 break end;1060 break end;
@@ -1023,8 +1064,7 @@ mod tests {
1023 return;1064 return;
1024 }1065 }
1025 };1066 };
1026- let head =1067+ let head = String::from_utf8_lossy(&req[..body_start]).to_string();
1027- String::from_utf8_lossy(&req[..body_start]).to_string();
1028 let first = head.lines().next().unwrap_or("").to_string();1068 let first = head.lines().next().unwrap_or("").to_string();
1029 let len = content_length(&head);1069 let len = content_length(&head);
1030 req.drain(..body_start + len);1070 req.drain(..body_start + len);
@@ -1131,23 +1171,23 @@ mod tests {
1131 let _ = canned1171 let _ = canned
1132 .jwks1172 .jwks
1133 .set(serde_json::json!({"keys": [jwk_of(&public, "test")]}).to_string());1173 .set(serde_json::json!({"keys": [jwk_of(&public, "test")]}).to_string());
1134- let _ = canned1174+ let _ = canned.token.set(
1135- .token1175+ serde_json::json!({
1136- .set(serde_json::json!({
1137 "id_token": id_token,1176 "id_token": id_token,
1138 "app_session": "tok-1",1177 "app_session": "tok-1",
1139 })1178 })
1140- .to_string());1179+ .to_string(),
1141- let _ = canned1180+ );
1142- .introspect1181+ let _ = canned.introspect.set(
1143- .set(serde_json::json!({1182+ serde_json::json!({
1144 "active": true,1183 "active": true,
1145 "sub": "user-1",1184 "sub": "user-1",
1146 "email": "ann@example.com",1185 "email": "ann@example.com",
1147 "name": "Ann",1186 "name": "Ann",
1148 "exp": now + 3600,1187 "exp": now + 3600,
1149 })1188 })
1150- .to_string());1189+ .to_string(),
1190+ );
1151 1191
1152 let router = test_router(test_config(fake.url()));1192 let router = test_router(test_config(fake.url()));
1153 let callback = TestResponse::of(1193 let callback = TestResponse::of(
@@ -1194,23 +1234,23 @@ mod tests {
1194 let _ = canned1234 let _ = canned
1195 .jwks1235 .jwks
1196 .set(serde_json::json!({"keys": [jwk_of(&public, "test")]}).to_string());1236 .set(serde_json::json!({"keys": [jwk_of(&public, "test")]}).to_string());
1197- let _ = canned1237+ let _ = canned.token.set(
1198- .token1238+ serde_json::json!({
1199- .set(serde_json::json!({
1200 "id_token": id_token,1239 "id_token": id_token,
1201 "app_session": "tok-1",1240 "app_session": "tok-1",
1202 })1241 })
1203- .to_string());1242+ .to_string(),
1204- let _ = canned1243+ );
1205- .introspect1244+ let _ = canned.introspect.set(
1206- .set(serde_json::json!({1245+ serde_json::json!({
1207 "active": true,1246 "active": true,
1208 "sub": "user-1",1247 "sub": "user-1",
1209 "email": "ann@example.com",1248 "email": "ann@example.com",
1210 "name": "Ann",1249 "name": "Ann",
1211 "exp": now + 3600,1250 "exp": now + 3600,
1212 })1251 })
1213- .to_string());1252+ .to_string(),
1253+ );
1214 1254
1215 let router = test_router(test_config(fake.url()));1255 let router = test_router(test_config(fake.url()));
1216 let callback = TestResponse::of(1256 let callback = TestResponse::of(
@@ -1317,16 +1357,16 @@ mod tests {
1317 async fn current_user_serves_the_introspected_user() {1357 async fn current_user_serves_the_introspected_user() {
1318 let now = OffsetDateTime::now_utc().unix_timestamp();1358 let now = OffsetDateTime::now_utc().unix_timestamp();
1319 let canned = CannedIm::default();1359 let canned = CannedIm::default();
1320- let _ = canned1360+ let _ = canned.introspect.set(
1321- .introspect1361+ serde_json::json!({
1322- .set(serde_json::json!({
1323 "active": true,1362 "active": true,
1324 "sub": "user-1",1363 "sub": "user-1",
1325 "email": "ann@example.com",1364 "email": "ann@example.com",
1326 "name": "Ann",1365 "name": "Ann",
1327 "exp": now + 3600,1366 "exp": now + 3600,
1328 })1367 })
1329- .to_string());1368+ .to_string(),
1369+ );
1330 let fake = FakeIm::spawn(canned).await;1370 let fake = FakeIm::spawn(canned).await;
1331 let router = test_router(test_config(fake.url()));1371 let router = test_router(test_config(fake.url()));
1332 let res = TestResponse::of(1372 let res = TestResponse::of(
crates/iz-core/src/store/mod.rsmodified+42 -12
@@ -12,19 +12,19 @@ use crate::Role;
12 use crate::board::{BoardReads, Moved, TaskRow, Transition};12 use crate::board::{BoardReads, Moved, TaskRow, Transition};
13 use crate::detail::{ActivityKind, DeletionCost, DetailReads};13 use crate::detail::{ActivityKind, DeletionCost, DetailReads};
14 14
15-#[cfg(feature = "server")]
16-pub mod secret;
17 #[cfg(feature = "server")]15 #[cfg(feature = "server")]
18 pub mod reconcile;16 pub mod reconcile;
19 #[cfg(feature = "server")]17 #[cfg(feature = "server")]
20-pub mod sniff;
21-#[cfg(feature = "server")]
22 pub mod schema;18 pub mod schema;
19+#[cfg(feature = "server")]
20+pub mod secret;
21+#[cfg(feature = "server")]
22+pub mod sniff;
23 pub mod turso_store;23 pub mod turso_store;
24 24
25-pub use turso_store::TursoStore;
26 #[cfg(feature = "server")]25 #[cfg(feature = "server")]
27-pub use reconcile::{reconcile, ReconcileOptions};26+pub use reconcile::{ReconcileOptions, reconcile};
27+pub use turso_store::TursoStore;
28 28
29 #[derive(Debug, Clone, thiserror::Error)]29 #[derive(Debug, Clone, thiserror::Error)]
30 pub enum StoreError {30 pub enum StoreError {
@@ -52,7 +52,6 @@ pub enum StoreError {
52 52
53 pub type Result<T> = std::result::Result<T, StoreError>;53 pub type Result<T> = std::result::Result<T, StoreError>;
54 54
55-
56 /// A workspace and the settings that ride on it.55 /// A workspace and the settings that ride on it.
57 ///56 ///
58 /// The sender is here except for its password, which has no field on purpose:57 /// The sender is here except for its password, which has no field on purpose:
@@ -217,6 +216,22 @@ pub struct UserStats {
217 pub comments: u32,216 pub comments: u32,
218 }217 }
219 218
219+/// What one directory sync did to a member row.
220+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
221+pub enum MemberSync {
222+ /// No row carried the person: one was born, linked to their subject.
223+ Inserted,
224+ /// An unclaimed row's address matched: the subject landed on it.
225+ Claimed,
226+ /// The provider's facts (address, name, admin flag) drifted; the row
227+ /// followed, or an unclaimed owner was claimed.
228+ Refreshed,
229+ /// The row already said what the directory says.
230+ Untouched,
231+ /// A new row had no workspace to live in: the first sign-in builds it,
232+ /// and the next beat mirrors everyone.
233+ Skipped,
234+}
220 235
221 /// A task as it is written. The key (`DZ-14`) is not here: the store hands it236 /// A task as it is written. The key (`DZ-14`) is not here: the store hands it
222 /// out from the board's counter, so two tasks created at once cannot collide.237 /// out from the board's counter, so two tasks created at once cannot collide.
@@ -664,7 +679,6 @@ pub trait Store: BoardReads + DetailReads + 'static {
664 fn subscribe(&self) -> tokio::sync::broadcast::Receiver<crate::live::Change>;679 fn subscribe(&self) -> tokio::sync::broadcast::Receiver<crate::live::Change>;
665 // -- workspace ---------------------------------------------------------680 // -- workspace ---------------------------------------------------------
666 681
667-
668 /// The account that claimed the workspace, if it has been claimed.682 /// The account that claimed the workspace, if it has been claimed.
669 async fn owner(&self) -> Result<Option<User>>;683 async fn owner(&self) -> Result<Option<User>>;
670 684
@@ -706,7 +720,6 @@ pub trait Store: BoardReads + DetailReads + 'static {
706 reminder_minutes: u32,720 reminder_minutes: u32,
707 ) -> Result<()>;721 ) -> Result<()>;
708 722
709-
710 // -- users -------------------------------------------------------------723 // -- users -------------------------------------------------------------
711 724
712 /// Upserts the account for a person who just proved who they are to im.725 /// Upserts the account for a person who just proved who they are to im.
@@ -748,6 +761,26 @@ pub trait Store: BoardReads + DetailReads + 'static {
748 role: Role,761 role: Role,
749 ) -> Result<User>;762 ) -> Result<User>;
750 763
764+ /// Mirrors one entry of im's directory into the member list.
765+ ///
766+ /// The directory vouches the subject, so a person nobody has ever seen
767+ /// gets a row born linked — assignable, mailable and avatar-able before
768+ /// their first visit. An unclaimed row with a matching address is
769+ /// claimed (sub stamped, id/role/preferences/history kept), a known row
770+ /// follows the provider's address, name and admin flag, and a row that
771+ /// already agrees is left alone. Unlike [`Store::provision_user`] this
772+ /// is not a sign-in: `last_signed_in_at` is never stamped, and an empty
773+ /// database grows no workspace (the first sign-in builds it; the next
774+ /// beat mirrors everyone). The admin flag claims an unclaimed owner the
775+ /// same way provision does. Says what happened through [`MemberSync`].
776+ async fn sync_member(
777+ &self,
778+ sub: &str,
779+ email: &str,
780+ display_name: &str,
781+ im_admin: bool,
782+ ) -> Result<MemberSync>;
783+
751 async fn user(&self, id: &str) -> Result<Option<User>>;784 async fn user(&self, id: &str) -> Result<Option<User>>;
752 785
753 /// Lookup by address. Callers must not turn a `None` into a different786 /// Lookup by address. Callers must not turn a `None` into a different
@@ -765,7 +798,6 @@ pub trait Store: BoardReads + DetailReads + 'static {
765 /// This is a read, for looking: nothing announces.798 /// This is a read, for looking: nothing announces.
766 async fn user_stats(&self, user_id: &str) -> Result<UserStats>;799 async fn user_stats(&self, user_id: &str) -> Result<UserStats>;
767 800
768-
769 /// Display-only preferences: stored data stays UTC/neutral, these only801 /// Display-only preferences: stored data stays UTC/neutral, these only
770 /// change how a browser renders it for this one person.802 /// change how a browser renders it for this one person.
771 async fn set_preferences(803 async fn set_preferences(
@@ -782,8 +814,6 @@ pub trait Store: BoardReads + DetailReads + 'static {
782 /// layer reads this and treats the person as signed out.814 /// layer reads this and treats the person as signed out.
783 async fn set_user_disabled(&self, user_id: &str, disabled: bool) -> Result<()>;815 async fn set_user_disabled(&self, user_id: &str, disabled: bool) -> Result<()>;
784 816
785-
786-
787 // -- board -------------------------------------------------------------817 // -- board -------------------------------------------------------------
788 818
789 /// Adds a column to the end of a board.819 /// Adds a column to the end of a board.
crates/iz-core/src/store/turso_store.rsmodified+146 -4
@@ -17,9 +17,9 @@ use super::secret;
17 use super::{17 use super::{
18 ActivityEvent, ActivityFilter, ActivityLine, Attachment, Audience, ClaimedSend, CommentWritten,18 ActivityEvent, ActivityFilter, ActivityLine, Attachment, Audience, ClaimedSend, CommentWritten,
19 Deletion, Dir, Event, FeedCursor, FeedPage, Freeing, MailDecision, MailOutcome, MailRule,19 Deletion, Dir, Event, FeedCursor, FeedPage, Freeing, MailDecision, MailOutcome, MailRule,
20- MailSend, NewAttachment, NewSender, NewTask, Recipient, Result, SendKind, SendState,20+ MailSend, MemberSync, NewAttachment, NewSender, NewTask, Recipient, Result, SendKind,
21- SenderCheck, SenderTest, Store, StoreError, Tag, TaskCreated, Trigger, User, UserStats,21+ SendState, SenderCheck, SenderTest, Store, StoreError, Tag, TaskCreated, Trigger, User,
22- Workspace,22+ UserStats, Workspace,
23 };23 };
24 use super::{ReconcileOptions, reconcile, schema, sniff};24 use super::{ReconcileOptions, reconcile, schema, sniff};
25 use crate::Role;25 use crate::Role;
@@ -1369,6 +1369,146 @@ impl Store for TursoStore {
1369 self.user(&id).await?.ok_or(StoreError::NotFound)1369 self.user(&id).await?.ok_or(StoreError::NotFound)
1370 }1370 }
1371 1371
1372+ async fn sync_member(
1373+ &self,
1374+ sub: &str,
1375+ email: &str,
1376+ display_name: &str,
1377+ im_admin: bool,
1378+ ) -> Result<MemberSync> {
1379+ let email = fold_email(email);
1380+ // IMMEDIATE like provision_user: a beat racing a first sign-in over
1381+ // the same address must not double the row, and two admin sightings
1382+ // must not both claim the owner.
1383+ let mut conn = self.tx_conn().await?;
1384+ let tx = conn
1385+ .transaction_with_behavior(TransactionBehavior::Immediate)
1386+ .await
1387+ .map_err(backend)?;
1388+ let now = now_text()?;
1389+ let by_sub = format!("SELECT {USER_COLUMNS} FROM user WHERE oidc_sub = ?1");
1390+ let mut rows = tx.query(&by_sub, params![sub]).await.map_err(backend)?;
1391+ let seen = match rows.next().await.map_err(backend)? {
1392+ Some(row) => Some(user_from(&row)?),
1393+ None => None,
1394+ };
1395+ drop(rows);
1396+ let outcome = if let Some(user) = seen {
1397+ let role = synced_role(user.role, im_admin);
1398+ // A sync is not a sign-in: last_signed_in_at is the person's own
1399+ // fact, and the directory says nothing about it.
1400+ if user.email == email && user.display_name == display_name && role == user.role {
1401+ Some((user.id, MemberSync::Untouched))
1402+ } else {
1403+ tx.execute(
1404+ "UPDATE user SET email = ?1, display_name = ?2, role = ?3 WHERE id = ?4",
1405+ params![email.clone(), display_name, role.as_str(), user.id.clone()],
1406+ )
1407+ .await
1408+ .map_err(backend)?;
1409+ Some((user.id, MemberSync::Refreshed))
1410+ }
1411+ } else {
1412+ let by_email =
1413+ format!("SELECT {USER_COLUMNS} FROM user WHERE email = ?1 COLLATE NOCASE");
1414+ let mut rows = tx
1415+ .query(&by_email, params![email.clone()])
1416+ .await
1417+ .map_err(backend)?;
1418+ let seen = match rows.next().await.map_err(backend)? {
1419+ Some(row) => Some(user_from(&row)?),
1420+ None => None,
1421+ };
1422+ drop(rows);
1423+ if let Some(user) = seen {
1424+ let role = synced_role(user.role, im_admin);
1425+ tx.execute(
1426+ "UPDATE user SET oidc_sub = ?1, email = ?2, display_name = ?3, role = ?4 \
1427+ WHERE id = ?5",
1428+ params![
1429+ sub,
1430+ email.clone(),
1431+ display_name,
1432+ role.as_str(),
1433+ user.id.clone()
1434+ ],
1435+ )
1436+ .await
1437+ .map_err(backend)?;
1438+ Some((user.id, MemberSync::Claimed))
1439+ } else {
1440+ let known = {
1441+ let mut rows = tx
1442+ .query("SELECT id FROM workspace LIMIT 1", ())
1443+ .await
1444+ .map_err(backend)?;
1445+ let known = match rows.next().await.map_err(backend)? {
1446+ Some(row) => Some(text(&row, 0)?),
1447+ None => None,
1448+ };
1449+ drop(rows);
1450+ known
1451+ };
1452+ match known {
1453+ None => None,
1454+ Some(workspace_id) => {
1455+ // Born linked: the directory vouches the subject, so
1456+ // the row never waits unclaimed — assignment, mail
1457+ // and the avatar proxy work before the first visit.
1458+ let id = Ulid::new().to_string();
1459+ let role = if im_admin { Role::Admin } else { Role::Member };
1460+ tx.execute(
1461+ "INSERT INTO user (id, workspace_id, oidc_sub, email, display_name, \
1462+ role, disabled, created_at, last_signed_in_at) \
1463+ VALUES (?1, ?2, ?3, ?4, ?5, ?6, 0, ?7, NULL)",
1464+ params![
1465+ id.clone(),
1466+ workspace_id,
1467+ sub,
1468+ email.clone(),
1469+ display_name,
1470+ role.as_str(),
1471+ now.clone()
1472+ ],
1473+ )
1474+ .await
1475+ .map_err(backend)?;
1476+ Some((id, MemberSync::Inserted))
1477+ }
1478+ }
1479+ }
1480+ };
1481+ let Some((id, mut sync)) = outcome else {
1482+ // No workspace to put a new row in: the first sign-in builds it,
1483+ // and the next beat mirrors everyone. Nothing was written.
1484+ drop(tx);
1485+ drop(conn);
1486+ return Ok(MemberSync::Skipped);
1487+ };
1488+ if im_admin {
1489+ // Same conditional claim as provision_user: the provider's first
1490+ // admin owns the workspace, a later one never steals it.
1491+ let claimed = tx
1492+ .execute(
1493+ "INSERT INTO workspace_owner (singleton, user_id, claimed_at) \
1494+ SELECT 1, ?1, ?2 WHERE NOT EXISTS \
1495+ (SELECT 1 FROM workspace_owner WHERE singleton = 1)",
1496+ params![id.clone(), now.clone()],
1497+ )
1498+ .await
1499+ .map_err(backend)?;
1500+ if claimed > 0 && sync == MemberSync::Untouched {
1501+ sync = MemberSync::Refreshed;
1502+ }
1503+ }
1504+ tx.commit().await.map_err(backend)?;
1505+ drop(conn);
1506+ if sync != MemberSync::Untouched {
1507+ self.announce([Topic::Members]);
1508+ }
1509+ Ok(sync)
1510+ }
1511+
1372 async fn add_member(1512 async fn add_member(
1373 &self,1513 &self,
1374 workspace_id: &str,1514 workspace_id: &str,
@@ -1393,7 +1533,9 @@ impl Store for TursoStore {
1393 // unique index below means what the case-insensitive check here1533 // unique index below means what the case-insensitive check here
1394 // says even for rows the password era left unfolded.1534 // says even for rows the password era left unfolded.
1395 let seen = {1535 let seen = {
1396- let sql = format!("SELECT {USER_COLUMNS} FROM user WHERE workspace_id = ?1 AND email = ?2 COLLATE NOCASE");1536+ let sql = format!(
1537+ "SELECT {USER_COLUMNS} FROM user WHERE workspace_id = ?1 AND email = ?2 COLLATE NOCASE"
1538+ );
1397 self.one_row(&sql, params![workspace_id, email.clone()])1539 self.one_row(&sql, params![workspace_id, email.clone()])
1398 .await?1540 .await?
1399 };1541 };
crates/iz-core/tests/store.rsmodified+111 -1
@@ -8069,7 +8069,10 @@ async fn an_added_member_waits_unclaimed_until_their_first_sign_in() {
8069 .into_iter()8069 .into_iter()
8070 .map(|user| user.email)8070 .map(|user| user.email)
8071 .collect();8071 .collect();
8072- assert_eq!(names, vec!["ada@iz.sh".to_string(), "mert@iz.sh".to_string()]);8072+ assert_eq!(
8073+ names,
8074+ vec!["ada@iz.sh".to_string(), "mert@iz.sh".to_string()]
8075+ );
8073 }8076 }
8074 8077
8075 #[tokio::test]8078 #[tokio::test]
@@ -8253,3 +8256,110 @@ async fn set_user_disabled_round_trips() {
8253 Err(StoreError::NotFound)8256 Err(StoreError::NotFound)
8254 ));8257 ));
8255 }8258 }
8259+
8260+#[tokio::test]
8261+async fn a_synced_member_is_born_linked_and_never_signed_in() {
8262+ let (scratch, workspace, _admin) = workspace_with_admin().await;
8263+ let sync = scratch
8264+ .store
8265+ .sync_member("sub-mert", "mert@iz.sh", "Mert", false)
8266+ .await
8267+ .unwrap();
8268+ assert_eq!(sync, iz_core::store::MemberSync::Inserted);
8269+ let row = scratch
8270+ .store
8271+ .user_by_email(&workspace, "mert@iz.sh")
8272+ .await
8273+ .unwrap()
8274+ .unwrap();
8275+ assert_eq!(row.oidc_sub.as_deref(), Some("sub-mert"));
8276+ assert_eq!(row.role, Role::Member);
8277+ assert!(row.last_signed_in_at.is_none());
8278+ // An im admin the workspace has never met is Admin from the first beat.
8279+ scratch
8280+ .store
8281+ .sync_member("sub-boss", "boss@iz.sh", "Boss", true)
8282+ .await
8283+ .unwrap();
8284+ let boss = scratch
8285+ .store
8286+ .user_by_email(&workspace, "boss@iz.sh")
8287+ .await
8288+ .unwrap()
8289+ .unwrap();
8290+ assert_eq!(boss.role, Role::Admin);
8291+}
8292+
8293+#[tokio::test]
8294+async fn a_sync_claims_an_unclaimed_row_without_touching_its_sign_in_fact() {
8295+ let (scratch, workspace, _admin) = workspace_with_admin().await;
8296+ let added = scratch
8297+ .store
8298+ .add_member(&workspace, "mert@iz.sh", "Mert", Role::Viewer)
8299+ .await
8300+ .unwrap();
8301+ let sync = scratch
8302+ .store
8303+ .sync_member("sub-mert", "MERT@iz.sh", "Mert Yılmaz", false)
8304+ .await
8305+ .unwrap();
8306+ assert_eq!(sync, iz_core::store::MemberSync::Claimed);
8307+ let row = scratch.store.user(&added.id).await.unwrap().unwrap();
8308+ assert_eq!(row.oidc_sub.as_deref(), Some("sub-mert"));
8309+ assert_eq!(row.display_name, "Mert Yılmaz");
8310+ assert_eq!(
8311+ row.role,
8312+ Role::Viewer,
8313+ "a local role is not the directory's"
8314+ );
8315+ assert!(row.last_signed_in_at.is_none(), "a sync is not a sign-in");
8316+}
8317+
8318+#[tokio::test]
8319+async fn a_sync_follows_provider_drift_but_not_the_sign_in_fact() {
8320+ let (scratch, workspace, admin_id) = workspace_with_admin().await;
8321+ let before = scratch.store.user(&admin_id).await.unwrap().unwrap();
8322+ let seen = before.last_signed_in_at.clone();
8323+ let sync = scratch
8324+ .store
8325+ .sync_member("sub-ada", "ada@iz.sh", "Ada Lovelace", true)
8326+ .await
8327+ .unwrap();
8328+ assert_eq!(sync, iz_core::store::MemberSync::Refreshed);
8329+ let after = scratch.store.user(&admin_id).await.unwrap().unwrap();
8330+ assert_eq!(after.display_name, "Ada Lovelace");
8331+ assert_eq!(after.last_signed_in_at, seen);
8332+ // Losing the flag in the directory drops an Admin to Member.
8333+ scratch
8334+ .store
8335+ .sync_member("sub-ada", "ada@iz.sh", "Ada Lovelace", false)
8336+ .await
8337+ .unwrap();
8338+ let demoted = scratch.store.user(&admin_id).await.unwrap().unwrap();
8339+ assert_eq!(demoted.role, Role::Member);
8340+}
8341+
8342+#[tokio::test]
8343+async fn an_agreeing_sync_is_untouched_and_silent() {
8344+ let (scratch, _, _) = workspace_with_admin().await;
8345+ let mut rx = scratch.store.subscribe();
8346+ let sync = scratch
8347+ .store
8348+ .sync_member("sub-ada", "ada@iz.sh", "Ada", true)
8349+ .await
8350+ .unwrap();
8351+ assert_eq!(sync, iz_core::store::MemberSync::Untouched);
8352+ assert!(announced(&mut rx).is_empty());
8353+}
8354+
8355+#[tokio::test]
8356+async fn a_sync_without_a_workspace_skips_and_writes_nothing() {
8357+ let scratch = Scratch::open().await;
8358+ let sync = scratch
8359+ .store
8360+ .sync_member("sub-mert", "mert@iz.sh", "Mert", false)
8361+ .await
8362+ .unwrap();
8363+ assert_eq!(sync, iz_core::store::MemberSync::Skipped);
8364+ assert!(scratch.store.workspace().await.unwrap().is_none());
8365+}
crates/iz-web/src/main.rsmodified+37 -0
@@ -137,6 +137,14 @@ async fn main() {
137 ));137 ));
138 tokio::spawn(sweep(engine.clone(), store.clone()));138 tokio::spawn(sweep(engine.clone(), store.clone()));
139 139
140+ // The member list mirrors im's directory: people are assignable and
141+ // mailable before their first visit, and the provider's renames and
142+ // admin flips follow on their own. Runs beside the sweep, first pass
143+ // right away so a fresh deploy sees everyone at boot.
144+ tokio::spawn(directory_sync(
145+ store.clone(),
146+ iz_client::IzClient::new(oidc.clone()),
147+ ));
140 // Told when the process is stopping, so the live streams end instead of148 // Told when the process is stopping, so the live streams end instead of
141 // being waited out. See `iz_web::live::Shutdown`.149 // being waited out. See `iz_web::live::Shutdown`.
142 let (stop, stopping) = tokio::sync::watch::channel(false);150 let (stop, stopping) = tokio::sync::watch::channel(false);
@@ -296,6 +304,35 @@ async fn sweep(engine: std::sync::Arc<iz_core::MailEngine>, store: Arc<dyn iz_co
296 }304 }
297 }305 }
298 306
307+/// How often the member list is re-mirrored from im. Short enough that a
308+/// person invited to im shows up here before anyone goes looking for them,
309+/// long enough that the two services are not talking about it constantly.
310+const DIRECTORY_SECONDS: u64 = 300;
311+
312+/// Keeps the member list a mirror of im's directory, first pass at boot and
313+/// then on the beat. Every pass is a full read of a short list, so the
314+/// store hears one entry at a time and announces only what changed. An im
315+/// that does not answer — down, restarting, mid-deploy — costs one log line
316+/// and nothing else: the rows stay, and the next beat asks again.
317+async fn directory_sync(store: Arc<dyn iz_core::store::Store>, client: iz_client::IzClient) {
318+ loop {
319+ match client.directory().await {
320+ Some(members) => {
321+ for member in members {
322+ if let Err(problem) = store
323+ .sync_member(&member.sub, &member.email, &member.name, member.admin)
324+ .await
325+ {
326+ eprintln!("directory sync: {}: {problem}", member.email);
327+ }
328+ }
329+ }
330+ None => eprintln!("directory sync: im did not answer; keeping the rows there are"),
331+ }
332+ tokio::time::sleep(std::time::Duration::from_secs(DIRECTORY_SECONDS)).await;
333+ }
334+}
335+
299 /// Waits for something to happen to the mail queue specifically.336 /// Waits for something to happen to the mail queue specifically.
300 ///337 ///
301 /// The channel carries every topic, and the sweep cares about one. Filtering338 /// The channel carries every topic, and the sweep cares about one. Filtering
crates/iz-web/tests/http.rsmodified+150 -56
@@ -120,20 +120,21 @@ impl FakeIm {
120 let len = content_length(&head);120 let len = content_length(&head);
121 let body: Vec<u8> = req[body_start..body_start + len].to_vec();121 let body: Vec<u8> = req[body_start..body_start + len].to_vec();
122 req.drain(..body_start + len);122 req.drain(..body_start + len);
123- let (status, content_type, payload) = match photo_answer(&pmap, &head, &first) {123+ let (status, content_type, payload) =
124- Some(photo) => photo,124+ match photo_answer(&pmap, &head, &first) {
125- None => match answer_for(&map, &first, &body) {125+ Some(photo) => photo,
126- Some(answer) => (126+ None => match answer_for(&map, &first, &body) {
127- "200 OK",127+ Some(answer) => (
128- "application/json".to_string(),128+ "200 OK",
129- serde_json::to_vec(&answer).unwrap(),129+ "application/json".to_string(),
130- ),130+ serde_json::to_vec(&answer).unwrap(),
131- // Anything but the introspection route is131+ ),
132- // nothing at all, the way the real im 404s132+ // Anything but the introspection route is
133- // unknown paths rather than answering them.133+ // nothing at all, the way the real im 404s
134- None => ("404 Not Found", "text/plain".to_string(), Vec::new()),134+ // unknown paths rather than answering them.
135- },135+ None => ("404 Not Found", "text/plain".to_string(), Vec::new()),
136- };136+ },
137+ };
137 let response = format!(138 let response = format!(
138 "HTTP/1.1 {status}\r\ncontent-type: {content_type}\r\ncontent-length: {}\r\n\r\n",139 "HTTP/1.1 {status}\r\ncontent-type: {content_type}\r\ncontent-length: {}\r\n\r\n",
139 payload.len()140 payload.len()
@@ -148,7 +149,11 @@ impl FakeIm {
148 });149 });
149 }150 }
150 });151 });
151- Self { addr, tokens, photos }152+ Self {
153+ addr,
154+ tokens,
155+ photos,
156+ }
152 }157 }
153 158
154 fn url(&self) -> String {159 fn url(&self) -> String {
@@ -180,7 +185,10 @@ fn photo_answer(
180 return None;185 return None;
181 }186 }
182 let target = parts.next().unwrap_or("");187 let target = parts.next().unwrap_or("");
183- let path = target.split_once('?').map(|(path, _)| path).unwrap_or(target);188+ let path = target
189+ .split_once('?')
190+ .map(|(path, _)| path)
191+ .unwrap_or(target);
184 let id = path.strip_prefix("/photo/")?;192 let id = path.strip_prefix("/photo/")?;
185 if id.is_empty() || id.contains('/') {193 if id.is_empty() || id.contains('/') {
186 return None;194 return None;
@@ -240,7 +248,8 @@ fn answer_for(
240 body: &[u8],248 body: &[u8],
241 ) -> Option<serde_json::Value> {249 ) -> Option<serde_json::Value> {
242 let mut head = request_line.split_whitespace();250 let mut head = request_line.split_whitespace();
243- let is_introspect = head.next() == Some("POST") && head.next() == Some(iz_client::introspect_path());251+ let is_introspect =
252+ head.next() == Some("POST") && head.next() == Some(iz_client::introspect_path());
244 if !is_introspect {253 if !is_introspect {
245 return None;254 return None;
246 }255 }
@@ -785,7 +794,11 @@ async fn admin(app: &App) -> String {
785 .provision_user(sub, "ada@iz.sh", "Ada Lovelace", true)794 .provision_user(sub, "ada@iz.sh", "Ada Lovelace", true)
786 .await795 .await
787 .unwrap();796 .unwrap();
788- assert_eq!(user.role, Role::Admin, "the first im admin did not claim admin");797+ assert_eq!(
798+ user.role,
799+ Role::Admin,
800+ "the first im admin did not claim admin"
801+ );
789 app.mint(sub, "ada@iz.sh", "Ada Lovelace", true)802 app.mint(sub, "ada@iz.sh", "Ada Lovelace", true)
790 }803 }
791 804
@@ -1915,7 +1928,6 @@ async fn a_parents_own_part_is_not_offered_as_a_blocker() {
1915 );1928 );
1916 }1929 }
1917 1930
1918-
1919 #[tokio::test]1931 #[tokio::test]
1920 async fn the_whole_control_box_opens_its_dropdown() {1932 async fn the_whole_control_box_opens_its_dropdown() {
1921 // A status control is a box holding a dot, the trigger and a chevron.1933 // 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() {
2281 );2293 );
2282 }2294 }
2283 2295
2284-
2285 #[tokio::test]2296 #[tokio::test]
2286 async fn a_member_who_posts_new_limits_anyway_is_refused() {2297 async fn a_member_who_posts_new_limits_anyway_is_refused() {
2287 let app = App::open().await;2298 let app = App::open().await;
@@ -2814,8 +2825,6 @@ async fn a_non_admin_may_not_set_roles_over_http() {
2814 );2825 );
2815 }2826 }
2816 2827
2817-
2818-
2819 // ---------------------------------------------------------------------------2828 // ---------------------------------------------------------------------------
2820 // Settings visibility: the sender and the member list are the admin's2829 // Settings visibility: the sender and the member list are the admin's
2821 // ---------------------------------------------------------------------------2830 // ---------------------------------------------------------------------------
@@ -4200,7 +4209,12 @@ async fn a_stamp_shifts_with_the_viewers_stored_timezone() {
4200 .post(4209 .post(
4201 "/api/save_profile",4210 "/api/save_profile",
4202 Some(&admin_cookie),4211 Some(&admin_cookie),
4203- &[("timezone", "UTC+03:00"), ("theme", "light"), ("language", "en"), ("ui", "instrument")],4212+ &[
4213+ ("timezone", "UTC+03:00"),
4214+ ("theme", "light"),
4215+ ("language", "en"),
4216+ ("ui", "instrument"),
4217+ ],
4204 )4218 )
4205 .await;4219 .await;
4206 assert!(4220 assert!(
@@ -4255,7 +4269,12 @@ async fn a_task_modal_stamp_shifts_with_the_viewers_stored_timezone() {
4255 .post(4269 .post(
4256 "/api/save_profile",4270 "/api/save_profile",
4257 Some(&admin_cookie),4271 Some(&admin_cookie),
4258- &[("timezone", "UTC+03:00"), ("theme", "light"), ("language", "en"), ("ui", "instrument")],4272+ &[
4273+ ("timezone", "UTC+03:00"),
4274+ ("theme", "light"),
4275+ ("language", "en"),
4276+ ("ui", "instrument"),
4277+ ],
4259 )4278 )
4260 .await;4279 .await;
4261 assert!(4280 assert!(
@@ -4292,7 +4311,10 @@ async fn an_unlisted_timezone_is_refused() {
4292 "/api/save_profile",4311 "/api/save_profile",
4293 Some(&admin_cookie),4312 Some(&admin_cookie),
4294 &[4313 &[
4295- ("timezone", "Mars/Olympus_Mons"), ("theme", "light"), ("language", "en"), ("ui", "instrument"),4314+ ("timezone", "Mars/Olympus_Mons"),
4315+ ("theme", "light"),
4316+ ("language", "en"),
4317+ ("ui", "instrument"),
4296 ],4318 ],
4297 )4319 )
4298 .await;4320 .await;
@@ -4312,7 +4334,12 @@ async fn the_dark_theme_is_saved_and_marks_the_page() {
4312 .post(4334 .post(
4313 "/api/save_profile",4335 "/api/save_profile",
4314 Some(&admin_cookie),4336 Some(&admin_cookie),
4315- &[("timezone", "UTC"), ("theme", "dark"), ("language", "en"), ("ui", "instrument")],4337+ &[
4338+ ("timezone", "UTC"),
4339+ ("theme", "dark"),
4340+ ("language", "en"),
4341+ ("ui", "instrument"),
4342+ ],
4316 )4343 )
4317 .await;4344 .await;
4318 assert!(4345 assert!(
@@ -4339,7 +4366,12 @@ async fn turkish_is_saved_and_the_board_renders_in_turkish() {
4339 .post(4366 .post(
4340 "/api/save_profile",4367 "/api/save_profile",
4341 Some(&admin_cookie),4368 Some(&admin_cookie),
4342- &[("timezone", "UTC"), ("theme", "light"), ("language", "tr"), ("ui", "instrument")],4369+ &[
4370+ ("timezone", "UTC"),
4371+ ("theme", "light"),
4372+ ("language", "tr"),
4373+ ("ui", "instrument"),
4374+ ],
4343 )4375 )
4344 .await;4376 .await;
4345 assert!(4377 assert!(
@@ -4375,7 +4407,12 @@ async fn an_unlisted_language_is_refused() {
4375 .post(4407 .post(
4376 "/api/save_profile",4408 "/api/save_profile",
4377 Some(&admin_cookie),4409 Some(&admin_cookie),
4378- &[("timezone", "UTC"), ("theme", "light"), ("language", "fr"), ("ui", "instrument")],4410+ &[
4411+ ("timezone", "UTC"),
4412+ ("theme", "light"),
4413+ ("language", "fr"),
4414+ ("ui", "instrument"),
4415+ ],
4379 )4416 )
4380 .await;4417 .await;
4381 assert_eq!(4418 assert_eq!(
@@ -4393,7 +4430,12 @@ async fn an_unlisted_theme_is_refused() {
4393 .post(4430 .post(
4394 "/api/save_profile",4431 "/api/save_profile",
4395 Some(&admin_cookie),4432 Some(&admin_cookie),
4396- &[("timezone", "UTC"), ("theme", "neon"), ("language", "en"), ("ui", "instrument")],4433+ &[
4434+ ("timezone", "UTC"),
4435+ ("theme", "neon"),
4436+ ("language", "en"),
4437+ ("ui", "instrument"),
4438+ ],
4397 )4439 )
4398 .await;4440 .await;
4399 let location = answer.location.as_deref().unwrap_or_default();4441 let location = answer.location.as_deref().unwrap_or_default();
@@ -4412,7 +4454,12 @@ async fn the_ledger_ui_is_saved_and_marks_the_page() {
4412 .post(4454 .post(
4413 "/api/save_profile",4455 "/api/save_profile",
4414 Some(&admin_cookie),4456 Some(&admin_cookie),
4415- &[("timezone", "UTC"), ("theme", "light"), ("language", "en"), ("ui", "ledger")],4457+ &[
4458+ ("timezone", "UTC"),
4459+ ("theme", "light"),
4460+ ("language", "en"),
4461+ ("ui", "ledger"),
4462+ ],
4416 )4463 )
4417 .await;4464 .await;
4418 assert!(4465 assert!(
@@ -4439,7 +4486,12 @@ async fn an_unlisted_ui_is_refused() {
4439 .post(4486 .post(
4440 "/api/save_profile",4487 "/api/save_profile",
4441 Some(&admin_cookie),4488 Some(&admin_cookie),
4442- &[("timezone", "UTC"), ("theme", "light"), ("language", "en"), ("ui", "neon")],4489+ &[
4490+ ("timezone", "UTC"),
4491+ ("theme", "light"),
4492+ ("language", "en"),
4493+ ("ui", "neon"),
4494+ ],
4443 )4495 )
4444 .await;4496 .await;
4445 let location = answer.location.as_deref().unwrap_or_default();4497 let location = answer.location.as_deref().unwrap_or_default();
@@ -4594,7 +4646,11 @@ async fn the_im_admin_flag_makes_an_admin() {
4594 .await4646 .await
4595 .unwrap()4647 .unwrap()
4596 .expect("no local row after the first login");4648 .expect("no local row after the first login");
4597- assert_eq!(user.role, Role::Admin, "the im admin flag did not make an admin");4649+ assert_eq!(
4650+ user.role,
4651+ Role::Admin,
4652+ "the im admin flag did not make an admin"
4653+ );
4598 }4654 }
4599 4655
4600 /// A first SSO login claims the legacy row by address: the `sub` is stamped4656 /// 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() {
4608 .provision_user("im-old", "ada@iz.sh", "Ada Lovelace", false)4664 .provision_user("im-old", "ada@iz.sh", "Ada Lovelace", false)
4609 .await4665 .await
4610 .unwrap();4666 .unwrap();
4611- app.store4667+ app.store.set_role(&legacy.id, Role::Viewer).await.unwrap();
4612- .set_role(&legacy.id, Role::Viewer)
4613- .await
4614- .unwrap();
4615 4668
4616 let cookie = app.mint("im-new", "ada@iz.sh", "Ada Lovelace", false);4669 let cookie = app.mint("im-new", "ada@iz.sh", "Ada Lovelace", false);
4617 let page = app.get("/", Some(&cookie)).await;4670 let page = app.get("/", Some(&cookie)).await;
@@ -4623,7 +4676,10 @@ async fn a_first_sso_login_claims_the_legacy_row_by_address() {
4623 .await4676 .await
4624 .unwrap()4677 .unwrap()
4625 .expect("the address has no row after claiming");4678 .expect("the address has no row after claiming");
4626- assert_eq!(claimed.id, legacy.id, "the login did not claim the legacy row");4679+ assert_eq!(
4680+ claimed.id, legacy.id,
4681+ "the login did not claim the legacy row"
4682+ );
4627 assert_eq!(4683 assert_eq!(
4628 claimed.role,4684 claimed.role,
4629 Role::Viewer,4685 Role::Viewer,
@@ -4641,10 +4697,7 @@ async fn a_disabled_member_reads_as_signed_out() {
4641 let admin_cookie = admin(&app).await;4697 let admin_cookie = admin(&app).await;
4642 let member = invited(&app, &admin_cookie, "emre@iz.sh", "Emre", Role::Member).await;4698 let member = invited(&app, &admin_cookie, "emre@iz.sh", "Emre", Role::Member).await;
4643 let member_id = user_id(&app, "emre@iz.sh").await;4699 let member_id = user_id(&app, "emre@iz.sh").await;
4644- app.store4700+ app.store.set_user_disabled(&member_id, true).await.unwrap();
4645- .set_user_disabled(&member_id, true)
4646- .await
4647- .unwrap();
4648 4701
4649 let page = app.get("/", Some(&member)).await;4702 let page = app.get("/", Some(&member)).await;
4650 let html = String::from_utf8_lossy(&page.bytes);4703 let html = String::from_utf8_lossy(&page.bytes);
@@ -4730,11 +4783,7 @@ async fn set_role_cannot_make_an_admin() {
4730 );4783 );
4731 4784
4732 let reloaded = app.store.user(&member_id).await.unwrap().unwrap();4785 let reloaded = app.store.user(&member_id).await.unwrap().unwrap();
4733- assert_eq!(4786+ assert_eq!(reloaded.role, Role::Member, "set_role made an admin anyway");
4734- reloaded.role,
4735- Role::Member,
4736- "set_role made an admin anyway"
4737- );
4738 }4787 }
4739 4788
4740 /// An admin may add a member who has never signed in, and the row is a4789 /// 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() {
4776 app.store.assign_task(&task, &member_id).await.unwrap();4825 app.store.assign_task(&task, &member_id).await.unwrap();
4777 }4826 }
4778 4827
4828+/// A member the directory beat mirrored — born linked, never signed in —
4829+/// is a member like any other: in the picker list and assignable straight
4830+/// away. Catches a sync that writes rows the board cannot see.
4831+#[tokio::test]
4832+async fn a_synced_member_is_listed_and_assignable_before_their_first_sign_in() {
4833+ let app = App::open().await;
4834+ let admin_cookie = admin(&app).await;
4835+ let admin_row = app
4836+ .store
4837+ .user(&user_id(&app, "ada@iz.sh").await)
4838+ .await
4839+ .unwrap()
4840+ .unwrap();
4841+
4842+ let sync = app
4843+ .store
4844+ .sync_member("sub-mert", "mert@iz.sh", "Mert", false)
4845+ .await
4846+ .unwrap();
4847+ assert_eq!(sync, iz_core::store::MemberSync::Inserted);
4848+
4849+ let member_id = user_id(&app, "mert@iz.sh").await;
4850+ let row = app.store.user(&member_id).await.unwrap().unwrap();
4851+ assert_eq!(row.oidc_sub.as_deref(), Some("sub-mert"));
4852+ assert!(row.last_signed_in_at.is_none());
4853+
4854+ let listed = app.store.users(&admin_row.workspace_id).await.unwrap();
4855+ assert!(
4856+ listed.iter().any(|user| user.id == member_id),
4857+ "the picker's source does not list the synced member"
4858+ );
4859+
4860+ let column = first_column(&app).await;
4861+ let task = a_task(&app, &admin_cookie, &column, "Onboard Mert").await;
4862+ app.store.assign_task(&task, &member_id).await.unwrap();
4863+}
4864+
4779 /// A member who posts to the add route anyway is refused, and no row is4865 /// A member who posts to the add route anyway is refused, and no row is
4780 /// written. Catches a handler that trusts the form's being hidden.4866 /// written. Catches a handler that trusts the form's being hidden.
4781 #[tokio::test]4867 #[tokio::test]
@@ -5031,7 +5117,9 @@ async fn the_avatar_is_not_found_without_an_im_photo() {
5031 let member = invited(&app, &admin_cookie, "emre@iz.sh", "Emre", Role::Member).await;5117 let member = invited(&app, &admin_cookie, "emre@iz.sh", "Emre", Role::Member).await;
5032 let member_id = user_id(&app, "emre@iz.sh").await;5118 let member_id = user_id(&app, "emre@iz.sh").await;
5033 5119
5034- let photo = app.get(&format!("/avatar/{member_id}"), Some(&member)).await;5120+ let photo = app
5121+ .get(&format!("/avatar/{member_id}"), Some(&member))
5122+ .await;
5035 assert_eq!(photo.status, StatusCode::NOT_FOUND);5123 assert_eq!(photo.status, StatusCode::NOT_FOUND);
5036 }5124 }
5037 /// Polls the store until a `Rule` send for `rule_id` addressed to `recipient`5125 /// 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 {
5329 .id5417 .id
5330 }5418 }
5331 5419
5332-
5333 /// The nav shows a page only to a role that can act on it: an admin's board5420 /// The nav shows a page only to a role that can act on it: an admin's board
5334 /// carries all four links, a member's carries neither Rules nor Logs.5421 /// carries all four links, a member's carries neither Rules nor Logs.
5335 #[tokio::test]5422 #[tokio::test]
@@ -7962,7 +8049,12 @@ async fn a_clock_saved_on_a_task_renders_in_the_viewers_stored_timezone() {
7962 .post(8049 .post(
7963 "/api/save_profile",8050 "/api/save_profile",
7964 Some(&admin_cookie),8051 Some(&admin_cookie),
7965- &[("timezone", "UTC+03:00"), ("theme", "light"), ("language", "en"), ("ui", "instrument")],8052+ &[
8053+ ("timezone", "UTC+03:00"),
8054+ ("theme", "light"),
8055+ ("language", "en"),
8056+ ("ui", "instrument"),
8057+ ],
7966 )8058 )
7967 .await;8059 .await;
7968 assert!(8060 assert!(
@@ -8321,7 +8413,12 @@ async fn a_card_wears_the_clock_chip_in_the_viewers_zone_instead_of_the_deadline
8321 .post(8413 .post(
8322 "/api/save_profile",8414 "/api/save_profile",
8323 Some(&admin_cookie),8415 Some(&admin_cookie),
8324- &[("timezone", "UTC+03:00"), ("theme", "light"), ("language", "en"), ("ui", "instrument")],8416+ &[
8417+ ("timezone", "UTC+03:00"),
8418+ ("theme", "light"),
8419+ ("language", "en"),
8420+ ("ui", "instrument"),
8421+ ],
8325 )8422 )
8326 .await;8423 .await;
8327 assert!(8424 assert!(
@@ -9008,7 +9105,6 @@ async fn checking_the_sender_records_an_event() {
9008 assert_eq!(lines[0].actor_name.as_deref(), Some("Ada Lovelace"));9105 assert_eq!(lines[0].actor_name.as_deref(), Some("Ada Lovelace"));
9009 }9106 }
9010 9107
9011-
9012 /// A card's dependency summary names both directions with keys: what the card9108 /// A card's dependency summary names both directions with keys: what the card
9013 /// blocks and what blocks it, the same list shape either way.9109 /// blocks and what blocks it, the same list shape either way.
9014 #[tokio::test]9110 #[tokio::test]
@@ -9057,11 +9153,9 @@ async fn a_card_lists_both_dependency_directions_as_keys() {
9057 )),9153 )),
9058 "the blocker's card did not name what it blocks: {html}"9154 "the blocker's card did not name what it blocks: {html}"
9059 );9155 );
9060- assert!(9156+ assert!(html.contains(&format!(
9061- html.contains(&format!(9157+ r#"class="card-blocked-by">blocked by {first_key}</span>"#
9062- r#"class="card-blocked-by">blocked by {first_key}</span>"#9158+ )),);
9063- )),
9064- );
9065 }9159 }
9066 9160
9067 /// The board search filters server-side by key and title, composes with the9161 /// The board search filters server-side by key and title, composes with the