Skip to main content

hyprstream_core/services/oauth/
federation_entity.rs

1//! OpenID Federation 1.0 entity configuration endpoint.
2//!
3//! Publishes `GET /.well-known/openid-federation` — a signed JWT (entity-statement+jwt)
4//! that makes this hyprstream node discoverable in OpenID Federation-aware networks.
5//!
6//! This is a purely additive step: existing `trusted_issuers`-based federation continues
7//! to work unchanged. The entity configuration is a prerequisite for future trust-chain
8//! resolution (Step 13, deferred).
9//!
10//! # Entity configuration JWT
11//! - Header: `{"alg":"EdDSA","typ":"entity-statement+jwt"}`
12//! - `iss` / `sub`: the node's issuer URL (self-issued — both equal)
13//! - `iat` / `exp`: now / now + 24h
14//! - `jwks`: the node's Ed25519 verifying key as OKP JWK
15//! - `metadata.oauth_authorization_server`: RFC 8414 AS metadata fields
16//! - `authority_hints`: Trust Anchor URLs from config (empty if none configured)
17
18use std::sync::Arc;
19use std::time::{SystemTime, UNIX_EPOCH};
20
21use axum::{
22    extract::State,
23    http::{header, StatusCode},
24    response::{IntoResponse, Response},
25};
26use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine};
27use ed25519_dalek::Signer;
28use ed25519_dalek::{SigningKey, VerifyingKey};
29
30use super::state::OAuthState;
31
32/// GET /.well-known/openid-federation — OpenID Federation 1.0 entity configuration
33pub async fn entity_configuration(State(state): State<Arc<OAuthState>>) -> Response {
34    match build_entity_configuration_jwt(&state).await {
35        Ok(jwt) => (
36            StatusCode::OK,
37            [(header::CONTENT_TYPE, "application/entity-statement+jwt")],
38            jwt,
39        )
40            .into_response(),
41        Err(reason) => (StatusCode::SERVICE_UNAVAILABLE, reason).into_response(),
42    }
43}
44
45/// Build the signed OpenID Federation 1.0 entity-configuration JWT for
46/// this AS, suitable for serving at `/.well-known/openid-federation` OR
47/// publishing to DiscoveryService.
48///
49/// Factored out of the HTTP handler so Phase 0.5 Stage D
50/// (`publish_entity_statement_to_discovery`) can reuse it.
51pub async fn build_entity_configuration_jwt(state: &OAuthState) -> Result<String, &'static str> {
52    let Some(sk) = state.active_root_identity_signing_key().await else {
53        return Err("signing key not configured for OpenID Federation");
54    };
55    let vk = sk.verifying_key();
56
57    // Build AS metadata (mirrors authorization_server_metadata endpoint)
58    let issuer = &state.issuer_url;
59    let as_metadata = serde_json::json!({
60        "issuer": issuer,
61        "authorization_endpoint": format!("{}/oauth/authorize", issuer),
62        "token_endpoint": format!("{}/oauth/token", issuer),
63        "registration_endpoint": format!("{}/oauth/register", issuer),
64        "device_authorization_endpoint": format!("{}/oauth/device", issuer),
65        "jwks_uri": format!("{}/oauth/jwks", issuer),
66        "response_types_supported": ["code"],
67        "grant_types_supported": [
68            "authorization_code",
69            "refresh_token",
70            "urn:ietf:params:oauth:grant-type:device_code",
71        ],
72        "code_challenge_methods_supported": ["S256"],
73        "token_endpoint_auth_methods_supported": ["none"],
74        "scopes_supported": state.default_scopes,
75        "client_id_metadata_document_supported": true,
76    });
77
78    // Build the entity JWKS. The first key is always the entity signing key
79    // (verifies the entity-statement JWT itself). Additional keys from the
80    // rotation store and CA/PolicyService key are appended so federation
81    // consumers see the same key set published at /oauth/jwks.
82    let mut jwks_keys: Vec<serde_json::Value> = Vec::new();
83
84    // Entity signing key first — verifies this JWT.
85    let signing_jwk = verifying_key_as_okp_jwk(&vk);
86    let signing_x = signing_jwk
87        .get("x")
88        .and_then(|v| v.as_str())
89        .unwrap_or_default()
90        .to_owned();
91    jwks_keys.push(signing_jwk);
92
93    if let Some(ref store) = state.signing_key_store {
94        for slot in store.all_slots_snapshot().await {
95            let vk_bytes = slot.verifying_key_bytes();
96            let jwk = verifying_key_bytes_as_okp_jwk(&vk_bytes);
97            let x = jwk.get("x").and_then(|v| v.as_str()).unwrap_or_default();
98            if x != signing_x {
99                jwks_keys.push(jwk);
100            }
101        }
102    }
103
104    // Include the CA/PolicyService verifying key (de-dup by x value).
105    {
106        let ca_jwk = verifying_key_bytes_as_okp_jwk(&state.verifying_key_bytes);
107        let ca_x = ca_jwk.get("x").and_then(|v| v.as_str()).unwrap_or_default();
108        if !jwks_keys
109            .iter()
110            .any(|k| k.get("x").and_then(|v| v.as_str()) == Some(ca_x))
111        {
112            jwks_keys.push(ca_jwk);
113        }
114    }
115
116    // ES256 keys from rotation store.
117    if let Some(ref store) = state.es256_key_store {
118        for slot in store.all_slots_snapshot() {
119            jwks_keys.push(crate::auth::jwt::es256_jwk(&slot.key));
120        }
121    }
122
123    // ML-DSA-65 keys from rotation store.
124    if let Some(ref store) = state.ml_dsa_key_store {
125        for slot in store.all_slots_snapshot().await {
126            let ml_vk = ml_dsa::Keypair::verifying_key(&*slot.key);
127            jwks_keys.push(crate::auth::jwt::ml_dsa_65_jwk(&ml_vk));
128        }
129    }
130
131    Ok(build_entity_configuration_with_keys(
132        issuer,
133        &sk,
134        jwks_keys,
135        as_metadata,
136        &state.authority_hints,
137    ))
138}
139
140/// Phase 0.5 Stage D — publish this AS's signed entity statement to the
141/// federation directory (DiscoveryService).
142///
143/// Once published, federation peers in the cluster can resolve this
144/// issuer's JWKS via `DiscoveryClient.get_entity_statement(issuer)` —
145/// no HTTPS round-trip required. The entity statement carries an `exp`
146/// (24h); callers should re-publish after each signing-key rotation so
147/// the embedded JWKS stays fresh.
148///
149/// Logs success/failure at debug level. Discovery push failures are
150/// **non-fatal**: the OAuth server continues to serve the entity
151/// statement at `/.well-known/openid-federation` and consumers can fall
152/// back to HTTPS resolution.
153pub async fn publish_entity_statement_to_discovery(state: Arc<OAuthState>) {
154    let jwt = match build_entity_configuration_jwt(&state).await {
155        Ok(j) => j,
156        Err(reason) => {
157            tracing::debug!(
158                reason = %reason,
159                "Skipping DiscoveryService entity-statement publish"
160            );
161            return;
162        }
163    };
164
165    let req = hyprstream_rpc_std::discovery_client::RegisterEntityStatementRequest {
166        issuer: state.issuer_url.clone(),
167        jwt,
168    };
169    match state.discovery_client.register_entity_statement(&req).await {
170        Ok(_) => tracing::info!(
171            issuer = %state.issuer_url,
172            "Published OIDF entity statement to DiscoveryService"
173        ),
174        Err(e) => tracing::warn!(
175            issuer = %state.issuer_url,
176            error = %e,
177            "Failed to publish entity statement to DiscoveryService (non-fatal — HTTPS fallback still works)"
178        ),
179    }
180}
181
182/// Build and sign an OpenID Federation 1.0 entity configuration JWT.
183///
184/// The JWT `typ` is `entity-statement+jwt` (not `JWT`), so we cannot use the
185/// existing `jwt::encode()` helper which hardcodes `"typ":"JWT"`. We build it
186/// directly using standard base64url encoding.
187pub fn build_entity_configuration(
188    issuer_url: &str,
189    signing_key: &SigningKey,
190    verifying_key: &VerifyingKey,
191    as_metadata: serde_json::Value,
192    authority_hints: &[String],
193) -> String {
194    let now = SystemTime::now()
195        .duration_since(UNIX_EPOCH)
196        .unwrap_or_default()
197        .as_secs() as i64;
198    let exp = now + 86400; // 24 hours
199
200    let header = base64url_json(serde_json::json!({
201        "alg": "EdDSA",
202        "typ": "entity-statement+jwt",
203    }));
204
205    let payload = base64url_json(serde_json::json!({
206        "iss": issuer_url,
207        "sub": issuer_url,
208        "iat": now,
209        "exp": exp,
210        "jwks": {
211            "keys": [verifying_key_as_okp_jwk(verifying_key)],
212        },
213        "metadata": {
214            "oauth_authorization_server": as_metadata,
215            "federation_entity": {
216                "organization_name": "hyprstream",
217            },
218        },
219        "authority_hints": authority_hints,
220    }));
221
222    let signing_input = format!("{header}.{payload}");
223    let signature = signing_key.sign(signing_input.as_bytes());
224    let sig_b64 = URL_SAFE_NO_PAD.encode(signature.to_bytes());
225
226    format!("{signing_input}.{sig_b64}")
227}
228
229/// Serialize a JSON value to base64url-encoded bytes (no padding).
230fn base64url_json(value: serde_json::Value) -> String {
231    // serde_json::to_vec on a Value never fails; unwrap_or_else avoids clippy::expect_used
232    let json_bytes = serde_json::to_vec(&value)
233        .unwrap_or_else(|_| unreachable!("Value serialization cannot fail"));
234    URL_SAFE_NO_PAD.encode(&json_bytes)
235}
236
237/// Represent an Ed25519 verifying key as an OKP JWK (RFC 8037).
238fn verifying_key_as_okp_jwk(vk: &VerifyingKey) -> serde_json::Value {
239    verifying_key_bytes_as_okp_jwk(vk.as_bytes())
240}
241
242/// Represent raw Ed25519 verifying-key bytes as an OKP JWK (RFC 8037).
243fn verifying_key_bytes_as_okp_jwk(bytes: &[u8; 32]) -> serde_json::Value {
244    let x_b64 = URL_SAFE_NO_PAD.encode(bytes);
245    serde_json::json!({
246        "kty": "OKP",
247        "crv": "Ed25519",
248        "x": x_b64,
249        "use": "sig",
250    })
251}
252
253/// Build and sign an entity configuration JWT with an explicit set of JWKS keys.
254pub fn build_entity_configuration_with_keys(
255    issuer_url: &str,
256    signing_key: &SigningKey,
257    jwks_keys: Vec<serde_json::Value>,
258    as_metadata: serde_json::Value,
259    authority_hints: &[String],
260) -> String {
261    let now = SystemTime::now()
262        .duration_since(UNIX_EPOCH)
263        .unwrap_or_default()
264        .as_secs() as i64;
265    let exp = now + 86400;
266
267    let header = base64url_json(serde_json::json!({
268        "alg": "EdDSA",
269        "typ": "entity-statement+jwt",
270    }));
271
272    let payload = base64url_json(serde_json::json!({
273        "iss": issuer_url,
274        "sub": issuer_url,
275        "iat": now,
276        "exp": exp,
277        "jwks": { "keys": jwks_keys },
278        "metadata": {
279            "oauth_authorization_server": as_metadata,
280            "federation_entity": {
281                "organization_name": "hyprstream",
282            },
283        },
284        "authority_hints": authority_hints,
285    }));
286
287    let signing_input = format!("{header}.{payload}");
288    let signature = signing_key.sign(signing_input.as_bytes());
289    let sig_b64 = URL_SAFE_NO_PAD.encode(signature.to_bytes());
290
291    format!("{signing_input}.{sig_b64}")
292}
293
294#[cfg(test)]
295#[allow(clippy::unwrap_used, clippy::expect_used)]
296mod tests {
297    use super::*;
298    use ed25519_dalek::SigningKey;
299
300    fn make_key() -> SigningKey {
301        SigningKey::generate(&mut rand::rngs::OsRng)
302    }
303
304    #[test]
305    fn test_entity_configuration_structure() {
306        let sk = make_key();
307        let vk = sk.verifying_key();
308        let as_meta = serde_json::json!({"issuer": "http://localhost:6791"});
309        let jwt = build_entity_configuration("http://localhost:6791", &sk, &vk, as_meta, &[]);
310
311        let parts: Vec<&str> = jwt.split('.').collect();
312        assert_eq!(parts.len(), 3, "JWT must have 3 parts");
313
314        // Decode header
315        let header_json = URL_SAFE_NO_PAD
316            .decode(parts[0])
317            .expect("header is valid base64url");
318        let header: serde_json::Value =
319            serde_json::from_slice(&header_json).expect("header is valid JSON");
320        assert_eq!(header["alg"], "EdDSA");
321        assert_eq!(header["typ"], "entity-statement+jwt");
322
323        // Decode payload
324        let payload_json = URL_SAFE_NO_PAD
325            .decode(parts[1])
326            .expect("payload is valid base64url");
327        let payload: serde_json::Value =
328            serde_json::from_slice(&payload_json).expect("payload is valid JSON");
329        assert_eq!(payload["iss"], "http://localhost:6791");
330        assert_eq!(payload["sub"], payload["iss"]);
331        assert!(payload["jwks"]["keys"].as_array().unwrap().len() == 1);
332        assert_eq!(payload["jwks"]["keys"][0]["kty"], "OKP");
333        assert_eq!(payload["jwks"]["keys"][0]["crv"], "Ed25519");
334        assert!(payload["metadata"]["oauth_authorization_server"].is_object());
335    }
336
337    #[test]
338    fn test_entity_configuration_signature_verifies() {
339        let sk = make_key();
340        let vk = sk.verifying_key();
341        let as_meta = serde_json::json!({"issuer": "http://example.com"});
342        let jwt = build_entity_configuration("http://example.com", &sk, &vk, as_meta, &[]);
343
344        let parts: Vec<&str> = jwt.split('.').collect();
345        assert_eq!(parts.len(), 3);
346
347        let signing_input = format!("{}.{}", parts[0], parts[1]);
348        let sig_bytes = URL_SAFE_NO_PAD
349            .decode(parts[2])
350            .expect("signature is valid base64url");
351        let sig_array: [u8; 64] = sig_bytes.try_into().expect("signature must be 64 bytes");
352        let sig = ed25519_dalek::Signature::from_bytes(&sig_array);
353
354        assert!(
355            vk.verify_strict(signing_input.as_bytes(), &sig).is_ok(),
356            "entity configuration JWT signature must verify"
357        );
358    }
359
360    #[test]
361    fn test_build_with_keys_embeds_multiple_keys() {
362        let sk = make_key();
363        let key1 = make_key().verifying_key();
364        let key2 = make_key().verifying_key();
365        let keys = vec![
366            verifying_key_as_okp_jwk(&key1),
367            verifying_key_as_okp_jwk(&key2),
368        ];
369        let as_meta = serde_json::json!({"issuer": "http://localhost:6791"});
370        let jwt =
371            build_entity_configuration_with_keys("http://localhost:6791", &sk, keys, as_meta, &[]);
372
373        let parts: Vec<&str> = jwt.split('.').collect();
374        assert_eq!(parts.len(), 3);
375
376        let payload_json = URL_SAFE_NO_PAD.decode(parts[1]).expect("valid base64url");
377        let payload: serde_json::Value = serde_json::from_slice(&payload_json).expect("valid JSON");
378        let jwks_keys = payload["jwks"]["keys"].as_array().unwrap();
379        assert_eq!(jwks_keys.len(), 2, "should embed both keys");
380        assert_eq!(jwks_keys[0]["x"], URL_SAFE_NO_PAD.encode(key1.as_bytes()));
381        assert_eq!(jwks_keys[1]["x"], URL_SAFE_NO_PAD.encode(key2.as_bytes()));
382    }
383
384    #[test]
385    fn test_verifying_key_bytes_as_okp_jwk_matches() {
386        let sk = make_key();
387        let vk = sk.verifying_key();
388        let from_ref = verifying_key_as_okp_jwk(&vk);
389        let from_bytes = verifying_key_bytes_as_okp_jwk(vk.as_bytes());
390        assert_eq!(from_ref, from_bytes);
391    }
392}