Skip to main content

hyprstream_core/services/oauth/
jwt_bearer.rs

1//! RFC 7523 JWT Bearer assertion grant handler.
2//!
3//! Grant type: `urn:ietf:params:oauth:grant-type:jwt-bearer`
4//!
5//! Validates a signed JWT assertion (WIT or federated OIDC token) and exchanges
6//! it for an OAuth `at+jwt` access token via PolicyService. No refresh token is
7//! issued — service-to-service flows are expected to re-assert per RFC 7523 § 4.
8
9use std::sync::Arc;
10
11use axum::{
12    http::{header, StatusCode},
13    response::{IntoResponse, Response},
14    Json,
15};
16use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine};
17use ed25519_dalek::VerifyingKey;
18
19use super::state::OAuthState;
20use hyprstream_rpc_std::policy_client::{IssueToken, IssueTokenProfile};
21
22/// Exchange a JWT bearer assertion for an access token (RFC 7523).
23pub async fn exchange_jwt_bearer(
24    state: &Arc<OAuthState>,
25    client_id: &str,
26    assertion: &str,
27) -> Response {
28    // Peek at claims without verifying — used only for issuer/subject routing.
29    let unverified = match hyprstream_rpc::auth::decode_unverified(assertion) {
30        Ok(c) => c,
31        Err(e) => {
32            return jwt_bearer_error(
33                StatusCode::BAD_REQUEST,
34                "invalid_grant",
35                &format!("Cannot parse assertion: {e}"),
36            );
37        }
38    };
39
40    let sub = unverified.sub.clone();
41    let iss = {
42        let iss = unverified.iss.clone();
43        if iss.is_empty() {
44            return jwt_bearer_error(
45                StatusCode::BAD_REQUEST,
46                "invalid_grant",
47                "Assertion missing 'iss' claim",
48            );
49        }
50        iss
51    };
52
53    // nbf (not-before) check: reject assertions that aren't valid yet (RFC 7523 §3).
54    {
55        let now = chrono::Utc::now().timestamp();
56        if let Some(nbf) = decode_jwt_nbf(assertion) {
57            if nbf > now + 5 {
58                return jwt_bearer_error(
59                    StatusCode::BAD_REQUEST,
60                    "invalid_grant",
61                    "Assertion not yet valid (nbf)",
62                );
63            }
64        }
65    }
66
67    // A service may publish drain and lead keys simultaneously. Verify against
68    // every current candidate and retain the exact key that succeeded.
69    let (claims, verified_service_key) = if sub.starts_with("service:") {
70        let service_name = sub.trim_start_matches("service:");
71        let token_endpoint = format!("{}/oauth/token", state.issuer_url.trim_end_matches('/'));
72        match decode_with_any_local_service_key(assertion, service_name, &token_endpoint) {
73            Some((claims, vk)) => (claims, Some(vk)),
74            None => {
75                return jwt_bearer_error(
76                    StatusCode::UNAUTHORIZED,
77                    "invalid_grant",
78                    &format!("Unknown service: {service_name}"),
79                );
80            }
81        }
82    } else {
83        // Federated subject — issuer must be explicitly trusted (RFC 7523 §3 allow-listing).
84        let issuer_config = match state.trusted_issuers.get(&iss) {
85            Some(cfg) => cfg.clone(),
86            None => {
87                return jwt_bearer_error(
88                    StatusCode::UNAUTHORIZED,
89                    "invalid_grant",
90                    &format!("Issuer not in trusted_issuers allow-list: {iss}"),
91                );
92            }
93        };
94        // Fetch JWKS from the issuer's discovery document.
95        let vk = match resolve_federated_key(state, &iss, assertion, issuer_config.allow_http).await
96        {
97            Ok(vk) => vk,
98            Err(e) => {
99                return jwt_bearer_error(StatusCode::UNAUTHORIZED, "invalid_grant", &e);
100            }
101        };
102        let token_endpoint = format!("{}/oauth/token", state.issuer_url.trim_end_matches('/'));
103        let claims =
104            match hyprstream_rpc::auth::decode_with_key(assertion, &vk, Some(&token_endpoint)) {
105                Ok(claims) => claims,
106                Err(e) => {
107                    return jwt_bearer_error(
108                        StatusCode::UNAUTHORIZED,
109                        "invalid_grant",
110                        &format!("Assertion verification failed: {e}"),
111                    )
112                }
113            };
114        (claims, None)
115    };
116
117    let sub = claims.sub.clone();
118    let tenant = authority_verified_assertion_tenant(&claims, verified_service_key.is_some());
119
120    // Delegate token issuance to PolicyService (authorization enforced there via Casbin).
121    let result = state
122        .policy_client
123        .issue_token(&IssueToken {
124            requested_scopes: None, // Let PolicyService apply service defaults
125            ttl: Some(state.token_ttl),
126            audience: claims.aud.clone(),
127            subject: Some(sub.clone()),
128            // OAuth signs the RPC envelope; PolicyService needs the service
129            // assertion key instead for its issued-token confirmation binding.
130            user_pub_key: verified_service_key.map(|key| URL_SAFE_NO_PAD.encode(key.to_bytes())),
131            dpop_jkt: None,
132            issuer: None,
133            tenant,
134            require_clearance: false,
135            session_id: None,
136            issuance_profile: if sub.starts_with("service:") {
137                IssueTokenProfile::Service
138            } else {
139                IssueTokenProfile::Rfc7523
140            },
141            // RFC 9068 §2.2.1: the RFC 7523 client on the user `at+jwt`; the
142            // service (`wit+jwt`) form carries none.
143            client_id: (!sub.starts_with("service:")).then(|| client_id.to_owned()),
144        })
145        .await;
146
147    match result {
148        Ok(token_info) => {
149            tracing::info!(client_id = %client_id, sub = %sub, "JWT bearer token issued");
150            let now = chrono::Utc::now().timestamp();
151            let expires_in = (token_info.expires_at - now).max(0);
152            (
153                StatusCode::OK,
154                [
155                    (header::CACHE_CONTROL, "no-store"),
156                    (header::PRAGMA, "no-cache"),
157                ],
158                Json(serde_json::json!({
159                    "access_token": token_info.token,
160                    "token_type": "Bearer",
161                    "expires_in": expires_in,
162                })),
163            )
164                .into_response()
165        }
166        Err(e) => {
167            tracing::error!(sub = %sub, error = %e, "JWT bearer token issuance failed");
168            jwt_bearer_error(
169                StatusCode::INTERNAL_SERVER_ERROR,
170                "server_error",
171                "Failed to issue token",
172            )
173        }
174    }
175}
176
177/// Preserve tenant claims only for assertions signed by a locally published
178/// service key. A trusted federated issuer proves identity, not membership in
179/// a local tenant; carrying its claim into a locally issued token would
180/// launder that external assertion into `verified_tenant`.
181fn authority_verified_assertion_tenant(
182    claims: &hyprstream_rpc::auth::Claims,
183    locally_verified_service: bool,
184) -> Option<String> {
185    if locally_verified_service {
186        claims.tenant.clone()
187    } else {
188        None
189    }
190}
191
192/// Verify a local service assertion against each currently published key.
193/// The returned key is the successful verifier, not a sorted-set selection.
194pub(super) fn decode_with_any_local_service_key(
195    assertion: &str,
196    service_name: &str,
197    expected_audience: &str,
198) -> Option<(hyprstream_rpc::auth::Claims, VerifyingKey)> {
199    decode_with_any_service_key_at(
200        hyprstream_service::global_trust_store(),
201        assertion,
202        service_name,
203        expected_audience,
204        chrono::Utc::now().timestamp(),
205    )
206}
207
208fn decode_with_any_service_key_at(
209    trust: &hyprstream_service::TrustStore,
210    assertion: &str,
211    service_name: &str,
212    expected_audience: &str,
213    now: i64,
214) -> Option<(hyprstream_rpc::auth::Claims, VerifyingKey)> {
215    trust
216        .published_keys_for_scope_at(service_name, now)
217        .into_iter()
218        .find_map(|candidate| {
219            hyprstream_rpc::auth::decode_with_key(
220                assertion,
221                &candidate.verifying_key,
222                Some(expected_audience),
223            )
224            .ok()
225            .map(|claims| (claims, candidate.verifying_key))
226        })
227}
228
229/// Fetch a verifying key for a federated issuer by resolving JWKS.
230/// Matches the `kid` JWT header against keys in the JWKS endpoint.
231/// Falls back to the first Ed25519 (OKP/Ed25519) key when no `kid` matches.
232/// Shared by jwt_bearer (RFC 7523) and token_exchange (RFC 8693).
233pub(super) async fn resolve_federated_key(
234    state: &Arc<OAuthState>,
235    issuer: &str,
236    assertion: &str,
237    allow_http: bool,
238) -> Result<VerifyingKey, String> {
239    let metadata = state
240        .oidc_discovery
241        .get_metadata(issuer, allow_http)
242        .await
243        .map_err(|e| format!("OIDC discovery failed for {issuer}: {e}"))?;
244
245    let jwks_resp = state
246        .http_client
247        .get(&metadata.jwks_uri)
248        .send()
249        .await
250        .map_err(|e| format!("JWKS fetch failed: {e}"))?;
251
252    let jwks: serde_json::Value = jwks_resp
253        .json()
254        .await
255        .map_err(|e| format!("JWKS parse failed: {e}"))?;
256
257    // Extract `kid` from JWT header for targeted lookup.
258    let header_kid: Option<String> = (|| -> Option<String> {
259        let parts: Vec<&str> = assertion.split('.').collect();
260        let hdr = URL_SAFE_NO_PAD.decode(parts.first()?).ok()?;
261        let v: serde_json::Value = serde_json::from_slice(&hdr).ok()?;
262        v["kid"].as_str().map(str::to_owned)
263    })();
264
265    let keys = jwks["keys"].as_array().ok_or("JWKS missing 'keys' array")?;
266
267    for key in keys {
268        // Filter by kid when present.
269        if let Some(ref kid) = header_kid {
270            if key["kid"].as_str() != Some(kid.as_str()) {
271                continue;
272            }
273        }
274        // Only accept OKP/Ed25519 keys.
275        if key["kty"].as_str() != Some("OKP") || key["crv"].as_str() != Some("Ed25519") {
276            continue;
277        }
278        if let Some(x_b64) = key["x"].as_str() {
279            let bytes: [u8; 32] = URL_SAFE_NO_PAD
280                .decode(x_b64)
281                .ok()
282                .and_then(|b| b.try_into().ok())
283                .ok_or("Invalid Ed25519 key in JWKS")?;
284            return VerifyingKey::from_bytes(&bytes).map_err(|e| format!("Invalid key bytes: {e}"));
285        }
286    }
287
288    Err(format!(
289        "No matching Ed25519 key in JWKS for issuer {issuer}"
290    ))
291}
292
293/// Decode `nbf` from a JWT payload without verifying the signature.
294fn decode_jwt_nbf(jwt: &str) -> Option<i64> {
295    let payload_b64 = jwt.split('.').nth(1)?;
296    let payload = URL_SAFE_NO_PAD.decode(payload_b64).ok()?;
297    let value: serde_json::Value = serde_json::from_slice(&payload).ok()?;
298    value.get("nbf")?.as_i64()
299}
300
301fn jwt_bearer_error(status: StatusCode, error: &str, description: &str) -> Response {
302    (
303        status,
304        [
305            (header::CACHE_CONTROL, "no-store"),
306            (header::PRAGMA, "no-cache"),
307        ],
308        Json(serde_json::json!({
309            "error": error,
310            "error_description": description,
311        })),
312    )
313        .into_response()
314}
315
316#[cfg(test)]
317mod tests {
318    use super::*;
319    use ed25519_dalek::SigningKey;
320
321    fn attestation(expires_at: i64) -> hyprstream_service::Attestation {
322        hyprstream_service::Attestation {
323            scopes: std::iter::once("model".to_owned()).collect(),
324            subject: None,
325            jwt: None,
326            expires_at,
327            attested_by: None,
328        }
329    }
330
331    #[test]
332    fn overlap_accepts_both_keys_then_rejects_retired_key_at_deadline() {
333        let trust = hyprstream_service::TrustStore::new();
334        let retired = SigningKey::generate(&mut rand::rngs::OsRng);
335        let lead = SigningKey::generate(&mut rand::rngs::OsRng);
336        let now = chrono::Utc::now().timestamp();
337        let retirement = now + 60;
338        trust.insert(retired.verifying_key(), attestation(retirement));
339        trust.insert(lead.verifying_key(), attestation(now + 600));
340        for signer in [&retired, &lead] {
341            let assertion = hyprstream_rpc::auth::jwt::encode(
342                &hyprstream_rpc::auth::Claims::new("service:model".to_owned(), now, now + 300)
343                    .with_issuer("https://issuer.example".to_owned())
344                    .with_audience(Some("https://issuer.example/oauth/token".to_owned())),
345                signer,
346            );
347            let Some((_, verified)) = decode_with_any_service_key_at(
348                &trust,
349                &assertion,
350                "model",
351                "https://issuer.example/oauth/token",
352                now,
353            ) else {
354                panic!("each overlap key must verify its own assertion");
355            };
356            assert_eq!(verified, signer.verifying_key());
357        }
358        let retired_assertion = hyprstream_rpc::auth::jwt::encode(
359            &hyprstream_rpc::auth::Claims::new("service:model".to_owned(), now, now + 300)
360                .with_issuer("https://issuer.example".to_owned())
361                .with_audience(Some("https://issuer.example/oauth/token".to_owned())),
362            &retired,
363        );
364        assert!(decode_with_any_service_key_at(
365            &trust,
366            &retired_assertion,
367            "model",
368            "https://issuer.example/oauth/token",
369            retirement
370        )
371        .is_none());
372    }
373
374    #[test]
375    fn federated_bearer_cannot_launder_tenant_into_local_token() {
376        let now = chrono::Utc::now().timestamp();
377        let claims = hyprstream_rpc::auth::Claims::new("external-user".to_owned(), now, now + 300)
378            .with_issuer("https://federated.example".to_owned())
379            .with_tenant("victim-domain".to_owned());
380
381        assert_eq!(
382            authority_verified_assertion_tenant(&claims, false),
383            None,
384            "a federated assertion's tenant must not reach PolicyService",
385        );
386        assert_eq!(
387            authority_verified_assertion_tenant(&claims, true).as_deref(),
388            Some("victim-domain"),
389            "a locally published service key remains an authority source",
390        );
391    }
392}