Skip to main content

hyprstream_rpc/transport/
moq_connect_auth.rs

1//! CONNECT-time authentication for the `/moq` WebTransport plane (#1153).
2//!
3//! The `/moq` WebTransport CONNECT is an entry point onto a *shared* streaming
4//! plane. This module authenticates it **before any stream is established**
5//! (the accept loop verifies the credential and refuses the CONNECT — by
6//! dropping the request, never completing the handshake — before
7//! `Request::ok()` runs), then binds the accepted session to a tenant derived
8//! from the *verified* identity.
9//!
10//! ## Credential accepted, and why
11//!
12//! The accepted credential is a **bearer JWT** carried in the HTTP/3
13//! [`Authorization`] header (`Authorization: Bearer <jwt>`). It is
14//! **verified, not merely parsed**: [`crate::auth::jwt::decode_with_key`]
15//! checks the EdDSA signature (and rejects any non-`EdDSA` `alg`, defeating
16//! algorithm-confusion), `exp`/`iat` validity, and the expected `aud`. A
17//! forged signature, a stripped claim, or an expired token fails closed.
18//!
19//! This reuses the same verified-identity primitive the RPC envelope path uses
20//! (`hyprstream_rpc::auth::jwt`/`Claims`) so the `/moq` plane and the RPC
21//! plane agree on what "verified subject" means — the derivation can be
22//! shared with the sibling Casbin-domain work (#1151) rather than invented a
23//! second time.
24//!
25//! ## Why the tenant is NOT read from the token
26//!
27//! Per the #1128 spike and #1146 (T2.1 / PR #1147), JWT scope/claim fields are
28//! not enforced at the verifier today — any tenant-shaped claim inside the
29//! token is caller-supplied data and therefore unenforceable (the existing
30//! `cap` field is the cautionary tale: present, unread). So the tenant is
31//! **never** taken from the token. It is derived, server-side, from the
32//! *verified subject* by [`MoqConnectAuthz::tenant_resolver`] — an
33//! authoritative subject→tenant provisioning map the operator controls. The
34//! token proves *who* the peer is; the resolver is the trust root for *which
35//! tenant that subject belongs to*. See `VerifiedConnect`.
36//!
37//! ## What this guarantees today (read before assuming isolation)
38//!
39//! With a `MoqConnectAuthz` installed, an unauthenticated or tenant-less
40//! `/moq` CONNECT is refused (fail-closed), and a connected peer can only
41//! enumerate/subscribe to its own tenant's broadcasts (structural scoping via
42//! [`crate::moq_authz::tenant_scoped_consumer`]). This is a **transport-plane,
43//! metadata/announce isolation boundary** on the `/moq` consumer path. It is
44//! NOT a cluster-wide tenant guarantee: frame content was already
45//! AEAD-sealed + chained-HMAC'd at the source (the relay/consumer holds no
46//! `enc_key`/`mac_key`), and other planes (RPC subject authorization, event
47//! prefixes, VFS) have their own independent stories documented in the #1128
48//! spike. Relay-mode (`with_moq_relay`) additionally refuses unauthenticated
49//! CONNECTs but the relay still routes by track name — it must, to rendezvous
50//! publisher and subscriber — so announce-name visibility through a relay is
51//! inherent to relay mode and not something this boundary removes.
52
53use std::sync::Arc;
54
55use ed25519_dalek::VerifyingKey;
56
57use crate::auth::jwt;
58use crate::moq_authz::PeerIdentity;
59
60/// HTTP/3 header carrying the bearer JWT.
61pub const AUTHORIZATION_HEADER: &str = "authorization";
62/// Scheme expected in the `Authorization` header value.
63pub const BEARER_SCHEME: &str = "Bearer";
64
65/// Server-side map from a **verified** subject to its tenant.
66///
67/// Authoritative server state (a subject→tenant provisioning table the
68/// operator controls), never a caller-supplied field — see the module docs on
69/// why a token claim is not used. The input is the verified `Claims::sub` from
70/// a JWT whose signature has already been checked; returning `None` fails the
71/// CONNECT closed.
72pub type VerifiedSubjectTenantResolver = Arc<dyn Fn(&str) -> Option<String> + Send + Sync>;
73
74/// CONNECT-time authentication + tenant-binding config for the `/moq` plane.
75///
76/// When installed on a
77/// [`crate::transport::quinn_transport::QuinnRpcServer`], every `/moq`
78/// WebTransport CONNECT must present a bearer JWT verifiable with
79/// `verify_key`; the verified subject is then mapped to a tenant by
80/// `tenant_resolver`. [`MoqConnectAuthz::verify`] returns `None` on any
81/// failure — missing header, wrong scheme, bad signature, expired/token-not-
82/// yet-valid, wrong audience, or an authenticated subject with no tenant —
83/// and the accept loop refuses the CONNECT (fail-closed). There is no
84/// fall-through to an unscoped consumer: that is the #1145 pattern and the
85/// single most likely way to get this wrong.
86#[derive(Clone)]
87pub struct MoqConnectAuthz {
88    verify_key: VerifyingKey,
89    expected_aud: Option<String>,
90    tenant_resolver: VerifiedSubjectTenantResolver,
91}
92
93impl std::fmt::Debug for MoqConnectAuthz {
94    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
95        f.debug_struct("MoqConnectAuthz")
96            .field("expected_aud", &self.expected_aud)
97            .finish_non_exhaustive()
98    }
99}
100
101impl MoqConnectAuthz {
102    /// Build with the verifying key for the JWT issuer this `/moq` endpoint
103    /// trusts and the authoritative subject→tenant resolver. The endpoint
104    /// accepts any `aud` unless [`Self::with_expected_aud`] is set.
105    pub fn new(verify_key: VerifyingKey, tenant_resolver: VerifiedSubjectTenantResolver) -> Self {
106        Self {
107            verify_key,
108            expected_aud: None,
109            tenant_resolver,
110        }
111    }
112
113    /// Require the JWT `aud` to equal `aud` (trailing-slash tolerant, matches
114    /// [`jwt::decode_with_key`]). A token with a different `aud` is rejected,
115    /// and — unlike the codebase-wide lenient [`jwt::decode_with_key`] — a
116    /// token with **no** `aud` is also rejected when this is set. On a
117    /// dedicated `/moq` boundary that closes the token-substitution vector
118    /// (a token minted for another service, which carries no `aud`, must not
119    /// be admitted here) per BCP 225 / RFC 8725bis. If the operator does not
120    /// set this, audience checking is off entirely (their choice).
121    pub fn with_expected_aud(mut self, aud: impl Into<String>) -> Self {
122        self.expected_aud = Some(aud.into());
123        self
124    }
125
126    /// Verify the bearer credential in `headers` and resolve the tenant from
127    /// the *verified* subject.
128    ///
129    /// Returns `None` — meaning the CONNECT MUST be refused — if:
130    /// - no `Authorization: Bearer <jwt>` header is present,
131    /// - the JWT signature, `alg`, `exp`, or `iat` check fails,
132    /// - the `aud` check fails — including a **missing** `aud` when
133    ///   [`Self::with_expected_aud`] is set (token substitution is not
134    ///   admitted on a boundary that specified an audience),
135    /// - or `tenant_resolver` returns `None` for the verified subject.
136    ///
137    /// Every branch is fail-closed; none falls back to an unscoped identity.
138    pub fn verify(&self, headers: &http::HeaderMap) -> Option<VerifiedConnect> {
139        let token = bearer_token(headers)?;
140        let claims =
141            jwt::decode_with_key(&token, &self.verify_key, self.expected_aud.as_deref()).ok()?;
142        // [`jwt::decode_with_key`] is lenient on a *missing* `aud` (accepts
143        // absent, rejects mismatch) to tolerate legacy federated issuers across
144        // the codebase. This dedicated `/moq` boundary is stricter: when an
145        // audience is configured, a token with no `aud` is a substitution
146        // attempt from another service and must fail closed (#1153, BCP 225).
147        if self.expected_aud.is_some() && claims.aud.is_none() {
148            return None;
149        }
150        let tenant = (self.tenant_resolver)(&claims.sub)?;
151        // `moq_net::Path::new` normalizes "/" to its empty wildcard path.
152        // Reject empty and multi-segment resolver output here, before it can
153        // become either a root consumer scope or unrestricted relay ingest.
154        if !crate::moq_authz::is_valid_tenant_segment(&tenant) {
155            return None;
156        }
157        Some(VerifiedConnect {
158            peer: PeerIdentity::authenticated(&claims.sub),
159            tenant,
160        })
161    }
162}
163
164/// The outcome of a successful CONNECT-time verification: a peer whose
165/// `subject` was verified by signature, and the tenant the server resolved
166/// for that subject. The tenant is authoritative server-side state, not a
167/// caller-supplied field.
168#[derive(Debug, Clone)]
169pub struct VerifiedConnect {
170    /// The verified application subject.
171    pub peer: PeerIdentity,
172    /// Server-resolved tenant for the verified subject.
173    pub tenant: String,
174}
175
176/// Extract the bearer token from the `Authorization` header.
177///
178/// Returns `None` if the header is absent, not valid UTF-8, not the `Bearer`
179/// scheme (compared case-insensitively per RFC 7235), or carries an empty
180/// token. Pure and independently testable.
181pub fn bearer_token(headers: &http::HeaderMap) -> Option<String> {
182    let raw = headers.get(AUTHORIZATION_HEADER)?.to_str().ok()?;
183    let mut split = raw.splitn(2, ' ');
184    let scheme = split.next()?;
185    if !scheme.trim().eq_ignore_ascii_case(BEARER_SCHEME) {
186        return None;
187    }
188    let token = split.next()?.trim();
189    if token.is_empty() {
190        None
191    } else {
192        Some(token.to_owned())
193    }
194}
195
196#[cfg(test)]
197#[allow(clippy::expect_used, clippy::unwrap_used)]
198mod tests {
199    use super::*;
200    use crate::auth::claims::Claims;
201    use ed25519_dalek::SigningKey;
202
203    fn mint(signing: &SigningKey, sub: &str, exp_delta_secs: i64) -> String {
204        let now = chrono::Utc::now().timestamp();
205        let claims = Claims::new(sub.to_owned(), now, now + exp_delta_secs);
206        crate::auth::jwt::encode(&claims, signing)
207    }
208
209    fn resolver(mapping: &'static [(&'static str, &'static str)]) -> VerifiedSubjectTenantResolver {
210        Arc::new(move |sub: &str| {
211            mapping
212                .iter()
213                .find(|(s, _)| *s == sub)
214                .map(|(_, t)| t.to_string())
215        })
216    }
217
218    #[test]
219    fn bearer_token_parses_well_formed_header() {
220        let mut h = http::HeaderMap::new();
221        h.insert("authorization", "Bearer abc.def.ghi".parse().unwrap());
222        assert_eq!(bearer_token(&h).as_deref(), Some("abc.def.ghi"));
223    }
224
225    #[test]
226    fn bearer_token_accepts_lowercase_scheme() {
227        // RFC 7235: scheme is case-insensitive.
228        let mut h = http::HeaderMap::new();
229        h.insert("authorization", "bearer t.ok.en".parse().unwrap());
230        assert_eq!(bearer_token(&h).as_deref(), Some("t.ok.en"));
231    }
232
233    #[test]
234    fn bearer_token_rejects_missing_or_wrong_scheme() {
235        let mut h = http::HeaderMap::new();
236        assert!(bearer_token(&h).is_none()); // absent
237        h.insert("authorization", "Basic dXNlcjpwYXNz".parse().unwrap());
238        assert!(bearer_token(&h).is_none()); // wrong scheme
239        h.insert("authorization", "Bearer   ".parse().unwrap());
240        assert!(bearer_token(&h).is_none()); // empty token
241    }
242
243    #[test]
244    fn verify_succeeds_for_known_subject_and_resolves_tenant() {
245        let key = SigningKey::from_bytes(&[1u8; 32]);
246        let vk = key.verifying_key();
247        let authz = MoqConnectAuthz::new(vk, resolver(&[("did:key:alice", "alice")]));
248        let tok = mint(&key, "did:key:alice", 60);
249        let mut h = http::HeaderMap::new();
250        h.insert("authorization", format!("Bearer {tok}").parse().unwrap());
251        let vc = authz.verify(&h).expect("verified");
252        assert_eq!(vc.peer.subject.as_deref(), Some("did:key:alice"));
253        assert_eq!(vc.tenant, "alice");
254        assert!(vc.peer.is_authenticated());
255    }
256
257    #[test]
258    fn verify_fails_when_no_authorization_header() {
259        let key = SigningKey::from_bytes(&[2u8; 32]);
260        let vk = key.verifying_key();
261        let authz = MoqConnectAuthz::new(vk, resolver(&[("s", "t")]));
262        assert!(authz.verify(&http::HeaderMap::new()).is_none());
263    }
264
265    #[test]
266    fn verify_fails_for_wrong_signature() {
267        // Signed by a different key than the verifier expects.
268        let issuer_key = SigningKey::from_bytes(&[3u8; 32]);
269        let rogue_key = SigningKey::from_bytes(&[4u8; 32]);
270        let authz = MoqConnectAuthz::new(issuer_key.verifying_key(), resolver(&[("s", "t")]));
271        let tok = mint(&rogue_key, "s", 60); // signed by rogue
272        let mut h = http::HeaderMap::new();
273        h.insert("authorization", format!("Bearer {tok}").parse().unwrap());
274        assert!(
275            authz.verify(&h).is_none(),
276            "forged signature must fail closed"
277        );
278    }
279
280    #[test]
281    fn verify_fails_for_expired_token() {
282        let key = SigningKey::from_bytes(&[5u8; 32]);
283        let vk = key.verifying_key();
284        let authz = MoqConnectAuthz::new(vk, resolver(&[("s", "t")]));
285        // exp in the past.
286        let now = chrono::Utc::now().timestamp();
287        let claims = Claims::new("s".to_owned(), now - 120, now - 60);
288        let tok = crate::auth::jwt::encode(&claims, &key);
289        let mut h = http::HeaderMap::new();
290        h.insert("authorization", format!("Bearer {tok}").parse().unwrap());
291        assert!(authz.verify(&h).is_none());
292    }
293
294    #[test]
295    fn verify_fails_when_subject_has_no_tenant() {
296        // Verified signature, but the resolver doesn't know this subject →
297        // fail closed (no wildcard tenant, no unscoped fallthrough).
298        let key = SigningKey::from_bytes(&[6u8; 32]);
299        let vk = key.verifying_key();
300        let authz = MoqConnectAuthz::new(vk, resolver(&[("did:key:alice", "alice")]));
301        let tok = mint(&key, "did:key:stranger", 60);
302        let mut h = http::HeaderMap::new();
303        h.insert("authorization", format!("Bearer {tok}").parse().unwrap());
304        assert!(authz.verify(&h).is_none());
305    }
306
307    #[test]
308    fn verify_fails_when_resolver_returns_invalid_tenant_segment() {
309        let key = SigningKey::from_bytes(&[10u8; 32]);
310        let token = mint(&key, "s", 60);
311        let mut headers = http::HeaderMap::new();
312        headers.insert("authorization", format!("Bearer {token}").parse().unwrap());
313
314        for tenant in ["", "/", "///", "/alice", "alice/", "alice/bob"] {
315            let tenant = tenant.to_owned();
316            let authz =
317                MoqConnectAuthz::new(key.verifying_key(), Arc::new(move |_| Some(tenant.clone())));
318            assert!(
319                authz.verify(&headers).is_none(),
320                "invalid tenant must fail CONNECT closed"
321            );
322        }
323    }
324
325    #[test]
326    fn verify_enforces_expected_audience() {
327        let key = SigningKey::from_bytes(&[7u8; 32]);
328        let vk = key.verifying_key();
329        let authz =
330            MoqConnectAuthz::new(vk, resolver(&[("s", "t")])).with_expected_aud("moq.example");
331        // Mint a token with the wrong aud.
332        let now = chrono::Utc::now().timestamp();
333        let mut claims = Claims::new("s".to_owned(), now, now + 60);
334        claims.aud = Some("other.example".to_owned());
335        let tok = crate::auth::jwt::encode(&claims, &key);
336        let mut h = http::HeaderMap::new();
337        h.insert("authorization", format!("Bearer {tok}").parse().unwrap());
338        assert!(authz.verify(&h).is_none(), "wrong aud must fail closed");
339    }
340
341    #[test]
342    fn verify_rejects_missing_aud_when_audience_is_configured() {
343        // BCP 225 / RFC 8725bis: on a boundary that specified an audience, a
344        // token with NO aud is a substitution attempt from another service
345        // and must fail closed — not be admitted by the lenient-on-absence
346        // decode_with_key default. (`jwt::decode_with_key` accepts a missing
347        // aud; `MoqConnectAuthz` must override that here.)
348        let key = SigningKey::from_bytes(&[8u8; 32]);
349        let vk = key.verifying_key();
350        let authz =
351            MoqConnectAuthz::new(vk, resolver(&[("s", "t")])).with_expected_aud("moq.example");
352        // Token with no aud (the default from Claims::new).
353        let tok = mint(&key, "s", 60);
354        let mut h = http::HeaderMap::new();
355        h.insert("authorization", format!("Bearer {tok}").parse().unwrap());
356        assert!(
357            authz.verify(&h).is_none(),
358            "missing aud must fail closed when an audience is configured"
359        );
360    }
361
362    #[test]
363    fn verify_accepts_missing_aud_when_no_audience_configured() {
364        // If the operator did not set expected_aud, audience checking is off
365        // entirely — a token with no aud is admitted (subject to the other
366        // checks). This is the operator's explicit choice.
367        let key = SigningKey::from_bytes(&[9u8; 32]);
368        let vk = key.verifying_key();
369        let authz = MoqConnectAuthz::new(vk, resolver(&[("s", "t")]));
370        let tok = mint(&key, "s", 60); // no aud
371        let mut h = http::HeaderMap::new();
372        h.insert("authorization", format!("Bearer {tok}").parse().unwrap());
373        assert!(
374            authz.verify(&h).is_some(),
375            "no-aud token admitted when no audience configured"
376        );
377    }
378}