From 7726f4c3fa5b8c5f1120305714cab3925fa8dd8b Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Mon, 16 Nov 2026 04:34:46 -0800 Subject: [PATCH 1/3] chore(quest): claim quest/m2/auth-attach-token.md Quest-Claim: 1e5f764cbd36dd29 From 9f99184af5f1181c6796ea7b748215edbd2beb0a Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Mon, 16 Nov 2026 04:49:32 -0800 Subject: [PATCH 2/3] feat(relay)!: an attached token arrives as a token, not in the query An in-band credential now rides Request.token (kind 0, any bytes) on attach and leaves query as dialed. The relay drops with_jwt, the UTF-8 refusal, and the query jwt check in its public rules; moq auth serve reads an event with auth from its token alone. Co-Authored-By: Claude Sonnet 5.5 --- doc/bin/relay/auth.md | 14 +-- js/auth/src/contract.ts | 5 +- quest/m2/README.md | 5 +- quest/m2/auth-attach-downstream.md | 22 +++++ quest/m2/auth-attach-token.md | 68 ------------- quest/m2/auth-grants.md | 1 - rs/moq-auth/src/request.rs | 7 +- rs/moq-auth/src/serve.rs | 60 +++++++++-- rs/moq-relay/src/auth.rs | 40 ++------ rs/moq-relay/src/auth/refresh.rs | 99 ++++++++----------- .../tests/integration/auth_lifetime.rs | 18 ++++ 11 files changed, 166 insertions(+), 173 deletions(-) create mode 100644 quest/m2/auth-attach-downstream.md delete mode 100644 quest/m2/auth-attach-token.md diff --git a/doc/bin/relay/auth.md b/doc/bin/relay/auth.md index 5b349af46b9..af60e87d47f 100644 --- a/doc/bin/relay/auth.md +++ b/doc/bin/relay/auth.md @@ -23,8 +23,8 @@ path patterns under a root, and the session can only see that part of the tree. The relay POSTs one JSON body per session event (`connect`, `attach`, `revalidate`, `end`) to `--auth-url` and reads a grant back. The request carries everything the relay knows: a session id, its own `node` name, the transport, addresses, -SNI and ALPN, the path and query exactly as dialed, a moq-transport SETUP -token, the declared role and implementation, and the verified client +SNI and ALPN, the path and query exactly as dialed, the SETUP +`token` (or, on `attach`, the credential attached in band), the declared role and implementation, and the verified client certificate. Nothing is parsed on the server's behalf: the `jwt` query parameter is a convention of `moq auth serve`, not of the relay. A path with a `.` or `..` segment is refused before the server is asked: a URL transport resolves those away, but a SETUP @@ -190,10 +190,12 @@ removes that token's grant: streams that lose permission reset, and other grants keep the connection alive. A refused new token leaves existing grants alone. The grant reports its real expiry so the client can renew in time. -The relay verifies a presented JWT through the same admission path, replacing -`jwt` in the original query and preserving the connection's identity. The auth -server sees `attach` for the same session id, with a fresh `auth` id -that also names its revalidations and end. Attached grants revalidate and end +The relay verifies a presented JWT through the same admission path, preserving +the connection's identity. The auth server sees `attach` for the same session +id, with a fresh `auth` id that also names its revalidations and end. The +attached credential arrives in `token` (`kind` 0, any bytes) and `query` stays +exactly as dialed, still holding the connection's first credential, so read an +event with `auth` from `token` alone; `moq auth serve` does. Attached grants revalidate and end independently. Each JWT counts against its own `--limit-token` cap while any credential using it remains on that connection. The initial credential remains responsible for the connection's stats tier. diff --git a/js/auth/src/contract.ts b/js/auth/src/contract.ts index a05eaaa87b7..8c73184c2c0 100644 --- a/js/auth/src/contract.ts +++ b/js/auth/src/contract.ts @@ -120,7 +120,10 @@ const BaseRequestSchema = z.object({ path: z.string(), /** The raw query string, without the leading `?`. */ query: z.optional(z.string()), - /** The credential a moq-transport client presented in its SETUP. */ + /** + * The credential the client presented: the Token of its SETUP, or on an `attach` (and that + * credential's `revalidate` and `end`) the one it attached in band, with `query` left as dialed. + */ token: z.optional(TokenSchema), /** The direction the client declared at SETUP; absent means both. */ role: z.optional(RoleSchema), diff --git a/quest/m2/README.md b/quest/m2/README.md index 42df4d4cfa6..61666abdfb1 100644 --- a/quest/m2/README.md +++ b/quest/m2/README.md @@ -49,9 +49,8 @@ removal, a rename, or a wire, catalog, or format change that is free until [the 0.14 leftovers](/quest/m2/relay-014-leftovers.md); [transport names](/quest/m2/transport-names.md); and [stats names](/quest/m2/stats-old-names.md). -- **Auth and crypto.** [Grants](/quest/m2/auth-grants.md), - [claims](/quest/m2/auth-claims.md), and - [the attached token](/quest/m2/auth-attach-token.md). End-to-end encryption +- **Auth and crypto.** [Grants](/quest/m2/auth-grants.md) and + [claims](/quest/m2/auth-claims.md). End-to-end encryption [is its own unpublished crate again](/quest/m2/e2ee-crate.md); its [finished format](/quest/m3/e2ee-format.md) follows in m3. - **Catalog, drafts, and formats.** [hang-04](/quest/m2/hang04/README.md) diff --git a/quest/m2/auth-attach-downstream.md b/quest/m2/auth-attach-downstream.md new file mode 100644 index 00000000000..403a34b03ba --- /dev/null +++ b/quest/m2/auth-attach-downstream.md @@ -0,0 +1,22 @@ +# [XS] Downstream auth servers read an attached credential from the token field + +## Goal + +Every auth server a deployment runs behind a relay reads a credential +attached in band, on `attach` and on that credential's `revalidate` and `end` +(the events with `auth`), from `token`, not from a `jwt` in `query`. + +## Plan + +The relay now sends an attached credential as `token` (`kind` 0) and leaves +`query` as dialed. `moq auth serve` already reads it so; a server that +verifies `query` at `attach` sees the connection's first credential instead. +Neither the presented token nor its expiry is then the one admitted. + +## Waiting + +- Maintainer: check the moq.pro and Kixel auth handlers read `attach` from + `token`, and fix one that does not before it meets a relay with this change. + An agent cannot read those private repositories from here. Done when both + handlers' tests present an attach whose `query` holds an expired `jwt` and + whose `token` holds a valid one. diff --git a/quest/m2/auth-attach-token.md b/quest/m2/auth-attach-token.md deleted file mode 100644 index bfc316983e6..00000000000 --- a/quest/m2/auth-attach-token.md +++ /dev/null @@ -1,68 +0,0 @@ -# [S] An attached token arrives as a token, not in the query - -## Goal - -When a client attaches a credential in band, the relay's `attach` request -to the auth server carries it in `Request.token` and leaves `query` exactly -as the client dialed it. The relay no longer knows the name `jwt`, and an -in-band token need not be UTF-8. `moq auth serve` and the docs read the -attached credential from `token`. - -## Plan - -Decided 2026-11-16 (maintainer, /quest-plan of the pre-cut audit): ✅ the -in-band token rides `Request.token` and the query stays as dialed (rejected: -keeping the rewrite and documenting it; a third field for the attached -credential). The contract says nothing is parsed on the relay's behalf, and -the rewrite is the one place the relay breaks that. - -Facts found by the audit: - -- The contract: "Nothing is parsed on the relay's behalf" and `query` is - "The raw query string" (`rs/moq-auth/src/request.rs:13,60`). -- For an in-band token the relay clones the connection's request, replaces - or appends a `jwt=` pair in `query`, and clears `token` - (`rs/moq-relay/src/auth/refresh.rs:259-265`, `with_jwt` at `:497-523`). - So an `attach` request carries a query the client never dialed, and a - server whose credential is not called `jwt` reads its own parameter at - `connect` and `jwt` at `attach`. -- The lite draft's token is opaque bytes, but the relay refuses one that is - not UTF-8 (`refresh.rs:259-262`), only because it must fit a query string. - A binary token works in SETUP (`token.value` is base64url) and fails in - band. -- `jwt` is also fixed in `presents_token` - (`rs/moq-relay/src/auth.rs:878-885`) and in the clients - (`rs/moq-net/src/auth/tokens.rs:456-532`, - `js/net/src/connection/tokens.ts:25-50`). -- `token`'s docs still say "a moq-transport client" - (`request.rs:63`, `js/auth/src/contract.ts:123`), though lite-07's Token - Setup Parameter lands there with `kind` 0. - -For the PR: - -- Relay: on `attach`, set `token` to `{kind: 0, value}` and leave `query` - alone. Delete `with_jwt` and the UTF-8 refusal. `presents_token` is the - relay's only other reader of `jwt`; replace it with a fact the request - already has, or move the question to the server, so the relay holds no - parameter name. -- `moq auth serve` verifies `token` when `event` is `attach`. Today it - counts a query `jwt` and a SETUP token once when equal and refuses when - they differ (`rs/moq-auth/src/serve.rs:195-197`); on `attach` the dialed - query still holds the first credential, so that rule must not fire there. -- The clients keep `?jwt=` only as the fallback for versions before - lite-07. Don't change them here. -- Both downstream auth servers read `attach` requests. This is a contract - break for them: record it in the Impact section, and check moq.pro's and - Kixel's handlers before merging. -- Update `request.rs`, `contract.ts`, and `doc/bin/relay/auth.md` (the - `token` field's description and the `attach` event). -- Tests: an attached binary token reaches the server unchanged; an `attach` - request's `query` equals the dialed one; `moq auth serve` renews a session - whose dialed query holds an expired `jwt`. - -Public API: none in Rust or JS beyond doc comments. HTTP contract: breaking -for `attach` (the credential moves from `query` to `token`). Wire: none. - -## Related - -- [A relay refuses a grant it does not fully understand](/quest/m2/auth-grants.md) - the other change to the same request and its docs diff --git a/quest/m2/auth-grants.md b/quest/m2/auth-grants.md index bfee317adaf..c44a5b67b4c 100644 --- a/quest/m2/auth-grants.md +++ b/quest/m2/auth-grants.md @@ -107,4 +107,3 @@ behind a temporary alias. Wire: none. ## Related - [Tokens are written as documented](/quest/m2/auth-claims.md) - the token side of the same types -- [An attached token arrives as a token](/quest/m2/auth-attach-token.md) - the other change to the request the server reads diff --git a/rs/moq-auth/src/request.rs b/rs/moq-auth/src/request.rs index f7079f0201a..9e126d29068 100644 --- a/rs/moq-auth/src/request.rs +++ b/rs/moq-auth/src/request.rs @@ -60,7 +60,9 @@ pub struct Request { /// The raw query string, without the leading `?`. pub query: Option, - /// The credential a moq-transport client presented in its SETUP. + /// The credential the client presented: the Token of its SETUP, or on an + /// [`Attach`](Event::Attach) (and that credential's revalidations and end) the one it + /// attached in band, with `query` left as the connection dialed it. pub token: Option, /// The direction the client declared at SETUP; absent means both. @@ -127,7 +129,8 @@ impl Request { } } -/// A credential from a moq-transport SETUP's `AUTHORIZATION TOKEN` option, unparsed. +/// A credential a client presented, unparsed: a SETUP Token (an `AUTHORIZATION TOKEN` on +/// moq-transport) or one attached in band. #[serde_as] #[derive(Clone, Serialize, Deserialize, PartialEq, Eq)] pub struct Token { diff --git a/rs/moq-auth/src/serve.rs b/rs/moq-auth/src/serve.rs index 17a4c819177..11ed49f336c 100644 --- a/rs/moq-auth/src/serve.rs +++ b/rs/moq-auth/src/serve.rs @@ -192,8 +192,9 @@ pub struct Rule { /// empty root: `anon/**` admits a session dialed at `/`, `/anon`, or `/anon/room`, /// each scoped to `anon/`, and refuses one dialed at `/other`. /// -/// The JWT is the `jwt` query parameter or a moq-transport SETUP token of type 0 -/// ([`Token::OUT_OF_BAND`]), verified alike. A session presenting both is verified +/// The JWT is the `jwt` query parameter or a SETUP token of type 0 +/// ([`Token::OUT_OF_BAND`]), verified alike. A credential attached in band is only the +/// event's `token`, since its `query` is the connection's. A session presenting both is verified /// once when they are the same JWT and refused when they differ, as is a SETUP token /// of any other type, and one presenting a JWT alongside a /// certificate: neither can safely win, since a certificate would override a JWT @@ -536,8 +537,15 @@ fn authorize(rules: &Permissions, path: &str) -> Result { /// The JWT the request presents: its SETUP token, or else its `jwt` query parameter. /// Both at once count as one only when they are the same JWT. +/// +/// An attached credential (an event with `auth`) is only its `token`: the `query` is the +/// connection's, still holding the first credential. fn jwt(request: &Request) -> Result>, Denial> { - match (&request.token, query_jwt(request)?) { + let query = match request.auth { + Some(_) => None, + None => query_jwt(request)?, + }; + match (&request.token, query) { // A client that offers a version without in-band auth copies its SETUP token // into the URL too, so the same JWT arrives twice. (Some(token), Some(jwt)) if token.kind == Token::OUT_OF_BAND && token.value == jwt.as_bytes() => Ok(Some(jwt)), @@ -745,8 +753,10 @@ impl Server { /// Answer one event: the grant, or why the session is refused. pub async fn answer(&self, request: &Request) -> Result, Denial> { - if matches!(request.event, Event::Attach) && request.auth.is_none() { - return Err(Denial::MalformedToken("an attachment needs an auth id".into())); + if matches!(request.event, Event::Attach) && (request.auth.is_none() || request.token.is_none()) { + return Err(Denial::MalformedToken( + "an attachment needs an auth id and a token".into(), + )); } let policy = self.policy(); match request.event { @@ -1401,6 +1411,43 @@ mod tests { assert_eq!(grant.publish, patterns(&["**"])); } + /// An attachment is its `token` alone: the dialed query's `jwt` is the connection's, so + /// it neither conflicts with the token nor stands in for a missing one. + #[tokio::test] + async fn an_attached_credential_is_read_from_its_token() { + let (dir, key) = key_dir(); + let server = Server::new(Policy { + keys: Some(Keys::Dir(dir.path().into())), + ..Default::default() + }) + .unwrap(); + // The connection dialed with a credential that has since expired. + let expired = Some(kio::clock::Wall::UNIX_EPOCH + Duration::from_secs(1)); + let dialed = sign(&key, "demo", &["**"], &[], expired); + let attached = sign(&key, "demo", &[], &["**"], None); + let mut attach = with_setup_token(with_token(request("/demo"), &dialed), Token::OUT_OF_BAND, &attached); + attach.auth = Some("attachment".into()); + attach.event = Event::Attach; + let grant = server.answer(&attach).await.unwrap().unwrap(); + assert_eq!(grant.subscribe, patterns(&["**"])); + assert!( + grant.publish.is_empty(), + "the dialed query's grant leaked into the attachment" + ); + + // Its revalidation reads the same token, not the expired query. + let mut revalidate = attach.clone(); + revalidate.event = Event::Revalidate; + assert!(server.answer(&revalidate).await.is_ok()); + + // The connection's credential is not the attachment's. + attach.token = None; + assert!(matches!( + server.answer(&attach).await.unwrap_err(), + Denial::MalformedToken(_) + )); + } + /// Two different credentials would leave the server guessing which one the client meant. #[tokio::test] async fn a_setup_token_and_a_different_query_jwt_are_refused() { @@ -2021,7 +2068,8 @@ mod tests { server.answer(&second).await.unwrap(); let attach = |session: &Request| { - let mut attach = with_token(session.clone(), &b); + // The dialed query still holds the connection's own `jwt`. + let mut attach = with_setup_token(session.clone(), Token::OUT_OF_BAND, &b); attach.auth = Some("attachment".into()); attach.event = Event::Attach; attach diff --git a/rs/moq-relay/src/auth.rs b/rs/moq-relay/src/auth.rs index 3af10326673..158daa0ad1c 100644 --- a/rs/moq-relay/src/auth.rs +++ b/rs/moq-relay/src/auth.rs @@ -853,7 +853,7 @@ impl Decider { } // Nothing here can verify a token, so one is refused rather than ignored: // its holder expects it to count, and the public grant is not what it says. - Self::Public(_) if presents_token(&request) => { + Self::Public(_) if request.token.is_some() => { tracing::debug!(path = ?request.path, "a token was presented to public rules"); Ok(Box::pin(std::future::ready(Err(Error::Refused(Default::default()))))) } @@ -874,16 +874,6 @@ impl Decider { } } -/// Whether `request` carries a token: a SETUP token of any type, or a non-empty -/// `jwt` query parameter, form-decoded as `moq auth serve` reads it, so an escaped -/// key such as `%6Awt` counts too. -fn presents_token(request: &Request) -> bool { - request.token.is_some() - || request.query.as_deref().is_some_and(|query| { - url::form_urlencoded::parse(query.as_bytes()).any(|(key, jwt)| key == "jwt" && !jwt.is_empty()) - }) -} - /// Admits sessions through one admission decider. #[derive(Clone)] pub struct Auth { @@ -1706,36 +1696,26 @@ mod tests { } } - /// Public rules verify nothing, so a token is refused rather than ignored, in - /// whichever form it arrives. + /// Public rules verify nothing, so a token is refused rather than ignored. #[tokio::test] async fn public_rules_refuse_a_token() { let auth = config(None, &["**"]) .init("relay-1", &moq_tokio::tls::Connect::default(), false) .unwrap(); - let mut query = auth.request(moq_auth::Transport::WebSocket, "/"); - query.query = Some("a=1&jwt=eyJ".into()); let mut setup = auth.request(moq_auth::Transport::Quic, "/"); setup.token = Some(moq_auth::Token { kind: moq_auth::Token::CAT, value: b"anything".to_vec(), }); - let mut http = auth.request(moq_auth::Transport::Http, "/"); - http.query = Some("jwt=eyJ".into()); - // `moq auth serve` form-decodes the key, so an escaped one is a token too. - let mut escaped = auth.request(moq_auth::Transport::WebSocket, "/"); - escaped.query = Some("%6Awt=eyJ".into()); - for request in [query, setup, http, escaped] { - let Err(err) = auth.admit(request).await else { - panic!("a token was admitted on the public grant"); - }; - assert!(matches!(err, Error::Refused(_)), "{err}"); - } + let Err(err) = auth.admit(setup).await else { + panic!("a token was admitted on the public grant"); + }; + assert!(matches!(err, Error::Refused(_)), "{err}"); - // An empty `jwt=` is no token. - let mut empty = auth.request(moq_auth::Transport::WebSocket, "/"); - empty.query = Some("jwt=&b=2".into()); - assert!(auth.admit(empty).await.is_ok()); + // A query is the client's own: the relay reads no parameter in it as a token. + let mut query = auth.request(moq_auth::Transport::WebSocket, "/"); + query.query = Some("jwt=eyJ".into()); + assert!(auth.admit(query).await.is_ok()); } /// A certificate is a fact the public rules ignore: it gets exactly what anyone does. diff --git a/rs/moq-relay/src/auth/refresh.rs b/rs/moq-relay/src/auth/refresh.rs index 9589a96b0a4..7671fc1122f 100644 --- a/rs/moq-relay/src/auth/refresh.rs +++ b/rs/moq-relay/src/auth/refresh.rs @@ -256,13 +256,13 @@ impl Refresh { request.reject(SessionError::Unsupported, "a certificate cannot be renewed in band"); return; } - let Ok(token) = std::str::from_utf8(request.token()) else { - request.reject(SessionError::MalformedAuthToken, "token is not UTF-8"); - return; - }; + // The dialed query stays as dialed: the attached credential rides `token`, + // whatever bytes it holds. let mut facts = source.request.clone(); - facts.query = Some(with_jwt(facts.query.as_deref(), token)); - facts.token = None; + facts.token = Some(moq_auth::Token { + kind: moq_auth::Token::OUT_OF_BAND, + value: request.token().to_vec(), + }); if self.waiting.len() >= 2 * self.survivors.max(1) { self.waiting.retain(|waiting| !waiting.withdrawn()); self.survivors = self.waiting.len(); @@ -494,34 +494,6 @@ fn refuse(request: auth::Request, err: super::Error) { } } -/// Replace the `jwt` pair, leaving every other byte of the dialed query as it was, -/// since the auth server may interpret or authenticate its raw form. -fn with_jwt(query: Option<&str>, token: &str) -> String { - let jwt = format!( - "jwt={}", - url::form_urlencoded::byte_serialize(token.as_bytes()).collect::() - ); - let mut pairs = Vec::new(); - let mut replaced = false; - let query = query.unwrap_or_default(); - let segments = query.split('&').filter(|_| !query.is_empty()); - for pair in segments { - let is_jwt = url::form_urlencoded::parse(pair.as_bytes()) - .next() - .is_some_and(|(key, _)| key == "jwt"); - if !is_jwt { - pairs.push(pair); - } else if !replaced { - pairs.push(&jwt); - replaced = true; - } - } - if !replaced { - pairs.push(&jwt); - } - pairs.join("&") -} - #[cfg(test)] mod tests { use super::*; @@ -630,6 +602,17 @@ mod tests { (client, server) } + /// What the connection dialed, with an expired credential an attachment must not touch. + const DIALED: &str = "a=1&jwt=expired"; + + /// The credential an attachment carries, asserting the dialed query rode through untouched. + fn presented(admission: &super::super::Admission) -> &[u8] { + assert_eq!(admission.request.query.as_deref(), Some(DIALED)); + let token = admission.request.token.as_ref().expect("an attachment carries a token"); + assert_eq!(token.kind, moq_auth::Token::OUT_OF_BAND); + &token.value + } + async fn admission(initial: Grant) -> (super::super::Lease, super::super::Admissions) { admission_with(initial, super::super::VERIFICATIONS).await } @@ -638,7 +621,8 @@ mod tests { async fn admission_with(initial: Grant, verifications: usize) -> (super::super::Lease, super::super::Admissions) { let (auth, mut admissions) = super::super::Auth::embedded("test"); let auth = auth.with_verifications(verifications); - let request = auth.request(moq_auth::Transport::Quic, "/room"); + let mut request = auth.request(moq_auth::Transport::Quic, "/room"); + request.query = Some(DIALED.into()); let (lease, ()) = tokio::join!(auth.admit(request), async { let admission = admissions.next().await.unwrap(); assert!(!admission.attached(), "a new session arrived as an attachment"); @@ -755,7 +739,7 @@ mod tests { admissions.next().await.unwrap().grant(lease::Consumer::fixed(label)); // Refused as an auth server fault, which may pass, so the client presents it again. let retried = admissions.next().await.unwrap(); - assert_eq!(retried.request.query.as_deref(), Some("jwt=invalid")); + assert_eq!(presented(&retried), b"invalid"); assert!( !invalid.is_finished(), "the invalid label was accepted or ended the token" @@ -771,7 +755,7 @@ mod tests { let auth = client.auth(); let (result, ()) = tokio::join!(added(&auth, "valid"), async { let admission = admissions.next().await.unwrap(); - assert_eq!(admission.request.query.as_deref(), Some("jwt=valid")); + assert_eq!(presented(&admission), b"valid"); admission.grant(lease::Consumer::fixed(grant("a/**", 3000))); }); result.unwrap(); @@ -975,11 +959,7 @@ mod tests { let mut adding = present(&client, "replacement"); for attempt in 0..3 { let admission = admissions.next().await.unwrap(); - assert_eq!( - admission.request.query.as_deref(), - Some("jwt=replacement"), - "attempt {attempt}" - ); + assert_eq!(presented(&admission), b"replacement", "attempt {attempt}"); admission.refuse(super::super::Error::Unavailable("auth server down".into())); // The refusal may pass, so the client presents the token again after a backoff // shorter than each step below, rather than ending it. @@ -1035,7 +1015,7 @@ mod tests { held.remove(0).grant(lease::Consumer::fixed(grant("a/**", 3000))); first.await.unwrap().unwrap(); let admission = admissions.next().await.unwrap(); - assert_eq!(admission.request.query.as_deref(), Some("jwt=third")); + assert_eq!(presented(&admission), b"third"); admission.grant(lease::Consumer::fixed(grant("a/**", 3000))); third.await.unwrap().unwrap(); client.abort(moq_net::Error::Cancel); @@ -1073,7 +1053,7 @@ mod tests { drop(held); let _next = present(&client, "next"); let admission = admissions.next().await.unwrap(); - assert_eq!(admission.request.query.as_deref(), Some("jwt=next")); + assert_eq!(presented(&admission), b"next"); client.abort(moq_net::Error::Cancel); supervising.abort(); let _ = supervising.await; @@ -1087,7 +1067,7 @@ mod tests { let auth = client.auth(); let (token, ()) = tokio::join!(added(&auth, "replacement"), async { let admission = admissions.next().await.unwrap(); - assert_eq!(admission.request.query.as_deref(), Some("jwt=replacement")); + assert_eq!(presented(&admission), b"replacement"); admission.grant(lease::Consumer::fixed(grant("a/**", 20))); }); let token = token.unwrap(); @@ -1317,7 +1297,7 @@ mod tests { held.grant(lease::Consumer::fixed(grant("a/**", 3000))); let admission = admissions.next().await.unwrap(); - assert_eq!(admission.request.query.as_deref(), Some("jwt=next")); + assert_eq!(presented(&admission), b"next"); admission.grant(lease::Consumer::fixed(grant("a/**", 3000))); next.await.unwrap().unwrap(); client.abort(moq_net::Error::Cancel); @@ -1325,16 +1305,23 @@ mod tests { let _ = supervising.await; } - #[test] - fn renewal_replaces_only_the_jwt_pair() { - assert_eq!( - with_jwt(Some("flag&a=%2f&jwt=old&b=x+y&j%77t=dup"), "new token"), - "flag&a=%2f&jwt=new+token&b=x+y" - ); - assert_eq!(with_jwt(Some("flag&&jwt=old&"), "t"), "flag&&jwt=t&"); - assert_eq!(with_jwt(Some("a=1"), "t"), "a=1&jwt=t"); - assert_eq!(with_jwt(Some(""), "t"), "jwt=t"); - assert_eq!(with_jwt(None, "t"), "jwt=t"); + /// A credential that is not UTF-8 reaches the decider unchanged. + #[tokio::test(start_paused = true)] + async fn a_binary_token_is_attached_unchanged() { + let (lease, mut admissions) = admission(grant("a/**", 3000)).await; + let (client, supervising) = sessions(lease).await; + let auth = client.auth(); + let binary: &[u8] = &[0xff, 0x00, 0xfe, b'&', b'=', 0x80]; + let (token, ()) = tokio::join!(added(&auth, binary.to_vec()), async { + let admission = admissions.next().await.unwrap(); + assert!(admission.attached()); + assert_eq!(presented(&admission), binary); + admission.grant(lease::Consumer::fixed(grant("a/**", 3000))); + }); + token.unwrap(); + client.abort(moq_net::Error::Cancel); + supervising.abort(); + let _ = supervising.await; } #[tokio::test(start_paused = true)] diff --git a/rs/moq-relay/tests/integration/auth_lifetime.rs b/rs/moq-relay/tests/integration/auth_lifetime.rs index f18e41163f2..a45dc974258 100644 --- a/rs/moq-relay/tests/integration/auth_lifetime.rs +++ b/rs/moq-relay/tests/integration/auth_lifetime.rs @@ -1942,6 +1942,24 @@ async fn in_band_tokens_widen_and_withdraw_live_prefixes() { script.on_connect(Answer::Grant(replacement)); let token = subscriber.auth().add("replacement").unwrap(); kio::clock::timeout(TIMEOUT, token.answered()).await.unwrap().unwrap(); + // The credential rides `token`; the query is exactly what the client dialed. + let attach = script + .seen + .lock() + .unwrap() + .iter() + .find(|request| request.event == Event::Attach) + .cloned() + .expect("the token was never attached"); + assert_eq!(attach.query.as_deref(), Some("jwt=token"), "{scheme}"); + assert_eq!( + attach.token, + Some(moq_auth::Token { + kind: moq_auth::Token::OUT_OF_BAND, + value: b"replacement".to_vec(), + }), + "{scheme}" + ); let b_read = kio::clock::timeout(TIMEOUT, read.follow("b/cam", None).unwrap().available()) .await .expect("new prefix not announced") From 5287e4ecd9f76b3ab9bcb68feb0ec88145368cfc Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Mon, 16 Nov 2026 18:45:23 -0800 Subject: [PATCH 3/3] fix(auth): moq auth serve reads a previous-release relay's attachment from the query A relay before this change rewrote an attached credential into the query's jwt and cleared the token. Keep reading that shape on attach and revalidate as a marked temporary migration, and refuse an event with auth that carries no credential rather than deciding it on the anonymous rules. Co-Authored-By: Claude Sonnet 5.5 --- doc/bin/relay/auth.md | 3 +- quest/m2/auth-attach-downstream.md | 13 +++++++ rs/moq-auth/src/serve.rs | 59 +++++++++++++++++++++++------- 3 files changed, 60 insertions(+), 15 deletions(-) diff --git a/doc/bin/relay/auth.md b/doc/bin/relay/auth.md index af60e87d47f..bba238d6f4a 100644 --- a/doc/bin/relay/auth.md +++ b/doc/bin/relay/auth.md @@ -195,7 +195,8 @@ the connection's identity. The auth server sees `attach` for the same session id, with a fresh `auth` id that also names its revalidations and end. The attached credential arrives in `token` (`kind` 0, any bytes) and `query` stays exactly as dialed, still holding the connection's first credential, so read an -event with `auth` from `token` alone; `moq auth serve` does. Attached grants revalidate and end +event with `auth` from `token` alone; `moq auth serve` does, and for now also reads the +attached credential from the query's `jwt` when a previous-release relay sends no `token`. Attached grants revalidate and end independently. Each JWT counts against its own `--limit-token` cap while any credential using it remains on that connection. The initial credential remains responsible for the connection's stats tier. diff --git a/quest/m2/auth-attach-downstream.md b/quest/m2/auth-attach-downstream.md index 403a34b03ba..e47f35773be 100644 --- a/quest/m2/auth-attach-downstream.md +++ b/quest/m2/auth-attach-downstream.md @@ -13,6 +13,19 @@ The relay now sends an attached credential as `token` (`kind` 0) and leaves verifies `query` at `attach` sees the connection's first credential instead. Neither the presented token nor its expiry is then the one admitted. +Found at moq.pro `9373cdfb3`: `rs/edge/src/auth/mod.rs` reads the credential +only from `request.query` through `query_jwt` (`:393`), never from +`request.token`. See `:1312-1317` (`End` forgets the query credential), +`:1331` (`Attach` and `Revalidate` decide on the query's `jwt`), `:1061`, and +`limits.rs:179`, `:383`, `:419`. Plain `?jwt=` dials are unaffected. Kixel's +`src/mesh.ts:557` reads a `credential` query parameter, and its client has no +attach use today. + +Until moq.pro reads `token`, it must not meet a relay with this change: +`moq auth serve` reads a previous-release relay's `query` shape for now (a +marked temporary migration in `rs/moq-auth/src/serve.rs`), but moq.pro has no +such reader for the new shape. + ## Waiting - Maintainer: check the moq.pro and Kixel auth handlers read `attach` from diff --git a/rs/moq-auth/src/serve.rs b/rs/moq-auth/src/serve.rs index 11ed49f336c..c1d70759dc5 100644 --- a/rs/moq-auth/src/serve.rs +++ b/rs/moq-auth/src/serve.rs @@ -539,11 +539,18 @@ fn authorize(rules: &Permissions, path: &str) -> Result { /// Both at once count as one only when they are the same JWT. /// /// An attached credential (an event with `auth`) is only its `token`: the `query` is the -/// connection's, still holding the first credential. +/// connection's, still holding the first credential. An event with `auth` and no credential +/// is refused, never decided on the anonymous or mTLS rules. fn jwt(request: &Request) -> Result>, Denial> { - let query = match request.auth { - Some(_) => None, - None => query_jwt(request)?, + let query = match (&request.auth, &request.token) { + // TEMPORARY migration: a relay before this change rewrote an attached credential into + // `jwt` in the query and cleared the token. Delete once no such relay runs beside us. + (Some(_), None) => match query_jwt(request)? { + Some(jwt) => Some(jwt), + None => return Err(Denial::MalformedToken("an attachment needs a token".into())), + }, + (Some(_), Some(_)) => None, + (None, _) => query_jwt(request)?, }; match (&request.token, query) { // A client that offers a version without in-band auth copies its SETUP token @@ -753,10 +760,8 @@ impl Server { /// Answer one event: the grant, or why the session is refused. pub async fn answer(&self, request: &Request) -> Result, Denial> { - if matches!(request.event, Event::Attach) && (request.auth.is_none() || request.token.is_none()) { - return Err(Denial::MalformedToken( - "an attachment needs an auth id and a token".into(), - )); + if matches!(request.event, Event::Attach) && request.auth.is_none() { + return Err(Denial::MalformedToken("an attachment needs an auth id".into())); } let policy = self.policy(); match request.event { @@ -1440,12 +1445,38 @@ mod tests { revalidate.event = Event::Revalidate; assert!(server.answer(&revalidate).await.is_ok()); - // The connection's credential is not the attachment's. - attach.token = None; - assert!(matches!( - server.answer(&attach).await.unwrap_err(), - Denial::MalformedToken(_) - )); + // An attachment with no credential at all is refused, never decided anonymously. + let mut bare = attach.clone(); + bare.token = None; + bare.query = None; + for event in [Event::Attach, Event::Revalidate] { + bare.event = event; + assert!(matches!( + server.answer(&bare).await.unwrap_err(), + Denial::MalformedToken(_) + )); + } + } + + /// TEMPORARY, with the migration in `jwt`: a previous-release relay sends the attached + /// credential as the query's `jwt` with no token, on `attach` and on `revalidate`. + #[tokio::test] + async fn a_previous_relays_attachment_is_read_from_its_query() { + let (dir, key) = key_dir(); + let server = Server::new(Policy { + keys: Some(Keys::Dir(dir.path().into())), + ..Default::default() + }) + .unwrap(); + let attached = sign(&key, "demo", &[], &["**"], None); + let mut attach = with_token(request("/demo"), &attached); + attach.auth = Some("attachment".into()); + for event in [Event::Attach, Event::Revalidate] { + attach.event = event; + let grant = server.answer(&attach).await.unwrap().unwrap(); + assert_eq!(grant.subscribe, patterns(&["**"])); + assert!(grant.publish.is_empty()); + } } /// Two different credentials would leave the server guessing which one the client meant.