capy-auth 0.10.0

Optional database-backed browser sessions and explicit authorization for Capy.
Documentation
//! Per-application bounded Argon2id workers. Admission is async; hashing is blocking.
use crate::Secret;
use argon2::{
    password_hash::{PasswordHash, PasswordHasher, PasswordVerifier, SaltString},
    Algorithm, Argon2, Params, Version,
};
use capy_core::{AppError, PasswordSettings, Result};
use rand_core::{OsRng, RngCore};
use std::{
    sync::{Arc, OnceLock},
    time::{Duration, Instant},
};
use tokio::sync::{OwnedSemaphorePermit, Semaphore};

/// Cloneable resource pool. Construct once per application and reuse it.
/// Cancellation while waiting removes the waiter. Once blocking work starts, its
/// permit remains owned by that work until completion, even if HTTP is cancelled.
#[derive(Clone, Debug)]
pub struct PasswordService {
    workers: Arc<Semaphore>,
    waiting: Arc<Semaphore>,
    settings: PasswordSettings,
    concurrency: usize,
}
impl PasswordService {
    /// Validate limits without spawning threads or hashing.
    pub fn new(settings: PasswordSettings) -> Result<Self> {
        let concurrency = settings.concurrency()?;
        Ok(Self {
            workers: Arc::new(Semaphore::new(concurrency)),
            waiting: Arc::new(Semaphore::new(settings.hash_queue_capacity)),
            settings,
            concurrency,
        })
    }
    /// Resolved worker limit; useful for startup telemetry.
    pub fn concurrency(&self) -> usize {
        self.concurrency
    }
    /// Stop admitting work and wake queued callers with a safe 503 error.
    /// Already running Argon2 calls finish while retaining their permits.
    pub fn close(&self) {
        self.workers.close();
        self.waiting.close();
    }
    async fn permit(&self) -> Result<OwnedSemaphorePermit> {
        let start = Instant::now();
        if let Ok(permit) = self.workers.clone().try_acquire_owned() {
            return Ok(permit);
        }
        tracing::debug!(
            event = "auth.password.queued",
            concurrency = self.concurrency
        );
        let _waiting = self.waiting.clone().try_acquire_owned().map_err(|_| {
            tracing::warn!(event = "auth.password.queue_full");
            AppError::AuthCapacity
        })?;
        let permit = tokio::time::timeout(
            Duration::from_millis(self.settings.hash_queue_timeout_ms),
            self.workers.clone().acquire_owned(),
        )
        .await
        .map_err(|_| {
            tracing::warn!(
                event = "auth.password.wait_timeout",
                wait_ms = start.elapsed().as_millis() as u64
            );
            AppError::AuthCapacity
        })?
        .map_err(|_| AppError::AuthCapacity)?;
        tracing::debug!(
            event = "auth.password.admitted",
            wait_ms = start.elapsed().as_millis() as u64
        );
        Ok(permit)
    }
    async fn run<T: Send + 'static>(
        &self,
        work: impl FnOnce(PasswordSettings) -> Result<T> + Send + 'static,
    ) -> Result<T> {
        let permit = self.permit().await?;
        let settings = self.settings.clone();
        tokio::task::spawn_blocking(move || {
            let _permit = permit;
            work(settings)
        })
        .await
        .map_err(|_| failed())?
    }
    /// Hash using a random 128-bit salt, Argon2id v19, one lane and a 32-byte output.
    pub async fn hash(&self, password: Secret) -> Result<Secret> {
        self.run(move |settings| {
            algorithm(&settings)?
                .hash_password(password.expose().as_bytes(), &salt()?)
                .map(|hash| Secret::new(hash.to_string()))
                .map_err(|_| failed())
        })
        .await
    }
    /// Verify a supported PHC hash. Unknown users execute identical configured work.
    /// Imported hashes exceeding this pool's cost limits are rejected before allocating;
    /// raise the limits before importing more expensive hashes. Invalid hashes are errors.
    pub async fn verify(&self, password: Secret, stored: Option<Secret>) -> Result<bool> {
        self.run(move |settings| {
            let algorithm = algorithm(&settings)?;
            match stored {
                Some(stored) => {
                    let parsed = PasswordHash::new(stored.expose()).map_err(|_| failed())?;
                    let params = Params::try_from(&parsed).map_err(|_| failed())?;
                    if parsed.algorithm.as_str() != "argon2id"
                        || parsed.version != Some(19)
                        || params.m_cost() > settings.memory_cost_kib
                        || params.t_cost() > settings.time_cost
                        || params.p_cost() != 1
                    {
                        return Err(failed());
                    }
                    match algorithm.verify_password(password.expose().as_bytes(), &parsed) {
                        Ok(()) => Ok(true),
                        Err(argon2::password_hash::Error::Password) => Ok(false),
                        Err(_) => Err(failed()),
                    }
                }
                None => {
                    algorithm
                        .hash_password(password.expose().as_bytes(), &salt()?)
                        .map_err(|_| failed())?;
                    Ok(false)
                }
            }
        })
        .await
    }
}
fn algorithm(settings: &PasswordSettings) -> Result<Argon2<'static>> {
    Ok(Argon2::new(
        Algorithm::Argon2id,
        Version::V0x13,
        Params::new(settings.memory_cost_kib, settings.time_cost, 1, Some(32))
            .map_err(|_| failed())?,
    ))
}
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())
}
// Compatibility only: built-in auth never uses this standalone default pool.
fn standalone() -> Result<&'static PasswordService> {
    static SERVICE: OnceLock<PasswordService> = OnceLock::new();
    if let Some(service) = SERVICE.get() {
        return Ok(service);
    }
    let _ = SERVICE.set(PasswordService::new(PasswordSettings::default())?);
    SERVICE.get().ok_or_else(failed)
}
/// Standalone compatibility helper with bounded waiting. Applications should reuse
/// `PasswordService` for explicit configuration and isolation from other applications.
pub async fn hash(password: Secret) -> Result<Secret> {
    standalone()?.hash(password).await
}
/// Standalone compatibility helper. `None` performs the same configured Argon2 work.
pub async fn verify(password: Secret, stored: Option<Secret>) -> Result<bool> {
    standalone()?.verify(password, stored).await
}

#[cfg(test)]
mod tests {
    use super::*;
    fn service(timeout: u64) -> PasswordService {
        PasswordService::new(PasswordSettings {
            hash_concurrency: capy_core::HashConcurrency::Fixed(1),
            hash_queue_timeout_ms: timeout,
            hash_queue_capacity: 1,
            ..Default::default()
        })
        .unwrap()
    }
    #[tokio::test]
    async fn cancellation_keeps_running_work_bounded_and_recovers_queue_slots() {
        let service = service(1000);
        let (entered, started) = tokio::sync::oneshot::channel();
        let (release, done) = std::sync::mpsc::channel();
        let worker = service.clone();
        let task = tokio::spawn(async move {
            worker
                .run(move |_| {
                    entered.send(()).unwrap();
                    done.recv().unwrap();
                    Ok(())
                })
                .await
        });
        started.await.unwrap();
        task.abort();
        assert!(task.await.unwrap_err().is_cancelled());
        assert_eq!(service.workers.available_permits(), 0);
        // Dropping a waiting operation releases the bounded queue slot.
        let waiter = service.clone();
        let waiting =
            tokio::spawn(async move { waiter.verify(Secret::new("unknown"), None).await });
        while service.waiting.available_permits() != 0 {
            tokio::task::yield_now().await;
        }
        assert!(matches!(
            service.hash(Secret::new("full")).await,
            Err(AppError::AuthCapacity)
        ));
        waiting.abort();
        let _ = waiting.await;
        assert_eq!(service.waiting.available_permits(), 1);
        release.send(()).unwrap();
        let hash = service.hash(Secret::new("after cancel")).await.unwrap();
        assert!(service
            .verify(Secret::new("after cancel"), Some(hash))
            .await
            .unwrap());
        assert_eq!(service.workers.available_permits(), 1);
    }
    #[tokio::test]
    async fn waiting_times_out_errors_release_and_close_wakes_waiters() {
        let service = service(20);
        let permit = service.workers.clone().acquire_owned().await.unwrap();
        assert!(matches!(
            service.verify(Secret::new("unknown"), None).await,
            Err(AppError::AuthCapacity)
        ));
        assert_eq!(service.waiting.available_permits(), 1);
        drop(permit);
        assert!(service
            .verify(Secret::new("pw"), Some(Secret::new("invalid PHC")))
            .await
            .is_err());
        assert_eq!(service.workers.available_permits(), 1);
        assert!(service
            .run::<()>(|_| panic!("test worker panic"))
            .await
            .is_err());
        assert_eq!(service.workers.available_permits(), 1);
        let other = super::tests::service(1000);
        let _permit = other.workers.clone().acquire_owned().await.unwrap();
        let cloned = other.clone();
        let waiting = tokio::spawn(async move { cloned.hash(Secret::new("pw")).await });
        while other.waiting.available_permits() != 0 {
            tokio::task::yield_now().await;
        }
        other.close();
        assert!(matches!(
            waiting.await.unwrap(),
            Err(AppError::AuthCapacity)
        ));
    }
    #[tokio::test]
    async fn unknown_users_use_the_same_admission_and_argon2_work() {
        let service = service(5000);
        let hash = service.hash(Secret::new("password")).await.unwrap();
        assert!(hash.expose().starts_with("$argon2id$v=19$m=19456,t=2,p=1$"));
        assert!(!service
            .verify(Secret::new("wrong"), Some(hash))
            .await
            .unwrap());
        assert!(!service.verify(Secret::new("password"), None).await.unwrap());
        // Bound imported PHC costs before the verifier can allocate attacker-sized memory.
        assert!(service.verify(Secret::new("pw"), Some(Secret::new("$argon2id$v=19$m=999999999,t=2,p=1$c29tZXNhbHQ$aGFzaGFzaGFzaGFzaGFzaGFzaGFzaGFzaGFzaGFzaGE"))).await.is_err());
    }
}