ch-auth 0.3.2

Authentication and session primitives with explicit security policies
Documentation
use base64::Engine;
use base64::engine::general_purpose::STANDARD as BASE64_STANDARD;
use getrandom::fill;
use otpauth::TOTP;
use qrcode::{QrCode, render::svg};
use std::time::{SystemTime, UNIX_EPOCH};
use thiserror::Error;
use zeroize::Zeroizing;

use crate::accounts::{RandomCodeSpec, generate_random_code};

use super::{BACKUP_CODE_COUNT, BACKUP_CODE_LENGTH, TOTP_PERIOD_SECONDS};

const TOTP_SECRET_LENGTH: usize = 20;
const BACKUP_CODE_ALPHABET: &str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";

/// Error states returned by server-side two-factor helpers.
#[derive(Debug, Clone, Copy, Error, PartialEq, Eq)]
pub enum TwoFactorServerError {
    /// The operating system could not provide cryptographically secure randomness.
    #[error("secure randomness is unavailable")]
    Random,
    /// The supplied TOTP secret was empty.
    #[error("the TOTP secret is missing")]
    TotpSecretMissing,
    /// The supplied Base32 TOTP secret could not be decoded.
    #[error("the TOTP secret is invalid")]
    TotpDecode,
    /// The OTPAUTH URI could not be encoded as a QR code.
    #[error("the OTPAUTH URI could not be encoded as a QR code")]
    QrCode,
    /// The system clock is earlier than the Unix epoch.
    #[error("the system clock predates the Unix epoch")]
    SystemTime,
}

/// Generates a new TOTP secret and OTPAUTH URI for the account identifier.
pub fn build_totp_secret(
    issuer: &str,
    account_identifier: &str,
) -> Result<(String, String), TwoFactorServerError> {
    let mut secret_bytes = Zeroizing::new(vec![0u8; TOTP_SECRET_LENGTH]);
    fill(secret_bytes.as_mut_slice()).map_err(|_| TwoFactorServerError::Random)?;

    let totp = TOTP::from_bytes(&secret_bytes);
    let secret = totp.base32_secret();
    let label = format!("{issuer}:{account_identifier}");
    let otpauth_uri = totp.to_uri(label, issuer.to_string());

    Ok((secret, otpauth_uri))
}

/// Builds an OTPAUTH URI for an existing Base32 TOTP secret.
pub fn build_totp_uri_from_secret(
    secret: &str,
    issuer: &str,
    account_identifier: &str,
) -> Result<String, TwoFactorServerError> {
    let secret = secret.trim();
    if secret.is_empty() {
        return Err(TwoFactorServerError::TotpSecretMissing);
    }

    let totp = TOTP::from_base32(secret).ok_or(TwoFactorServerError::TotpDecode)?;
    let label = format!("{issuer}:{account_identifier}");
    Ok(totp.to_uri(label, issuer.to_string()))
}

/// Renders QR code artifacts for the provided OTPAUTH URI.
pub fn render_qr_artifacts(otpauth_uri: &str) -> Result<(String, String), TwoFactorServerError> {
    let qr_code = QrCode::new(otpauth_uri.as_bytes()).map_err(|_| TwoFactorServerError::QrCode)?;

    let qr_svg = qr_code
        .render::<svg::Color>()
        .min_dimensions(256, 256)
        .dark_color(svg::Color("#0f172a"))
        .light_color(svg::Color("#ffffff"))
        .build();

    let qr_png_data_uri = format!(
        "data:image/svg+xml;base64,{}",
        BASE64_STANDARD.encode(qr_svg.as_bytes())
    );

    Ok((qr_svg, qr_png_data_uri))
}

/// Generates a batch of randomized backup codes.
pub fn build_backup_codes() -> Result<Vec<String>, TwoFactorServerError> {
    let mut codes = Vec::with_capacity(BACKUP_CODE_COUNT);

    while codes.len() < BACKUP_CODE_COUNT {
        let code = random_backup_code()?;

        if codes.iter().any(|existing| existing == &code) {
            continue;
        }

        codes.push(code);
    }

    Ok(codes)
}

fn random_backup_code() -> Result<String, TwoFactorServerError> {
    let spec = RandomCodeSpec::new(BACKUP_CODE_LENGTH, BACKUP_CODE_ALPHABET)
        .expect("the static backup-code format is valid");
    generate_random_code(spec).map_err(|_| TwoFactorServerError::Random)
}

/// Returns the matching TOTP timestep at the current system time.
/// The application must consume this step durably before granting access.
pub fn verify_totp_step(secret: &str, code: u32) -> Result<Option<u64>, TwoFactorServerError> {
    let timestamp = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map_err(|_| TwoFactorServerError::SystemTime)?
        .as_secs();
    verify_totp_step_at(secret, code, timestamp)
}

/// Returns the matching timestep for a supplied timestamp.
/// Only the current 30-second step is accepted. No drift window is added.
pub fn verify_totp_step_at(
    secret: &str,
    code: u32,
    timestamp: u64,
) -> Result<Option<u64>, TwoFactorServerError> {
    let secret = secret.trim();
    if secret.is_empty() {
        return Err(TwoFactorServerError::TotpSecretMissing);
    }
    let totp = TOTP::from_base32(secret).ok_or(TwoFactorServerError::TotpDecode)?;
    Ok(totp
        .verify(code, TOTP_PERIOD_SECONDS, timestamp)
        .then_some(timestamp / TOTP_PERIOD_SECONDS))
}

#[cfg(test)]
mod tests {
    use super::{
        BACKUP_CODE_ALPHABET, BACKUP_CODE_COUNT, BACKUP_CODE_LENGTH, build_backup_codes,
        build_totp_secret, build_totp_uri_from_secret, render_qr_artifacts,
    };
    use otpauth::TOTP;

    #[test]
    fn verified_step_uses_the_same_clock_sample_and_rejects_adjacent_windows() {
        let secret = "GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ";
        assert_eq!(super::verify_totp_step_at(secret, 287082, 59), Ok(Some(1)));
        assert_eq!(super::verify_totp_step_at(secret, 287082, 60), Ok(None));
        assert_eq!(super::verify_totp_step_at(secret, 287082, 29), Ok(None));
        assert_eq!(
            super::verify_totp_step_at("", 287082, 59),
            Err(super::TwoFactorServerError::TotpSecretMissing)
        );
        assert_eq!(
            super::verify_totp_step_at("invalid!", 287082, 59),
            Err(super::TwoFactorServerError::TotpDecode)
        );
    }

    #[test]
    fn backup_codes_are_unique_and_well_formed() {
        let codes = build_backup_codes().expect("backup codes should generate");
        assert_eq!(codes.len(), BACKUP_CODE_COUNT);
        for code in &codes {
            assert_eq!(code.len(), BACKUP_CODE_LENGTH);
            assert!(
                code.bytes()
                    .all(|byte| BACKUP_CODE_ALPHABET.as_bytes().contains(&byte))
            );
        }
    }

    #[test]
    fn rejection_sampling_maps_every_symbol_equally() {
        let acceptance_bound = 256 - (256 % BACKUP_CODE_ALPHABET.len());
        let mut counts = vec![0_usize; BACKUP_CODE_ALPHABET.len()];
        for byte in 0_u8..=u8::MAX {
            if usize::from(byte) < acceptance_bound {
                counts[usize::from(byte) % BACKUP_CODE_ALPHABET.len()] += 1;
            }
        }
        assert!(counts.windows(2).all(|window| window[0] == window[1]));
    }

    #[test]
    fn totp_secret_and_uri_include_issuer_and_identifier() {
        let (secret, uri) =
            build_totp_secret("TestIssuer", "test@example.com").expect("secret should generate");
        assert!(!secret.is_empty());
        assert!(uri.contains("TestIssuer"));
        assert!(uri.contains("test@example.com"));
    }

    #[test]
    fn totp_uri_from_secret_includes_issuer() {
        let totp = TOTP::from_bytes(&[0u8; 20]);
        let secret = totp.base32_secret();
        let uri = build_totp_uri_from_secret(&secret, "TestIssuer", "test@example.com")
            .expect("uri should build");
        assert!(uri.contains("TestIssuer"));
        assert!(uri.contains("test@example.com"));
    }

    #[test]
    fn qr_artifacts_are_rendered() {
        let uri = "otpauth://totp/TestIssuer:test@example.com?secret=ABC&issuer=TestIssuer";
        let (svg, png) = render_qr_artifacts(uri).expect("qr should render");
        assert!(!svg.is_empty());
        assert!(png.starts_with("data:image/svg+xml;base64,"));
    }
}