hyprstream_rpc/auth/federation.rs
1//! Abstraction layer for multi-issuer JWT key resolution on the ZMQ transport.
2//!
3//! Defines `FederationKeySource`, an async trait implemented by
4//! `hyprstream::auth::FederationKeyResolver`. The indirection avoids a circular
5//! crate dependency: `hyprstream-rpc` cannot import from `hyprstream` directly.
6
7use anyhow::Result;
8use ed25519_dalek::VerifyingKey;
9
10/// One named Ed25519 key published in a federation JWKS.
11///
12/// `kid` stays attached to its key until verification. Collapsing this to a
13/// bare `VerifyingKey` would let a token that names one key verify with a
14/// different, merely co-published key.
15#[derive(Clone, Debug)]
16pub struct FederationKey {
17 pub kid: Option<String>,
18 pub verifying_key: VerifyingKey,
19}
20
21/// Resolves external JWT issuer URLs to Ed25519 verifying keys.
22///
23/// Implemented by `hyprstream::auth::FederationKeyResolver`. Services that
24/// serve external traffic return `Some(Arc<dyn FederationKeySource>)` from
25/// `RequestService::federation_key_source()` so the default `verify_claims()`
26/// can perform real key resolution instead of rejecting federated JWTs.
27///
28/// # Key-set semantics (rotation-aware, #1185)
29///
30/// A published JWKS is a **named set**, never an ordered singleton. `get_keys`
31/// returns every usable named Ed25519 entry from the issuer's current JWKS so
32/// a token without a `kid` can try each candidate. When the JWT carries a
33/// `kid`, it returns only entries with that exact `kid`; a named token must
34/// never verify with another co-published key.
35///
36/// The resolver MUST NOT collapse the set to a positional singleton: returning
37/// the "first" Ed25519 key forecloses rotation (#1183). An empty result is an
38/// `Err`.
39///
40/// # Note on `Send` bounds
41///
42/// `get_keys` uses the default (`Send`) flavour of `#[async_trait]` because
43/// `FederationKeyResolver` performs real async I/O (HTTPS JWKS fetch) whose
44/// future must be `Send`. Call sites inside `#[async_trait(?Send)]` contexts
45/// (e.g. `RequestService::verify_claims`) may `.await` this future directly:
46/// it is valid in Rust to await a `Send` future from within a `!Send`
47/// async function — the `?Send` bound constrains the outer function's
48/// future, not the futures it polls. `RequestService::verify_claims` does
49/// exactly this and compiles correctly.
50#[async_trait::async_trait]
51pub trait FederationKeySource: Send + Sync + 'static {
52 /// Return `true` if `issuer` is in the configured trusted-issuer list.
53 ///
54 /// Callers should check this before calling `get_keys` to distinguish an
55 /// untrusted issuer (policy reject → 401) from a transient fetch error
56 /// (retry eligible → 503).
57 fn is_trusted(&self, issuer: &str) -> bool;
58
59 /// Fetch (or return from cache) the Ed25519 candidate verifying keys for
60 /// `issuer`.
61 ///
62 /// Returns every usable named Ed25519 key from the issuer's JWKS. When
63 /// `kid` is `Some`, every returned entry has that exact `kid`; when it is
64 /// `None`, the caller may try each candidate against the JWT.
65 ///
66 /// On a cache miss for the requested `kid`, the resolver refetches the
67 /// JWKS once and re-checks. A `kid` that is still absent after a fresh
68 /// fetch fails closed (`Err`); the resolver MUST NOT silently substitute
69 /// another key for a named `kid`.
70 ///
71 /// # Errors
72 ///
73 /// Returns `Err` if:
74 /// - the issuer is not in the trusted list (`is_trusted` returns `false`), or
75 /// - the JWKS endpoint is unreachable or returns no usable Ed25519 key, or
76 /// - `kid` is `Some` and no candidate with that `kid` exists after refetch.
77 async fn get_keys(&self, issuer: &str, kid: Option<&str>) -> Result<Vec<FederationKey>>;
78}
79
80#[cfg(test)]
81mod tests {
82 use super::*;
83 use std::sync::Arc;
84
85 /// Minimal stub that rejects all issuers. Verifies the trait compiles as
86 /// `Arc<dyn FederationKeySource>` and that `Send + Sync + 'static` bounds hold.
87 struct AlwaysReject;
88
89 #[async_trait::async_trait]
90 impl FederationKeySource for AlwaysReject {
91 fn is_trusted(&self, _issuer: &str) -> bool {
92 false
93 }
94
95 async fn get_keys(&self, issuer: &str, _kid: Option<&str>) -> Result<Vec<FederationKey>> {
96 let _ = issuer;
97 anyhow::bail!("Issuer not trusted: {}", issuer)
98 }
99 }
100
101 #[tokio::test]
102 async fn trait_object_compiles_and_rejects() {
103 let src: Arc<dyn FederationKeySource> = Arc::new(AlwaysReject);
104 assert!(!src.is_trusted("https://evil.example.com"));
105 assert!(src
106 .get_keys("https://evil.example.com", None)
107 .await
108 .is_err());
109 }
110}