Skip to main content

tablo_core/auth/
password_reset.rs

1//! The panel's password reset: the [`PasswordResetter`] trait that finds an account by email and
2//! sets its password, the [`PasswordReset`] configuration, and the `{prefix}/forgot-password` and
3//! `{prefix}/reset-password` routes.
4
5mod pages;
6
7use std::{any::TypeId, future::Future, marker::PhantomData, time::Duration};
8
9use topcoat::{
10    context::Cx,
11    router::{Body, RouteFuture, error::see_other, response::IntoResponse},
12};
13
14use self::pages::{ForgotAlert, forgot_response, invalid_link, reset_response};
15use super::{
16    LoginThrottle, PanelUser,
17    hook::{AuthEvent, AuthEventKind},
18    infrastructure_failure,
19    login::login_url,
20    mail::{AuthLetterKind, TOKEN_FIELD, after_response, token_from_query},
21    registration::new_password_errors,
22    session::{credential_panels, end_credentials},
23    token::{self, REVOCATION, TokenPurpose, run_serializable},
24};
25use crate::{
26    BoxFuture,
27    auth::realm::{Realm, current_realm, hosted, panel_prefix},
28    flash::set_notification,
29    form::FieldErrors,
30    outcome::Notification,
31};
32
33/// How long a reset link works: one hour, fixed.
34pub const RESET_LIFETIME: Duration = Duration::from_hours(1);
35
36/// How a panel finds the account a password reset names and sets its new password, installed
37/// with [`Auth::password_reset`](super::Auth::password_reset) through a [`PasswordReset`].
38///
39/// [`PasswordAuth`](super::PasswordAuth) resets a [`PasswordAccount`](super::PasswordAccount);
40/// an app whose user table is not one implements it beside its
41/// [`Authenticator`](super::Authenticator), for the same user type. The link goes to the address
42/// [`PanelUser::email`] answers, the one the account stores, never the one the visitor typed: a
43/// lookup that matches loosely, such as a collation folding accents, would otherwise mail one
44/// account's link to another address. An account without one gets no link.
45///
46/// ```rust
47/// # use tablo_core::{PanelUser, PasswordResetter, auth::hash_password};
48/// # use topcoat::context::Cx;
49/// # #[derive(Debug, Clone, toasty::Model)]
50/// # struct Staff {
51/// #     #[key] #[auto] id: uuid::Uuid,
52/// #     #[unique] email: String,
53/// #     password_hash: String,
54/// #     name: String,
55/// # }
56/// # impl PanelUser for Staff {
57/// #     fn user_id(&self) -> String { self.id.to_string() }
58/// #     fn display_name(&self) -> &str { &self.name }
59/// #     fn can_access_panel(&self, _panel: &tablo_core::PanelId) -> bool { true }
60/// #     fn email(&self) -> Option<&str> { Some(&self.email) }
61/// # }
62/// struct StaffAuth;
63///
64/// impl PasswordResetter for StaffAuth {
65///     type User = Staff;
66///
67///     async fn find_by_email(&self, cx: &Cx, email: &str) -> topcoat::Result<Option<Staff>> {
68///         let mut db = tablo_core::db::db(cx)?;
69///         Ok(Staff::filter_by_email(email).first().exec(&mut db).await?)
70///     }
71///
72///     async fn reset_password(
73///         &self,
74///         _cx: &Cx,
75///         user_id: &str,
76///         password: &str,
77///         ex: &mut dyn toasty::Executor,
78///     ) -> topcoat::Result<()> {
79///         let Ok(id) = user_id.parse::<uuid::Uuid>() else {
80///             return Ok(());
81///         };
82///         Staff::filter_by_id(id)
83///             .update()
84///             .password_hash(hash_password(password).await?)
85///             .exec(ex)
86///             .await?;
87///         Ok(())
88///     }
89/// }
90/// ```
91pub trait PasswordResetter: Send + Sync + 'static {
92    /// The account a reset names: the type the panel's [`Authenticator`](super::Authenticator)
93    /// loads, which mounting checks.
94    type User: PanelUser;
95
96    /// The account `email` signs in as, or `None`. The address arrives trimmed, as the visitor
97    /// typed it.
98    fn find_by_email(
99        &self,
100        cx: &Cx,
101        email: &str,
102    ) -> impl Future<Output = topcoat::Result<Option<Self::User>>> + Send;
103
104    /// Set the password of the account [`PanelUser::user_id`] `user_id` names to `password`,
105    /// through the reset's transaction `ex`, which commits when it returns `Ok`. The panel's
106    /// authenticator still loads the account and it may enter the panel; the password is at
107    /// least [`MIN_PASSWORD_CHARS`](super::MIN_PASSWORD_CHARS) long and was typed twice. It may
108    /// run again for one reset when the database aborts the transaction for a concurrent one, so
109    /// it writes only through `ex`.
110    fn reset_password(
111        &self,
112        cx: &Cx,
113        user_id: &str,
114        password: &str,
115        ex: &mut dyn toasty::Executor,
116    ) -> impl Future<Output = topcoat::Result<()>> + Send;
117}
118
119/// The account a reset link is mailed to.
120pub(crate) struct Recipient {
121    address: String,
122    user_id: String,
123    /// The account's [`locale`](PanelUser::locale), which the mail is written in.
124    locale: Option<topcoat::l10n::Locale>,
125}
126
127/// [`PasswordResetter`] with its user type erased, as the panel keeps it.
128pub(crate) trait DynPasswordResetter: Send + Sync {
129    /// Whom to mail a reset link to for `email`, when an account that may enter the panel and
130    /// stores an address signs in as `email`.
131    fn recipient<'a>(
132        &'a self,
133        cx: &'a Cx,
134        panel: &'a crate::PanelId,
135        email: &'a str,
136    ) -> BoxFuture<'a, topcoat::Result<Option<Recipient>>>;
137    fn reset_password<'a>(
138        &'a self,
139        cx: &'a Cx,
140        user_id: &'a str,
141        password: &'a str,
142        ex: &'a mut dyn toasty::Executor,
143    ) -> BoxFuture<'a, topcoat::Result<()>>;
144    /// The [`TypeId`] of [`PasswordResetter::User`], the authenticator's: whose sessions a link
145    /// ends.
146    fn user_type(&self) -> TypeId;
147}
148
149impl<R: PasswordResetter> DynPasswordResetter for R {
150    fn recipient<'a>(
151        &'a self,
152        cx: &'a Cx,
153        panel: &'a crate::PanelId,
154        email: &'a str,
155    ) -> BoxFuture<'a, topcoat::Result<Option<Recipient>>> {
156        Box::pin(async move {
157            let user = self.find_by_email(cx, email).await?;
158            let Some(user) = user.filter(|user| user.can_access_panel(panel)) else {
159                return Ok(None);
160            };
161            let Some(email) = user.email() else {
162                // The page still answers that a link is on its way: it never says who exists.
163                tracing::warn!(
164                    user = std::any::type_name::<R::User>(),
165                    "a password reset found an account whose `PanelUser::email` is `None`"
166                );
167                return Ok(None);
168            };
169            Ok(Some(Recipient {
170                address: email.to_string(),
171                user_id: user.user_id(),
172                locale: user.locale(),
173            }))
174        })
175    }
176
177    fn reset_password<'a>(
178        &'a self,
179        cx: &'a Cx,
180        user_id: &'a str,
181        password: &'a str,
182        ex: &'a mut dyn toasty::Executor,
183    ) -> BoxFuture<'a, topcoat::Result<()>> {
184        Box::pin(PasswordResetter::reset_password(
185            self, cx, user_id, password, ex,
186        ))
187    }
188
189    fn user_type(&self) -> TypeId {
190        TypeId::of::<R::User>()
191    }
192}
193
194/// A panel's password reset, installed with
195/// [`Auth::password_reset`](super::Auth::password_reset): the [`PasswordResetter`], and how many
196/// links one address may ask for. The links go out through the panel's
197/// [`AuthMail`](super::AuthMail).
198///
199/// ```rust
200/// use tablo_core::{Auth, AuthMail, PasswordAuth, PasswordReset};
201/// use topcoat::mail::Mailbox;
202///
203/// # fn main() -> Result<(), topcoat::mail::AddressError> {
204/// let auth = Auth::password()
205///     .mail(AuthMail::new(
206///         Mailbox::new("no-reply@example.com")?,
207///         "https://admin.example.com",
208///     ))
209///     .password_reset(PasswordReset::new(PasswordAuth::new()));
210/// # let _ = auth;
211/// # Ok(())
212/// # }
213/// ```
214///
215/// `U` is the user type the resetter loads; [`Auth`](crate::Auth) takes only one over the type its
216/// authenticator loads.
217pub struct PasswordReset<U> {
218    resetter: Box<dyn DynPasswordResetter>,
219    pub(in crate::auth) throttle: LoginThrottle,
220    user: PhantomData<fn() -> U>,
221}
222
223impl<U: PanelUser> PasswordReset<U> {
224    /// Resets passwords through `resetter`.
225    #[must_use]
226    pub fn new(resetter: impl PasswordResetter<User = U>) -> Self {
227        Self {
228            resetter: Box::new(resetter),
229            throttle: LoginThrottle::new(3, Duration::from_mins(15)),
230            user: PhantomData,
231        }
232    }
233
234    /// How many reset links one email address may request in a window, from any client;
235    /// defaults to three in fifteen minutes. Every request that names an address counts, whether
236    /// or not an account uses it. A limit per client belongs at the proxy.
237    #[must_use]
238    pub fn throttle(mut self, throttle: LoginThrottle) -> Self {
239        self.throttle = throttle;
240        self
241    }
242
243    /// The same declaration, its user type checked by [`Auth`](crate::Auth).
244    pub(crate) fn erase(self) -> PasswordReset<()> {
245        PasswordReset {
246            resetter: self.resetter,
247            throttle: self.throttle,
248            user: PhantomData,
249        }
250    }
251}
252
253impl PasswordReset<()> {
254    pub(crate) fn resetter(&self) -> &dyn DynPasswordResetter {
255        &*self.resetter
256    }
257}
258
259impl<U> std::fmt::Debug for PasswordReset<U> {
260    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
261        f.debug_struct("PasswordReset")
262            .field("throttle", &self.throttle)
263            .finish_non_exhaustive()
264    }
265}
266
267/// The key the forgot-password form posts the address under.
268const EMAIL_FIELD: &str = "email";
269/// The keys the reset form's password controls post under, as [`new_password_errors`] names
270/// them.
271const PASSWORD_FIELD: &str = "password";
272const CONFIRMATION_FIELD: &str = "password_confirmation";
273
274/// Where the panel's forgot-password page lives: `{prefix}/forgot-password`.
275pub(crate) fn forgot_url(cx: &Cx) -> String {
276    format!("{}/forgot-password", panel_prefix(cx))
277}
278
279/// Where the panel's reset page lives: `{prefix}/reset-password`.
280pub(crate) fn reset_url(cx: &Cx) -> String {
281    format!("{}/reset-password", panel_prefix(cx))
282}
283
284/// Whether the request's panel installs a [`PasswordReset`].
285pub(crate) fn offered(cx: &Cx) -> bool {
286    current_realm(cx).is_some_and(|panel| panel.auth.reset().is_some())
287}
288
289/// `GET {prefix}/forgot-password` — the form asking for an email address.
290pub(super) fn forgot_page(cx: &Cx, _body: Body) -> RouteFuture<'_> {
291    Box::pin(async move { forgot_response(cx, "", &FieldErrors::new(), None).await })
292}
293
294/// `POST {prefix}/forgot-password` — mail a reset link to the account the address names, then
295/// answer the same whether one does or not.
296pub(super) fn forgot_post(cx: &Cx, body: Body) -> RouteFuture<'_> {
297    Box::pin(async move {
298        let panel = current_realm(cx).ok_or_else(topcoat::router::error::not_found)?;
299        let reset = panel
300            .auth
301            .reset()
302            .ok_or_else(topcoat::router::error::not_found)?;
303        let form = crate::auth::input::read_form(cx, body).await?;
304        crate::csrf::verify(cx, form.last(crate::csrf::FIELD_NAME))?;
305        let email = form.last(EMAIL_FIELD).map_or("", str::trim);
306        if email.is_empty() {
307            let mut errors = FieldErrors::new();
308            errors.add_field(EMAIL_FIELD, crate::text!("tablo-reset-enter-email"));
309            return forgot_response(cx, email, &errors, None).await;
310        }
311        if !reset
312            .throttle
313            .attempt(cx, "password-reset", email, None)
314            .await?
315        {
316            tracing::warn!(panel = %panel.prefix, "password reset request throttled");
317            return forgot_response(cx, email, &FieldErrors::new(), Some(ForgotAlert::Throttled))
318                .await;
319        }
320        let recipient = match reset.resetter().recipient(cx, &panel.id, email).await {
321            Ok(recipient) => recipient,
322            Err(error) => {
323                let error = infrastructure_failure(error);
324                if crate::error::TabloError::is_infrastructure(&error) {
325                    return forgot_response(
326                        cx,
327                        email,
328                        &FieldErrors::new(),
329                        Some(ForgotAlert::Unavailable),
330                    )
331                    .await;
332                }
333                return Err(error);
334            }
335        };
336        if let Some(recipient) = recipient {
337            after_response(cx, "password reset link", move |cx, panel| async move {
338                mail_link(&cx, &panel, &recipient).await
339            });
340        }
341        set_notification(
342            cx,
343            Notification::success(crate::t!(cx, "tablo-reset-sent"))
344                .description(crate::t!(cx, "tablo-reset-sent-description")),
345        );
346        see_other(login_url(cx)).into_response(cx)
347    })
348}
349
350/// Records a new reset token for `recipient` on `panel`, replacing the account's earlier ones
351/// there, and mails its link to the account's address, in its locale.
352async fn mail_link(cx: &Cx, panel: &Realm, recipient: &Recipient) -> topcoat::Result<()> {
353    let Recipient {
354        address,
355        user_id,
356        locale,
357    } = recipient;
358    let cx = &crate::i18n::addressed_to(cx, locale.as_ref());
359    let mail = panel
360        .auth
361        .auth_mail()
362        .ok_or_else(topcoat::router::error::not_found)?;
363    let brand = hosted(cx)?.brand_name(cx);
364    let minutes = RESET_LIFETIME.as_secs() / 60;
365    token::issue_mailed(
366        cx,
367        mail,
368        TokenPurpose::PasswordReset,
369        user_id,
370        None,
371        RESET_LIFETIME,
372        |token| {
373            mail.letter(
374                AuthLetterKind::PasswordReset,
375                address,
376                crate::t!(cx, "tablo-reset-mail-subject", brand = brand.clone()),
377                crate::t!(
378                    cx,
379                    "tablo-reset-mail-body",
380                    brand = brand.clone(),
381                    minutes = minutes,
382                    link = mail.link(&reset_url(cx), token)
383                ),
384                Some(RESET_LIFETIME),
385            )
386        },
387    )
388    .await
389}
390
391/// The live reset token `encoded` names on the request's panel.
392async fn live_token(
393    cx: &Cx,
394    ex: &mut dyn toasty::Executor,
395    encoded: &str,
396) -> topcoat::Result<Option<token::AuthToken>> {
397    token::live(cx, ex, TokenPurpose::PasswordReset, encoded).await
398}
399
400/// `GET {prefix}/reset-password?token=…` — the form choosing a new password, or the page saying
401/// the link no longer works.
402pub(super) fn reset_page(cx: &Cx, _body: Body) -> RouteFuture<'_> {
403    Box::pin(async move {
404        let token = token_from_query(cx);
405        let mut db = crate::db::db(cx)?;
406        let live = live_token(cx, &mut db, &token).await?;
407        if live.is_none() {
408            return invalid_link(cx).await;
409        }
410        reset_response(cx, &token, &FieldErrors::new()).await
411    })
412}
413
414/// `POST {prefix}/reset-password` — set the new password, end every session and reset link the
415/// account holds, and send it to sign in.
416pub(super) fn reset_post(cx: &Cx, body: Body) -> RouteFuture<'_> {
417    Box::pin(async move {
418        let panel = current_realm(cx).ok_or_else(topcoat::router::error::not_found)?;
419        let reset = panel
420            .auth
421            .reset()
422            .ok_or_else(topcoat::router::error::not_found)?;
423        let form = crate::auth::input::read_form(cx, body).await?;
424        crate::csrf::verify(cx, form.last(crate::csrf::FIELD_NAME))?;
425        let token = form.last(TOKEN_FIELD).unwrap_or_default().to_string();
426        let password = form.last(PASSWORD_FIELD).unwrap_or_default();
427        let confirmation = form.last(CONFIRMATION_FIELD).unwrap_or_default();
428        let mut db = crate::db::db(cx)?;
429        let Some(row) = live_token(cx, &mut db, &token).await? else {
430            return invalid_link(cx).await;
431        };
432        // The account is loaded before the transaction opens: the authenticator reads through a
433        // connection of its own.
434        if !may_enter(cx, panel, &row.user_id).await? {
435            return invalid_link(cx).await;
436        }
437        let errors = new_password_errors(password, confirmation);
438        if !errors.is_empty() {
439            return reset_response(cx, &token, &errors).await;
440        }
441        let reset_done = run_serializable!(cx, |tx| async {
442            // Read again inside the transaction: of two requests racing on one link, one commits.
443            if live_token(cx, tx, &token).await?.is_none() {
444                return Ok(false);
445            }
446            reset
447                .resetter()
448                .reset_password(cx, &row.user_id, password, tx)
449                .await
450                .map_err(infrastructure_failure)?;
451            let user_type = reset.resetter().user_type();
452            let panels = credential_panels(cx, user_type, panel);
453            end_credentials(tx, &row.user_id, &panels, REVOCATION).await?;
454            let event =
455                AuthEvent::unsigned(AuthEventKind::PasswordReset, &panel.id, Some(&row.user_id));
456            super::hook::run(cx, &panel.auth_hooks, &event, tx).await?;
457            Ok(true)
458        })?;
459        if !reset_done {
460            return invalid_link(cx).await;
461        }
462        set_notification(
463            cx,
464            Notification::success(crate::t!(cx, "tablo-reset-done"))
465                .description(crate::t!(cx, "tablo-reset-done-description")),
466        );
467        see_other(login_url(cx)).into_response(cx)
468    })
469}
470
471/// Whether the account `user_id` names still signs in to `panel` and may enter it: a link mailed
472/// before the account was deactivated or deleted resets nothing.
473async fn may_enter(cx: &Cx, panel: &Realm, user_id: &str) -> topcoat::Result<bool> {
474    let Some(authenticator) = panel.auth.authenticator() else {
475        return Ok(false);
476    };
477    let user = authenticator
478        .find_by_id(cx, user_id)
479        .await
480        .map_err(infrastructure_failure)?;
481    Ok(user.is_some_and(|user| user.can_access_panel(&panel.id)))
482}
483
484/// The mistakes in a panel's [`Auth::password_reset`](super::Auth::password_reset): a reset without
485/// auth, and a resetter whose user is not the authenticator's. What its mail needs,
486/// [`super::mail_declaration_errors`] checks.
487pub(super) fn declaration_errors(auth: &super::AuthConfig) -> Vec<crate::DeclarationErrorKind> {
488    use crate::{DeclarationErrorKind, declaration::ResetFault};
489
490    if auth.reset.is_some() && auth.authenticator().is_none() {
491        return vec![DeclarationErrorKind::PasswordReset(
492            ResetFault::AuthDisabled,
493        )];
494    }
495    Vec::new()
496}