Skip to main content

tablo_core/auth/
email_change.rs

1//! Email-change confirmation: [`request_email_change`], which a profile editor calls to keep the
2//! old address until the new one proves itself, and the `{prefix}/email-change` routes its two
3//! links open.
4
5use std::{
6    sync::{Arc, Mutex},
7    time::Duration,
8};
9
10use topcoat::{
11    context::{Cx, try_context},
12    router::{
13        Body, RouteFuture,
14        error::see_other,
15        response::{IntoResponse, Response},
16    },
17    view::{ViewExt, attributes, view},
18};
19
20use super::{
21    PanelUser, SignedIn,
22    hook::{AuthEvent, AuthEventKind},
23    infrastructure_failure,
24    login::login_url,
25    mail::{
26        AuthLetter, AuthLetterKind, TOKEN_FIELD, after_response, private, send, token_from_query,
27    },
28    page::{AuthPage, render},
29    panel_root,
30    session::{Activity, credential_panels, end_credentials, resolve, start_once},
31    token::{self, AuthToken, CREDENTIALS, REVOCATION, TokenPurpose, run_serializable},
32    verification::VERIFICATION_LIFETIME,
33};
34use crate::{
35    auth::realm::{Realm, current_realm, hosted, panel_prefix},
36    flash::set_notification,
37    outcome::Notification,
38};
39
40/// How long the old address may undo a change: long enough to notice a mail while away.
41const CANCEL_LIFETIME: Duration = Duration::from_hours(24 * 7);
42
43/// What [`request_email_change`] did with a new address.
44#[derive(Debug, Clone, Copy, PartialEq, Eq)]
45#[must_use]
46pub enum EmailChange {
47    /// The panel mails the new address a link that stores it, and the old one a link that
48    /// cancels: keep the old address until the first is opened.
49    Pending,
50    /// The panel verifies no address: store the new one now.
51    Immediate,
52}
53
54/// Asks the account `user` to confirm `email` as its new address before it changes, when the
55/// request's panel installs [`Auth::email_verification`](super::Auth::email_verification); call
56/// it from [`ProfileEditor::save`](super::ProfileEditor::save) through the save's transaction
57/// `ex`, in place of writing the address.
58///
59/// It answers [`EmailChange::Pending`] once it has recorded the change: the panel mails the new
60/// address a link that stores it, verified, and the old address a link that keeps it, both after
61/// the save commits. Confirming the first is a credential change. The second works for a week,
62/// before or after the change goes through: it restores the old address and ends every session
63/// the account holds. It answers [`EmailChange::Immediate`] on a panel that verifies no address,
64/// and writes nothing: store the address yourself.
65///
66/// The link proves only that whoever asked reads the new mailbox, and a stolen session can name
67/// one its thief reads: ask for the current password before calling it, as
68/// [`PasswordAuth`](super::PasswordAuth)'s profile does.
69///
70/// ```rust
71/// # use tablo_core::{PanelUser, auth::{self, EmailChange}};
72/// # use topcoat::context::Cx;
73/// # #[derive(Debug, Clone, toasty::Model)]
74/// # struct Staff { #[key] #[auto] id: uuid::Uuid, email: String, name: String }
75/// # impl PanelUser for Staff {
76/// #     fn user_id(&self) -> String { self.id.to_string() }
77/// #     fn display_name(&self) -> &str { &self.name }
78/// #     fn can_access_panel(&self, _panel: &tablo_core::PanelId) -> bool { true }
79/// #     fn email(&self) -> Option<&str> { Some(&self.email) }
80/// # }
81/// async fn save_email(
82///     cx: &Cx,
83///     staff: &Staff,
84///     email: String,
85///     ex: &mut dyn toasty::Executor,
86/// ) -> topcoat::Result<()> {
87///     if auth::request_email_change(cx, ex, staff, &email).await? == EmailChange::Immediate {
88///         Staff::filter_by_id(staff.id)
89///             .update()
90///             .email(email)
91///             .exec(ex)
92///             .await?;
93///     }
94///     Ok(())
95/// }
96/// ```
97///
98/// # Errors
99///
100/// 403 while the signed-in user is acted as through
101/// [`Auth::impersonation`](super::Auth::impersonation); the opaque outage when the database cannot
102/// answer.
103pub async fn request_email_change(
104    cx: &Cx,
105    ex: &mut dyn toasty::Executor,
106    user: &dyn PanelUser,
107    email: &str,
108) -> topcoat::Result<EmailChange> {
109    // A user acting as another never changes the target's address.
110    if super::signed(cx).is_some_and(|signed| signed.impersonator.is_some()) {
111        return Err(topcoat::router::error::forbidden().into());
112    }
113    if !current_realm(cx).is_some_and(|panel| panel.auth.verification().is_some()) {
114        return Ok(EmailChange::Immediate);
115    }
116    let mail = current_realm(cx)
117        .and_then(|panel| panel.auth.auth_mail())
118        .ok_or_else(topcoat::router::error::not_found)?;
119    let user_id = user.user_id();
120    let confirm = token::issue(
121        cx,
122        &mut *ex,
123        TokenPurpose::EmailChange,
124        &user_id,
125        Some(email.to_string()),
126        VERIFICATION_LIFETIME,
127    )
128    .await?;
129    let brand = hosted(cx)?.brand_name(cx);
130    let mut letters = vec![mail.letter(
131        AuthLetterKind::EmailChange,
132        email,
133        crate::t!(cx, "tablo-email-change-mail-subject", brand = brand.clone()),
134        crate::t!(
135            cx,
136            "tablo-email-change-mail-body",
137            new = email,
138            brand = brand.clone(),
139            link = mail.link(&confirm_url(cx), &confirm)
140        ),
141        Some(VERIFICATION_LIFETIME),
142    )?];
143    // The cancel link carries the address it restores; an account without one has none to keep.
144    if let Some(old) = user.email() {
145        let cancel = token::issue(
146            cx,
147            &mut *ex,
148            TokenPurpose::EmailChangeCancel,
149            &user_id,
150            Some(old.to_string()),
151            CANCEL_LIFETIME,
152        )
153        .await?;
154        letters.push(mail.letter(
155            AuthLetterKind::EmailChangeCancel,
156            old,
157            crate::t!(
158                cx,
159                "tablo-email-change-notice-subject",
160                brand = brand.clone()
161            ),
162            crate::t!(
163                cx,
164                "tablo-email-change-notice-body",
165                brand = brand,
166                new = email,
167                old = old,
168                link = mail.link(&cancel_url(cx), &cancel)
169            ),
170            Some(CANCEL_LIFETIME),
171        )?);
172    }
173    let mut pending = Vec::new();
174    for letter in letters {
175        pending.extend(mail.hand(cx, &mut *ex, letter).await?);
176    }
177    match try_context::<Requested>(cx) {
178        // Sent once the save commits: a rolled-back save sends nothing.
179        Some(requested) => requested.push(pending),
180        None => send_after_response(cx, pending),
181    }
182    Ok(EmailChange::Pending)
183}
184
185/// The letters a request's email change left to send through the `Mailer`, which its handler
186/// sends once the save commits. A change handed to a delivery leaves none.
187#[derive(Clone, Default)]
188pub(super) struct Requested(Arc<Mutex<Option<Vec<AuthLetter>>>>);
189
190impl Requested {
191    fn push(&self, letters: Vec<AuthLetter>) {
192        self.0
193            .lock()
194            .unwrap_or_else(|poison| poison.into_inner())
195            .get_or_insert_default()
196            .extend(letters);
197    }
198
199    /// Sends the letters the request left after the response, and answers whether it recorded a
200    /// change.
201    pub(super) fn send(&self, cx: &Cx) -> bool {
202        let letters = self
203            .0
204            .lock()
205            .unwrap_or_else(|poison| poison.into_inner())
206            .take();
207        let any = letters.is_some();
208        send_after_response(cx, letters.unwrap_or_default());
209        any
210    }
211}
212
213/// Sends `letters` through the router's `Mailer` after the response.
214fn send_after_response(cx: &Cx, letters: Vec<AuthLetter>) {
215    if letters.is_empty() {
216        return;
217    }
218    after_response(cx, "email change links", move |cx, _| async move {
219        for letter in letters {
220            send(&cx, letter).await?;
221        }
222        Ok(())
223    });
224}
225
226/// Where the link to the new address opens: `{prefix}/email-change/confirm`.
227pub(crate) fn confirm_url(cx: &Cx) -> String {
228    format!("{}/email-change/confirm", panel_prefix(cx))
229}
230
231/// Where the link to the old address opens: `{prefix}/email-change/cancel`.
232pub(crate) fn cancel_url(cx: &Cx) -> String {
233    format!("{}/email-change/cancel", panel_prefix(cx))
234}
235
236/// A link the account may still use: its live token, the account, and the signed-in user of this
237/// browser when it is that account.
238struct Opened {
239    row: AuthToken,
240    account: Arc<dyn PanelUser>,
241    signed: Option<SignedIn>,
242}
243
244/// The live token for `purpose` that `encoded` names, on an account that may still enter the
245/// panel, or on any account for a cancel link, or `None`.
246async fn opened(
247    cx: &Cx,
248    panel: &Arc<Realm>,
249    purpose: TokenPurpose,
250    encoded: &str,
251) -> topcoat::Result<Option<Opened>> {
252    let Some(authenticator) = panel.auth.authenticator() else {
253        return Ok(None);
254    };
255    let mut db = crate::db::db(cx)?;
256    let Some(row) = token::live(cx, &mut db, purpose, encoded).await? else {
257        return Ok(None);
258    };
259    let account = authenticator
260        .find_by_id(cx, &row.user_id)
261        .await
262        .map_err(infrastructure_failure)?
263        // A cancel link only restores the old address and ends sessions: a rule that reads the
264        // address must not refuse it to the account the change shut out.
265        .filter(|account| {
266            purpose == TokenPurpose::EmailChangeCancel || account.can_access_panel(&panel.id)
267        });
268    let Some(account) = account else {
269        return Ok(None);
270    };
271    // The routes answer signed out, so the gate resolved no session for them.
272    let signed = resolve(cx, panel, authenticator, Activity::Counts)
273        .await?
274        .filter(|signed| signed.user.user_id() == row.user_id && signed.impersonator.is_none());
275    Ok(Some(Opened {
276        row,
277        account,
278        signed,
279    }))
280}
281
282/// The page a link opens: what posting it does, and the button that does it. Opening a link
283/// changes nothing, so a mail scanner that fetches it changes nothing either.
284async fn link_page(
285    cx: &Cx,
286    title: String,
287    description: String,
288    button: String,
289) -> topcoat::Result<Response> {
290    let csrf = crate::csrf::ensure_token(cx);
291    let action = topcoat::router::request::uri(cx).path().to_string();
292    let token = token_from_query(cx);
293    let form = view! {
294        <form method="post" action=(action) data-email-change="">
295            (crate::csrf::field(cx, &csrf))
296            <input type="hidden" name=(TOKEN_FIELD) value=(token)>
297            tablo_ui::button(
298                variant: tablo_ui::ButtonVariant::Primary,
299                attrs: attributes! { type="submit" class="w-full" },
300                (button)
301            )
302        </form>
303    }
304    .boxed();
305    let page = render(
306        cx,
307        AuthPage {
308            title,
309            description,
310            status: None,
311            form,
312            switch: None,
313            note: None,
314        },
315    )
316    .await?;
317    private(page.single().await?.into_response(cx)?)
318}
319
320/// The panel's verification and the link `encoded` names for `purpose`, or the page an unusable
321/// link lands on.
322async fn link(
323    cx: &Cx,
324    purpose: TokenPurpose,
325    encoded: &str,
326) -> topcoat::Result<Result<(Arc<Realm>, Opened), Response>> {
327    let panel = current_realm(cx).ok_or_else(topcoat::router::error::not_found)?;
328    if panel.auth.verification().is_none() {
329        return Err(topcoat::router::error::not_found().into());
330    }
331    match opened(cx, panel, purpose, encoded).await? {
332        Some(opened) => Ok(Ok((Arc::clone(panel), opened))),
333        None => Ok(Err(super::verification::invalid_link(cx).await?)),
334    }
335}
336
337/// The token a link's form posts.
338async fn posted_token(cx: &Cx, body: Body) -> topcoat::Result<String> {
339    let form = crate::auth::input::read_form(cx, body).await?;
340    crate::csrf::verify(cx, form.last(crate::csrf::FIELD_NAME))?;
341    Ok(form.last(TOKEN_FIELD).unwrap_or_default().to_string())
342}
343
344/// `GET {prefix}/email-change/confirm?token=…` — the button that confirms the new address.
345pub(super) fn confirm_page(cx: &Cx, _body: Body) -> RouteFuture<'_> {
346    Box::pin(async move {
347        let (_, opened) = match link(cx, TokenPurpose::EmailChange, &token_from_query(cx)).await? {
348            Ok(link) => link,
349            Err(invalid) => return Ok(invalid),
350        };
351        let email = opened.row.email.unwrap_or_default();
352        link_page(
353            cx,
354            crate::t!(cx, "tablo-email-change-confirm-title"),
355            crate::t!(cx, "tablo-email-change-confirm-description", email = email),
356            crate::t!(cx, "tablo-confirm"),
357        )
358        .await
359    })
360}
361
362/// `POST {prefix}/email-change/confirm` — store the new address, verified, and end the account's
363/// sessions and sign-in links on each panel signing in its user type, keeping this browser's when
364/// it is the account's.
365pub(super) fn confirm_post(cx: &Cx, body: Body) -> RouteFuture<'_> {
366    Box::pin(async move {
367        let encoded = posted_token(cx, body).await?;
368        let (panel, Opened { row, signed, .. }) =
369            match link(cx, TokenPurpose::EmailChange, &encoded).await? {
370                Ok(link) => link,
371                Err(invalid) => return Ok(invalid),
372            };
373        let verifier = panel
374            .auth
375            .verification()
376            .ok_or_else(topcoat::router::error::not_found)?
377            .verifier();
378        let email = row.email.clone().unwrap_or_default();
379        let user_type = verifier.user_type();
380        let mut started = None;
381        let landing = run_serializable!(cx, |tx| async {
382            // Read again inside the transaction: of two requests racing on one link, one commits.
383            if token::live(cx, tx, TokenPurpose::EmailChange, &encoded)
384                .await?
385                .is_none()
386            {
387                return Ok(None);
388            }
389            token::spend(tx, &row).await?;
390            verifier
391                .store_verified_email(cx, &row.user_id, &email, tx)
392                .await
393                .map_err(infrastructure_failure)?;
394            let kind = AuthEventKind::EmailChanged;
395            let event = match &signed {
396                Some(signed) => {
397                    AuthEvent::own(kind, &panel.id, signed.acting_tenant(cx), &*signed.user)
398                }
399                None => AuthEvent::unsigned(kind, &panel.id, Some(&row.user_id)),
400            };
401            super::hook::run(cx, &panel.auth_hooks, &event, tx).await?;
402            Ok(Some(match &signed {
403                Some(signed) => {
404                    let session = start_once(cx, &mut started).await?;
405                    super::session::replace_sessions(cx, tx, signed, user_type, &session).await?;
406                    panel_root(cx)
407                }
408                None => {
409                    let panels = credential_panels(cx, user_type, &panel);
410                    end_credentials(tx, &row.user_id, &panels, CREDENTIALS).await?;
411                    login_url(cx)
412                }
413            }))
414        })?;
415        let Some(landing) = landing else {
416            return super::verification::invalid_link(cx).await;
417        };
418        set_notification(
419            cx,
420            Notification::success(crate::t!(cx, "tablo-email-change-done")).description(crate::t!(
421                cx,
422                "tablo-email-change-done-description",
423                email = email
424            )),
425        );
426        private(see_other(landing).into_response(cx)?)
427    })
428}
429
430/// `GET {prefix}/email-change/cancel?token=…` — the button that keeps the old address.
431pub(super) fn cancel_page(cx: &Cx, _body: Body) -> RouteFuture<'_> {
432    Box::pin(async move {
433        let (_, opened) =
434            match link(cx, TokenPurpose::EmailChangeCancel, &token_from_query(cx)).await? {
435                Ok(link) => link,
436                Err(invalid) => return Ok(invalid),
437            };
438        let email = opened.row.email.unwrap_or_default();
439        link_page(
440            cx,
441            crate::t!(cx, "tablo-email-change-keep-title"),
442            crate::t!(cx, "tablo-email-change-keep-description", email = email),
443            crate::t!(cx, "tablo-email-change-keep"),
444        )
445        .await
446    })
447}
448
449/// `POST {prefix}/email-change/cancel` — keep the old address, restoring it when the change went
450/// through, and end every session, sign-in link and pending change the account holds on each panel
451/// signing in its user type: whoever asked for the change may hold one.
452pub(super) fn cancel_post(cx: &Cx, body: Body) -> RouteFuture<'_> {
453    Box::pin(async move {
454        let encoded = posted_token(cx, body).await?;
455        let (panel, Opened { row, account, .. }) =
456            match link(cx, TokenPurpose::EmailChangeCancel, &encoded).await? {
457                Ok(link) => link,
458                Err(invalid) => return Ok(invalid),
459            };
460        let verifier = panel
461            .auth
462            .verification()
463            .ok_or_else(topcoat::router::error::not_found)?
464            .verifier();
465        let old = row.email.clone().unwrap_or_default();
466        let cancelled = run_serializable!(cx, |tx| async {
467            if token::live(cx, tx, TokenPurpose::EmailChangeCancel, &encoded)
468                .await?
469                .is_none()
470            {
471                return Ok(false);
472            }
473            token::spend(tx, &row).await?;
474            if account.email() != Some(old.as_str()) {
475                // The change went through: the old address, which this link proved, comes back.
476                verifier
477                    .store_verified_email(cx, &row.user_id, &old, tx)
478                    .await
479                    .map_err(infrastructure_failure)?;
480            }
481            let panels = credential_panels(cx, verifier.user_type(), &panel);
482            end_credentials(tx, &row.user_id, &panels, REVOCATION).await?;
483            Ok(true)
484        })?;
485        if !cancelled {
486            return super::verification::invalid_link(cx).await;
487        }
488        // The cancelling browser may hold one of the ended sessions; its cookie goes too.
489        super::session::stop(cx).await?;
490        set_notification(
491            cx,
492            Notification::success(crate::t!(cx, "tablo-email-change-kept")).description(crate::t!(
493                cx,
494                "tablo-email-change-kept-description",
495                email = old
496            )),
497        );
498        private(see_other(login_url(cx)).into_response(cx)?)
499    })
500}