tablo-core 0.8.0

The core toolkit types for Tablo, a server-rendered admin toolkit on Topcoat and Toasty.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
//! Server-side sessions: the [`AuthSession`] rows, their lookup, revocation
//! and sweep.

use std::{sync::Arc, time::Duration};

use jiff::Timestamp;
use topcoat::{
    context::Cx,
    session::{self, TokenHash},
};
use uuid::Uuid;

use super::{
    DynAuthenticator, PanelUser, SignedIn, infrastructure_failure,
    token::{CREDENTIALS, REVOCATION, TokenPurpose},
};
use crate::auth::realm::{Realm, current_realm, realms};

/// How long a session stays valid: seven days, fixed.
pub const SESSION_LIFETIME: Duration = Duration::from_hours(24 * 7);

/// Shipped server-side session record: the SHA-256 hash of the client token,
/// the user it authenticates, the panel that signed the user in, and its
/// expiry. The raw token is never stored.
///
/// A session lasts [`SESSION_LIFETIME`] from login, is replaced on each login and deleted on
/// logout; each successful login also deletes up to 500 expired sessions. It belongs to the panel
/// that signed the user in: another panel's gate treats the request as anonymous, and
/// [`auth::user`](crate::auth::user) answers `None` there. One browser holds one session, so
/// signing in to a second panel ends the first, and renaming a panel's prefix ends the sessions
/// it issued. Sessions stay valid until they expire unless
/// [`revoke_sessions_for_user`](crate::auth::revoke_sessions_for_user) ends them.
///
/// The row records the panel's prefix in a non-null `panel` column and the selected tenant in a
/// nullable `tenant` column, typed as Toasty stores a `Uuid` on the database. A table created
/// without them gains them by migration: add `panel` with the panel's prefix as its default
/// (`ALTER TABLE auth_sessions ADD COLUMN panel TEXT NOT NULL DEFAULT '/admin'`), then drop the
/// default once every row names its panel.
#[derive(Debug, Clone, toasty::Model)]
pub struct AuthSession {
    /// Hex-encoded SHA-256 of the session token.
    #[key]
    pub token_hash: String,
    /// [`PanelUser::user_id`] of the authenticated user.
    #[index]
    pub user_id: String,
    /// The prefix of the panel that signed the user in (e.g. `/admin`): the
    /// only panel the session authenticates.
    pub panel: String,
    /// The tenant the user selected; `None` acts for the first.
    pub tenant: Option<Uuid>,
    /// Indexed for the login sweep's range scan on this column.
    #[index]
    pub expires_at: Timestamp,
    pub created_at: Timestamp,
}

pub(super) fn token_key(hash: &TokenHash) -> String {
    use std::fmt::Write as _;

    let mut key = String::with_capacity(64);
    for byte in hash.iter() {
        write!(key, "{byte:02x}").expect("writing to a String cannot fail");
    }
    key
}

pub(super) async fn record(
    cx: &Cx,
    session: &session::Session,
    user: &dyn PanelUser,
    panel: &Realm,
) -> topcoat::Result<()> {
    let expires_at = Timestamp::try_from(session.expires_at).map_err(topcoat::Error::from)?;
    insert(
        &mut crate::db::db(cx)?,
        &session.token_hash,
        user.user_id(),
        panel.prefix.clone(),
        None,
        expires_at,
    )
    .await
    .map_err(infrastructure_failure)
}

/// The realms whose authenticator loads `user_type`, or `own` outside a router: the panels that
/// share a user's credentials, so a credential change ends the user's sessions and reset links on
/// each.
pub(super) fn credential_panels(
    cx: &Cx,
    user_type: std::any::TypeId,
    own: &Arc<Realm>,
) -> Vec<Arc<Realm>> {
    let realms = realms(cx);
    if realms.is_empty() {
        return vec![Arc::clone(own)];
    }
    realms
        .into_iter()
        .filter(|realm| {
            realm
                .auth
                .authenticator()
                .is_some_and(|auth| auth.user_type() == user_type)
        })
        .collect()
}

/// Deletes every session `user_id` holds on `panels`, and every [`AuthToken`](super::AuthToken)
/// for one of `purposes` it holds on those that issue them, through `ex`: what a credential
/// change ends, with [`CREDENTIALS`], or a revocation, with [`REVOCATION`].
pub(super) async fn end_credentials(
    ex: &mut dyn toasty::Executor,
    user_id: &str,
    panels: &[Arc<Realm>],
    purposes: &[TokenPurpose],
) -> topcoat::Result<()> {
    let prefixes: Vec<String> = panels.iter().map(|panel| panel.prefix.clone()).collect();
    AuthSession::filter(
        AuthSession::fields()
            .user_id()
            .eq(user_id.to_string())
            .and(AuthSession::fields().panel().in_list(prefixes)),
    )
    .delete()
    .exec(&mut *ex)
    .await
    .map_err(infrastructure_failure)?;
    let issuing: Vec<String> = panels
        .iter()
        .filter(|panel| panel.auth.issues_tokens())
        .map(|panel| panel.prefix.clone())
        .collect();
    if issuing.is_empty() {
        // A panel that issues no token may leave its model unregistered.
        return Ok(());
    }
    super::token::end_all(ex, user_id, Some(issuing), purposes).await
}

/// Replaces every session `user_id` holds, on every panel whose authenticator loads `user_type`,
/// with `session` on the panel and tenant `signed` acts under, and ends its tokens there,
/// through `ex`: what a credential change does inside the transaction that writes it, so the new
/// credential and the revocation commit together.
pub(super) async fn replace_sessions(
    cx: &Cx,
    ex: &mut dyn toasty::Executor,
    signed: &SignedIn,
    user_type: std::any::TypeId,
    session: &session::Session,
) -> topcoat::Result<()> {
    let panels = credential_panels(cx, user_type, &signed.realm);
    let user_id = signed.user.user_id();
    end_credentials(&mut *ex, &user_id, &panels, CREDENTIALS).await?;
    let expires_at = Timestamp::try_from(session.expires_at).map_err(topcoat::Error::from)?;
    insert(
        ex,
        &session.token_hash,
        user_id,
        signed.realm.prefix.clone(),
        signed.tenant,
        expires_at,
    )
    .await
    .map_err(infrastructure_failure)
}

/// Records a session for `user` on the panel `Panel::new(panel)` mounts, as a successful login
/// does, and returns the token its session cookie carries. No credential is checked.
///
/// `tablo::testing`'s `TestClient::sign_in` is the caller: it lets a test act as a signed-in user
/// without a password hash.
#[doc(hidden)]
pub async fn mint_session(
    ex: &mut dyn toasty::Executor,
    panel: &str,
    user: &dyn PanelUser,
) -> topcoat::Result<String> {
    let token = session::Token::random();
    let expires_at = Timestamp::try_from(std::time::SystemTime::now() + SESSION_LIFETIME)
        .map_err(topcoat::Error::from)?;
    insert(
        ex,
        &token.hash(),
        user.user_id(),
        crate::naming::normalize_prefix(panel),
        None,
        expires_at,
    )
    .await?;
    Ok(token.encode())
}

async fn insert(
    ex: &mut dyn toasty::Executor,
    hash: &TokenHash,
    user_id: String,
    panel: String,
    tenant: Option<Uuid>,
    expires_at: Timestamp,
) -> toasty::Result<()> {
    toasty::create!(AuthSession {
        token_hash: token_key(hash),
        user_id,
        panel,
        tenant,
        expires_at,
        created_at: Timestamp::now(),
    })
    .exec(ex)
    .await?;
    Ok(())
}

pub(super) async fn select_tenant(cx: &Cx, tenant: Uuid) -> topcoat::Result<()> {
    let Some(hash) = session::token_hash(cx).await? else {
        return Err(topcoat::router::error::forbidden().into());
    };
    let mut db = crate::db::db(cx)?;
    AuthSession::filter(AuthSession::fields().token_hash().eq(token_key(&hash)))
        .update()
        .tenant(Some(tenant))
        .exec(&mut db)
        .await
        .map_err(infrastructure_failure)?;
    Ok(())
}

pub(super) async fn delete_session(cx: &Cx, hash: &TokenHash) -> topcoat::Result<()> {
    delete_session_row(cx, &token_key(hash)).await
}

/// The session `started` holds, or a new one it then holds: a transaction
/// [`run_serializable`](super::token::run_serializable) runs again records the session the first
/// run gave the browser, rather than one more cookie.
pub(super) async fn start_once(
    cx: &Cx,
    started: &mut Option<session::Session>,
) -> topcoat::Result<session::Session> {
    if let Some(session) = started {
        return Ok(session.clone());
    }
    let session = session::start(cx).await?;
    *started = Some(session.clone());
    Ok(session)
}

/// Ends the session the request presents and starts a new one, so a token presented before a
/// sign-in cannot be replayed after it.
///
/// # Errors
///
/// The opaque sign-in outage when the database cannot answer; any other failure keeps its mapping.
pub(super) async fn fresh_session(cx: &Cx) -> topcoat::Result<session::Session> {
    if let Some(hash) = session::token_hash(cx)
        .await
        .map_err(infrastructure_failure)?
    {
        delete_session(cx, &hash).await?;
    }
    session::start(cx).await.map_err(infrastructure_failure)
}

async fn delete_session_row(cx: &Cx, key: &str) -> topcoat::Result<()> {
    let mut db = crate::db::db(cx)?;
    AuthSession::filter(AuthSession::fields().token_hash().eq(key.to_string()))
        .delete()
        .exec(&mut db)
        .await
        .map_err(infrastructure_failure)?;
    Ok(())
}

/// Revokes every live session of `user_id`, its pending sign-ins, its reset links and its pending
/// email change, on the current panel and on each panel sharing its users, whose authenticator
/// loads the same user type, or on every panel outside any panel; call it whenever a credential
/// changes. A link that proves an address or undoes an email change survives.
///
/// # Errors
///
/// The opaque sign-in outage when the database cannot answer.
pub async fn revoke_sessions_for_user(cx: &Cx, user_id: &str) -> topcoat::Result<()> {
    let mut db = crate::db::db(cx)?;
    if let Some(panel) = current_realm(cx) {
        let panels = match panel.auth.authenticator() {
            Some(auth) => credential_panels(cx, auth.user_type(), panel),
            None => vec![Arc::clone(panel)],
        };
        end_credentials(&mut db, user_id, &panels, REVOCATION).await?;
        wake_bells(
            cx,
            user_id,
            panels.iter().map(|panel| panel.prefix.as_str()),
        );
        return Ok(());
    }
    AuthSession::filter(AuthSession::fields().user_id().eq(user_id.to_string()))
        .delete()
        .exec(&mut db)
        .await
        .map_err(infrastructure_failure)?;
    let realms = realms(cx);
    if realms.iter().any(|realm| realm.auth.issues_tokens()) {
        super::token::end_all(&mut db, user_id, None, REVOCATION).await?;
    }
    wake_bells(
        cx,
        user_id,
        realms.iter().map(|realm| realm.prefix.as_str()),
    );
    Ok(())
}

/// Wakes the bells `user_id` has open on `panels`, so each checks its session again and stops.
fn wake_bells<'a>(cx: &Cx, user_id: &str, panels: impl Iterator<Item = &'a str>) {
    let bus = crate::bus::bus(cx);
    for panel in panels {
        bus.wake(panel, user_id);
    }
}

/// How many expired session rows one sweep drops: the bound that keeps one
/// login from deleting an unbounded number of rows.
pub(super) const SESSION_SWEEP_BATCH: usize = 500;

/// Drops up to [`SESSION_SWEEP_BATCH`] expired session rows on successful login.
pub(super) async fn sweep_expired_sessions(cx: &Cx) -> topcoat::Result<()> {
    let now = Timestamp::now();
    let mut db = crate::db::db(cx)?;
    let expired: Vec<String> = AuthSession::filter(AuthSession::fields().expires_at().le(now))
        .limit(SESSION_SWEEP_BATCH)
        .exec(&mut db)
        .await
        .map_err(infrastructure_failure)?
        .into_iter()
        .map(|row| row.token_hash)
        .collect();
    if expired.is_empty() {
        return Ok(());
    }
    // The expiry is re-checked: the select and the delete are two statements.
    AuthSession::filter(
        AuthSession::fields()
            .token_hash()
            .in_list(expired)
            .and(AuthSession::fields().expires_at().le(now)),
    )
    .delete()
    .exec(&mut db)
    .await
    .map_err(infrastructure_failure)?;
    Ok(())
}

/// Returns the request's live session row, purging it when expired and reading
/// nothing when no session cookie is present.
pub(super) async fn session_row(cx: &Cx) -> topcoat::Result<Option<AuthSession>> {
    let Some(hash) = session::token_hash(cx).await? else {
        return Ok(None);
    };
    let key = token_key(&hash);
    let mut db = crate::db::db(cx)?;
    let row = AuthSession::filter(AuthSession::fields().token_hash().eq(key))
        .first()
        .exec(&mut db)
        .await
        .map_err(infrastructure_failure)?;
    let Some(row) = row else {
        return Ok(None);
    };
    if row.expires_at <= Timestamp::now() {
        delete_session_row(cx, &row.token_hash).await?;
        return Ok(None);
    }
    Ok(Some(row))
}

/// Resolves `row` to its user, purging the row when the user no longer
/// authenticates.
pub(super) async fn session_user(
    cx: &Cx,
    row: AuthSession,
    panel: &Arc<Realm>,
    authenticator: &dyn DynAuthenticator,
) -> topcoat::Result<Option<SignedIn>> {
    match authenticator
        .find_by_id(cx, &row.user_id)
        .await
        .map_err(infrastructure_failure)?
    {
        Some(user) => Ok(Some(SignedIn {
            user,
            realm: Arc::clone(panel),
            tenant: row.tenant,
        })),
        None => {
            delete_session_row(cx, &row.token_hash).await?;
            Ok(None)
        }
    }
}

/// Resolves the request's session into `panel`'s user; a session another panel
/// issued resolves to no one here and stays valid there.
pub(super) async fn resolve(
    cx: &Cx,
    panel: &Arc<Realm>,
    authenticator: &dyn DynAuthenticator,
) -> topcoat::Result<Option<SignedIn>> {
    match session_row(cx).await? {
        Some(row) if row.panel == panel.prefix => session_user(cx, row, panel, authenticator).await,
        _ => Ok(None),
    }
}