laravel-two-factor-rust 0.3.0

Laravel Two Factor for Rust: authenticator app codes, QR codes and recovery codes for Laravel for Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
//! Two-factor authentication with one-time codes from an authenticator app, for
//! [Laravel for Rust](https://laravel.com/rust).
//!
//! Give a user a [`Secret`], show it as a QR code, and check the codes their app shows:
//!
//! ```
//! use laravel_two_factor::{Secret, TwoFactor};
//!
//! let two_factor = TwoFactor::default();
//! let secret = two_factor.generate_secret()?;
//!
//! // Shown once, for the user to scan with their app.
//! let svg = two_factor.qr_code_svg(&secret, "taylor@example.com")?;
//!
//! let code = two_factor.code(&secret);
//! assert!(two_factor.verify(&secret, &code));
//! # Ok::<(), laravel_two_factor::Error>(())
//! ```

mod hotp;
mod recovery;
mod secret;

#[cfg(doctest)]
#[doc = include_str!("../README.md")]
struct ReadmeDoctests;

use std::fmt::Write as _;
use std::time::{SystemTime, UNIX_EPOCH};

use laravel::axum::extract::FromRequestParts;
use laravel::axum::http::request::Parts;
use laravel::config::cache::StoreConfig;
use laravel::config::{Config, Env, Section};
use laravel::container::Container;
use laravel::context::Context;
use laravel::foundation::ServiceProvider;
use laravel::rate_limit::{self, Limit, Quota, TooManyAttempts};
use qrcode::QrCode;
use qrcode::render::svg;
use subtle::{Choice, ConditionallySelectable, ConstantTimeEq};

pub use crate::recovery::RecoveryCodes;
pub use crate::secret::{MIN_SECRET_BYTES, MIN_STORED_SECRET_BYTES, Secret};

/// The hash function codes are derived with.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum Algorithm {
    /// HMAC-SHA1, which every authenticator app supports.
    #[default]
    Sha1,
    /// HMAC-SHA256. Google Authenticator ignores it and shows wrong codes.
    Sha256,
    /// HMAC-SHA512. Google Authenticator ignores it and shows wrong codes.
    Sha512,
}

impl std::str::FromStr for Algorithm {
    type Err = Error;

    /// Reads `SHA1`, `SHA256` or `SHA512`, in either case.
    fn from_str(name: &str) -> Result<Self, Error> {
        match name.to_ascii_uppercase().as_str() {
            "SHA1" => Ok(Self::Sha1),
            "SHA256" => Ok(Self::Sha256),
            "SHA512" => Ok(Self::Sha512),
            _ => Err(Error::InvalidConfig("the algorithm must be SHA1, SHA256 or SHA512")),
        }
    }
}

impl Algorithm {
    /// The name `otpauth://` URLs use: `SHA1`, `SHA256` or `SHA512`.
    #[must_use]
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Sha1 => "SHA1",
            Self::Sha256 => "SHA256",
            Self::Sha512 => "SHA512",
        }
    }
}

/// How codes are made and checked.
///
/// The defaults are what every authenticator app shows. Each field reads from its `TWO_FACTOR_*`
/// variable:
///
/// ```
/// use laravel_two_factor::TwoFactorConfig;
///
/// let config = TwoFactorConfig {
///     issuer: Some("Steddle".into()),
///     window: 0,
///     ..TwoFactorConfig::default()
/// };
/// ```
#[derive(Clone, Debug, PartialEq, Eq, Section)]
pub struct TwoFactorConfig {
    /// The name the app shows above the code, without a `:`. `None` uses `APP_NAME`.
    #[env("TWO_FACTOR_ISSUER")]
    pub issuer: Option<String>,
    /// Digits per code: 6 to 8.
    #[env("TWO_FACTOR_DIGITS", default = 6)]
    pub digits: u32,
    /// Seconds each code lasts, up to [`MAX_PERIOD`].
    #[env("TWO_FACTOR_PERIOD", default = 30)]
    pub period: u64,
    /// Periods before and after the current one that also pass, for a phone whose clock is off.
    #[env("TWO_FACTOR_WINDOW", default = 1)]
    pub window: u64,
    /// The hash function codes are derived with.
    #[env("TWO_FACTOR_ALGORITHM", default = Algorithm::Sha1)]
    pub algorithm: Algorithm,
    /// Bytes in a new secret, at least [`MIN_SECRET_BYTES`].
    #[env("TWO_FACTOR_SECRET_BYTES", default = 20)]
    pub secret_bytes: usize,
    /// The cache store [`verify_once`](TwoFactor::verify_once) keeps its marks in. `None` uses
    /// the default store.
    #[env("TWO_FACTOR_CACHE_STORE")]
    pub cache_store: Option<String>,
}

impl TwoFactorConfig {
    /// Checks that apps can show the codes this config makes.
    ///
    /// # Errors
    ///
    /// Fails when the issuer holds a `:`, `digits` is outside 6 to 8, `period` is outside 1 to
    /// [`MAX_PERIOD`] seconds, `window` is over 10, or `secret_bytes` is below
    /// [`MIN_SECRET_BYTES`].
    pub fn validate(&self) -> Result<(), Error> {
        if self.issuer.as_deref().is_some_and(|issuer| issuer.contains(':')) {
            return Err(Error::InvalidConfig("the issuer can't contain a colon"));
        }
        if !(6..=8).contains(&self.digits) {
            return Err(Error::InvalidConfig("digits must be 6, 7 or 8"));
        }
        if !(1..=MAX_PERIOD).contains(&self.period) {
            return Err(Error::InvalidConfig("the period must be 1 to 86400 seconds"));
        }
        if self.window > 10 {
            return Err(Error::InvalidConfig("the window must be 10 periods or fewer"));
        }
        if self.secret_bytes < MIN_SECRET_BYTES {
            return Err(Error::SecretTooShort);
        }

        Ok(())
    }
}

/// The longest [`TwoFactorConfig::period`]: a day, in seconds.
pub const MAX_PERIOD: u64 = 86_400;

/// The tries [`TwoFactor::attempt`] allows per key each minute.
pub const ATTEMPTS_PER_MINUTE: u32 = 5;

/// What can go wrong with a secret, a config or a QR code.
#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum Error {
    /// A new secret would hold fewer than [`MIN_SECRET_BYTES`] bytes, or an existing one fewer
    /// than [`MIN_STORED_SECRET_BYTES`].
    #[error("the two-factor secret is too short: a new one needs 16 bytes, an existing one 10 (16 base32 characters)")]
    SecretTooShort,
    /// The secret isn't base32: it has a character outside the alphabet, or a length or last
    /// character no bytes encode to.
    #[error(
        "a two-factor secret must be base32: the letters A to Z and digits 2 to 7, as many as whole bytes encode to"
    )]
    InvalidSecret,
    /// The operating system couldn't provide random bytes.
    #[error("the operating system couldn't provide random bytes")]
    Random,
    /// A [`TwoFactorConfig`] value no authenticator app can show.
    #[error("invalid two-factor config: {0}")]
    InvalidConfig(&'static str),
    /// The `otpauth://` URL is too long for a QR code, because the issuer and account are.
    #[error("the two-factor URL is too long for a QR code")]
    QrCode,
    /// The account holds a `:`.
    #[error("the two-factor account name can't contain a colon")]
    InvalidAccount,
}

/// Makes secrets, QR codes and codes, and checks the codes users type.
///
/// As a handler argument, or from [`from_app`](Self::from_app), it carries the application's
/// [`TwoFactorConfig`].
#[derive(Clone, Debug, Default)]
pub struct TwoFactor {
    config: TwoFactorConfig,
}

impl TwoFactor {
    /// Two-factor with the given config.
    ///
    /// # Errors
    ///
    /// Fails when the config doesn't [validate](TwoFactorConfig::validate).
    pub fn new(config: TwoFactorConfig) -> Result<Self, Error> {
        config.validate()?;

        Ok(Self { config })
    }

    /// Two-factor with the application's config, or the defaults outside the application.
    ///
    /// # Errors
    ///
    /// Fails when the application's config doesn't [validate](TwoFactorConfig::validate).
    pub fn from_app() -> Result<Self, Error> {
        let Some(config) = Context::current().map(|_| laravel::config()) else {
            return Ok(Self::default());
        };

        Self::new(effective_config(&config))
    }

    /// The config codes are made and checked with.
    #[must_use]
    pub fn config(&self) -> &TwoFactorConfig {
        &self.config
    }

    /// A new random secret of [`TwoFactorConfig::secret_bytes`] bytes.
    ///
    /// # Errors
    ///
    /// Fails when the operating system can't provide random bytes.
    pub fn generate_secret(&self) -> Result<Secret, Error> {
        Secret::generate(self.config.secret_bytes)
    }

    /// The `otpauth://totp/` URL an authenticator app adds an account from. `account` is the
    /// name the app shows under the issuer, usually the user's email address.
    ///
    /// # Errors
    ///
    /// Fails with [`Error::InvalidAccount`] when the account holds a `:`.
    pub fn url(&self, secret: &Secret, account: &str) -> Result<String, Error> {
        if account.contains(':') {
            return Err(Error::InvalidAccount);
        }

        let label = match &self.config.issuer {
            Some(issuer) => format!("{}:{}", encode(issuer), encode(account)),
            None => encode(account),
        };
        let mut url = format!("otpauth://totp/{label}?secret={}", secret.to_base32());

        if let Some(issuer) = &self.config.issuer {
            let _ = write!(url, "&issuer={}", encode(issuer));
        }

        let _ = write!(
            url,
            "&algorithm={}&digits={}&period={}",
            self.config.algorithm.as_str(),
            self.config.digits,
            self.config.period
        );

        Ok(url)
    }

    /// The [`url`](Self::url) as a QR code: an SVG image at least 192 pixels wide, black on white.
    ///
    /// # Errors
    ///
    /// Fails with [`Error::InvalidAccount`] when the account holds a `:`, and with
    /// [`Error::QrCode`] when the URL is too long for a QR code.
    pub fn qr_code_svg(&self, secret: &Secret, account: &str) -> Result<String, Error> {
        let code = QrCode::new(self.url(secret, account)?).map_err(|_| Error::QrCode)?;

        Ok(code
            .render::<svg::Color<'_>>()
            .min_dimensions(192, 192)
            .dark_color(svg::Color("#000000"))
            .light_color(svg::Color("#ffffff"))
            .build())
    }

    /// The code the user's app shows now.
    #[must_use]
    pub fn code(&self, secret: &Secret) -> String {
        self.code_at(secret, now())
    }

    /// The code the app shows at `time`, in seconds since the Unix epoch.
    #[must_use]
    pub fn code_at(&self, secret: &Secret, time: u64) -> String {
        hotp::code(secret, self.step(time), &self.config)
    }

    /// Whether `code` is the app's code now, or within [`TwoFactorConfig::window`] periods of it.
    /// Spaces and hyphens are ignored. Use [`verify_once`](Self::verify_once) for logins.
    #[must_use]
    pub fn verify(&self, secret: &Secret, code: &str) -> bool {
        self.verify_at(secret, code, now()).is_some()
    }

    /// The counter (period) `code` belongs to when it passes at `time`, in seconds since the Unix
    /// epoch. When two counters share the digits, it's the latest.
    #[must_use]
    pub fn verify_at(&self, secret: &Secret, code: &str, time: u64) -> Option<u64> {
        let code: String = code.chars().filter(|c| !c.is_whitespace() && *c != '-').collect();
        if code.len() != self.config.digits as usize || !code.bytes().all(|byte| byte.is_ascii_digit()) {
            return None;
        }

        let current = self.step(time);
        let first = current.saturating_sub(self.config.window);
        let last = current.saturating_add(self.config.window);

        // Constant time, so the time taken doesn't tell which step matched.
        let mut found = Choice::from(0);
        let mut matched = 0;

        for step in first..=last {
            let equal = hotp::code(secret, step, &self.config).as_bytes().ct_eq(code.as_bytes());
            matched.conditional_assign(&step, equal);
            found |= equal;
        }

        bool::from(found).then_some(matched)
    }

    /// Counts a try at a code or a recovery code for `key`, such as the user's ID: five at once,
    /// then one more every 12 seconds. In a handler, `??` turns a try over the limit into a `429`.
    ///
    /// # Errors
    ///
    /// Fails when the default store is a `discard` or `failover` store, or when the cache is
    /// unavailable.
    ///
    /// # Panics
    ///
    /// Panics outside the application, which the cache belongs to.
    pub async fn attempt(&self, key: &str) -> laravel::Result<Result<Quota, TooManyAttempts>> {
        let config = laravel::config();
        check_store(&config, &config.cache.default)?;

        rate_limit::attempt(
            &format!("two-factor:{key}:attempts"),
            Limit::per_minute(ATTEMPTS_PER_MINUTE),
        )
        .await
    }

    /// Like [`verify`](Self::verify), but each counter (period) passes once per `key`, such as the
    /// user's ID. Once a code passes, it and every earlier code in the window fail.
    ///
    /// The marks live in [`TwoFactorConfig::cache_store`]. A mark the store loses early lets its
    /// code pass once more. With the `database` store, a call inside a transaction on the cache's
    /// connection is final only once that transaction commits.
    ///
    /// # Errors
    ///
    /// Fails when the store is a `discard` or `failover` store, or when the cache is unavailable.
    ///
    /// # Panics
    ///
    /// Panics outside the application, which the cache belongs to.
    pub async fn verify_once(&self, secret: &Secret, code: &str, key: &str) -> laravel::Result<bool> {
        let config = laravel::config();
        let name = self.config.cache_store.as_deref().unwrap_or(&config.cache.default);
        check_store(&config, name)?;
        let cache = laravel::cache::store(name)?;

        let time = now();
        let Some(step) = self.verify_at(secret, code, time) else {
            return Ok(false);
        };
        let first = self.step(time).saturating_sub(self.config.window);

        let seconds = self.config.period * (2 * self.config.window + 1);
        let ttl = laravel::time::ToSpan::seconds(i64::try_from(seconds).unwrap_or(i64::MAX));

        // `add` is atomic, so one request marks each counter. Mark the earlier ones first, so they
        // fail from the moment this one passes.
        for earlier in first..step {
            cache
                .add(&format!("two-factor:{key}:step:{earlier}"), true, ttl)
                .await?;
        }

        if !cache.add(&format!("two-factor:{key}:step:{step}"), true, ttl).await? {
            return Ok(false);
        }

        // The code may have expired while the cache was slow.
        let current = self.step(now());

        Ok(current.saturating_sub(self.config.window) <= step && step <= current.saturating_add(self.config.window))
    }

    fn step(&self, time: u64) -> u64 {
        time / self.config.period
    }
}

/// Takes [`TwoFactor`] as a handler argument, with the application's config.
impl<S: Send + Sync> FromRequestParts<S> for TwoFactor {
    type Rejection = laravel::Error;

    async fn from_request_parts(_parts: &mut Parts, _state: &S) -> Result<Self, Self::Rejection> {
        Ok(Self::from_app()?)
    }
}

/// Sets the default [`TwoFactorConfig`]. Change it in `with_config`:
///
/// ```
/// use laravel::Application;
/// use laravel_two_factor::{TwoFactorConfig, TwoFactorServiceProvider};
///
/// Application::configure()
///     .with_providers(|providers| {
///         providers.add(TwoFactorServiceProvider);
///     })
///     .with_config(|config, _| {
///         config.section_mut::<TwoFactorConfig>().window = 0;
///     });
/// ```
#[derive(Clone, Copy, Debug, Default)]
pub struct TwoFactorServiceProvider;

impl ServiceProvider for TwoFactorServiceProvider {
    fn config(&self, config: &mut Config, env: &Env) {
        config.discover(env!("CARGO_CRATE_NAME"), env);
    }

    /// Refuses a config no authenticator app can show, and a cache store two-factor can't trust.
    async fn boot(&self, app: &Container) -> laravel::Result<()> {
        let config = app.config();
        let two_factor = effective_config(config);
        two_factor.validate()?;

        check_store(config, &config.cache.default)?;

        if let Some(name) = &two_factor.cache_store {
            if !config.cache.stores.contains_key(name) {
                return Err(laravel::Error::msg(format!(
                    "two-factor's cache store `{name}` isn't defined"
                )));
            }
            check_store(config, name)?;
        }

        Ok(())
    }
}

/// Refuses a `discard` store, which keeps nothing, and a `failover` store, whose next store never
/// saw the marks.
fn check_store(config: &Config, name: &str) -> laravel::Result<()> {
    match config.cache.stores.get(name) {
        Some(StoreConfig::Discard) => Err(laravel::Error::msg(format!(
            "two-factor needs a cache store that keeps values, and `{name}` is a discard store"
        ))),
        Some(StoreConfig::Failover(_)) => Err(laravel::Error::msg(format!(
            "two-factor needs one cache store it can trust, and `{name}` is a failover store; \
             use one of its stores instead"
        ))),
        _ => Ok(()),
    }
}

/// The application's [`TwoFactorConfig`], with the issuer defaulting to `APP_NAME`.
fn effective_config(config: &Config) -> TwoFactorConfig {
    let mut two_factor = config.get::<TwoFactorConfig>().cloned().unwrap_or_default();

    if two_factor.issuer.is_none() && !config.app.name.is_empty() {
        two_factor.issuer = Some(config.app.name.clone());
    }

    two_factor
}

/// Seconds since the Unix epoch, on the application's clock when there is one.
fn now() -> u64 {
    match Context::current() {
        Some(_) => u64::try_from(laravel::now().timestamp().as_second()).unwrap_or(0),
        None => SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .map_or(0, |since| since.as_secs()),
    }
}

/// Percent-encodes everything but unreserved characters.
fn encode(text: &str) -> String {
    let mut encoded = String::with_capacity(text.len());

    for byte in text.bytes() {
        if byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'.' | b'_' | b'~') {
            encoded.push(char::from(byte));
        } else {
            let _ = write!(encoded, "%{byte:02X}");
        }
    }

    encoded
}