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())
}
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())?
}
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 => {
let salt = salt()?;
algorithm()
.hash_password(password.expose().as_bytes(), &salt)
.map_err(|_| failed())?;
Ok(false)
}
}
})
.await
.map_err(|_| failed())?
}