From f94f61ebb81e47937563778ad9636b34122d74ed 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:07 +0300 Subject: [PATCH] =?UTF-8?q?=F0=9F=94=92=20fix:=20JWKS=20fetched=20outside?= =?UTF-8?q?=20the=20key=20lock=20after=20a=20header=20check,=20nbf=20enfor?= =?UTF-8?q?ced,=20capped=20directory=20reads,=20bounded=20photo=20fetch,?= =?UTF-8?q?=20calmer=20reconnects,=20replayed=20logout=20answers=20200,=20?= =?UTF-8?q?unique=20cache=20temp=20names?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Cargo.lock | 1 + crates/in-web/Cargo.toml | 1 + crates/in-web/src/directory.rs | 87 +++++++--- crates/in-web/src/oidc.rs | 223 +++++++++++++++++-------- crates/in-web/src/pages/backchannel.rs | 16 +- crates/in-web/src/pages/photo.rs | 20 +-- docs/contracts.md | 2 +- 7 files changed, 235 insertions(+), 115 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index e971124..ee6852f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2004,6 +2004,7 @@ dependencies = [ "topcoat", "tracing", "tracing-subscriber", + "ulid", ] [[package]] diff --git a/crates/in-web/Cargo.toml b/crates/in-web/Cargo.toml index 31e69a7..3b58e3d 100644 --- a/crates/in-web/Cargo.toml +++ b/crates/in-web/Cargo.toml @@ -33,6 +33,7 @@ tokio = { workspace = true, features = ["net", "signal", "time", "sync", "fs", " topcoat.workspace = true tracing.workspace = true tracing-subscriber = { workspace = true, features = ["env-filter"] } +ulid.workspace = true [dev-dependencies] serde_urlencoded.workspace = true diff --git a/crates/in-web/src/directory.rs b/crates/in-web/src/directory.rs index 780f5d2..c622bda 100644 --- a/crates/in-web/src/directory.rs +++ b/crates/in-web/src/directory.rs @@ -8,10 +8,12 @@ //! //! When the stream fails, the worker waits with exponential backoff from 1 s to 60 s, each wait a random //! point between half of the step and the whole step, so a restarted `im` is not hit all at once. A stream that ends -//! on its own (the 50-minute close of contracts section 3.2) is reconnected after one second. +//! on its own (the 50-minute close of contracts section 3.2) is reconnected after one second, provided it +//! carried events or stayed open for a minute. A stream that closes at once without events is retried with +//! the backoff, so a proxy that keeps closing connections cannot make the worker reconnect every second. use std::collections::HashSet; -use std::time::Duration; +use std::time::{Duration, Instant}; use futures_util::StreamExt; use http::header::ACCEPT; @@ -20,7 +22,7 @@ use in_core::time::now_stamp; use serde::Deserialize; use tokio::sync::watch; -use crate::oidc::{OidcClient, OidcError}; +use crate::oidc::{OidcClient, OidcError, read_limited}; use crate::state::AppState; /// The `settings` key of the directory cursor. @@ -35,6 +37,16 @@ const BACKOFF_MAX: Duration = Duration::from_secs(60); /// The pause after a stream that ended cleanly, before it is reconnected. const CLEAN_PAUSE: Duration = Duration::from_secs(1); +/// How long a stream must stay open, with no event at all, to count as healthy. A quiet directory keeps +/// a stream open for a long time without events, so that is not a failure. +const QUIET_STREAM_HEALTHY: Duration = Duration::from_secs(60); + +/// The largest full listing the mirror reads. Matches the cap that `iz` uses for the same listing. +const ROSTER_MAX_BYTES: usize = 8 * 1024 * 1024; + +/// The largest single event, and the longest line, the stream may carry. A longer one ends the stream. +const MAX_STREAM_BYTES: usize = 64 * 1024; + /// Why one round of syncing failed. #[derive(Debug, thiserror::Error)] enum SyncError { @@ -53,6 +65,9 @@ enum SyncError { /// The full directory could not be read. #[error("the directory listing is not what the contracts describe")] Listing, + /// `im` sent more than the mirror accepts, in one answer or one event. + #[error("im sent more than the mirror accepts")] + TooLarge, } /// One member as the directory sends it (contracts section 3.1). Unknown fields are ignored. @@ -111,8 +126,9 @@ struct SseParser { impl SseParser { /// Adds bytes and returns the events they complete. A blank line ends an event; lines that start - /// with `:` are comments (keep-alives) and are skipped. - fn push(&mut self, chunk: &[u8]) -> Vec { + /// with `:` are comments (keep-alives) and are skipped. An event or a line over + /// [`MAX_STREAM_BYTES`] is an error, so a hostile stream cannot grow the buffers without bound. + fn push(&mut self, chunk: &[u8]) -> Result, SyncError> { self.buffer.extend_from_slice(chunk); let mut events = Vec::new(); while let Some(end) = self.buffer.iter().position(|byte| *byte == b'\n') { @@ -144,12 +160,20 @@ impl SseParser { }; match field { "event" => self.event = value.to_owned(), - "data" => self.data.push(value.to_owned()), + "data" => { + self.data.push(value.to_owned()); + if self.data.iter().map(String::len).sum::() > MAX_STREAM_BYTES { + return Err(SyncError::TooLarge); + } + } "id" => self.id = Some(value.to_owned()), _ => {} } } - events + if self.buffer.len() > MAX_STREAM_BYTES { + return Err(SyncError::TooLarge); + } + Ok(events) } } @@ -157,8 +181,16 @@ impl SseParser { enum Ended { /// The server asked for a full fetch. Resync, - /// The stream closed (the server's 50-minute close, or a stop). - Closed, + /// The stream closed (the server's 50-minute close, or a stop). `healthy` is false for a stream + /// that closed at once without events, which counts as a failure for the backoff. + Closed { healthy: bool }, +} + +/// The outcome of a stream that closed on its own, judged by what it did before it closed. +fn closed(opened: Instant, applied: bool) -> Ended { + Ended::Closed { + healthy: applied || opened.elapsed() >= QUIET_STREAM_HEALTHY, + } } /// Runs the mirror until `stop` is set. Does nothing without an OIDC client. @@ -178,10 +210,15 @@ pub async fn run(state: AppState, mut stop: watch::Receiver) { backoff = BACKOFF_FIRST; CLEAN_PAUSE } - Ok(Ended::Closed) => { + Ok(Ended::Closed { healthy: true }) => { backoff = BACKOFF_FIRST; CLEAN_PAUSE } + Ok(Ended::Closed { healthy: false }) => { + let pause = jittered(backoff); + backoff = (backoff * 2).min(BACKOFF_MAX); + pause + } Err(error) => { tracing::warn!(error = %error, "directory: sync failed, retrying"); needs_full = true; @@ -225,10 +262,10 @@ async fn full_sync(state: &AppState, oidc: &OidcClient) -> Result<(), SyncError> if !response.status().is_success() { return Err(SyncError::Status(response.status())); } - let bytes = response - .bytes() + let bytes = read_limited(response, ROSTER_MAX_BYTES) .await - .map_err(|e| SyncError::Transport(e.to_string()))?; + .map_err(|e| SyncError::Transport(e.to_string()))? + .ok_or(SyncError::TooLarge)?; let listing: Listing = serde_json::from_slice(&bytes).map_err(|_| SyncError::Listing)?; let mut named = HashSet::new(); @@ -274,18 +311,21 @@ async fn follow( } tracing::info!("directory: stream connected"); + let opened = Instant::now(); + let mut applied = false; let mut body = response.bytes_stream(); let mut parser = SseParser::default(); loop { let chunk = tokio::select! { chunk = body.next() => chunk, - _ = stop.wait_for(|stopped| *stopped) => return Ok(Ended::Closed), + _ = stop.wait_for(|stopped| *stopped) => return Ok(closed(opened, applied)), }; let Some(chunk) = chunk else { - return Ok(Ended::Closed); + return Ok(closed(opened, applied)); }; let chunk = chunk.map_err(|e| SyncError::Transport(e.to_string()))?; - for event in parser.push(&chunk) { + for event in parser.push(&chunk)? { + applied = true; if let Some(ended) = apply_event(state, event).await? { return Ok(ended); } @@ -400,8 +440,15 @@ mod tests { #[test] fn events_are_parsed_across_chunks_and_comments_are_skipped() { let mut parser = SseParser::default(); - assert!(parser.push(b": keep-alive\nid: 7\nevent: mem").is_empty()); - let events = parser.push(b"ber\ndata: {\"sub\":\"a\"}\n\n"); + assert!( + parser + .push(b": keep-alive\nid: 7\nevent: mem") + .expect("bytes") + .is_empty() + ); + let events = parser + .push(b"ber\ndata: {\"sub\":\"a\"}\n\n") + .expect("bytes"); assert_eq!( events, vec![SseEvent { @@ -410,7 +457,9 @@ mod tests { data: "{\"sub\":\"a\"}".into(), }] ); - let events = parser.push(b"event: resync\ndata: {}\r\n\r\n"); + let events = parser + .push(b"event: resync\ndata: {}\r\n\r\n") + .expect("bytes"); assert_eq!(events[0].event, "resync"); } diff --git a/crates/in-web/src/oidc.rs b/crates/in-web/src/oidc.rs index 6a5073d..b6c7c1d 100644 --- a/crates/in-web/src/oidc.rs +++ b/crates/in-web/src/oidc.rs @@ -18,7 +18,7 @@ use in_core::config::Oidc; use in_core::error::{Error as CoreError, Result as CoreResult}; use in_core::token::constant_time_eq; use jsonwebtoken::errors::ErrorKind; -use jsonwebtoken::{Algorithm, DecodingKey, Validation, decode, decode_header}; +use jsonwebtoken::{Algorithm, DecodingKey, Validation, decode}; use serde::Deserialize; use serde_json::{Map, Value}; use sha2::{Digest, Sha256}; @@ -33,8 +33,9 @@ pub const MAX_FUTURE_IAT_SECS: i64 = 300; /// How long a fetched key set is used before it is fetched again (contracts section 2.2). pub const JWKS_MAX_AGE: Duration = Duration::from_secs(60 * 60); -/// The shortest gap between two key fetches caused by an unknown `kid`. Protects `im` from a flood of -/// tokens that name keys that do not exist. +/// The shortest gap between two key fetches. A fetch for an unknown `kid`, and a retry after a failed +/// fetch, both wait this long. It is the one-minute refetch limit of contracts section 2.2, and it +/// protects `im` from a flood of tokens that name keys that do not exist. pub const JWKS_REFRESH_GAP: Duration = Duration::from_secs(60); /// How long a failed discovery is not retried. Until it succeeds the standard paths are used. @@ -274,31 +275,48 @@ fn check_iat(claims: &Map, now: i64) -> Result<(), TokenError> { Ok(()) } -/// Checks the algorithm, the key id, the signature, the issuer and the expiry, and returns the claims. -/// Audience, nonce and the rest are the job of the callers, which know what they expect. +/// Reads the protected header of `token` and refuses what `in` can never verify: the token must have +/// three segments, the header must name EdDSA, and it must carry a `kid`. Returns the `kid`. /// -/// The algorithm is read from the raw header first, so `none` and any other algorithm are refused -/// before a library sees the token. -pub fn verify_signed( - keys: &KeySet, - token: &str, - issuer: &str, -) -> Result, TokenError> { - let first_segment = token.split('.').next().ok_or(TokenError::Malformed)?; +/// The algorithm is read from the raw header, so `none` and any other algorithm are refused before a +/// library sees the token. Callers run this before any key is fetched, so a token that cannot verify +/// costs no network call. +pub fn check_header(token: &str) -> Result { + let segments: Vec<&str> = token.split('.').collect(); + if segments.len() != 3 { + return Err(TokenError::Malformed); + } let header_bytes = BASE64_URL_SAFE_NO_PAD - .decode(first_segment) + .decode(segments[0]) .map_err(|_| TokenError::Malformed)?; let header: Value = serde_json::from_slice(&header_bytes).map_err(|_| TokenError::Malformed)?; if header.get("alg").and_then(Value::as_str) != Some("EdDSA") { return Err(TokenError::Algorithm); } - let parsed = decode_header(token).map_err(|_| TokenError::Malformed)?; - let kid = parsed.kid.ok_or(TokenError::NoKeyId)?; + header + .get("kid") + .and_then(Value::as_str) + .filter(|kid| !kid.is_empty()) + .map(str::to_owned) + .ok_or(TokenError::NoKeyId) +} + +/// Checks the algorithm, the key id, the signature, the issuer, the expiry and the not-before time, and +/// returns the claims. Audience, nonce and the rest are the job of the callers, which know what they +/// expect. +pub fn verify_signed( + keys: &KeySet, + token: &str, + issuer: &str, +) -> Result, TokenError> { + let kid = check_header(token)?; let key = keys.get(&kid).ok_or(TokenError::UnknownKey)?; let mut validation = Validation::new(Algorithm::EdDSA); validation.leeway = u64::try_from(CLOCK_LEEWAY_SECS).unwrap_or(0); validation.validate_exp = true; + // A token whose `nbf` lies beyond the leeway is not valid yet. A token without `nbf` is unaffected. + validation.validate_nbf = true; // Audience is checked by the callers, because the rule differs by token kind. validation.validate_aud = false; validation.set_issuer(&[issuer]); @@ -312,6 +330,7 @@ pub fn verify_signed( ErrorKind::InvalidSignature => TokenError::Signature, ErrorKind::InvalidIssuer => TokenError::Claim("iss"), ErrorKind::InvalidAlgorithm => TokenError::Algorithm, + ErrorKind::ImmatureSignature => TokenError::Claim("nbf"), ErrorKind::MissingRequiredClaim(_) => TokenError::Claim("required claim"), _ => TokenError::Malformed, } @@ -512,6 +531,29 @@ pub fn pkce_challenge(verifier: &str) -> String { BASE64_URL_SAFE_NO_PAD.encode(Sha256::digest(verifier.as_bytes())) } +/// Reads a response body of at most `limit` bytes. Returns `None` when the body is larger, and stops +/// reading as soon as it is, so a server that lies about its length cannot make `in` hold more than +/// `limit` bytes. +pub async fn read_limited( + mut response: reqwest::Response, + limit: usize, +) -> Result>, reqwest::Error> { + if response + .content_length() + .is_some_and(|len| len > u64::try_from(limit).unwrap_or(u64::MAX)) + { + return Ok(None); + } + let mut body = Vec::new(); + while let Some(chunk) = response.chunk().await? { + if body.len() + chunk.len() > limit { + return Ok(None); + } + body.extend_from_slice(&chunk); + } + Ok(Some(body)) +} + /// Percent-encodes one value for a query, a form body or a Basic credential (RFC 6749 section 2.3.1): /// unreserved characters pass, everything else becomes `%XX`. pub fn percent_encode(value: &str) -> String { @@ -537,8 +579,8 @@ struct TokenResponse { expires_in: Option, } -/// Cached state of the client. Every field is behind one lock, and no method holds it while it -/// takes it again. +/// Cached state of the client. Every field is behind one lock. No method holds it across a network +/// call, and no method holds it while it takes it again. #[derive(Default)] struct Cache { /// The endpoints from discovery, once fetched. @@ -554,6 +596,26 @@ struct Cache { service: Option<(String, Instant)>, } +/// What the cache answers for the key set, without the network. `None` means a fetch is due. +/// +/// A fresh set is used as it is unless a refetch is forced. Any set, fresh or stale, is also used while +/// the last fetch attempt is younger than [`JWKS_REFRESH_GAP`]. That rate-limits forced refetches for +/// unknown key ids and retries after a failed refetch alike. With no set at all, a recent failure is an +/// answer of its own, so requests do not each wait for `im` again. +fn keys_from_cache(cache: &Cache, force: bool) -> Option, OidcError>> { + let recently_tried = cache + .keys_refresh_at + .is_some_and(|at| at.elapsed() < JWKS_REFRESH_GAP); + match &cache.keys { + Some((at, keys)) if at.elapsed() < JWKS_MAX_AGE && !force => Some(Ok(Arc::clone(keys))), + Some((_, keys)) if recently_tried => Some(Ok(Arc::clone(keys))), + None if recently_tried => Some(Err(OidcError::Unavailable( + "the signing keys are not available yet".to_owned(), + ))), + _ => None, + } +} + /// The OpenID Connect client. One per process, shared through the app state. pub struct OidcClient { issuer: String, @@ -563,6 +625,9 @@ pub struct OidcClient { http: reqwest::Client, stream_http: reqwest::Client, cache: Mutex, + /// Held while the key set is fetched. One fetch runs at a time, and the requests that wait for it + /// read the result from the cache. It is never held while `cache` is held. + refresh: Mutex<()>, } impl OidcClient { @@ -590,6 +655,7 @@ impl OidcClient { http, stream_http, cache: Mutex::new(Cache::default()), + refresh: Mutex::new(()), }) } @@ -611,28 +677,34 @@ impl OidcClient { /// The endpoints of `im`. Fetched from discovery once; when discovery fails, the standard paths /// under the issuer are used and discovery is retried after [`DISCOVERY_RETRY_GAP`]. pub async fn endpoints(&self) -> Arc { - let mut cache = self.cache.lock().await; - if let Some(endpoints) = &cache.endpoints { - return Arc::clone(endpoints); + { + let cache = self.cache.lock().await; + if let Some(endpoints) = &cache.endpoints { + return Arc::clone(endpoints); + } + if cache + .discovery_failed_at + .is_some_and(|at| at.elapsed() < DISCOVERY_RETRY_GAP) + { + return Arc::new(self.standard_endpoints()); + } } - let recently_failed = cache - .discovery_failed_at - .is_some_and(|at| at.elapsed() < DISCOVERY_RETRY_GAP); - if !recently_failed { - match self.fetch_discovery().await { - Ok(endpoints) => { - let endpoints = Arc::new(endpoints); - cache.endpoints = Some(Arc::clone(&endpoints)); - cache.discovery_failed_at = None; - return endpoints; - } - Err(error) => { - tracing::warn!(error = %error, "oidc: discovery failed, using the standard paths"); - cache.discovery_failed_at = Some(Instant::now()); - } + // The lock is not held during the request. Two requests may race to fetch; both get the same + // document, so that is harmless. + match self.fetch_discovery().await { + Ok(endpoints) => { + let endpoints = Arc::new(endpoints); + let mut cache = self.cache.lock().await; + cache.endpoints = Some(Arc::clone(&endpoints)); + cache.discovery_failed_at = None; + endpoints + } + Err(error) => { + tracing::warn!(error = %error, "oidc: discovery failed, using the standard paths"); + self.cache.lock().await.discovery_failed_at = Some(Instant::now()); + Arc::new(self.standard_endpoints()) } } - Arc::new(self.standard_endpoints()) } /// The paths of contracts section 2.1, under the issuer. @@ -686,33 +758,25 @@ impl OidcClient { serde_json::from_slice(&bytes).map_err(|e| OidcError::Unavailable(e.to_string())) } - /// The key set in use. A fresh cache is used as it is; an expired one is refetched, and a failed - /// refetch keeps the old set, because a stale key still verifies tokens that were signed with it. + /// The key set in use. The cache answers when it can (see [`keys_from_cache`]). Otherwise one request + /// at a time fetches it, with no lock held during the network call. A failed refetch keeps the old + /// set, because a stale key still verifies tokens that were signed with it. async fn load_keys(&self, force: bool) -> Result, OidcError> { - let endpoints = self.endpoints().await; - let mut cache = self.cache.lock().await; - let fresh = cache - .keys - .as_ref() - .is_some_and(|(at, _)| at.elapsed() < JWKS_MAX_AGE); - if fresh - && !force - && let Some((_, keys)) = &cache.keys - { - return Ok(Arc::clone(keys)); + let decided = keys_from_cache(&*self.cache.lock().await, force); + if let Some(answer) = decided { + return answer; } - // A forced refetch (unknown kid) is rate limited. Within the gap the old set is the answer. - let refreshed_recently = cache - .keys_refresh_at - .is_some_and(|at| at.elapsed() < JWKS_REFRESH_GAP); - if force - && refreshed_recently - && let Some((_, keys)) = &cache.keys - { - return Ok(Arc::clone(keys)); + let _single_flight = self.refresh.lock().await; + // A request that waited for the fetch above finds its answer here. + let decided = keys_from_cache(&*self.cache.lock().await, force); + if let Some(answer) = decided { + return answer; } - cache.keys_refresh_at = Some(Instant::now()); - match self.get_json::(&endpoints.jwks).await { + let endpoints = self.endpoints().await; + self.cache.lock().await.keys_refresh_at = Some(Instant::now()); + let fetched = self.get_json::(&endpoints.jwks).await; + let mut cache = self.cache.lock().await; + match fetched { Ok(jwks) => { let keys = Arc::new(KeySet::from_jwks(&jwks)); cache.keys = Some((Instant::now(), Arc::clone(&keys))); @@ -735,15 +799,20 @@ impl OidcClient { token: &str, audience: &str, ) -> Result { - self.verify_with(|keys| verify_machine_token(keys, token, &self.issuer, audience)) - .await + self.verify_with(token, |keys| { + verify_machine_token(keys, token, &self.issuer, audience) + }) + .await } - /// Runs `check` against the key set. An unknown key id triggers one rate-limited refetch. + /// Runs `check` against the key set. The header is checked first, so a token that cannot verify + /// fetches nothing. An unknown key id triggers one rate-limited refetch. async fn verify_with( &self, + token: &str, check: impl Fn(&KeySet) -> Result, ) -> Result { + check_header(token)?; let keys = self.load_keys(false).await?; match check(&keys) { Err(TokenError::UnknownKey) => { @@ -756,14 +825,18 @@ impl OidcClient { /// Verifies an ID token of this sign-in. See [`verify_id_token`]. pub async fn verify_id_token(&self, token: &str, nonce: &str) -> Result { - self.verify_with(|keys| verify_id_token(keys, token, &self.issuer, &self.client_id, nonce)) - .await + self.verify_with(token, |keys| { + verify_id_token(keys, token, &self.issuer, &self.client_id, nonce) + }) + .await } /// Verifies a back-channel logout token. See [`verify_logout_token`]. pub async fn verify_logout_token(&self, token: &str) -> Result { - self.verify_with(|keys| verify_logout_token(keys, token, &self.issuer, &self.client_id)) - .await + self.verify_with(token, |keys| { + verify_logout_token(keys, token, &self.issuer, &self.client_id) + }) + .await } /// The URL that sends the browser to `im` to sign in (contracts section 2.3, step 1). @@ -828,13 +901,15 @@ impl OidcClient { /// A client-credentials token for the directory at `im` (contracts section 2.6). Cached until /// [`SERVICE_TOKEN_MARGIN`] before its stated lifetime ends. pub async fn service_token(&self) -> Result { - let endpoints = self.endpoints().await; - let mut cache = self.cache.lock().await; - if let Some((token, until)) = &cache.service - && Instant::now() < *until { - return Ok(token.clone()); + let cache = self.cache.lock().await; + if let Some((token, until)) = &cache.service + && Instant::now() < *until + { + return Ok(token.clone()); + } } + let endpoints = self.endpoints().await; let response = self .token_request( &endpoints.token, @@ -850,7 +925,7 @@ impl OidcClient { .ok_or(OidcError::Token(TokenError::Claim("access_token")))?; let lifetime = Duration::from_secs(response.expires_in.unwrap_or(0)); let until = Instant::now() + lifetime.saturating_sub(SERVICE_TOKEN_MARGIN); - cache.service = Some((token.clone(), until)); + self.cache.lock().await.service = Some((token.clone(), until)); Ok(token) } diff --git a/crates/in-web/src/pages/backchannel.rs b/crates/in-web/src/pages/backchannel.rs index 6396cd6..7d2f4cd 100644 --- a/crates/in-web/src/pages/backchannel.rs +++ b/crates/in-web/src/pages/backchannel.rs @@ -46,15 +46,15 @@ struct LogoutTokenForm { pub enum Outcome { /// The token was new. This many sessions ended (possibly none). Ended(u64), - /// The `jti` was seen before. The token is refused and nothing is ended. + /// The `jti` was seen before. Nothing is ended: the sessions it named are already gone. Replayed, } /// Ends the sessions a verified logout token names, then records its `jti`. /// -/// A recorded `jti` is a replay and ends nothing. The `jti` is recorded only after the sessions are -/// gone: if ending them fails, `im` retries the same token and it is acted on again, so a transient -/// failure never leaves sessions alive. Two parallel deliveries may both delete, which is harmless. +/// A recorded `jti` is a replay: it ends nothing, and the delivery is still answered as accepted. The +/// `jti` is recorded only after the sessions are gone: if ending them fails, `im` retries the same token +/// and it is acted on again, so a transient failure never leaves sessions alive. Two parallel deliveries may both delete, which is harmless. /// The `sid` names one `im` session; a token with only `sub` ends every session of the person. pub async fn end_sessions(store: &Store, claims: &LogoutClaims) -> CoreResult { if store.jti_recorded(&claims.jti).await? { @@ -144,11 +144,9 @@ async fn deliver(cx: &Cx, body: Body) -> Answer { tracing::info!(sessions = count, "backchannel: logout applied"); accepted() } - Ok(Outcome::Replayed) => json_error( - StatusCode::BAD_REQUEST, - "invalid_request", - "The logout token was already used.", - ), + // The sessions of an applied token are already gone, so a redelivery is a success. An error + // here would make `im` retry the same token for 24 hours. + Ok(Outcome::Replayed) => accepted(), Err(error) => { tracing::error!(error = %error, "backchannel: could not end the sessions"); json_error( diff --git a/crates/in-web/src/pages/photo.rs b/crates/in-web/src/pages/photo.rs index df4a47b..aaa9269 100644 --- a/crates/in-web/src/pages/photo.rs +++ b/crates/in-web/src/pages/photo.rs @@ -19,7 +19,7 @@ use topcoat::router::request::{headers, uri}; use topcoat::router::{StatusCode, route}; use crate::auth::current_member; -use crate::oidc::OidcClient; +use crate::oidc::{OidcClient, read_limited}; use crate::state::AppState; /// The image types a photo may be served as. `im` may store others; they are not served. @@ -90,9 +90,10 @@ async fn write_cache(photo_dir: &Path, sub: &str, version: i64, content_type: &s } } -/// Writes `bytes` to `path` through a sibling temporary file and a rename. +/// Writes `bytes` to `path` through a temporary file and a rename. The temporary name carries a fresh +/// ULID, so two writers of the same photo never share one, and a rename never publishes a mix of two. async fn write_atomically(path: &Path, bytes: &[u8]) -> std::io::Result<()> { - let temporary = path.with_extension("tmp"); + let temporary = PathBuf::from(format!("{}.{}.tmp", path.display(), ulid::Ulid::generate())); tokio::fs::write(&temporary, bytes).await?; tokio::fs::rename(&temporary, path).await } @@ -135,15 +136,10 @@ async fn fetch_photo( let Some(content_type) = content_type else { return Ok(None); }; - if response - .content_length() - .is_some_and(|length| length > MAX_PHOTO_BYTES as u64) - { - return Ok(None); - } - let bytes = match response.bytes().await { - Ok(bytes) if bytes.len() <= MAX_PHOTO_BYTES => bytes.to_vec(), - Ok(_) => return Ok(None), + // The size is checked while the body is read, so an oversized photo is never held whole. + let bytes = match read_limited(response, MAX_PHOTO_BYTES).await { + Ok(Some(bytes)) => bytes, + Ok(None) => return Ok(None), Err(error) => { tracing::warn!(error = %error, "photo: the body could not be read"); return Err(unavailable()); 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