🔒 races: sessions re-check the sign-in state, single TOTP enrolment, one pending key, photo lock, no links for disabled accounts
Browse files at this commitd3228adf9a2558ba097b0ab7c27a596a2c3b4c06Parent: ec12b7821 changed files +349 -89
- crates/im-core/src/store/backchannel.rs +3 -1
- crates/im-core/src/store/keys.rs +19 -5
- crates/im-core/src/store/links.rs +23 -5
- crates/im-core/src/store/sessions.rs +100 -9
- crates/im-core/src/store/users.rs +39 -8
- crates/im-web/src/auth.rs +17 -6
- crates/im-web/src/backchannel.rs +8 -2
- crates/im-web/src/boot.rs +2 -0
- crates/im-web/src/oidc/signing.rs +11 -14
- crates/im-web/src/oidc/tests.rs +4 -2
- crates/im-web/src/pages/admin/tests.rs +10 -2
- crates/im-web/src/pages/invite.rs +5 -1
- crates/im-web/src/pages/login.rs +63 -26
- crates/im-web/src/pages/profile.rs +4 -0
- crates/im-web/src/pages/reset.rs +11 -1
- crates/im-web/src/pages/security.rs +10 -1
- crates/im-web/src/pages/setup.rs +5 -1
- crates/im-web/src/pages/tests.rs +4 -2
- crates/im-web/src/state.rs +3 -0
- docs/architecture.md +7 -2
- docs/contracts.md +1 -1
crates/im-core/src/store/backchannel.rsmodified+3 -1
| @@ -316,7 +316,7 @@ mod tests { | |||
| 316 | use crate::model::amr; | 316 | use crate::model::amr; |
| 317 | use crate::store::clients::NewClient; | 317 | use crate::store::clients::NewClient; |
| 318 | use crate::store::oidc::{NewAuthCode, NewRefreshToken}; | 318 | use crate::store::oidc::{NewAuthCode, NewRefreshToken}; |
| 319 | - use crate::store::sessions::{NewSession, SESSION_IDLE}; | 319 | + use crate::store::sessions::{NewSession, SESSION_IDLE, SignInState}; |
| 320 | use crate::time::stamp_after; | 320 | use crate::time::stamp_after; |
| 321 | use crate::token::hash_token; | 321 | use crate::token::hash_token; |
| 322 | 322 | ||
| @@ -350,6 +350,7 @@ mod tests { | |||
| 350 | .create_session( | 350 | .create_session( |
| 351 | &NewSession { | 351 | &NewSession { |
| 352 | user_id: &user.id, | 352 | user_id: &user.id, |
| 353 | + decided_on: SignInState::of(&user), | ||
| 353 | token_hash: "session-token", | 354 | token_hash: "session-token", |
| 354 | csrf_token: "csrf", | 355 | csrf_token: "csrf", |
| 355 | amr: amr::PASSWORD, | 356 | amr: amr::PASSWORD, |
| @@ -362,6 +363,7 @@ mod tests { | |||
| 362 | ) | 363 | ) |
| 363 | .await | 364 | .await |
| 364 | .expect("session") | 365 | .expect("session") |
| 366 | + .expect("not refused") | ||
| 365 | .session; | 367 | .session; |
| 366 | for client in &clients { | 368 | for client in &clients { |
| 367 | store | 369 | store |
crates/im-core/src/store/keys.rsmodified+19 -5
| @@ -8,7 +8,8 @@ use turso::Value; | |||
| 8 | 8 | ||
| 9 | use crate::error::{Error, Result}; | 9 | use crate::error::{Error, Result}; |
| 10 | use crate::model::KeyRecord; | 10 | use crate::model::KeyRecord; |
| 11 | -use crate::store::{Store, col_opt_text, col_text, db_err, fetch_all, finish}; | 11 | +use crate::store::{Store, col_int, col_opt_text, col_text, db_err, fetch_all, fetch_opt, finish}; |
| 12 | +use crate::time::now_stamp; | ||
| 12 | 13 | ||
| 13 | /// The columns of a key row, in the order [`map_key`] reads them. | 14 | /// The columns of a key row, in the order [`map_key`] reads them. |
| 14 | const KEY_COLS: &str = "kid, private_sealed, public_raw, created_at, activates_at, retires_at"; | 15 | const KEY_COLS: &str = "kid, private_sealed, public_raw, created_at, activates_at, retires_at"; |
| @@ -42,11 +43,24 @@ impl Store { | |||
| 42 | } | 43 | } |
| 43 | 44 | ||
| 44 | /// Adds a key. Every key that is not yet retired and activates before it is retired at its | 45 | /// Adds a key. Every key that is not yet retired and activates before it is retired at its |
| 45 | - /// activation time, in the same transaction. | 46 | + /// activation time, in the same transaction. Returns false, with nothing changed, when another key |
| 46 | - pub async fn add_signing_key(&self, key: &KeyRecord) -> Result<()> { | 47 | + /// is still waiting to activate: two pending keys would make the retirement order ambiguous. The |
| 48 | + /// check and the insert are one transaction, so parallel rotations cannot both pass it. | ||
| 49 | + pub async fn add_signing_key(&self, key: &KeyRecord) -> Result<bool> { | ||
| 50 | + let now = now_stamp(); | ||
| 47 | let conn = self.inner.conn.lock().await; | 51 | let conn = self.inner.conn.lock().await; |
| 48 | let tx = conn.unchecked_transaction().await.map_err(db_err)?; | 52 | let tx = conn.unchecked_transaction().await.map_err(db_err)?; |
| 49 | - let outcome: Result<()> = async { | 53 | + let outcome: Result<bool> = async { |
| 54 | + let pending = fetch_opt( | ||
| 55 | + &tx, | ||
| 56 | + "SELECT 1 FROM signing_keys WHERE retires_at IS NULL AND activates_at > ?1", | ||
| 57 | + (now,), | ||
| 58 | + |row| col_int(row, 0), | ||
| 59 | + ) | ||
| 60 | + .await?; | ||
| 61 | + if pending.is_some() { | ||
| 62 | + return Ok(false); | ||
| 63 | + } | ||
| 50 | tx.execute( | 64 | tx.execute( |
| 51 | "UPDATE signing_keys SET retires_at = ?1 \ | 65 | "UPDATE signing_keys SET retires_at = ?1 \ |
| 52 | WHERE retires_at IS NULL AND activates_at < ?1", | 66 | WHERE retires_at IS NULL AND activates_at < ?1", |
| @@ -67,7 +81,7 @@ impl Store { | |||
| 67 | ) | 81 | ) |
| 68 | .await | 82 | .await |
| 69 | .map_err(db_err)?; | 83 | .map_err(db_err)?; |
| 70 | - Ok(()) | 84 | + Ok(true) |
| 71 | } | 85 | } |
| 72 | .await; | 86 | .await; |
| 73 | finish(tx, outcome).await | 87 | finish(tx, outcome).await |
crates/im-core/src/store/links.rsmodified+23 -5
| @@ -80,8 +80,9 @@ impl Store { | |||
| 80 | /// Creates a password-reset link and queues its `mail` in one transaction. The mail is checked first | 80 | /// Creates a password-reset link and queues its `mail` in one transaction. The mail is checked first |
| 81 | /// (see `store::mail`): when it would be dropped, nothing changes, so an older link that was mailed | 81 | /// (see `store::mail`): when it would be dropped, nothing changes, so an older link that was mailed |
| 82 | /// keeps working and no new link is made that nobody receives. Otherwise older pending reset links of | 82 | /// keeps working and no new link is made that nobody receives. Otherwise older pending reset links of |
| 83 | - /// the person stop working. Returns the outbox id, or `None` when the mail was dropped. The caller has | 83 | + /// the person stop working. Returns the outbox id, or `None` when the mail was dropped or the person is |
| 84 | - /// checked that the person exists and is not disabled. | 84 | + /// disabled or missing (nothing is created then). The check is in the same transaction as the insert, so |
| 85 | + /// a link is never made for an account that a parallel disable has just ended. | ||
| 85 | pub async fn create_reset_link( | 86 | pub async fn create_reset_link( |
| 86 | &self, | 87 | &self, |
| 87 | user_id: &str, | 88 | user_id: &str, |
| @@ -93,7 +94,14 @@ impl Store { | |||
| 93 | let conn = self.inner.conn.lock().await; | 94 | let conn = self.inner.conn.lock().await; |
| 94 | let tx = conn.unchecked_transaction().await.map_err(db_err)?; | 95 | let tx = conn.unchecked_transaction().await.map_err(db_err)?; |
| 95 | let outcome: Result<Option<String>> = async { | 96 | let outcome: Result<Option<String>> = async { |
| 96 | - if !admitted(&tx, mail).await? { | 97 | + let enabled = fetch_opt( |
| 98 | + &tx, | ||
| 99 | + "SELECT 1 FROM users WHERE id = ?1 AND disabled_at IS NULL", | ||
| 100 | + (user_id.to_string(),), | ||
| 101 | + |_row| Ok(()), | ||
| 102 | + ) | ||
| 103 | + .await?; | ||
| 104 | + if enabled.is_none() || !admitted(&tx, mail).await? { | ||
| 97 | return Ok(None); | 105 | return Ok(None); |
| 98 | } | 106 | } |
| 99 | tx.execute( | 107 | tx.execute( |
| @@ -208,8 +216,8 @@ impl Store { | |||
| 208 | /// Starts an email change: two links, one for each address, sharing a pair id, with their two mails | 216 | /// Starts an email change: two links, one for each address, sharing a pair id, with their two mails |
| 209 | /// (`mails[0]` to the current address, `mails[1]` to the new one). Older pending email links of the | 217 | /// (`mails[0]` to the current address, `mails[1]` to the new one). Older pending email links of the |
| 210 | /// person stop working. Fails with a conflict when `new_email` belongs to an account. When either mail | 218 | /// person stop working. Fails with a conflict when `new_email` belongs to an account. When either mail |
| 211 | - /// would be dropped by the limits, nothing changes and the answer is `false`. `expires_at` is the same | 219 | + /// would be dropped by the limits, or the person is disabled or missing, nothing changes and the answer |
| 212 | - /// for both halves. | 220 | + /// is `false`. `expires_at` is the same for both halves. |
| 213 | pub async fn start_email_change( | 221 | pub async fn start_email_change( |
| 214 | &self, | 222 | &self, |
| 215 | user_id: &str, | 223 | user_id: &str, |
| @@ -236,6 +244,16 @@ impl Store { | |||
| 236 | "that email address cannot be used".into(), | 244 | "that email address cannot be used".into(), |
| 237 | )); | 245 | )); |
| 238 | } | 246 | } |
| 247 | + let enabled = fetch_opt( | ||
| 248 | + &tx, | ||
| 249 | + "SELECT 1 FROM users WHERE id = ?1 AND disabled_at IS NULL", | ||
| 250 | + (user_id.to_string(),), | ||
| 251 | + |_row| Ok(()), | ||
| 252 | + ) | ||
| 253 | + .await?; | ||
| 254 | + if enabled.is_none() { | ||
| 255 | + return Ok(false); | ||
| 256 | + } | ||
| 239 | for mail in mails { | 257 | for mail in mails { |
| 240 | if !admitted(&tx, mail).await? { | 258 | if !admitted(&tx, mail).await? { |
| 241 | return Ok(false); | 259 | return Ok(false); |
crates/im-core/src/store/sessions.rsmodified+100 -9
| @@ -14,9 +14,11 @@ use std::time::Duration; | |||
| 14 | use turso::Connection; | 14 | use turso::Connection; |
| 15 | 15 | ||
| 16 | use crate::error::Result; | 16 | use crate::error::Result; |
| 17 | -use crate::model::Session; | 17 | +use crate::model::{Session, User}; |
| 18 | use crate::store::backchannel::{self, EndReason}; | 18 | use crate::store::backchannel::{self, EndReason}; |
| 19 | -use crate::store::{Store, col_opt_text, col_text, db_err, fetch_all, fetch_opt, finish, new_id}; | 19 | +use crate::store::{ |
| 20 | + Store, col_int, col_opt_text, col_text, db_err, fetch_all, fetch_opt, finish, new_id, | ||
| 21 | +}; | ||
| 20 | use crate::time::{now_stamp, stamp_after, stamp_before}; | 22 | use crate::time::{now_stamp, stamp_after, stamp_before}; |
| 21 | 23 | ||
| 22 | /// The least time between two writes of `last_seen_at` for one session. Every request reads the | 24 | /// The least time between two writes of `last_seen_at` for one session. Every request reads the |
| @@ -49,12 +51,36 @@ fn map_session(row: &turso::Row) -> Result<Session> { | |||
| 49 | }) | 51 | }) |
| 50 | } | 52 | } |
| 51 | 53 | ||
| 54 | +/// The authentication state a sign-in was decided on: the password hash and whether two-factor | ||
| 55 | +/// sign-in was on. A session is created only while the user still has this state (see | ||
| 56 | +/// [`Store::create_session`]), so a password change, reset, enrolment or disable that committed | ||
| 57 | +/// after the sign-in was decided is not undone by it. | ||
| 58 | +#[derive(Debug, Clone, Copy)] | ||
| 59 | +pub struct SignInState<'a> { | ||
| 60 | + /// The argon2id hash the password step was checked against, or the one a reset just set. | ||
| 61 | + pub password_hash: &'a str, | ||
| 62 | + /// Whether two-factor sign-in was on when the sign-in was decided. | ||
| 63 | + pub totp_enabled: bool, | ||
| 64 | +} | ||
| 65 | + | ||
| 66 | +impl<'a> SignInState<'a> { | ||
| 67 | + /// The state of `user` as it was read. | ||
| 68 | + pub fn of(user: &'a User) -> Self { | ||
| 69 | + Self { | ||
| 70 | + password_hash: &user.password_hash, | ||
| 71 | + totp_enabled: user.totp_enabled(), | ||
| 72 | + } | ||
| 73 | + } | ||
| 74 | +} | ||
| 75 | + | ||
| 52 | /// What is needed to create a session. `token_hash` is the hash of the cookie token; the token | 76 | /// What is needed to create a session. `token_hash` is the hash of the cookie token; the token |
| 53 | /// itself never reaches the store. | 77 | /// itself never reaches the store. |
| 54 | #[derive(Debug, Clone)] | 78 | #[derive(Debug, Clone)] |
| 55 | pub struct NewSession<'a> { | 79 | pub struct NewSession<'a> { |
| 56 | /// Owner of the session. | 80 | /// Owner of the session. |
| 57 | pub user_id: &'a str, | 81 | pub user_id: &'a str, |
| 82 | + /// The state the sign-in was decided on. Checked again inside the write. | ||
| 83 | + pub decided_on: SignInState<'a>, | ||
| 58 | /// Hex SHA-256 of the token that goes in the cookie. | 84 | /// Hex SHA-256 of the token that goes in the cookie. |
| 59 | pub token_hash: &'a str, | 85 | pub token_hash: &'a str, |
| 60 | /// The per-session CSRF token. | 86 | /// The per-session CSRF token. |
| @@ -154,14 +180,18 @@ pub(crate) async fn end_all_sessions( | |||
| 154 | impl Store { | 180 | impl Store { |
| 155 | /// Creates a session for a user who has just proved who they are. | 181 | /// Creates a session for a user who has just proved who they are. |
| 156 | /// | 182 | /// |
| 157 | - /// In one transaction: if the user already has `max_sessions` live sessions, the oldest ones | 183 | + /// In one transaction: first the user must still be enabled, with the password hash and the |
| 158 | - /// are ended until there is room for the new one, then the new row is inserted. The check and | 184 | + /// two-factor state the sign-in was decided on. Otherwise nothing is written and `None` is |
| 159 | - /// the insert are in the same transaction, so two parallel sign-ins cannot both exceed the cap. | 185 | + /// returned. Then, if the user already has `max_sessions` live sessions, the oldest ones are |
| 186 | + /// ended until there is room for the new one, and the new row is inserted. The check and the | ||
| 187 | + /// insert are in the same transaction, so two parallel sign-ins cannot both exceed the cap, and | ||
| 188 | + /// a concurrent password change or disable either commits first (and this returns `None`) or | ||
| 189 | + /// waits for this session to exist (and then ends it). | ||
| 160 | pub async fn create_session( | 190 | pub async fn create_session( |
| 161 | &self, | 191 | &self, |
| 162 | new: &NewSession<'_>, | 192 | new: &NewSession<'_>, |
| 163 | max_sessions: u32, | 193 | max_sessions: u32, |
| 164 | - ) -> Result<CreatedSession> { | 194 | + ) -> Result<Option<CreatedSession>> { |
| 165 | let now = now_stamp(); | 195 | let now = now_stamp(); |
| 166 | let hard_expires_at = stamp_after(new.max_age); | 196 | let hard_expires_at = stamp_after(new.max_age); |
| 167 | let idle_expires_at = stamp_after(new.idle); | 197 | let idle_expires_at = stamp_after(new.idle); |
| @@ -190,7 +220,22 @@ impl Store { | |||
| 190 | 220 | ||
| 191 | let conn = self.inner.conn.lock().await; | 221 | let conn = self.inner.conn.lock().await; |
| 192 | let tx = conn.unchecked_transaction().await.map_err(db_err)?; | 222 | let tx = conn.unchecked_transaction().await.map_err(db_err)?; |
| 193 | - let outcome: Result<CreatedSession> = async { | 223 | + let outcome: Result<Option<CreatedSession>> = async { |
| 224 | + let still_decided = fetch_opt( | ||
| 225 | + &tx, | ||
| 226 | + "SELECT 1 FROM users WHERE id = ?1 AND disabled_at IS NULL \ | ||
| 227 | + AND password_hash = ?2 AND (totp_enabled_at IS NOT NULL) = ?3", | ||
| 228 | + ( | ||
| 229 | + new.user_id.to_string(), | ||
| 230 | + new.decided_on.password_hash.to_string(), | ||
| 231 | + i64::from(new.decided_on.totp_enabled), | ||
| 232 | + ), | ||
| 233 | + |row| col_int(row, 0), | ||
| 234 | + ) | ||
| 235 | + .await?; | ||
| 236 | + if still_decided.is_none() { | ||
| 237 | + return Ok(None); | ||
| 238 | + } | ||
| 194 | let live = fetch_all( | 239 | let live = fetch_all( |
| 195 | &tx, | 240 | &tx, |
| 196 | "SELECT id FROM sessions WHERE user_id = ?1 AND expires_at > ?2 \ | 241 | "SELECT id FROM sessions WHERE user_id = ?1 AND expires_at > ?2 \ |
| @@ -224,10 +269,10 @@ impl Store { | |||
| 224 | ) | 269 | ) |
| 225 | .await | 270 | .await |
| 226 | .map_err(db_err)?; | 271 | .map_err(db_err)?; |
| 227 | - Ok(CreatedSession { | 272 | + Ok(Some(CreatedSession { |
| 228 | session: session.clone(), | 273 | session: session.clone(), |
| 229 | ended, | 274 | ended, |
| 230 | - }) | 275 | + })) |
| 231 | } | 276 | } |
| 232 | .await; | 277 | .await; |
| 233 | finish(tx, outcome).await | 278 | finish(tx, outcome).await |
| @@ -434,6 +479,7 @@ mod tests { | |||
| 434 | .create_session( | 479 | .create_session( |
| 435 | &NewSession { | 480 | &NewSession { |
| 436 | user_id: &user.id, | 481 | user_id: &user.id, |
| 482 | + decided_on: SignInState::of(&user), | ||
| 437 | token_hash: &token, | 483 | token_hash: &token, |
| 438 | csrf_token: "csrf", | 484 | csrf_token: "csrf", |
| 439 | amr: "pwd", | 485 | amr: "pwd", |
| @@ -445,6 +491,7 @@ mod tests { | |||
| 445 | 2, | 491 | 2, |
| 446 | ) | 492 | ) |
| 447 | .await | 493 | .await |
| 494 | + .unwrap() | ||
| 448 | .unwrap(); | 495 | .unwrap(); |
| 449 | if n < 2 { | 496 | if n < 2 { |
| 450 | assert!(created.ended.is_empty()); | 497 | assert!(created.ended.is_empty()); |
| @@ -471,6 +518,48 @@ mod tests { | |||
| 471 | ); | 518 | ); |
| 472 | } | 519 | } |
| 473 | 520 | ||
| 521 | + #[tokio::test] | ||
| 522 | + async fn a_session_is_refused_once_the_decided_state_has_changed() { | ||
| 523 | + let dir = tempfile::tempdir().unwrap(); | ||
| 524 | + let store = Store::open(&dir.path().join("im.db")).await.unwrap(); | ||
| 525 | + let user = store | ||
| 526 | + .create_user("ada@example.com", "Ada", "hash", false) | ||
| 527 | + .await | ||
| 528 | + .unwrap(); | ||
| 529 | + let new = |token: &'static str, decided_on| NewSession { | ||
| 530 | + user_id: &user.id, | ||
| 531 | + decided_on, | ||
| 532 | + token_hash: token, | ||
| 533 | + csrf_token: "csrf", | ||
| 534 | + amr: "pwd", | ||
| 535 | + ip: None, | ||
| 536 | + user_agent: None, | ||
| 537 | + idle: SESSION_IDLE, | ||
| 538 | + max_age: Duration::from_secs(3600), | ||
| 539 | + }; | ||
| 540 | + // The password changed after the sign-in was decided on: nothing is created. | ||
| 541 | + let stale = SignInState { | ||
| 542 | + password_hash: "old-hash", | ||
| 543 | + totp_enabled: false, | ||
| 544 | + }; | ||
| 545 | + assert!( | ||
| 546 | + store | ||
| 547 | + .create_session(&new("stale", stale), 10) | ||
| 548 | + .await | ||
| 549 | + .unwrap() | ||
| 550 | + .is_none() | ||
| 551 | + ); | ||
| 552 | + assert!(store.list_sessions(&user.id).await.unwrap().is_empty()); | ||
| 553 | + // The state as decided on still holds: the session is created. | ||
| 554 | + assert!( | ||
| 555 | + store | ||
| 556 | + .create_session(&new("fresh", SignInState::of(&user)), 10) | ||
| 557 | + .await | ||
| 558 | + .unwrap() | ||
| 559 | + .is_some() | ||
| 560 | + ); | ||
| 561 | + } | ||
| 562 | + | ||
| 474 | #[tokio::test] | 563 | #[tokio::test] |
| 475 | async fn idle_extension_never_passes_the_hard_cap() { | 564 | async fn idle_extension_never_passes_the_hard_cap() { |
| 476 | let dir = tempfile::tempdir().unwrap(); | 565 | let dir = tempfile::tempdir().unwrap(); |
| @@ -484,6 +573,7 @@ mod tests { | |||
| 484 | .create_session( | 573 | .create_session( |
| 485 | &NewSession { | 574 | &NewSession { |
| 486 | user_id: &user.id, | 575 | user_id: &user.id, |
| 576 | + decided_on: SignInState::of(&user), | ||
| 487 | token_hash: "capped", | 577 | token_hash: "capped", |
| 488 | csrf_token: "csrf", | 578 | csrf_token: "csrf", |
| 489 | amr: "pwd", | 579 | amr: "pwd", |
| @@ -495,6 +585,7 @@ mod tests { | |||
| 495 | 10, | 585 | 10, |
| 496 | ) | 586 | ) |
| 497 | .await | 587 | .await |
| 588 | + .unwrap() | ||
| 498 | .unwrap(); | 589 | .unwrap(); |
| 499 | let cap = created.session.hard_expires_at.clone(); | 590 | let cap = created.session.hard_expires_at.clone(); |
| 500 | assert!(created.session.expires_at <= cap); | 591 | assert!(created.session.expires_at <= cap); |
crates/im-core/src/store/users.rsmodified+39 -8
| @@ -358,7 +358,8 @@ impl Store { | |||
| 358 | /// Disables an account. The last enabled administrator cannot be disabled: that is part of the | 358 | /// Disables an account. The last enabled administrator cannot be disabled: that is part of the |
| 359 | /// same conditional `UPDATE`, so two parallel requests cannot both disable the last two. In one transaction: the account is marked disabled, the directory feed | 359 | /// same conditional `UPDATE`, so two parallel requests cannot both disable the last two. In one transaction: the account is marked disabled, the directory feed |
| 360 | /// records the change, one `sub`-only back-channel logout is queued for every client the person | 360 | /// records the change, one `sub`-only back-channel logout is queued for every client the person |
| 361 | - /// used (contracts.md 2.5), the refresh tokens are revoked and every session is deleted. Returns | 361 | + /// used (contracts.md 2.5), the refresh tokens are revoked, the pending reset and email-change links are |
| 362 | + /// used up, and every session is deleted. Returns | ||
| 362 | /// false, with nothing changed, when the account is missing or already disabled. | 363 | /// false, with nothing changed, when the account is missing or already disabled. |
| 363 | pub async fn disable_user(&self, user_id: &str) -> Result<bool> { | 364 | pub async fn disable_user(&self, user_id: &str) -> Result<bool> { |
| 364 | let now = now_stamp(); | 365 | let now = now_stamp(); |
| @@ -379,6 +380,8 @@ impl Store { | |||
| 379 | return Ok(false); | 380 | return Ok(false); |
| 380 | } | 381 | } |
| 381 | record_change(&tx, user_id, ChangeKind::Member).await?; | 382 | record_change(&tx, user_id, ChangeKind::Member).await?; |
| 383 | + // A reset or email-change link must not come back to life when the account is enabled again. | ||
| 384 | + invalidate_links(&tx, user_id, &now).await?; | ||
| 382 | // Queued before the sessions go, because the client links are read from them. | 385 | // Queued before the sessions go, because the client links are read from them. |
| 383 | backchannel::queue_user(&tx, user_id, EndReason::Disabled, &now).await?; | 386 | backchannel::queue_user(&tx, user_id, EndReason::Disabled, &now).await?; |
| 384 | tx.execute( | 387 | tx.execute( |
| @@ -419,7 +422,8 @@ impl Store { | |||
| 419 | /// it as used, replaces the recovery codes with `recovery_hashes` and drops the pending secret. | 422 | /// it as used, replaces the recovery codes with `recovery_hashes` and drops the pending secret. |
| 420 | /// Sessions created before it are not second-factor sessions, so in the same transaction every live | 423 | /// Sessions created before it are not second-factor sessions, so in the same transaction every live |
| 421 | /// session except `keep_session_id` ends, with its back-channel logouts. `None` ends all of them. | 424 | /// session except `keep_session_id` ends, with its back-channel logouts. `None` ends all of them. |
| 422 | - /// One transaction. | 425 | + /// One transaction. Returns false, with nothing changed, when two-factor sign-in is already on (a |
| 426 | + /// parallel confirmation won) or the account is missing. | ||
| 423 | pub async fn enable_totp( | 427 | pub async fn enable_totp( |
| 424 | &self, | 428 | &self, |
| 425 | user_id: &str, | 429 | user_id: &str, |
| @@ -427,17 +431,20 @@ impl Store { | |||
| 427 | step: u64, | 431 | step: u64, |
| 428 | recovery_hashes: &[String], | 432 | recovery_hashes: &[String], |
| 429 | keep_session_id: Option<&str>, | 433 | keep_session_id: Option<&str>, |
| 430 | - ) -> Result<()> { | 434 | + ) -> Result<bool> { |
| 431 | let step = | 435 | let step = |
| 432 | i64::try_from(step).map_err(|_| Error::Invalid("totp step out of range".into()))?; | 436 | i64::try_from(step).map_err(|_| Error::Invalid("totp step out of range".into()))?; |
| 433 | let now = now_stamp(); | 437 | let now = now_stamp(); |
| 434 | let conn = self.inner.conn.lock().await; | 438 | let conn = self.inner.conn.lock().await; |
| 435 | let tx = conn.unchecked_transaction().await.map_err(db_err)?; | 439 | let tx = conn.unchecked_transaction().await.map_err(db_err)?; |
| 436 | - let outcome: Result<()> = async { | 440 | + let outcome: Result<bool> = async { |
| 441 | + // Conditional on the state read here: a second confirmation of the same enrolment finds | ||
| 442 | + // two-factor sign-in already on, and changes nothing (its recovery codes are not replaced). | ||
| 437 | let changed = tx | 443 | let changed = tx |
| 438 | .execute( | 444 | .execute( |
| 439 | "UPDATE users SET totp_secret_sealed = ?2, totp_enabled_at = ?3, \ | 445 | "UPDATE users SET totp_secret_sealed = ?2, totp_enabled_at = ?3, \ |
| 440 | - totp_last_step = ?4, updated_at = ?3 WHERE id = ?1", | 446 | + totp_last_step = ?4, updated_at = ?3 \ |
| 447 | + WHERE id = ?1 AND totp_enabled_at IS NULL", | ||
| 441 | ( | 448 | ( |
| 442 | user_id.to_string(), | 449 | user_id.to_string(), |
| 443 | sealed_secret.to_string(), | 450 | sealed_secret.to_string(), |
| @@ -447,8 +454,8 @@ impl Store { | |||
| 447 | ) | 454 | ) |
| 448 | .await | 455 | .await |
| 449 | .map_err(db_err)?; | 456 | .map_err(db_err)?; |
| 450 | - if changed == 0 { | 457 | + if changed != 1 { |
| 451 | - return Err(Error::NotFound); | 458 | + return Ok(false); |
| 452 | } | 459 | } |
| 453 | replace_codes(&tx, user_id, recovery_hashes).await?; | 460 | replace_codes(&tx, user_id, recovery_hashes).await?; |
| 454 | tx.execute( | 461 | tx.execute( |
| @@ -459,7 +466,7 @@ impl Store { | |||
| 459 | .map_err(db_err)?; | 466 | .map_err(db_err)?; |
| 460 | let ids = live_session_ids(&tx, user_id, keep_session_id, &now).await?; | 467 | let ids = live_session_ids(&tx, user_id, keep_session_id, &now).await?; |
| 461 | end_rows(&tx, user_id, &ids, EndReason::Revoked, &now).await?; | 468 | end_rows(&tx, user_id, &ids, EndReason::Revoked, &now).await?; |
| 462 | - Ok(()) | 469 | + Ok(true) |
| 463 | } | 470 | } |
| 464 | .await; | 471 | .await; |
| 465 | finish(tx, outcome).await | 472 | finish(tx, outcome).await |
| @@ -631,6 +638,30 @@ mod tests { | |||
| 631 | assert_eq!(store.user_count().await.unwrap(), 1); | 638 | assert_eq!(store.user_count().await.unwrap(), 1); |
| 632 | } | 639 | } |
| 633 | 640 | ||
| 641 | + #[tokio::test] | ||
| 642 | + async fn a_second_enrolment_confirmation_changes_nothing() { | ||
| 643 | + let (_dir, store) = store().await; | ||
| 644 | + let user = store | ||
| 645 | + .create_user("ada@example.com", "Ada", "hash", false) | ||
| 646 | + .await | ||
| 647 | + .unwrap(); | ||
| 648 | + assert!( | ||
| 649 | + store | ||
| 650 | + .enable_totp(&user.id, "v1:first", 100, &["h1".to_string()], None) | ||
| 651 | + .await | ||
| 652 | + .unwrap() | ||
| 653 | + ); | ||
| 654 | + // A parallel confirmation of the same enrolment: refused, and its recovery codes are not stored. | ||
| 655 | + assert!( | ||
| 656 | + !store | ||
| 657 | + .enable_totp(&user.id, "v1:second", 101, &["h2".to_string()], None) | ||
| 658 | + .await | ||
| 659 | + .unwrap() | ||
| 660 | + ); | ||
| 661 | + let after = store.user_by_id(&user.id).await.unwrap().unwrap(); | ||
| 662 | + assert_eq!(after.totp_last_step, Some(100)); | ||
| 663 | + } | ||
| 664 | + | ||
| 634 | #[tokio::test] | 665 | #[tokio::test] |
| 635 | async fn a_totp_step_is_accepted_once_and_only_while_enabled() { | 666 | async fn a_totp_step_is_accepted_once_and_only_while_enabled() { |
| 636 | let (_dir, store) = store().await; | 667 | let (_dir, store) = store().await; |
crates/im-web/src/auth.rsmodified+17 -6
| @@ -12,7 +12,7 @@ use im_core::model::{Session, User, amr}; | |||
| 12 | use im_core::secret; | 12 | use im_core::secret; |
| 13 | use im_core::store::Store; | 13 | use im_core::store::Store; |
| 14 | use im_core::store::backchannel::EndReason; | 14 | use im_core::store::backchannel::EndReason; |
| 15 | -use im_core::store::sessions::{NewSession, SESSION_IDLE}; | 15 | +use im_core::store::sessions::{NewSession, SESSION_IDLE, SignInState}; |
| 16 | use im_core::token::{constant_time_eq, generate_token, hash_token}; | 16 | use im_core::token::{constant_time_eq, generate_token, hash_token}; |
| 17 | use im_core::totp; | 17 | use im_core::totp; |
| 18 | use topcoat::Result; | 18 | use topcoat::Result; |
| @@ -150,13 +150,20 @@ pub fn check_csrf(session: &Session, submitted: &str) -> bool { | |||
| 150 | && constant_time_eq(session.csrf_token.as_bytes(), submitted.as_bytes()) | 150 | && constant_time_eq(session.csrf_token.as_bytes(), submitted.as_bytes()) |
| 151 | } | 151 | } |
| 152 | 152 | ||
| 153 | -/// Creates a session for `user`, authenticated by `amr`, and sets the cookie. | 153 | +/// Creates a session for `user`, authenticated by `amr`, and sets the cookie. Returns `false`, with no |
| 154 | +/// session and no cookie, when `decided_on` no longer holds for the user (see | ||
| 155 | +/// [`im_core::store::Store::create_session`]). The caller then treats the sign-in as failed. | ||
| 154 | /// | 156 | /// |
| 155 | /// A session the browser already presented is ended first, whoever it belongs to, so a sign-in always | 157 | /// A session the browser already presented is ended first, whoever it belongs to, so a sign-in always |
| 156 | /// rotates the session id and no row is left live with no cookie holding it. The session lives | 158 | /// rotates the session id and no row is left live with no cookie holding it. The session lives |
| 157 | /// [`SESSION_IDLE`] after its last use, up to the policy's `session_max_days` from now; the store keeps | 159 | /// [`SESSION_IDLE`] after its last use, up to the policy's `session_max_days` from now; the store keeps |
| 158 | /// both limits. The per-person cap of the policy is applied inside the store, in the same write. | 160 | /// both limits. The per-person cap of the policy is applied inside the store, in the same write. |
| 159 | -pub async fn start_session(cx: &Cx, user: &User, amr: &str) -> Result<Session> { | 161 | +pub async fn start_session( |
| 162 | + cx: &Cx, | ||
| 163 | + user: &User, | ||
| 164 | + amr: &str, | ||
| 165 | + decided_on: SignInState<'_>, | ||
| 166 | +) -> Result<bool> { | ||
| 160 | let state = app_context::<AppState>(cx); | 167 | let state = app_context::<AppState>(cx); |
| 161 | let max_age = Duration::from_secs(u64::from(state.policy().session_max_days) * DAY); | 168 | let max_age = Duration::from_secs(u64::from(state.policy().session_max_days) * DAY); |
| 162 | if let Some(old) = presented_session(cx).await? { | 169 | if let Some(old) = presented_session(cx).await? { |
| @@ -174,11 +181,12 @@ pub async fn start_session(cx: &Cx, user: &User, amr: &str) -> Result<Session> { | |||
| 174 | let csrf = generate_token(); | 181 | let csrf = generate_token(); |
| 175 | let ip = client_addr(cx).to_string(); | 182 | let ip = client_addr(cx).to_string(); |
| 176 | let user_agent = user_agent(cx); | 183 | let user_agent = user_agent(cx); |
| 177 | - let created = state | 184 | + let Some(_) = state |
| 178 | .store | 185 | .store |
| 179 | .create_session( | 186 | .create_session( |
| 180 | &NewSession { | 187 | &NewSession { |
| 181 | user_id: &user.id, | 188 | user_id: &user.id, |
| 189 | + decided_on, | ||
| 182 | token_hash: &hash_token(&token), | 190 | token_hash: &hash_token(&token), |
| 183 | csrf_token: &csrf, | 191 | csrf_token: &csrf, |
| 184 | amr, | 192 | amr, |
| @@ -189,7 +197,10 @@ pub async fn start_session(cx: &Cx, user: &User, amr: &str) -> Result<Session> { | |||
| 189 | }, | 197 | }, |
| 190 | state.policy().max_sessions, | 198 | state.policy().max_sessions, |
| 191 | ) | 199 | ) |
| 192 | - .await?; | 200 | + .await? |
| 201 | + else { | ||
| 202 | + return Ok(false); | ||
| 203 | + }; | ||
| 193 | // Sessions ended by the cap were queued for back-channel logout in the store's transaction. | 204 | // Sessions ended by the cap were queued for back-channel logout in the store's transaction. |
| 194 | state.live.bump(&Topic::Account(user.id.clone())); | 205 | state.live.bump(&Topic::Account(user.id.clone())); |
| 195 | // The browser keeps the cookie for the hard cap; the server decides the real expiry. | 206 | // The browser keeps the cookie for the hard cap; the server decides the real expiry. |
| @@ -203,7 +214,7 @@ pub async fn start_session(cx: &Cx, user: &User, amr: &str) -> Result<Session> { | |||
| 203 | .max_age(cookie_age) | 214 | .max_age(cookie_age) |
| 204 | .build(), | 215 | .build(), |
| 205 | ); | 216 | ); |
| 206 | - Ok(created.session) | 217 | + Ok(true) |
| 207 | } | 218 | } |
| 208 | 219 | ||
| 209 | /// Ends the session of `viewer` (with its back-channel logouts) and clears its cookie. Other sessions of | 220 | /// Ends the session of `viewer` (with its back-channel logouts) and clears its cookie. Other sessions of |
crates/im-web/src/backchannel.rsmodified+8 -2
| @@ -130,7 +130,11 @@ pub async fn process_due( | |||
| 130 | "back-channel logout abandoned" | 130 | "back-channel logout abandoned" |
| 131 | ), | 131 | ), |
| 132 | } | 132 | } |
| 133 | - store.record_attempt(&job.id, attempt, &now_stamp()).await?; | 133 | + // A failed write must not hold up the rows after it: they were already sent, and an unrecorded row |
| 134 | + // is sent again on the next pass. The failure is logged and the loop goes on. | ||
| 135 | + if let Err(error) = store.record_attempt(&job.id, attempt, &now_stamp()).await { | ||
| 136 | + tracing::error!(row = %job.id, error = %error, "back-channel attempt could not be recorded"); | ||
| 137 | + } | ||
| 134 | } | 138 | } |
| 135 | Ok(due.len()) | 139 | Ok(due.len()) |
| 136 | } | 140 | } |
| @@ -235,7 +239,7 @@ mod tests { | |||
| 235 | use im_core::model::amr; | 239 | use im_core::model::amr; |
| 236 | use im_core::store::backchannel::EndReason; | 240 | use im_core::store::backchannel::EndReason; |
| 237 | use im_core::store::clients::NewClient; | 241 | use im_core::store::clients::NewClient; |
| 238 | - use im_core::store::sessions::{NewSession, SESSION_IDLE}; | 242 | + use im_core::store::sessions::{NewSession, SESSION_IDLE, SignInState}; |
| 239 | use im_core::time::stamp_after; | 243 | use im_core::time::stamp_after; |
| 240 | use tokio::io::{AsyncReadExt, AsyncWriteExt}; | 244 | use tokio::io::{AsyncReadExt, AsyncWriteExt}; |
| 241 | use tokio::net::{TcpListener, TcpStream}; | 245 | use tokio::net::{TcpListener, TcpStream}; |
| @@ -316,6 +320,7 @@ mod tests { | |||
| 316 | .create_session( | 320 | .create_session( |
| 317 | &NewSession { | 321 | &NewSession { |
| 318 | user_id: &user.id, | 322 | user_id: &user.id, |
| 323 | + decided_on: SignInState::of(&user), | ||
| 319 | token_hash: "token", | 324 | token_hash: "token", |
| 320 | csrf_token: "csrf", | 325 | csrf_token: "csrf", |
| 321 | amr: amr::PASSWORD, | 326 | amr: amr::PASSWORD, |
| @@ -328,6 +333,7 @@ mod tests { | |||
| 328 | ) | 333 | ) |
| 329 | .await | 334 | .await |
| 330 | .expect("session") | 335 | .expect("session") |
| 336 | + .expect("not refused") | ||
| 331 | .session; | 337 | .session; |
| 332 | state | 338 | state |
| 333 | .store | 339 | .store |
crates/im-web/src/boot.rsmodified+2 -0
| @@ -173,6 +173,7 @@ pub(crate) async fn open_state(config: Config) -> im_core::Result<AppState> { | |||
| 173 | // Replaced by the stop flag of `serve` before any listener starts. The CLI never serves. | 173 | // Replaced by the stop flag of `serve` before any listener starts. The CLI never serves. |
| 174 | stop: watch::channel(false).1, | 174 | stop: watch::channel(false).1, |
| 175 | settings_lock: Arc::new(tokio::sync::Mutex::new(())), | 175 | settings_lock: Arc::new(tokio::sync::Mutex::new(())), |
| 176 | + photo_lock: Arc::new(tokio::sync::Mutex::new(())), | ||
| 176 | }) | 177 | }) |
| 177 | } | 178 | } |
| 178 | 179 | ||
| @@ -297,6 +298,7 @@ mod tests { | |||
| 297 | anonymous_streams: Arc::new(Semaphore::new(MAX_ANONYMOUS_STREAMS)), | 298 | anonymous_streams: Arc::new(Semaphore::new(MAX_ANONYMOUS_STREAMS)), |
| 298 | stop: watch::channel(false).1, | 299 | stop: watch::channel(false).1, |
| 299 | settings_lock: Arc::new(tokio::sync::Mutex::new(())), | 300 | settings_lock: Arc::new(tokio::sync::Mutex::new(())), |
| 301 | + photo_lock: Arc::new(tokio::sync::Mutex::new(())), | ||
| 300 | }; | 302 | }; |
| 301 | (dir, state) | 303 | (dir, state) |
| 302 | } | 304 | } |
crates/im-web/src/oidc/signing.rsmodified+11 -14
| @@ -36,8 +36,10 @@ pub async fn maintain(store: &Store, instance_key: &[u8; 32]) -> im_core::Result | |||
| 36 | activates_at: activates_at.clone(), | 36 | activates_at: activates_at.clone(), |
| 37 | retires_at: None, | 37 | retires_at: None, |
| 38 | }; | 38 | }; |
| 39 | - store.add_signing_key(&record).await?; | 39 | + // A parallel run added the successor first: its key is the pending one, so this one is not needed. |
| 40 | - tracing::info!(kid = %record.kid, activates_at = %activates_at, "signing key created"); | 40 | + if store.add_signing_key(&record).await? { |
| 41 | + tracing::info!(kid = %record.kid, activates_at = %activates_at, "signing key created"); | ||
| 42 | + } | ||
| 41 | } | 43 | } |
| 42 | // A key retired by a successor keeps its seed until its retirement time, because it signs until then. | 44 | // A key retired by a successor keeps its seed until its retirement time, because it signs until then. |
| 43 | let scrubbed = store.scrub_retired_signing_seeds(&now).await?; | 45 | let scrubbed = store.scrub_retired_signing_seeds(&now).await?; |
| @@ -78,17 +80,6 @@ pub fn spawn( | |||
| 78 | pub async fn rotate_now(store: &Store, instance_key: &[u8; 32]) -> im_core::Result<String> { | 80 | pub async fn rotate_now(store: &Store, instance_key: &[u8; 32]) -> im_core::Result<String> { |
| 79 | let fresh = keys::generate(); | 81 | let fresh = keys::generate(); |
| 80 | let now = now_stamp(); | 82 | let now = now_stamp(); |
| 81 | - let pending = store | ||
| 82 | - .signing_keys() | ||
| 83 | - .await? | ||
| 84 | - .iter() | ||
| 85 | - .any(|key| key.retires_at.is_none() && key.activates_at > now); | ||
| 86 | - if pending { | ||
| 87 | - return Err(im_core::Error::Conflict( | ||
| 88 | - "another signing key is still waiting to activate; rotate after it starts signing" | ||
| 89 | - .into(), | ||
| 90 | - )); | ||
| 91 | - } | ||
| 92 | let activates_at = stamp_plus(&now, keys::PUBLISH_LEAD).ok_or_else(|| { | 83 | let activates_at = stamp_plus(&now, keys::PUBLISH_LEAD).ok_or_else(|| { |
| 93 | im_core::Error::Crypto("the new key's activation time is out of range".into()) | 84 | im_core::Error::Crypto("the new key's activation time is out of range".into()) |
| 94 | })?; | 85 | })?; |
| @@ -100,7 +91,13 @@ pub async fn rotate_now(store: &Store, instance_key: &[u8; 32]) -> im_core::Resu | |||
| 100 | activates_at, | 91 | activates_at, |
| 101 | retires_at: None, | 92 | retires_at: None, |
| 102 | }; | 93 | }; |
| 103 | - store.add_signing_key(&record).await?; | 94 | + // The store refuses while another key is pending, inside the same transaction as the insert. |
| 95 | + if !store.add_signing_key(&record).await? { | ||
| 96 | + return Err(im_core::Error::Conflict( | ||
| 97 | + "another signing key is still waiting to activate; rotate after it starts signing" | ||
| 98 | + .into(), | ||
| 99 | + )); | ||
| 100 | + } | ||
| 104 | Ok(fresh.kid) | 101 | Ok(fresh.kid) |
| 105 | } | 102 | } |
| 106 | 103 | ||
crates/im-web/src/oidc/tests.rsmodified+4 -2
| @@ -10,7 +10,7 @@ use im_core::model::Client; | |||
| 10 | use im_core::oauth::pkce_s256; | 10 | use im_core::oauth::pkce_s256; |
| 11 | use im_core::password::hash_password; | 11 | use im_core::password::hash_password; |
| 12 | use im_core::store::clients::NewClient; | 12 | use im_core::store::clients::NewClient; |
| 13 | -use im_core::store::sessions::{NewSession, SESSION_IDLE}; | 13 | +use im_core::store::sessions::{NewSession, SESSION_IDLE, SignInState}; |
| 14 | use im_core::token::{generate_token, hash_token}; | 14 | use im_core::token::{generate_token, hash_token}; |
| 15 | use serde_json::Value; | 15 | use serde_json::Value; |
| 16 | use topcoat::router::response::Response; | 16 | use topcoat::router::response::Response; |
| @@ -72,6 +72,7 @@ async fn fixture() -> Fixture { | |||
| 72 | .create_session( | 72 | .create_session( |
| 73 | &NewSession { | 73 | &NewSession { |
| 74 | user_id: &user.id, | 74 | user_id: &user.id, |
| 75 | + decided_on: SignInState::of(&user), | ||
| 75 | token_hash: &hash_token(&cookie), | 76 | token_hash: &hash_token(&cookie), |
| 76 | csrf_token: &generate_token(), | 77 | csrf_token: &generate_token(), |
| 77 | amr: "pwd", | 78 | amr: "pwd", |
| @@ -83,7 +84,8 @@ async fn fixture() -> Fixture { | |||
| 83 | 10, | 84 | 10, |
| 84 | ) | 85 | ) |
| 85 | .await | 86 | .await |
| 86 | - .expect("session"); | 87 | + .expect("session") |
| 88 | + .expect("not refused"); | ||
| 87 | Fixture { | 89 | Fixture { |
| 88 | _dir: dir, | 90 | _dir: dir, |
| 89 | state, | 91 | state, |
crates/im-web/src/pages/admin/tests.rsmodified+10 -2
| @@ -6,7 +6,7 @@ use std::time::Duration; | |||
| 6 | 6 | ||
| 7 | use http::header::{CONTENT_TYPE, COOKIE, LOCATION}; | 7 | use http::header::{CONTENT_TYPE, COOKIE, LOCATION}; |
| 8 | use im_core::password::hash_password; | 8 | use im_core::password::hash_password; |
| 9 | -use im_core::store::sessions::{NewSession, SESSION_IDLE}; | 9 | +use im_core::store::sessions::{NewSession, SESSION_IDLE, SignInState}; |
| 10 | use im_core::token::{generate_token, hash_token}; | 10 | use im_core::token::{generate_token, hash_token}; |
| 11 | use topcoat::router::{Body, to_bytes}; | 11 | use topcoat::router::{Body, to_bytes}; |
| 12 | 12 | ||
| @@ -61,11 +61,18 @@ async fn post(state: AppState, path: &str, cookie: &str, form: &str) -> Reply { | |||
| 61 | async fn session_for(state: &AppState, user_id: &str) -> (String, String) { | 61 | async fn session_for(state: &AppState, user_id: &str) -> (String, String) { |
| 62 | let token = generate_token(); | 62 | let token = generate_token(); |
| 63 | let csrf = generate_token(); | 63 | let csrf = generate_token(); |
| 64 | + let user = state | ||
| 65 | + .store | ||
| 66 | + .user_by_id(user_id) | ||
| 67 | + .await | ||
| 68 | + .expect("user") | ||
| 69 | + .expect("a user"); | ||
| 64 | state | 70 | state |
| 65 | .store | 71 | .store |
| 66 | .create_session( | 72 | .create_session( |
| 67 | &NewSession { | 73 | &NewSession { |
| 68 | user_id, | 74 | user_id, |
| 75 | + decided_on: SignInState::of(&user), | ||
| 69 | token_hash: &hash_token(&token), | 76 | token_hash: &hash_token(&token), |
| 70 | csrf_token: &csrf, | 77 | csrf_token: &csrf, |
| 71 | amr: "pwd", | 78 | amr: "pwd", |
| @@ -77,7 +84,8 @@ async fn session_for(state: &AppState, user_id: &str) -> (String, String) { | |||
| 77 | 10, | 84 | 10, |
| 78 | ) | 85 | ) |
| 79 | .await | 86 | .await |
| 80 | - .expect("session"); | 87 | + .expect("session") |
| 88 | + .expect("not refused"); | ||
| 81 | (token, csrf) | 89 | (token, csrf) |
| 82 | } | 90 | } |
| 83 | 91 | ||
crates/im-web/src/pages/invite.rsmodified+5 -1
| @@ -10,6 +10,7 @@ use im_core::model::{AuditAction, amr}; | |||
| 10 | use im_core::names::parse_display_name; | 10 | use im_core::names::parse_display_name; |
| 11 | use im_core::password::{check_policy, hash_password_async}; | 11 | use im_core::password::{check_policy, hash_password_async}; |
| 12 | use im_core::store::invites::AcceptOutcome; | 12 | use im_core::store::invites::AcceptOutcome; |
| 13 | +use im_core::store::sessions::SignInState; | ||
| 13 | use im_core::token::hash_token; | 14 | use im_core::token::hash_token; |
| 14 | use serde::Deserialize; | 15 | use serde::Deserialize; |
| 15 | use serde_json::json; | 16 | use serde_json::json; |
| @@ -104,7 +105,10 @@ async fn invite_submit(cx: &Cx, Form(form): Form<InviteForm>) -> Result<impl Vie | |||
| 104 | AcceptOutcome::Accepted(user) => *user, | 105 | AcceptOutcome::Accepted(user) => *user, |
| 105 | AcceptOutcome::Refused => return Err(not_found().into()), | 106 | AcceptOutcome::Refused => return Err(not_found().into()), |
| 106 | }; | 107 | }; |
| 107 | - start_session(cx, &user, amr::PASSWORD).await?; | 108 | + if !start_session(cx, &user, amr::PASSWORD, SignInState::of(&user)).await? { |
| 109 | + clear_pre_csrf(cx); | ||
| 110 | + return Err(see_other("/login").into()); | ||
| 111 | + } | ||
| 108 | clear_pre_csrf(cx); | 112 | clear_pre_csrf(cx); |
| 109 | record( | 113 | record( |
| 110 | cx, | 114 | cx, |
crates/im-web/src/pages/login.rsmodified+63 -26
| @@ -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::store::sessions::SignInState; | ||
| 14 | use im_core::time::stamp_after; | 15 | use im_core::time::stamp_after; |
| 15 | use serde::Deserialize; | 16 | use serde::Deserialize; |
| 16 | use serde_json::{Value, json}; | 17 | use serde_json::{Value, json}; |
| @@ -134,28 +135,9 @@ async fn login_submit(cx: &Cx, Form(form): Form<LoginForm>) -> Result<impl View> | |||
| 134 | let target_id = found.as_ref().map(|user| user.id.clone()); | 135 | let target_id = found.as_ref().map(|user| user.id.clone()); |
| 135 | // The attempt stays counted on every failure below. | 136 | // The attempt stays counted on every failure below. |
| 136 | let Some(user) = found.filter(|user| password_ok && !user.is_disabled()) else { | 137 | let Some(user) = found.filter(|user| password_ok && !user.is_disabled()) else { |
| 137 | - // One audit row per account, or per client address when the account is unknown, each minute. A | 138 | + audit_failed_sign_in(cx, state, target_id).await; |
| 138 | - // flood of failures therefore cannot grow the audit log. The throttle above still counts every failure. | ||
| 139 | - let audit_key = match &target_id { | ||
| 140 | - Some(id) => login_audit_user_key(id), | ||
| 141 | - None => ip_key("login-audit-ip", client_ip(cx)), | ||
| 142 | - }; | ||
| 143 | - if state | ||
| 144 | - .per_minute | ||
| 145 | - .reserve(&audit_key, LOGIN_AUDIT_LIMIT, Instant::now()) | ||
| 146 | - .is_ok() | ||
| 147 | - { | ||
| 148 | - let target = target_id.as_deref().map(|id| ("user", id)); | ||
| 149 | - record( | ||
| 150 | - cx, | ||
| 151 | - Actor::Anonymous, | ||
| 152 | - AuditAction::LoginFailed, | ||
| 153 | - target, | ||
| 154 | - json!({ "reason": "credentials" }), | ||
| 155 | - ) | ||
| 156 | - .await; | ||
| 157 | - } | ||
| 158 | let lang = page_lang(cx, None); | 139 | let lang = page_lang(cx, None); |
| 140 | + let csrf = pre_csrf_token(cx); | ||
| 159 | return Ok(login_view( | 141 | return Ok(login_view( |
| 160 | cx, | 142 | cx, |
| 161 | lang, | 143 | lang, |
| @@ -174,7 +156,49 @@ async fn login_submit(cx: &Cx, Form(form): Form<LoginForm>) -> Result<impl View> | |||
| 174 | set_pending_login(cx, &state.key, &user.id, &next)?; | 156 | set_pending_login(cx, &state.key, &user.id, &next)?; |
| 175 | return Err(see_other("/login/2fa").into()); | 157 | return Err(see_other("/login/2fa").into()); |
| 176 | } | 158 | } |
| 177 | - Err(finish_sign_in(cx, &user, amr::PASSWORD, &next).await?) | 159 | + match finish_sign_in(cx, &user, amr::PASSWORD, &next).await? { |
| 160 | + Some(redirect) => Err(redirect), | ||
| 161 | + // The account changed after the password was checked: the sign-in fails like a wrong password. | ||
| 162 | + None => { | ||
| 163 | + audit_failed_sign_in(cx, state, target_id).await; | ||
| 164 | + let lang = page_lang(cx, None); | ||
| 165 | + let csrf = pre_csrf_token(cx); | ||
| 166 | + Ok(login_view( | ||
| 167 | + cx, | ||
| 168 | + lang, | ||
| 169 | + csrf, | ||
| 170 | + form.email, | ||
| 171 | + next, | ||
| 172 | + Some(Failure::Invalid), | ||
| 173 | + false, | ||
| 174 | + )) | ||
| 175 | + } | ||
| 176 | + } | ||
| 177 | +} | ||
| 178 | + | ||
| 179 | +/// Audits a sign-in that failed after the lookup. The row is per account, or per client address when | ||
| 180 | +/// the account is unknown, and at most one each minute, so a flood of failures cannot grow the audit | ||
| 181 | +/// log. The throttle still counts every failure. | ||
| 182 | +async fn audit_failed_sign_in(cx: &Cx, state: &AppState, target_id: Option<String>) { | ||
| 183 | + let audit_key = match &target_id { | ||
| 184 | + Some(id) => login_audit_user_key(id), | ||
| 185 | + None => ip_key("login-audit-ip", client_ip(cx)), | ||
| 186 | + }; | ||
| 187 | + if state | ||
| 188 | + .per_minute | ||
| 189 | + .reserve(&audit_key, LOGIN_AUDIT_LIMIT, Instant::now()) | ||
| 190 | + .is_ok() | ||
| 191 | + { | ||
| 192 | + let target = target_id.as_deref().map(|id| ("user", id)); | ||
| 193 | + record( | ||
| 194 | + cx, | ||
| 195 | + Actor::Anonymous, | ||
| 196 | + AuditAction::LoginFailed, | ||
| 197 | + target, | ||
| 198 | + json!({ "reason": "credentials" }), | ||
| 199 | + ) | ||
| 200 | + .await; | ||
| 201 | + } | ||
| 178 | } | 202 | } |
| 179 | 203 | ||
| 180 | /// `GET /login/2fa`. Needs a pending password step; without one, back to sign-in. | 204 | /// `GET /login/2fa`. Needs a pending password step; without one, back to sign-in. |
| @@ -236,7 +260,11 @@ async fn two_factor_submit(cx: &Cx, Form(form): Form<TwoFactorForm>) -> Result<i | |||
| 236 | Ok(Some(method)) => { | 260 | Ok(Some(method)) => { |
| 237 | state.throttle.clear(&limit); | 261 | state.throttle.clear(&limit); |
| 238 | clear_pending_login(cx); | 262 | clear_pending_login(cx); |
| 239 | - Err(finish_sign_in(cx, &user, method, &pending.next).await?) | 263 | + match finish_sign_in(cx, &user, method, &pending.next).await? { |
| 264 | + Some(redirect) => Err(redirect), | ||
| 265 | + // The account changed since the password step: the pending login is over. | ||
| 266 | + None => Err(see_other("/login").into()), | ||
| 267 | + } | ||
| 240 | } | 268 | } |
| 241 | Ok(None) => { | 269 | Ok(None) => { |
| 242 | state.store.release_pending_login(&pending.nonce).await?; | 270 | state.store.release_pending_login(&pending.nonce).await?; |
| @@ -264,9 +292,18 @@ async fn two_factor_submit(cx: &Cx, Form(form): Form<TwoFactorForm>) -> Result<i | |||
| 264 | } | 292 | } |
| 265 | 293 | ||
| 266 | /// Starts the session, clears the pre-session token, audits the sign-in and sends the person on. | 294 | /// Starts the session, clears the pre-session token, audits the sign-in and sends the person on. |
| 267 | -async fn finish_sign_in(cx: &Cx, user: &User, method: &str, next: &str) -> Result<topcoat::Error> { | 295 | +/// Starts the session of a sign-in decided on `user`, records it, and returns the redirect. `None` when |
| 296 | +/// the decision no longer holds (see [`start_session`]): nothing was created, and the caller fails the sign-in. | ||
| 297 | +async fn finish_sign_in( | ||
| 298 | + cx: &Cx, | ||
| 299 | + user: &User, | ||
| 300 | + method: &str, | ||
| 301 | + next: &str, | ||
| 302 | +) -> Result<Option<topcoat::Error>> { | ||
| 268 | let state = app_context::<AppState>(cx); | 303 | let state = app_context::<AppState>(cx); |
| 269 | - start_session(cx, user, method).await?; | 304 | + if !start_session(cx, user, method, SignInState::of(user)).await? { |
| 305 | + return Ok(None); | ||
| 306 | + } | ||
| 270 | clear_pre_csrf(cx); | 307 | clear_pre_csrf(cx); |
| 271 | record( | 308 | record( |
| 272 | cx, | 309 | cx, |
| @@ -276,7 +313,7 @@ async fn finish_sign_in(cx: &Cx, user: &User, method: &str, next: &str) -> Resul | |||
| 276 | json!({ "amr": method }), | 313 | json!({ "amr": method }), |
| 277 | ) | 314 | ) |
| 278 | .await; | 315 | .await; |
| 279 | - Ok(see_other(after_sign_in(state, user, next)).into()) | 316 | + Ok(Some(see_other(after_sign_in(state, user, next)).into())) |
| 280 | } | 317 | } |
| 281 | 318 | ||
| 282 | /// The hash checked against when the email is unknown or the account disabled. Computed once, so | 319 | /// The hash checked against when the email is unknown or the account disabled. Computed once, so |
crates/im-web/src/pages/profile.rsmodified+4 -0
| @@ -210,6 +210,8 @@ async fn upload_photo(cx: &Cx, mut multipart: Multipart) -> Result<impl View> { | |||
| 210 | Err(error) => return Err(error.into()), | 210 | Err(error) => return Err(error.into()), |
| 211 | }; | 211 | }; |
| 212 | 212 | ||
| 213 | + // Held until the row names the new file: a parallel removal cannot delete it in between. | ||
| 214 | + let _photo = state.photo_lock.lock().await; | ||
| 213 | // The file first, then the row: the row only ever names a file that is already in place. | 215 | // The file first, then the row: the row only ever names a file that is already in place. |
| 214 | let dir = state.config.data_dir.clone(); | 216 | let dir = state.config.data_dir.clone(); |
| 215 | let user_id = viewer.user.id.clone(); | 217 | let user_id = viewer.user.id.clone(); |
| @@ -243,6 +245,8 @@ fn upload_problem(cx: &Cx, lang: Lang, viewer: Viewer, message: &str) -> impl Vi | |||
| 243 | async fn remove_photo(cx: &Cx, Form(form): Form<CsrfForm>) -> Result<SeeOther> { | 245 | async fn remove_photo(cx: &Cx, Form(form): Form<CsrfForm>) -> Result<SeeOther> { |
| 244 | let viewer = require_csrf(cx, &form.csrf).await?; | 246 | let viewer = require_csrf(cx, &form.csrf).await?; |
| 245 | let state = app_context::<AppState>(cx); | 247 | let state = app_context::<AppState>(cx); |
| 248 | + // Held through the file removal, so a parallel upload cannot have its new file deleted here. | ||
| 249 | + let _photo = state.photo_lock.lock().await; | ||
| 246 | if state.store.clear_photo(&viewer.user.id).await? { | 250 | if state.store.clear_photo(&viewer.user.id).await? { |
| 247 | state.live.bump(&Topic::Account(viewer.user.id.clone())); | 251 | state.live.bump(&Topic::Account(viewer.user.id.clone())); |
| 248 | let dir = state.config.data_dir.clone(); | 252 | let dir = state.config.data_dir.clone(); |
crates/im-web/src/pages/reset.rsmodified+11 -1
| @@ -17,6 +17,7 @@ use im_core::names::{normalize_email, parse_email}; | |||
| 17 | use im_core::password::{check_policy, hash_password_async, verify_password_async}; | 17 | use im_core::password::{check_policy, hash_password_async, verify_password_async}; |
| 18 | use im_core::store::Store; | 18 | use im_core::store::Store; |
| 19 | use im_core::store::audit::NewAudit; | 19 | use im_core::store::audit::NewAudit; |
| 20 | +use im_core::store::sessions::SignInState; | ||
| 20 | use im_core::time::stamp_after; | 21 | use im_core::time::stamp_after; |
| 21 | use im_core::token::{generate_token, hash_token}; | 22 | use im_core::token::{generate_token, hash_token}; |
| 22 | use serde::Deserialize; | 23 | use serde::Deserialize; |
| @@ -264,7 +265,16 @@ async fn reset_submit(cx: &Cx, Form(form): Form<ResetForm>) -> Result<impl View> | |||
| 264 | clear_pre_csrf(cx); | 265 | clear_pre_csrf(cx); |
| 265 | return Err(see_other("/login").into()); | 266 | return Err(see_other("/login").into()); |
| 266 | } | 267 | } |
| 267 | - start_session(cx, &user, amr::PASSWORD).await?; | 268 | + // The state the reset just set, with no second factor (checked above): a disable that committed |
| 269 | + // since then refuses the session. | ||
| 270 | + let decided_on = SignInState { | ||
| 271 | + password_hash: &hash, | ||
| 272 | + totp_enabled: false, | ||
| 273 | + }; | ||
| 274 | + if !start_session(cx, &user, amr::PASSWORD, decided_on).await? { | ||
| 275 | + clear_pre_csrf(cx); | ||
| 276 | + return Err(see_other("/login").into()); | ||
| 277 | + } | ||
| 268 | clear_pre_csrf(cx); | 278 | clear_pre_csrf(cx); |
| 269 | Err(see_other(after_sign_in(state, &user, "/")).into()) | 279 | Err(see_other(after_sign_in(state, &user, "/")).into()) |
| 270 | } | 280 | } |
crates/im-web/src/pages/security.rsmodified+10 -1
| @@ -283,7 +283,7 @@ async fn confirm_enrolment(cx: &Cx, Form(form): Form<CodeForm>) -> Result<impl V | |||
| 283 | .map(|code| totp::recovery_code_hash(&state.key, code)) | 283 | .map(|code| totp::recovery_code_hash(&state.key, code)) |
| 284 | .collect(); | 284 | .collect(); |
| 285 | // The other sessions end with the first factor (see `Store::enable_totp`); this one stays. | 285 | // The other sessions end with the first factor (see `Store::enable_totp`); this one stays. |
| 286 | - state | 286 | + let enabled = state |
| 287 | .store | 287 | .store |
| 288 | .enable_totp( | 288 | .enable_totp( |
| 289 | &viewer.user.id, | 289 | &viewer.user.id, |
| @@ -293,6 +293,15 @@ async fn confirm_enrolment(cx: &Cx, Form(form): Form<CodeForm>) -> Result<impl V | |||
| 293 | Some(&viewer.session.id), | 293 | Some(&viewer.session.id), |
| 294 | ) | 294 | ) |
| 295 | .await?; | 295 | .await?; |
| 296 | + // A parallel confirmation of the same enrolment got there first: its codes are the ones shown. | ||
| 297 | + if !enabled { | ||
| 298 | + return render_security( | ||
| 299 | + cx, | ||
| 300 | + viewer.clone(), | ||
| 301 | + Flash::alert(text(lang, Txt::ErrNoPending)), | ||
| 302 | + ) | ||
| 303 | + .await; | ||
| 304 | + } | ||
| 296 | changed(state, &viewer); | 305 | changed(state, &viewer); |
| 297 | record( | 306 | record( |
| 298 | cx, | 307 | cx, |
crates/im-web/src/pages/setup.rsmodified+5 -1
| @@ -5,6 +5,7 @@ | |||
| 5 | use im_core::model::{AuditAction, amr}; | 5 | use im_core::model::{AuditAction, amr}; |
| 6 | use im_core::names::{normalize_email, parse_display_name, parse_email}; | 6 | use im_core::names::{normalize_email, parse_display_name, parse_email}; |
| 7 | use im_core::password::{check_policy, hash_password_async}; | 7 | use im_core::password::{check_policy, hash_password_async}; |
| 8 | +use im_core::store::sessions::SignInState; | ||
| 8 | use serde::Deserialize; | 9 | use serde::Deserialize; |
| 9 | use serde_json::Value; | 10 | use serde_json::Value; |
| 10 | use topcoat::Result; | 11 | use topcoat::Result; |
| @@ -106,7 +107,10 @@ async fn setup_submit(cx: &Cx, Form(form): Form<SetupForm>) -> Result<impl View> | |||
| 106 | Err(im_core::Error::Conflict(_)) => return Err(not_found().into()), | 107 | Err(im_core::Error::Conflict(_)) => return Err(not_found().into()), |
| 107 | Err(error) => return Err(error.into()), | 108 | Err(error) => return Err(error.into()), |
| 108 | }; | 109 | }; |
| 109 | - start_session(cx, &user, amr::PASSWORD).await?; | 110 | + if !start_session(cx, &user, amr::PASSWORD, SignInState::of(&user)).await? { |
| 111 | + clear_pre_csrf(cx); | ||
| 112 | + return Err(see_other("/login").into()); | ||
| 113 | + } | ||
| 110 | clear_pre_csrf(cx); | 114 | clear_pre_csrf(cx); |
| 111 | record( | 115 | record( |
| 112 | cx, | 116 | cx, |
crates/im-web/src/pages/tests.rsmodified+4 -2
| @@ -5,7 +5,7 @@ use std::time::Duration; | |||
| 5 | 5 | ||
| 6 | use http::header::{CONTENT_TYPE, COOKIE}; | 6 | use http::header::{CONTENT_TYPE, COOKIE}; |
| 7 | use im_core::password::hash_password; | 7 | use im_core::password::hash_password; |
| 8 | -use im_core::store::sessions::{NewSession, SESSION_IDLE}; | 8 | +use im_core::store::sessions::{NewSession, SESSION_IDLE, SignInState}; |
| 9 | use im_core::token::{generate_token, hash_token}; | 9 | use im_core::token::{generate_token, hash_token}; |
| 10 | use topcoat::router::{Body, to_bytes}; | 10 | use topcoat::router::{Body, to_bytes}; |
| 11 | 11 | ||
| @@ -45,6 +45,7 @@ async fn signed_in(state: &AppState) -> String { | |||
| 45 | .create_session( | 45 | .create_session( |
| 46 | &NewSession { | 46 | &NewSession { |
| 47 | user_id: &user.id, | 47 | user_id: &user.id, |
| 48 | + decided_on: SignInState::of(&user), | ||
| 48 | token_hash: &hash_token(&token), | 49 | token_hash: &hash_token(&token), |
| 49 | csrf_token: &generate_token(), | 50 | csrf_token: &generate_token(), |
| 50 | amr: "pwd", | 51 | amr: "pwd", |
| @@ -56,7 +57,8 @@ async fn signed_in(state: &AppState) -> String { | |||
| 56 | 10, | 57 | 10, |
| 57 | ) | 58 | ) |
| 58 | .await | 59 | .await |
| 59 | - .expect("session"); | 60 | + .expect("session") |
| 61 | + .expect("not refused"); | ||
| 60 | token | 62 | token |
| 61 | } | 63 | } |
| 62 | 64 | ||
crates/im-web/src/state.rsmodified+3 -0
| @@ -46,6 +46,9 @@ pub struct AppState { | |||
| 46 | /// Held by every change to the saved policy, from the write to the refresh of `policy_live`. Two saves | 46 | /// Held by every change to the saved policy, from the write to the refresh of `policy_live`. Two saves |
| 47 | /// then run one after the other, and the in-memory policy always matches what the database last committed. | 47 | /// then run one after the other, and the in-memory policy always matches what the database last committed. |
| 48 | pub settings_lock: Arc<tokio::sync::Mutex<()>>, | 48 | pub settings_lock: Arc<tokio::sync::Mutex<()>>, |
| 49 | + /// Held by every profile photo change, from the row write to the file write or removal, so that a | ||
| 50 | + /// removal cannot delete the file a parallel upload has just put in place. | ||
| 51 | + pub photo_lock: Arc<tokio::sync::Mutex<()>>, | ||
| 49 | } | 52 | } |
| 50 | 53 | ||
| 51 | impl AppState { | 54 | impl AppState { |
docs/architecture.mdmodified+7 -2
| @@ -146,7 +146,8 @@ minute per account, or per client address when the account is unknown; the throt | |||
| 146 | 146 | ||
| 147 | **settings**: `key` PK, `value`, `updated_at` (UI overrides and sealed SMTP password). | 147 | **settings**: `key` PK, `value`, `updated_at` (UI overrides and sealed SMTP password). |
| 148 | 148 | ||
| 149 | -Files beside the DB in `data_dir`: `im.key`, `photos/<user_id>` (0600, written by temp file + fsync + rename). | 149 | +Files beside the DB in `data_dir`: `im.key`, `photos/<user_id>` (0600, written by temp file + fsync + rename). Photo upload and removal run under one |
| 150 | +process-wide lock (`photo_lock`), so a removal cannot delete a file a parallel upload has just put in place. | ||
| 150 | 151 | ||
| 151 | --- | 152 | --- |
| 152 | 153 | ||
| @@ -212,7 +213,11 @@ redirects). Other errors redirect to the client with `error=` and `state`. | |||
| 212 | refresh-token family or authorization code; an account asks for at most 3 email changes an hour; each form | 213 | refresh-token family or authorization code; an account asks for at most 3 email changes an hour; each form |
| 213 | route reads at most 16 KiB, and the photo and admin message routes keep their own limits. | 214 | route reads at most 16 KiB, and the photo and admin message routes keep their own limits. |
| 214 | - Password change ends every other session; reset ends all. Enabling or disabling TOTP ends every other session | 215 | - Password change ends every other session; reset ends all. Enabling or disabling TOTP ends every other session |
| 215 | - (the current one stays). Disable and delete end all and queue back-channel logout by `sub`. | 216 | + (the current one stays). Disable and delete end all and queue back-channel logout by `sub`. Disable also uses up |
| 217 | + the account's pending reset and email-change links, and no new one is made for a disabled account. | ||
| 218 | +- A session is created only in the same write that re-checks the sign-in: the account is still enabled, with the | ||
| 219 | + password hash and two-factor state the sign-in was decided on. If a password change, reset, TOTP change or | ||
| 220 | + disable committed in between, nothing is created and the sign-in fails like a wrong password. | ||
| 216 | - Signing in ends the session the browser presented, whoever it belonged to, so no row is left without its cookie. | 221 | - Signing in ends the session the browser presented, whoever it belonged to, so no row is left without its cookie. |
| 217 | - TOTP enroll: secret generated and held sealed in a pending state until a valid code confirms it; enrolling | 222 | - TOTP enroll: secret generated and held sealed in a pending state until a valid code confirms it; enrolling |
| 218 | again while enabled requires the current code (old defect: re-visiting enroll reset it). Disabling TOTP | 223 | again while enabled requires the current code (old defect: re-visiting enroll reset it). Disabling TOTP |
docs/contracts.mdmodified+1 -1
| @@ -60,7 +60,7 @@ Clients fetch discovery once at boot and cache it. They may hard-code the paths | |||
| 60 | the last 7 days, as `{"kty":"OKP","crv":"Ed25519","x":...,"kid":...,"use":"sig","alg":"EdDSA"}`. | 60 | the last 7 days, as `{"kty":"OKP","crv":"Ed25519","x":...,"kid":...,"use":"sig","alg":"EdDSA"}`. |
| 61 | - `im` rotates the signing key every 90 days and on admin demand. A new key is published 24 hours before it | 61 | - `im` rotates the signing key every 90 days and on admin demand. A new key is published 24 hours before it |
| 62 | signs anything. | 62 | signs anything. |
| 63 | -- Clients cache the JWKS for 1 hour, and refetch at most once a minute when a token names an unknown `kid`. | 63 | +- Clients cache the JWKS for 10 minutes, and refetch at most once a minute when a token names an unknown `kid`. |
| 64 | 64 | ||
| 65 | ### 2.3 Sign-in (authorization code + PKCE) | 65 | ### 2.3 Sign-in (authorization code + PKCE) |
| 66 | 66 | ||