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
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
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
//! The panel's sign-up page: the [`Registrar`] trait that creates accounts, the shipped
//! [`SignUp`] form, and the `{prefix}/register` routes.

use std::{future::Future, sync::Arc};

use topcoat::{
    context::Cx,
    router::{
        Body, RouteFuture,
        request::client_ip,
        response::{IntoResponse, Response},
    },
    view::{BoxView, ViewExt},
};

use super::{
    PanelUser, infrastructure_failure, input,
    login::{NEXT_FIELD, login_url, next_from_query, safe_next},
    panel_root,
    session::{fresh_session, record},
};
use crate::{
    BoxFuture,
    auth::realm::{current_realm, hosted, panel_prefix},
    flash::set_notification,
    form::{FieldError, FieldErrors, FormInput, FormValues, parse_password, parse_scalar},
    outcome::Notification,
    schema::{Field, Schema, Source},
};

/// How a panel creates accounts from its sign-up page, installed with
/// [`Auth::registration`](super::Auth::registration).
///
/// It mirrors an [`Action`](crate::Action) with input: [`Input`](Self::Input) is the form the
/// page asks for, [`validate`](Self::validate) refuses a submission field by field, and
/// [`register`](Self::register) writes the account. Both run in one transaction the framework
/// opens, so a uniqueness probe in `validate` sees what `register` writes against.
///
/// The shipped [`PasswordSignUp`](crate::PasswordSignUp) registers an
/// [`AdminUser`](super::AdminUser) from a [`SignUp`]; an app with its own user table implements
/// it beside its [`Authenticator`](super::Authenticator), for the same user type:
///
/// ```rust
/// # use tablo_core::{FieldErrors, PanelUser, Registrar, SignUp, auth::hash_password};
/// # use topcoat::context::Cx;
/// # #[derive(Debug, Clone, toasty::Model)]
/// # struct Staff {
/// #     #[key] #[auto] id: uuid::Uuid,
/// #     #[unique] email: String,
/// #     password_hash: String,
/// #     name: String,
/// # }
/// # impl PanelUser for Staff {
/// #     fn user_id(&self) -> String { self.id.to_string() }
/// #     fn display_name(&self) -> &str { &self.name }
/// # }
/// struct StaffAuth;
///
/// impl Registrar for StaffAuth {
///     type Input = SignUp;
///     type User = Staff;
///
///     async fn validate(
///         &self,
///         _cx: &Cx,
///         sign_up: &SignUp,
///         ex: &mut dyn toasty::Executor,
///     ) -> topcoat::Result<FieldErrors> {
///         let mut errors = sign_up.password_errors();
///         let taken = Staff::filter_by_email(&sign_up.email)
///             .first()
///             .exec(ex)
///             .await?;
///         if taken.is_some() {
///             errors.add("email", "Email has already been taken");
///         }
///         Ok(errors)
///     }
///
///     async fn register(
///         &self,
///         _cx: &Cx,
///         sign_up: SignUp,
///         ex: &mut dyn toasty::Executor,
///     ) -> topcoat::Result<Staff> {
///         Ok(toasty::create!(Staff {
///             email: sign_up.email,
///             password_hash: hash_password(&sign_up.password).await?,
///             name: sign_up.name,
///         })
///         .exec(ex)
///         .await?)
///     }
/// }
/// ```
///
/// A new account that [may access the panel](PanelUser::can_access_panel) is signed in and lands
/// on the panel; one that may not, such as an account awaiting approval, lands on the login page
/// with a notification saying it was created.
pub trait Registrar: Send + Sync + 'static {
    /// What the sign-up page asks for: [`SignUp`], or the app's own
    /// [`#[derive(FormInput)]`](derive@crate::FormInput) struct. `#[form(password)]` masks a
    /// field, and `#[form(email)]` checks an address.
    type Input: FormInput;

    /// The account a sign-up creates: the type the panel's
    /// [`Authenticator`](super::Authenticator) loads, which mounting checks.
    type User: PanelUser;

    /// Refuse a submission [`register`](Self::register) should not receive, such as an email
    /// another account holds: each error names an input field's key and renders under its
    /// control. Defaults to none. A key no control renders is a declaration error: the page
    /// would show no message.
    ///
    /// It runs inside the sign-up's transaction `ex`, after the input parses and its controls'
    /// own rules pass.
    fn validate(
        &self,
        _cx: &Cx,
        _input: &Self::Input,
        _ex: &mut dyn toasty::Executor,
    ) -> impl Future<Output = topcoat::Result<FieldErrors>> + Send {
        async { Ok(FieldErrors::new()) }
    }

    /// Create the account from a validated `input` through the transaction `ex`, which commits
    /// when it returns `Ok`.
    fn register(
        &self,
        cx: &Cx,
        input: Self::Input,
        ex: &mut dyn toasty::Executor,
    ) -> impl Future<Output = topcoat::Result<Self::User>> + Send;
}

/// What a sign-up submission came to.
pub(crate) enum Outcome {
    /// The committed account.
    Registered(Arc<dyn PanelUser>),
    /// The refused submission, its values, and why. The page renders a password control empty.
    Refused {
        values: FormValues,
        errors: FieldErrors,
    },
}

/// [`Registrar`] with its input and user types erased, as the panel keeps it.
pub(crate) trait DynRegistrar: Send + Sync {
    /// The sign-up form.
    fn schema(&self) -> Schema;
    /// Parses, checks, validates and registers one submission.
    fn sign_up<'a>(
        &'a self,
        cx: &'a Cx,
        values: FormValues,
    ) -> BoxFuture<'a, topcoat::Result<Outcome>>;
}

impl<R: Registrar> DynRegistrar for R {
    fn schema(&self) -> Schema {
        R::Input::schema()
    }

    fn sign_up<'a>(
        &'a self,
        cx: &'a Cx,
        values: FormValues,
    ) -> BoxFuture<'a, topcoat::Result<Outcome>> {
        Box::pin(async move {
            let input =
                match input::parse::<R::Input>(cx, &values, &FormValues::new(), "sign-up").await? {
                    Ok(input) => input,
                    Err(errors) => return Ok(Outcome::Refused { values, errors }),
                };
            let mut db = crate::db::db(cx)?;
            let mut tx = db.transaction().await.map_err(infrastructure_failure)?;
            let errors = self.validate(cx, &input, &mut tx).await?;
            input::placed(&R::Input::schema(), &errors, "the registrar", "sign-up")?;
            if !errors.is_empty() {
                return Ok(Outcome::Refused { values, errors });
            }
            let user = self.register(cx, input, &mut tx).await?;
            tx.commit().await.map_err(infrastructure_failure)?;
            Ok(Outcome::Registered(Arc::new(user)))
        })
    }
}

/// The sign-up form [`PasswordSignUp`](crate::PasswordSignUp) registers from, and a custom
/// [`Registrar`] can take as its input: a name, an email address, and a new password typed
/// twice.
#[derive(Clone, PartialEq, Eq)]
pub struct SignUp {
    /// The display name, posted as `name`.
    pub name: String,
    /// The email address the account signs in with, posted as `email`.
    pub email: String,
    /// The new password, posted as `password`.
    pub password: String,
    /// The password typed again, posted as `password_confirmation`.
    pub password_confirmation: String,
}

impl SignUp {
    /// The refusals [`new_password_errors`] makes of this sign-up's passwords.
    pub fn password_errors(&self) -> FieldErrors {
        new_password_errors(&self.password, &self.password_confirmation)
    }
}

/// Redacts the passwords, so a sign-up logged with `?` writes none to the log.
impl std::fmt::Debug for SignUp {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("SignUp")
            .field("name", &self.name)
            .field("email", &self.email)
            .field("password", &"<redacted>")
            .field("password_confirmation", &"<redacted>")
            .finish()
    }
}

impl FormInput for SignUp {
    fn schema() -> Schema {
        let field = crate::form::required_input;
        Schema::new((
            field(Field::text_input::<String>("name").label(crate::text!("tablo-auth-name"))),
            field(
                Field::text_input::<String>("email")
                    .email()
                    .label(crate::text!("tablo-auth-email")),
            ),
            field(
                Field::text_input::<String>(PASSWORD_FIELD)
                    .password()
                    .label(crate::text!("tablo-auth-password")),
            ),
            field(
                Field::text_input::<String>(CONFIRMATION_FIELD)
                    .password()
                    .label(crate::text!("tablo-auth-confirm-password")),
            ),
        ))
    }

    fn parse(_cx: &Cx, values: &FormValues) -> Result<Self, Vec<FieldError>> {
        let mut errors = Vec::new();
        type Parse = fn(&str, &FormValues, Option<String>) -> Result<String, FieldError>;
        let mut read = |key: &str, parse: Parse| {
            parse(key, values, None)
                .map_err(|error| errors.push(error))
                .ok()
        };
        let name = read("name", parse_scalar::<String>);
        let email = read("email", parse_scalar::<String>);
        let password = read(PASSWORD_FIELD, parse_password);
        let confirmation = read(CONFIRMATION_FIELD, parse_password);
        match (name, email, password, confirmation) {
            (Some(name), Some(email), Some(password), Some(password_confirmation))
                if errors.is_empty() =>
            {
                Ok(Self {
                    name,
                    email,
                    password,
                    password_confirmation,
                })
            }
            _ => Err(errors),
        }
    }

    fn write(&self, out: &mut FormValues) {
        out.insert("name".to_string(), self.name.clone());
        out.insert("email".to_string(), self.email.clone());
    }
}

/// The key [`SignUp`]'s new password posts under.
const PASSWORD_FIELD: &str = "password";
/// The key [`SignUp`]'s repeated password posts under.
const CONFIRMATION_FIELD: &str = "password_confirmation";

/// The fewest characters a new password holds, as NIST SP 800-63B asks of a password a user
/// chooses.
pub const MIN_PASSWORD_CHARS: usize = 8;

/// Refuses a new `password` shorter than [`MIN_PASSWORD_CHARS`] under the `password` key, and a
/// `confirmation` that differs from it under `password_confirmation`: the checks a sign-up form
/// with [`SignUp`]'s password keys runs in [`Registrar::validate`].
#[must_use]
pub fn new_password_errors(password: &str, confirmation: &str) -> FieldErrors {
    let mut errors = FieldErrors::new();
    if password.chars().count() < MIN_PASSWORD_CHARS {
        errors.add(
            PASSWORD_FIELD,
            crate::text!("tablo-password-too-short", min = MIN_PASSWORD_CHARS),
        );
    }
    if password != confirmation {
        errors.add(CONFIRMATION_FIELD, crate::text!("tablo-password-mismatch"));
    }
    errors
}

/// The keys a sign-up POST carries besides its input, which no input field may post.
pub(crate) const RESERVED_KEYS: [&str; 2] = [crate::csrf::FIELD_NAME, NEXT_FIELD];

/// Where the panel's sign-up page lives: `{prefix}/register`.
pub(crate) fn register_url(cx: &Cx) -> String {
    format!("{}/register", panel_prefix(cx))
}

/// `url` with `next` in its query: how the login and sign-up pages carry it to each other.
pub(crate) fn with_next(url: String, next: &str) -> String {
    if next.is_empty() {
        return url;
    }
    let mut serializer = form_urlencoded::Serializer::new(String::new());
    serializer.append_pair(NEXT_FIELD, next);
    format!("{url}?{}", serializer.finish())
}

/// Whether the request's panel installs a [`Registrar`].
pub(crate) fn offered(cx: &Cx) -> bool {
    current_realm(cx).is_some_and(|panel| panel.auth.registrar().is_some())
}

/// `GET {prefix}/register` — the standalone sign-up page.
pub(super) fn register_page(cx: &Cx, _body: Body) -> RouteFuture<'_> {
    Box::pin(async move {
        let next = next_from_query(cx).unwrap_or_default();
        page_response(cx, &FormValues::new(), &FieldErrors::new(), next, None).await
    })
}

/// `POST {prefix}/register` — create the account, then sign it in or send it to the login page.
pub(super) fn register_post(cx: &Cx, body: Body) -> RouteFuture<'_> {
    Box::pin(async move {
        let panel = current_realm(cx).ok_or_else(topcoat::router::error::not_found)?;
        let registrar = panel
            .auth
            .registrar()
            .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))?;
        let next = form
            .last(NEXT_FIELD)
            .and_then(safe_next)
            .map(str::to_string)
            .unwrap_or_default();
        let schema = registrar.schema();
        let values = schema.read_input(cx, &form.pairs, &RESERVED_KEYS)?;
        let client = client_ip(cx);
        if !panel.auth.throttle_sign_ups().attempt("", client) {
            tracing::warn!(panel = %panel.prefix, client = ?client, "sign-up attempt throttled");
            return page_response(
                cx,
                &values,
                &FieldErrors::new(),
                next,
                Some(Alert::Throttled),
            )
            .await;
        }
        let user = match registrar.sign_up(cx, values).await {
            Ok(Outcome::Registered(user)) => user,
            Ok(Outcome::Refused { values, errors }) => {
                return page_response(cx, &values, &errors, next, None).await;
            }
            Err(error) => {
                let error = infrastructure_failure(error);
                if crate::error::TabloError::is_infrastructure(&error) {
                    return unavailable(cx, next).await;
                }
                return Err(error);
            }
        };
        if !user.can_access_panel() {
            set_notification(
                cx,
                Notification::success(crate::t!(cx, "tablo-sign-up-created"))
                    .description(crate::t!(cx, "tablo-sign-up-pending")),
            );
            return topcoat::router::error::see_other(login_url(cx)).into_response(cx);
        }
        // Rotate as a login does, so a session presented before the sign-up cannot be replayed.
        let recorded = match fresh_session(cx).await {
            Ok(session) => record(cx, &session, &*user, panel).await,
            Err(error) => Err(error),
        };
        if let Err(error) = recorded {
            // The account is committed: send it to sign in rather than to a sign-up whose retry
            // would find its email taken.
            tracing::error!(error = %infrastructure_failure(error), "sign-up session not recorded");
            set_notification(
                cx,
                Notification::success(crate::t!(cx, "tablo-sign-up-created"))
                    .description(crate::t!(cx, "tablo-sign-up-sign-in")),
            );
            return topcoat::router::error::see_other(login_url(cx)).into_response(cx);
        }
        super::verification::mail_after_sign_up(cx, &*user);
        let target = if next.is_empty() {
            panel_root(cx)
        } else {
            next
        };
        topcoat::router::error::see_other(target).into_response(cx)
    })
}

/// The sign-up page with the outage alert.
async fn unavailable(cx: &Cx, next: String) -> topcoat::Result<Response> {
    let values = FormValues::new();
    page_response(
        cx,
        &values,
        &FieldErrors::new(),
        next,
        Some(Alert::Unavailable),
    )
    .await
}

/// What the sign-up page says above its form, besides a field's error.
#[derive(Debug, Clone, Copy)]
enum Alert {
    /// The client is past its sign-up limit; answers 429.
    Throttled,
    /// The database behind sign-up could not answer; answers 503.
    Unavailable,
}

impl Alert {
    /// The message the page renders.
    fn message(self) -> &'static str {
        match self {
            Self::Throttled => "tablo-sign-up-throttled",
            Self::Unavailable => "tablo-sign-up-unavailable",
        }
    }

    fn status(self) -> http::StatusCode {
        match self {
            Self::Throttled => http::StatusCode::TOO_MANY_REQUESTS,
            Self::Unavailable => http::StatusCode::SERVICE_UNAVAILABLE,
        }
    }
}

/// The sign-up page: 422 for a refused submission, the alert's status with one, else 200.
async fn page_response(
    cx: &Cx,
    values: &FormValues,
    errors: &FieldErrors,
    next: String,
    alert: Option<Alert>,
) -> topcoat::Result<Response> {
    let status = match alert {
        Some(alert) => Some(alert.status()),
        None => (!errors.is_empty()).then_some(http::StatusCode::UNPROCESSABLE_ENTITY),
    };
    let page = render_page(cx, values, errors, next, alert, status).await?;
    page.single().await?.into_response(cx)
}

/// Renders the standalone sign-up document: the brand, the registrar's form with its errors,
/// and a link to the login page.
async fn render_page<'a>(
    cx: &'a Cx,
    values: &FormValues,
    errors: &FieldErrors,
    next: String,
    alert: Option<Alert>,
    status: Option<http::StatusCode>,
) -> topcoat::Result<BoxView<'a>> {
    let schema = current_realm(cx)
        .and_then(|panel| panel.auth.registrar())
        .map_or_else(Schema::empty, DynRegistrar::schema);
    let csrf = crate::csrf::ensure_token(cx);
    let action = register_url(cx);
    let login = with_next(login_url(cx), &next);
    let fields = schema.render(cx, Source::form(values, errors)).await?;
    let form = topcoat::view::view! {
        cx =>
        <form method="post" action=(action) class="flex flex-col gap-5">
            (crate::csrf::field(cx, &csrf))
            <input type="hidden" name=(NEXT_FIELD) value=(next)>
            if let Some(alert) = alert {
                tablo_ui::alert(
                    variant: tablo_ui::AlertVariant::Destructive,
                    attrs: topcoat::view::attributes! { role="alert" },
                    tablo_ui::alert_title((crate::t!(cx, alert.message())))
                )
            }
            (fields)
            tablo_ui::button(
                variant: tablo_ui::ButtonVariant::Primary,
                attrs: topcoat::view::attributes! { type="submit" class="w-full" },
                (crate::t!(cx, "tablo-sign-up-submit"))
            )
        </form>
    }
    .boxed();
    super::page::render(
        cx,
        super::page::AuthPage {
            title: crate::t!(cx, "tablo-sign-up-title"),
            description: crate::t!(
                cx,
                "tablo-sign-up-description",
                brand = hosted(cx)?.brand_name(cx)
            ),
            status,
            form,
            switch: Some(super::page::switch_link(
                cx,
                "tablo-sign-up-have-account",
                &login,
                "tablo-sign-up-sign-in-link",
            )),
            note: None,
        },
    )
    .await
}

/// The mistakes in a panel's [`Auth::registration`](super::Auth::registration): a registration
/// without auth, a registrar whose user is not the authenticator's, and a sign-up form field the
/// page cannot serve.
pub(super) fn declaration_errors(auth: &super::AuthConfig) -> Vec<crate::DeclarationErrorKind> {
    use super::input::FieldFault;
    use crate::{DeclarationErrorKind, declaration::SignUpFault};

    let Some(registrar) = auth.registrar.as_deref() else {
        return Vec::new();
    };
    if auth.authenticator().is_none() {
        return vec![DeclarationErrorKind::SignUp(SignUpFault::AuthDisabled)];
    }
    let mut kinds = Vec::new();
    let schema = registrar.schema();
    kinds.extend(schema.declaration_errors());
    kinds.extend(schema.empty_choices());
    kinds.extend(
        input::field_faults(&schema, &RESERVED_KEYS).map(|(fault, name)| {
            DeclarationErrorKind::SignUp(match fault {
                FieldFault::Reserved => SignUpFault::ReservedField(name),
                FieldFault::File => SignUpFault::FileField(name),
                FieldFault::Relationship => SignUpFault::RelationshipField(name),
            })
        }),
    );
    kinds
}

#[cfg(test)]
mod tests;