Skip to content
1        10        20        30        40        50        60        70        80        901use anyhow::{Result, bail};2use argon2::password_hash::phc::PasswordHash;3use argon2::{Argon2, PasswordHasher, PasswordVerifier};4use rand::TryRng;5use rand::rngs::SysRng;6use rusqlite::{Connection, OptionalExtension, params};7use uuid::Uuid;89use crate::db::now;1011/// Minimum length for a password a person chooses. Generated passwords are longer.12pub const MIN_PASSWORD_LEN: usize = 12;13const MAX_USERNAME_LEN: usize = 64;1415pub struct User {16    pub id: String,17    pub username: String,18}1920/// A 128-bit random password, printed once by the CLI and changed later on the Account page.21pub fn generate_password() -> String {22    let mut bytes = [0u8; 16];23    SysRng24        .try_fill_bytes(&mut bytes)25        .expect("operating system RNG should be available");26    hex::encode(bytes)27}2829pub fn check_username(username: &str) -> Result<(), String> {30    if username.is_empty() || username.len() > MAX_USERNAME_LEN {31        return Err(format!(32            "usernames must be 1 to {MAX_USERNAME_LEN} characters"33        ));34    }35    if !username36        .chars()37        .all(|c| c.is_ascii_alphanumeric() || matches!(c, '_' | '-' | '.'))38    {39        return Err("usernames may only contain letters, digits, '_', '-' and '.'".to_string());40    }41    Ok(())42}4344pub fn check_password(password: &str) -> Result<(), String> {45    if password.chars().count() < MIN_PASSWORD_LEN {46        return Err(format!(47            "passwords must be at least {MIN_PASSWORD_LEN} characters"48        ));49    }50    Ok(())51}5253fn hash_password(password: &str) -> Result<String> {54    let hash = Argon2::default()55        .hash_password(password.as_bytes())56        .map_err(|error| anyhow::anyhow!("{error}"))?;57    Ok(hash.to_string())58}5960fn verify_password(password: &str, hash: &str) -> bool {61    PasswordHash::new(hash).is_ok_and(|parsed| {62        Argon2::default()63            .verify_password(password.as_bytes(), &parsed)64            .is_ok()65    })66}6768pub fn create(connection: &Connection, username: &str, password: &str) -> Result<User> {69    if let Err(message) = check_username(username) {70        bail!(message);71    }72    let taken: bool = connection.query_row(73        "SELECT EXISTS (SELECT 1 FROM users WHERE username = ?1)",74        [username],75        |row| row.get(0),76    )?;77    if taken {78        bail!("a user named {username:?} already exists");79    }80    let user = User {81        id: Uuid::new_v4().to_string(),82        username: username.to_string(),83    };84    connection.execute(85        "INSERT INTO users (id, username, password_hash, created_at) VALUES (?1, ?2, ?3, ?4)",86        params![user.id, user.username, hash_password(password)?, now()],87    )?;88    Ok(user)89}9091/// Returns the user when the username and password match. Unknown users and wrong92/// passwords look the same to the caller.93pub fn verify(connection: &Connection, username: &str, password: &str) -> Result<Option<User>> {94    let row = connection95        .query_row(96            "SELECT id, username, password_hash FROM users WHERE username = ?1",97            [username],98            |row| {99                Ok((100                    row.get::<_, String>(0)?,101                    row.get::<_, String>(1)?,102                    row.get::<_, String>(2)?,103                ))104            },105        )106        .optional()?;107    Ok(row.and_then(|(id, username, hash)| {108        verify_password(password, &hash).then_some(User { id, username })109    }))110}111112/// Sets a new password for a user. Returns whether the user exists.113pub fn reset_password(connection: &Connection, username: &str, password: &str) -> Result<bool> {114    let updated = connection.execute(115        "UPDATE users SET password_hash = ?2 WHERE username = ?1",116        params![username, hash_password(password)?],117    )?;118    Ok(updated > 0)119}120121#[cfg(test)]122mod tests {123    use super::*;124    use crate::db::open_in_memory;125126    #[test]127    fn passwords_verify_and_wrong_ones_do_not() {128        let connection = open_in_memory().unwrap();129        create(&connection, "silen", "correct horse battery").unwrap();130        assert!(131            verify(&connection, "silen", "correct horse battery")132                .unwrap()133                .is_some()134        );135        assert!(136            verify(&connection, "silen", "wrong password!!")137                .unwrap()138                .is_none()139        );140        assert!(141            verify(&connection, "nobody", "correct horse battery")142                .unwrap()143                .is_none()144        );145    }146147    #[test]148    fn usernames_are_unique_regardless_of_case() {149        let connection = open_in_memory().unwrap();150        create(&connection, "Silen", "a long enough password").unwrap();151        assert!(create(&connection, "silen", "another long password").is_err());152        assert!(153            verify(&connection, "SILEN", "a long enough password")154                .unwrap()155                .is_some()156        );157    }158159    #[test]160    fn reset_replaces_the_password() {161        let connection = open_in_memory().unwrap();162        create(&connection, "silen", "original password").unwrap();163        assert!(reset_password(&connection, "silen", "replacement password").unwrap());164        assert!(165            verify(&connection, "silen", "original password")166                .unwrap()167                .is_none()168        );169        assert!(170            verify(&connection, "silen", "replacement password")171                .unwrap()172                .is_some()173        );174        assert!(!reset_password(&connection, "nobody", "replacement password").unwrap());175    }176177    #[test]178    fn generated_passwords_are_long_and_distinct() {179        let first = generate_password();180        assert!(first.len() >= 32);181        assert_ne!(first, generate_password());182        assert!(check_password(&first).is_ok());183    }184185    #[test]186    fn input_rules() {187        assert!(check_username("silen.l-1").is_ok());188        assert!(check_username("bad name").is_err());189        assert!(check_username("").is_err());190        assert!(check_password("short").is_err());191    }192}