diff --git a/crates/iz-web/src/directory.rs b/crates/iz-web/src/directory.rs index 1fa34ad..c9b6675 100644 --- a/crates/iz-web/src/directory.rs +++ b/crates/iz-web/src/directory.rs @@ -95,7 +95,8 @@ enum Ended { /// `im` asked for a full read again. Resync, /// The stream closed, went idle, or `im` closed it after 50 minutes. Reconnect with the cursor. - Closed, + /// `delivered` says whether the connection carried any event. + Closed { delivered: bool }, } /// Starts the mirror. Does nothing when OIDC is not configured. @@ -108,19 +109,29 @@ pub fn spawn(state: AppState, stop: watch::Receiver) { async fn run(state: AppState, oidc: std::sync::Arc, mut stop: watch::Receiver) { let mut backoff = BACKOFF_MIN; + // A full read is needed at the start, after a resync, and after a failure. A plain reconnect + // resumes from the stored cursor, so it does not read the whole listing again. + let mut full = true; loop { - match mirror_once(&state, &oidc, &mut stop).await { + match mirror_once(&state, &oidc, &mut stop, full).await { Ok(Ended::Stopped) => return, Ok(Ended::Resync) => { tracing::info!("directory: the stream asked for a full read"); backoff = BACKOFF_MIN; + full = true; } - Ok(Ended::Closed) => { + Ok(Ended::Closed { delivered }) => { tracing::info!("directory: the stream closed; reconnecting"); - backoff = BACKOFF_MIN; + // A connection that carried events resets the wait. A silent one keeps growing it, so + // an `im` that closes streams at once is not polled every second. + if delivered { + backoff = BACKOFF_MIN; + } + full = false; } Err(error) => { tracing::warn!(error = %error, retry_in = ?backoff, "directory: the mirror failed"); + full = true; } } if wait_or_stop(jittered(backoff), &mut stop).await { @@ -130,13 +141,16 @@ async fn run(state: AppState, oidc: std::sync::Arc, mut stop: watch: } } -/// One full read and then one stream connection. +/// An optional full read, then one stream connection. async fn mirror_once( state: &AppState, oidc: &OidcClient, stop: &mut watch::Receiver, + full: bool, ) -> std::result::Result { - full_read(state, oidc).await?; + if full { + full_read(state, oidc).await?; + } stream(state, oidc, stop).await } @@ -223,6 +237,7 @@ async fn stream( } let mut chunks = response.bytes_stream(); let mut parser = SseParser::default(); + let mut delivered = false; loop { let next = tokio::select! { _ = stop.wait_for(|stopped| *stopped) => return Ok(Ended::Stopped), @@ -230,12 +245,14 @@ async fn stream( }; let chunk = match next { // Silence for longer than the limit: reconnect. - Err(_elapsed) => return Ok(Ended::Closed), - Ok(None) => return Ok(Ended::Closed), + Err(_elapsed) => return Ok(Ended::Closed { delivered }), + Ok(None) => return Ok(Ended::Closed { delivered }), Ok(Some(Err(error))) => return Err(ImError::Unavailable(error.to_string()).into()), Ok(Some(Ok(bytes))) => bytes, }; - for event in parser.feed(&chunk).map_err(ImError::BadResponse)? { + let events = parser.feed(&chunk).map_err(ImError::BadResponse)?; + delivered |= !events.is_empty(); + for event in events { match event.name.as_str() { "member" => match serde_json::from_str::(&event.data) .ok() @@ -426,11 +443,16 @@ impl SseParser { } } -/// Fetches a member's photo from `im` with the service token. `None` when `im` has no photo, or the -/// photo has a type iz does not serve. -pub async fn fetch_photo(oidc: &OidcClient, sub: &str) -> ImResult)>> { +/// Fetches the photo of `sub` at `version` from `im` with the service token. `None` when `im` has no +/// photo, or the photo has a type iz does not serve. The answer must carry the ETag of that version: +/// otherwise `im` has a newer photo, and it must not be cached under the older version. +pub async fn fetch_photo( + oidc: &OidcClient, + sub: &str, + version: i64, +) -> ImResult)>> { let token = oidc.service_token().await?; - let url = format!("{}/api/v1/people/{sub}/photo", oidc.issuer()); + let url = format!("{}/api/v1/people/{sub}/photo?v={version}", oidc.issuer()); let response = oidc .http() .get(url) @@ -464,6 +486,14 @@ pub async fn fetch_photo(oidc: &OidcClient, sub: &str) -> ImResult PUT_ANSWER_MAX { - return Err(InError::BadResponse("the PUT answer is too large".into())); - } + // The cap applies while the body is read, so an oversized answer is never held whole. + let text = read_limited(response, PUT_ANSWER_MAX) + .await + .map_err(|error| match error { + ImError::Unavailable(reason) => InError::Unavailable(reason), + _ => InError::BadResponse("the PUT answer is too large".into()), + })?; let answer: Value = serde_json::from_slice(&text) .map_err(|error| InError::BadResponse(format!("the PUT answer: {error}")))?; let stored = Stored { diff --git a/crates/iz-web/src/oidc.rs b/crates/iz-web/src/oidc.rs index e9fd597..5a73442 100644 --- a/crates/iz-web/src/oidc.rs +++ b/crates/iz-web/src/oidc.rs @@ -8,11 +8,12 @@ //! It decides nothing about who may sign in: that is `pages/sign_in.rs` and the store. It keeps no //! session state: that is `iz_core::store::sessions`. //! -//! Verification accepts EdDSA only. The algorithm is checked before a key is looked up, so `none` -//! and every other algorithm are refused. The checks are: the signature, `iss` equal to the -//! configured issuer, `aud` equal to the client id, `exp` with 60 seconds of leeway, `iat` not more -//! than five minutes ahead, and the claims each token kind needs. The pure functions below take the -//! key set and the clock as arguments, so the tests can run without a network. +//! Verification accepts EdDSA only. The shape, the algorithm and the `kid` are checked before any key +//! set is fetched, so `none` and every other algorithm are refused without a call to `im`. The checks +//! are: the signature, `iss` equal to the configured issuer, `aud` equal to the client id, `exp` and +//! `nbf` with 60 seconds of leeway, `iat` not more than five minutes ahead, and the claims each token +//! kind needs. The pure functions below take the key set and the clock as arguments, so the tests can +//! run without a network. use std::collections::HashMap; use std::path::Path; @@ -52,7 +53,8 @@ pub const MAX_RESPONSE_BYTES: usize = 256 * 1024; const DISCOVERY_TTL: Duration = Duration::from_secs(3600); /// How long the JWKS is cached, before it is fetched again (contracts.md 2.2). const KEYS_TTL: Duration = Duration::from_secs(3600); -/// The shortest gap between two JWKS fetches caused by unknown key ids (contracts.md 2.2). +/// The shortest gap between two JWKS fetch attempts (contracts.md 2.2). It bounds the refetch for unknown +/// key ids, and the retries after a failed fetch, so an unreachable `im` is not asked once per request. const UNKNOWN_KEY_REFETCH: Duration = Duration::from_secs(60); /// A service token is replaced this long before it expires (contracts.md 2.6). const SERVICE_TOKEN_MARGIN: Duration = Duration::from_secs(60); @@ -216,13 +218,18 @@ pub struct OidcClient { stream_http: reqwest::Client, discovery: Mutex)>>, keys: Mutex, + /// Held across a JWKS fetch, so one fetch runs at a time. It is never held together with `keys`, + /// which is only locked for reads and writes of the cache. + refresh: Mutex<()>, /// Client-credentials tokens by `(audience, scope)`. Each target has its own entry. service: Mutex>, } #[derive(Default)] struct KeyCache { + /// The last key set fetched, and when it was fetched. current: Option<(Instant, Arc)>, + /// When a fetch was last attempted, whether it succeeded or not. last_fetch: Option, } @@ -259,6 +266,7 @@ impl OidcClient { stream_http, discovery: Mutex::new(None), keys: Mutex::new(KeyCache::default()), + refresh: Mutex::new(()), service: Mutex::new(HashMap::new()), }) } @@ -307,21 +315,61 @@ impl OidcClient { Ok(doc) } - /// The key set, from the cache when it is fresh. With `refetch_unknown` set, it is fetched again - /// unless the last fetch was less than a minute ago. + /// The key set to check a token against. A fresh cached set is used as it is. An expired one is + /// fetched again, and when that fails the cached set is kept and used (contracts.md 2.2). With + /// `refetch_unknown` set, a token names a key that is not in the set, so it is fetched again once + /// [`UNKNOWN_KEY_REFETCH`] has passed since the last attempt. async fn key_set(&self, refetch_unknown: bool) -> ImResult> { + if let Some(keys) = self.keys_without_fetch(refetch_unknown).await? { + return Ok(keys); + } + // One fetch at a time. The cache lock is not held here, so a slow `im` stalls only the callers + // that need a fetch, never a caller that a cached set can answer. A caller that waited may find + // the set refreshed by the one before it. + let _single_flight = self.refresh.lock().await; + if let Some(keys) = self.keys_without_fetch(refetch_unknown).await? { + return Ok(keys); + } + self.keys.lock().await.last_fetch = Some(Instant::now()); + let fetched = self.fetch_keys().await; let mut cache = self.keys.lock().await; - if let Some((at, keys)) = cache.current.as_ref() { - if at.elapsed() < KEYS_TTL && !refetch_unknown { - return Ok(keys.clone()); + match fetched { + Ok(keys) => { + cache.current = Some((Instant::now(), keys.clone())); + Ok(keys) } - let recently_fetched = cache - .last_fetch - .is_some_and(|at| at.elapsed() < UNKNOWN_KEY_REFETCH); - if refetch_unknown && recently_fetched { - return Ok(keys.clone()); + Err(error) => match &cache.current { + Some((_, keys)) => { + tracing::warn!(error = %error, "oidc: key fetch failed, keeping the cached keys"); + Ok(keys.clone()) + } + None => Err(error), + }, + } + } + + /// The cached key set, when no fetch is due: it is fresh, or a fetch was attempted less than + /// [`UNKNOWN_KEY_REFETCH`] ago. `None` when a fetch is due. With no cached set and a fetch attempted + /// that recently, the answer is an error at once, without a network call. + async fn keys_without_fetch(&self, refetch_unknown: bool) -> ImResult>> { + let cache = self.keys.lock().await; + let attempted_recently = cache + .last_fetch + .is_some_and(|at| at.elapsed() < UNKNOWN_KEY_REFETCH); + match &cache.current { + Some((at, keys)) => { + let fresh = at.elapsed() < KEYS_TTL && !refetch_unknown; + Ok((fresh || attempted_recently).then(|| keys.clone())) } + None if attempted_recently => Err(ImError::Unavailable( + "the key set has not been fetched yet".into(), + )), + None => Ok(None), } + } + + /// Fetches the key set from `im`'s JWKS endpoint. Called only under `refresh`. + async fn fetch_keys(&self) -> ImResult> { let discovery = self.discovery().await?; let response = self .http @@ -336,11 +384,7 @@ impl OidcClient { ))); } let body = read_limited(response, MAX_RESPONSE_BYTES).await?; - let keys = Arc::new(KeySet::from_jwks(&body)?); - let now = Instant::now(); - cache.last_fetch = Some(now); - cache.current = Some((now, keys.clone())); - Ok(keys) + Ok(Arc::new(KeySet::from_jwks(&body)?)) } /// Runs a check against the cached keys. A token that names an unknown key gets one more try @@ -479,6 +523,7 @@ impl OidcClient { /// Verifies an ID token against the current keys, and the nonce of the flight. pub async fn verify_id_token(&self, token: &str, nonce: &str) -> ImResult { + check_shape(token)?; let now = unix_now(); self.with_keys(|keys| { verify_id_token(keys, &self.issuer, &self.client_id, token, nonce, now) @@ -488,6 +533,7 @@ impl OidcClient { /// Verifies a back-channel logout token against the current keys. pub async fn verify_logout_token(&self, token: &str) -> ImResult { + check_shape(token)?; let now = unix_now(); self.with_keys(|keys| verify_logout_token(keys, &self.issuer, &self.client_id, token, now)) .await @@ -570,6 +616,28 @@ pub fn verify_logout_token( Ok(LogoutClaims { jti, sid, sub }) } +/// Refuses a token that cannot verify before any key set is fetched: three segments, a header that +/// names EdDSA, and a `kid`. A hostile token therefore costs no call to `im`. +fn check_shape(token: &str) -> ImResult<()> { + if token.split('.').count() != 3 { + return Err(ImError::Rejected( + "the token does not have three segments".into(), + )); + } + let header = decode_header(token) + .map_err(|e| ImError::Rejected(format!("the header is malformed: {e}")))?; + if header.alg != Algorithm::EdDSA { + return Err(ImError::Rejected(format!( + "the algorithm {:?} is not accepted", + header.alg + ))); + } + if header.kid.is_none() { + return Err(ImError::Rejected("the header has no kid".into())); + } + Ok(()) +} + /// Checks the header, finds the key, and verifies the signature and the registered claims. Returns /// the claims as a map, for the token-specific checks. fn verify_signature( @@ -594,14 +662,33 @@ fn verify_signature( let key = keys.get(kid).ok_or(ImError::UnknownKey)?; let mut validation = Validation::new(Algorithm::EdDSA); validation.leeway = LEEWAY_SECS; + validation.validate_nbf = true; validation.set_issuer(&[issuer]); validation.set_audience(&[client_id]); validation.set_required_spec_claims(&["exp", "iss", "aud"]); let data = decode::>(token, key, &validation) .map_err(|e| ImError::Rejected(e.to_string()))?; + // `set_audience` accepts any member of an array, so the exact rule is applied here. + if !audience_is(data.claims.get("aud"), client_id) { + return Err(ImError::Rejected( + "the aud claim is not the client id".into(), + )); + } Ok(data.claims) } +/// Whether `aud` names `expected`. A string must equal it; an array must hold exactly that one value. +/// Contracts require an exact `client_id`, so a longer audience list is refused. +fn audience_is(aud: Option<&Value>, expected: &str) -> bool { + match aud { + Some(Value::String(single)) => single == expected, + Some(Value::Array(items)) => { + items.len() == 1 && items.first().and_then(Value::as_str) == Some(expected) + } + _ => false, + } +} + /// `iat` must be present and not more than [`MAX_IAT_AHEAD_SECS`] ahead of `now`. fn check_iat(claims: &Map, now: u64) -> ImResult<()> { let iat = claims diff --git a/crates/iz-web/src/pages/backchannel.rs b/crates/iz-web/src/pages/backchannel.rs index f3f9c53..e4665f4 100644 --- a/crates/iz-web/src/pages/backchannel.rs +++ b/crates/iz-web/src/pages/backchannel.rs @@ -6,7 +6,8 @@ //! machine endpoint: no CSRF token, no cookie, and a body capped at 16 KiB. Success is `200` with an //! empty body. Every other answer is a JSON error (`docs/contracts.md` section 7): `413` for a body //! over 16 KiB, `503` when `im`'s keys cannot be fetched, `400` for anything else the request gets -//! wrong (a token iz refuses, a replayed token included), and `500` when the database fails. +//! wrong (a token iz refuses), and `500` when the database fails. A token whose id was already applied +//! answers `200`: its sessions ended on the first delivery. use std::time::Duration; @@ -125,13 +126,11 @@ async fn backchannel_logout(cx: &Cx, body: Body) -> Result<(StatusCode, HeaderMa tracing::info!(ended, "back-channel logout"); Ok((StatusCode::OK, HeaderMap::new(), String::new())) } + // The sessions of this token already ended on its first use. A redelivery (im retries when its + // 200 was lost) is answered as success, so im does not count it as a failure. Err(BackchannelError::Replay) => { - tracing::warn!("back-channel logout: a token was replayed"); - Ok(json_error( - StatusCode::BAD_REQUEST, - "invalid_request", - "the logout token was already used", - )) + tracing::info!("back-channel logout: a token was delivered again"); + Ok((StatusCode::OK, HeaderMap::new(), String::new())) } Err(BackchannelError::Store(error)) => { tracing::error!(error = %error, "back-channel logout: the database failed"); diff --git a/crates/iz-web/src/pages/photo.rs b/crates/iz-web/src/pages/photo.rs index 6ee2a76..1ff527c 100644 --- a/crates/iz-web/src/pages/photo.rs +++ b/crates/iz-web/src/pages/photo.rs @@ -108,7 +108,7 @@ async fn load(state: &AppState, sub: &str, version: i64) -> Option<(String, Vec< return Some(cached); } let oidc = state.oidc.as_ref()?; - match fetch_photo(oidc, sub).await { + match fetch_photo(oidc, sub, version).await { Ok(Some((mime, bytes))) => { if let Err(error) = write_cache(&dir, version, &mime, &bytes).await { tracing::warn!(error = %error, "photo: could not write the cache"); @@ -140,7 +140,10 @@ async fn read_cache(path: &Path) -> Option<(String, Vec)> { async fn write_cache(dir: &Path, version: i64, mime: &str, bytes: &[u8]) -> std::io::Result<()> { tokio::fs::create_dir_all(dir).await?; let name = format!("{version}.img"); - let tmp = dir.join(format!("{version}.tmp")); + // A random suffix per write, so two concurrent writers of one version never share a temporary file. + let mut suffix = [0u8; 8]; + rand::fill(&mut suffix); + let tmp = dir.join(format!("{version}.{}.tmp", hex::encode(suffix))); let mut data = Vec::with_capacity(mime.len() + 1 + bytes.len()); data.extend_from_slice(mime.as_bytes()); data.push(b'\n');