glacier-web 0.4.0

A batteries-included web framework for Rust, inspired by Rails, Phoenix and Laravel.
Documentation
//! Time-based one-time passwords (TOTP, RFC 6238), the six-digit codes an
//! authenticator app shows, for two-factor sign-in.
//!
//! The app keeps a [`new_secret`] for each user who turns two-factor
//! sign-in on, shows it to their authenticator app as a QR code
//! ([`qr_svg`] of [`uri`]), and from then on asks for a code after the
//! password ([`verify`]). Codes change every 30 seconds; one from the step
//! before or after is accepted too, for clocks that drift. [`verify`]
//! returns the step a code was for, which the app stores: a later code must
//! be for a later step, so an overheard code can't be used again.
//!
//! [`recovery_codes`] are for a lost phone: each works once, and the
//! database keeps only their digests ([`crate::auth::token_digest`]).

use hmac::{Hmac, Mac};
use sha1::Sha1;

/// How long a code lasts.
const STEP_SECONDS: i64 = 30;
const DIGITS: u32 = 6;
const BASE32: &[u8; 32] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";

/// A new random secret: 20 bytes (160 bits, as RFC 4226 recommends),
/// base32-encoded as authenticator apps take it.
///
/// # Panics
///
/// If the system's random number generator fails.
pub fn new_secret() -> String {
    let mut bytes = [0u8; 20];
    getrandom::fill(&mut bytes).expect("the system's random number generator failed");
    base32(&bytes)
}

/// The `otpauth://` address an authenticator app reads from a QR code:
/// `account` (an email address) at `issuer` (the app's name).
pub fn uri(secret: &str, account: &str, issuer: &str) -> String {
    let escape = |text: &str| {
        percent_encoding::utf8_percent_encode(text, percent_encoding::NON_ALPHANUMERIC).to_string()
    };
    format!(
        "otpauth://totp/{}:{}?secret={secret}&issuer={}&algorithm=SHA1&digits={DIGITS}&period={STEP_SECONDS}",
        escape(issuer),
        escape(account),
        escape(issuer)
    )
}

/// `text` (a [`uri`]) as a QR code, an `<svg>` element to put in a page.
pub fn qr_svg(text: &str) -> String {
    match qrcode::QrCode::new(text.as_bytes()) {
        Ok(code) => code
            .render::<qrcode::render::svg::Color>()
            .min_dimensions(200, 200)
            .quiet_zone(true)
            .build(),
        // Only text too long for any QR code fails; a `uri` never is.
        Err(_) => String::new(),
    }
}

/// The code for `secret` at `unix_seconds`, as an authenticator app shows
/// it then. `None` for a secret that isn't base32.
pub fn code_at(secret: &str, unix_seconds: i64) -> Option<String> {
    let key = from_base32(secret)?;
    Some(code_for_step(&key, unix_seconds.div_euclid(STEP_SECONDS)))
}

/// The step `code` is for, when it's right for `secret` now (or a step
/// either side) and later than `after`, the step of the last code used;
/// otherwise `None`. Store the step, and pass it as `after` next time.
pub fn verify(secret: &str, code: &str, after: Option<i64>) -> Option<i64> {
    let key = from_base32(secret)?;
    let code: String = code.chars().filter(|c| !c.is_whitespace()).collect();
    if code.len() != DIGITS as usize || !code.chars().all(|c| c.is_ascii_digit()) {
        return None;
    }
    let now = crate::time::now().timestamp().div_euclid(STEP_SECONDS);
    // Every step is checked, so the time taken doesn't say which matched.
    let mut matched = None;
    for step in now - 1..=now + 1 {
        let expected = code_for_step(&key, step);
        if constant_time_eq(expected.as_bytes(), code.as_bytes())
            && after.is_none_or(|last| step > last)
        {
            matched = Some(step);
        }
    }
    matched
}

/// `count` new recovery codes, `xxxxx-xxxxx` in lowercase letters and
/// digits, to show the user once. Store their digests.
///
/// # Panics
///
/// If the system's random number generator fails.
pub fn recovery_codes(count: usize) -> Vec<String> {
    const ALPHABET: &[u8] = b"abcdefghjkmnpqrstuvwxyz23456789";
    (0..count)
        .map(|_| {
            let mut bytes = [0u8; 10];
            getrandom::fill(&mut bytes).expect("the system's random number generator failed");
            let chars: String = bytes
                .iter()
                .map(|b| ALPHABET[usize::from(*b) % ALPHABET.len()] as char)
                .collect();
            format!("{}-{}", &chars[..5], &chars[5..])
        })
        .collect()
}

/// A recovery code as typed, made ready for [`crate::auth::token_digest`]:
/// lowercase, without spaces.
pub fn normalize_recovery_code(code: &str) -> String {
    code.chars()
        .filter(|c| !c.is_whitespace())
        .collect::<String>()
        .to_lowercase()
}

fn code_for_step(key: &[u8], step: i64) -> String {
    let mut mac = Hmac::<Sha1>::new_from_slice(key).expect("HMAC takes a key of any length");
    mac.update(&step.to_be_bytes());
    let hash = mac.finalize().into_bytes();
    // RFC 4226's dynamic truncation.
    let offset = usize::from(hash[19] & 0x0f);
    let binary = u32::from_be_bytes([
        hash[offset] & 0x7f,
        hash[offset + 1],
        hash[offset + 2],
        hash[offset + 3],
    ]);
    format!(
        "{:0width$}",
        binary % 10u32.pow(DIGITS),
        width = DIGITS as usize
    )
}

fn constant_time_eq(a: &[u8], b: &[u8]) -> bool {
    a.len() == b.len() && a.iter().zip(b).fold(0u8, |acc, (x, y)| acc | (x ^ y)) == 0
}

fn base32(bytes: &[u8]) -> String {
    let mut out = String::new();
    let (mut buffer, mut bits) = (0u32, 0u32);
    for byte in bytes {
        buffer = (buffer << 8) | u32::from(*byte);
        bits += 8;
        while bits >= 5 {
            bits -= 5;
            out.push(BASE32[((buffer >> bits) & 31) as usize] as char);
        }
    }
    if bits > 0 {
        out.push(BASE32[((buffer << (5 - bits)) & 31) as usize] as char);
    }
    out
}

fn from_base32(text: &str) -> Option<Vec<u8>> {
    let mut out = Vec::new();
    let (mut buffer, mut bits) = (0u32, 0u32);
    for c in text.chars().filter(|c| !c.is_whitespace() && *c != '=') {
        let value = BASE32
            .iter()
            .position(|b| *b as char == c.to_ascii_uppercase())?;
        buffer = (buffer << 5) | value as u32;
        bits += 5;
        if bits >= 8 {
            bits -= 8;
            out.push((buffer >> bits) as u8);
        }
    }
    (!out.is_empty()).then_some(out)
}

#[cfg(test)]
mod tests {
    use super::*;

    /// RFC 6238's SHA-1 test secret, "12345678901234567890".
    fn rfc_secret() -> String {
        base32(b"12345678901234567890")
    }

    #[test]
    fn matches_rfc_6238() {
        // The RFC's 8-digit codes, of which these are the last six.
        let secret = rfc_secret();
        assert_eq!(secret, "GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ");
        assert_eq!(code_at(&secret, 59).unwrap(), "287082");
        assert_eq!(code_at(&secret, 1111111109).unwrap(), "081804");
        assert_eq!(code_at(&secret, 1234567890).unwrap(), "005924");
        assert_eq!(code_at(&secret, 2000000000).unwrap(), "279037");
    }

    #[test]
    fn base32_round_trips() {
        for bytes in [&b"f"[..], b"fo", b"foo", b"foob", b"fooba", b"foobar"] {
            assert_eq!(from_base32(&base32(bytes)).unwrap(), bytes);
        }
        assert_eq!(base32(b"foobar"), "MZXW6YTBOI");
        assert!(from_base32("not base32!").is_none());
        assert_eq!(new_secret().len(), 32);
    }

    #[test]
    fn makes_an_otpauth_uri_and_a_qr_code() {
        let uri = uri("ABC", "ada@example.com", "My App");
        assert_eq!(
            uri,
            "otpauth://totp/My%20App:ada%40example%2Ecom?secret=ABC&issuer=My%20App&algorithm=SHA1&digits=6&period=30"
        );
        assert!(qr_svg(&uri).contains("<svg"));
    }

    #[test]
    fn verifies_a_code_once() {
        let secret = new_secret();
        let now = crate::time::now().timestamp();
        let code = code_at(&secret, now).unwrap();
        let step = verify(&secret, &code, None).expect("the current code");
        assert!(verify(&secret, &code, Some(step)).is_none(), "used already");
        let spaced = format!("{} {}", &code[..3], &code[3..]);
        assert!(verify(&secret, &spaced, Some(step - 2)).is_some());
        let old = code_at(&secret, now - 120).unwrap();
        assert!(
            old == code || verify(&secret, &old, None).is_none(),
            "too old"
        );
        assert!(verify(&secret, "12345", None).is_none());
        assert!(verify(&secret, "abcdef", None).is_none());
    }

    #[test]
    fn recovery_codes_are_distinct() {
        let codes = recovery_codes(10);
        assert_eq!(codes.len(), 10);
        assert!(codes.iter().all(|c| c.len() == 11 && &c[5..6] == "-"));
        let mut unique = codes.clone();
        unique.sort();
        unique.dedup();
        assert_eq!(unique.len(), 10);
        assert_eq!(normalize_recovery_code(" ABCDE-12345 "), "abcde-12345");
    }
}