Skip to main content

tablo_core/auth/
token.rs

1//! The single-use secrets auth hands out besides sessions: the [`AuthToken`] rows a mailed link
2//! or a pending sign-in carries, issued, read, used and ended here.
3
4use std::time::Duration;
5
6use jiff::Timestamp;
7use topcoat::{context::Cx, session::Token};
8
9use super::{
10    infrastructure_failure,
11    mail::{AuthLetter, AuthMail},
12    session::token_key,
13};
14use crate::{
15    auth::realm::{current_realm, panel_prefix},
16    error::TabloError,
17    toasty_compat::IsolationLevel,
18};
19
20/// Shipped single-use secret record: the SHA-256 hash of the token a mailed link or a pending
21/// sign-in carries, what it is for, the account and the panel it acts on, and its expiry. The
22/// raw token is never stored.
23#[derive(Debug, Clone, toasty::Model)]
24pub struct AuthToken {
25    /// Hex-encoded SHA-256 of the token.
26    #[key]
27    pub token_hash: String,
28    /// What the token does when used.
29    pub purpose: TokenPurpose,
30    /// [`PanelUser::user_id`](super::PanelUser::user_id) of the account the token acts on.
31    #[index]
32    pub user_id: String,
33    /// The prefix of the panel that issued the token: the only panel it works on.
34    pub panel: String,
35    /// The address a link proves the account reads, for a purpose that proves one.
36    pub email: Option<String>,
37    #[index]
38    pub expires_at: Timestamp,
39    pub created_at: Timestamp,
40}
41
42/// What an [`AuthToken`] does when used. Stored as its `snake_case` name in a text column, so a
43/// purpose a later release adds needs no migration.
44#[derive(Debug, Clone, Copy, PartialEq, Eq, toasty::Embed)]
45#[column(type = text)]
46#[non_exhaustive]
47pub enum TokenPurpose {
48    /// A mailed link that sets a new password.
49    PasswordReset,
50    /// A mailed link that proves the account reads the address it was mailed to.
51    EmailVerification,
52    /// A link mailed to a new address that makes it the account's.
53    EmailChange,
54    /// A link mailed to the old address that cancels a pending change.
55    EmailChangeCancel,
56    /// A sign-in whose password verified, waiting for its second factor.
57    TwoFactorChallenge,
58    /// A code mailed as a second factor, to sign in or to set the factor up.
59    TwoFactorEmailCode,
60}
61
62/// A new token for `purpose` on the request's panel, held by `user_id` until `lifetime` passes,
63/// written through `ex`. The account's earlier tokens for the purpose on that panel end; expired
64/// ones wait for [`sweep_expired`].
65pub(super) async fn issue(
66    cx: &Cx,
67    ex: &mut dyn toasty::Executor,
68    purpose: TokenPurpose,
69    user_id: &str,
70    email: Option<String>,
71    lifetime: Duration,
72) -> topcoat::Result<Token> {
73    let token = Token::random();
74    record(
75        cx,
76        ex,
77        purpose,
78        user_id,
79        email,
80        lifetime,
81        token_key(&token.hash()),
82    )
83    .await?;
84    Ok(token)
85}
86
87/// Records `token_hash` as `user_id`'s token for `purpose` on the request's panel until
88/// `lifetime` passes, in place of the account's earlier ones there and every expired token.
89pub(super) async fn record(
90    cx: &Cx,
91    ex: &mut dyn toasty::Executor,
92    purpose: TokenPurpose,
93    user_id: &str,
94    email: Option<String>,
95    lifetime: Duration,
96    token_hash: String,
97) -> topcoat::Result<()> {
98    let now = Timestamp::now();
99    let expires_at = Timestamp::try_from(std::time::SystemTime::now() + lifetime)
100        .map_err(topcoat::Error::from)?;
101    let panel = panel_prefix(cx);
102    AuthToken::filter(
103        AuthToken::fields()
104            .user_id()
105            .eq(user_id.to_string())
106            .and(AuthToken::fields().panel().eq(panel.clone()))
107            .and(AuthToken::fields().purpose().eq(purpose)),
108    )
109    .delete()
110    .exec(&mut *ex)
111    .await
112    .map_err(infrastructure_failure)?;
113    toasty::create!(AuthToken {
114        token_hash,
115        purpose,
116        user_id: user_id.to_string(),
117        panel,
118        email,
119        expires_at,
120        created_at: now,
121    })
122    .exec(ex)
123    .await
124    .map_err(infrastructure_failure)?;
125    Ok(())
126}
127
128/// The live token for `purpose` that `encoded` names on the request's panel, or `None` for an
129/// unknown, expired, malformed or other panel's one.
130pub(super) async fn live(
131    cx: &Cx,
132    ex: &mut dyn toasty::Executor,
133    purpose: TokenPurpose,
134    encoded: &str,
135) -> topcoat::Result<Option<AuthToken>> {
136    let Ok(token) = Token::decode(encoded) else {
137        return Ok(None);
138    };
139    recorded(cx, ex, purpose, token_key(&token.hash())).await
140}
141
142/// The live token for `purpose` that [`record`] stored as `token_hash` on the request's panel.
143pub(super) async fn recorded(
144    cx: &Cx,
145    ex: &mut dyn toasty::Executor,
146    purpose: TokenPurpose,
147    token_hash: String,
148) -> topcoat::Result<Option<AuthToken>> {
149    let row = AuthToken::filter(AuthToken::fields().token_hash().eq(token_hash))
150        .first()
151        .exec(ex)
152        .await
153        .map_err(infrastructure_failure)?;
154    let prefix = panel_prefix(cx);
155    Ok(row.filter(|row| {
156        row.purpose == purpose && row.panel == prefix && row.expires_at > Timestamp::now()
157    }))
158}
159
160/// Deletes `row` through `ex`: a used token works once.
161pub(super) async fn spend(ex: &mut dyn toasty::Executor, row: &AuthToken) -> topcoat::Result<()> {
162    AuthToken::filter(AuthToken::fields().token_hash().eq(row.token_hash.clone()))
163        .delete()
164        .exec(ex)
165        .await
166        .map_err(infrastructure_failure)
167}
168
169/// The purposes a credential change ends: the tokens that sign in or set a credential. A link
170/// that proves an address, makes a change the account asked for, or undoes one outlives it.
171pub(super) const CREDENTIALS: &[TokenPurpose] = &[
172    TokenPurpose::PasswordReset,
173    TokenPurpose::TwoFactorChallenge,
174    TokenPurpose::TwoFactorEmailCode,
175];
176
177/// The purposes a reset, a cancelled email change or a revocation ends: those of a credential
178/// change, and a pending email change, which whoever knew the password may have asked for.
179pub(super) const REVOCATION: &[TokenPurpose] = &[
180    TokenPurpose::PasswordReset,
181    TokenPurpose::TwoFactorChallenge,
182    TokenPurpose::TwoFactorEmailCode,
183    TokenPurpose::EmailChange,
184];
185
186/// Deletes every token for one of `purposes` that `user_id` holds on the panels `prefixes` names,
187/// or on every panel for `None`, through `ex`.
188pub(super) async fn end_all(
189    ex: &mut dyn toasty::Executor,
190    user_id: &str,
191    prefixes: Option<Vec<String>>,
192    purposes: &[TokenPurpose],
193) -> topcoat::Result<()> {
194    let user = AuthToken::fields()
195        .user_id()
196        .eq(user_id.to_string())
197        .and(AuthToken::fields().purpose().in_list(purposes.to_vec()));
198    match prefixes {
199        Some(prefixes) => {
200            AuthToken::filter(user.and(AuthToken::fields().panel().in_list(prefixes)))
201        }
202        None => AuthToken::filter(user),
203    }
204    .delete()
205    .exec(ex)
206    .await
207    .map_err(infrastructure_failure)
208}
209
210/// How many expired token rows one sweep drops: the bound that keeps one login from deleting an
211/// unbounded number of rows.
212pub(super) const TOKEN_SWEEP_BATCH: usize = 500;
213
214/// Drops up to [`TOKEN_SWEEP_BATCH`] expired token rows when a login succeeds on a panel that
215/// issues tokens, outside any transaction: inside one, every issue would contend on the same rows.
216pub(super) async fn sweep_expired(cx: &Cx) -> topcoat::Result<()> {
217    // A panel that issues no token may leave the model unregistered.
218    if current_realm(cx).is_some_and(|panel| panel.auth.issues_tokens()) {
219        sweep(&mut crate::db::db(cx)?).await?;
220    }
221    Ok(())
222}
223
224/// Drops up to [`TOKEN_SWEEP_BATCH`] expired token rows from `db`.
225pub(super) async fn sweep(db: &mut toasty::Db) -> topcoat::Result<()> {
226    let now = Timestamp::now();
227    let expired: Vec<String> = AuthToken::filter(AuthToken::fields().expires_at().le(now))
228        .limit(TOKEN_SWEEP_BATCH)
229        .exec(&mut *db)
230        .await
231        .map_err(infrastructure_failure)?
232        .into_iter()
233        .map(|row| row.token_hash)
234        .collect();
235    if expired.is_empty() {
236        return Ok(());
237    }
238    // The expiry is re-checked: the select and the delete are two statements.
239    AuthToken::filter(
240        AuthToken::fields()
241            .token_hash()
242            .in_list(expired)
243            .and(AuthToken::fields().expires_at().le(now)),
244    )
245    .delete()
246    .exec(db)
247    .await
248    .map_err(infrastructure_failure)
249}
250
251/// A serializable transaction on `db`: two requests racing on one token, or one account, then
252/// cannot both commit.
253pub(super) async fn serializable(db: &mut toasty::Db) -> topcoat::Result<toasty::Transaction<'_>> {
254    db.transaction_builder()
255        .isolation(IsolationLevel::Serializable)
256        .begin()
257        .await
258        .map_err(infrastructure_failure)
259}
260
261/// How many times [`run_serializable!`] runs its transaction before it gives up on a conflict.
262///
263/// PostgreSQL scans a small table whole, so concurrent transactions on different accounts abort
264/// each other too: five runs left one of eight concurrent recovery-code renewals failing now and
265/// then, where ten carried thirty-two through.
266const ATTEMPTS: u32 = 10;
267
268/// Runs `$body`, an async block answering a `topcoat::Result`, in a serializable transaction it
269/// reaches as `$tx` (a `&mut toasty::Transaction`), and commits when `$body` answers `Ok`. When the
270/// database aborts the transaction for a concurrent one, both run again: PostgreSQL and MySQL abort
271/// one of two overlapping transactions even when they act on different accounts.
272///
273/// `$body` may run several times, so it does nothing the transaction does not undo: a mail, a
274/// notification or a page waits for the answer, and a session goes through
275/// [`super::session::start_once`]. A macro rather than a function taking a closure: a closure
276/// borrowing the transaction and the request's locals has no lifetime to name.
277macro_rules! run_serializable {
278    ($cx:expr, |$tx:ident| $body:expr) => {{
279        let mut db = crate::db::db($cx)?;
280        let mut attempt = 1;
281        loop {
282            let run = async {
283                let mut tx = crate::auth::token::serializable(&mut db).await?;
284                let answer = {
285                    let $tx = &mut tx;
286                    crate::auth::token::answering($body).await?
287                };
288                tx.commit()
289                    .await
290                    .map_err(crate::auth::infrastructure_failure)?;
291                topcoat::Result::Ok(answer)
292            }
293            .await;
294            let Err(error) = run else { break run };
295            if !crate::auth::token::waited_to_retry(&mut attempt, &error).await {
296                break Err(error);
297            }
298        }
299    }};
300}
301pub(super) use run_serializable;
302
303/// `body` as it is: names the error type a [`run_serializable!`] body answers, which its `?`
304/// cannot infer.
305pub(super) fn answering<T>(
306    body: impl Future<Output = topcoat::Result<T>>,
307) -> impl Future<Output = topcoat::Result<T>> {
308    body
309}
310
311/// Whether a transaction that failed with `error` on its `attempt`th run runs again: after a
312/// conflict, up to [`ATTEMPTS`] runs, once a [`backoff`] has passed.
313pub(super) async fn waited_to_retry(attempt: &mut u32, error: &topcoat::Error) -> bool {
314    if *attempt >= ATTEMPTS || !TabloError::is_conflict(error) {
315        return false;
316    }
317    tokio::time::sleep(backoff(*attempt)).await;
318    *attempt += 1;
319    true
320}
321
322/// Issues a token as [`issue`] does and writes the letter `write` builds around it, in a
323/// transaction of its own that [`run_serializable!`] runs again on a conflict: a link mailed after
324/// the response has no visitor left to try again. The letter goes to `mail`'s delivery inside
325/// that transaction, or through the router's `Mailer` once it commits.
326pub(super) async fn issue_mailed(
327    cx: &Cx,
328    mail: &AuthMail,
329    purpose: TokenPurpose,
330    user_id: &str,
331    email: Option<String>,
332    lifetime: Duration,
333    write: impl Fn(&Token) -> topcoat::Result<AuthLetter> + Send + Sync,
334) -> topcoat::Result<()> {
335    let pending = run_serializable!(cx, |tx| async {
336        let token = issue(cx, &mut *tx, purpose, user_id, email.clone(), lifetime).await?;
337        mail.hand(cx, tx, write(&token)?).await
338    })?;
339    if let Some(letter) = pending {
340        super::mail::send(cx, letter).await?;
341    }
342    Ok(())
343}
344
345/// A random wait under 20ms doubled per failed `attempt`: transactions that aborted each other
346/// would meet again if they waited alike.
347fn backoff(attempt: u32) -> Duration {
348    let ceiling = 20u64 << attempt.min(6);
349    let jitter = getrandom::u64().map_or(ceiling / 2, |random| random % ceiling);
350    Duration::from_millis(jitter)
351}