Skip to main content

hyprstream_core/auth/
federation.rs

1//! JWKS fetch and cache for multi-issuer JWT verification.
2//!
3//! `FederationKeyResolver` resolves external issuer URLs to Ed25519 verifying
4//! keys by fetching and caching JWKS (RFC 7517) documents.
5//!
6//! # Rotation-aware key set (#1185)
7//!
8//! The cache retains **every** usable Ed25519 key an issuer publishes, keyed by
9//! `kid`, so two keys published simultaneously during an overlap rotation both
10//! verify. A `kid` hint selects the preferred candidate; without one, the
11//! caller tries each. The resolver never collapses the published set to a
12//! positional singleton — that anti-pattern forecloses both overlap rotation
13//! and PQ-hybrid publication (#1183).
14
15use anyhow::{anyhow, Result};
16use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine};
17use ed25519_dalek::VerifyingKey;
18use hyprstream_rpc::auth::{FederationKey, FederationKeySource};
19use hyprstream_rpc_std::discovery_client::DiscoveryClient;
20use std::collections::HashMap;
21use std::pin::Pin;
22use std::sync::Arc;
23use std::time::{Duration, Instant};
24use tokio::sync::{Mutex, RwLock};
25
26/// Async function that fetches raw JWKS JSON from a URL. Defaults to a
27/// reqwest GET; injectable for tests.
28type JwksFetcher = Arc<
29    dyn Fn(&str) -> Pin<Box<dyn std::future::Future<Output = Result<serde_json::Value>> + Send>>
30        + Send
31        + Sync,
32>;
33
34/// One Ed25519 entry from a published JWKS, with its optional `kid`.
35#[derive(Clone)]
36struct JwksEntry {
37    kid: Option<String>,
38    key: VerifyingKey,
39}
40
41/// All Ed25519 keys currently published by one issuer, plus cache bookkeeping.
42struct CachedJwks {
43    entries: Vec<JwksEntry>,
44    fetched_at: Instant,
45    ttl: Duration,
46}
47
48impl CachedJwks {
49    fn is_expired(&self) -> bool {
50        self.fetched_at.elapsed() > self.ttl
51    }
52}
53
54/// Resolves external issuer URLs to Ed25519 verifying keys via JWKS.
55///
56/// Thread-safe (uses `Arc<RwLock<...>>`). Caches keys to avoid fetching
57/// on every request. Falls back to OIDC metadata discovery if no explicit
58/// JWKS URI is configured.
59///
60/// By default all JWKS URIs must use HTTPS with TLS certificate verification.
61/// Set `allow_http: true` in `TrustedIssuerConfig` on a per-issuer basis to
62/// permit plain HTTP (development / internal use only).
63pub struct FederationKeyResolver {
64    /// issuer_url → cached JWKS key set.
65    ///
66    cache: RwLock<HashMap<String, CachedJwks>>,
67    /// Short-lived cache of named keys that were absent after a refresh.
68    /// This bounds attacker-controlled repeated unknown-`kid` requests.
69    negative_cache: Mutex<HashMap<(String, String), Instant>>,
70    /// Per-issuer single-flight guards. Different trusted issuers never block
71    /// each other while one issuer refreshes its JWKS.
72    fetch_locks: Mutex<HashMap<String, Arc<Mutex<()>>>>,
73    /// issuer_url → (optional jwks_uri_override, ttl, allow_http)
74    config: HashMap<String, (Option<String>, Duration, bool)>,
75    http: reqwest::Client,
76    /// Injectable JWKS fetcher (url → raw JWKS JSON). Defaults to a reqwest
77    /// GET; overridable in tests so the rotation/overlap behaviour of
78    /// `get_keys` can be exercised end-to-end without a network mock.
79    jwks_fetcher: JwksFetcher,
80    /// Phase 0.5 Stage D — optional DiscoveryService client.
81    ///
82    /// When configured, `get_keys` consults DiscoveryService for a cached
83    /// signed entity statement before falling back to HTTPS JWKS fetch.
84    /// This avoids the HTTPS round-trip for local-issuer verification and
85    /// the 300s TTL becomes irrelevant for cluster-internal traffic.
86    /// Falls through to HTTPS on miss/error (conservative: never downgrade
87    /// trust on missing data).
88    discovery_client: Option<Arc<DiscoveryClient>>,
89    /// Unified federation trust gate (atproto-style). When set, every
90    /// `get_keys` call additionally verifies the issuer's origin is
91    /// permitted by PolicyService `federation:register` — same gate as
92    /// CIMD client registration. The `trusted_issuers` config carries
93    /// operational metadata (jwks_uri override, scheme, TTL); this
94    /// PolicyService check carries the hot-reloadable trust decision.
95    ///
96    /// `None` retains the legacy posture (config-only trust) for
97    /// callers that haven't wired PolicyService access yet.
98    policy_client: Option<Arc<hyprstream_rpc_std::policy_client::PolicyClient>>,
99}
100
101impl FederationKeyResolver {
102    pub fn new(trusted_issuers: &HashMap<String, crate::config::TrustedIssuerConfig>) -> Self {
103        let config = trusted_issuers
104            .iter()
105            .map(|(iss, cfg)| {
106                (
107                    iss.clone(),
108                    (
109                        cfg.jwks_uri.clone(),
110                        Duration::from_secs(cfg.jwks_cache_ttl_secs),
111                        cfg.allow_http,
112                    ),
113                )
114            })
115            .collect();
116        let http = reqwest::Client::builder()
117            .timeout(Duration::from_secs(10))
118            .build()
119            .unwrap_or_default();
120        Self {
121            cache: RwLock::new(HashMap::new()),
122            negative_cache: Mutex::new(HashMap::new()),
123            fetch_locks: Mutex::new(HashMap::new()),
124            config,
125            // TLS certificate verification is enabled by default (reqwest default).
126            jwks_fetcher: default_jwks_fetcher(http.clone()),
127            http,
128            discovery_client: None,
129            policy_client: None,
130        }
131    }
132
133    /// Override the JWKS fetcher (url → raw JWKS JSON). Test-only seam that
134    /// lets the rotation/overlap behaviour of [`get_keys`] be exercised
135    /// end-to-end without standing up an HTTPS server.
136    #[cfg(test)]
137    pub(crate) fn with_jwks_fetcher(mut self, fetcher: JwksFetcher) -> Self {
138        self.jwks_fetcher = fetcher;
139        self
140    }
141
142    /// Wire the PolicyService client so [`get_keys`] enforces the
143    /// `federation:register` trust gate before any HTTPS fetch. When
144    /// set, calls to `get_keys` for issuers that aren't currently
145    /// permitted by PolicyService policy return Err — fail-closed,
146    /// matching the CIMD client path.
147    pub fn with_policy_client(
148        mut self,
149        client: Arc<hyprstream_rpc_std::policy_client::PolicyClient>,
150    ) -> Self {
151        self.policy_client = Some(client);
152        self
153    }
154
155    /// Phase 0.5 Stage D — wire a DiscoveryService client for federation
156    /// directory consultation. When set, [`get_keys`] will try fetching the
157    /// issuer's signed entity statement via DiscoveryService before falling
158    /// back to HTTPS JWKS fetch.
159    ///
160    /// Conservative on errors: any failure of the DiscoveryService path
161    /// (network, parse, missing entity, no Ed25519 key) falls through to
162    /// the existing HTTPS path. The resolver never downgrades trust based
163    /// on missing data — if both Discovery AND HTTPS fail, key resolution
164    /// fails and the caller rejects the JWT.
165    pub fn with_discovery_client(mut self, client: Arc<DiscoveryClient>) -> Self {
166        self.discovery_client = Some(client);
167        self
168    }
169
170    /// Returns true if this issuer is in the trusted list.
171    pub fn is_trusted(&self, issuer: &str) -> bool {
172        self.config.contains_key(issuer)
173    }
174
175    /// Get the Ed25519 candidate verifying keys for an issuer, fetching /
176    /// refreshing JWKS as needed. See the trait docs for the rotation-aware
177    /// key-set contract (#1185).
178    ///
179    /// Uses a single `Mutex` for both cache reads and writes so that concurrent
180    /// requests for the same issuer serialise: the second waiter re-checks the
181    /// cache after the first finishes, finding a fresh entry rather than issuing
182    /// a redundant JWKS fetch.
183    pub async fn get_keys(&self, issuer: &str, kid: Option<&str>) -> Result<Vec<FederationKey>> {
184        // Look up config before acquiring cache lock (config is immutable after new())
185        let (jwks_uri_override, ttl, allow_http) = self
186            .config
187            .get(issuer)
188            .map(|(u, t, h)| (u.clone(), *t, *h))
189            .ok_or_else(|| anyhow!("Issuer not in trusted list: {}", issuer))?;
190
191        // Unified federation trust gate: when PolicyService is wired,
192        // also require the issuer's origin to be permitted by the
193        // `federation:register` policy. Layered on top of the
194        // trusted_issuers config — both must accept. Operators see
195        // `trusted_issuers` as operational config (how to reach this
196        // peer) and PolicyService as the hot-reloadable trust decision
197        // (do we currently accept this peer). Same gate as CIMD; same
198        // fail-closed semantics on RPC outage.
199        if let Some(ref pc) = self.policy_client {
200            use hyprstream_rpc_std::policy_client::PolicyCheck;
201            // Reuse the OAuth-side RFC 6454 origin extractor: same
202            // normalization (scheme + lowercase host + non-default port)
203            // means a single Casbin rule covers a CIMD client at
204            // app.partner.org AND a peer at hyprstream.partner.org.
205            let origin = crate::services::oauth::registration::extract_origin(issuer)
206                .ok_or_else(|| anyhow!("Invalid issuer URL: {issuer}"))?;
207            let resource = crate::auth::federation_registration_resource(&origin)?;
208            match pc
209                .check(&PolicyCheck {
210                    subject: String::new(),
211                    domain: String::new(),
212                    resource,
213                    operation: "check".to_owned(),
214                })
215                .await
216            {
217                Ok(true) => { /* permitted, fall through to fetch */ }
218                Ok(false) => {
219                    anyhow::bail!(
220                        "peer {origin} is not permitted by policy (federation:register denied)"
221                    );
222                }
223                Err(e) => {
224                    tracing::error!(
225                        issuer = %issuer,
226                        origin = %origin,
227                        error = %e,
228                        "PolicyService unreachable during peer federation:register check — failing closed"
229                    );
230                    anyhow::bail!(
231                        "PolicyService unreachable; peer federation rejected (fail-closed): {e}"
232                    );
233                }
234            }
235        }
236
237        if let Some(candidates) = self.fresh_candidates(issuer, kid).await {
238            return Ok(candidates);
239        }
240        if self.is_negative_cached(issuer, kid).await {
241            anyhow::bail!("JWKS has no Ed25519 key with requested kid (negative cached)");
242        }
243
244        // Recheck cache and the negative cache after acquiring this issuer's
245        // single-flight guard. This makes one refresh serve all same-issuer
246        // waiters without globally head-of-line blocking unrelated issuers.
247        let fetch_lock = {
248            let mut locks = self.fetch_locks.lock().await;
249            Arc::clone(
250                locks
251                    .entry(issuer.to_owned())
252                    .or_insert_with(|| Arc::new(Mutex::new(()))),
253            )
254        };
255        let _fetch_guard = fetch_lock.lock().await;
256        if let Some(candidates) = self.fresh_candidates(issuer, kid).await {
257            return Ok(candidates);
258        }
259        if self.is_negative_cached(issuer, kid).await {
260            anyhow::bail!("JWKS has no Ed25519 key with requested kid (negative cached)");
261        }
262
263        // Phase 0.5 Stage D — try DiscoveryService first if configured.
264        // This is an optimization: federation peers can cache signed
265        // entity statements that contain JWKS, letting us skip the HTTPS
266        // round-trip. Conservative on errors: any failure falls through
267        // to the existing HTTPS path. Never downgrades trust.
268        if let Some(ref dc) = self.discovery_client {
269            match self.try_get_keys_from_discovery(dc, issuer).await {
270                Ok(entries) if !entries.is_empty() => {
271                    if has_requested_kid(&entries, kid) {
272                        self.cache_entries(issuer, entries, ttl).await;
273                        self.clear_negative_cache(issuer, kid).await;
274                        // A selector exists only to select: do not return
275                        // unrelated co-published keys as signature fallbacks.
276                        return self.fresh_candidates(issuer, kid).await.ok_or_else(|| {
277                            anyhow!("fresh Discovery JWKS unexpectedly missing requested key")
278                        });
279                    }
280                    // A stale Discovery statement cannot hide an HTTPS JWKS
281                    // rotation. Preserve it for kid-less callers only if the
282                    // authoritative HTTPS lookup below fails.
283                    self.cache_entries(issuer, entries, ttl).await;
284                }
285                Ok(_) => {
286                    tracing::debug!(
287                        issuer = %issuer,
288                        "DiscoveryService federation lookup returned no Ed25519 keys; \
289                         falling through to HTTPS"
290                    );
291                }
292                Err(e) => {
293                    tracing::debug!(
294                        issuer = %issuer,
295                        error = %e,
296                        "DiscoveryService federation lookup miss; falling through to HTTPS"
297                    );
298                }
299            }
300        }
301
302        // Cache miss, expired, or unknown kid — fetch while holding the
303        // lock so concurrent callers for the same issuer block here and
304        // reuse the result.
305        let jwks_uri = if let Some(uri) = jwks_uri_override {
306            self.check_scheme(&uri, allow_http)?;
307            uri
308        } else {
309            self.discover_jwks_uri(issuer, allow_http).await?
310        };
311
312        let entries = self.fetch_ed25519_keys(&jwks_uri).await?;
313        if entries.is_empty() {
314            anyhow::bail!("No Ed25519 key found in JWKS at {}", jwks_uri);
315        }
316
317        let found = has_requested_kid(&entries, kid);
318        self.cache_entries(issuer, entries, ttl).await;
319        if !found {
320            self.record_negative_cache(issuer, kid).await;
321            let Some(requested_kid) = kid else {
322                anyhow::bail!("JWKS unexpectedly contained no usable Ed25519 key");
323            };
324            anyhow::bail!(
325                "JWKS at {} has no Ed25519 key with kid={}",
326                jwks_uri,
327                requested_kid
328            );
329        }
330        self.clear_negative_cache(issuer, kid).await;
331        let cache = self.cache.read().await;
332        Ok(select_candidates(&cache[issuer].entries, kid))
333    }
334
335    async fn fresh_candidates(
336        &self,
337        issuer: &str,
338        kid: Option<&str>,
339    ) -> Option<Vec<FederationKey>> {
340        let cache = self.cache.read().await;
341        let entry = cache.get(issuer)?;
342        (!entry.is_expired() && has_requested_kid(&entry.entries, kid))
343            .then(|| select_candidates(&entry.entries, kid))
344    }
345
346    async fn cache_entries(&self, issuer: &str, entries: Vec<JwksEntry>, ttl: Duration) {
347        self.cache.write().await.insert(
348            issuer.to_owned(),
349            CachedJwks {
350                entries,
351                fetched_at: Instant::now(),
352                ttl,
353            },
354        );
355    }
356
357    async fn is_negative_cached(&self, issuer: &str, kid: Option<&str>) -> bool {
358        const NEGATIVE_TTL: Duration = Duration::from_secs(5);
359        let Some(kid) = kid else {
360            return false;
361        };
362        let key = (issuer.to_owned(), kid.to_owned());
363        let mut misses = self.negative_cache.lock().await;
364        match misses.get(&key) {
365            Some(seen) if seen.elapsed() < NEGATIVE_TTL => true,
366            Some(_) => {
367                misses.remove(&key);
368                false
369            }
370            None => false,
371        }
372    }
373
374    async fn record_negative_cache(&self, issuer: &str, kid: Option<&str>) {
375        const NEGATIVE_TTL: Duration = Duration::from_secs(5);
376        const MAX_NEGATIVE_ENTRIES: usize = 1024;
377        let Some(kid) = kid else {
378            return;
379        };
380        let mut misses = self.negative_cache.lock().await;
381        misses.retain(|_, seen| seen.elapsed() < NEGATIVE_TTL);
382        if misses.len() >= MAX_NEGATIVE_ENTRIES {
383            if let Some(key) = misses.keys().next().cloned() {
384                misses.remove(&key);
385            }
386        }
387        misses.insert((issuer.to_owned(), kid.to_owned()), Instant::now());
388    }
389
390    async fn clear_negative_cache(&self, issuer: &str, kid: Option<&str>) {
391        if let Some(kid) = kid {
392            self.negative_cache
393                .lock()
394                .await
395                .remove(&(issuer.to_owned(), kid.to_owned()));
396        }
397    }
398
399    /// Try fetching the Ed25519 verifying keys for `issuer` via DiscoveryService.
400    ///
401    /// Calls `DiscoveryClient::get_entity_statement(issuer)` to retrieve a
402    /// cached signed OIDF entity statement, then performs self-validating
403    /// signature verification:
404    ///
405    /// 1. Parse JWT header → extract `alg` (must be `EdDSA`)
406    /// 2. Parse JWT payload → require `iss == sub == issuer` (self-issued check)
407    /// 3. Parse JWT payload → extract `jwks.keys`
408    /// 4. For each Ed25519 key in the JWKS: try verifying the JWT signature
409    /// 5. Return the full candidate set once SOME embedded key verifies
410    ///
411    /// This self-validation establishes that the JWT was signed by a key
412    /// listed in its own embedded JWKS — defeats tampering during delivery
413    /// even when DiscoveryService is untrusted. A compromised DiscoveryService
414    /// can't substitute fake keys because the JWT signature must still verify
415    /// against one of them.
416    ///
417    /// Returns `Err` on any of:
418    ///   - DiscoveryService RPC failure
419    ///   - No entity statement cached for the issuer
420    ///   - JWT structurally invalid (not 3-part, header/payload not JSON, alg ≠ EdDSA)
421    ///   - `iss`/`sub` don't match the requested issuer
422    ///   - No Ed25519 key in the embedded JWKS
423    ///   - NONE of the embedded keys verify the JWT signature
424    ///
425    /// The caller treats `Err` as "fall through to HTTPS" — never as
426    /// "trust failure" — so a Discovery miss is operationally benign.
427    ///
428    /// NOTE: this does not verify against an external trust anchor. That's
429    /// Phase 0.5 Decision 4 territory (pinned trust-anchor JWKS, requiring
430    /// the entity-statement signing key to match a pre-configured fingerprint).
431    /// Self-validation is the strongest check we can do without trust anchors;
432    /// the existing per-issuer `trusted_issuers` config provides the trust root
433    /// for the *result* (since only configured issuers reach this path at all).
434    async fn try_get_keys_from_discovery(
435        &self,
436        dc: &DiscoveryClient,
437        issuer: &str,
438    ) -> Result<Vec<JwksEntry>> {
439        let stmt = dc
440            .get_entity_statement(issuer)
441            .await
442            .map_err(|e| anyhow!("DiscoveryService.getEntityStatement RPC failed: {}", e))?;
443
444        if stmt.jwt.is_empty() {
445            anyhow::bail!("DiscoveryService returned empty entity statement JWT");
446        }
447
448        // Self-validation establishes which embedded key signed the statement.
449        // The full published JWKS is retained (all Ed25519 entries with their
450        // kids) so overlap candidates survive a Discovery lookup, matching the
451        // HTTPS JWKS path's rotation semantics (#1185).
452        extract_self_issued_jwks(&stmt.jwt, issuer)
453    }
454
455    /// Validate that `url` uses HTTPS (or HTTP when explicitly permitted).
456    ///
457    /// Rejects all non-HTTP(S) schemes (e.g. `ftp://`, `file://`) regardless
458    /// of the `allow_http` flag.
459    fn check_scheme(&self, url: &str, allow_http: bool) -> Result<()> {
460        if url.starts_with("https://") || (allow_http && url.starts_with("http://")) {
461            Ok(())
462        } else if url.starts_with("http://") {
463            // HTTP but not explicitly allowed
464            anyhow::bail!(
465                "JWKS URI must use HTTPS for security (got '{}'). \
466                 Set allow_http: true in trusted_issuers config to permit HTTP \
467                 (development / internal networks only).",
468                url
469            )
470        } else {
471            // Non-HTTP(S) scheme (ftp://, file://, javascript:, etc.)
472            anyhow::bail!("JWKS URI must use HTTPS or HTTP scheme (got '{}').", url)
473        }
474    }
475
476    async fn discover_jwks_uri(&self, issuer: &str, allow_http: bool) -> Result<String> {
477        // Validate the issuer URL scheme before fetching AS metadata
478        self.check_scheme(issuer, allow_http)?;
479        let meta_url = format!("{}/.well-known/oauth-authorization-server", issuer);
480        let meta: serde_json::Value = self.http.get(&meta_url).send().await?.json().await?;
481        let jwks_uri = meta["jwks_uri"]
482            .as_str()
483            .map(str::to_owned)
484            .ok_or_else(|| anyhow!("No jwks_uri in AS metadata for {}", issuer))?;
485        // Validate the discovered jwks_uri scheme as well
486        self.check_scheme(&jwks_uri, allow_http)?;
487        Ok(jwks_uri)
488    }
489
490    /// Fetch every Ed25519 key in the JWKS at `jwks_uri`, each with its
491    /// optional `kid`. All usable entries are retained — callers select by
492    /// `kid` and/or try each candidate (rotation overlap, PQ-hybrid).
493    async fn fetch_ed25519_keys(&self, jwks_uri: &str) -> Result<Vec<JwksEntry>> {
494        let jwks = (self.jwks_fetcher)(jwks_uri).await?;
495        Ok(parse_jwks_ed25519(&jwks, jwks_uri))
496    }
497}
498
499/// The default JWKS fetcher: a reqwest GET returning the parsed JSON body.
500/// Captured as a `JwksFetcher` so the production path and the test seam
501/// share one shape (#1185).
502fn default_jwks_fetcher(http: reqwest::Client) -> JwksFetcher {
503    Arc::new(move |url: &str| {
504        let url = url.to_owned();
505        let http = http.clone();
506        Box::pin(async move {
507            let jwks: serde_json::Value = http.get(&url).send().await?.json().await?;
508            Ok(jwks)
509        })
510    })
511}
512
513/// Parse every Ed25519 entry (with its `kid`) out of a JWKS document. All
514/// usable entries are retained — callers select by `kid` and/or try each
515/// candidate. Pure (no I/O) so rotation/overlap behaviour is unit-testable.
516fn parse_jwks_ed25519(jwks: &serde_json::Value, jwks_uri: &str) -> Vec<JwksEntry> {
517    let mut out = Vec::new();
518    let Some(keys) = jwks["keys"].as_array() else {
519        return out;
520    };
521    for key in keys {
522        if key["kty"].as_str() != Some("OKP") || key["crv"].as_str() != Some("Ed25519") {
523            continue;
524        }
525        let x = match key["x"].as_str() {
526            Some(s) => s,
527            None => continue,
528        };
529        let raw = match URL_SAFE_NO_PAD.decode(x) {
530            Ok(r) => r,
531            Err(_) => continue,
532        };
533        let bytes: [u8; 32] = match raw.try_into() {
534            Ok(b) => b,
535            Err(_) => continue,
536        };
537        let vk = match VerifyingKey::from_bytes(&bytes) {
538            Ok(v) => v,
539            Err(_) => continue,
540        };
541        let kid = key["kid"]
542            .as_str()
543            .filter(|s| !s.is_empty())
544            .map(str::to_owned);
545        out.push(JwksEntry { kid, key: vk });
546    }
547    let _ = jwks_uri; // context only (error reporting is at call sites)
548    out
549}
550
551/// A named token selects only its exact entry. A kid-less token can try every
552/// compatible published key, preserving the overlap-rotation case.
553fn select_candidates(entries: &[JwksEntry], kid: Option<&str>) -> Vec<FederationKey> {
554    entries
555        .iter()
556        .filter(|entry| match kid {
557            Some(requested_kid) => entry.kid.as_deref() == Some(requested_kid),
558            None => true,
559        })
560        .map(|entry| FederationKey {
561            kid: entry.kid.clone(),
562            verifying_key: entry.key,
563        })
564        .collect()
565}
566
567fn has_requested_kid(entries: &[JwksEntry], kid: Option<&str>) -> bool {
568    match kid {
569        Some(requested_kid) => entries
570            .iter()
571            .any(|entry| entry.kid.as_deref() == Some(requested_kid)),
572        None => !entries.is_empty(),
573    }
574}
575
576/// Phase 0.5 Stage D — self-validating signature verification of an
577/// OpenID Federation 1.0 entity statement received from DiscoveryService.
578///
579/// **Security model:** the JWT is self-issued (`iss == sub == issuer`)
580/// and the signing key is one of the keys it publishes in its own
581/// `jwks.keys` claim. Verification:
582///
583/// 1. JWT structure (3-part compact)
584/// 2. Header alg is EdDSA
585/// 3. `iss == sub == expected_issuer`
586/// 4. `exp` (if present) is in the future
587/// 5. SOME Ed25519 key in the embedded JWKS verifies the JWT signature
588///
589/// Returns the verifying key that produced the signature. For the full
590/// published key set (rotation-aware), use [`extract_self_issued_jwks`].
591///
592/// This defeats tampering during delivery: a man-in-the-middle (or a
593/// compromised intermediary like DiscoveryService) cannot substitute
594/// fake keys because they would also need a corresponding private key
595/// for one of the published keys to produce a valid signature.
596///
597/// Note this does NOT verify against an external trust anchor. The
598/// caller is expected to have already established that `expected_issuer`
599/// is in the trusted-issuer config; self-validation defeats tampering of
600/// the delivered statement, not initial trust establishment.
601#[cfg(test)]
602pub(crate) fn verify_self_issued_entity_statement(
603    jwt: &str,
604    expected_issuer: &str,
605) -> Result<VerifyingKey> {
606    let (_entries, signer) = parse_self_issued_entity_statement(jwt, expected_issuer)?;
607    Ok(signer)
608}
609
610/// Phase 0.5 Stage D — self-validating signature verification of an
611/// OpenID Federation 1.0 entity statement received from DiscoveryService.
612///
613/// Returns the full published Ed25519 key set (each with its `kid`) after
614/// confirming at least one of them produced the statement's signature. The
615/// set is retained — not collapsed to the signer — so overlap rotation and
616/// PQ-hybrid publication work through the Discovery path as they do through
617/// HTTPS JWKS (#1185).
618fn extract_self_issued_jwks(jwt: &str, expected_issuer: &str) -> Result<Vec<JwksEntry>> {
619    let (entries, _signer) = parse_self_issued_entity_statement(jwt, expected_issuer)?;
620    Ok(entries)
621}
622
623/// Shared parse + self-validation for a self-issued entity statement.
624///
625/// Performs the full structural/claim/exp checks and self-validates the
626/// signature against the embedded JWKS, returning both the complete
627/// Ed25519 candidate list (with kids) and the key that produced the
628/// signature. Both entry points (`verify_self_issued_entity_statement`
629/// for the single signer key, `extract_self_issued_jwks` for the rotation
630/// set) run this identical check.
631fn parse_self_issued_entity_statement(
632    jwt: &str,
633    expected_issuer: &str,
634) -> Result<(Vec<JwksEntry>, VerifyingKey)> {
635    let parts: Vec<&str> = jwt.split('.').collect();
636    if parts.len() != 3 {
637        anyhow::bail!("entity statement JWT not in 3-part compact form");
638    }
639
640    // Header — alg must be EdDSA.
641    let header_bytes = URL_SAFE_NO_PAD
642        .decode(parts[0])
643        .map_err(|e| anyhow!("entity statement JWT header not base64url: {}", e))?;
644    let header: serde_json::Value = serde_json::from_slice(&header_bytes)
645        .map_err(|e| anyhow!("entity statement JWT header not JSON: {}", e))?;
646    let alg = header.get("alg").and_then(|v| v.as_str()).unwrap_or("");
647    if alg != "EdDSA" {
648        anyhow::bail!(
649            "entity statement JWT alg is '{}', only EdDSA supported",
650            alg
651        );
652    }
653
654    // Payload — iss/sub bind to expected issuer; exp not expired.
655    let payload_bytes = URL_SAFE_NO_PAD
656        .decode(parts[1])
657        .map_err(|e| anyhow!("entity statement JWT payload not base64url: {}", e))?;
658    let claims: serde_json::Value = serde_json::from_slice(&payload_bytes)
659        .map_err(|e| anyhow!("entity statement JWT payload not JSON: {}", e))?;
660
661    let iss = claims.get("iss").and_then(|v| v.as_str()).unwrap_or("");
662    let sub = claims.get("sub").and_then(|v| v.as_str()).unwrap_or("");
663    if iss != expected_issuer {
664        anyhow::bail!(
665            "entity statement iss '{}' != expected issuer '{}'",
666            iss,
667            expected_issuer
668        );
669    }
670    if sub != expected_issuer {
671        anyhow::bail!(
672            "entity statement sub '{}' != iss (must be self-issued)",
673            sub
674        );
675    }
676
677    if let Some(exp) = claims.get("exp").and_then(serde_json::Value::as_i64) {
678        let now = std::time::SystemTime::now()
679            .duration_since(std::time::UNIX_EPOCH)
680            .map(|d| d.as_secs() as i64)
681            .unwrap_or(0);
682        if exp <= now {
683            anyhow::bail!("entity statement expired (exp={} now={})", exp, now);
684        }
685    }
686
687    // JWKS — extract every Ed25519 candidate, retaining each `kid` so the
688    // caller can select by id and keep overlap candidates (#1185).
689    let keys = claims
690        .get("jwks")
691        .and_then(|j| j.get("keys"))
692        .and_then(|k| k.as_array())
693        .ok_or_else(|| anyhow!("entity statement missing jwks.keys"))?;
694
695    // Self-validating signature check: one of the embedded keys MUST verify.
696    let signing_input = format!("{}.{}", parts[0], parts[1]);
697    let sig_bytes = URL_SAFE_NO_PAD
698        .decode(parts[2])
699        .map_err(|e| anyhow!("entity statement signature not base64url: {}", e))?;
700    if sig_bytes.len() != 64 {
701        anyhow::bail!(
702            "Ed25519 signature must be 64 bytes, got {}",
703            sig_bytes.len()
704        );
705    }
706    let mut sig_arr = [0u8; 64];
707    sig_arr.copy_from_slice(&sig_bytes);
708    let signature = ed25519_dalek::Signature::from_bytes(&sig_arr);
709
710    let mut entries: Vec<JwksEntry> = Vec::new();
711    let mut signer: Option<VerifyingKey> = None;
712    for key in keys {
713        if key.get("kty").and_then(|v| v.as_str()) != Some("OKP")
714            || key.get("crv").and_then(|v| v.as_str()) != Some("Ed25519")
715        {
716            continue;
717        }
718        let x = match key.get("x").and_then(|v| v.as_str()) {
719            Some(s) => s,
720            None => continue,
721        };
722        let raw = match URL_SAFE_NO_PAD.decode(x) {
723            Ok(r) => r,
724            Err(_) => continue,
725        };
726        let bytes: [u8; 32] = match raw.try_into() {
727            Ok(b) => b,
728            Err(_) => continue,
729        };
730        let vk = match VerifyingKey::from_bytes(&bytes) {
731            Ok(v) => v,
732            Err(_) => continue,
733        };
734        let kid = key
735            .get("kid")
736            .and_then(|v| v.as_str())
737            .filter(|s| !s.is_empty())
738            .map(str::to_owned);
739        if signer.is_none()
740            && vk
741                .verify_strict(signing_input.as_bytes(), &signature)
742                .is_ok()
743        {
744            signer = Some(vk);
745        }
746        entries.push(JwksEntry { kid, key: vk });
747    }
748
749    match signer {
750        Some(vk) => Ok((entries, vk)),
751        None => anyhow::bail!(
752            "entity statement self-validation failed: no Ed25519 key in jwks verifies the signature"
753        ),
754    }
755}
756
757// Adapter: delegates to the inherent methods. Using fully-qualified paths
758// prevents latent infinite recursion if the inherent methods are later
759// removed or made private during API cleanup.
760#[async_trait::async_trait]
761impl FederationKeySource for FederationKeyResolver {
762    fn is_trusted(&self, issuer: &str) -> bool {
763        FederationKeyResolver::is_trusted(self, issuer)
764    }
765
766    async fn get_keys(
767        &self,
768        issuer: &str,
769        kid: Option<&str>,
770    ) -> anyhow::Result<Vec<FederationKey>> {
771        FederationKeyResolver::get_keys(self, issuer, kid).await
772    }
773}
774
775#[cfg(test)]
776#[allow(clippy::unwrap_used, clippy::expect_used)]
777mod tests {
778    use super::*;
779
780    #[test]
781    fn test_untrusted_issuer_rejected() {
782        let resolver = FederationKeyResolver::new(&Default::default());
783        assert!(!resolver.is_trusted("https://evil.example.com"));
784        assert!(!resolver.is_trusted(""));
785    }
786
787    #[test]
788    fn test_trusted_issuer_recognized() {
789        let mut issuers = HashMap::new();
790        issuers.insert(
791            "https://trusted.example.com".to_owned(),
792            crate::config::TrustedIssuerConfig {
793                jwks_uri: Some("https://trusted.example.com/jwks".to_owned()),
794                jwks_cache_ttl_secs: 300,
795                allow_http: false,
796                federate_tui_client: None,
797            },
798        );
799        let resolver = FederationKeyResolver::new(&issuers);
800        assert!(resolver.is_trusted("https://trusted.example.com"));
801        assert!(!resolver.is_trusted("https://untrusted.example.com"));
802    }
803
804    // ──────────────────────────────────────────────────────────────────
805    // Phase 0.5 Stage D — self-validating entity statement verification
806    // ──────────────────────────────────────────────────────────────────
807
808    use ed25519_dalek::{Signer, SigningKey};
809    use hyprstream_rpc::auth::{jwt, Claims};
810    use rand::rngs::OsRng;
811
812    fn b64u(bytes: &[u8]) -> String {
813        URL_SAFE_NO_PAD.encode(bytes)
814    }
815
816    fn b64u_json(value: &serde_json::Value) -> String {
817        b64u(&serde_json::to_vec(value).expect("json"))
818    }
819
820    /// Build a self-issued entity statement JWT signed by `signing_key`,
821    /// with the provided JWKS in the payload.
822    ///
823    /// `jwks_keys` is the JSON array placed under `jwks.keys`; tests can
824    /// pass any combination of keys (with/without the signer's key) to
825    /// exercise self-validation logic.
826    fn build_entity_statement(
827        signing_key: &SigningKey,
828        issuer: &str,
829        sub: &str,
830        exp: i64,
831        jwks_keys: Vec<serde_json::Value>,
832    ) -> String {
833        let header = serde_json::json!({"alg": "EdDSA", "typ": "entity-statement+jwt"});
834        let payload = serde_json::json!({
835            "iss": issuer,
836            "sub": sub,
837            "iat": exp - 86400,
838            "exp": exp,
839            "jwks": {"keys": jwks_keys},
840        });
841        let h = b64u_json(&header);
842        let p = b64u_json(&payload);
843        let signing_input = format!("{}.{}", h, p);
844        let sig = signing_key.sign(signing_input.as_bytes());
845        format!("{}.{}", signing_input, b64u(&sig.to_bytes()))
846    }
847
848    fn jwk_of(vk: &VerifyingKey) -> serde_json::Value {
849        serde_json::json!({
850            "kty": "OKP",
851            "crv": "Ed25519",
852            "x": b64u(vk.as_bytes()),
853            "use": "sig",
854        })
855    }
856
857    fn future_exp() -> i64 {
858        std::time::SystemTime::now()
859            .duration_since(std::time::UNIX_EPOCH)
860            .map(|d| d.as_secs() as i64)
861            .unwrap_or(0)
862            + 3600
863    }
864
865    #[test]
866    fn entity_stmt_self_validation_accepts_legitimate_statement() {
867        let sk = SigningKey::generate(&mut OsRng);
868        let vk = sk.verifying_key();
869        let jwt = build_entity_statement(
870            &sk,
871            "https://issuer.example",
872            "https://issuer.example",
873            future_exp(),
874            vec![jwk_of(&vk)],
875        );
876        let resolved = verify_self_issued_entity_statement(&jwt, "https://issuer.example")
877            .expect("legitimate self-issued statement must verify");
878        assert_eq!(resolved.as_bytes(), vk.as_bytes());
879    }
880
881    #[test]
882    fn entity_stmt_self_validation_rejects_iss_mismatch() {
883        let sk = SigningKey::generate(&mut OsRng);
884        let vk = sk.verifying_key();
885        let jwt = build_entity_statement(
886            &sk,
887            "https://other.example",
888            "https://other.example",
889            future_exp(),
890            vec![jwk_of(&vk)],
891        );
892        let err = verify_self_issued_entity_statement(&jwt, "https://issuer.example")
893            .expect_err("iss mismatch must reject");
894        assert!(format!("{err}").contains("iss"), "got: {err}");
895    }
896
897    #[test]
898    fn entity_stmt_self_validation_rejects_sub_iss_mismatch() {
899        // iss matches expected but sub differs — must reject (self-issued check).
900        let sk = SigningKey::generate(&mut OsRng);
901        let vk = sk.verifying_key();
902        let jwt = build_entity_statement(
903            &sk,
904            "https://issuer.example",
905            "https://different.example",
906            future_exp(),
907            vec![jwk_of(&vk)],
908        );
909        let err = verify_self_issued_entity_statement(&jwt, "https://issuer.example")
910            .expect_err("sub != iss must reject");
911        assert!(format!("{err}").contains("sub"), "got: {err}");
912    }
913
914    #[test]
915    fn entity_stmt_self_validation_rejects_expired() {
916        let sk = SigningKey::generate(&mut OsRng);
917        let vk = sk.verifying_key();
918        let past_exp = std::time::SystemTime::now()
919            .duration_since(std::time::UNIX_EPOCH)
920            .map(|d| d.as_secs() as i64)
921            .unwrap_or(0)
922            - 60;
923        let jwt = build_entity_statement(
924            &sk,
925            "https://issuer.example",
926            "https://issuer.example",
927            past_exp,
928            vec![jwk_of(&vk)],
929        );
930        let err = verify_self_issued_entity_statement(&jwt, "https://issuer.example")
931            .expect_err("expired must reject");
932        assert!(format!("{err}").contains("expired"), "got: {err}");
933    }
934
935    #[test]
936    fn entity_stmt_self_validation_rejects_tampered_payload() {
937        let sk = SigningKey::generate(&mut OsRng);
938        let vk = sk.verifying_key();
939        let jwt = build_entity_statement(
940            &sk,
941            "https://issuer.example",
942            "https://issuer.example",
943            future_exp(),
944            vec![jwk_of(&vk)],
945        );
946        // Re-encode payload with a different exp; signature stays from the
947        // original. Verifier MUST reject.
948        let parts: Vec<&str> = jwt.split('.').collect();
949        let tampered_payload = b64u_json(&serde_json::json!({
950            "iss": "https://issuer.example",
951            "sub": "https://issuer.example",
952            "iat": future_exp() - 7200,
953            "exp": future_exp() + 99999, // tampered
954            "jwks": {"keys": [jwk_of(&vk)]},
955        }));
956        let tampered_jwt = format!("{}.{}.{}", parts[0], tampered_payload, parts[2]);
957        let err = verify_self_issued_entity_statement(&tampered_jwt, "https://issuer.example")
958            .expect_err("tampered payload must reject");
959        assert!(format!("{err}").contains("no Ed25519 key"), "got: {err}");
960    }
961
962    #[test]
963    fn entity_stmt_self_validation_rejects_stripping_attack() {
964        // Attacker presents an entity statement whose jwks contains ONLY
965        // their own key (legitimate issuer's key stripped), but signs with
966        // their own key. Verifier MUST reject because the signing key is
967        // not the legitimate issuer's — even though the JWT internally
968        // self-validates against the attacker's key. The "issuer is trusted"
969        // contract is enforced by the trusted_issuers config layer above
970        // this function; here we test that an attacker who substitutes a
971        // statement with their own jwks-and-signing-key still cannot do so
972        // unless they ALSO control the legitimate issuer URL — that is,
973        // self-validation is necessary but not sufficient. This test just
974        // confirms the function CAN validate against an arbitrary attacker
975        // key (trust is layered outside): no key from the original issuer
976        // is needed; the function trusts iss+self-validation.
977        //
978        // The real defense against an attacker with full control is the
979        // trusted_issuers config, not self-validation. Self-validation
980        // defeats tampering during delivery, which is its purpose.
981        let attacker_sk = SigningKey::generate(&mut OsRng);
982        let attacker_vk = attacker_sk.verifying_key();
983        let jwt = build_entity_statement(
984            &attacker_sk,
985            "https://issuer.example",
986            "https://issuer.example",
987            future_exp(),
988            vec![jwk_of(&attacker_vk)],
989        );
990        // Self-validates because attacker controls everything internally.
991        // This proves the function does NOT establish trust in the issuer;
992        // it only checks the statement is self-consistent.
993        let resolved = verify_self_issued_entity_statement(&jwt, "https://issuer.example")
994            .expect("self-consistent statement validates regardless of who signed it");
995        assert_eq!(resolved.as_bytes(), attacker_vk.as_bytes());
996    }
997
998    #[test]
999    fn entity_stmt_self_validation_rejects_signature_from_key_not_in_jwks() {
1000        // The realistic delivery-tampering scenario: attacker takes a
1001        // legitimate statement and substitutes the signature with their own
1002        // (without putting their key in the jwks). MUST reject.
1003        let legit_sk = SigningKey::generate(&mut OsRng);
1004        let legit_vk = legit_sk.verifying_key();
1005        let attacker_sk = SigningKey::generate(&mut OsRng);
1006
1007        // Build the legitimate signed input but sign with the attacker key.
1008        let header = serde_json::json!({"alg": "EdDSA", "typ": "entity-statement+jwt"});
1009        let payload = serde_json::json!({
1010            "iss": "https://issuer.example",
1011            "sub": "https://issuer.example",
1012            "iat": future_exp() - 3600,
1013            "exp": future_exp(),
1014            "jwks": {"keys": [jwk_of(&legit_vk)]},
1015        });
1016        let h = b64u_json(&header);
1017        let p = b64u_json(&payload);
1018        let signing_input = format!("{}.{}", h, p);
1019        let bad_sig = attacker_sk.sign(signing_input.as_bytes());
1020        let bad_jwt = format!("{}.{}", signing_input, b64u(&bad_sig.to_bytes()));
1021
1022        let err = verify_self_issued_entity_statement(&bad_jwt, "https://issuer.example")
1023            .expect_err("signature from key not in jwks must reject");
1024        assert!(format!("{err}").contains("no Ed25519 key"), "got: {err}");
1025    }
1026
1027    #[test]
1028    fn entity_stmt_self_validation_rejects_non_eddsa_alg() {
1029        // Header with alg=RS256 must be rejected outright.
1030        let sk = SigningKey::generate(&mut OsRng);
1031        let vk = sk.verifying_key();
1032        let header = serde_json::json!({"alg": "RS256", "typ": "entity-statement+jwt"});
1033        let payload = serde_json::json!({
1034            "iss": "https://issuer.example",
1035            "sub": "https://issuer.example",
1036            "iat": future_exp() - 3600,
1037            "exp": future_exp(),
1038            "jwks": {"keys": [jwk_of(&vk)]},
1039        });
1040        let h = b64u_json(&header);
1041        let p = b64u_json(&payload);
1042        let signing_input = format!("{}.{}", h, p);
1043        let sig = sk.sign(signing_input.as_bytes());
1044        let jwt = format!("{}.{}", signing_input, b64u(&sig.to_bytes()));
1045        let err = verify_self_issued_entity_statement(&jwt, "https://issuer.example")
1046            .expect_err("non-EdDSA alg must reject");
1047        assert!(format!("{err}").contains("EdDSA"), "got: {err}");
1048    }
1049
1050    #[test]
1051    fn entity_stmt_self_validation_rejects_malformed_jwt() {
1052        let err = verify_self_issued_entity_statement("not.a.jwt.with.too.many.parts", "x")
1053            .expect_err("malformed JWT must reject");
1054        assert!(format!("{err}").contains("3-part"), "got: {err}");
1055    }
1056
1057    // ──────────────────────────────────────────────────────────────────
1058    // #1185 — rotation-aware JWKS key set (overlap + kid selection)
1059    // ──────────────────────────────────────────────────────────────────
1060
1061    use std::sync::atomic::{AtomicU32, Ordering};
1062
1063    fn jwk_with_kid(vk: &VerifyingKey, kid: &str) -> serde_json::Value {
1064        serde_json::json!({
1065            "kty": "OKP",
1066            "crv": "Ed25519",
1067            "x": b64u(vk.as_bytes()),
1068            "use": "sig",
1069            "alg": "EdDSA",
1070            "kid": kid,
1071        })
1072    }
1073
1074    fn federation_token(signing_key: &SigningKey, kid: &str, sub: &str) -> String {
1075        let exp = future_exp();
1076        let claims = Claims::new(sub.to_owned(), exp - 3600, exp)
1077            .with_issuer("https://fed.example".to_owned());
1078        let header = serde_json::json!({"alg": "EdDSA", "typ": "at+jwt", "kid": kid});
1079        let signing_input = format!(
1080            "{}.{}",
1081            b64u_json(&header),
1082            b64u(&serde_json::to_vec(&claims).expect("claims json"))
1083        );
1084        let signature = signing_key.sign(signing_input.as_bytes());
1085        format!("{}.{}", signing_input, b64u(&signature.to_bytes()))
1086    }
1087
1088    fn trusted_issuer(jwks_uri: &str) -> HashMap<String, crate::config::TrustedIssuerConfig> {
1089        let mut issuers = HashMap::new();
1090        issuers.insert(
1091            "https://fed.example".to_owned(),
1092            crate::config::TrustedIssuerConfig {
1093                jwks_uri: Some(jwks_uri.to_owned()),
1094                jwks_cache_ttl_secs: 300,
1095                allow_http: true,
1096                federate_tui_client: None,
1097            },
1098        );
1099        issuers
1100    }
1101
1102    /// `parse_jwks_ed25519` retains EVERY published Ed25519 key with its kid,
1103    /// not just the first — the core anti-singleton invariant from #1183.
1104    #[test]
1105    fn parse_jwks_retains_all_ed25519_entries_with_kids() {
1106        let sk_a = SigningKey::generate(&mut OsRng);
1107        let sk_b = SigningKey::generate(&mut OsRng);
1108        let jwks = serde_json::json!({
1109            "keys": [
1110                jwk_with_kid(&sk_a.verifying_key(), "kid-old"),
1111                jwk_with_kid(&sk_b.verifying_key(), "kid-new"),
1112            ]
1113        });
1114        let entries = parse_jwks_ed25519(&jwks, "https://fed.example/jwks");
1115        assert_eq!(entries.len(), 2, "both published keys must be retained");
1116        let kids: Vec<Option<&str>> = entries.iter().map(|e| e.kid.as_deref()).collect();
1117        assert!(kids.contains(&Some("kid-old")));
1118        assert!(kids.contains(&Some("kid-new")));
1119    }
1120
1121    /// Production-boundary overlap acceptance: two published keys each verify
1122    /// their own named token. A named token is never allowed to fall back to a
1123    /// different co-published key.
1124    #[tokio::test]
1125    async fn get_keys_overlap_returns_both_and_resolves_second_by_kid() {
1126        let sk_old = SigningKey::generate(&mut OsRng);
1127        let sk_new = SigningKey::generate(&mut OsRng);
1128        let vk_old = sk_old.verifying_key();
1129        let vk_new = sk_new.verifying_key();
1130        let jwks = serde_json::json!({
1131            "keys": [
1132                jwk_with_kid(&vk_old, "kid-old"),
1133                jwk_with_kid(&vk_new, "kid-new"),
1134            ]
1135        });
1136        let fetcher: JwksFetcher = Arc::new(move |_url| {
1137            let jwks = jwks.clone();
1138            Box::pin(async move { Ok(jwks) })
1139        });
1140        let resolver = FederationKeyResolver::new(&trusted_issuer("https://fed.example/jwks"))
1141            .with_jwks_fetcher(fetcher);
1142
1143        let old_token = federation_token(&sk_old, "kid-old", "old-subject");
1144        let new_token = federation_token(&sk_new, "kid-new", "new-subject");
1145
1146        // No kid → all candidates are available to a genuinely kid-less token.
1147        let all = resolver
1148            .get_keys("https://fed.example", None)
1149            .await
1150            .expect("both keys");
1151        assert_eq!(all.len(), 2, "overlap: both keys must be returned");
1152
1153        let new_candidates = resolver
1154            .get_keys("https://fed.example", Some("kid-new"))
1155            .await
1156            .expect("kid-new resolves");
1157        assert_eq!(new_candidates.len(), 1, "named lookup must not fall back");
1158        assert_eq!(new_candidates[0].verifying_key, vk_new);
1159        assert_eq!(
1160            jwt::decode_with_federation_candidates(&new_token, &new_candidates, None)
1161                .expect("new overlap token verifies")
1162                .sub,
1163            "new-subject"
1164        );
1165
1166        let old_candidates = resolver
1167            .get_keys("https://fed.example", Some("kid-old"))
1168            .await
1169            .expect("kid-old resolves");
1170        assert_eq!(old_candidates.len(), 1, "named lookup must not fall back");
1171        assert_eq!(old_candidates[0].verifying_key, vk_old);
1172        assert_eq!(
1173            jwt::decode_with_federation_candidates(&old_token, &old_candidates, None)
1174                .expect("old overlap token verifies")
1175                .sub,
1176            "old-subject"
1177        );
1178    }
1179
1180    /// A named `kid` that is not in the published set after a fresh fetch
1181    /// MUST fail closed — never silently substitute another published key
1182    /// (the positional-singleton anti-pattern, #1183).
1183    #[tokio::test]
1184    async fn get_keys_unknown_kid_fails_closed_without_substitution() {
1185        let sk = SigningKey::generate(&mut OsRng);
1186        let jwks = serde_json::json!({"keys": [jwk_with_kid(&sk.verifying_key(), "kid-real")]});
1187        let fetcher: JwksFetcher = Arc::new(move |_url| {
1188            let jwks = jwks.clone();
1189            Box::pin(async move { Ok(jwks) })
1190        });
1191        let resolver = FederationKeyResolver::new(&trusted_issuer("https://fed.example/jwks"))
1192            .with_jwks_fetcher(fetcher);
1193
1194        let err = resolver
1195            .get_keys("https://fed.example", Some("kid-ghost"))
1196            .await
1197            .expect_err("unknown kid must fail closed");
1198        assert!(
1199            format!("{err}").contains("kid-ghost"),
1200            "error must name the missing kid: {err}"
1201        );
1202    }
1203
1204    #[tokio::test]
1205    async fn repeated_unknown_kid_uses_one_refresh_within_negative_ttl() {
1206        let sk = SigningKey::generate(&mut OsRng);
1207        let jwks = serde_json::json!({"keys": [jwk_with_kid(&sk.verifying_key(), "kid-real")]});
1208        let fetch_count = Arc::new(AtomicU32::new(0));
1209        let count = Arc::clone(&fetch_count);
1210        let fetcher: JwksFetcher = Arc::new(move |_url| {
1211            let jwks = jwks.clone();
1212            let count = Arc::clone(&count);
1213            Box::pin(async move {
1214                count.fetch_add(1, Ordering::SeqCst);
1215                Ok(jwks)
1216            })
1217        });
1218        let resolver = FederationKeyResolver::new(&trusted_issuer("https://fed.example/jwks"))
1219            .with_jwks_fetcher(fetcher);
1220
1221        for _ in 0..3 {
1222            assert!(resolver
1223                .get_keys("https://fed.example", Some("kid-ghost"))
1224                .await
1225                .is_err());
1226        }
1227        assert_eq!(
1228            fetch_count.load(Ordering::SeqCst),
1229            1,
1230            "one miss → one refresh per negative TTL"
1231        );
1232    }
1233
1234    /// Overlap rotation lifecycle: publish [old,new] (both accepted), then
1235    /// publish [new] only — the rotation completed and `old` is now retired
1236    /// past its bounded observation window. A subsequent request for `old`
1237    /// refetches and finds it gone, so it fails closed. This is the
1238    /// "retired one rejected after bounded window" overlap test.
1239    #[tokio::test]
1240    async fn get_keys_retired_key_rejected_after_rotation_completes() {
1241        let sk_old = SigningKey::generate(&mut OsRng);
1242        let sk_new = SigningKey::generate(&mut OsRng);
1243        let vk_old = sk_old.verifying_key();
1244        let vk_new = sk_new.verifying_key();
1245
1246        // Overlap window: both keys published.
1247        let overlap = serde_json::json!({
1248            "keys": [
1249                jwk_with_kid(&vk_old, "kid-old"),
1250                jwk_with_kid(&vk_new, "kid-new"),
1251            ]
1252        });
1253        // Post-rotation: only the new key remains (old retired).
1254        let rotated = serde_json::json!({"keys": [jwk_with_kid(&vk_new, "kid-new")]});
1255
1256        // The fetcher returns `overlap` for the first call and `rotated`
1257        // thereafter — modelling a JWKS that drops the old key between
1258        // the two observations (the bounded drain window elapsing).
1259        let call_count = Arc::new(AtomicU32::new(0));
1260        let cc = call_count.clone();
1261        let fetcher: JwksFetcher = Arc::new(move |_url| {
1262            let cc = cc.clone();
1263            let overlap = overlap.clone();
1264            let rotated = rotated.clone();
1265            Box::pin(async move {
1266                let n = cc.fetch_add(1, Ordering::SeqCst);
1267                if n == 0 {
1268                    Ok(overlap)
1269                } else {
1270                    Ok(rotated)
1271                }
1272            })
1273        });
1274
1275        // Use a zero TTL so the second lookup forces a fresh refetch.
1276        let mut issuers = HashMap::new();
1277        issuers.insert(
1278            "https://fed.example".to_owned(),
1279            crate::config::TrustedIssuerConfig {
1280                jwks_uri: Some("https://fed.example/jwks".to_owned()),
1281                jwks_cache_ttl_secs: 0,
1282                allow_http: true,
1283                federate_tui_client: None,
1284            },
1285        );
1286        let resolver = FederationKeyResolver::new(&issuers).with_jwks_fetcher(fetcher);
1287
1288        let old_token = federation_token(&sk_old, "kid-old", "old-subject");
1289        let new_token = federation_token(&sk_new, "kid-new", "new-subject");
1290
1291        // During overlap both signed tokens verify at the resolver/verifier
1292        // boundary, not merely by inspecting returned vectors.
1293        let during_overlap = resolver
1294            .get_keys("https://fed.example", Some("kid-old"))
1295            .await
1296            .expect("old key honoured during overlap");
1297        assert!(jwt::decode_with_federation_candidates(&old_token, &during_overlap, None).is_ok());
1298        let new_during_overlap = resolver
1299            .get_keys("https://fed.example", Some("kid-new"))
1300            .await
1301            .expect("new key honoured during overlap");
1302        assert!(
1303            jwt::decode_with_federation_candidates(&new_token, &new_during_overlap, None).is_ok()
1304        );
1305
1306        // After rotation drains, the old kid is gone — refetch, fail closed.
1307        let err = resolver
1308            .get_keys("https://fed.example", Some("kid-old"))
1309            .await
1310            .expect_err("retired key must be rejected after drain");
1311        assert!(
1312            format!("{err}").contains("kid-old"),
1313            "retired-key error must name the kid: {err}"
1314        );
1315
1316        // The new key is unaffected.
1317        let after = resolver
1318            .get_keys("https://fed.example", Some("kid-new"))
1319            .await
1320            .expect("new key still resolves");
1321        assert!(jwt::decode_with_federation_candidates(&new_token, &after, None).is_ok());
1322    }
1323}