🔒 logout auto-submits only for the viewer's own hint; code replay revokes its access token; TOTP enable and sign-in end stale sessions
Browse files at this commitec12b7803886c649d6cff2670a0bd47f2be48936Parent: 7f1e12a12 changed files +160 -49
- crates/im-core/migrations/0007_code_access_token.sql +6 -0
- crates/im-core/src/model.rs +4 -0
- crates/im-core/src/store/backchannel.rs +2 -0
- crates/im-core/src/store/migrate.rs +4 -0
- crates/im-core/src/store/oidc.rs +16 -6
- crates/im-core/src/store/users.rs +13 -2
- crates/im-web/src/auth.rs +14 -11
- crates/im-web/src/oidc/logout.rs +28 -14
- crates/im-web/src/oidc/token.rs +60 -12
- crates/im-web/src/pages/security.rs +8 -1
- docs/architecture.md +3 -2
- docs/contracts.md +2 -1
crates/im-core/migrations/0007_code_access_token.sqladded+6 -0
| @@ -0,0 +1,6 @@ | |||
| 1 | +-- 0007: the access token issued from an authorization code, by its `jti` and its expiry, written in the | ||
| 2 | +-- same transaction that marks the code used. A replayed code revokes that access token too (RFC 6749 | ||
| 3 | +-- section 4.1.2), through the revoked_access_tokens list. Codes exchanged before this migration have none. | ||
| 4 | + | ||
| 5 | +ALTER TABLE auth_codes ADD COLUMN access_jti TEXT; | ||
| 6 | +ALTER TABLE auth_codes ADD COLUMN access_expires_at TEXT; | ||
crates/im-core/src/model.rsmodified+4 -0
| @@ -339,6 +339,10 @@ pub struct AuthCode { | |||
| 339 | pub expires_at: String, | 339 | pub expires_at: String, |
| 340 | /// Set when the code was exchanged. A code is exchanged once. | 340 | /// Set when the code was exchanged. A code is exchanged once. |
| 341 | pub used_at: Option<String>, | 341 | pub used_at: Option<String>, |
| 342 | + /// The `jti` of the access token issued at the exchange. A replay revokes it. | ||
| 343 | + pub access_jti: Option<String>, | ||
| 344 | + /// When that access token expires; its revocation is kept until then. | ||
| 345 | + pub access_expires_at: Option<String>, | ||
| 342 | } | 346 | } |
| 343 | 347 | ||
| 344 | /// A refresh token row. Only the hash of the token is stored. | 348 | /// A refresh token row. Only the hash of the token is stored. |
crates/im-core/src/store/backchannel.rsmodified+2 -0
| @@ -395,6 +395,8 @@ mod tests { | |||
| 395 | store | 395 | store |
| 396 | .redeem_auth_code( | 396 | .redeem_auth_code( |
| 397 | "code", | 397 | "code", |
| 398 | + "access-1", | ||
| 399 | + &refresh_expires, | ||
| 398 | &NewRefreshToken { | 400 | &NewRefreshToken { |
| 399 | id: "refresh-1", | 401 | id: "refresh-1", |
| 400 | token_hash: &hash_token("refresh"), | 402 | token_hash: &hash_token("refresh"), |
crates/im-core/src/store/migrate.rsmodified+4 -0
| @@ -29,6 +29,10 @@ pub const MIGRATIONS: &[(u32, &str)] = &[ | |||
| 29 | 6, | 29 | 6, |
| 30 | include_str!("../../migrations/0006_mail_outbox_recipient.sql"), | 30 | include_str!("../../migrations/0006_mail_outbox_recipient.sql"), |
| 31 | ), | 31 | ), |
| 32 | + ( | ||
| 33 | + 7, | ||
| 34 | + include_str!("../../migrations/0007_code_access_token.sql"), | ||
| 35 | + ), | ||
| 32 | ]; | 36 | ]; |
| 33 | 37 | ||
| 34 | fn migration_err(e: turso::Error) -> Error { | 38 | fn migration_err(e: turso::Error) -> Error { |
crates/im-core/src/store/oidc.rsmodified+16 -6
| @@ -14,7 +14,7 @@ use crate::time::now_stamp; | |||
| 14 | 14 | ||
| 15 | /// The columns of an authorization code row, in the order [`map_code`] reads them. | 15 | /// The columns of an authorization code row, in the order [`map_code`] reads them. |
| 16 | const CODE_COLS: &str = "code_hash, client_id, user_id, session_id, redirect_uri, scope, nonce, \ | 16 | const CODE_COLS: &str = "code_hash, client_id, user_id, session_id, redirect_uri, scope, nonce, \ |
| 17 | - code_challenge, expires_at, used_at"; | 17 | + code_challenge, expires_at, used_at, access_jti, access_expires_at"; |
| 18 | 18 | ||
| 19 | /// The columns of a refresh token row, in the order [`map_refresh`] reads them. | 19 | /// The columns of a refresh token row, in the order [`map_refresh`] reads them. |
| 20 | const REFRESH_COLS: &str = "id, token_hash, family_id, client_id, user_id, session_id, code_hash, \ | 20 | const REFRESH_COLS: &str = "id, token_hash, family_id, client_id, user_id, session_id, code_hash, \ |
| @@ -32,6 +32,8 @@ fn map_code(row: &turso::Row) -> Result<AuthCode> { | |||
| 32 | code_challenge: col_text(row, 7)?, | 32 | code_challenge: col_text(row, 7)?, |
| 33 | expires_at: col_text(row, 8)?, | 33 | expires_at: col_text(row, 8)?, |
| 34 | used_at: col_opt_text(row, 9)?, | 34 | used_at: col_opt_text(row, 9)?, |
| 35 | + access_jti: col_opt_text(row, 10)?, | ||
| 36 | + access_expires_at: col_opt_text(row, 11)?, | ||
| 35 | }) | 37 | }) |
| 36 | } | 38 | } |
| 37 | 39 | ||
| @@ -220,12 +222,15 @@ impl Store { | |||
| 220 | .await | 222 | .await |
| 221 | } | 223 | } |
| 222 | 224 | ||
| 223 | - /// Exchanges a code: marks it used and stores the first refresh token, in one transaction. Returns | 225 | + /// Exchanges a code: marks it used, records the `jti` and expiry of the access token issued with it, and |
| 224 | - /// false, with nothing changed, when the code is already used, expired or unknown. The caller treats | 226 | + /// stores the first refresh token, in one transaction. Returns false, with nothing changed, when the code |
| 225 | - /// a false after its own checks passed as a race, which is a reuse. | 227 | + /// is already used, expired or unknown. The caller treats a false after its own checks passed as a race, |
| 228 | + /// which is a reuse. | ||
| 226 | pub async fn redeem_auth_code( | 229 | pub async fn redeem_auth_code( |
| 227 | &self, | 230 | &self, |
| 228 | code_hash: &str, | 231 | code_hash: &str, |
| 232 | + access_jti: &str, | ||
| 233 | + access_expires_at: &str, | ||
| 229 | refresh: &NewRefreshToken<'_>, | 234 | refresh: &NewRefreshToken<'_>, |
| 230 | ) -> Result<bool> { | 235 | ) -> Result<bool> { |
| 231 | let now = now_stamp(); | 236 | let now = now_stamp(); |
| @@ -234,9 +239,14 @@ impl Store { | |||
| 234 | let outcome: Result<bool> = async { | 239 | let outcome: Result<bool> = async { |
| 235 | let changed = tx | 240 | let changed = tx |
| 236 | .execute( | 241 | .execute( |
| 237 | - "UPDATE auth_codes SET used_at = ?2 \ | 242 | + "UPDATE auth_codes SET used_at = ?2, access_jti = ?3, access_expires_at = ?4 \ |
| 238 | WHERE code_hash = ?1 AND used_at IS NULL AND expires_at > ?2", | 243 | WHERE code_hash = ?1 AND used_at IS NULL AND expires_at > ?2", |
| 239 | - (code_hash.to_string(), now.clone()), | 244 | + ( |
| 245 | + code_hash.to_string(), | ||
| 246 | + now.clone(), | ||
| 247 | + access_jti.to_string(), | ||
| 248 | + access_expires_at.to_string(), | ||
| 249 | + ), | ||
| 240 | ) | 250 | ) |
| 241 | .await | 251 | .await |
| 242 | .map_err(db_err)?; | 252 | .map_err(db_err)?; |
crates/im-core/src/store/users.rsmodified+13 -2
| @@ -417,6 +417,8 @@ impl Store { | |||
| 417 | 417 | ||
| 418 | /// Turns two-factor sign-in on: stores the confirmed secret, records the step that confirmed | 418 | /// Turns two-factor sign-in on: stores the confirmed secret, records the step that confirmed |
| 419 | /// it as used, replaces the recovery codes with `recovery_hashes` and drops the pending secret. | 419 | /// 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 | ||
| 421 | + /// session except `keep_session_id` ends, with its back-channel logouts. `None` ends all of them. | ||
| 420 | /// One transaction. | 422 | /// One transaction. |
| 421 | pub async fn enable_totp( | 423 | pub async fn enable_totp( |
| 422 | &self, | 424 | &self, |
| @@ -424,6 +426,7 @@ impl Store { | |||
| 424 | sealed_secret: &str, | 426 | sealed_secret: &str, |
| 425 | step: u64, | 427 | step: u64, |
| 426 | recovery_hashes: &[String], | 428 | recovery_hashes: &[String], |
| 429 | + keep_session_id: Option<&str>, | ||
| 427 | ) -> Result<()> { | 430 | ) -> Result<()> { |
| 428 | let step = | 431 | let step = |
| 429 | i64::try_from(step).map_err(|_| Error::Invalid("totp step out of range".into()))?; | 432 | i64::try_from(step).map_err(|_| Error::Invalid("totp step out of range".into()))?; |
| @@ -435,7 +438,12 @@ impl Store { | |||
| 435 | .execute( | 438 | .execute( |
| 436 | "UPDATE users SET totp_secret_sealed = ?2, totp_enabled_at = ?3, \ | 439 | "UPDATE users SET totp_secret_sealed = ?2, totp_enabled_at = ?3, \ |
| 437 | totp_last_step = ?4, updated_at = ?3 WHERE id = ?1", | 440 | totp_last_step = ?4, updated_at = ?3 WHERE id = ?1", |
| 438 | - (user_id.to_string(), sealed_secret.to_string(), now, step), | 441 | + ( |
| 442 | + user_id.to_string(), | ||
| 443 | + sealed_secret.to_string(), | ||
| 444 | + now.clone(), | ||
| 445 | + step, | ||
| 446 | + ), | ||
| 439 | ) | 447 | ) |
| 440 | .await | 448 | .await |
| 441 | .map_err(db_err)?; | 449 | .map_err(db_err)?; |
| @@ -449,6 +457,8 @@ impl Store { | |||
| 449 | ) | 457 | ) |
| 450 | .await | 458 | .await |
| 451 | .map_err(db_err)?; | 459 | .map_err(db_err)?; |
| 460 | + let ids = live_session_ids(&tx, user_id, keep_session_id, &now).await?; | ||
| 461 | + end_rows(&tx, user_id, &ids, EndReason::Revoked, &now).await?; | ||
| 452 | Ok(()) | 462 | Ok(()) |
| 453 | } | 463 | } |
| 454 | .await; | 464 | .await; |
| @@ -636,7 +646,7 @@ mod tests { | |||
| 636 | Some("v1:sealed") | 646 | Some("v1:sealed") |
| 637 | ); | 647 | ); |
| 638 | store | 648 | store |
| 639 | - .enable_totp(&user.id, "v1:sealed", 100, &["h1".to_string()]) | 649 | + .enable_totp(&user.id, "v1:sealed", 100, &["h1".to_string()], None) |
| 640 | .await | 650 | .await |
| 641 | .unwrap(); | 651 | .unwrap(); |
| 642 | assert!(store.totp_pending(&user.id).await.unwrap().is_none()); | 652 | assert!(store.totp_pending(&user.id).await.unwrap().is_none()); |
| @@ -662,6 +672,7 @@ mod tests { | |||
| 662 | "v1:sealed", | 672 | "v1:sealed", |
| 663 | 5, | 673 | 5, |
| 664 | &["code-a".to_string(), "code-b".to_string()], | 674 | &["code-a".to_string(), "code-b".to_string()], |
| 675 | + None, | ||
| 665 | ) | 676 | ) |
| 666 | .await | 677 | .await |
| 667 | .unwrap(); | 678 | .unwrap(); |
crates/im-web/src/auth.rsmodified+14 -11
| @@ -152,21 +152,23 @@ pub fn check_csrf(session: &Session, submitted: &str) -> bool { | |||
| 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. |
| 154 | /// | 154 | /// |
| 155 | -/// A session the browser already presented for the same person is ended first, so a sign-in always | 155 | +/// A session the browser already presented is ended first, whoever it belongs to, so a sign-in always |
| 156 | -/// rotates the session id. The session lives [`SESSION_IDLE`] after its last use, up to the policy's | 156 | +/// rotates the session id and no row is left live with no cookie holding it. The session lives |
| 157 | -/// `session_max_days` from now; the store keeps both limits. The per-person cap of the policy is | 157 | +/// [`SESSION_IDLE`] after its last use, up to the policy's `session_max_days` from now; the store keeps |
| 158 | -/// applied inside the store, in the same write. | 158 | +/// 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> { | 159 | pub async fn start_session(cx: &Cx, user: &User, amr: &str) -> Result<Session> { |
| 160 | let state = app_context::<AppState>(cx); | 160 | let state = app_context::<AppState>(cx); |
| 161 | let max_age = Duration::from_secs(u64::from(state.policy().session_max_days) * DAY); | 161 | let max_age = Duration::from_secs(u64::from(state.policy().session_max_days) * DAY); |
| 162 | - if let Some(old) = presented_session(cx) | 162 | + if let Some(old) = presented_session(cx).await? { |
| 163 | - .await? | 163 | + // The owner is the session's own user, so the store's ownership check passes for it. |
| 164 | - .filter(|old| old.user_id == user.id) | 164 | + if state |
| 165 | - { | ||
| 166 | - state | ||
| 167 | .store | 165 | .store |
| 168 | - .end_session(&user.id, &old.id, EndReason::Replaced) | 166 | + .end_session(&old.user_id, &old.id, EndReason::Replaced) |
| 169 | - .await?; | 167 | + .await? |
| 168 | + && old.user_id != user.id | ||
| 169 | + { | ||
| 170 | + state.live.bump(&Topic::Account(old.user_id.clone())); | ||
| 171 | + } | ||
| 170 | } | 172 | } |
| 171 | let token = generate_token(); | 173 | let token = generate_token(); |
| 172 | let csrf = generate_token(); | 174 | let csrf = generate_token(); |
| @@ -536,6 +538,7 @@ mod tests { | |||
| 536 | &sealed, | 538 | &sealed, |
| 537 | 1, | 539 | 1, |
| 538 | &[totp::recovery_code_hash(&state.key, &code)], | 540 | &[totp::recovery_code_hash(&state.key, &code)], |
| 541 | + None, | ||
| 539 | ) | 542 | ) |
| 540 | .await | 543 | .await |
| 541 | .expect("enable"); | 544 | .expect("enable"); |
crates/im-web/src/oidc/logout.rsmodified+28 -14
| @@ -9,12 +9,12 @@ | |||
| 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` never ends a session: a link or an image on another site must not sign the browser out. A | 11 | //! - A `GET` never ends a session: a link or an image on another site must not sign the browser out. A |
| 12 | -//! `GET` with a session answers with a form that carries the session's CSRF token. When a valid | 12 | +//! `GET` with a session answers with a form that carries the session's CSRF token. The form posts itself |
| 13 | -//! `id_token_hint` came with it (a client's sign-out), the form posts itself (`data-auto-submit`, run by | 13 | +//! (`data-auto-submit`, run by `assets/pages.js`) only when the hint is this browser's own: its `sid` is |
| 14 | -//! `assets/pages.js`), so the browser returns to the client without a second click; a bare `GET` waits for | 14 | +//! the viewer's session and its `sub` is the viewer. That is a client's sign-out, so the browser returns |
| 15 | -//! the person's click, so a link on another site cannot sign them out. The visible button is the fallback | 15 | +//! to the client without a second click. Any other hint (anyone can hold a valid ID token of their own) |
| 16 | -//! without JS. Only the `POST` ends the session, and it | 16 | +//! leaves the person to click. The visible button is the fallback without JS. Only the `POST` ends the |
| 17 | -//! checks that token before anything changes. | 17 | +//! session, and it checks that token before anything changes. |
| 18 | //! - Ending the session is `im`'s own: the browser session is deleted (and its clients told by | 18 | //! - Ending the session is `im`'s own: the browser session is deleted (and its clients told by |
| 19 | //! back-channel logout, in the store's transaction). When the hint names another session of the same | 19 | //! back-channel logout, in the store's transaction). When the hint names another session of the same |
| 20 | //! person, that one ends too. | 20 | //! person, that one ends too. |
| @@ -57,8 +57,10 @@ pub struct LogoutForm { | |||
| 57 | state: String, | 57 | state: String, |
| 58 | } | 58 | } |
| 59 | 59 | ||
| 60 | -/// What a valid hint says: the session it names, and the client it was issued to. | 60 | +/// What a valid hint says: the person it was issued to and the session it names. |
| 61 | struct Hint { | 61 | struct Hint { |
| 62 | + /// The `sub` claim: the person the ID token was issued to. | ||
| 63 | + sub: Option<String>, | ||
| 62 | /// The `im` session of the sign-in, when the hint names one. | 64 | /// The `im` session of the sign-in, when the hint names one. |
| 63 | sid: Option<String>, | 65 | sid: Option<String>, |
| 64 | } | 66 | } |
| @@ -81,12 +83,13 @@ fn usable_state(value: &str) -> bool { | |||
| 81 | } | 83 | } |
| 82 | 84 | ||
| 83 | /// Verifies an ID token of ours for logout. `None` when it is not an ID token of this provider, or its | 85 | /// Verifies an ID token of ours for logout. `None` when it is not an ID token of this provider, or its |
| 84 | -/// signature or issuer is wrong. The expiry is not checked. | 86 | +/// signature or issuer is wrong. The expiry is not checked. Returns the client it was issued to and the |
| 87 | +/// hint's claims that matter here. | ||
| 85 | async fn verify_hint( | 88 | async fn verify_hint( |
| 86 | store: &Store, | 89 | store: &Store, |
| 87 | issuer: &str, | 90 | issuer: &str, |
| 88 | token: &str, | 91 | token: &str, |
| 89 | -) -> im_core::Result<Option<(String, Option<String>)>> { | 92 | +) -> im_core::Result<Option<(String, Hint)>> { |
| 90 | let published = signing::published_keys(store).await?; | 93 | let published = signing::published_keys(store).await?; |
| 91 | let keys: Vec<PublishedKey> = published | 94 | let keys: Vec<PublishedKey> = published |
| 92 | .iter() | 95 | .iter() |
| @@ -106,8 +109,11 @@ async fn verify_hint( | |||
| 106 | let Some(client_id) = jwt::single_audience(&claims) else { | 109 | let Some(client_id) = jwt::single_audience(&claims) else { |
| 107 | return Ok(None); | 110 | return Ok(None); |
| 108 | }; | 111 | }; |
| 109 | - let sid = claims.get("sid").and_then(Value::as_str).map(str::to_owned); | 112 | + let hint = Hint { |
| 110 | - Ok(Some((client_id.to_owned(), sid))) | 113 | + sub: claims.get("sub").and_then(Value::as_str).map(str::to_owned), |
| 114 | + sid: claims.get("sid").and_then(Value::as_str).map(str::to_owned), | ||
| 115 | + }; | ||
| 116 | + Ok(Some((client_id.to_owned(), hint))) | ||
| 111 | } | 117 | } |
| 112 | 118 | ||
| 113 | /// Checks the request. Nothing here changes state. | 119 | /// Checks the request. Nothing here changes state. |
| @@ -124,7 +130,7 @@ async fn read(app: &AppState, form: &LogoutForm) -> Result<Asked> { | |||
| 124 | if form.id_token_hint.is_empty() { | 130 | if form.id_token_hint.is_empty() { |
| 125 | return Ok(asked); | 131 | return Ok(asked); |
| 126 | } | 132 | } |
| 127 | - let Some((client_id, sid)) = verify_hint(&app.store, issuer(app), &form.id_token_hint).await? | 133 | + let Some((client_id, hint)) = verify_hint(&app.store, issuer(app), &form.id_token_hint).await? |
| 128 | else { | 134 | else { |
| 129 | return Ok(asked); | 135 | return Ok(asked); |
| 130 | }; | 136 | }; |
| @@ -139,7 +145,7 @@ async fn read(app: &AppState, form: &LogoutForm) -> Result<Asked> { | |||
| 139 | { | 145 | { |
| 140 | asked.redirect = Some(form.post_logout_redirect_uri.clone()); | 146 | asked.redirect = Some(form.post_logout_redirect_uri.clone()); |
| 141 | } | 147 | } |
| 142 | - asked.hint = Some(Hint { sid }); | 148 | + asked.hint = Some(hint); |
| 143 | Ok(asked) | 149 | Ok(asked) |
| 144 | } | 150 | } |
| 145 | 151 | ||
| @@ -187,9 +193,15 @@ async fn logout_get(cx: &Cx, Form(form): Form<LogoutForm>) -> Result<impl View> | |||
| 187 | let lang = page_lang(cx, viewer.as_ref()); | 193 | let lang = page_lang(cx, viewer.as_ref()); |
| 188 | match viewer { | 194 | match viewer { |
| 189 | Some(viewer) => { | 195 | Some(viewer) => { |
| 196 | + // Only the browser's own hint (a client's sign-out) may post the form without a click. | ||
| 197 | + let own = asked.hint.as_ref().is_some_and(|hint| { | ||
| 198 | + hint.sid.as_deref() == Some(viewer.session.id.as_str()) | ||
| 199 | + && hint.sub.as_deref() == Some(viewer.user.id.as_str()) | ||
| 200 | + }); | ||
| 190 | let confirm = Confirm { | 201 | let confirm = Confirm { |
| 191 | csrf: viewer.session.csrf_token.clone(), | 202 | csrf: viewer.session.csrf_token.clone(), |
| 192 | raw_hint: asked.raw_hint.clone(), | 203 | raw_hint: asked.raw_hint.clone(), |
| 204 | + auto_submit: own, | ||
| 193 | redirect: asked.redirect.clone(), | 205 | redirect: asked.redirect.clone(), |
| 194 | state: asked.state.clone(), | 206 | state: asked.state.clone(), |
| 195 | }; | 207 | }; |
| @@ -229,6 +241,8 @@ async fn logout_post(cx: &Cx, Form(form): Form<LogoutForm>) -> Result<impl View> | |||
| 229 | struct Confirm { | 241 | struct Confirm { |
| 230 | csrf: String, | 242 | csrf: String, |
| 231 | raw_hint: Option<String>, | 243 | raw_hint: Option<String>, |
| 244 | + /// True when the hint is this browser's own, so the form posts without a click. | ||
| 245 | + auto_submit: bool, | ||
| 232 | redirect: Option<String>, | 246 | redirect: Option<String>, |
| 233 | state: Option<String>, | 247 | state: Option<String>, |
| 234 | } | 248 | } |
| @@ -247,7 +261,7 @@ fn logout_view(cx: &Cx, lang: Lang, confirm: Option<Confirm>) -> impl View { | |||
| 247 | <h1>(title)</h1> | 261 | <h1>(title)</h1> |
| 248 | if let Some(confirm) = confirm { | 262 | if let Some(confirm) = confirm { |
| 249 | <p class="muted">(text(lang, OidcText::ConfirmBody))</p> | 263 | <p class="muted">(text(lang, OidcText::ConfirmBody))</p> |
| 250 | - <form method="post" action="/logout" class="stack" data-hard="true" data-auto-submit=(if confirm.raw_hint.is_some() { "true" } else { "false" })> | 264 | + <form method="post" action="/logout" class="stack" data-hard="true" data-auto-submit=(if confirm.auto_submit { "true" } else { "false" })> |
| 251 | <input type="hidden" name="csrf" value=(confirm.csrf)> | 265 | <input type="hidden" name="csrf" value=(confirm.csrf)> |
| 252 | if let Some(hint) = confirm.raw_hint { | 266 | if let Some(hint) = confirm.raw_hint { |
| 253 | <input type="hidden" name="id_token_hint" value=(hint)> | 267 | <input type="hidden" name="id_token_hint" value=(hint)> |
crates/im-web/src/oidc/token.rsmodified+60 -12
| @@ -12,12 +12,12 @@ use std::time::Instant; | |||
| 12 | 12 | ||
| 13 | use base64::prelude::{BASE64_STANDARD, Engine as _}; | 13 | use base64::prelude::{BASE64_STANDARD, Engine as _}; |
| 14 | use http::header::{AUTHORIZATION, RETRY_AFTER}; | 14 | use http::header::{AUTHORIZATION, RETRY_AFTER}; |
| 15 | -use im_core::model::{Client, Session, User, amr}; | 15 | +use im_core::model::{AuthCode, Client, Session, User, amr}; |
| 16 | use im_core::oauth::{is_supported_scope, is_user_scope, is_valid_family_key}; | 16 | use im_core::oauth::{is_supported_scope, is_user_scope, is_valid_family_key}; |
| 17 | use im_core::oauth::{is_valid_verifier, pkce_s256}; | 17 | use im_core::oauth::{is_valid_verifier, pkce_s256}; |
| 18 | use im_core::store::new_id; | 18 | use im_core::store::new_id; |
| 19 | use im_core::store::oidc::NewRefreshToken; | 19 | use im_core::store::oidc::NewRefreshToken; |
| 20 | -use im_core::time::{now_stamp, stamp_after, unix_now, unix_seconds}; | 20 | +use im_core::time::{now_stamp, stamp_after, stamp_of_unix, unix_now, unix_seconds}; |
| 21 | use im_core::token::{constant_time_eq, generate_token, hash_token}; | 21 | use im_core::token::{constant_time_eq, generate_token, hash_token}; |
| 22 | use serde_json::{Map, Value, json}; | 22 | use serde_json::{Map, Value, json}; |
| 23 | use topcoat::Result; | 23 | use topcoat::Result; |
| @@ -217,8 +217,10 @@ async fn grant_code(app: &AppState, client: &Client, pairs: &Pairs) -> Result<Re | |||
| 217 | return Ok(response); | 217 | return Ok(response); |
| 218 | } | 218 | } |
| 219 | if row.used_at.is_some() { | 219 | if row.used_at.is_some() { |
| 220 | - // The code was exchanged before. Whoever holds the tokens made from it must lose them. | 220 | + // The code was exchanged before. Whoever holds the tokens made from it must lose them, the access |
| 221 | + // token included. | ||
| 221 | app.store.revoke_code_refresh_tokens(&code_hash).await?; | 222 | app.store.revoke_code_refresh_tokens(&code_hash).await?; |
| 223 | + revoke_code_access(app, &row).await?; | ||
| 222 | return Ok(invalid_grant()); | 224 | return Ok(invalid_grant()); |
| 223 | } | 225 | } |
| 224 | let pkce_ok = is_valid_verifier(verifier) | 226 | let pkce_ok = is_valid_verifier(verifier) |
| @@ -244,6 +246,12 @@ async fn grant_code(app: &AppState, client: &Client, pairs: &Pairs) -> Result<Re | |||
| 244 | let refresh = generate_token(); | 246 | let refresh = generate_token(); |
| 245 | let refresh_id = new_id(); | 247 | let refresh_id = new_id(); |
| 246 | let refresh_expires = stamp_after(REFRESH_TTL); | 248 | let refresh_expires = stamp_after(REFRESH_TTL); |
| 249 | + // The access token's jti and expiry are recorded with the redemption, so a replay can revoke it. | ||
| 250 | + let access_jti = generate_token(); | ||
| 251 | + let access_exp = access_expiry(); | ||
| 252 | + let access_expires_at = stamp_of_unix(access_exp).ok_or_else(|| { | ||
| 253 | + im_core::Error::Database("the access token's expiry is out of range".into()) | ||
| 254 | + })?; | ||
| 247 | let first = NewRefreshToken { | 255 | let first = NewRefreshToken { |
| 248 | id: &refresh_id, | 256 | id: &refresh_id, |
| 249 | token_hash: &hash_token(&refresh), | 257 | token_hash: &hash_token(&refresh), |
| @@ -255,9 +263,17 @@ async fn grant_code(app: &AppState, client: &Client, pairs: &Pairs) -> Result<Re | |||
| 255 | scope: &row.scope, | 263 | scope: &row.scope, |
| 256 | expires_at: &refresh_expires, | 264 | expires_at: &refresh_expires, |
| 257 | }; | 265 | }; |
| 258 | - if !app.store.redeem_auth_code(&code_hash, &first).await? { | 266 | + if !app |
| 259 | - // A parallel exchange of the same code won the race: that is a reuse. | 267 | + .store |
| 268 | + .redeem_auth_code(&code_hash, &access_jti, &access_expires_at, &first) | ||
| 269 | + .await? | ||
| 270 | + { | ||
| 271 | + // A parallel exchange of the same code won the race: that is a reuse. The winner's access token | ||
| 272 | + // was recorded in its own redemption, so it is read again and revoked too. | ||
| 260 | app.store.revoke_code_refresh_tokens(&code_hash).await?; | 273 | app.store.revoke_code_refresh_tokens(&code_hash).await?; |
| 274 | + if let Some(winner) = app.store.auth_code(&code_hash).await? { | ||
| 275 | + revoke_code_access(app, &winner).await?; | ||
| 276 | + } | ||
| 261 | return Ok(invalid_grant()); | 277 | return Ok(invalid_grant()); |
| 262 | } | 278 | } |
| 263 | 279 | ||
| @@ -270,7 +286,15 @@ async fn grant_code(app: &AppState, client: &Client, pairs: &Pairs) -> Result<Re | |||
| 270 | row.nonce.as_deref(), | 286 | row.nonce.as_deref(), |
| 271 | ) | 287 | ) |
| 272 | .await?; | 288 | .await?; |
| 273 | - let access_token = access_token(app, &user, client, &session, &row.scope).await?; | 289 | + let access_token = access_token( |
| 290 | + app, | ||
| 291 | + &user, | ||
| 292 | + client, | ||
| 293 | + &session, | ||
| 294 | + &row.scope, | ||
| 295 | + (&access_jti, access_exp), | ||
| 296 | + ) | ||
| 297 | + .await?; | ||
| 274 | Ok(token_response( | 298 | Ok(token_response( |
| 275 | access_token, | 299 | access_token, |
| 276 | &row.scope, | 300 | &row.scope, |
| @@ -344,7 +368,16 @@ async fn grant_refresh(app: &AppState, client: &Client, pairs: &Pairs) -> Result | |||
| 344 | app.store.revoke_refresh_family(&row.family_id).await?; | 368 | app.store.revoke_refresh_family(&row.family_id).await?; |
| 345 | return Ok(invalid_grant()); | 369 | return Ok(invalid_grant()); |
| 346 | } | 370 | } |
| 347 | - let access_token = access_token(app, &user, client, &session, &row.scope).await?; | 371 | + let access_jti = generate_token(); |
| 372 | + let access_token = access_token( | ||
| 373 | + app, | ||
| 374 | + &user, | ||
| 375 | + client, | ||
| 376 | + &session, | ||
| 377 | + &row.scope, | ||
| 378 | + (&access_jti, access_expiry()), | ||
| 379 | + ) | ||
| 380 | + .await?; | ||
| 348 | Ok(token_response( | 381 | Ok(token_response( |
| 349 | access_token, | 382 | access_token, |
| 350 | &row.scope, | 383 | &row.scope, |
| @@ -445,16 +478,31 @@ pub fn person_claims(user: &User, scope: &str) -> Map<String, Value> { | |||
| 445 | claims | 478 | claims |
| 446 | } | 479 | } |
| 447 | 480 | ||
| 481 | +/// When an access token issued now expires, in Unix seconds. | ||
| 482 | +fn access_expiry() -> i64 { | ||
| 483 | + unix_now() + i64::try_from(ACCESS_TTL.as_secs()).unwrap_or(0) | ||
| 484 | +} | ||
| 485 | + | ||
| 486 | +/// Revokes the access token issued with an authorization code, when the code recorded one. From then on | ||
| 487 | +/// it is refused, as a token revoked at `/revoke` is. | ||
| 488 | +async fn revoke_code_access(app: &AppState, code: &AuthCode) -> im_core::Result<()> { | ||
| 489 | + if let (Some(jti), Some(expires_at)) = (&code.access_jti, &code.access_expires_at) { | ||
| 490 | + app.store.revoke_access_token(jti, expires_at).await?; | ||
| 491 | + } | ||
| 492 | + Ok(()) | ||
| 493 | +} | ||
| 494 | + | ||
| 448 | /// The user's access token: addressed to this provider's userinfo, carrying the session it belongs to | 495 | /// The user's access token: addressed to this provider's userinfo, carrying the session it belongs to |
| 449 | -/// and the client it was issued to (`azp`), so userinfo can check that the session still lives. | 496 | +/// and the client it was issued to (`azp`), so userinfo can check that the session still lives. Its |
| 497 | +/// `jti` and expiry are given by the caller, which records them when it needs to revoke the token. | ||
| 450 | async fn access_token( | 498 | async fn access_token( |
| 451 | app: &AppState, | 499 | app: &AppState, |
| 452 | user: &User, | 500 | user: &User, |
| 453 | client: &Client, | 501 | client: &Client, |
| 454 | session: &Session, | 502 | session: &Session, |
| 455 | scope: &str, | 503 | scope: &str, |
| 504 | + (jti, exp): (&str, i64), | ||
| 456 | ) -> im_core::Result<String> { | 505 | ) -> im_core::Result<String> { |
| 457 | - let now = im_core::time::unix_now(); | ||
| 458 | let claims = json!({ | 506 | let claims = json!({ |
| 459 | "iss": issuer(app), | 507 | "iss": issuer(app), |
| 460 | "sub": user.id, | 508 | "sub": user.id, |
| @@ -462,9 +510,9 @@ async fn access_token( | |||
| 462 | "azp": client.id, | 510 | "azp": client.id, |
| 463 | "scope": scope, | 511 | "scope": scope, |
| 464 | "sid": session.id, | 512 | "sid": session.id, |
| 465 | - "iat": now, | 513 | + "iat": unix_now(), |
| 466 | - "exp": now + i64::try_from(ACCESS_TTL.as_secs()).unwrap_or(0), | 514 | + "exp": exp, |
| 467 | - "jti": generate_token(), | 515 | + "jti": jti, |
| 468 | }); | 516 | }); |
| 469 | signing::sign(&app.store, &app.key, &claims).await | 517 | signing::sign(&app.store, &app.key, &claims).await |
| 470 | } | 518 | } |
crates/im-web/src/pages/security.rsmodified+8 -1
| @@ -282,9 +282,16 @@ async fn confirm_enrolment(cx: &Cx, Form(form): Form<CodeForm>) -> Result<impl V | |||
| 282 | .iter() | 282 | .iter() |
| 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 | state | 286 | state |
| 286 | .store | 287 | .store |
| 287 | - .enable_totp(&viewer.user.id, &sealed, step, &hashes) | 288 | + .enable_totp( |
| 289 | + &viewer.user.id, | ||
| 290 | + &sealed, | ||
| 291 | + step, | ||
| 292 | + &hashes, | ||
| 293 | + Some(&viewer.session.id), | ||
| 294 | + ) | ||
| 288 | .await?; | 295 | .await?; |
| 289 | changed(state, &viewer); | 296 | changed(state, &viewer); |
| 290 | record( | 297 | record( |
docs/architecture.mdmodified+3 -2
| @@ -211,8 +211,9 @@ redirects). Other errors redirect to the client with `error=` and `state`. | |||
| 211 | the redirect URI); `/token` allows 1200 requests a minute per authenticated client, and 30 a minute per | 211 | the redirect URI); `/token` allows 1200 requests a minute per authenticated client, and 30 a minute per |
| 212 | refresh-token family or authorization code; an account asks for at most 3 email changes an hour; each form | 212 | 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. | 213 | 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. Disable and delete end all and queue | 214 | +- Password change ends every other session; reset ends all. Enabling or disabling TOTP ends every other session |
| 215 | - back-channel logout by `sub`. | 215 | + (the current one stays). Disable and delete end all and queue back-channel logout by `sub`. |
| 216 | +- Signing in ends the session the browser presented, whoever it belonged to, so no row is left without its cookie. | ||
| 216 | - TOTP enroll: secret generated and held sealed in a pending state until a valid code confirms it; enrolling | 217 | - TOTP enroll: secret generated and held sealed in a pending state until a valid code confirms it; enrolling |
| 217 | again while enabled requires the current code (old defect: re-visiting enroll reset it). Disabling TOTP | 218 | again while enabled requires the current code (old defect: re-visiting enroll reset it). Disabling TOTP |
| 218 | requires the password and a code. Admin "reset 2FA" clears TOTP and recovery codes and is audited and mailed | 219 | requires the password and a code. Admin "reset 2FA" clears TOTP and recovery codes and is audited and mailed |
docs/contracts.mdmodified+2 -1
| @@ -68,7 +68,8 @@ Clients fetch discovery once at boot and cache it. They may hard-code the paths | |||
| 68 | with a registered URI), `scope` containing `openid` (and `profile email`), `state` (≥128 bits), | 68 | with a registered URI), `scope` containing `openid` (and `profile email`), `state` (≥128 bits), |
| 69 | `nonce` (≥128 bits), `code_challenge`, `code_challenge_method=S256`. PKCE is mandatory. | 69 | `nonce` (≥128 bits), `code_challenge`, `code_challenge_method=S256`. PKCE is mandatory. |
| 70 | 2. `im` signs the user in (password, then TOTP or a recovery code if enrolled) and redirects back with | 70 | 2. `im` signs the user in (password, then TOTP or a recovery code if enrolled) and redirects back with |
| 71 | - `code` and `state`. Codes live 60 seconds and are single use. A reused code revokes every token issued from it. | 71 | + `code` and `state`. Codes live 60 seconds and are single use. A reused code revokes every token issued from it, |
| 72 | + the access token included. | ||
| 72 | 3. App posts to `/token` (`grant_type=authorization_code`, `code`, `redirect_uri`, `code_verifier`), client auth | 73 | 3. App posts to `/token` (`grant_type=authorization_code`, `code`, `redirect_uri`, `code_verifier`), client auth |
| 73 | by `client_secret_basic` or `client_secret_post`. Response: `access_token` (JWT, 10 min), `id_token`, | 74 | by `client_secret_basic` or `client_secret_post`. Response: `access_token` (JWT, 10 min), `id_token`, |
| 74 | `refresh_token`, `token_type: "Bearer"`, `expires_in`. | 75 | `refresh_token`, `token_type: "Bearer"`, `expires_in`. |