Skip to main content

tablo_core/auth/
session.rs

1//! Server-side sessions: the [`AuthSession`] rows, their lookup, revocation
2//! and sweep.
3
4use std::{
5    sync::Arc,
6    time::{Duration, SystemTime},
7};
8
9use jiff::Timestamp;
10use topcoat::{
11    context::Cx,
12    session::{self, TokenHash, TokenStore, cookie::CookieTokenStore},
13};
14
15use super::{
16    DynAuthenticator, PanelUser, SignedIn,
17    hook::{AuthEvent, AuthEventKind},
18    infrastructure_failure,
19    token::{CREDENTIALS, REVOCATION, TokenPurpose},
20};
21use crate::{
22    TenantId,
23    auth::realm::{Realm, current_realm, realms},
24};
25
26mod lifetime;
27pub(super) mod sweep;
28
29pub use self::lifetime::Sessions;
30use self::lifetime::Standing;
31
32/// How long a session stays valid unless [`Auth::sessions`](crate::Auth::sessions) says otherwise:
33/// seven days.
34pub const SESSION_LIFETIME: Duration = Duration::from_hours(24 * 7);
35
36/// What every panel's [`session_cookie`] starts with.
37#[doc(hidden)]
38pub const SESSION_COOKIE_PREFIX: &str = "__Host-tablo_session_";
39
40/// The cookie that carries a session's token on the panel `Panel::new(panel)` mounts; `panel` is
41/// spelled as for [`Panel::new`](crate::Panel::new). Each panel has its own, so a browser stays
42/// signed in to several. Tablo keeps them apart from the router's
43/// [`SessionTokenStore`](topcoat::session::SessionTokenStore), so a host app's own Topcoat sessions
44/// and a panel's never replace each other's token.
45#[must_use]
46pub fn session_cookie(panel: &str) -> String {
47    format!(
48        "__Host-{}",
49        store_name(&crate::naming::normalize_prefix(panel))
50    )
51}
52
53/// The session cookie's name for `prefix`, as the store takes it: the store adds the `__Host-`
54/// prefix, which fixes `Path=/`, so panels differ by name alone. A byte a cookie name may not hold
55/// becomes `_` and its hex, and so does `_`, so no two prefixes share a name.
56fn store_name(prefix: &str) -> String {
57    use std::fmt::Write as _;
58
59    let mut name = SESSION_COOKIE_PREFIX
60        .trim_start_matches("__Host-")
61        .to_owned();
62    for byte in prefix.trim_start_matches('/').bytes() {
63        if byte.is_ascii_alphanumeric() || byte == b'-' {
64            name.push(char::from(byte));
65        } else {
66            write!(name, "_{byte:02x}").expect("writing to a String cannot fail");
67        }
68    }
69    name
70}
71
72/// The store of `panel`'s [`session_cookie`].
73fn token_store(panel: &Realm) -> CookieTokenStore {
74    CookieTokenStore::new().name(store_name(&panel.prefix))
75}
76
77/// The panel whose route is answering: only a panel's own routes start or end a session.
78fn session_panel(cx: &Cx) -> topcoat::Result<&Arc<Realm>> {
79    current_realm(cx).ok_or_else(|| {
80        crate::error::declaration("a panel session changes only under a panel".to_owned())
81    })
82}
83
84/// Shipped server-side session record: the SHA-256 hash of the client token,
85/// the user it authenticates, the panel that signed the user in, and its
86/// expiry. The raw token is never stored.
87///
88/// A session rides in its panel's [`session_cookie`], lasts as long as the panel's
89/// [`Sessions`] say, [`SESSION_LIFETIME`] from login by default, is replaced on each login and
90/// deleted on logout; each successful login also deletes up to 500
91/// expired sessions. It belongs to the panel
92/// that signed the user in: another panel's gate treats the request as anonymous, and
93/// [`auth::user`](crate::auth::user) answers `None` there. A browser holds one session on each
94/// panel, so signing in to a second panel leaves the first alone, and renaming a panel's prefix
95/// ends the sessions it issued. Sessions stay valid until they expire unless
96/// [`revoke_sessions_for_user`](crate::auth::revoke_sessions_for_user) ends them.
97///
98/// The row records the panel's prefix in a non-null `panel` column and the selected tenant in a
99/// nullable `tenant` column, a [`TenantId`] Toasty stores as a `Uuid` on the database. A table
100/// created without them gains them by migration: add `panel` with the panel's prefix as its
101/// default (`ALTER TABLE auth_sessions ADD COLUMN panel TEXT NOT NULL DEFAULT '/admin'`), then drop
102/// the default once every row names its panel. [`Auth::impersonation`](crate::Auth::impersonation)
103/// reads two more nullable columns, `impersonating` (`TEXT`) and `impersonating_until`, a
104/// timestamp: a table created without them gains them by `ALTER TABLE ... ADD COLUMN`.
105#[derive(Debug, Clone, toasty::Model)]
106pub struct AuthSession {
107    /// Hex-encoded SHA-256 of the session token.
108    #[key]
109    pub token_hash: String,
110    /// [`PanelUser::user_id`] of the authenticated user.
111    #[index]
112    pub user_id: String,
113    /// The prefix of the panel that signed the user in (e.g. `/admin`): the
114    /// only panel the session authenticates.
115    pub panel: String,
116    /// The tenant the user selected; `None` acts for the first.
117    pub tenant: Option<TenantId>,
118    /// Indexed for the login sweep's range scan on this column.
119    #[index]
120    pub expires_at: Timestamp,
121    pub created_at: Timestamp,
122    /// [`PanelUser::user_id`] of the user the session's user acts as, through
123    /// [`Auth::impersonation`](crate::Auth::impersonation); `None` while they act as themselves.
124    pub impersonating: Option<String>,
125    /// When acting as `impersonating` ends on its own.
126    pub impersonating_until: Option<Timestamp>,
127}
128
129/// Starts a new session, issuing a fresh token in the request's panel's [`session_cookie`].
130pub(super) async fn start(cx: &Cx) -> topcoat::Result<session::Session> {
131    let token = session::Token::random();
132    let panel = session_panel(cx)?;
133    let sessions = &panel.auth.sessions;
134    // The cookie outlives an idle timeout: the row decides, and a request moves its end.
135    token_store(panel)
136        .write(cx, token.clone(), sessions.lasts())
137        .await?;
138    Ok(session::Session {
139        token_hash: token.hash(),
140        expires_at: SystemTime::from(sessions.first_end(Timestamp::now())),
141    })
142}
143
144/// Discards the request's token, returning its hash so the caller can delete the row.
145pub(super) async fn stop(cx: &Cx) -> topcoat::Result<Option<TokenHash>> {
146    let panel = session_panel(cx)?;
147    let hash = token_hash(cx, panel).await?;
148    token_store(panel).delete(cx).await?;
149    Ok(hash)
150}
151
152/// The hash of the token the request presents to `panel`; `None` when it presents none or a
153/// malformed one.
154async fn token_hash(cx: &Cx, panel: &Realm) -> topcoat::Result<Option<TokenHash>> {
155    let token = token_store(panel).read(cx).await?;
156    Ok(token.map(|token| token.hash()))
157}
158
159pub(super) fn token_key(hash: &TokenHash) -> String {
160    use std::fmt::Write as _;
161
162    let mut key = String::with_capacity(64);
163    for byte in hash.iter() {
164        write!(key, "{byte:02x}").expect("writing to a String cannot fail");
165    }
166    key
167}
168
169pub(super) async fn record(
170    cx: &Cx,
171    session: &session::Session,
172    user: &dyn PanelUser,
173    panel: &Realm,
174) -> topcoat::Result<()> {
175    let expires_at = Timestamp::try_from(session.expires_at).map_err(topcoat::Error::from)?;
176    let mut db = crate::db::db(cx)?;
177    let mut tx = db.transaction().await.map_err(infrastructure_failure)?;
178    insert(
179        &mut tx,
180        &session.token_hash,
181        user.user_id(),
182        panel.prefix.clone(),
183        None,
184        expires_at,
185    )
186    .await
187    .map_err(infrastructure_failure)?;
188    // The session and its record commit together: a sign-in the trail cannot hold opens nothing.
189    let event = AuthEvent::own(AuthEventKind::SignIn, &panel.id, None, user);
190    super::hook::run(cx, &panel.auth_hooks, &event, &mut tx).await?;
191    tx.commit().await.map_err(infrastructure_failure)
192}
193
194/// The realms whose authenticator loads `user_type`, or `own` outside a router: the panels that
195/// share a user's credentials, so a credential change ends the user's sessions and reset links on
196/// each.
197pub(super) fn credential_panels(
198    cx: &Cx,
199    user_type: std::any::TypeId,
200    own: &Arc<Realm>,
201) -> Vec<Arc<Realm>> {
202    let realms = realms(cx);
203    if realms.is_empty() {
204        return vec![Arc::clone(own)];
205    }
206    realms
207        .into_iter()
208        .filter(|realm| {
209            realm
210                .auth
211                .authenticator()
212                .is_some_and(|auth| auth.user_type() == user_type)
213        })
214        .collect()
215}
216
217/// Deletes every session `user_id` holds on `panels`, and every [`AuthToken`](super::AuthToken)
218/// for one of `purposes` it holds on those that issue them, through `ex`: what a credential
219/// change ends, with [`CREDENTIALS`], or a revocation, with [`REVOCATION`].
220pub(super) async fn end_credentials(
221    ex: &mut dyn toasty::Executor,
222    user_id: &str,
223    panels: &[Arc<Realm>],
224    purposes: &[TokenPurpose],
225) -> topcoat::Result<()> {
226    let prefixes: Vec<String> = panels.iter().map(|panel| panel.prefix.clone()).collect();
227    AuthSession::filter(
228        AuthSession::fields()
229            .user_id()
230            .eq(user_id.to_string())
231            .and(AuthSession::fields().panel().in_list(prefixes)),
232    )
233    .delete()
234    .exec(&mut *ex)
235    .await
236    .map_err(infrastructure_failure)?;
237    let issuing: Vec<String> = panels
238        .iter()
239        .filter(|panel| panel.auth.issues_tokens())
240        .map(|panel| panel.prefix.clone())
241        .collect();
242    if issuing.is_empty() {
243        // A panel that issues no token may leave its model unregistered.
244        return Ok(());
245    }
246    super::token::end_all(ex, user_id, Some(issuing), purposes).await
247}
248
249/// Replaces every session `user_id` holds, on every panel whose authenticator loads `user_type`,
250/// with `session` on the panel and tenant `signed` acts under, and ends its tokens there,
251/// through `ex`: what a credential change does inside the transaction that writes it, so the new
252/// credential and the revocation commit together.
253pub(super) async fn replace_sessions(
254    cx: &Cx,
255    ex: &mut dyn toasty::Executor,
256    signed: &SignedIn,
257    user_type: std::any::TypeId,
258    session: &session::Session,
259) -> topcoat::Result<()> {
260    let panels = credential_panels(cx, user_type, &signed.realm);
261    let user_id = signed.user.user_id();
262    end_credentials(&mut *ex, &user_id, &panels, CREDENTIALS).await?;
263    let expires_at = Timestamp::try_from(session.expires_at).map_err(topcoat::Error::from)?;
264    insert(
265        ex,
266        &session.token_hash,
267        user_id,
268        signed.realm.prefix.clone(),
269        signed.tenant,
270        expires_at,
271    )
272    .await
273    .map_err(infrastructure_failure)
274}
275
276/// Records a session for `user` on the panel `Panel::new(panel)` mounts, as a successful login
277/// does, and returns the token its session cookie carries. No credential is checked.
278///
279/// `tablo::testing`'s `TestClient::sign_in` is the caller: it lets a test act as a signed-in user
280/// without a password hash. The `testing` feature, which only `tablo-test` turns on, compiles it:
281/// a production build carries no way to open a session without a credential.
282#[cfg(feature = "testing")]
283#[doc(hidden)]
284pub async fn mint_session(
285    ex: &mut dyn toasty::Executor,
286    panel: &str,
287    user: &dyn PanelUser,
288) -> topcoat::Result<String> {
289    let token = session::Token::random();
290    let expires_at = Timestamp::try_from(std::time::SystemTime::now() + SESSION_LIFETIME)
291        .map_err(topcoat::Error::from)?;
292    insert(
293        ex,
294        &token.hash(),
295        user.user_id(),
296        crate::naming::normalize_prefix(panel),
297        None,
298        expires_at,
299    )
300    .await?;
301    Ok(token.encode())
302}
303
304async fn insert(
305    ex: &mut dyn toasty::Executor,
306    hash: &TokenHash,
307    user_id: String,
308    panel: String,
309    tenant: Option<TenantId>,
310    expires_at: Timestamp,
311) -> toasty::Result<()> {
312    toasty::create!(AuthSession {
313        token_hash: token_key(hash),
314        user_id,
315        panel,
316        tenant,
317        expires_at,
318        created_at: Timestamp::now(),
319        impersonating: None,
320        impersonating_until: None,
321    })
322    .exec(ex)
323    .await?;
324    Ok(())
325}
326
327pub(super) async fn select_tenant(cx: &Cx, tenant: TenantId) -> topcoat::Result<()> {
328    let Some(hash) = token_hash(cx, session_panel(cx)?).await? else {
329        return Err(topcoat::router::error::forbidden().into());
330    };
331    let mut db = crate::db::db(cx)?;
332    AuthSession::filter(AuthSession::fields().token_hash().eq(token_key(&hash)))
333        .update()
334        .tenant(Some(tenant))
335        .exec(&mut db)
336        .await
337        .map_err(infrastructure_failure)?;
338    Ok(())
339}
340
341/// Makes the request's session act as `target` until `until`, for no tenant yet, or, with `None`,
342/// as its own user again, through `ex`.
343pub(super) async fn impersonate(
344    cx: &Cx,
345    ex: &mut dyn toasty::Executor,
346    target: Option<(String, Timestamp)>,
347) -> topcoat::Result<()> {
348    let Some(hash) = token_hash(cx, session_panel(cx)?).await? else {
349        return Err(topcoat::router::error::forbidden().into());
350    };
351    set_impersonation(ex, &token_key(&hash), target).await
352}
353
354/// Sets what the session row keyed `key` acts as, through `ex`: see [`impersonate`].
355pub(super) async fn set_impersonation(
356    ex: &mut dyn toasty::Executor,
357    key: &str,
358    target: Option<(String, Timestamp)>,
359) -> topcoat::Result<()> {
360    let (user, until) = target.unzip();
361    AuthSession::filter(AuthSession::fields().token_hash().eq(key.to_owned()))
362        .update()
363        .impersonating(user)
364        .impersonating_until(until)
365        .tenant(None)
366        .exec(ex)
367        .await
368        .map_err(infrastructure_failure)?;
369    Ok(())
370}
371
372pub(super) async fn delete_session(cx: &Cx, hash: &TokenHash) -> topcoat::Result<()> {
373    delete_session_row(cx, &token_key(hash)).await
374}
375
376/// The session `started` holds, or a new one it then holds: a transaction
377/// [`run_serializable`](super::token::run_serializable) runs again records the session the first
378/// run gave the browser, rather than one more cookie.
379pub(super) async fn start_once(
380    cx: &Cx,
381    started: &mut Option<session::Session>,
382) -> topcoat::Result<session::Session> {
383    if let Some(session) = started {
384        return Ok(session.clone());
385    }
386    let session = start(cx).await?;
387    *started = Some(session.clone());
388    Ok(session)
389}
390
391/// Ends the session the request presents and starts a new one, so a token presented before a
392/// sign-in cannot be replayed after it.
393///
394/// # Errors
395///
396/// The opaque sign-in outage when the database cannot answer; any other failure keeps its mapping.
397pub(super) async fn fresh_session(cx: &Cx) -> topcoat::Result<session::Session> {
398    let panel = session_panel(cx)?;
399    if let Some(hash) = token_hash(cx, panel)
400        .await
401        .map_err(infrastructure_failure)?
402    {
403        delete_session(cx, &hash).await?;
404    }
405    start(cx).await.map_err(infrastructure_failure)
406}
407
408async fn delete_session_row(cx: &Cx, key: &str) -> topcoat::Result<()> {
409    let mut db = crate::db::db(cx)?;
410    AuthSession::filter(AuthSession::fields().token_hash().eq(key.to_string()))
411        .delete()
412        .exec(&mut db)
413        .await
414        .map_err(infrastructure_failure)?;
415    Ok(())
416}
417
418/// Revokes every live session of `user_id`, its pending sign-ins, its reset links and its pending
419/// email change, on the current panel and on each panel sharing its users, whose authenticator
420/// loads the same user type, or on every panel outside any panel; call it whenever a credential
421/// changes. A link that proves an address or undoes an email change survives.
422///
423/// # Errors
424///
425/// The opaque sign-in outage when the database cannot answer.
426pub async fn revoke_sessions_for_user(cx: &Cx, user_id: &str) -> topcoat::Result<()> {
427    let mut db = crate::db::db(cx)?;
428    if let Some(panel) = current_realm(cx) {
429        let panels = match panel.auth.authenticator() {
430            Some(auth) => credential_panels(cx, auth.user_type(), panel),
431            None => vec![Arc::clone(panel)],
432        };
433        end_credentials(&mut db, user_id, &panels, REVOCATION).await?;
434        wake_bells(
435            cx,
436            user_id,
437            panels.iter().map(|panel| panel.prefix.as_str()),
438        );
439        return Ok(());
440    }
441    AuthSession::filter(AuthSession::fields().user_id().eq(user_id.to_string()))
442        .delete()
443        .exec(&mut db)
444        .await
445        .map_err(infrastructure_failure)?;
446    let realms = realms(cx);
447    if realms.iter().any(|realm| realm.auth.issues_tokens()) {
448        super::token::end_all(&mut db, user_id, None, REVOCATION).await?;
449    }
450    wake_bells(
451        cx,
452        user_id,
453        realms.iter().map(|realm| realm.prefix.as_str()),
454    );
455    Ok(())
456}
457
458/// Wakes the bells `user_id` has open on `panels`, so each checks its session again and stops.
459fn wake_bells<'a>(cx: &Cx, user_id: &str, panels: impl Iterator<Item = &'a str>) {
460    let bus = crate::bus::bus(cx);
461    for panel in panels {
462        bus.wake(panel, user_id);
463    }
464}
465
466/// Returns the live session row the request presents to `panel`, purging it when expired and
467/// reading nothing when `panel`'s cookie is absent. A token moved over from another panel's cookie
468/// finds no row here, since a row serves only the panel that issued it.
469///
470/// `activity` says whether the request counts against the panel's
471/// [`idle_timeout`](Sessions::idle_timeout): one that does moves the row's end forward.
472pub(super) async fn session_row(
473    cx: &Cx,
474    panel: &Realm,
475    activity: Activity,
476) -> topcoat::Result<Option<AuthSession>> {
477    let Some(hash) = token_hash(cx, panel).await? else {
478        return Ok(None);
479    };
480    let key = token_key(&hash);
481    let mut db = crate::db::db(cx)?;
482    let row = AuthSession::filter(AuthSession::fields().token_hash().eq(key))
483        .first()
484        .exec(&mut db)
485        .await
486        .map_err(infrastructure_failure)?;
487    let Some(mut row) = row else {
488        return Ok(None);
489    };
490    let end = match panel.auth.sessions.check(&row, Timestamp::now()) {
491        Standing::Ended => {
492            delete_session_row(cx, &row.token_hash).await?;
493            return Ok(None);
494        }
495        Standing::Live(end) => end,
496    };
497    if row.panel != panel.prefix {
498        return Ok(None);
499    }
500    if let (Activity::Counts, Some(end)) = (activity, end) {
501        AuthSession::filter(
502            AuthSession::fields()
503                .token_hash()
504                .eq(row.token_hash.clone()),
505        )
506        .update()
507        .expires_at(end)
508        .exec(&mut db)
509        .await
510        .map_err(infrastructure_failure)?;
511        row.expires_at = end;
512    }
513    Ok(Some(row))
514}
515
516/// Whether a request that presents a session counts as its user being there.
517#[derive(Debug, Clone, Copy, PartialEq, Eq)]
518pub(super) enum Activity {
519    /// A request the user's browser sends: it moves an idle timeout's end.
520    Counts,
521    /// A look at the session from a connection already open, which proves no one is there.
522    Ignored,
523}
524
525/// Resolves `row` to its user, purging the row when the user no longer authenticates.
526///
527/// A panel behind [`ExternalAuth`](crate::ExternalAuth) keeps it: there `None` speaks for this
528/// request's copy of the app's cookies, which a live connection opened before a rotation still
529/// holds, and the browser's fresh tab goes on using the row. It serves no one the app does not
530/// name, and the next entry for another user replaces it.
531pub(super) async fn session_user(
532    cx: &Cx,
533    row: AuthSession,
534    panel: &Arc<Realm>,
535    authenticator: &dyn DynAuthenticator,
536) -> topcoat::Result<Option<SignedIn>> {
537    match authenticator
538        .find_by_id(cx, &row.user_id)
539        .await
540        .map_err(infrastructure_failure)?
541    {
542        Some(user) if row.impersonating.is_some() => {
543            super::impersonation::resolve(cx, row, user, panel, authenticator)
544                .await
545                .map(Some)
546        }
547        Some(user) => Ok(Some(SignedIn {
548            user,
549            realm: Arc::clone(panel),
550            tenant: row.tenant,
551            impersonator: None,
552        })),
553        None => {
554            if panel.auth.external().is_none() {
555                delete_session_row(cx, &row.token_hash).await?;
556            }
557            Ok(None)
558        }
559    }
560}
561
562/// Resolves the request's session on `panel` into its user.
563pub(super) async fn resolve(
564    cx: &Cx,
565    panel: &Arc<Realm>,
566    authenticator: &dyn DynAuthenticator,
567    activity: Activity,
568) -> topcoat::Result<Option<SignedIn>> {
569    match session_row(cx, panel, activity).await? {
570        Some(row) => session_user(cx, row, panel, authenticator).await,
571        None => Ok(None),
572    }
573}