From 240a2b890ab1f2791acbb96db2c702a9a21af86f Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Tue, 29 Sep 2026 13:31:00 -0700 Subject: [PATCH 1/5] chore(quest): claim quest/m1/auth/error-codes Co-Authored-By: Claude Opus 5.5 From c63b1d169f4a4b01a6afc9cc52bfe147230b5264 Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Tue, 29 Sep 2026 15:05:42 -0700 Subject: [PATCH 2/5] fix(net): make every AUTH stream ending exact on both sides A lite AUTH_ERROR code past u32 closes the session with PROTOCOL_VIOLATION instead of saturating. JS AuthSession.close() recomputes the union, and a JS presenter closes its side when the acceptor FINs. A dropped serve task settles Issued::closed with the session's error. Co-Authored-By: Claude Opus 5.5 --- drafts/draft-lcurley-moq-lite.md | 1 + js/net/src/auth.test.ts | 30 +++++++++++++ js/net/src/auth_session.ts | 4 +- quest/m1/auth/README.md | 1 - quest/m1/auth/error-codes.md | 37 ---------------- rs/moq-net/src/auth.rs | 32 ++++++++++++-- rs/moq-net/src/ietf/auth.rs | 9 ++-- rs/moq-net/src/ietf/session.rs | 6 +++ rs/moq-net/src/lite/publisher.rs | 17 ++++---- rs/moq-net/src/lite/session.rs | 74 ++++++++++++++++++++++++++++++-- rs/moq-net/tests/auth.rs | 33 ++++++++++++-- 11 files changed, 182 insertions(+), 62 deletions(-) delete mode 100644 quest/m1/auth/error-codes.md diff --git a/drafts/draft-lcurley-moq-lite.md b/drafts/draft-lcurley-moq-lite.md index 2b4662f099f..6c3ea0fbafe 100644 --- a/drafts/draft-lcurley-moq-lite.md +++ b/drafts/draft-lcurley-moq-lite.md @@ -1372,6 +1372,7 @@ AUTH_ERROR Message { **Error Code**: A code from the [session error registry](#session-error-codes), such as UNAUTHORIZED. +A code that does not fit in 32 bits is a PROTOCOL_VIOLATION that closes the session. **Reason Phrase**: A human-readable reason, at most 8,192 bytes. diff --git a/js/net/src/auth.test.ts b/js/net/src/auth.test.ts index dd1a9478977..a2f0123fe7d 100644 --- a/js/net/src/auth.test.ts +++ b/js/net/src/auth.test.ts @@ -158,6 +158,36 @@ describe.each([Lite.ALPN_06, Ietf.ALPN.DRAFT_17, Ietf.ALPN.DRAFT_22])("%s", (pro server.close(); }); + test("closing the session drops the grant", async () => { + const { client, server } = await connect({ publish: new OriginProducer(), protocol }); + await waitFor(client.auth.grant, (g) => g !== undefined && g.publish.size > 0); + + // Checked before any stream notices the transport closing. + client.close(); + const closed = client.auth.grant.peek(); + expect(closed?.publish.size).toBe(0); + expect(closed?.subscribe.size).toBe(0); + server.close(); + }); + + test("an acceptor that ends a grant sees its stream close", async () => { + const { client, server } = await connect({ publish: new OriginProducer(), protocol }); + const requests = server.auth.requests(); + const request = await requests.next(); + const issued = request?.accept(grant(["a"], [])); + await waitFor(client.auth.grant, (g) => g !== undefined && g.publish.size > 0); + + issued?.close(); + let timer: ReturnType | undefined; + const timeout = new Promise((resolve) => { + timer = setTimeout(() => resolve("timeout"), 1000); + }); + expect(await Promise.race([issued?.closed, timeout])).toBeNull(); + clearTimeout(timer); + client.close(); + server.close(); + }); + test("a refused setup token grants nothing rather than everything", async () => { const { client, server } = await connect({ publish: new OriginProducer(), protocol }); const requests = server.auth.requests(); diff --git a/js/net/src/auth_session.ts b/js/net/src/auth_session.ts index 5f5f16705c9..ac9c3824c65 100644 --- a/js/net/src/auth_session.ts +++ b/js/net/src/auth_session.ts @@ -324,6 +324,7 @@ export class AuthSession implements AuthApi { this.#closed = true; for (const token of this.#tokens) token.end(new Error("session closed")); this.#tokens.clear(); + this.#recompute(); if (this.#acceptor instanceof RequestQueue) this.#acceptor.close(); } @@ -346,8 +347,9 @@ export class AuthSession implements AuthApi { const reply = await wire.read(stream); if (!reply) { // The peer ended the grant without revoking it, or closed without ever - // answering. + // answering. Close our side too, which is what settles its Issued.closed. result = token.isAnswered ? null : new Unsupported(); + stream.close(); break; } if ("grant" in reply) { diff --git a/quest/m1/auth/README.md b/quest/m1/auth/README.md index b930917037f..adc08e4670c 100644 --- a/quest/m1/auth/README.md +++ b/quest/m1/auth/README.md @@ -90,7 +90,6 @@ existing lite-06 ALPN. ## Required - [AUTH_OK preflight](/quest/m1/auth/auth-ok-preflight.md) - an unencodable IETF grant answers NOT_SUPPORTED with nothing written, as JS already does -- [AUTH endings](/quest/m1/auth/error-codes.md) - an out-of-range AUTH_ERROR code is refused, and both sides settle and recompute grants when a stream ends - [Origin narrowing](/quest/m1/auth/narrowing.md) - a live grant narrows in place: subscriptions outside it reset, publishes outside it abort, and relay revalidation stops closing the session diff --git a/quest/m1/auth/error-codes.md b/quest/m1/auth/error-codes.md deleted file mode 100644 index 71881c1f510..00000000000 --- a/quest/m1/auth/error-codes.md +++ /dev/null @@ -1,37 +0,0 @@ -# [S] AUTH endings are exact on both sides - -## Goal - -The loose ends Codex left on [#4062](https://github.com/moq-dev/moq/pull/4062) -are closed, so every way an AUTH stream ends reports what actually happened: - -- A lite AUTH_ERROR whose code does not fit a `u32` is a protocol violation. - Today `rs/moq-net/src/lite/session.rs` saturates it with - `u32::try_from(refused.code).unwrap_or(u32::MAX)`, so distinct peer codes - collapse into one and the app sees a code the peer never sent. -- JS `AuthSession.close()` in `js/net/src/auth_session.ts` clears its tokens - but never recomputes the union, so a retained `auth.grant` keeps reporting - a live grant after the session closed. Rust already clears it. -- A JS presenter whose acceptor ends the grant with a clean FIN exits the read - loop without closing its own write half, unlike the AUTH_ERROR branch, so - the acceptor's `Issued.closed` stays pending until the session ends. -- A Rust `Issued::closed()` never resolves if the session drops the task - serving that token (`AuthServe` in the lite publisher, `Serve` in - `ietf/auth.rs`): only the task's own completion records `issue.peer`. - -## Plan - -- Fail loud on the unrepresentable code rather than widen the error type: - the codes AUTH_ERROR carries are session codes, which are `u32` everywhere - else. A malformed AUTH_ERROR closes the session with PROTOCOL_VIOLATION, - the same rule as a malformed AUTH_OK, rather than ending only the token. -- Settle a dropped serve task from a drop path (a guard that records the - session's error on `Issue` and wakes waiters), so no exit path can forget - it. -- One regression test per item, each failing without its fix. - -The fifth deferred item, a grant recheck after async origin resolution, -belongs to [Origin narrowing](/quest/m1/auth/narrowing.md) with the other -watcher races. - -Public API: none. Wire: none. diff --git a/rs/moq-net/src/auth.rs b/rs/moq-net/src/auth.rs index 7ea4acf06a5..cd02cd17f83 100644 --- a/rs/moq-net/src/auth.rs +++ b/rs/moq-net/src/auth.rs @@ -606,10 +606,34 @@ pub(crate) struct Issue { pub peer: Option, } -impl Issue { - /// A fresh stream's shared state. - pub(crate) fn shared() -> kio::Shared { - kio::Shared::default() +/// The serving task's hold on one peer token's [`Issue`]. +/// +/// Dropping it settles [`Issued::closed`] with the session's error, unless the task +/// already recorded why the stream ended, so no exit path leaves the acceptor waiting. +pub(crate) struct Serving { + pub issue: kio::Shared, + handle: Handle, +} + +impl Serving { + /// A fresh stream's shared state, settled by the session `handle` if the task drops. + pub(crate) fn new(handle: Handle) -> Self { + Self { + issue: kio::Shared::default(), + handle, + } + } + + /// Record why the stream ended on the peer's side; the first reason wins. + pub(crate) fn end(&self, err: Error) { + self.issue.lock().peer.get_or_insert(err); + } +} + +impl Drop for Serving { + fn drop(&mut self) { + let err = self.handle.state.read().closed().unwrap_or(Error::Cancel); + self.end(err); } } diff --git a/rs/moq-net/src/ietf/auth.rs b/rs/moq-net/src/ietf/auth.rs index 76214462b56..c72ad14a344 100644 --- a/rs/moq-net/src/ietf/auth.rs +++ b/rs/moq-net/src/ietf/auth.rs @@ -13,7 +13,7 @@ use std::time::Duration; use bytes::Bytes; -use crate::auth::{Grant, Handle, Issue, Reply, Request}; +use crate::auth::{Grant, Handle, Issue, Reply, Request, Serving}; use crate::coding::{Decode, DecodeError, Encode, EncodeError, Sizer, Stream}; use crate::{Error, Path, Pattern, Patterns, SessionError}; @@ -394,7 +394,8 @@ impl Serve { msg: Auth, version: Version, ) { - let issue = Issue::shared(); + let serving = Serving::new(self.handle.clone()); + let issue = &serving.issue; match self.handle.acceptor() { Some(requests) => { // A closed queue hands the request back, and dropping it refuses the token. @@ -415,7 +416,7 @@ impl Serve { None => issue.lock().outbox.push_back(Reply::Grant(self.peer_grant)), } - let err = match serve_issue(&self.runtime, &issue, &mut stream, version).await { + let err = match serve_issue(&self.runtime, issue, &mut stream, version).await { Ok(()) => Error::Cancel, Err(err) => { match &err { @@ -427,7 +428,7 @@ impl Serve { err } }; - issue.lock().peer.get_or_insert(err); + serving.end(err); } } diff --git a/rs/moq-net/src/ietf/session.rs b/rs/moq-net/src/ietf/session.rs index 496f9541655..b6414638749 100644 --- a/rs/moq-net/src/ietf/session.rs +++ b/rs/moq-net/src/ietf/session.rs @@ -466,6 +466,12 @@ where Poll::Pending }) .await; + // Before this arm's Auth serve tasks drop, so each settles with the + // session's error rather than a bare cancel. + auth.close(match &res { + Ok(()) => Error::Cancel, + Err(err) => err.clone(), + }); if let Err(err) = &res { // Every track this session was receiving ends with its error. subscriber.abort(err); diff --git a/rs/moq-net/src/lite/publisher.rs b/rs/moq-net/src/lite/publisher.rs index 321af8bb81b..46313a747c7 100644 --- a/rs/moq-net/src/lite/publisher.rs +++ b/rs/moq-net/src/lite/publisher.rs @@ -350,7 +350,7 @@ struct AuthServe { stream: Option>, /// Shared with the app's [`crate::auth::Request`] / [`crate::auth::Issued`], or /// filled in by the default acceptor. - issue: Option>, + serving: Option, /// Our side is finished: FIN sent, waiting for the acknowledgement. finished: bool, } @@ -364,7 +364,7 @@ impl AuthServe { Ok(Self { shared, stream: Some(stream), - issue: None, + serving: None, finished: false, }) } @@ -386,8 +386,8 @@ impl AuthServe { err } }; - if let Some(issue) = &self.issue { - issue.lock().peer.get_or_insert(err); + if let Some(serving) = &self.serving { + serving.end(err); } Poll::Ready(Ok(())) } @@ -396,11 +396,12 @@ impl AuthServe { let mut cx = Context::from_waker(waiter.waker()); let stream = self.stream.as_mut().expect("stream present"); - let issue = match &self.issue { - Some(issue) => issue.clone(), + let issue = match &self.serving { + Some(serving) => serving.issue.clone(), None => { let msg = ready!(stream.reader.poll_decode::(&mut cx))?; - let issue = crate::auth::Issue::shared(); + let serving = crate::auth::Serving::new(self.shared.auth.clone()); + let issue = serving.issue.clone(); match self.shared.auth.acceptor() { Some(requests) => { // A closed queue hands the request back, and dropping it refuses @@ -416,7 +417,7 @@ impl AuthServe { issue.lock().outbox.push_back(crate::auth::Reply::Grant(grant)); } } - self.issue = Some(issue.clone()); + self.serving = Some(serving); issue } }; diff --git a/rs/moq-net/src/lite/session.rs b/rs/moq-net/src/lite/session.rs index 85b5e33bbaa..4a7a833b808 100644 --- a/rs/moq-net/src/lite/session.rs +++ b/rs/moq-net/src/lite/session.rs @@ -230,6 +230,7 @@ where handle: auth.clone(), going_away: goaway.going_away.clone(), tokens: kio::Tasks::new(), + violation: Default::default(), started: false, _setup: setup_token, }, @@ -306,8 +307,10 @@ where fn poll_protocol(&mut self, waiter: &kio::Waiter) -> Poll> { let mut cx = Context::from_waker(waiter.waker()); - // Presenting tokens never ends the session. - self.auth.poll(waiter); + // Presenting tokens ends the session only when the peer breaks the protocol. + if let Poll::Ready(err) = self.auth.poll(waiter) { + return Poll::Ready(Err(err)); + } // The send-side machines never end the session; completion just retires them. if let Some(setup) = &mut self.setup @@ -351,6 +354,8 @@ struct Present { handle: crate::auth::Handle, going_away: crate::goaway::GoingAway, tokens: kio::Tasks>, + /// Set by a token whose peer broke the protocol, which ends the session. + violation: kio::Shared>, /// Whether the first poll decided who answers the peer's tokens. started: bool, /// The connection's own credential, held for the life of the session. @@ -358,7 +363,8 @@ struct Present { } impl Present { - fn poll(&mut self, waiter: &kio::Waiter) { + /// Resolve only when a token's peer broke the protocol. + fn poll(&mut self, waiter: &kio::Waiter) -> Poll { if !self.started { // Decided once, before any AUTH stream can be accepted: the app took the // requests before running the driver, or the session answers itself. @@ -372,11 +378,17 @@ impl Present { version: self.version, handle: self.handle.clone(), going_away: self.going_away.clone(), + violation: self.violation.clone(), id, state: PresentState::Open { token }, }); } let _ = self.tokens.poll(waiter); + // A token sets it from inside the poll above, so nothing needs waking. + match self.violation.lock().take() { + Some(err) => Poll::Ready(err), + None => Poll::Pending, + } } } @@ -388,6 +400,7 @@ struct PresentToken { version: Version, handle: crate::auth::Handle, going_away: crate::goaway::GoingAway, + violation: kio::Shared>, id: u64, state: PresentState, } @@ -418,6 +431,9 @@ impl kio::Task for PresentToken { } err => tracing::warn!(%err, "auth token ended"), } + if let Error::ProtocolViolation = err { + self.violation.lock().get_or_insert(err.clone()); + } self.handle.ended(self.id, err); Poll::Ready(()) } @@ -487,7 +503,10 @@ impl PresentToken { ); } super::AuthReply::Error(refused) => { - let code = u32::try_from(refused.code).unwrap_or(u32::MAX); + // Session codes are u32 everywhere else, so a wider one is malformed. + let Ok(code) = u32::try_from(refused.code) else { + return Poll::Ready(Error::ProtocolViolation); + }; let err = Error::Session(crate::SessionError::from_code(code)); tracing::warn!(%err, reason = %refused.reason, "auth token refused"); self.handle.refused(self.id); @@ -735,3 +754,50 @@ impl SendGoaway { } } } + +#[cfg(test)] +mod tests { + use super::*; + use crate::coding::Encode; + use crate::lite::test_transport::ScriptedSession; + + /// An AUTH_ERROR code the session registry cannot hold is the peer breaking the + /// protocol: it closes the session rather than surfacing a code the peer never sent. + #[tokio::test(start_paused = true)] + async fn an_auth_error_code_past_u32_closes_the_session() { + let refused = crate::lite::AuthReply::Error(crate::lite::AuthError { + code: u64::from(u32::MAX) + 1, + reason: String::new(), + }); + let mut script = Vec::new(); + refused.encode(&mut script, Version::Lite06).unwrap(); + // The setup token's AUTH stream is the first one the session opens. + let transport = ScriptedSession::per_stream(vec![script]); + let log = transport.log.clone(); + + let start = start(Config { + runtime: crate::time::Clock::tokio(), + client: true, + session: transport, + setup_stream: None, + publish: None, + subscribe: None, + peer_hop: None, + version: Version::Lite06, + our_setup: Setup::default(), + peer_setup: None, + auth: crate::auth::Handle::new(true), + }) + .unwrap(); + let mut driver = start.driver; + + let res = tokio::time::timeout( + std::time::Duration::from_secs(10), + kio::wait(|waiter| driver.poll(waiter)), + ) + .await + .expect("the session outlived a malformed AUTH_ERROR"); + assert!(matches!(res, Err(Error::ProtocolViolation)), "{res:?}"); + assert_eq!(log.closes()[0].0, SessionError::ProtocolViolation.to_code()); + } +} diff --git a/rs/moq-net/tests/auth.rs b/rs/moq-net/tests/auth.rs index 2cd2592cd48..f5879844bd3 100644 --- a/rs/moq-net/tests/auth.rs +++ b/rs/moq-net/tests/auth.rs @@ -50,6 +50,7 @@ cases!( a_refused_setup_token_grants_nothing, dropping_the_requests_refuses_queued_tokens, a_closed_session_holds_no_grant, + an_issued_grant_ends_with_its_session, a_reset_auth_stream_reports_unsupported, a_revoked_grant_cancels_its_subscriptions, nothing_outside_the_grant_reaches_the_peer, @@ -163,6 +164,8 @@ struct Pair { server: Session, client_transport: MockSession, requests: Option, + /// Aborting it drops the server's driver without letting it finish. + server_driver: tokio::task::AbortHandle, } async fn connect(opts: Options) -> Pair { @@ -201,16 +204,17 @@ async fn connect(opts: Options) -> Pair { .server_requests .then(|| handshake.auth().requests().expect("requests available before ok()")); let (session, driver) = handshake.ok().await.expect("server accept"); - tokio::spawn(run(driver)); - (session, requests) + let driver = tokio::spawn(run(driver)).abort_handle(); + (session, requests, driver) }; - let (client, (server, requests)) = tokio::join!(client_fut, server_fut); + let (client, (server, requests, server_driver)) = tokio::join!(client_fut, server_fut); Pair { client, server, client_transport: observe, requests, + server_driver, } } @@ -594,6 +598,29 @@ async fn a_closed_session_holds_no_grant(version: &'static str) { .expect("timed out"); } +/// A grant this side issued settles once its session ends, even when the task serving +/// its stream is dropped rather than run to completion. +async fn an_issued_grant_ends_with_its_session(version: &'static str) { + within(async { + let mut pair = connect(Options { + version: Some(version), + client_publish: Some(produce_origin(2)), + server_requests: true, + ..Default::default() + }) + .await; + let mut requests = pair.requests.take().unwrap(); + let issued = requests.next().await.expect("setup token").accept(Grant::default()); + granted(&pair.client).await; + + pair.server_driver.abort(); + let err = issued.closed().await; + assert!(matches!(err, Error::Cancel), "{err:?}"); + }) + .await + .expect("timed out"); +} + /// A peer that takes no tokens in band says so (lite resets the stream, moq-transport /// answers NOT_SUPPORTED), which reads as unsupported rather than a refusal: the same as /// a peer that predates AUTH. From 39d5f08ab3d964cde6fc1930e4f7574f47573b7e Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Tue, 29 Sep 2026 16:12:09 -0700 Subject: [PATCH 3/5] fix(net): log the AUTH_ERROR code limit, and drop the raw timer in its JS test Co-Authored-By: Claude Opus 5.5 --- drafts/draft-lcurley-moq-lite.md | 1 + js/net/src/auth.test.ts | 17 ++++++++--------- 2 files changed, 9 insertions(+), 9 deletions(-) diff --git a/drafts/draft-lcurley-moq-lite.md b/drafts/draft-lcurley-moq-lite.md index 6c3ea0fbafe..1ce2004279a 100644 --- a/drafts/draft-lcurley-moq-lite.md +++ b/drafts/draft-lcurley-moq-lite.md @@ -1441,6 +1441,7 @@ The `Message Length` describes the payload size on the wire. - Removed SUBSCRIBE_DROP and its type 0x2; a group without a Group Stream is not counted. - The Subscribe Stream FIN now follows once every counted Group Stream has finished or been reset. - Added announce compression: ANNOUNCE_START gains `Path Base` and `Path Keep` to copy the head of a live advertisement's suffix, and ANNOUNCE_START and ANNOUNCE_UPDATE gain `Hop Base` and `Hop Keep` to copy the tail of a live advertisement's Hop ID list. +- An AUTH_ERROR code that does not fit in 32 bits is a PROTOCOL_VIOLATION. ## moq-lite-06 diff --git a/js/net/src/auth.test.ts b/js/net/src/auth.test.ts index a2f0123fe7d..3912c7286b9 100644 --- a/js/net/src/auth.test.ts +++ b/js/net/src/auth.test.ts @@ -177,15 +177,14 @@ describe.each([Lite.ALPN_06, Ietf.ALPN.DRAFT_17, Ietf.ALPN.DRAFT_22])("%s", (pro const issued = request?.accept(grant(["a"], [])); await waitFor(client.auth.grant, (g) => g !== undefined && g.publish.size > 0); - issued?.close(); - let timer: ReturnType | undefined; - const timeout = new Promise((resolve) => { - timer = setTimeout(() => resolve("timeout"), 1000); - }); - expect(await Promise.race([issued?.closed, timeout])).toBeNull(); - clearTimeout(timer); - client.close(); - server.close(); + try { + issued?.close(); + // A regression leaves `closed` pending, so the test runner's timeout fails it. + expect(await issued?.closed).toBeNull(); + } finally { + client.close(); + server.close(); + } }); test("a refused setup token grants nothing rather than everything", async () => { From d2755ac02b3e0adcc72f5acd9749337af18782c1 Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Tue, 29 Sep 2026 21:48:00 -0700 Subject: [PATCH 4/5] test(net): bound the JS grant-stream regression wait A regression left `Issued.closed` pending, so the test hung until the runner's own timeout, once per protocol. Race it against the existing `withTimeout` helper, which clears its timer, and fail loud when the setup token never arrives. --- js/net/src/auth.test.ts | 18 ++++++++++-------- 1 file changed, 10 insertions(+), 8 deletions(-) diff --git a/js/net/src/auth.test.ts b/js/net/src/auth.test.ts index 3912c7286b9..ab0690a2a78 100644 --- a/js/net/src/auth.test.ts +++ b/js/net/src/auth.test.ts @@ -10,6 +10,7 @@ import { Producer as OriginProducer } from "./origin.ts"; import * as Path from "./path.ts"; import { Writer } from "./stream.ts"; import { Timestamp } from "./time.ts"; +import { withTimeout } from "./util/timeout.ts"; import { wireOf } from "./wire.ts"; const url = new URL("https://localhost:4443/test"); @@ -172,15 +173,16 @@ describe.each([Lite.ALPN_06, Ietf.ALPN.DRAFT_17, Ietf.ALPN.DRAFT_22])("%s", (pro test("an acceptor that ends a grant sees its stream close", async () => { const { client, server } = await connect({ publish: new OriginProducer(), protocol }); - const requests = server.auth.requests(); - const request = await requests.next(); - const issued = request?.accept(grant(["a"], [])); - await waitFor(client.auth.grant, (g) => g !== undefined && g.publish.size > 0); - try { - issued?.close(); - // A regression leaves `closed` pending, so the test runner's timeout fails it. - expect(await issued?.closed).toBeNull(); + const requests = server.auth.requests(); + const request = await requests.next(); + if (!request) throw new Error("the setup token never arrived"); + const issued = request.accept(grant(["a"], [])); + await waitFor(client.auth.grant, (g) => g !== undefined && g.publish.size > 0); + + issued.close(); + // A regression leaves `closed` pending, so bound the wait rather than hang the runner. + expect(await withTimeout(Promise.resolve(issued.closed), 1000, "the grant stream never closed")).toBeNull(); } finally { client.close(); server.close(); From 6857be9ba85ec349c1168ee2c0a46ea8897247d5 Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Wed, 30 Sep 2026 06:29:52 -0700 Subject: [PATCH 5/5] fix(net): settle grants with the error that ended the session `run_dispatch` owns the TaskSet that holds the AUTH serve tasks, so an error return dropped them before the driver reached its own `auth.close`. The new `Serving` guard then read a still-open handle and recorded `Cancel`, and because the first reason wins, the driver's later close with the real error could not correct it. Every grant on the session reported a bare cancel instead of, say, `UnexpectedStream`. Scope the loop so the handle closes while `tasks` is still alive. The driver closes it again with the same error, which then does nothing. No public API or wire change. Co-Authored-By: Space Bunny Free --- rs/moq-net/src/ietf/session.rs | 152 +++++++++++++++++++-------------- 1 file changed, 88 insertions(+), 64 deletions(-) diff --git a/rs/moq-net/src/ietf/session.rs b/rs/moq-net/src/ietf/session.rs index d296815f80f..6f3f3c3fa81 100644 --- a/rs/moq-net/src/ietf/session.rs +++ b/rs/moq-net/src/ietf/session.rs @@ -856,74 +856,98 @@ where let declared = subscriber.solicit().await; let mut tasks = TaskSet::owned(); - let mut accept = session.clone(); - loop { - let mut stream = tasks - .drive(|waiter| { - let mut cx = std::task::Context::from_waker(waiter.waker()); - Stream::poll_accept(&mut accept, version, &mut cx) - }) - .await?; - - // The intermediate results live outside the poll closure, so a Pending - // mid-header resumes where it left off. - let mut hdr_id: Option = None; - let mut hdr_size: Option = None; - let header = tasks - .drive(|waiter| { - let mut cx = std::task::Context::from_waker(waiter.waker()); - let id = match hdr_id { - Some(id) => id, - None => *hdr_id.insert(std::task::ready!(stream.reader.poll_decode(&mut cx))?), - }; - let size = match hdr_size { - Some(size) => size, - None => *hdr_size.insert(std::task::ready!(stream.reader.poll_decode(&mut cx))?), - }; - let data = std::task::ready!(stream.reader.poll_read_exact(&mut cx, size as usize))?; - std::task::Poll::Ready(Ok::<_, Error>((id, data))) - }) - .await; - // Same tolerance as `run_unis`: a request stream that dies before its header - // is the peer abandoning that request, not the session. Anything else, a - // header that does not parse included, still fails the session. - let (id, data) = match header { - Ok(header) => header, - Err(err @ (Error::Cancel | Error::Stream(_) | Error::Remote(_) | Error::Decode(DecodeError::Short))) => { - tracing::debug!(%err, "dropping bidi stream that died before its header"); - continue; - } - Err(err) => return Err(err), - }; - - match id { - // Publisher handles: Subscribe, Fetch, SubscribeNamespace (0x50 modern / - // 0x11 legacy), TrackStatus - ietf::Subscribe::ID - | ietf::Fetch::ID - | ietf::SubscribeNamespace::ID - | ietf::SubscribeNamespaceLegacy::ID - | ietf::TrackStatus::ID => { - tasks.push(publisher.handle_stream(id, data, stream)?); - } - // Subscriber handles: Publish, PublishNamespace - ietf::Publish::ID | ietf::PublishNamespace::ID => { - tasks.push(subscriber.handle_stream(id, data, stream, peer, declared)?); - } - auth::Auth::ID if let Some(serve) = &serve => { - let mut data = data; - let msg = auth::Auth::decode_msg(&mut data, version)?; - if !data.is_empty() { - return Err(Error::WrongSize); + // Each AUTH serve task settles `Issued::closed` from whatever the auth handle + // holds when it drops, and the first reason wins. So the error that ends the + // session has to reach the handle while `tasks` is still alive, or every grant + // reports a bare cancel instead. `None` when the peer never negotiated AUTH, + // which leaves no serve task to settle. + let handle = serve.as_ref().map(|serve| serve.handle.clone()); + + // Scoped so `tasks` outlives the close below: the loop borrows it, so it only + // drops once this block's future is done. + let res: Result<(), Error> = async { + let mut accept = session.clone(); + loop { + let mut stream = tasks + .drive(|waiter| { + let mut cx = std::task::Context::from_waker(waiter.waker()); + Stream::poll_accept(&mut accept, version, &mut cx) + }) + .await?; + + // The intermediate results live outside the poll closure, so a Pending + // mid-header resumes where it left off. + let mut hdr_id: Option = None; + let mut hdr_size: Option = None; + let header = tasks + .drive(|waiter| { + let mut cx = std::task::Context::from_waker(waiter.waker()); + let id = match hdr_id { + Some(id) => id, + None => *hdr_id.insert(std::task::ready!(stream.reader.poll_decode(&mut cx))?), + }; + let size = match hdr_size { + Some(size) => size, + None => *hdr_size.insert(std::task::ready!(stream.reader.poll_decode(&mut cx))?), + }; + let data = std::task::ready!(stream.reader.poll_read_exact(&mut cx, size as usize))?; + std::task::Poll::Ready(Ok::<_, Error>((id, data))) + }) + .await; + // Same tolerance as `run_unis`: a request stream that dies before its header + // is the peer abandoning that request, not the session. Anything else, a + // header that does not parse included, still fails the session. + let (id, data) = match header { + Ok(header) => header, + Err( + err @ (Error::Cancel | Error::Stream(_) | Error::Remote(_) | Error::Decode(DecodeError::Short)), + ) => { + tracing::debug!(%err, "dropping bidi stream that died before its header"); + continue; + } + Err(err) => return Err(err), + }; + + match id { + // Publisher handles: Subscribe, Fetch, SubscribeNamespace (0x50 modern / + // 0x11 legacy), TrackStatus + ietf::Subscribe::ID + | ietf::Fetch::ID + | ietf::SubscribeNamespace::ID + | ietf::SubscribeNamespaceLegacy::ID + | ietf::TrackStatus::ID => { + tasks.push(publisher.handle_stream(id, data, stream)?); + } + // Subscriber handles: Publish, PublishNamespace + ietf::Publish::ID | ietf::PublishNamespace::ID => { + tasks.push(subscriber.handle_stream(id, data, stream, peer, declared)?); + } + auth::Auth::ID if let Some(serve) = &serve => { + let mut data = data; + let msg = auth::Auth::decode_msg(&mut data, version)?; + if !data.is_empty() { + return Err(Error::WrongSize); + } + tasks.push(serve.clone().run(stream, msg, version)); + } + _ => { + tracing::warn!(id, "unexpected bidi stream type"); + return Err(Error::UnexpectedStream); } - tasks.push(serve.clone().run(stream, msg, version)); - } - _ => { - tracing::warn!(id, "unexpected bidi stream type"); - return Err(Error::UnexpectedStream); } } } + .await; + + // Every error exit above drops the AUTH serve tasks in `tasks`, so the session's + // error has to land on the handle first. The driver closes it again with the same + // error, which then does nothing. + if let Some(handle) = &handle + && let Err(err) = &res + { + handle.close(err.clone()); + } + res } /// Monitor the peer's SETUP stream for a GOAWAY, surfacing it through