From e787bb29f35dd87c1a99475366da78ef7ba9be31 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 11:50:10 +0300 Subject: [PATCH] =?UTF-8?q?=F0=9F=94=92=20fix:=20revoked=20access=20tokens?= =?UTF-8?q?=20refused=20everywhere,=20idle=20live=20streams=20re-check=20t?= =?UTF-8?q?he=20viewer=20every=2015=20s,=20repeated=20logout=20jti=20docum?= =?UTF-8?q?ented?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../migrations/0004_revoked_access_tokens.sql | 10 ++++ crates/im-core/src/store/migrate.rs | 4 ++ crates/im-core/src/store/mod.rs | 2 +- crates/im-core/src/store/oidc.rs | 38 +++++++++++++ crates/im-core/src/time.rs | 7 +++ crates/im-web/src/api/machine_auth.rs | 9 +-- crates/im-web/src/live.rs | 4 ++ crates/im-web/src/oidc/introspect.rs | 14 ++--- crates/im-web/src/oidc/revoke.rs | 55 +++++++++++++++---- crates/im-web/src/oidc/signing.rs | 29 +++++++++- crates/im-web/src/oidc/tests.rs | 42 ++++++++++++++ crates/im-web/src/oidc/userinfo.rs | 9 +-- crates/im-web/src/sweeper.rs | 6 ++ docs/contracts.md | 2 +- 14 files changed, 194 insertions(+), 37 deletions(-) create mode 100644 crates/im-core/migrations/0004_revoked_access_tokens.sql diff --git a/crates/im-core/migrations/0004_revoked_access_tokens.sql b/crates/im-core/migrations/0004_revoked_access_tokens.sql new file mode 100644 index 0000000..a1aaee4 --- /dev/null +++ b/crates/im-core/migrations/0004_revoked_access_tokens.sql @@ -0,0 +1,10 @@ +-- 0004: the access tokens (by their `jti`) that a client has revoked through /revoke. An access token +-- is refused while its jti is listed here. Each row is kept until the token would have expired anyway; +-- the sweeper removes rows past expires_at. + +CREATE TABLE revoked_access_tokens ( + jti TEXT PRIMARY KEY NOT NULL, + expires_at TEXT NOT NULL +); + +CREATE INDEX revoked_access_tokens_expires ON revoked_access_tokens (expires_at); diff --git a/crates/im-core/src/store/migrate.rs b/crates/im-core/src/store/migrate.rs index c6162a1..153e420 100644 --- a/crates/im-core/src/store/migrate.rs +++ b/crates/im-core/src/store/migrate.rs @@ -20,6 +20,10 @@ pub const MIGRATIONS: &[(u32, &str)] = &[ 3, include_str!("../../migrations/0003_consumed_pending_logins.sql"), ), + ( + 4, + include_str!("../../migrations/0004_revoked_access_tokens.sql"), + ), ]; fn migration_err(e: turso::Error) -> Error { diff --git a/crates/im-core/src/store/mod.rs b/crates/im-core/src/store/mod.rs index ad1dcbc..7199d5d 100644 --- a/crates/im-core/src/store/mod.rs +++ b/crates/im-core/src/store/mod.rs @@ -353,6 +353,6 @@ mod tests { }) .await .unwrap(); - assert_eq!(applied, vec![1, 2, 3]); + assert_eq!(applied, vec![1, 2, 3, 4]); } } diff --git a/crates/im-core/src/store/oidc.rs b/crates/im-core/src/store/oidc.rs index 58d15a2..02d2e0b 100644 --- a/crates/im-core/src/store/oidc.rs +++ b/crates/im-core/src/store/oidc.rs @@ -147,6 +147,44 @@ impl Store { .map_err(db_err) } + /// Records the access token `jti` as revoked until `expires_at`, the token's own expiry. Revoking an + /// already revoked token changes nothing. + pub async fn revoke_access_token(&self, jti: &str, expires_at: &str) -> Result<()> { + let conn = self.inner.conn.lock().await; + conn.execute( + "INSERT OR IGNORE INTO revoked_access_tokens (jti, expires_at) VALUES (?1, ?2)", + (jti.to_string(), expires_at.to_string()), + ) + .await + .map_err(db_err)?; + Ok(()) + } + + /// True when the access token `jti` was revoked and the revocation has not yet been swept. + pub async fn access_token_revoked(&self, jti: &str) -> Result { + let conn = self.read_conn().await; + let row = fetch_opt( + &conn, + "SELECT jti FROM revoked_access_tokens WHERE jti = ?1", + (jti.to_string(),), + |row| col_text(row, 0), + ) + .await?; + Ok(row.is_some()) + } + + /// Deletes the revocations of access tokens that expired before `now`: such a token is refused by its + /// expiry already. Run by the sweeper. + pub async fn sweep_revoked_access_tokens(&self, now: &str) -> Result { + let conn = self.inner.conn.lock().await; + conn.execute( + "DELETE FROM revoked_access_tokens WHERE expires_at < ?1", + (now.to_string(),), + ) + .await + .map_err(db_err) + } + pub async fn insert_auth_code(&self, new: &NewAuthCode<'_>) -> Result<()> { let conn = self.inner.conn.lock().await; conn.execute( diff --git a/crates/im-core/src/time.rs b/crates/im-core/src/time.rs index 83f6943..ecbf54e 100644 --- a/crates/im-core/src/time.rs +++ b/crates/im-core/src/time.rs @@ -68,6 +68,13 @@ pub fn unix_now() -> i64 { OffsetDateTime::now_utc().unix_timestamp() } +/// The stamp of a Unix time in whole seconds. `None` when the time is out of range. +pub fn stamp_of_unix(seconds: i64) -> Option { + OffsetDateTime::from_unix_timestamp(seconds) + .ok() + .map(format_stamp) +} + /// The IANA time zone names of the database compiled into this build, sorted. The bundled database /// is used on purpose, so every install offers the same list whatever the host has installed. pub fn zone_names() -> Vec { diff --git a/crates/im-web/src/api/machine_auth.rs b/crates/im-web/src/api/machine_auth.rs index 326704a..a56ed7d 100644 --- a/crates/im-web/src/api/machine_auth.rs +++ b/crates/im-web/src/api/machine_auth.rs @@ -7,7 +7,7 @@ //! access token and an ID token fail one of these checks, so they never open a machine route. use http::header::AUTHORIZATION; -use im_core::jwt::{self, PublishedKey}; +use im_core::jwt; use im_core::oauth::is_valid_family_key; use im_core::time::unix_now; use serde_json::Value; @@ -49,12 +49,7 @@ pub async fn require( let Some(token) = bearer(headers(cx).get(AUTHORIZATION)) else { return Ok(Err(refused())); }; - let published = signing::published_keys(&app.store).await?; - let keys: Vec = published - .iter() - .filter_map(|key| PublishedKey::new(key.kid.clone(), &key.public_raw)) - .collect(); - let Ok(claims) = jwt::verify(&keys, token) else { + let Some(claims) = signing::verify_access(&app.store, token).await? else { return Ok(Err(refused())); }; // The audience must be exactly the string `im`. `check_claims` also checks it, and the exp and iat. diff --git a/crates/im-web/src/live.rs b/crates/im-web/src/live.rs index 8497d5e..d3af2da 100644 --- a/crates/im-web/src/live.rs +++ b/crates/im-web/src/live.rs @@ -40,6 +40,9 @@ pub const KEEP_ALIVE: Duration = Duration::from_secs(30); /// Longest a stream lives, whatever happens on it. The browser reconnects after it, and a reconnect /// authenticates and authorises again, so a session that ended or lost its role is not kept by a stream. pub const MAX_STREAM_LIFE: Duration = Duration::from_secs(60 * 60); +/// How often an idle `changed` stream runs its fingerprint anyway, so a viewer who signed out or lost +/// access is noticed even when no topic of the stream changes. +pub const RECHECK: Duration = Duration::from_secs(15); /// Anonymous `/-/alive` streams open at once, across the whole process. A further one gets `429`. pub const MAX_ANONYMOUS_STREAMS: usize = 256; @@ -145,6 +148,7 @@ where woke = wait_any(&mut follow.wakes) => woke, () = stopped(&mut follow.stop) => false, () = tokio::time::sleep_until(follow.until) => false, + () = tokio::time::sleep(RECHECK) => true, }; if !woke { return None; diff --git a/crates/im-web/src/oidc/introspect.rs b/crates/im-web/src/oidc/introspect.rs index 2464702..fa0a642 100644 --- a/crates/im-web/src/oidc/introspect.rs +++ b/crates/im-web/src/oidc/introspect.rs @@ -7,7 +7,7 @@ //! and account are. A refresh token is active while it is unused, unrevoked and unexpired, and its //! session is live. The client authenticates like at `/token`. -use im_core::jwt::{self, PublishedKey}; +use im_core::jwt; use im_core::model::Client; use im_core::time::{now_stamp, unix_now, unix_seconds}; use im_core::token::hash_token; @@ -40,15 +40,11 @@ async fn introspect(cx: &Cx, body: Body) -> Result { Ok(json_response(StatusCode::OK, &answer)) } -/// The answer for an access token of ours. `None` when the text is not a token of this provider, so the -/// caller tries the refresh tokens. +/// The answer for an access token of ours. `None` when the text is not an access token of this provider +/// that is still unrevoked, so the caller tries the refresh tokens. A revoked access token is therefore +/// answered by the refresh lookup, which finds nothing and reports it inactive. async fn access_answer(app: &AppState, client: &Client, token: &str) -> Result> { - let published = signing::published_keys(&app.store).await?; - let keys: Vec = published - .iter() - .filter_map(|key| PublishedKey::new(key.kid.clone(), &key.public_raw)) - .collect(); - let Ok(claims) = jwt::verify(&keys, token) else { + let Some(claims) = signing::verify_access(&app.store, token).await? else { return Ok(None); }; let now = unix_now(); diff --git a/crates/im-web/src/oidc/revoke.rs b/crates/im-web/src/oidc/revoke.rs index 944a96b..0ec6612 100644 --- a/crates/im-web/src/oidc/revoke.rs +++ b/crates/im-web/src/oidc/revoke.rs @@ -1,20 +1,26 @@ -//! `POST /revoke` (RFC 7009): a client gives back one of its own refresh tokens, and the whole chain of -//! that token is revoked. +//! `POST /revoke` (RFC 7009): a client gives back one of its own tokens, and that token stops working. +//! +//! A refresh token revokes its whole chain. An access token is recorded by its `jti` until its own expiry +//! (`revoked_access_tokens`), so `/userinfo`, `/introspect` and the machine routes refuse it at once. Only an +//! access token issued to the authenticated client (`azp`) is recorded; an expired one needs nothing, since +//! it is refused by its expiry already. //! //! The client authenticates like at `/token`. The answer is `200` with an empty body for every token: a //! token that is unknown, belongs to another client, or is already revoked gets the same answer, so the -//! endpoint does not reveal which tokens exist (RFC 7009 section 2.2). Access tokens need no table here: -//! they live ten minutes and are refused at once when their session ends, so revoking the session is the -//! way to end them. +//! endpoint does not reveal which tokens exist (RFC 7009 section 2.2). +use im_core::jwt; +use im_core::model::Client; +use im_core::time::{stamp_of_unix, unix_now}; use im_core::token::hash_token; +use serde_json::Value; use topcoat::Result; use topcoat::context::Cx; use topcoat::router::response::Response; use topcoat::router::{Body, StatusCode, route}; use super::token::client_form; -use super::{oauth_error, one}; +use super::{issuer, oauth_error, one, signing}; use crate::state::AppState; use topcoat::context::app_context; @@ -29,12 +35,41 @@ async fn revoke(cx: &Cx, body: Body) -> Result { let Some(token) = one(&pairs, "token") else { return Ok(oauth_error(StatusCode::BAD_REQUEST, "invalid_request")); }; - if let Some(row) = app.store.refresh_token(&hash_token(token)).await? - && row.client_id == client.id - { - app.store.revoke_refresh_family(&row.family_id).await?; + match app.store.refresh_token(&hash_token(token)).await? { + Some(row) => { + if row.client_id == client.id { + app.store.revoke_refresh_family(&row.family_id).await?; + } + } + None => revoke_access(app, &client, token).await?, } let mut response = Response::new(Body::empty()); *response.status_mut() = StatusCode::OK; Ok(response) } + +/// Records an access token of ours as revoked. Anything else, including an expired token, changes nothing. +async fn revoke_access(app: &AppState, client: &Client, token: &str) -> Result<()> { + let Some(claims) = signing::verify_access(&app.store, token).await? else { + return Ok(()); + }; + if jwt::check_issuer(&claims, issuer(app)).is_err() + || claims.get("azp").and_then(Value::as_str) != Some(client.id.as_str()) + { + return Ok(()); + } + let (Some(jti), Some(exp)) = ( + claims.get("jti").and_then(Value::as_str), + claims.get("exp").and_then(Value::as_i64), + ) else { + return Ok(()); + }; + if exp <= unix_now() { + return Ok(()); + } + let Some(expires_at) = stamp_of_unix(exp) else { + return Ok(()); + }; + app.store.revoke_access_token(jti, &expires_at).await?; + Ok(()) +} diff --git a/crates/im-web/src/oidc/signing.rs b/crates/im-web/src/oidc/signing.rs index efb45b1..ec09a9a 100644 --- a/crates/im-web/src/oidc/signing.rs +++ b/crates/im-web/src/oidc/signing.rs @@ -8,13 +8,13 @@ use std::sync::Arc; use std::time::Duration; -use im_core::jwt; +use im_core::jwt::{self, PublishedKey}; use im_core::keys::{self, OVERLAP}; use im_core::model::KeyRecord; use im_core::secret; use im_core::store::Store; use im_core::time::{now_stamp, stamp_minus, stamp_plus}; -use serde_json::Value; +use serde_json::{Map, Value}; use tokio::sync::watch; /// How often the worker checks the chain of keys. @@ -96,6 +96,31 @@ pub async fn published_keys(store: &Store) -> im_core::Result> { .collect()) } +/// Verifies an access token this provider issued: its signature against the published keys, and that its +/// `jti` has not been revoked (`/revoke`). Returns the claims, or `None` when the token is not ours, is +/// forged, has no `jti`, or was revoked. The caller still checks `iss`, `aud`, `exp` and what the token +/// grants, with `jwt::check_claims`. +pub async fn verify_access( + store: &Store, + token: &str, +) -> im_core::Result>> { + let published = published_keys(store).await?; + let keys: Vec = published + .iter() + .filter_map(|key| PublishedKey::new(key.kid.clone(), &key.public_raw)) + .collect(); + let Ok(claims) = jwt::verify(&keys, token) else { + return Ok(None); + }; + let Some(jti) = claims.get("jti").and_then(Value::as_str) else { + return Ok(None); + }; + if store.access_token_revoked(jti).await? { + return Ok(None); + } + Ok(Some(claims)) +} + /// Signs `claims` with the key that is current now. pub async fn sign( store: &Store, diff --git a/crates/im-web/src/oidc/tests.rs b/crates/im-web/src/oidc/tests.rs index e520ebb..13957a9 100644 --- a/crates/im-web/src/oidc/tests.rs +++ b/crates/im-web/src/oidc/tests.rs @@ -416,6 +416,48 @@ async fn introspection_reports_a_token_inactive_for_any_client_but_its_own() { assert_eq!(foreign, serde_json::json!({ "active": false })); } +#[tokio::test] +async fn a_revoked_access_token_is_refused_by_userinfo_and_introspection() { + let f = fixture().await; + let verifier = generate_token(); + let code = code_for(&f, &f.client, &verifier).await; + let (status, issued) = token_with(&f, &f.client, &f.secret, &code_body(&code, &verifier)).await; + assert_eq!(status, StatusCode::OK, "{issued}"); + let access = issued["access_token"] + .as_str() + .expect("access token") + .to_owned(); + let userinfo = || { + let request = http::Request::get("/userinfo") + .header(AUTHORIZATION, format!("Bearer {access}")) + .body(Body::empty()) + .expect("request"); + send(&f.state, request) + }; + assert_eq!(userinfo().await.0, StatusCode::OK); + + let (status, _) = post_as( + &f, + "/revoke", + &f.client, + &f.secret, + &format!("token={access}"), + ) + .await; + assert_eq!(status, StatusCode::OK); + assert_eq!(userinfo().await.0, StatusCode::UNAUTHORIZED); + let (status, answer) = post_as( + &f, + "/introspect", + &f.client, + &f.secret, + &format!("token={access}"), + ) + .await; + assert_eq!(status, StatusCode::OK); + assert_eq!(answer, serde_json::json!({ "active": false })); +} + /// The ID token of a fresh sign-in of the fixture's person, and the code exchange's session id. async fn id_token_of(f: &Fixture) -> String { let verifier = generate_token(); diff --git a/crates/im-web/src/oidc/userinfo.rs b/crates/im-web/src/oidc/userinfo.rs index ec55a41..dbd6795 100644 --- a/crates/im-web/src/oidc/userinfo.rs +++ b/crates/im-web/src/oidc/userinfo.rs @@ -6,7 +6,7 @@ //! names: a session that ended, or a disabled account, refuses the token at once, even before it expires. use http::header::{AUTHORIZATION, HeaderValue, WWW_AUTHENTICATE}; -use im_core::jwt::{self, PublishedKey}; +use im_core::jwt; use im_core::time::unix_now; use serde_json::{Value, json}; use topcoat::Result; @@ -27,12 +27,7 @@ async fn userinfo(cx: &Cx) -> Result { let Some(token) = bearer(headers(cx).get(AUTHORIZATION)) else { return Ok(unauthorized()); }; - let published = signing::published_keys(&app.store).await?; - let keys: Vec = published - .iter() - .filter_map(|key| PublishedKey::new(key.kid.clone(), &key.public_raw)) - .collect(); - let Ok(claims) = jwt::verify(&keys, token) else { + let Some(claims) = signing::verify_access(&app.store, token).await? else { return Ok(unauthorized()); }; let now = unix_now(); diff --git a/crates/im-web/src/sweeper.rs b/crates/im-web/src/sweeper.rs index aa8659d..aa08ec2 100644 --- a/crates/im-web/src/sweeper.rs +++ b/crates/im-web/src/sweeper.rs @@ -4,6 +4,7 @@ //! - authorization codes that expired more than a day ago (a day is kept so that a reused code is still //! recognised as reuse, which revokes the tokens it issued); //! - refresh tokens past their expiry; +//! - revoked access tokens past their expiry (the revocation has done its work by then); //! - directory change rows older than 30 days (a cursor older than the oldest row gets `resync`); //! - account links and invitations past their expiry; //! - sent mail older than 30 days (its body was blanked when it was sent). @@ -60,6 +61,11 @@ pub async fn sweep_once(store: &Store) { Ok(count) => tracing::info!(count, "sweeper: expired refresh tokens removed"), Err(error) => tracing::error!(error = %error, "sweeper: refresh tokens"), } + match store.sweep_revoked_access_tokens(&now).await { + Ok(0) => {} + Ok(count) => tracing::info!(count, "sweeper: expired access token revocations removed"), + Err(error) => tracing::error!(error = %error, "sweeper: access token revocations"), + } match store .prune_directory_changes(&stamp_before(DIRECTORY_KEEP)) .await diff --git a/docs/contracts.md b/docs/contracts.md index c910d5a..f08fbad 100644 --- a/docs/contracts.md +++ b/docs/contracts.md @@ -102,7 +102,7 @@ token), keyed by `sub`, and stores `sid` beside it. The app does not call `im` a `events: {"http://schemas.openid.net/event/backchannel-logout": {}}`, and `sid` (and `sub`). For "disable" and "delete" it carries only `sub`, which means "every session of this user". - The app validates it like an ID token (no `nonce`; it must carry `events` and must not carry `nonce`), - rejects a reused `jti` for 10 minutes, deletes the matching local sessions, and answers `200` with an empty + records each `jti` for 10 minutes (a repeat is already applied: it changes nothing and answers `200`), deletes the matching local sessions, and answers `200` with an empty body. Any other answer is a failure. - `im` delivers through a durable outbox: retries with backoff (10 s, 30 s, 1 min, 5 min, then every 15 min) for 24 hours. Combined with the 12-hour local session cap (2.4), a missed delivery cannot keep a revoked