forge
Explore
Log in

Don't you dare go Hollow

in_old

Clone
★ 0

0 watching0 forksRustGPL-3.01.1 MiB218b775Tahinli2 months ago90 commits

main.rs745 lines, 30.1 KiBHistoryRawDownload
1use std::sync::Arc;
2
3use in_core::Config;
4use in_core::store::r2::R2Blobs;
5use in_core::store::{Store, TursoStore};
6use topcoat::Result;
7use topcoat::asset::{AssetBundle, RouterBuilderAssetExt};
8use topcoat::context::Cx;
9use topcoat::cookie::RouterBuilderCookieExt;
10use topcoat::router::{BodyLimit, Router, RouterBuilderDiscoverExt, route};
11use topcoat::runtime::RouterBuilderRuntimeExt;
12
13#[route(GET "/healthz")]
14async fn healthz() -> Result<&'static str> {
15 // The deploy asserts this against the commit it pushed, so a stale
16 // process still holding the port fails the deploy instead of
17 // answering a green health check.
18 Ok(concat!("ok ", env!("IN_BUILD_SHA")))
19}
20
21#[tokio::main]
22async fn main() {
23 let args: Vec<String> = std::env::args().collect();
24 if args.get(1).map(|s| s.as_str()) == Some("reconcile") {
25 let mut dry_run = false;
26 let mut yes = false;
27 for arg in &args[2..] {
28 match arg.as_str() {
29 "--dry-run" => dry_run = true,
30 "--yes" => yes = true,
31 _ => {
32 eprintln!("in reconcile: unknown option {arg}");
33 std::process::exit(2);
34 }
35 }
36 }
37 let config = match Config::load() {
38 Ok(config) => config,
39 Err(problem) => {
40 eprintln!("in: {problem}");
41 std::process::exit(2);
42 }
43 };
44 if let Err(problem) = in_core::store::reconcile(
45 &config.database,
46 Some(config.storage.as_path()),
47 in_core::store::ReconcileOptions {
48 dry_run,
49 yes,
50 auto: false,
51 },
52 )
53 .await
54 {
55 eprintln!("in reconcile: {problem}");
56 std::process::exit(1);
57 }
58 return;
59 }
60
61 // config/in.toml is read here, before anything is opened, and written with
62 // development defaults if it is not there yet. A broken key stops the
63 // boot with its name in the message: the failure this prevents is not an
64 // empty database, it is a second in writing a different file while
65 // everyone believes they share a drive.
66 let config = match Config::load() {
67 Ok(config) => config,
68 Err(problem) => {
69 eprintln!("in: {problem}");
70 std::process::exit(2);
71 }
72 };
73 // Said once, so the answer to "which file are we on" lives in the log.
74 println!("in database {}", config.database);
75 println!("in storage {}", config.storage.display());
76 println!("in listen {}", config.listen);
77
78 // The bundle beside the executable is the only stylesheet this process
79 // can serve, and nothing in topcoat binds it to this binary's
80 // generation: a bundle left behind by another deploy loads as happily
81 // as the right one, and the pages then reference a stylesheet whose
82 // bytes are days old — the mixed generation a browser once caught on
83 // production. The fingerprint build.rs stamped into this binary is
84 // checked against the bundle's bytes, and a foreign bundle refuses the
85 // boot rather than serving under it.
86 let bundle = AssetBundle::load().unwrap_or_else(|err| {
87 eprintln!("in: the asset bundle beside the executable failed to load: {err}");
88 std::process::exit(2);
89 });
90 let stylesheet = match in_web::server::stylesheet_guard(&bundle) {
91 Ok(line) => line,
92 Err(problem) => {
93 eprintln!("in: {problem}");
94 std::process::exit(2);
95 }
96 };
97 println!("in {stylesheet}");
98
99 // File bytes, thumbnails and staged chunks live beside the database, not
100 // in a table. The tree is made before the store opens, because the
101 // reconcile an old database triggers on the way needs somewhere to put
102 // what it finds.
103 ensure_storage_tree(&config.storage);
104
105 // One process per database file: Turso is a single-writer engine and a
106 // second process on the same file loses writes rather than queueing.
107 //
108 // `open` applies any unapplied migration before it returns. With
109 // `[storage.r2]` set, the bytes open against the bucket instead of the
110 // tree — the tree keeps staging chunks, the bucket holds `files/` and
111 // `thumbs/`. No `[storage.r2]` is the local backend, today's shape.
112 let store = match &config.r2 {
113 Some(r2) => {
114 // Two lines: the access key id, then the secret. The file is
115 // the deployment's, outside the repository; an unreadable one
116 // stops the boot here rather than letting every write fail
117 // later with the same message.
118 let keys = match std::fs::read_to_string(&r2.key_file) {
119 Ok(keys) => keys,
120 Err(problem) => {
121 eprintln!("in: could not read {}: {problem}", r2.key_file.display());
122 std::process::exit(2);
123 }
124 };
125 let mut lines = keys.lines().map(str::trim).filter(|line| !line.is_empty());
126 let access_key_id = lines.next().unwrap_or_default();
127 let secret_access_key = lines.next().unwrap_or_default();
128 if access_key_id.is_empty() || secret_access_key.is_empty() {
129 eprintln!(
130 "in: {} must carry the access key id on its first line and the secret on its second",
131 r2.key_file.display()
132 );
133 std::process::exit(2);
134 }
135 let endpoint = format!("https://{}.r2.cloudflarestorage.com", r2.account_id);
136 let blobs = match R2Blobs::open(
137 &endpoint,
138 &r2.bucket,
139 access_key_id,
140 secret_access_key,
141 false,
142 ) {
143 Ok(blobs) => blobs,
144 Err(problem) => {
145 eprintln!("in: could not open the r2 bucket {}: {problem}", r2.bucket);
146 std::process::exit(2);
147 }
148 };
149 eprintln!("in blobs r2 {}", r2.bucket);
150 TursoStore::open_with_blobs(
151 &config.database,
152 Some(config.storage.as_path()),
153 Arc::new(blobs),
154 )
155 .await
156 .expect("failed to open the database")
157 }
158 None => TursoStore::open(&config.database, Some(config.storage.as_path()))
159 .await
160 .expect("failed to open the database"),
161 };
162 let store = Arc::new(store);
163
164 // Trash purge is policy, not storage hygiene: it happens with the
165 // configured horizon rather than any built-in default, so a deployment
166 // keeping trash longer than the default is never over-purged.
167 let cutoff =
168 time::OffsetDateTime::now_utc() - time::Duration::days(i64::from(config.purge_after_days));
169
170 // Nothing the first request needs waits for the boot's hygiene: the
171 // walk of every file and thumbnail on disk, the aborted uploads, the
172 // trash purge. The store is usable the moment `open` returns — schema
173 // live, storage tree in place — and the sweeps only delete what no row
174 // names and what has already expired, so they run as a background task
175 // while the port is about to answer. A sweep that fails is logged and
176 // lived with: an unswept tree is slow, never wrong.
177 let sweeper = store.clone();
178 tokio::spawn(async move {
179 if let Err(problem) = sweeper.boot_sweeps().await {
180 eprintln!("in: boot sweeps failed: {problem}");
181 }
182 match sweeper.purge_expired(cutoff).await {
183 Ok(0) => {}
184 Ok(purged) => println!("in purged {purged} trashed item(s)"),
185 Err(problem) => eprintln!("in: trash purge failed: {problem}"),
186 }
187 });
188 let store: Arc<dyn in_core::store::Store> = store;
189
190 // The `in.key` loaded here seals two things: the OIDC session cookies
191 // below, and — through the app context — the share-link tokens their
192 // creation seals onto setting rows, so the full link addresses can be
193 // re-shown later. One key per deployment, never in the repository.
194 let key_path = std::path::Path::new(&config.database)
195 .parent()
196 .map(|parent| parent.join("in.key"))
197 .unwrap_or_else(|| std::path::PathBuf::from("in.key"));
198 let cookie_key = match in_core::store::secret::load_or_create_key(&key_path) {
199 Ok(key) => key,
200 Err(problem) => {
201 eprintln!("in: could not load {}: {problem}", key_path.display());
202 std::process::exit(2);
203 }
204 };
205 let oidc = in_client::Config {
206 issuer: config.oidc.issuer.clone(),
207 client_id: config.oidc.client_id.clone(),
208 client_secret: config.oidc.client_secret.clone(),
209 redirect_uri: config.oidc.redirect_uri.clone(),
210 cookie_name: "in_session".to_string(),
211 cookie_key,
212 // Where im's `/logout` sends the browser after the central
213 // sign-out: the same origin public links carry.
214 logout_back: config.public_origin(),
215 };
216
217 // The same client pair, pointed at im's identity directory: the roster
218 // the mirror below files, the photo bytes the avatar route proxies, and
219 // the live feed that makes both arrive without waiting for a beat.
220 let directory = im_client::directory::DirectoryClient::new(
221 config.oidc.issuer.clone(),
222 config.oidc.client_id.clone(),
223 config.oidc.client_secret.clone(),
224 );
225 let default_quota_bytes = config.default_quota_bytes;
226 let health = in_web::server::DirectoryHealth::new();
227 tokio::spawn(identity_sync(
228 store.clone(),
229 directory.clone(),
230 default_quota_bytes,
231 health.clone(),
232 ));
233
234 // The suite the switcher's wordmarks link to is im's to keep: im's
235 // admin panel owns the list and `/family` serves it to registered
236 // apps. This mirror is refreshed on the beat, first pass right away so
237 // a fresh deploy shows the trio at boot; an im that does not answer —
238 // down, restarting, mid-deploy — costs one log line and nothing else:
239 // the last list filed keeps the switcher alive until the next beat.
240 // The address the app registers itself under: `base_url` alone, without
241 // the trailing slash im keeps its entries free of. The bound address is
242 // no fallback here — a loopback bind is not an address anyone else can
243 // reach, and filing it would overwrite the real one in every switcher.
244 let public_origin = config
245 .base_url
246 .as_deref()
247 .unwrap_or("")
248 .trim_end_matches('/')
249 .to_string();
250 tokio::spawn(family_sync(
251 store.clone(),
252 in_client::InClient::new(oidc.clone()),
253 public_origin,
254 default_quota_bytes,
255 ));
256
257 // Told when the process is stopping, so the live streams end instead of
258 // being waited out. See `in_web::live::Shutdown`.
259 let (stop, stopping) = tokio::sync::watch::channel(false);
260 let live_seconds = config.live_seconds;
261 let listen = config.listen;
262
263 let router = in_client::mount(
264 Router::builder()
265 .discover()
266 .runtime()
267 // BodyLimit is only a memory guard here, not the upload policy:
268 // the account quota, enforced in the store at start and finish,
269 // is the only size limit. `/files` takes whole multipart bodies,
270 // so its guard sits at a hard 2 GiB; `/api/upload` carries single
271 // 8 MiB chunks, so 32 MiB leaves ample headroom.
272 .layer(BodyLimit::max(32 * 1024 * 1024).at("/api/upload"))
273 .layer(BodyLimit::max(512 * 1024 * 1024).at("/api/service/files"))
274 .layer(BodyLimit::max(2usize * 1024 * 1024 * 1024).at("/files"))
275 .cookies()
276 .assets(bundle)
277 .trusted_proxies(in_web::server::trusted_proxies()),
278 oidc,
279 )
280 .app_context(in_web::server::App {
281 store,
282 config,
283 shutdown: in_web::live::Shutdown(stopping),
284 link_key: cookie_key,
285 directory,
286 health,
287 })
288 .app_context(in_client::LogoutBack(Arc::new(|cx: &Cx| {
289 Box::pin(async move { Some(in_web::server::share_origin(cx).await) })
290 })))
291 .app_context(in_web::live::LiveWindow(std::time::Duration::from_secs(
292 live_seconds,
293 )))
294 .build();
295
296 // `topcoat::start` binds HOST/PORT from the environment; the listen
297 // address is a config/in.toml decision, so the listener is bound
298 // explicitly against the same value the boot log just printed.
299 let listener = tokio::net::TcpListener::bind(listen)
300 .await
301 .expect("failed to bind the listen address");
302 // Not `topcoat::serve`, which installs its own signal handler and gives
303 // no way to hear it. The handler is taken over so the live streams learn
304 // about the stop before the graceful shutdown starts counting: without
305 // that, every open tab holds a stream the shutdown waits its full thirty
306 // seconds for, and Ctrl+C appears to hang.
307 topcoat::serve_until(listener, router, async move {
308 shutdown_signal().await;
309 let _ = stop.send(true);
310 })
311 .await
312 .expect("server error");
313}
314
315/// Makes the storage tree the store keeps binary files in, if it is not
316/// there: `<storage>/files`, `<storage>/thumbs` and `<storage>/uploads`,
317/// private to the user the process runs as. A
318/// directory that exists is left exactly as it is; one that cannot be made
319/// stops the boot — the failure
320/// this prevents is an upload landing in a tree that is not there, and it is
321/// better met before anything is opened.
322fn ensure_storage_tree(storage: &std::path::Path) {
323 let make = |dir: &std::path::Path| {
324 if let Err(err) = std::fs::create_dir_all(dir) {
325 eprintln!("in: could not create {}: {err}", dir.display());
326 std::process::exit(2);
327 }
328 #[cfg(unix)]
329 {
330 use std::os::unix::fs::PermissionsExt;
331 if let Err(err) = std::fs::set_permissions(dir, std::fs::Permissions::from_mode(0o700))
332 {
333 eprintln!("in: could not restrict {}: {err}", dir.display());
334 std::process::exit(2);
335 }
336 }
337 };
338 make(storage);
339 for name in ["files", "thumbs", "uploads"] {
340 make(&storage.join(name));
341 }
342}
343
344/// Resolves when the process is asked to stop: Ctrl+C, or `SIGTERM` from a
345/// service manager.
346async fn shutdown_signal() {
347 let interrupt = async {
348 tokio::signal::ctrl_c()
349 .await
350 .expect("failed to install the Ctrl+C handler");
351 };
352 let terminate = async {
353 tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate())
354 .expect("failed to install the SIGTERM handler")
355 .recv()
356 .await;
357 };
358
359 tokio::select! {
360 () = interrupt => {}
361 () = terminate => {}
362 }
363}
364
365/// The longest wait a run of directory failures earns before trying again.
366const IDENTITY_BACKOFF_CAP: std::time::Duration = std::time::Duration::from_secs(30);
367
368/// Mirrors one member's identity into the local row: the JIT upsert that
369/// keeps address, name, admin flag and photo stamp following im — and the
370/// disablement flag with it, both directions, for the row is im's word on
371/// the person and a re-enable must land here as surely as a kill. The
372/// store announces a `profile` change itself when a mirrored field moved,
373/// and a flipped disablement announces the admin surface, the profile and
374/// the person's own tabs all at once, so the only job left here is the
375/// write and its one log line when it fails.
376async fn mirror_member(
377 store: &Arc<dyn in_core::store::Store>,
378 member: &im_client::directory::DirectoryMember,
379 default_quota_bytes: u64,
380) {
381 let user = match store
382 .provision_user(
383 &member.sub,
384 &member.email,
385 &member.name,
386 Some(member.admin),
387 member.photo_version,
388 default_quota_bytes,
389 )
390 .await
391 {
392 Ok(user) => user,
393 Err(problem) => {
394 eprintln!("in: directory mirror of {}: {problem}", member.sub);
395 return;
396 }
397 };
398 if user.disabled != member.disabled
399 && let Err(problem) = store.set_user_disabled(&user.id, member.disabled).await
400 {
401 eprintln!(
402 "in: directory disablement mirror of {}: {problem}",
403 member.sub
404 );
405 }
406}
407
408/// Keeps the local user rows a live mirror of im's identity directory.
409///
410/// The shape is one pass, one stream, repeat: a full `/directory` pass
411/// files (or heals) every member row, then `/directory/live` carries each
412/// change as it happens. When the stream ends — im restarting, or its
413/// window closing — the loop simply runs the full pass again: a lagged
414/// reader hears silence, not partial frames, so the re-list is what catches
415/// it up, and the redial is the fast path again. A pass that fails backs
416/// off a second, then doubles to the cap, resetting on the next answer.
417/// Runs the whole life of the process; nothing here is worth keeping alive
418/// past shutdown.
419async fn identity_sync(
420 store: Arc<dyn in_core::store::Store>,
421 client: im_client::directory::DirectoryClient,
422 default_quota_bytes: u64,
423 health: in_web::server::DirectoryHealth,
424) {
425 let mut backoff = std::time::Duration::from_secs(1);
426 loop {
427 match client.directory().await {
428 Ok(members) => {
429 backoff = std::time::Duration::from_secs(1);
430 for member in &members {
431 mirror_member(&store, member, default_quota_bytes).await;
432 }
433 // The roster pass committed: the card's healer heartbeat.
434 health.note_pass();
435 match client.open_stream().await {
436 Ok(mut stream) => {
437 health.connected();
438 while let Some(event) = stream.next().await {
439 match event {
440 Ok(event) => {
441 apply_directory_event(
442 &store,
443 &health,
444 event,
445 default_quota_bytes,
446 )
447 .await;
448 }
449 // A network failure ends the stream; the full
450 // pass below re-lists before the redial.
451 Err(problem) => {
452 health.reconnecting();
453 eprintln!("in: directory stream failed: {problem}");
454 break;
455 }
456 }
457 }
458 // The stream closed cleanly — im restarting or its
459 // window running out. The card goes amber until the
460 // redial below opens the next one.
461 health.reconnecting();
462 }
463 Err(problem) => {
464 health.reconnecting();
465 eprintln!("in: directory stream refused: {problem}")
466 }
467 }
468 }
469 Err(problem) => {
470 health.reconnecting();
471 eprintln!("in: directory pass failed: {problem}")
472 }
473 }
474 tokio::time::sleep(backoff).await;
475 backoff = (backoff * 2).min(IDENTITY_BACKOFF_CAP);
476 }
477}
478
479/// One event off the directory stream, applied to the local mirror. The
480/// seam exists so the tests can drive a constructed event through the
481/// same door identity_sync's stream loop uses — the loop itself only
482/// knows how to read the wire.
483async fn apply_directory_event(
484 store: &Arc<dyn in_core::store::Store>,
485 health: &in_web::server::DirectoryHealth,
486 event: im_client::directory::DirectoryEvent,
487 default_quota_bytes: u64,
488) {
489 match event {
490 im_client::directory::DirectoryEvent::Profile(member) => {
491 mirror_member(store, &member, default_quota_bytes).await;
492 }
493 // Sessions died at im; no local row moved. Wake the person
494 // through the profile topic — their tabs refetch, meet the dead
495 // introspection, and morph to the sign-in card.
496 im_client::directory::DirectoryEvent::Revoked { sub } => {
497 announce_revocation(store, &sub).await;
498 }
499 }
500 // Every event is proof the feed is alive; the card's age line reads
501 // this.
502 health.note_event();
503}
504
505/// The session-targeted half of a directory revocation: im revoked the
506/// person's sessions and no local row moved, but every tab carrying them
507/// must find out. The row is woken through the ordinary profile
508/// announcement — the one topic every signed-in reader may hear — so the
509/// revoked person's own tabs refetch, meet a dead introspection, and
510/// morph to the sign-in card: the whole of what a session-level logout
511/// looks like from here. No hard redirect: which of the person's
512/// sessions died is im's knowledge alone, and a surviving tab must not
513/// be ordered out for its sibling's death.
514async fn announce_revocation(store: &Arc<dyn in_core::store::Store>, sub: &str) {
515 match store.user_by_oidc_sub(sub).await {
516 Ok(Some(user)) => store.announce_profile(&user.id),
517 // Nobody local carries this subject: nobody here to wake.
518 Ok(None) => {}
519 Err(problem) => eprintln!("in: revocation wake for {sub}: {problem}"),
520 }
521}
522
523/// How often the suite list is re-fetched from im. Short enough that a
524/// service the admin adds over there shows up here before anyone goes
525/// looking for its wordmark, long enough that the two are not talking
526/// about it constantly.
527const FAMILY_SECONDS: u64 = 300;
528
529/// Keeps the switcher's list a mirror of im's family: fetched as this app
530/// (Basic client credentials) and filed as a JSON string under the
531/// `family` setting — the one row the switcher reads, so a beat that
532/// answers simply replaces what is filed. Runs the whole life of the
533/// process; nothing here is worth keeping alive past shutdown.
534async fn family_sync(
535 store: Arc<dyn in_core::store::Store>,
536 client: in_client::InClient,
537 origin: String,
538 default_quota_bytes: u64,
539) {
540 if origin.is_empty() {
541 eprintln!("family: no public address to register; set base_url");
542 }
543 loop {
544 // Announced before every fetch, so an im that was down, restarted
545 // or freshly seeded learns this app on the next beat. A refusal is
546 // one log line: the mirror below runs either way.
547 if !origin.is_empty()
548 && let Err(problem) = client.register_family("in", "Files", &origin).await
549 {
550 eprintln!("family register: {problem}");
551 }
552 match client.family().await {
553 Some(family) => {
554 // The limits ride the same list: every service key's account
555 // takes the ceiling im states for it (the house default when
556 // im states none). A refused write is one log line — the
557 // next beat carries the same word.
558 if let Err(problem) =
559 in_web::service::apply_family_limits(&store, &family, default_quota_bytes).await
560 {
561 eprintln!("family limits: {problem}");
562 }
563 match serde_json::to_string(&family) {
564 Ok(json) => {
565 if let Err(problem) = store.set_setting("family", &json).await {
566 eprintln!("family sync: {problem}");
567 }
568 }
569 Err(problem) => eprintln!("family sync: {problem}"),
570 }
571 }
572 None => eprintln!("family sync: im did not answer; keeping the list there is"),
573 }
574 tokio::time::sleep(std::time::Duration::from_secs(FAMILY_SECONDS)).await;
575 }
576}
577
578#[cfg(test)]
579mod tests {
580 use super::*;
581 use in_core::store::Store;
582
583 /// A revoked session at im wakes the person's row by its local id:
584 /// one profile announcement, heard by every signed-in reader, with
585 /// the person's own tabs morphing to the sign-in card on the refetch.
586 /// A subject that never signed in here wakes nobody.
587 #[tokio::test]
588 async fn a_revoked_session_wakes_the_persons_row_through_the_profile_topic() {
589 let dir = std::env::temp_dir().join(format!("in-revoke-{}", ulid::Ulid::generate()));
590 std::fs::create_dir_all(&dir).unwrap();
591 let store: Arc<dyn in_core::store::Store> = Arc::new(
592 in_core::store::TursoStore::open(
593 dir.join("in.db").to_str().unwrap(),
594 Some(&dir.join("storage")),
595 )
596 .await
597 .unwrap(),
598 );
599 let user = store
600 .provision_user("sub-gone", "gone@in.test", "Gone", None, 0, 1024)
601 .await
602 .unwrap();
603 let mut rx = store.subscribe();
604
605 announce_revocation(&store, "sub-gone").await;
606
607 let change = rx.try_recv().unwrap();
608 assert_eq!(change.topic.kind(), "profile");
609 assert_eq!(change.topic.id(), user.id);
610 assert!(matches!(
611 rx.try_recv(),
612 Err(tokio::sync::broadcast::error::TryRecvError::Empty)
613 ));
614
615 announce_revocation(&store, "sub-unknown").await;
616 assert!(matches!(
617 rx.try_recv(),
618 Err(tokio::sync::broadcast::error::TryRecvError::Empty)
619 ));
620
621 drop(store);
622 let _ = std::fs::remove_dir_all(&dir);
623 }
624
625 /// One roster member as the wire carries it.
626 fn member(sub: &str, disabled: bool) -> im_client::directory::DirectoryMember {
627 im_client::directory::DirectoryMember {
628 sub: sub.to_string(),
629 email: format!("{sub}@in.test"),
630 name: "Member".to_string(),
631 admin: false,
632 photo_version: 0,
633 timezone: "UTC+03:00".to_string(),
634 disabled,
635 }
636 }
637
638 async fn scratch() -> (std::path::PathBuf, Arc<dyn in_core::store::Store>) {
639 let dir = std::env::temp_dir().join(format!("in-event-{}", ulid::Ulid::generate()));
640 std::fs::create_dir_all(&dir).unwrap();
641 let store: Arc<dyn in_core::store::Store> = Arc::new(
642 in_core::store::TursoStore::open(
643 dir.join("in.db").to_str().unwrap(),
644 Some(&dir.join("storage")),
645 )
646 .await
647 .unwrap(),
648 );
649 (dir, store)
650 }
651
652 /// A `revoked` frame off the stream — im's word that the subject's
653 /// sessions died — wakes the person's row by its local id through
654 /// the profile topic, and stamps the connection card's freshness.
655 #[tokio::test]
656 async fn a_stream_revocation_announces_through_the_profile_topic() {
657 let (dir, store) = scratch().await;
658 let health = in_web::server::DirectoryHealth::new();
659 let user = store
660 .provision_user("sub-gone", "gone@in.test", "Gone", None, 0, 1024)
661 .await
662 .unwrap();
663 let mut rx = store.subscribe();
664
665 apply_directory_event(
666 &store,
667 &health,
668 im_client::directory::DirectoryEvent::Revoked {
669 sub: "sub-gone".to_string(),
670 },
671 1024,
672 )
673 .await;
674
675 let change = rx.try_recv().unwrap();
676 assert_eq!(change.topic.kind(), "profile");
677 assert_eq!(change.topic.id(), user.id);
678 assert!(matches!(
679 rx.try_recv(),
680 Err(tokio::sync::broadcast::error::TryRecvError::Empty)
681 ));
682 assert!(health.last_event_age_secs().is_some());
683
684 drop(store);
685 let _ = std::fs::remove_dir_all(&dir);
686 }
687
688 /// The member's disablement flag follows im in both directions: a
689 /// `profile` frame carrying `disabled` flips the local row and — the
690 /// part the tabs wait for — the store announces the kill (and, on
691 /// the way back, the reopening) on all three surfaces at once.
692 #[tokio::test]
693 async fn a_members_disabled_flag_mirrors_both_ways() {
694 let (dir, store) = scratch().await;
695 let health = in_web::server::DirectoryHealth::new();
696 let mut rx = store.subscribe();
697
698 // First sight: the mirror inserts the row, present and enabled.
699 apply_directory_event(
700 &store,
701 &health,
702 im_client::directory::DirectoryEvent::Profile(member("sub-m", false)),
703 1024,
704 )
705 .await;
706 let user = store.user_by_oidc_sub("sub-m").await.unwrap().unwrap();
707 assert!(!user.disabled);
708 // A fresh row announces the admin surface and the profile — the
709 // two reads that keep the later phases' queues clean.
710 assert_eq!(rx.try_recv().unwrap().topic.kind(), "admin");
711 assert_eq!(rx.try_recv().unwrap().topic.kind(), "profile");
712 // im switches the member off: the row follows, and the revoked
713 // frame rides to the person's own tabs.
714 apply_directory_event(
715 &store,
716 &health,
717 im_client::directory::DirectoryEvent::Profile(member("sub-m", true)),
718 1024,
719 )
720 .await;
721 let killed = store.user_by_oidc_sub("sub-m").await.unwrap().unwrap();
722 assert!(killed.disabled);
723 assert_eq!(rx.try_recv().unwrap().topic.kind(), "admin");
724 assert_eq!(rx.try_recv().unwrap().topic.kind(), "profile");
725 assert_eq!(rx.try_recv().unwrap().topic.kind(), "revoked");
726
727 // im lets them back in: the same channel carries the reopening.
728 apply_directory_event(
729 &store,
730 &health,
731 im_client::directory::DirectoryEvent::Profile(member("sub-m", false)),
732 1024,
733 )
734 .await;
735 let back = store.user_by_oidc_sub("sub-m").await.unwrap().unwrap();
736 assert!(!back.disabled);
737 assert_eq!(rx.try_recv().unwrap().topic.kind(), "admin");
738 assert_eq!(rx.try_recv().unwrap().topic.kind(), "profile");
739 assert_eq!(rx.try_recv().unwrap().topic.kind(), "revoked");
740 assert!(health.last_event_age_secs().is_some());
741
742 drop(store);
743 let _ = std::fs::remove_dir_all(&dir);
744 }
745}