forge
Explore
Log in

Don't you dare go Hollow

Atomic throttle reservations, bounded argon2 with length cap, password before 2FA enrolment, single-use pending 2FA, logout only on POST, atomic password change, HMAC recovery codes, admin 404 for anonymous, live stream re-checks and caps, admin 2FA policy on refresh

Browse files at this commit

adfb39f6647f7634fbff1e8151d09fab6d644f62Ahmet Kaan GümüşParent: 52864eb
  • fix
    • atomic throttle reservations, bounded argon2 with length cap, password before 2FA enrolment, single-use pending 2FA, logout only on POST, atomic password change, HMAC recovery codes, admin 404 for anonymous, live stream re-checks and caps, admin 2FA policy on refresh
Show full message
🔒 fix: atomic throttle reservations, bounded argon2 with length cap, password before 2FA enrolment, single-use pending 2FA, logout only on POST, atomic password change, HMAC recovery codes, admin 404 for anonymous, live stream re-checks and caps, admin 2FA policy on refresh
crates/im-core/migrations/0003_consumed_pending_logins.sqladded+10 -0
@@ -0,0 +1,10 @@
1+-- 0003: the pending-login nonces that a second factor has spent. A password-verified sign-in may be
2+-- completed once; its nonce is kept until the pending cookie would have expired, so a restart does not
3+-- reopen a spent cookie. Rows past expires_at are removed by the next spend.
4+
5+CREATE TABLE consumed_pending_logins (
6+ nonce TEXT PRIMARY KEY NOT NULL,
7+ expires_at TEXT NOT NULL
8+);
9+
10+CREATE INDEX consumed_pending_logins_expires ON consumed_pending_logins (expires_at);
crates/im-core/src/password.rsmodified+38 -4
@@ -7,6 +7,7 @@
7 use argon2::Argon2;7 use argon2::Argon2;
8 use argon2::password_hash::phc::PasswordHash;8 use argon2::password_hash::phc::PasswordHash;
9 use argon2::password_hash::{PasswordHasher, PasswordVerifier};9 use argon2::password_hash::{PasswordHasher, PasswordVerifier};
10+use tokio::sync::{Semaphore, SemaphorePermit};
10 11
11 use crate::error::{Error, Result};12 use crate::error::{Error, Result};
12 13
@@ -18,12 +19,28 @@ pub const MIN_PASSWORD_CHARS: usize = 10;
18 /// per request.19 /// per request.
19 pub const MAX_PASSWORD_CHARS: usize = 256;20 pub const MAX_PASSWORD_CHARS: usize = 256;
20 21
22+/// Most argon2 operations running at once. Each one takes tens of megabytes, so a burst of requests
23+/// queues here instead of starting one blocking thread and one hash per request.
24+const HASH_PERMITS: usize = 4;
25+
26+/// The gate of every async hash and verify.
27+static HASHING: Semaphore = Semaphore::const_new(HASH_PERMITS);
28+
29+/// True for a password longer than [`MAX_PASSWORD_CHARS`]. Such a password is never hashed or verified.
30+fn too_long(pw: &str) -> bool {
31+ pw.chars().count() > MAX_PASSWORD_CHARS
32+}
33+
21 /// Shortest word of the name or email local part that a password may not contain, in characters.34 /// Shortest word of the name or email local part that a password may not contain, in characters.
22 /// Shorter words are too common to forbid: a two-letter word would reject many good passwords.35 /// Shorter words are too common to forbid: a two-letter word would reject many good passwords.
23 pub const MIN_FORBIDDEN_WORD_CHARS: usize = 4;36 pub const MIN_FORBIDDEN_WORD_CHARS: usize = 4;
24 37
25-/// Hashes `pw` with argon2id (default parameters) and a fresh random salt. Returns a PHC string.38+/// Hashes `pw` with argon2id (default parameters) and a fresh random salt. Returns a PHC string. A
39+/// password over [`MAX_PASSWORD_CHARS`] is refused before any hashing.
26 pub fn hash_password(pw: &str) -> Result<String> {40 pub fn hash_password(pw: &str) -> Result<String> {
41+ if too_long(pw) {
42+ return Err(Error::Invalid("the password is too long".into()));
43+ }
27 Argon2::default()44 Argon2::default()
28 .hash_password(pw.as_bytes())45 .hash_password(pw.as_bytes())
29 .map(|h| h.to_string())46 .map(|h| h.to_string())
@@ -31,8 +48,11 @@ pub fn hash_password(pw: &str) -> Result<String> {
31 }48 }
32 49
33 /// Returns true only if `pw` matches the PHC string `hash`. A malformed hash gives false, never50 /// Returns true only if `pw` matches the PHC string `hash`. A malformed hash gives false, never
34-/// a panic.51+/// a panic. A password over [`MAX_PASSWORD_CHARS`] gives false without any hashing.
35 pub fn verify_password(pw: &str, hash: &str) -> bool {52 pub fn verify_password(pw: &str, hash: &str) -> bool {
53+ if too_long(pw) {
54+ return false;
55+ }
36 let Ok(parsed) = PasswordHash::new(hash) else {56 let Ok(parsed) = PasswordHash::new(hash) else {
37 return false;57 return false;
38 };58 };
@@ -41,15 +61,29 @@ pub fn verify_password(pw: &str, hash: &str) -> bool {
41 .is_ok()61 .is_ok()
42 }62 }
43 63
44-/// [`hash_password`] on the blocking thread pool.64+/// Takes one of the [`HASH_PERMITS`] slots. Held until the blocking work ends.
65+async fn gate() -> Result<SemaphorePermit<'static>> {
66+ HASHING
67+ .acquire()
68+ .await
69+ .map_err(|e| Error::Crypto(format!("hashing gate closed: {e}")))
70+}
71+
72+/// [`hash_password`] on the blocking thread pool, behind the hashing gate.
45 pub async fn hash_password_async(pw: String) -> Result<String> {73 pub async fn hash_password_async(pw: String) -> Result<String> {
74+ let _permit = gate().await?;
46 tokio::task::spawn_blocking(move || hash_password(&pw))75 tokio::task::spawn_blocking(move || hash_password(&pw))
47 .await76 .await
48 .map_err(|e| Error::Crypto(format!("hashing task failed: {e}")))?77 .map_err(|e| Error::Crypto(format!("hashing task failed: {e}")))?
49 }78 }
50 79
51-/// [`verify_password`] on the blocking thread pool.80+/// [`verify_password`] on the blocking thread pool, behind the hashing gate. An over-long password is
81+/// answered without taking a slot.
52 pub async fn verify_password_async(pw: String, hash: String) -> Result<bool> {82 pub async fn verify_password_async(pw: String, hash: String) -> Result<bool> {
83+ if too_long(&pw) {
84+ return Ok(false);
85+ }
86+ let _permit = gate().await?;
53 tokio::task::spawn_blocking(move || verify_password(&pw, &hash))87 tokio::task::spawn_blocking(move || verify_password(&pw, &hash))
54 .await88 .await
55 .map_err(|e| Error::Crypto(format!("verify task failed: {e}")))89 .map_err(|e| Error::Crypto(format!("verify task failed: {e}")))
crates/im-core/src/store/migrate.rsmodified+4 -0
@@ -16,6 +16,10 @@ pub const MIGRATIONS: &[(u32, &str)] = &[
16 2,16 2,
17 include_str!("../../migrations/0002_sessions_cap_and_language.sql"),17 include_str!("../../migrations/0002_sessions_cap_and_language.sql"),
18 ),18 ),
19+ (
20+ 3,
21+ include_str!("../../migrations/0003_consumed_pending_logins.sql"),
22+ ),
19 ];23 ];
20 24
21 fn migration_err(e: turso::Error) -> Error {25 fn migration_err(e: turso::Error) -> Error {
crates/im-core/src/store/mod.rsmodified+1 -1
@@ -335,6 +335,6 @@ mod tests {
335 })335 })
336 .await336 .await
337 .unwrap();337 .unwrap();
338- assert_eq!(applied, vec![1, 2]);338+ assert_eq!(applied, vec![1, 2, 3]);
339 }339 }
340 }340 }
crates/im-core/src/store/sessions.rsmodified+1 -1
@@ -83,7 +83,7 @@ pub struct CreatedSession {
83 83
84 /// The ids of the live sessions of `user_id` except `keep` (none keeps nothing), oldest first.84 /// The ids of the live sessions of `user_id` except `keep` (none keeps nothing), oldest first.
85 /// Only sessions that are still live count; expired rows are removed by the sweeper.85 /// Only sessions that are still live count; expired rows are removed by the sweeper.
86-async fn live_session_ids(86+pub(crate) async fn live_session_ids(
87 conn: &Connection,87 conn: &Connection,
88 user_id: &str,88 user_id: &str,
89 keep: Option<&str>,89 keep: Option<&str>,
crates/im-core/src/store/users.rsmodified+64 -15
@@ -18,6 +18,7 @@ use crate::error::{Error, Result};
18 use crate::model::User;18 use crate::model::User;
19 use crate::store::backchannel::{self, EndReason};19 use crate::store::backchannel::{self, EndReason};
20 use crate::store::directory::{ChangeKind, record_change};20 use crate::store::directory::{ChangeKind, record_change};
21+use crate::store::sessions::{end_rows, live_session_ids};
21 use crate::store::{22 use crate::store::{
22 Store, col_int, col_opt_int, col_opt_text, col_text, db_err, fetch_opt, finish, new_id,23 Store, col_int, col_opt_int, col_opt_text, col_text, db_err, fetch_opt, finish, new_id,
23 };24 };
@@ -318,20 +319,36 @@ impl Store {
318 result319 result
319 }320 }
320 321
321- /// Stores a new argon2id hash. The caller has checked the policy and the current password.322+ /// Stores a new argon2id hash and ends every live session of the person except `keep_session_id`,
322- pub async fn set_password_hash(&self, id: &str, password_hash: &str) -> Result<()> {323+ /// with their back-channel logouts. One transaction: the old password never stays in force for a
324+ /// session that the new one has ended, and nothing changes unless both happen. The caller has checked
325+ /// the policy and the current password. Returns the ids of the sessions ended.
326+ pub async fn change_password(
327+ &self,
328+ id: &str,
329+ password_hash: &str,
330+ keep_session_id: &str,
331+ ) -> Result<Vec<String>> {
332+ let now = now_stamp();
323 let conn = self.inner.conn.lock().await;333 let conn = self.inner.conn.lock().await;
324- let changed = conn334+ let tx = conn.unchecked_transaction().await.map_err(db_err)?;
325- .execute(335+ let outcome: Result<Vec<String>> = async {
326- "UPDATE users SET password_hash = ?2, updated_at = ?3 WHERE id = ?1",336+ let changed = tx
327- (id.to_string(), password_hash.to_string(), now_stamp()),337+ .execute(
328- )338+ "UPDATE users SET password_hash = ?2, updated_at = ?3 WHERE id = ?1",
329- .await339+ (id.to_string(), password_hash.to_string(), now.clone()),
330- .map_err(db_err)?;340+ )
331- if changed == 0 {341+ .await
332- return Err(Error::NotFound);342+ .map_err(db_err)?;
343+ if changed == 0 {
344+ return Err(Error::NotFound);
345+ }
346+ let ids = live_session_ids(&tx, id, Some(keep_session_id), &now).await?;
347+ end_rows(&tx, id, &ids, EndReason::PasswordChanged, &now).await?;
348+ Ok(ids)
333 }349 }
334- Ok(())350+ .await;
351+ finish(tx, outcome).await
335 }352 }
336 353
337 /// Disables an account. The last enabled administrator cannot be disabled: that is part of the354 /// Disables an account. The last enabled administrator cannot be disabled: that is part of the
@@ -435,8 +452,11 @@ impl Store {
435 }452 }
436 453
437 /// Turns two-factor sign-in off: clears the secret, the step and the recovery codes, and drops454 /// Turns two-factor sign-in off: clears the secret, the step and the recovery codes, and drops
438- /// any pending enrolment. One transaction.455+ /// any pending enrolment. Two-factor sign-in was the policy's guard for the session, so in the same
439- pub async fn disable_totp(&self, user_id: &str) -> Result<()> {456+ /// transaction the person's refresh tokens are revoked and every live session except `keep_session_id`
457+ /// ends, with its back-channel logouts. `None` ends all of them.
458+ pub async fn disable_totp(&self, user_id: &str, keep_session_id: Option<&str>) -> Result<()> {
459+ let now = now_stamp();
440 let conn = self.inner.conn.lock().await;460 let conn = self.inner.conn.lock().await;
441 let tx = conn.unchecked_transaction().await.map_err(db_err)?;461 let tx = conn.unchecked_transaction().await.map_err(db_err)?;
442 let outcome: Result<()> = async {462 let outcome: Result<()> = async {
@@ -444,7 +464,7 @@ impl Store {
444 .execute(464 .execute(
445 "UPDATE users SET totp_secret_sealed = NULL, totp_enabled_at = NULL, \465 "UPDATE users SET totp_secret_sealed = NULL, totp_enabled_at = NULL, \
446 totp_last_step = NULL, updated_at = ?2 WHERE id = ?1",466 totp_last_step = NULL, updated_at = ?2 WHERE id = ?1",
447- (user_id.to_string(), now_stamp()),467+ (user_id.to_string(), now.clone()),
448 )468 )
449 .await469 .await
450 .map_err(db_err)?;470 .map_err(db_err)?;
@@ -463,12 +483,41 @@ impl Store {
463 )483 )
464 .await484 .await
465 .map_err(db_err)?;485 .map_err(db_err)?;
486+ tx.execute(
487+ "UPDATE refresh_tokens SET revoked_at = ?2 WHERE user_id = ?1 AND revoked_at IS NULL",
488+ (user_id.to_string(), now.clone()),
489+ )
490+ .await
491+ .map_err(db_err)?;
492+ let ids = live_session_ids(&tx, user_id, keep_session_id, &now).await?;
493+ end_rows(&tx, user_id, &ids, EndReason::Revoked, &now).await?;
466 Ok(())494 Ok(())
467 }495 }
468 .await;496 .await;
469 finish(tx, outcome).await497 finish(tx, outcome).await
470 }498 }
471 499
500+ /// Spends the pending-login nonce of a password-verified sign-in that has just passed its second
501+ /// factor. Returns true only for the first spend. `keep_until` is when the nonce may be forgotten:
502+ /// after the pending cookie expired, it could not be used anyway. Expired nonces are removed here.
503+ pub async fn consume_pending_login(&self, nonce: &str, keep_until: &str) -> Result<bool> {
504+ let conn = self.inner.conn.lock().await;
505+ conn.execute(
506+ "DELETE FROM consumed_pending_logins WHERE expires_at <= ?1",
507+ (now_stamp(),),
508+ )
509+ .await
510+ .map_err(db_err)?;
511+ let changed = conn
512+ .execute(
513+ "INSERT OR IGNORE INTO consumed_pending_logins (nonce, expires_at) VALUES (?1, ?2)",
514+ (nonce.to_string(), keep_until.to_string()),
515+ )
516+ .await
517+ .map_err(db_err)?;
518+ Ok(changed == 1)
519+ }
520+
472 /// Records `step` as the last accepted TOTP step. Returns true only when that moved the guard521 /// Records `step` as the last accepted TOTP step. Returns true only when that moved the guard
473 /// forward. A step that is not later than the recorded one, or any step while two-factor is off,522 /// forward. A step that is not later than the recorded one, or any step while two-factor is off,
474 /// returns false. This is the replay guard: a code is spent by this single statement.523 /// returns false. This is the replay guard: a code is spent by this single statement.
crates/im-core/src/totp.rsmodified+25 -8
@@ -9,7 +9,7 @@
9 9
10 use hmac::{Hmac, KeyInit, Mac};10 use hmac::{Hmac, KeyInit, Mac};
11 use sha1::Sha1;11 use sha1::Sha1;
12-use sha2::{Digest, Sha256};12+use sha2::Sha256;
13 13
14 use crate::token::{constant_time_eq, random_readable};14 use crate::token::{constant_time_eq, random_readable};
15 15
@@ -32,6 +32,12 @@ const BASE32_ALPHABET: &[u8; 32] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
32 32
33 type HmacSha1 = Hmac<Sha1>;33 type HmacSha1 = Hmac<Sha1>;
34 34
35+type HmacSha256 = Hmac<Sha256>;
36+
37+/// What a recovery-code subkey is derived for. The subkey is HMAC of this label under the instance key,
38+/// so the instance key itself keys only that derivation.
39+const RECOVERY_SUBKEY_LABEL: &[u8] = b"im recovery code key v1";
40+
35 /// A fresh random secret of [`SECRET_LEN`] bytes.41 /// A fresh random secret of [`SECRET_LEN`] bytes.
36 pub fn new_secret() -> [u8; SECRET_LEN] {42 pub fn new_secret() -> [u8; SECRET_LEN] {
37 let mut secret = [0u8; SECRET_LEN];43 let mut secret = [0u8; SECRET_LEN];
@@ -144,16 +150,26 @@ pub fn new_recovery_code() -> String {
144 format!("{}-{}", &raw[..4], &raw[4..])150 format!("{}-{}", &raw[..4], &raw[4..])
145 }151 }
146 152
147-/// Hex SHA-256 of a recovery code after normalisation: lowercase, without dashes and spaces. The153+/// Hex HMAC-SHA256 of a recovery code after normalisation: lowercase, without dashes and spaces. The
148-/// stored hash and the checked input go through the same normalisation, so how the person types154+/// key is a subkey of the instance key `key`, so a copy of the database alone cannot be checked against
149-/// the code does not matter.155+/// guesses: the codes are random, but a fast unkeyed hash would still allow an offline search. The stored
150-pub fn recovery_code_hash(code: &str) -> String {156+/// hash and the checked input go through the same normalisation, so how the person types the code does
157+/// not matter.
158+pub fn recovery_code_hash(key: &[u8; 32], code: &str) -> String {
151 let normalized: String = code159 let normalized: String = code
152 .chars()160 .chars()
153 .filter(|c| !c.is_whitespace() && *c != '-')161 .filter(|c| !c.is_whitespace() && *c != '-')
154 .map(|c| c.to_ascii_lowercase())162 .map(|c| c.to_ascii_lowercase())
155 .collect();163 .collect();
156- hex::encode(Sha256::digest(normalized.as_bytes()))164+ // HMAC accepts a key of any length, so construction cannot fail.
165+ let mut derive =
166+ <HmacSha256 as KeyInit>::new_from_slice(key).expect("HMAC takes any key length");
167+ derive.update(RECOVERY_SUBKEY_LABEL);
168+ let subkey = derive.finalize().into_bytes();
169+ let mut mac =
170+ <HmacSha256 as KeyInit>::new_from_slice(&subkey).expect("HMAC takes any key length");
171+ mac.update(normalized.as_bytes());
172+ hex::encode(mac.finalize().into_bytes())
157 }173 }
158 174
159 #[cfg(test)]175 #[cfg(test)]
@@ -220,9 +236,10 @@ mod tests {
220 let code = new_recovery_code();236 let code = new_recovery_code();
221 assert_eq!(code.len(), 9);237 assert_eq!(code.len(), 9);
222 assert_eq!(code.as_bytes()[4], b'-');238 assert_eq!(code.as_bytes()[4], b'-');
239+ let key = [7u8; 32];
223 assert_eq!(240 assert_eq!(
224- recovery_code_hash(&code),241+ recovery_code_hash(&key, &code),
225- recovery_code_hash(&code.to_uppercase().replace('-', " "))242+ recovery_code_hash(&key, &code.to_uppercase().replace('-', " "))
226 );243 );
227 }244 }
228 }245 }
crates/im-web/src/auth.rsmodified+23 -8
@@ -102,11 +102,15 @@ pub async fn require_user(cx: &Cx) -> Result<Viewer> {
102 }102 }
103 }103 }
104 104
105-/// The signed-in administrator. A person who is not an administrator gets 404, the same answer as a105+/// The signed-in administrator. A visitor without a session, and a person who is not an administrator,
106-/// page that does not exist. An administrator without two-factor sign-in, while the policy requires106+/// get 404, the same answer as a page that does not exist. An administrator without two-factor sign-in, while the policy requires
107 /// it, is sent to the security page instead.107 /// it, is sent to the security page instead.
108 pub async fn require_admin(cx: &Cx) -> Result<Viewer> {108 pub async fn require_admin(cx: &Cx) -> Result<Viewer> {
109- let viewer = require_user(cx).await?;109+ // Anyone without a live session gets 404 too: an admin page does not redirect to sign-in, so its
110+ // existence is not revealed to visitors.
111+ let Some(viewer) = current_user(cx).await? else {
112+ return Err(not_found().into());
113+ };
110 if !viewer.user.is_admin {114 if !viewer.user.is_admin {
111 return Err(not_found().into());115 return Err(not_found().into());
112 }116 }
@@ -256,6 +260,8 @@ fn pre_csrf_cookie(token: String) -> Cookie<'static> {
256 /// A password-verified sign-in that waits for its second factor.260 /// A password-verified sign-in that waits for its second factor.
257 #[derive(Debug, Clone, PartialEq, Eq)]261 #[derive(Debug, Clone, PartialEq, Eq)]
258 pub struct Pending {262 pub struct Pending {
263+ /// Random id of this pending sign-in. The second factor spends it once (`Store::consume_pending_login`).
264+ pub nonce: String,
259 /// The person who passed the password step.265 /// The person who passed the password step.
260 pub user_id: String,266 pub user_id: String,
261 /// The authentication method so far. Always the password.267 /// The authentication method so far. Always the password.
@@ -265,10 +271,12 @@ pub struct Pending {
265 }271 }
266 272
267 /// Parks a password-verified sign-in in the pending cookie. The payload is sealed with the instance273 /// Parks a password-verified sign-in in the pending cookie. The payload is sealed with the instance
268-/// key, so the browser can neither change the person nor extend the expiry.274+/// key, so the browser can neither change the person nor extend the expiry. It carries a random nonce,
275+/// which a successful second factor spends, so the same cookie cannot sign in twice.
269 pub fn set_pending_login(cx: &Cx, key: &[u8; 32], user_id: &str, next: &str) -> Result<()> {276 pub fn set_pending_login(cx: &Cx, key: &[u8; 32], user_id: &str, next: &str) -> Result<()> {
270 let expires = unix_now() + PENDING_TTL.as_secs();277 let expires = unix_now() + PENDING_TTL.as_secs();
271- let payload = format!("{user_id}|{expires}|{}|{next}", amr::PASSWORD);278+ let nonce = generate_token();
279+ let payload = format!("{user_id}|{expires}|{}|{nonce}|{next}", amr::PASSWORD);
272 let sealed = secret::seal(key, payload.as_bytes())?;280 let sealed = secret::seal(key, payload.as_bytes())?;
273 let max_age = time::Duration::seconds(i64::try_from(PENDING_TTL.as_secs()).unwrap_or(0));281 let max_age = time::Duration::seconds(i64::try_from(PENDING_TTL.as_secs()).unwrap_or(0));
274 jar(cx).add(282 jar(cx).add(
@@ -290,15 +298,17 @@ pub fn pending_login(cx: &Cx, key: &[u8; 32]) -> Option<Pending> {
290 let plain = secret::open(key, cookie.value()).ok()?;298 let plain = secret::open(key, cookie.value()).ok()?;
291 let text = String::from_utf8(plain).ok()?;299 let text = String::from_utf8(plain).ok()?;
292 // `next` comes last, so a `|` inside it cannot shift the other fields.300 // `next` comes last, so a `|` inside it cannot shift the other fields.
293- let mut parts = text.splitn(4, '|');301+ let mut parts = text.splitn(5, '|');
294 let user_id = parts.next()?;302 let user_id = parts.next()?;
295 let expires: u64 = parts.next()?.parse().ok()?;303 let expires: u64 = parts.next()?.parse().ok()?;
296 let amr = parts.next()?;304 let amr = parts.next()?;
305+ let nonce = parts.next()?;
297 let next = parts.next()?;306 let next = parts.next()?;
298 if unix_now() >= expires {307 if unix_now() >= expires {
299 return None;308 return None;
300 }309 }
301 Some(Pending {310 Some(Pending {
311+ nonce: nonce.to_owned(),
302 user_id: user_id.to_owned(),312 user_id: user_id.to_owned(),
303 amr: amr.to_owned(),313 amr: amr.to_owned(),
304 next: next.to_owned(),314 next: next.to_owned(),
@@ -346,7 +356,7 @@ pub async fn check_second_factor(
346 return Ok(None);356 return Ok(None);
347 }357 }
348 let spent = store358 let spent = store
349- .consume_recovery_code(&user.id, &totp::recovery_code_hash(input))359+ .consume_recovery_code(&user.id, &totp::recovery_code_hash(key, input))
350 .await?;360 .await?;
351 Ok(spent.then_some(amr::PASSWORD_RECOVERY))361 Ok(spent.then_some(amr::PASSWORD_RECOVERY))
352 }362 }
@@ -466,7 +476,12 @@ mod tests {
466 let code = totp::new_recovery_code();476 let code = totp::new_recovery_code();
467 state477 state
468 .store478 .store
469- .enable_totp(&user.id, &sealed, 1, &[totp::recovery_code_hash(&code)])479+ .enable_totp(
480+ &user.id,
481+ &sealed,
482+ 1,
483+ &[totp::recovery_code_hash(&state.key, &code)],
484+ )
470 .await485 .await
471 .expect("enable");486 .expect("enable");
472 let user = state487 let user = state
crates/im-web/src/boot.rsmodified+4 -2
@@ -16,13 +16,13 @@ use im_core::secret;
16 use im_core::store::Store;16 use im_core::store::Store;
17 use tokio::net::TcpListener;17 use tokio::net::TcpListener;
18 use tokio::signal::unix::{SignalKind, signal};18 use tokio::signal::unix::{SignalKind, signal};
19-use tokio::sync::watch;19+use tokio::sync::{Semaphore, watch};
20 use topcoat::cookie::RouterBuilderCookieExt;20 use topcoat::cookie::RouterBuilderCookieExt;
21 use topcoat::router::{BodyLimit, Router, RouterBuilderDiscoverExt, RouterService};21 use topcoat::router::{BodyLimit, Router, RouterBuilderDiscoverExt, RouterService};
22 22
23 use crate::api::directory::StreamSlots;23 use crate::api::directory::StreamSlots;
24 use crate::backchannel;24 use crate::backchannel;
25-use crate::live::LiveHub;25+use crate::live::{LiveHub, MAX_ANONYMOUS_STREAMS};
26 use crate::mail;26 use crate::mail;
27 use crate::oidc::signing;27 use crate::oidc::signing;
28 use crate::pages::not_found::NotFoundLayer;28 use crate::pages::not_found::NotFoundLayer;
@@ -152,6 +152,7 @@ pub(crate) async fn open_state(config: Config) -> im_core::Result<AppState> {
152 live: Arc::new(LiveHub::default()),152 live: Arc::new(LiveHub::default()),
153 throttle: Arc::new(Throttle::default()),153 throttle: Arc::new(Throttle::default()),
154 stream_slots: Arc::new(StreamSlots::default()),154 stream_slots: Arc::new(StreamSlots::default()),
155+ anonymous_streams: Arc::new(Semaphore::new(MAX_ANONYMOUS_STREAMS)),
155 // Replaced by the stop flag of `serve` before any listener starts. The CLI never serves.156 // Replaced by the stop flag of `serve` before any listener starts. The CLI never serves.
156 stop: watch::channel(false).1,157 stop: watch::channel(false).1,
157 })158 })
@@ -256,6 +257,7 @@ mod tests {
256 live: Arc::new(LiveHub::default()),257 live: Arc::new(LiveHub::default()),
257 throttle: Arc::new(Throttle::default()),258 throttle: Arc::new(Throttle::default()),
258 stream_slots: Arc::new(StreamSlots::default()),259 stream_slots: Arc::new(StreamSlots::default()),
260+ anonymous_streams: Arc::new(Semaphore::new(MAX_ANONYMOUS_STREAMS)),
259 stop: watch::channel(false).1,261 stop: watch::channel(false).1,
260 };262 };
261 (dir, state)263 (dir, state)
crates/im-web/src/live.rsmodified+40 -10
@@ -10,22 +10,24 @@
10 //! authenticates and authorises first, then calls [`stream_changes`].10 //! authenticates and authorises first, then calls [`stream_changes`].
11 //!11 //!
12 //! Every stream ends when the process stops (the stop flag in [`AppState`]), so a shutdown does not wait12 //! Every stream ends when the process stops (the stop flag in [`AppState`]), so a shutdown does not wait
13-//! for a browser to close its connection.13+//! for a browser to close its connection. No stream lives longer than [`MAX_STREAM_LIFE`]: the browser
14+//! reconnects, and each new connection authenticates again.
14 15
15 use std::collections::HashMap;16 use std::collections::HashMap;
16 use std::future::Future;17 use std::future::Future;
17-use std::sync::{Mutex, MutexGuard, PoisonError};18+use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
18 use std::time::Duration;19 use std::time::Duration;
19 20
20 use futures_util::{Stream, StreamExt, future::select_all, stream};21 use futures_util::{Stream, StreamExt, future::select_all, stream};
21 use im_core::store::Store;22 use im_core::store::Store;
22-use tokio::sync::watch;23+use tokio::sync::{OwnedSemaphorePermit, watch};
23 use topcoat::Result;24 use topcoat::Result;
24 use topcoat::context::{Cx, app_context};25 use topcoat::context::{Cx, app_context};
25 use topcoat::router::content::sse::{Event, KeepAlive, Sse};26 use topcoat::router::content::sse::{Event, KeepAlive, Sse};
26 use topcoat::router::response::{IntoResponse, Response};27 use topcoat::router::response::{IntoResponse, Response};
27-use topcoat::router::{HeaderValue, route};28+use topcoat::router::{HeaderValue, StatusCode, route};
28 29
30+use crate::api::api_error;
29 use crate::auth::current_user;31 use crate::auth::current_user;
30 use crate::state::AppState;32 use crate::state::AppState;
31 33
@@ -35,6 +37,13 @@ pub const STREAM_RETRY: Duration = Duration::from_millis(1000);
35 /// Silence after which the server sends a keep-alive comment, so proxies keep the stream open.37 /// Silence after which the server sends a keep-alive comment, so proxies keep the stream open.
36 pub const KEEP_ALIVE: Duration = Duration::from_secs(30);38 pub const KEEP_ALIVE: Duration = Duration::from_secs(30);
37 39
40+/// Longest a stream lives, whatever happens on it. The browser reconnects after it, and a reconnect
41+/// authenticates and authorises again, so a session that ended or lost its role is not kept by a stream.
42+pub const MAX_STREAM_LIFE: Duration = Duration::from_secs(60 * 60);
43+
44+/// Anonymous `/-/alive` streams open at once, across the whole process. A further one gets `429`.
45+pub const MAX_ANONYMOUS_STREAMS: usize = 256;
46+
38 /// What a live page follows.47 /// What a live page follows.
39 #[derive(Clone, Debug, PartialEq, Eq, Hash)]48 #[derive(Clone, Debug, PartialEq, Eq, Hash)]
40 pub enum Topic {49 pub enum Topic {
@@ -96,6 +105,8 @@ impl LiveHub {
96 struct Follow<F> {105 struct Follow<F> {
97 wakes: Vec<watch::Receiver<u64>>,106 wakes: Vec<watch::Receiver<u64>>,
98 stop: watch::Receiver<bool>,107 stop: watch::Receiver<bool>,
108+ /// When the stream ends, whatever else happened ([`MAX_STREAM_LIFE`]).
109+ until: tokio::time::Instant,
99 fingerprint: F,110 fingerprint: F,
100 last: String,111 last: String,
101 }112 }
@@ -104,8 +115,9 @@ struct Follow<F> {
104 /// differs from the value it last sent, so a bump that changes nothing the viewer sees sends115 /// differs from the value it last sent, so a bump that changes nothing the viewer sees sends
105 /// nothing. Nothing is sent on connect: the page already shows the state that `fingerprint` read.116 /// nothing. Nothing is sent on connect: the page already shows the state that `fingerprint` read.
106 ///117 ///
107-/// `fingerprint` must be cheap and must describe everything the page shows. A read that fails ends118+/// `fingerprint` must be cheap and must describe everything the page shows. It runs on every wake, before
108-/// the stream, and the browser reconnects.119+/// anything is sent, so it is also the place to check the viewer again: an error (a read that fails, or a
120+/// viewer who may no longer see the page) ends the stream, and the browser reconnects and is refused.
109 pub async fn stream_changes<F, Fut>(121 pub async fn stream_changes<F, Fut>(
110 cx: &Cx,122 cx: &Cx,
111 hub: &LiveHub,123 hub: &LiveHub,
@@ -123,6 +135,7 @@ where
123 let follow = Follow {135 let follow = Follow {
124 wakes,136 wakes,
125 stop: app_context::<AppState>(cx).stop.clone(),137 stop: app_context::<AppState>(cx).stop.clone(),
138+ until: tokio::time::Instant::now() + MAX_STREAM_LIFE,
126 fingerprint,139 fingerprint,
127 last,140 last,
128 };141 };
@@ -131,6 +144,7 @@ where
131 let woke = tokio::select! {144 let woke = tokio::select! {
132 woke = wait_any(&mut follow.wakes) => woke,145 woke = wait_any(&mut follow.wakes) => woke,
133 () = stopped(&mut follow.stop) => false,146 () = stopped(&mut follow.stop) => false,
147+ () = tokio::time::sleep_until(follow.until) => false,
134 };148 };
135 if !woke {149 if !woke {
136 return None;150 return None;
@@ -197,6 +211,8 @@ struct AccountFollow {
197 wake: watch::Receiver<u64>,211 wake: watch::Receiver<u64>,
198 /// Set when the process stops. The stream then ends.212 /// Set when the process stops. The stream then ends.
199 stop: watch::Receiver<bool>,213 stop: watch::Receiver<bool>,
214+ /// When the stream ends, whatever else happened ([`MAX_STREAM_LIFE`]).
215+ until: tokio::time::Instant,
200 /// Checks that the session of this stream still exists.216 /// Checks that the session of this stream still exists.
201 store: Store,217 store: Store,
202 /// The session the stream was opened with.218 /// The session the stream was opened with.
@@ -215,10 +231,22 @@ struct AccountFollow {
215 async fn alive(cx: &Cx) -> Result<Response> {231 async fn alive(cx: &Cx) -> Result<Response> {
216 let state = app_context::<AppState>(cx);232 let state = app_context::<AppState>(cx);
217 let Some(viewer) = current_user(cx).await? else {233 let Some(viewer) = current_user(cx).await? else {
218- // Anonymous: no events, but the stream still ends when the process stops.234+ // Anonymous: no events, but the stream still ends when the process stops or its time is up. The
219- let events = stream::unfold(state.stop.clone(), |mut stop| async move {235+ // slot is held for the life of the stream, so the number of these is capped for the process.
220- stopped(&mut stop).await;236+ let Ok(slot) = Arc::clone(&state.anonymous_streams).try_acquire_owned() else {
221- None::<(Result<Event>, watch::Receiver<bool>)>237+ return Ok(api_error(
238+ StatusCode::TOO_MANY_REQUESTS,
239+ "rate_limited",
240+ "Too many open streams. Try again shortly.",
241+ None,
242+ ));
243+ };
244+ let events = stream::unfold((state.stop.clone(), slot), |(mut stop, _slot)| async move {
245+ tokio::select! {
246+ () = stopped(&mut stop) => {}
247+ () = tokio::time::sleep(MAX_STREAM_LIFE) => {}
248+ }
249+ None::<(Result<Event>, (watch::Receiver<bool>, OwnedSemaphorePermit))>
222 });250 });
223 return events_response(cx, events);251 return events_response(cx, events);
224 };252 };
@@ -227,6 +255,7 @@ async fn alive(cx: &Cx) -> Result<Response> {
227 .live255 .live
228 .subscribe(&Topic::Account(viewer.user.id.clone())),256 .subscribe(&Topic::Account(viewer.user.id.clone())),
229 stop: state.stop.clone(),257 stop: state.stop.clone(),
258+ until: tokio::time::Instant::now() + MAX_STREAM_LIFE,
230 store: state.store.clone(),259 store: state.store.clone(),
231 session_id: viewer.session.id.clone(),260 session_id: viewer.session.id.clone(),
232 done: false,261 done: false,
@@ -238,6 +267,7 @@ async fn alive(cx: &Cx) -> Result<Response> {
238 let changed = tokio::select! {267 let changed = tokio::select! {
239 changed = follow.wake.changed() => changed.is_ok(),268 changed = follow.wake.changed() => changed.is_ok(),
240 () = stopped(&mut follow.stop) => false,269 () = stopped(&mut follow.stop) => false,
270+ () = tokio::time::sleep_until(follow.until) => false,
241 };271 };
242 if !changed {272 if !changed {
243 return None;273 return None;
crates/im-web/src/oidc/logout.rsmodified+4 -18
@@ -8,9 +8,9 @@
8 //! `post_logout_redirect_uri` equals one of its registered URIs exactly. Otherwise the answer is the8 //! `post_logout_redirect_uri` equals one of its registered URIs exactly. Otherwise the answer is the
9 //! signed-out page, never a redirect.9 //! signed-out page, never a redirect.
10 //! - `state` is echoed on the redirect only when it is usable (bounded, no control characters).10 //! - `state` is echoed on the redirect only when it is usable (bounded, no control characters).
11-//! - A `GET` ends a session only when the hint's `sid` is the browser's own session: an attacker's11+//! - A `GET` never ends a session: a link or an image on another site must not sign the browser out. A
12-//! link cannot know that. Any other `GET` shows a confirmation form, which carries the session's CSRF12+//! `GET` with a session shows a confirmation form, which carries the session's CSRF token. Only the
13-//! token. A `POST` checks that token before anything changes.13+//! `POST` ends the session, and it checks that token before anything changes.
14 //! - Ending the session is `im`'s own: the browser session is deleted (and its clients told by14 //! - Ending the session is `im`'s own: the browser session is deleted (and its clients told by
15 //! back-channel logout, in the store's transaction). When the hint names another session of the same15 //! back-channel logout, in the store's transaction). When the hint names another session of the same
16 //! person, that one ends too.16 //! person, that one ends too.
@@ -173,28 +173,14 @@ async fn sign_out(cx: &Cx, viewer: &Viewer, hint_sid: Option<&str>) -> Result<()
173 Ok(())173 Ok(())
174 }174 }
175 175
176-/// `GET /logout`.176+/// `GET /logout`. Never ends a session: with one, it shows the confirmation form.
177 #[page(GET "/logout")]177 #[page(GET "/logout")]
178 async fn logout_get(cx: &Cx, Form(form): Form<LogoutForm>) -> Result<impl View> {178 async fn logout_get(cx: &Cx, Form(form): Form<LogoutForm>) -> Result<impl View> {
179 let app = app_context::<AppState>(cx);179 let app = app_context::<AppState>(cx);
180 let asked = read(app, &form).await?;180 let asked = read(app, &form).await?;
181 let viewer = current_user(cx).await?;181 let viewer = current_user(cx).await?;
182 let lang = page_lang(cx, viewer.as_ref());182 let lang = page_lang(cx, viewer.as_ref());
183- let own_session = viewer.as_ref().is_some_and(|viewer| {
184- asked
185- .hint
186- .as_ref()
187- .and_then(|hint| hint.sid.as_deref())
188- .is_some_and(|sid| sid == viewer.session.id)
189- });
190 match viewer {183 match viewer {
191- Some(viewer) if own_session => {
192- sign_out(cx, &viewer, None).await?;
193- if let Some(target) = redirect_target(&asked) {
194- return Err(see_other(target).into());
195- }
196- Ok(logout_view(cx, lang, None))
197- }
198 Some(viewer) => {184 Some(viewer) => {
199 let confirm = Confirm {185 let confirm = Confirm {
200 csrf: viewer.session.csrf_token.clone(),186 csrf: viewer.session.csrf_token.clone(),
crates/im-web/src/oidc/tests.rsmodified+25 -8
@@ -425,16 +425,30 @@ async fn id_token_of(f: &Fixture) -> String {
425 tokens["id_token"].as_str().expect("id_token").to_owned()425 tokens["id_token"].as_str().expect("id_token").to_owned()
426 }426 }
427 427
428+/// The CSRF token of the fixture's browser session.
429+async fn csrf_of(f: &Fixture) -> String {
430+ f.state
431+ .store
432+ .session_by_token_hash(&hash_token(&f.cookie))
433+ .await
434+ .expect("lookup")
435+ .expect("session")
436+ .csrf_token
437+}
438+
428 #[tokio::test]439 #[tokio::test]
429 async fn logout_redirects_only_to_the_registered_post_logout_uri() {440 async fn logout_redirects_only_to_the_registered_post_logout_uri() {
430 let f = fixture().await;441 let f = fixture().await;
431 let hint = encode_value(&id_token_of(&f).await);442 let hint = encode_value(&id_token_of(&f).await);
432 let unregistered = encode_value("http://127.0.0.1:17651/elsewhere");443 let unregistered = encode_value("http://127.0.0.1:17651/elsewhere");
433- let path =444+ let body = format!(
434- format!("/logout?id_token_hint={hint}&post_logout_redirect_uri={unregistered}&state=abc");445+ "csrf={}&id_token_hint={hint}&post_logout_redirect_uri={unregistered}&state=abc",
435- let request = http::Request::get(path)446+ csrf_of(&f).await
447+ );
448+ let request = http::Request::post("/logout")
436 .header(COOKIE, format!("{SESSION_COOKIE}={}", f.cookie))449 .header(COOKIE, format!("{SESSION_COOKIE}={}", f.cookie))
437- .body(Body::empty())450+ .header(CONTENT_TYPE, "application/x-www-form-urlencoded")
451+ .body(Body::from(body))
438 .expect("request");452 .expect("request");
439 let (status, headers, body) = send(&f.state, request).await;453 let (status, headers, body) = send(&f.state, request).await;
440 assert_eq!(status, StatusCode::OK, "{body}");454 assert_eq!(status, StatusCode::OK, "{body}");
@@ -457,11 +471,14 @@ async fn logout_with_the_registered_uri_redirects_and_carries_the_state() {
457 let f = fixture().await;471 let f = fixture().await;
458 let hint = encode_value(&id_token_of(&f).await);472 let hint = encode_value(&id_token_of(&f).await);
459 let registered = encode_value(POST_LOGOUT);473 let registered = encode_value(POST_LOGOUT);
460- let path =474+ let body = format!(
461- format!("/logout?id_token_hint={hint}&post_logout_redirect_uri={registered}&state=abc");475+ "csrf={}&id_token_hint={hint}&post_logout_redirect_uri={registered}&state=abc",
462- let request = http::Request::get(path)476+ csrf_of(&f).await
477+ );
478+ let request = http::Request::post("/logout")
463 .header(COOKIE, format!("{SESSION_COOKIE}={}", f.cookie))479 .header(COOKIE, format!("{SESSION_COOKIE}={}", f.cookie))
464- .body(Body::empty())480+ .header(CONTENT_TYPE, "application/x-www-form-urlencoded")
481+ .body(Body::from(body))
465 .expect("request");482 .expect("request");
466 let (status, headers, _) = send(&f.state, request).await;483 let (status, headers, _) = send(&f.state, request).await;
467 assert_eq!(status, StatusCode::SEE_OTHER);484 assert_eq!(status, StatusCode::SEE_OTHER);
crates/im-web/src/oidc/token.rsmodified+5 -0
@@ -283,6 +283,11 @@ async fn grant_refresh(app: &AppState, client: &Client, pairs: &Pairs) -> Result
283 else {283 else {
284 return Ok(invalid_grant());284 return Ok(invalid_grant());
285 };285 };
286+ // The administrator policy holds for refresh too: an administrator without two-factor sign-in gets no
287+ // more tokens, the same as the admin pages refuse them.
288+ if user.is_admin && app.policy().require_2fa_for_admins && !user.totp_enabled() {
289+ return Ok(invalid_grant());
290+ }
286 291
287 let refresh = generate_token();292 let refresh = generate_token();
288 let refresh_id = new_id();293 let refresh_id = new_id();
crates/im-web/src/pages/admin/message.rsmodified+4 -4
@@ -84,11 +84,12 @@ async fn send_message(cx: &Cx, Form(form): Form<MessageForm>) -> Result<SeeOther
84 if body.chars().count() > BODY_MAX {84 if body.chars().count() > BODY_MAX {
85 return Ok(refused("/admin/message", "message-body"));85 return Ok(refused("/admin/message", "message-body"));
86 }86 }
87- let now = Instant::now();87+ // Counted before the sends, so parallel submits cannot all pass the limit. A send is what is limited, so
88+ // the count stays whatever the outcome.
88 if state89 if state
89 .throttle90 .throttle
90- .check(THROTTLE_KEY, SENDS_PER_WINDOW, now)91+ .reserve(THROTTLE_KEY, SENDS_PER_WINDOW, Instant::now())
91- .is_some()92+ .is_err()
92 {93 {
93 return Ok(refused("/admin/message", "rate-limited"));94 return Ok(refused("/admin/message", "rate-limited"));
94 }95 }
@@ -105,7 +106,6 @@ async fn send_message(cx: &Cx, Form(form): Form<MessageForm>) -> Result<SeeOther
105 mail::queue(&state.store, &state.key, &to, lang, &mail).await?;106 mail::queue(&state.store, &state.key, &to, lang, &mail).await?;
106 recipients += 1;107 recipients += 1;
107 }108 }
108- state.throttle.record_failure(THROTTLE_KEY, now);
109 record(109 record(
110 cx,110 cx,
111 Actor::User(&viewer.user.id),111 Actor::User(&viewer.user.id),
crates/im-web/src/pages/admin/mod.rsmodified+23 -2
@@ -182,14 +182,35 @@ async fn admin_root(cx: &Cx) -> Result<SeeOther> {
182 182
183 /// `GET /admin/events`: the live stream of the admin pages. It sends one `changed` event for each admin183 /// `GET /admin/events`: the live stream of the admin pages. It sends one `changed` event for each admin
184 /// write, and the page fetches itself again. Non-administrators get 404.184 /// write, and the page fetches itself again. Non-administrators get 404.
185+///
186+/// The session and the administrator role are checked again on every wake, before an event is sent. A
187+/// session that ended, or an account that lost the role or was disabled, ends the stream.
185 #[route(GET "/admin/events")]188 #[route(GET "/admin/events")]
186 async fn admin_events(cx: &Cx) -> Result<Response> {189 async fn admin_events(cx: &Cx) -> Result<Response> {
187- require_admin(cx).await?;190+ let viewer = require_admin(cx).await?;
188 let state = app_context::<AppState>(cx);191 let state = app_context::<AppState>(cx);
189 let live = state.live.clone();192 let live = state.live.clone();
193+ let store = state.store.clone();
194+ let session_id = viewer.session.id.clone();
195+ let user_id = viewer.user.id.clone();
190 stream_changes(cx, &state.live, &[Topic::Admin], move || {196 stream_changes(cx, &state.live, &[Topic::Admin], move || {
191 let live = live.clone();197 let live = live.clone();
192- async move { Ok(live.generation(&Topic::Admin).to_string()) }198+ let store = store.clone();
199+ let session_id = session_id.clone();
200+ let user_id = user_id.clone();
201+ async move {
202+ let session_live = store.session_is_live(&session_id).await?;
203+ let admin = store
204+ .user_by_id(&user_id)
205+ .await?
206+ .is_some_and(|user| user.is_admin && !user.is_disabled());
207+ if !(session_live && admin) {
208+ return Err(topcoat::Error::msg(
209+ "the administrator stream is no longer allowed",
210+ ));
211+ }
212+ Ok(live.generation(&Topic::Admin).to_string())
213+ }
193 })214 })
194 .await215 .await
195 }216 }
crates/im-web/src/pages/admin/users.rsmodified+1 -1
@@ -423,7 +423,7 @@ async fn reset_two_factor(cx: &Cx, Form(form): Form<ActionForm>) -> Result<SeeOt
423 return Ok(refused(&base, "self"));423 return Ok(refused(&base, "self"));
424 }424 }
425 let state = app_context::<AppState>(cx);425 let state = app_context::<AppState>(cx);
426- state.store.disable_totp(&user.id).await?;426+ state.store.disable_totp(&user.id, None).await?;
427 state.live.bump(&Topic::Account(user.id.clone()));427 state.live.bump(&Topic::Account(user.id.clone()));
428 changed(&state.live);428 changed(&state.live);
429 let request_lang = page_lang(cx, Some(&viewer));429 let request_lang = page_lang(cx, Some(&viewer));
crates/im-web/src/pages/email.rsmodified+3 -6
@@ -30,7 +30,7 @@ use crate::i18n::flows::{Flow, email_link_summary, text as flow_text};
30 use crate::live::Topic;30 use crate::live::Topic;
31 use crate::mail::{self, Mail, Recipient};31 use crate::mail::{self, Mail, Recipient};
32 use crate::pages::path_param;32 use crate::pages::path_param;
33-use crate::pages::security::{password_locked, password_matches};33+use crate::pages::security::password_problem;
34 use crate::state::AppState;34 use crate::state::AppState;
35 use crate::views::{ViewerInfo, alert, field, notice, page_lang, shell};35 use crate::views::{ViewerInfo, alert, field, notice, page_lang, shell};
36 36
@@ -97,11 +97,8 @@ async fn email_request_submit(cx: &Cx, Form(form): Form<EmailRequestForm>) -> Re
97 )97 )
98 };98 };
99 99
100- if password_locked(state, &viewer) {100+ if let Some(problem) = password_problem(state, &viewer, &form.current_password).await? {
101- return Ok(refuse(Txt::ErrThrottled));101+ return Ok(refuse(problem));
102- }
103- if !password_matches(state, &viewer, &form.current_password).await? {
104- return Ok(refuse(Txt::ErrWrongPassword));
105 }102 }
106 let new_email = match parse_email(&form.new_email) {103 let new_email = match parse_email(&form.new_email) {
107 Ok(email) => email,104 Ok(email) => email,
crates/im-web/src/pages/login.rsmodified+26 -14
@@ -11,6 +11,7 @@ use std::time::{Duration, Instant};
11 use im_core::model::{AuditAction, User, amr};11 use im_core::model::{AuditAction, User, amr};
12 use im_core::names::normalize_email;12 use im_core::names::normalize_email;
13 use im_core::password::{hash_password_async, verify_password_async};13 use im_core::password::{hash_password_async, verify_password_async};
14+use im_core::time::stamp_after;
14 use serde::Deserialize;15 use serde::Deserialize;
15 use serde_json::{Value, json};16 use serde_json::{Value, json};
16 use topcoat::Result;17 use topcoat::Result;
@@ -23,8 +24,8 @@ use topcoat::view::{View, view};
23 24
24 use crate::audit::{Actor, record};25 use crate::audit::{Actor, record};
25 use crate::auth::{26 use crate::auth::{
26- after_sign_in, check_pre_csrf, check_second_factor, clear_pending_login, clear_pre_csrf,27+ PENDING_TTL, after_sign_in, check_pre_csrf, check_second_factor, clear_pending_login,
27- pending_login, pre_csrf_token, safe_next, set_pending_login, start_session,28+ clear_pre_csrf, pending_login, pre_csrf_token, safe_next, set_pending_login, start_session,
28 };29 };
29 use crate::client_ip::client_ip;30 use crate::client_ip::client_ip;
30 use crate::i18n::Lang;31 use crate::i18n::Lang;
@@ -102,14 +103,14 @@ async fn login_submit(cx: &Cx, Form(form): Form<LoginForm>) -> Result<impl View>
102 let email = normalize_email(&form.email);103 let email = normalize_email(&form.email);
103 let user_limit = user_key(&email);104 let user_limit = user_key(&email);
104 let ip_limit = ip_key("login-ip", client_ip(cx));105 let ip_limit = ip_key("login-ip", client_ip(cx));
105- let now = Instant::now();
106 106
107- // A key over its limit answers with the throttle message and a Retry-After, before any lookup.107+ // Both keys are counted before the lookup, as one step. A key over its limit answers with the throttle
108- let wait = [(&user_limit, LOGIN_USER_LIMIT), (&ip_limit, LOGIN_IP_LIMIT)]108+ // message and a Retry-After, and nothing is counted against the other key either.
109- .iter()109+ let reserved = state.throttle.reserve_all(
110- .filter_map(|(key, limit)| state.throttle.check(key, *limit, now))110+ &[(&user_limit, LOGIN_USER_LIMIT), (&ip_limit, LOGIN_IP_LIMIT)],
111- .max();111+ Instant::now(),
112- if let Some(wait) = wait {112+ );
113+ if let Err(wait) = reserved {
113 retry_after(cx, wait);114 retry_after(cx, wait);
114 let lang = page_lang(cx, None);115 let lang = page_lang(cx, None);
115 return Ok(login_view(116 return Ok(login_view(
@@ -130,9 +131,8 @@ async fn login_submit(cx: &Cx, Form(form): Form<LoginForm>) -> Result<impl View>
130 };131 };
131 let password_ok = verify_password_async(form.password.clone(), hash).await?;132 let password_ok = verify_password_async(form.password.clone(), hash).await?;
132 let target_id = found.as_ref().map(|user| user.id.clone());133 let target_id = found.as_ref().map(|user| user.id.clone());
134+ // The attempt stays counted on every failure below.
133 let Some(user) = found.filter(|user| password_ok && !user.is_disabled()) else {135 let Some(user) = found.filter(|user| password_ok && !user.is_disabled()) else {
134- state.throttle.record_failure(&user_limit, now);
135- state.throttle.record_failure(&ip_limit, now);
136 let target = target_id.as_deref().map(|id| ("user", id));136 let target = target_id.as_deref().map(|id| ("user", id));
137 record(137 record(
138 cx,138 cx,
@@ -154,7 +154,9 @@ async fn login_submit(cx: &Cx, Form(form): Form<LoginForm>) -> Result<impl View>
154 ));154 ));
155 };155 };
156 156
157+ // A success forgets the account's earlier failures, and gives this address's attempt back.
157 state.throttle.clear(&user_limit);158 state.throttle.clear(&user_limit);
159+ state.throttle.refund(&ip_limit);
158 if user.totp_enabled() {160 if user.totp_enabled() {
159 set_pending_login(cx, &state.key, &user.id, &next)?;161 set_pending_login(cx, &state.key, &user.id, &next)?;
160 return Err(see_other("/login/2fa").into());162 return Err(see_other("/login/2fa").into());
@@ -192,8 +194,10 @@ async fn two_factor_submit(cx: &Cx, Form(form): Form<TwoFactorForm>) -> Result<i
192 };194 };
193 let csrf = pre_csrf_token(cx);195 let csrf = pre_csrf_token(cx);
194 let limit = two_factor_key(&user.id);196 let limit = two_factor_key(&user.id);
195- let now = Instant::now();197+ if let Err(wait) = state
196- if let Some(wait) = state.throttle.check(&limit, TWO_FACTOR_USER_LIMIT, now) {198+ .throttle
199+ .reserve(&limit, TWO_FACTOR_USER_LIMIT, Instant::now())
200+ {
197 retry_after(cx, wait);201 retry_after(cx, wait);
198 return Ok(two_factor_view(202 return Ok(two_factor_view(
199 cx,203 cx,
@@ -206,12 +210,20 @@ async fn two_factor_submit(cx: &Cx, Form(form): Form<TwoFactorForm>) -> Result<i
206 210
207 match check_second_factor(&state.store, &state.key, &user, &form.code).await? {211 match check_second_factor(&state.store, &state.key, &user, &form.code).await? {
208 Some(method) => {212 Some(method) => {
213+ // The pending cookie is good for one sign-in. A second use of it is refused like an expired one.
214+ let spent = state
215+ .store
216+ .consume_pending_login(&pending.nonce, &stamp_after(PENDING_TTL))
217+ .await?;
218+ if !spent {
219+ clear_pending_login(cx);
220+ return Err(see_other("/login").into());
221+ }
209 state.throttle.clear(&limit);222 state.throttle.clear(&limit);
210 clear_pending_login(cx);223 clear_pending_login(cx);
211 Err(finish_sign_in(cx, &user, method, &pending.next).await?)224 Err(finish_sign_in(cx, &user, method, &pending.next).await?)
212 }225 }
213 None => {226 None => {
214- state.throttle.record_failure(&limit, now);
215 record(227 record(
216 cx,228 cx,
217 Actor::User(&user.id),229 Actor::User(&user.id),
crates/im-web/src/pages/reset.rsmodified+10 -9
@@ -84,21 +84,22 @@ async fn forgot_submit(cx: &Cx, Form(form): Form<ForgotForm>) -> Result<impl Vie
84 }84 }
85 let state = app_context::<AppState>(cx);85 let state = app_context::<AppState>(cx);
86 let lang = page_lang(cx, None);86 let lang = page_lang(cx, None);
87- let now = Instant::now();
88 let email = normalize_email(&form.email);87 let email = normalize_email(&form.email);
89 let client = client_ip(cx);88 let client = client_ip(cx);
90 let email_limit = forgot_email_key(&email);89 let email_limit = forgot_email_key(&email);
91 let client_limit = ip_key("forgot-ip", client);90 let client_limit = ip_key("forgot-ip", client);
91+ // Counted only while neither key is limited: a request refused by the limit is not counted again, so
92+ // the mail of a flood is capped at the limit's worth per window.
92 let limited = state93 let limited = state
93 .throttle94 .throttle
94- .check(&email_limit, FORGOT_EMAIL_LIMIT, now)95+ .reserve_all(
95- .is_some()96+ &[
96- || state97+ (&email_limit, FORGOT_EMAIL_LIMIT),
97- .throttle98+ (&client_limit, FORGOT_IP_LIMIT),
98- .check(&client_limit, FORGOT_IP_LIMIT, now)99+ ],
99- .is_some();100+ Instant::now(),
100- state.throttle.record_failure(&email_limit, now);101+ )
101- state.throttle.record_failure(&client_limit, now);102+ .is_err();
102 103
103 // The same lookup for a known and an unknown address; only a known, enabled one gets a link.104 // The same lookup for a known and an unknown address; only a known, enabled one gets a link.
104 if !limited105 if !limited
crates/im-web/src/pages/security.rsmodified+58 -90
@@ -9,7 +9,6 @@ use base64::engine::general_purpose::STANDARD as BASE64;
9 use im_core::model::AuditAction;9 use im_core::model::AuditAction;
10 use im_core::password::{check_policy, hash_password_async, verify_password_async};10 use im_core::password::{check_policy, hash_password_async, verify_password_async};
11 use im_core::secret;11 use im_core::secret;
12-use im_core::store::backchannel::EndReason;
13 use im_core::totp;12 use im_core::totp;
14 use serde::Deserialize;13 use serde::Deserialize;
15 use serde_json::json;14 use serde_json::json;
@@ -62,6 +61,17 @@ struct CodeForm {
62 code: String,61 code: String,
63 }62 }
64 63
64+/// The enrolment form: the current password when two-factor sign-in is off, a code when it is on.
65+#[derive(Deserialize, Default)]
66+struct StartForm {
67+ #[serde(default)]
68+ csrf: String,
69+ #[serde(default)]
70+ current_password: String,
71+ #[serde(default)]
72+ code: String,
73+}
74+
65 /// The turn-off form: the password and a second factor.75 /// The turn-off form: the password and a second factor.
66 #[derive(Deserialize, Default)]76 #[derive(Deserialize, Default)]
67 struct DisableForm {77 struct DisableForm {
@@ -131,21 +141,8 @@ async fn change_password(cx: &Cx, Form(form): Form<PasswordForm>) -> Result<impl
131 let viewer = require_csrf(cx, &form.csrf).await?;141 let viewer = require_csrf(cx, &form.csrf).await?;
132 let state = app_context::<AppState>(cx);142 let state = app_context::<AppState>(cx);
133 let lang = page_lang(cx, Some(&viewer));143 let lang = page_lang(cx, Some(&viewer));
134- if password_locked(state, &viewer) {144+ if let Some(problem) = password_problem(state, &viewer, &form.current_password).await? {
135- return render_security(145+ return render_security(cx, viewer.clone(), Flash::alert(text(lang, problem))).await;
136- cx,
137- viewer.clone(),
138- Flash::alert(text(lang, Txt::ErrThrottled)),
139- )
140- .await;
141- }
142- if !password_matches(state, &viewer, &form.current_password).await? {
143- return render_security(
144- cx,
145- viewer.clone(),
146- Flash::alert(text(lang, Txt::ErrWrongPassword)),
147- )
148- .await;
149 }146 }
150 if form.new_password != form.new_password_again {147 if form.new_password != form.new_password_again {
151 return render_security(148 return render_security(
@@ -170,18 +167,11 @@ async fn change_password(cx: &Cx, Form(form): Form<PasswordForm>) -> Result<impl
170 }167 }
171 168
172 let hash = hash_password_async(form.new_password.clone()).await?;169 let hash = hash_password_async(form.new_password.clone()).await?;
173- state170+ // One transaction: the new hash, and the end of every other session of the person with the old
174- .store171+ // password. This session stays signed in.
175- .set_password_hash(&viewer.user.id, &hash)
176- .await?;
177- // Every other session of the person ends with the old password. This one stays signed in.
178 let ended = state172 let ended = state
179 .store173 .store
180- .end_other_sessions(174+ .change_password(&viewer.user.id, &hash, &viewer.session.id)
181- &viewer.user.id,
182- &viewer.session.id,
183- EndReason::PasswordChanged,
184- )
185 .await?;175 .await?;
186 changed(state, &viewer);176 changed(state, &viewer);
187 record(177 record(
@@ -206,7 +196,7 @@ async fn change_password(cx: &Cx, Form(form): Form<PasswordForm>) -> Result<impl
206 /// `POST /account/security/2fa/start`: starts an enrolment. Turning on needs no code; replacing an196 /// `POST /account/security/2fa/start`: starts an enrolment. Turning on needs no code; replacing an
207 /// authenticator of an account that already has two-factor sign-in needs its current code.197 /// authenticator of an account that already has two-factor sign-in needs its current code.
208 #[page(POST "/account/security/2fa/start")]198 #[page(POST "/account/security/2fa/start")]
209-async fn start_enrolment(cx: &Cx, Form(form): Form<CodeForm>) -> Result<impl View> {199+async fn start_enrolment(cx: &Cx, Form(form): Form<StartForm>) -> Result<impl View> {
210 let viewer = require_csrf(cx, &form.csrf).await?;200 let viewer = require_csrf(cx, &form.csrf).await?;
211 let state = app_context::<AppState>(cx);201 let state = app_context::<AppState>(cx);
212 let lang = page_lang(cx, Some(&viewer));202 let lang = page_lang(cx, Some(&viewer));
@@ -220,11 +210,10 @@ async fn start_enrolment(cx: &Cx, Form(form): Form<CodeForm>) -> Result<impl Vie
220 .await;210 .await;
221 }211 }
222 let limit = two_factor_key(&viewer.user.id);212 let limit = two_factor_key(&viewer.user.id);
223- let now = Instant::now();
224 if state213 if state
225 .throttle214 .throttle
226- .check(&limit, TWO_FACTOR_USER_LIMIT, now)215+ .reserve(&limit, TWO_FACTOR_USER_LIMIT, Instant::now())
227- .is_some()216+ .is_err()
228 {217 {
229 return render_security(218 return render_security(
230 cx,219 cx,
@@ -237,7 +226,6 @@ async fn start_enrolment(cx: &Cx, Form(form): Form<CodeForm>) -> Result<impl Vie
237 .await?226 .await?
238 .is_none()227 .is_none()
239 {228 {
240- state.throttle.record_failure(&limit, now);
241 return render_security(229 return render_security(
242 cx,230 cx,
243 viewer.clone(),231 viewer.clone(),
@@ -245,6 +233,10 @@ async fn start_enrolment(cx: &Cx, Form(form): Form<CodeForm>) -> Result<impl Vie
245 )233 )
246 .await;234 .await;
247 }235 }
236+ state.throttle.refund(&limit);
237+ } else if let Some(problem) = password_problem(state, &viewer, &form.current_password).await? {
238+ // Turning two-factor sign-in on is a change of the account, so the password is needed too.
239+ return render_security(cx, viewer.clone(), Flash::alert(text(lang, problem))).await;
248 }240 }
249 let secret = totp::new_secret();241 let secret = totp::new_secret();
250 let sealed = secret::seal(&state.key, &secret)?;242 let sealed = secret::seal(&state.key, &secret)?;
@@ -288,7 +280,7 @@ async fn confirm_enrolment(cx: &Cx, Form(form): Form<CodeForm>) -> Result<impl V
288 let codes = issue_codes();280 let codes = issue_codes();
289 let hashes: Vec<String> = codes281 let hashes: Vec<String> = codes
290 .iter()282 .iter()
291- .map(|code| totp::recovery_code_hash(code))283+ .map(|code| totp::recovery_code_hash(&state.key, code))
292 .collect();284 .collect();
293 state285 state
294 .store286 .store
@@ -335,28 +327,22 @@ async fn disable_two_factor(cx: &Cx, Form(form): Form<DisableForm>) -> Result<im
335 if !viewer.user.totp_enabled() {327 if !viewer.user.totp_enabled() {
336 return Err(see_other("/account/security").into());328 return Err(see_other("/account/security").into());
337 }329 }
338- if password_locked(state, &viewer) {330+ if let Some(problem) = password_problem(state, &viewer, &form.current_password).await? {
339- return render_security(331+ return render_security(cx, viewer.clone(), Flash::alert(text(lang, problem))).await;
340- cx,
341- viewer.clone(),
342- Flash::alert(text(lang, Txt::ErrThrottled)),
343- )
344- .await;
345 }332 }
346- if !password_matches(state, &viewer, &form.current_password).await? {333+ if form.code.trim().is_empty() {
347 return render_security(334 return render_security(
348 cx,335 cx,
349 viewer.clone(),336 viewer.clone(),
350- Flash::alert(text(lang, Txt::ErrWrongPassword)),337+ Flash::alert(text(lang, Txt::ErrCodeMissing)),
351 )338 )
352 .await;339 .await;
353 }340 }
354 let limit = two_factor_key(&viewer.user.id);341 let limit = two_factor_key(&viewer.user.id);
355- let now = Instant::now();
356 if state342 if state
357 .throttle343 .throttle
358- .check(&limit, TWO_FACTOR_USER_LIMIT, now)344+ .reserve(&limit, TWO_FACTOR_USER_LIMIT, Instant::now())
359- .is_some()345+ .is_err()
360 {346 {
361 return render_security(347 return render_security(
362 cx,348 cx,
@@ -365,19 +351,10 @@ async fn disable_two_factor(cx: &Cx, Form(form): Form<DisableForm>) -> Result<im
365 )351 )
366 .await;352 .await;
367 }353 }
368- if form.code.trim().is_empty() {
369- return render_security(
370- cx,
371- viewer.clone(),
372- Flash::alert(text(lang, Txt::ErrCodeMissing)),
373- )
374- .await;
375- }
376 if check_second_factor(&state.store, &state.key, &viewer.user, &form.code)354 if check_second_factor(&state.store, &state.key, &viewer.user, &form.code)
377 .await?355 .await?
378 .is_none()356 .is_none()
379 {357 {
380- state.throttle.record_failure(&limit, now);
381 return render_security(358 return render_security(
382 cx,359 cx,
383 viewer.clone(),360 viewer.clone(),
@@ -386,7 +363,11 @@ async fn disable_two_factor(cx: &Cx, Form(form): Form<DisableForm>) -> Result<im
386 .await;363 .await;
387 }364 }
388 365
389- state.store.disable_totp(&viewer.user.id).await?;366+ // The other sessions end with the second factor (see `Store::disable_totp`); this one stays.
367+ state
368+ .store
369+ .disable_totp(&viewer.user.id, Some(&viewer.session.id))
370+ .await?;
390 state.throttle.clear(&limit);371 state.throttle.clear(&limit);
391 changed(state, &viewer);372 changed(state, &viewer);
392 record(373 record(
@@ -417,27 +398,14 @@ async fn regenerate_recovery(cx: &Cx, Form(form): Form<RecoveryForm>) -> Result<
417 if !viewer.user.totp_enabled() {398 if !viewer.user.totp_enabled() {
418 return Err(see_other("/account/security").into());399 return Err(see_other("/account/security").into());
419 }400 }
420- if password_locked(state, &viewer) {401+ if let Some(problem) = password_problem(state, &viewer, &form.current_password).await? {
421- return render_security(402+ return render_security(cx, viewer.clone(), Flash::alert(text(lang, problem))).await;
422- cx,
423- viewer.clone(),
424- Flash::alert(text(lang, Txt::ErrThrottled)),
425- )
426- .await;
427- }
428- if !password_matches(state, &viewer, &form.current_password).await? {
429- return render_security(
430- cx,
431- viewer.clone(),
432- Flash::alert(text(lang, Txt::ErrWrongPassword)),
433- )
434- .await;
435 }403 }
436 404
437 let codes = issue_codes();405 let codes = issue_codes();
438 let hashes: Vec<String> = codes406 let hashes: Vec<String> = codes
439 .iter()407 .iter()
440- .map(|code| totp::recovery_code_hash(code))408+ .map(|code| totp::recovery_code_hash(&state.key, code))
441 .collect();409 .collect();
442 state410 state
443 .store411 .store
@@ -473,29 +441,28 @@ fn issue_codes() -> Vec<String> {
473 .collect()441 .collect()
474 }442 }
475 443
476-/// True while the password counters hold the account. Wrong passwords on this page count toward444+/// Checks the password of the signed-in person, counted against the same limit as sign-in. The attempt is
477-/// the same limit as sign-in.445+/// counted before the check, so parallel guesses cannot all pass. `None` when the password is right;
478-pub fn password_locked(state: &AppState, viewer: &Viewer) -> bool {446+/// otherwise the message to show: the throttle's, or the wrong-password one. Wrong passwords on this page
479- state447+/// count toward the sign-in limit, so guessing here locks sign-in too.
480- .throttle448+pub async fn password_problem(
481- .check(449+ state: &AppState,
482- &user_key(&viewer.user.email),450+ viewer: &Viewer,
483- LOGIN_USER_LIMIT,451+ given: &str,
484- Instant::now(),452+) -> Result<Option<Txt>> {
485- )
486- .is_some()
487-}
488-
489-/// Checks the password of the signed-in person and records the outcome in the throttle.
490-pub async fn password_matches(state: &AppState, viewer: &Viewer, given: &str) -> Result<bool> {
491- let ok = verify_password_async(given.to_owned(), viewer.user.password_hash.clone()).await?;
492 let limit = user_key(&viewer.user.email);453 let limit = user_key(&viewer.user.email);
493- if ok {454+ if state
455+ .throttle
456+ .reserve(&limit, LOGIN_USER_LIMIT, Instant::now())
457+ .is_err()
458+ {
459+ return Ok(Some(Txt::ErrThrottled));
460+ }
461+ if verify_password_async(given.to_owned(), viewer.user.password_hash.clone()).await? {
494 state.throttle.clear(&limit);462 state.throttle.clear(&limit);
495- } else {463+ return Ok(None);
496- state.throttle.record_failure(&limit, Instant::now());
497 }464 }
498- Ok(ok)465+ Ok(Some(Txt::ErrWrongPassword))
499 }466 }
500 467
501 /// Tells the open account pages that the person's security changed.468 /// Tells the open account pages that the person's security changed.
@@ -629,6 +596,7 @@ fn security_view(
629 } else if !has_pending {596 } else if !has_pending {
630 <form method="post" action="/account/security/2fa/start" class="stack">597 <form method="post" action="/account/security/2fa/start" class="stack">
631 <input type="hidden" name="csrf" value=(csrf.clone())>598 <input type="hidden" name="csrf" value=(csrf.clone())>
599+ field(label: text(lang, Txt::CurrentPassword), name: "current_password", kind: "password", autocomplete: "current-password", value: String::new())
632 <button type="submit" class="button primary">(text(lang, Txt::TurnOn))</button>600 <button type="submit" class="button primary">(text(lang, Txt::TurnOn))</button>
633 </form>601 </form>
634 }602 }
crates/im-web/src/state.rsmodified+3 -1
@@ -4,7 +4,7 @@ use std::sync::{Arc, PoisonError, RwLock};
4 4
5 use im_core::config::{Config, PolicyConfig};5 use im_core::config::{Config, PolicyConfig};
6 use im_core::store::Store;6 use im_core::store::Store;
7-use tokio::sync::watch;7+use tokio::sync::{Semaphore, watch};
8 8
9 use crate::api::directory::StreamSlots;9 use crate::api::directory::StreamSlots;
10 use crate::live::LiveHub;10 use crate::live::LiveHub;
@@ -29,6 +29,8 @@ pub struct AppState {
29 pub throttle: Arc<Throttle>,29 pub throttle: Arc<Throttle>,
30 /// The open directory streams of each machine client.30 /// The open directory streams of each machine client.
31 pub stream_slots: Arc<StreamSlots>,31 pub stream_slots: Arc<StreamSlots>,
32+ /// The open anonymous `/-/alive` streams, at most [`MAX_ANONYMOUS_STREAMS`].
33+ pub anonymous_streams: Arc<Semaphore>,
32 /// Set when the process is stopping. Long-lived streams end when it is, so the server can drain.34 /// Set when the process is stopping. Long-lived streams end when it is, so the server can drain.
33 pub stop: watch::Receiver<bool>,35 pub stop: watch::Receiver<bool>,
34 }36 }
crates/im-web/src/throttle.rsmodified+181 -49
@@ -1,9 +1,17 @@
1 //! In-memory sliding-window failure counters that slow down password guessing.1 //! In-memory sliding-window failure counters that slow down password guessing.
2 //!2 //!
3 //! Each key keeps the instants of its recent failures, and is limited while it has `limit` of them3 //! Each key keeps the instants of its recent failures, and is limited while it has `limit` of them
4-//! inside [`WINDOW`]. Only rejected attempts are recorded, so a locked key stops growing. Memory is4+//! inside [`WINDOW`]. An attempt first asks [`Throttle::reserve`], which counts it before the work
5-//! bounded: expired instants and empty keys are pruned every few hundred failures, and at the key5+//! is done and answers with the wait when the key is already limited. A success gives the count back
6-//! cap the key whose latest failure is oldest is evicted.6+//! with [`Throttle::refund`] (or drops the key with [`Throttle::clear`] where the old failures go too).
7+//! Check and count are one step under one lock, so parallel attempts cannot all pass together.
8+//!
9+//! Memory is bounded. Expired instants and empty keys are pruned every few hundred attempts. At the key
10+//! cap, expired keys go first; then the key whose latest failure is oldest is evicted, but never a key
11+//! that is limited right now. When every key is limited, a new key is refused: fail closed.
12+//!
13+//! Email keys are capped too. An address that is too long or not plausible shares one fixed key, so a
14+//! flood of junk addresses cannot grow the map or the key size.
7 //!15 //!
8 //! The counters live in one process. A restart clears them, and two processes would each count16 //! The counters live in one process. A restart clears them, and two processes would each count
9 //! their own. `im` runs as one process, so this is the whole picture.17 //! their own. `im` runs as one process, so this is the whole picture.
@@ -13,6 +21,8 @@ use std::net::IpAddr;
13 use std::sync::{Mutex, MutexGuard};21 use std::sync::{Mutex, MutexGuard};
14 use std::time::{Duration, Instant};22 use std::time::{Duration, Instant};
15 23
24+use im_core::names::parse_email;
25+
16 /// Length of the failure window.26 /// Length of the failure window.
17 pub const WINDOW: Duration = Duration::from_secs(15 * 60);27 pub const WINDOW: Duration = Duration::from_secs(15 * 60);
18 28
@@ -37,9 +47,13 @@ pub const FORGOT_IP_LIMIT: usize = 20;
37 /// this.47 /// this.
38 const MAX_KEYS: usize = 100_000;48 const MAX_KEYS: usize = 100_000;
39 49
40-/// A full prune runs every this many recorded failures.50+/// A full prune runs every this many attempts.
41 const PRUNE_EVERY: u32 = 256;51 const PRUNE_EVERY: u32 = 256;
42 52
53+/// The part of an email key used for an address that is too long or not plausible. Contains `<`, which
54+/// no valid address contains, so it never collides with a real address.
55+const INVALID_ADDRESS: &str = "<invalid>";
56+
43 /// The failure counters of the process. Shared by every request through the app state.57 /// The failure counters of the process. Shared by every request through the app state.
44 pub struct Throttle {58 pub struct Throttle {
45 window: Duration,59 window: Duration,
@@ -49,8 +63,14 @@ pub struct Throttle {
49 63
50 #[derive(Default)]64 #[derive(Default)]
51 struct State {65 struct State {
52- failures: HashMap<String, VecDeque<Instant>>,66+ failures: HashMap<String, Entry>,
53- recorded: u32,67+ attempts: u32,
68+}
69+
70+/// The failures of one key, and the limit they were counted against.
71+struct Entry {
72+ stamps: VecDeque<Instant>,
73+ limit: usize,
54 }74 }
55 75
56 impl Default for Throttle {76 impl Default for Throttle {
@@ -69,33 +89,43 @@ impl Throttle {
69 }89 }
70 }90 }
71 91
72- /// How long until `key` drops below `limit` failures, or `None` when it is not limited.92+ /// Counts one attempt of `key` now, before the work is done. When the key already has `limit`
73- pub fn check(&self, key: &str, limit: usize, now: Instant) -> Option<Duration> {93+ /// failures inside the window, nothing is counted and the wait until it may try again comes back
74- let mut state = self.lock();94+ /// (at least one second when it is the key cap that refuses a new key).
75- let timestamps = state.failures.get_mut(key)?;95+ pub fn reserve(&self, key: &str, limit: usize, now: Instant) -> Result<(), Duration> {
76- drop_expired(timestamps, self.window, now);96+ self.reserve_all(&[(key, limit)], now)
77- if timestamps.len() < limit {
78- return None;
79- }
80- // The failure at this index leaves the window first, and that brings the count below limit.
81- let index = timestamps.len().checked_sub(limit)?;
82- let oldest = *timestamps.get(index)?;
83- Some((oldest + self.window).saturating_duration_since(now))
84 }97 }
85 98
86- /// Records one rejected attempt for `key` at `now`.99+ /// Counts one attempt against every key, or against none. All keys are checked under one lock. When
87- pub fn record_failure(&self, key: &str, now: Instant) {100+ /// one of them refuses, the keys already counted are given back, and the longest wait comes back.
101+ pub fn reserve_all(&self, keys: &[(&str, usize)], now: Instant) -> Result<(), Duration> {
88 let mut state = self.lock();102 let mut state = self.lock();
89- state.recorded = state.recorded.wrapping_add(1);103+ state.attempts = state.attempts.wrapping_add(1);
90- if state.recorded.is_multiple_of(PRUNE_EVERY) {104+ if state.attempts.is_multiple_of(PRUNE_EVERY) {
91 self.prune_locked(&mut state, now);105 self.prune_locked(&mut state, now);
92 }106 }
93- if !state.failures.contains_key(key) && state.failures.len() >= self.max_keys {107+ let mut admitted = Vec::with_capacity(keys.len());
94- self.evict_oldest_locked(&mut state);108+ let mut wait: Option<Duration> = None;
109+ for &(key, limit) in keys {
110+ match self.reserve_locked(&mut state, key, limit, now) {
111+ Ok(()) => admitted.push(key),
112+ Err(due) => wait = Some(wait.map_or(due, |longest| longest.max(due))),
113+ }
114+ }
115+ match wait {
116+ None => Ok(()),
117+ Some(due) => {
118+ for key in admitted {
119+ self.refund_locked(&mut state, key);
120+ }
121+ Err(due)
122+ }
95 }123 }
96- let timestamps = state.failures.entry(key.to_owned()).or_default();124+ }
97- drop_expired(timestamps, self.window, now);125+
98- timestamps.push_back(now);126+ /// Takes back the newest counted attempt of `key`, for an attempt that succeeded.
127+ pub fn refund(&self, key: &str) {
128+ self.refund_locked(&mut self.lock(), key);
99 }129 }
100 130
101 /// Forgets the failures of `key`, after a success.131 /// Forgets the failures of `key`, after a success.
@@ -103,28 +133,87 @@ impl Throttle {
103 self.lock().failures.remove(key);133 self.lock().failures.remove(key);
104 }134 }
105 135
106- /// Drops expired failures and the keys left empty.136+ /// Counts one attempt of `key` under `limit`, with the lock already held.
107- fn prune_locked(&self, state: &mut State, now: Instant) {137+ fn reserve_locked(
108- let window = self.window;138+ &self,
109- state.failures.retain(|_, timestamps| {139+ state: &mut State,
110- drop_expired(timestamps, window, now);140+ key: &str,
111- !timestamps.is_empty()141+ limit: usize,
112- });142+ now: Instant,
143+ ) -> Result<(), Duration> {
144+ if !state.failures.contains_key(key)
145+ && state.failures.len() >= self.max_keys
146+ && !self.make_room_locked(state, now)
147+ {
148+ // Every key is limited right now: the new one is refused, which is the fail-closed answer.
149+ return Err(self.window);
150+ }
151+ let entry = state
152+ .failures
153+ .entry(key.to_owned())
154+ .or_insert_with(|| Entry {
155+ stamps: VecDeque::new(),
156+ limit,
157+ });
158+ entry.limit = limit;
159+ drop_expired(&mut entry.stamps, self.window, now);
160+ if entry.stamps.len() >= limit {
161+ return Err(wait_for(&entry.stamps, limit, self.window, now));
162+ }
163+ entry.stamps.push_back(now);
164+ Ok(())
165+ }
166+
167+ /// Gives back the newest failure of `key`, and drops the key when nothing is left.
168+ fn refund_locked(&self, state: &mut State, key: &str) {
169+ let emptied = match state.failures.get_mut(key) {
170+ Some(entry) => {
171+ entry.stamps.pop_back();
172+ entry.stamps.is_empty()
173+ }
174+ None => false,
175+ };
176+ if emptied {
177+ state.failures.remove(key);
178+ }
113 }179 }
114 180
115- /// Removes the key whose latest failure is the oldest. Runs only when the cap is reached.181+ /// Frees one slot for a new key. Expired failures go first. Then the key whose latest failure is the
116- fn evict_oldest_locked(&self, state: &mut State) {182+ /// oldest is removed, but only among keys that are not limited now. Returns false when every key is
183+ /// limited, so nothing can be removed.
184+ fn make_room_locked(&self, state: &mut State, now: Instant) -> bool {
185+ let window = self.window;
186+ state.failures.retain(|_, entry| {
187+ drop_expired(&mut entry.stamps, window, now);
188+ !entry.stamps.is_empty()
189+ });
190+ if state.failures.len() < self.max_keys {
191+ return true;
192+ }
117 let victim = state193 let victim = state
118 .failures194 .failures
119 .iter()195 .iter()
120- .filter_map(|(key, timestamps)| timestamps.back().map(|last| (key, *last)))196+ .filter(|(_, entry)| entry.stamps.len() < entry.limit)
121- .min_by_key(|(_, last)| *last)197+ .min_by_key(|(_, entry)| entry.stamps.back().copied())
122 .map(|(key, _)| key.clone());198 .map(|(key, _)| key.clone());
123- if let Some(key) = victim {199+ match victim {
124- state.failures.remove(&key);200+ Some(key) => {
201+ state.failures.remove(&key);
202+ true
203+ }
204+ None => false,
125 }205 }
126 }206 }
127 207
208+ /// Drops expired failures and the keys left empty.
209+ fn prune_locked(&self, state: &mut State, now: Instant) {
210+ let window = self.window;
211+ state.failures.retain(|_, entry| {
212+ drop_expired(&mut entry.stamps, window, now);
213+ !entry.stamps.is_empty()
214+ });
215+ }
216+
128 fn lock(&self) -> MutexGuard<'_, State> {217 fn lock(&self) -> MutexGuard<'_, State> {
129 // A poisoned lock still holds consistent counters, so the next caller uses it as it is.218 // A poisoned lock still holds consistent counters, so the next caller uses it as it is.
130 self.state.lock().unwrap_or_else(|e| e.into_inner())219 self.state.lock().unwrap_or_else(|e| e.into_inner())
@@ -141,14 +230,34 @@ fn drop_expired(timestamps: &mut VecDeque<Instant>, window: Duration, now: Insta
141 }230 }
142 }231 }
143 232
233+/// The wait until `stamps` drops below `limit` failures: the failure at this index is the last one to
234+/// leave the window before the count does.
235+fn wait_for(stamps: &VecDeque<Instant>, limit: usize, window: Duration, now: Instant) -> Duration {
236+ let Some(index) = stamps.len().checked_sub(limit) else {
237+ return Duration::ZERO;
238+ };
239+ stamps.get(index).map_or(Duration::ZERO, |oldest| {
240+ (*oldest + window).saturating_duration_since(now)
241+ })
242+}
243+
244+/// The part of an email key for `email`: the address itself when it is plausible and short, otherwise
245+/// one fixed sentinel. The sentinel keeps the keys of junk input bounded, and the answer the same.
246+fn address_part(email: &str) -> String {
247+ match parse_email(email) {
248+ Ok(address) => address,
249+ Err(_) => INVALID_ADDRESS.to_owned(),
250+ }
251+}
252+
144 /// Throttle key for a normalised email address.253 /// Throttle key for a normalised email address.
145 pub fn user_key(email: &str) -> String {254 pub fn user_key(email: &str) -> String {
146- format!("user:{email}")255+ format!("user:{}", address_part(email))
147 }256 }
148 257
149 /// Throttle key for the reset-link requests of one normalised address.258 /// Throttle key for the reset-link requests of one normalised address.
150 pub fn forgot_email_key(email: &str) -> String {259 pub fn forgot_email_key(email: &str) -> String {
151- format!("forgot:{email}")260+ format!("forgot:{}", address_part(email))
152 }261 }
153 262
154 /// Throttle key for the second factor of one user, by user id.263 /// Throttle key for the second factor of one user, by user id.
@@ -164,6 +273,7 @@ pub fn ip_key(scope: &str, ip: IpAddr) -> String {
164 #[cfg(test)]273 #[cfg(test)]
165 mod tests {274 mod tests {
166 use super::*;275 use super::*;
276+ use std::sync::Arc;
167 277
168 #[test]278 #[test]
169 fn a_key_is_limited_at_the_threshold_and_free_when_the_window_passes() {279 fn a_key_is_limited_at_the_threshold_and_free_when_the_window_passes() {
@@ -171,26 +281,48 @@ mod tests {
171 let t0 = Instant::now();281 let t0 = Instant::now();
172 for i in 0..3 {282 for i in 0..3 {
173 let at = t0 + Duration::from_secs(i);283 let at = t0 + Duration::from_secs(i);
174- assert!(throttle.check("k", 3, at).is_none());284+ assert!(throttle.reserve("k", 3, at).is_ok());
175- throttle.record_failure("k", at);
176 }285 }
177 let retry = throttle286 let retry = throttle
178- .check("k", 3, t0 + Duration::from_secs(10))287+ .reserve("k", 3, t0 + Duration::from_secs(10))
179- .expect("limited");288+ .expect_err("limited");
180 assert_eq!(retry, Duration::from_secs(50));289 assert_eq!(retry, Duration::from_secs(50));
181 assert!(290 assert!(
182 throttle291 throttle
183- .check("k", 3, t0 + Duration::from_secs(60))292+ .reserve("k", 3, t0 + Duration::from_secs(60))
184- .is_none()293+ .is_ok()
185 );294 );
186 }295 }
187 296
297+ /// Twenty parallel wrong-password attempts against one key: only the limit's worth is counted and
298+ /// admitted, and the rest are refused. Check and count are one step, so none can slip past.
299+ #[test]
300+ fn parallel_reservations_admit_no_more_than_the_limit() {
301+ let throttle = Arc::new(Throttle::with_limits(WINDOW, MAX_KEYS));
302+ let handles: Vec<_> = (0..20)
303+ .map(|_| {
304+ let throttle = Arc::clone(&throttle);
305+ std::thread::spawn(move || {
306+ throttle
307+ .reserve("login", LOGIN_USER_LIMIT, Instant::now())
308+ .is_ok()
309+ })
310+ })
311+ .collect();
312+ let admitted = handles
313+ .into_iter()
314+ .map(|handle| handle.join().expect("attempt thread"))
315+ .filter(|ok| *ok)
316+ .count();
317+ assert_eq!(admitted, LOGIN_USER_LIMIT);
318+ }
319+
188 #[test]320 #[test]
189 fn the_key_count_stays_at_the_cap() {321 fn the_key_count_stays_at_the_cap() {
190 let throttle = Throttle::with_limits(Duration::from_secs(10), 8);322 let throttle = Throttle::with_limits(Duration::from_secs(10), 8);
191 let t0 = Instant::now();323 let t0 = Instant::now();
192 for i in 0..1000u64 {324 for i in 0..1000u64 {
193- throttle.record_failure(&format!("key-{i}"), t0 + Duration::from_millis(i));325+ let _ = throttle.reserve(&format!("key-{i}"), 2, t0 + Duration::from_millis(i));
194 assert!(throttle.lock().failures.len() <= 8);326 assert!(throttle.lock().failures.len() <= 8);
195 }327 }
196 }328 }