forge
Explore
Log in

Don't you dare go Hollow

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 commit

f94f61ebb81e47937563778ad9636b34122d74edAhmet Kaan GümüşParent: 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
Show full message
🔒 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
Cargo.lockmodified+1 -0
@@ -2004,6 +2004,7 @@ dependencies = [
20042004 "topcoat",
20052005 "tracing",
20062006 "tracing-subscriber",
2007+ "ulid",
20072008 ]
20082009
20092010 [[package]]
crates/in-web/Cargo.tomlmodified+1 -0
@@ -33,6 +33,7 @@ tokio = { workspace = true, features = ["net", "signal", "time", "sync", "fs", "
3333 topcoat.workspace = true
3434 tracing.workspace = true
3535 tracing-subscriber = { workspace = true, features = ["env-filter"] }
36+ulid.workspace = true
3637
3738 [dev-dependencies]
3839 serde_urlencoded.workspace = true
crates/in-web/src/directory.rsmodified+68 -19
@@ -8,10 +8,12 @@
88 //!
99 //! When the stream fails, the worker waits with exponential backoff from 1 s to 60 s, each wait a random
1010 //! 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.
1214
1315 use std::collections::HashSet;
14-use std::time::Duration;
16+use std::time::{Duration, Instant};
1517
1618 use futures_util::StreamExt;
1719 use http::header::ACCEPT;
@@ -20,7 +22,7 @@ use in_core::time::now_stamp;
2022 use serde::Deserialize;
2123 use tokio::sync::watch;
2224
23-use crate::oidc::{OidcClient, OidcError};
25+use crate::oidc::{OidcClient, OidcError, read_limited};
2426 use crate::state::AppState;
2527
2628 /// The `settings` key of the directory cursor.
@@ -35,6 +37,16 @@ const BACKOFF_MAX: Duration = Duration::from_secs(60);
3537 /// The pause after a stream that ended cleanly, before it is reconnected.
3638 const CLEAN_PAUSE: Duration = Duration::from_secs(1);
3739
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+
3850 /// Why one round of syncing failed.
3951 #[derive(Debug, thiserror::Error)]
4052 enum SyncError {
@@ -53,6 +65,9 @@ enum SyncError {
5365 /// The full directory could not be read.
5466 #[error("the directory listing is not what the contracts describe")]
5567 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,
5671 }
5772
5873 /// One member as the directory sends it (contracts section 3.1). Unknown fields are ignored.
@@ -111,8 +126,9 @@ struct SseParser {
111126
112127 impl SseParser {
113128 /// 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> {
116132 self.buffer.extend_from_slice(chunk);
117133 let mut events = Vec::new();
118134 while let Some(end) = self.buffer.iter().position(|byte| *byte == b'\n') {
@@ -144,12 +160,20 @@ impl SseParser {
144160 };
145161 match field {
146162 "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+ }
148169 "id" => self.id = Some(value.to_owned()),
149170 _ => {}
150171 }
151172 }
152- events
173+ if self.buffer.len() > MAX_STREAM_BYTES {
174+ return Err(SyncError::TooLarge);
175+ }
176+ Ok(events)
153177 }
154178 }
155179
@@ -157,8 +181,16 @@ impl SseParser {
157181 enum Ended {
158182 /// The server asked for a full fetch.
159183 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+ }
162194 }
163195
164196 /// 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>) {
178210 backoff = BACKOFF_FIRST;
179211 CLEAN_PAUSE
180212 }
181- Ok(Ended::Closed) => {
213+ Ok(Ended::Closed { healthy: true }) => {
182214 backoff = BACKOFF_FIRST;
183215 CLEAN_PAUSE
184216 }
217+ Ok(Ended::Closed { healthy: false }) => {
218+ let pause = jittered(backoff);
219+ backoff = (backoff * 2).min(BACKOFF_MAX);
220+ pause
221+ }
185222 Err(error) => {
186223 tracing::warn!(error = %error, "directory: sync failed, retrying");
187224 needs_full = true;
@@ -225,10 +262,10 @@ async fn full_sync(state: &AppState, oidc: &OidcClient) -> Result<(), SyncError>
225262 if !response.status().is_success() {
226263 return Err(SyncError::Status(response.status()));
227264 }
228- let bytes = response
229- .bytes()
265+ let bytes = read_limited(response, ROSTER_MAX_BYTES)
230266 .await
231- .map_err(|e| SyncError::Transport(e.to_string()))?;
267+ .map_err(|e| SyncError::Transport(e.to_string()))?
268+ .ok_or(SyncError::TooLarge)?;
232269 let listing: Listing = serde_json::from_slice(&bytes).map_err(|_| SyncError::Listing)?;
233270
234271 let mut named = HashSet::new();
@@ -274,18 +311,21 @@ async fn follow(
274311 }
275312 tracing::info!("directory: stream connected");
276313
314+ let opened = Instant::now();
315+ let mut applied = false;
277316 let mut body = response.bytes_stream();
278317 let mut parser = SseParser::default();
279318 loop {
280319 let chunk = tokio::select! {
281320 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)),
283322 };
284323 let Some(chunk) = chunk else {
285- return Ok(Ended::Closed);
324+ return Ok(closed(opened, applied));
286325 };
287326 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;
289329 if let Some(ended) = apply_event(state, event).await? {
290330 return Ok(ended);
291331 }
@@ -400,8 +440,15 @@ mod tests {
400440 #[test]
401441 fn events_are_parsed_across_chunks_and_comments_are_skipped() {
402442 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");
405452 assert_eq!(
406453 events,
407454 vec![SseEvent {
@@ -410,7 +457,9 @@ mod tests {
410457 data: "{\"sub\":\"a\"}".into(),
411458 }]
412459 );
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");
414463 assert_eq!(events[0].event, "resync");
415464 }
416465
crates/in-web/src/oidc.rsmodified+149 -74
@@ -18,7 +18,7 @@ use in_core::config::Oidc;
1818 use in_core::error::{Error as CoreError, Result as CoreResult};
1919 use in_core::token::constant_time_eq;
2020 use jsonwebtoken::errors::ErrorKind;
21-use jsonwebtoken::{Algorithm, DecodingKey, Validation, decode, decode_header};
21+use jsonwebtoken::{Algorithm, DecodingKey, Validation, decode};
2222 use serde::Deserialize;
2323 use serde_json::{Map, Value};
2424 use sha2::{Digest, Sha256};
@@ -33,8 +33,9 @@ pub const MAX_FUTURE_IAT_SECS: i64 = 300;
3333 /// How long a fetched key set is used before it is fetched again (contracts section 2.2).
3434 pub const JWKS_MAX_AGE: Duration = Duration::from_secs(60 * 60);
3535
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.
3839 pub const JWKS_REFRESH_GAP: Duration = Duration::from_secs(60);
3940
4041 /// 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> {
274275 Ok(())
275276 }
276277
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`.
279280 ///
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+ }
288289 let header_bytes = BASE64_URL_SAFE_NO_PAD
289- .decode(first_segment)
290+ .decode(segments[0])
290291 .map_err(|_| TokenError::Malformed)?;
291292 let header: Value = serde_json::from_slice(&header_bytes).map_err(|_| TokenError::Malformed)?;
292293 if header.get("alg").and_then(Value::as_str) != Some("EdDSA") {
293294 return Err(TokenError::Algorithm);
294295 }
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)?;
297313 let key = keys.get(&kid).ok_or(TokenError::UnknownKey)?;
298314
299315 let mut validation = Validation::new(Algorithm::EdDSA);
300316 validation.leeway = u64::try_from(CLOCK_LEEWAY_SECS).unwrap_or(0);
301317 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;
302320 // Audience is checked by the callers, because the rule differs by token kind.
303321 validation.validate_aud = false;
304322 validation.set_issuer(&[issuer]);
@@ -312,6 +330,7 @@ pub fn verify_signed(
312330 ErrorKind::InvalidSignature => TokenError::Signature,
313331 ErrorKind::InvalidIssuer => TokenError::Claim("iss"),
314332 ErrorKind::InvalidAlgorithm => TokenError::Algorithm,
333+ ErrorKind::ImmatureSignature => TokenError::Claim("nbf"),
315334 ErrorKind::MissingRequiredClaim(_) => TokenError::Claim("required claim"),
316335 _ => TokenError::Malformed,
317336 }
@@ -512,6 +531,29 @@ pub fn pkce_challenge(verifier: &str) -> String {
512531 BASE64_URL_SAFE_NO_PAD.encode(Sha256::digest(verifier.as_bytes()))
513532 }
514533
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+
515557 /// Percent-encodes one value for a query, a form body or a Basic credential (RFC 6749 section 2.3.1):
516558 /// unreserved characters pass, everything else becomes `%XX`.
517559 pub fn percent_encode(value: &str) -> String {
@@ -537,8 +579,8 @@ struct TokenResponse {
537579 expires_in: Option<u64>,
538580 }
539581
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.
542584 #[derive(Default)]
543585 struct Cache {
544586 /// The endpoints from discovery, once fetched.
@@ -554,6 +596,26 @@ struct Cache {
554596 service: Option<(String, Instant)>,
555597 }
556598
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+
557619 /// The OpenID Connect client. One per process, shared through the app state.
558620 pub struct OidcClient {
559621 issuer: String,
@@ -563,6 +625,9 @@ pub struct OidcClient {
563625 http: reqwest::Client,
564626 stream_http: reqwest::Client,
565627 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<()>,
566631 }
567632
568633 impl OidcClient {
@@ -590,6 +655,7 @@ impl OidcClient {
590655 http,
591656 stream_http,
592657 cache: Mutex::new(Cache::default()),
658+ refresh: Mutex::new(()),
593659 })
594660 }
595661
@@ -611,28 +677,34 @@ impl OidcClient {
611677 /// The endpoints of `im`. Fetched from discovery once; when discovery fails, the standard paths
612678 /// under the issuer are used and discovery is retried after [`DISCOVERY_RETRY_GAP`].
613679 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+ }
617691 }
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())
633706 }
634707 }
635- Arc::new(self.standard_endpoints())
636708 }
637709
638710 /// The paths of contracts section 2.1, under the issuer.
@@ -686,33 +758,25 @@ impl OidcClient {
686758 serde_json::from_slice(&bytes).map_err(|e| OidcError::Unavailable(e.to_string()))
687759 }
688760
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.
691764 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;
703768 }
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;
713774 }
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 {
716780 Ok(jwks) => {
717781 let keys = Arc::new(KeySet::from_jwks(&jwks));
718782 cache.keys = Some((Instant::now(), Arc::clone(&keys)));
@@ -735,15 +799,20 @@ impl OidcClient {
735799 token: &str,
736800 audience: &str,
737801 ) -> 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
740806 }
741807
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.
743810 async fn verify_with<T>(
744811 &self,
812+ token: &str,
745813 check: impl Fn(&KeySet) -> Result<T, TokenError>,
746814 ) -> Result<T, OidcError> {
815+ check_header(token)?;
747816 let keys = self.load_keys(false).await?;
748817 match check(&keys) {
749818 Err(TokenError::UnknownKey) => {
@@ -756,14 +825,18 @@ impl OidcClient {
756825
757826 /// Verifies an ID token of this sign-in. See [`verify_id_token`].
758827 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
761832 }
762833
763834 /// Verifies a back-channel logout token. See [`verify_logout_token`].
764835 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
767840 }
768841
769842 /// The URL that sends the browser to `im` to sign in (contracts section 2.3, step 1).
@@ -828,13 +901,15 @@ impl OidcClient {
828901 /// A client-credentials token for the directory at `im` (contracts section 2.6). Cached until
829902 /// [`SERVICE_TOKEN_MARGIN`] before its stated lifetime ends.
830903 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
835904 {
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+ }
837911 }
912+ let endpoints = self.endpoints().await;
838913 let response = self
839914 .token_request(
840915 &endpoints.token,
@@ -850,7 +925,7 @@ impl OidcClient {
850925 .ok_or(OidcError::Token(TokenError::Claim("access_token")))?;
851926 let lifetime = Duration::from_secs(response.expires_in.unwrap_or(0));
852927 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));
854929 Ok(token)
855930 }
856931
crates/in-web/src/pages/backchannel.rsmodified+7 -9
@@ -46,15 +46,15 @@ struct LogoutTokenForm {
4646 pub enum Outcome {
4747 /// The token was new. This many sessions ended (possibly none).
4848 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.
5050 Replayed,
5151 }
5252
5353 /// Ends the sessions a verified logout token names, then records its `jti`.
5454 ///
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.
5858 /// The `sid` names one `im` session; a token with only `sub` ends every session of the person.
5959 pub async fn end_sessions(store: &Store, claims: &LogoutClaims) -> CoreResult<Outcome> {
6060 if store.jti_recorded(&claims.jti).await? {
@@ -144,11 +144,9 @@ async fn deliver(cx: &Cx, body: Body) -> Answer {
144144 tracing::info!(sessions = count, "backchannel: logout applied");
145145 accepted()
146146 }
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(),
152150 Err(error) => {
153151 tracing::error!(error = %error, "backchannel: could not end the sessions");
154152 json_error(
crates/in-web/src/pages/photo.rsmodified+8 -12
@@ -19,7 +19,7 @@ use topcoat::router::request::{headers, uri};
1919 use topcoat::router::{StatusCode, route};
2020
2121 use crate::auth::current_member;
22-use crate::oidc::OidcClient;
22+use crate::oidc::{OidcClient, read_limited};
2323 use crate::state::AppState;
2424
2525 /// 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
9090 }
9191 }
9292
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.
9495 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()));
9697 tokio::fs::write(&temporary, bytes).await?;
9798 tokio::fs::rename(&temporary, path).await
9899 }
@@ -135,15 +136,10 @@ async fn fetch_photo(
135136 let Some(content_type) = content_type else {
136137 return Ok(None);
137138 };
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),
147143 Err(error) => {
148144 tracing::warn!(error = %error, "photo: the body could not be read");
149145 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
102102 `events: {"http://schemas.openid.net/event/backchannel-logout": {}}`, and `sid` (and `sub`). For "disable" and
103103 "delete" it carries only `sub`, which means "every session of this user".
104104 - 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
106106 body. Any other answer is a failure.
107107 - `im` delivers through a durable outbox: retries with backoff (10 s, 30 s, 1 min, 5 min, then every 15 min)
108108 for 24 hours. Combined with the 12-hour local session cap (2.4), a missed delivery cannot keep a revoked