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
use std::fmt;
use std::str::FromStr;

use crate::Error;

/// The RFC 4648 base32 alphabet that authenticator apps read secrets in.
const ALPHABET: &[u8; 32] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";

/// The fewest bytes a new secret may hold: 128 bits, the minimum RFC 4226 allows.
pub const MIN_SECRET_BYTES: usize = 16;

/// The fewest bytes an existing secret may hold: 80 bits, the 16 base32 characters Fortify and
/// google2fa have long generated, so their users' secrets keep working.
pub const MIN_STORED_SECRET_BYTES: usize = 10;

/// The key an authenticator app and the server share, from which both derive the codes.
///
/// It reads and writes as base32. `Debug` hides the key.
///
/// ```
/// use laravel_two_factor::Secret;
///
/// let secret: Secret = "jbsw y3dp ehpk 3pxp jbsw y3dp ehpk 3pxp".parse()?;
///
/// assert_eq!(secret.to_base32(), "JBSWY3DPEHPK3PXPJBSWY3DPEHPK3PXP");
/// # Ok::<(), laravel_two_factor::Error>(())
/// ```
#[derive(Clone, PartialEq, Eq)]
pub struct Secret {
    bytes: Vec<u8>,
}

impl Secret {
    /// A new random secret of `bytes` bytes, from the operating system's random source.
    ///
    /// # Errors
    ///
    /// Fails when `bytes` is below [`MIN_SECRET_BYTES`], or when the operating system can't
    /// provide random bytes.
    pub fn generate(bytes: usize) -> Result<Self, Error> {
        if bytes < MIN_SECRET_BYTES {
            return Err(Error::SecretTooShort);
        }

        let mut key = vec![0; bytes];
        getrandom::fill(&mut key).map_err(|_| Error::Random)?;

        Ok(Self { bytes: key })
    }

    /// A secret from its raw bytes.
    ///
    /// # Errors
    ///
    /// Fails when there are fewer than [`MIN_STORED_SECRET_BYTES`] bytes.
    pub fn from_bytes(bytes: impl Into<Vec<u8>>) -> Result<Self, Error> {
        let bytes = bytes.into();

        if bytes.len() < MIN_STORED_SECRET_BYTES {
            return Err(Error::SecretTooShort);
        }

        Ok(Self { bytes })
    }

    /// The secret as base32 without padding, as authenticator apps and `otpauth://` URLs take it.
    #[must_use]
    pub fn to_base32(&self) -> String {
        let mut encoded = String::with_capacity(self.bytes.len().div_ceil(5) * 8);
        let mut buffer: u16 = 0;
        let mut bits = 0;

        for &byte in &self.bytes {
            buffer = (buffer << 8) | u16::from(byte);
            bits += 8;

            while bits >= 5 {
                bits -= 5;
                encoded.push(char::from(ALPHABET[usize::from((buffer >> bits) & 31)]));
            }
        }

        if bits > 0 {
            encoded.push(char::from(ALPHABET[usize::from((buffer << (5 - bits)) & 31)]));
        }

        encoded
    }

    /// The raw key bytes.
    #[must_use]
    pub fn as_bytes(&self) -> &[u8] {
        &self.bytes
    }
}

impl FromStr for Secret {
    type Err = Error;

    /// Reads base32 in either case, skipping spaces, hyphens and `=` padding. Refuses a length or
    /// last character no bytes encode to.
    fn from_str(base32: &str) -> Result<Self, Error> {
        let mut bytes = Vec::with_capacity(base32.len() * 5 / 8);
        let mut buffer: u16 = 0;
        let mut bits = 0;
        let text = base32.trim_end_matches(['=', ' ']);

        for character in text.bytes() {
            if matches!(character, b' ' | b'-') {
                continue;
            }

            let value = ALPHABET
                .iter()
                .position(|&letter| letter == character.to_ascii_uppercase())
                .ok_or(Error::InvalidSecret)?;

            buffer = (buffer << 5) | u16::try_from(value).expect("an index below 32");
            bits += 5;

            if bits >= 8 {
                bits -= 8;
                bytes.push(u8::try_from((buffer >> bits) & 0xff).expect("a byte"));
            }
        }

        // Leftover bits are padding, fewer than 5 and all zero.
        if bits >= 5 || buffer & ((1 << bits) - 1) != 0 {
            return Err(Error::InvalidSecret);
        }

        Self::from_bytes(bytes)
    }
}

impl fmt::Debug for Secret {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str("Secret(..)")
    }
}