Skip to main content

hyprstream_core/services/oauth/
auth.rs

1//! Bearer token authentication middleware for the OAuth service.
2//!
3//! Applied as an Axum middleware layer to the protected route group (SCIM
4//! user management). Public endpoints (discovery, token, authorize) bypass
5//! this layer.
6//!
7//! On success, inserts `AuthenticatedUser` into request extensions so
8//! downstream handlers can identify the caller.
9
10use std::sync::Arc;
11
12use axum::{
13    extract::{Request, State},
14    http::{header, StatusCode},
15    middleware::Next,
16    response::{IntoResponse, Response},
17};
18use subtle::ConstantTimeEq;
19
20use super::state::OAuthState;
21pub use crate::server::middleware::AuthenticatedUser;
22
23/// Require a valid Bearer or DPoP token on the request.
24///
25/// Routes JWT verification by the protected `alg` header, then validates the
26/// exact OAuth-self audience and one of this node's exact profile issuers.
27/// When `Authorization: DPoP` is used, also verifies the `DPoP` proof header and
28/// checks that `cnf.jkt` in the token matches the proof key's thumbprint.
29/// Inserts `AuthenticatedUser` into request extensions on success.
30/// Returns 401 if the token is absent, expired, or has an invalid signature.
31pub async fn require_bearer_token(
32    State(state): State<Arc<OAuthState>>,
33    mut request: Request,
34    next: Next,
35) -> Response {
36    let auth_header = request
37        .headers()
38        .get(header::AUTHORIZATION)
39        .and_then(|v| v.to_str().ok())
40        .map(str::to_owned);
41
42    let (scheme, token) = match auth_header.as_deref().and_then(|h| {
43        if let Some(t) = h.strip_prefix("Bearer ") {
44            Some(("Bearer", t.to_owned()))
45        } else if let Some(t) = h.strip_prefix("DPoP ") {
46            Some(("DPoP", t.to_owned()))
47        } else {
48            None
49        }
50    }) {
51        Some(pair) => pair,
52        None => {
53            return (
54                StatusCode::UNAUTHORIZED,
55                [(header::WWW_AUTHENTICATE, "Bearer")],
56                axum::Json(serde_json::json!({"error": "invalid_token", "error_description": "Bearer token required"})),
57            )
58                .into_response();
59        }
60    };
61
62    // For DPoP, also grab the DPoP proof header.
63    let dpop_proof_str = if scheme == "DPoP" {
64        match request.headers().get("DPoP").and_then(|v| v.to_str().ok()) {
65            Some(p) => Some(p.to_owned()),
66            None => {
67                return (
68                    StatusCode::UNAUTHORIZED,
69                    [(header::WWW_AUTHENTICATE, "Bearer error=\"invalid_token\"")],
70                    axum::Json(serde_json::json!({"error": "invalid_token", "error_description": "DPoP proof header required when using DPoP scheme"})),
71                )
72                    .into_response();
73            }
74        }
75    } else {
76        None
77    };
78
79    let claims = match validate_oauth_access_token(&state, &token).await {
80        Ok(c) => c,
81        Err(_) => {
82            return (
83                StatusCode::UNAUTHORIZED,
84                [(header::WWW_AUTHENTICATE, "Bearer error=\"invalid_token\"")],
85                axum::Json(serde_json::json!({"error": "invalid_token", "error_description": "Token invalid or expired"})),
86            )
87                .into_response();
88        }
89    };
90
91    // DPoP-bound tokens (cnf.jkt) MUST NOT be accepted as plain Bearer (RFC 9449 §7).
92    // A stolen DPoP-bound token presented as Bearer bypasses key-possession binding.
93    if claims.cnf_jkt().is_some() && dpop_proof_str.is_none() {
94        return (
95            StatusCode::UNAUTHORIZED,
96            [(header::WWW_AUTHENTICATE, "DPoP error=\"invalid_token\"")],
97            axum::Json(serde_json::json!({"error": "invalid_token", "error_description": "DPoP-bound token must use Authorization: DPoP scheme"})),
98        )
99            .into_response();
100    }
101
102    // For DPoP: verify the proof and validate cnf.jkt matches the proof key.
103    if let Some(ref proof_str) = dpop_proof_str {
104        let method = request.method().as_str();
105        let uri = request.uri();
106        // RFC 9449 htu is the absolute target URI without query or fragment.
107        // Axum server requests normally carry origin-form URIs, so reconstruct
108        // the authority from the operator-configured canonical OAuth origin.
109        let htu = format!("{}{}", state.atproto_issuer_url(), uri.path());
110        let proof = match super::dpop::verify_dpop_proof(proof_str, method, &htu, Some(&token)) {
111            Ok(p) => p,
112            Err(e) => {
113                return (
114                    StatusCode::UNAUTHORIZED,
115                    [(header::WWW_AUTHENTICATE, "Bearer error=\"invalid_token\"")],
116                    axum::Json(serde_json::json!({"error": "invalid_dpop_proof", "error_description": e.to_string()})),
117                )
118                    .into_response();
119            }
120        };
121        // JTI replay prevention for resource requests (RFC 9449 §11.1).
122        if !state.check_and_record_dpop_jti(&proof.jti, proof.iat) {
123            return (
124                StatusCode::UNAUTHORIZED,
125                [(header::WWW_AUTHENTICATE, "Bearer error=\"invalid_token\"")],
126                axum::Json(serde_json::json!({"error": "invalid_dpop_proof", "error_description": "DPoP proof jti already used"})),
127            )
128                .into_response();
129        }
130
131        // RFC 9449 §8 nonce enforcement (resource server).
132        // Once this jkt has been issued a nonce by us, all subsequent proofs
133        // must include a valid server-issued nonce.
134        let needs_nonce = state.dpop_client_requires_nonce(&proof.jkt).await;
135        let nonce_ok = match proof.nonce.as_deref() {
136            Some(n) => state.verify_dpop_nonce(n).await,
137            None => false,
138        };
139        if needs_nonce && !nonce_ok {
140            let fresh = state.issue_dpop_nonce().await;
141            state.mark_dpop_client_nonced(&proof.jkt).await;
142            let mut resp = (
143                StatusCode::UNAUTHORIZED,
144                [(header::WWW_AUTHENTICATE, "DPoP error=\"use_dpop_nonce\"")],
145                axum::Json(serde_json::json!({
146                    "error": "use_dpop_nonce",
147                    "error_description": "DPoP proof must include a server-issued nonce",
148                })),
149            )
150                .into_response();
151            if let Ok(val) = axum::http::HeaderValue::from_str(&fresh) {
152                resp.headers_mut().insert("DPoP-Nonce", val);
153            }
154            return resp;
155        }
156        if proof.nonce.is_some() && !nonce_ok {
157            // Presented nonce but it was bogus — same rejection.
158            let fresh = state.issue_dpop_nonce().await;
159            state.mark_dpop_client_nonced(&proof.jkt).await;
160            let mut resp = (
161                StatusCode::UNAUTHORIZED,
162                [(header::WWW_AUTHENTICATE, "DPoP error=\"use_dpop_nonce\"")],
163                axum::Json(serde_json::json!({
164                    "error": "use_dpop_nonce",
165                    "error_description": "DPoP nonce invalid or expired",
166                })),
167            )
168                .into_response();
169            if let Ok(val) = axum::http::HeaderValue::from_str(&fresh) {
170                resp.headers_mut().insert("DPoP-Nonce", val);
171            }
172            return resp;
173        }
174        // Verify cnf.jkt in token matches the DPoP proof key.
175        if let Some(token_jkt) = claims.cnf_jkt() {
176            if token_jkt.as_bytes().ct_eq(proof.jkt.as_bytes()).unwrap_u8() == 0 {
177                return (
178                    StatusCode::UNAUTHORIZED,
179                    [(header::WWW_AUTHENTICATE, "Bearer error=\"invalid_token\"")],
180                    axum::Json(serde_json::json!({"error": "invalid_token", "error_description": "cnf.jkt does not match DPoP proof key"})),
181                )
182                    .into_response();
183            }
184        }
185    }
186
187    let user = AuthenticatedUser {
188        user: claims.sub,
189        verified_tenant: claims.tenant,
190        token: Some(token),
191        exp: Some(claims.exp),
192    };
193    if user.authorization_domain().is_err() {
194        return (
195            StatusCode::FORBIDDEN,
196            axum::Json(serde_json::json!({
197                "error": "insufficient_scope",
198                "error_description": "Verified hosted-account tenant binding required"
199            })),
200        )
201            .into_response();
202    }
203    request.extensions_mut().insert(user);
204
205    next.run(request).await
206}
207
208/// Restrict cross-tenant OAuth administration to a tenantless service authority.
209///
210/// This layer runs inside [`require_bearer_token`], after the verified identity
211/// has been inserted. Tenant-bound users may use self-service OAuth routes, but
212/// cannot enumerate or mutate the global SCIM store or mint service workload
213/// identities. Introspection has its own same-tenant check.
214pub async fn require_global_service_authority(request: Request, next: Next) -> Response {
215    let authorized = request
216        .extensions()
217        .get::<AuthenticatedUser>()
218        .is_some_and(|user| user.authorization_domain().as_deref() == Ok("*"));
219    if !authorized {
220        return (
221            StatusCode::FORBIDDEN,
222            axum::Json(serde_json::json!({
223                "error": "insufficient_scope",
224                "error_description": "global service authority required"
225            })),
226        )
227            .into_response();
228    }
229    next.run(request).await
230}
231
232/// Verify a JWT access token against the OAuth server's complete local signing
233/// surface. PolicyService mints composite tokens, while classical EdDSA remains
234/// accepted for explicitly classical deployments and legacy rotation slots.
235///
236/// Audience and issuer are mandatory here. The canonical origin is the OAuth
237/// server's RFC 9728 resource identifier, while the configured issuer remains
238/// an accepted local audience alias for default-audience tokens minted before
239/// the resource indicator is known. No other audience is accepted.
240pub(super) async fn validate_oauth_access_token(
241    state: &OAuthState,
242    token: &str,
243) -> Result<hyprstream_rpc::auth::Claims, &'static str> {
244    let claims = verify_access_token(state, token, AudiencePolicy::Exact).await?;
245
246    // Fail-closed revocation: if the token carries a jti but no store is
247    // configured, reject — a potentially-revoked credential must not be
248    // admitted when revocation status cannot be checked. The credential
249    // profile makes jti REQUIRED on locally issued tokens (issuer locality
250    // is enforced above), so a missing jti is a hard rejection, not a skip.
251    match claims.jti.as_deref() {
252        Some(jti) => {
253            let cred_id = hyprstream_rpc::auth::CredentialId::jwt(&claims.iss, jti);
254            match hyprstream_rpc::auth::global_credential_revocation_store() {
255                Some(store) => {
256                    if store.is_revoked(&cred_id).await {
257                        return Err("JWT revoked");
258                    }
259                }
260                None => return Err("revocation store unavailable"),
261            }
262        }
263        None => return Err("local credential missing required jti"),
264    }
265
266    // Session check (v16 §3.3): a token carrying a session ID is rejected
267    // when the session is revoked, expired, unknown, or cannot be checked.
268    let session_key = match claims.session_key() {
269        Ok(key) => key,
270        Err(_) => return Err("malformed session claims"),
271    };
272    if let Some(session_key) = session_key {
273        match hyprstream_rpc::auth::global_session_registry() {
274            Some(registry) => {
275                if registry.is_revoked(&session_key).await {
276                    return Err("session revoked");
277                }
278            }
279            None => return Err("session registry unavailable"),
280        }
281    }
282    // RFC 9068 §2.2.1 (v16 credential profile): this OAuth access token is an
283    // `at+jwt` (`verify_access_token` positively rejects any other `typ`), so
284    // it MUST carry a non-empty `client_id`.
285    if claims
286        .client_id
287        .as_deref()
288        .is_none_or(|c| c.trim().is_empty())
289    {
290        return Err("at+jwt credential missing required client_id");
291    }
292    Ok(claims)
293}
294
295/// Audience policy for [`verify_access_token`].
296///
297/// - `Exact`: the token's `aud` must match the resource server's canonical
298///   audience or issuer URL. Used by resource-server auth (OAI, MCP).
299/// - `AnyLocalIssuer`: the token's `aud` may be any RFC 8707 resource
300///   audience; the issuer must still be local. Used by the revocation
301///   endpoint (RFC 7009), which must be able to revoke resource-audience
302///   tokens, not just OAuth-self-audience tokens.
303pub(super) enum AudiencePolicy {
304    Exact,
305    AnyLocalIssuer,
306}
307
308/// One signature/profile/local-issuer verification stack with caller-
309/// selected audience policy. Both [`validate_oauth_access_token`] (resource
310/// auth, exact audience) and the revocation endpoint (any local-issuer
311/// resource audience) call this function. No unverified authority
312/// derivation: signature, typ, and local-issuer checks are always enforced.
313pub(super) async fn verify_access_token(
314    state: &OAuthState,
315    token: &str,
316    audience_policy: AudiencePolicy,
317) -> Result<hyprstream_rpc::auth::Claims, &'static str> {
318    let header =
319        hyprstream_rpc::auth::parse_protected_header(token).map_err(|_| "JWT header invalid")?;
320    if !hyprstream_rpc::auth::is_rfc9068_access_token_type(&header.typ) {
321        return Err("JWT type invalid");
322    }
323
324    let canonical_audience = state.atproto_issuer_url();
325    let unverified =
326        hyprstream_rpc::auth::decode_unverified(token).map_err(|_| "JWT claims invalid")?;
327
328    // Audience policy dispatch. Both paths enforce a non-empty audience.
329    let expected_audience = match (&audience_policy, unverified.aud.as_deref()) {
330        (AudiencePolicy::Exact, Some(audience))
331            if audience == canonical_audience || audience == state.issuer_url.as_str() =>
332        {
333            audience.to_owned()
334        }
335        (AudiencePolicy::AnyLocalIssuer, Some(audience)) if !audience.is_empty() => {
336            audience.to_owned()
337        }
338        _ => return Err("JWT audience invalid"),
339    };
340
341    let claims = match header.alg.as_str() {
342        "ML-DSA-65-Ed25519" => {
343            let dispatch = hyprstream_rpc::auth::parse_composite_dispatch(
344                token,
345                hyprstream_rpc::auth::RFC9068_ACCESS_TOKEN_TYPES,
346            )
347            .map_err(|_| "composite JWT dispatch invalid")?;
348            let snapshot = hyprstream_rpc::auth::global_composite_key_set().snapshot();
349            let pair = snapshot
350                .pair(dispatch.kid())
351                .ok_or("composite JWT kid unknown")?;
352            hyprstream_rpc::auth::jwt::decode_composite(
353                token,
354                pair.ml_dsa(),
355                pair.ed25519(),
356                Some(&expected_audience),
357                &dispatch,
358            )
359            .map_err(|_| "composite JWT validation failed")?
360        }
361        "EdDSA" => {
362            let key = state
363                .jwt_bearer_verifying_key()
364                .await
365                .ok_or("EdDSA verification key unavailable")?;
366            hyprstream_rpc::auth::jwt::decode(token, &key, Some(&expected_audience))
367                .map_err(|_| "EdDSA JWT validation failed")?
368        }
369        _ => return Err("JWT algorithm unsupported"),
370    };
371
372    // Local-issuer enforcement is always applied, regardless of audience
373    // policy. A federated token is never accepted through either path.
374    let issuer_is_local = claims.iss == canonical_audience || claims.iss == state.issuer_url;
375    if !issuer_is_local {
376        return Err("JWT issuer invalid");
377    }
378    Ok(claims)
379}