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
//! Codes, secrets and URLs, checked against the RFCs' own test vectors.

use laravel_two_factor::{Algorithm, Error, MAX_PERIOD, RecoveryCodes, Secret, TwoFactor, TwoFactorConfig};

fn two_factor(algorithm: Algorithm, digits: u32) -> TwoFactor {
    TwoFactor::new(TwoFactorConfig {
        algorithm,
        digits,
        ..TwoFactorConfig::default()
    })
    .unwrap()
}

fn ascii_secret(text: &str) -> Secret {
    Secret::from_bytes(text.as_bytes()).unwrap()
}

/// RFC 4226, appendix D: the HOTP values for counters 0 to 9. TOTP at `30 * counter` seconds is
/// HOTP at that counter.
#[test]
fn hotp_matches_rfc_4226() {
    let secret = ascii_secret("12345678901234567890");
    let expected = [
        "755224", "287082", "359152", "969429", "338314", "254676", "287922", "162583", "399871", "520489",
    ];

    for (counter, code) in (0u64..).zip(expected) {
        assert_eq!(
            TwoFactor::default().code_at(&secret, counter * 30),
            code,
            "counter {counter}"
        );
    }
}

/// RFC 6238, appendix B: eight-digit codes for SHA1, SHA256 and SHA512, including ones that
/// start with a zero and times past 2038.
#[test]
fn totp_matches_rfc_6238() {
    let sha1 = ascii_secret("12345678901234567890");
    let sha256 = ascii_secret("12345678901234567890123456789012");
    let sha512 = ascii_secret("1234567890123456789012345678901234567890123456789012345678901234");
    let table = [
        (59, "94287082", "46119246", "90693936"),
        (1_111_111_109, "07081804", "68084774", "25091201"),
        (1_111_111_111, "14050471", "67062674", "99943326"),
        (1_234_567_890, "89005924", "91819424", "93441116"),
        (2_000_000_000, "69279037", "90698825", "38618901"),
        (20_000_000_000, "65353130", "77737706", "47863826"),
    ];

    for (time, one, two_five_six, five_twelve) in table {
        assert_eq!(
            two_factor(Algorithm::Sha1, 8).code_at(&sha1, time),
            one,
            "SHA1 at {time}"
        );
        assert_eq!(
            two_factor(Algorithm::Sha256, 8).code_at(&sha256, time),
            two_five_six,
            "SHA256 at {time}"
        );
        assert_eq!(
            two_factor(Algorithm::Sha512, 8).code_at(&sha512, time),
            five_twelve,
            "SHA512 at {time}"
        );
    }
}

/// The codes google2fa's own tests expect, for a 16-character secret Fortify could have stored,
/// around period 26213400 (Unix time 786402000).
#[test]
fn codes_match_google2fa_for_short_stored_secrets() {
    let secret: Secret = "ADUMJO5634NPDEKW".parse().unwrap();
    let table = [
        (26_213_397, "093183", "152688", "705476"),
        (26_213_399, "981084", "064978", "048034"),
        (26_213_400, "512396", "758576", "752139"),
        (26_213_402, "239815", "044590", "424074"),
    ];

    for (step, one, two_five_six, five_twelve) in table {
        let time = step * 30;
        assert_eq!(two_factor(Algorithm::Sha1, 6).code_at(&secret, time), one);
        assert_eq!(two_factor(Algorithm::Sha256, 6).code_at(&secret, time), two_five_six);
        assert_eq!(two_factor(Algorithm::Sha512, 6).code_at(&secret, time), five_twelve);
    }

    assert_eq!(
        two_factor(Algorithm::Sha1, 7).code_at(&secret, 26_213_399 * 30),
        "8981084"
    );
}

#[test]
fn verify_accepts_the_window_and_nothing_past_it() {
    let secret = ascii_secret("12345678901234567890");
    let two_factor = TwoFactor::default();
    let now = 1_111_111_111; // Step 37037037, 1 second into it.

    let previous = two_factor.code_at(&secret, now - 30);
    let next = two_factor.code_at(&secret, now + 30);
    let too_old = two_factor.code_at(&secret, now - 60);
    let too_new = two_factor.code_at(&secret, now + 60);

    assert_eq!(two_factor.verify_at(&secret, &previous, now), Some(37_037_036));
    assert_eq!(two_factor.verify_at(&secret, &next, now), Some(37_037_038));
    assert_eq!(two_factor.verify_at(&secret, &too_old, now), None);
    assert_eq!(two_factor.verify_at(&secret, &too_new, now), None);

    let strict = TwoFactor::new(TwoFactorConfig {
        window: 0,
        ..TwoFactorConfig::default()
    })
    .unwrap();
    assert_eq!(strict.verify_at(&secret, &previous, now), None);
}

#[test]
fn verify_reads_spaces_and_refuses_anything_but_the_digits() {
    let secret = ascii_secret("12345678901234567890");
    let two_factor = two_factor(Algorithm::Sha1, 8);
    let time = 1_111_111_109;

    // The code starts with a zero, which a number would drop.
    assert!(two_factor.verify_at(&secret, "07081804", time).is_some());
    assert!(two_factor.verify_at(&secret, " 0708 1804 ", time).is_some());
    assert!(two_factor.verify_at(&secret, "0708-1804", time).is_some());
    assert!(two_factor.verify_at(&secret, "7081804", time).is_none());
    assert!(two_factor.verify_at(&secret, "070818040", time).is_none());
    assert!(two_factor.verify_at(&secret, "+7081804", time).is_none());
    assert!(two_factor.verify_at(&secret, "", time).is_none());
}

#[test]
fn verify_at_the_start_of_time_does_not_underflow() {
    let secret = ascii_secret("12345678901234567890");

    assert_eq!(TwoFactor::default().verify_at(&secret, "755224", 0), Some(0));
}

#[test]
fn secrets_read_and_write_base32() {
    let secret = ascii_secret("12345678901234567890");

    assert_eq!(secret.to_base32(), "GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ");
    assert_eq!(
        "gezd gnbv gy3t qojq gezd gnbv gy3t qojq".parse::<Secret>().unwrap(),
        secret
    );
    assert_eq!(
        "GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ====".parse::<Secret>().unwrap(),
        secret
    );

    // 16 characters hold 10 bytes, the shortest stored secret Fortify writes; 15 hold 9.
    let short: Secret = "ADUMJO5634NPDEKW".parse().unwrap();
    assert_eq!(short.as_bytes().len(), 10);
    assert_eq!(short.to_base32(), "ADUMJO5634NPDEKW");
    assert_eq!(Secret::from_bytes([0; 9]), Err(Error::SecretTooShort));
    assert_eq!("ADUMJO5634NPDEQ".parse::<Secret>(), Err(Error::SecretTooShort));
    assert_eq!(
        "GEZDGNBVGY3TQOJQGEZDGNBVGY1".parse::<Secret>(),
        Err(Error::InvalidSecret)
    );
    assert_eq!(format!("{secret:?}"), "Secret(..)");
}

#[test]
fn generated_secrets_are_random_and_the_configured_size() {
    let two_factor = TwoFactor::default();
    let one = two_factor.generate_secret().unwrap();
    let two = two_factor.generate_secret().unwrap();

    assert_eq!(one.as_bytes().len(), 20);
    assert_eq!(one.to_base32().len(), 32);
    assert_ne!(one, two);
    assert_eq!(Secret::generate(15), Err(Error::SecretTooShort));
    assert!(Secret::generate(16).is_ok());
}

#[test]
fn urls_name_the_issuer_and_account() {
    let secret = ascii_secret("12345678901234567890");
    let two_factor = TwoFactor::new(TwoFactorConfig {
        issuer: Some("Acme & Co".into()),
        ..TwoFactorConfig::default()
    })
    .unwrap();

    assert_eq!(
        two_factor.url(&secret, "taylor+2fa@example.com").unwrap(),
        "otpauth://totp/Acme%20%26%20Co:taylor%2B2fa%40example.com?secret=GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ&issuer=Acme%20%26%20Co&algorithm=SHA1&digits=6&period=30",
    );
    assert_eq!(
        TwoFactor::default().url(&secret, "taylor").unwrap(),
        "otpauth://totp/taylor?secret=GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ&algorithm=SHA1&digits=6&period=30",
    );

    let accented = TwoFactor::new(TwoFactorConfig {
        issuer: Some("Café".into()),
        ..TwoFactorConfig::default()
    })
    .unwrap();
    assert!(
        accented
            .url(&secret, "zoë")
            .unwrap()
            .starts_with("otpauth://totp/Caf%C3%A9:zo%C3%AB?")
    );

    // The scan itself is checked by hand in an authenticator app; here, the code follows the URL.
    let svg = two_factor.qr_code_svg(&secret, "taylor@example.com").unwrap();
    assert!(svg.starts_with("<?xml") && svg.contains("<svg"), "{svg}");
    assert_eq!(Ok(svg.clone()), two_factor.qr_code_svg(&secret, "taylor@example.com"));
    assert_ne!(Ok(svg), two_factor.qr_code_svg(&secret, "abigail@example.com"));
}

#[test]
fn recovery_codes_log_in_once_each() {
    let mut codes = RecoveryCodes::generate(8);

    assert_eq!(codes.len(), 8);
    assert!(codes.iter().all(|code| code.len() == 21 && code.as_bytes()[10] == b'-'));

    let used = codes[3].clone();
    let others = [codes[0].clone(), codes[7].clone()];

    assert!(RecoveryCodes::redeem(&mut codes, &format!(" {used} ")));
    assert!(!RecoveryCodes::redeem(&mut codes, &used));
    assert!(!codes.contains(&used));
    assert_eq!(codes.len(), 8);
    assert!(others.iter().all(|code| codes.contains(code)));
    assert!(!RecoveryCodes::redeem(&mut codes, ""));
}

#[test]
fn the_defaults_are_what_every_app_shows() {
    let config = TwoFactorConfig::default();

    assert_eq!(
        (
            config.issuer,
            config.digits,
            config.period,
            config.window,
            config.algorithm,
            config.secret_bytes,
            config.cache_store
        ),
        (None, 6, 30, 1, Algorithm::Sha1, 20, None)
    );
}

#[test]
fn configs_no_app_can_show_are_refused() {
    let with = |change: fn(&mut TwoFactorConfig)| {
        let mut config = TwoFactorConfig::default();
        change(&mut config);
        TwoFactor::new(config).map(|_| ())
    };

    assert!(with(|c| c.digits = 8).is_ok());
    assert!(matches!(with(|c| c.digits = 5), Err(Error::InvalidConfig(_))));
    assert!(matches!(with(|c| c.digits = 9), Err(Error::InvalidConfig(_))));
    assert!(matches!(with(|c| c.period = 0), Err(Error::InvalidConfig(_))));
    assert!(with(|c| c.window = 10).is_ok());
    assert!(matches!(with(|c| c.window = 11), Err(Error::InvalidConfig(_))));
    assert!(matches!(
        with(|c| c.period = MAX_PERIOD + 1),
        Err(Error::InvalidConfig(_))
    ));
    assert!(matches!(
        with(|c| c.issuer = Some("Acme: Billing".into())),
        Err(Error::InvalidConfig(_))
    ));
    assert_eq!(with(|c| c.secret_bytes = 15), Err(Error::SecretTooShort));
    assert!(
        with(|c| {
            c.period = MAX_PERIOD;
            c.window = 10;
        })
        .is_ok()
    );

    assert_eq!("sha256".parse(), Ok(Algorithm::Sha256));
    assert!(matches!("md5".parse::<Algorithm>(), Err(Error::InvalidConfig(_))));
}

#[test]
fn urls_carry_the_configured_digits_and_period() {
    let secret = ascii_secret("12345678901234567890");
    let two_factor = TwoFactor::new(TwoFactorConfig {
        digits: 8,
        period: 60,
        algorithm: Algorithm::Sha256,
        ..TwoFactorConfig::default()
    })
    .unwrap();

    assert!(
        two_factor
            .url(&secret, "taylor")
            .unwrap()
            .ends_with("&algorithm=SHA256&digits=8&period=60")
    );
    // A 60-second period: 0 to 59 is one code, 60 the next.
    assert_eq!(two_factor.code_at(&secret, 0), two_factor.code_at(&secret, 59));
    assert_ne!(two_factor.code_at(&secret, 59), two_factor.code_at(&secret, 60));
    assert_eq!(two_factor.code_at(&secret, 0).len(), 8);
}

#[test]
fn base32_refuses_lengths_and_last_characters_no_bytes_encode_to() {
    let short: Secret = "ADUMJO5634NPDEKW".parse().unwrap();

    // Case, spaces, hyphens and padding still read.
    assert_eq!("adumjo56-34np dekw======".parse::<Secret>(), Ok(short));

    // 17 characters: 16 hold 10 bytes, and one more holds 5 bits, not a byte.
    assert_eq!("ADUMJO5634NPDEKWA".parse::<Secret>(), Err(Error::InvalidSecret));
    assert_eq!("ADUMJO5634NPDEKWAAA".parse::<Secret>(), Err(Error::InvalidSecret));
    assert_eq!("ADUMJO5634NPDEKWAAAAAA".parse::<Secret>(), Err(Error::InvalidSecret));

    // 18 characters hold 11 bytes and 2 bits over, which must be zero: `Q` is 10000, `R` 10001.
    assert_eq!("ADUMJO5634NPDEKWAQ".parse::<Secret>().unwrap().as_bytes().len(), 11);
    assert_eq!("ADUMJO5634NPDEKWAR".parse::<Secret>(), Err(Error::InvalidSecret));
}

#[test]
fn an_account_with_a_colon_or_a_url_too_long_for_a_qr_code_is_an_error() {
    let secret = ascii_secret("12345678901234567890");
    let two_factor = TwoFactor::default();

    assert_eq!(two_factor.url(&secret, "taylor:otwell"), Err(Error::InvalidAccount));
    assert_eq!(
        two_factor.qr_code_svg(&secret, "taylor:otwell"),
        Err(Error::InvalidAccount)
    );
    assert_eq!(two_factor.qr_code_svg(&secret, &"a".repeat(3_000)), Err(Error::QrCode));
}