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
//! The panel's email verification: the [`EmailVerifier`] trait that records an address an account
//! proved it reads, the [`EmailVerification`] configuration, and the `{prefix}/verify-email`
//! routes.

mod pages;

use std::{
    any::{Any, TypeId},
    future::Future,
    marker::PhantomData,
    time::Duration,
};

use topcoat::{
    context::Cx,
    router::{
        Body, RouteFuture,
        error::{see_other, too_many_requests},
        response::IntoResponse,
    },
};

pub(super) use self::pages::invalid_link;
use self::pages::notice;
use super::{
    LoginThrottle, PanelUser, infrastructure_failure,
    login::login_url,
    mail::{after_response, private, token_from_query},
    panel_root, resolved,
    session::resolve,
    token::{self, TokenPurpose, run_serializable},
    unauthenticated_error,
};
use crate::{
    BoxFuture,
    auth::realm::{Realm, current_realm, hosted, panel_prefix},
    flash::set_notification,
    outcome::Notification,
};

/// How long a verification link works: one day, fixed.
pub const VERIFICATION_LIFETIME: Duration = Duration::from_hours(24);

/// How a panel records that an account reads the address it stores, installed with
/// [`Auth::email_verification`](super::Auth::email_verification) through an
/// [`EmailVerification`].
///
/// The link goes to the address [`PanelUser::email`] answers. The shipped
/// [`PasswordAuth`](super::PasswordAuth) verifies an [`AdminUser`](super::AdminUser); an app with
/// its own user table implements it beside its [`Authenticator`](super::Authenticator), for the
/// same user type:
///
/// ```rust
/// # use tablo_core::{PanelUser, auth::EmailVerifier};
/// # use topcoat::context::Cx;
/// # #[derive(Debug, Clone, toasty::Model)]
/// # struct Staff {
/// #     #[key] #[auto] id: uuid::Uuid,
/// #     email: String,
/// #     email_verified_at: Option<jiff::Timestamp>,
/// #     name: String,
/// # }
/// # impl PanelUser for Staff {
/// #     fn user_id(&self) -> String { self.id.to_string() }
/// #     fn display_name(&self) -> &str { &self.name }
/// #     fn can_access_panel(&self, _panel: &str) -> bool { true }
/// #     fn email(&self) -> Option<&str> { Some(&self.email) }
/// # }
/// struct StaffAuth;
///
/// impl EmailVerifier for StaffAuth {
///     type User = Staff;
///
///     fn is_verified(&self, staff: &Staff) -> bool {
///         staff.email_verified_at.is_some()
///     }
///
///     async fn store_verified_email(
///         &self,
///         _cx: &Cx,
///         user_id: &str,
///         email: &str,
///         ex: &mut dyn toasty::Executor,
///     ) -> topcoat::Result<()> {
///         let id = user_id
///             .parse::<uuid::Uuid>()
///             .map_err(|_| topcoat::router::error::not_found())?;
///         Staff::filter_by_id(id)
///             .update()
///             .email(email)
///             .email_verified_at(Some(jiff::Timestamp::now()))
///             .exec(ex)
///             .await?;
///         Ok(())
///     }
/// }
/// ```
pub trait EmailVerifier: Send + Sync + 'static {
    /// The account a link verifies: the type the panel's [`Authenticator`](super::Authenticator)
    /// loads, which mounting checks.
    type User: PanelUser;

    /// Whether `user` proved it reads the address [`PanelUser::email`] answers. A user who has
    /// not reaches only the page that asks for the proof.
    fn is_verified(&self, user: &Self::User) -> bool;

    /// Record, through the transaction `ex`, which commits when it returns `Ok`, that the account
    /// [`PanelUser::user_id`] `user_id` names proved it reads `email`: store `email` as the
    /// address it signs in with, which an email change makes new, and mark it verified. An id
    /// that names no account is an error, not a success: the link is spent either way. It may run
    /// again for one link when the database aborts the transaction for a concurrent one, so it
    /// writes only through `ex`.
    fn store_verified_email(
        &self,
        cx: &Cx,
        user_id: &str,
        email: &str,
        ex: &mut dyn toasty::Executor,
    ) -> impl Future<Output = topcoat::Result<()>> + Send;
}

/// [`EmailVerifier`] with its user type erased, as the panel keeps it.
pub(crate) trait DynEmailVerifier: Send + Sync {
    /// Whether `user` is verified; a user of another type is not.
    fn is_verified(&self, user: &dyn PanelUser) -> bool;
    fn store_verified_email<'a>(
        &'a self,
        cx: &'a Cx,
        user_id: &'a str,
        email: &'a str,
        ex: &'a mut dyn toasty::Executor,
    ) -> BoxFuture<'a, topcoat::Result<()>>;
    /// The [`TypeId`] of [`EmailVerifier::User`], the authenticator's: whose sessions a link ends.
    fn user_type(&self) -> TypeId;
}

impl<V: EmailVerifier> DynEmailVerifier for V {
    fn is_verified(&self, user: &dyn PanelUser) -> bool {
        let user: &dyn Any = user;
        user.downcast_ref::<V::User>()
            .is_some_and(|user| EmailVerifier::is_verified(self, user))
    }

    fn store_verified_email<'a>(
        &'a self,
        cx: &'a Cx,
        user_id: &'a str,
        email: &'a str,
        ex: &'a mut dyn toasty::Executor,
    ) -> BoxFuture<'a, topcoat::Result<()>> {
        Box::pin(EmailVerifier::store_verified_email(
            self, cx, user_id, email, ex,
        ))
    }

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

/// A panel's email verification, installed with
/// [`Auth::email_verification`](super::Auth::email_verification): the [`EmailVerifier`], and how
/// many links one account may ask for. The links go out through the panel's
/// [`AuthMail`](super::AuthMail).
///
/// ```rust
/// use tablo_core::{Auth, AuthMail, EmailVerification, PasswordAuth, PasswordSignUp};
/// use topcoat::mail::Mailbox;
///
/// # fn main() -> Result<(), topcoat::mail::AddressError> {
/// let auth = Auth::password()
///     .mail(AuthMail::new(
///         Mailbox::new("no-reply@example.com")?,
///         "https://admin.example.com",
///     ))
///     .registration(PasswordSignUp::open())
///     .email_verification(EmailVerification::new(PasswordAuth));
/// # let _ = auth;
/// # Ok(())
/// # }
/// ```
///
/// `U` is the user type the verifier loads; [`Auth`](crate::Auth) takes only one over the type its
/// authenticator loads.
pub struct EmailVerification<U> {
    verifier: Box<dyn DynEmailVerifier>,
    pub(in crate::auth) throttle: LoginThrottle,
    user: PhantomData<fn() -> U>,
}

impl<U: PanelUser> EmailVerification<U> {
    /// Verifies addresses through `verifier`.
    #[must_use]
    pub fn new(verifier: impl EmailVerifier<User = U>) -> Self {
        Self {
            verifier: Box::new(verifier),
            throttle: LoginThrottle::new(3, Duration::from_mins(15)),
            user: PhantomData,
        }
    }

    /// How many links one signed-in account may ask for in a window, from any client; defaults
    /// to three in fifteen minutes. The link a sign-up mails does not count.
    #[must_use]
    pub fn throttle(mut self, throttle: LoginThrottle) -> Self {
        self.throttle = throttle;
        self
    }

    /// The same declaration, its user type checked by [`Auth`](crate::Auth).
    pub(crate) fn erase(self) -> EmailVerification<()> {
        EmailVerification {
            verifier: self.verifier,
            throttle: self.throttle,
            user: PhantomData,
        }
    }
}

impl EmailVerification<()> {
    pub(crate) fn verifier(&self) -> &dyn DynEmailVerifier {
        &*self.verifier
    }
}

impl<U> std::fmt::Debug for EmailVerification<U> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("EmailVerification")
            .field("throttle", &self.throttle)
            .finish_non_exhaustive()
    }
}

/// Where the panel asks a signed-in user to verify their address: `{prefix}/verify-email`.
pub(crate) fn notice_url(cx: &Cx) -> String {
    format!("{}/verify-email", panel_prefix(cx))
}

/// Where a verification link opens: `{prefix}/verify-email/confirm`.
pub(crate) fn confirm_url(cx: &Cx) -> String {
    format!("{}/verify-email/confirm", panel_prefix(cx))
}

/// Whether `panel` makes `user` verify their address before anything else: a user without one has
/// nothing to prove, and no link could reach them.
pub(crate) fn pending(panel: &Realm, user: &dyn PanelUser) -> bool {
    user.email().is_some()
        && panel
            .auth
            .verification()
            .is_some_and(|verification| !verification.verifier().is_verified(user))
}

/// Mails a verification link to `user` after the response, when the request's panel verifies
/// addresses and `user` stores one it has not verified: what a sign-up does.
pub(super) fn mail_after_sign_up(cx: &Cx, user: &dyn PanelUser) {
    let Some(panel) = current_realm(cx) else {
        return;
    };
    let Some(email) = user.email().filter(|_| pending(panel, user)) else {
        return;
    };
    let (email, user_id) = (email.to_string(), user.user_id());
    let locale = user.locale();
    after_response(cx, "verification link", move |cx, panel| async move {
        let cx = crate::i18n::addressed_to(&cx, locale.as_ref());
        mail_link(&cx, &panel, &user_id, &email).await
    });
}

/// Records a new verification token for `user_id` proving `email`, replacing the account's
/// earlier ones on `panel`, and mails its link to `email`.
async fn mail_link(cx: &Cx, panel: &Realm, user_id: &str, email: &str) -> topcoat::Result<()> {
    let mail = panel
        .auth
        .auth_mail()
        .ok_or_else(topcoat::router::error::not_found)?;
    let token = token::issue_alone(
        cx,
        TokenPurpose::EmailVerification,
        user_id,
        Some(email.to_string()),
        VERIFICATION_LIFETIME,
    )
    .await?;
    let link = mail.link(&confirm_url(cx), &token);
    let brand = hosted(cx)?.brand_name(cx);
    let message = mail.compose(
        email,
        crate::t!(cx, "tablo-verify-mail-subject", brand = brand.clone()),
        crate::t!(
            cx,
            "tablo-verify-mail-body",
            email = email,
            brand = brand,
            link = link
        ),
    )?;
    topcoat::mail::send(cx, message).await?;
    Ok(())
}

/// `GET {prefix}/verify-email` — the page asking a signed-in user to verify their address, or
/// the panel for one who has.
pub(super) fn notice_page(cx: &Cx, _body: Body) -> RouteFuture<'_> {
    Box::pin(async move {
        let signed = resolved(cx).ok_or_else(|| unauthenticated_error(cx))?;
        if !pending(&signed.realm, signed.user.as_ref()) {
            return see_other(panel_root(cx)).into_response(cx);
        }
        notice(cx, signed.user.email().unwrap_or_default()).await
    })
}

/// `POST {prefix}/verify-email` — mail the signed-in user a new link, then land back on the
/// notice.
pub(super) fn notice_post(cx: &Cx, body: Body) -> RouteFuture<'_> {
    Box::pin(async move {
        let signed = resolved(cx).ok_or_else(|| unauthenticated_error(cx))?;
        let verification = signed
            .realm
            .auth
            .verification()
            .ok_or_else(topcoat::router::error::not_found)?;
        let form = crate::auth::input::read_form(cx, body).await?;
        crate::csrf::verify(cx, form.last(crate::csrf::FIELD_NAME))?;
        if !pending(&signed.realm, signed.user.as_ref()) {
            return see_other(panel_root(cx)).into_response(cx);
        }
        let user_id = signed.user.user_id();
        if !verification
            .throttle
            .attempt(cx, "verification", &user_id, None)
            .await?
        {
            tracing::warn!(panel = %signed.realm.prefix, "verification link request throttled");
            return Err(too_many_requests(verification.throttle.window_secs()).into());
        }
        if let Some(email) = signed.user.email() {
            let email = email.to_string();
            let locale = signed.user.locale();
            after_response(cx, "verification link", move |cx, panel| async move {
                let cx = crate::i18n::addressed_to(&cx, locale.as_ref());
                mail_link(&cx, &panel, &user_id, &email).await
            });
        }
        set_notification(
            cx,
            Notification::success(crate::t!(cx, "tablo-reset-sent"))
                .description(crate::t!(cx, "tablo-verify-sent-description")),
        );
        see_other(notice_url(cx)).into_response(cx)
    })
}

/// `GET {prefix}/verify-email/confirm?token=…` — verify the address the link was mailed to, then
/// land on the panel, or on the login page for a browser that is not signed in as the account.
///
/// The link verifies on `GET`, so a mail scanner that opens it verifies the address too: the
/// scanner fetched it from the mailbox the link proves.
pub(super) fn confirm_page(cx: &Cx, _body: Body) -> RouteFuture<'_> {
    Box::pin(async move {
        let panel = current_realm(cx).ok_or_else(topcoat::router::error::not_found)?;
        let verification = panel
            .auth
            .verification()
            .ok_or_else(topcoat::router::error::not_found)?;
        let encoded = token_from_query(cx);
        let mut db = crate::db::db(cx)?;
        let Some(row) = token::live(cx, &mut db, TokenPurpose::EmailVerification, &encoded).await?
        else {
            return invalid_link(cx).await;
        };
        // A link to an address the account no longer stores proves nothing about the one it
        // stores now.
        if !stores(cx, panel, &row).await? {
            return invalid_link(cx).await;
        }
        let email = row.email.clone().unwrap_or_default();
        let verified = run_serializable!(cx, |tx| async {
            // Read again inside the transaction: of two requests racing on one link, one commits.
            if token::live(cx, tx, TokenPurpose::EmailVerification, &encoded)
                .await?
                .is_none()
            {
                return Ok(false);
            }
            verification
                .verifier()
                .store_verified_email(cx, &row.user_id, &email, tx)
                .await
                .map_err(infrastructure_failure)?;
            token::spend(tx, &row).await?;
            Ok(true)
        })?;
        if !verified {
            return invalid_link(cx).await;
        }
        set_notification(
            cx,
            Notification::success(crate::t!(cx, "tablo-verify-done")),
        );
        // The route answers signed out, so the gate resolved no session for it.
        let signed_in_here = match panel.auth.authenticator() {
            Some(authenticator) => resolve(cx, panel, authenticator)
                .await?
                .is_some_and(|signed| {
                    signed.user.user_id() == row.user_id && signed.impersonator.is_none()
                }),
            None => false,
        };
        let target = if signed_in_here {
            panel_root(cx)
        } else {
            login_url(cx)
        };
        private(see_other(target).into_response(cx)?)
    })
}

/// Whether the account `row` names still signs in to `panel`, may enter it, and stores the
/// address `row` proves.
async fn stores(cx: &Cx, panel: &Realm, row: &token::AuthToken) -> topcoat::Result<bool> {
    let Some(authenticator) = panel.auth.authenticator() else {
        return Ok(false);
    };
    let user = authenticator
        .find_by_id(cx, &row.user_id)
        .await
        .map_err(infrastructure_failure)?;
    Ok(user.is_some_and(|user| {
        user.can_access_panel(&panel.prefix)
            && user.email().is_some()
            && user.email() == row.email.as_deref()
    }))
}

/// The mistakes in a panel's [`Auth::email_verification`](super::Auth::email_verification): a
/// verification without auth, and a verifier whose user is not the authenticator's.
pub(super) fn declaration_errors(auth: &super::AuthConfig) -> Vec<crate::DeclarationErrorKind> {
    use crate::{DeclarationErrorKind, declaration::VerificationFault};

    if auth.verification.is_some() && auth.authenticator().is_none() {
        return vec![DeclarationErrorKind::EmailVerification(
            VerificationFault::AuthDisabled,
        )];
    }
    Vec::new()
}