Skip to main content

tablo_core/auth/
registration.rs

1//! The panel's sign-up page: the [`Registrar`] trait that creates accounts, the shipped
2//! [`SignUp`] form, and the `{prefix}/register` routes.
3
4use std::{future::Future, sync::Arc};
5
6use topcoat::{
7    context::Cx,
8    router::{
9        Body, RouteFuture,
10        request::client_ip,
11        response::{IntoResponse, Response},
12    },
13    view::{BoxView, ViewExt},
14};
15
16use super::{
17    PanelUser, infrastructure_failure, input,
18    login::{NEXT_FIELD, login_url, next_from_query, safe_next},
19    panel_root,
20    session::{fresh_session, record},
21};
22use crate::{
23    BoxFuture,
24    auth::realm::{current_realm, hosted, panel_prefix},
25    flash::set_notification,
26    form::{FieldError, FieldErrors, FormInput, FormValues, parse_password, parse_scalar},
27    outcome::Notification,
28    schema::{Field, Schema, Source},
29};
30
31/// How a panel creates accounts from its sign-up page, installed with
32/// [`Auth::registration`](super::Auth::registration).
33///
34/// It mirrors an [`Action`](crate::Action) with input: [`Input`](Self::Input) is the form the
35/// page asks for, [`validate`](Self::validate) refuses a submission field by field, and
36/// [`register`](Self::register) writes the account. Both run in one transaction the framework
37/// opens, so a uniqueness probe in `validate` sees what `register` writes against.
38///
39/// The shipped [`PasswordSignUp`](crate::PasswordSignUp) registers an
40/// [`AdminUser`](super::AdminUser) from a [`SignUp`]; an app with its own user table implements
41/// it beside its [`Authenticator`](super::Authenticator), for the same user type:
42///
43/// ```rust
44/// # use tablo_core::{FieldErrors, PanelUser, Registrar, SignUp, auth::hash_password};
45/// # use topcoat::context::Cx;
46/// # #[derive(Debug, Clone, toasty::Model)]
47/// # struct Staff {
48/// #     #[key] #[auto] id: uuid::Uuid,
49/// #     #[unique] email: String,
50/// #     password_hash: String,
51/// #     name: String,
52/// # }
53/// # impl PanelUser for Staff {
54/// #     fn user_id(&self) -> String { self.id.to_string() }
55/// #     fn display_name(&self) -> &str { &self.name }
56/// #     fn can_access_panel(&self, _panel: &tablo_core::PanelId) -> bool { true }
57/// # }
58/// struct StaffAuth;
59///
60/// impl Registrar for StaffAuth {
61///     type Input = SignUp;
62///     type User = Staff;
63///
64///     async fn validate(
65///         &self,
66///         _cx: &Cx,
67///         sign_up: &SignUp,
68///         ex: &mut dyn toasty::Executor,
69///     ) -> topcoat::Result<FieldErrors> {
70///         let mut errors = sign_up.password_errors();
71///         let taken = Staff::filter_by_email(&sign_up.email)
72///             .first()
73///             .exec(ex)
74///             .await?;
75///         if taken.is_some() {
76///             errors.add_field("email", "Email has already been taken");
77///         }
78///         Ok(errors)
79///     }
80///
81///     async fn register(
82///         &self,
83///         _cx: &Cx,
84///         sign_up: SignUp,
85///         ex: &mut dyn toasty::Executor,
86///     ) -> topcoat::Result<Staff> {
87///         Ok(toasty::create!(Staff {
88///             email: sign_up.email,
89///             password_hash: hash_password(&sign_up.password).await?,
90///             name: sign_up.name,
91///         })
92///         .exec(ex)
93///         .await?)
94///     }
95/// }
96/// ```
97///
98/// A new account that [may access the panel](PanelUser::can_access_panel) is signed in and lands
99/// on the panel; one that may not, such as an account awaiting approval, lands on the login page
100/// with a notification saying it was created.
101pub trait Registrar: Send + Sync + 'static {
102    /// What the sign-up page asks for: [`SignUp`], or the app's own
103    /// [`#[derive(FormInput)]`](derive@crate::FormInput) struct. `#[form(password)]` masks a
104    /// field, and `#[form(email)]` checks an address.
105    type Input: FormInput;
106
107    /// The account a sign-up creates: the type the panel's
108    /// [`Authenticator`](super::Authenticator) loads, which mounting checks.
109    type User: PanelUser;
110
111    /// Refuse a submission [`register`](Self::register) should not receive, such as an email
112    /// another account holds: each error names an input field's key and renders under its
113    /// control. Defaults to none. A key no control renders is a declaration error: the page
114    /// would show no message.
115    ///
116    /// It runs inside the sign-up's transaction `ex`, after the input parses and its controls'
117    /// own rules pass.
118    fn validate(
119        &self,
120        _cx: &Cx,
121        _input: &Self::Input,
122        _ex: &mut dyn toasty::Executor,
123    ) -> impl Future<Output = topcoat::Result<FieldErrors>> + Send {
124        async { Ok(FieldErrors::new()) }
125    }
126
127    /// Create the account from a validated `input` through the transaction `ex`, which commits
128    /// when it returns `Ok`.
129    fn register(
130        &self,
131        cx: &Cx,
132        input: Self::Input,
133        ex: &mut dyn toasty::Executor,
134    ) -> impl Future<Output = topcoat::Result<Self::User>> + Send;
135}
136
137/// What a sign-up submission came to.
138pub(crate) enum Outcome {
139    /// The committed account.
140    Registered(Arc<dyn PanelUser>),
141    /// The refused submission, its values, and why. The page renders a password control empty.
142    Refused {
143        values: FormValues,
144        errors: FieldErrors,
145    },
146}
147
148/// [`Registrar`] with its input and user types erased, as the panel keeps it.
149pub(crate) trait DynRegistrar: Send + Sync {
150    /// The sign-up form.
151    fn schema(&self) -> Schema;
152    /// Parses, checks, validates and registers one submission.
153    fn sign_up<'a>(
154        &'a self,
155        cx: &'a Cx,
156        values: FormValues,
157    ) -> BoxFuture<'a, topcoat::Result<Outcome>>;
158}
159
160impl<R: Registrar> DynRegistrar for R {
161    fn schema(&self) -> Schema {
162        R::Input::schema()
163    }
164
165    fn sign_up<'a>(
166        &'a self,
167        cx: &'a Cx,
168        values: FormValues,
169    ) -> BoxFuture<'a, topcoat::Result<Outcome>> {
170        Box::pin(async move {
171            let input =
172                match input::parse::<R::Input>(cx, &values, &FormValues::new(), "sign-up").await? {
173                    Ok(input) => input,
174                    Err(errors) => return Ok(Outcome::Refused { values, errors }),
175                };
176            let mut db = crate::db::db(cx)?;
177            let mut tx = db.transaction().await.map_err(infrastructure_failure)?;
178            let errors = self.validate(cx, &input, &mut tx).await?;
179            input::placed(&R::Input::schema(), &errors, "the registrar", "sign-up")?;
180            if !errors.is_empty() {
181                return Ok(Outcome::Refused { values, errors });
182            }
183            let user = self.register(cx, input, &mut tx).await?;
184            tx.commit().await.map_err(infrastructure_failure)?;
185            Ok(Outcome::Registered(Arc::new(user)))
186        })
187    }
188}
189
190/// The sign-up form [`PasswordSignUp`](crate::PasswordSignUp) registers from, and a custom
191/// [`Registrar`] can take as its input: a name, an email address, and a new password typed
192/// twice.
193#[derive(Clone, PartialEq, Eq)]
194pub struct SignUp {
195    /// The display name, posted as `name`.
196    pub name: String,
197    /// The email address the account signs in with, posted as `email`.
198    pub email: String,
199    /// The new password, posted as `password`.
200    pub password: String,
201    /// The password typed again, posted as `password_confirmation`.
202    pub password_confirmation: String,
203}
204
205impl SignUp {
206    /// The refusals [`new_password_errors`] makes of this sign-up's passwords.
207    pub fn password_errors(&self) -> FieldErrors {
208        new_password_errors(&self.password, &self.password_confirmation)
209    }
210}
211
212/// Redacts the passwords, so a sign-up logged with `?` writes none to the log.
213impl std::fmt::Debug for SignUp {
214    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
215        f.debug_struct("SignUp")
216            .field("name", &self.name)
217            .field("email", &self.email)
218            .field("password", &"<redacted>")
219            .field("password_confirmation", &"<redacted>")
220            .finish()
221    }
222}
223
224impl crate::FormFields for SignUp {
225    type Field = std::convert::Infallible;
226    type Keys = ();
227
228    fn keys() -> Self::Keys {}
229}
230
231impl FormInput for SignUp {
232    fn key(field: Self::Field) -> &'static str {
233        match field {}
234    }
235
236    fn schema() -> Schema {
237        let field = crate::form::required_input;
238        Schema::new((
239            field(Field::text_input::<String>("name").label(crate::text!("tablo-auth-name"))),
240            field(
241                Field::text_input::<String>("email")
242                    .email()
243                    .label(crate::text!("tablo-auth-email")),
244            ),
245            field(
246                Field::text_input::<String>(PASSWORD_FIELD)
247                    .password()
248                    .label(crate::text!("tablo-auth-password")),
249            ),
250            field(
251                Field::text_input::<String>(CONFIRMATION_FIELD)
252                    .password()
253                    .label(crate::text!("tablo-auth-confirm-password")),
254            ),
255        ))
256    }
257
258    fn parse(_cx: &Cx, values: &FormValues) -> Result<Self, Vec<FieldError>> {
259        let mut errors = Vec::new();
260        type Parse = fn(&str, &FormValues, Option<String>) -> Result<String, FieldError>;
261        let mut read = |key: &str, parse: Parse| {
262            parse(key, values, None)
263                .map_err(|error| errors.push(error))
264                .ok()
265        };
266        let name = read("name", parse_scalar::<String>);
267        let email = read("email", parse_scalar::<String>);
268        let password = read(PASSWORD_FIELD, parse_password);
269        let confirmation = read(CONFIRMATION_FIELD, parse_password);
270        match (name, email, password, confirmation) {
271            (Some(name), Some(email), Some(password), Some(password_confirmation))
272                if errors.is_empty() =>
273            {
274                Ok(Self {
275                    name,
276                    email,
277                    password,
278                    password_confirmation,
279                })
280            }
281            _ => Err(errors),
282        }
283    }
284
285    fn write(&self, out: &mut FormValues) {
286        out.insert("name".to_string(), self.name.clone());
287        out.insert("email".to_string(), self.email.clone());
288    }
289}
290
291/// The key [`SignUp`]'s new password posts under.
292const PASSWORD_FIELD: &str = "password";
293/// The key [`SignUp`]'s repeated password posts under.
294const CONFIRMATION_FIELD: &str = "password_confirmation";
295
296/// The fewest characters a new password holds, as NIST SP 800-63B asks of a password a user
297/// chooses.
298pub const MIN_PASSWORD_CHARS: usize = 8;
299
300/// Refuses a new `password` shorter than [`MIN_PASSWORD_CHARS`] under the `password` key, and a
301/// `confirmation` that differs from it under `password_confirmation`: the checks a sign-up form
302/// with [`SignUp`]'s password keys runs in [`Registrar::validate`].
303#[must_use]
304pub fn new_password_errors(password: &str, confirmation: &str) -> FieldErrors {
305    let mut errors = FieldErrors::new();
306    if password.chars().count() < MIN_PASSWORD_CHARS {
307        errors.add_field(
308            PASSWORD_FIELD,
309            crate::text!("tablo-password-too-short", min = MIN_PASSWORD_CHARS),
310        );
311    }
312    if password != confirmation {
313        errors.add_field(CONFIRMATION_FIELD, crate::text!("tablo-password-mismatch"));
314    }
315    errors
316}
317
318/// The keys a sign-up POST carries besides its input, which no input field may post.
319pub(crate) const RESERVED_KEYS: [&str; 2] = [crate::csrf::FIELD_NAME, NEXT_FIELD];
320
321/// Where the panel's sign-up page lives: `{prefix}/register`.
322pub(crate) fn register_url(cx: &Cx) -> String {
323    format!("{}/register", panel_prefix(cx))
324}
325
326/// `url` with `next` in its query: how the login and sign-up pages carry it to each other.
327pub(crate) fn with_next(url: String, next: &str) -> String {
328    if next.is_empty() {
329        return url;
330    }
331    let mut serializer = form_urlencoded::Serializer::new(String::new());
332    serializer.append_pair(NEXT_FIELD, next);
333    format!("{url}?{}", serializer.finish())
334}
335
336/// Whether the request's panel installs a [`Registrar`].
337pub(crate) fn offered(cx: &Cx) -> bool {
338    current_realm(cx).is_some_and(|panel| panel.auth.registrar().is_some())
339}
340
341/// `GET {prefix}/register` — the standalone sign-up page.
342pub(super) fn register_page(cx: &Cx, _body: Body) -> RouteFuture<'_> {
343    Box::pin(async move {
344        let next = next_from_query(cx).unwrap_or_default();
345        // The page starts from each field's default, as the POST reads a disabled one.
346        let values = current_realm(cx)
347            .and_then(|panel| panel.auth.registrar())
348            .map_or_else(FormValues::new, |registrar| registrar.schema().defaults());
349        page_response(cx, &values, &FieldErrors::new(), next, None).await
350    })
351}
352
353/// `POST {prefix}/register` — create the account, then sign it in or send it to the login page.
354pub(super) fn register_post(cx: &Cx, body: Body) -> RouteFuture<'_> {
355    Box::pin(async move {
356        let panel = current_realm(cx).ok_or_else(topcoat::router::error::not_found)?;
357        let registrar = panel
358            .auth
359            .registrar()
360            .ok_or_else(topcoat::router::error::not_found)?;
361        let form = crate::auth::input::read_form(cx, body).await?;
362        crate::csrf::verify(cx, form.last(crate::csrf::FIELD_NAME))?;
363        let next = form
364            .last(NEXT_FIELD)
365            .and_then(safe_next)
366            .map(str::to_string)
367            .unwrap_or_default();
368        let schema = registrar.schema();
369        let values = schema.read_input(cx, &form.pairs, &RESERVED_KEYS)?;
370        let client = client_ip(cx);
371        if !panel
372            .auth
373            .throttle_sign_ups()
374            .attempt(cx, "sign-up", "", client)
375            .await?
376        {
377            tracing::warn!(panel = %panel.prefix, client = ?client, "sign-up attempt throttled");
378            return page_response(
379                cx,
380                &values,
381                &FieldErrors::new(),
382                next,
383                Some(Alert::Throttled),
384            )
385            .await;
386        }
387        let user = match registrar.sign_up(cx, values).await {
388            Ok(Outcome::Registered(user)) => user,
389            Ok(Outcome::Refused { values, errors }) => {
390                return page_response(cx, &values, &errors, next, None).await;
391            }
392            Err(error) => {
393                let error = infrastructure_failure(error);
394                if crate::error::TabloError::is_infrastructure(&error) {
395                    return unavailable(cx, next).await;
396                }
397                return Err(error);
398            }
399        };
400        if !user.can_access_panel(&panel.id) {
401            set_notification(
402                cx,
403                Notification::success(crate::t!(cx, "tablo-sign-up-created"))
404                    .description(crate::t!(cx, "tablo-sign-up-pending")),
405            );
406            return topcoat::router::error::see_other(login_url(cx)).into_response(cx);
407        }
408        // Rotate as a login does, so a session presented before the sign-up cannot be replayed.
409        let recorded = match fresh_session(cx).await {
410            Ok(session) => record(cx, &session, &*user, panel).await,
411            Err(error) => Err(error),
412        };
413        if let Err(error) = recorded {
414            // The account is committed: send it to sign in rather than to a sign-up whose retry
415            // would find its email taken.
416            tracing::error!(error = %infrastructure_failure(error), "sign-up session not recorded");
417            set_notification(
418                cx,
419                Notification::success(crate::t!(cx, "tablo-sign-up-created"))
420                    .description(crate::t!(cx, "tablo-sign-up-sign-in")),
421            );
422            return topcoat::router::error::see_other(login_url(cx)).into_response(cx);
423        }
424        super::verification::mail_after_sign_up(cx, &*user);
425        let target = if next.is_empty() {
426            panel_root(cx)
427        } else {
428            next
429        };
430        topcoat::router::error::see_other(target).into_response(cx)
431    })
432}
433
434/// The sign-up page with the outage alert.
435async fn unavailable(cx: &Cx, next: String) -> topcoat::Result<Response> {
436    let values = FormValues::new();
437    page_response(
438        cx,
439        &values,
440        &FieldErrors::new(),
441        next,
442        Some(Alert::Unavailable),
443    )
444    .await
445}
446
447/// What the sign-up page says above its form, besides a field's error.
448#[derive(Debug, Clone, Copy)]
449enum Alert {
450    /// The client is past its sign-up limit; answers 429.
451    Throttled,
452    /// The database behind sign-up could not answer; answers 503.
453    Unavailable,
454}
455
456impl Alert {
457    /// The message the page renders.
458    fn message(self) -> &'static str {
459        match self {
460            Self::Throttled => "tablo-sign-up-throttled",
461            Self::Unavailable => "tablo-sign-up-unavailable",
462        }
463    }
464
465    fn status(self) -> http::StatusCode {
466        match self {
467            Self::Throttled => http::StatusCode::TOO_MANY_REQUESTS,
468            Self::Unavailable => http::StatusCode::SERVICE_UNAVAILABLE,
469        }
470    }
471}
472
473/// The sign-up page: 422 for a refused submission, the alert's status with one, else 200.
474async fn page_response(
475    cx: &Cx,
476    values: &FormValues,
477    errors: &FieldErrors,
478    next: String,
479    alert: Option<Alert>,
480) -> topcoat::Result<Response> {
481    let status = match alert {
482        Some(alert) => Some(alert.status()),
483        None => (!errors.is_empty()).then_some(http::StatusCode::UNPROCESSABLE_ENTITY),
484    };
485    let page = render_page(cx, values, errors, next, alert, status).await?;
486    page.single().await?.into_response(cx)
487}
488
489/// Renders the standalone sign-up document: the brand, the registrar's form with its errors,
490/// and a link to the login page.
491async fn render_page<'a>(
492    cx: &'a Cx,
493    values: &FormValues,
494    errors: &FieldErrors,
495    next: String,
496    alert: Option<Alert>,
497    status: Option<http::StatusCode>,
498) -> topcoat::Result<BoxView<'a>> {
499    let schema = current_realm(cx)
500        .and_then(|panel| panel.auth.registrar())
501        .map_or_else(Schema::empty, DynRegistrar::schema);
502    let csrf = crate::csrf::ensure_token(cx);
503    let action = register_url(cx);
504    let login = with_next(login_url(cx), &next);
505    let providers = super::oidc::buttons(cx, &next);
506    let fields = schema.render(cx, Source::form(values, errors)).await?;
507    let form = topcoat::view::view! {
508        <form method="post" action=(action) class="flex flex-col gap-5">
509            (crate::csrf::field(cx, &csrf))
510            <input type="hidden" name=(NEXT_FIELD) value=(next)>
511            if let Some(alert) = alert {
512                tablo_ui::alert(
513                    variant: tablo_ui::AlertVariant::Destructive,
514                    attrs: topcoat::view::attributes! { role="alert" },
515                    tablo_ui::alert_title((crate::t!(cx, alert.message())))
516                )
517            }
518            (fields)
519            tablo_ui::button(
520                variant: tablo_ui::ButtonVariant::Primary,
521                attrs: topcoat::view::attributes! { type="submit" class="w-full" },
522                (crate::t!(cx, "tablo-sign-up-submit"))
523            )
524        </form>
525        if let Some(providers) = providers {
526            <div class="mt-5">(providers)</div>
527        }
528    }
529    .boxed();
530    super::page::render(
531        cx,
532        super::page::AuthPage {
533            title: crate::t!(cx, "tablo-sign-up-title"),
534            description: crate::t!(
535                cx,
536                "tablo-sign-up-description",
537                brand = hosted(cx)?.brand_name(cx)
538            ),
539            status,
540            form,
541            switch: Some(super::page::switch_link(
542                cx,
543                "tablo-sign-up-have-account",
544                &login,
545                "tablo-sign-up-sign-in-link",
546            )),
547            note: None,
548        },
549    )
550    .await
551}
552
553/// The mistakes in a panel's [`Auth::registration`](super::Auth::registration): a registration
554/// without auth, a registrar whose user is not the authenticator's, and a sign-up form field the
555/// page cannot serve.
556pub(super) fn declaration_errors(auth: &super::AuthConfig) -> Vec<crate::DeclarationErrorKind> {
557    use super::input::FieldFault;
558    use crate::{DeclarationErrorKind, declaration::SignUpFault};
559
560    let Some(registrar) = auth.registrar.as_deref() else {
561        return Vec::new();
562    };
563    if auth.authenticator().is_none() {
564        return vec![DeclarationErrorKind::SignUp(SignUpFault::AuthDisabled)];
565    }
566    let mut kinds = Vec::new();
567    let schema = registrar.schema();
568    kinds.extend(schema.declaration_errors());
569    kinds.extend(schema.empty_choices());
570    kinds.extend(
571        input::field_faults(&schema, &RESERVED_KEYS).map(|(fault, name)| {
572            DeclarationErrorKind::SignUp(match fault {
573                FieldFault::Reserved => SignUpFault::ReservedField(name),
574                FieldFault::File => SignUpFault::FileField(name),
575                FieldFault::Relationship => SignUpFault::RelationshipField(name),
576            })
577        }),
578    );
579    kinds
580}
581
582#[cfg(test)]
583mod tests;