1#![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#[async_trait::async_trait]
45pub trait JwtKeySource: Send + Sync + 'static {
46 async fn get_key(&self, issuer: &str, kid: Option<&str>) -> Result<VerifyingKey>;
57
58 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 fn is_trusted(&self, issuer: &str) -> bool;
80
81 fn local_issuers(&self) -> &[String];
86
87 fn ml_dsa_verifying_keys(&self) -> Vec<crate::crypto::pq::MlDsaVerifyingKey> {
92 vec![]
93 }
94
95 fn composite_key_set(&self) -> Arc<super::CompositeKeySet> {
97 super::global_composite_key_set()
98 }
99
100 fn composite_pair(&self, kid: &str) -> Option<super::CompositeKeyPair> {
108 self.composite_key_set().snapshot().pair(kid).cloned()
109 }
110
111 fn kid_algs(&self, _issuer: &str, _kid: &str) -> Vec<String> {
123 Vec::new()
124 }
125}
126
127#[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 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 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 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 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 pub fn with_composite_key_set(mut self, keys: Arc<super::CompositeKeySet>) -> Self {
210 self.composite_keys = keys;
211 self
212 }
213
214 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 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 if issuer.is_empty() {
263 return true;
264 }
265 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 self.ca_composite
292 .as_ref()
293 .filter(|pair| pair.kid() == kid)
294 .cloned()
295 }
296}
297
298pub struct FederatedKeySource {
306 local: ClusterKeySource,
307 federation: std::sync::Arc<dyn super::FederationKeySource>,
308}
309
310impl FederatedKeySource {
311 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 if self.local.is_trusted(issuer) {
330 return self.local.get_key(issuer, kid).await;
331 }
332 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
397pub 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#[derive(Clone)]
409pub enum JwksMode {
410 Isolated { jwks_url: String },
412 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#[async_trait::async_trait]
436pub trait IssuerResolver: Send + Sync + 'static {
437 async fn resolve(&self, issuer: &str) -> Result<String>;
438}
439
440struct CachedKey {
442 verifying_key: VerifyingKey,
443 #[allow(dead_code)]
444 fetched_at: std::time::Instant,
445}
446
447pub 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 kid_alg_map: parking_lot::RwLock<HashMap<String, HashMap<String, Vec<String>>>>,
464 fetch_semaphore: Semaphore,
465 #[allow(dead_code)]
467 soft_ttl: std::time::Duration,
468 negative_ttl: std::time::Duration,
470 ml_dsa_vks: Arc<std::sync::RwLock<Vec<crate::crypto::pq::MlDsaVerifyingKey>>>,
471 local_ca_key: Option<VerifyingKey>,
482 local_ca_kid: Option<String>,
483 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 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 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 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 }
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 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 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 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 async fn resolve_by_kid(&self, issuer: &str, kid_str: &str) -> Result<VerifyingKey> {
675 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 {
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 if let Err(e) = self.fetch_and_cache(issuer).await {
715 tracing::warn!("JWKS fetch failed for issuer={}: {}", issuer, e);
716 }
717
718 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 {
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 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 if let Some(kid_str) = kid {
760 return self.resolve_by_kid(issuer, kid_str).await;
761 }
762
763 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 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 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 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 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("")); 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 #[tokio::test]
913 async fn jwks_source_resolves_local_ca_key_offline() -> anyhow::Result<()> {
914 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 let key = ks.get_key("http://localhost:9080", Some(&ca_kid)).await?;
935 assert_eq!(key, ca_vk);
936
937 let key = ks.get_key("", Some(&ca_kid)).await?;
939 assert_eq!(key, ca_vk);
940
941 Ok(())
942 }
943
944 #[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 assert!(ks
965 .get_key("http://localhost:9080", Some("some-other-kid"))
966 .await
967 .is_err());
968
969 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 #[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 #[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 #[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 #[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]); let sk_b = SigningKey::from_bytes(&[0x22; 32]); 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 #[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 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 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 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 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 #[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 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 #[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 #[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}