JWKS fetched outside the key lock after a header check, nbf enforced, capped directory reads, bounded photo fetch, calmer reconnects, replayed logout answers 200, unique cache temp names
Browse files at this commitf94f61ebb81e47937563778ad9636b34122d74edParent: a495c27- fix
- JWKS fetched outside the key lock after a header check, nbf enforced, capped directory reads, bounded photo fetch, calmer reconnects, replayed logout answers 200, unique cache temp names
7 changed files +235 -115
- Cargo.lock +1 -0
- crates/in-web/Cargo.toml +1 -0
- crates/in-web/src/directory.rs +68 -19
- crates/in-web/src/oidc.rs +149 -74
- crates/in-web/src/pages/backchannel.rs +7 -9
- crates/in-web/src/pages/photo.rs +8 -12
- docs/contracts.md +1 -1
Cargo.lockmodified+1 -0
| @@ -2004,6 +2004,7 @@ dependencies = [ | ||
| 2004 | 2004 | "topcoat", |
| 2005 | 2005 | "tracing", |
| 2006 | 2006 | "tracing-subscriber", |
| 2007 | + "ulid", | |
| 2007 | 2008 | ] |
| 2008 | 2009 | |
| 2009 | 2010 | [[package]] |
crates/in-web/Cargo.tomlmodified+1 -0
| @@ -33,6 +33,7 @@ tokio = { workspace = true, features = ["net", "signal", "time", "sync", "fs", " | ||
| 33 | 33 | topcoat.workspace = true |
| 34 | 34 | tracing.workspace = true |
| 35 | 35 | tracing-subscriber = { workspace = true, features = ["env-filter"] } |
| 36 | +ulid.workspace = true | |
| 36 | 37 | |
| 37 | 38 | [dev-dependencies] |
| 38 | 39 | serde_urlencoded.workspace = true |
crates/in-web/src/directory.rsmodified+68 -19
| @@ -8,10 +8,12 @@ | ||
| 8 | 8 | //! |
| 9 | 9 | //! When the stream fails, the worker waits with exponential backoff from 1 s to 60 s, each wait a random |
| 10 | 10 | //! point between half of the step and the whole step, so a restarted `im` is not hit all at once. A stream that ends |
| 11 | -//! on its own (the 50-minute close of contracts section 3.2) is reconnected after one second. | |
| 11 | +//! on its own (the 50-minute close of contracts section 3.2) is reconnected after one second, provided it | |
| 12 | +//! carried events or stayed open for a minute. A stream that closes at once without events is retried with | |
| 13 | +//! the backoff, so a proxy that keeps closing connections cannot make the worker reconnect every second. | |
| 12 | 14 | |
| 13 | 15 | use std::collections::HashSet; |
| 14 | -use std::time::Duration; | |
| 16 | +use std::time::{Duration, Instant}; | |
| 15 | 17 | |
| 16 | 18 | use futures_util::StreamExt; |
| 17 | 19 | use http::header::ACCEPT; |
| @@ -20,7 +22,7 @@ use in_core::time::now_stamp; | ||
| 20 | 22 | use serde::Deserialize; |
| 21 | 23 | use tokio::sync::watch; |
| 22 | 24 | |
| 23 | -use crate::oidc::{OidcClient, OidcError}; | |
| 25 | +use crate::oidc::{OidcClient, OidcError, read_limited}; | |
| 24 | 26 | use crate::state::AppState; |
| 25 | 27 | |
| 26 | 28 | /// The `settings` key of the directory cursor. |
| @@ -35,6 +37,16 @@ const BACKOFF_MAX: Duration = Duration::from_secs(60); | ||
| 35 | 37 | /// The pause after a stream that ended cleanly, before it is reconnected. |
| 36 | 38 | const CLEAN_PAUSE: Duration = Duration::from_secs(1); |
| 37 | 39 | |
| 40 | +/// How long a stream must stay open, with no event at all, to count as healthy. A quiet directory keeps | |
| 41 | +/// a stream open for a long time without events, so that is not a failure. | |
| 42 | +const QUIET_STREAM_HEALTHY: Duration = Duration::from_secs(60); | |
| 43 | + | |
| 44 | +/// The largest full listing the mirror reads. Matches the cap that `iz` uses for the same listing. | |
| 45 | +const ROSTER_MAX_BYTES: usize = 8 * 1024 * 1024; | |
| 46 | + | |
| 47 | +/// The largest single event, and the longest line, the stream may carry. A longer one ends the stream. | |
| 48 | +const MAX_STREAM_BYTES: usize = 64 * 1024; | |
| 49 | + | |
| 38 | 50 | /// Why one round of syncing failed. |
| 39 | 51 | #[derive(Debug, thiserror::Error)] |
| 40 | 52 | enum SyncError { |
| @@ -53,6 +65,9 @@ enum SyncError { | ||
| 53 | 65 | /// The full directory could not be read. |
| 54 | 66 | #[error("the directory listing is not what the contracts describe")] |
| 55 | 67 | Listing, |
| 68 | + /// `im` sent more than the mirror accepts, in one answer or one event. | |
| 69 | + #[error("im sent more than the mirror accepts")] | |
| 70 | + TooLarge, | |
| 56 | 71 | } |
| 57 | 72 | |
| 58 | 73 | /// One member as the directory sends it (contracts section 3.1). Unknown fields are ignored. |
| @@ -111,8 +126,9 @@ struct SseParser { | ||
| 111 | 126 | |
| 112 | 127 | impl SseParser { |
| 113 | 128 | /// Adds bytes and returns the events they complete. A blank line ends an event; lines that start |
| 114 | - /// with `:` are comments (keep-alives) and are skipped. | |
| 115 | - fn push(&mut self, chunk: &[u8]) -> Vec<SseEvent> { | |
| 129 | + /// with `:` are comments (keep-alives) and are skipped. An event or a line over | |
| 130 | + /// [`MAX_STREAM_BYTES`] is an error, so a hostile stream cannot grow the buffers without bound. | |
| 131 | + fn push(&mut self, chunk: &[u8]) -> Result<Vec<SseEvent>, SyncError> { | |
| 116 | 132 | self.buffer.extend_from_slice(chunk); |
| 117 | 133 | let mut events = Vec::new(); |
| 118 | 134 | while let Some(end) = self.buffer.iter().position(|byte| *byte == b'\n') { |
| @@ -144,12 +160,20 @@ impl SseParser { | ||
| 144 | 160 | }; |
| 145 | 161 | match field { |
| 146 | 162 | "event" => self.event = value.to_owned(), |
| 147 | - "data" => self.data.push(value.to_owned()), | |
| 163 | + "data" => { | |
| 164 | + self.data.push(value.to_owned()); | |
| 165 | + if self.data.iter().map(String::len).sum::<usize>() > MAX_STREAM_BYTES { | |
| 166 | + return Err(SyncError::TooLarge); | |
| 167 | + } | |
| 168 | + } | |
| 148 | 169 | "id" => self.id = Some(value.to_owned()), |
| 149 | 170 | _ => {} |
| 150 | 171 | } |
| 151 | 172 | } |
| 152 | - events | |
| 173 | + if self.buffer.len() > MAX_STREAM_BYTES { | |
| 174 | + return Err(SyncError::TooLarge); | |
| 175 | + } | |
| 176 | + Ok(events) | |
| 153 | 177 | } |
| 154 | 178 | } |
| 155 | 179 | |
| @@ -157,8 +181,16 @@ impl SseParser { | ||
| 157 | 181 | enum Ended { |
| 158 | 182 | /// The server asked for a full fetch. |
| 159 | 183 | Resync, |
| 160 | - /// The stream closed (the server's 50-minute close, or a stop). | |
| 161 | - Closed, | |
| 184 | + /// The stream closed (the server's 50-minute close, or a stop). `healthy` is false for a stream | |
| 185 | + /// that closed at once without events, which counts as a failure for the backoff. | |
| 186 | + Closed { healthy: bool }, | |
| 187 | +} | |
| 188 | + | |
| 189 | +/// The outcome of a stream that closed on its own, judged by what it did before it closed. | |
| 190 | +fn closed(opened: Instant, applied: bool) -> Ended { | |
| 191 | + Ended::Closed { | |
| 192 | + healthy: applied || opened.elapsed() >= QUIET_STREAM_HEALTHY, | |
| 193 | + } | |
| 162 | 194 | } |
| 163 | 195 | |
| 164 | 196 | /// 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<bool>) { | ||
| 178 | 210 | backoff = BACKOFF_FIRST; |
| 179 | 211 | CLEAN_PAUSE |
| 180 | 212 | } |
| 181 | - Ok(Ended::Closed) => { | |
| 213 | + Ok(Ended::Closed { healthy: true }) => { | |
| 182 | 214 | backoff = BACKOFF_FIRST; |
| 183 | 215 | CLEAN_PAUSE |
| 184 | 216 | } |
| 217 | + Ok(Ended::Closed { healthy: false }) => { | |
| 218 | + let pause = jittered(backoff); | |
| 219 | + backoff = (backoff * 2).min(BACKOFF_MAX); | |
| 220 | + pause | |
| 221 | + } | |
| 185 | 222 | Err(error) => { |
| 186 | 223 | tracing::warn!(error = %error, "directory: sync failed, retrying"); |
| 187 | 224 | needs_full = true; |
| @@ -225,10 +262,10 @@ async fn full_sync(state: &AppState, oidc: &OidcClient) -> Result<(), SyncError> | ||
| 225 | 262 | if !response.status().is_success() { |
| 226 | 263 | return Err(SyncError::Status(response.status())); |
| 227 | 264 | } |
| 228 | - let bytes = response | |
| 229 | - .bytes() | |
| 265 | + let bytes = read_limited(response, ROSTER_MAX_BYTES) | |
| 230 | 266 | .await |
| 231 | - .map_err(|e| SyncError::Transport(e.to_string()))?; | |
| 267 | + .map_err(|e| SyncError::Transport(e.to_string()))? | |
| 268 | + .ok_or(SyncError::TooLarge)?; | |
| 232 | 269 | let listing: Listing = serde_json::from_slice(&bytes).map_err(|_| SyncError::Listing)?; |
| 233 | 270 | |
| 234 | 271 | let mut named = HashSet::new(); |
| @@ -274,18 +311,21 @@ async fn follow( | ||
| 274 | 311 | } |
| 275 | 312 | tracing::info!("directory: stream connected"); |
| 276 | 313 | |
| 314 | + let opened = Instant::now(); | |
| 315 | + let mut applied = false; | |
| 277 | 316 | let mut body = response.bytes_stream(); |
| 278 | 317 | let mut parser = SseParser::default(); |
| 279 | 318 | loop { |
| 280 | 319 | let chunk = tokio::select! { |
| 281 | 320 | chunk = body.next() => chunk, |
| 282 | - _ = stop.wait_for(|stopped| *stopped) => return Ok(Ended::Closed), | |
| 321 | + _ = stop.wait_for(|stopped| *stopped) => return Ok(closed(opened, applied)), | |
| 283 | 322 | }; |
| 284 | 323 | let Some(chunk) = chunk else { |
| 285 | - return Ok(Ended::Closed); | |
| 324 | + return Ok(closed(opened, applied)); | |
| 286 | 325 | }; |
| 287 | 326 | let chunk = chunk.map_err(|e| SyncError::Transport(e.to_string()))?; |
| 288 | - for event in parser.push(&chunk) { | |
| 327 | + for event in parser.push(&chunk)? { | |
| 328 | + applied = true; | |
| 289 | 329 | if let Some(ended) = apply_event(state, event).await? { |
| 290 | 330 | return Ok(ended); |
| 291 | 331 | } |
| @@ -400,8 +440,15 @@ mod tests { | ||
| 400 | 440 | #[test] |
| 401 | 441 | fn events_are_parsed_across_chunks_and_comments_are_skipped() { |
| 402 | 442 | let mut parser = SseParser::default(); |
| 403 | - assert!(parser.push(b": keep-alive\nid: 7\nevent: mem").is_empty()); | |
| 404 | - let events = parser.push(b"ber\ndata: {\"sub\":\"a\"}\n\n"); | |
| 443 | + assert!( | |
| 444 | + parser | |
| 445 | + .push(b": keep-alive\nid: 7\nevent: mem") | |
| 446 | + .expect("bytes") | |
| 447 | + .is_empty() | |
| 448 | + ); | |
| 449 | + let events = parser | |
| 450 | + .push(b"ber\ndata: {\"sub\":\"a\"}\n\n") | |
| 451 | + .expect("bytes"); | |
| 405 | 452 | assert_eq!( |
| 406 | 453 | events, |
| 407 | 454 | vec![SseEvent { |
| @@ -410,7 +457,9 @@ mod tests { | ||
| 410 | 457 | data: "{\"sub\":\"a\"}".into(), |
| 411 | 458 | }] |
| 412 | 459 | ); |
| 413 | - let events = parser.push(b"event: resync\ndata: {}\r\n\r\n"); | |
| 460 | + let events = parser | |
| 461 | + .push(b"event: resync\ndata: {}\r\n\r\n") | |
| 462 | + .expect("bytes"); | |
| 414 | 463 | assert_eq!(events[0].event, "resync"); |
| 415 | 464 | } |
| 416 | 465 |
crates/in-web/src/oidc.rsmodified+149 -74
| @@ -18,7 +18,7 @@ use in_core::config::Oidc; | ||
| 18 | 18 | use in_core::error::{Error as CoreError, Result as CoreResult}; |
| 19 | 19 | use in_core::token::constant_time_eq; |
| 20 | 20 | use jsonwebtoken::errors::ErrorKind; |
| 21 | -use jsonwebtoken::{Algorithm, DecodingKey, Validation, decode, decode_header}; | |
| 21 | +use jsonwebtoken::{Algorithm, DecodingKey, Validation, decode}; | |
| 22 | 22 | use serde::Deserialize; |
| 23 | 23 | use serde_json::{Map, Value}; |
| 24 | 24 | use sha2::{Digest, Sha256}; |
| @@ -33,8 +33,9 @@ pub const MAX_FUTURE_IAT_SECS: i64 = 300; | ||
| 33 | 33 | /// How long a fetched key set is used before it is fetched again (contracts section 2.2). |
| 34 | 34 | pub const JWKS_MAX_AGE: Duration = Duration::from_secs(60 * 60); |
| 35 | 35 | |
| 36 | -/// The shortest gap between two key fetches caused by an unknown `kid`. Protects `im` from a flood of | |
| 37 | -/// tokens that name keys that do not exist. | |
| 36 | +/// The shortest gap between two key fetches. A fetch for an unknown `kid`, and a retry after a failed | |
| 37 | +/// fetch, both wait this long. It is the one-minute refetch limit of contracts section 2.2, and it | |
| 38 | +/// protects `im` from a flood of tokens that name keys that do not exist. | |
| 38 | 39 | pub const JWKS_REFRESH_GAP: Duration = Duration::from_secs(60); |
| 39 | 40 | |
| 40 | 41 | /// 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<String, Value>, now: i64) -> Result<(), TokenError> { | ||
| 274 | 275 | Ok(()) |
| 275 | 276 | } |
| 276 | 277 | |
| 277 | -/// Checks the algorithm, the key id, the signature, the issuer and the expiry, and returns the claims. | |
| 278 | -/// Audience, nonce and the rest are the job of the callers, which know what they expect. | |
| 278 | +/// Reads the protected header of `token` and refuses what `in` can never verify: the token must have | |
| 279 | +/// three segments, the header must name EdDSA, and it must carry a `kid`. Returns the `kid`. | |
| 279 | 280 | /// |
| 280 | -/// The algorithm is read from the raw header first, so `none` and any other algorithm are refused | |
| 281 | -/// before a library sees the token. | |
| 282 | -pub fn verify_signed( | |
| 283 | - keys: &KeySet, | |
| 284 | - token: &str, | |
| 285 | - issuer: &str, | |
| 286 | -) -> Result<Map<String, Value>, TokenError> { | |
| 287 | - let first_segment = token.split('.').next().ok_or(TokenError::Malformed)?; | |
| 281 | +/// The algorithm is read from the raw header, so `none` and any other algorithm are refused before a | |
| 282 | +/// library sees the token. Callers run this before any key is fetched, so a token that cannot verify | |
| 283 | +/// costs no network call. | |
| 284 | +pub fn check_header(token: &str) -> Result<String, TokenError> { | |
| 285 | + let segments: Vec<&str> = token.split('.').collect(); | |
| 286 | + if segments.len() != 3 { | |
| 287 | + return Err(TokenError::Malformed); | |
| 288 | + } | |
| 288 | 289 | let header_bytes = BASE64_URL_SAFE_NO_PAD |
| 289 | - .decode(first_segment) | |
| 290 | + .decode(segments[0]) | |
| 290 | 291 | .map_err(|_| TokenError::Malformed)?; |
| 291 | 292 | let header: Value = serde_json::from_slice(&header_bytes).map_err(|_| TokenError::Malformed)?; |
| 292 | 293 | if header.get("alg").and_then(Value::as_str) != Some("EdDSA") { |
| 293 | 294 | return Err(TokenError::Algorithm); |
| 294 | 295 | } |
| 295 | - let parsed = decode_header(token).map_err(|_| TokenError::Malformed)?; | |
| 296 | - let kid = parsed.kid.ok_or(TokenError::NoKeyId)?; | |
| 296 | + header | |
| 297 | + .get("kid") | |
| 298 | + .and_then(Value::as_str) | |
| 299 | + .filter(|kid| !kid.is_empty()) | |
| 300 | + .map(str::to_owned) | |
| 301 | + .ok_or(TokenError::NoKeyId) | |
| 302 | +} | |
| 303 | + | |
| 304 | +/// Checks the algorithm, the key id, the signature, the issuer, the expiry and the not-before time, and | |
| 305 | +/// returns the claims. Audience, nonce and the rest are the job of the callers, which know what they | |
| 306 | +/// expect. | |
| 307 | +pub fn verify_signed( | |
| 308 | + keys: &KeySet, | |
| 309 | + token: &str, | |
| 310 | + issuer: &str, | |
| 311 | +) -> Result<Map<String, Value>, TokenError> { | |
| 312 | + let kid = check_header(token)?; | |
| 297 | 313 | let key = keys.get(&kid).ok_or(TokenError::UnknownKey)?; |
| 298 | 314 | |
| 299 | 315 | let mut validation = Validation::new(Algorithm::EdDSA); |
| 300 | 316 | validation.leeway = u64::try_from(CLOCK_LEEWAY_SECS).unwrap_or(0); |
| 301 | 317 | validation.validate_exp = true; |
| 318 | + // A token whose `nbf` lies beyond the leeway is not valid yet. A token without `nbf` is unaffected. | |
| 319 | + validation.validate_nbf = true; | |
| 302 | 320 | // Audience is checked by the callers, because the rule differs by token kind. |
| 303 | 321 | validation.validate_aud = false; |
| 304 | 322 | validation.set_issuer(&[issuer]); |
| @@ -312,6 +330,7 @@ pub fn verify_signed( | ||
| 312 | 330 | ErrorKind::InvalidSignature => TokenError::Signature, |
| 313 | 331 | ErrorKind::InvalidIssuer => TokenError::Claim("iss"), |
| 314 | 332 | ErrorKind::InvalidAlgorithm => TokenError::Algorithm, |
| 333 | + ErrorKind::ImmatureSignature => TokenError::Claim("nbf"), | |
| 315 | 334 | ErrorKind::MissingRequiredClaim(_) => TokenError::Claim("required claim"), |
| 316 | 335 | _ => TokenError::Malformed, |
| 317 | 336 | } |
| @@ -512,6 +531,29 @@ pub fn pkce_challenge(verifier: &str) -> String { | ||
| 512 | 531 | BASE64_URL_SAFE_NO_PAD.encode(Sha256::digest(verifier.as_bytes())) |
| 513 | 532 | } |
| 514 | 533 | |
| 534 | +/// Reads a response body of at most `limit` bytes. Returns `None` when the body is larger, and stops | |
| 535 | +/// reading as soon as it is, so a server that lies about its length cannot make `in` hold more than | |
| 536 | +/// `limit` bytes. | |
| 537 | +pub async fn read_limited( | |
| 538 | + mut response: reqwest::Response, | |
| 539 | + limit: usize, | |
| 540 | +) -> Result<Option<Vec<u8>>, reqwest::Error> { | |
| 541 | + if response | |
| 542 | + .content_length() | |
| 543 | + .is_some_and(|len| len > u64::try_from(limit).unwrap_or(u64::MAX)) | |
| 544 | + { | |
| 545 | + return Ok(None); | |
| 546 | + } | |
| 547 | + let mut body = Vec::new(); | |
| 548 | + while let Some(chunk) = response.chunk().await? { | |
| 549 | + if body.len() + chunk.len() > limit { | |
| 550 | + return Ok(None); | |
| 551 | + } | |
| 552 | + body.extend_from_slice(&chunk); | |
| 553 | + } | |
| 554 | + Ok(Some(body)) | |
| 555 | +} | |
| 556 | + | |
| 515 | 557 | /// Percent-encodes one value for a query, a form body or a Basic credential (RFC 6749 section 2.3.1): |
| 516 | 558 | /// unreserved characters pass, everything else becomes `%XX`. |
| 517 | 559 | pub fn percent_encode(value: &str) -> String { |
| @@ -537,8 +579,8 @@ struct TokenResponse { | ||
| 537 | 579 | expires_in: Option<u64>, |
| 538 | 580 | } |
| 539 | 581 | |
| 540 | -/// Cached state of the client. Every field is behind one lock, and no method holds it while it | |
| 541 | -/// takes it again. | |
| 582 | +/// Cached state of the client. Every field is behind one lock. No method holds it across a network | |
| 583 | +/// call, and no method holds it while it takes it again. | |
| 542 | 584 | #[derive(Default)] |
| 543 | 585 | struct Cache { |
| 544 | 586 | /// The endpoints from discovery, once fetched. |
| @@ -554,6 +596,26 @@ struct Cache { | ||
| 554 | 596 | service: Option<(String, Instant)>, |
| 555 | 597 | } |
| 556 | 598 | |
| 599 | +/// What the cache answers for the key set, without the network. `None` means a fetch is due. | |
| 600 | +/// | |
| 601 | +/// A fresh set is used as it is unless a refetch is forced. Any set, fresh or stale, is also used while | |
| 602 | +/// the last fetch attempt is younger than [`JWKS_REFRESH_GAP`]. That rate-limits forced refetches for | |
| 603 | +/// unknown key ids and retries after a failed refetch alike. With no set at all, a recent failure is an | |
| 604 | +/// answer of its own, so requests do not each wait for `im` again. | |
| 605 | +fn keys_from_cache(cache: &Cache, force: bool) -> Option<Result<Arc<KeySet>, OidcError>> { | |
| 606 | + let recently_tried = cache | |
| 607 | + .keys_refresh_at | |
| 608 | + .is_some_and(|at| at.elapsed() < JWKS_REFRESH_GAP); | |
| 609 | + match &cache.keys { | |
| 610 | + Some((at, keys)) if at.elapsed() < JWKS_MAX_AGE && !force => Some(Ok(Arc::clone(keys))), | |
| 611 | + Some((_, keys)) if recently_tried => Some(Ok(Arc::clone(keys))), | |
| 612 | + None if recently_tried => Some(Err(OidcError::Unavailable( | |
| 613 | + "the signing keys are not available yet".to_owned(), | |
| 614 | + ))), | |
| 615 | + _ => None, | |
| 616 | + } | |
| 617 | +} | |
| 618 | + | |
| 557 | 619 | /// The OpenID Connect client. One per process, shared through the app state. |
| 558 | 620 | pub struct OidcClient { |
| 559 | 621 | issuer: String, |
| @@ -563,6 +625,9 @@ pub struct OidcClient { | ||
| 563 | 625 | http: reqwest::Client, |
| 564 | 626 | stream_http: reqwest::Client, |
| 565 | 627 | cache: Mutex<Cache>, |
| 628 | + /// Held while the key set is fetched. One fetch runs at a time, and the requests that wait for it | |
| 629 | + /// read the result from the cache. It is never held while `cache` is held. | |
| 630 | + refresh: Mutex<()>, | |
| 566 | 631 | } |
| 567 | 632 | |
| 568 | 633 | impl OidcClient { |
| @@ -590,6 +655,7 @@ impl OidcClient { | ||
| 590 | 655 | http, |
| 591 | 656 | stream_http, |
| 592 | 657 | cache: Mutex::new(Cache::default()), |
| 658 | + refresh: Mutex::new(()), | |
| 593 | 659 | }) |
| 594 | 660 | } |
| 595 | 661 | |
| @@ -611,28 +677,34 @@ impl OidcClient { | ||
| 611 | 677 | /// The endpoints of `im`. Fetched from discovery once; when discovery fails, the standard paths |
| 612 | 678 | /// under the issuer are used and discovery is retried after [`DISCOVERY_RETRY_GAP`]. |
| 613 | 679 | pub async fn endpoints(&self) -> Arc<Endpoints> { |
| 614 | - let mut cache = self.cache.lock().await; | |
| 615 | - if let Some(endpoints) = &cache.endpoints { | |
| 616 | - return Arc::clone(endpoints); | |
| 680 | + { | |
| 681 | + let cache = self.cache.lock().await; | |
| 682 | + if let Some(endpoints) = &cache.endpoints { | |
| 683 | + return Arc::clone(endpoints); | |
| 684 | + } | |
| 685 | + if cache | |
| 686 | + .discovery_failed_at | |
| 687 | + .is_some_and(|at| at.elapsed() < DISCOVERY_RETRY_GAP) | |
| 688 | + { | |
| 689 | + return Arc::new(self.standard_endpoints()); | |
| 690 | + } | |
| 617 | 691 | } |
| 618 | - let recently_failed = cache | |
| 619 | - .discovery_failed_at | |
| 620 | - .is_some_and(|at| at.elapsed() < DISCOVERY_RETRY_GAP); | |
| 621 | - if !recently_failed { | |
| 622 | - match self.fetch_discovery().await { | |
| 623 | - Ok(endpoints) => { | |
| 624 | - let endpoints = Arc::new(endpoints); | |
| 625 | - cache.endpoints = Some(Arc::clone(&endpoints)); | |
| 626 | - cache.discovery_failed_at = None; | |
| 627 | - return endpoints; | |
| 628 | - } | |
| 629 | - Err(error) => { | |
| 630 | - tracing::warn!(error = %error, "oidc: discovery failed, using the standard paths"); | |
| 631 | - cache.discovery_failed_at = Some(Instant::now()); | |
| 632 | - } | |
| 692 | + // The lock is not held during the request. Two requests may race to fetch; both get the same | |
| 693 | + // document, so that is harmless. | |
| 694 | + match self.fetch_discovery().await { | |
| 695 | + Ok(endpoints) => { | |
| 696 | + let endpoints = Arc::new(endpoints); | |
| 697 | + let mut cache = self.cache.lock().await; | |
| 698 | + cache.endpoints = Some(Arc::clone(&endpoints)); | |
| 699 | + cache.discovery_failed_at = None; | |
| 700 | + endpoints | |
| 701 | + } | |
| 702 | + Err(error) => { | |
| 703 | + tracing::warn!(error = %error, "oidc: discovery failed, using the standard paths"); | |
| 704 | + self.cache.lock().await.discovery_failed_at = Some(Instant::now()); | |
| 705 | + Arc::new(self.standard_endpoints()) | |
| 633 | 706 | } |
| 634 | 707 | } |
| 635 | - Arc::new(self.standard_endpoints()) | |
| 636 | 708 | } |
| 637 | 709 | |
| 638 | 710 | /// The paths of contracts section 2.1, under the issuer. |
| @@ -686,33 +758,25 @@ impl OidcClient { | ||
| 686 | 758 | serde_json::from_slice(&bytes).map_err(|e| OidcError::Unavailable(e.to_string())) |
| 687 | 759 | } |
| 688 | 760 | |
| 689 | - /// The key set in use. A fresh cache is used as it is; an expired one is refetched, and a failed | |
| 690 | - /// refetch keeps the old set, because a stale key still verifies tokens that were signed with it. | |
| 761 | + /// The key set in use. The cache answers when it can (see [`keys_from_cache`]). Otherwise one request | |
| 762 | + /// at a time fetches it, with no lock held during the network call. A failed refetch keeps the old | |
| 763 | + /// set, because a stale key still verifies tokens that were signed with it. | |
| 691 | 764 | async fn load_keys(&self, force: bool) -> Result<Arc<KeySet>, OidcError> { |
| 692 | - let endpoints = self.endpoints().await; | |
| 693 | - let mut cache = self.cache.lock().await; | |
| 694 | - let fresh = cache | |
| 695 | - .keys | |
| 696 | - .as_ref() | |
| 697 | - .is_some_and(|(at, _)| at.elapsed() < JWKS_MAX_AGE); | |
| 698 | - if fresh | |
| 699 | - && !force | |
| 700 | - && let Some((_, keys)) = &cache.keys | |
| 701 | - { | |
| 702 | - return Ok(Arc::clone(keys)); | |
| 765 | + let decided = keys_from_cache(&*self.cache.lock().await, force); | |
| 766 | + if let Some(answer) = decided { | |
| 767 | + return answer; | |
| 703 | 768 | } |
| 704 | - // A forced refetch (unknown kid) is rate limited. Within the gap the old set is the answer. | |
| 705 | - let refreshed_recently = cache | |
| 706 | - .keys_refresh_at | |
| 707 | - .is_some_and(|at| at.elapsed() < JWKS_REFRESH_GAP); | |
| 708 | - if force | |
| 709 | - && refreshed_recently | |
| 710 | - && let Some((_, keys)) = &cache.keys | |
| 711 | - { | |
| 712 | - return Ok(Arc::clone(keys)); | |
| 769 | + let _single_flight = self.refresh.lock().await; | |
| 770 | + // A request that waited for the fetch above finds its answer here. | |
| 771 | + let decided = keys_from_cache(&*self.cache.lock().await, force); | |
| 772 | + if let Some(answer) = decided { | |
| 773 | + return answer; | |
| 713 | 774 | } |
| 714 | - cache.keys_refresh_at = Some(Instant::now()); | |
| 715 | - match self.get_json::<Jwks>(&endpoints.jwks).await { | |
| 775 | + let endpoints = self.endpoints().await; | |
| 776 | + self.cache.lock().await.keys_refresh_at = Some(Instant::now()); | |
| 777 | + let fetched = self.get_json::<Jwks>(&endpoints.jwks).await; | |
| 778 | + let mut cache = self.cache.lock().await; | |
| 779 | + match fetched { | |
| 716 | 780 | Ok(jwks) => { |
| 717 | 781 | let keys = Arc::new(KeySet::from_jwks(&jwks)); |
| 718 | 782 | cache.keys = Some((Instant::now(), Arc::clone(&keys))); |
| @@ -735,15 +799,20 @@ impl OidcClient { | ||
| 735 | 799 | token: &str, |
| 736 | 800 | audience: &str, |
| 737 | 801 | ) -> Result<MachineClaims, OidcError> { |
| 738 | - self.verify_with(|keys| verify_machine_token(keys, token, &self.issuer, audience)) | |
| 739 | - .await | |
| 802 | + self.verify_with(token, |keys| { | |
| 803 | + verify_machine_token(keys, token, &self.issuer, audience) | |
| 804 | + }) | |
| 805 | + .await | |
| 740 | 806 | } |
| 741 | 807 | |
| 742 | - /// Runs `check` against the key set. An unknown key id triggers one rate-limited refetch. | |
| 808 | + /// Runs `check` against the key set. The header is checked first, so a token that cannot verify | |
| 809 | + /// fetches nothing. An unknown key id triggers one rate-limited refetch. | |
| 743 | 810 | async fn verify_with<T>( |
| 744 | 811 | &self, |
| 812 | + token: &str, | |
| 745 | 813 | check: impl Fn(&KeySet) -> Result<T, TokenError>, |
| 746 | 814 | ) -> Result<T, OidcError> { |
| 815 | + check_header(token)?; | |
| 747 | 816 | let keys = self.load_keys(false).await?; |
| 748 | 817 | match check(&keys) { |
| 749 | 818 | Err(TokenError::UnknownKey) => { |
| @@ -756,14 +825,18 @@ impl OidcClient { | ||
| 756 | 825 | |
| 757 | 826 | /// Verifies an ID token of this sign-in. See [`verify_id_token`]. |
| 758 | 827 | pub async fn verify_id_token(&self, token: &str, nonce: &str) -> Result<IdClaims, OidcError> { |
| 759 | - self.verify_with(|keys| verify_id_token(keys, token, &self.issuer, &self.client_id, nonce)) | |
| 760 | - .await | |
| 828 | + self.verify_with(token, |keys| { | |
| 829 | + verify_id_token(keys, token, &self.issuer, &self.client_id, nonce) | |
| 830 | + }) | |
| 831 | + .await | |
| 761 | 832 | } |
| 762 | 833 | |
| 763 | 834 | /// Verifies a back-channel logout token. See [`verify_logout_token`]. |
| 764 | 835 | pub async fn verify_logout_token(&self, token: &str) -> Result<LogoutClaims, OidcError> { |
| 765 | - self.verify_with(|keys| verify_logout_token(keys, token, &self.issuer, &self.client_id)) | |
| 766 | - .await | |
| 836 | + self.verify_with(token, |keys| { | |
| 837 | + verify_logout_token(keys, token, &self.issuer, &self.client_id) | |
| 838 | + }) | |
| 839 | + .await | |
| 767 | 840 | } |
| 768 | 841 | |
| 769 | 842 | /// The URL that sends the browser to `im` to sign in (contracts section 2.3, step 1). |
| @@ -828,13 +901,15 @@ impl OidcClient { | ||
| 828 | 901 | /// A client-credentials token for the directory at `im` (contracts section 2.6). Cached until |
| 829 | 902 | /// [`SERVICE_TOKEN_MARGIN`] before its stated lifetime ends. |
| 830 | 903 | pub async fn service_token(&self) -> Result<String, OidcError> { |
| 831 | - let endpoints = self.endpoints().await; | |
| 832 | - let mut cache = self.cache.lock().await; | |
| 833 | - if let Some((token, until)) = &cache.service | |
| 834 | - && Instant::now() < *until | |
| 835 | 904 | { |
| 836 | - return Ok(token.clone()); | |
| 905 | + let cache = self.cache.lock().await; | |
| 906 | + if let Some((token, until)) = &cache.service | |
| 907 | + && Instant::now() < *until | |
| 908 | + { | |
| 909 | + return Ok(token.clone()); | |
| 910 | + } | |
| 837 | 911 | } |
| 912 | + let endpoints = self.endpoints().await; | |
| 838 | 913 | let response = self |
| 839 | 914 | .token_request( |
| 840 | 915 | &endpoints.token, |
| @@ -850,7 +925,7 @@ impl OidcClient { | ||
| 850 | 925 | .ok_or(OidcError::Token(TokenError::Claim("access_token")))?; |
| 851 | 926 | let lifetime = Duration::from_secs(response.expires_in.unwrap_or(0)); |
| 852 | 927 | let until = Instant::now() + lifetime.saturating_sub(SERVICE_TOKEN_MARGIN); |
| 853 | - cache.service = Some((token.clone(), until)); | |
| 928 | + self.cache.lock().await.service = Some((token.clone(), until)); | |
| 854 | 929 | Ok(token) |
| 855 | 930 | } |
| 856 | 931 |
crates/in-web/src/pages/backchannel.rsmodified+7 -9
| @@ -46,15 +46,15 @@ struct LogoutTokenForm { | ||
| 46 | 46 | pub enum Outcome { |
| 47 | 47 | /// The token was new. This many sessions ended (possibly none). |
| 48 | 48 | Ended(u64), |
| 49 | - /// The `jti` was seen before. The token is refused and nothing is ended. | |
| 49 | + /// The `jti` was seen before. Nothing is ended: the sessions it named are already gone. | |
| 50 | 50 | Replayed, |
| 51 | 51 | } |
| 52 | 52 | |
| 53 | 53 | /// Ends the sessions a verified logout token names, then records its `jti`. |
| 54 | 54 | /// |
| 55 | -/// A recorded `jti` is a replay and ends nothing. The `jti` is recorded only after the sessions are | |
| 56 | -/// gone: if ending them fails, `im` retries the same token and it is acted on again, so a transient | |
| 57 | -/// failure never leaves sessions alive. Two parallel deliveries may both delete, which is harmless. | |
| 55 | +/// A recorded `jti` is a replay: it ends nothing, and the delivery is still answered as accepted. The | |
| 56 | +/// `jti` is recorded only after the sessions are gone: if ending them fails, `im` retries the same token | |
| 57 | +/// and it is acted on again, so a transient failure never leaves sessions alive. Two parallel deliveries may both delete, which is harmless. | |
| 58 | 58 | /// The `sid` names one `im` session; a token with only `sub` ends every session of the person. |
| 59 | 59 | pub async fn end_sessions(store: &Store, claims: &LogoutClaims) -> CoreResult<Outcome> { |
| 60 | 60 | if store.jti_recorded(&claims.jti).await? { |
| @@ -144,11 +144,9 @@ async fn deliver(cx: &Cx, body: Body) -> Answer { | ||
| 144 | 144 | tracing::info!(sessions = count, "backchannel: logout applied"); |
| 145 | 145 | accepted() |
| 146 | 146 | } |
| 147 | - Ok(Outcome::Replayed) => json_error( | |
| 148 | - StatusCode::BAD_REQUEST, | |
| 149 | - "invalid_request", | |
| 150 | - "The logout token was already used.", | |
| 151 | - ), | |
| 147 | + // The sessions of an applied token are already gone, so a redelivery is a success. An error | |
| 148 | + // here would make `im` retry the same token for 24 hours. | |
| 149 | + Ok(Outcome::Replayed) => accepted(), | |
| 152 | 150 | Err(error) => { |
| 153 | 151 | tracing::error!(error = %error, "backchannel: could not end the sessions"); |
| 154 | 152 | json_error( |
crates/in-web/src/pages/photo.rsmodified+8 -12
| @@ -19,7 +19,7 @@ use topcoat::router::request::{headers, uri}; | ||
| 19 | 19 | use topcoat::router::{StatusCode, route}; |
| 20 | 20 | |
| 21 | 21 | use crate::auth::current_member; |
| 22 | -use crate::oidc::OidcClient; | |
| 22 | +use crate::oidc::{OidcClient, read_limited}; | |
| 23 | 23 | use crate::state::AppState; |
| 24 | 24 | |
| 25 | 25 | /// 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 | ||
| 90 | 90 | } |
| 91 | 91 | } |
| 92 | 92 | |
| 93 | -/// Writes `bytes` to `path` through a sibling temporary file and a rename. | |
| 93 | +/// Writes `bytes` to `path` through a temporary file and a rename. The temporary name carries a fresh | |
| 94 | +/// ULID, so two writers of the same photo never share one, and a rename never publishes a mix of two. | |
| 94 | 95 | async fn write_atomically(path: &Path, bytes: &[u8]) -> std::io::Result<()> { |
| 95 | - let temporary = path.with_extension("tmp"); | |
| 96 | + let temporary = PathBuf::from(format!("{}.{}.tmp", path.display(), ulid::Ulid::generate())); | |
| 96 | 97 | tokio::fs::write(&temporary, bytes).await?; |
| 97 | 98 | tokio::fs::rename(&temporary, path).await |
| 98 | 99 | } |
| @@ -135,15 +136,10 @@ async fn fetch_photo( | ||
| 135 | 136 | let Some(content_type) = content_type else { |
| 136 | 137 | return Ok(None); |
| 137 | 138 | }; |
| 138 | - if response | |
| 139 | - .content_length() | |
| 140 | - .is_some_and(|length| length > MAX_PHOTO_BYTES as u64) | |
| 141 | - { | |
| 142 | - return Ok(None); | |
| 143 | - } | |
| 144 | - let bytes = match response.bytes().await { | |
| 145 | - Ok(bytes) if bytes.len() <= MAX_PHOTO_BYTES => bytes.to_vec(), | |
| 146 | - Ok(_) => return Ok(None), | |
| 139 | + // The size is checked while the body is read, so an oversized photo is never held whole. | |
| 140 | + let bytes = match read_limited(response, MAX_PHOTO_BYTES).await { | |
| 141 | + Ok(Some(bytes)) => bytes, | |
| 142 | + Ok(None) => return Ok(None), | |
| 147 | 143 | Err(error) => { |
| 148 | 144 | tracing::warn!(error = %error, "photo: the body could not be read"); |
| 149 | 145 | return Err(unavailable()); |
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 | 102 | `events: {"http://schemas.openid.net/event/backchannel-logout": {}}`, and `sid` (and `sub`). For "disable" and |
| 103 | 103 | "delete" it carries only `sub`, which means "every session of this user". |
| 104 | 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 empty | |
| 105 | + 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 | 106 | body. Any other answer is a failure. |
| 107 | 107 | - `im` delivers through a durable outbox: retries with backoff (10 s, 30 s, 1 min, 5 min, then every 15 min) |
| 108 | 108 | for 24 hours. Combined with the 12-hour local session cap (2.4), a missed delivery cannot keep a revoked |