Skip to main content

hyprstream_core/server/
middleware.rs

1//! Middleware for authentication, logging, and request processing
2
3use crate::auth::jwt;
4use crate::server::state::ResourceAuthState;
5use axum::{
6    extract::{Request, State},
7    http::{header, HeaderValue, StatusCode},
8    middleware::Next,
9    response::{IntoResponse, Response},
10};
11use hyprstream_util::InsertIfAbsentNoEvictResult;
12use std::sync::Arc;
13use std::time::Duration;
14use std::time::Instant;
15use subtle::ConstantTimeEq as _;
16use tracing::{debug, info, warn};
17
18/// Authenticated identity extracted from token
19#[derive(Clone)]
20pub struct AuthenticatedUser {
21    /// Username (from JWT sub claim)
22    pub user: String,
23    /// Tenant/Casbin domain from the authority-verified hosted-account binding.
24    ///
25    /// This is copied only from a successfully verified JWT. It is never
26    /// inferred from `user` or accepted from request data.
27    pub verified_tenant: Option<String>,
28    /// Original JWT token for e2e verification through service chain.
29    /// SECURITY: Never logged — custom Debug impl redacts this field.
30    pub token: Option<String>,
31    /// JWT expiration timestamp (from the validated JWT claims).
32    pub exp: Option<i64>,
33}
34
35impl std::fmt::Debug for AuthenticatedUser {
36    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
37        f.debug_struct("AuthenticatedUser")
38            .field("user", &self.user)
39            .field("verified_tenant", &self.verified_tenant)
40            .field("token", &self.token.as_ref().map(|_| "[REDACTED]"))
41            .field("exp", &self.exp)
42            .finish()
43    }
44}
45
46impl AuthenticatedUser {
47    /// Select the Casbin domain for an authenticated HTTP request.
48    ///
49    /// Tenant-bound identities stay in their authority-verified hosted-account
50    /// tenant. A tenantless `service:*` authority may use the global domain,
51    /// matching `PolicyService::request_domain`; ordinary tenantless identities
52    /// fail closed. A present but malformed/wildcard binding always fails,
53    /// including for services.
54    pub fn authorization_domain(&self) -> Result<String, &'static str> {
55        if let Some(tenant) = self.verified_tenant.as_deref() {
56            // The canonical tenant-component rule (crate::auth); every
57            // tenant-carrying plane enforces the same syntax.
58            if !crate::auth::valid_tenant_component(tenant) {
59                return Err("invalid verified tenant");
60            }
61            return Ok(tenant.to_owned());
62        }
63
64        if self.user.starts_with("service:") {
65            return Ok("*".to_owned());
66        }
67
68        Err("missing verified tenant")
69    }
70}
71
72/// JWT authentication middleware
73///
74/// Validates JWT tokens via Ed25519 signature verification.
75/// Accepts `Authorization: Bearer <token>` and `Authorization: DPoP <token>`.
76///
77/// When the token carries a `cnf.jkt` claim (DPoP-bound token per RFC 9449),
78/// the `Authorization: DPoP` scheme MUST be used and a valid `DPoP` proof
79/// header MUST accompany the request — plain Bearer is rejected to prevent
80/// token replay after theft.
81///
82/// Revoked tokens (via `POST /oauth/revoke`) are rejected via JTI blocklist.
83///
84/// On success, inserts `AuthenticatedUser` into request extensions.
85pub async fn auth_middleware(
86    State(state): State<ResourceAuthState>,
87    mut request: Request,
88    next: Next,
89) -> Response {
90    let client_ip = extract_client_ip(&request);
91    let method = request.method().as_str().to_owned();
92    let path = request.uri().path().to_owned();
93
94    // Accept both Bearer and DPoP schemes (RFC 6750, RFC 9449)
95    let auth_hdr = request
96        .headers()
97        .get(header::AUTHORIZATION)
98        .and_then(|v| v.to_str().ok())
99        .map(str::to_owned);
100
101    let (scheme, token) = match auth_hdr.as_deref().and_then(|h| {
102        if h.len() > 7 && h[..7].eq_ignore_ascii_case("bearer ") {
103            Some(("bearer", h[7..].trim().to_owned()))
104        } else if h.len() > 5 && h[..5].eq_ignore_ascii_case("dpop ") {
105            Some(("dpop", h[5..].trim().to_owned()))
106        } else {
107            None
108        }
109    }) {
110        Some(pair) => pair,
111        None => {
112            let www_authenticate = build_www_authenticate(&state);
113            return unauthorized_response("Authentication required", &www_authenticate);
114        }
115    };
116
117    // Build WWW-Authenticate header for 401 responses (RFC 9728)
118    let www_authenticate = build_www_authenticate(&state);
119
120    // Verify the token to validated claims via the shared auth chain
121    // (malformed check, local-vs-federation issuer routing, signature +
122    // audience validation, JTI revocation). Reused verbatim by the 9P mount
123    // ticket validator (H1a / #764). DPoP sender-binding is enforced below,
124    // after we hold the claims, because it is header/scheme-specific.
125    let atproto_issuer =
126        crate::services::oauth::state::canonical_issuer_origin(&state.oauth_issuer_url)
127            .unwrap_or_else(|| state.oauth_issuer_url.clone());
128    let local_issuers: &[&str] = &[&*state.oauth_issuer_url, &atproto_issuer];
129    let claims = match verify_resource_token_claims(&state, &token).await {
130        Ok(c) => c,
131        Err(reason) => {
132            warn!(client_ip = %client_ip, method = %method, path = %path, reason, "Auth failure");
133            return unauthorized_response("Authentication failed", &www_authenticate);
134        }
135    };
136
137    // DPoP binding enforcement (RFC 9449).
138    // A token with cnf.jkt MUST be presented with Authorization: DPoP + DPoP proof header.
139    // Accepting it as Bearer would let a stolen token replay without proof of key possession.
140    if let Some(expected_jkt) = claims.cnf_jkt() {
141        if scheme != "dpop" {
142            warn!(sub = %claims.sub, "DPoP-bound token presented with Bearer scheme — rejected");
143            return unauthorized_response("Authentication failed", &www_authenticate);
144        }
145        let dpop_proof = match request.headers().get("DPoP").and_then(|v| v.to_str().ok()) {
146            Some(p) => p.to_owned(),
147            None => {
148                debug!("DPoP-bound token missing DPoP proof header");
149                return unauthorized_response("Authentication failed", &www_authenticate);
150            }
151        };
152        let method = request.method().as_str().to_owned();
153        let path = request.uri().path().to_owned();
154        // Build absolute htu from the server's resource_url (scheme + host) + request path.
155        // Axum doesn't populate scheme/host in the URI for HTTPS behind a TLS terminator,
156        // so we use the pre-configured resource_url as the authority base.
157        let htu = format!("{}{}", state.resource_url.trim_end_matches('/'), path);
158        let proof = match crate::services::oauth::dpop::verify_dpop_proof(
159            &dpop_proof,
160            &method,
161            &htu,
162            Some(&token),
163        ) {
164            Ok(p) => p,
165            Err(e) => {
166                debug!("DPoP proof verification failed: {}", e);
167                return unauthorized_response("Authentication failed", &www_authenticate);
168            }
169        };
170        // Replay prevention: each DPoP jti is accepted at most once (within
171        // iat ±60s window). Atomic check-and-record on the shared TtlCache.
172        {
173            let now = chrono::Utc::now().timestamp();
174            let Some(ttl_secs) = proof
175                .iat
176                .checked_add(120)
177                .and_then(|deadline| deadline.checked_sub(now))
178                .filter(|remaining| *remaining > 0 && *remaining <= 180)
179                .and_then(|remaining| u64::try_from(remaining).ok())
180            else {
181                return unauthorized_response("Authentication failed", &www_authenticate);
182            };
183            let result = state.dpop_jti_seen.insert_if_absent_no_evict(
184                crate::services::oauth::replay_key::dpop_jti(&proof.jti),
185                (),
186                Duration::from_secs(ttl_secs),
187            );
188            if result != InsertIfAbsentNoEvictResult::Inserted {
189                crate::services::oauth::replay_metrics::record_rejection(
190                    crate::services::oauth::replay_metrics::DPOP,
191                    result,
192                );
193                if crate::services::oauth::replay_metrics::should_warn_full(
194                    crate::services::oauth::replay_metrics::DPOP,
195                    result,
196                ) {
197                    warn!("DPoP replay barrier is full; refusing fresh proof");
198                } else if result == InsertIfAbsentNoEvictResult::Duplicate {
199                    debug!("DPoP proof replayed");
200                }
201                return unauthorized_response("Authentication failed", &www_authenticate);
202            }
203        }
204        // cnf.jkt must match the DPoP proof key thumbprint.
205        if expected_jkt
206            .as_bytes()
207            .ct_eq(proof.jkt.as_bytes())
208            .unwrap_u8()
209            == 0
210        {
211            warn!(sub = %claims.sub, "cnf.jkt mismatch — DPoP proof key does not match token binding");
212            return unauthorized_response("Authentication failed", &www_authenticate);
213        }
214    }
215
216    debug!("JWT validated for user: {}", claims.sub);
217    let subject = claims.subject(local_issuers);
218    // The signed hosted-account DID is allowed only with its exact verified
219    // tenant; legacy local and federated subject validation remains unchanged.
220    if !crate::auth::valid_resource_subject(
221        &subject,
222        &claims.iss,
223        local_issuers,
224        claims.tenant.as_deref(),
225    ) {
226        debug!("JWT sub validation failed");
227        return unauthorized_response("Authentication failed", &www_authenticate);
228    }
229    let user_str = match subject.name() {
230        Some(n) => n.to_owned(),
231        None => {
232            debug!("JWT has empty sub");
233            return unauthorized_response("Authentication failed", &www_authenticate);
234        }
235    };
236    let user = AuthenticatedUser {
237        user: user_str,
238        verified_tenant: claims.tenant.clone(),
239        token: Some(token),
240        exp: Some(claims.exp),
241    };
242    if let Err(reason) = user.authorization_domain() {
243        warn!(subject = %user.user, reason, "HTTP authorization has no valid hosted-account tenant binding");
244        return (
245            StatusCode::FORBIDDEN,
246            "Verified hosted-account tenant binding required",
247        )
248            .into_response();
249    }
250    request.extensions_mut().insert(user);
251    next.run(request).await
252}
253
254/// Request logging middleware
255pub async fn logging_middleware(request: Request, next: Next) -> Response {
256    let method = request.method().clone();
257    let uri = request.uri().clone();
258    let start = Instant::now();
259
260    let response = next.run(request).await;
261
262    let duration = start.elapsed();
263    let status = response.status();
264
265    if status.is_client_error() || status.is_server_error() {
266        warn!("{} {} {} ({:?})", method, uri, status, duration);
267    } else {
268        info!("{} {} {} ({:?})", method, uri, status, duration);
269    }
270
271    response
272}
273
274/// Fixed-window per-subject rate limiter.
275///
276/// Tracks request counts per authenticated subject (JWT sub).
277/// The window resets cleanly at the end of each window period.
278pub struct RateLimiter {
279    /// subject → (request_count, window_start_unix)
280    counters: parking_lot::RwLock<std::collections::HashMap<String, (u32, i64)>>,
281    max_requests: u32,
282    window_secs: i64,
283}
284
285impl RateLimiter {
286    pub fn new(max_requests: u32, window_secs: i64) -> Self {
287        Self {
288            counters: parking_lot::RwLock::new(std::collections::HashMap::new()),
289            max_requests,
290            window_secs,
291        }
292    }
293
294    /// Check + increment. Returns `true` if the caller is over quota.
295    pub fn check_and_increment(&self, subject: &str) -> bool {
296        let now = chrono::Utc::now().timestamp();
297        let mut map = self.counters.write();
298        // Evict stale entries to bound memory growth
299        if map.len() > 10_000 {
300            let window_secs = self.window_secs;
301            map.retain(|_, (_, ws)| now - *ws < window_secs * 2);
302        }
303        let entry = map.entry(subject.to_owned()).or_insert((0, now));
304        if now - entry.1 >= self.window_secs {
305            // New window: reset
306            *entry = (1, now);
307            false
308        } else if entry.0 >= self.max_requests {
309            true // over quota
310        } else {
311            entry.0 += 1;
312            false
313        }
314    }
315}
316
317/// Rate limiting middleware — enforces per-authenticated-subject request quotas.
318///
319/// Runs after `auth_middleware` (which inserts `AuthenticatedUser`).
320/// Defaults: 300 requests per 60-second window (~5 req/s sustained).
321/// Returns 429 when the window quota is exceeded.
322pub async fn rate_limit_middleware(
323    State(state): State<ResourceAuthState>,
324    request: Request,
325    next: Next,
326) -> Response {
327    let subject = request
328        .extensions()
329        .get::<AuthenticatedUser>()
330        .map(|u| u.user.clone())
331        .unwrap_or_else(|| "anonymous".to_owned());
332
333    if state.rate_limiter.check_and_increment(&subject) {
334        warn!(subject = %subject, "Rate limit exceeded");
335        return (
336            StatusCode::TOO_MANY_REQUESTS,
337            "Rate limit exceeded — retry after window expires",
338        )
339            .into_response();
340    }
341
342    next.run(request).await
343}
344
345/// Rate-limit the public browser-provisioning route before accepted-state
346/// resolution or hybrid projection signing. A single stable bucket is
347/// intentional: this boundary may run without trustworthy peer-address
348/// metadata, and client-controlled forwarding headers must not select buckets.
349pub async fn browser_provisioning_rate_limit_middleware(
350    State(rate_limiter): State<Arc<RateLimiter>>,
351    request: Request,
352    next: Next,
353) -> Response {
354    const PROVISIONING_BUCKET: &str = "browser-provisioning";
355    if rate_limiter.check_and_increment(PROVISIONING_BUCKET) {
356        warn!("Browser provisioning rate limit exceeded");
357        return (
358            StatusCode::TOO_MANY_REQUESTS,
359            "Browser provisioning rate limit exceeded — retry after window expires",
360        )
361            .into_response();
362    }
363
364    next.run(request).await
365}
366
367/// Rate-limit public metadata and pre-upgrade routes with one stable bucket.
368///
369/// These routes intentionally have no authenticated subject from which to
370/// derive a per-tenant bucket. Forwarding headers are client-controlled at
371/// this boundary, so neither `X-Forwarded-For` nor `X-Real-IP` may select the
372/// bucket. Health probes use a separate, unmetered router.
373pub async fn public_route_rate_limit_middleware(
374    State(rate_limiter): State<Arc<RateLimiter>>,
375    request: Request,
376    next: Next,
377) -> Response {
378    const PUBLIC_ROUTE_BUCKET: &str = "public-routes";
379    if rate_limiter.check_and_increment(PUBLIC_ROUTE_BUCKET) {
380        warn!("Public route rate limit exceeded");
381        return (
382            StatusCode::TOO_MANY_REQUESTS,
383            "Public route rate limit exceeded — retry after window expires",
384        )
385            .into_response();
386    }
387
388    next.run(request).await
389}
390
391/// Verify a bearer/ticket token to its validated [`jwt::Claims`] using the
392/// shared server auth chain.
393///
394/// This is the token-verification core factored out of [`auth_middleware`] so
395/// the 9P mount-ticket validator (H1a / #764) reuses the *exact* same chain
396/// rather than re-implementing one:
397///
398/// 1. malformed-token rejection,
399/// 2. local-vs-federation issuer routing (local `verifying_key` or
400///    `federation_resolver`),
401/// 3. Ed25519 / ML-DSA signature + audience validation via `jwt::decode`,
402/// 4. JTI revocation against the shared blocklist (RFC 7009).
403///
404/// It does **not** enforce DPoP sender-binding: that is header/scheme-specific
405/// and stays in [`auth_middleware`]. Returns `Err(reason)` with a short,
406/// log-safe reason string on any failure (never leaks token contents).
407/// RFC 7638 JWK thumbprint (the JWKS `kid`) for an Ed25519 verifying key.
408fn ed25519_kid(key: &ed25519_dalek::VerifyingKey) -> String {
409    hyprstream_rpc::auth::jwk_thumbprint(&hyprstream_rpc::auth::JwkThumbprintInput::Ed25519 {
410        x: key.as_bytes(),
411    })
412}
413
414/// Verify a locally-issued JWT against the node's full published key set: the
415/// cluster CA key plus every currently-published Ed25519 rotation slot (the same
416/// key set `/oauth/jwks` publishes). Accepts the token if ANY of these trusted,
417/// node-published keys verifies it — standard JWKS/`kid`-rotation semantics.
418///
419/// Composite tokens verify only against exact published pairs; component key
420/// sets are never cross-paired. `alg`, `typ`, and `kid` are mandatory, and
421/// EdDSA is accepted only when the configured crypto policy permits it.
422fn decode_local_multi_key(
423    token: &str,
424    ca_key: &ed25519_dalek::VerifyingKey,
425    published_ed25519: &[ed25519_dalek::VerifyingKey],
426    published_composite: &[hyprstream_rpc::auth::CompositeKeyPair],
427    expected_aud: Option<&str>,
428    allow_eddsa: bool,
429) -> Result<jwt::Claims, &'static str> {
430    let header =
431        hyprstream_rpc::auth::parse_protected_header(token).map_err(|_| "JWT validation failed")?;
432    if !hyprstream_rpc::auth::is_rfc9068_access_token_type(&header.typ) {
433        return Err("JWT validation failed");
434    }
435    match header.alg.as_str() {
436        "ML-DSA-65-Ed25519" => {
437            decode_composite_multi(token, published_composite, expected_aud, &header)
438        }
439        "EdDSA" if allow_eddsa => {
440            decode_ed25519_multi(token, ca_key, published_ed25519, expected_aud, &header.kid)
441        }
442        _ => Err("JWT validation failed"),
443    }
444}
445
446fn decode_ed25519_multi(
447    token: &str,
448    ca_key: &ed25519_dalek::VerifyingKey,
449    published_ed25519: &[ed25519_dalek::VerifyingKey],
450    expected_aud: Option<&str>,
451    token_kid: &str,
452) -> Result<jwt::Claims, &'static str> {
453    let mut candidates: Vec<&ed25519_dalek::VerifyingKey> =
454        Vec::with_capacity(1 + published_ed25519.len());
455    candidates.push(ca_key);
456    candidates.extend(published_ed25519.iter());
457    let key = candidates
458        .into_iter()
459        .find(|key| ed25519_kid(key) == token_kid)
460        .ok_or("JWT validation failed")?;
461    jwt::decode(token, key, expected_aud).map_err(|_| "JWT validation failed")
462}
463
464fn decode_composite_multi(
465    token: &str,
466    published_composite: &[hyprstream_rpc::auth::CompositeKeyPair],
467    expected_aud: Option<&str>,
468    header: &hyprstream_rpc::auth::ProtectedHeader,
469) -> Result<jwt::Claims, &'static str> {
470    let dispatch = hyprstream_rpc::auth::parse_composite_dispatch(
471        token,
472        hyprstream_rpc::auth::RFC9068_ACCESS_TOKEN_TYPES,
473    )
474    .map_err(|_| "JWT validation failed")?;
475    if dispatch.kid() != header.kid {
476        return Err("JWT validation failed");
477    }
478    let pair = published_composite
479        .iter()
480        .find(|pair| pair.kid() == header.kid)
481        .ok_or("JWT validation failed")?;
482    hyprstream_rpc::auth::jwt::decode_composite(
483        token,
484        pair.ml_dsa(),
485        pair.ed25519(),
486        expected_aud,
487        &dispatch,
488    )
489    .map_err(|_| "JWT validation failed")
490}
491
492fn local_issuer_matches(claims: &jwt::Claims, expected: &str) -> bool {
493    claims.iss == expected
494}
495
496/// W1.3: the Federate TUI class is never an HTTP resource credential. Its
497/// only surface is the tui RPC service (and Policy's delegated read-only
498/// check); over HTTP it would otherwise act as a generic bearer credential
499/// for its DID (HTTP sender binding covers cnf.jkt, while this class
500/// carries cnf.jwk). Classify by marker set OR the deployment's class pin,
501/// so the all-stripped shape denies too.
502fn reject_federate_tui_http(
503    claims: &jwt::Claims,
504    local_issuers: &[&str],
505) -> Result<(), &'static str> {
506    if claims.is_federate_tui_class(local_issuers) {
507        return Err("federate TUI credentials are not HTTP resource credentials");
508    }
509    Ok(())
510}
511
512pub(crate) async fn verify_resource_token_claims(
513    state: &ResourceAuthState,
514    token: &str,
515) -> Result<jwt::Claims, &'static str> {
516    if !token.contains('.') {
517        return Err("malformed token");
518    }
519
520    // Extract iss for key routing (local node key vs trusted federation peer).
521    let iss = extract_iss_from_token(token);
522    let atproto_issuer =
523        crate::services::oauth::state::canonical_issuer_origin(&state.oauth_issuer_url)
524            .unwrap_or_else(|| state.oauth_issuer_url.clone());
525    let local_issuers: &[&str] = &[&*state.oauth_issuer_url, &atproto_issuer];
526    let mut claims = if hyprstream_rpc::auth::is_local_iss(&iss, local_issuers) {
527        // Local-issuer tokens may be signed by EITHER the cluster CA key OR any
528        // currently-published rotation slot (the OAuth token endpoint signs with
529        // `active_jwt_signing_key()` → the rotation active slot). Validate against
530        // the same key set the /oauth/jwks endpoint publishes (CA + rotation
531        // slots), accepting if ANY trusted, published key verifies (#777).
532        let published = {
533            let guard = state
534                .published_jwt_verifying_keys
535                .read()
536                .unwrap_or_else(std::sync::PoisonError::into_inner);
537            guard.clone()
538        };
539        // Published ML-DSA-65 verifying keys (PQ half of the composite key set
540        // `/oauth/jwks` publishes). Lives in the same process-shared handle the
541        // MAC/key-rotation path populates at boot and after each ML-DSA rotation.
542        // Empty under Classical policy or before the OAuth store is provisioned —
543        // in which case a composite token simply fails closed here.
544        let published_composite = state.composite_key_set.snapshot();
545        let claims = decode_local_multi_key(
546            token,
547            &state.verifying_key,
548            &published,
549            published_composite.pairs(),
550            Some(&state.resource_url),
551            false,
552        )?;
553        if !local_issuer_matches(&claims, &state.oauth_issuer_url) {
554            return Err("JWT validation failed");
555        }
556        claims
557    } else {
558        if !state.federation_resolver.is_trusted(&iss) {
559            return Err("untrusted federation issuer");
560        }
561        // Rotation-aware federation verification (#1185): the resolver
562        // returns every Ed25519 key the issuer currently publishes
563        // (ordered kid-first), and we accept the token if ANY candidate
564        // verifies it. This is what makes overlap rotation safe — a
565        // token signed by a non-first key succeeds when its kid is
566        // published — and mirrors `decode_local_multi_key` for external
567        // issuers. The token's own `kid`, when present, is passed to
568        // the resolver so it can refetch on an unknown kid.
569        let kid = extract_kid_from_token(token);
570        match state
571            .federation_resolver
572            .get_keys(&iss, kid.as_deref())
573            .await
574        {
575            Ok(candidates) if !candidates.is_empty() => jwt::decode_with_federation_candidates(
576                token,
577                &candidates,
578                Some(&state.resource_url),
579            )
580            .map_err(|_| "JWT validation failed")?,
581            // Empty candidate set or fetch failure: fail closed either way.
582            Ok(_) | Err(_) => return Err("federation key resolution failed"),
583        }
584    };
585
586    // W1.3: the Federate TUI class is never an HTTP resource credential.
587    reject_federate_tui_http(&claims, local_issuers)?;
588
589    // Credential revocation check (RFC 7009) — fail-closed on store absence.
590    // The credential profile makes `jti` REQUIRED on locally issued tokens:
591    // a local token without one is rejected outright (revocation could never
592    // observe it). Federated tokens keep the revocation check only.
593    let token_is_local = hyprstream_rpc::auth::is_local_iss(&claims.iss, local_issuers);
594    if token_is_local && claims.jti.is_none() {
595        return Err("local credential missing required jti");
596    }
597    if let Some(ref jti) = claims.jti {
598        let cred_id = hyprstream_rpc::auth::CredentialId::jwt(&claims.iss, jti);
599        match hyprstream_rpc::auth::global_credential_revocation_store() {
600            Some(store) => {
601                if store.is_revoked(&cred_id).await {
602                    return Err("revoked token");
603                }
604            }
605            None => return Err("revocation store unavailable"),
606        }
607    }
608
609    // Session check (v16 §3.3): a local token carrying a session ID is
610    // rejected when the session is revoked, expired, unknown, or cannot be
611    // checked.
612    if token_is_local {
613        let session_key = match claims.session_key() {
614            Ok(key) => key,
615            Err(_) => return Err("malformed session claims"),
616        };
617        if let Some(session_key) = session_key {
618            match hyprstream_rpc::auth::global_session_registry() {
619                Some(registry) => {
620                    if registry.is_revoked(&session_key).await {
621                        return Err("session revoked");
622                    }
623                }
624                None => return Err("session registry unavailable"),
625            }
626        }
627    }
628
629    // RFC 9068 §2.2.1 (v16 credential profile): every token admitted on this
630    // resource-server path is an `at+jwt` (the verifier positively rejects any
631    // other `typ` before decoding — see the resource verifier's
632    // `is_rfc9068_access_token_type` gate), so it MUST carry a non-empty
633    // `client_id`. This covers local AND trusted federated at+jwt.
634    if claims
635        .client_id
636        .as_deref()
637        .is_none_or(|c| c.trim().is_empty())
638    {
639        return Err("at+jwt credential missing required client_id");
640    }
641
642    // The HTTP resource verifier is also used by bare-token faces (Flight and
643    // one-use 9P tickets). A cnf.jwk/hs_signer_suite credential is dispatch
644    // proof-of-possession, not an HTTP bearer: none of these faces verifies its
645    // original holder's signature. DPoP cnf.jkt is checked by auth_middleware;
646    // faces without a DPoP proof transport must reject it themselves.
647    if claims
648        .cnf
649        .as_ref()
650        .is_some_and(|cnf| cnf.jwk.is_some() || cnf.hs_signer_suite.is_some())
651    {
652        return Err("key-bound credential requires original holder proof");
653    }
654
655    // Federation is trusted for identity, never for choosing a local
656    // PDS/Casbin tenant or asserting local MAC clearance.
657    claims.strip_federated_clearance(local_issuers);
658    claims.strip_federated_tenant(local_issuers);
659    Ok(claims)
660}
661
662/// Build WWW-Authenticate header value with resource_metadata URL (RFC 9728).
663fn build_www_authenticate(state: &ResourceAuthState) -> String {
664    let resource_metadata_url = format!(
665        "{}/.well-known/oauth-protected-resource",
666        state.resource_url
667    );
668    format!("Bearer resource_metadata=\"{}\"", resource_metadata_url,)
669}
670
671/// Return a 401 response with WWW-Authenticate header.
672fn unauthorized_response(message: &str, www_authenticate: &str) -> Response {
673    let mut response = (StatusCode::UNAUTHORIZED, message.to_owned()).into_response();
674    if let Ok(val) = HeaderValue::from_str(www_authenticate) {
675        response.headers_mut().insert(header::WWW_AUTHENTICATE, val);
676    }
677    response
678}
679
680/// Extract the `iss` claim from a JWT payload without signature verification.
681/// Exported for use in other middleware-like contexts (e.g. MCP inline auth).
682/// Returns an empty string on any parse failure.
683pub fn extract_iss_from_token(token: &str) -> String {
684    use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine};
685    let parts: Vec<&str> = token.splitn(3, '.').collect();
686    if parts.len() < 2 {
687        return String::new();
688    }
689    // Guard against adversarially large payloads (real JWT payloads are < 1KB)
690    if parts[1].len() > 8192 {
691        return String::new();
692    }
693    let payload_bytes = match URL_SAFE_NO_PAD.decode(parts[1]) {
694        Ok(b) => b,
695        Err(_) => return String::new(),
696    };
697    let payload: serde_json::Value = match serde_json::from_slice(&payload_bytes) {
698        Ok(v) => v,
699        Err(_) => return String::new(),
700    };
701    payload
702        .get("iss")
703        .and_then(|v| v.as_str())
704        .unwrap_or("")
705        .to_owned()
706}
707
708/// Extract `kid` from a JWT header without full validation.
709pub fn extract_kid_from_token(token: &str) -> Option<String> {
710    use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine};
711    let header_b64 = token.split('.').next()?;
712    if header_b64.len() > 4096 {
713        return None;
714    }
715    let header_bytes = URL_SAFE_NO_PAD.decode(header_b64).ok()?;
716    let header: serde_json::Value = serde_json::from_slice(&header_bytes).ok()?;
717    header
718        .get("kid")
719        .and_then(|v| v.as_str())
720        .map(str::to_owned)
721}
722
723/// Extract the client IP from `X-Forwarded-For` or `X-Real-IP` headers.
724/// Falls back to `"unknown"` when no header is present (e.g. direct connection
725/// where ConnectInfo is not available in this middleware form).
726fn extract_client_ip(request: &Request) -> String {
727    if let Some(xff) = request.headers().get("x-forwarded-for") {
728        if let Ok(s) = xff.to_str() {
729            // Take the leftmost (original client) IP
730            if let Some(ip) = s.split(',').next() {
731                return ip.trim().to_owned();
732            }
733        }
734    }
735    if let Some(xri) = request.headers().get("x-real-ip") {
736        if let Ok(s) = xri.to_str() {
737            return s.trim().to_owned();
738        }
739    }
740    "unknown".to_owned()
741}
742
743/// CORS middleware configuration
744pub fn cors_layer(config: &crate::server::state::CorsConfig) -> tower_http::cors::CorsLayer {
745    use axum::http::{HeaderName, HeaderValue, Method};
746    use tower_http::cors::{Any, CorsLayer};
747
748    let mut cors = CorsLayer::new()
749        .allow_methods([
750            Method::GET,
751            Method::POST,
752            Method::PUT,
753            Method::DELETE,
754            Method::OPTIONS,
755        ])
756        // Cross-origin clients must be able to follow RFC 9728 challenges and
757        // consume RFC 9449 nonce challenges. Neither header carries authority.
758        .expose_headers([
759            header::WWW_AUTHENTICATE,
760            HeaderName::from_static("dpop-nonce"),
761        ])
762        .max_age(std::time::Duration::from_secs(config.max_age));
763
764    // Configure allowed headers
765    if config.permissive_headers {
766        // Permissive mode — allow any request header. Deliberately scoped to the
767        // public, secret-free DID-document routes (CorsConfig::did_document); must
768        // not be enabled for the broad public router. Logged at warn! so the
769        // relaxed posture stays auditable to operators.
770        cors = cors.allow_headers(Any);
771        warn!("⚠️  CORS: allowing ALL request headers (permissive_headers=true)");
772    } else {
773        // Explicit mode - only allow specific headers for security
774        cors = cors.allow_headers([
775            // Standard HTTP headers
776            header::CONTENT_TYPE,
777            header::AUTHORIZATION,
778            // RFC 9449 proof accompanying `Authorization: DPoP ...`.
779            HeaderName::from_static("dpop"),
780            header::USER_AGENT,
781            header::ACCEPT,
782            header::ACCEPT_LANGUAGE,
783            header::ACCEPT_ENCODING,
784            header::REFERER,
785            header::ORIGIN,
786            header::CONNECTION,
787            // OpenAI SDK headers (x-stainless-*)
788            HeaderName::from_static("x-stainless-arch"),
789            HeaderName::from_static("x-stainless-lang"),
790            HeaderName::from_static("x-stainless-os"),
791            HeaderName::from_static("x-stainless-package-version"),
792            HeaderName::from_static("x-stainless-retry-count"),
793            HeaderName::from_static("x-stainless-runtime"),
794            HeaderName::from_static("x-stainless-runtime-version"),
795            HeaderName::from_static("x-stainless-timeout"),
796            // Additional OpenAI headers
797            HeaderName::from_static("openai-organization"),
798            HeaderName::from_static("openai-project"),
799            HeaderName::from_static("openai-beta"),
800            // Request ID tracking
801            HeaderName::from_static("x-request-id"),
802            HeaderName::from_static("x-trace-id"),
803        ]);
804    }
805
806    // Configure allowed origins
807    if config.allowed_origins.contains(&"*".to_owned()) {
808        // Allow all origins with Any (handles wildcard properly)
809        cors = cors.allow_origin(Any);
810        // Never allow credentials with wildcard
811        cors = cors.allow_credentials(false);
812    } else {
813        // Allow specific origins.
814        //
815        // The whole set MUST be passed in a single `allow_origin` call:
816        // `CorsLayer::allow_origin` is documented to *override* on every call
817        // (`self.allow_origin = origin.into()`), and a single `HeaderValue`
818        // becomes `AllowOrigin::exact(...)` — a constant `Access-Control-Allow-Origin`
819        // emitted unconditionally, not a membership check. Iterating and calling
820        // it once per origin would therefore honor only the LAST origin in the
821        // list, silently dropping every earlier origin. Passing the
822        // `Vec<HeaderValue>` makes tower-http build `AllowOrigin::list(...)`,
823        // which performs exact-equality membership matching against the full set.
824        let origins: Vec<HeaderValue> = if config.allowed_origins.is_empty() {
825            // If no origins specified, use default localhost origins
826            [
827                "http://localhost:3000",
828                "http://localhost:3001",
829                "http://127.0.0.1:3000",
830                "http://127.0.0.1:3001",
831            ]
832            .into_iter()
833            .filter_map(|o| o.parse::<HeaderValue>().ok())
834            .collect()
835        } else {
836            config
837                .allowed_origins
838                .iter()
839                .filter_map(|o| o.parse::<HeaderValue>().ok())
840                .collect()
841        };
842        cors = cors.allow_origin(origins);
843        // Configure credentials based on config
844        if config.allow_credentials {
845            cors = cors.allow_credentials(true);
846        }
847    }
848
849    cors
850}
851
852/// Runtime-behavior tests for [`cors_layer`].
853///
854/// Every assertion drives the real tower-http layer on an axum router. Config
855/// value tests would not catch origin-list override bugs or rejected browser
856/// preflights.
857#[cfg(test)]
858#[allow(clippy::expect_used, clippy::unwrap_used)]
859mod cors_layer_tests {
860    use super::cors_layer;
861    use crate::config::server::ServerConfig;
862    use crate::server::state::CorsConfig;
863    use axum::{
864        body::Body,
865        http::{header, Method, Request as HttpRequest, Response},
866        routing::get,
867        Router,
868    };
869    use tower::ServiceExt;
870
871    async fn response_for(
872        config: &CorsConfig,
873        method: Method,
874        origin: &str,
875        requested_method: Option<&str>,
876        requested_headers: Option<&str>,
877    ) -> Response<Body> {
878        let app = Router::new()
879            .route("/probe", get(|| async { "ok" }))
880            .layer(cors_layer(config));
881        let mut request = HttpRequest::builder()
882            .method(method)
883            .uri("/probe")
884            .header(header::ORIGIN, origin);
885        if let Some(requested_method) = requested_method {
886            request = request.header(header::ACCESS_CONTROL_REQUEST_METHOD, requested_method);
887        }
888        if let Some(requested_headers) = requested_headers {
889            request = request.header(header::ACCESS_CONTROL_REQUEST_HEADERS, requested_headers);
890        }
891        app.oneshot(request.body(Body::empty()).expect("request"))
892            .await
893            .expect("response")
894    }
895
896    async fn acao_for(config: &CorsConfig, origin: &str) -> Option<String> {
897        response_for(config, Method::GET, origin, None, None)
898            .await
899            .headers()
900            .get(header::ACCESS_CONTROL_ALLOW_ORIGIN)
901            .and_then(|v| v.to_str().ok())
902            .map(str::to_owned)
903    }
904
905    #[tokio::test]
906    async fn default_posture_is_wildcard_at_runtime() {
907        let config = CorsConfig::default();
908        for origin in ["https://hyprstream.com", "https://third-party.example"] {
909            assert_eq!(
910                acao_for(&config, origin).await,
911                Some("*".to_owned()),
912                "default public API posture must allow {origin}"
913            );
914        }
915    }
916
917    #[tokio::test]
918    async fn default_posture_never_advertises_credentials() {
919        let response = response_for(
920            &CorsConfig::default(),
921            Method::GET,
922            "https://third-party.example",
923            None,
924            None,
925        )
926        .await;
927        assert!(
928            !response
929                .headers()
930                .contains_key(header::ACCESS_CONTROL_ALLOW_CREDENTIALS),
931            "wildcard resource API must not advertise ambient credentials"
932        );
933    }
934
935    fn explicit_origins() -> CorsConfig {
936        ServerConfig::builder()
937            .cors_origins(vec![
938                "https://hyprstream.com".to_owned(),
939                "https://www.hyprstream.com".to_owned(),
940                "https://app.example.com".to_owned(),
941            ])
942            .build()
943            .cors
944    }
945
946    #[tokio::test]
947    async fn explicit_origin_list_still_exact_matches() {
948        let config = explicit_origins();
949        for origin in [
950            "https://hyprstream.com",
951            "https://www.hyprstream.com",
952            "https://app.example.com",
953        ] {
954            assert_eq!(
955                acao_for(&config, origin).await,
956                Some(origin.to_owned()),
957                "explicit origin list must honor {origin}"
958            );
959        }
960        assert_eq!(acao_for(&config, "https://evil.example.com").await, None);
961    }
962
963    #[tokio::test]
964    async fn explicit_list_near_miss_origins_are_rejected() {
965        let config = explicit_origins();
966        for evil in [
967            "https://hyprstream.com.evil.tld",
968            "https://evilhyprstream.com",
969            "http://hyprstream.com",
970            "https://www.hyprstream.com.evil",
971        ] {
972            assert_eq!(
973                acao_for(&config, evil).await,
974                None,
975                "explicit origin list must reject near miss {evil}"
976            );
977        }
978    }
979
980    #[tokio::test]
981    async fn explicit_list_with_credentials_preserves_legacy_escape_hatch() {
982        let config = ServerConfig::builder()
983            .cors_origins(vec!["https://app.example.com".to_owned()])
984            .cors_allow_credentials(true)
985            .build()
986            .cors;
987        let response =
988            response_for(&config, Method::GET, "https://app.example.com", None, None).await;
989        assert_eq!(
990            response
991                .headers()
992                .get(header::ACCESS_CONTROL_ALLOW_CREDENTIALS)
993                .and_then(|value| value.to_str().ok()),
994            Some("true")
995        );
996    }
997
998    #[tokio::test]
999    async fn wildcard_never_pairs_with_credentials() {
1000        let mut config = CorsConfig::public();
1001        config.allow_credentials = true;
1002        let response = response_for(
1003            &config,
1004            Method::GET,
1005            "https://third-party.example",
1006            None,
1007            None,
1008        )
1009        .await;
1010        assert_eq!(
1011            response
1012                .headers()
1013                .get(header::ACCESS_CONTROL_ALLOW_ORIGIN)
1014                .and_then(|v| v.to_str().ok()),
1015            Some("*")
1016        );
1017        assert!(!response
1018            .headers()
1019            .contains_key(header::ACCESS_CONTROL_ALLOW_CREDENTIALS));
1020    }
1021
1022    #[tokio::test]
1023    async fn preflight_allows_bearer_and_dpop_headers() {
1024        let response = response_for(
1025            &CorsConfig::default(),
1026            Method::OPTIONS,
1027            "https://third-party.example",
1028            Some("POST"),
1029            Some("authorization,dpop"),
1030        )
1031        .await;
1032        assert_eq!(
1033            response
1034                .headers()
1035                .get(header::ACCESS_CONTROL_ALLOW_ORIGIN)
1036                .and_then(|v| v.to_str().ok()),
1037            Some("*")
1038        );
1039        let allowed = response
1040            .headers()
1041            .get(header::ACCESS_CONTROL_ALLOW_HEADERS)
1042            .and_then(|value| value.to_str().ok())
1043            .expect("successful preflight must advertise allowed headers")
1044            .to_ascii_lowercase();
1045        assert!(allowed
1046            .split(',')
1047            .any(|value| value.trim() == "authorization"));
1048        assert!(allowed.split(',').any(|value| value.trim() == "dpop"));
1049    }
1050
1051    #[tokio::test]
1052    async fn preflight_rejects_unlisted_header() {
1053        let response = response_for(
1054            &CorsConfig::default(),
1055            Method::OPTIONS,
1056            "https://third-party.example",
1057            Some("POST"),
1058            Some("x-not-allowed"),
1059        )
1060        .await;
1061        let allowed = response
1062            .headers()
1063            .get(header::ACCESS_CONTROL_ALLOW_HEADERS)
1064            .and_then(|value| value.to_str().ok())
1065            .expect("explicit policy advertises its configured allowlist")
1066            .to_ascii_lowercase();
1067        assert!(
1068            !allowed
1069                .split(',')
1070                .any(|value| value.trim() == "x-not-allowed"),
1071            "product API header policy must not admit unlisted request headers"
1072        );
1073    }
1074
1075    #[tokio::test]
1076    async fn auth_challenge_headers_are_exposed() {
1077        let response = response_for(
1078            &CorsConfig::default(),
1079            Method::GET,
1080            "https://third-party.example",
1081            None,
1082            None,
1083        )
1084        .await;
1085        let exposed = response
1086            .headers()
1087            .get(header::ACCESS_CONTROL_EXPOSE_HEADERS)
1088            .and_then(|value| value.to_str().ok())
1089            .expect("cross-origin clients need readable auth challenges")
1090            .to_ascii_lowercase();
1091        assert!(exposed
1092            .split(',')
1093            .any(|value| value.trim() == "www-authenticate"));
1094        assert!(exposed.split(',').any(|value| value.trim() == "dpop-nonce"));
1095    }
1096
1097    #[tokio::test]
1098    async fn permissive_headers_remain_confined_to_did_documents() {
1099        let did_response = response_for(
1100            &CorsConfig::did_document(),
1101            Method::OPTIONS,
1102            "https://third-party.example",
1103            Some("GET"),
1104            Some("x-did-extension"),
1105        )
1106        .await;
1107        assert_eq!(
1108            did_response
1109                .headers()
1110                .get(header::ACCESS_CONTROL_ALLOW_HEADERS)
1111                .and_then(|value| value.to_str().ok()),
1112            Some("*")
1113        );
1114
1115        let product_response = response_for(
1116            &CorsConfig::default(),
1117            Method::OPTIONS,
1118            "https://third-party.example",
1119            Some("GET"),
1120            Some("x-did-extension"),
1121        )
1122        .await;
1123        let product_headers = product_response
1124            .headers()
1125            .get(header::ACCESS_CONTROL_ALLOW_HEADERS)
1126            .and_then(|value| value.to_str().ok())
1127            .expect("product API advertises its explicit allowlist")
1128            .to_ascii_lowercase();
1129        assert_ne!(product_headers, "*");
1130        assert!(!product_headers
1131            .split(',')
1132            .any(|value| value.trim() == "x-did-extension"));
1133    }
1134
1135    #[tokio::test]
1136    async fn public_and_default_layers_share_wildcard_without_credentials() {
1137        for config in [CorsConfig::default(), CorsConfig::public()] {
1138            let response = response_for(
1139                &config,
1140                Method::GET,
1141                "https://third-party.example",
1142                None,
1143                None,
1144            )
1145            .await;
1146            assert_eq!(
1147                response
1148                    .headers()
1149                    .get(header::ACCESS_CONTROL_ALLOW_ORIGIN)
1150                    .and_then(|value| value.to_str().ok()),
1151                Some("*")
1152            );
1153            assert!(!response
1154                .headers()
1155                .contains_key(header::ACCESS_CONTROL_ALLOW_CREDENTIALS));
1156        }
1157    }
1158}
1159
1160#[cfg(test)]
1161#[allow(clippy::expect_used, clippy::unwrap_used)]
1162mod tests {
1163    use super::*;
1164
1165    #[tokio::test]
1166    async fn hosted_did_resource_auth_reaches_route_only_with_matching_signed_tenant() {
1167        use axum::{
1168            body::Body, http::Request as HttpRequest, middleware, routing::get, Extension, Router,
1169        };
1170        use hyprstream_rpc::auth::{
1171            global_credential_revocation_store, set_global_credential_revocation_store,
1172            CompositeKeyPair, CompositeKeySet, CompositePairRole, CompositePairState,
1173            InMemoryCredentialRevocationStore,
1174        };
1175        use std::sync::atomic::{AtomicUsize, Ordering};
1176        use tower::ServiceExt;
1177
1178        let issuer = "https://oauth.publisher.test";
1179        let resource = "https://resource.publisher.test";
1180        let did = "did:web:canary-agent.publisher.staging.lab.hyprstream.com";
1181        let tenant = "publisher.staging.lab.hyprstream.com";
1182        let ca = ed25519_dalek::SigningKey::from_bytes(&[0x31; 32]);
1183        let ed = ed25519_dalek::SigningKey::from_bytes(&[0x32; 32]);
1184        let (pq, pq_vk) = hyprstream_rpc::crypto::pq::ml_dsa_generate_keypair();
1185        let pair = CompositeKeyPair::verifying(
1186            jwt::composite_kid(&pq_vk, &ed.verifying_key()),
1187            pq_vk,
1188            ed.verifying_key(),
1189            CompositePairRole::OAuth,
1190            CompositePairState::Active,
1191            0,
1192            i64::MAX,
1193        );
1194        let published = Arc::new(CompositeKeySet::default());
1195        published
1196            .publish(1, "hosted-did-resource-test".to_owned(), vec![pair])
1197            .unwrap();
1198        let mut state = ResourceAuthState::new(
1199            ca.verifying_key(),
1200            resource.to_owned(),
1201            issuer.to_owned(),
1202            Arc::new(crate::auth::FederationKeyResolver::new(&Default::default())),
1203        );
1204        state.composite_key_set = published;
1205        if global_credential_revocation_store().is_none() {
1206            let _ = set_global_credential_revocation_store(Arc::new(
1207                InMemoryCredentialRevocationStore::new(),
1208            ));
1209        }
1210        let reached = Arc::new(AtomicUsize::new(0));
1211        let probe = Arc::clone(&reached);
1212        let app = Router::new()
1213            .route(
1214                "/oai/v1/models",
1215                get(move |Extension(user): Extension<AuthenticatedUser>| {
1216                    let probe = Arc::clone(&probe);
1217                    async move {
1218                        probe.fetch_add(1, Ordering::SeqCst);
1219                        assert_eq!(user.user, did);
1220                        assert_eq!(user.authorization_domain().unwrap(), tenant);
1221                        StatusCode::OK
1222                    }
1223                }),
1224            )
1225            .layer(middleware::from_fn_with_state(state, auth_middleware));
1226        let now = chrono::Utc::now().timestamp();
1227        let base = jwt::Claims::new(did.to_owned(), now, now + 300)
1228            .with_issuer(issuer.to_owned())
1229            .with_audience(Some(resource.to_owned()))
1230            .with_client_id("hosted-client")
1231            .with_tenant(tenant.to_owned())
1232            .with_jti();
1233        let request = |claims: jwt::Claims| {
1234            let token = jwt::encode_composite_ml_dsa_65_ed25519(&claims, &pq, &ed);
1235            HttpRequest::get("/oai/v1/models")
1236                .header(header::AUTHORIZATION, format!("Bearer {token}"))
1237                .body(Body::empty())
1238                .unwrap()
1239        };
1240        assert_eq!(
1241            app.clone()
1242                .oneshot(request(base.clone()))
1243                .await
1244                .unwrap()
1245                .status(),
1246            StatusCode::OK
1247        );
1248        for invalid in [
1249            base.clone()
1250                .with_tenant("other.staging.lab.hyprstream.com".to_owned()),
1251            base.clone().with_issuer("https://foreign.test".to_owned()),
1252            jwt::Claims::new(did.to_owned(), now, now + 300)
1253                .with_issuer(issuer.to_owned())
1254                .with_audience(Some(resource.to_owned()))
1255                .with_client_id("hosted-client")
1256                .with_jti(),
1257            jwt::Claims::new(
1258                "did:web:canary-agent.publisher.staging.lab.hyprstream.com:users".to_owned(),
1259                now,
1260                now + 300,
1261            )
1262            .with_issuer(issuer.to_owned())
1263            .with_audience(Some(resource.to_owned()))
1264            .with_client_id("hosted-client")
1265            .with_tenant(tenant.to_owned())
1266            .with_jti(),
1267            jwt::Claims::new(
1268                "did:web:canary-agent.publisher.staging.lab.hyprstream.com://evil".to_owned(),
1269                now,
1270                now + 300,
1271            )
1272            .with_issuer(issuer.to_owned())
1273            .with_audience(Some(resource.to_owned()))
1274            .with_client_id("hosted-client")
1275            .with_tenant(tenant.to_owned())
1276            .with_jti(),
1277        ] {
1278            assert_ne!(
1279                app.clone()
1280                    .oneshot(request(invalid))
1281                    .await
1282                    .unwrap()
1283                    .status(),
1284                StatusCode::OK
1285            );
1286        }
1287        assert_eq!(reached.load(Ordering::SeqCst), 1);
1288    }
1289
1290    #[test]
1291    fn http_domain_uses_verified_hosted_account_tenant_not_subject() {
1292        let alice = AuthenticatedUser {
1293            user: "did:web:alice.accounts.example".to_owned(),
1294            verified_tenant: Some("acme.example".to_owned()),
1295            token: None,
1296            exp: None,
1297        };
1298        let bob = AuthenticatedUser {
1299            user: "did:web:bob.accounts.example".to_owned(),
1300            verified_tenant: Some("acme.example".to_owned()),
1301            token: None,
1302            exp: None,
1303        };
1304
1305        assert_eq!(alice.authorization_domain().unwrap(), "acme.example");
1306        assert_eq!(alice.authorization_domain(), bob.authorization_domain());
1307        assert_ne!(alice.authorization_domain().unwrap(), alice.user);
1308    }
1309
1310    #[test]
1311    fn http_domain_fails_closed_except_for_tenantless_services() {
1312        for verified_tenant in [
1313            None,
1314            Some(String::new()),
1315            Some("*".to_owned()),
1316            Some(" acme.example".to_owned()),
1317            Some("did:web:alice.acme.example".to_owned()),
1318            Some("../acme".to_owned()),
1319        ] {
1320            let user = AuthenticatedUser {
1321                user: "did:web:alice.accounts.example".to_owned(),
1322                verified_tenant,
1323                token: None,
1324                exp: None,
1325            };
1326            assert!(user.authorization_domain().is_err());
1327        }
1328
1329        let service = AuthenticatedUser {
1330            user: "service:oauth".to_owned(),
1331            verified_tenant: None,
1332            token: None,
1333            exp: None,
1334        };
1335        assert_eq!(service.authorization_domain().unwrap(), "*");
1336
1337        let malformed_service = AuthenticatedUser {
1338            user: "service:oauth".to_owned(),
1339            verified_tenant: Some("*".to_owned()),
1340            token: None,
1341            exp: None,
1342        };
1343        assert!(malformed_service.authorization_domain().is_err());
1344    }
1345
1346    #[test]
1347    fn federated_tenant_assertion_cannot_select_http_domain() {
1348        let mut claims = jwt::Claims::new("service:forged".to_owned(), 1, 2)
1349            .with_issuer("https://idp.example".to_owned())
1350            .with_tenant("victim.example".to_owned());
1351        claims.strip_federated_tenant(&["https://oauth.local"]);
1352        let subject = claims.subject(&["https://oauth.local"]);
1353        let user = AuthenticatedUser {
1354            user: subject.name().unwrap().to_owned(),
1355            verified_tenant: claims.tenant,
1356            token: None,
1357            exp: None,
1358        };
1359        assert!(user.authorization_domain().is_err());
1360        assert!(!user.user.starts_with("service:"));
1361    }
1362
1363    #[tokio::test]
1364    async fn http_policy_domain_blocks_cross_tenant_replay() {
1365        let policy = crate::auth::PolicyManager::new_in_memory().await.unwrap();
1366        policy
1367            .add_policy_with_domain(
1368                "did:web:alice.accounts.example",
1369                "tenant-a.example",
1370                "model:qwen",
1371                "infer.generate",
1372                "allow",
1373            )
1374            .await
1375            .unwrap();
1376
1377        let tenant_a = AuthenticatedUser {
1378            user: "did:web:alice.accounts.example".to_owned(),
1379            verified_tenant: Some("tenant-a.example".to_owned()),
1380            token: None,
1381            exp: None,
1382        };
1383        let replayed_in_tenant_b = AuthenticatedUser {
1384            user: tenant_a.user.clone(),
1385            verified_tenant: Some("tenant-b.example".to_owned()),
1386            token: None,
1387            exp: None,
1388        };
1389
1390        assert!(
1391            policy
1392                .check_with_domain(
1393                    &tenant_a.user,
1394                    &tenant_a.authorization_domain().unwrap(),
1395                    "model:qwen",
1396                    "infer.generate",
1397                )
1398                .await
1399        );
1400        assert!(
1401            !policy
1402                .check_with_domain(
1403                    &replayed_in_tenant_b.user,
1404                    &replayed_in_tenant_b.authorization_domain().unwrap(),
1405                    "model:qwen",
1406                    "infer.generate",
1407                )
1408                .await
1409        );
1410    }
1411
1412    #[test]
1413    fn test_extract_iss_from_token() {
1414        use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine};
1415
1416        // Craft a JWT with iss in payload: header.payload.sig
1417        // payload = base64url({"iss":"https://node-a","sub":"alice","exp":9999999999,"iat":0})
1418        let payload = URL_SAFE_NO_PAD
1419            .encode(r#"{"iss":"https://node-a","sub":"alice","exp":9999999999,"iat":0}"#);
1420        let token = format!("eyJ0eXAiOiJKV1QiLCJhbGciOiJFZERTQSJ9.{}.fakesig", payload);
1421        assert_eq!(extract_iss_from_token(&token), "https://node-a");
1422
1423        // Token without iss
1424        let payload2 = URL_SAFE_NO_PAD.encode(r#"{"sub":"alice","exp":9999999999,"iat":0}"#);
1425        let token2 = format!("eyJhbGciOiJFZERTQSJ9.{}.fakesig", payload2);
1426        assert_eq!(extract_iss_from_token(&token2), "");
1427
1428        // Garbage input
1429        assert_eq!(extract_iss_from_token("notavalidtoken"), "");
1430    }
1431}
1432
1433/// Rotation/JWKS-aware local-token validation (#777).
1434///
1435/// Proves `decode_local_multi_key` accepts a token signed by ANY currently
1436/// published key (CA or rotation slot) and rejects unpublished keys / wrong
1437/// audience, and that the shared jti-revocation check still rejects a
1438/// validly-decoded token.
1439#[cfg(test)]
1440#[allow(clippy::unwrap_used, clippy::expect_used)]
1441mod rotation_aware_tests {
1442    use super::*;
1443    use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine as _};
1444    use ed25519_dalek::{Signer as _, SigningKey};
1445
1446    const AUD: &str = "https://node-a/resource";
1447
1448    fn now() -> i64 {
1449        chrono::Utc::now().timestamp()
1450    }
1451
1452    fn new_key() -> SigningKey {
1453        SigningKey::generate(&mut rand::rngs::OsRng)
1454    }
1455
1456    /// Build a locally-issued at+JWT signed by `key`, with the given audience and
1457    /// optional explicit jti (`jwt::encode` auto-assigns a random jti otherwise).
1458    fn signed_token(key: &SigningKey, aud: &str, jti: Option<&str>) -> String {
1459        signed_token_with_type(key, aud, jti, "at+jwt")
1460    }
1461
1462    fn signed_token_with_type(key: &SigningKey, aud: &str, jti: Option<&str>, typ: &str) -> String {
1463        let n = now();
1464        let mut claims =
1465            jwt::Claims::new("alice".to_owned(), n, n + 3600).with_audience(Some(aud.to_owned()));
1466        if let Some(j) = jti {
1467            claims.jti = Some(j.to_owned());
1468        }
1469        let header = serde_json::json!({
1470            "alg": "EdDSA",
1471            "typ": typ,
1472            "kid": ed25519_kid(&key.verifying_key()),
1473        });
1474        let input = format!(
1475            "{}.{}",
1476            URL_SAFE_NO_PAD.encode(serde_json::to_vec(&header).unwrap()),
1477            URL_SAFE_NO_PAD.encode(serde_json::to_vec(&claims).unwrap()),
1478        );
1479        format!(
1480            "{input}.{}",
1481            URL_SAFE_NO_PAD.encode(key.sign(input.as_bytes()).to_bytes())
1482        )
1483    }
1484
1485    #[test]
1486    fn federate_tui_credentials_are_never_http_resource_credentials() {
1487        // Marker path: any TUI marker classifies, no reservation needed.
1488        let mut claims = jwt::Claims::new("did:plc:abc".into(), 1, 2);
1489        claims.iss = "https://cell.test".into();
1490        let issuers = ["https://cell.test"];
1491        assert!(reject_federate_tui_http(&claims, &issuers).is_ok());
1492        claims.hs_tui_profile = Some("federate-tui-v1".into());
1493        assert!(reject_federate_tui_http(&claims, &issuers).is_err());
1494        // Pin path: the deployment reservation classifies by (local iss,
1495        // configured client id) with every marker stripped. Install-once is
1496        // idempotent for the same value (another test may have installed it).
1497        if hyprstream_rpc::auth::federate_tui_class_client().is_none() {
1498            hyprstream_rpc::auth::install_federate_tui_class_client(Some("hyprstream-tui-staging"))
1499                .expect("install class reservation");
1500        }
1501        let mut pinned = jwt::Claims::new("did:plc:abc".into(), 1, 2);
1502        pinned.iss = "https://cell.test".into();
1503        pinned.client_id = Some("hyprstream-tui-staging".into());
1504        assert!(reject_federate_tui_http(&pinned, &issuers).is_err());
1505        // A different local client id stays a generic HTTP credential.
1506        pinned.client_id = Some("ordinary-local-client".into());
1507        assert!(reject_federate_tui_http(&pinned, &issuers).is_ok());
1508    }
1509
1510    #[test]
1511    fn ordinary_eddsa_verifier_accepts_exact_rfc9068_type_forms() {
1512        let ca = new_key();
1513        let rotation = new_key();
1514        let published = [rotation.verifying_key()];
1515
1516        for typ in hyprstream_rpc::auth::RFC9068_ACCESS_TOKEN_TYPES {
1517            let token = signed_token_with_type(&rotation, AUD, None, typ);
1518            let claims = decode_local_multi_key(
1519                &token,
1520                &ca.verifying_key(),
1521                &published,
1522                &[],
1523                Some(AUD),
1524                true,
1525            )
1526            .unwrap();
1527            assert_eq!(claims.sub, "alice");
1528        }
1529
1530        for typ in [
1531            "",
1532            "AT+JWT",
1533            "at+JWT",
1534            " at+jwt",
1535            "at+jwt ",
1536            "Application/at+jwt",
1537            "application/AT+JWT",
1538            "application/at+jwt ",
1539            "JWT",
1540            "wit+jwt",
1541        ] {
1542            let token = signed_token_with_type(&rotation, AUD, None, typ);
1543            assert!(
1544                decode_local_multi_key(
1545                    &token,
1546                    &ca.verifying_key(),
1547                    &published,
1548                    &[],
1549                    Some(AUD),
1550                    true,
1551                )
1552                .is_err(),
1553                "accepted non-RFC 9068 access-token type {typ:?}"
1554            );
1555        }
1556    }
1557
1558    #[test]
1559    fn rotation_active_slot_verifies() {
1560        // Token signed by a rotation slot that is NOT the CA key — this is the
1561        // exact case that 401'd before #777.
1562        let ca = new_key();
1563        let rotation = new_key();
1564        let token = signed_token(&rotation, AUD, None);
1565        let published = vec![rotation.verifying_key()];
1566
1567        let claims = decode_local_multi_key(
1568            &token,
1569            &ca.verifying_key(),
1570            &published,
1571            &[],
1572            Some(AUD),
1573            true,
1574        )
1575        .unwrap();
1576        assert_eq!(claims.sub, "alice");
1577    }
1578
1579    #[test]
1580    fn ca_key_signed_token_still_verifies() {
1581        // CA-signed token must still verify — even with no rotation slots published.
1582        let ca = new_key();
1583        let token = signed_token(&ca, AUD, None);
1584
1585        let claims =
1586            decode_local_multi_key(&token, &ca.verifying_key(), &[], &[], Some(AUD), true).unwrap();
1587        assert_eq!(claims.sub, "alice");
1588    }
1589
1590    #[test]
1591    fn unpublished_random_key_rejected() {
1592        // A token signed by a key the node never published must be rejected — the
1593        // core security invariant (only trusted, published keys are ever tried).
1594        let ca = new_key();
1595        let rotation = new_key();
1596        let attacker = new_key();
1597        let token = signed_token(&attacker, AUD, None);
1598        let published = vec![rotation.verifying_key()];
1599
1600        let err = decode_local_multi_key(
1601            &token,
1602            &ca.verifying_key(),
1603            &published,
1604            &[],
1605            Some(AUD),
1606            true,
1607        )
1608        .unwrap_err();
1609        assert_eq!(err, "JWT validation failed");
1610    }
1611
1612    #[test]
1613    fn wrong_audience_rejected() {
1614        // Correct (published) key but wrong audience → still rejected. Strict
1615        // local-issuer audience validation is unchanged.
1616        let ca = new_key();
1617        let rotation = new_key();
1618        let token = signed_token(&rotation, "https://evil/other", None);
1619        let published = vec![rotation.verifying_key()];
1620
1621        let err = decode_local_multi_key(
1622            &token,
1623            &ca.verifying_key(),
1624            &published,
1625            &[],
1626            Some(AUD),
1627            true,
1628        )
1629        .unwrap_err();
1630        assert_eq!(err, "JWT validation failed");
1631    }
1632
1633    #[tokio::test]
1634    async fn revoked_jti_still_rejected() {
1635        // A rotation-signed token decodes cleanly, but the global
1636        // credential-revocation store check still rejects it.
1637        use hyprstream_rpc::auth::{
1638            global_credential_revocation_store, set_global_credential_revocation_store,
1639            CredentialId, InMemoryCredentialRevocationStore,
1640        };
1641
1642        let ca = new_key();
1643        let rotation = new_key();
1644        let token = signed_token(&rotation, AUD, Some("jti-777"));
1645        let published = vec![rotation.verifying_key()];
1646
1647        let claims = decode_local_multi_key(
1648            &token,
1649            &ca.verifying_key(),
1650            &published,
1651            &[],
1652            Some(AUD),
1653            true,
1654        )
1655        .unwrap();
1656        assert_eq!(claims.jti.as_deref(), Some("jti-777"));
1657
1658        // Ensure the global store is set.
1659        if global_credential_revocation_store().is_none() {
1660            let _ = set_global_credential_revocation_store(std::sync::Arc::new(
1661                InMemoryCredentialRevocationStore::new(),
1662            ));
1663        }
1664        let store = global_credential_revocation_store().unwrap();
1665        let issuer = claims.iss.as_str();
1666        store
1667            .revoke_credential(CredentialId::jwt(issuer, "jti-777"), now() + 3600)
1668            .await
1669            .unwrap();
1670        // This mirrors the exact post-decode check in `verify_token_claims`.
1671        assert!(
1672            store
1673                .is_revoked(&CredentialId::jwt(issuer, claims.jti.as_deref().unwrap()))
1674                .await
1675        );
1676    }
1677
1678    #[test]
1679    fn kid_hint_finds_rotation_slot_behind_ca() {
1680        // The rotation slot is listed after the CA candidate; the kid-preference
1681        // reorder must still locate and verify against it (it also verifies
1682        // without any kid, since every candidate is tried).
1683        let ca = new_key();
1684        let rotation = new_key();
1685        let token = signed_token(&rotation, AUD, None);
1686        // Token header carries the rotation key's RFC 7638 thumbprint as kid.
1687        assert_eq!(
1688            extract_kid_from_token(&token).as_deref(),
1689            Some(ed25519_kid(&rotation.verifying_key()).as_str()),
1690        );
1691        let published = vec![rotation.verifying_key()];
1692
1693        let claims = decode_local_multi_key(
1694            &token,
1695            &ca.verifying_key(),
1696            &published,
1697            &[],
1698            Some(AUD),
1699            true,
1700        )
1701        .unwrap();
1702        assert_eq!(claims.sub, "alice");
1703    }
1704}
1705
1706/// Composite (`ML-DSA-65-Ed25519`) local-token verification (#1038).
1707///
1708/// Exercises the composite branch of `decode_local_multi_key` end-to-end:
1709/// happy path (active pair + via-CA-ed pair), both wrong-half rejections,
1710/// header confusion, exact-pair rotation, audience/issuer/time/JTI rejection,
1711/// half stripping, and policy-controlled plain `EdDSA` compatibility.
1712#[cfg(test)]
1713#[allow(clippy::unwrap_used, clippy::expect_used)]
1714mod composite_aware_tests {
1715    use super::*;
1716    use crate::auth::jwt::encode_composite_ml_dsa_65_ed25519;
1717    use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine};
1718    use ed25519_dalek::SigningKey;
1719
1720    const AUD: &str = "https://node-a/resource";
1721
1722    fn now() -> i64 {
1723        chrono::Utc::now().timestamp()
1724    }
1725
1726    fn new_ed_key() -> SigningKey {
1727        SigningKey::generate(&mut rand::rngs::OsRng)
1728    }
1729
1730    fn new_ml_dsa() -> (
1731        hyprstream_rpc::crypto::pq::MlDsaSigningKey,
1732        hyprstream_rpc::crypto::pq::MlDsaVerifyingKey,
1733    ) {
1734        hyprstream_rpc::crypto::pq::ml_dsa_generate_keypair()
1735    }
1736
1737    fn published_pair(
1738        ml_dsa: hyprstream_rpc::crypto::pq::MlDsaVerifyingKey,
1739        ed25519: ed25519_dalek::VerifyingKey,
1740    ) -> hyprstream_rpc::auth::CompositeKeyPair {
1741        let kid = crate::auth::jwt::composite_kid(&ml_dsa, &ed25519);
1742        hyprstream_rpc::auth::CompositeKeyPair::verifying(
1743            kid,
1744            ml_dsa,
1745            ed25519,
1746            hyprstream_rpc::auth::CompositePairRole::OAuth,
1747            hyprstream_rpc::auth::CompositePairState::Drain,
1748            0,
1749            i64::MAX,
1750        )
1751    }
1752
1753    /// A composite at+JWT signed by `(pq, ed)`, audience `aud`.
1754    fn composite_token(
1755        pq: &hyprstream_rpc::crypto::pq::MlDsaSigningKey,
1756        ed: &SigningKey,
1757        aud: &str,
1758    ) -> String {
1759        let n = now();
1760        let claims =
1761            jwt::Claims::new("alice".to_owned(), n, n + 3600).with_audience(Some(aud.to_owned()));
1762        encode_composite_ml_dsa_65_ed25519(&claims, pq, ed)
1763    }
1764
1765    fn composite_token_with_header(
1766        pq: &hyprstream_rpc::crypto::pq::MlDsaSigningKey,
1767        ed: &SigningKey,
1768        claims: &jwt::Claims,
1769        alg: &str,
1770        typ: &str,
1771        kid: &str,
1772    ) -> String {
1773        use ed25519_dalek::Signer as _;
1774        let header = serde_json::json!({ "alg": alg, "typ": typ, "kid": kid });
1775        let header_b64 = URL_SAFE_NO_PAD.encode(serde_json::to_vec(&header).unwrap());
1776        let payload_b64 = URL_SAFE_NO_PAD.encode(serde_json::to_vec(claims).unwrap());
1777        let signing_input = format!("{header_b64}.{payload_b64}");
1778        let mut signature = hyprstream_rpc::crypto::pq::ml_dsa_sign(pq, signing_input.as_bytes());
1779        signature.extend_from_slice(&ed.sign(signing_input.as_bytes()).to_bytes());
1780        format!("{signing_input}.{}", URL_SAFE_NO_PAD.encode(signature))
1781    }
1782
1783    #[tokio::test]
1784    async fn key_bound_http_resource_tokens_require_holder_proof() {
1785        use axum::{
1786            body::Body, http::Request as HttpRequest, middleware, routing::get, Extension, Router,
1787        };
1788        use ed25519_dalek::Signer as _;
1789        use hyprstream_rpc::auth::{
1790            global_credential_revocation_store, set_global_credential_revocation_store,
1791            CompositeKeySet, InMemoryCredentialRevocationStore,
1792        };
1793        use sha2::{Digest as _, Sha256};
1794        use std::sync::atomic::{AtomicUsize, Ordering};
1795        use tower::ServiceExt;
1796
1797        let issuer = "https://issuer.test";
1798        let resource = "https://resource.test";
1799        let ca = new_ed_key();
1800        let (pq, pq_vk) = new_ml_dsa();
1801        let ed = new_ed_key();
1802        let pair = published_pair(pq_vk, ed.verifying_key());
1803        let published = Arc::new(CompositeKeySet::default());
1804        published
1805            .publish(1, "http-holder-test".to_owned(), vec![pair])
1806            .unwrap();
1807        let mut state = ResourceAuthState::new(
1808            ca.verifying_key(),
1809            resource.to_owned(),
1810            issuer.to_owned(),
1811            Arc::new(crate::auth::FederationKeyResolver::new(&Default::default())),
1812        );
1813        state.composite_key_set = published;
1814        if global_credential_revocation_store().is_none() {
1815            let _ = set_global_credential_revocation_store(Arc::new(
1816                InMemoryCredentialRevocationStore::new(),
1817            ));
1818        }
1819        let holder = new_ed_key();
1820        let base = jwt::Claims::new("alice".to_owned(), now(), now() + 3600)
1821            .with_issuer(issuer.to_owned())
1822            .with_audience(Some(resource.to_owned()))
1823            .with_tenant("fixture-tenant".to_owned())
1824            .with_client_id("oauth-client")
1825            .with_scope(Some("read:registry:*".to_owned()));
1826        let (holder_pq_sk, _) = new_ml_dsa();
1827        let holder_ed = holder.verifying_key();
1828        let holder_suite = URL_SAFE_NO_PAD.encode(hyprstream_rpc::auth::signer_suite_thumbprint(
1829            hyprstream_rpc::auth::SUITE_HYBRID_ED25519_MLDSA65,
1830            &[
1831                holder_ed.as_bytes(),
1832                &hyprstream_rpc::crypto::pq::ml_dsa_sk_to_vk_bytes(&holder_pq_sk),
1833            ],
1834        ));
1835        let key_bound = encode_composite_ml_dsa_65_ed25519(
1836            &base
1837                .clone()
1838                .with_cnf_jwk(holder_ed.as_bytes())
1839                .with_cnf_hs_signer_suite(holder_suite),
1840            &pq,
1841            &ed,
1842        );
1843        // A valid token and grant must be rejected before the route publishes
1844        // an HTTP identity when the original holder supplied no key proof.
1845        let invoked = Arc::new(AtomicUsize::new(0));
1846        let probe = Arc::clone(&invoked);
1847        let app = Router::new()
1848            .route(
1849                "/oai/v1/models",
1850                get(move |Extension(identity): Extension<AuthenticatedUser>| {
1851                    let probe = Arc::clone(&probe);
1852                    async move {
1853                        probe.fetch_add(1, Ordering::SeqCst);
1854                        assert_eq!(identity.user, "alice");
1855                        StatusCode::OK
1856                    }
1857                }),
1858            )
1859            .layer(middleware::from_fn_with_state(state, auth_middleware));
1860        let request = |scheme: &str, token: &str, proof: Option<&str>| {
1861            let mut builder = HttpRequest::get("/oai/v1/models")
1862                .header(header::AUTHORIZATION, format!("{scheme} {token}"));
1863            if let Some(proof) = proof {
1864                builder = builder.header("DPoP", proof);
1865            }
1866            builder.body(Body::empty()).unwrap()
1867        };
1868        let response = app
1869            .clone()
1870            .oneshot(request("Bearer", &key_bound, None))
1871            .await
1872            .unwrap();
1873        assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
1874        assert_eq!(invoked.load(Ordering::SeqCst), 0);
1875        let unbound = encode_composite_ml_dsa_65_ed25519(&base, &pq, &ed);
1876        let response = app
1877            .clone()
1878            .oneshot(request("Bearer", &unbound, None))
1879            .await
1880            .unwrap();
1881        assert_eq!(response.status(), StatusCode::OK);
1882        assert_eq!(invoked.load(Ordering::SeqCst), 1);
1883
1884        let dpop_holder = new_ed_key();
1885        let dpop = encode_composite_ml_dsa_65_ed25519(
1886            &base.with_cnf_jkt(dpop_holder.verifying_key().as_bytes()),
1887            &pq,
1888            &ed,
1889        );
1890        let proof_for = |signer: &SigningKey, nonce: &str| {
1891            let header = serde_json::json!({
1892                "typ": "dpop+jwt", "alg": "EdDSA",
1893                "jwk": { "kty": "OKP", "crv": "Ed25519",
1894                    "x": URL_SAFE_NO_PAD.encode(signer.verifying_key().as_bytes()) }
1895            });
1896            let payload = serde_json::json!({
1897                "jti": nonce, "htm": "GET", "htu": "https://resource.test/oai/v1/models",
1898                "iat": now(), "ath": URL_SAFE_NO_PAD.encode(Sha256::digest(dpop.as_bytes()))
1899            });
1900            let input = format!(
1901                "{}.{}",
1902                URL_SAFE_NO_PAD.encode(serde_json::to_vec(&header).unwrap()),
1903                URL_SAFE_NO_PAD.encode(serde_json::to_vec(&payload).unwrap())
1904            );
1905            format!(
1906                "{input}.{}",
1907                URL_SAFE_NO_PAD.encode(signer.sign(input.as_bytes()).to_bytes())
1908            )
1909        };
1910        let good_proof = proof_for(&dpop_holder, "good-proof");
1911        let wrong_proof = proof_for(&holder, "wrong-proof");
1912        for (scheme, proof) in [
1913            ("Bearer", Some(good_proof.as_str())),
1914            ("DPoP", None),
1915            ("DPoP", Some(wrong_proof.as_str())),
1916        ] {
1917            let response = app
1918                .clone()
1919                .oneshot(request(scheme, &dpop, proof))
1920                .await
1921                .unwrap();
1922            assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
1923        }
1924        let response = app
1925            .clone()
1926            .oneshot(request("DPoP", &dpop, Some(&good_proof)))
1927            .await
1928            .unwrap();
1929        assert_eq!(response.status(), StatusCode::OK);
1930        assert_eq!(invoked.load(Ordering::SeqCst), 2);
1931    }
1932
1933    #[test]
1934    fn composite_active_pair_verifies() {
1935        // The common post-#574 case: token minted by the active (ML-DSA, Ed25519)
1936        // pair the node publishes. This is the exact case that 401'd before #1038.
1937        let ca = new_ed_key();
1938        let (pq, pq_vk) = new_ml_dsa();
1939        let active = new_ed_key();
1940        let published_ed = vec![active.verifying_key()];
1941        let pairs = [published_pair(pq_vk, active.verifying_key())];
1942        let claims = jwt::Claims::new("alice".to_owned(), now(), now() + 3600)
1943            .with_audience(Some(AUD.to_owned()));
1944
1945        for typ in hyprstream_rpc::auth::RFC9068_ACCESS_TOKEN_TYPES {
1946            let token = composite_token_with_header(
1947                &pq,
1948                &active,
1949                &claims,
1950                "ML-DSA-65-Ed25519",
1951                typ,
1952                pairs[0].kid(),
1953            );
1954            let verified = decode_local_multi_key(
1955                &token,
1956                &ca.verifying_key(),
1957                &published_ed,
1958                &pairs,
1959                Some(AUD),
1960                false,
1961            )
1962            .unwrap();
1963            assert_eq!(verified.sub, "alice");
1964        }
1965    }
1966
1967    #[test]
1968    fn composite_verifies_via_ca_ed_half() {
1969        // No Ed25519 rotation slots published — only the CA key. A composite
1970        // token signed with the CA Ed25519 half verifies through the CA entry.
1971        let ca = new_ed_key();
1972        let (pq, pq_vk) = new_ml_dsa();
1973        let token = composite_token(&pq, &ca, AUD);
1974        let pairs = [published_pair(pq_vk, ca.verifying_key())];
1975
1976        let claims =
1977            decode_local_multi_key(&token, &ca.verifying_key(), &[], &pairs, Some(AUD), false)
1978                .unwrap();
1979        assert_eq!(claims.sub, "alice");
1980    }
1981
1982    #[test]
1983    fn composite_wrong_pq_half_rejected() {
1984        // Correct Ed25519 half, wrong (unpublished) ML-DSA half → rejected.
1985        // The Ed25519 half alone can never verify a composite signature.
1986        let ca = new_ed_key();
1987        let (pq, _pq_vk) = new_ml_dsa();
1988        let (_other_pq, other_pq_vk) = new_ml_dsa();
1989        let active = new_ed_key();
1990        let token = composite_token(&pq, &active, AUD);
1991        let published_ed = vec![active.verifying_key()];
1992        let pairs = [published_pair(other_pq_vk, active.verifying_key())];
1993
1994        let err = decode_local_multi_key(
1995            &token,
1996            &ca.verifying_key(),
1997            &published_ed,
1998            &pairs,
1999            Some(AUD),
2000            false,
2001        )
2002        .unwrap_err();
2003        assert_eq!(err, "JWT validation failed");
2004    }
2005
2006    #[test]
2007    fn composite_wrong_ed25519_half_rejected() {
2008        // Correct ML-DSA half, wrong (unpublished) Ed25519 half → rejected.
2009        // The ML-DSA half alone can never verify a composite signature.
2010        let ca = new_ed_key();
2011        let (pq, pq_vk) = new_ml_dsa();
2012        let active = new_ed_key();
2013        let attacker = new_ed_key();
2014        let token = composite_token(&pq, &active, AUD);
2015        // Only the attacker's (unpublished) Ed25519 key is offered alongside CA.
2016        let published_ed = vec![attacker.verifying_key()];
2017        let pairs = [published_pair(pq_vk, attacker.verifying_key())];
2018
2019        let err = decode_local_multi_key(
2020            &token,
2021            &ca.verifying_key(),
2022            &published_ed,
2023            &pairs,
2024            Some(AUD),
2025            false,
2026        )
2027        .unwrap_err();
2028        assert_eq!(err, "JWT validation failed");
2029    }
2030
2031    #[test]
2032    fn composite_cross_paired_published_halves_rejected() {
2033        let ca = new_ed_key();
2034        let (pq_a, pq_a_vk) = new_ml_dsa();
2035        let (_pq_b, pq_b_vk) = new_ml_dsa();
2036        let ed_a = new_ed_key();
2037        let ed_b = new_ed_key();
2038        let cross_token = composite_token(&pq_a, &ed_b, AUD);
2039        let published = [
2040            published_pair(pq_a_vk, ed_a.verifying_key()),
2041            published_pair(pq_b_vk, ed_b.verifying_key()),
2042        ];
2043
2044        assert!(decode_local_multi_key(
2045            &cross_token,
2046            &ca.verifying_key(),
2047            &[ed_a.verifying_key(), ed_b.verifying_key()],
2048            &published,
2049            Some(AUD),
2050            false,
2051        )
2052        .is_err());
2053    }
2054
2055    #[test]
2056    fn composite_signed_header_mutations_rejected() {
2057        let ca = new_ed_key();
2058        let (pq, pq_vk) = new_ml_dsa();
2059        let ed = new_ed_key();
2060        let pair = published_pair(pq_vk, ed.verifying_key());
2061        let claims = jwt::Claims::new("alice".to_owned(), now(), now() + 3600)
2062            .with_audience(Some(AUD.to_owned()));
2063        let wrong_kid = "not-the-published-pair";
2064        for (alg, typ, kid) in [
2065            ("EdDSA", "at+jwt", pair.kid()),
2066            ("ML-DSA-65-Ed25519", "wit+jwt", pair.kid()),
2067            ("ML-DSA-65-Ed25519", "AT+JWT", pair.kid()),
2068            ("ML-DSA-65-Ed25519", "at+jwt ", pair.kid()),
2069            ("ML-DSA-65-Ed25519", "Application/at+jwt", pair.kid()),
2070            ("ML-DSA-65-Ed25519", "application/AT+JWT", pair.kid()),
2071            ("ML-DSA-65-Ed25519", "application/at+jwt ", pair.kid()),
2072            ("ML-DSA-65-Ed25519", "at+jwt", wrong_kid),
2073        ] {
2074            let token = composite_token_with_header(&pq, &ed, &claims, alg, typ, kid);
2075            assert!(
2076                decode_local_multi_key(
2077                    &token,
2078                    &ca.verifying_key(),
2079                    &[ed.verifying_key()],
2080                    std::slice::from_ref(&pair),
2081                    Some(AUD),
2082                    true,
2083                )
2084                .is_err(),
2085                "accepted altered header alg={alg} typ={typ} kid={kid}"
2086            );
2087        }
2088    }
2089
2090    #[test]
2091    fn composite_expiry_future_iat_and_missing_audience_rejected() {
2092        let ca = new_ed_key();
2093        let (pq, pq_vk) = new_ml_dsa();
2094        let ed = new_ed_key();
2095        let pair = published_pair(pq_vk, ed.verifying_key());
2096        let cases = [
2097            (
2098                "expired",
2099                jwt::Claims::new("expired".to_owned(), now() - 7200, now() - 10)
2100                    .with_audience(Some(AUD.to_owned())),
2101            ),
2102            (
2103                "future",
2104                jwt::Claims::new("future".to_owned(), now() + 120, now() + 3600)
2105                    .with_audience(Some(AUD.to_owned())),
2106            ),
2107            (
2108                "no-aud",
2109                jwt::Claims::new("no-aud".to_owned(), now(), now() + 3600),
2110            ),
2111        ];
2112        for (case, claims) in cases {
2113            let token = composite_token_with_header(
2114                &pq,
2115                &ed,
2116                &claims,
2117                "ML-DSA-65-Ed25519",
2118                "at+jwt",
2119                pair.kid(),
2120            );
2121            assert!(
2122                decode_local_multi_key(
2123                    &token,
2124                    &ca.verifying_key(),
2125                    &[ed.verifying_key()],
2126                    std::slice::from_ref(&pair),
2127                    Some(AUD),
2128                    false,
2129                )
2130                .is_err(),
2131                "accepted invalid {case} claims"
2132            );
2133        }
2134    }
2135
2136    #[test]
2137    fn composite_wrong_issuer_rejected_by_local_policy() {
2138        let ca = new_ed_key();
2139        let (pq, pq_vk) = new_ml_dsa();
2140        let ed = new_ed_key();
2141        let pair = published_pair(pq_vk, ed.verifying_key());
2142        let claims = jwt::Claims::new("alice".to_owned(), now(), now() + 3600)
2143            .with_issuer("https://other.example".to_owned())
2144            .with_audience(Some(AUD.to_owned()));
2145        let token = composite_token_with_header(
2146            &pq,
2147            &ed,
2148            &claims,
2149            "ML-DSA-65-Ed25519",
2150            "at+jwt",
2151            pair.kid(),
2152        );
2153        let verified = decode_local_multi_key(
2154            &token,
2155            &ca.verifying_key(),
2156            &[ed.verifying_key()],
2157            std::slice::from_ref(&pair),
2158            Some(AUD),
2159            false,
2160        )
2161        .unwrap();
2162        assert!(!local_issuer_matches(&verified, "https://node-a.example"));
2163    }
2164
2165    #[test]
2166    fn composite_half_signature_stripping_rejected() {
2167        let ca = new_ed_key();
2168        let (pq, pq_vk) = new_ml_dsa();
2169        let active = new_ed_key();
2170        let token = composite_token(&pq, &active, AUD);
2171        let published_ed = vec![active.verifying_key()];
2172        let pairs = [published_pair(pq_vk, active.verifying_key())];
2173
2174        // Sanity: the well-formed composite token verifies.
2175        decode_local_multi_key(
2176            &token,
2177            &ca.verifying_key(),
2178            &published_ed,
2179            &pairs,
2180            Some(AUD),
2181            false,
2182        )
2183        .unwrap();
2184
2185        let dot2 = token.rfind('.').unwrap();
2186        let sig_b64 = &token[dot2 + 1..];
2187        let sig_bytes = URL_SAFE_NO_PAD.decode(sig_b64).unwrap();
2188        for stripped in [&sig_bytes[..3309], &sig_bytes[3309..]] {
2189            let tampered = format!("{}.{}", &token[..dot2], URL_SAFE_NO_PAD.encode(stripped));
2190            assert!(decode_local_multi_key(
2191                &tampered,
2192                &ca.verifying_key(),
2193                &published_ed,
2194                &pairs,
2195                Some(AUD),
2196                false,
2197            )
2198            .is_err());
2199        }
2200    }
2201
2202    #[test]
2203    fn plain_eddsa_is_policy_controlled() {
2204        let ca = new_ed_key();
2205        let active = new_ed_key();
2206        let n = now();
2207        let claims =
2208            jwt::Claims::new("alice".to_owned(), n, n + 3600).with_audience(Some(AUD.to_owned()));
2209        let token = jwt::encode(&claims, &active);
2210        let published_ed = vec![active.verifying_key()];
2211        // Even with composite keys published, a plain EdDSA token routes to and
2212        // verifies via the plain Ed25519 branch.
2213        let (pq, pq_vk) = new_ml_dsa();
2214        let pairs = [published_pair(pq_vk, active.verifying_key())];
2215        let _ = pq;
2216        let claims = decode_local_multi_key(
2217            &token,
2218            &ca.verifying_key(),
2219            &published_ed,
2220            &pairs,
2221            Some(AUD),
2222            true,
2223        )
2224        .unwrap();
2225        assert_eq!(claims.sub, "alice");
2226
2227        assert!(decode_local_multi_key(
2228            &token,
2229            &ca.verifying_key(),
2230            &published_ed,
2231            &pairs,
2232            Some(AUD),
2233            false,
2234        )
2235        .is_err());
2236    }
2237
2238    #[tokio::test]
2239    async fn composite_jti_remains_subject_to_revocation() {
2240        use hyprstream_rpc::auth::{
2241            global_credential_revocation_store, set_global_credential_revocation_store,
2242            CredentialId, InMemoryCredentialRevocationStore,
2243        };
2244
2245        let ca = new_ed_key();
2246        let (pq, pq_vk) = new_ml_dsa();
2247        let ed = new_ed_key();
2248        let pair = published_pair(pq_vk, ed.verifying_key());
2249        let claims = jwt::Claims::new("alice".to_owned(), now(), now() + 3600)
2250            .with_audience(Some(AUD.to_owned()))
2251            .with_jti();
2252        let token = composite_token_with_header(
2253            &pq,
2254            &ed,
2255            &claims,
2256            "ML-DSA-65-Ed25519",
2257            "at+jwt",
2258            pair.kid(),
2259        );
2260        let verified = decode_local_multi_key(
2261            &token,
2262            &ca.verifying_key(),
2263            &[ed.verifying_key()],
2264            std::slice::from_ref(&pair),
2265            Some(AUD),
2266            false,
2267        )
2268        .unwrap();
2269        let jti = verified.jti.as_deref().unwrap();
2270        let issuer = verified.iss.as_str();
2271        if global_credential_revocation_store().is_none() {
2272            let _ = set_global_credential_revocation_store(std::sync::Arc::new(
2273                InMemoryCredentialRevocationStore::new(),
2274            ));
2275        }
2276        let store = global_credential_revocation_store().unwrap();
2277        store
2278            .revoke_credential(CredentialId::jwt(issuer, jti), verified.exp)
2279            .await
2280            .unwrap();
2281        assert!(store.is_revoked(&CredentialId::jwt(issuer, jti)).await);
2282    }
2283
2284    #[test]
2285    fn composite_wrong_audience_rejected() {
2286        // Correct published pair, wrong audience → rejected. Composite audience
2287        // validation is as strict as the plain path.
2288        let ca = new_ed_key();
2289        let (pq, pq_vk) = new_ml_dsa();
2290        let active = new_ed_key();
2291        let token = composite_token(&pq, &active, "https://evil/other");
2292        let published_ed = vec![active.verifying_key()];
2293        let pairs = [published_pair(pq_vk, active.verifying_key())];
2294
2295        let err = decode_local_multi_key(
2296            &token,
2297            &ca.verifying_key(),
2298            &published_ed,
2299            &pairs,
2300            Some(AUD),
2301            false,
2302        )
2303        .unwrap_err();
2304        assert_eq!(err, "JWT validation failed");
2305    }
2306
2307    #[test]
2308    fn composite_survives_independent_ed_rotation() {
2309        // A token signed under (ml_dsa, ed_active) still verifies after the
2310        // Ed25519 half rotates because its previously authorized exact pair is
2311        // retained while both halves remain published.
2312        let ca = new_ed_key();
2313        let (pq, pq_vk) = new_ml_dsa();
2314        let ed_old_active = new_ed_key();
2315        let token = composite_token(&pq, &ed_old_active, AUD);
2316        // Post-rotation published set: old active is now in drain, new active added.
2317        let ed_new_active = new_ed_key();
2318        let published_ed = vec![ed_new_active.verifying_key(), ed_old_active.verifying_key()];
2319        let pairs = [published_pair(pq_vk, ed_old_active.verifying_key())];
2320
2321        let claims = decode_local_multi_key(
2322            &token,
2323            &ca.verifying_key(),
2324            &published_ed,
2325            &pairs,
2326            Some(AUD),
2327            false,
2328        )
2329        .unwrap();
2330        assert_eq!(claims.sub, "alice");
2331    }
2332}
2333
2334#[cfg(test)]
2335#[allow(clippy::expect_used)]
2336mod public_rate_limit_tests {
2337    use super::*;
2338    use axum::{body::Body, http::Request as HttpRequest, middleware, routing::get, Router};
2339    use std::sync::atomic::{AtomicUsize, Ordering};
2340    use tower::ServiceExt;
2341
2342    #[tokio::test]
2343    async fn provisioning_limit_rejects_before_handler_work() {
2344        let invoked = Arc::new(AtomicUsize::new(0));
2345        let handler_invoked = Arc::clone(&invoked);
2346        let limiter = Arc::new(RateLimiter::new(1, 60));
2347        let app = Router::new()
2348            .route(
2349                "/provision",
2350                get(move || {
2351                    let handler_invoked = Arc::clone(&handler_invoked);
2352                    async move {
2353                        handler_invoked.fetch_add(1, Ordering::SeqCst);
2354                        StatusCode::OK
2355                    }
2356                }),
2357            )
2358            .layer(middleware::from_fn_with_state(
2359                limiter,
2360                browser_provisioning_rate_limit_middleware,
2361            ));
2362
2363        let first = app
2364            .clone()
2365            .oneshot(
2366                HttpRequest::get("/provision")
2367                    .body(Body::empty())
2368                    .expect("request"),
2369            )
2370            .await
2371            .expect("first response");
2372        let rejected = app
2373            .oneshot(
2374                HttpRequest::get("/provision")
2375                    .body(Body::empty())
2376                    .expect("request"),
2377            )
2378            .await
2379            .expect("limited response");
2380
2381        assert_eq!(first.status(), StatusCode::OK);
2382        assert_eq!(rejected.status(), StatusCode::TOO_MANY_REQUESTS);
2383        assert_eq!(
2384            invoked.load(Ordering::SeqCst),
2385            1,
2386            "rejected request must not enter resolver/signing handler work"
2387        );
2388    }
2389
2390    #[tokio::test]
2391    async fn public_route_limit_returns_429_over_quota() {
2392        let limiter = Arc::new(RateLimiter::new(1, 60));
2393        let app = Router::new()
2394            .route("/metadata", get(|| async { StatusCode::OK }))
2395            .layer(middleware::from_fn_with_state(
2396                limiter,
2397                public_route_rate_limit_middleware,
2398            ));
2399
2400        let first = app
2401            .clone()
2402            .oneshot(
2403                HttpRequest::get("/metadata")
2404                    .body(Body::empty())
2405                    .expect("request"),
2406            )
2407            .await
2408            .expect("first response");
2409        let rejected = app
2410            .oneshot(
2411                HttpRequest::get("/metadata")
2412                    .body(Body::empty())
2413                    .expect("request"),
2414            )
2415            .await
2416            .expect("limited response");
2417
2418        assert_eq!(first.status(), StatusCode::OK);
2419        assert_eq!(rejected.status(), StatusCode::TOO_MANY_REQUESTS);
2420    }
2421
2422    #[tokio::test]
2423    async fn public_route_bucket_is_not_selected_by_forwarding_headers() {
2424        let limiter = Arc::new(RateLimiter::new(1, 60));
2425        let app = Router::new()
2426            .route("/metadata", get(|| async { StatusCode::OK }))
2427            .layer(middleware::from_fn_with_state(
2428                limiter,
2429                public_route_rate_limit_middleware,
2430            ));
2431
2432        let first = app
2433            .clone()
2434            .oneshot(
2435                HttpRequest::get("/metadata")
2436                    .header("x-forwarded-for", "192.0.2.10")
2437                    .header("x-real-ip", "192.0.2.11")
2438                    .body(Body::empty())
2439                    .expect("request"),
2440            )
2441            .await
2442            .expect("first response");
2443        let rejected = app
2444            .oneshot(
2445                HttpRequest::get("/metadata")
2446                    .header("x-forwarded-for", "198.51.100.20")
2447                    .header("x-real-ip", "198.51.100.21")
2448                    .body(Body::empty())
2449                    .expect("request"),
2450            )
2451            .await
2452            .expect("limited response");
2453
2454        assert_eq!(first.status(), StatusCode::OK);
2455        assert_eq!(rejected.status(), StatusCode::TOO_MANY_REQUESTS);
2456    }
2457}