From ec12b7803886c649d6cff2670a0bd47f2be48936 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Wed, 28 Oct 2026 15:24:16 +0300 Subject: [PATCH] =?UTF-8?q?=F0=9F=94=92=20logout=20auto-submits=20only=20f?= =?UTF-8?q?or=20the=20viewer's=20own=20hint;=20code=20replay=20revokes=20i?= =?UTF-8?q?ts=20access=20token;=20TOTP=20enable=20and=20sign-in=20end=20st?= =?UTF-8?q?ale=20sessions?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../migrations/0007_code_access_token.sql | 6 ++ crates/im-core/src/model.rs | 4 ++ crates/im-core/src/store/backchannel.rs | 2 + crates/im-core/src/store/migrate.rs | 4 ++ crates/im-core/src/store/oidc.rs | 22 ++++-- crates/im-core/src/store/users.rs | 15 +++- crates/im-web/src/auth.rs | 25 ++++--- crates/im-web/src/oidc/logout.rs | 42 +++++++---- crates/im-web/src/oidc/token.rs | 72 +++++++++++++++---- crates/im-web/src/pages/security.rs | 9 ++- docs/architecture.md | 5 +- docs/contracts.md | 3 +- 12 files changed, 160 insertions(+), 49 deletions(-) create mode 100644 crates/im-core/migrations/0007_code_access_token.sql diff --git a/crates/im-core/migrations/0007_code_access_token.sql b/crates/im-core/migrations/0007_code_access_token.sql new file mode 100644 index 0000000..ce7cb2a --- /dev/null +++ b/crates/im-core/migrations/0007_code_access_token.sql @@ -0,0 +1,6 @@ +-- 0007: the access token issued from an authorization code, by its `jti` and its expiry, written in the +-- same transaction that marks the code used. A replayed code revokes that access token too (RFC 6749 +-- section 4.1.2), through the revoked_access_tokens list. Codes exchanged before this migration have none. + +ALTER TABLE auth_codes ADD COLUMN access_jti TEXT; +ALTER TABLE auth_codes ADD COLUMN access_expires_at TEXT; diff --git a/crates/im-core/src/model.rs b/crates/im-core/src/model.rs index 6b3621e..4dedc5f 100644 --- a/crates/im-core/src/model.rs +++ b/crates/im-core/src/model.rs @@ -339,6 +339,10 @@ pub struct AuthCode { pub expires_at: String, /// Set when the code was exchanged. A code is exchanged once. pub used_at: Option, + /// The `jti` of the access token issued at the exchange. A replay revokes it. + pub access_jti: Option, + /// When that access token expires; its revocation is kept until then. + pub access_expires_at: Option, } /// A refresh token row. Only the hash of the token is stored. diff --git a/crates/im-core/src/store/backchannel.rs b/crates/im-core/src/store/backchannel.rs index edd96b7..75633aa 100644 --- a/crates/im-core/src/store/backchannel.rs +++ b/crates/im-core/src/store/backchannel.rs @@ -395,6 +395,8 @@ mod tests { store .redeem_auth_code( "code", + "access-1", + &refresh_expires, &NewRefreshToken { id: "refresh-1", token_hash: &hash_token("refresh"), diff --git a/crates/im-core/src/store/migrate.rs b/crates/im-core/src/store/migrate.rs index f1cf724..fe0ce47 100644 --- a/crates/im-core/src/store/migrate.rs +++ b/crates/im-core/src/store/migrate.rs @@ -29,6 +29,10 @@ pub const MIGRATIONS: &[(u32, &str)] = &[ 6, include_str!("../../migrations/0006_mail_outbox_recipient.sql"), ), + ( + 7, + include_str!("../../migrations/0007_code_access_token.sql"), + ), ]; fn migration_err(e: turso::Error) -> Error { diff --git a/crates/im-core/src/store/oidc.rs b/crates/im-core/src/store/oidc.rs index 02d2e0b..b98e12e 100644 --- a/crates/im-core/src/store/oidc.rs +++ b/crates/im-core/src/store/oidc.rs @@ -14,7 +14,7 @@ use crate::time::now_stamp; /// The columns of an authorization code row, in the order [`map_code`] reads them. const CODE_COLS: &str = "code_hash, client_id, user_id, session_id, redirect_uri, scope, nonce, \ - code_challenge, expires_at, used_at"; + code_challenge, expires_at, used_at, access_jti, access_expires_at"; /// The columns of a refresh token row, in the order [`map_refresh`] reads them. 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 { code_challenge: col_text(row, 7)?, expires_at: col_text(row, 8)?, used_at: col_opt_text(row, 9)?, + access_jti: col_opt_text(row, 10)?, + access_expires_at: col_opt_text(row, 11)?, }) } @@ -220,12 +222,15 @@ impl Store { .await } - /// Exchanges a code: marks it used and stores the first refresh token, in one transaction. Returns - /// false, with nothing changed, when the code is already used, expired or unknown. The caller treats - /// a false after its own checks passed as a race, which is a reuse. + /// Exchanges a code: marks it used, records the `jti` and expiry of the access token issued with it, and + /// stores the first refresh token, in one transaction. Returns false, with nothing changed, when the code + /// is already used, expired or unknown. The caller treats a false after its own checks passed as a race, + /// which is a reuse. pub async fn redeem_auth_code( &self, code_hash: &str, + access_jti: &str, + access_expires_at: &str, refresh: &NewRefreshToken<'_>, ) -> Result { let now = now_stamp(); @@ -234,9 +239,14 @@ impl Store { let outcome: Result = async { let changed = tx .execute( - "UPDATE auth_codes SET used_at = ?2 \ + "UPDATE auth_codes SET used_at = ?2, access_jti = ?3, access_expires_at = ?4 \ WHERE code_hash = ?1 AND used_at IS NULL AND expires_at > ?2", - (code_hash.to_string(), now.clone()), + ( + code_hash.to_string(), + now.clone(), + access_jti.to_string(), + access_expires_at.to_string(), + ), ) .await .map_err(db_err)?; diff --git a/crates/im-core/src/store/users.rs b/crates/im-core/src/store/users.rs index 74c2d50..a341f72 100644 --- a/crates/im-core/src/store/users.rs +++ b/crates/im-core/src/store/users.rs @@ -417,6 +417,8 @@ impl Store { /// Turns two-factor sign-in on: stores the confirmed secret, records the step that confirmed /// it as used, replaces the recovery codes with `recovery_hashes` and drops the pending secret. + /// Sessions created before it are not second-factor sessions, so in the same transaction every live + /// session except `keep_session_id` ends, with its back-channel logouts. `None` ends all of them. /// One transaction. pub async fn enable_totp( &self, @@ -424,6 +426,7 @@ impl Store { sealed_secret: &str, step: u64, recovery_hashes: &[String], + keep_session_id: Option<&str>, ) -> Result<()> { let step = i64::try_from(step).map_err(|_| Error::Invalid("totp step out of range".into()))?; @@ -435,7 +438,12 @@ impl Store { .execute( "UPDATE users SET totp_secret_sealed = ?2, totp_enabled_at = ?3, \ totp_last_step = ?4, updated_at = ?3 WHERE id = ?1", - (user_id.to_string(), sealed_secret.to_string(), now, step), + ( + user_id.to_string(), + sealed_secret.to_string(), + now.clone(), + step, + ), ) .await .map_err(db_err)?; @@ -449,6 +457,8 @@ impl Store { ) .await .map_err(db_err)?; + let ids = live_session_ids(&tx, user_id, keep_session_id, &now).await?; + end_rows(&tx, user_id, &ids, EndReason::Revoked, &now).await?; Ok(()) } .await; @@ -636,7 +646,7 @@ mod tests { Some("v1:sealed") ); store - .enable_totp(&user.id, "v1:sealed", 100, &["h1".to_string()]) + .enable_totp(&user.id, "v1:sealed", 100, &["h1".to_string()], None) .await .unwrap(); assert!(store.totp_pending(&user.id).await.unwrap().is_none()); @@ -662,6 +672,7 @@ mod tests { "v1:sealed", 5, &["code-a".to_string(), "code-b".to_string()], + None, ) .await .unwrap(); diff --git a/crates/im-web/src/auth.rs b/crates/im-web/src/auth.rs index 75d82ad..0836326 100644 --- a/crates/im-web/src/auth.rs +++ b/crates/im-web/src/auth.rs @@ -152,21 +152,23 @@ pub fn check_csrf(session: &Session, submitted: &str) -> bool { /// Creates a session for `user`, authenticated by `amr`, and sets the cookie. /// -/// A session the browser already presented for the same person is ended first, so a sign-in always -/// rotates the session id. The session lives [`SESSION_IDLE`] after its last use, up to the policy's -/// `session_max_days` from now; the store keeps both limits. The per-person cap of the policy is -/// applied inside the store, in the same write. +/// A session the browser already presented is ended first, whoever it belongs to, so a sign-in always +/// rotates the session id and no row is left live with no cookie holding it. The session lives +/// [`SESSION_IDLE`] after its last use, up to the policy's `session_max_days` from now; the store keeps +/// both limits. The per-person cap of the policy is applied inside the store, in the same write. pub async fn start_session(cx: &Cx, user: &User, amr: &str) -> Result { let state = app_context::(cx); let max_age = Duration::from_secs(u64::from(state.policy().session_max_days) * DAY); - if let Some(old) = presented_session(cx) - .await? - .filter(|old| old.user_id == user.id) - { - state + if let Some(old) = presented_session(cx).await? { + // The owner is the session's own user, so the store's ownership check passes for it. + if state .store - .end_session(&user.id, &old.id, EndReason::Replaced) - .await?; + .end_session(&old.user_id, &old.id, EndReason::Replaced) + .await? + && old.user_id != user.id + { + state.live.bump(&Topic::Account(old.user_id.clone())); + } } let token = generate_token(); let csrf = generate_token(); @@ -536,6 +538,7 @@ mod tests { &sealed, 1, &[totp::recovery_code_hash(&state.key, &code)], + None, ) .await .expect("enable"); diff --git a/crates/im-web/src/oidc/logout.rs b/crates/im-web/src/oidc/logout.rs index aa25a96..ee79830 100644 --- a/crates/im-web/src/oidc/logout.rs +++ b/crates/im-web/src/oidc/logout.rs @@ -9,12 +9,12 @@ //! signed-out page, never a redirect. //! - `state` is echoed on the redirect only when it is usable (bounded, no control characters). //! - A `GET` never ends a session: a link or an image on another site must not sign the browser out. A -//! `GET` with a session answers with a form that carries the session's CSRF token. When a valid -//! `id_token_hint` came with it (a client's sign-out), the form posts itself (`data-auto-submit`, run by -//! `assets/pages.js`), so the browser returns to the client without a second click; a bare `GET` waits for -//! the person's click, so a link on another site cannot sign them out. The visible button is the fallback -//! without JS. Only the `POST` ends the session, and it -//! checks that token before anything changes. +//! `GET` with a session answers with a form that carries the session's CSRF token. The form posts itself +//! (`data-auto-submit`, run by `assets/pages.js`) only when the hint is this browser's own: its `sid` is +//! the viewer's session and its `sub` is the viewer. That is a client's sign-out, so the browser returns +//! to the client without a second click. Any other hint (anyone can hold a valid ID token of their own) +//! leaves the person to click. The visible button is the fallback without JS. Only the `POST` ends the +//! session, and it checks that token before anything changes. //! - Ending the session is `im`'s own: the browser session is deleted (and its clients told by //! back-channel logout, in the store's transaction). When the hint names another session of the same //! person, that one ends too. @@ -57,8 +57,10 @@ pub struct LogoutForm { state: String, } -/// What a valid hint says: the session it names, and the client it was issued to. +/// What a valid hint says: the person it was issued to and the session it names. struct Hint { + /// The `sub` claim: the person the ID token was issued to. + sub: Option, /// The `im` session of the sign-in, when the hint names one. sid: Option, } @@ -81,12 +83,13 @@ fn usable_state(value: &str) -> bool { } /// Verifies an ID token of ours for logout. `None` when it is not an ID token of this provider, or its -/// signature or issuer is wrong. The expiry is not checked. +/// signature or issuer is wrong. The expiry is not checked. Returns the client it was issued to and the +/// hint's claims that matter here. async fn verify_hint( store: &Store, issuer: &str, token: &str, -) -> im_core::Result)>> { +) -> im_core::Result> { let published = signing::published_keys(store).await?; let keys: Vec = published .iter() @@ -106,8 +109,11 @@ async fn verify_hint( let Some(client_id) = jwt::single_audience(&claims) else { return Ok(None); }; - let sid = claims.get("sid").and_then(Value::as_str).map(str::to_owned); - Ok(Some((client_id.to_owned(), sid))) + let hint = Hint { + sub: claims.get("sub").and_then(Value::as_str).map(str::to_owned), + sid: claims.get("sid").and_then(Value::as_str).map(str::to_owned), + }; + Ok(Some((client_id.to_owned(), hint))) } /// Checks the request. Nothing here changes state. @@ -124,7 +130,7 @@ async fn read(app: &AppState, form: &LogoutForm) -> Result { if form.id_token_hint.is_empty() { return Ok(asked); } - let Some((client_id, sid)) = verify_hint(&app.store, issuer(app), &form.id_token_hint).await? + let Some((client_id, hint)) = verify_hint(&app.store, issuer(app), &form.id_token_hint).await? else { return Ok(asked); }; @@ -139,7 +145,7 @@ async fn read(app: &AppState, form: &LogoutForm) -> Result { { asked.redirect = Some(form.post_logout_redirect_uri.clone()); } - asked.hint = Some(Hint { sid }); + asked.hint = Some(hint); Ok(asked) } @@ -187,9 +193,15 @@ async fn logout_get(cx: &Cx, Form(form): Form) -> Result let lang = page_lang(cx, viewer.as_ref()); match viewer { Some(viewer) => { + // Only the browser's own hint (a client's sign-out) may post the form without a click. + let own = asked.hint.as_ref().is_some_and(|hint| { + hint.sid.as_deref() == Some(viewer.session.id.as_str()) + && hint.sub.as_deref() == Some(viewer.user.id.as_str()) + }); let confirm = Confirm { csrf: viewer.session.csrf_token.clone(), raw_hint: asked.raw_hint.clone(), + auto_submit: own, redirect: asked.redirect.clone(), state: asked.state.clone(), }; @@ -229,6 +241,8 @@ async fn logout_post(cx: &Cx, Form(form): Form) -> Result struct Confirm { csrf: String, raw_hint: Option, + /// True when the hint is this browser's own, so the form posts without a click. + auto_submit: bool, redirect: Option, state: Option, } @@ -247,7 +261,7 @@ fn logout_view(cx: &Cx, lang: Lang, confirm: Option) -> impl View {

(title)

if let Some(confirm) = confirm {

(text(lang, OidcText::ConfirmBody))

-
+ if let Some(hint) = confirm.raw_hint { diff --git a/crates/im-web/src/oidc/token.rs b/crates/im-web/src/oidc/token.rs index 58294b4..a219942 100644 --- a/crates/im-web/src/oidc/token.rs +++ b/crates/im-web/src/oidc/token.rs @@ -12,12 +12,12 @@ use std::time::Instant; use base64::prelude::{BASE64_STANDARD, Engine as _}; use http::header::{AUTHORIZATION, RETRY_AFTER}; -use im_core::model::{Client, Session, User, amr}; +use im_core::model::{AuthCode, Client, Session, User, amr}; use im_core::oauth::{is_supported_scope, is_user_scope, is_valid_family_key}; use im_core::oauth::{is_valid_verifier, pkce_s256}; use im_core::store::new_id; use im_core::store::oidc::NewRefreshToken; -use im_core::time::{now_stamp, stamp_after, unix_now, unix_seconds}; +use im_core::time::{now_stamp, stamp_after, stamp_of_unix, unix_now, unix_seconds}; use im_core::token::{constant_time_eq, generate_token, hash_token}; use serde_json::{Map, Value, json}; use topcoat::Result; @@ -217,8 +217,10 @@ async fn grant_code(app: &AppState, client: &Client, pairs: &Pairs) -> Result Result Result Result Result app.store.revoke_refresh_family(&row.family_id).await?; return Ok(invalid_grant()); } - let access_token = access_token(app, &user, client, &session, &row.scope).await?; + let access_jti = generate_token(); + let access_token = access_token( + app, + &user, + client, + &session, + &row.scope, + (&access_jti, access_expiry()), + ) + .await?; Ok(token_response( access_token, &row.scope, @@ -445,16 +478,31 @@ pub fn person_claims(user: &User, scope: &str) -> Map { claims } +/// When an access token issued now expires, in Unix seconds. +fn access_expiry() -> i64 { + unix_now() + i64::try_from(ACCESS_TTL.as_secs()).unwrap_or(0) +} + +/// Revokes the access token issued with an authorization code, when the code recorded one. From then on +/// it is refused, as a token revoked at `/revoke` is. +async fn revoke_code_access(app: &AppState, code: &AuthCode) -> im_core::Result<()> { + if let (Some(jti), Some(expires_at)) = (&code.access_jti, &code.access_expires_at) { + app.store.revoke_access_token(jti, expires_at).await?; + } + Ok(()) +} + /// The user's access token: addressed to this provider's userinfo, carrying the session it belongs to -/// and the client it was issued to (`azp`), so userinfo can check that the session still lives. +/// and the client it was issued to (`azp`), so userinfo can check that the session still lives. Its +/// `jti` and expiry are given by the caller, which records them when it needs to revoke the token. async fn access_token( app: &AppState, user: &User, client: &Client, session: &Session, scope: &str, + (jti, exp): (&str, i64), ) -> im_core::Result { - let now = im_core::time::unix_now(); let claims = json!({ "iss": issuer(app), "sub": user.id, @@ -462,9 +510,9 @@ async fn access_token( "azp": client.id, "scope": scope, "sid": session.id, - "iat": now, - "exp": now + i64::try_from(ACCESS_TTL.as_secs()).unwrap_or(0), - "jti": generate_token(), + "iat": unix_now(), + "exp": exp, + "jti": jti, }); signing::sign(&app.store, &app.key, &claims).await } diff --git a/crates/im-web/src/pages/security.rs b/crates/im-web/src/pages/security.rs index 7ba29bf..120c598 100644 --- a/crates/im-web/src/pages/security.rs +++ b/crates/im-web/src/pages/security.rs @@ -282,9 +282,16 @@ async fn confirm_enrolment(cx: &Cx, Form(form): Form) -> Result