Skip to main content

hyprstream_rpc/auth/
key_source.rs

1//! JWT key source abstraction for unified key resolution.
2//!
3//! `JwtKeySource` provides a unified interface for resolving JWT verification keys,
4//! abstracting the difference between:
5//! - Regular services (trust only cluster CA)
6//! - PolicyService (handles federation via ID-JAG, SPIFFE, OIDC)
7//!
8//! # Trust Model
9//!
10//! Services within a cluster all trust the same PolicyService. The CA verifying key
11//! is derived from the cluster's root signing key via HKDF:
12//! `derive_purpose_key(&root_key, "hyprstream-jwt-v1").verifying_key()`
13//!
14//! # Usage
15//!
16//! Services receive a `JwtKeySource` at construction time, binding them to their
17//! trust anchors. Most services use `ClusterKeySource`; PolicyService uses
18//! `FederatedKeySource` for cross-cluster token exchange.
19//!
20//! ```ignore
21//! // In service factory:
22//! let key_source = ctx.cluster_key_source();
23//! let service = MyService::new(...).with_jwt_key_source(key_source);
24//! ```
25
26// The ML-DSA-65 verifying-key list is shared across crates (the rotation task
27// in `hyprstream` and the service factory in `hyprstream-service`) via an
28// `Arc<std::sync::RwLock<..>>` contract, so this module intentionally uses
29// `std::sync::RwLock` for that field rather than `parking_lot::RwLock`.
30#![allow(clippy::disallowed_types)]
31
32use anyhow::Result;
33use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine};
34use ed25519_dalek::VerifyingKey;
35use std::collections::{HashMap, HashSet};
36use std::sync::Arc;
37use tokio::sync::{RwLock, Semaphore};
38
39/// Source of JWT verification keys.
40///
41/// Abstracts key resolution for both local (cluster CA) and federated
42/// (external IdP) tokens. Services receive this at construction time,
43/// binding them to their trust anchors.
44#[async_trait::async_trait]
45pub trait JwtKeySource: Send + Sync + 'static {
46    /// Get the verifying key for a given issuer and optional kid.
47    ///
48    /// A supplied `kid` is a strict selector: implementations MUST return only
49    /// the key published under that exact name or fail. It is never permission
50    /// to substitute another co-published key. Kid-less multi-key verification
51    /// uses [`JwtKeySource::get_keys`] instead.
52    ///
53    /// # Errors
54    ///
55    /// Returns error if the issuer is untrusted or key resolution fails.
56    async fn get_key(&self, issuer: &str, kid: Option<&str>) -> Result<VerifyingKey>;
57
58    /// Resolve **all** algorithm-compatible candidates for an issuer/kid pair.
59    ///
60    /// This is the safe default for verifying a kid-less JWT: when no `kid`
61    /// selector is present the verifier cannot know which published key signed
62    /// the token, so it MUST retain every compatible candidate and try each
63    /// until one verifies — never collapse the published set to a positional
64    /// singleton (`first`/`next`/`values().next()`). See #1183 / #1184.
65    ///
66    /// Single-key sources return a one-element vec. JWKS-backed sources
67    /// override this to return every Ed25519 entry when `kid` is `None`.
68    ///
69    /// Callers pair this with [`crate::auth::jwt::decode_with_any_key`] to
70    /// try each candidate against the JWT signature.
71    async fn get_keys(&self, issuer: &str, kid: Option<&str>) -> Result<Vec<VerifyingKey>> {
72        let key = self.get_key(issuer, kid).await?;
73        Ok(vec![key])
74    }
75
76    /// Check if an issuer is trusted (before attempting key fetch).
77    ///
78    /// Returns `true` for local issuers and configured federated issuers.
79    fn is_trusted(&self, issuer: &str) -> bool;
80
81    /// List of issuer URLs considered "local" (for subject formatting).
82    ///
83    /// Used by `Claims::subject()` to determine whether to namespace the
84    /// subject with the issuer URL (federated) or use it bare (local).
85    fn local_issuers(&self) -> &[String];
86
87    /// Get all current ML-DSA-65 verifying keys for PQ-hybrid JWT verification.
88    ///
89    /// Returns keys for all rotation slots (drain/active/lead) so that tokens
90    /// signed by any current slot can be verified. Empty vec disables PQ verification.
91    fn ml_dsa_verifying_keys(&self) -> Vec<crate::crypto::pq::MlDsaVerifyingKey> {
92        vec![]
93    }
94
95    /// Return the authoritative exact-pair composite key ledger.
96    fn composite_key_set(&self) -> Arc<super::CompositeKeySet> {
97        super::global_composite_key_set()
98    }
99
100    /// Resolve the exact composite verification pair for a JOSE `kid`.
101    ///
102    /// The default consults the composite key ledger. Sources that also hold
103    /// an out-of-ledger CA composite pair (the service-JWT plane, where the
104    /// ML-DSA-65 half is derived from the CA JWT signing key rather than
105    /// rotated through the ledger) override this to consult it as well.
106    /// An unknown `kid` resolves to `None` — verification fails closed.
107    fn composite_pair(&self, kid: &str) -> Option<super::CompositeKeyPair> {
108        self.composite_key_set().snapshot().pair(kid).cloned()
109    }
110
111    /// Return the list of `alg` values bound to a given `kid` in the JWKS.
112    ///
113    /// This is used as a **stripping defense**: when a JWKS entry carries a
114    /// composite-signature `alg` (e.g. `ML-DSA-65-Ed25519`) under a kid, the
115    /// verifier MUST require that any JWT presenting that kid uses the exact
116    /// same alg — preventing an attacker who controls one component key from
117    /// presenting a single-algorithm JWT under the composite kid.
118    ///
119    /// Default implementation returns an empty vec, which means "no policy
120    /// constraint" (legacy behavior). Implementations backed by JWKS should
121    /// override to surface the algs they observed.
122    fn kid_algs(&self, _issuer: &str, _kid: &str) -> Vec<String> {
123        Vec::new()
124    }
125}
126
127/// Key source for regular services — trusts only the cluster CA.
128///
129/// This is the common case: all services in a cluster trust one PolicyService,
130/// identified by its OAuth issuer URL. JWTs with empty `iss` or matching the
131/// local issuer URL are verified against the CA key.
132///
133/// # NOT a mesh authority (#328)
134///
135/// `ClusterKeySource` holds a SINGLE shared CA key and treats an empty `iss` as
136/// always-trusted/local. That is correct for the in-cluster bare-`sub` token
137/// plane, but it MUST NOT be the verification authority for networked **mesh
138/// peers**: a single shared key cannot distinguish per-host peers, and the
139/// empty-`iss` shortcut would let a networked peer inherit local trust. Mesh
140/// peer identity is established by the per-host key roster (Ed25519 signer →
141/// `service:inference:host-<label>`, resolved fail-closed via
142/// `RequestService::resolve_key_subject`), and the empty-`iss` shortcut is
143/// confined to genuine in-process callers in `verify_claims`
144/// (`EnvelopeContext::is_local_caller`). For kid-routed multi-key verification
145/// prefer [`JwksKeySource`], which honors the `kid` hint.
146#[derive(Clone)]
147pub struct ClusterKeySource {
148    ca_verifying_key: VerifyingKey,
149    local_issuers_vec: Vec<String>,
150    ml_dsa_vks: Arc<std::sync::RwLock<Vec<crate::crypto::pq::MlDsaVerifyingKey>>>,
151    composite_keys: Arc<super::CompositeKeySet>,
152    /// Out-of-ledger CA composite pair for hybrid service-JWT verification.
153    ///
154    /// The CA's ML-DSA-65 half is derived from the CA JWT signing key rather
155    /// than rotated through the composite ledger, so the ledger never lists
156    /// its kid. Holding the exact pair here lets a hybrid service WIT resolve
157    /// without weakening the ledger: any other kid still fails closed.
158    ca_composite: Option<super::CompositeKeyPair>,
159}
160
161fn local_issuer_aliases(local_issuer_url: &str) -> Vec<String> {
162    if local_issuer_url.is_empty() {
163        return Vec::new();
164    }
165    let mut issuers = vec![local_issuer_url.to_owned()];
166    // Keep this byte-for-byte aligned with OAuthState::canonical_issuer_origin:
167    // the atproto issuer is the configured scheme + authority with its path
168    // removed, without URL-library normalization of ports or casing.
169    if let Some((scheme, rest)) = local_issuer_url.split_once("://") {
170        let authority = rest.split('/').next().unwrap_or_default();
171        let origin = format!("{scheme}://{authority}");
172        if !scheme.is_empty() && !authority.is_empty() && origin != local_issuer_url {
173            issuers.push(origin);
174        }
175    }
176    issuers
177}
178
179impl ClusterKeySource {
180    /// Create a new cluster key source.
181    ///
182    /// # Arguments
183    ///
184    /// * `ca_verifying_key` - The cluster's CA verifying key (from PolicyService)
185    /// * `local_issuer_url` - The OAuth issuer URL (e.g., "http://127.0.0.1:9080")
186    pub fn new(ca_verifying_key: VerifyingKey, local_issuer_url: String) -> Self {
187        let local_issuers_vec = local_issuer_aliases(&local_issuer_url);
188        Self {
189            ca_verifying_key,
190            local_issuers_vec,
191            ml_dsa_vks: Arc::new(std::sync::RwLock::new(Vec::new())),
192            composite_keys: super::global_composite_key_set(),
193            ca_composite: None,
194        }
195    }
196
197    /// Set the shared ML-DSA-65 verifying key list for PQ-hybrid JWT verification.
198    ///
199    /// The Arc is shared with the rotation task so keys stay current.
200    pub fn with_ml_dsa_verifying_keys(
201        mut self,
202        vks: Arc<std::sync::RwLock<Vec<crate::crypto::pq::MlDsaVerifyingKey>>>,
203    ) -> Self {
204        self.ml_dsa_vks = vks;
205        self
206    }
207
208    /// Override the composite key ledger, primarily for isolated service instances.
209    pub fn with_composite_key_set(mut self, keys: Arc<super::CompositeKeySet>) -> Self {
210        self.composite_keys = keys;
211        self
212    }
213
214    /// Bind the CA's derived ML-DSA-65 verifying key so the CA composite kid
215    /// resolves to BOTH halves (this ML-DSA key + the CA Ed25519 key).
216    ///
217    /// This is how hybrid service WITs — signed by the exact pair
218    /// `(derived ML-DSA, CA Ed25519)` — verify on the dispatch plane. The
219    /// pair is registered under the Policy role: it belongs to the CA /
220    /// service-certification signing domain, so role-constrained consumers
221    /// (service-key certification, announcements) accept it while the
222    /// OAuth-role token-issuance domain stays separate.
223    pub fn with_ca_composite_key(
224        mut self,
225        ml_dsa_vk: crate::crypto::pq::MlDsaVerifyingKey,
226    ) -> Self {
227        let kid = super::jwt::composite_kid(&ml_dsa_vk, &self.ca_verifying_key);
228        self.ca_composite = Some(super::CompositeKeyPair::verifying(
229            kid,
230            ml_dsa_vk,
231            self.ca_verifying_key,
232            super::CompositePairRole::Policy,
233            super::CompositePairState::Active,
234            0,
235            i64::MAX,
236        ));
237        self
238    }
239
240    /// Get the CA verifying key.
241    pub fn ca_verifying_key(&self) -> VerifyingKey {
242        self.ca_verifying_key
243    }
244}
245
246#[async_trait::async_trait]
247impl JwtKeySource for ClusterKeySource {
248    async fn get_key(&self, issuer: &str, _kid: Option<&str>) -> Result<VerifyingKey> {
249        if self.is_trusted(issuer) {
250            Ok(self.ca_verifying_key)
251        } else {
252            anyhow::bail!("Untrusted issuer: {}", issuer)
253        }
254    }
255
256    fn is_trusted(&self, issuer: &str) -> bool {
257        // Empty issuer is treated as local here. This is SOUND only because the
258        // empty-`iss` shortcut is gated by transport upstream in
259        // `verify_claims` (#328): a networked / mesh caller presenting an
260        // empty-`iss` token is rejected before this is consulted, so empty `iss`
261        // reaches here only for genuine in-process / IPC callers.
262        if issuer.is_empty() {
263            return true;
264        }
265        // The atproto profile emits the canonical origin while generic OAuth
266        // retains the configured issuer (which may carry a path). Both are
267        // exact local aliases; sibling paths and foreign origins remain denied.
268        self.local_issuers_vec.iter().any(|local| local == issuer)
269    }
270
271    fn local_issuers(&self) -> &[String] {
272        &self.local_issuers_vec
273    }
274
275    fn ml_dsa_verifying_keys(&self) -> Vec<crate::crypto::pq::MlDsaVerifyingKey> {
276        self.ml_dsa_vks
277            .read()
278            .unwrap_or_else(std::sync::PoisonError::into_inner)
279            .clone()
280    }
281
282    fn composite_key_set(&self) -> Arc<super::CompositeKeySet> {
283        self.composite_keys.clone()
284    }
285
286    fn composite_pair(&self, kid: &str) -> Option<super::CompositeKeyPair> {
287        if let Some(pair) = self.composite_keys.snapshot().pair(kid) {
288            return Some(pair.clone());
289        }
290        // Exact-kid match only: any other kid stays unresolvable (fail closed).
291        self.ca_composite
292            .as_ref()
293            .filter(|pair| pair.kid() == kid)
294            .cloned()
295    }
296}
297
298/// Key source that combines local cluster trust with federation.
299///
300/// Used by PolicyService to accept tokens from:
301/// - Local cluster (via `ClusterKeySource`)
302/// - Federated IdPs (via `FederationKeySource`)
303///
304/// This enables ID-JAG token exchange for cross-cluster requests.
305pub struct FederatedKeySource {
306    local: ClusterKeySource,
307    federation: std::sync::Arc<dyn super::FederationKeySource>,
308}
309
310impl FederatedKeySource {
311    /// Create a federated key source.
312    ///
313    /// # Arguments
314    ///
315    /// * `local` - The cluster's local key source
316    /// * `federation` - Source for resolving federated issuer keys
317    pub fn new(
318        local: ClusterKeySource,
319        federation: std::sync::Arc<dyn super::FederationKeySource>,
320    ) -> Self {
321        Self { local, federation }
322    }
323}
324
325#[async_trait::async_trait]
326impl JwtKeySource for FederatedKeySource {
327    async fn get_key(&self, issuer: &str, kid: Option<&str>) -> Result<VerifyingKey> {
328        // Try local first
329        if self.local.is_trusted(issuer) {
330            return self.local.get_key(issuer, kid).await;
331        }
332        // Fall back to federation. A named token may use only the exact named
333        // key; a kid-less legacy caller retains the single-key fallback this
334        // trait requires.
335        if self.federation.is_trusted(issuer) {
336            let candidates = self.federation.get_keys(issuer, kid).await?;
337            return candidates
338                .iter()
339                .find(|candidate| match kid {
340                    Some(named_kid) => candidate.kid.as_deref() == Some(named_kid),
341                    None => true,
342                })
343                .map(|candidate| candidate.verifying_key)
344                .ok_or_else(|| anyhow::anyhow!("No Ed25519 key for issuer {}", issuer));
345        }
346        anyhow::bail!("Untrusted issuer: {}", issuer)
347    }
348
349    async fn get_keys(&self, issuer: &str, kid: Option<&str>) -> Result<Vec<VerifyingKey>> {
350        if self.local.is_trusted(issuer) {
351            return self.local.get_keys(issuer, kid).await;
352        }
353        if !self.federation.is_trusted(issuer) {
354            anyhow::bail!("Untrusted issuer: {}", issuer);
355        }
356
357        let candidates = self.federation.get_keys(issuer, kid).await?;
358        let keys: Vec<VerifyingKey> = candidates
359            .iter()
360            .filter(|candidate| match kid {
361                Some(named_kid) => candidate.kid.as_deref() == Some(named_kid),
362                None => true,
363            })
364            .map(|candidate| candidate.verifying_key)
365            .collect();
366        if keys.is_empty() {
367            anyhow::bail!("No Ed25519 key for issuer {}", issuer);
368        }
369        Ok(keys)
370    }
371
372    fn is_trusted(&self, issuer: &str) -> bool {
373        self.local.is_trusted(issuer) || self.federation.is_trusted(issuer)
374    }
375
376    fn local_issuers(&self) -> &[String] {
377        self.local.local_issuers()
378    }
379
380    fn ml_dsa_verifying_keys(&self) -> Vec<crate::crypto::pq::MlDsaVerifyingKey> {
381        self.local.ml_dsa_verifying_keys()
382    }
383
384    fn composite_key_set(&self) -> Arc<super::CompositeKeySet> {
385        self.local.composite_key_set()
386    }
387
388    fn composite_pair(&self, kid: &str) -> Option<super::CompositeKeyPair> {
389        self.local.composite_pair(kid)
390    }
391
392    fn kid_algs(&self, issuer: &str, kid: &str) -> Vec<String> {
393        self.local.kid_algs(issuer, kid)
394    }
395}
396
397/// Async function that fetches raw JWKS JSON from a URL.
398pub type JwksFetcher = Arc<
399    dyn Fn(
400            String,
401        )
402            -> std::pin::Pin<Box<dyn std::future::Future<Output = Result<serde_json::Value>> + Send>>
403        + Send
404        + Sync,
405>;
406
407/// Deployment mode for JWKS-backed key resolution.
408#[derive(Clone)]
409pub enum JwksMode {
410    /// Single-node: fetches JWKS from local `/oauth/jwks` endpoint.
411    Isolated { jwks_url: String },
412    /// Multi-node / cross-org: resolves issuer → JWKS URL via `IssuerResolver`.
413    Federated {
414        local_jwks_url: String,
415        resolver: Arc<dyn IssuerResolver>,
416    },
417}
418
419impl std::fmt::Debug for JwksMode {
420    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
421        match self {
422            Self::Isolated { jwks_url } => f
423                .debug_struct("Isolated")
424                .field("jwks_url", jwks_url)
425                .finish(),
426            Self::Federated { local_jwks_url, .. } => f
427                .debug_struct("Federated")
428                .field("local_jwks_url", local_jwks_url)
429                .finish(),
430        }
431    }
432}
433
434/// Resolves an issuer string to its JWKS endpoint URL.
435#[async_trait::async_trait]
436pub trait IssuerResolver: Send + Sync + 'static {
437    async fn resolve(&self, issuer: &str) -> Result<String>;
438}
439
440/// Cached JWKS key entry.
441struct CachedKey {
442    verifying_key: VerifyingKey,
443    #[allow(dead_code)]
444    fetched_at: std::time::Instant,
445}
446
447/// JWKS-backed key source with issuer-and-kid-based resolution.
448///
449/// Replaces `ClusterKeySource` with standards-aligned JWKS key lookup:
450/// - Caches keys by `(issuer, kid)` after fetching from the JWKS endpoint
451/// - On cache miss, refetches JWKS (primary invalidation mechanism)
452/// - Issuer-scoped negative cache prevents DoS from random kid spam (5s TTL)
453/// - Semaphore bounds concurrent JWKS fetches
454pub struct JwksKeySource {
455    mode: JwksMode,
456    local_issuers_vec: Vec<String>,
457    fetcher: JwksFetcher,
458    cache: RwLock<HashMap<String, HashMap<String, CachedKey>>>,
459    negative_cache: RwLock<HashMap<String, HashMap<String, std::time::Instant>>>,
460    /// Multi-alg map: issuer → kid → all `alg` values in that issuer's JWKS.
461    /// Populated alongside `cache` during `fetch_and_cache`. Both dimensions
462    /// are security boundaries: two issuers may legitimately reuse a kid.
463    kid_alg_map: parking_lot::RwLock<HashMap<String, HashMap<String, Vec<String>>>>,
464    fetch_semaphore: Semaphore,
465    /// Soft TTL for cache refresh (keys older than this trigger background refresh)
466    #[allow(dead_code)]
467    soft_ttl: std::time::Duration,
468    /// Negative cache TTL (unknown kids cached as missing for this duration)
469    negative_ttl: std::time::Duration,
470    ml_dsa_vks: Arc<std::sync::RwLock<Vec<crate::crypto::pq::MlDsaVerifyingKey>>>,
471    /// Authoritative local CA verifying key (on-disk, from PolicyService).
472    ///
473    /// Lets local-issuer JWTs — notably service-to-service WIT JWTs signed by
474    /// the CA over the local IPC plane — verify WITHOUT a network round-trip to
475    /// `/oauth/jwks`. The HTTP JWKS endpoint is not guaranteed to be up during
476    /// service startup (and #441 makes registration a hard precondition), so
477    /// depending on it for local service auth is a startup-ordering fail.
478    /// Consulted only for local issuers (`is_local`), and only when the JOSE
479    /// `kid` matches this key's JWK thumbprint — so it never overrides a
480    /// rotated/JWKS-published key, and is irrelevant to federated issuers.
481    local_ca_key: Option<VerifyingKey>,
482    local_ca_kid: Option<String>,
483    /// Out-of-ledger CA composite pair for hybrid service-JWT verification —
484    /// the JWKS-backed twin of `ClusterKeySource::ca_composite`, and offline
485    /// for the same startup-ordering reason as `local_ca_key`.
486    local_ca_composite: Option<super::CompositeKeyPair>,
487}
488
489impl JwksKeySource {
490    pub fn new(mode: JwksMode, local_issuer_url: String, fetcher: JwksFetcher) -> Self {
491        let local_issuers_vec = local_issuer_aliases(&local_issuer_url);
492        Self {
493            mode,
494            local_issuers_vec,
495            fetcher,
496            cache: RwLock::new(HashMap::new()),
497            negative_cache: RwLock::new(HashMap::new()),
498            kid_alg_map: parking_lot::RwLock::new(HashMap::new()),
499            fetch_semaphore: Semaphore::new(4),
500            soft_ttl: std::time::Duration::from_secs(300),
501            negative_ttl: std::time::Duration::from_secs(5),
502            ml_dsa_vks: Arc::new(std::sync::RwLock::new(Vec::new())),
503            local_ca_key: None,
504            local_ca_kid: None,
505            local_ca_composite: None,
506        }
507    }
508
509    /// Set the shared ML-DSA-65 verifying key list for PQ-hybrid JWT verification.
510    pub fn with_ml_dsa_verifying_keys(
511        mut self,
512        vks: Arc<std::sync::RwLock<Vec<crate::crypto::pq::MlDsaVerifyingKey>>>,
513    ) -> Self {
514        self.ml_dsa_vks = vks;
515        self
516    }
517
518    /// Provide the authoritative local CA verifying key for offline resolution
519    /// of local-issuer (service) JWTs. See the `local_ca_key` field docs.
520    pub fn with_local_ca_key(mut self, ca_vk: VerifyingKey) -> Self {
521        self.local_ca_kid = Some(crate::auth::jwt::jwk_thumbprint(
522            &crate::auth::jwt::JwkThumbprintInput::Ed25519 {
523                x: ca_vk.as_bytes(),
524            },
525        ));
526        self.local_ca_key = Some(ca_vk);
527        self
528    }
529
530    /// Bind the CA's derived ML-DSA-65 verifying key so the CA composite kid
531    /// resolves to BOTH halves (this ML-DSA key + the CA Ed25519 key) for
532    /// hybrid service-JWT verification. Registered under the Policy role —
533    /// the CA / service-certification signing domain — exactly like
534    /// [`ClusterKeySource::with_ca_composite_key`].
535    pub fn with_local_ca_composite(
536        mut self,
537        ml_dsa_vk: crate::crypto::pq::MlDsaVerifyingKey,
538        ca_vk: VerifyingKey,
539    ) -> Self {
540        let kid = super::jwt::composite_kid(&ml_dsa_vk, &ca_vk);
541        self.local_ca_composite = Some(super::CompositeKeyPair::verifying(
542            kid,
543            ml_dsa_vk,
544            ca_vk,
545            super::CompositePairRole::Policy,
546            super::CompositePairState::Active,
547            0,
548            i64::MAX,
549        ));
550        self
551    }
552
553    fn jwks_url_for_issuer(&self, issuer: &str) -> Option<String> {
554        match &self.mode {
555            JwksMode::Isolated { jwks_url } => {
556                if self.is_local(issuer) {
557                    Some(jwks_url.clone())
558                } else {
559                    None
560                }
561            }
562            JwksMode::Federated { local_jwks_url, .. } => {
563                if self.is_local(issuer) {
564                    Some(local_jwks_url.clone())
565                } else {
566                    None // federated resolution is async, handled in get_key
567                }
568            }
569        }
570    }
571
572    fn is_local(&self, issuer: &str) -> bool {
573        issuer.is_empty() || self.local_issuers_vec.iter().any(|local| local == issuer)
574    }
575
576    async fn resolve_jwks_url(&self, issuer: &str) -> Result<String> {
577        if let Some(url) = self.jwks_url_for_issuer(issuer) {
578            return Ok(url);
579        }
580        match &self.mode {
581            JwksMode::Federated { resolver, .. } => resolver.resolve(issuer).await,
582            JwksMode::Isolated { .. } => {
583                anyhow::bail!("Untrusted issuer in isolated mode: {}", issuer)
584            }
585        }
586    }
587
588    async fn fetch_and_cache(&self, issuer: &str) -> Result<()> {
589        let _permit = self
590            .fetch_semaphore
591            .acquire()
592            .await
593            .map_err(|_| anyhow::anyhow!("JWKS fetch semaphore closed"))?;
594
595        let url = self.resolve_jwks_url(issuer).await?;
596        let jwks = (self.fetcher)(url).await?;
597
598        let keys = jwks
599            .get("keys")
600            .and_then(|v| v.as_array())
601            .ok_or_else(|| anyhow::anyhow!("JWKS response missing 'keys' array"))?;
602
603        let now = std::time::Instant::now();
604        let mut issuer_cache: HashMap<String, CachedKey> = HashMap::new();
605        let mut issuer_kid_algs: HashMap<String, Vec<String>> = HashMap::new();
606
607        for key in keys {
608            let kty = key.get("kty").and_then(|v| v.as_str()).unwrap_or_default();
609            let crv = key.get("crv").and_then(|v| v.as_str()).unwrap_or_default();
610            let kid = key.get("kid").and_then(|v| v.as_str()).map(str::to_owned);
611            let alg = key.get("alg").and_then(|v| v.as_str()).map(str::to_owned);
612
613            // Track ALL JWKS entries (Ed25519, P-256, AKP) under their kid.
614            // The stripping defense fires when a kid has a composite alg, so we
615            // need to record those algs even though we can't verify-decode them
616            // here.
617            if let (Some(kid_str), Some(alg)) = (kid.as_ref(), alg) {
618                let entry = issuer_kid_algs.entry(kid_str.clone()).or_default();
619                if !entry.contains(&alg) {
620                    entry.push(alg);
621                }
622            }
623
624            if kty == "OKP" && crv == "Ed25519" {
625                if let Some(kid) = kid {
626                    if let Some(x) = key.get("x").and_then(|v| v.as_str()) {
627                        if let Ok(x_bytes) = URL_SAFE_NO_PAD.decode(x) {
628                            if x_bytes.len() == 32 {
629                                let mut arr = [0u8; 32];
630                                arr.copy_from_slice(&x_bytes);
631                                if let Ok(vk) = VerifyingKey::from_bytes(&arr) {
632                                    issuer_cache.insert(
633                                        kid,
634                                        CachedKey {
635                                            verifying_key: vk,
636                                            fetched_at: now,
637                                        },
638                                    );
639                                }
640                            }
641                        }
642                    }
643                }
644            }
645        }
646
647        let cached_kids: HashSet<String> = issuer_cache.keys().cloned().collect();
648
649        // Replace only this issuer's snapshot. A kid is not globally unique:
650        // publishing issuer B must neither overwrite nor expose issuer A's
651        // keys or algorithm metadata.
652        self.cache
653            .write()
654            .await
655            .insert(issuer.to_owned(), issuer_cache);
656        self.kid_alg_map
657            .write()
658            .insert(issuer.to_owned(), issuer_kid_algs);
659
660        // Clear negative-cache entries only for keys this issuer now has.
661        let mut neg = self.negative_cache.write().await;
662        if let Some(issuer_neg) = neg.get_mut(issuer) {
663            issuer_neg.retain(|kid, _| !cached_kids.contains(kid));
664        }
665
666        Ok(())
667    }
668
669    /// Resolve a single key by `kid`, consulting the offline local-CA path,
670    /// the JWKS cache, the negative cache, and (on miss) a refetch. The
671    /// `kid` selector makes the choice unambiguous — contrast with the
672    /// kid-less path in [`JwtKeySource::get_keys`] which must return every
673    /// candidate.
674    async fn resolve_by_kid(&self, issuer: &str, kid_str: &str) -> Result<VerifyingKey> {
675        // Authoritative local CA key (offline): for a LOCAL issuer whose
676        // `kid` matches the on-disk CA key thumbprint, resolve without any
677        // network fetch. This is the service-to-service WIT JWT path; the
678        // HTTP /oauth/jwks endpoint may not be up yet during startup, and
679        // #441 makes service-key registration a hard precondition, so this
680        // resolution must not depend on it. Never overrides a JWKS-published
681        // (rotated) key because it's keyed on the exact CA thumbprint.
682        if self.is_local(issuer) {
683            if let (Some(ca_kid), Some(ca_key)) = (self.local_ca_kid.as_deref(), self.local_ca_key)
684            {
685                if ca_kid == kid_str {
686                    return Ok(ca_key);
687                }
688            }
689        }
690        {
691            let cache = self.cache.read().await;
692            if let Some(entry) = cache
693                .get(issuer)
694                .and_then(|issuer_cache| issuer_cache.get(kid_str))
695            {
696                return Ok(entry.verifying_key);
697            }
698        }
699
700        // Check negative cache
701        {
702            let neg = self.negative_cache.read().await;
703            if let Some(&ts) = neg
704                .get(issuer)
705                .and_then(|issuer_cache| issuer_cache.get(kid_str))
706            {
707                if ts.elapsed() < self.negative_ttl {
708                    anyhow::bail!("Key not found for kid={} (negative cached)", kid_str);
709                }
710            }
711        }
712
713        // On-miss refetch
714        if let Err(e) = self.fetch_and_cache(issuer).await {
715            tracing::warn!("JWKS fetch failed for issuer={}: {}", issuer, e);
716        }
717
718        // Retry from cache
719        let cache = self.cache.read().await;
720        if let Some(entry) = cache
721            .get(issuer)
722            .and_then(|issuer_cache| issuer_cache.get(kid_str))
723        {
724            return Ok(entry.verifying_key);
725        }
726        drop(cache);
727
728        // Add to negative cache
729        {
730            let mut neg = self.negative_cache.write().await;
731            neg.entry(issuer.to_owned())
732                .or_default()
733                .insert(kid_str.to_owned(), std::time::Instant::now());
734        }
735
736        anyhow::bail!("Key not found in JWKS for kid={}", kid_str)
737    }
738
739    /// Ensure the JWKS cache has been populated for `issuer` (refetch on
740    /// empty). Used by the kid-less resolution paths before they read every
741    /// candidate out of the cache.
742    async fn ensure_cached(&self, issuer: &str) {
743        if !self.cache.read().await.contains_key(issuer) {
744            if let Err(e) = self.fetch_and_cache(issuer).await {
745                tracing::warn!("JWKS fetch failed for issuer={}: {}", issuer, e);
746            }
747        }
748    }
749}
750
751#[async_trait::async_trait]
752impl JwtKeySource for JwksKeySource {
753    async fn get_key(&self, issuer: &str, kid: Option<&str>) -> Result<VerifyingKey> {
754        if !self.is_trusted(issuer) {
755            anyhow::bail!("Untrusted issuer: {}", issuer);
756        }
757
758        // A presented `kid` is unambiguous: resolve that exact slot.
759        if let Some(kid_str) = kid {
760            return self.resolve_by_kid(issuer, kid_str).await;
761        }
762
763        // No kid: refuse to collapse a multi-key published set to a positional
764        // singleton. `get_keys` is the safe API for kid-less tokens — it
765        // returns every Ed25519 candidate so the caller can try each. Here we
766        // only succeed when the JWKS publishes exactly one key, which is the
767        // unambiguous case. Two or more published keys is overlap rotation /
768        // PQ-hybrid rollout territory and MUST NOT be resolved to "the first
769        // one" (#1183 / #1184).
770        self.ensure_cached(issuer).await;
771        let cache = self.cache.read().await;
772        let mut iter = cache
773            .get(issuer)
774            .into_iter()
775            .flat_map(|issuer_cache| issuer_cache.values());
776        match (iter.next(), iter.next()) {
777            (Some(first), None) => Ok(first.verifying_key),
778            (None, _) => anyhow::bail!("No Ed25519 keys in JWKS for issuer {}", issuer),
779            (Some(_), Some(_)) => anyhow::bail!(
780                "Issuer {} publishes multiple Ed25519 keys and the JWT carries no kid; \
781                 use get_keys() and try each candidate (overlap rotation / hybrid rollout)",
782                issuer
783            ),
784        }
785    }
786
787    async fn get_keys(&self, issuer: &str, kid: Option<&str>) -> Result<Vec<VerifyingKey>> {
788        if !self.is_trusted(issuer) {
789            anyhow::bail!("Untrusted issuer: {}", issuer);
790        }
791
792        // A presented `kid` selects one slot.
793        if let Some(kid_str) = kid {
794            let vk = self.resolve_by_kid(issuer, kid_str).await?;
795            return Ok(vec![vk]);
796        }
797
798        // No kid: return EVERY Ed25519 candidate so the caller can try each
799        // until one verifies. Never positional selection (#1183 / #1184).
800        self.ensure_cached(issuer).await;
801        let cache = self.cache.read().await;
802        let v: Vec<VerifyingKey> = cache
803            .get(issuer)
804            .into_iter()
805            .flat_map(|issuer_cache| issuer_cache.values())
806            .map(|e| e.verifying_key)
807            .collect();
808        if v.is_empty() {
809            anyhow::bail!("No Ed25519 keys in JWKS for issuer {}", issuer);
810        }
811        Ok(v)
812    }
813
814    fn is_trusted(&self, issuer: &str) -> bool {
815        if self.is_local(issuer) {
816            return true;
817        }
818        matches!(&self.mode, JwksMode::Federated { resolver, .. } if {
819            // Synchronous trust check — resolver.resolve() is async,
820            // so we can only check local issuers synchronously.
821            // For federated mode, we optimistically trust and let get_key fail.
822            true
823        })
824    }
825
826    fn local_issuers(&self) -> &[String] {
827        &self.local_issuers_vec
828    }
829
830    fn ml_dsa_verifying_keys(&self) -> Vec<crate::crypto::pq::MlDsaVerifyingKey> {
831        self.ml_dsa_vks
832            .read()
833            .unwrap_or_else(std::sync::PoisonError::into_inner)
834            .clone()
835    }
836
837    fn composite_pair(&self, kid: &str) -> Option<super::CompositeKeyPair> {
838        if let Some(pair) = self.composite_key_set().snapshot().pair(kid) {
839            return Some(pair.clone());
840        }
841        // Exact-kid match only: any other kid stays unresolvable (fail closed).
842        self.local_ca_composite
843            .as_ref()
844            .filter(|pair| pair.kid() == kid)
845            .cloned()
846    }
847
848    fn kid_algs(&self, issuer: &str, kid: &str) -> Vec<String> {
849        self.kid_alg_map
850            .read()
851            .get(issuer)
852            .and_then(|issuer_algs| issuer_algs.get(kid))
853            .cloned()
854            .unwrap_or_default()
855    }
856}
857
858#[cfg(test)]
859mod tests {
860    use super::*;
861    use ed25519_dalek::SigningKey;
862
863    fn test_ca_key() -> VerifyingKey {
864        let signing_key = SigningKey::from_bytes(&[1u8; 32]);
865        signing_key.verifying_key()
866    }
867
868    #[tokio::test]
869    async fn cluster_key_source_trusts_local_issuer() -> anyhow::Result<()> {
870        let ks = ClusterKeySource::new(test_ca_key(), "http://localhost:9080".to_owned());
871
872        assert!(ks.is_trusted("http://localhost:9080"));
873        assert!(ks.is_trusted("")); // Empty issuer is always local
874        assert!(!ks.is_trusted("http://other.example.com"));
875
876        let key = ks.get_key("http://localhost:9080", None).await?;
877        assert_eq!(key, test_ca_key());
878        Ok(())
879    }
880
881    #[tokio::test]
882    async fn local_key_sources_trust_canonical_origin_for_path_issuer() -> anyhow::Result<()> {
883        let configured = "https://pds.example.test/configured/path";
884        let origin = "https://pds.example.test";
885        let ks = ClusterKeySource::new(test_ca_key(), configured.to_owned());
886        assert!(ks.is_trusted(configured));
887        assert!(ks.is_trusted(origin));
888        assert!(!ks.is_trusted("https://pds.example.test/other"));
889        assert_eq!(ks.get_key(origin, None).await?, test_ca_key());
890        assert_eq!(ks.local_issuers(), &[configured, origin]);
891
892        let fetcher: JwksFetcher = std::sync::Arc::new(|_url: String| {
893            Box::pin(async move { anyhow::bail!("network must not be used") })
894        });
895        let jwks = JwksKeySource::new(
896            JwksMode::Isolated {
897                jwks_url: "https://pds.example.test/oauth/jwks".to_owned(),
898            },
899            configured.to_owned(),
900            fetcher,
901        )
902        .with_local_ca_key(test_ca_key());
903        assert!(jwks.is_trusted(origin));
904        assert_eq!(jwks.local_issuers(), &[configured, origin]);
905        Ok(())
906    }
907
908    /// #441/AAA: a JwksKeySource with a local CA key resolves a local-issuer
909    /// service JWT OFFLINE (no JWKS fetch) when the JOSE `kid` matches the CA
910    /// thumbprint — the service-to-service auth path must not depend on the HTTP
911    /// /oauth/jwks endpoint being up during startup.
912    #[tokio::test]
913    async fn jwks_source_resolves_local_ca_key_offline() -> anyhow::Result<()> {
914        // A fetcher that always fails — proves resolution does NOT touch it.
915        let fetcher: JwksFetcher = std::sync::Arc::new(|_url: String| {
916            Box::pin(
917                async move { anyhow::bail!("network must not be used for local CA resolution") },
918            )
919        });
920        let ca_sk = SigningKey::from_bytes(&[7u8; 32]);
921        let ca_vk = ca_sk.verifying_key();
922        let ca_kid = crate::auth::jwt::kid_for_key(&ca_sk);
923
924        let ks = JwksKeySource::new(
925            JwksMode::Isolated {
926                jwks_url: "http://127.0.0.1:1/oauth/jwks".to_owned(),
927            },
928            "http://localhost:9080".to_owned(),
929            fetcher,
930        )
931        .with_local_ca_key(ca_vk);
932
933        // Local issuer + matching kid -> resolved offline to the CA key.
934        let key = ks.get_key("http://localhost:9080", Some(&ca_kid)).await?;
935        assert_eq!(key, ca_vk);
936
937        // Empty issuer is also local (in-process plane) -> same offline resolution.
938        let key = ks.get_key("", Some(&ca_kid)).await?;
939        assert_eq!(key, ca_vk);
940
941        Ok(())
942    }
943
944    /// The offline CA fallback must NOT fire for a non-matching kid (forces a
945    /// JWKS fetch, which fails here) nor for a non-local issuer — it is scoped
946    /// strictly to local-issuer tokens signed by the exact CA key.
947    #[tokio::test]
948    async fn jwks_source_local_ca_key_scoped_to_matching_kid_and_local_issuer() {
949        let fetcher: JwksFetcher = std::sync::Arc::new(|_url: String| {
950            Box::pin(async move { anyhow::bail!("no network") })
951        });
952        let ca_vk = SigningKey::from_bytes(&[7u8; 32]).verifying_key();
953        let ks = JwksKeySource::new(
954            JwksMode::Isolated {
955                jwks_url: "http://127.0.0.1:1/oauth/jwks".to_owned(),
956            },
957            "http://localhost:9080".to_owned(),
958            fetcher,
959        )
960        .with_local_ca_key(ca_vk);
961
962        // Local issuer but a different kid -> CA fallback does NOT fire; the
963        // JWKS fetch is attempted and fails -> error (not the CA key).
964        assert!(ks
965            .get_key("http://localhost:9080", Some("some-other-kid"))
966            .await
967            .is_err());
968
969        // Non-local issuer is untrusted in isolated mode regardless of kid.
970        assert!(ks
971            .get_key("https://evil.example.com", Some("some-other-kid"))
972            .await
973            .is_err());
974    }
975
976    #[tokio::test]
977    async fn cluster_key_source_rejects_untrusted() {
978        let ks = ClusterKeySource::new(test_ca_key(), "http://localhost:9080".to_owned());
979
980        let result = ks.get_key("http://evil.example.com", None).await;
981        assert!(result.is_err());
982        let err_msg = result.err().map(|e| e.to_string()).unwrap_or_default();
983        assert!(err_msg.contains("Untrusted issuer"));
984    }
985
986    #[test]
987    fn cluster_key_source_local_issuers() {
988        let ks = ClusterKeySource::new(test_ca_key(), "http://localhost:9080".to_owned());
989        assert_eq!(ks.local_issuers(), &["http://localhost:9080"]);
990
991        let ks_empty = ClusterKeySource::new(test_ca_key(), String::new());
992        assert!(ks_empty.local_issuers().is_empty());
993    }
994
995    #[test]
996    fn trait_object_compiles() {
997        let ks = ClusterKeySource::new(test_ca_key(), "http://localhost:9080".to_owned());
998        let _: std::sync::Arc<dyn JwtKeySource> = std::sync::Arc::new(ks);
999    }
1000
1001    fn mock_jwks_json(keys: &[&SigningKey]) -> serde_json::Value {
1002        let jwk_entries: Vec<serde_json::Value> = keys
1003            .iter()
1004            .map(|sk| {
1005                let vk = sk.verifying_key();
1006                let x = base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(vk.as_bytes());
1007                let kid = crate::auth::jwt::kid_for_key(sk);
1008                serde_json::json!({
1009                    "kty": "OKP",
1010                    "crv": "Ed25519",
1011                    "use": "sig",
1012                    "alg": "EdDSA",
1013                    "kid": kid,
1014                    "x": x,
1015                })
1016            })
1017            .collect();
1018        serde_json::json!({ "keys": jwk_entries })
1019    }
1020
1021    fn mock_fetcher(jwks: serde_json::Value) -> JwksFetcher {
1022        Arc::new(move |_url| {
1023            let jwks = jwks.clone();
1024            Box::pin(async move { Ok(jwks) })
1025        })
1026    }
1027
1028    #[tokio::test]
1029    async fn jwks_key_source_resolves_by_kid() -> anyhow::Result<()> {
1030        let sk_a = SigningKey::from_bytes(&[0xAA; 32]);
1031        let sk_b = SigningKey::from_bytes(&[0xBB; 32]);
1032        let kid_a = crate::auth::jwt::kid_for_key(&sk_a);
1033        let kid_b = crate::auth::jwt::kid_for_key(&sk_b);
1034
1035        let jwks = mock_jwks_json(&[&sk_a, &sk_b]);
1036        let ks = JwksKeySource::new(
1037            JwksMode::Isolated {
1038                jwks_url: "http://localhost/oauth/jwks".to_owned(),
1039            },
1040            "http://localhost".to_owned(),
1041            mock_fetcher(jwks),
1042        );
1043
1044        let key_a = ks.get_key("http://localhost", Some(&kid_a)).await?;
1045        assert_eq!(key_a, sk_a.verifying_key());
1046
1047        let key_b = ks.get_key("http://localhost", Some(&kid_b)).await?;
1048        assert_eq!(key_b, sk_b.verifying_key());
1049        Ok(())
1050    }
1051
1052    #[tokio::test]
1053    async fn jwks_key_source_unknown_kid_fails() {
1054        let sk = SigningKey::from_bytes(&[0xCC; 32]);
1055        let jwks = mock_jwks_json(&[&sk]);
1056        let ks = JwksKeySource::new(
1057            JwksMode::Isolated {
1058                jwks_url: "http://localhost/oauth/jwks".to_owned(),
1059            },
1060            "http://localhost".to_owned(),
1061            mock_fetcher(jwks),
1062        );
1063
1064        let result = ks
1065            .get_key("http://localhost", Some("nonexistent-kid"))
1066            .await;
1067        assert!(result.is_err());
1068    }
1069
1070    /// #1184: with exactly one published key, `get_key(None)` is unambiguous
1071    /// and resolves to that key. (Two or more published keys is the overlap
1072    /// case, covered by `jwks_key_source_no_kid_multi_key_get_keys_tries_all`.)
1073    #[tokio::test]
1074    async fn jwks_key_source_no_kid_single_key_resolves() -> anyhow::Result<()> {
1075        let sk = SigningKey::from_bytes(&[0xDD; 32]);
1076        let jwks = mock_jwks_json(&[&sk]);
1077        let ks = JwksKeySource::new(
1078            JwksMode::Isolated {
1079                jwks_url: "http://localhost/oauth/jwks".to_owned(),
1080            },
1081            "http://localhost".to_owned(),
1082            mock_fetcher(jwks),
1083        );
1084
1085        let key = ks.get_key("http://localhost", None).await?;
1086        assert_eq!(key, sk.verifying_key());
1087        Ok(())
1088    }
1089
1090    /// I2: even if another published key actually signed the token, a declared
1091    /// kid selects exactly its own key. Resolution plus verification rejects
1092    /// kid-new/signed-by-kid-old substitution.
1093    #[tokio::test]
1094    async fn jwks_named_kid_cannot_substitute_another_published_key() -> anyhow::Result<()> {
1095        use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine as _};
1096        use ed25519_dalek::Signer as _;
1097
1098        let old = SigningKey::from_bytes(&[0x31; 32]);
1099        let new = SigningKey::from_bytes(&[0x32; 32]);
1100        let new_kid = crate::auth::jwt::kid_for_key(&new);
1101        let jwks = mock_jwks_json(&[&old, &new]);
1102        let ks = JwksKeySource::new(
1103            JwksMode::Isolated {
1104                jwks_url: "http://localhost/oauth/jwks".to_owned(),
1105            },
1106            "http://localhost".to_owned(),
1107            mock_fetcher(jwks),
1108        );
1109
1110        let now = chrono::Utc::now().timestamp();
1111        let claims = crate::auth::Claims::new("user-1".to_owned(), now, now + 300);
1112        let header = serde_json::json!({"alg": "EdDSA", "typ": "at+jwt", "kid": new_kid});
1113        let signing_input = format!(
1114            "{}.{}",
1115            URL_SAFE_NO_PAD.encode(serde_json::to_vec(&header)?),
1116            URL_SAFE_NO_PAD.encode(serde_json::to_vec(&claims)?),
1117        );
1118        let token = format!(
1119            "{}.{}",
1120            signing_input,
1121            URL_SAFE_NO_PAD.encode(old.sign(signing_input.as_bytes()).to_bytes())
1122        );
1123
1124        let selected = ks
1125            .get_key("http://localhost", header["kid"].as_str())
1126            .await?;
1127        assert_eq!(selected, new.verifying_key());
1128        assert!(crate::auth::jwt::decode_with_key(&token, &selected, None).is_err());
1129        Ok(())
1130    }
1131
1132    /// #1184: `get_key(None)` MUST refuse to collapse a multi-key published
1133    /// set to a positional singleton — that forecloses overlap rotation and
1134    /// PQ-hybrid rollout. The previous implementation returned
1135    /// `HashMap::values().next()` (nondeterministic); reverting this hunk to
1136    /// "return the first candidate" makes the assertion below fail.
1137    #[tokio::test]
1138    async fn jwks_key_source_no_kid_multi_key_get_key_refuses_arbitrary() {
1139        let sk_a = SigningKey::from_bytes(&[0x11; 32]);
1140        let sk_b = SigningKey::from_bytes(&[0x22; 32]);
1141        let jwks = mock_jwks_json(&[&sk_a, &sk_b]);
1142        let ks = JwksKeySource::new(
1143            JwksMode::Isolated {
1144                jwks_url: "http://localhost/oauth/jwks".to_owned(),
1145            },
1146            "http://localhost".to_owned(),
1147            mock_fetcher(jwks),
1148        );
1149
1150        let result = ks.get_key("http://localhost", None).await;
1151        assert!(
1152            result.is_err(),
1153            "multi-key no-kid get_key must refuse arbitrary selection"
1154        );
1155        let msg = result.err().map(|e| e.to_string()).unwrap_or_default();
1156        assert!(
1157            msg.contains("multiple Ed25519 keys") && msg.contains("no kid"),
1158            "expected a refusal to pick arbitrarily, got: {msg}"
1159        );
1160    }
1161
1162    /// #1184 overlap: two Ed25519 keys published simultaneously. `get_keys`
1163    /// MUST return BOTH so a kid-less verifier can try each — overlap
1164    /// rotation and PQ-hybrid rollout depend on this. A token signed by the
1165    /// non-first key still verifies because both candidates are tried.
1166    #[tokio::test]
1167    async fn jwks_key_source_no_kid_multi_key_get_keys_tries_all() -> anyhow::Result<()> {
1168        let sk_a = SigningKey::from_bytes(&[0x11; 32]); // "first" in JWKS order
1169        let sk_b = SigningKey::from_bytes(&[0x22; 32]); // "second"
1170        let vk_a = sk_a.verifying_key();
1171        let vk_b = sk_b.verifying_key();
1172
1173        let jwks = mock_jwks_json(&[&sk_a, &sk_b]);
1174        let ks = JwksKeySource::new(
1175            JwksMode::Isolated {
1176                jwks_url: "http://localhost/oauth/jwks".to_owned(),
1177            },
1178            "http://localhost".to_owned(),
1179            mock_fetcher(jwks),
1180        );
1181
1182        let candidates = ks.get_keys("http://localhost", None).await?;
1183        assert_eq!(candidates.len(), 2, "both published keys must be returned");
1184        assert!(candidates.contains(&vk_a));
1185        assert!(candidates.contains(&vk_b));
1186        Ok(())
1187    }
1188
1189    /// #1184 overlap: a token signed by the non-first published key verifies
1190    /// when the caller uses `get_keys` + `decode_with_any_key`. Reverting
1191    /// `JwksKeySource` to return a single arbitrary candidate makes this fail
1192    /// (the wrong candidate is returned roughly half the time).
1193    #[tokio::test]
1194    async fn jwks_key_source_overlap_non_first_signer_verifies() -> anyhow::Result<()> {
1195        use crate::auth::jwt::decode_with_any_key_lenient;
1196        use ed25519_dalek::Signer as _;
1197
1198        let sk_a = SigningKey::from_bytes(&[0x11; 32]);
1199        let sk_b = SigningKey::from_bytes(&[0x22; 32]);
1200
1201        let jwks = mock_jwks_json(&[&sk_a, &sk_b]);
1202        let ks = JwksKeySource::new(
1203            JwksMode::Isolated {
1204                jwks_url: "http://localhost/oauth/jwks".to_owned(),
1205            },
1206            "http://localhost".to_owned(),
1207            mock_fetcher(jwks),
1208        );
1209
1210        // Sign with the SECOND key — no kid in the header, so the verifier
1211        // must try both candidates.
1212        let now = chrono::Utc::now().timestamp();
1213        let claims = crate::auth::Claims::new("user-1".to_owned(), now, now + 300);
1214        let header = URL_SAFE_NO_PAD.encode(r#"{"alg":"EdDSA","typ":"at+jwt"}"#);
1215        let payload = URL_SAFE_NO_PAD.encode(serde_json::to_vec(&claims)?);
1216        let signing_input = format!("{header}.{payload}");
1217        let token = format!(
1218            "{signing_input}.{}",
1219            URL_SAFE_NO_PAD.encode(sk_b.sign(signing_input.as_bytes()).to_bytes())
1220        );
1221        let candidates = ks.get_keys("http://localhost", None).await?;
1222        let verified = decode_with_any_key_lenient(&token, &candidates, None)?;
1223        assert_eq!(verified.sub, "user-1");
1224        Ok(())
1225    }
1226
1227    #[tokio::test]
1228    async fn jwks_key_source_negative_cache() {
1229        let sk = SigningKey::from_bytes(&[0xEE; 32]);
1230        let jwks = mock_jwks_json(&[&sk]);
1231        let fetch_count = Arc::new(std::sync::atomic::AtomicU32::new(0));
1232        let count = fetch_count.clone();
1233        let fetcher: JwksFetcher = Arc::new(move |_url| {
1234            let jwks = jwks.clone();
1235            let count = count.clone();
1236            Box::pin(async move {
1237                count.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1238                Ok(jwks)
1239            })
1240        });
1241
1242        let ks = JwksKeySource::new(
1243            JwksMode::Isolated {
1244                jwks_url: "http://localhost/oauth/jwks".to_owned(),
1245            },
1246            "http://localhost".to_owned(),
1247            fetcher,
1248        );
1249
1250        // First miss triggers fetch
1251        let _ = ks.get_key("http://localhost", Some("bad-kid-1")).await;
1252        assert_eq!(fetch_count.load(std::sync::atomic::Ordering::Relaxed), 1);
1253
1254        // Same kid within negative TTL does NOT refetch
1255        let _ = ks.get_key("http://localhost", Some("bad-kid-1")).await;
1256        assert_eq!(fetch_count.load(std::sync::atomic::Ordering::Relaxed), 1);
1257
1258        // Different kid triggers a new fetch
1259        let _ = ks.get_key("http://localhost", Some("bad-kid-2")).await;
1260        assert_eq!(fetch_count.load(std::sync::atomic::Ordering::Relaxed), 2);
1261    }
1262
1263    #[tokio::test]
1264    async fn jwks_key_source_rejects_untrusted_issuer() {
1265        let sk = SigningKey::from_bytes(&[0xFF; 32]);
1266        let jwks = mock_jwks_json(&[&sk]);
1267        let ks = JwksKeySource::new(
1268            JwksMode::Isolated {
1269                jwks_url: "http://localhost/oauth/jwks".to_owned(),
1270            },
1271            "http://localhost".to_owned(),
1272            mock_fetcher(jwks),
1273        );
1274
1275        let result = ks.get_key("http://evil.example.com", None).await;
1276        assert!(result.is_err());
1277    }
1278
1279    /// dpop_stripping_jwks_lists_composite_alg:
1280    /// When the JWKS lists a kid with a composite alg (e.g.
1281    /// `ML-DSA-65-Ed25519`), `kid_algs` must surface that alg so the
1282    /// verifier's stripping-defense policy can require all components.
1283    #[tokio::test]
1284    async fn dpop_stripping_jwks_kid_algs_surface_composite() -> anyhow::Result<()> {
1285        let kid = "composite-test-kid";
1286        let jwks = serde_json::json!({
1287            "keys": [
1288                {
1289                    "kty": "AKP",
1290                    "alg": "ML-DSA-65-Ed25519",
1291                    "use": "sig",
1292                    "kid": kid,
1293                    "pub": base64::engine::general_purpose::URL_SAFE_NO_PAD.encode([0u8; 16]),
1294                }
1295            ]
1296        });
1297        let ks = JwksKeySource::new(
1298            JwksMode::Isolated {
1299                jwks_url: "http://localhost/oauth/jwks".to_owned(),
1300            },
1301            "http://localhost".to_owned(),
1302            mock_fetcher(jwks),
1303        );
1304        // Trigger cache fill (looking up an unknown Ed25519 kid still pulls JWKS).
1305        let _ = ks.get_key("http://localhost", Some("unknown")).await;
1306        let algs = ks.kid_algs("http://localhost", kid);
1307        assert_eq!(algs, vec!["ML-DSA-65-Ed25519".to_owned()]);
1308        Ok(())
1309    }
1310
1311    /// dpop_stripping_jwks_multi_alg_per_kid:
1312    /// When the JWKS publishes two entries sharing a kid with different algs
1313    /// (e.g. an Ed25519 entry and an ML-DSA-65 entry under the same kid for
1314    /// composite key publication), `kid_algs` must return both, so the
1315    /// verifier's "all-listed-required" policy can fire.
1316    #[tokio::test]
1317    async fn dpop_stripping_jwks_multi_alg_per_kid() -> anyhow::Result<()> {
1318        let sk = SigningKey::from_bytes(&[0x77; 32]);
1319        let kid = crate::auth::jwt::kid_for_key(&sk);
1320        let x =
1321            base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(sk.verifying_key().as_bytes());
1322        let jwks = serde_json::json!({
1323            "keys": [
1324                {"kty": "OKP", "crv": "Ed25519", "use": "sig", "alg": "EdDSA", "kid": kid.clone(), "x": x},
1325                {"kty": "AKP", "alg": "ML-DSA-65", "use": "sig", "kid": kid.clone(),
1326                 "pub": base64::engine::general_purpose::URL_SAFE_NO_PAD.encode([0u8; 16])},
1327            ]
1328        });
1329        let ks = JwksKeySource::new(
1330            JwksMode::Isolated {
1331                jwks_url: "http://localhost/oauth/jwks".to_owned(),
1332            },
1333            "http://localhost".to_owned(),
1334            mock_fetcher(jwks),
1335        );
1336        let _ = ks.get_key("http://localhost", Some(&kid)).await?;
1337        let mut algs = ks.kid_algs("http://localhost", &kid);
1338        algs.sort();
1339        assert_eq!(algs, vec!["EdDSA".to_owned(), "ML-DSA-65".to_owned()]);
1340        Ok(())
1341    }
1342
1343    /// dpop_stripping_default_impl_empty:
1344    /// `ClusterKeySource` doesn't track JWKS metadata, so `kid_algs` returns
1345    /// empty (legacy behavior, no policy constraint).
1346    #[test]
1347    fn dpop_stripping_default_impl_empty() {
1348        let ks = ClusterKeySource::new(test_ca_key(), "http://localhost:9080".to_owned());
1349        assert!(ks.kid_algs("http://localhost:9080", "anything").is_empty());
1350    }
1351
1352    #[test]
1353    fn jwks_key_source_trait_object_compiles() {
1354        let sk = SigningKey::from_bytes(&[0x11; 32]);
1355        let jwks = mock_jwks_json(&[&sk]);
1356        let ks = JwksKeySource::new(
1357            JwksMode::Isolated {
1358                jwks_url: "http://localhost/oauth/jwks".to_owned(),
1359            },
1360            "http://localhost".to_owned(),
1361            mock_fetcher(jwks),
1362        );
1363        let _: Arc<dyn JwtKeySource> = Arc::new(ks);
1364    }
1365}