Skip to main content

hyprstream_core/services/oauth/
spiffe.rs

1//! SPIFFE/JWT-SVID compatibility surface for the Kubernetes security spine.
2//!
3//! This module deliberately reuses the existing OAuth trust machinery:
4//! external cluster/SPIRE issuers must already be present in
5//! `OAuthState::trusted_issuers`, which is populated only after the normal
6//! `federation:register` admission path. Accepted workload JWTs are re-issued
7//! as local WITs; hyprstream-provided JWT-SVIDs are signed by the same active
8//! JWT signing key published by the bundle endpoint.
9
10use std::sync::Arc;
11
12use axum::{
13    extract::State,
14    http::{header, HeaderMap, StatusCode},
15    response::{IntoResponse, Response},
16    Extension, Json,
17};
18use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine as _};
19use ed25519_dalek::{Signature, Signer as _, Verifier as _};
20use serde::{Deserialize, Serialize};
21
22use super::state::OAuthState;
23use crate::server::middleware::AuthenticatedUser;
24
25const K8S_WIT_TTL: i64 = 10 * 60;
26const JWT_SVID_TTL: i64 = 10 * 60;
27
28#[derive(Debug, Deserialize)]
29pub struct WorkloadWitRequest {
30    /// Projected Kubernetes ServiceAccount token or SPIRE JWT-SVID.
31    pub subject_token: String,
32    /// Expected audience of the presented token. Kubernetes projected tokens
33    /// should request this audience explicitly; absent/wrong aud fails closed.
34    pub audience: String,
35    /// Optional base64url Ed25519 key to carry as `cnf.jwk` in the issued WIT.
36    /// If omitted and a valid DPoP proof is supplied, the DPoP public key binds
37    /// the WIT instead.
38    #[serde(default)]
39    pub pubkey: Option<String>,
40}
41
42#[derive(Debug, Serialize)]
43pub struct WorkloadWitResponse {
44    pub wit: String,
45    pub token_type: &'static str,
46    pub expires_in: i64,
47    pub subject: String,
48    pub source_issuer: String,
49    pub source_subject: String,
50}
51
52#[derive(Debug, Deserialize)]
53pub struct ServiceSvidRequest {
54    /// Service name in `spiffe://<trust-domain>/service/<name>`.
55    pub service: String,
56    /// JWT-SVID audiences. At least one is required by SPIFFE JWT-SVID.
57    pub audience: Vec<String>,
58}
59
60#[derive(Debug, Serialize)]
61pub struct ServiceSvidResponse {
62    pub token: String,
63    pub token_type: &'static str,
64    pub expires_in: i64,
65    pub spiffe_id: String,
66    pub bundle_endpoint: String,
67}
68
69#[derive(Debug, Serialize)]
70struct JwtSvidClaims {
71    iss: String,
72    sub: String,
73    aud: Vec<String>,
74    iat: i64,
75    exp: i64,
76}
77
78#[derive(Debug, Deserialize)]
79struct ExternalWorkloadClaims {
80    iss: String,
81    sub: String,
82    exp: i64,
83    #[serde(default)]
84    nbf: Option<i64>,
85    #[serde(default)]
86    aud: serde_json::Value,
87}
88
89/// `POST /oauth/spiffe/wit` — exchange a cluster/SPIRE JWT for a local WIT.
90pub async fn exchange_workload_wit(
91    State(state): State<Arc<OAuthState>>,
92    headers: HeaderMap,
93    Json(body): Json<WorkloadWitRequest>,
94) -> Response {
95    if body.audience.trim().is_empty() {
96        return oauth_error(
97            StatusCode::BAD_REQUEST,
98            "invalid_request",
99            Some("audience is required"),
100        );
101    }
102
103    let source =
104        match verify_external_workload_jwt(&state, &body.subject_token, &body.audience).await {
105            Ok(c) => c,
106            Err(e) => {
107                tracing::warn!(error = %e, "SPIFFE/WIT exchange rejected");
108                return oauth_error(StatusCode::UNAUTHORIZED, "invalid_grant", None);
109            }
110        };
111
112    let endpoint = format!(
113        "{}/oauth/spiffe/wit",
114        state.issuer_url.trim_end_matches('/')
115    );
116    let bind_key = match binding_key(&headers, body.pubkey.as_deref(), &endpoint) {
117        Ok(v) => v,
118        Err(e) => {
119            tracing::warn!(error = %e, "SPIFFE/WIT exchange rejected: invalid sender binding");
120            return oauth_error(StatusCode::BAD_REQUEST, "invalid_request", Some(e));
121        }
122    };
123
124    let ca_key = match state.active_jwt_signing_key().await {
125        Some(k) => k,
126        None => {
127            return oauth_error(
128                StatusCode::SERVICE_UNAVAILABLE,
129                "temporarily_unavailable",
130                Some("WIT issuance not available"),
131            );
132        }
133    };
134
135    let now = chrono::Utc::now().timestamp();
136    let exp = now + K8S_WIT_TTL;
137    let subject = map_workload_subject(&source.iss, &source.sub);
138    let mut claims = hyprstream_rpc::auth::Claims::new(subject.clone(), now, exp)
139        .with_issuer(state.issuer_url.clone())
140        .with_audience(Some(body.audience));
141    if let Some(key) = bind_key {
142        claims = claims.with_cnf_jwk(&key);
143    }
144    // Hybrid mint: this WIT is for calling local hyprstream services over the
145    // dispatch plane, whose mandatory Hybrid crypto policy rejects classical
146    // EdDSA tokens. (The JWT-SVID below stays EdDSA — it is consumed by
147    // external SPIFFE validators, not by the dispatch plane.)
148    let wit = match crate::auth::jwt::encode_service_jwt_hybrid_via_authority(&claims, &ca_key) {
149        Ok(wit) => wit,
150        Err(error) => {
151            tracing::warn!(%error, "WIT issuance refused: hybrid signing authority unavailable");
152            return oauth_error(
153                StatusCode::SERVICE_UNAVAILABLE,
154                "temporarily_unavailable",
155                Some("WIT issuance not available — hybrid signing authority unavailable"),
156            );
157        }
158    };
159
160    tracing::info!(
161        source_issuer = %source.iss,
162        source_subject = %source.sub,
163        subject = %subject,
164        "SPIFFE/Kubernetes workload token exchanged for WIT"
165    );
166
167    (
168        StatusCode::OK,
169        [
170            (header::CACHE_CONTROL, "no-store"),
171            (header::PRAGMA, "no-cache"),
172        ],
173        Json(WorkloadWitResponse {
174            wit,
175            token_type: "wit+jwt",
176            expires_in: K8S_WIT_TTL,
177            subject,
178            source_issuer: source.iss,
179            source_subject: source.sub,
180        }),
181    )
182        .into_response()
183}
184
185/// `POST /oauth/spiffe/service-svid` — issue a JWT-SVID for a hyprstream service.
186///
187/// Protected by normal OAuth bearer auth. PolicyService remains the authority
188/// behind issuance; this HTTP surface only shapes the token as JWT-SVID.
189pub async fn issue_service_svid(
190    State(state): State<Arc<OAuthState>>,
191    Extension(user): Extension<AuthenticatedUser>,
192    Json(body): Json<ServiceSvidRequest>,
193) -> Response {
194    let requester_service = user.user.strip_prefix("service:");
195    if requester_service != Some(body.service.as_str()) {
196        return oauth_error(
197            StatusCode::FORBIDDEN,
198            "insufficient_scope",
199            Some("service authority may mint only its own JWT-SVID"),
200        );
201    }
202    if !valid_service_name(&body.service) {
203        return oauth_error(
204            StatusCode::BAD_REQUEST,
205            "invalid_request",
206            Some("service must contain only [A-Za-z0-9._-]"),
207        );
208    }
209    if body.audience.is_empty() || body.audience.iter().any(|a| a.trim().is_empty()) {
210        return oauth_error(
211            StatusCode::BAD_REQUEST,
212            "invalid_request",
213            Some("audience must contain at least one non-empty value"),
214        );
215    }
216
217    let signing_key = match state.active_jwt_signing_key().await {
218        Some(k) => k,
219        None => {
220            return oauth_error(
221                StatusCode::SERVICE_UNAVAILABLE,
222                "temporarily_unavailable",
223                Some("JWT-SVID issuance not available"),
224            );
225        }
226    };
227
228    let now = chrono::Utc::now().timestamp();
229    let exp = now + JWT_SVID_TTL;
230    let spiffe_id = service_spiffe_id(&state.issuer_url, &body.service);
231    let claims = JwtSvidClaims {
232        iss: state.issuer_url.clone(),
233        sub: spiffe_id.clone(),
234        aud: body.audience,
235        iat: now,
236        exp,
237    };
238    // JWT-SVID stays classical EdDSA: it feeds the external SPIFFE interop
239    // contract (validated against the trust-domain bundle by SPIFFE-aware
240    // consumers), not the dispatch plane's Hybrid policy gate.
241    let token = encode_jwt_svid(&claims, &signing_key);
242
243    tracing::info!(
244        requester = %user.user,
245        spiffe_id = %spiffe_id,
246        "SPIFFE JWT-SVID issued for hyprstream service"
247    );
248
249    (
250        StatusCode::OK,
251        [
252            (header::CACHE_CONTROL, "no-store"),
253            (header::PRAGMA, "no-cache"),
254        ],
255        Json(ServiceSvidResponse {
256            token,
257            token_type: "jwt-svid",
258            expires_in: JWT_SVID_TTL,
259            spiffe_id,
260            bundle_endpoint: format!(
261                "{}/.well-known/spiffe/bundle",
262                state.issuer_url.trim_end_matches('/')
263            ),
264        }),
265    )
266        .into_response()
267}
268
269/// `GET /.well-known/spiffe/bundle` — SPIFFE trust-domain bundle.
270pub async fn spiffe_bundle(State(state): State<Arc<OAuthState>>) -> Response {
271    let composite_snapshot = hyprstream_rpc::auth::global_composite_key_set().snapshot();
272    let keys = super::jwks::jwks_json(&state, &composite_snapshot).await;
273    Json(serde_json::json!({
274        "spiffe_sequence": 1,
275        "keys": keys,
276    }))
277    .into_response()
278}
279
280async fn verify_external_workload_jwt(
281    state: &Arc<OAuthState>,
282    token: &str,
283    expected_audience: &str,
284) -> Result<ExternalWorkloadClaims, String> {
285    let unverified = decode_external_claims_unverified(token)
286        .map_err(|e| format!("cannot parse workload jwt: {e}"))?;
287    if unverified.iss.is_empty() {
288        return Err("workload jwt missing iss".to_owned());
289    }
290    if unverified.sub.is_empty() {
291        return Err("workload jwt missing sub".to_owned());
292    }
293
294    let cfg = state
295        .trusted_issuers
296        .get(&unverified.iss)
297        .ok_or_else(|| format!("issuer is not registered/trusted: {}", unverified.iss))?
298        .clone();
299    let vk =
300        super::jwt_bearer::resolve_federated_key(state, &unverified.iss, token, cfg.allow_http)
301            .await?;
302    verify_external_eddsa_jwt(token, &vk)?;
303    let claims = decode_external_claims_unverified(token)?;
304    validate_external_claims(&claims, expected_audience)?;
305    Ok(claims)
306}
307
308fn decode_external_claims_unverified(token: &str) -> Result<ExternalWorkloadClaims, String> {
309    let payload_b64 = token
310        .split('.')
311        .nth(1)
312        .ok_or_else(|| "invalid jwt format".to_owned())?;
313    let payload = URL_SAFE_NO_PAD
314        .decode(payload_b64)
315        .map_err(|_| "invalid jwt payload base64".to_owned())?;
316    serde_json::from_slice(&payload).map_err(|e| format!("invalid jwt claims: {e}"))
317}
318
319fn verify_external_eddsa_jwt(token: &str, key: &ed25519_dalek::VerifyingKey) -> Result<(), String> {
320    let parts: Vec<&str> = token.split('.').collect();
321    if parts.len() != 3 {
322        return Err("invalid jwt format".to_owned());
323    }
324    let header = URL_SAFE_NO_PAD
325        .decode(parts[0])
326        .map_err(|_| "invalid jwt header base64".to_owned())?;
327    let header: serde_json::Value =
328        serde_json::from_slice(&header).map_err(|e| format!("invalid jwt header: {e}"))?;
329    if header.get("alg").and_then(|v| v.as_str()) != Some("EdDSA") {
330        return Err("only EdDSA workload JWTs are supported".to_owned());
331    }
332    let sig_bytes = URL_SAFE_NO_PAD
333        .decode(parts[2])
334        .map_err(|_| "invalid jwt signature base64".to_owned())?;
335    let sig_bytes: [u8; 64] = sig_bytes
336        .try_into()
337        .map_err(|_| "invalid Ed25519 signature length".to_owned())?;
338    let signing_input = format!("{}.{}", parts[0], parts[1]);
339    key.verify(signing_input.as_bytes(), &Signature::from_bytes(&sig_bytes))
340        .map_err(|_| "workload jwt signature verification failed".to_owned())
341}
342
343fn validate_external_claims(
344    claims: &ExternalWorkloadClaims,
345    expected_audience: &str,
346) -> Result<(), String> {
347    let now = chrono::Utc::now().timestamp();
348    if claims.exp <= now {
349        return Err("workload jwt expired".to_owned());
350    }
351    if claims.nbf.is_some_and(|nbf| nbf > now + 5) {
352        return Err("workload jwt not yet valid".to_owned());
353    }
354    let audience_ok = match &claims.aud {
355        serde_json::Value::String(aud) => aud == expected_audience,
356        serde_json::Value::Array(auds) => auds
357            .iter()
358            .any(|aud| aud.as_str() == Some(expected_audience)),
359        _ => false,
360    };
361    if !audience_ok {
362        return Err("workload jwt audience mismatch".to_owned());
363    }
364    Ok(())
365}
366
367fn binding_key(
368    headers: &HeaderMap,
369    explicit_pubkey: Option<&str>,
370    endpoint: &str,
371) -> Result<Option<[u8; 32]>, &'static str> {
372    if let Some(pubkey) = explicit_pubkey {
373        return decode_ed25519_pubkey(pubkey).map(Some);
374    }
375
376    let Some(dpop) = headers.get("DPoP").and_then(|v| v.to_str().ok()) else {
377        return Ok(None);
378    };
379    let proof = super::dpop::verify_dpop_proof(dpop, "POST", endpoint, None)
380        .map_err(|_| "invalid DPoP proof")?;
381    match proof.key {
382        super::dpop::DpopKey::Ed25519 { bytes } => Ok(Some(bytes)),
383        _ => Err("DPoP proof key must be Ed25519 for WIT cnf.jwk binding"),
384    }
385}
386
387fn decode_ed25519_pubkey(value: &str) -> Result<[u8; 32], &'static str> {
388    let bytes: [u8; 32] = URL_SAFE_NO_PAD
389        .decode(value)
390        .ok()
391        .and_then(|b| b.try_into().ok())
392        .ok_or("pubkey must be base64url-encoded 32-byte Ed25519 public key")?;
393    ed25519_dalek::VerifyingKey::from_bytes(&bytes)
394        .map_err(|_| "pubkey is not a valid Ed25519 public key")?;
395    Ok(bytes)
396}
397
398fn map_workload_subject(issuer: &str, sub: &str) -> String {
399    if let Some(rest) = sub.strip_prefix("system:serviceaccount:") {
400        let mut parts = rest.splitn(2, ':');
401        if let (Some(ns), Some(sa)) = (parts.next(), parts.next()) {
402            return format!("k8s:{}:{}:{}", trust_domain_from_issuer(issuer), ns, sa);
403        }
404    }
405    if let Some(rest) = sub.strip_prefix("spiffe://") {
406        return format!("spiffe:{rest}");
407    }
408    format!("federated:{}:{}", trust_domain_from_issuer(issuer), sub)
409}
410
411fn service_spiffe_id(issuer_url: &str, service: &str) -> String {
412    format!(
413        "spiffe://{}/service/{service}",
414        trust_domain_from_issuer(issuer_url)
415    )
416}
417
418fn trust_domain_from_issuer(issuer_url: &str) -> String {
419    issuer_url
420        .trim_start_matches("https://")
421        .trim_start_matches("http://")
422        .trim_end_matches('/')
423        .split('/')
424        .next()
425        .unwrap_or(issuer_url)
426        .to_owned()
427}
428
429fn valid_service_name(value: &str) -> bool {
430    !value.is_empty()
431        && value
432            .chars()
433            .all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-'))
434}
435
436fn encode_jwt_svid(claims: &JwtSvidClaims, signing_key: &ed25519_dalek::SigningKey) -> String {
437    let kid = hyprstream_rpc::auth::jwt::kid_for_key(signing_key);
438    let header = serde_json::json!({
439        "alg": "EdDSA",
440        "typ": "JWT",
441        "kid": kid,
442    });
443    let header_b64 = URL_SAFE_NO_PAD.encode(header.to_string());
444    let payload = serde_json::to_vec(claims).unwrap_or_default();
445    let payload_b64 = URL_SAFE_NO_PAD.encode(payload);
446    let signing_input = format!("{header_b64}.{payload_b64}");
447    let sig = signing_key.sign(signing_input.as_bytes());
448    format!(
449        "{}.{}",
450        signing_input,
451        URL_SAFE_NO_PAD.encode(sig.to_bytes())
452    )
453}
454
455fn oauth_error(status: StatusCode, error: &str, description: Option<&str>) -> Response {
456    let mut body = serde_json::Map::new();
457    body.insert(
458        "error".to_owned(),
459        serde_json::Value::String(error.to_owned()),
460    );
461    if let Some(description) = description {
462        body.insert(
463            "error_description".to_owned(),
464            serde_json::Value::String(description.to_owned()),
465        );
466    }
467    (
468        status,
469        [
470            (header::CACHE_CONTROL, "no-store"),
471            (header::PRAGMA, "no-cache"),
472        ],
473        Json(serde_json::Value::Object(body)),
474    )
475        .into_response()
476}
477
478#[cfg(test)]
479mod tests {
480    use super::*;
481    use rand::rngs::OsRng;
482
483    #[test]
484    fn k8s_service_account_subject_maps_without_collision() {
485        assert_eq!(
486            map_workload_subject(
487                "https://issuer.example.test",
488                "system:serviceaccount:training:runner"
489            ),
490            "k8s:issuer.example.test:training:runner"
491        );
492    }
493
494    #[test]
495    fn service_spiffe_id_uses_issuer_host_as_trust_domain() {
496        assert_eq!(
497            service_spiffe_id("https://hypr.example.test/oauth", "model"),
498            "spiffe://hypr.example.test/service/model"
499        );
500    }
501
502    #[test]
503    fn service_svid_requester_binding_is_exact() {
504        let requester = "service:model";
505        assert_eq!(requester.strip_prefix("service:"), Some("model"));
506        assert_ne!(requester.strip_prefix("service:"), Some("policy"));
507    }
508
509    #[test]
510    fn jwt_svid_uses_audience_array() {
511        let key = ed25519_dalek::SigningKey::generate(&mut OsRng);
512        let token = encode_jwt_svid(
513            &JwtSvidClaims {
514                iss: "https://hypr.example.test".to_owned(),
515                sub: "spiffe://hypr.example.test/service/model".to_owned(),
516                aud: vec!["9p".to_owned(), "rpc".to_owned()],
517                iat: 1,
518                exp: 2,
519            },
520            &key,
521        );
522        let Some(payload_b64) = token.split('.').nth(1) else {
523            panic!("payload part");
524        };
525        let payload = match URL_SAFE_NO_PAD.decode(payload_b64) {
526            Ok(payload) => payload,
527            Err(e) => panic!("payload decodes: {e}"),
528        };
529        let value: serde_json::Value = match serde_json::from_slice(&payload) {
530            Ok(value) => value,
531            Err(e) => panic!("json payload: {e}"),
532        };
533        assert_eq!(value["aud"], serde_json::json!(["9p", "rpc"]));
534        assert_eq!(value["sub"], "spiffe://hypr.example.test/service/model");
535    }
536}