Skip to main content

capy_auth/
password.rs

1//! Per-application bounded Argon2id workers. Admission is async; hashing is blocking.
2use crate::Secret;
3use argon2::{
4    password_hash::{PasswordHash, PasswordHasher, PasswordVerifier, SaltString},
5    Algorithm, Argon2, Params, Version,
6};
7use capy_core::{AppError, PasswordSettings, Result};
8use rand_core::{OsRng, RngCore};
9use std::{
10    sync::{Arc, OnceLock},
11    time::{Duration, Instant},
12};
13use tokio::sync::{OwnedSemaphorePermit, Semaphore};
14
15/// Cloneable resource pool. Construct once per application and reuse it.
16/// Cancellation while waiting removes the waiter. Once blocking work starts, its
17/// permit remains owned by that work until completion, even if HTTP is cancelled.
18#[derive(Clone, Debug)]
19pub struct PasswordService {
20    workers: Arc<Semaphore>,
21    waiting: Arc<Semaphore>,
22    settings: PasswordSettings,
23    concurrency: usize,
24}
25impl PasswordService {
26    /// Validate limits without spawning threads or hashing.
27    pub fn new(settings: PasswordSettings) -> Result<Self> {
28        let concurrency = settings.concurrency()?;
29        Ok(Self {
30            workers: Arc::new(Semaphore::new(concurrency)),
31            waiting: Arc::new(Semaphore::new(settings.hash_queue_capacity)),
32            settings,
33            concurrency,
34        })
35    }
36    /// Resolved worker limit; useful for startup telemetry.
37    pub fn concurrency(&self) -> usize {
38        self.concurrency
39    }
40    /// Stop admitting work and wake queued callers with a safe 503 error.
41    /// Already running Argon2 calls finish while retaining their permits.
42    pub fn close(&self) {
43        self.workers.close();
44        self.waiting.close();
45    }
46    async fn permit(&self) -> Result<OwnedSemaphorePermit> {
47        let start = Instant::now();
48        if let Ok(permit) = self.workers.clone().try_acquire_owned() {
49            return Ok(permit);
50        }
51        tracing::debug!(
52            event = "auth.password.queued",
53            concurrency = self.concurrency
54        );
55        let _waiting = self.waiting.clone().try_acquire_owned().map_err(|_| {
56            tracing::warn!(event = "auth.password.queue_full");
57            AppError::AuthCapacity
58        })?;
59        let permit = tokio::time::timeout(
60            Duration::from_millis(self.settings.hash_queue_timeout_ms),
61            self.workers.clone().acquire_owned(),
62        )
63        .await
64        .map_err(|_| {
65            tracing::warn!(
66                event = "auth.password.wait_timeout",
67                wait_ms = start.elapsed().as_millis() as u64
68            );
69            AppError::AuthCapacity
70        })?
71        .map_err(|_| AppError::AuthCapacity)?;
72        tracing::debug!(
73            event = "auth.password.admitted",
74            wait_ms = start.elapsed().as_millis() as u64
75        );
76        Ok(permit)
77    }
78    async fn run<T: Send + 'static>(
79        &self,
80        work: impl FnOnce(PasswordSettings) -> Result<T> + Send + 'static,
81    ) -> Result<T> {
82        let permit = self.permit().await?;
83        let settings = self.settings.clone();
84        tokio::task::spawn_blocking(move || {
85            let _permit = permit;
86            work(settings)
87        })
88        .await
89        .map_err(|_| failed())?
90    }
91    /// Hash using a random 128-bit salt, Argon2id v19, one lane and a 32-byte output.
92    pub async fn hash(&self, password: Secret) -> Result<Secret> {
93        self.run(move |settings| {
94            algorithm(&settings)?
95                .hash_password(password.expose().as_bytes(), &salt()?)
96                .map(|hash| Secret::new(hash.to_string()))
97                .map_err(|_| failed())
98        })
99        .await
100    }
101    /// Verify a supported PHC hash. Unknown users execute identical configured work.
102    /// Imported hashes exceeding this pool's cost limits are rejected before allocating;
103    /// raise the limits before importing more expensive hashes. Invalid hashes are errors.
104    pub async fn verify(&self, password: Secret, stored: Option<Secret>) -> Result<bool> {
105        self.run(move |settings| {
106            let algorithm = algorithm(&settings)?;
107            match stored {
108                Some(stored) => {
109                    let parsed = PasswordHash::new(stored.expose()).map_err(|_| failed())?;
110                    let params = Params::try_from(&parsed).map_err(|_| failed())?;
111                    if parsed.algorithm.as_str() != "argon2id"
112                        || parsed.version != Some(19)
113                        || params.m_cost() > settings.memory_cost_kib
114                        || params.t_cost() > settings.time_cost
115                        || params.p_cost() != 1
116                    {
117                        return Err(failed());
118                    }
119                    match algorithm.verify_password(password.expose().as_bytes(), &parsed) {
120                        Ok(()) => Ok(true),
121                        Err(argon2::password_hash::Error::Password) => Ok(false),
122                        Err(_) => Err(failed()),
123                    }
124                }
125                None => {
126                    algorithm
127                        .hash_password(password.expose().as_bytes(), &salt()?)
128                        .map_err(|_| failed())?;
129                    Ok(false)
130                }
131            }
132        })
133        .await
134    }
135}
136fn algorithm(settings: &PasswordSettings) -> Result<Argon2<'static>> {
137    Ok(Argon2::new(
138        Algorithm::Argon2id,
139        Version::V0x13,
140        Params::new(settings.memory_cost_kib, settings.time_cost, 1, Some(32))
141            .map_err(|_| failed())?,
142    ))
143}
144fn salt() -> Result<SaltString> {
145    let mut bytes = [0u8; 16];
146    OsRng.try_fill_bytes(&mut bytes).map_err(|_| failed())?;
147    SaltString::encode_b64(&bytes).map_err(|_| failed())
148}
149fn failed() -> AppError {
150    AppError::Configuration("Password hashing service unavailable".into())
151}
152// Compatibility only: built-in auth never uses this standalone default pool.
153fn standalone() -> Result<&'static PasswordService> {
154    static SERVICE: OnceLock<PasswordService> = OnceLock::new();
155    if let Some(service) = SERVICE.get() {
156        return Ok(service);
157    }
158    let _ = SERVICE.set(PasswordService::new(PasswordSettings::default())?);
159    SERVICE.get().ok_or_else(failed)
160}
161/// Standalone compatibility helper with bounded waiting. Applications should reuse
162/// `PasswordService` for explicit configuration and isolation from other applications.
163pub async fn hash(password: Secret) -> Result<Secret> {
164    standalone()?.hash(password).await
165}
166/// Standalone compatibility helper. `None` performs the same configured Argon2 work.
167pub async fn verify(password: Secret, stored: Option<Secret>) -> Result<bool> {
168    standalone()?.verify(password, stored).await
169}
170
171#[cfg(test)]
172mod tests {
173    use super::*;
174    fn service(timeout: u64) -> PasswordService {
175        PasswordService::new(PasswordSettings {
176            hash_concurrency: capy_core::HashConcurrency::Fixed(1),
177            hash_queue_timeout_ms: timeout,
178            hash_queue_capacity: 1,
179            ..Default::default()
180        })
181        .unwrap()
182    }
183    #[tokio::test]
184    async fn cancellation_keeps_running_work_bounded_and_recovers_queue_slots() {
185        let service = service(1000);
186        let (entered, started) = tokio::sync::oneshot::channel();
187        let (release, done) = std::sync::mpsc::channel();
188        let worker = service.clone();
189        let task = tokio::spawn(async move {
190            worker
191                .run(move |_| {
192                    entered.send(()).unwrap();
193                    done.recv().unwrap();
194                    Ok(())
195                })
196                .await
197        });
198        started.await.unwrap();
199        task.abort();
200        assert!(task.await.unwrap_err().is_cancelled());
201        assert_eq!(service.workers.available_permits(), 0);
202        // Dropping a waiting operation releases the bounded queue slot.
203        let waiter = service.clone();
204        let waiting =
205            tokio::spawn(async move { waiter.verify(Secret::new("unknown"), None).await });
206        while service.waiting.available_permits() != 0 {
207            tokio::task::yield_now().await;
208        }
209        assert!(matches!(
210            service.hash(Secret::new("full")).await,
211            Err(AppError::AuthCapacity)
212        ));
213        waiting.abort();
214        let _ = waiting.await;
215        assert_eq!(service.waiting.available_permits(), 1);
216        release.send(()).unwrap();
217        let hash = service.hash(Secret::new("after cancel")).await.unwrap();
218        assert!(service
219            .verify(Secret::new("after cancel"), Some(hash))
220            .await
221            .unwrap());
222        assert_eq!(service.workers.available_permits(), 1);
223    }
224    #[tokio::test]
225    async fn waiting_times_out_errors_release_and_close_wakes_waiters() {
226        let service = service(20);
227        let permit = service.workers.clone().acquire_owned().await.unwrap();
228        assert!(matches!(
229            service.verify(Secret::new("unknown"), None).await,
230            Err(AppError::AuthCapacity)
231        ));
232        assert_eq!(service.waiting.available_permits(), 1);
233        drop(permit);
234        assert!(service
235            .verify(Secret::new("pw"), Some(Secret::new("invalid PHC")))
236            .await
237            .is_err());
238        assert_eq!(service.workers.available_permits(), 1);
239        assert!(service
240            .run::<()>(|_| panic!("test worker panic"))
241            .await
242            .is_err());
243        assert_eq!(service.workers.available_permits(), 1);
244        let other = super::tests::service(1000);
245        let _permit = other.workers.clone().acquire_owned().await.unwrap();
246        let cloned = other.clone();
247        let waiting = tokio::spawn(async move { cloned.hash(Secret::new("pw")).await });
248        while other.waiting.available_permits() != 0 {
249            tokio::task::yield_now().await;
250        }
251        other.close();
252        assert!(matches!(
253            waiting.await.unwrap(),
254            Err(AppError::AuthCapacity)
255        ));
256    }
257    #[tokio::test]
258    async fn unknown_users_use_the_same_admission_and_argon2_work() {
259        let service = service(5000);
260        let hash = service.hash(Secret::new("password")).await.unwrap();
261        assert!(hash.expose().starts_with("$argon2id$v=19$m=19456,t=2,p=1$"));
262        assert!(!service
263            .verify(Secret::new("wrong"), Some(hash))
264            .await
265            .unwrap());
266        assert!(!service.verify(Secret::new("password"), None).await.unwrap());
267        // Bound imported PHC costs before the verifier can allocate attacker-sized memory.
268        assert!(service.verify(Secret::new("pw"), Some(Secret::new("$argon2id$v=19$m=999999999,t=2,p=1$c29tZXNhbHQ$aGFzaGFzaGFzaGFzaGFzaGFzaGFzaGFzaGFzaGFzaGE"))).await.is_err());
269    }
270}