forge
Explore
Log in

Don't you dare go Hollow

im_old

Clone
★ 0

0 watching0 forksRustGPL-3.0755.6 KiB84318dcTahinli2 months ago77 commits

directory.rs1661 lines, 62.5 KiBHistoryRawDownload
1//! The family phonebook: every non-disabled user, answered to registered
2//! apps only. A sibling (iz, in) mirrors this into its own member rows, so
3//! a person can be assigned or mailed before their first visit. Browsers
4//! never see it — the only credential is a client's Basic pair, the same
5//! one the photo route takes.
6
7use std::time::{Duration, Instant};
8
9use futures_util::StreamExt;
10use tokio::sync::broadcast::error::RecvError;
11use topcoat::context::Cx;
12use topcoat::router::content::Json;
13use topcoat::router::content::sse::{Event, KeepAlive, Sse};
14use topcoat::router::response::IntoResponse as _;
15use topcoat::router::{StatusCode, route};
16
17use crate::server;
18
19/// One directory entry: exactly what an app needs to provision a member —
20/// the stable subject, the address, the display name, whether im calls
21/// them an admin (apps derive their own admin authorization from it, as
22/// with `/introspect`), and how many times the photo has changed — the
23/// `?v=` that lets `/photo/{sub}` stay cacheable and still go fresh. One
24/// shape, three readers: `/directory` JSON, the `/directory/live` stream,
25/// and the in-process live bus all serialize it the same way.
26#[derive(Clone, Debug, serde::Serialize)]
27pub struct DirectoryMember {
28 pub sub: String,
29 pub email: String,
30 pub name: String,
31 pub admin: bool,
32 pub photo_version: u64,
33 /// The member's display timezone, iz's fixed-offset spelling. This
34 /// side only serializes — the field is always written — so the serde
35 /// default lives on the SDK's reading half.
36 pub timezone: String,
37 /// Whether im has switched the member off. Always written; older
38 /// readers take the serde default — a member whose flag they cannot
39 /// see reads as present-and-enabled, which it was.
40 #[serde(default)]
41 pub disabled: bool,
42}
43
44impl DirectoryMember {
45 /// The member this user row answers as right now.
46 pub fn of(user: &im_core::model::User) -> Self {
47 Self {
48 sub: user.id.to_string(),
49 email: user.email.clone(),
50 name: user.name.clone(),
51 admin: user.admin,
52 photo_version: user.photo_version,
53 timezone: user.timezone.clone(),
54 disabled: user.disabled,
55 }
56 }
57}
58
59/// `GET /directory`: the non-disabled roster as JSON. A wrong or missing
60/// client pair is `invalid_client`, the way `/introspect` refuses.
61#[route(GET "/directory")]
62async fn directory(cx: &Cx) -> topcoat::Result<topcoat::router::response::Response> {
63 if !server::valid_app(cx).await {
64 return (
65 StatusCode::UNAUTHORIZED,
66 Json(serde_json::json!({ "error": "invalid_client" })),
67 )
68 .into_response(cx);
69 }
70 let store = server::app(cx).store.clone();
71 let users = im_core::accounts::list_users(&store).await?;
72 let members: Vec<DirectoryMember> = users
73 .into_iter()
74 .filter(|user| !user.disabled)
75 .map(|user| DirectoryMember::of(&user))
76 .collect();
77 let members = serde_json::to_value(members)?;
78 Json(members).into_response(cx)
79}
80/// `GET /directory/live`: the roster's change feed, as server-sent events.
81/// The same Basic pair `/directory` takes is the only credential. The
82/// stream opens with the reconnection hint, then carries one `profile`
83/// event per changed member, serialized exactly as `/directory` would
84/// answer that member; keep-alive comments hold quiet stretches and
85/// proxies open. Every change announces itself after its commit, so a
86/// frame's row never runs ahead of `/directory` itself. A lagged reader
87/// gets no frame — which rows dropped is unknowable — and heals the gap
88/// the way any disconnect does: wait out the retry hint, re-list the
89/// whole roster, resume. A `revoked` frame carries only the subject whose
90/// sessions died — the cue for an app to send that subject's tabs home.
91#[route(GET "/directory/live")]
92async fn directory_live(cx: &Cx) -> topcoat::Result<topcoat::router::response::Response> {
93 if server::app_client(cx).await.is_none() {
94 return (
95 StatusCode::UNAUTHORIZED,
96 Json(serde_json::json!({ "error": "invalid_client" })),
97 )
98 .into_response(cx);
99 }
100 let rx = server::app(cx).live.subscribe();
101 let stopping =
102 topcoat::context::try_app_context::<crate::live::Shutdown>(cx).map(|s| s.0.clone());
103 let deadline = Instant::now() + crate::live::WINDOW;
104
105 let events = futures_util::stream::unfold(
106 (rx, deadline, stopping, true),
107 |(mut rx, deadline, mut stopping, mut first)| async move {
108 // The one frame every client sees first: how long to wait
109 // before dialing back in after the stream drops.
110 if first {
111 first = false;
112 return Some((
113 Ok::<_, std::convert::Infallible>(
114 Event::new()
115 .comment("directory live")
116 .retry(Duration::from_millis(5000)),
117 ),
118 (rx, deadline, stopping, first),
119 ));
120 }
121 loop {
122 // Already going down: end, so this connection is not one
123 // the shutdown has to sit and wait out.
124 if stopping.as_ref().is_some_and(|watch| *watch.borrow()) {
125 return None;
126 }
127 let left = deadline.saturating_duration_since(Instant::now());
128 if left.is_zero() {
129 return None;
130 }
131 let heard = tokio::time::timeout(left, async {
132 match stopping.as_mut() {
133 Some(watch) => tokio::select! {
134 _ = watch.changed() => None,
135 got = rx.recv() => Some(got),
136 },
137 None => Some(rx.recv().await),
138 }
139 })
140 .await;
141 let member = match heard {
142 // The window closed, the server is stopping, or the
143 // broadcaster is gone — the process with it. Ending is
144 // the point: the client reconnects on its own.
145 Err(_) | Ok(None) => return None,
146 Ok(Some(Err(RecvError::Closed))) => return None,
147 // A tick moves im's own pages, not the roster; a lagged
148 // reader cannot know which rows it lost. Both are silence
149 // here — a full re-list after any reconnect heals both.
150 Ok(Some(Err(RecvError::Lagged(_)))) | Ok(Some(Ok(server::LiveEvent::Tick))) => {
151 continue;
152 }
153 Ok(Some(Ok(server::LiveEvent::Profile(member)))) => member,
154 // A sign-out in motion: every app watching the roster
155 // hears which subject just lost its sessions, and sends
156 // its own signed-in tabs of that subject home. Which
157 // session died is im's own business.
158 Ok(Some(Ok(server::LiveEvent::Revoked { user_id, .. }))) => {
159 return Some((
160 Ok(Event::new().event("revoked").data(
161 serde_json::json!({ "sub": user_id }).to_string(),
162 )),
163 (rx, deadline, stopping, first),
164 ));
165 }
166 };
167 // A member that will not serialize cannot happen — plain
168 // fields all the way down — but a stream cannot panic on
169 // the impossible: ending is the honest answer, and the
170 // client heals the gap the way it heals any disconnect.
171 let Ok(json) = serde_json::to_string(&member) else {
172 return None;
173 };
174 return Some((
175 Ok(Event::new().event("profile").data(json)),
176 (rx, deadline, stopping, first),
177 ));
178 }
179 },
180 );
181
182 Sse::new(events.boxed())
183 .keep_alive(KeepAlive::new())
184 .into_response(cx)
185}
186
187/// `GET /family`: the app switcher's list — every service with its wordmark,
188/// name, and base URL, in the stored order, as a bare JSON array. Registered
189/// apps only, exactly like `/directory`: a sibling copies this into its own
190/// database and renders its switcher from that copy, so the family list has
191/// one home (this table) and every other surface a cached mirror. The rows
192/// come from the panel and from the apps themselves — see
193/// `POST /family/register`.
194#[route(GET "/family")]
195async fn family(cx: &Cx) -> topcoat::Result<topcoat::router::response::Response> {
196 if !server::valid_app(cx).await {
197 return (
198 StatusCode::UNAUTHORIZED,
199 Json(serde_json::json!({ "error": "invalid_client" })),
200 )
201 .into_response(cx);
202 }
203 let store = server::app(cx).store.clone();
204 let services = im_core::services::list(&store).await?;
205 let services = serde_json::to_value(services)?;
206 Json(services).into_response(cx)
207}
208
209/// The body a sibling posts to keep its own row: its wordmark key, the
210/// name a fresh row is born with, and the address it answers on now.
211#[derive(serde::Deserialize)]
212struct Registration {
213 key: String,
214 name: String,
215 url: String,
216}
217
218/// `POST /family/register`: an app writes its own row of the family. Same
219/// Basic pair as `/family`, and the authenticated client id is the owner —
220/// so a row an app keeps is refreshed on its every boot, never taken over
221/// by another app (409) and no longer the panel's to remove or re-point.
222#[route(POST "/family/register")]
223async fn family_register(
224 cx: &Cx,
225 Json(input): Json<Registration>,
226) -> topcoat::Result<topcoat::router::response::Response> {
227 let Some(client_id) = server::app_client(cx).await else {
228 return (
229 StatusCode::UNAUTHORIZED,
230 Json(serde_json::json!({ "error": "invalid_client" })),
231 )
232 .into_response(cx);
233 };
234 let store = server::app(cx).store.clone();
235 match im_core::services::register(
236 &store,
237 &input.key,
238 &input.name,
239 &input.url,
240 &client_id,
241 Some(&client_id),
242 )
243 .await
244 {
245 Ok(service) => {
246 let service = serde_json::to_value(&service)?;
247 Json(service).into_response(cx)
248 }
249 Err(im_core::store::StoreError::Conflict(_)) => (
250 StatusCode::CONFLICT,
251 Json(serde_json::json!({ "error": "owned" })),
252 )
253 .into_response(cx),
254 Err(im_core::store::StoreError::Invalid(reason)) => (
255 StatusCode::BAD_REQUEST,
256 Json(serde_json::json!({ "error": "invalid", "reason": reason })),
257 )
258 .into_response(cx),
259 Err(e) => Err(e.into()),
260 }
261}
262
263#[cfg(test)]
264mod tests {
265 use std::path::Path;
266 use std::sync::Arc;
267
268 use im_core::accounts::{create_invite, create_user_from_invite};
269 use im_core::model::ClientId;
270 use im_core::oidc::create_client;
271 use im_core::store::Store;
272 use topcoat::asset::RouterBuilderAssetExt as _;
273 use topcoat::cookie::RouterBuilderCookieExt as _;
274 use topcoat::router::{
275 Body, Router, RouterBuilderDiscoverExt as _, StatusCode, header, to_bytes,
276 };
277
278 use crate::config::Config;
279 use crate::server::{self, SESSION_COOKIE};
280
281 struct Setup {
282 router: Router,
283 client_id: String,
284 secret: String,
285 store: Arc<Store>,
286 /// A handle on the live bus, for asserting what a change announces.
287 live: tokio::sync::broadcast::Sender<server::LiveEvent>,
288 }
289
290 async fn setup() -> Setup {
291 let store = Arc::new(Store::open(Path::new(":memory:")).await.unwrap());
292 let (client_id, secret) =
293 create_client(&store, "tasks", vec!["http://app/callback".into()])
294 .await
295 .unwrap();
296 let admin_invite = create_invite(&store, "ada@example.com", None, true)
297 .await
298 .unwrap();
299 create_user_from_invite(&store, admin_invite.expose(), "Ada", "tDLr9!mZQ2xv")
300 .await
301 .unwrap();
302 let plain_invite = create_invite(&store, "ben@example.com", None, false)
303 .await
304 .unwrap();
305 create_user_from_invite(&store, plain_invite.expose(), "Ben", "tDLr9!mZQ2xv")
306 .await
307 .unwrap();
308 let gone_invite = create_invite(&store, "gone@example.com", None, false)
309 .await
310 .unwrap();
311 let gone = create_user_from_invite(&store, gone_invite.expose(), "Gone", "tDLr9!mZQ2xv")
312 .await
313 .unwrap();
314 im_core::accounts::set_disabled(&store, &gone.id, true)
315 .await
316 .unwrap();
317 let services = vec![
318 crate::config::Service {
319 key: "in".into(),
320 name: "Files".into(),
321 url: "http://127.0.0.1:7655".into(),
322 },
323 crate::config::Service {
324 key: "im".into(),
325 name: "Account".into(),
326 url: "http://127.0.0.1:7650".into(),
327 },
328 crate::config::Service {
329 key: "iz".into(),
330 name: "Board".into(),
331 url: "http://127.0.0.1:7654".into(),
332 },
333 ];
334 // The boot's one-time seed: the config's list becomes the table's
335 // starting rows, which is what every reader — /family, the trio, the
336 // landing card, the logout allowlist — now goes through.
337 im_core::services::seed_from(&store, &core_services(&services))
338 .await
339 .unwrap();
340 let (live, _) = tokio::sync::broadcast::channel(64);
341 let app = server::App {
342 store: store.clone(),
343 config: Config {
344 database: ":memory:".into(),
345 listen: "127.0.0.1:7650".parse().unwrap(),
346 issuer: "http://127.0.0.1:7650".into(),
347 services,
348 },
349 live: live.clone(),
350 };
351 let router = Router::builder()
352 .discover()
353 .cookies()
354 // The pages shell renders its stylesheet link through the asset
355 // catalog, so the tests render pages against a real bundle: the
356 // one `serve` loads beside the executable where it exists, and
357 // otherwise a one-entry bundle folded from the stylesheet
358 // build.rs already compiled — a fresh checkout runs `cargo test`
359 // before any bundling step, and no test reads the bytes.
360 .assets(test_assets())
361 .app_context(app)
362 .build();
363 Setup {
364 router,
365 client_id: client_id.to_string(),
366 secret: secret.expose().to_string(),
367 store,
368 live,
369 }
370 }
371
372 /// The bundle the router renders against. A dev machine carries the
373 /// real one under `target/debug/assets`; on one that never ran the
374 /// bundler (CI), a minimal manifest is written beside a copy of the
375 /// stylesheet build.rs produced, so page GETs resolve their `<link>`
376 /// without any deploy-time step.
377 fn test_assets() -> topcoat::asset::AssetBundle {
378 // The layout's own declaration: `asset!` folds the declaring source
379 // file into the id, so a fresh one here would catalog a different
380 // id than any rendered page resolves.
381 let style = crate::layout::STYLE;
382 let dev = concat!(env!("CARGO_MANIFEST_DIR"), "/../../target/debug/assets");
383 if std::path::Path::new(dev).join("manifest.toml").is_file() {
384 return topcoat::asset::AssetBundle::load_dir(dev).unwrap();
385 }
386 // One directory per call: tests run on shared threads, and two
387 // setups rewriting one manifest can interleave a half-written file
388 // under the other's load.
389 static N: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
390 let dir = std::env::temp_dir().join(format!(
391 "im-web-test-assets-{}-{}",
392 std::process::id(),
393 N.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
394 ));
395 std::fs::create_dir_all(&dir).unwrap();
396 std::fs::copy(
397 concat!(env!("CARGO_MANIFEST_DIR"), "/assets/main.css"),
398 dir.join("main.css"),
399 )
400 .unwrap();
401 topcoat::asset::Manifest {
402 version: topcoat::asset::MANIFEST_VERSION,
403 assets: vec![topcoat::asset::ManifestEntry {
404 id: style.id(),
405 file: "main.css".into(),
406 hash: "0".repeat(64),
407 content_type: "text/css".into(),
408 }],
409 }
410 .save(dir.join("manifest.toml"))
411 .unwrap();
412 topcoat::asset::AssetBundle::load_dir(&dir).unwrap()
413 }
414
415 fn basic(client_id: &str, secret: &str) -> String {
416 use base64::Engine as _;
417 format!(
418 "Basic {}",
419 base64::engine::general_purpose::STANDARD.encode(format!("{client_id}:{secret}"))
420 )
421 }
422
423 async fn get(router: &Router, authorization: Option<String>) -> (StatusCode, String) {
424 let mut builder = http::Request::builder().uri("/directory");
425 if let Some(value) = authorization {
426 builder = builder.header(header::AUTHORIZATION, value);
427 }
428 let response = router.handle(builder.body(Body::empty()).unwrap()).await;
429 let (parts, body) = response.into_parts();
430 let bytes = to_bytes(body, usize::MAX).await.unwrap().to_vec();
431 (parts.status, String::from_utf8(bytes).unwrap())
432 }
433
434 /// The config's service list as the domain module's own shape — the one
435 /// conversion the boot-time seed needs.
436 fn core_services(config: &[crate::config::Service]) -> Vec<im_core::services::Service> {
437 config
438 .iter()
439 .map(|service| im_core::services::Service {
440 key: service.key.clone(),
441 name: service.name.clone(),
442 url: service.url.clone(),
443 owner: None,
444 client_id: None,
445 storage_limit_bytes: None,
446 })
447 .collect()
448 }
449
450 /// A form post through the router, answered as (status, Location, body).
451 async fn post_form(
452 router: &Router,
453 uri: &str,
454 body: &str,
455 cookie: Option<&str>,
456 ) -> (StatusCode, Option<String>, String) {
457 let mut builder = http::Request::builder()
458 .method(http::Method::POST)
459 .uri(uri)
460 .header(header::CONTENT_TYPE, "application/x-www-form-urlencoded");
461 if let Some(cookie) = cookie {
462 builder = builder.header(header::COOKIE, cookie);
463 }
464 let response = router
465 .handle(builder.body(Body::from(body.to_string())).unwrap())
466 .await;
467 let (parts, body) = response.into_parts();
468 let location = parts
469 .headers
470 .get(header::LOCATION)
471 .and_then(|v| v.to_str().ok())
472 .map(str::to_string);
473 let bytes = to_bytes(body, usize::MAX).await.unwrap().to_vec();
474 (parts.status, location, String::from_utf8(bytes).unwrap())
475 }
476
477 /// A top-level GET (the RP-initiated logout's shape), same answer triple.
478 async fn get_location(
479 router: &Router,
480 uri: &str,
481 cookie: &str,
482 ) -> (StatusCode, Option<String>) {
483 let response = router
484 .handle(
485 http::Request::builder()
486 .uri(uri)
487 .header(header::COOKIE, cookie)
488 .body(Body::empty())
489 .unwrap(),
490 )
491 .await;
492 let (parts, _) = response.into_parts();
493 let location = parts
494 .headers
495 .get(header::LOCATION)
496 .and_then(|v| v.to_str().ok())
497 .map(str::to_string);
498 (parts.status, location)
499 }
500
501 /// `GET /family` with an app's Basic pair (or without one).
502 async fn get_family(router: &Router, authorization: Option<String>) -> (StatusCode, String) {
503 let mut builder = http::Request::builder().uri("/family");
504 if let Some(value) = authorization {
505 builder = builder.header(header::AUTHORIZATION, value);
506 }
507 let response = router.handle(builder.body(Body::empty()).unwrap()).await;
508 let (parts, body) = response.into_parts();
509 let bytes = to_bytes(body, usize::MAX).await.unwrap().to_vec();
510 (parts.status, String::from_utf8(bytes).unwrap())
511 }
512
513 /// `POST /family/register` with a JSON body and (maybe) an app's pair.
514 async fn post_register(
515 router: &Router,
516 authorization: Option<String>,
517 body: serde_json::Value,
518 ) -> (StatusCode, serde_json::Value) {
519 let mut builder = http::Request::builder()
520 .method(http::Method::POST)
521 .uri("/family/register")
522 .header(header::CONTENT_TYPE, "application/json");
523 if let Some(value) = authorization {
524 builder = builder.header(header::AUTHORIZATION, value);
525 }
526 let response = router
527 .handle(builder.body(Body::from(body.to_string())).unwrap())
528 .await;
529 let (parts, body) = response.into_parts();
530 let bytes = to_bytes(body, usize::MAX).await.unwrap().to_vec();
531 let text = String::from_utf8(bytes).unwrap();
532 let json = serde_json::from_str(&text).unwrap_or(serde_json::Value::String(text));
533 (parts.status, json)
534 }
535
536 /// A page GET as a signed-in browser: the whole document back.
537 async fn get_page(router: &Router, uri: &str, cookie: &str) -> String {
538 let response = router
539 .handle(
540 http::Request::builder()
541 .uri(uri)
542 .header(header::COOKIE, cookie)
543 .body(Body::empty())
544 .unwrap(),
545 )
546 .await;
547 let (_, body) = response.into_parts();
548 let bytes = to_bytes(body, usize::MAX).await.unwrap().to_vec();
549 String::from_utf8(bytes).unwrap()
550 }
551
552 #[tokio::test]
553 async fn the_directory_names_every_non_disabled_user_with_its_admin_flag() {
554 let Setup {
555 router,
556 client_id,
557 secret,
558 ..
559 } = setup().await;
560 let (status, body) = get(&router, Some(basic(&client_id, &secret))).await;
561 assert_eq!(status, StatusCode::OK);
562 let members: serde_json::Value = serde_json::from_str(&body).unwrap();
563 let members = members.as_array().unwrap();
564 assert_eq!(members.len(), 2, "the disabled user must be absent: {body}");
565 let ada = members
566 .iter()
567 .find(|m| m["email"] == "ada@example.com")
568 .unwrap();
569 assert_eq!(ada["name"], "Ada");
570 assert_eq!(ada["admin"], true);
571 assert!(!ada["sub"].as_str().unwrap().is_empty());
572 let ben = members
573 .iter()
574 .find(|m| m["email"] == "ben@example.com")
575 .unwrap();
576 assert_eq!(ben["admin"], false);
577 }
578
579 #[tokio::test]
580 async fn the_directory_refuses_a_browser_and_an_unknown_client_alike() {
581 let Setup {
582 router, client_id, ..
583 } = setup().await;
584 let (status, _) = get(&router, None).await;
585 assert_eq!(status, StatusCode::UNAUTHORIZED);
586 let (status, _) = get(&router, Some(basic(&client_id, "wrong"))).await;
587 assert_eq!(status, StatusCode::UNAUTHORIZED);
588 let (status, _) = get(&router, Some(basic("no-such-client", "wrong"))).await;
589 assert_eq!(status, StatusCode::UNAUTHORIZED);
590 }
591
592 #[tokio::test]
593 async fn logout_revokes_the_central_session_and_only_returns_known_origins() {
594 let Setup {
595 router,
596 client_id,
597 secret,
598 store,
599 ..
600 } = setup().await;
601 let ada = im_core::accounts::user_by_email(&store, "ada@example.com")
602 .await
603 .unwrap()
604 .unwrap();
605
606 // The RP-initiated exit: `back` naming a stored service's own
607 // origin is honored verbatim — the sibling gets its browser back.
608 // The allowlist is the seeded table now; the config's copy is only
609 // the seed's source.
610 let one = im_core::sessions::create_session(&store, &ada.id, &Default::default())
611 .await
612 .unwrap();
613 let (status, location) = get_location(
614 &router,
615 "/logout?back=http%3A%2F%2F127.0.0.1%3A7655%2F",
616 &format!("{SESSION_COOKIE}={}", one.expose()),
617 )
618 .await;
619 assert_eq!(status, StatusCode::SEE_OTHER);
620 assert_eq!(location.as_deref(), Some("http://127.0.0.1:7655/"));
621
622 // A live app session bound to a second central session introspects
623 // active — until a logout with a foreign `back` lands. The refusal
624 // itself goes to the front door, and the revocation still lands:
625 // the very next introspection is inactive.
626 let two = im_core::sessions::create_session(&store, &ada.id, &Default::default())
627 .await
628 .unwrap();
629 let app_token = im_core::oidc::issue_app_session(
630 &store,
631 &ada.id,
632 &ClientId::from(client_id.clone()),
633 &im_core::accounts::hash_token(two.expose()),
634 )
635 .await
636 .unwrap();
637 let probe = format!(
638 "token={}&client_id={client_id}&client_secret={secret}",
639 app_token.expose()
640 );
641 let (status, _, body) = post_form(&router, "/introspect", &probe, None).await;
642 assert_eq!(status, StatusCode::OK);
643 assert_eq!(
644 serde_json::from_str::<serde_json::Value>(&body).unwrap()["active"],
645 true
646 );
647
648 let (status, location) = get_location(
649 &router,
650 "/logout?back=https%3A%2F%2Fevil.example%2F",
651 &format!("{SESSION_COOKIE}={}", two.expose()),
652 )
653 .await;
654 assert_eq!(status, StatusCode::SEE_OTHER);
655 assert_eq!(location.as_deref(), Some("/"));
656 let (status, _, body) = post_form(&router, "/introspect", &probe, None).await;
657 assert_eq!(status, StatusCode::OK);
658 assert_eq!(
659 serde_json::from_str::<serde_json::Value>(&body).unwrap()["active"],
660 false
661 );
662
663 // im's own form logout is untouched: front door, no `back` at all.
664 let three = im_core::sessions::create_session(&store, &ada.id, &Default::default())
665 .await
666 .unwrap();
667 let (status, location, _) = post_form(
668 &router,
669 "/logout",
670 "",
671 Some(&format!("{SESSION_COOKIE}={}", three.expose())),
672 )
673 .await;
674 assert_eq!(status, StatusCode::SEE_OTHER);
675 assert_eq!(location.as_deref(), Some("/"));
676 }
677
678 #[tokio::test]
679 async fn family_serves_the_stored_list_to_registered_apps_only() {
680 let Setup {
681 router,
682 client_id,
683 secret,
684 ..
685 } = setup().await;
686 let (status, body) = get_family(&router, None).await;
687 assert_eq!(status, StatusCode::UNAUTHORIZED);
688 assert_eq!(
689 serde_json::from_str::<serde_json::Value>(&body).unwrap()["error"],
690 "invalid_client"
691 );
692 let (status, _) = get_family(&router, Some(basic(&client_id, "wrong"))).await;
693 assert_eq!(status, StatusCode::UNAUTHORIZED);
694
695 // The seeded rows, in stored order, as a bare JSON array.
696 let (status, body) = get_family(&router, Some(basic(&client_id, &secret))).await;
697 assert_eq!(status, StatusCode::OK);
698 let family = serde_json::from_str::<serde_json::Value>(&body).unwrap();
699 let family = family
700 .as_array()
701 .unwrap()
702 .iter()
703 .map(|s| s["key"].as_str().unwrap())
704 .collect::<Vec<_>>();
705 assert_eq!(family, vec!["in", "im", "iz"], "{body}");
706 }
707
708 #[tokio::test]
709 async fn family_carries_the_limit_bytes_null_and_stated() {
710 let Setup {
711 router,
712 client_id,
713 secret,
714 store,
715 ..
716 } = setup().await;
717 let pair = basic(&client_id, &secret);
718 // No limit stated anywhere yet: every row's `limit_bytes` is null,
719 // the shape an unconfigured sibling still parses.
720 let (status, body) = get_family(&router, Some(pair.clone())).await;
721 assert_eq!(status, StatusCode::OK);
722 let family = serde_json::from_str::<serde_json::Value>(&body).unwrap();
723 for row in family.as_array().unwrap() {
724 assert!(
725 row.get("limit_bytes").unwrap().is_null(),
726 "no limit yet: {row}"
727 );
728 }
729
730 // The panel sets iz's cap; the next read carries plain bytes.
731 im_core::services::edit(
732 &store,
733 "iz",
734 "Board",
735 "http://127.0.0.1:7654",
736 Some(512 * 1024 * 1024),
737 )
738 .await
739 .unwrap();
740 let (status, body) = get_family(&router, Some(pair)).await;
741 assert_eq!(status, StatusCode::OK);
742 let family = serde_json::from_str::<serde_json::Value>(&body).unwrap();
743 let iz = family
744 .as_array()
745 .unwrap()
746 .iter()
747 .find(|row| row["key"] == "iz")
748 .unwrap();
749 assert_eq!(
750 iz["limit_bytes"],
751 serde_json::json!(512 * 1024 * 1024),
752 "{body}"
753 );
754 }
755
756
757 #[tokio::test]
758 async fn the_panel_edits_the_family_and_every_reader_follows_the_table() {
759 let Setup {
760 router,
761 client_id,
762 secret,
763 store,
764 ..
765 } = setup().await;
766 let ada = im_core::accounts::user_by_email(&store, "ada@example.com")
767 .await
768 .unwrap()
769 .unwrap();
770 let ben = im_core::accounts::user_by_email(&store, "ben@example.com")
771 .await
772 .unwrap()
773 .unwrap();
774
775 // A non-admin's post is sent to the front door and writes nothing.
776 let ben_session = im_core::sessions::create_session(&store, &ben.id, &Default::default())
777 .await
778 .unwrap();
779 let (status, location, _) = post_form(
780 &router,
781 "/admin/services_add",
782 "key=wiki&name=Wiki&url=http%3A%2F%2F127.0.0.1%3A99",
783 Some(&format!("{SESSION_COOKIE}={}", ben_session.expose())),
784 )
785 .await;
786 assert_eq!(status, StatusCode::SEE_OTHER);
787 assert_eq!(location.as_deref(), Some("/"));
788
789 // The admin's add lands back on the section, and /family carries
790 // the new row at the end — trailing slash stored off, like every URL.
791 let session = im_core::sessions::create_session(&store, &ada.id, &Default::default())
792 .await
793 .unwrap();
794 let cookie = format!("{SESSION_COOKIE}={}", session.expose());
795 let (status, location, _) = post_form(
796 &router,
797 "/admin/services_add",
798 "key=wiki&name=Wiki&url=http%3A%2F%2F127.0.0.1%3A99%2F",
799 Some(&cookie),
800 )
801 .await;
802 assert_eq!(status, StatusCode::SEE_OTHER);
803 assert_eq!(
804 location.as_deref(),
805 Some("/admin?section=services&ok=services")
806 );
807 let (_, body) = get_family(&router, Some(basic(&client_id, &secret))).await;
808 let family = serde_json::from_str::<serde_json::Value>(&body).unwrap();
809 let family = family.as_array().unwrap();
810 let keys = family
811 .iter()
812 .map(|s| s["key"].as_str().unwrap())
813 .collect::<Vec<_>>();
814 assert_eq!(keys, vec!["in", "im", "iz", "wiki"], "{body}");
815 assert_eq!(family[3]["url"], "http://127.0.0.1:99");
816 // The forms live on the panel's Services section now.
817 let panel = get_page(&router, "/admin?section=services", &cookie).await;
818 assert!(panel.contains(r#"action="/admin/services_add""#));
819 assert!(panel.contains(r#"action="/admin/services_edit""#));
820 // The landing is the read-only directory, admins included.
821 assert!(
822 !get_page(&router, "/?section=profile", &cookie)
823 .await
824 .contains(r#"action="/admin/services_add""#)
825 );
826 // And a non-admin cannot open the section at all — the panel's
827 // front-door redirect, like every admin page.
828 let (status, location) = get_location(
829 &router,
830 "/admin?section=services",
831 &format!("{SESSION_COOKIE}={}", ben_session.expose()),
832 )
833 .await;
834 assert_eq!(status, StatusCode::SEE_OTHER);
835 assert_eq!(location.as_deref(), Some("/"));
836
837 // Edit rewrites name and address; move up swaps with the neighbor.
838 let (_status, location, _) = post_form(
839 &router,
840 "/admin/services_edit",
841 "key=wiki&name=Docs&url=http%3A%2F%2F127.0.0.1%3A98",
842 Some(&cookie),
843 )
844 .await;
845 assert_eq!(
846 location.as_deref(),
847 Some("/admin?section=services&ok=services")
848 );
849 let (_status, location, _) = post_form(
850 &router,
851 "/admin/services_move",
852 "key=wiki&dir=up",
853 Some(&cookie),
854 )
855 .await;
856 assert_eq!(
857 location.as_deref(),
858 Some("/admin?section=services&ok=services")
859 );
860 let (_, body) = get_family(&router, Some(basic(&client_id, &secret))).await;
861 let family = serde_json::from_str::<serde_json::Value>(&body).unwrap();
862 let family = family.as_array().unwrap();
863 let keys = family
864 .iter()
865 .map(|s| s["key"].as_str().unwrap())
866 .collect::<Vec<_>>();
867 assert_eq!(keys, vec!["in", "im", "wiki", "iz"], "{body}");
868 assert_eq!(family[2]["name"], "Docs");
869 assert_eq!(family[2]["url"], "http://127.0.0.1:98");
870
871 // The logout allowlist is the table too: the DB-added origin — one
872 // no config ever named — gets its browser back.
873 let wiki_session = im_core::sessions::create_session(&store, &ada.id, &Default::default())
874 .await
875 .unwrap();
876 let (status, location) = get_location(
877 &router,
878 "/logout?back=http%3A%2F%2F127.0.0.1%3A98%2F",
879 &format!("{SESSION_COOKIE}={}", wiki_session.expose()),
880 )
881 .await;
882 assert_eq!(status, StatusCode::SEE_OTHER);
883 assert_eq!(location.as_deref(), Some("http://127.0.0.1:98/"));
884
885 // And once the row is gone, the same origin is refused to the door.
886 let (_status, location, _) =
887 post_form(&router, "/admin/services_remove", "key=wiki", Some(&cookie)).await;
888 assert_eq!(
889 location.as_deref(),
890 Some("/admin?section=services&ok=services")
891 );
892 let (_, body) = get_family(&router, Some(basic(&client_id, &secret))).await;
893 let family = serde_json::from_str::<serde_json::Value>(&body).unwrap();
894 let keys = family
895 .as_array()
896 .unwrap()
897 .iter()
898 .map(|s| s["key"].as_str().unwrap())
899 .collect::<Vec<_>>();
900 assert_eq!(keys, vec!["in", "im", "iz"], "{body}");
901 let gone_session = im_core::sessions::create_session(&store, &ada.id, &Default::default())
902 .await
903 .unwrap();
904 let (_status, location) = get_location(
905 &router,
906 "/logout?back=http%3A%2F%2F127.0.0.1%3A98%2F",
907 &format!("{SESSION_COOKIE}={}", gone_session.expose()),
908 )
909 .await;
910 assert_eq!(location.as_deref(), Some("/"));
911
912 // A value against the rules is the panel's refusal, not a write.
913 let bad_session = im_core::sessions::create_session(&store, &ada.id, &Default::default())
914 .await
915 .unwrap();
916 let (_status, location, _) = post_form(
917 &router,
918 "/admin/services_add",
919 "key=Wiki!&name=Wiki&url=http%3A%2F%2F127.0.0.1%3A97",
920 Some(&format!("{SESSION_COOKIE}={}", bad_session.expose())),
921 )
922 .await;
923 assert_eq!(
924 location.as_deref(),
925 Some("/admin?section=services&error=bad_service")
926 );
927 let (_, body) = get_family(&router, Some(basic(&client_id, &secret))).await;
928 assert_eq!(
929 serde_json::from_str::<serde_json::Value>(&body)
930 .unwrap()
931 .as_array()
932 .unwrap()
933 .len(),
934 3,
935 "{body}"
936 );
937 }
938
939 #[tokio::test]
940 async fn the_seed_fills_an_empty_table_once_and_never_rewrites_it() {
941 let Setup {
942 router,
943 client_id,
944 secret,
945 store,
946 ..
947 } = setup().await;
948 // The setup already seeded; a re-boot's seed must be a no-op, even
949 // though `in` is exactly the name the config carries.
950 let reseed = vec![im_core::services::Service {
951 key: "in".into(),
952 name: "Files".into(),
953 url: "http://127.0.0.1:7655".into(),
954 owner: None,
955 client_id: None,
956 storage_limit_bytes: None,
957 }];
958 assert!(!im_core::services::seed_from(&store, &reseed).await.unwrap());
959 let (_, body) = get_family(&router, Some(basic(&client_id, &secret))).await;
960 assert_eq!(
961 serde_json::from_str::<serde_json::Value>(&body)
962 .unwrap()
963 .as_array()
964 .unwrap()
965 .len(),
966 3,
967 "{body}"
968 );
969 }
970
971 #[tokio::test]
972 async fn an_app_registers_its_own_row_and_only_its_own() {
973 let Setup {
974 router,
975 client_id,
976 secret,
977 store,
978 ..
979 } = setup().await;
980
981 // No pair, no write.
982 let (status, body) = post_register(
983 &router,
984 None,
985 serde_json::json!({"key": "wiki", "name": "Wiki", "url": "http://wiki.example"}),
986 )
987 .await;
988 assert_eq!(status, StatusCode::UNAUTHORIZED);
989 assert_eq!(body["error"], "invalid_client");
990
991 // A fresh key is appended, and /family carries it right away.
992 let (status, body) = post_register(
993 &router,
994 Some(basic(&client_id, &secret)),
995 serde_json::json!({"key": "wiki", "name": "Wiki", "url": "http://wiki.example/"}),
996 )
997 .await;
998 assert_eq!(status, StatusCode::OK, "{body}");
999 assert_eq!(body["url"], "http://wiki.example");
1000 assert!(
1001 body.get("owner").is_none(),
1002 "the owner never leaves: {body}"
1003 );
1004 let (_, listed) = get_family(&router, Some(basic(&client_id, &secret))).await;
1005 let listed = serde_json::from_str::<serde_json::Value>(&listed).unwrap();
1006 let keys = listed
1007 .as_array()
1008 .unwrap()
1009 .iter()
1010 .map(|s| s["key"].as_str().unwrap())
1011 .collect::<Vec<_>>();
1012 assert_eq!(keys, vec!["in", "im", "iz", "wiki"]);
1013
1014 // A second app cannot take the key over.
1015 let (other_id, other_secret) =
1016 create_client(&store, "other", vec!["http://other/callback".into()])
1017 .await
1018 .unwrap();
1019 let (status, body) = post_register(
1020 &router,
1021 Some(basic(&other_id.to_string(), other_secret.expose())),
1022 serde_json::json!({"key": "wiki", "name": "Mine", "url": "http://evil.example"}),
1023 )
1024 .await;
1025 assert_eq!(status, StatusCode::CONFLICT);
1026 assert_eq!(body["error"], "owned");
1027
1028 // The keeper's next boot moves the address; the name is the panel's.
1029 im_core::services::edit(&store, "wiki", "Vikipedi", "http://wiki.example", None)
1030 .await
1031 .unwrap();
1032 let (status, body) = post_register(
1033 &router,
1034 Some(basic(&client_id, &secret)),
1035 serde_json::json!({"key": "wiki", "name": "Wiki", "url": "http://wiki.dizey.sh"}),
1036 )
1037 .await;
1038 assert_eq!(status, StatusCode::OK);
1039 assert_eq!(body["name"], "Vikipedi");
1040 assert_eq!(body["url"], "http://wiki.dizey.sh");
1041
1042 // A value against the rules is a 400 with the store's own reason.
1043 let (status, body) = post_register(
1044 &router,
1045 Some(basic(&client_id, &secret)),
1046 serde_json::json!({"key": "wiki", "name": "Wiki", "url": "ftp://wiki.example"}),
1047 )
1048 .await;
1049 assert_eq!(status, StatusCode::BAD_REQUEST);
1050 assert_eq!(body["error"], "invalid");
1051 assert!(body["reason"].as_str().unwrap().contains("http"), "{body}");
1052 }
1053
1054 #[tokio::test]
1055 async fn the_panel_cannot_remove_a_row_its_app_keeps() {
1056 let Setup {
1057 router,
1058 client_id,
1059 secret,
1060 store,
1061 ..
1062 } = setup().await;
1063 let ada = im_core::accounts::user_by_email(&store, "ada@example.com")
1064 .await
1065 .unwrap()
1066 .unwrap();
1067 let session = im_core::sessions::create_session(&store, &ada.id, &Default::default())
1068 .await
1069 .unwrap();
1070 let cookie = format!("{SESSION_COOKIE}={}", session.expose());
1071
1072 // The app claims the seeded `in` row.
1073 let (status, _) = post_register(
1074 &router,
1075 Some(basic(&client_id, &secret)),
1076 serde_json::json!({"key": "in", "name": "Files", "url": "https://in.dizey.sh"}),
1077 )
1078 .await;
1079 assert_eq!(status, StatusCode::OK);
1080
1081 // The panel's remove is refused and the row stays.
1082 let (_status, location, _) =
1083 post_form(&router, "/admin/services_remove", "key=in", Some(&cookie)).await;
1084 assert_eq!(
1085 location.as_deref(),
1086 Some("/admin?section=services&error=bad_service")
1087 );
1088 // So is a re-point; a rename still lands.
1089 let (_status, location, _) = post_form(
1090 &router,
1091 "/admin/services_edit",
1092 "key=in&name=Dosyalar&url=http%3A%2F%2Felsewhere.example",
1093 Some(&cookie),
1094 )
1095 .await;
1096 assert_eq!(
1097 location.as_deref(),
1098 Some("/admin?section=services&error=bad_service")
1099 );
1100 let (_status, location, _) = post_form(
1101 &router,
1102 "/admin/services_edit",
1103 "key=in&name=Dosyalar&url=https%3A%2F%2Fin.dizey.sh",
1104 Some(&cookie),
1105 )
1106 .await;
1107 assert_eq!(
1108 location.as_deref(),
1109 Some("/admin?section=services&ok=services")
1110 );
1111 let (_, body) = get_family(&router, Some(basic(&client_id, &secret))).await;
1112 let family = serde_json::from_str::<serde_json::Value>(&body).unwrap();
1113 assert_eq!(family[0]["key"], "in");
1114 assert_eq!(family[0]["name"], "Dosyalar");
1115 assert_eq!(family[0]["url"], "https://in.dizey.sh");
1116
1117 // And the panel offers no remove form for it — the marker instead.
1118 let panel = get_page(&router, "/admin?section=services", &cookie).await;
1119 assert!(panel.contains("kept by the app"), "the marker is missing");
1120 assert!(
1121 !panel.contains(r#"value="in"><button class="admin-action admin-danger"#),
1122 "an owned row must carry no remove form"
1123 );
1124 // The unowned rows still do.
1125 assert!(panel.contains(r#"action="/admin/services_remove""#));
1126 }
1127 #[tokio::test]
1128 async fn admin_settings_save_and_echo_the_max_sessions_ceiling() {
1129 let Setup { router, store, .. } = setup().await;
1130 let ada = im_core::accounts::user_by_email(&store, "ada@example.com")
1131 .await
1132 .unwrap()
1133 .unwrap();
1134 let session = im_core::sessions::create_session(&store, &ada.id, &Default::default())
1135 .await
1136 .unwrap();
1137 let cookie = format!("{SESSION_COOKIE}={}", session.expose());
1138
1139 let (_status, location, _) = post_form(
1140 &router,
1141 "/admin/settings",
1142 "invite_days=30&session_days=7&max_sessions=2&pending_minutes=10&reset_minutes=15&login_attempts_per_hour=20",
1143 Some(&cookie),
1144 )
1145 .await;
1146 assert_eq!(
1147 location.as_deref(),
1148 Some("/admin?section=settings&ok=settings")
1149 );
1150 let panel = get_page(&router, "/admin?section=settings", &cookie).await;
1151 assert!(
1152 panel.contains(r#"name="max_sessions" min="1" value="2""#),
1153 "the saved ceiling must echo back into the form: {panel}"
1154 );
1155 }
1156
1157 #[tokio::test]
1158 async fn family_register_stamps_the_authenticated_client_on_its_row() {
1159 let Setup {
1160 router,
1161 client_id,
1162 secret,
1163 store,
1164 ..
1165 } = setup().await;
1166
1167 // First register: the row is appended with the caller's stamp.
1168 let (status, _) = post_register(
1169 &router,
1170 Some(basic(&client_id, &secret)),
1171 serde_json::json!({"key": "drive", "name": "Drive", "url": "https://drive.dizey.sh"}),
1172 )
1173 .await;
1174 assert_eq!(status, StatusCode::OK);
1175 let rows = im_core::services::list(&store).await.unwrap();
1176 let row = rows.iter().find(|s| s.key == "drive").unwrap();
1177 assert_eq!(row.client_id.as_deref(), Some(client_id.as_str()));
1178
1179 // The next boot's register refreshes the row and keeps the stamp
1180 // current — one row, still the caller's.
1181 let (status, _) = post_register(
1182 &router,
1183 Some(basic(&client_id, &secret)),
1184 serde_json::json!({"key": "drive", "name": "Drive", "url": "https://drive2.dizey.sh"}),
1185 )
1186 .await;
1187 assert_eq!(status, StatusCode::OK);
1188 let rows = im_core::services::list(&store).await.unwrap();
1189 assert_eq!(rows.iter().filter(|s| s.key == "drive").count(), 1);
1190 let row = rows.iter().find(|s| s.key == "drive").unwrap();
1191 assert_eq!(row.url, "https://drive2.dizey.sh");
1192 assert_eq!(row.client_id.as_deref(), Some(client_id.as_str()));
1193 }
1194
1195 #[tokio::test]
1196 async fn the_landing_lists_connected_apps_and_an_empty_note_without_them() {
1197 let Setup {
1198 router,
1199 client_id,
1200 store,
1201 ..
1202 } = setup().await;
1203 let ben = im_core::accounts::user_by_email(&store, "ben@example.com")
1204 .await
1205 .unwrap()
1206 .unwrap();
1207 let session = im_core::sessions::create_session(&store, &ben.id, &Default::default())
1208 .await
1209 .unwrap();
1210 let cookie = format!("{SESSION_COOKIE}={}", session.expose());
1211
1212 // No grants yet: the section is its empty note, with no rows at all.
1213 let page = get_page(&router, "/?section=apps", &cookie).await;
1214 assert!(page.contains("Connected apps"), "the title is missing");
1215 assert!(
1216 page.contains("No apps are connected yet."),
1217 "the empty note is missing: {page}"
1218 );
1219
1220 // A minted app session is a grant: the seeded app shows under Ben's
1221 // landing with its name, its client id and its active count.
1222 im_core::oidc::issue_app_session(
1223 &store,
1224 &ben.id,
1225 &ClientId::from(client_id.clone()),
1226 &im_core::accounts::hash_token(session.expose()),
1227 )
1228 .await
1229 .unwrap();
1230 let page = get_page(&router, "/?section=apps", &cookie).await;
1231 assert!(page.contains("tasks"), "the app's name is missing: {page}");
1232 assert!(
1233 page.contains(&client_id),
1234 "the client id is missing: {page}"
1235 );
1236 assert!(
1237 !page.contains("No apps are connected yet."),
1238 "the empty note must yield once a grant exists"
1239 );
1240 }
1241
1242 /// Percent-decodes a query value back into text — the tests read the
1243 /// once-shown confirmation links out of the redirect's Location.
1244 fn pct_decode(raw: &str) -> String {
1245 let bytes = raw.as_bytes();
1246 let mut out = Vec::new();
1247 let mut i = 0;
1248 while i < bytes.len() {
1249 if bytes[i] == b'%' {
1250 out.push(
1251 u8::from_str_radix(std::str::from_utf8(&bytes[i + 1..i + 3]).unwrap(), 16)
1252 .unwrap(),
1253 );
1254 i += 3;
1255 } else {
1256 out.push(bytes[i]);
1257 i += 1;
1258 }
1259 }
1260 String::from_utf8(out).unwrap()
1261 }
1262
1263 #[tokio::test]
1264 async fn admin_email_edit_applies_directly_and_refuses_taken_address() {
1265 let Setup {
1266 router, store, ..
1267 } = setup().await;
1268 let ada = im_core::accounts::user_by_email(&store, "ada@example.com")
1269 .await
1270 .unwrap()
1271 .unwrap();
1272 let ben = im_core::accounts::user_by_email(&store, "ben@example.com")
1273 .await
1274 .unwrap()
1275 .unwrap();
1276 let session = im_core::sessions::create_session(&store, &ada.id, &Default::default())
1277 .await
1278 .unwrap();
1279 let cookie = format!("{SESSION_COOKIE}={}", session.expose());
1280
1281 // A non-admin's edit is sent to the front door and writes nothing.
1282 let ben_session = im_core::sessions::create_session(&store, &ben.id, &Default::default())
1283 .await
1284 .unwrap();
1285 let (status, location, _) = post_form(
1286 &router,
1287 "/admin/user_email",
1288 &format!("user={}&email=changed%40example.com", ben.id),
1289 Some(&format!("{SESSION_COOKIE}={}", ben_session.expose())),
1290 )
1291 .await;
1292 assert_eq!(status, StatusCode::SEE_OTHER);
1293 assert_eq!(location.as_deref(), Some("/"));
1294 assert!(
1295 im_core::accounts::user_by_email(&store, "changed@example.com")
1296 .await
1297 .unwrap()
1298 .is_none()
1299 );
1300
1301 // The admin's edit lands back on the section with its ok code, the
1302 // address normalized the way the login path reads it.
1303 let (status, location, _) = post_form(
1304 &router,
1305 "/admin/user_email",
1306 &format!("user={}&email=%20Ben.New%40Example.COM%20", ben.id),
1307 Some(&cookie),
1308 )
1309 .await;
1310 assert_eq!(status, StatusCode::SEE_OTHER);
1311 assert_eq!(
1312 location.as_deref(),
1313 Some("/admin?section=users&ok=email_changed")
1314 );
1315 let moved = im_core::accounts::user_by_email(&store, "ben.new@example.com")
1316 .await
1317 .unwrap()
1318 .unwrap();
1319 assert_eq!(moved.id, ben.id);
1320 assert_eq!(moved.email, "ben.new@example.com");
1321 assert!(
1322 im_core::accounts::user_by_email(&store, "ben@example.com")
1323 .await
1324 .unwrap()
1325 .is_none()
1326 );
1327 let panel = get_page(&router, "/admin?section=users", &cookie).await;
1328 assert!(panel.contains("ben.new@example.com"), "{panel}");
1329
1330 // Another account's address is refused by name; the account's
1331 // address stays.
1332 let (status, location, _) = post_form(
1333 &router,
1334 "/admin/user_email",
1335 &format!("user={}&email=ada%40example.com", ben.id),
1336 Some(&cookie),
1337 )
1338 .await;
1339 assert_eq!(status, StatusCode::SEE_OTHER);
1340 assert_eq!(
1341 location.as_deref(),
1342 Some("/admin?section=users&error=email_taken")
1343 );
1344 assert_eq!(
1345 im_core::accounts::user_by_email(&store, "ben.new@example.com")
1346 .await
1347 .unwrap()
1348 .unwrap()
1349 .id,
1350 ben.id
1351 );
1352 }
1353
1354 #[tokio::test]
1355 async fn self_served_email_change_applies_after_both_addresses_confirm() {
1356 let Setup {
1357 router, store, ..
1358 } = setup().await;
1359 let ben = im_core::accounts::user_by_email(&store, "ben@example.com")
1360 .await
1361 .unwrap()
1362 .unwrap();
1363 let session = im_core::sessions::create_session(&store, &ben.id, &Default::default())
1364 .await
1365 .unwrap();
1366 let cookie = format!("{SESSION_COOKIE}={}", session.expose());
1367
1368 // The ask: with no sender configured, the two confirmation links
1369 // come back on the redirect once — the crate's unmailed idiom.
1370 let (status, location, _) = post_form(
1371 &router,
1372 "/email_change",
1373 "email=ben2%40example.com",
1374 Some(&cookie),
1375 )
1376 .await;
1377 assert_eq!(status, StatusCode::SEE_OTHER);
1378 let location = location.expect("a redirect carrying the once-shown links");
1379 assert!(
1380 location.contains("/?section=password&ok=email_change_asked"),
1381 "{location}"
1382 );
1383
1384 // The address card answers on the password section only; the profile
1385 // carries no address-mutation form anymore.
1386 let profile_page = get_page(&router, "/?section=profile", &cookie).await;
1387 assert!(
1388 !profile_page.contains(r#"action="/email_change""#),
1389 "{profile_page}"
1390 );
1391 let password_page = get_page(&router, "/?section=password", &cookie).await;
1392 assert!(
1393 password_page.contains(r#"action="/email_change""#),
1394 "{password_page}"
1395 );
1396 let encoded = location
1397 .split("links=")
1398 .nth(1)
1399 .expect("the unmailed pair shows once");
1400 let tokens: Vec<String> = pct_decode(encoded)
1401 .split(' ')
1402 .map(|link| {
1403 link.rsplit('/')
1404 .next()
1405 .expect("each link ends in its token")
1406 .to_string()
1407 })
1408 .collect();
1409 assert_eq!(tokens.len(), 2);
1410
1411 // The card names the address being gained, and the POST under it is
1412 // the only door.
1413 let card = get_page(&router, &format!("/email/{}", tokens[1]), "").await;
1414 assert!(card.contains("ben2@example.com"), "{card}");
1415 assert!(card.contains(r#"action="/email""#), "{card}");
1416
1417 // The first click marks its side; the address does not move.
1418 let (status, location, _) = post_form(
1419 &router,
1420 "/email",
1421 &format!("token={}", tokens[1]),
1422 Some(&cookie),
1423 )
1424 .await;
1425 assert_eq!(status, StatusCode::SEE_OTHER);
1426 assert_eq!(
1427 location.as_deref(),
1428 Some("/?section=profile&ok=email_half_confirmed")
1429 );
1430 assert!(
1431 im_core::accounts::user_by_email(&store, "ben@example.com")
1432 .await
1433 .unwrap()
1434 .is_some()
1435 );
1436
1437 // The second mailbox's agreement applies the change.
1438 let (status, location, _) = post_form(
1439 &router,
1440 "/email",
1441 &format!("token={}", tokens[0]),
1442 Some(&cookie),
1443 )
1444 .await;
1445 assert_eq!(status, StatusCode::SEE_OTHER);
1446 assert_eq!(
1447 location.as_deref(),
1448 Some("/?section=profile&ok=email_changed")
1449 );
1450 let moved = im_core::accounts::user_by_email(&store, "ben2@example.com")
1451 .await
1452 .unwrap()
1453 .unwrap();
1454 assert_eq!(moved.id, ben.id);
1455 assert!(
1456 im_core::accounts::user_by_email(&store, "ben@example.com")
1457 .await
1458 .unwrap()
1459 .is_none()
1460 );
1461
1462 // Spent whole: either link answers dead now.
1463 let (status, location, _) = post_form(
1464 &router,
1465 "/email",
1466 &format!("token={}", tokens[0]),
1467 Some(&cookie),
1468 )
1469 .await;
1470 assert_eq!(status, StatusCode::SEE_OTHER);
1471 assert_eq!(
1472 location.as_deref(),
1473 Some("/login?error=email_change_invalid")
1474 );
1475 }
1476
1477 #[tokio::test]
1478 async fn timezone_rides_the_directory_and_the_live_frame() {
1479 let Setup {
1480 router,
1481 client_id,
1482 secret,
1483 store,
1484 live,
1485 } = setup().await;
1486 let ada = im_core::accounts::user_by_email(&store, "ada@example.com")
1487 .await
1488 .unwrap()
1489 .unwrap();
1490 let session = im_core::sessions::create_session(&store, &ada.id, &Default::default())
1491 .await
1492 .unwrap();
1493 let cookie = format!("{SESSION_COOKIE}={}", session.expose());
1494
1495 // The entry carries the family default before anyone touches it.
1496 let (status, body) = get(&router, Some(basic(&client_id, &secret))).await;
1497 assert_eq!(status, StatusCode::OK);
1498 let roster = serde_json::from_str::<serde_json::Value>(&body).unwrap();
1499 assert_eq!(roster[0]["timezone"], "UTC+03:00");
1500
1501 // Saving preferences with a new timezone refuses a value outside
1502 // the select's list, and announces a real change as a profile
1503 // frame — the same ride a name or photo change takes.
1504 let mut rx = live.subscribe();
1505 let (status, location, _) = post_form(
1506 &router,
1507 "/preferences",
1508 "theme=light&ui=instrument&language=en&timezone=UTC-05:00",
1509 Some(&cookie),
1510 )
1511 .await;
1512 assert_eq!(status, StatusCode::SEE_OTHER);
1513 assert_eq!(
1514 location.as_deref(),
1515 Some("/?section=preferences&ok=preferences")
1516 );
1517 match rx.try_recv().unwrap() {
1518 server::LiveEvent::Profile(member) => {
1519 assert_eq!(member.timezone, "UTC-05:00");
1520 }
1521 other => panic!("a profile change announces the row, got {other:?}"),
1522 }
1523
1524 // And the roster reads the stored zone back.
1525 let (_, body) = get(&router, Some(basic(&client_id, &secret))).await;
1526 let roster = serde_json::from_str::<serde_json::Value>(&body).unwrap();
1527 let ada_entry = roster
1528 .as_array()
1529 .unwrap()
1530 .iter()
1531 .find(|member| member["email"] == "ada@example.com")
1532 .unwrap();
1533 assert_eq!(ada_entry["timezone"], "UTC-05:00");
1534
1535 // A value the select never offers is refused whole.
1536 let (status, location, _) = post_form(
1537 &router,
1538 "/preferences",
1539 "theme=light&ui=instrument&language=en&timezone=Mars/Olympus",
1540 Some(&cookie),
1541 )
1542 .await;
1543 assert_eq!(status, StatusCode::SEE_OTHER);
1544 assert_eq!(
1545 location.as_deref(),
1546 Some("/?section=preferences&error=bad_zone")
1547 );
1548 let reloaded = im_core::accounts::user_by_id(&store, &ada.id)
1549 .await
1550 .unwrap()
1551 .unwrap();
1552 assert_eq!(reloaded.timezone, "UTC-05:00", "nothing half-written");
1553 }
1554
1555 /// The eviction rides the roster stream too: a revoke announces the
1556 /// subject whose sessions died, and a disable follows with a Profile
1557 /// frame whose `disabled` flag is set — the two cues a sibling needs
1558 /// to send that subject's tabs home and drop them from its copy.
1559 #[tokio::test]
1560 async fn a_revoke_and_a_disable_ride_the_directory_stream() {
1561 /// The next body frame off the stream, as text. Bounded, so a
1562 /// regression fails loudly instead of hanging the suite.
1563 async fn next_chunk(
1564 stream: &mut std::pin::Pin<Box<topcoat::router::BodyDataStream>>,
1565 ) -> String {
1566 use futures_util::StreamExt as _;
1567 let chunk = tokio::time::timeout(
1568 std::time::Duration::from_secs(20),
1569 stream.as_mut().next(),
1570 )
1571 .await
1572 .expect("a frame arrives in time")
1573 .expect("stream stays open")
1574 .expect("frames succeed");
1575 String::from_utf8_lossy(&chunk).into_owned()
1576 }
1577
1578 let Setup {
1579 router,
1580 client_id,
1581 secret,
1582 store,
1583 ..
1584 } = setup().await;
1585 let ada = im_core::accounts::user_by_email(&store, "ada@example.com")
1586 .await
1587 .unwrap()
1588 .unwrap();
1589 let ben = im_core::accounts::user_by_email(&store, "ben@example.com")
1590 .await
1591 .unwrap()
1592 .unwrap();
1593 let ada_session =
1594 im_core::sessions::create_session(&store, &ada.id, &Default::default())
1595 .await
1596 .unwrap();
1597
1598 // Open the roster stream as an app would, past the reconnection hint.
1599 let response = router
1600 .handle(
1601 http::Request::builder()
1602 .uri("/directory/live")
1603 .header(header::AUTHORIZATION, basic(&client_id, &secret))
1604 .body(Body::empty())
1605 .unwrap(),
1606 )
1607 .await;
1608 let (parts, body) = response.into_parts();
1609 assert_eq!(parts.status, StatusCode::OK);
1610 let mut stream = Box::pin(body.into_data_stream());
1611 let mut wire = String::new();
1612 while !wire.contains("retry: 5000") {
1613 wire.push_str(&next_chunk(&mut stream).await);
1614 }
1615
1616 // Revoke ben everywhere: the roster names the subject, nothing more.
1617 let admin_cookie = format!("{SESSION_COOKIE}={}", ada_session.expose());
1618 let (status, location, _) = post_form(
1619 &router,
1620 "/admin/revoke",
1621 &format!("user={}", ben.id),
1622 Some(&admin_cookie),
1623 )
1624 .await;
1625 assert_eq!(status, StatusCode::SEE_OTHER);
1626 assert_eq!(location.as_deref(), Some("/admin?section=users&ok=revoked"));
1627 wire.clear();
1628 while !wire.contains("event: revoked") {
1629 wire.push_str(&next_chunk(&mut stream).await);
1630 }
1631 assert!(wire.contains(&format!("\"sub\":\"{}\"", ben.id)));
1632
1633 // Disable ben: the revoked cue again, then the row itself with the
1634 // flag set — and the roster no longer lists them.
1635 let (status, _, _) = post_form(
1636 &router,
1637 "/admin/disable",
1638 &format!("user={}", ben.id),
1639 Some(&admin_cookie),
1640 )
1641 .await;
1642 assert_eq!(status, StatusCode::SEE_OTHER);
1643 wire.clear();
1644 while !wire.contains("\"disabled\":true") {
1645 wire.push_str(&next_chunk(&mut stream).await);
1646 }
1647 assert!(wire.contains("event: profile"), "{wire}");
1648
1649 let (status, body) = get(&router, Some(basic(&client_id, &secret))).await;
1650 assert_eq!(status, StatusCode::OK);
1651 let roster: serde_json::Value = serde_json::from_str(&body).unwrap();
1652 assert!(
1653 !roster
1654 .as_array()
1655 .unwrap()
1656 .iter()
1657 .any(|member| member["sub"] == ben.id.to_string()),
1658 "the disabled member leaves the roster"
1659 );
1660 }
1661}