From edc7f267003ffcd518477f611f41d5f1a89aad3f Mon Sep 17 00:00:00 2001 From: Thinh Phuc Nguyen Date: Thu, 12 Nov 2026 16:17:26 -0500 Subject: [PATCH] feat(oauth2): Add jti replay cache for external assertions Signed-off-by: Thinh Phuc Nguyen --- crates/core/src/oauth2_client.rs | 2 + .../src/oauth2_client/assertion_replay.rs | 182 +++++++++++ crates/core/src/oauth2_client/dpop_replay.rs | 110 ++----- crates/core/src/oauth2_client/replay.rs | 293 ++++++++++++++++++ crates/core/src/oauth2_client/verify.rs | 2 +- 5 files changed, 496 insertions(+), 93 deletions(-) create mode 100644 crates/core/src/oauth2_client/assertion_replay.rs create mode 100644 crates/core/src/oauth2_client/replay.rs diff --git a/crates/core/src/oauth2_client.rs b/crates/core/src/oauth2_client.rs index 6df37aa2e..f4d0a4d7e 100644 --- a/crates/core/src/oauth2_client.rs +++ b/crates/core/src/oauth2_client.rs @@ -17,6 +17,7 @@ //! validation only in Phase 2 -- wiring into the mapping engine's //! `IdentitySource` for actual `/token` issuance is Phase 3/4. +pub mod assertion_replay; pub mod backend; pub mod bound_bearer; pub mod crypto; @@ -32,6 +33,7 @@ pub mod id_token; pub mod on_behalf_of; pub mod pkce; mod provider_api; +pub mod replay; pub mod service; pub mod token; pub mod token_exchange; diff --git a/crates/core/src/oauth2_client/assertion_replay.rs b/crates/core/src/oauth2_client/assertion_replay.rs new file mode 100644 index 000000000..1ff938513 --- /dev/null +++ b/crates/core/src/oauth2_client/assertion_replay.rs @@ -0,0 +1,182 @@ +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// SPDX-License-Identifier: Apache-2.0 +// Crypto inventory: none (bookkeeping of identifiers only). +//! # Replay cache for external assertions (ADR 0026 §1, ADR 0036 §6.4) +//! +//! A JWT from an external IdP can be presented to the token endpoint more +//! than once while it is valid. This cache remembers the `jti` of each +//! accepted assertion, per `(domain, issuer)`, and refuses a second use. +//! +//! An entry is kept until the assertion can no longer pass verification: the +//! profile accepts a token up to the clock skew after its `exp`, so the entry +//! lives until `exp` plus that skew. The profile also caps the lifetime of +//! an assertion, so the cache stays small. +//! +//! Call it only with the `exp` of a token that +//! [`verify_subject_token_jwt`](super::verify::verify_subject_token_jwt) +//! accepted. The bounds, the no-eviction rule and the per-process limits are +//! those of [`ReplayCache`]. +use super::replay::{ReplayCache, ReplayError}; +use super::verify::PROFILE_CLOCK_SKEW; + +/// Replay cache for the `jti` of external assertions. +pub struct AssertionReplayCache { + cache: ReplayCache, +} + +impl AssertionReplayCache { + /// Create a cache. `max_per_issuer` bounds the live entries of one + /// `(domain, issuer)` so a single IdP cannot fill the cache; `max_total` + /// bounds all of them. + pub fn new(max_per_issuer: usize, max_total: usize) -> Self { + Self { + cache: ReplayCache::new(max_per_issuer, max_total), + } + } + + /// Record the `jti` of a verified assertion, refusing a replay. + /// + /// `exp` is the `exp` claim of the verified token and `now` the current + /// unix time. + /// + /// # Errors + /// [`ReplayError::Replayed`] for a seen `(domain, issuer, jti)`, and the + /// quota errors when the bounds are reached; live entries are never + /// evicted. + pub fn check_and_insert( + &self, + domain_id: &str, + issuer: &str, + jti: &str, + exp: i64, + now: i64, + ) -> Result<(), ReplayError> { + let skew = i64::try_from(PROFILE_CLOCK_SKEW.as_secs()).unwrap_or(i64::MAX / 4); + let expires = exp.saturating_add(skew).saturating_add(1); + self.cache + .check_and_insert(&scope(domain_id, issuer), jti, expires, now) + } + + /// Drop expired entries; meant for a periodic background task. + pub fn purge_expired(&self, now: i64) { + self.cache.purge_expired(now); + } + + /// Number of entries currently held (live or not yet purged). + pub fn len(&self) -> usize { + self.cache.len() + } + + /// Whether the cache holds no entry. + pub fn is_empty(&self) -> bool { + self.cache.is_empty() + } +} + +/// The scope of an entry. The length prefix keeps `(domain, issuer)` pairs +/// that concatenate to the same text apart. +fn scope(domain_id: &str, issuer: &str) -> String { + format!("{}:{domain_id}{issuer}", domain_id.len()) +} + +#[cfg(test)] +mod tests { + use super::*; + + const NOW: i64 = 1_760_000_000; + const ISSUER: &str = "https://token.actions.githubusercontent.com"; + const SKEW: i64 = 60; + + #[test] + fn test_second_use_of_a_jti_is_refused() { + let cache = AssertionReplayCache::new(10, 100); + let exp = NOW + 300; + assert!(cache.check_and_insert("d1", ISSUER, "a", exp, NOW).is_ok()); + assert_eq!( + cache.check_and_insert("d1", ISSUER, "a", exp, NOW + 1), + Err(ReplayError::Replayed) + ); + assert!(cache.check_and_insert("d1", ISSUER, "b", exp, NOW).is_ok()); + } + + #[test] + fn test_same_jti_is_independent_per_domain_and_issuer() { + let cache = AssertionReplayCache::new(10, 100); + let exp = NOW + 300; + cache.check_and_insert("d1", ISSUER, "a", exp, NOW).unwrap(); + assert!(cache.check_and_insert("d2", ISSUER, "a", exp, NOW).is_ok()); + assert!( + cache + .check_and_insert("d1", "https://idp.example.com", "a", exp, NOW) + .is_ok() + ); + } + + #[test] + fn test_scope_is_injective() { + // Both pairs concatenate to "ab"; the scopes still differ. + assert_ne!(scope("a", "b"), scope("ab", "")); + let cache = AssertionReplayCache::new(10, 100); + let exp = NOW + 300; + cache.check_and_insert("a", "b", "x", exp, NOW).unwrap(); + assert!(cache.check_and_insert("ab", "", "x", exp, NOW).is_ok()); + } + + /// The token still passes verification until `exp` plus the skew, so a + /// replay up to then must be caught and not a second longer. + #[test] + fn test_entry_lives_until_exp_plus_skew() { + let cache = AssertionReplayCache::new(10, 100); + let exp = NOW + 300; + cache.check_and_insert("d1", ISSUER, "a", exp, NOW).unwrap(); + assert_eq!( + cache.check_and_insert("d1", ISSUER, "a", exp, exp + SKEW), + Err(ReplayError::Replayed) + ); + assert!( + cache + .check_and_insert("d1", ISSUER, "a", exp + 2 * SKEW, exp + SKEW + 1) + .is_ok() + ); + } + + #[test] + fn test_one_issuer_cannot_fill_the_cache() { + let cache = AssertionReplayCache::new(2, 100); + let exp = NOW + 300; + cache.check_and_insert("d1", ISSUER, "a", exp, NOW).unwrap(); + cache.check_and_insert("d1", ISSUER, "b", exp, NOW).unwrap(); + assert_eq!( + cache.check_and_insert("d1", ISSUER, "c", exp, NOW), + Err(ReplayError::ScopeQuotaExceeded) + ); + assert!( + cache + .check_and_insert("d1", "https://idp.example.com", "a", exp, NOW) + .is_ok() + ); + } + + #[test] + fn test_purge_expired() { + let cache = AssertionReplayCache::new(10, 100); + cache + .check_and_insert("d1", ISSUER, "a", NOW + 300, NOW) + .unwrap(); + cache.purge_expired(NOW + 300 + SKEW); + assert_eq!(cache.len(), 1); + cache.purge_expired(NOW + 300 + SKEW + 1); + assert!(cache.is_empty()); + } +} diff --git a/crates/core/src/oauth2_client/dpop_replay.rs b/crates/core/src/oauth2_client/dpop_replay.rs index 2207ca0ff..3b57937c2 100644 --- a/crates/core/src/oauth2_client/dpop_replay.rs +++ b/crates/core/src/oauth2_client/dpop_replay.rs @@ -14,21 +14,13 @@ // Crypto inventory: none (bookkeeping of identifiers only). //! # DPoP proof replay cache (RFC 9449 §11.1, ADR 0043 §2) //! -//! Bounded in-memory set of `(jkt, jti)` pairs, kept for as long as a proof -//! can still pass the `iat` window. The cache never evicts a live entry to -//! make room: once a key exceeds its share or the cache is full, new proofs -//! are rejected instead. Otherwise an attacker could flood the cache with -//! proofs from fresh keys, push out the entry of a captured proof and replay -//! it. -//! -//! The cache is per process; see ADR 0043 "Consequences" for the cross-node -//! limits. -use std::collections::HashMap; -use std::sync::{Mutex, PoisonError}; - +//! Set of `(jkt, jti)` pairs, kept for as long as a proof can still pass the +//! `iat` window. The bounds, the no-eviction rule and the per-process +//! limits are those of [`ReplayCache`]. use thiserror::Error; use super::dpop::VerifiedDpopProof; +use super::replay::{ReplayCache, ReplayError}; /// Why a proof was refused by the cache. #[derive(Debug, Error, PartialEq, Eq)] @@ -46,40 +38,19 @@ pub enum DpopReplayError { Replayed, } -#[derive(Default)] -struct Inner { - /// Lower bound of the earliest expiry held. Nothing can be dead before - /// it, so a purge before then is skipped instead of scanning every entry. - earliest: i64, - /// `jkt` -> (`jti` -> unix second after which the entry is dead). - keys: HashMap>, - total: usize, -} - -impl Inner { - fn purge(&mut self, now: i64) { - if self.earliest > now { - return; +impl From for DpopReplayError { + fn from(error: ReplayError) -> Self { + match error { + ReplayError::CacheFull => Self::CacheFull, + ReplayError::ScopeQuotaExceeded => Self::KeyQuotaExceeded, + ReplayError::Replayed => Self::Replayed, } - let mut removed = 0; - let mut earliest = i64::MAX; - self.keys.retain(|_, jtis| { - let before = jtis.len(); - jtis.retain(|_, expires| *expires > now); - removed += before - jtis.len(); - earliest = jtis.values().fold(earliest, |acc, e| acc.min(*e)); - !jtis.is_empty() - }); - self.total -= removed; - self.earliest = earliest; } } /// Replay cache for DPoP proofs. pub struct DpopReplayCache { - inner: Mutex, - max_per_key: usize, - max_total: usize, + cache: ReplayCache, /// Seconds an entry outlives its `iat`: the verifier's `max_skew_secs`. window_secs: i64, } @@ -94,10 +65,8 @@ impl DpopReplayCache { /// `max_total` bound the live entries. pub fn new(window_secs: u64, max_per_key: usize, max_total: usize) -> Self { Self { - inner: Mutex::new(Inner::default()), + cache: ReplayCache::new(max_per_key, max_total), window_secs: i64::try_from(window_secs).unwrap_or(i64::MAX / 4), - max_per_key, - max_total, } } @@ -112,67 +81,24 @@ impl DpopReplayCache { now: i64, ) -> Result<(), DpopReplayError> { let expires = proof.iat.saturating_add(self.window_secs).saturating_add(1); - let mut inner = self.inner.lock().unwrap_or_else(PoisonError::into_inner); - - // Free dead entries only when a bound is about to be hit; the common - // path stays O(1). - if inner.total >= self.max_total - || inner - .keys - .get(&proof.jkt) - .is_some_and(|jtis| jtis.len() >= self.max_per_key) - { - inner.purge(now); - } - - // An expired entry for the same `jti` is overwritten, so it neither - // grows the key nor the cache. - let mut overwrites = false; - if let Some(jtis) = inner.keys.get(&proof.jkt) { - match jtis.get(&proof.jti) { - Some(e) if *e > now => return Err(DpopReplayError::Replayed), - Some(_) => overwrites = true, - None => {} - } - if !overwrites && jtis.len() >= self.max_per_key { - return Err(DpopReplayError::KeyQuotaExceeded); - } - } - if !overwrites && inner.total >= self.max_total { - return Err(DpopReplayError::CacheFull); - } - - inner - .keys - .entry(proof.jkt.clone()) - .or_default() - .insert(proof.jti.clone(), expires); - if !overwrites { - inner.total += 1; - } - inner.earliest = inner.earliest.min(expires); - Ok(()) + Ok(self + .cache + .check_and_insert(&proof.jkt, &proof.jti, expires, now)?) } /// Drop expired entries; meant for a periodic background task. pub fn purge_expired(&self, now: i64) { - self.inner - .lock() - .unwrap_or_else(PoisonError::into_inner) - .purge(now); + self.cache.purge_expired(now); } /// Number of entries currently held (live or not yet purged). pub fn len(&self) -> usize { - self.inner - .lock() - .unwrap_or_else(PoisonError::into_inner) - .total + self.cache.len() } /// Whether the cache holds no entry. pub fn is_empty(&self) -> bool { - self.len() == 0 + self.cache.is_empty() } } diff --git a/crates/core/src/oauth2_client/replay.rs b/crates/core/src/oauth2_client/replay.rs new file mode 100644 index 000000000..22551f74e --- /dev/null +++ b/crates/core/src/oauth2_client/replay.rs @@ -0,0 +1,293 @@ +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// SPDX-License-Identifier: Apache-2.0 +// Crypto inventory: none (bookkeeping of identifiers only). +//! # Bounded replay cache +//! +//! Bounded in-memory set of `(scope, id)` pairs, each kept until the moment +//! the caller says the credential can no longer be accepted. The cache never +//! evicts a live entry to make room: once a scope exceeds its share or the +//! cache is full, new credentials are rejected instead. Otherwise an attacker +//! could flood the cache with credentials from fresh scopes, push out the +//! entry of a captured credential and replay it. +//! +//! The caller picks what the scope and the id are and when an entry dies: +//! [`DpopReplayCache`](super::dpop_replay::DpopReplayCache) (RFC 9449 §11.1) +//! and [`AssertionReplayCache`](super::assertion_replay::AssertionReplayCache) +//! (`jti` of external assertions) are the two users. +//! +//! The cache is per process; see ADR 0043 "Consequences" for the cross-node +//! limits. +use std::collections::HashMap; +use std::sync::{Mutex, PoisonError}; + +use thiserror::Error; + +/// Why a credential was refused by the cache. +#[derive(Debug, Error, PartialEq, Eq)] +pub enum ReplayError { + /// The cache holds its maximum number of live entries. + #[error("replay cache is full")] + CacheFull, + + /// The scope already holds its share of live entries. + #[error("too many live entries for this scope")] + ScopeQuotaExceeded, + + /// The `(scope, id)` pair was already seen and has not expired. + #[error("credential was already used")] + Replayed, +} + +#[derive(Default)] +struct Inner { + /// Lower bound of the earliest expiry held. Nothing can be dead before + /// it, so a purge before then is skipped instead of scanning every entry. + earliest: i64, + /// scope -> (id -> unix second after which the entry is dead). + scopes: HashMap>, + total: usize, +} + +impl Inner { + fn purge(&mut self, now: i64) { + if self.earliest > now { + return; + } + let mut removed = 0; + let mut earliest = i64::MAX; + self.scopes.retain(|_, ids| { + let before = ids.len(); + ids.retain(|_, expires| *expires > now); + removed += before - ids.len(); + earliest = ids.values().fold(earliest, |acc, e| acc.min(*e)); + !ids.is_empty() + }); + self.total -= removed; + self.earliest = earliest; + } +} + +/// Bounded set of seen `(scope, id)` pairs. +pub struct ReplayCache { + inner: Mutex, + max_per_scope: usize, + max_total: usize, +} + +impl ReplayCache { + /// Create a cache. `max_per_scope` and `max_total` bound the live + /// entries. + pub fn new(max_per_scope: usize, max_total: usize) -> Self { + Self { + inner: Mutex::new(Inner::default()), + max_per_scope, + max_total, + } + } + + /// Record a credential, refusing a replay. + /// + /// `expires` is the first unix second at which the entry is dead. It must + /// not be earlier than the last moment the same credential could still + /// pass verification; an earlier value opens a replay gap. + /// + /// # Errors + /// [`ReplayError::Replayed`] for a seen `(scope, id)`, and the quota errors + /// when the bounds are reached; live entries are never evicted. + pub fn check_and_insert( + &self, + scope: &str, + id: &str, + expires: i64, + now: i64, + ) -> Result<(), ReplayError> { + let mut inner = self.inner.lock().unwrap_or_else(PoisonError::into_inner); + + // Free dead entries only when a bound is about to be hit; the common + // path stays O(1). + if inner.total >= self.max_total + || inner + .scopes + .get(scope) + .is_some_and(|ids| ids.len() >= self.max_per_scope) + { + inner.purge(now); + } + + // An expired entry for the same id is overwritten, so it neither + // grows the scope nor the cache. + let mut overwrites = false; + if let Some(ids) = inner.scopes.get(scope) { + match ids.get(id) { + Some(e) if *e > now => return Err(ReplayError::Replayed), + Some(_) => overwrites = true, + None => {} + } + if !overwrites && ids.len() >= self.max_per_scope { + return Err(ReplayError::ScopeQuotaExceeded); + } + } + if !overwrites && inner.total >= self.max_total { + return Err(ReplayError::CacheFull); + } + + inner + .scopes + .entry(scope.to_owned()) + .or_default() + .insert(id.to_owned(), expires); + if !overwrites { + inner.total += 1; + } + inner.earliest = inner.earliest.min(expires); + Ok(()) + } + + /// Drop expired entries; meant for a periodic background task. + pub fn purge_expired(&self, now: i64) { + self.inner + .lock() + .unwrap_or_else(PoisonError::into_inner) + .purge(now); + } + + /// Number of entries currently held (live or not yet purged). + pub fn len(&self) -> usize { + self.inner + .lock() + .unwrap_or_else(PoisonError::into_inner) + .total + } + + /// Whether the cache holds no entry. + pub fn is_empty(&self) -> bool { + self.len() == 0 + } +} + +#[cfg(test)] +mod tests { + use super::*; + + const NOW: i64 = 1_760_000_000; + const LIFETIME: i64 = 60; + + fn insert(cache: &ReplayCache, scope: &str, id: &str, at: i64) -> Result<(), ReplayError> { + cache.check_and_insert(scope, id, at + LIFETIME, at) + } + + #[test] + fn test_replay_rejected_and_other_id_or_scope_accepted() { + let cache = ReplayCache::new(10, 100); + assert!(insert(&cache, "s1", "a", NOW).is_ok()); + assert_eq!(insert(&cache, "s1", "a", NOW), Err(ReplayError::Replayed)); + assert!(insert(&cache, "s1", "b", NOW).is_ok()); + assert!(insert(&cache, "s2", "a", NOW).is_ok()); + } + + #[test] + fn test_entry_dies_exactly_at_expires() { + let cache = ReplayCache::new(10, 100); + cache + .check_and_insert("s1", "a", NOW + LIFETIME, NOW) + .unwrap(); + // One second before the expiry the entry is still live. + assert_eq!( + cache.check_and_insert("s1", "a", NOW + 2 * LIFETIME, NOW + LIFETIME - 1), + Err(ReplayError::Replayed) + ); + // From the expiry on it is dead and the id can be recorded again. + assert!( + cache + .check_and_insert("s1", "a", NOW + 2 * LIFETIME, NOW + LIFETIME) + .is_ok() + ); + } + + #[test] + fn test_scope_quota_does_not_evict() { + let cache = ReplayCache::new(2, 100); + insert(&cache, "s1", "a", NOW).unwrap(); + insert(&cache, "s1", "b", NOW).unwrap(); + assert_eq!( + insert(&cache, "s1", "c", NOW), + Err(ReplayError::ScopeQuotaExceeded) + ); + // The earlier entries are still protected. + assert_eq!(insert(&cache, "s1", "a", NOW), Err(ReplayError::Replayed)); + // Other scopes are unaffected. + assert!(insert(&cache, "s2", "a", NOW).is_ok()); + } + + #[test] + fn test_fresh_scope_flood_sheds_load_and_keeps_live_entries() { + let cache = ReplayCache::new(10, 3); + insert(&cache, "victim", "x", NOW).unwrap(); + insert(&cache, "f1", "a", NOW).unwrap(); + insert(&cache, "f2", "a", NOW).unwrap(); + assert_eq!(insert(&cache, "f3", "a", NOW), Err(ReplayError::CacheFull)); + assert_eq!(cache.len(), 3); + // The victim's captured credential is still rejected as a replay. + assert_eq!( + insert(&cache, "victim", "x", NOW), + Err(ReplayError::Replayed) + ); + } + + #[test] + fn test_expired_entries_free_room() { + let cache = ReplayCache::new(10, 2); + insert(&cache, "s1", "a", NOW).unwrap(); + insert(&cache, "s2", "a", NOW).unwrap(); + let later = NOW + 100; + assert!(insert(&cache, "s3", "a", later).is_ok()); + assert_eq!(cache.len(), 1); + } + + #[test] + fn test_reusing_expired_id_does_not_inflate_count() { + let cache = ReplayCache::new(10, 2); + // Each round reuses the id once the previous entry has expired, + // without a purge in between. + for round in 0..5 { + insert(&cache, "s1", "a", NOW + round * 100).unwrap(); + } + assert_eq!(cache.len(), 1); + // The cache is not spuriously full. + assert!(insert(&cache, "s2", "a", NOW + 500).is_ok()); + assert_eq!(cache.len(), 2); + } + + #[test] + fn test_overwrite_allowed_at_quota() { + let cache = ReplayCache::new(1, 1); + insert(&cache, "s1", "a", NOW).unwrap(); + assert!(insert(&cache, "s1", "a", NOW + 100).is_ok()); + assert_eq!(cache.len(), 1); + } + + #[test] + fn test_purge_expired() { + let cache = ReplayCache::new(10, 100); + insert(&cache, "s1", "a", NOW).unwrap(); + insert(&cache, "s1", "b", NOW + 30).unwrap(); + // Nothing dead yet: the entries stay. + cache.purge_expired(NOW + 10); + assert_eq!(cache.len(), 2); + cache.purge_expired(NOW + 70); + assert_eq!(cache.len(), 1); + cache.purge_expired(NOW + 91); + assert!(cache.is_empty()); + } +} diff --git a/crates/core/src/oauth2_client/verify.rs b/crates/core/src/oauth2_client/verify.rs index 3c62d3d2e..0812bf243 100644 --- a/crates/core/src/oauth2_client/verify.rs +++ b/crates/core/src/oauth2_client/verify.rs @@ -263,7 +263,7 @@ const NATIVE_REQUIRED_CLAIMS: &[&str] = &["exp", "iat", "nbf", "iss", "aud", "su const EXTERNAL_REQUIRED_CLAIMS: &[&str] = &["exp", "iss", "aud", "sub"]; const ASSERTION_REQUIRED_CLAIMS: &[&str] = &["exp", "iat", "iss", "aud", "sub", "jti"]; const PROFILE_STRING_CLAIMS: &[&str] = &["iss", "sub", "jti"]; -const PROFILE_CLOCK_SKEW: Duration = Duration::from_secs(60); +pub(crate) const PROFILE_CLOCK_SKEW: Duration = Duration::from_secs(60); const EXTERNAL_MAX_AGE: Duration = Duration::from_secs(300); fn owned_claims(claims: &[&str]) -> Vec {