Skip to main content

tablo_core/auth/
two_factor.rs

1//! Two-factor sign-in: the [`TwoFactor`] a panel installs, the [`AuthFactor`] rows that hold each
2//! account's authenticator secret and recovery codes, and the checks the challenge and settings
3//! pages run against them.
4
5mod backoff;
6mod challenge;
7mod cipher;
8mod email;
9mod pages;
10mod scope;
11mod settings;
12mod totp;
13
14use std::{any::Any, sync::Arc, time::Duration};
15
16use jiff::Timestamp;
17use subtle::ConstantTimeEq;
18use topcoat::{
19    context::{Cx, try_context},
20    cookie::Key,
21};
22
23pub(crate) use self::{challenge::challenge_url, settings::settings_url};
24pub(super) use self::{
25    challenge::{begin as begin_challenge, challenge_page, challenge_post},
26    settings::{settings_page, settings_post},
27};
28use super::{LoginThrottle, PanelUser, infrastructure_failure};
29use crate::auth::realm::{Realm, panel_prefix};
30
31/// A panel's two-factor sign-in, installed with [`Auth::two_factor`](super::Auth::two_factor):
32/// each signed-in user may add an authenticator app, or codes by email when the panel mails them,
33/// at `{prefix}/two-factor`, and an account that has one signs in with a code from it after its
34/// password.
35///
36/// ```rust
37/// use tablo_core::{Auth, TwoFactor};
38///
39/// let auth = Auth::password().two_factor(TwoFactor::new().required());
40/// # let _ = auth;
41/// ```
42#[derive(Debug)]
43pub struct TwoFactor {
44    required: Requirement,
45    email: bool,
46    pub(in crate::auth) throttle: LoginThrottle,
47    pub(in crate::auth) mail_throttle: LoginThrottle,
48}
49
50impl TwoFactor {
51    /// Two-factor sign-in each user may turn on.
52    #[must_use]
53    pub fn new() -> Self {
54        Self {
55            required: Requirement::Nobody,
56            email: false,
57            throttle: LoginThrottle::new(5, Duration::from_mins(1)),
58            mail_throttle: LoginThrottle::new(3, Duration::from_mins(15)),
59        }
60    }
61
62    /// Sends a signed-in user without a second factor to `{prefix}/two-factor` before anything
63    /// else: a page answers with a redirect to it and any other request with 403, after an
64    /// unverified address.
65    #[must_use]
66    pub fn required(mut self) -> Self {
67        self.required = Requirement::Everyone;
68        self
69    }
70
71    /// Requires a second factor of the users `rule` answers `true` for, as
72    /// [`required`](Self::required) does of every user, and leaves it optional for the others:
73    /// staff, say, or the members of a tenant that asks it of them.
74    ///
75    /// The rule is asked on every request, so a user it starts to cover is sent to set up a
76    /// factor at their next one. A user of another type than `U` is required one: the panel
77    /// signs in no such user, so the rule cannot have meant to let them through.
78    ///
79    /// ```rust
80    /// use tablo_core::{Auth, TwoFactor, auth::AdminUser};
81    ///
82    /// let auth = Auth::password().two_factor(
83    ///     TwoFactor::new()
84    ///         .required_for(|_cx, user: &AdminUser| user.email.ends_with("@staff.example")),
85    /// );
86    /// # let _ = auth;
87    /// ```
88    #[must_use]
89    pub fn required_for<U: PanelUser>(
90        mut self,
91        rule: impl Fn(&Cx, &U) -> bool + Send + Sync + 'static,
92    ) -> Self {
93        self.required = Requirement::Some(Arc::new(move |cx, user| {
94            let user: &dyn Any = user;
95            user.downcast_ref::<U>().is_none_or(|user| rule(cx, user))
96        }));
97        self
98    }
99
100    /// Lets a user with an address choose codes mailed to it in place of an authenticator app:
101    /// each sign-in mails one, through [`Auth::mail`](super::Auth::mail), which mounting then
102    /// requires. A mailed code works once, for ten minutes.
103    #[must_use]
104    pub fn email_codes(mut self) -> Self {
105        self.email = true;
106        self
107    }
108
109    /// How many codes one account may have mailed in a window; defaults to three in fifteen
110    /// minutes.
111    #[must_use]
112    pub fn mail_throttle(mut self, throttle: LoginThrottle) -> Self {
113        self.mail_throttle = throttle;
114        self
115    }
116
117    /// How many codes one account may try in a window, from any client, at sign-in and on the
118    /// settings page together; defaults to five a minute.
119    #[must_use]
120    pub fn throttle(mut self, throttle: LoginThrottle) -> Self {
121        self.throttle = throttle;
122        self
123    }
124}
125
126impl TwoFactor {
127    /// Whether the panel asks `user` for a second factor before anything else.
128    fn requires(&self, cx: &Cx, user: &dyn PanelUser) -> bool {
129        match &self.required {
130            Requirement::Nobody => false,
131            Requirement::Everyone => true,
132            Requirement::Some(rule) => rule(cx, user),
133        }
134    }
135
136    /// Whether the panel mails codes.
137    pub(in crate::auth) fn mails(&self) -> bool {
138        self.email
139    }
140}
141
142/// The rule of [`TwoFactor::required_for`], with its user type erased.
143type Rule = dyn Fn(&Cx, &dyn PanelUser) -> bool + Send + Sync;
144
145/// Whom a [`TwoFactor`] requires a second factor of.
146enum Requirement {
147    Nobody,
148    Everyone,
149    Some(Arc<Rule>),
150}
151
152impl std::fmt::Debug for Requirement {
153    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
154        f.write_str(match self {
155            Self::Nobody => "Nobody",
156            Self::Everyone => "Everyone",
157            Self::Some(_) => "Some(..)",
158        })
159    }
160}
161
162impl Default for TwoFactor {
163    fn default() -> Self {
164        Self::new()
165    }
166}
167
168/// Shipped second-factor record: an account's authenticator secret, sealed, or the hash of one of
169/// its recovery codes. It signs in to the panel that enrolled it and to every panel whose
170/// authenticator loads the same user type.
171#[derive(Debug, Clone, toasty::Model)]
172pub struct AuthFactor {
173    #[key]
174    #[auto]
175    pub id: uuid::Uuid,
176    /// [`PanelUser::user_id`](super::PanelUser::user_id) of the account the factor signs in.
177    #[index]
178    pub user_id: String,
179    /// The prefix of the panel that enrolled the factor, which its secret is sealed for.
180    pub panel: String,
181    pub kind: FactorKind,
182    /// The authenticator secret, sealed under the router's cookie key, or the hash of a recovery
183    /// code, keyed under it.
184    pub secret: String,
185    /// When a code proved the authenticator app holds the secret; `None` while it is being set
186    /// up. A recovery code is confirmed when issued.
187    pub confirmed_at: Option<Timestamp>,
188    /// The last 30-second step an authenticator code signed in with: a code works once.
189    pub last_step: Option<i64>,
190    /// The wrong codes in a row signing in since the last right one, on the confirmed factor.
191    pub failures: i64,
192    /// Until when signing in refuses the confirmed factor's codes after
193    /// [`failures`](Self::failures) wrong ones; a recovery code still works.
194    pub retry_at: Option<Timestamp>,
195    pub created_at: Timestamp,
196}
197
198/// What an [`AuthFactor`] is. Stored as its `snake_case` name in a text column, so a kind a later
199/// release adds needs no migration.
200#[derive(Debug, Clone, Copy, PartialEq, Eq, toasty::Embed)]
201#[column(type = text)]
202#[non_exhaustive]
203pub enum FactorKind {
204    /// An authenticator app's RFC 6238 secret.
205    Authenticator,
206    /// A single-use recovery code, for an account that lost its authenticator.
207    RecoveryCode,
208    /// Codes mailed to the account's address, one per sign-in; the row holds no secret.
209    EmailCode,
210}
211
212/// How many recovery codes a set-up or a regeneration issues.
213const RECOVERY_CODES: usize = 8;
214
215/// The characters a recovery code draws from: lowercase base32, which reads without ambiguity.
216const RECOVERY_ALPHABET: &[u8; 32] = b"abcdefghijklmnopqrstuvwxyz234567";
217
218/// The router's cookie key, which seals authenticator secrets.
219fn key(cx: &Cx) -> topcoat::Result<&Key> {
220    try_context::<Key>(cx)
221        .ok_or_else(|| crate::error::declaration("two-factor sign-in needs the router's `Key`"))
222}
223
224/// What a sealed secret is bound to: its account on its panel.
225fn binding(user_id: &str, panel: &str) -> String {
226    format!("{user_id}\n{panel}")
227}
228
229/// What `user_id` holds on the request's panel and the panels sharing with it: the confirmed
230/// factor, an authenticator or mailed codes, the one being set up, and how many recovery codes
231/// are left.
232#[derive(Debug, Default)]
233pub(super) struct Enrolment {
234    pub(super) confirmed: Option<AuthFactor>,
235    pub(super) unconfirmed: Option<AuthFactor>,
236    pub(super) recovery_codes: usize,
237}
238
239/// `user_id`'s [`Enrolment`] on the request's panel.
240pub(super) async fn enrolment(
241    cx: &Cx,
242    ex: &mut dyn toasty::Executor,
243    user_id: &str,
244) -> topcoat::Result<Enrolment> {
245    enrolment_on(ex, &scope::here(cx), &panel_prefix(cx), user_id).await
246}
247
248/// `user_id`'s [`Enrolment`] on `panels`, the panel at `own` and those sharing with it. Factors
249/// confirmed on two of them before they shared stay apart: `own`'s counts, else the oldest.
250async fn enrolment_on(
251    ex: &mut dyn toasty::Executor,
252    panels: &[String],
253    own: &str,
254    user_id: &str,
255) -> topcoat::Result<Enrolment> {
256    let mut enrolment = Enrolment::default();
257    for factor in scope::factors(ex, panels, user_id).await? {
258        match (factor.kind, factor.confirmed_at.is_some()) {
259            (FactorKind::RecoveryCode, _) => enrolment.recovery_codes += 1,
260            (_, true) if enrolment.confirmed.is_none() || factor.panel == own => {
261                enrolment.confirmed = Some(factor);
262            }
263            (_, true) => {}
264            (_, false) => enrolment.unconfirmed = Some(factor),
265        }
266    }
267    Ok(enrolment)
268}
269
270/// The kind of second factor `user` signs in to the request's panel with, if any.
271pub(super) async fn enrolled(cx: &Cx, user: &dyn PanelUser) -> topcoat::Result<Option<FactorKind>> {
272    let mut db = crate::db::db(cx)?;
273    Ok(enrolment(cx, &mut db, &user.user_id())
274        .await?
275        .confirmed
276        .map(|factor| factor.kind))
277}
278
279/// Whether the request's panel offers the signed-in user two-factor sign-in, which it never does
280/// to someone acting as them.
281pub(crate) fn offered(cx: &Cx) -> bool {
282    super::signed(cx).is_some_and(|signed| {
283        signed.impersonator.is_none() && signed.realm.auth.two_factor_config().is_some()
284    })
285}
286
287/// Whether `panel` sends `user` to set up an authenticator before anything else: it requires one
288/// of them, and the user holds none.
289pub(super) async fn setup_pending(
290    cx: &Cx,
291    panel: &Realm,
292    user: &dyn PanelUser,
293) -> topcoat::Result<bool> {
294    match panel.auth.two_factor_config() {
295        Some(two_factor) if two_factor.requires(cx, user) => {
296            let mut db = crate::db::db(cx)?;
297            let panels = scope::sharing(cx, panel);
298            let enrolment = enrolment_on(&mut db, &panels, &panel.prefix, &user.user_id()).await?;
299            Ok(enrolment.confirmed.is_none())
300        }
301        _ => Ok(false),
302    }
303}
304
305/// Starts setting up a factor of `kind` holding `secret` for `user_id`, unconfirmed, in place of
306/// any factor set up before and not confirmed.
307async fn start(
308    cx: &Cx,
309    ex: &mut dyn toasty::Executor,
310    user_id: &str,
311    kind: FactorKind,
312    secret: String,
313) -> topcoat::Result<()> {
314    // A recovery code is confirmed when issued: only a factor being set up matches.
315    scope::remove(cx, &mut *ex, user_id, |factor| {
316        factor.confirmed_at.is_none()
317    })
318    .await?;
319    toasty::create!(AuthFactor {
320        user_id: user_id.to_string(),
321        panel: panel_prefix(cx),
322        kind,
323        secret,
324        confirmed_at: None,
325        last_step: None,
326        failures: 0,
327        retry_at: None,
328        created_at: Timestamp::now(),
329    })
330    .exec(ex)
331    .await
332    .map_err(infrastructure_failure)?;
333    Ok(())
334}
335
336/// Starts setting up an authenticator for `user_id`: a new secret, sealed. Answers the secret,
337/// for the QR code.
338async fn start_authenticator(
339    cx: &Cx,
340    ex: &mut dyn toasty::Executor,
341    user_id: &str,
342) -> topcoat::Result<Vec<u8>> {
343    let secret = totp::secret();
344    let sealed = cipher::seal(key(cx)?, &secret, &binding(user_id, &panel_prefix(cx)));
345    start(cx, ex, user_id, FactorKind::Authenticator, sealed).await?;
346    Ok(secret.to_vec())
347}
348
349/// The secret `factor` seals, or `None` when the router's key no longer opens it.
350fn secret(cx: &Cx, factor: &AuthFactor) -> topcoat::Result<Option<Vec<u8>>> {
351    Ok(cipher::open(
352        key(cx)?,
353        &factor.secret,
354        &binding(&factor.user_id, &factor.panel),
355    ))
356}
357
358/// Whether `code` is the current code of `factor`'s authenticator, not used before; a match
359/// records its step through `ex`, so the code works once.
360async fn accept_code(
361    cx: &Cx,
362    ex: &mut dyn toasty::Executor,
363    factor: &AuthFactor,
364    code: &str,
365) -> topcoat::Result<bool> {
366    let Some(secret) = secret(cx, factor)? else {
367        tracing::error!(panel = %factor.panel, "a two-factor secret does not open under the key");
368        return Ok(false);
369    };
370    let now = std::time::SystemTime::now()
371        .duration_since(std::time::UNIX_EPOCH)
372        .map_err(|_| crate::error::declaration("the clock is before 1970"))?
373        .as_secs();
374    let used = factor.last_step.and_then(|step| u64::try_from(step).ok());
375    let Some(step) = totp::verify(&secret, code, totp::step(now), used) else {
376        return Ok(false);
377    };
378    AuthFactor::filter(AuthFactor::fields().id().eq(factor.id))
379        .update()
380        .last_step(i64::try_from(step).ok())
381        .exec(ex)
382        .await
383        .map_err(infrastructure_failure)?;
384    Ok(true)
385}
386
387/// A recovery code as typed, read the way it was issued: lowercase, without separators.
388fn normalize_recovery_code(code: &str) -> String {
389    code.chars()
390        .filter(char::is_ascii_alphanumeric)
391        .map(|c| c.to_ascii_lowercase())
392        .collect()
393}
394
395/// A recovery code as `user_id`'s row on `panel` stores it: keyed under the router's cookie key.
396fn recovery_hash(cx: &Cx, user_id: &str, panel: &str, code: &str) -> topcoat::Result<String> {
397    Ok(cipher::recovery_hash(
398        key(cx)?,
399        &binding(user_id, panel),
400        &normalize_recovery_code(code),
401    ))
402}
403
404/// Whether `code` is one of `user_id`'s recovery codes on the request's panel or one sharing with
405/// it; a match is deleted through `ex`, so each works once.
406async fn spend_recovery_code(
407    cx: &Cx,
408    ex: &mut dyn toasty::Executor,
409    user_id: &str,
410    code: &str,
411) -> topcoat::Result<bool> {
412    for factor in scope::factors(&mut *ex, &scope::here(cx), user_id).await? {
413        // A hash is bound to the panel that issued the code.
414        if factor.kind == FactorKind::RecoveryCode
415            && bool::from(
416                factor
417                    .secret
418                    .as_bytes()
419                    .ct_eq(recovery_hash(cx, user_id, &factor.panel, code)?.as_bytes()),
420            )
421        {
422            AuthFactor::filter(AuthFactor::fields().id().eq(factor.id))
423                .delete()
424                .exec(ex)
425                .await
426                .map_err(infrastructure_failure)?;
427            return Ok(true);
428        }
429    }
430    Ok(false)
431}
432
433/// Whether `code` is a code of `factor`, used up: its authenticator's current one, or the one
434/// last mailed for it.
435async fn accept_factor(
436    cx: &Cx,
437    ex: &mut dyn toasty::Executor,
438    factor: &AuthFactor,
439    code: &str,
440) -> topcoat::Result<bool> {
441    match factor.kind {
442        FactorKind::Authenticator => accept_code(cx, ex, factor, code).await,
443        FactorKind::EmailCode => email::accept(cx, ex, &factor.user_id, code).await,
444        FactorKind::RecoveryCode => Ok(false),
445    }
446}
447
448/// Whether `code` reads as a code of the factor rather than a recovery code: apps show a code as
449/// "123 456"; a recovery code is ten characters, so six digits are a code.
450fn factor_code(code: &str) -> Option<String> {
451    let code: String = code.chars().filter(|c| !c.is_whitespace()).collect();
452    (code.len() == 6 && code.bytes().all(|b| b.is_ascii_digit())).then_some(code)
453}
454
455/// Whether `code` proves `user_id` holds their second factor on the request's panel: a code of
456/// their confirmed factor, or one of their recovery codes, which it uses up.
457pub(super) async fn accept(
458    cx: &Cx,
459    ex: &mut dyn toasty::Executor,
460    user_id: &str,
461    code: &str,
462) -> topcoat::Result<bool> {
463    let enrolment = enrolment(cx, &mut *ex, user_id).await?;
464    let Some(factor) = enrolment.confirmed else {
465        return Ok(false);
466    };
467    match factor_code(code) {
468        Some(code) => accept_factor(cx, ex, &factor, &code).await,
469        None => {
470            let code: String = code.chars().filter(|c| !c.is_whitespace()).collect();
471            spend_recovery_code(cx, ex, user_id, &code).await
472        }
473    }
474}
475
476/// Fresh recovery codes for `user_id`, issued by the request's panel, in place of any earlier ones.
477/// Answers the codes, which are shown once: only their hashes are stored.
478async fn issue_recovery_codes(
479    cx: &Cx,
480    ex: &mut dyn toasty::Executor,
481    user_id: &str,
482) -> topcoat::Result<Vec<String>> {
483    let panel = panel_prefix(cx);
484    scope::remove(cx, &mut *ex, user_id, |factor| {
485        factor.kind == FactorKind::RecoveryCode
486    })
487    .await?;
488    let mut codes = Vec::with_capacity(RECOVERY_CODES);
489    let now = Timestamp::now();
490    for _ in 0..RECOVERY_CODES {
491        let code = recovery_code();
492        toasty::create!(AuthFactor {
493            user_id: user_id.to_string(),
494            panel: panel.clone(),
495            kind: FactorKind::RecoveryCode,
496            secret: recovery_hash(cx, user_id, &panel, &code)?,
497            confirmed_at: Some(now),
498            last_step: None,
499            failures: 0,
500            retry_at: None,
501            created_at: now,
502        })
503        .exec(&mut *ex)
504        .await
505        .map_err(infrastructure_failure)?;
506        codes.push(code);
507    }
508    Ok(codes)
509}
510
511/// A random recovery code: ten characters of [`RECOVERY_ALPHABET`], in two groups of five.
512fn recovery_code() -> String {
513    let mut bytes = [0u8; 10];
514    getrandom::fill(&mut bytes).expect("the recovery code randomness source failed");
515    // 256 is a multiple of 32, so the low five bits are uniform.
516    let chars: String = bytes
517        .iter()
518        .map(|byte| char::from(RECOVERY_ALPHABET[usize::from(byte & 31)]))
519        .collect();
520    format!("{}-{}", &chars[..5], &chars[5..])
521}
522
523/// Deletes every factor `user_id` holds on the request's panel and the panels sharing with it,
524/// through `ex`.
525async fn remove_all(cx: &Cx, ex: &mut dyn toasty::Executor, user_id: &str) -> topcoat::Result<()> {
526    scope::remove(cx, ex, user_id, |_| true).await
527}
528
529/// The mistakes in a panel's [`Auth::two_factor`](super::Auth::two_factor): two-factor sign-in
530/// without auth, and a router without the cookie key that seals the secrets.
531pub(super) fn declaration_errors(
532    auth: &super::AuthConfig,
533    has_key: bool,
534) -> Vec<crate::DeclarationErrorKind> {
535    use crate::{DeclarationErrorKind, declaration::TwoFactorFault};
536
537    if auth.two_factor.is_none() {
538        return Vec::new();
539    }
540    if auth.authenticator().is_none() {
541        return vec![DeclarationErrorKind::TwoFactor(
542            TwoFactorFault::AuthDisabled,
543        )];
544    }
545    if has_key {
546        Vec::new()
547    } else {
548        vec![DeclarationErrorKind::TwoFactor(TwoFactorFault::MissingKey)]
549    }
550}
551
552#[cfg(test)]
553mod tests {
554    use super::*;
555
556    /// A recovery code reads the same however it is typed, and two codes differ.
557    #[test]
558    fn a_recovery_code_matches_however_it_is_typed() {
559        let code = recovery_code();
560        assert_eq!(code.len(), 11);
561        let read = normalize_recovery_code(&code);
562        assert_eq!(normalize_recovery_code(&code.to_uppercase()), read);
563        assert_eq!(normalize_recovery_code(&code.replace('-', " ")), read);
564        assert_ne!(normalize_recovery_code(&recovery_code()), read);
565    }
566}