Skip to main content

tablo_core/
auth.rs

1//! Authenticates panel users and gates panel routes.
2//!
3//! Gates panels by default with [`PasswordAuth`] or a custom
4//! [`Authenticator`], reads the signed-in
5//! user through [`user`] and [`require_user`], and keeps each panel's [`AuthSession`]s.
6
7pub(crate) mod account;
8mod columns;
9pub(crate) mod config;
10mod email_change;
11pub(crate) mod external;
12mod gate;
13pub(crate) mod hook;
14pub(crate) mod impersonation;
15pub(crate) mod input;
16mod login;
17pub(crate) mod mail;
18pub(crate) mod mount;
19pub(crate) mod oidc;
20mod page;
21pub(crate) mod panel_user;
22pub(crate) mod password;
23pub(crate) mod password_reset;
24pub(crate) mod profile;
25mod realm;
26pub(crate) mod registration;
27pub(crate) mod session;
28pub(crate) mod tenant_profile;
29pub(crate) mod tenant_registration;
30pub(crate) mod throttle;
31mod token;
32#[cfg(feature = "two-factor")]
33pub(crate) mod two_factor;
34pub(crate) mod verification;
35
36use std::{
37    any::{Any, TypeId},
38    sync::Arc,
39};
40
41use topcoat::{
42    context::{Cx, try_context},
43    router::{
44        error::{forbidden, redirect, unauthorized},
45        request::{method, original_headers, original_method, uri},
46    },
47};
48
49use self::realm::realms;
50#[cfg(feature = "testing")]
51pub use self::session::mint_session;
52#[cfg(feature = "two-factor")]
53pub use self::two_factor::{AuthFactor, FactorKind};
54// What the crate root exports, under the paths this module's own code names.
55#[cfg(feature = "two-factor")]
56pub(crate) use self::two_factor::{
57    TwoFactor, offered as two_factor_offered, settings_url as two_factor_url,
58};
59pub use self::{
60    account::normalize_email,
61    columns::ColumnPreference,
62    email_change::{EmailChange, request_email_change},
63    impersonation::{IMPERSONATE_FIELD, impersonate, impersonate_button, impersonator},
64    login::{LOGIN_FIELD, NEXT_FIELD, PASSWORD_FIELD, TENANT_FIELD, safe_next},
65    password::{AdminUser, create_admin, hash_password, verify_password},
66    password_reset::RESET_LIFETIME,
67    registration::{MIN_PASSWORD_CHARS, new_password_errors},
68    session::{
69        AuthSession, SESSION_COOKIE_PREFIX, SESSION_LIFETIME, revoke_sessions_for_user,
70        session_cookie,
71    },
72    throttle::AuthThrottle,
73    token::{AuthToken, TokenPurpose},
74    verification::VERIFICATION_LIFETIME,
75};
76pub(crate) use self::{
77    account::{PasswordAccount, PasswordAuth},
78    columns::{load_choice, save_choice},
79    config::{Auth, AuthConfig},
80    gate::{PagePanelStamp, PanelGate, RuntimeGate, still_signed_in},
81    impersonation::{may_impersonate, stop_url as stop_impersonating_url},
82    login::{logout_url, tenant_url},
83    mail::AuthMail,
84    panel_user::{Authenticator, PanelUser},
85    password::end_changed_credentials,
86    password_reset::PasswordReset,
87    profile::{
88        Profile, ProfileEditor, ProfileField, ProfileUpdate, offered as profile_offered,
89        profile_url,
90    },
91    realm::{
92        AuthHost, CurrentRealm, Host, Realm, SettingsPage, SettingsPaths, current_realm,
93        declared_host, panel_prefix,
94    },
95    registration::{Registrar, SignUp},
96    tenant_profile::{TenantEditor, offered as tenant_profile_offered, tenant_profile_url},
97    tenant_registration::{
98        TenantRegistration, offered as tenant_registration_offered, register_tenant_url,
99    },
100    throttle::LoginThrottle,
101    verification::EmailVerification,
102};
103use crate::{
104    BoxFuture,
105    tenancy::{Membership, TenantId},
106};
107
108/// [`Authenticator`] with its user type erased, as the panel keeps it.
109pub(crate) trait DynAuthenticator: Send + Sync {
110    fn verify<'a>(
111        &'a self,
112        cx: &'a Cx,
113        login: &'a str,
114        password: &'a str,
115    ) -> BoxFuture<'a, topcoat::Result<Option<Arc<dyn PanelUser>>>>;
116    fn find_by_id<'a>(
117        &'a self,
118        cx: &'a Cx,
119        id: &'a str,
120    ) -> BoxFuture<'a, topcoat::Result<Option<Arc<dyn PanelUser>>>>;
121    /// Whether `password` is `user`'s; a user of another type has none.
122    #[cfg(feature = "two-factor")]
123    fn confirm_password<'a>(
124        &'a self,
125        cx: &'a Cx,
126        user: &'a dyn PanelUser,
127        password: &'a str,
128    ) -> BoxFuture<'a, topcoat::Result<bool>>;
129    /// Stores `locale` as `user`'s; a user of another type stores nothing.
130    fn store_locale<'a>(
131        &'a self,
132        cx: &'a Cx,
133        user: &'a dyn PanelUser,
134        locale: &'a topcoat::l10n::Locale,
135    ) -> BoxFuture<'a, topcoat::Result<()>>;
136    /// The [`TypeId`] of [`Authenticator::User`], so mounting knows when the
137    /// shipped [`AdminUser`] must be registered.
138    fn user_type(&self) -> TypeId;
139    /// The name of [`Authenticator::User`], for a message that names it.
140    fn user_type_name(&self) -> &'static str;
141    /// [`Authenticator::changed_credentials`].
142    fn changed_credentials(&self, before: &dyn Any, after: &dyn Any) -> Option<String>;
143}
144
145impl<A: Authenticator> DynAuthenticator for A {
146    fn verify<'a>(
147        &'a self,
148        cx: &'a Cx,
149        login: &'a str,
150        password: &'a str,
151    ) -> BoxFuture<'a, topcoat::Result<Option<Arc<dyn PanelUser>>>> {
152        Box::pin(async move {
153            let user = Authenticator::verify(self, cx, login, password).await?;
154            Ok(user.map(|user| Arc::new(user) as Arc<dyn PanelUser>))
155        })
156    }
157
158    fn find_by_id<'a>(
159        &'a self,
160        cx: &'a Cx,
161        id: &'a str,
162    ) -> BoxFuture<'a, topcoat::Result<Option<Arc<dyn PanelUser>>>> {
163        Box::pin(async move {
164            let user = Authenticator::find_by_id(self, cx, id).await?;
165            Ok(user.map(|user| Arc::new(user) as Arc<dyn PanelUser>))
166        })
167    }
168
169    #[cfg(feature = "two-factor")]
170    fn confirm_password<'a>(
171        &'a self,
172        cx: &'a Cx,
173        user: &'a dyn PanelUser,
174        password: &'a str,
175    ) -> BoxFuture<'a, topcoat::Result<bool>> {
176        Box::pin(async move {
177            let user: &dyn Any = user;
178            match user.downcast_ref::<A::User>() {
179                Some(user) => Authenticator::confirm_password(self, cx, user, password).await,
180                None => Ok(false),
181            }
182        })
183    }
184
185    fn store_locale<'a>(
186        &'a self,
187        cx: &'a Cx,
188        user: &'a dyn PanelUser,
189        locale: &'a topcoat::l10n::Locale,
190    ) -> BoxFuture<'a, topcoat::Result<()>> {
191        Box::pin(async move {
192            let user: &dyn Any = user;
193            match user.downcast_ref::<A::User>() {
194                Some(user) => Authenticator::store_locale(self, cx, user, locale).await,
195                None => Ok(()),
196            }
197        })
198    }
199
200    fn user_type(&self) -> TypeId {
201        TypeId::of::<A::User>()
202    }
203
204    fn user_type_name(&self) -> &'static str {
205        std::any::type_name::<A::User>()
206    }
207
208    fn changed_credentials(&self, before: &dyn Any, after: &dyn Any) -> Option<String> {
209        Authenticator::changed_credentials(self, before, after)
210    }
211}
212
213/// The user a panel's gate resolved, as request `Cx` carries it.
214#[derive(Clone)]
215pub(crate) struct SignedIn {
216    pub(crate) user: Arc<dyn PanelUser>,
217    /// The realm whose session signed the user in: the only panel the user
218    /// is the user of.
219    pub(crate) realm: Arc<Realm>,
220    /// The tenant the session selected, if any. [`tenant_id`](crate::tenant_id)
221    /// honors it only while it is one of the user's memberships.
222    pub(crate) tenant: Option<TenantId>,
223    /// The user who acts as `user` through [`Auth::impersonation`](crate::Auth::impersonation),
224    /// and whom stopping restores; `None` while `user` acts as themselves.
225    pub(crate) impersonator: Option<Arc<dyn PanelUser>>,
226}
227
228impl SignedIn {
229    /// Whether the user may enter the panel whose session signed them in.
230    pub(crate) fn may_enter(&self) -> bool {
231        self.user.can_access_panel(&self.realm.id)
232    }
233
234    /// `cx` with the user signed in, its words in the user's [`locale`](PanelUser::locale) when
235    /// the panel offers a match and the visitor picked none from the shell's language menu, and
236    /// its writes refused while an actor acts as the user under a read-only impersonation.
237    pub(crate) fn sign_into(self, cx: &Cx) -> Cx {
238        let cx = if self.refuses_writes() {
239            cx.with(crate::policy::WritesRefused)
240        } else {
241            cx.clone()
242        };
243        if crate::i18n::chose_locale(&cx) {
244            return cx.with(self);
245        }
246        crate::i18n::addressed_to(&cx, self.user.locale().as_ref()).with(self)
247    }
248
249    /// The tenant the user acts for on a request to their panel: the one the test claims, else the
250    /// one the session selected, else the user's default, else their first, each while it is
251    /// still one of the user's memberships. `None` on a panel that does not act for tenants.
252    pub(crate) fn acting_tenant(&self, cx: &Cx) -> Option<TenantId> {
253        acting_tenant(&self.realm, &*self.user, self.tenant, cx)
254    }
255}
256
257/// The tenant `user` acts for on `realm`, the session having selected `selected`: what
258/// [`SignedIn::acting_tenant`] answers, for a user a session holds beside the one it signs in.
259pub(crate) fn acting_tenant(
260    realm: &Realm,
261    user: &dyn PanelUser,
262    selected: Option<TenantId>,
263    cx: &Cx,
264) -> Option<TenantId> {
265    if !realm.serves_tenants {
266        return None;
267    }
268    let tenants = user.tenants();
269    let member = |tenant: TenantId| tenants.iter().find(|m| m.tenant == tenant);
270    claimed_tenant(cx)
271        .and_then(member)
272        .or_else(|| selected.and_then(member))
273        .or_else(|| user.default_tenant().and_then(member))
274        .or_else(|| tenants.first())
275        .map(|membership| membership.tenant)
276}
277
278/// The tenant a test claims its request acts for.
279fn claimed_tenant(cx: &Cx) -> Option<TenantId> {
280    try_context::<http::request::Parts>(cx)
281        .and_then(|parts| parts.extensions.get::<crate::tenancy::ClaimedTenant>())
282        .map(|claimed| claimed.0)
283}
284
285/// The request's signed-in user on the request's panel, whatever their panel
286/// access. Only the logout route reads a user without access.
287pub(crate) fn resolved(cx: &Cx) -> Option<&SignedIn> {
288    let signed = try_context::<SignedIn>(cx)?;
289    match current_realm(cx) {
290        Some(realm) if !Arc::ptr_eq(&signed.realm, realm) => None,
291        _ => Some(signed),
292    }
293}
294
295/// The request's signed-in user, erased: on the request's panel, with panel
296/// access.
297pub(crate) fn signed(cx: &Cx) -> Option<&SignedIn> {
298    resolved(cx).filter(|signed| signed.may_enter())
299}
300
301/// The signed-in user's membership the request acts under: the tenant the
302/// session selected while it is still one of the user's
303/// [`tenants`](PanelUser::tenants), else the user's
304/// [`default_tenant`](PanelUser::default_tenant), else the first. `None` without a
305/// signed-in user, for a user with no tenant, and when a `Tenant` override
306/// names a tenant the user is not a member of.
307pub fn membership(cx: &Cx) -> Option<&Membership> {
308    let tenant = crate::tenant_id(cx)?;
309    signed(cx)?
310        .user
311        .tenants()
312        .iter()
313        .find(|m| m.tenant == tenant)
314}
315
316/// The tenant of the session's selected membership, else of the user's default, else of their
317/// first: the [`TenantSource`](crate::tenancy::TenantSource) the panel installs. `None` on a panel
318/// that does not act for tenants, which offers no way to see or switch the tenant.
319pub(crate) fn session_tenant(cx: &Cx) -> Option<TenantId> {
320    match signed(cx) {
321        Some(signed) => signed.acting_tenant(cx),
322        None => claimed_tenant(cx),
323    }
324}
325
326/// The signed-in user's [`time_zone`](PanelUser::time_zone), else the request panel's
327/// [`time_zone`](crate::Panel::time_zone): the [`ZoneSource`](crate::values::ZoneSource) the panel
328/// installs.
329pub(crate) fn session_time_zone(cx: &Cx) -> Option<jiff::tz::TimeZone> {
330    signed(cx)
331        .and_then(|signed| signed.user.time_zone())
332        .or_else(|| current_realm(cx).map(|realm| realm.time_zone.clone()))
333}
334
335/// The request panel's catalog: the [`CatalogSource`](crate::i18n::CatalogSource) the panel
336/// installs.
337pub(crate) fn session_catalog(cx: &Cx) -> Option<&crate::i18n::Catalog> {
338    current_realm(cx).map(|realm| &*realm.catalog)
339}
340
341/// The signed-in user, as the app's own user type.
342///
343/// `None` when nobody is signed in to the request's panel, and when the
344/// panel's [`Authenticator`] loads another type than `U` — a helper shared by
345/// two panels with different user types answers `None` on the other one.
346///
347/// When no mounted panel's authenticator loads `U`, that `U` can only answer `None`, so every
348/// check through it denies: the first such call logs an error naming `U` and the types the panels
349/// load. Debug and release builds behave alike.
350///
351/// ```rust
352/// # struct Staff { admin: bool }
353/// # use tablo_core::{PanelUser, auth};
354/// # use topcoat::context::Cx;
355/// # impl PanelUser for Staff {
356/// #     fn user_id(&self) -> String { String::new() }
357/// #     fn display_name(&self) -> &str { "" }
358/// #     fn can_access_panel(&self, _panel: &tablo_core::PanelId) -> bool { true }
359/// # }
360/// fn admins_only(cx: &Cx) -> bool {
361///     auth::user::<Staff>(cx).is_some_and(|staff| staff.admin)
362/// }
363/// ```
364pub fn user<U: PanelUser>(cx: &Cx) -> Option<&U> {
365    let found = signed(cx).and_then(|signed| {
366        let user: &dyn Any = &*signed.user;
367        user.downcast_ref()
368    });
369    if found.is_none() {
370        report_unloaded::<U>(cx);
371    }
372    found
373}
374
375/// Logs, once per type, that no mounted panel loads `U`.
376fn report_unloaded<U: PanelUser>(cx: &Cx) {
377    static REPORTED: std::sync::Mutex<Vec<TypeId>> = std::sync::Mutex::new(Vec::new());
378    let Some(message) = unloaded_type::<U>(cx) else {
379        return;
380    };
381    let mut reported = REPORTED
382        .lock()
383        .unwrap_or_else(std::sync::PoisonError::into_inner);
384    if !reported.contains(&TypeId::of::<U>()) {
385        reported.push(TypeId::of::<U>());
386        tracing::error!("{message}");
387    }
388}
389
390/// Why `auth::user::<U>` can never find a user, when panels sign users in and none of them
391/// loads a `U`.
392fn unloaded_type<U: PanelUser>(cx: &Cx) -> Option<String> {
393    let mut mounted = realms(cx);
394    if mounted.is_empty() {
395        mounted.extend(current_realm(cx).cloned());
396    }
397    let loaded: Vec<&dyn DynAuthenticator> = mounted
398        .iter()
399        .filter_map(|realm| realm.auth.authenticator())
400        .collect();
401    if loaded.is_empty()
402        || loaded
403            .iter()
404            .any(|auth| auth.user_type() == TypeId::of::<U>())
405    {
406        return None;
407    }
408    let names: std::collections::BTreeSet<_> =
409        loaded.iter().map(|auth| auth.user_type_name()).collect();
410    Some(format!(
411        "auth::user::<{}> can never find a user: the mounted panels sign in {}",
412        std::any::type_name::<U>(),
413        names.into_iter().collect::<Vec<_>>().join(", "),
414    ))
415}
416
417/// The person behind the request: the user acting as another through
418/// [impersonation](crate::Impersonation), else the signed-in user; `None` when nobody is signed in
419/// to the request's panel.
420///
421/// What a request did is theirs, so an audit trail names this user, not [`user`]'s.
422///
423/// ```rust
424/// # use tablo_core::auth;
425/// # use topcoat::context::Cx;
426/// fn signed_by(cx: &Cx) -> String {
427///     auth::actor(cx).map_or_else(String::new, |actor| actor.display_name().to_owned())
428/// }
429/// ```
430pub fn actor(cx: &Cx) -> Option<&dyn PanelUser> {
431    signed(cx).map(|signed| &**signed.impersonator.as_ref().unwrap_or(&signed.user))
432}
433
434/// Require the signed-in user, as the app's own user type.
435///
436/// # Errors
437///
438/// Answers per request kind (ADR-0013): pages redirect to the login route with
439/// a same-origin-relative `next`; runtime endpoints, non-GET requests, and
440/// page re-runs (marked POSTs the runtime layer rewrites into GETs) answer
441/// 401. A signed-in user of another type than `U` answers 403, and [`user`] logs a type no
442/// mounted panel loads.
443pub fn require_user<U: PanelUser>(cx: &Cx) -> topcoat::Result<&U> {
444    match signed(cx) {
445        Some(_) => user(cx).ok_or_else(|| forbidden().into()),
446        None => Err(unauthenticated_error(cx)),
447    }
448}
449
450/// Whether a user is signed in to the request's panel.
451pub fn signed_in(cx: &Cx) -> bool {
452    signed(cx).is_some()
453}
454
455/// Whether the request's panel requires a signed-in user.
456///
457/// Outside any panel — an app's own page, or a shard no panel declared — it
458/// answers whether some mounted panel does, so a check there fails closed.
459pub fn enforced(cx: &Cx) -> bool {
460    match current_realm(cx) {
461        Some(realm) => realm.gates(),
462        None => realms(cx).iter().any(|realm| realm.gates()),
463    }
464}
465
466/// Require a signed-in user when the request's panel requires sign-in.
467///
468/// Every panel handler runs it first, and a page, route or shard the app
469/// serves under a panel runs it to answer exactly as the panel's own pages do.
470/// Shards are the case that needs it: Topcoat serves them at its runtime path,
471/// where the page's checks do not run. A form route also verifies its CSRF token with
472/// [`csrf::verify`](crate::csrf::verify).
473///
474/// # Errors
475///
476/// 401, or a redirect to the login page, as [`require_user`] answers.
477pub fn guard(cx: &Cx) -> topcoat::Result<()> {
478    if enforced(cx) && !signed_in(cx) {
479        return Err(unauthenticated_error(cx));
480    }
481    Ok(())
482}
483
484/// The error an unauthenticated request answers with, by request kind.
485fn unauthenticated_error(cx: &Cx) -> topcoat::Error {
486    if page_load(cx) {
487        redirect(login::login_url_with_next(cx)).into()
488    } else {
489        unauthorized().into()
490    }
491}
492
493/// Whether the request loads a page: a `GET` or `HEAD` outside Topcoat's runtime path that is not
494/// a page re-run.
495pub(crate) fn page_load(cx: &Cx) -> bool {
496    let page_method = matches!(*method(cx), http::Method::GET | http::Method::HEAD);
497    // A page re-run reaches the gate as a rewritten GET: Topcoat's runtime
498    // layer rewrites the browser's marked POST into a GET for the page's own
499    // URL. The original request tells it apart from a plain page load.
500    let rerun = !matches!(*original_method(cx), http::Method::GET | http::Method::HEAD)
501        && original_headers(cx).get(&topcoat::runtime::RUNTIME_HEADER) == Some(&RERUN_MARKER);
502    page_method
503        && !rerun
504        && !uri(cx)
505            .path()
506            .starts_with(crate::topcoat_compat::RUNTIME_PREFIX)
507}
508
509/// The panel root: where a completed login or tenant switch lands.
510fn panel_root(cx: &Cx) -> String {
511    panel_prefix(cx)
512}
513
514/// Map a failed auth or session operation to the error the response carries:
515/// [`crate::error::driver_failure`] with the sign-in outage copy.
516///
517/// A driver failure becomes an infrastructure error whose `Display` is
518/// [`UNAVAILABLE_ERROR`], and the driver's own text goes to the log, never to
519/// the page; anything else is app-authored (a custom [`Authenticator`]'s own
520/// error) and keeps its mapping. Every auth and session path maps through
521/// here, which is what keeps a database outage from reading as a rejected
522/// password — and what makes the two distinguishable in the logs: a rejection
523/// is `Ok(None)`, the generic 403 and no error line, while an outage logs the
524/// driver's text.
525fn infrastructure_failure(error: impl Into<topcoat::Error>) -> topcoat::Error {
526    crate::error::driver_failure(error, UNAVAILABLE_ERROR)
527}
528
529/// What a failed login attempt renders when the database behind it could not
530/// answer.
531///
532/// The credential rejection is deliberately non-specific about *why*
533/// credentials were refused, so reusing it for an outage would tell a user
534/// their password was wrong while the database was down — the one place they
535/// would retry uselessly. This copy names the machinery that is down instead,
536/// and like the generic one it never carries driver text: that goes to the
537/// log.
538const UNAVAILABLE_ERROR: &str = "Sign-in is unavailable right now. Try again shortly.";
539
540/// The runtime-header value marking a page re-run POST (`true`, per Topcoat's
541/// page-rerun protocol).
542static RERUN_MARKER: http::HeaderValue = http::HeaderValue::from_static("true");
543
544#[cfg(test)]
545mod tests;