Skip to main content

laravel_two_factor/
lib.rs

1//! Two-factor authentication with one-time codes from an authenticator app, for
2//! [Laravel for Rust](https://laravel.com/rust).
3//!
4//! Give a user a [`Secret`], show it as a QR code, and check the codes their app shows:
5//!
6//! ```
7//! use laravel_two_factor::{Secret, TwoFactor};
8//!
9//! let two_factor = TwoFactor::default();
10//! let secret = two_factor.generate_secret()?;
11//!
12//! // Shown once, for the user to scan with their app.
13//! let svg = two_factor.qr_code_svg(&secret, "taylor@example.com")?;
14//!
15//! let code = two_factor.code(&secret);
16//! assert!(two_factor.verify(&secret, &code));
17//! # Ok::<(), laravel_two_factor::Error>(())
18//! ```
19
20mod hotp;
21mod recovery;
22mod secret;
23
24#[cfg(doctest)]
25#[doc = include_str!("../README.md")]
26struct ReadmeDoctests;
27
28use std::fmt::Write as _;
29use std::time::{SystemTime, UNIX_EPOCH};
30
31use laravel::axum::extract::FromRequestParts;
32use laravel::axum::http::request::Parts;
33use laravel::config::cache::StoreConfig;
34use laravel::config::{Config, Env, Section};
35use laravel::container::Container;
36use laravel::context::Context;
37use laravel::foundation::ServiceProvider;
38use laravel::rate_limit::{self, Limit, Quota, TooManyAttempts};
39use qrcode::QrCode;
40use qrcode::render::svg;
41use subtle::{Choice, ConditionallySelectable, ConstantTimeEq};
42
43pub use crate::recovery::RecoveryCodes;
44pub use crate::secret::{MIN_SECRET_BYTES, MIN_STORED_SECRET_BYTES, Secret};
45
46/// The hash function codes are derived with.
47#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
48pub enum Algorithm {
49    /// HMAC-SHA1, which every authenticator app supports.
50    #[default]
51    Sha1,
52    /// HMAC-SHA256. Google Authenticator ignores it and shows wrong codes.
53    Sha256,
54    /// HMAC-SHA512. Google Authenticator ignores it and shows wrong codes.
55    Sha512,
56}
57
58impl std::str::FromStr for Algorithm {
59    type Err = Error;
60
61    /// Reads `SHA1`, `SHA256` or `SHA512`, in either case.
62    fn from_str(name: &str) -> Result<Self, Error> {
63        match name.to_ascii_uppercase().as_str() {
64            "SHA1" => Ok(Self::Sha1),
65            "SHA256" => Ok(Self::Sha256),
66            "SHA512" => Ok(Self::Sha512),
67            _ => Err(Error::InvalidConfig("the algorithm must be SHA1, SHA256 or SHA512")),
68        }
69    }
70}
71
72impl Algorithm {
73    /// The name `otpauth://` URLs use: `SHA1`, `SHA256` or `SHA512`.
74    #[must_use]
75    pub fn as_str(self) -> &'static str {
76        match self {
77            Self::Sha1 => "SHA1",
78            Self::Sha256 => "SHA256",
79            Self::Sha512 => "SHA512",
80        }
81    }
82}
83
84/// How codes are made and checked.
85///
86/// The defaults are what every authenticator app shows. Each field reads from its `TWO_FACTOR_*`
87/// variable:
88///
89/// ```
90/// use laravel_two_factor::TwoFactorConfig;
91///
92/// let config = TwoFactorConfig {
93///     issuer: Some("Steddle".into()),
94///     window: 0,
95///     ..TwoFactorConfig::default()
96/// };
97/// ```
98#[derive(Clone, Debug, PartialEq, Eq, Section)]
99pub struct TwoFactorConfig {
100    /// The name the app shows above the code, without a `:`. `None` uses `APP_NAME`.
101    #[env("TWO_FACTOR_ISSUER")]
102    pub issuer: Option<String>,
103    /// Digits per code: 6 to 8.
104    #[env("TWO_FACTOR_DIGITS", default = 6)]
105    pub digits: u32,
106    /// Seconds each code lasts, up to [`MAX_PERIOD`].
107    #[env("TWO_FACTOR_PERIOD", default = 30)]
108    pub period: u64,
109    /// Periods before and after the current one that also pass, for a phone whose clock is off.
110    #[env("TWO_FACTOR_WINDOW", default = 1)]
111    pub window: u64,
112    /// The hash function codes are derived with.
113    #[env("TWO_FACTOR_ALGORITHM", default = Algorithm::Sha1)]
114    pub algorithm: Algorithm,
115    /// Bytes in a new secret, at least [`MIN_SECRET_BYTES`].
116    #[env("TWO_FACTOR_SECRET_BYTES", default = 20)]
117    pub secret_bytes: usize,
118    /// The cache store [`verify_once`](TwoFactor::verify_once) keeps its marks in. `None` uses
119    /// the default store.
120    #[env("TWO_FACTOR_CACHE_STORE")]
121    pub cache_store: Option<String>,
122}
123
124impl TwoFactorConfig {
125    /// Checks that apps can show the codes this config makes.
126    ///
127    /// # Errors
128    ///
129    /// Fails when the issuer holds a `:`, `digits` is outside 6 to 8, `period` is outside 1 to
130    /// [`MAX_PERIOD`] seconds, `window` is over 10, or `secret_bytes` is below
131    /// [`MIN_SECRET_BYTES`].
132    pub fn validate(&self) -> Result<(), Error> {
133        if self.issuer.as_deref().is_some_and(|issuer| issuer.contains(':')) {
134            return Err(Error::InvalidConfig("the issuer can't contain a colon"));
135        }
136        if !(6..=8).contains(&self.digits) {
137            return Err(Error::InvalidConfig("digits must be 6, 7 or 8"));
138        }
139        if !(1..=MAX_PERIOD).contains(&self.period) {
140            return Err(Error::InvalidConfig("the period must be 1 to 86400 seconds"));
141        }
142        if self.window > 10 {
143            return Err(Error::InvalidConfig("the window must be 10 periods or fewer"));
144        }
145        if self.secret_bytes < MIN_SECRET_BYTES {
146            return Err(Error::SecretTooShort);
147        }
148
149        Ok(())
150    }
151}
152
153/// The longest [`TwoFactorConfig::period`]: a day, in seconds.
154pub const MAX_PERIOD: u64 = 86_400;
155
156/// The tries [`TwoFactor::attempt`] allows per key each minute.
157pub const ATTEMPTS_PER_MINUTE: u32 = 5;
158
159/// What can go wrong with a secret, a config or a QR code.
160#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)]
161#[non_exhaustive]
162pub enum Error {
163    /// A new secret would hold fewer than [`MIN_SECRET_BYTES`] bytes, or an existing one fewer
164    /// than [`MIN_STORED_SECRET_BYTES`].
165    #[error("the two-factor secret is too short: a new one needs 16 bytes, an existing one 10 (16 base32 characters)")]
166    SecretTooShort,
167    /// The secret isn't base32: it has a character outside the alphabet, or a length or last
168    /// character no bytes encode to.
169    #[error(
170        "a two-factor secret must be base32: the letters A to Z and digits 2 to 7, as many as whole bytes encode to"
171    )]
172    InvalidSecret,
173    /// The operating system couldn't provide random bytes.
174    #[error("the operating system couldn't provide random bytes")]
175    Random,
176    /// A [`TwoFactorConfig`] value no authenticator app can show.
177    #[error("invalid two-factor config: {0}")]
178    InvalidConfig(&'static str),
179    /// The `otpauth://` URL is too long for a QR code, because the issuer and account are.
180    #[error("the two-factor URL is too long for a QR code")]
181    QrCode,
182    /// The account holds a `:`.
183    #[error("the two-factor account name can't contain a colon")]
184    InvalidAccount,
185}
186
187/// Makes secrets, QR codes and codes, and checks the codes users type.
188///
189/// As a handler argument, or from [`from_app`](Self::from_app), it carries the application's
190/// [`TwoFactorConfig`].
191#[derive(Clone, Debug, Default)]
192pub struct TwoFactor {
193    config: TwoFactorConfig,
194}
195
196impl TwoFactor {
197    /// Two-factor with the given config.
198    ///
199    /// # Errors
200    ///
201    /// Fails when the config doesn't [validate](TwoFactorConfig::validate).
202    pub fn new(config: TwoFactorConfig) -> Result<Self, Error> {
203        config.validate()?;
204
205        Ok(Self { config })
206    }
207
208    /// Two-factor with the application's config, or the defaults outside the application.
209    ///
210    /// # Errors
211    ///
212    /// Fails when the application's config doesn't [validate](TwoFactorConfig::validate).
213    pub fn from_app() -> Result<Self, Error> {
214        let Some(config) = Context::current().map(|_| laravel::config()) else {
215            return Ok(Self::default());
216        };
217
218        Self::new(effective_config(&config))
219    }
220
221    /// The config codes are made and checked with.
222    #[must_use]
223    pub fn config(&self) -> &TwoFactorConfig {
224        &self.config
225    }
226
227    /// A new random secret of [`TwoFactorConfig::secret_bytes`] bytes.
228    ///
229    /// # Errors
230    ///
231    /// Fails when the operating system can't provide random bytes.
232    pub fn generate_secret(&self) -> Result<Secret, Error> {
233        Secret::generate(self.config.secret_bytes)
234    }
235
236    /// The `otpauth://totp/` URL an authenticator app adds an account from. `account` is the
237    /// name the app shows under the issuer, usually the user's email address.
238    ///
239    /// # Errors
240    ///
241    /// Fails with [`Error::InvalidAccount`] when the account holds a `:`.
242    pub fn url(&self, secret: &Secret, account: &str) -> Result<String, Error> {
243        if account.contains(':') {
244            return Err(Error::InvalidAccount);
245        }
246
247        let label = match &self.config.issuer {
248            Some(issuer) => format!("{}:{}", encode(issuer), encode(account)),
249            None => encode(account),
250        };
251        let mut url = format!("otpauth://totp/{label}?secret={}", secret.to_base32());
252
253        if let Some(issuer) = &self.config.issuer {
254            let _ = write!(url, "&issuer={}", encode(issuer));
255        }
256
257        let _ = write!(
258            url,
259            "&algorithm={}&digits={}&period={}",
260            self.config.algorithm.as_str(),
261            self.config.digits,
262            self.config.period
263        );
264
265        Ok(url)
266    }
267
268    /// The [`url`](Self::url) as a QR code: an SVG image at least 192 pixels wide, black on white.
269    ///
270    /// # Errors
271    ///
272    /// Fails with [`Error::InvalidAccount`] when the account holds a `:`, and with
273    /// [`Error::QrCode`] when the URL is too long for a QR code.
274    pub fn qr_code_svg(&self, secret: &Secret, account: &str) -> Result<String, Error> {
275        let code = QrCode::new(self.url(secret, account)?).map_err(|_| Error::QrCode)?;
276
277        Ok(code
278            .render::<svg::Color<'_>>()
279            .min_dimensions(192, 192)
280            .dark_color(svg::Color("#000000"))
281            .light_color(svg::Color("#ffffff"))
282            .build())
283    }
284
285    /// The code the user's app shows now.
286    #[must_use]
287    pub fn code(&self, secret: &Secret) -> String {
288        self.code_at(secret, now())
289    }
290
291    /// The code the app shows at `time`, in seconds since the Unix epoch.
292    #[must_use]
293    pub fn code_at(&self, secret: &Secret, time: u64) -> String {
294        hotp::code(secret, self.step(time), &self.config)
295    }
296
297    /// Whether `code` is the app's code now, or within [`TwoFactorConfig::window`] periods of it.
298    /// Spaces and hyphens are ignored. Use [`verify_once`](Self::verify_once) for logins.
299    #[must_use]
300    pub fn verify(&self, secret: &Secret, code: &str) -> bool {
301        self.verify_at(secret, code, now()).is_some()
302    }
303
304    /// The counter (period) `code` belongs to when it passes at `time`, in seconds since the Unix
305    /// epoch. When two counters share the digits, it's the latest.
306    #[must_use]
307    pub fn verify_at(&self, secret: &Secret, code: &str, time: u64) -> Option<u64> {
308        let code: String = code.chars().filter(|c| !c.is_whitespace() && *c != '-').collect();
309        if code.len() != self.config.digits as usize || !code.bytes().all(|byte| byte.is_ascii_digit()) {
310            return None;
311        }
312
313        let current = self.step(time);
314        let first = current.saturating_sub(self.config.window);
315        let last = current.saturating_add(self.config.window);
316
317        // Constant time, so the time taken doesn't tell which step matched.
318        let mut found = Choice::from(0);
319        let mut matched = 0;
320
321        for step in first..=last {
322            let equal = hotp::code(secret, step, &self.config).as_bytes().ct_eq(code.as_bytes());
323            matched.conditional_assign(&step, equal);
324            found |= equal;
325        }
326
327        bool::from(found).then_some(matched)
328    }
329
330    /// Counts a try at a code or a recovery code for `key`, such as the user's ID: five at once,
331    /// then one more every 12 seconds. In a handler, `??` turns a try over the limit into a `429`.
332    ///
333    /// # Errors
334    ///
335    /// Fails when the default store is a `discard` or `failover` store, or when the cache is
336    /// unavailable.
337    ///
338    /// # Panics
339    ///
340    /// Panics outside the application, which the cache belongs to.
341    pub async fn attempt(&self, key: &str) -> laravel::Result<Result<Quota, TooManyAttempts>> {
342        let config = laravel::config();
343        check_store(&config, &config.cache.default)?;
344
345        rate_limit::attempt(
346            &format!("two-factor:{key}:attempts"),
347            Limit::per_minute(ATTEMPTS_PER_MINUTE),
348        )
349        .await
350    }
351
352    /// Like [`verify`](Self::verify), but each counter (period) passes once per `key`, such as the
353    /// user's ID. Once a code passes, it and every earlier code in the window fail.
354    ///
355    /// The marks live in [`TwoFactorConfig::cache_store`]. A mark the store loses early lets its
356    /// code pass once more. With the `database` store, a call inside a transaction on the cache's
357    /// connection is final only once that transaction commits.
358    ///
359    /// # Errors
360    ///
361    /// Fails when the store is a `discard` or `failover` store, or when the cache is unavailable.
362    ///
363    /// # Panics
364    ///
365    /// Panics outside the application, which the cache belongs to.
366    pub async fn verify_once(&self, secret: &Secret, code: &str, key: &str) -> laravel::Result<bool> {
367        let config = laravel::config();
368        let name = self.config.cache_store.as_deref().unwrap_or(&config.cache.default);
369        check_store(&config, name)?;
370        let cache = laravel::cache::store(name)?;
371
372        let time = now();
373        let Some(step) = self.verify_at(secret, code, time) else {
374            return Ok(false);
375        };
376        let first = self.step(time).saturating_sub(self.config.window);
377
378        let seconds = self.config.period * (2 * self.config.window + 1);
379        let ttl = laravel::time::ToSpan::seconds(i64::try_from(seconds).unwrap_or(i64::MAX));
380
381        // `add` is atomic, so one request marks each counter. Mark the earlier ones first, so they
382        // fail from the moment this one passes.
383        for earlier in first..step {
384            cache
385                .add(&format!("two-factor:{key}:step:{earlier}"), true, ttl)
386                .await?;
387        }
388
389        if !cache.add(&format!("two-factor:{key}:step:{step}"), true, ttl).await? {
390            return Ok(false);
391        }
392
393        // The code may have expired while the cache was slow.
394        let current = self.step(now());
395
396        Ok(current.saturating_sub(self.config.window) <= step && step <= current.saturating_add(self.config.window))
397    }
398
399    fn step(&self, time: u64) -> u64 {
400        time / self.config.period
401    }
402}
403
404/// Takes [`TwoFactor`] as a handler argument, with the application's config.
405impl<S: Send + Sync> FromRequestParts<S> for TwoFactor {
406    type Rejection = laravel::Error;
407
408    async fn from_request_parts(_parts: &mut Parts, _state: &S) -> Result<Self, Self::Rejection> {
409        Ok(Self::from_app()?)
410    }
411}
412
413/// Sets the default [`TwoFactorConfig`]. Change it in `with_config`:
414///
415/// ```
416/// use laravel::Application;
417/// use laravel_two_factor::{TwoFactorConfig, TwoFactorServiceProvider};
418///
419/// Application::configure()
420///     .with_providers(|providers| {
421///         providers.add(TwoFactorServiceProvider);
422///     })
423///     .with_config(|config, _| {
424///         config.section_mut::<TwoFactorConfig>().window = 0;
425///     });
426/// ```
427#[derive(Clone, Copy, Debug, Default)]
428pub struct TwoFactorServiceProvider;
429
430impl ServiceProvider for TwoFactorServiceProvider {
431    fn config(&self, config: &mut Config, env: &Env) {
432        config.discover(env!("CARGO_CRATE_NAME"), env);
433    }
434
435    /// Refuses a config no authenticator app can show, and a cache store two-factor can't trust.
436    async fn boot(&self, app: &Container) -> laravel::Result<()> {
437        let config = app.config();
438        let two_factor = effective_config(config);
439        two_factor.validate()?;
440
441        check_store(config, &config.cache.default)?;
442
443        if let Some(name) = &two_factor.cache_store {
444            if !config.cache.stores.contains_key(name) {
445                return Err(laravel::Error::msg(format!(
446                    "two-factor's cache store `{name}` isn't defined"
447                )));
448            }
449            check_store(config, name)?;
450        }
451
452        Ok(())
453    }
454}
455
456/// Refuses a `discard` store, which keeps nothing, and a `failover` store, whose next store never
457/// saw the marks.
458fn check_store(config: &Config, name: &str) -> laravel::Result<()> {
459    match config.cache.stores.get(name) {
460        Some(StoreConfig::Discard) => Err(laravel::Error::msg(format!(
461            "two-factor needs a cache store that keeps values, and `{name}` is a discard store"
462        ))),
463        Some(StoreConfig::Failover(_)) => Err(laravel::Error::msg(format!(
464            "two-factor needs one cache store it can trust, and `{name}` is a failover store; \
465             use one of its stores instead"
466        ))),
467        _ => Ok(()),
468    }
469}
470
471/// The application's [`TwoFactorConfig`], with the issuer defaulting to `APP_NAME`.
472fn effective_config(config: &Config) -> TwoFactorConfig {
473    let mut two_factor = config.get::<TwoFactorConfig>().cloned().unwrap_or_default();
474
475    if two_factor.issuer.is_none() && !config.app.name.is_empty() {
476        two_factor.issuer = Some(config.app.name.clone());
477    }
478
479    two_factor
480}
481
482/// Seconds since the Unix epoch, on the application's clock when there is one.
483fn now() -> u64 {
484    match Context::current() {
485        Some(_) => u64::try_from(laravel::now().timestamp().as_second()).unwrap_or(0),
486        None => SystemTime::now()
487            .duration_since(UNIX_EPOCH)
488            .map_or(0, |since| since.as_secs()),
489    }
490}
491
492/// Percent-encodes everything but unreserved characters.
493fn encode(text: &str) -> String {
494    let mut encoded = String::with_capacity(text.len());
495
496    for byte in text.bytes() {
497        if byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'.' | b'_' | b'~') {
498            encoded.push(char::from(byte));
499        } else {
500            let _ = write!(encoded, "%{byte:02X}");
501        }
502    }
503
504    encoded
505}