Skip to main content

hyprstream_core/services/oauth/
jwks.rs

1//! GET /oauth/jwks — JSON Web Key Set (RFC 7517).
2//!
3//! Returns the node's signing keys: Ed25519 (OKP, RFC 8037) and optionally
4//! RSA (for RS256 interop with enterprise RPs).
5
6use super::state::OAuthState;
7use axum::{extract::State, response::IntoResponse, Json};
8use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine};
9use hyprstream_rpc::auth::{jwk_thumbprint, JwkThumbprintInput};
10use std::sync::Arc;
11
12/// Compute the RFC 7638 JWK Thumbprint for an Ed25519 key (32-byte raw pubkey).
13pub fn compute_kid(key_bytes: &[u8]) -> String {
14    let bytes: [u8; 32] = match key_bytes.try_into() {
15        Ok(b) => b,
16        Err(_) => {
17            tracing::error!(
18                "compute_kid called with {} bytes, expected 32",
19                key_bytes.len()
20            );
21            return String::new();
22        }
23    };
24    jwk_thumbprint(&JwkThumbprintInput::Ed25519 { x: &bytes })
25}
26
27/// Compute the RFC 7638 JWK Thumbprint for an RSA key (n and e as base64url strings).
28pub fn compute_rsa_kid(n: &str, e: &str) -> String {
29    jwk_thumbprint(&JwkThumbprintInput::Rsa { n, e })
30}
31
32/// GET /oauth/jwks
33pub async fn jwks(State(state): State<Arc<OAuthState>>) -> impl IntoResponse {
34    let snapshot = hyprstream_rpc::auth::global_composite_key_set().snapshot();
35    Json(serde_json::json!({
36        "keys": jwks_json(&state, &snapshot).await,
37        "composite_version": snapshot.version(),
38        "composite_component_digest": snapshot.component_digest(),
39    }))
40}
41
42/// Build the public JWKS key array shared by `/oauth/jwks` and the SPIFFE
43/// bundle endpoint.
44pub async fn jwks_json(
45    state: &OAuthState,
46    composite_snapshot: &hyprstream_rpc::auth::CompositeKeySetSnapshot,
47) -> Vec<serde_json::Value> {
48    let mut keys: Vec<serde_json::Value> = Vec::new();
49
50    // Serve all rotation slots (drain + active + lead) when the store is present.
51    // WITs and rotating-issuance tokens use these.
52    if let Some(ref store) = state.signing_key_store {
53        for slot in store.all_slots_snapshot().await {
54            let vk_bytes = slot.verifying_key_bytes();
55            let kid = compute_kid(&vk_bytes);
56            let x = URL_SAFE_NO_PAD.encode(vk_bytes);
57            keys.push(serde_json::json!({
58                "kty": "OKP",
59                "crv": "Ed25519",
60                "use": "sig",
61                "alg": "EdDSA",
62                "kid": kid,
63                "x": x,
64                "nbf": slot.nbf,
65                "exp": slot.exp,
66            }));
67        }
68    }
69
70    // Always publish the cluster CA verifying key (state.verifying_key_bytes).
71    // This is the key PolicyService uses to sign at+JWTs — for single-process
72    // mode it's the derived `hyprstream-jwt-v1` key set by
73    // `generate_independent_service_keys` (factory.rs); for IPC mode it's the
74    // loaded ca-pubkey credential. Clients fetching JWKS to verify at+JWTs
75    // need this key regardless of whether a rotation store is present.
76    // De-duplicate against rotation slots by kid.
77    {
78        let key_bytes = state.verifying_key_bytes;
79        let eddsa_kid = compute_kid(&key_bytes);
80        let already = keys
81            .iter()
82            .any(|k| k.get("kid").and_then(|v| v.as_str()) == Some(eddsa_kid.as_str()));
83        if !already {
84            let x = URL_SAFE_NO_PAD.encode(key_bytes);
85            keys.push(serde_json::json!({
86                "kty": "OKP",
87                "crv": "Ed25519",
88                "use": "sig",
89                "alg": "EdDSA",
90                "kid": eddsa_kid,
91                "x": x,
92                "nbf": state.jwt_key_nbf,
93                "exp": state.jwt_key_exp,
94            }));
95        }
96    }
97
98    // ES256 from rotation store — publish all slots (drain/active/lead)
99    if let Some(ref store) = state.es256_key_store {
100        for slot in store.all_slots_snapshot() {
101            let mut jwk = crate::auth::jwt::es256_jwk(&slot.key);
102            if let Some(obj) = jwk.as_object_mut() {
103                obj.insert("nbf".to_owned(), slot.nbf.into());
104                obj.insert("exp".to_owned(), slot.exp.into());
105            }
106            keys.push(jwk);
107        }
108    }
109
110    // ML-DSA-65 from rotation store — publish all component slots.
111    if let Some(ref store) = state.ml_dsa_key_store {
112        for slot in store.all_slots_snapshot().await {
113            let vk = ml_dsa::Keypair::verifying_key(&*slot.key);
114            let mut jwk = crate::auth::jwt::ml_dsa_65_jwk(&vk);
115            if let Some(obj) = jwk.as_object_mut() {
116                obj.insert("nbf".to_owned(), slot.nbf.into());
117                obj.insert("exp".to_owned(), slot.exp.into());
118            }
119            keys.push(jwk);
120        }
121    }
122
123    // Publish exactly the pairs accepted by the local verifier. Never rebuild
124    // these as a Cartesian product of independently published component keys.
125    keys.extend(
126        composite_snapshot
127            .pairs()
128            .iter()
129            .map(|pair| crate::auth::jwt::composite_jwk(pair.ml_dsa(), pair.ed25519())),
130    );
131
132    // Add RSA public key if available
133    if let Some(ref rsa_jwk) = state.rsa_jwk {
134        keys.push(rsa_jwk.clone());
135    }
136
137    keys
138}
139
140#[cfg(test)]
141mod tests {
142    use super::compute_kid;
143    use base64::engine::general_purpose::URL_SAFE_NO_PAD;
144    use base64::Engine;
145
146    #[test]
147    fn test_kid_is_rfc7638_thumbprint() {
148        let key_bytes = [0u8; 32];
149        let kid = compute_kid(&key_bytes);
150        // RFC 7638 thumbprint: base64url(SHA-256(canonical_jwk)) = 43 chars
151        assert_eq!(kid.len(), 43);
152        assert!(!kid.contains('='));
153    }
154
155    #[test]
156    fn test_kid_deterministic() {
157        let key_bytes = [1u8; 32];
158        assert_eq!(compute_kid(&key_bytes), compute_kid(&key_bytes));
159    }
160
161    #[test]
162    fn test_kid_matches_jwt_module() {
163        let key_bytes = [42u8; 32];
164        let kid = compute_kid(&key_bytes);
165        let jwt_kid = hyprstream_rpc::auth::jwk_thumbprint(
166            &hyprstream_rpc::auth::JwkThumbprintInput::Ed25519 { x: &key_bytes },
167        );
168        assert_eq!(kid, jwt_kid);
169    }
170
171    #[test]
172    fn test_x_is_base64url_no_pad() {
173        let key_bytes = [1u8; 32];
174        let x = URL_SAFE_NO_PAD.encode(key_bytes);
175        // 32 bytes base64url no-pad = 43 chars
176        assert_eq!(x.len(), 43);
177        assert!(!x.contains('='));
178    }
179}