forge
Explore
Log in

Don't you dare go Hollow

im: live session-revocation logout

Browse files at this commit

08994cc7ec0b5209abc4be71e9b02cc4ed00df3fAhmet Kaan GümüşParent: df62108
- LiveEvent::Revoked { user_id, session_hash } broadcast from EVERY write
  path (admin revoke/disable/delete, self revoke, password change
  revoke-except, reset redeem, sign-out-everywhere)
- /live keeps connect-time identity; targeted 'revoked' SSE event only to
  the killed session's connections; password change spares the asking tab
- /directory/live emits revoked {"sub"}; DirectoryMember gains disabled
- client: revoked event or /api/me 401 on SSE error -> hard navigate to /
- new GET /api/me (204/401)
- fix: admin disable never wrote the disabled flag (regression at HEAD)
crates/im-core/src/sessions.rsmodified+8 -6
@@ -298,12 +298,15 @@ pub async fn revoke_user_sessions(store: &Store, user: &UserId) -> Result<u64> {
298 298
299 /// A password change's revoke: every session dies except the one holding the299 /// A password change's revoke: every session dies except the one holding the
300 /// form — the browser that just proved the old password stays signed in, and300 /// form — the browser that just proved the old password stays signed in, and
301-/// every other device (and every app token born of them) is out.301+/// every other device (and every app token born of them) is out. The dead
302+/// sessions' token hashes come back, so the caller can address the eviction
303+/// news: a live connection only leaves when the hash it holds is among
304+/// these, and the asking browser's never is.
302 pub async fn revoke_user_sessions_except(305 pub async fn revoke_user_sessions_except(
303 store: &Store,306 store: &Store,
304 user: &UserId,307 user: &UserId,
305 keep_token: &str,308 keep_token: &str,
306-) -> Result<u64> {309+) -> Result<Vec<String>> {
307 let keep = hash_token(keep_token);310 let keep = hash_token(keep_token);
308 let hashes = {311 let hashes = {
309 let conn = store.conn.lock().await;312 let conn = store.conn.lock().await;
@@ -321,7 +324,6 @@ pub async fn revoke_user_sessions_except(
321 }324 }
322 hashes325 hashes
323 };326 };
324- let count = hashes.len() as u64;
325 for hash in &hashes {327 for hash in &hashes {
326 revoke_session_hash(store, hash).await?;328 revoke_session_hash(store, hash).await?;
327 }329 }
@@ -343,7 +345,7 @@ pub async fn revoke_user_sessions_except(
343 )345 )
344 .await346 .await
345 .map_err(backend)?;347 .map_err(backend)?;
346- Ok(count)348+ Ok(hashes)
347 }349 }
348 350
349 #[cfg(test)]351 #[cfg(test)]
@@ -400,10 +402,10 @@ mod tests {
400 .await402 .await
401 .unwrap();403 .unwrap();
402 404
403- let count = revoke_user_sessions_except(&store, &user_id, mine.expose())405+ let revoked = revoke_user_sessions_except(&store, &user_id, mine.expose())
404 .await406 .await
405 .unwrap();407 .unwrap();
406- assert_eq!(count, 1);408+ assert_eq!(revoked, vec![hash_token(other.expose())]);
407 assert!(409 assert!(
408 resolve_session(&store, mine.expose())410 resolve_session(&store, mine.expose())
409 .await411 .await
crates/im-web/src/admin.rsmodified+12 -0
@@ -1677,6 +1677,9 @@ async fn delete(cx: &Cx, Form(input): Form<UserAction>) -> Result<Response> {
1677 .await?1677 .await?
1678 .map(|u| u.email);1678 .map(|u| u.email);
1679 accounts::delete_user(store, &user_id).await?;1679 accounts::delete_user(store, &user_id).await?;
1680+ // The person is gone; their sessions went with them, and their tabs
1681+ // hear it here.
1682+ server::note_revoked(cx, user_id.as_str(), None).await;
1680 server::log_event(cx, "user_deleted", Some(&me.email), email.as_deref()).await;1683 server::log_event(cx, "user_deleted", Some(&me.email), email.as_deref()).await;
1681 back(cx, "users", "&ok=deleted")1684 back(cx, "users", "&ok=deleted")
1682 }1685 }
@@ -1694,6 +1697,8 @@ async fn revoke(cx: &Cx, Form(input): Form<UserAction>) -> Result<Response> {
1694 let store = &app(cx).store;1697 let store = &app(cx).store;
1695 let user_id = UserId::from(input.user);1698 let user_id = UserId::from(input.user);
1696 let sessions = im_core::sessions::revoke_user_sessions(store, &user_id).await?;1699 let sessions = im_core::sessions::revoke_user_sessions(store, &user_id).await?;
1700+ // Every session of theirs died; their open tabs each hear it and leave.
1701+ server::note_revoked(cx, user_id.as_str(), None).await;
1697 let email = accounts::user_by_id(store, &user_id)1702 let email = accounts::user_by_id(store, &user_id)
1698 .await?1703 .await?
1699 .map(|u| u.email);1704 .map(|u| u.email);
@@ -1728,6 +1733,7 @@ async fn session_revoke(cx: &Cx, Form(input): Form<SessionRevokeForm>) -> Result
1728 if !im_core::sessions::revoke_owned_session(&app(cx).store, &user_id, &input.session).await? {1733 if !im_core::sessions::revoke_owned_session(&app(cx).store, &user_id, &input.session).await? {
1729 return back(cx, "users", "&error=session_unknown");1734 return back(cx, "users", "&error=session_unknown");
1730 }1735 }
1736+ server::note_revoked(cx, user_id.as_str(), Some(&input.session)).await;
1731 server::log_event(cx, "session_revoked", Some(&me.email), Some(&input.user)).await;1737 server::log_event(cx, "session_revoked", Some(&me.email), Some(&input.user)).await;
1732 back(cx, "users", "&ok=session_revoked")1738 back(cx, "users", "&ok=session_revoked")
1733 }1739 }
@@ -1749,9 +1755,15 @@ async fn set_disabled(cx: &Cx, input: UserAction, disabled: bool) -> Result<Resp
1749 };1755 };
1750 let store = &app(cx).store;1756 let store = &app(cx).store;
1751 let user_id = UserId::from(input.user);1757 let user_id = UserId::from(input.user);
1758+ // The flag moves first: the announcements below — the eviction news and
1759+ // the member's row — must describe the account as it now stands.
1760+ accounts::set_disabled(store, &user_id, disabled).await?;
1752 if disabled {1761 if disabled {
1753 // A disabled account keeps no sessions either.1762 // A disabled account keeps no sessions either.
1754 im_core::sessions::revoke_user_sessions(store, &user_id).await?;1763 im_core::sessions::revoke_user_sessions(store, &user_id).await?;
1764+ // The disable ends every session; the disabled flag itself rides the
1765+ // Profile announcement right below.
1766+ server::note_revoked(cx, user_id.as_str(), None).await;
1755 }1767 }
1756 // Announced whether the flag moved either way: the disable drops the1768 // Announced whether the flag moved either way: the disable drops the
1757 // member from the next roster read, the enable restores it.1769 // member from the next roster read, the enable restores it.
crates/im-web/src/auth.rsmodified+44 -4
@@ -8,6 +8,7 @@ use serde::Deserialize;
8 use topcoat::Result;8 use topcoat::Result;
9 use topcoat::context::Cx;9 use topcoat::context::Cx;
10 use topcoat::router::content::Form;10 use topcoat::router::content::Form;
11+use topcoat::router::response::IntoResponse as _;
11 use topcoat::router::{HeaderName, StatusCode, header, route};12 use topcoat::router::{HeaderName, StatusCode, header, route};
12 13
13 use crate::server::{self, PendingPurpose};14 use crate::server::{self, PendingPurpose};
@@ -300,11 +301,24 @@ async fn logout(cx: &Cx) -> Redirect {
300 /// tidied. Where the browser goes next is each route's own business.301 /// tidied. Where the browser goes next is each route's own business.
301 async fn sign_out_everywhere(cx: &Cx) -> Result<()> {302 async fn sign_out_everywhere(cx: &Cx) -> Result<()> {
302 if let Some(token) = server::presented_session(cx) {303 if let Some(token) = server::presented_session(cx) {
303- let email = im_core::sessions::resolve_session(&server::app(cx).store, &token)304+ let user = im_core::sessions::resolve_session(&server::app(cx).store, &token)
304 .await?305 .await?
305- .map(|u| u.email);306+ .map(|u| (u.id, u.email));
306 im_core::sessions::revoke_session(&server::app(cx).store, &token).await?;307 im_core::sessions::revoke_session(&server::app(cx).store, &token).await?;
307- server::log_event(cx, "logout", email.as_deref(), None).await;308+ // The eviction news is addressed to the dying session's own
309+ // connection, so its tab leaves at once instead of at the next
310+ // full refetch.
311+ if let Some((id, _)) = &user {
312+ server::note_revoked(cx, id.as_str(), Some(&im_core::accounts::hash_token(&token)))
313+ .await;
314+ }
315+ server::log_event(
316+ cx,
317+ "logout",
318+ user.as_ref().map(|(_, email)| email.as_str()),
319+ None,
320+ )
321+ .await;
308 }322 }
309 server::clear_session_cookie(cx);323 server::clear_session_cookie(cx);
310 Ok(())324 Ok(())
@@ -326,6 +340,19 @@ async fn logout_return(cx: &Cx) -> Redirect {
326 see(logout_target(back.as_deref(), &services))340 see(logout_target(back.as_deref(), &services))
327 }341 }
328 342
343+/// The signed-in probe behind the live channel's error path: a tab whose
344+/// stream died asks here whether its session still stands, and the bare
345+/// status — no HTML, no redirect — is the whole answer. 204 signed in,
346+/// 401 not.
347+#[route(GET "/api/me")]
348+async fn me_probe(cx: &Cx) -> topcoat::Result<topcoat::router::response::Response> {
349+ if server::current_user(cx).await.is_some() {
350+ (StatusCode::NO_CONTENT, "").into_response(cx)
351+ } else {
352+ (StatusCode::UNAUTHORIZED, "").into_response(cx)
353+ }
354+}
355+
329 #[derive(Deserialize)]356 #[derive(Deserialize)]
330 pub struct ForgotForm {357 pub struct ForgotForm {
331 email: String,358 email: String,
@@ -374,6 +401,9 @@ async fn reset(cx: &Cx, Form(input): Form<ResetForm>) -> Redirect {
374 let store = &server::app(cx).store;401 let store = &server::app(cx).store;
375 match accounts::redeem_reset(store, &input.token, &input.password).await {402 match accounts::redeem_reset(store, &input.token, &input.password).await {
376 Ok(user) => {403 Ok(user) => {
404+ // redeem_reset swept every session of theirs inside the core;
405+ // their tabs hear the eviction here.
406+ server::note_revoked(cx, user.id.as_str(), None).await;
377 server::log_event(cx, "password_reset", Some(&user.email), None).await;407 server::log_event(cx, "password_reset", Some(&user.email), None).await;
378 see("/login?ok=reset".to_string())408 see("/login?ok=reset".to_string())
379 }409 }
@@ -522,6 +552,9 @@ async fn revoke_session(cx: &Cx, Form(input): Form<SessionRevokeForm>) -> Redire
522 && im_core::accounts::hash_token(&presented) == input.session552 && im_core::accounts::hash_token(&presented) == input.session
523 {553 {
524 im_core::sessions::revoke_session(store, &presented).await?;554 im_core::sessions::revoke_session(store, &presented).await?;
555+ // The news is addressed to this very session; this tab hears its
556+ // own eviction and goes home like any other.
557+ server::note_revoked(cx, user.id.as_str(), Some(&input.session)).await;
525 server::clear_session_cookie(cx);558 server::clear_session_cookie(cx);
526 return see("/".to_string());559 return see("/".to_string());
527 }560 }
@@ -535,6 +568,7 @@ async fn revoke_session(cx: &Cx, Form(input): Form<SessionRevokeForm>) -> Redire
535 if !im_core::sessions::revoke_owned_session(store, &user.id, &input.session).await? {568 if !im_core::sessions::revoke_owned_session(store, &user.id, &input.session).await? {
536 return see("/?section=sessions&error=session_unknown".to_string());569 return see("/?section=sessions&error=session_unknown".to_string());
537 }570 }
571+ server::note_revoked(cx, user.id.as_str(), Some(&input.session)).await;
538 server::log_event(cx, "session_revoked", Some(&user.email), ip.as_deref()).await;572 server::log_event(cx, "session_revoked", Some(&user.email), ip.as_deref()).await;
539 see("/?section=sessions&ok=session_revoked".to_string())573 see("/?section=sessions&ok=session_revoked".to_string())
540 }574 }
@@ -623,7 +657,13 @@ async fn password(cx: &Cx, Form(input): Form<PasswordForm>) -> Redirect {
623 Err(e) => return Err(topcoat::Error::from(std::io::Error::other(e.to_string()))),657 Err(e) => return Err(topcoat::Error::from(std::io::Error::other(e.to_string()))),
624 }658 }
625 if let Some(token) = server::presented_session(cx) {659 if let Some(token) = server::presented_session(cx) {
626- im_core::sessions::revoke_user_sessions_except(store, &me.id, &token).await?;660+ let revoked = im_core::sessions::revoke_user_sessions_except(store, &me.id, &token)
661+ .await?;
662+ // Each dead session's own tab hears its eviction; the asking
663+ // browser's hash is never among them, so this tab stays.
664+ for hash in &revoked {
665+ server::note_revoked(cx, me.id.as_str(), Some(hash)).await;
666+ }
627 }667 }
628 server::log_event(cx, "password_changed", Some(&me.email), None).await;668 server::log_event(cx, "password_changed", Some(&me.email), None).await;
629 see("/?section=password&ok=password".to_string())669 see("/?section=password&ok=password".to_string())
crates/im-web/src/directory.rsmodified+127 -1
@@ -34,6 +34,11 @@ pub struct DirectoryMember {
34 /// side only serializes — the field is always written — so the serde34 /// side only serializes — the field is always written — so the serde
35 /// default lives on the SDK's reading half.35 /// default lives on the SDK's reading half.
36 pub timezone: String,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,
37 }42 }
38 43
39 impl DirectoryMember {44 impl DirectoryMember {
@@ -46,6 +51,7 @@ impl DirectoryMember {
46 admin: user.admin,51 admin: user.admin,
47 photo_version: user.photo_version,52 photo_version: user.photo_version,
48 timezone: user.timezone.clone(),53 timezone: user.timezone.clone(),
54+ disabled: user.disabled,
49 }55 }
50 }56 }
51 }57 }
@@ -80,7 +86,8 @@ async fn directory(cx: &Cx) -> topcoat::Result<topcoat::router::response::Respon
80 /// frame's row never runs ahead of `/directory` itself. A lagged reader86 /// frame's row never runs ahead of `/directory` itself. A lagged reader
81 /// gets no frame — which rows dropped is unknowable — and heals the gap87 /// gets no frame — which rows dropped is unknowable — and heals the gap
82 /// the way any disconnect does: wait out the retry hint, re-list the88 /// the way any disconnect does: wait out the retry hint, re-list the
83-/// whole roster, resume.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.
84 #[route(GET "/directory/live")]91 #[route(GET "/directory/live")]
85 async fn directory_live(cx: &Cx) -> topcoat::Result<topcoat::router::response::Response> {92 async fn directory_live(cx: &Cx) -> topcoat::Result<topcoat::router::response::Response> {
86 if server::app_client(cx).await.is_none() {93 if server::app_client(cx).await.is_none() {
@@ -144,6 +151,18 @@ async fn directory_live(cx: &Cx) -> topcoat::Result<topcoat::router::response::R
144 continue;151 continue;
145 }152 }
146 Ok(Some(Ok(server::LiveEvent::Profile(member)))) => member,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+ }
147 };166 };
148 // A member that will not serialize cannot happen — plain167 // A member that will not serialize cannot happen — plain
149 // fields all the way down — but a stream cannot panic on168 // fields all the way down — but a stream cannot panic on
@@ -1532,4 +1551,111 @@ mod tests {
1532 .unwrap();1551 .unwrap();
1533 assert_eq!(reloaded.timezone, "UTC-05:00", "nothing half-written");1552 assert_eq!(reloaded.timezone, "UTC-05:00", "nothing half-written");
1534 }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+ }
1535 }1661 }
crates/im-web/src/layout.rsmodified+13 -1
@@ -462,7 +462,9 @@ pub async fn soft_nav_script(cx: &Cx) -> Result<impl View + '_> {
462 /// moved; the page re-fetches itself through the ordinary route — where the462 /// moved; the page re-fetches itself through the ordinary route — where the
463 /// ordinary gate answers — and morphs with fields and scroll intact. A463 /// ordinary gate answers — and morphs with fields and scroll intact. A
464 /// focused field freezes the refresh mid-typing. Mounted only for a signed-in464 /// focused field freezes the refresh mid-typing. Mounted only for a signed-in
465-/// viewer, so auth screens never reconnect against a 401.465+/// viewer, so auth screens never reconnect against a 401. A `revoked`
466+/// frame — the eviction news, addressed — or a probe answering 401 sends
467+/// the tab home instead of re-reading.
466 pub async fn live_script(cx: &Cx) -> Result<impl View + '_> {468 pub async fn live_script(cx: &Cx) -> Result<impl View + '_> {
467 use topcoat::view::Unescaped;469 use topcoat::view::Unescaped;
468 const JS: &str = r#"(function () {470 const JS: &str = r#"(function () {
@@ -476,6 +478,16 @@ pub async fn live_script(cx: &Cx) -> Result<impl View + '_> {
476 try {478 try {
477 var src = new EventSource('/live');479 var src = new EventSource('/live');
478 src.onmessage = function () { schedule(); };480 src.onmessage = function () { schedule(); };
481+ // A sign-out in motion: this tab's own session was revoked — go home.
482+ src.addEventListener('revoked', function () { location.href = '/'; });
483+ // A dropped stream reconnects by itself, but one that keeps dying
484+ // against a revoked session is news: the bare probe says whether the
485+ // session still stands.
486+ src.onerror = function () {
487+ fetch('/api/me').then(function (r) {
488+ if (r.status === 401) { location.href = '/'; }
489+ }).catch(function () {});
490+ };
479 } catch (err) {}491 } catch (err) {}
480 })();"#;492 })();"#;
481 Ok(view! { cx => <script>(Unescaped::new_unchecked(JS))</script> })493 Ok(view! { cx => <script>(Unescaped::new_unchecked(JS))</script> })
crates/im-web/src/live.rsmodified+387 -55
@@ -1,11 +1,12 @@
1 //! The live channel: one long-lived connection per open signed-in tab,1 //! The live channel: one long-lived connection per open signed-in tab,
2 //! carrying the news that something changed — ported from iz's `live.rs`.2 //! carrying the news that something changed — ported from iz's `live.rs`.
3 //!3 //!
4-//! What travels here is a bare tick and nothing else — never a row, never a4+//! What travels here is a bare tick — "the page moved, re-read it" — and one
5-//! name. The client is told only *that* the page moved, and re-fetches it5+//! addressed frame: a `revoked` event whose emptiness is the whole message,
6-//! through the ordinary route, where the ordinary gate answers. Every page6+//! sent only to the connection the eviction names. A revoked tab does not
7-//! behind it needs the same session the stream asked for, so there is no7+//! re-read (its session would refuse it); it goes home. Everything else
8-//! per-topic filtering to get wrong.8+//! stays nameless: the client re-fetches through the ordinary route, where
9+//! the ordinary gate answers.
9 10
10 use std::time::{Duration, Instant};11 use std::time::{Duration, Instant};
11 12
@@ -39,68 +40,96 @@ pub struct Shutdown(pub tokio::sync::watch::Receiver<bool>);
39 #[route(GET "/live")]40 #[route(GET "/live")]
40 async fn live(cx: &Cx) -> topcoat::Result<Response> {41 async fn live(cx: &Cx) -> topcoat::Result<Response> {
41 // Resolved once, here, and never again for the life of this connection.42 // Resolved once, here, and never again for the life of this connection.
42- let Ok(_user) = server::current_user(cx).await.ok_or(()) else {43+ // Both halves stay: the id and the session's token hash are the address
44+ // a `Revoked` announcement is checked against — the eviction news is
45+ // addressed, and this connection reads its own address off it.
46+ let Ok(user) = server::current_user(cx).await.ok_or(()) else {
43 return (StatusCode::UNAUTHORIZED, "").into_response(cx);47 return (StatusCode::UNAUTHORIZED, "").into_response(cx);
44 };48 };
49+ let me = user.id.to_string();
50+ let mine = server::presented_session(cx)
51+ .as_deref()
52+ .map(im_core::accounts::hash_token);
45 let rx = server::app(cx).live.subscribe();53 let rx = server::app(cx).live.subscribe();
46 let stopping = topcoat::context::try_app_context::<Shutdown>(cx).map(|s| s.0.clone());54 let stopping = topcoat::context::try_app_context::<Shutdown>(cx).map(|s| s.0.clone());
47 let deadline = Instant::now() + WINDOW;55 let deadline = Instant::now() + WINDOW;
48 56
49 let events = futures_util::stream::unfold(57 let events = futures_util::stream::unfold(
50- (rx, deadline, stopping),58+ (rx, deadline, stopping, me, mine),
51- |(mut rx, deadline, mut stopping)| async move {59+ |(mut rx, deadline, mut stopping, me, mine)| async move {
52- // Already going down: end, so this connection is not one the60+ loop {
53- // shutdown has to sit and wait out.61+ // Already going down: end, so this connection is not one the
54- if stopping.as_ref().is_some_and(|watch| *watch.borrow()) {62+ // shutdown has to sit and wait out.
55- return None;63+ if stopping.as_ref().is_some_and(|watch| *watch.borrow()) {
56- }64+ return None;
57- let left = deadline.saturating_duration_since(Instant::now());
58- if left.is_zero() {
59- return None;
60- }
61- // Three things end the wait: an announcement, the window
62- // running out, and the server being told to stop. The third
63- // is watched rather than polled, so SIGTERM is felt at once.
64- let heard = tokio::time::timeout(left, async {
65- match stopping.as_mut() {
66- Some(watch) => tokio::select! {
67- _ = watch.changed() => None,
68- got = rx.recv() => Some(got),
69- },
70- None => Some(rx.recv().await),
71 }65 }
72- })66+ let left = deadline.saturating_duration_since(Instant::now());
73- .await;67+ if left.is_zero() {
74- match heard {68+ return None;
75- // The window closed, or the server is stopping. Ending69+ }
76- // the stream is the point: the browser reconnects by70+ // Three things end the wait: an announcement, the window
77- // itself and authenticates again.71+ // running out, and the server being told to stop. The third
78- Err(_) | Ok(None) => return None,72+ // is watched rather than polled, so SIGTERM is felt at once.
79- // The broadcaster is gone, which means the process is73+ let heard = tokio::time::timeout(left, async {
80- // going with it.74+ match stopping.as_mut() {
81- Ok(Some(Err(RecvError::Closed))) => return None,75+ Some(watch) => tokio::select! {
82- // This reader fell behind and announcements were dropped.76+ _ = watch.changed() => None,
83- // Which ones is unknowable, so the tick says "re-read77+ got = rx.recv() => Some(got),
84- // everything" — the client refetches the whole page, so78+ },
85- // a lagged tick and a plain tick are the same frame.79+ None => Some(rx.recv().await),
86- Ok(Some(Err(RecvError::Lagged(_)))) | Ok(Some(Ok(server::LiveEvent::Tick))) => {}80+ }
87- // One member's row changed. The frame names which one —81+ })
88- // im's own client still just re-fetches the page it is82+ .await;
89- // on, so the payload is forward-compatibility for a83+ match heard {
90- // future page that can react to its own subject alone.84+ // The window closed, or the server is stopping. Ending
91- Ok(Some(Ok(server::LiveEvent::Profile(member)))) => {85+ // the stream is the point: the browser reconnects by
92- return Some((86+ // itself and authenticates again.
93- Ok::<_, std::convert::Infallible>(Event::new().data(87+ Err(_) | Ok(None) => return None,
94- serde_json::json!({ "kind": "profile", "sub": member.sub })88+ // The broadcaster is gone, which means the process is
95- .to_string(),89+ // going with it.
96- )),90+ Ok(Some(Err(RecvError::Closed))) => return None,
97- (rx, deadline, stopping),91+ // This reader fell behind and announcements were dropped.
98- ));92+ // Which ones is unknowable, so the tick says "re-read
93+ // everything" — the client refetches the whole page, so
94+ // a lagged tick and a plain tick are the same frame.
95+ Ok(Some(Err(RecvError::Lagged(_))))
96+ | Ok(Some(Ok(server::LiveEvent::Tick))) => break,
97+ // One member's row changed. The frame names which one —
98+ // im's own client still just re-fetches the page it is
99+ // on, so the payload is forward-compatibility for a
100+ // future page that can react to its own subject alone.
101+ Ok(Some(Ok(server::LiveEvent::Profile(member)))) => {
102+ return Some((
103+ Ok::<_, std::convert::Infallible>(Event::new().data(
104+ serde_json::json!({ "kind": "profile", "sub": member.sub })
105+ .to_string(),
106+ )),
107+ (rx, deadline, stopping, me, mine),
108+ ));
109+ }
110+ // A sign-out in motion: every session of the named user,
111+ // or the one named session. Addressed news — this
112+ // connection answers only when it is the one evicted;
113+ // anyone else's news is silence here.
114+ Ok(Some(Ok(server::LiveEvent::Revoked {
115+ user_id,
116+ session_hash,
117+ }))) => {
118+ let evicted = session_hash
119+ .as_deref()
120+ .is_none_or(|hash| mine.as_deref() == Some(hash));
121+ if user_id == me && evicted {
122+ return Some((
123+ Ok(Event::new().event("revoked").data("")),
124+ (rx, deadline, stopping, me, mine),
125+ ));
126+ }
127+ }
99 }128 }
100 }129 }
101 Some((130 Some((
102 Ok::<_, std::convert::Infallible>(Event::new().data("{}")),131 Ok::<_, std::convert::Infallible>(Event::new().data("{}")),
103- (rx, deadline, stopping),132+ (rx, deadline, stopping, me, mine),
104 ))133 ))
105 },134 },
106 );135 );
@@ -109,3 +138,306 @@ async fn live(cx: &Cx) -> topcoat::Result<Response> {
109 .keep_alive(KeepAlive::new())138 .keep_alive(KeepAlive::new())
110 .into_response(cx)139 .into_response(cx)
111 }140 }
141+
142+#[cfg(test)]
143+mod tests {
144+ use std::path::Path;
145+ use std::pin::Pin;
146+ use std::sync::Arc;
147+
148+ use futures_util::StreamExt as _;
149+ use im_core::accounts::{create_invite, create_user_from_invite, hash_token};
150+ use im_core::model::UserId;
151+ use im_core::sessions::{SessionMeta, create_session, resolve_session};
152+ use im_core::store::Store;
153+ use topcoat::cookie::RouterBuilderCookieExt as _;
154+ use topcoat::router::{
155+ Body, BodyDataStream, Router, RouterBuilderDiscoverExt as _, StatusCode, header, to_bytes,
156+ };
157+
158+ use crate::config::Config;
159+ use crate::server::{self, SESSION_COOKIE};
160+
161+ struct Setup {
162+ router: Router,
163+ store: Arc<Store>,
164+ admin_cookie: String,
165+ /// Ben's two sessions, by raw token — each opens its own `/live`
166+ /// connection through its cookie.
167+ ben_tokens: [String; 2],
168+ ben_id: UserId,
169+ }
170+
171+ async fn setup() -> Setup {
172+ let store = Store::open(Path::new(":memory:")).await.unwrap();
173+ let admin_invite = create_invite(&store, "ada@example.com", None, true)
174+ .await
175+ .unwrap();
176+ let admin = create_user_from_invite(&store, admin_invite.expose(), "Ada", "tDLr9!mZQ2xv")
177+ .await
178+ .unwrap();
179+ let ben_invite = create_invite(&store, "ben@example.com", None, false)
180+ .await
181+ .unwrap();
182+ let ben = create_user_from_invite(&store, ben_invite.expose(), "Ben", "tDLr9!mZQ2xv")
183+ .await
184+ .unwrap();
185+ let admin_session = create_session(&store, &admin.id, &SessionMeta::default())
186+ .await
187+ .unwrap();
188+ let ben_a = create_session(&store, &ben.id, &SessionMeta::default())
189+ .await
190+ .unwrap();
191+ let ben_b = create_session(&store, &ben.id, &SessionMeta::default())
192+ .await
193+ .unwrap();
194+ let store = Arc::new(store);
195+ let app = server::App {
196+ store: store.clone(),
197+ config: Config {
198+ database: ":memory:".into(),
199+ listen: "127.0.0.1:7650".parse().unwrap(),
200+ issuer: "http://127.0.0.1:7650".into(),
201+ services: Vec::new(),
202+ },
203+ live: tokio::sync::broadcast::channel(64).0,
204+ };
205+ let router = Router::builder()
206+ .discover()
207+ .cookies()
208+ .app_context(app)
209+ .build();
210+ Setup {
211+ router,
212+ store,
213+ admin_cookie: format!("{SESSION_COOKIE}={}", admin_session.expose()),
214+ ben_tokens: [ben_a.expose().to_string(), ben_b.expose().to_string()],
215+ ben_id: ben.id,
216+ }
217+ }
218+
219+ fn cookie(token: &str) -> String {
220+ format!("{SESSION_COOKIE}={token}")
221+ }
222+
223+ /// A form post through the router, answered as (status, Location).
224+ async fn post_form(
225+ router: &Router,
226+ uri: &str,
227+ body: &str,
228+ cookie: Option<&str>,
229+ ) -> (StatusCode, Option<String>) {
230+ let mut builder = http::Request::builder()
231+ .method(http::Method::POST)
232+ .uri(uri)
233+ .header(header::CONTENT_TYPE, "application/x-www-form-urlencoded");
234+ if let Some(cookie) = cookie {
235+ builder = builder.header(header::COOKIE, cookie);
236+ }
237+ let response = router
238+ .handle(builder.body(Body::from(body.to_string())).unwrap())
239+ .await;
240+ let (parts, body) = response.into_parts();
241+ let location = parts
242+ .headers
243+ .get(header::LOCATION)
244+ .and_then(|v| v.to_str().ok())
245+ .map(str::to_string);
246+ let _ = to_bytes(body, usize::MAX).await.unwrap();
247+ (parts.status, location)
248+ }
249+
250+ /// Opens `/live` as a signed-in tab would and pins the body's data
251+ /// stream. A single SSE frame may straddle two body frames, so callers
252+ /// accumulate text and match on substrings.
253+ async fn open_live(router: &Router, cookie: &str) -> Pin<Box<BodyDataStream>> {
254+ let response = router
255+ .handle(
256+ http::Request::builder()
257+ .uri("/live")
258+ .header(header::COOKIE, cookie)
259+ .body(Body::empty())
260+ .unwrap(),
261+ )
262+ .await;
263+ let (parts, body) = response.into_parts();
264+ assert_eq!(parts.status, StatusCode::OK);
265+ Box::pin(body.into_data_stream())
266+ }
267+
268+ /// The next body frame off the stream, as text. Bounded, so a
269+ /// regression fails loudly instead of hanging the suite — under the
270+ /// single-threaded test runtime a plain park can miss the producer's
271+ /// wakeup entirely.
272+ async fn next_chunk(stream: &mut Pin<Box<BodyDataStream>>) -> String {
273+ let chunk = tokio::time::timeout(std::time::Duration::from_secs(10), stream.as_mut().next())
274+ .await
275+ .expect("a frame arrives in time")
276+ .expect("stream stays open")
277+ .expect("frames succeed");
278+ String::from_utf8_lossy(&chunk).into_owned()
279+ }
280+
281+ /// Reads frames until `needle` appears, returning everything read.
282+ async fn read_until(stream: &mut Pin<Box<BodyDataStream>>, needle: &str) -> String {
283+ let mut wire = String::new();
284+ while !wire.contains(needle) {
285+ wire.push_str(&next_chunk(stream).await);
286+ }
287+ wire
288+ }
289+
290+ /// The heart of the live logout: a revoke reaches the revoked session's
291+ /// own tab as an addressed `revoked` event, while a bystander's tab —
292+ /// on the same bus — hears only the tick the action logs. The
293+ /// bystander's read is the absence proof: frames arrive in send order,
294+ /// and the eviction news is sent before the tick, so a tick with no
295+ /// revoked frame before it means none was addressed here.
296+ #[tokio::test]
297+ async fn a_revoke_reaches_the_revoked_tab_and_not_a_bystanders() {
298+ let setup = setup().await;
299+ let mut ben = open_live(&setup.router, &cookie(&setup.ben_tokens[0])).await;
300+ let mut ada = open_live(&setup.router, &setup.admin_cookie).await;
301+
302+ let (status, _) = post_form(
303+ &setup.router,
304+ "/admin/revoke",
305+ &format!("user={}", setup.ben_id),
306+ Some(&setup.admin_cookie),
307+ )
308+ .await;
309+ assert_eq!(status, StatusCode::SEE_OTHER);
310+
311+ let wire = read_until(&mut ben, "event: revoked").await;
312+ assert!(wire.contains("event: revoked"), "{wire}");
313+
314+ let wire = read_until(&mut ada, "data: {}").await;
315+ assert!(!wire.contains("event: revoked"), "{wire}");
316+ }
317+
318+ /// A per-session revoke is aimed: the named session's tab hears its
319+ /// eviction, the same person's other tab hears only the tick.
320+ #[tokio::test]
321+ async fn a_session_revoke_spares_the_same_users_other_tab() {
322+ let setup = setup().await;
323+ let mut kept = open_live(&setup.router, &cookie(&setup.ben_tokens[0])).await;
324+ let mut killed = open_live(&setup.router, &cookie(&setup.ben_tokens[1])).await;
325+
326+ let (status, _) = post_form(
327+ &setup.router,
328+ "/admin/session_revoke",
329+ &format!(
330+ "user={}&session={}",
331+ setup.ben_id,
332+ hash_token(&setup.ben_tokens[1])
333+ ),
334+ Some(&setup.admin_cookie),
335+ )
336+ .await;
337+ assert_eq!(status, StatusCode::SEE_OTHER);
338+
339+ let wire = read_until(&mut killed, "event: revoked").await;
340+ assert!(wire.contains("event: revoked"), "{wire}");
341+
342+ let wire = read_until(&mut kept, "data: {}").await;
343+ assert!(!wire.contains("event: revoked"), "{wire}");
344+ }
345+
346+ /// The password change's courtesy: the browser that proved the old
347+ /// password keeps its tab — no revoked frame ever names its session —
348+ /// while every other session really dies.
349+ #[tokio::test]
350+ async fn a_password_change_keeps_the_asking_tab_signed_in() {
351+ let setup = setup().await;
352+ let mut asking = open_live(&setup.router, &cookie(&setup.ben_tokens[0])).await;
353+
354+ let (status, location) = post_form(
355+ &setup.router,
356+ "/password",
357+ "current=tDLr9!mZQ2xv&password=n3w-Hard-Pass!9&password_confirm=n3w-Hard-Pass!9",
358+ Some(&cookie(&setup.ben_tokens[0])),
359+ )
360+ .await;
361+ assert_eq!(status, StatusCode::SEE_OTHER);
362+ assert_eq!(location.as_deref(), Some("/?section=password&ok=password"));
363+
364+ let wire = read_until(&mut asking, "data: {}").await;
365+ assert!(!wire.contains("event: revoked"), "{wire}");
366+ assert!(
367+ resolve_session(&setup.store, &setup.ben_tokens[0])
368+ .await
369+ .unwrap()
370+ .is_some(),
371+ "the asking session survives"
372+ );
373+ assert!(
374+ resolve_session(&setup.store, &setup.ben_tokens[1])
375+ .await
376+ .unwrap()
377+ .is_none(),
378+ "the other session dies"
379+ );
380+ }
381+
382+ /// A disable is a sign-out too: the disabled account's tab hears the
383+ /// eviction on the spot. The roster half — the Profile frame carrying
384+ /// `disabled` — is asserted in directory.rs's stream test.
385+ #[tokio::test]
386+ async fn a_disable_reaches_the_disabled_tab() {
387+ let setup = setup().await;
388+ let mut ben = open_live(&setup.router, &cookie(&setup.ben_tokens[0])).await;
389+
390+ let (status, _) = post_form(
391+ &setup.router,
392+ "/admin/disable",
393+ &format!("user={}", setup.ben_id),
394+ Some(&setup.admin_cookie),
395+ )
396+ .await;
397+ assert_eq!(status, StatusCode::SEE_OTHER);
398+
399+ let wire = read_until(&mut ben, "event: revoked").await;
400+ assert!(wire.contains("event: revoked"), "{wire}");
401+ }
402+
403+ /// A delete takes the person's sessions with them, and their tabs hear
404+ /// it like any other eviction.
405+ #[tokio::test]
406+ async fn a_delete_reaches_the_deleted_users_tab() {
407+ let setup = setup().await;
408+ let mut ben = open_live(&setup.router, &cookie(&setup.ben_tokens[0])).await;
409+
410+ let (status, _) = post_form(
411+ &setup.router,
412+ "/admin/delete",
413+ &format!("user={}", setup.ben_id),
414+ Some(&setup.admin_cookie),
415+ )
416+ .await;
417+ assert_eq!(status, StatusCode::SEE_OTHER);
418+
419+ let wire = read_until(&mut ben, "event: revoked").await;
420+ assert!(wire.contains("event: revoked"), "{wire}");
421+ }
422+
423+ /// The live client's fallback probe: a bare status, no HTML — 204 when
424+ /// the session still stands, 401 when it does not.
425+ #[tokio::test]
426+ async fn the_me_probe_answers_a_bare_status() {
427+ let setup = setup().await;
428+ for (cookie, expected) in [
429+ (Some(setup.admin_cookie.as_str()), StatusCode::NO_CONTENT),
430+ (None, StatusCode::UNAUTHORIZED),
431+ ] {
432+ let mut builder = http::Request::builder().uri("/api/me");
433+ if let Some(cookie) = cookie {
434+ builder = builder.header(header::COOKIE, cookie);
435+ }
436+ let response = setup
437+ .router
438+ .handle(builder.body(Body::empty()).unwrap())
439+ .await;
440+ assert_eq!(response.into_parts().0.status, expected);
441+ }
442+ }
443+}
crates/im-web/src/server.rsmodified+20 -1
@@ -39,11 +39,17 @@ pub struct App {
39 39
40 /// What travels the live channel. `Tick` is the panel's "something moved —40 /// What travels the live channel. `Tick` is the panel's "something moved —
41 /// re-read"; `Profile` is the directory's own news: this member's row, as it41 /// re-read"; `Profile` is the directory's own news: this member's row, as it
42-/// now stands, serialized exactly as `/directory` would have answered it.42+/// now stands, serialized exactly as `/directory` would have answered it;
43+/// `Revoked` is a sign-out in motion: this user's session(s) just died, the
44+/// one named by hash when the revocation was session-targeted.
43 #[derive(Clone, Debug)]45 #[derive(Clone, Debug)]
44 pub enum LiveEvent {46 pub enum LiveEvent {
45 Tick,47 Tick,
46 Profile(crate::directory::DirectoryMember),48 Profile(crate::directory::DirectoryMember),
49+ Revoked {
50+ user_id: String,
51+ session_hash: Option<String>,
52+ },
47 }53 }
48 54
49 /// Announce that the panel's data moved. Sends are lossy on purpose: nobody55 /// Announce that the panel's data moved. Sends are lossy on purpose: nobody
@@ -65,6 +71,19 @@ pub async fn notify_profile(cx: &Cx, user_id: &im_core::model::UserId) {
65 ));71 ));
66 }72 }
67 73
74+/// Announce that `user`'s sessions died — one of them when `session_hash`
75+/// names a session, all of them when it does not. Every write path that ends
76+/// sessions speaks here, so the dead sessions' open tabs hear their own
77+/// eviction on the live channel and leave without waiting out the stream
78+/// window. Sent right after the write commits and before the tick, so a
79+/// connection that swallows the tick has already missed nothing.
80+pub async fn note_revoked(cx: &Cx, user_id: &str, session_hash: Option<&str>) {
81+ let _ = app(cx).live.send(LiveEvent::Revoked {
82+ user_id: user_id.to_string(),
83+ session_hash: session_hash.map(str::to_string),
84+ });
85+}
86+
68 /// Log the event, then tick the live channel — the two travel together so87 /// Log the event, then tick the live channel — the two travel together so
69 /// the Logs page (and any watching panel) catches up without a reload.88 /// the Logs page (and any watching panel) catches up without a reload.
70 pub async fn log_event(cx: &Cx, kind: &str, actor: Option<&str>, detail: Option<&str>) {89 pub async fn log_event(cx: &Cx, kind: &str, actor: Option<&str>, detail: Option<&str>) {