1mod 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#[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 #[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 #[must_use]
66 pub fn required(mut self) -> Self {
67 self.required = Requirement::Everyone;
68 self
69 }
70
71 #[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 #[must_use]
104 pub fn email_codes(mut self) -> Self {
105 self.email = true;
106 self
107 }
108
109 #[must_use]
112 pub fn mail_throttle(mut self, throttle: LoginThrottle) -> Self {
113 self.mail_throttle = throttle;
114 self
115 }
116
117 #[must_use]
120 pub fn throttle(mut self, throttle: LoginThrottle) -> Self {
121 self.throttle = throttle;
122 self
123 }
124}
125
126impl TwoFactor {
127 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 pub(in crate::auth) fn mails(&self) -> bool {
138 self.email
139 }
140}
141
142type Rule = dyn Fn(&Cx, &dyn PanelUser) -> bool + Send + Sync;
144
145enum 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#[derive(Debug, Clone, toasty::Model)]
172pub struct AuthFactor {
173 #[key]
174 #[auto]
175 pub id: uuid::Uuid,
176 #[index]
178 pub user_id: String,
179 pub panel: String,
181 pub kind: FactorKind,
182 pub secret: String,
185 pub confirmed_at: Option<Timestamp>,
188 pub last_step: Option<i64>,
190 pub failures: i64,
192 pub retry_at: Option<Timestamp>,
195 pub created_at: Timestamp,
196}
197
198#[derive(Debug, Clone, Copy, PartialEq, Eq, toasty::Embed)]
201#[column(type = text)]
202#[non_exhaustive]
203pub enum FactorKind {
204 Authenticator,
206 RecoveryCode,
208 EmailCode,
210}
211
212const RECOVERY_CODES: usize = 8;
214
215const RECOVERY_ALPHABET: &[u8; 32] = b"abcdefghijklmnopqrstuvwxyz234567";
217
218fn 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
224fn binding(user_id: &str, panel: &str) -> String {
226 format!("{user_id}\n{panel}")
227}
228
229#[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
239pub(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
248async 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
270pub(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
279pub(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
287pub(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
305async 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 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
336async 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
349fn 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
358async 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
387fn 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
395fn 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
404async 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 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
433async 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
448fn 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
455pub(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
476async 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
511fn recovery_code() -> String {
513 let mut bytes = [0u8; 10];
514 getrandom::fill(&mut bytes).expect("the recovery code randomness source failed");
515 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
523async 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
529pub(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 #[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}