feat(auth): password hashing, TOTP and recovery codes

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Lucas RayanandClaude Opus 5.5 committed 2026-11-04 19:10:26 -03:00
1 parent fbaeeca60c
commit deea3e245b
5 files changed
+10887 -2

No files matched your search

+2
View File
@@ -22,6 +22,8 @@ duckdb = "~1.10506.1"
aes-gcm = "0.10"
base64 = "0.22"
fs2 = "0.4"
argon2 = "0.6.0"
totp-rs = { version = "6.0.0", features = ["qr", "otpauth"] }
[dev-dependencies]
tempfile = "3"
File diff suppressed because it is too large. Load diff
+362
View File
@@ -0,0 +1,362 @@
//! Password hashing, TOTP and recovery codes. Crypto comes from audited
//! crates (`argon2`, `totp-rs`); nothing here is hand-rolled.
use super::secrets::{hash_token, random_token};
use crate::error::{AcauaError, Result};
use aes_gcm::aead::{rand_core::RngCore, OsRng};
use argon2::password_hash::{PasswordHasher, PasswordVerifier};
use argon2::{Algorithm, Argon2, Params, Version};
use std::collections::HashSet;
use std::str::FromStr;
use std::sync::OnceLock;
use totp_rs::{Algorithm as TotpAlgorithm, Builder as TotpBuilder, Totp};
/// Minimum password length, in characters.
pub const PASSWORD_MIN_CHARS: usize = 12;
/// Maximum password length, in bytes (bounds Argon2 work per request).
pub const PASSWORD_MAX_BYTES: usize = 256;
/// Argon2id cost: m=19456 KiB, t=2, p=1 (OWASP minimum profile).
const ARGON_M_KIB: u32 = 19_456;
const ARGON_T: u32 = 2;
const ARGON_P: u32 = 1;
const TOTP_SECRET_BYTES: usize = 20;
const TOTP_DIGITS: u8 = 6;
const TOTP_STEP_SECS: u64 = 30;
const TOTP_SKEW: u16 = 1;
const TOTP_ISSUER: &str = "Acauã";
const RECOVERY_CODE_COUNT: usize = 10;
const RECOVERY_CODE_BYTES: usize = 10; // 80 bits
/// SecLists 10k-most-common (MIT). Untrusted data: only a word list.
static COMMON_PASSWORDS_RAW: &str = include_str!("common-passwords.txt");
fn common_passwords() -> &'static HashSet<String> {
static SET: OnceLock<HashSet<String>> = OnceLock::new();
SET.get_or_init(|| {
COMMON_PASSWORDS_RAW
.lines()
.map(str::trim)
.filter(|l| !l.is_empty() && !l.starts_with('#'))
.map(str::to_lowercase)
.collect()
})
}
fn is_common(password: &str) -> bool {
let lower = password.to_lowercase();
let set = common_passwords();
if set.contains(&lower) {
return true;
}
// Common word plus a numeric suffix ("password1234") is no better.
let base = lower.trim_end_matches(|c: char| c.is_ascii_digit());
!base.is_empty() && base.len() != lower.len() && set.contains(base)
}
/// Rejects short, oversized and common passwords. No composition rules.
/// Error messages never echo the password.
pub fn validate_password(password: &str) -> Result<()> {
if password.len() > PASSWORD_MAX_BYTES {
return Err(AcauaError::InvalidInput(format!(
"password must be at most {PASSWORD_MAX_BYTES} bytes"
)));
}
if password.chars().count() < PASSWORD_MIN_CHARS {
return Err(AcauaError::InvalidInput(format!(
"password must be at least {PASSWORD_MIN_CHARS} characters"
)));
}
if is_common(password) {
return Err(AcauaError::InvalidInput(
"password is too common".to_string(),
));
}
Ok(())
}
fn argon2() -> Result<Argon2<'static>> {
let params = Params::new(ARGON_M_KIB, ARGON_T, ARGON_P, None).map_err(|_| hash_failure())?;
Ok(Argon2::new(Algorithm::Argon2id, Version::V0x13, params))
}
fn hash_failure() -> AcauaError {
AcauaError::CommandFailed {
cmd: "argon2".to_string(),
detail: "password hashing failed".to_string(),
}
}
/// Argon2id (m=19456 KiB, t=2, p=1) hash in PHC string format, random salt.
pub fn hash_password(password: &str) -> Result<String> {
if password.len() > PASSWORD_MAX_BYTES {
return Err(AcauaError::InvalidInput(format!(
"password must be at most {PASSWORD_MAX_BYTES} bytes"
)));
}
let hash = argon2()?
.hash_password(password.as_bytes())
.map_err(|_| hash_failure())?;
Ok(hash.to_string())
}
fn dummy_hash() -> Option<&'static str> {
static DUMMY: OnceLock<Option<String>> = OnceLock::new();
DUMMY
.get_or_init(|| hash_password(&random_token(24)).ok())
.as_deref()
}
/// Verifies a candidate. With `hash == None` (unknown user) a dummy hash is
/// still verified so timing does not reveal whether the user exists; the
/// result is then always `false`. A malformed stored hash also yields `false`.
pub fn verify_password(hash: Option<&str>, candidate: &str) -> bool {
// Oversized input is refused before any Argon2 work.
if candidate.len() > PASSWORD_MAX_BYTES {
return false;
}
let Ok(engine) = argon2() else { return false };
let (stored, real) = match hash {
Some(h) => (h, true),
None => match dummy_hash() {
Some(d) => (d, false),
None => return false,
},
};
let Ok(parsed) = argon2::password_hash::phc::PasswordHash::from_str(stored) else {
return false;
};
let ok = engine
.verify_password(candidate.as_bytes(), &parsed)
.is_ok();
ok && real
}
/// 160-bit random TOTP secret from the OS CSPRNG.
pub fn new_totp_secret() -> Vec<u8> {
let mut buf = vec![0u8; TOTP_SECRET_BYTES];
OsRng.fill_bytes(&mut buf);
buf
}
fn build_totp(secret: &[u8], account: &str) -> Result<Totp> {
TotpBuilder::new()
.with_algorithm(TotpAlgorithm::SHA1)
.with_digits(TOTP_DIGITS)
.with_skew(TOTP_SKEW)
.with_step_duration(TOTP_STEP_SECS)
.with_secret(secret.to_vec())
.with_account_name(account)
.with_issuer(Some(TOTP_ISSUER))
.build()
.map_err(|_| AcauaError::InvalidInput("invalid TOTP secret or account name".to_string()))
}
/// `otpauth://` URI and the QR code as base64 PNG.
pub fn totp_uri_and_qr(secret: &[u8], account: &str) -> Result<(String, String)> {
let totp = build_totp(secret, account)?;
let fail = |_| AcauaError::InvalidInput("could not encode TOTP enrolment".to_string());
let uri = totp.to_url().map_err(fail)?;
let qr = totp.to_qr_base64().map_err(fail)?;
Ok((uri, qr))
}
/// Checks a code at `unix` (SHA-1, 6 digits, 30 s, +-1 step). Returns the
/// accepted step, or `None` if invalid or not newer than `last_step`
/// (a step is never accepted twice).
pub fn verify_totp(secret: &[u8], code: &str, unix: u64, last_step: Option<u64>) -> Option<u64> {
let totp = build_totp(secret, "acaua").ok()?;
let step = totp.check(code.trim(), unix)?;
match last_step {
Some(last) if step <= last => None,
_ => Some(step),
}
}
/// Canonical form used for hashing: alphanumerics only, lowercase.
fn canonical_recovery(code: &str) -> String {
code.chars()
.filter(char::is_ascii_alphanumeric)
.map(|c| c.to_ascii_lowercase())
.collect()
}
/// Hash stored for a recovery code (case and separators ignored).
pub fn hash_recovery_code(code: &str) -> String {
hash_token(&canonical_recovery(code))
}
/// Ten single-use 80-bit codes: `(display texts, SHA-256 hashes)`. Codes are
/// 20 hex digits in groups of five; only the hashes should be persisted.
pub fn new_recovery_codes() -> (Vec<String>, Vec<String>) {
let mut seen = HashSet::new();
let mut texts = Vec::with_capacity(RECOVERY_CODE_COUNT);
let mut hashes = Vec::with_capacity(RECOVERY_CODE_COUNT);
while texts.len() < RECOVERY_CODE_COUNT {
let mut raw = [0u8; RECOVERY_CODE_BYTES];
OsRng.fill_bytes(&mut raw);
let hex: String = raw.iter().map(|b| format!("{b:02x}")).collect();
if !seen.insert(hex.clone()) {
continue;
}
let text = format!(
"{}-{}-{}-{}",
&hex[0..5],
&hex[5..10],
&hex[10..15],
&hex[15..20]
);
hashes.push(hash_recovery_code(&text));
texts.push(text);
}
(texts, hashes)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn rejects_short_common_and_oversized_password() {
assert!(validate_password("abcdefghijk").is_err(), "11 chars");
assert!(validate_password("password1234").is_err(), "common");
assert!(
validate_password("PASSWORD1234").is_err(),
"common, case-insensitive"
);
assert!(validate_password(&"a1".repeat(129)).is_err(), "258 bytes");
assert!(validate_password(&"x".repeat(257)).is_err(), "257 bytes");
assert!(validate_password("correct horse battery staple").is_ok());
assert!(validate_password("ação de graças tardia").is_ok());
// 12 chars but more than 12 bytes: length counts characters.
assert!(validate_password("ããããããããããàã").is_ok());
}
#[test]
fn password_roundtrip_and_params() {
let h = hash_password("correct horse battery staple").unwrap();
assert!(h.starts_with("$argon2id$v=19$m=19456,t=2,p=1$"), "{h}");
assert!(verify_password(Some(&h), "correct horse battery staple"));
assert!(!verify_password(Some(&h), "correct horse battery stapl"));
assert!(!verify_password(Some("not a phc string"), "x"));
assert_ne!(
h,
hash_password("correct horse battery staple").unwrap(),
"salted"
);
}
#[test]
fn verify_password_handles_missing_user() {
assert!(!verify_password(None, "x"));
assert!(!verify_password(None, "correct horse battery staple"));
}
fn rfc_secret() -> &'static [u8] {
b"12345678901234567890"
}
#[test]
fn totp_rfc6238_vector() {
// RFC 6238 appendix B, T=59 -> 94287082 (8 digits) -> 287082 (6).
assert_eq!(verify_totp(rfc_secret(), "287082", 59, None), Some(1));
assert_eq!(verify_totp(rfc_secret(), "287083", 59, None), None);
assert_eq!(verify_totp(rfc_secret(), "28708", 59, None), None);
assert_eq!(verify_totp(rfc_secret(), "2870820", 59, None), None);
assert_eq!(verify_totp(rfc_secret(), "abcdef", 59, None), None);
}
#[test]
fn totp_window_and_replay() {
// "287082" is the code for step 1. Steps 0 and 2 are +-1 of it.
assert_eq!(
verify_totp(rfc_secret(), "287082", 0, None),
Some(1),
"-1 step"
);
assert_eq!(
verify_totp(rfc_secret(), "287082", 89, None),
Some(1),
"+1 step"
);
assert_eq!(
verify_totp(rfc_secret(), "287082", 30 * 3, None),
None,
"+2 steps"
);
assert_eq!(
verify_totp(rfc_secret(), "287082", 30 * 4, None),
None,
"+3 steps"
);
// Step 1 at unix 1000 would be -32 steps; use a larger base to test -2.
assert_eq!(verify_totp(rfc_secret(), "287082", 30 * 101, None), None);
assert_eq!(
verify_totp(rfc_secret(), "287082", 59, Some(1)),
None,
"replay"
);
assert_eq!(
verify_totp(rfc_secret(), "287082", 59, Some(2)),
None,
"older than last"
);
assert_eq!(verify_totp(rfc_secret(), "287082", 59, Some(0)), Some(1));
}
#[test]
fn totp_rejects_future_steps_beyond_tolerance() {
let totp = build_totp(rfc_secret(), "a").unwrap();
let code_step_5 = totp.generate(5 * 30).to_string();
assert_eq!(
verify_totp(rfc_secret(), &code_step_5, 4 * 30, None),
Some(5),
"+1 ahead"
);
assert_eq!(
verify_totp(rfc_secret(), &code_step_5, 3 * 30, None),
None,
"2 ahead"
);
}
#[test]
fn totp_uri_and_qr_shape() {
let secret = new_totp_secret();
assert_eq!(secret.len(), 20);
assert_ne!(secret, new_totp_secret());
let (uri, qr) = totp_uri_and_qr(&secret, "ana@example.org").unwrap();
assert!(uri.starts_with("otpauth://totp/"), "{uri}");
// SHA1 / 6 digits / 30 s are the otpauth defaults, so they are omitted.
assert!(uri.contains("secret=") && !uri.contains("algorithm=SHA256"));
assert!(uri.contains("issuer="), "{uri}");
use base64::{engine::general_purpose::STANDARD, Engine};
let png = STANDARD.decode(qr).unwrap();
assert_eq!(&png[..4], b"\x89PNG");
}
#[test]
fn recovery_codes_unique_and_hashed() {
let (codes, hashes) = new_recovery_codes();
assert_eq!(codes.len(), 10);
assert_eq!(hashes.len(), 10);
let uniq: std::collections::HashSet<_> = codes.iter().collect();
assert_eq!(uniq.len(), 10);
let uh: std::collections::HashSet<_> = hashes.iter().collect();
assert_eq!(uh.len(), 10);
for (c, h) in codes.iter().zip(&hashes) {
assert_ne!(c, h);
assert_eq!(h, &hash_recovery_code(c));
assert_eq!(h.len(), 64);
}
}
#[test]
fn recovery_hash_ignores_case_and_separators() {
let (codes, hashes) = new_recovery_codes();
let mangled = codes[0].replace('-', " ").to_uppercase();
assert_eq!(hash_recovery_code(&mangled), hashes[0]);
}
}
+1
View File
@@ -3,6 +3,7 @@
//! Layout: `<data_dir>/auth/{state.json,secret.key,audit.jsonl,.lock}`.
pub mod audit;
pub mod credentials;
pub mod secrets;
pub mod store;