Skip to main content

koan_server/auth/
password.rs

1//! Username and password checks for transports that send them with every
2//! request, such as Subsonic's `p=`.
3//!
4//! argon2 is deliberately slow, and a Subsonic client authenticates each call,
5//! so a successful check is remembered for a while. The key is a digest of the
6//! username, the password and the stored hash, so changing the password or
7//! deleting the user ends it; the role is read afresh every time.
8//!
9//! A check that misses the cache runs argon2, which costs ~19 MiB and a core
10//! for tens of milliseconds, and anyone may ask for one — an unknown username
11//! still pays, so response time does not say which exist. So only a few run at
12//! once, and a request that finds them all busy is refused rather than queued.
13//! Requests carrying the same credentials while one is being checked wait for
14//! that check instead, which is what a client's burst of requests on first
15//! contact looks like.
16//!
17//! Subsonic token auth (`t`/`s`) is not checked here: it needs the plaintext
18//! password, and koan keeps only the hash.
19//!
20//! One verifier serves every door a password comes through — Subsonic, the
21//! JSON login and the web UI's form — so the ceiling on argon2 and the
22//! per-username budget on failures hold across all of them.
23//!
24//! The budget stops a guesser with many addresses, and on its own would let
25//! anyone with two keep an account locked out. So the networks an account has
26//! recently signed in from are remembered, and the budget does not apply to
27//! them: an outsider can spend it, but not for the account's own people.
28
29use std::collections::HashMap;
30use std::net::IpAddr;
31use std::num::NonZeroUsize;
32use std::sync::Arc;
33use std::time::{Duration, Instant};
34
35use koan_core::auth;
36use koan_core::db::pool::Pool;
37use koan_core::db::queries::auth::{self as auth_queries, UserRow};
38use lru::LruCache;
39use parking_lot::{Condvar, Mutex};
40use sha2::{Digest, Sha256};
41
42const REMEMBER: Duration = Duration::from_secs(600);
43
44/// How long a request waits on another's check of the same credentials.
45const WAIT_FOR_CHECK: Duration = Duration::from_secs(5);
46
47/// Failed password sign-ins allowed for one username in a minute, from every
48/// address together. Per-address limits do not stop a guesser with many
49/// addresses; this does, at a rate no person typing would reach.
50pub(crate) const FAILURES_PER_USERNAME_PER_MINUTE: u32 = 60;
51pub(crate) const FAILURE_WINDOW: Duration = Duration::from_secs(60);
52
53/// How long a network an account signed in from is spared its spent budget.
54/// A browser that keeps its session refreshes it every few minutes, which
55/// renews this.
56const KNOWN_FOR: Duration = Duration::from_secs(7 * 24 * 3600);
57
58/// Failures by key, in fixed windows of `FAILURE_WINDOW`.
59pub(crate) struct FailureLimiter<K> {
60    limit: u32,
61    windows: Mutex<HashMap<K, (Instant, u32)>>,
62}
63
64impl<K: std::hash::Hash + Eq> FailureLimiter<K> {
65    pub(crate) fn new(limit: u32) -> Self {
66        Self {
67            limit,
68            windows: Default::default(),
69        }
70    }
71
72    pub(crate) fn exhausted(&self, key: &K) -> bool {
73        let windows = self.windows.lock();
74        windows
75            .get(key)
76            .is_some_and(|(start, count)| start.elapsed() < FAILURE_WINDOW && *count >= self.limit)
77    }
78
79    pub(crate) fn record(&self, key: K) {
80        let mut windows = self.windows.lock();
81        if windows.len() > 4096 {
82            windows.retain(|_, (start, _)| start.elapsed() < FAILURE_WINDOW);
83        }
84        let entry = windows.entry(key).or_insert((Instant::now(), 0));
85        if entry.0.elapsed() >= FAILURE_WINDOW {
86            *entry = (Instant::now(), 0);
87        }
88        entry.1 += 1;
89    }
90}
91
92/// argon2 checks allowed at once.
93fn max_checks() -> usize {
94    std::thread::available_parallelism().map_or(2, |n| n.get().clamp(2, 8))
95}
96
97/// Why a password was not accepted.
98#[derive(Debug, Clone, Copy, PartialEq, Eq)]
99pub enum Refused {
100    /// Not this account's password, or no such account.
101    Wrong,
102    /// Every argon2 slot was taken; nothing was checked.
103    Busy,
104}
105
106/// A check in progress: its outcome once known, and a signal for those waiting.
107#[derive(Default)]
108struct Check {
109    outcome: Mutex<Option<bool>>,
110    done: Condvar,
111}
112
113pub struct PasswordVerifier {
114    pool: Arc<Pool>,
115    verified: Mutex<LruCache<[u8; 32], Instant>>,
116    /// Checks running now, by the same key as `verified`.
117    checking: Mutex<HashMap<[u8; 32], Arc<Check>>>,
118    max_checks: usize,
119    /// Failed sign-ins by username, whatever the address, counted by the
120    /// doors that take passwords. Only those: API keys and the Subsonic shared
121    /// secret are random and not worth guessing, so a flood of wrong passwords
122    /// for an account never locks out the apps signed in with either.
123    failures: FailureLimiter<String>,
124    /// When each username last signed in from each network (`routes::network`).
125    known: Mutex<LruCache<(String, IpAddr), Instant>>,
126    /// Subsonic credentials that just signed in, for the throttle to read back
127    /// once the request is answered; see `passed`.
128    passes: Mutex<LruCache<[u8; 32], ()>>,
129}
130
131impl PasswordVerifier {
132    pub fn new(pool: Arc<Pool>) -> Self {
133        Self {
134            pool,
135            verified: Mutex::new(LruCache::new(NonZeroUsize::new(256).expect("non-zero"))),
136            checking: Mutex::new(HashMap::new()),
137            max_checks: max_checks(),
138            failures: FailureLimiter::new(FAILURES_PER_USERNAME_PER_MINUTE),
139            known: Mutex::new(LruCache::new(NonZeroUsize::new(4096).expect("non-zero"))),
140            passes: Mutex::new(LruCache::new(NonZeroUsize::new(256).expect("non-zero"))),
141        }
142    }
143
144    /// Whether `username` has spent its failures for the minute, as far as a
145    /// sign-in from `from` is concerned: never from a network it recently
146    /// signed in from.
147    pub(crate) fn spent(&self, username: &str, from: IpAddr) -> bool {
148        self.failures.exhausted(&username.to_owned())
149            && !self
150                .known
151                .lock()
152                .get(&(username.to_owned(), super::routes::network(from)))
153                .is_some_and(|at| at.elapsed() < KNOWN_FOR)
154    }
155
156    /// Whether `username` has spent its failures for the minute, from any
157    /// network: for a password check that is not a sign-in, which the sparing
158    /// of known networks would otherwise let a guesser on one of them repeat
159    /// without limit.
160    pub(crate) fn exhausted(&self, username: &str) -> bool {
161        self.failures.exhausted(&username.to_owned())
162    }
163
164    /// Count a failed sign-in for `username`.
165    pub(crate) fn failed(&self, username: &str) {
166        self.failures.record(username.to_owned());
167    }
168
169    /// Remember that `username` signed in from `from`'s network.
170    pub(crate) fn signed_in(&self, username: &str, from: IpAddr) {
171        self.known.lock().put(
172            (username.to_owned(), super::routes::network(from)),
173            Instant::now(),
174        );
175    }
176
177    /// Note that the Subsonic credential `digest` signed in. The check runs
178    /// inside the handler, which knows nothing of the client's address; the
179    /// throttle around it does, and takes this back with `took_pass`.
180    pub(crate) fn passed(&self, digest: [u8; 32]) {
181        self.passes.lock().put(digest, ());
182    }
183
184    /// Whether `digest` signed in since it was last asked.
185    pub(crate) fn took_pass(&self, digest: &[u8; 32]) -> bool {
186        self.passes.lock().pop(digest).is_some()
187    }
188
189    /// The account, as it stands, when the password is its.
190    pub fn verify(&self, username: &str, password: &str) -> Result<UserRow, Refused> {
191        let db = self.pool.get().map_err(|_| Refused::Wrong)?;
192        let user =
193            auth_queries::get_user_by_username(&db.conn, username).map_err(|_| Refused::Wrong)?;
194        // An unknown username is checked against the dummy hash, so response
195        // time doesn't say which usernames exist.
196        let hash = user.as_ref().map_or_else(
197            || super::routes::dummy_password_hash(),
198            |u| u.password_hash.as_str(),
199        );
200        let key: [u8; 32] = Sha256::new()
201            .chain_update(username)
202            .chain_update([0])
203            .chain_update(password)
204            .chain_update([0])
205            .chain_update(hash)
206            .finalize()
207            .into();
208        let fresh = self
209            .verified
210            .lock()
211            .get(&key)
212            .is_some_and(|at| at.elapsed() < REMEMBER);
213        if !fresh && !self.check(key, password, hash)? {
214            return Err(Refused::Wrong);
215        }
216        user.ok_or(Refused::Wrong)
217    }
218
219    /// Run argon2 for `key`, or wait on the check already running for it.
220    fn check(&self, key: [u8; 32], password: &str, hash: &str) -> Result<bool, Refused> {
221        let (check, running) = {
222            let mut checking = self.checking.lock();
223            match checking.get(&key) {
224                Some(check) => (check.clone(), true),
225                None if checking.len() >= self.max_checks => return Err(Refused::Busy),
226                None => {
227                    let check = Arc::new(Check::default());
228                    checking.insert(key, check.clone());
229                    (check, false)
230                }
231            }
232        };
233        if running {
234            let deadline = Instant::now() + WAIT_FOR_CHECK;
235            let mut outcome = check.outcome.lock();
236            while outcome.is_none() && !check.done.wait_until(&mut outcome, deadline).timed_out() {}
237            return outcome.ok_or(Refused::Busy);
238        }
239        let ok = auth::verify_password(password, hash).is_ok();
240        if ok {
241            self.verified.lock().put(key, Instant::now());
242        }
243        *check.outcome.lock() = Some(ok);
244        check.done.notify_all();
245        self.checking.lock().remove(&key);
246        Ok(ok)
247    }
248}
249
250#[cfg(test)]
251mod tests {
252    use super::*;
253    use koan_core::auth::Role;
254    use koan_core::db::connection::Database;
255
256    impl PasswordVerifier {
257        fn check_as(&self, username: &str, password: &str) -> Result<(i64, Role), Refused> {
258            self.verify(username, password).map(|u| (u.id, u.role))
259        }
260    }
261
262    fn verifier() -> (PasswordVerifier, tempfile::TempDir) {
263        let dir = tempfile::tempdir().unwrap();
264        let path = dir.path().join("test.db");
265        let db = Database::open(&path).unwrap();
266        koan_core::db::schema::create_tables(&db.conn).unwrap();
267        auth_queries::create_user(&db.conn, "mate", "hunter22", Role::Readonly).unwrap();
268        (PasswordVerifier::new(Arc::new(Pool::new(path))), dir)
269    }
270
271    #[test]
272    fn right_password_gives_the_users_role() {
273        let (v, _dir) = verifier();
274        assert_eq!(v.check_as("mate", "hunter22"), Ok((1, Role::Readonly)));
275        // Remembered, and still answered from the database's role.
276        assert_eq!(v.check_as("mate", "hunter22"), Ok((1, Role::Readonly)));
277    }
278
279    #[test]
280    fn wrong_password_or_unknown_user_is_refused() {
281        let (v, _dir) = verifier();
282        assert_eq!(v.check_as("mate", "hunter2"), Err(Refused::Wrong));
283        assert_eq!(v.check_as("nobody", "hunter22"), Err(Refused::Wrong));
284    }
285
286    #[test]
287    fn checks_beyond_the_ceiling_are_refused_without_running() {
288        let (mut v, _dir) = verifier();
289        v.max_checks = 1;
290        assert!(v.check_as("mate", "hunter22").is_ok());
291        v.checking.lock().insert([0; 32], Arc::default());
292        assert_eq!(v.check_as("nobody", "guess"), Err(Refused::Busy));
293        assert_eq!(v.check_as("mate", "hunter2"), Err(Refused::Busy));
294        // A remembered sign-in needs no check, so it still works.
295        assert_eq!(v.check_as("mate", "hunter22"), Ok((1, Role::Readonly)));
296    }
297
298    #[test]
299    fn a_burst_of_one_sign_in_waits_for_a_single_check() {
300        let (mut v, _dir) = verifier();
301        v.max_checks = 1;
302        let v = Arc::new(v);
303        let burst: Vec<_> = (0..8)
304            .map(|_| {
305                let v = v.clone();
306                std::thread::spawn(move || v.check_as("mate", "hunter22"))
307            })
308            .collect();
309        for t in burst {
310            assert_eq!(t.join().unwrap(), Ok((1, Role::Readonly)));
311        }
312    }
313
314    #[test]
315    fn a_changed_password_forgets_the_old_one() {
316        let (v, dir) = verifier();
317        assert!(v.check_as("mate", "hunter22").is_ok());
318        let db = Database::open(&dir.path().join("test.db")).unwrap();
319        auth_queries::update_password(&db.conn, "mate", "correct horse").unwrap();
320        assert_eq!(v.check_as("mate", "hunter22"), Err(Refused::Wrong));
321        assert_eq!(v.check_as("mate", "correct horse"), Ok((1, Role::Readonly)));
322    }
323}