capy-auth 0.7.0

Optional database-backed browser sessions and explicit authorization for Capy.
Documentation
//! Password operations run on bounded blocking workers, never the async executor.
use crate::Secret;
use argon2::{
    password_hash::{PasswordHash, PasswordHasher, PasswordVerifier, SaltString},
    Algorithm, Argon2, Params, Version,
};
use capy_core::{AppError, Result};
use rand_core::{OsRng, RngCore};
use std::sync::{Arc, OnceLock};
use tokio::sync::Semaphore;

fn algorithm() -> Argon2<'static> {
    Argon2::new(
        Algorithm::Argon2id,
        Version::V0x13,
        Params::new(19456, 2, 1, Some(32)).expect("fixed Argon2 parameters"),
    )
}
fn workers() -> &'static Arc<Semaphore> {
    static WORKERS: OnceLock<Arc<Semaphore>> = OnceLock::new();
    WORKERS.get_or_init(|| Arc::new(Semaphore::new(4)))
}
fn salt() -> Result<SaltString> {
    let mut bytes = [0u8; 16];
    OsRng.try_fill_bytes(&mut bytes).map_err(|_| failed())?;
    SaltString::encode_b64(&bytes).map_err(|_| failed())
}
fn failed() -> AppError {
    AppError::Configuration("Password hashing service unavailable".into())
}

/// Hash with Argon2id (19 MiB, two passes, one lane) and a random 128-bit salt.
/// Four concurrent blocking jobs bound hashing memory per process; excess work returns 429.
pub async fn hash(password: Secret) -> Result<Secret> {
    let permit = workers()
        .clone()
        .try_acquire_owned()
        .map_err(|_| AppError::TooManyRequests)?;
    tokio::task::spawn_blocking(move || {
        let _permit = permit;
        let salt = salt()?;
        algorithm()
            .hash_password(password.expose().as_bytes(), &salt)
            .map(|hash| Secret::new(hash.to_string()))
            .map_err(|_| failed())
    })
    .await
    .map_err(|_| failed())?
}

/// Verify a stored PHC hash. None still performs the same Argon2 work for unknown users.
pub async fn verify(password: Secret, stored: Option<Secret>) -> Result<bool> {
    let permit = workers()
        .clone()
        .try_acquire_owned()
        .map_err(|_| AppError::TooManyRequests)?;
    tokio::task::spawn_blocking(move || {
        let _permit = permit;
        match stored {
            Some(stored) => {
                let parsed = PasswordHash::new(stored.expose()).map_err(|_| failed())?;
                Ok(algorithm()
                    .verify_password(password.expose().as_bytes(), &parsed)
                    .is_ok())
            }
            None => {
                // A hash with the identical cost avoids the no-user fast path. The salt
                // need not be secret; generate one just as in normal registration.
                let salt = salt()?;
                algorithm()
                    .hash_password(password.expose().as_bytes(), &salt)
                    .map_err(|_| failed())?;
                Ok(false)
            }
        }
    })
    .await
    .map_err(|_| failed())?
}