From 586231628c35f9dbc2b81c53790477bd14e36deb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Tue, 8 Sep 2026 18:12:48 +0300 Subject: [PATCH] =?UTF-8?q?a=20person's=20sign-ins=20are=20capped=20by=20t?= =?UTF-8?q?he=20panel's=20new=20per-user=20ceiling:=20create=5Fsession,=20?= =?UTF-8?q?already=20the=20one=20door=20every=20login=20walks=20through,?= =?UTF-8?q?=20keeps=20the=20newest=20max=5Fsessions=20live=20rows=20and=20?= =?UTF-8?q?revokes=20the=20overflow=20in=20the=20same=20critical=20section?= =?UTF-8?q?=20as=20the=20insert=20=E2=80=94=20newest-first=20with=20a=20ro?= =?UTF-8?q?wid=20tiebreak=20so=20the=20cut=20is=20deterministic=20and=20th?= =?UTF-8?q?e=20fresh=20login=20never=20evicts=20itself,=20expired=20rows?= =?UTF-8?q?=20holding=20no=20slot=20=E2=80=94=20and=20the=20cascade=20alre?= =?UTF-8?q?ady=20written=20for=20revocation=20takes=20the=20overflow's=20a?= =?UTF-8?q?pp=20sessions=20and=20refresh=20tokens=20down=20with=20it,=20so?= =?UTF-8?q?=20the=20oldest=20device=20is=20truly=20logged=20out,=20not=20j?= =?UTF-8?q?ust=20the=20cookie=20ignored;=20the=20ceiling=20defaults=20to?= =?UTF-8?q?=20five,=20clamped=20at=20one,=20set=20from=20the=20admin=20pan?= =?UTF-8?q?el's=20settings=20card=20as=20'Sign-in=20sessions=20per=20user'?= =?UTF-8?q?;=20and=20every=20person=20can=20now=20see=20their=20connected?= =?UTF-8?q?=20apps:=20a=20new=20apps=20tab=20on=20the=20signed-in=20landin?= =?UTF-8?q?g=20lists=20the=20OIDC=20clients=20holding=20live=20grants=20?= =?UTF-8?q?=E2=80=94=20name,=20client=20id,=20grant=20count,=20last=20conn?= =?UTF-8?q?ected=20=E2=80=94=20grouped=20per=20client=20from=20list=5Fconn?= =?UTF-8?q?ected=5Fapps,=20empty-noted=20when=20nothing=20is=20connected,?= =?UTF-8?q?=20everything=20user-or-app-controlled=20escaped?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- crates/im-core/src/oidc.rs | 186 +++++++++++++++++++++++++++++++++ crates/im-core/src/sessions.rs | 166 ++++++++++++++++++++++++++++- crates/im-core/src/settings.rs | 33 ++++++ crates/im-web/src/admin.rs | 10 +- crates/im-web/src/directory.rs | 77 ++++++++++++++ crates/im-web/src/i18n.rs | 15 +++ crates/im-web/src/pages.rs | 52 ++++++++- 7 files changed, 534 insertions(+), 5 deletions(-) diff --git a/crates/im-core/src/oidc.rs b/crates/im-core/src/oidc.rs index e384ff5..cf561d2 100644 --- a/crates/im-core/src/oidc.rs +++ b/crates/im-core/src/oidc.rs @@ -516,6 +516,51 @@ pub async fn introspect_app_session( }))) } +/// One app a person is signed into, as the connected-apps list shows it: +/// the client, its display name, how many of its app sessions are live, +/// and when the person first and last connected to it. +#[derive(Debug, Clone)] +pub struct ConnectedApp { + pub client_id: String, + pub name: String, + pub count: i64, + pub first_at: time::OffsetDateTime, + pub last_at: time::OffsetDateTime, +} + +/// The OIDC clients holding at least one live app session for `user`, +/// most recently connected first. Revocation and expiry filter in SQL +/// beside the introspection answer and `stats`' counts; the display name +/// falls back to the raw `client_id` when no registered client row stands +/// behind it. +pub async fn list_connected_apps(store: &Store, user: &UserId) -> Result> { + let conn = store.conn.lock().await; + let mut rows = conn + .query( + "SELECT a.client_id, COALESCE(c.name, a.client_id), COUNT(*), \ + MIN(a.created_at), MAX(a.created_at) \ + FROM app_sessions a \ + LEFT JOIN oidc_clients c ON c.client_id = a.client_id \ + WHERE a.user_id = ?1 AND a.revoked_at IS NULL AND a.expires_at > ?2 \ + GROUP BY a.client_id \ + ORDER BY MAX(a.created_at) DESC, a.client_id", + turso::params![user.to_string(), store::stamp(store::now())?], + ) + .await + .map_err(backend)?; + let mut out = Vec::new(); + while let Some(row) = rows.next().await.map_err(backend)? { + out.push(ConnectedApp { + client_id: store::text(&row, 0)?, + name: store::text(&row, 1)?, + count: store::int(&row, 2)?, + first_at: store::parse_stamp(&store::text(&row, 3)?)?, + last_at: store::parse_stamp(&store::text(&row, 4)?)?, + }); + } + Ok(out) +} + #[cfg(test)] mod tests { use super::*; @@ -723,4 +768,145 @@ mod tests { .contains(&"http://app/callback".to_string()) ); } + + #[tokio::test] + async fn connected_apps_list_live_grants_newest_first() { + let (store, client_id, user_id) = fixture().await; + let (other_id, _secret) = + create_client(&store, "other", vec!["http://other/callback".into()]) + .await + .unwrap(); + let session = create_session(&store, &user_id, &SessionMeta::default()) + .await + .unwrap(); + + // Two grants on the first client, one on the second; the second + // client connected last and leads. + issue_app_session(&store, &user_id, &client_id, &session.hash()) + .await + .unwrap(); + issue_app_session(&store, &user_id, &client_id, &session.hash()) + .await + .unwrap(); + issue_app_session(&store, &user_id, &other_id, &session.hash()) + .await + .unwrap(); + let apps = list_connected_apps(&store, &user_id).await.unwrap(); + assert_eq!(apps.len(), 2); + assert_eq!(apps[0].client_id, other_id.as_str()); + assert_eq!(apps[0].name, "other"); + assert_eq!(apps[0].count, 1); + // The first client aggregates its two grants under its registered + // display name. + assert_eq!(apps[1].client_id, client_id.as_str()); + assert_eq!(apps[1].name, "demo"); + assert_eq!(apps[1].count, 2); + assert!(apps[1].first_at <= apps[1].last_at); + + // Backdate the second client's grant an hour: it connected last no + // more, and the order follows the stamps, not the inserts. + let conn = store.conn.lock().await; + conn.execute( + "UPDATE app_sessions SET created_at = ?1 WHERE client_id = ?2", + turso::params![ + store::stamp(store::now() - time::Duration::hours(1)).unwrap(), + other_id.as_str(), + ], + ) + .await + .unwrap(); + drop(conn); + let apps = list_connected_apps(&store, &user_id).await.unwrap(); + assert_eq!(apps[0].client_id, client_id.as_str()); + assert_eq!(apps[1].client_id, other_id.as_str()); + assert_eq!(apps[1].first_at, apps[1].last_at); + + // Another person's grants never show up in someone else's list. + let invite = create_invite(&store, "bob@example.com", None, false) + .await + .unwrap(); + let bob = create_user_from_invite(&store, invite.expose(), "Bob", "tDLr9!mZQ2xvQ") + .await + .unwrap(); + let bobs_session = create_session(&store, &bob.id, &SessionMeta::default()) + .await + .unwrap(); + issue_app_session(&store, &bob.id, &other_id, &bobs_session.hash()) + .await + .unwrap(); + let bobs_apps = list_connected_apps(&store, &bob.id).await.unwrap(); + assert_eq!(bobs_apps.len(), 1); + assert_eq!(bobs_apps[0].client_id, other_id.as_str()); + assert_eq!(bobs_apps[0].count, 1); + } + + #[tokio::test] + async fn connected_apps_skip_revoked_grants_and_fall_back_to_raw_ids() { + let (store, client_id, user_id) = fixture().await; + let session = create_session(&store, &user_id, &SessionMeta::default()) + .await + .unwrap(); + + // Two grants on the client; then one of them is revoked. + let revocable = issue_app_session(&store, &user_id, &client_id, &session.hash()) + .await + .unwrap(); + issue_app_session(&store, &user_id, &client_id, &session.hash()) + .await + .unwrap(); + let conn = store.conn.lock().await; + conn.execute( + "UPDATE app_sessions SET revoked_at = ?1 WHERE token_hash = ?2", + turso::params![ + store::stamp(store::now()).unwrap(), + hash_token(revocable.expose()), + ], + ) + .await + .unwrap(); + drop(conn); + let apps = list_connected_apps(&store, &user_id).await.unwrap(); + assert_eq!(apps.len(), 1); + assert_eq!(apps[0].client_id, client_id.as_str()); + assert_eq!(apps[0].count, 1); + + // A grant whose client row never existed shows the raw client_id + // as its name. + let conn = store.conn.lock().await; + conn.execute( + "INSERT INTO app_sessions \ + (token_hash, user_id, client_id, session_hash, created_at, expires_at) \ + VALUES ('ghost-hash', ?1, 'ghost-app', ?2, ?3, ?4)", + turso::params![ + user_id.to_string(), + session.hash(), + store::stamp(store::now()).unwrap(), + store::stamp(store::now() + time::Duration::days(30)).unwrap(), + ], + ) + .await + .unwrap(); + drop(conn); + let apps = list_connected_apps(&store, &user_id).await.unwrap(); + assert_eq!(apps.len(), 2); + let ghost = apps + .iter() + .find(|app| app.client_id == "ghost-app") + .unwrap(); + assert_eq!(ghost.name, "ghost-app"); + assert_eq!(ghost.count, 1); + + // And an expired grant is not a connected app either. + let conn = store.conn.lock().await; + conn.execute( + "UPDATE app_sessions SET expires_at = ?1 WHERE client_id = 'ghost-app'", + turso::params![store::stamp(store::now() - time::Duration::days(1)).unwrap()], + ) + .await + .unwrap(); + drop(conn); + let apps = list_connected_apps(&store, &user_id).await.unwrap(); + assert_eq!(apps.len(), 1); + assert_eq!(apps[0].client_id, client_id.as_str()); + } } diff --git a/crates/im-core/src/sessions.rs b/crates/im-core/src/sessions.rs index 296424b..6766535 100644 --- a/crates/im-core/src/sessions.rs +++ b/crates/im-core/src/sessions.rs @@ -36,10 +36,17 @@ pub struct SessionInfo { /// Creates a session for `user`, returning the raw cookie token. The row /// holds only its digest, plus what `meta` says about the browser — and the /// first sighting is creation itself, so `seen_at` starts at `created_at`. +/// +/// The panel's `max_sessions` policy caps how many live sessions one +/// person may hold: past the cap the oldest of their sessions is revoked +/// in the same write, and the cascade takes every app session and refresh +/// token born under it down too. The session being created is the newest +/// by construction, so a fresh login never evicts itself. pub async fn create_session(store: &Store, user: &UserId, meta: &SessionMeta) -> Result { let token = Token::mint(); let now = store::now(); - let days = crate::settings::policy(store).await?.session_days; + // One policy read serves both the lifetime and the per-user cap. + let policy = crate::settings::policy(store).await?; let conn = store.conn.lock().await; conn.execute( "INSERT INTO sessions (token_hash, user_id, created_at, expires_at, ip, agent, seen_at) \ @@ -48,13 +55,45 @@ pub async fn create_session(store: &Store, user: &UserId, meta: &SessionMeta) -> token.hash(), user.to_string(), store::stamp(now)?, - store::stamp(now + time::Duration::days(days))?, + store::stamp(now + time::Duration::days(policy.session_days))?, meta.ip.clone(), meta.agent.clone(), ], ) .await .map_err(backend)?; + // The cap, enforced beside the insert: keep the newest `max_sessions` + // live sessions of this user and revoke the rest, under the same lock + // so the store never shows more than the cap allows. Newest-first with + // a rowid tiebreak keeps the cut deterministic when stamps collide, and + // an expired row is no session anymore — it neither holds a slot nor + // needs a revoke. + let mut rows = conn + .query( + "SELECT token_hash, expires_at FROM sessions \ + WHERE user_id = ?1 AND revoked_at IS NULL \ + ORDER BY created_at DESC, rowid DESC", + turso::params![user.to_string()], + ) + .await + .map_err(backend)?; + let mut kept = 0i64; + let mut overflow = Vec::new(); + while let Some(row) = rows.next().await.map_err(backend)? { + // Expiry is a stamp comparison beside `resolve_session`, where a + // corrupt stamp surfaces as an error. + if store::parse_stamp(&store::text(&row, 1)?)? < now { + continue; + } + if kept < policy.max_sessions { + kept += 1; + } else { + overflow.push(store::text(&row, 0)?); + } + } + for hash in &overflow { + revoke_session_hash_conn(&conn, hash).await?; + } Ok(token) } @@ -120,6 +159,13 @@ pub async fn revoke_session(store: &Store, token: &str) -> Result<()> { /// revoke-everything below. pub(crate) async fn revoke_session_hash(store: &Store, hash: &str) -> Result<()> { let conn = store.conn.lock().await; + revoke_session_hash_conn(&conn, hash).await +} + +/// The UPDATE half of [`revoke_session_hash`], runnable under a lock the +/// caller already holds — session creation revokes its overflow with it +/// inside the same critical section that inserts the fresh row. +async fn revoke_session_hash_conn(conn: &turso::Connection, hash: &str) -> Result<()> { let now = store::stamp(store::now())?; conn.execute( "UPDATE sessions SET revoked_at = ?1 WHERE token_hash = ?2 AND revoked_at IS NULL", @@ -505,4 +551,120 @@ mod tests { let again = list_sessions(&store, &user_id).await.unwrap(); assert_eq!(again[0].seen_at, Some(fresh)); } + + #[tokio::test] + async fn cap_evicts_the_oldest_session_and_its_app_tokens() { + let (store, user_id) = fixture().await; + let mut tokens = Vec::new(); + for _ in 0..5 { + tokens.push( + create_session(&store, &user_id, &SessionMeta::default()) + .await + .unwrap(), + ); + } + // An app session and a refresh token ride on the oldest central + // session, so the eviction's cascade has something to kill. + let (client_id, _secret) = + crate::oidc::create_client(&store, "evictee", vec!["http://app/callback".into()]) + .await + .unwrap(); + let oldest = &tokens[0]; + let app_token = + crate::oidc::issue_app_session(&store, &user_id, &client_id, &oldest.hash()) + .await + .unwrap(); + let refresh = + crate::oidc::issue_refresh(&store, &user_id, &client_id, &oldest.hash()) + .await + .unwrap(); + + // The sixth login pushes the first one out. + let fresh = create_session(&store, &user_id, &SessionMeta::default()) + .await + .unwrap(); + assert!( + resolve_session(&store, oldest.expose()) + .await + .unwrap() + .is_none() + ); + for token in &tokens[1..] { + assert!( + resolve_session(&store, token.expose()) + .await + .unwrap() + .is_some() + ); + } + assert!( + resolve_session(&store, fresh.expose()) + .await + .unwrap() + .is_some() + ); + assert_eq!(list_sessions(&store, &user_id).await.unwrap().len(), 5); + + // The cascade: the evicted session's app session and refresh token + // stop resolving too. + assert!( + crate::oidc::introspect_app_session( + &store, + app_token.expose(), + client_id.as_str() + ) + .await + .unwrap() + .is_none() + ); + assert!( + crate::oidc::rotate_refresh(&store, refresh.expose()) + .await + .unwrap() + .is_none() + ); + } + + #[tokio::test] + async fn cap_follows_the_policy() { + let (store, user_id) = fixture().await; + crate::settings::set_policy( + &store, + &crate::settings::Policy { + max_sessions: 2, + ..Default::default() + }, + ) + .await + .unwrap(); + + let first = create_session(&store, &user_id, &SessionMeta::default()) + .await + .unwrap(); + let second = create_session(&store, &user_id, &SessionMeta::default()) + .await + .unwrap(); + // The third login evicts the first: the cap is two now. + let third = create_session(&store, &user_id, &SessionMeta::default()) + .await + .unwrap(); + assert!( + resolve_session(&store, first.expose()) + .await + .unwrap() + .is_none() + ); + assert!( + resolve_session(&store, second.expose()) + .await + .unwrap() + .is_some() + ); + assert!( + resolve_session(&store, third.expose()) + .await + .unwrap() + .is_some() + ); + } } diff --git a/crates/im-core/src/settings.rs b/crates/im-core/src/settings.rs index ca2fd83..5198970 100644 --- a/crates/im-core/src/settings.rs +++ b/crates/im-core/src/settings.rs @@ -238,6 +238,7 @@ pub async fn set_smtp(store: &Store, smtp: &Smtp, password: Option<&str>) -> Res pub struct Policy { pub invite_days: i64, pub session_days: i64, + pub max_sessions: i64, pub pending_minutes: i64, pub reset_minutes: i64, pub login_attempts_per_hour: i64, @@ -248,6 +249,7 @@ impl Default for Policy { Self { invite_days: 7, session_days: 30, + max_sessions: 5, pending_minutes: 10, reset_minutes: 60, login_attempts_per_hour: 10, @@ -268,6 +270,7 @@ pub async fn policy(store: &Store) -> Result { Ok(Policy { invite_days: number(store, "invite_days", defaults.invite_days).await?, session_days: number(store, "session_days", defaults.session_days).await?, + max_sessions: number(store, "max_sessions", defaults.max_sessions).await?, pending_minutes: number(store, "pending_minutes", defaults.pending_minutes).await?, reset_minutes: number(store, "reset_minutes", defaults.reset_minutes).await?, login_attempts_per_hour: number( @@ -297,6 +300,12 @@ pub async fn set_policy(store: &Store, policy: &Policy) -> Result<()> { &clamp(policy.session_days, defaults.session_days).to_string(), ) .await?; + set( + store, + "max_sessions", + &clamp(policy.max_sessions, defaults.max_sessions).to_string(), + ) + .await?; set( store, "pending_minutes", @@ -461,4 +470,28 @@ mod tests { assert_eq!(standing(&store).await.unwrap(), Standing::Unchecked); assert!(last_check(&store).await.unwrap().is_none()); } + + #[tokio::test] + async fn policy_defaults_roundtrip_and_zero_clamps_to_default() { + let store = Store::open(Path::new(":memory:")).await.unwrap(); + + // A fresh database reads as the born-with defaults. + assert_eq!(policy(&store).await.unwrap(), Policy::default()); + assert_eq!(policy(&store).await.unwrap().max_sessions, 5); + + // A written value comes back... + let mut value = Policy::default(); + value.max_sessions = 2; + set_policy(&store, &value).await.unwrap(); + assert_eq!(policy(&store).await.unwrap().max_sessions, 2); + + // ...and zero or negative — a cap that would lock every user out + // of their own account — clamps back to the default, unstored. + value.max_sessions = 0; + set_policy(&store, &value).await.unwrap(); + assert_eq!(policy(&store).await.unwrap().max_sessions, 5); + value.max_sessions = -3; + set_policy(&store, &value).await.unwrap(); + assert_eq!(policy(&store).await.unwrap().max_sessions, 5); + } } diff --git a/crates/im-web/src/admin.rs b/crates/im-web/src/admin.rs index 3d249e7..80e2e50 100644 --- a/crates/im-web/src/admin.rs +++ b/crates/im-web/src/admin.rs @@ -604,8 +604,8 @@ async fn service_outcome( } /// The knobs the code shipped with, now the panel's: invite and reset link -/// lifetimes, the sign-in session's days, the pending marker's minutes, and -/// the sign-in failure ceiling. Same form skin as Mail. +/// lifetimes, the sign-in session's days and per-user ceiling, the pending +/// marker's minutes, and the sign-in failure ceiling. Same form skin as Mail. async fn settings_section(cx: &Cx, lang: i18n::Lang) -> Result { let policy = settings::policy(&app(cx).store).await?; Ok(format!( @@ -617,6 +617,8 @@ async fn settings_section(cx: &Cx, lang: i18n::Lang) -> Result +