JWKS fetched outside the key lock after a shape check, stale keys kept on failure, exact aud and nbf, bounded in answers, calmer directory reconnects, replayed logout answers 200, versioned avatar fetch, unique cache temp names
Browse files at this commit7742ceb9d4c9be845e8bc6a6c9d913d2af906ff5Parent: 796484e- fix
- JWKS fetched outside the key lock after a shape check, stale keys kept on failure, exact aud and nbf, bounded in answers, calmer directory reconnects, replayed logout answers 200, versioned avatar fetch, unique cache temp names
5 changed files +172 -50
- crates/iz-web/src/directory.rs +43 -13
- crates/iz-web/src/in_store.rs +10 -7
- crates/iz-web/src/oidc.rs +108 -21
- crates/iz-web/src/pages/backchannel.rs +6 -7
- crates/iz-web/src/pages/photo.rs +5 -2
crates/iz-web/src/directory.rsmodified+43 -13
| @@ -95,7 +95,8 @@ enum Ended { | |||
| 95 | /// `im` asked for a full read again. | 95 | /// `im` asked for a full read again. |
| 96 | Resync, | 96 | Resync, |
| 97 | /// The stream closed, went idle, or `im` closed it after 50 minutes. Reconnect with the cursor. | 97 | /// The stream closed, went idle, or `im` closed it after 50 minutes. Reconnect with the cursor. |
| 98 | - Closed, | 98 | + /// `delivered` says whether the connection carried any event. |
| 99 | + Closed { delivered: bool }, | ||
| 99 | } | 100 | } |
| 100 | 101 | ||
| 101 | /// Starts the mirror. Does nothing when OIDC is not configured. | 102 | /// Starts the mirror. Does nothing when OIDC is not configured. |
| @@ -108,19 +109,29 @@ pub fn spawn(state: AppState, stop: watch::Receiver<bool>) { | |||
| 108 | 109 | ||
| 109 | async fn run(state: AppState, oidc: std::sync::Arc<OidcClient>, mut stop: watch::Receiver<bool>) { | 110 | async fn run(state: AppState, oidc: std::sync::Arc<OidcClient>, mut stop: watch::Receiver<bool>) { |
| 110 | let mut backoff = BACKOFF_MIN; | 111 | let mut backoff = BACKOFF_MIN; |
| 112 | + // A full read is needed at the start, after a resync, and after a failure. A plain reconnect | ||
| 113 | + // resumes from the stored cursor, so it does not read the whole listing again. | ||
| 114 | + let mut full = true; | ||
| 111 | loop { | 115 | loop { |
| 112 | - match mirror_once(&state, &oidc, &mut stop).await { | 116 | + match mirror_once(&state, &oidc, &mut stop, full).await { |
| 113 | Ok(Ended::Stopped) => return, | 117 | Ok(Ended::Stopped) => return, |
| 114 | Ok(Ended::Resync) => { | 118 | Ok(Ended::Resync) => { |
| 115 | tracing::info!("directory: the stream asked for a full read"); | 119 | tracing::info!("directory: the stream asked for a full read"); |
| 116 | backoff = BACKOFF_MIN; | 120 | backoff = BACKOFF_MIN; |
| 121 | + full = true; | ||
| 117 | } | 122 | } |
| 118 | - Ok(Ended::Closed) => { | 123 | + Ok(Ended::Closed { delivered }) => { |
| 119 | tracing::info!("directory: the stream closed; reconnecting"); | 124 | tracing::info!("directory: the stream closed; reconnecting"); |
| 120 | - backoff = BACKOFF_MIN; | 125 | + // A connection that carried events resets the wait. A silent one keeps growing it, so |
| 126 | + // an `im` that closes streams at once is not polled every second. | ||
| 127 | + if delivered { | ||
| 128 | + backoff = BACKOFF_MIN; | ||
| 129 | + } | ||
| 130 | + full = false; | ||
| 121 | } | 131 | } |
| 122 | Err(error) => { | 132 | Err(error) => { |
| 123 | tracing::warn!(error = %error, retry_in = ?backoff, "directory: the mirror failed"); | 133 | tracing::warn!(error = %error, retry_in = ?backoff, "directory: the mirror failed"); |
| 134 | + full = true; | ||
| 124 | } | 135 | } |
| 125 | } | 136 | } |
| 126 | if wait_or_stop(jittered(backoff), &mut stop).await { | 137 | if wait_or_stop(jittered(backoff), &mut stop).await { |
| @@ -130,13 +141,16 @@ async fn run(state: AppState, oidc: std::sync::Arc<OidcClient>, mut stop: watch: | |||
| 130 | } | 141 | } |
| 131 | } | 142 | } |
| 132 | 143 | ||
| 133 | -/// One full read and then one stream connection. | 144 | +/// An optional full read, then one stream connection. |
| 134 | async fn mirror_once( | 145 | async fn mirror_once( |
| 135 | state: &AppState, | 146 | state: &AppState, |
| 136 | oidc: &OidcClient, | 147 | oidc: &OidcClient, |
| 137 | stop: &mut watch::Receiver<bool>, | 148 | stop: &mut watch::Receiver<bool>, |
| 149 | + full: bool, | ||
| 138 | ) -> std::result::Result<Ended, MirrorError> { | 150 | ) -> std::result::Result<Ended, MirrorError> { |
| 139 | - full_read(state, oidc).await?; | 151 | + if full { |
| 152 | + full_read(state, oidc).await?; | ||
| 153 | + } | ||
| 140 | stream(state, oidc, stop).await | 154 | stream(state, oidc, stop).await |
| 141 | } | 155 | } |
| 142 | 156 | ||
| @@ -223,6 +237,7 @@ async fn stream( | |||
| 223 | } | 237 | } |
| 224 | let mut chunks = response.bytes_stream(); | 238 | let mut chunks = response.bytes_stream(); |
| 225 | let mut parser = SseParser::default(); | 239 | let mut parser = SseParser::default(); |
| 240 | + let mut delivered = false; | ||
| 226 | loop { | 241 | loop { |
| 227 | let next = tokio::select! { | 242 | let next = tokio::select! { |
| 228 | _ = stop.wait_for(|stopped| *stopped) => return Ok(Ended::Stopped), | 243 | _ = stop.wait_for(|stopped| *stopped) => return Ok(Ended::Stopped), |
| @@ -230,12 +245,14 @@ async fn stream( | |||
| 230 | }; | 245 | }; |
| 231 | let chunk = match next { | 246 | let chunk = match next { |
| 232 | // Silence for longer than the limit: reconnect. | 247 | // Silence for longer than the limit: reconnect. |
| 233 | - Err(_elapsed) => return Ok(Ended::Closed), | 248 | + Err(_elapsed) => return Ok(Ended::Closed { delivered }), |
| 234 | - Ok(None) => return Ok(Ended::Closed), | 249 | + Ok(None) => return Ok(Ended::Closed { delivered }), |
| 235 | Ok(Some(Err(error))) => return Err(ImError::Unavailable(error.to_string()).into()), | 250 | Ok(Some(Err(error))) => return Err(ImError::Unavailable(error.to_string()).into()), |
| 236 | Ok(Some(Ok(bytes))) => bytes, | 251 | Ok(Some(Ok(bytes))) => bytes, |
| 237 | }; | 252 | }; |
| 238 | - for event in parser.feed(&chunk).map_err(ImError::BadResponse)? { | 253 | + let events = parser.feed(&chunk).map_err(ImError::BadResponse)?; |
| 254 | + delivered |= !events.is_empty(); | ||
| 255 | + for event in events { | ||
| 239 | match event.name.as_str() { | 256 | match event.name.as_str() { |
| 240 | "member" => match serde_json::from_str::<Value>(&event.data) | 257 | "member" => match serde_json::from_str::<Value>(&event.data) |
| 241 | .ok() | 258 | .ok() |
| @@ -426,11 +443,16 @@ impl SseParser { | |||
| 426 | } | 443 | } |
| 427 | } | 444 | } |
| 428 | 445 | ||
| 429 | -/// Fetches a member's photo from `im` with the service token. `None` when `im` has no photo, or the | 446 | +/// Fetches the photo of `sub` at `version` from `im` with the service token. `None` when `im` has no |
| 430 | -/// photo has a type iz does not serve. | 447 | +/// photo, or the photo has a type iz does not serve. The answer must carry the ETag of that version: |
| 431 | -pub async fn fetch_photo(oidc: &OidcClient, sub: &str) -> ImResult<Option<(String, Vec<u8>)>> { | 448 | +/// otherwise `im` has a newer photo, and it must not be cached under the older version. |
| 449 | +pub async fn fetch_photo( | ||
| 450 | + oidc: &OidcClient, | ||
| 451 | + sub: &str, | ||
| 452 | + version: i64, | ||
| 453 | +) -> ImResult<Option<(String, Vec<u8>)>> { | ||
| 432 | let token = oidc.service_token().await?; | 454 | let token = oidc.service_token().await?; |
| 433 | - let url = format!("{}/api/v1/people/{sub}/photo", oidc.issuer()); | 455 | + let url = format!("{}/api/v1/people/{sub}/photo?v={version}", oidc.issuer()); |
| 434 | let response = oidc | 456 | let response = oidc |
| 435 | .http() | 457 | .http() |
| 436 | .get(url) | 458 | .get(url) |
| @@ -464,6 +486,14 @@ pub async fn fetch_photo(oidc: &OidcClient, sub: &str) -> ImResult<Option<(Strin | |||
| 464 | if !PHOTO_TYPES.contains(&mime.as_str()) { | 486 | if !PHOTO_TYPES.contains(&mime.as_str()) { |
| 465 | return Ok(None); | 487 | return Ok(None); |
| 466 | } | 488 | } |
| 489 | + let etag = format!("\"p{version}\""); | ||
| 490 | + let answered = response | ||
| 491 | + .headers() | ||
| 492 | + .get(reqwest::header::ETAG) | ||
| 493 | + .and_then(|value| value.to_str().ok()); | ||
| 494 | + if answered != Some(etag.as_str()) { | ||
| 495 | + return Ok(None); | ||
| 496 | + } | ||
| 467 | let bytes = read_limited(response, PHOTO_MAX_BYTES).await?; | 497 | let bytes = read_limited(response, PHOTO_MAX_BYTES).await?; |
| 468 | Ok(Some((mime, bytes))) | 498 | Ok(Some((mime, bytes))) |
| 469 | } | 499 | } |
crates/iz-web/src/in_store.rsmodified+10 -7
| @@ -22,7 +22,7 @@ use http::header::{CONTENT_LENGTH, CONTENT_TYPE, RANGE}; | |||
| 22 | use serde_json::Value; | 22 | use serde_json::Value; |
| 23 | use tokio::io::AsyncReadExt; | 23 | use tokio::io::AsyncReadExt; |
| 24 | 24 | ||
| 25 | -use crate::oidc::OidcClient; | 25 | +use crate::oidc::{ImError, OidcClient, read_limited}; |
| 26 | 26 | ||
| 27 | /// The audience of every object call: the family key of `in`. | 27 | /// The audience of every object call: the family key of `in`. |
| 28 | pub const IN_AUDIENCE: &str = "in"; | 28 | pub const IN_AUDIENCE: &str = "in"; |
| @@ -40,8 +40,8 @@ const READ_STALL: Duration = Duration::from_secs(30); | |||
| 40 | const UPLOAD_FRAME: usize = 64 * 1024; | 40 | const UPLOAD_FRAME: usize = 64 * 1024; |
| 41 | /// The longest `X-Object-Name` sent, in bytes. `in` refuses longer names. | 41 | /// The longest `X-Object-Name` sent, in bytes. `in` refuses longer names. |
| 42 | const NAME_MAX_BYTES: usize = 255; | 42 | const NAME_MAX_BYTES: usize = 255; |
| 43 | -/// The largest JSON answer of a PUT that is read. | 43 | +/// The largest JSON answer of a PUT that is read, in bytes. |
| 44 | -const PUT_ANSWER_MAX: u64 = 4096; | 44 | +const PUT_ANSWER_MAX: usize = 4096; |
| 45 | 45 | ||
| 46 | /// Why a call to `in` did not give its answer. | 46 | /// Why a call to `in` did not give its answer. |
| 47 | #[derive(Debug, thiserror::Error)] | 47 | #[derive(Debug, thiserror::Error)] |
| @@ -143,10 +143,13 @@ impl InStore { | |||
| 143 | if status != 200 && status != 201 { | 143 | if status != 200 && status != 201 { |
| 144 | return Err(InError::Refused(status)); | 144 | return Err(InError::Refused(status)); |
| 145 | } | 145 | } |
| 146 | - let text = response.bytes().await.map_err(transport)?; | 146 | + // The cap applies while the body is read, so an oversized answer is never held whole. |
| 147 | - if u64::try_from(text.len()).unwrap_or(u64::MAX) > PUT_ANSWER_MAX { | 147 | + let text = read_limited(response, PUT_ANSWER_MAX) |
| 148 | - return Err(InError::BadResponse("the PUT answer is too large".into())); | 148 | + .await |
| 149 | - } | 149 | + .map_err(|error| match error { |
| 150 | + ImError::Unavailable(reason) => InError::Unavailable(reason), | ||
| 151 | + _ => InError::BadResponse("the PUT answer is too large".into()), | ||
| 152 | + })?; | ||
| 150 | let answer: Value = serde_json::from_slice(&text) | 153 | let answer: Value = serde_json::from_slice(&text) |
| 151 | .map_err(|error| InError::BadResponse(format!("the PUT answer: {error}")))?; | 154 | .map_err(|error| InError::BadResponse(format!("the PUT answer: {error}")))?; |
| 152 | let stored = Stored { | 155 | let stored = Stored { |
crates/iz-web/src/oidc.rsmodified+108 -21
| @@ -8,11 +8,12 @@ | |||
| 8 | //! It decides nothing about who may sign in: that is `pages/sign_in.rs` and the store. It keeps no | 8 | //! It decides nothing about who may sign in: that is `pages/sign_in.rs` and the store. It keeps no |
| 9 | //! session state: that is `iz_core::store::sessions`. | 9 | //! session state: that is `iz_core::store::sessions`. |
| 10 | //! | 10 | //! |
| 11 | -//! Verification accepts EdDSA only. The algorithm is checked before a key is looked up, so `none` | 11 | +//! Verification accepts EdDSA only. The shape, the algorithm and the `kid` are checked before any key |
| 12 | -//! and every other algorithm are refused. The checks are: the signature, `iss` equal to the | 12 | +//! set is fetched, so `none` and every other algorithm are refused without a call to `im`. The checks |
| 13 | -//! configured issuer, `aud` equal to the client id, `exp` with 60 seconds of leeway, `iat` not more | 13 | +//! are: the signature, `iss` equal to the configured issuer, `aud` equal to the client id, `exp` and |
| 14 | -//! than five minutes ahead, and the claims each token kind needs. The pure functions below take the | 14 | +//! `nbf` with 60 seconds of leeway, `iat` not more than five minutes ahead, and the claims each token |
| 15 | -//! key set and the clock as arguments, so the tests can run without a network. | 15 | +//! kind needs. The pure functions below take the key set and the clock as arguments, so the tests can |
| 16 | +//! run without a network. | ||
| 16 | 17 | ||
| 17 | use std::collections::HashMap; | 18 | use std::collections::HashMap; |
| 18 | use std::path::Path; | 19 | use std::path::Path; |
| @@ -52,7 +53,8 @@ pub const MAX_RESPONSE_BYTES: usize = 256 * 1024; | |||
| 52 | const DISCOVERY_TTL: Duration = Duration::from_secs(3600); | 53 | const DISCOVERY_TTL: Duration = Duration::from_secs(3600); |
| 53 | /// How long the JWKS is cached, before it is fetched again (contracts.md 2.2). | 54 | /// How long the JWKS is cached, before it is fetched again (contracts.md 2.2). |
| 54 | const KEYS_TTL: Duration = Duration::from_secs(3600); | 55 | const KEYS_TTL: Duration = Duration::from_secs(3600); |
| 55 | -/// The shortest gap between two JWKS fetches caused by unknown key ids (contracts.md 2.2). | 56 | +/// The shortest gap between two JWKS fetch attempts (contracts.md 2.2). It bounds the refetch for unknown |
| 57 | +/// key ids, and the retries after a failed fetch, so an unreachable `im` is not asked once per request. | ||
| 56 | const UNKNOWN_KEY_REFETCH: Duration = Duration::from_secs(60); | 58 | const UNKNOWN_KEY_REFETCH: Duration = Duration::from_secs(60); |
| 57 | /// A service token is replaced this long before it expires (contracts.md 2.6). | 59 | /// A service token is replaced this long before it expires (contracts.md 2.6). |
| 58 | const SERVICE_TOKEN_MARGIN: Duration = Duration::from_secs(60); | 60 | const SERVICE_TOKEN_MARGIN: Duration = Duration::from_secs(60); |
| @@ -216,13 +218,18 @@ pub struct OidcClient { | |||
| 216 | stream_http: reqwest::Client, | 218 | stream_http: reqwest::Client, |
| 217 | discovery: Mutex<Option<(Instant, Arc<Discovery>)>>, | 219 | discovery: Mutex<Option<(Instant, Arc<Discovery>)>>, |
| 218 | keys: Mutex<KeyCache>, | 220 | keys: Mutex<KeyCache>, |
| 221 | + /// Held across a JWKS fetch, so one fetch runs at a time. It is never held together with `keys`, | ||
| 222 | + /// which is only locked for reads and writes of the cache. | ||
| 223 | + refresh: Mutex<()>, | ||
| 219 | /// Client-credentials tokens by `(audience, scope)`. Each target has its own entry. | 224 | /// Client-credentials tokens by `(audience, scope)`. Each target has its own entry. |
| 220 | service: Mutex<HashMap<(String, String), (Instant, String)>>, | 225 | service: Mutex<HashMap<(String, String), (Instant, String)>>, |
| 221 | } | 226 | } |
| 222 | 227 | ||
| 223 | #[derive(Default)] | 228 | #[derive(Default)] |
| 224 | struct KeyCache { | 229 | struct KeyCache { |
| 230 | + /// The last key set fetched, and when it was fetched. | ||
| 225 | current: Option<(Instant, Arc<KeySet>)>, | 231 | current: Option<(Instant, Arc<KeySet>)>, |
| 232 | + /// When a fetch was last attempted, whether it succeeded or not. | ||
| 226 | last_fetch: Option<Instant>, | 233 | last_fetch: Option<Instant>, |
| 227 | } | 234 | } |
| 228 | 235 | ||
| @@ -259,6 +266,7 @@ impl OidcClient { | |||
| 259 | stream_http, | 266 | stream_http, |
| 260 | discovery: Mutex::new(None), | 267 | discovery: Mutex::new(None), |
| 261 | keys: Mutex::new(KeyCache::default()), | 268 | keys: Mutex::new(KeyCache::default()), |
| 269 | + refresh: Mutex::new(()), | ||
| 262 | service: Mutex::new(HashMap::new()), | 270 | service: Mutex::new(HashMap::new()), |
| 263 | }) | 271 | }) |
| 264 | } | 272 | } |
| @@ -307,21 +315,61 @@ impl OidcClient { | |||
| 307 | Ok(doc) | 315 | Ok(doc) |
| 308 | } | 316 | } |
| 309 | 317 | ||
| 310 | - /// The key set, from the cache when it is fresh. With `refetch_unknown` set, it is fetched again | 318 | + /// The key set to check a token against. A fresh cached set is used as it is. An expired one is |
| 311 | - /// unless the last fetch was less than a minute ago. | 319 | + /// fetched again, and when that fails the cached set is kept and used (contracts.md 2.2). With |
| 320 | + /// `refetch_unknown` set, a token names a key that is not in the set, so it is fetched again once | ||
| 321 | + /// [`UNKNOWN_KEY_REFETCH`] has passed since the last attempt. | ||
| 312 | async fn key_set(&self, refetch_unknown: bool) -> ImResult<Arc<KeySet>> { | 322 | async fn key_set(&self, refetch_unknown: bool) -> ImResult<Arc<KeySet>> { |
| 323 | + if let Some(keys) = self.keys_without_fetch(refetch_unknown).await? { | ||
| 324 | + return Ok(keys); | ||
| 325 | + } | ||
| 326 | + // One fetch at a time. The cache lock is not held here, so a slow `im` stalls only the callers | ||
| 327 | + // that need a fetch, never a caller that a cached set can answer. A caller that waited may find | ||
| 328 | + // the set refreshed by the one before it. | ||
| 329 | + let _single_flight = self.refresh.lock().await; | ||
| 330 | + if let Some(keys) = self.keys_without_fetch(refetch_unknown).await? { | ||
| 331 | + return Ok(keys); | ||
| 332 | + } | ||
| 333 | + self.keys.lock().await.last_fetch = Some(Instant::now()); | ||
| 334 | + let fetched = self.fetch_keys().await; | ||
| 313 | let mut cache = self.keys.lock().await; | 335 | let mut cache = self.keys.lock().await; |
| 314 | - if let Some((at, keys)) = cache.current.as_ref() { | 336 | + match fetched { |
| 315 | - if at.elapsed() < KEYS_TTL && !refetch_unknown { | 337 | + Ok(keys) => { |
| 316 | - return Ok(keys.clone()); | 338 | + cache.current = Some((Instant::now(), keys.clone())); |
| 339 | + Ok(keys) | ||
| 317 | } | 340 | } |
| 318 | - let recently_fetched = cache | 341 | + Err(error) => match &cache.current { |
| 319 | - .last_fetch | 342 | + Some((_, keys)) => { |
| 320 | - .is_some_and(|at| at.elapsed() < UNKNOWN_KEY_REFETCH); | 343 | + tracing::warn!(error = %error, "oidc: key fetch failed, keeping the cached keys"); |
| 321 | - if refetch_unknown && recently_fetched { | 344 | + Ok(keys.clone()) |
| 322 | - return Ok(keys.clone()); | 345 | + } |
| 346 | + None => Err(error), | ||
| 347 | + }, | ||
| 348 | + } | ||
| 349 | + } | ||
| 350 | + | ||
| 351 | + /// The cached key set, when no fetch is due: it is fresh, or a fetch was attempted less than | ||
| 352 | + /// [`UNKNOWN_KEY_REFETCH`] ago. `None` when a fetch is due. With no cached set and a fetch attempted | ||
| 353 | + /// that recently, the answer is an error at once, without a network call. | ||
| 354 | + async fn keys_without_fetch(&self, refetch_unknown: bool) -> ImResult<Option<Arc<KeySet>>> { | ||
| 355 | + let cache = self.keys.lock().await; | ||
| 356 | + let attempted_recently = cache | ||
| 357 | + .last_fetch | ||
| 358 | + .is_some_and(|at| at.elapsed() < UNKNOWN_KEY_REFETCH); | ||
| 359 | + match &cache.current { | ||
| 360 | + Some((at, keys)) => { | ||
| 361 | + let fresh = at.elapsed() < KEYS_TTL && !refetch_unknown; | ||
| 362 | + Ok((fresh || attempted_recently).then(|| keys.clone())) | ||
| 323 | } | 363 | } |
| 364 | + None if attempted_recently => Err(ImError::Unavailable( | ||
| 365 | + "the key set has not been fetched yet".into(), | ||
| 366 | + )), | ||
| 367 | + None => Ok(None), | ||
| 324 | } | 368 | } |
| 369 | + } | ||
| 370 | + | ||
| 371 | + /// Fetches the key set from `im`'s JWKS endpoint. Called only under `refresh`. | ||
| 372 | + async fn fetch_keys(&self) -> ImResult<Arc<KeySet>> { | ||
| 325 | let discovery = self.discovery().await?; | 373 | let discovery = self.discovery().await?; |
| 326 | let response = self | 374 | let response = self |
| 327 | .http | 375 | .http |
| @@ -336,11 +384,7 @@ impl OidcClient { | |||
| 336 | ))); | 384 | ))); |
| 337 | } | 385 | } |
| 338 | let body = read_limited(response, MAX_RESPONSE_BYTES).await?; | 386 | let body = read_limited(response, MAX_RESPONSE_BYTES).await?; |
| 339 | - let keys = Arc::new(KeySet::from_jwks(&body)?); | 387 | + Ok(Arc::new(KeySet::from_jwks(&body)?)) |
| 340 | - let now = Instant::now(); | ||
| 341 | - cache.last_fetch = Some(now); | ||
| 342 | - cache.current = Some((now, keys.clone())); | ||
| 343 | - Ok(keys) | ||
| 344 | } | 388 | } |
| 345 | 389 | ||
| 346 | /// Runs a check against the cached keys. A token that names an unknown key gets one more try | 390 | /// Runs a check against the cached keys. A token that names an unknown key gets one more try |
| @@ -479,6 +523,7 @@ impl OidcClient { | |||
| 479 | 523 | ||
| 480 | /// Verifies an ID token against the current keys, and the nonce of the flight. | 524 | /// Verifies an ID token against the current keys, and the nonce of the flight. |
| 481 | pub async fn verify_id_token(&self, token: &str, nonce: &str) -> ImResult<IdClaims> { | 525 | pub async fn verify_id_token(&self, token: &str, nonce: &str) -> ImResult<IdClaims> { |
| 526 | + check_shape(token)?; | ||
| 482 | let now = unix_now(); | 527 | let now = unix_now(); |
| 483 | self.with_keys(|keys| { | 528 | self.with_keys(|keys| { |
| 484 | verify_id_token(keys, &self.issuer, &self.client_id, token, nonce, now) | 529 | verify_id_token(keys, &self.issuer, &self.client_id, token, nonce, now) |
| @@ -488,6 +533,7 @@ impl OidcClient { | |||
| 488 | 533 | ||
| 489 | /// Verifies a back-channel logout token against the current keys. | 534 | /// Verifies a back-channel logout token against the current keys. |
| 490 | pub async fn verify_logout_token(&self, token: &str) -> ImResult<LogoutClaims> { | 535 | pub async fn verify_logout_token(&self, token: &str) -> ImResult<LogoutClaims> { |
| 536 | + check_shape(token)?; | ||
| 491 | let now = unix_now(); | 537 | let now = unix_now(); |
| 492 | self.with_keys(|keys| verify_logout_token(keys, &self.issuer, &self.client_id, token, now)) | 538 | self.with_keys(|keys| verify_logout_token(keys, &self.issuer, &self.client_id, token, now)) |
| 493 | .await | 539 | .await |
| @@ -570,6 +616,28 @@ pub fn verify_logout_token( | |||
| 570 | Ok(LogoutClaims { jti, sid, sub }) | 616 | Ok(LogoutClaims { jti, sid, sub }) |
| 571 | } | 617 | } |
| 572 | 618 | ||
| 619 | +/// Refuses a token that cannot verify before any key set is fetched: three segments, a header that | ||
| 620 | +/// names EdDSA, and a `kid`. A hostile token therefore costs no call to `im`. | ||
| 621 | +fn check_shape(token: &str) -> ImResult<()> { | ||
| 622 | + if token.split('.').count() != 3 { | ||
| 623 | + return Err(ImError::Rejected( | ||
| 624 | + "the token does not have three segments".into(), | ||
| 625 | + )); | ||
| 626 | + } | ||
| 627 | + let header = decode_header(token) | ||
| 628 | + .map_err(|e| ImError::Rejected(format!("the header is malformed: {e}")))?; | ||
| 629 | + if header.alg != Algorithm::EdDSA { | ||
| 630 | + return Err(ImError::Rejected(format!( | ||
| 631 | + "the algorithm {:?} is not accepted", | ||
| 632 | + header.alg | ||
| 633 | + ))); | ||
| 634 | + } | ||
| 635 | + if header.kid.is_none() { | ||
| 636 | + return Err(ImError::Rejected("the header has no kid".into())); | ||
| 637 | + } | ||
| 638 | + Ok(()) | ||
| 639 | +} | ||
| 640 | + | ||
| 573 | /// Checks the header, finds the key, and verifies the signature and the registered claims. Returns | 641 | /// Checks the header, finds the key, and verifies the signature and the registered claims. Returns |
| 574 | /// the claims as a map, for the token-specific checks. | 642 | /// the claims as a map, for the token-specific checks. |
| 575 | fn verify_signature( | 643 | fn verify_signature( |
| @@ -594,14 +662,33 @@ fn verify_signature( | |||
| 594 | let key = keys.get(kid).ok_or(ImError::UnknownKey)?; | 662 | let key = keys.get(kid).ok_or(ImError::UnknownKey)?; |
| 595 | let mut validation = Validation::new(Algorithm::EdDSA); | 663 | let mut validation = Validation::new(Algorithm::EdDSA); |
| 596 | validation.leeway = LEEWAY_SECS; | 664 | validation.leeway = LEEWAY_SECS; |
| 665 | + validation.validate_nbf = true; | ||
| 597 | validation.set_issuer(&[issuer]); | 666 | validation.set_issuer(&[issuer]); |
| 598 | validation.set_audience(&[client_id]); | 667 | validation.set_audience(&[client_id]); |
| 599 | validation.set_required_spec_claims(&["exp", "iss", "aud"]); | 668 | validation.set_required_spec_claims(&["exp", "iss", "aud"]); |
| 600 | let data = decode::<Map<String, Value>>(token, key, &validation) | 669 | let data = decode::<Map<String, Value>>(token, key, &validation) |
| 601 | .map_err(|e| ImError::Rejected(e.to_string()))?; | 670 | .map_err(|e| ImError::Rejected(e.to_string()))?; |
| 671 | + // `set_audience` accepts any member of an array, so the exact rule is applied here. | ||
| 672 | + if !audience_is(data.claims.get("aud"), client_id) { | ||
| 673 | + return Err(ImError::Rejected( | ||
| 674 | + "the aud claim is not the client id".into(), | ||
| 675 | + )); | ||
| 676 | + } | ||
| 602 | Ok(data.claims) | 677 | Ok(data.claims) |
| 603 | } | 678 | } |
| 604 | 679 | ||
| 680 | +/// Whether `aud` names `expected`. A string must equal it; an array must hold exactly that one value. | ||
| 681 | +/// Contracts require an exact `client_id`, so a longer audience list is refused. | ||
| 682 | +fn audience_is(aud: Option<&Value>, expected: &str) -> bool { | ||
| 683 | + match aud { | ||
| 684 | + Some(Value::String(single)) => single == expected, | ||
| 685 | + Some(Value::Array(items)) => { | ||
| 686 | + items.len() == 1 && items.first().and_then(Value::as_str) == Some(expected) | ||
| 687 | + } | ||
| 688 | + _ => false, | ||
| 689 | + } | ||
| 690 | +} | ||
| 691 | + | ||
| 605 | /// `iat` must be present and not more than [`MAX_IAT_AHEAD_SECS`] ahead of `now`. | 692 | /// `iat` must be present and not more than [`MAX_IAT_AHEAD_SECS`] ahead of `now`. |
| 606 | fn check_iat(claims: &Map<String, Value>, now: u64) -> ImResult<()> { | 693 | fn check_iat(claims: &Map<String, Value>, now: u64) -> ImResult<()> { |
| 607 | let iat = claims | 694 | let iat = claims |
crates/iz-web/src/pages/backchannel.rsmodified+6 -7
| @@ -6,7 +6,8 @@ | |||
| 6 | //! machine endpoint: no CSRF token, no cookie, and a body capped at 16 KiB. Success is `200` with an | 6 | //! machine endpoint: no CSRF token, no cookie, and a body capped at 16 KiB. Success is `200` with an |
| 7 | //! empty body. Every other answer is a JSON error (`docs/contracts.md` section 7): `413` for a body | 7 | //! empty body. Every other answer is a JSON error (`docs/contracts.md` section 7): `413` for a body |
| 8 | //! over 16 KiB, `503` when `im`'s keys cannot be fetched, `400` for anything else the request gets | 8 | //! over 16 KiB, `503` when `im`'s keys cannot be fetched, `400` for anything else the request gets |
| 9 | -//! wrong (a token iz refuses, a replayed token included), and `500` when the database fails. | 9 | +//! wrong (a token iz refuses), and `500` when the database fails. A token whose id was already applied |
| 10 | +//! answers `200`: its sessions ended on the first delivery. | ||
| 10 | 11 | ||
| 11 | use std::time::Duration; | 12 | use std::time::Duration; |
| 12 | 13 | ||
| @@ -125,13 +126,11 @@ async fn backchannel_logout(cx: &Cx, body: Body) -> Result<(StatusCode, HeaderMa | |||
| 125 | tracing::info!(ended, "back-channel logout"); | 126 | tracing::info!(ended, "back-channel logout"); |
| 126 | Ok((StatusCode::OK, HeaderMap::new(), String::new())) | 127 | Ok((StatusCode::OK, HeaderMap::new(), String::new())) |
| 127 | } | 128 | } |
| 129 | + // The sessions of this token already ended on its first use. A redelivery (im retries when its | ||
| 130 | + // 200 was lost) is answered as success, so im does not count it as a failure. | ||
| 128 | Err(BackchannelError::Replay) => { | 131 | Err(BackchannelError::Replay) => { |
| 129 | - tracing::warn!("back-channel logout: a token was replayed"); | 132 | + tracing::info!("back-channel logout: a token was delivered again"); |
| 130 | - Ok(json_error( | 133 | + Ok((StatusCode::OK, HeaderMap::new(), String::new())) |
| 131 | - StatusCode::BAD_REQUEST, | ||
| 132 | - "invalid_request", | ||
| 133 | - "the logout token was already used", | ||
| 134 | - )) | ||
| 135 | } | 134 | } |
| 136 | Err(BackchannelError::Store(error)) => { | 135 | Err(BackchannelError::Store(error)) => { |
| 137 | tracing::error!(error = %error, "back-channel logout: the database failed"); | 136 | tracing::error!(error = %error, "back-channel logout: the database failed"); |
crates/iz-web/src/pages/photo.rsmodified+5 -2
| @@ -108,7 +108,7 @@ async fn load(state: &AppState, sub: &str, version: i64) -> Option<(String, Vec< | |||
| 108 | return Some(cached); | 108 | return Some(cached); |
| 109 | } | 109 | } |
| 110 | let oidc = state.oidc.as_ref()?; | 110 | let oidc = state.oidc.as_ref()?; |
| 111 | - match fetch_photo(oidc, sub).await { | 111 | + match fetch_photo(oidc, sub, version).await { |
| 112 | Ok(Some((mime, bytes))) => { | 112 | Ok(Some((mime, bytes))) => { |
| 113 | if let Err(error) = write_cache(&dir, version, &mime, &bytes).await { | 113 | if let Err(error) = write_cache(&dir, version, &mime, &bytes).await { |
| 114 | tracing::warn!(error = %error, "photo: could not write the cache"); | 114 | tracing::warn!(error = %error, "photo: could not write the cache"); |
| @@ -140,7 +140,10 @@ async fn read_cache(path: &Path) -> Option<(String, Vec<u8>)> { | |||
| 140 | async fn write_cache(dir: &Path, version: i64, mime: &str, bytes: &[u8]) -> std::io::Result<()> { | 140 | async fn write_cache(dir: &Path, version: i64, mime: &str, bytes: &[u8]) -> std::io::Result<()> { |
| 141 | tokio::fs::create_dir_all(dir).await?; | 141 | tokio::fs::create_dir_all(dir).await?; |
| 142 | let name = format!("{version}.img"); | 142 | let name = format!("{version}.img"); |
| 143 | - let tmp = dir.join(format!("{version}.tmp")); | 143 | + // A random suffix per write, so two concurrent writers of one version never share a temporary file. |
| 144 | + let mut suffix = [0u8; 8]; | ||
| 145 | + rand::fill(&mut suffix); | ||
| 146 | + let tmp = dir.join(format!("{version}.{}.tmp", hex::encode(suffix))); | ||
| 144 | let mut data = Vec::with_capacity(mime.len() + 1 + bytes.len()); | 147 | let mut data = Vec::with_capacity(mime.len() + 1 + bytes.len()); |
| 145 | data.extend_from_slice(mime.as_bytes()); | 148 | data.extend_from_slice(mime.as_bytes()); |
| 146 | data.push(b'\n'); | 149 | data.push(b'\n'); |