forge
Explore
Log in

Don't you dare go Hollow

Revoked access tokens refused everywhere, idle live streams re-check the viewer every 15 s, repeated logout jti documented

Browse files at this commit

e787bb29f35dd87c1a99475366da78ef7ba9be31Ahmet Kaan GümüşParent: 924d542
  • fix
    • revoked access tokens refused everywhere, idle live streams re-check the viewer every 15 s, repeated logout jti documented
Show full message
🔒 fix: revoked access tokens refused everywhere, idle live streams re-check the viewer every 15 s, repeated logout jti documented
crates/im-core/migrations/0004_revoked_access_tokens.sqladded+10 -0
@@ -0,0 +1,10 @@
1+-- 0004: the access tokens (by their `jti`) that a client has revoked through /revoke. An access token
2+-- is refused while its jti is listed here. Each row is kept until the token would have expired anyway;
3+-- the sweeper removes rows past expires_at.
4+
5+CREATE TABLE revoked_access_tokens (
6+ jti TEXT PRIMARY KEY NOT NULL,
7+ expires_at TEXT NOT NULL
8+);
9+
10+CREATE INDEX revoked_access_tokens_expires ON revoked_access_tokens (expires_at);
crates/im-core/src/store/migrate.rsmodified+4 -0
@@ -20,6 +20,10 @@ pub const MIGRATIONS: &[(u32, &str)] = &[
20 3,20 3,
21 include_str!("../../migrations/0003_consumed_pending_logins.sql"),21 include_str!("../../migrations/0003_consumed_pending_logins.sql"),
22 ),22 ),
23+ (
24+ 4,
25+ include_str!("../../migrations/0004_revoked_access_tokens.sql"),
26+ ),
23 ];27 ];
24 28
25 fn migration_err(e: turso::Error) -> Error {29 fn migration_err(e: turso::Error) -> Error {
crates/im-core/src/store/mod.rsmodified+1 -1
@@ -353,6 +353,6 @@ mod tests {
353 })353 })
354 .await354 .await
355 .unwrap();355 .unwrap();
356- assert_eq!(applied, vec![1, 2, 3]);356+ assert_eq!(applied, vec![1, 2, 3, 4]);
357 }357 }
358 }358 }
crates/im-core/src/store/oidc.rsmodified+38 -0
@@ -147,6 +147,44 @@ impl Store {
147 .map_err(db_err)147 .map_err(db_err)
148 }148 }
149 149
150+ /// Records the access token `jti` as revoked until `expires_at`, the token's own expiry. Revoking an
151+ /// already revoked token changes nothing.
152+ pub async fn revoke_access_token(&self, jti: &str, expires_at: &str) -> Result<()> {
153+ let conn = self.inner.conn.lock().await;
154+ conn.execute(
155+ "INSERT OR IGNORE INTO revoked_access_tokens (jti, expires_at) VALUES (?1, ?2)",
156+ (jti.to_string(), expires_at.to_string()),
157+ )
158+ .await
159+ .map_err(db_err)?;
160+ Ok(())
161+ }
162+
163+ /// True when the access token `jti` was revoked and the revocation has not yet been swept.
164+ pub async fn access_token_revoked(&self, jti: &str) -> Result<bool> {
165+ let conn = self.read_conn().await;
166+ let row = fetch_opt(
167+ &conn,
168+ "SELECT jti FROM revoked_access_tokens WHERE jti = ?1",
169+ (jti.to_string(),),
170+ |row| col_text(row, 0),
171+ )
172+ .await?;
173+ Ok(row.is_some())
174+ }
175+
176+ /// Deletes the revocations of access tokens that expired before `now`: such a token is refused by its
177+ /// expiry already. Run by the sweeper.
178+ pub async fn sweep_revoked_access_tokens(&self, now: &str) -> Result<u64> {
179+ let conn = self.inner.conn.lock().await;
180+ conn.execute(
181+ "DELETE FROM revoked_access_tokens WHERE expires_at < ?1",
182+ (now.to_string(),),
183+ )
184+ .await
185+ .map_err(db_err)
186+ }
187+
150 pub async fn insert_auth_code(&self, new: &NewAuthCode<'_>) -> Result<()> {188 pub async fn insert_auth_code(&self, new: &NewAuthCode<'_>) -> Result<()> {
151 let conn = self.inner.conn.lock().await;189 let conn = self.inner.conn.lock().await;
152 conn.execute(190 conn.execute(
crates/im-core/src/time.rsmodified+7 -0
@@ -68,6 +68,13 @@ pub fn unix_now() -> i64 {
68 OffsetDateTime::now_utc().unix_timestamp()68 OffsetDateTime::now_utc().unix_timestamp()
69 }69 }
70 70
71+/// The stamp of a Unix time in whole seconds. `None` when the time is out of range.
72+pub fn stamp_of_unix(seconds: i64) -> Option<String> {
73+ OffsetDateTime::from_unix_timestamp(seconds)
74+ .ok()
75+ .map(format_stamp)
76+}
77+
71 /// The IANA time zone names of the database compiled into this build, sorted. The bundled database78 /// The IANA time zone names of the database compiled into this build, sorted. The bundled database
72 /// is used on purpose, so every install offers the same list whatever the host has installed.79 /// is used on purpose, so every install offers the same list whatever the host has installed.
73 pub fn zone_names() -> Vec<String> {80 pub fn zone_names() -> Vec<String> {
crates/im-web/src/api/machine_auth.rsmodified+2 -7
@@ -7,7 +7,7 @@
7 //! access token and an ID token fail one of these checks, so they never open a machine route.7 //! access token and an ID token fail one of these checks, so they never open a machine route.
8 8
9 use http::header::AUTHORIZATION;9 use http::header::AUTHORIZATION;
10-use im_core::jwt::{self, PublishedKey};10+use im_core::jwt;
11 use im_core::oauth::is_valid_family_key;11 use im_core::oauth::is_valid_family_key;
12 use im_core::time::unix_now;12 use im_core::time::unix_now;
13 use serde_json::Value;13 use serde_json::Value;
@@ -49,12 +49,7 @@ pub async fn require(
49 let Some(token) = bearer(headers(cx).get(AUTHORIZATION)) else {49 let Some(token) = bearer(headers(cx).get(AUTHORIZATION)) else {
50 return Ok(Err(refused()));50 return Ok(Err(refused()));
51 };51 };
52- let published = signing::published_keys(&app.store).await?;52+ let Some(claims) = signing::verify_access(&app.store, token).await? else {
53- let keys: Vec<PublishedKey> = published
54- .iter()
55- .filter_map(|key| PublishedKey::new(key.kid.clone(), &key.public_raw))
56- .collect();
57- let Ok(claims) = jwt::verify(&keys, token) else {
58 return Ok(Err(refused()));53 return Ok(Err(refused()));
59 };54 };
60 // The audience must be exactly the string `im`. `check_claims` also checks it, and the exp and iat.55 // The audience must be exactly the string `im`. `check_claims` also checks it, and the exp and iat.
crates/im-web/src/live.rsmodified+4 -0
@@ -40,6 +40,9 @@ pub const KEEP_ALIVE: Duration = Duration::from_secs(30);
40 /// Longest a stream lives, whatever happens on it. The browser reconnects after it, and a reconnect40 /// Longest a stream lives, whatever happens on it. The browser reconnects after it, and a reconnect
41 /// authenticates and authorises again, so a session that ended or lost its role is not kept by a stream.41 /// authenticates and authorises again, so a session that ended or lost its role is not kept by a stream.
42 pub const MAX_STREAM_LIFE: Duration = Duration::from_secs(60 * 60);42 pub const MAX_STREAM_LIFE: Duration = Duration::from_secs(60 * 60);
43+/// How often an idle `changed` stream runs its fingerprint anyway, so a viewer who signed out or lost
44+/// access is noticed even when no topic of the stream changes.
45+pub const RECHECK: Duration = Duration::from_secs(15);
43 46
44 /// Anonymous `/-/alive` streams open at once, across the whole process. A further one gets `429`.47 /// Anonymous `/-/alive` streams open at once, across the whole process. A further one gets `429`.
45 pub const MAX_ANONYMOUS_STREAMS: usize = 256;48 pub const MAX_ANONYMOUS_STREAMS: usize = 256;
@@ -145,6 +148,7 @@ where
145 woke = wait_any(&mut follow.wakes) => woke,148 woke = wait_any(&mut follow.wakes) => woke,
146 () = stopped(&mut follow.stop) => false,149 () = stopped(&mut follow.stop) => false,
147 () = tokio::time::sleep_until(follow.until) => false,150 () = tokio::time::sleep_until(follow.until) => false,
151+ () = tokio::time::sleep(RECHECK) => true,
148 };152 };
149 if !woke {153 if !woke {
150 return None;154 return None;
crates/im-web/src/oidc/introspect.rsmodified+5 -9
@@ -7,7 +7,7 @@
7 //! and account are. A refresh token is active while it is unused, unrevoked and unexpired, and its7 //! and account are. A refresh token is active while it is unused, unrevoked and unexpired, and its
8 //! session is live. The client authenticates like at `/token`.8 //! session is live. The client authenticates like at `/token`.
9 9
10-use im_core::jwt::{self, PublishedKey};10+use im_core::jwt;
11 use im_core::model::Client;11 use im_core::model::Client;
12 use im_core::time::{now_stamp, unix_now, unix_seconds};12 use im_core::time::{now_stamp, unix_now, unix_seconds};
13 use im_core::token::hash_token;13 use im_core::token::hash_token;
@@ -40,15 +40,11 @@ async fn introspect(cx: &Cx, body: Body) -> Result<Response> {
40 Ok(json_response(StatusCode::OK, &answer))40 Ok(json_response(StatusCode::OK, &answer))
41 }41 }
42 42
43-/// The answer for an access token of ours. `None` when the text is not a token of this provider, so the43+/// The answer for an access token of ours. `None` when the text is not an access token of this provider
44-/// caller tries the refresh tokens.44+/// that is still unrevoked, so the caller tries the refresh tokens. A revoked access token is therefore
45+/// answered by the refresh lookup, which finds nothing and reports it inactive.
45 async fn access_answer(app: &AppState, client: &Client, token: &str) -> Result<Option<Value>> {46 async fn access_answer(app: &AppState, client: &Client, token: &str) -> Result<Option<Value>> {
46- let published = signing::published_keys(&app.store).await?;47+ let Some(claims) = signing::verify_access(&app.store, token).await? else {
47- let keys: Vec<PublishedKey> = published
48- .iter()
49- .filter_map(|key| PublishedKey::new(key.kid.clone(), &key.public_raw))
50- .collect();
51- let Ok(claims) = jwt::verify(&keys, token) else {
52 return Ok(None);48 return Ok(None);
53 };49 };
54 let now = unix_now();50 let now = unix_now();
crates/im-web/src/oidc/revoke.rsmodified+44 -9
@@ -1,20 +1,26 @@
1-//! `POST /revoke` (RFC 7009): a client gives back one of its own refresh tokens, and the whole chain of1+//! `POST /revoke` (RFC 7009): a client gives back one of its own tokens, and that token stops working.
2-//! that token is revoked.2+//!
3+//! A refresh token revokes its whole chain. An access token is recorded by its `jti` until its own expiry
4+//! (`revoked_access_tokens`), so `/userinfo`, `/introspect` and the machine routes refuse it at once. Only an
5+//! access token issued to the authenticated client (`azp`) is recorded; an expired one needs nothing, since
6+//! it is refused by its expiry already.
3 //!7 //!
4 //! The client authenticates like at `/token`. The answer is `200` with an empty body for every token: a8 //! The client authenticates like at `/token`. The answer is `200` with an empty body for every token: a
5 //! token that is unknown, belongs to another client, or is already revoked gets the same answer, so the9 //! token that is unknown, belongs to another client, or is already revoked gets the same answer, so the
6-//! endpoint does not reveal which tokens exist (RFC 7009 section 2.2). Access tokens need no table here:10+//! endpoint does not reveal which tokens exist (RFC 7009 section 2.2).
7-//! they live ten minutes and are refused at once when their session ends, so revoking the session is the
8-//! way to end them.
9 11
12+use im_core::jwt;
13+use im_core::model::Client;
14+use im_core::time::{stamp_of_unix, unix_now};
10 use im_core::token::hash_token;15 use im_core::token::hash_token;
16+use serde_json::Value;
11 use topcoat::Result;17 use topcoat::Result;
12 use topcoat::context::Cx;18 use topcoat::context::Cx;
13 use topcoat::router::response::Response;19 use topcoat::router::response::Response;
14 use topcoat::router::{Body, StatusCode, route};20 use topcoat::router::{Body, StatusCode, route};
15 21
16 use super::token::client_form;22 use super::token::client_form;
17-use super::{oauth_error, one};23+use super::{issuer, oauth_error, one, signing};
18 use crate::state::AppState;24 use crate::state::AppState;
19 use topcoat::context::app_context;25 use topcoat::context::app_context;
20 26
@@ -29,12 +35,41 @@ async fn revoke(cx: &Cx, body: Body) -> Result<Response> {
29 let Some(token) = one(&pairs, "token") else {35 let Some(token) = one(&pairs, "token") else {
30 return Ok(oauth_error(StatusCode::BAD_REQUEST, "invalid_request"));36 return Ok(oauth_error(StatusCode::BAD_REQUEST, "invalid_request"));
31 };37 };
32- if let Some(row) = app.store.refresh_token(&hash_token(token)).await?38+ match app.store.refresh_token(&hash_token(token)).await? {
33- && row.client_id == client.id39+ Some(row) => {
34- {40+ if row.client_id == client.id {
35 app.store.revoke_refresh_family(&row.family_id).await?;41 app.store.revoke_refresh_family(&row.family_id).await?;
36 }42 }
43+ }
44+ None => revoke_access(app, &client, token).await?,
45+ }
37 let mut response = Response::new(Body::empty());46 let mut response = Response::new(Body::empty());
38 *response.status_mut() = StatusCode::OK;47 *response.status_mut() = StatusCode::OK;
39 Ok(response)48 Ok(response)
40 }49 }
50+
51+/// Records an access token of ours as revoked. Anything else, including an expired token, changes nothing.
52+async fn revoke_access(app: &AppState, client: &Client, token: &str) -> Result<()> {
53+ let Some(claims) = signing::verify_access(&app.store, token).await? else {
54+ return Ok(());
55+ };
56+ if jwt::check_issuer(&claims, issuer(app)).is_err()
57+ || claims.get("azp").and_then(Value::as_str) != Some(client.id.as_str())
58+ {
59+ return Ok(());
60+ }
61+ let (Some(jti), Some(exp)) = (
62+ claims.get("jti").and_then(Value::as_str),
63+ claims.get("exp").and_then(Value::as_i64),
64+ ) else {
65+ return Ok(());
66+ };
67+ if exp <= unix_now() {
68+ return Ok(());
69+ }
70+ let Some(expires_at) = stamp_of_unix(exp) else {
71+ return Ok(());
72+ };
73+ app.store.revoke_access_token(jti, &expires_at).await?;
74+ Ok(())
75+}
crates/im-web/src/oidc/signing.rsmodified+27 -2
@@ -8,13 +8,13 @@
8 use std::sync::Arc;8 use std::sync::Arc;
9 use std::time::Duration;9 use std::time::Duration;
10 10
11-use im_core::jwt;11+use im_core::jwt::{self, PublishedKey};
12 use im_core::keys::{self, OVERLAP};12 use im_core::keys::{self, OVERLAP};
13 use im_core::model::KeyRecord;13 use im_core::model::KeyRecord;
14 use im_core::secret;14 use im_core::secret;
15 use im_core::store::Store;15 use im_core::store::Store;
16 use im_core::time::{now_stamp, stamp_minus, stamp_plus};16 use im_core::time::{now_stamp, stamp_minus, stamp_plus};
17-use serde_json::Value;17+use serde_json::{Map, Value};
18 use tokio::sync::watch;18 use tokio::sync::watch;
19 19
20 /// How often the worker checks the chain of keys.20 /// How often the worker checks the chain of keys.
@@ -96,6 +96,31 @@ pub async fn published_keys(store: &Store) -> im_core::Result<Vec<KeyRecord>> {
96 .collect())96 .collect())
97 }97 }
98 98
99+/// Verifies an access token this provider issued: its signature against the published keys, and that its
100+/// `jti` has not been revoked (`/revoke`). Returns the claims, or `None` when the token is not ours, is
101+/// forged, has no `jti`, or was revoked. The caller still checks `iss`, `aud`, `exp` and what the token
102+/// grants, with `jwt::check_claims`.
103+pub async fn verify_access(
104+ store: &Store,
105+ token: &str,
106+) -> im_core::Result<Option<Map<String, Value>>> {
107+ let published = published_keys(store).await?;
108+ let keys: Vec<PublishedKey> = published
109+ .iter()
110+ .filter_map(|key| PublishedKey::new(key.kid.clone(), &key.public_raw))
111+ .collect();
112+ let Ok(claims) = jwt::verify(&keys, token) else {
113+ return Ok(None);
114+ };
115+ let Some(jti) = claims.get("jti").and_then(Value::as_str) else {
116+ return Ok(None);
117+ };
118+ if store.access_token_revoked(jti).await? {
119+ return Ok(None);
120+ }
121+ Ok(Some(claims))
122+}
123+
99 /// Signs `claims` with the key that is current now.124 /// Signs `claims` with the key that is current now.
100 pub async fn sign(125 pub async fn sign(
101 store: &Store,126 store: &Store,
crates/im-web/src/oidc/tests.rsmodified+42 -0
@@ -416,6 +416,48 @@ async fn introspection_reports_a_token_inactive_for_any_client_but_its_own() {
416 assert_eq!(foreign, serde_json::json!({ "active": false }));416 assert_eq!(foreign, serde_json::json!({ "active": false }));
417 }417 }
418 418
419+#[tokio::test]
420+async fn a_revoked_access_token_is_refused_by_userinfo_and_introspection() {
421+ let f = fixture().await;
422+ let verifier = generate_token();
423+ let code = code_for(&f, &f.client, &verifier).await;
424+ let (status, issued) = token_with(&f, &f.client, &f.secret, &code_body(&code, &verifier)).await;
425+ assert_eq!(status, StatusCode::OK, "{issued}");
426+ let access = issued["access_token"]
427+ .as_str()
428+ .expect("access token")
429+ .to_owned();
430+ let userinfo = || {
431+ let request = http::Request::get("/userinfo")
432+ .header(AUTHORIZATION, format!("Bearer {access}"))
433+ .body(Body::empty())
434+ .expect("request");
435+ send(&f.state, request)
436+ };
437+ assert_eq!(userinfo().await.0, StatusCode::OK);
438+
439+ let (status, _) = post_as(
440+ &f,
441+ "/revoke",
442+ &f.client,
443+ &f.secret,
444+ &format!("token={access}"),
445+ )
446+ .await;
447+ assert_eq!(status, StatusCode::OK);
448+ assert_eq!(userinfo().await.0, StatusCode::UNAUTHORIZED);
449+ let (status, answer) = post_as(
450+ &f,
451+ "/introspect",
452+ &f.client,
453+ &f.secret,
454+ &format!("token={access}"),
455+ )
456+ .await;
457+ assert_eq!(status, StatusCode::OK);
458+ assert_eq!(answer, serde_json::json!({ "active": false }));
459+}
460+
419 /// The ID token of a fresh sign-in of the fixture's person, and the code exchange's session id.461 /// The ID token of a fresh sign-in of the fixture's person, and the code exchange's session id.
420 async fn id_token_of(f: &Fixture) -> String {462 async fn id_token_of(f: &Fixture) -> String {
421 let verifier = generate_token();463 let verifier = generate_token();
crates/im-web/src/oidc/userinfo.rsmodified+2 -7
@@ -6,7 +6,7 @@
6 //! names: a session that ended, or a disabled account, refuses the token at once, even before it expires.6 //! names: a session that ended, or a disabled account, refuses the token at once, even before it expires.
7 7
8 use http::header::{AUTHORIZATION, HeaderValue, WWW_AUTHENTICATE};8 use http::header::{AUTHORIZATION, HeaderValue, WWW_AUTHENTICATE};
9-use im_core::jwt::{self, PublishedKey};9+use im_core::jwt;
10 use im_core::time::unix_now;10 use im_core::time::unix_now;
11 use serde_json::{Value, json};11 use serde_json::{Value, json};
12 use topcoat::Result;12 use topcoat::Result;
@@ -27,12 +27,7 @@ async fn userinfo(cx: &Cx) -> Result<Response> {
27 let Some(token) = bearer(headers(cx).get(AUTHORIZATION)) else {27 let Some(token) = bearer(headers(cx).get(AUTHORIZATION)) else {
28 return Ok(unauthorized());28 return Ok(unauthorized());
29 };29 };
30- let published = signing::published_keys(&app.store).await?;30+ let Some(claims) = signing::verify_access(&app.store, token).await? else {
31- let keys: Vec<PublishedKey> = published
32- .iter()
33- .filter_map(|key| PublishedKey::new(key.kid.clone(), &key.public_raw))
34- .collect();
35- let Ok(claims) = jwt::verify(&keys, token) else {
36 return Ok(unauthorized());31 return Ok(unauthorized());
37 };32 };
38 let now = unix_now();33 let now = unix_now();
crates/im-web/src/sweeper.rsmodified+6 -0
@@ -4,6 +4,7 @@
4 //! - authorization codes that expired more than a day ago (a day is kept so that a reused code is still4 //! - authorization codes that expired more than a day ago (a day is kept so that a reused code is still
5 //! recognised as reuse, which revokes the tokens it issued);5 //! recognised as reuse, which revokes the tokens it issued);
6 //! - refresh tokens past their expiry;6 //! - refresh tokens past their expiry;
7+//! - revoked access tokens past their expiry (the revocation has done its work by then);
7 //! - directory change rows older than 30 days (a cursor older than the oldest row gets `resync`);8 //! - directory change rows older than 30 days (a cursor older than the oldest row gets `resync`);
8 //! - account links and invitations past their expiry;9 //! - account links and invitations past their expiry;
9 //! - sent mail older than 30 days (its body was blanked when it was sent).10 //! - 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) {
60 Ok(count) => tracing::info!(count, "sweeper: expired refresh tokens removed"),61 Ok(count) => tracing::info!(count, "sweeper: expired refresh tokens removed"),
61 Err(error) => tracing::error!(error = %error, "sweeper: refresh tokens"),62 Err(error) => tracing::error!(error = %error, "sweeper: refresh tokens"),
62 }63 }
64+ match store.sweep_revoked_access_tokens(&now).await {
65+ Ok(0) => {}
66+ Ok(count) => tracing::info!(count, "sweeper: expired access token revocations removed"),
67+ Err(error) => tracing::error!(error = %error, "sweeper: access token revocations"),
68+ }
63 match store69 match store
64 .prune_directory_changes(&stamp_before(DIRECTORY_KEEP))70 .prune_directory_changes(&stamp_before(DIRECTORY_KEEP))
65 .await71 .await
docs/contracts.mdmodified+1 -1
@@ -102,7 +102,7 @@ token), keyed by `sub`, and stores `sid` beside it. The app does not call `im` a
102 `events: {"http://schemas.openid.net/event/backchannel-logout": {}}`, and `sid` (and `sub`). For "disable" and102 `events: {"http://schemas.openid.net/event/backchannel-logout": {}}`, and `sid` (and `sub`). For "disable" and
103 "delete" it carries only `sub`, which means "every session of this user".103 "delete" it carries only `sub`, which means "every session of this user".
104 - The app validates it like an ID token (no `nonce`; it must carry `events` and must not carry `nonce`),104 - The app validates it like an ID token (no `nonce`; it must carry `events` and must not carry `nonce`),
105- rejects a reused `jti` for 10 minutes, deletes the matching local sessions, and answers `200` with an empty105+ 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
106 body. Any other answer is a failure.106 body. Any other answer is a failure.
107 - `im` delivers through a durable outbox: retries with backoff (10 s, 30 s, 1 min, 5 min, then every 15 min)107 - `im` delivers through a durable outbox: retries with backoff (10 s, 30 s, 1 min, 5 min, then every 15 min)
108 for 24 hours. Combined with the 12-hour local session cap (2.4), a missed delivery cannot keep a revoked108 for 24 hours. Combined with the 12-hour local session cap (2.4), a missed delivery cannot keep a revoked