tablo-core 0.10.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
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
//! Authenticates panel users and gates panel routes.
//!
//! Gates panels by default with [`PasswordAuth`] or a custom
//! [`Authenticator`], reads the signed-in
//! user through [`user`] and [`require_user`], and keeps each panel's [`AuthSession`]s.

mod columns;
pub(crate) mod config;
mod email_change;
pub(crate) mod external;
mod gate;
pub(crate) mod impersonation;
pub(crate) mod input;
mod login;
pub(crate) mod mail;
pub(crate) mod mount;
pub(crate) mod oidc;
mod page;
pub(crate) mod panel_user;
pub(crate) mod password;
pub(crate) mod password_reset;
pub(crate) mod profile;
mod realm;
pub(crate) mod registration;
mod session;
mod tenant_profile;
pub(crate) mod tenant_registration;
pub(crate) mod throttle;
mod token;
pub(crate) mod two_factor;
pub(crate) mod verification;

use std::{
    any::{Any, TypeId},
    sync::Arc,
};

use topcoat::{
    context::{Cx, try_context},
    router::{
        error::{forbidden, redirect, unauthorized},
        request::{method, original_headers, original_method, uri},
    },
};

use self::realm::realms;
pub use self::{
    columns::ColumnPreference,
    email_change::{EmailChange, request_email_change},
    impersonation::{IMPERSONATE_FIELD, impersonate_button, impersonator},
    login::{LOGIN_FIELD, NEXT_FIELD, PASSWORD_FIELD, TENANT_FIELD, safe_next},
    password::{AdminUser, create_admin, hash_password, verify_password},
    password_reset::{PasswordResetter, RESET_LIFETIME},
    registration::{MIN_PASSWORD_CHARS, new_password_errors},
    session::{
        AuthSession, SESSION_COOKIE_PREFIX, SESSION_LIFETIME, mint_session,
        revoke_sessions_for_user, session_cookie,
    },
    tenant_profile::TenantEditor,
    tenant_registration::TenantRegistrar,
    throttle::AuthThrottle,
    token::{AuthToken, TokenPurpose},
    two_factor::{AuthFactor, FactorKind},
    verification::{EmailVerifier, VERIFICATION_LIFETIME},
};
// What the crate root exports, under the paths this module's own code names.
pub(crate) use self::{
    columns::{load_choice, save_choice},
    config::{Auth, AuthConfig},
    gate::{PagePanelStamp, PanelGate, RuntimeGate, still_signed_in},
    impersonation::{may_impersonate, start as impersonate, stop_url as stop_impersonating_url},
    login::{logout_url, tenant_url},
    mail::AuthMail,
    panel_user::{Authenticator, PanelUser},
    password::{PasswordAuth, end_changed_credentials},
    password_reset::PasswordReset,
    profile::{Profile, ProfileEditor, ProfileUpdate, offered as profile_offered, profile_url},
    realm::{
        AuthHost, CurrentRealm, Host, Realm, SettingsPage, SettingsPaths, current_realm,
        panel_prefix,
    },
    registration::{Registrar, SignUp},
    tenant_profile::{offered as tenant_profile_offered, tenant_profile_url},
    tenant_registration::{
        TenantRegistration, offered as tenant_registration_offered, register_tenant_url,
    },
    throttle::LoginThrottle,
    two_factor::{TwoFactor, offered as two_factor_offered, settings_url as two_factor_url},
    verification::EmailVerification,
};
use crate::{
    BoxFuture,
    tenancy::{Membership, TenantId},
};

/// [`Authenticator`] with its user type erased, as the panel keeps it.
pub(crate) trait DynAuthenticator: Send + Sync {
    fn verify<'a>(
        &'a self,
        cx: &'a Cx,
        login: &'a str,
        password: &'a str,
    ) -> BoxFuture<'a, topcoat::Result<Option<Arc<dyn PanelUser>>>>;
    fn find_by_id<'a>(
        &'a self,
        cx: &'a Cx,
        id: &'a str,
    ) -> BoxFuture<'a, topcoat::Result<Option<Arc<dyn PanelUser>>>>;
    /// Whether `password` is `user`'s; a user of another type has none.
    fn confirm_password<'a>(
        &'a self,
        cx: &'a Cx,
        user: &'a dyn PanelUser,
        password: &'a str,
    ) -> BoxFuture<'a, topcoat::Result<bool>>;
    /// Stores `locale` as `user`'s; a user of another type stores nothing.
    fn store_locale<'a>(
        &'a self,
        cx: &'a Cx,
        user: &'a dyn PanelUser,
        locale: &'a topcoat::l10n::Locale,
    ) -> BoxFuture<'a, topcoat::Result<()>>;
    /// The [`TypeId`] of [`Authenticator::User`], so mounting knows when the
    /// shipped [`AdminUser`] must be registered.
    fn user_type(&self) -> TypeId;
    /// The name of [`Authenticator::User`], for a message that names it.
    fn user_type_name(&self) -> &'static str;
}

impl<A: Authenticator> DynAuthenticator for A {
    fn verify<'a>(
        &'a self,
        cx: &'a Cx,
        login: &'a str,
        password: &'a str,
    ) -> BoxFuture<'a, topcoat::Result<Option<Arc<dyn PanelUser>>>> {
        Box::pin(async move {
            let user = Authenticator::verify(self, cx, login, password).await?;
            Ok(user.map(|user| Arc::new(user) as Arc<dyn PanelUser>))
        })
    }

    fn find_by_id<'a>(
        &'a self,
        cx: &'a Cx,
        id: &'a str,
    ) -> BoxFuture<'a, topcoat::Result<Option<Arc<dyn PanelUser>>>> {
        Box::pin(async move {
            let user = Authenticator::find_by_id(self, cx, id).await?;
            Ok(user.map(|user| Arc::new(user) as Arc<dyn PanelUser>))
        })
    }

    fn confirm_password<'a>(
        &'a self,
        cx: &'a Cx,
        user: &'a dyn PanelUser,
        password: &'a str,
    ) -> BoxFuture<'a, topcoat::Result<bool>> {
        Box::pin(async move {
            let user: &dyn Any = user;
            match user.downcast_ref::<A::User>() {
                Some(user) => Authenticator::confirm_password(self, cx, user, password).await,
                None => Ok(false),
            }
        })
    }

    fn store_locale<'a>(
        &'a self,
        cx: &'a Cx,
        user: &'a dyn PanelUser,
        locale: &'a topcoat::l10n::Locale,
    ) -> BoxFuture<'a, topcoat::Result<()>> {
        Box::pin(async move {
            let user: &dyn Any = user;
            match user.downcast_ref::<A::User>() {
                Some(user) => Authenticator::store_locale(self, cx, user, locale).await,
                None => Ok(()),
            }
        })
    }

    fn user_type(&self) -> TypeId {
        TypeId::of::<A::User>()
    }

    fn user_type_name(&self) -> &'static str {
        std::any::type_name::<A::User>()
    }
}

/// The user a panel's gate resolved, as request `Cx` carries it.
#[derive(Clone)]
pub(crate) struct SignedIn {
    pub(crate) user: Arc<dyn PanelUser>,
    /// The realm whose session signed the user in: the only panel the user
    /// is the user of.
    pub(crate) realm: Arc<Realm>,
    /// The tenant the session selected, if any. [`tenant_id`](crate::tenant_id)
    /// honors it only while it is one of the user's memberships.
    pub(crate) tenant: Option<TenantId>,
    /// The user who acts as `user` through [`Auth::impersonation`](crate::Auth::impersonation),
    /// and whom stopping restores; `None` while `user` acts as themselves.
    pub(crate) impersonator: Option<Arc<dyn PanelUser>>,
}

impl SignedIn {
    /// Whether the user may enter the panel whose session signed them in.
    pub(crate) fn may_enter(&self) -> bool {
        self.user.can_access_panel(&self.realm.prefix)
    }

    /// `cx` with the user signed in, its words in the user's [`locale`](PanelUser::locale) when
    /// the panel offers a match and the visitor picked none from the shell's language menu.
    pub(crate) fn sign_into(self, cx: &Cx) -> Cx {
        if crate::i18n::chose_locale(cx) {
            return cx.with(self);
        }
        crate::i18n::addressed_to(cx, self.user.locale().as_ref()).with(self)
    }
}

/// The request's signed-in user on the request's panel, whatever their panel
/// access. Only the logout route reads a user without access.
pub(crate) fn resolved(cx: &Cx) -> Option<&SignedIn> {
    let signed = try_context::<SignedIn>(cx)?;
    match current_realm(cx) {
        Some(realm) if !Arc::ptr_eq(&signed.realm, realm) => None,
        _ => Some(signed),
    }
}

/// The request's signed-in user, erased: on the request's panel, with panel
/// access.
pub(crate) fn signed(cx: &Cx) -> Option<&SignedIn> {
    resolved(cx).filter(|signed| signed.may_enter())
}

/// The signed-in user's membership the request acts under: the tenant the
/// session selected while it is still one of the user's
/// [`tenants`](PanelUser::tenants), else the user's
/// [`default_tenant`](PanelUser::default_tenant), else the first. `None` without a
/// signed-in user, for a user with no tenant, and when a `Tenant` override
/// names a tenant the user is not a member of.
pub fn membership(cx: &Cx) -> Option<&Membership> {
    let tenant = crate::tenant_id(cx)?;
    signed(cx)?
        .user
        .tenants()
        .iter()
        .find(|m| m.tenant == tenant)
}

/// The tenant of the session's selected membership, else of the user's default, else of their
/// first: the [`TenantSource`](crate::tenancy::TenantSource) the panel installs. `None` on a panel
/// that does not act for tenants, which offers no way to see or switch the tenant.
pub(crate) fn session_tenant(cx: &Cx) -> Option<TenantId> {
    let claimed = try_context::<http::request::Parts>(cx)
        .and_then(|parts| parts.extensions.get::<crate::tenancy::ClaimedTenant>())
        .map(|claimed| claimed.0);
    let Some(signed) = signed(cx) else {
        return claimed;
    };
    if !signed.realm.serves_tenants {
        return None;
    }
    let tenants = signed.user.tenants();
    let member = |tenant: TenantId| tenants.iter().find(|m| m.tenant == tenant);
    claimed
        .and_then(member)
        .or_else(|| signed.tenant.and_then(member))
        .or_else(|| signed.user.default_tenant().and_then(member))
        .or_else(|| tenants.first())
        .map(|membership| membership.tenant)
}

/// The signed-in user's [`time_zone`](PanelUser::time_zone), else the request panel's
/// [`time_zone`](crate::Panel::time_zone): the [`ZoneSource`](crate::values::ZoneSource) the panel
/// installs.
pub(crate) fn session_time_zone(cx: &Cx) -> Option<jiff::tz::TimeZone> {
    signed(cx)
        .and_then(|signed| signed.user.time_zone())
        .or_else(|| current_realm(cx).map(|realm| realm.time_zone.clone()))
}

/// The request panel's catalog: the [`CatalogSource`](crate::i18n::CatalogSource) the panel
/// installs.
pub(crate) fn session_catalog(cx: &Cx) -> Option<&crate::i18n::Catalog> {
    current_realm(cx).map(|realm| &*realm.catalog)
}

/// The signed-in user, as the app's own user type.
///
/// `None` when nobody is signed in to the request's panel, and when the
/// panel's [`Authenticator`] loads another type than `U` — a helper shared by
/// two panels with different user types answers `None` on the other one.
///
/// When no mounted panel's authenticator loads `U`, that `U` can only answer `None`, so every
/// check through it denies: the first such call logs an error naming `U` and the types the panels
/// load. Debug and release builds behave alike.
///
/// ```rust
/// # struct Staff { admin: bool }
/// # use tablo_core::{PanelUser, auth};
/// # use topcoat::context::Cx;
/// # impl PanelUser for Staff {
/// #     fn user_id(&self) -> String { String::new() }
/// #     fn display_name(&self) -> &str { "" }
/// #     fn can_access_panel(&self, _panel: &str) -> bool { true }
/// # }
/// fn admins_only(cx: &Cx) -> bool {
///     auth::user::<Staff>(cx).is_some_and(|staff| staff.admin)
/// }
/// ```
pub fn user<U: PanelUser>(cx: &Cx) -> Option<&U> {
    let found = signed(cx).and_then(|signed| {
        let user: &dyn Any = &*signed.user;
        user.downcast_ref()
    });
    if found.is_none() {
        report_unloaded::<U>(cx);
    }
    found
}

/// Logs, once per type, that no mounted panel loads `U`.
fn report_unloaded<U: PanelUser>(cx: &Cx) {
    static REPORTED: std::sync::Mutex<Vec<TypeId>> = std::sync::Mutex::new(Vec::new());
    let Some(message) = unloaded_type::<U>(cx) else {
        return;
    };
    let mut reported = REPORTED
        .lock()
        .unwrap_or_else(std::sync::PoisonError::into_inner);
    if !reported.contains(&TypeId::of::<U>()) {
        reported.push(TypeId::of::<U>());
        tracing::error!("{message}");
    }
}

/// Why `auth::user::<U>` can never find a user, when panels sign users in and none of them
/// loads a `U`.
fn unloaded_type<U: PanelUser>(cx: &Cx) -> Option<String> {
    let mut mounted = realms(cx);
    if mounted.is_empty() {
        mounted.extend(current_realm(cx).cloned());
    }
    let loaded: Vec<&dyn DynAuthenticator> = mounted
        .iter()
        .filter_map(|realm| realm.auth.authenticator())
        .collect();
    if loaded.is_empty()
        || loaded
            .iter()
            .any(|auth| auth.user_type() == TypeId::of::<U>())
    {
        return None;
    }
    let names: std::collections::BTreeSet<_> =
        loaded.iter().map(|auth| auth.user_type_name()).collect();
    Some(format!(
        "auth::user::<{}> can never find a user: the mounted panels sign in {}",
        std::any::type_name::<U>(),
        names.into_iter().collect::<Vec<_>>().join(", "),
    ))
}

/// Require the signed-in user, as the app's own user type.
///
/// # Errors
///
/// Answers per request kind (ADR-0013): pages redirect to the login route with
/// a same-origin-relative `next`; runtime endpoints, non-GET requests, and
/// page re-runs (marked POSTs the runtime layer rewrites into GETs) answer
/// 401. A signed-in user of another type than `U` answers 403, and [`user`] logs a type no
/// mounted panel loads.
pub fn require_user<U: PanelUser>(cx: &Cx) -> topcoat::Result<&U> {
    match signed(cx) {
        Some(_) => user(cx).ok_or_else(|| forbidden().into()),
        None => Err(unauthenticated_error(cx)),
    }
}

/// Whether a user is signed in to the request's panel.
pub fn signed_in(cx: &Cx) -> bool {
    signed(cx).is_some()
}

/// Whether the request's panel requires a signed-in user.
///
/// Outside any panel — an app's own page, or a shard no panel declared — it
/// answers whether some mounted panel does, so a check there fails closed.
pub fn enforced(cx: &Cx) -> bool {
    match current_realm(cx) {
        Some(realm) => realm.gates(),
        None => realms(cx).iter().any(|realm| realm.gates()),
    }
}

/// Require a signed-in user when the request's panel requires sign-in.
///
/// Every panel handler runs it first, and a page, route or shard the app
/// serves under a panel runs it to answer exactly as the panel's own pages do.
/// Shards are the case that needs it: Topcoat serves them at its runtime path,
/// where the page's checks do not run. A form route also verifies its CSRF token with
/// [`csrf::verify`](crate::csrf::verify).
///
/// # Errors
///
/// 401, or a redirect to the login page, as [`require_user`] answers.
pub fn guard(cx: &Cx) -> topcoat::Result<()> {
    if enforced(cx) && !signed_in(cx) {
        return Err(unauthenticated_error(cx));
    }
    Ok(())
}

/// The error an unauthenticated request answers with, by request kind.
fn unauthenticated_error(cx: &Cx) -> topcoat::Error {
    if page_load(cx) {
        redirect(login::login_url_with_next(cx)).into()
    } else {
        unauthorized().into()
    }
}

/// Whether the request loads a page: a `GET` or `HEAD` outside Topcoat's runtime path that is not
/// a page re-run.
pub(crate) fn page_load(cx: &Cx) -> bool {
    let page_method = matches!(*method(cx), http::Method::GET | http::Method::HEAD);
    // A page re-run reaches the gate as a rewritten GET: Topcoat's runtime
    // layer rewrites the browser's marked POST into a GET for the page's own
    // URL. The original request tells it apart from a plain page load.
    let rerun = !matches!(*original_method(cx), http::Method::GET | http::Method::HEAD)
        && original_headers(cx).get(&topcoat::runtime::RUNTIME_HEADER) == Some(&RERUN_MARKER);
    page_method
        && !rerun
        && !uri(cx)
            .path()
            .starts_with(crate::topcoat_compat::RUNTIME_PREFIX)
}

/// The panel root: where a completed login or tenant switch lands.
fn panel_root(cx: &Cx) -> String {
    panel_prefix(cx)
}

/// Map a failed auth or session operation to the error the response carries:
/// [`crate::error::driver_failure`] with the sign-in outage copy.
///
/// A driver failure becomes an infrastructure error whose `Display` is
/// [`UNAVAILABLE_ERROR`], and the driver's own text goes to the log, never to
/// the page; anything else is app-authored (a custom [`Authenticator`]'s own
/// error) and keeps its mapping. Every auth and session path maps through
/// here, which is what keeps a database outage from reading as a rejected
/// password — and what makes the two distinguishable in the logs: a rejection
/// is `Ok(None)`, the generic 403 and no error line, while an outage logs the
/// driver's text.
fn infrastructure_failure(error: impl Into<topcoat::Error>) -> topcoat::Error {
    crate::error::driver_failure(error, UNAVAILABLE_ERROR)
}

/// What a failed login attempt renders when the database behind it could not
/// answer.
///
/// The credential rejection is deliberately non-specific about *why*
/// credentials were refused, so reusing it for an outage would tell a user
/// their password was wrong while the database was down — the one place they
/// would retry uselessly. This copy names the machinery that is down instead,
/// and like the generic one it never carries driver text: that goes to the
/// log.
const UNAVAILABLE_ERROR: &str = "Sign-in is unavailable right now. Try again shortly.";

/// The runtime-header value marking a page re-run POST (`true`, per Topcoat's
/// page-rerun protocol).
static RERUN_MARKER: http::HeaderValue = http::HeaderValue::from_static("true");

#[cfg(test)]
mod tests;