diff --git a/drafts/draft-lcurley-moq-lite.md b/drafts/draft-lcurley-moq-lite.md index e60b06b0279..81f2f60a0d6 100644 --- a/drafts/draft-lcurley-moq-lite.md +++ b/drafts/draft-lcurley-moq-lite.md @@ -1374,6 +1374,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. @@ -1443,6 +1444,7 @@ The `Message Length` describes the payload size on the wire. - 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. - Capped the SETUP Message Length at 65,536 bytes. +- 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 dd1a9478977..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"); @@ -158,6 +159,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 }); + try { + 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(); + } + }); + 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 8309b073718..1455effa2b3 100644 --- a/quest/m1/auth/README.md +++ b/quest/m1/auth/README.md @@ -88,7 +88,6 @@ existing lite-06 ALPN. ## Required -- [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 - [Lite NOT_SUPPORTED](/quest/m1/auth/not-supported.md) - a lite acceptor answers AUTH_ERROR NOT_SUPPORTED after a grant too, and lite messages cap at moq-transport's 65,535 bytes - [AUTH violations](/quest/m1/auth/violations.md) - every AUTH protocol violation closes the session in Rust and JS, lite and IETF - [JS fetch grant watch](/quest/m1/auth/js-fetch-watch.md) - a JS `fetchGroup` ends `Unauthorized` when its path leaves the grant diff --git a/quest/m1/auth/error-codes.md b/quest/m1/auth/error-codes.md deleted file mode 100644 index b1bd9e518d4..00000000000 --- a/quest/m1/auth/error-codes.md +++ /dev/null @@ -1,33 +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. - -Public API: none. Wire: none. diff --git a/quest/m1/auth/not-supported.md b/quest/m1/auth/not-supported.md index ccd1e2debd2..09031b14f58 100644 --- a/quest/m1/auth/not-supported.md +++ b/quest/m1/auth/not-supported.md @@ -59,4 +59,4 @@ code, and a lower lite message ceiling. ## Related -- [AUTH endings](/quest/m1/auth/error-codes.md) - a malformed or out-of-range AUTH_ERROR code is refused on the same path +- [AUTH violations](/quest/m1/auth/violations.md) - AUTH protocol violations close the session on the same path (AUTH endings landed in #4550) diff --git a/quest/m1/auth/violations.md b/quest/m1/auth/violations.md index 204aa3da7a1..481af71115b 100644 --- a/quest/m1/auth/violations.md +++ b/quest/m1/auth/violations.md @@ -10,7 +10,7 @@ decode, such as a bad pattern or length. ## Plan -[AUTH endings](/quest/m1/auth/error-codes.md) (#4550) closes the session only +AUTH endings (#4550) closes the session only on an explicit `ProtocolViolation` in Rust lite. These gaps remain: - JS reports the exact oversized code but doesn't close the session. Let the @@ -39,7 +39,3 @@ regression test per case, and check the lite and IETF draft text agrees. Run `just test interop --all`. Public API: none. Wire: none beyond draft wording. - -## Related - -- [AUTH endings](/quest/m1/auth/error-codes.md) - the Rust lite case this generalizes diff --git a/rs/moq-net/src/auth.rs b/rs/moq-net/src/auth.rs index 6403a3ac79a..3a584598ba7 100644 --- a/rs/moq-net/src/auth.rs +++ b/rs/moq-net/src/auth.rs @@ -738,10 +738,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 cf7e591ba76..eb4f0a47560 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; let mut default = None; match self.handle.acceptor() { Some(requests) => { @@ -417,7 +418,7 @@ impl Serve { None => default = Some(crate::auth::DefaultGrant::new(self.handle.clone(), self.peer_grant)), } - let err = match serve_issue(&self.runtime, &issue, default.as_mut(), &mut stream, version).await { + let err = match serve_issue(&self.runtime, issue, default.as_mut(), &mut stream, version).await { Ok(()) => Error::Cancel, Err(err) => { match &err { @@ -429,7 +430,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 45141d585d5..6f3f3c3fa81 100644 --- a/rs/moq-net/src/ietf/session.rs +++ b/rs/moq-net/src/ietf/session.rs @@ -469,6 +469,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); @@ -850,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 diff --git a/rs/moq-net/src/lite/publisher.rs b/rs/moq-net/src/lite/publisher.rs index 706564b19a3..2a004edad4b 100644 --- a/rs/moq-net/src/lite/publisher.rs +++ b/rs/moq-net/src/lite/publisher.rs @@ -384,7 +384,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, /// The default acceptor's grant for the connection's credential, re-sent as a /// new limit changes it. `None` when the app answers. default: Option, @@ -401,7 +401,7 @@ impl AuthServe { Ok(Self { shared, stream: Some(stream), - issue: None, + serving: None, default: None, finished: false, }) @@ -424,8 +424,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(())) } @@ -434,11 +434,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 @@ -456,7 +457,7 @@ impl AuthServe { )); } } - 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 b8b8e236f7d..51f72b3d9d9 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, }, @@ -311,8 +312,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 @@ -356,6 +359,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. @@ -363,7 +368,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. @@ -377,11 +383,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, + } } } @@ -393,6 +405,7 @@ struct PresentToken { version: Version, handle: crate::auth::Handle, going_away: crate::goaway::GoingAway, + violation: kio::Shared>, id: u64, state: PresentState, } @@ -423,6 +436,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(()) } @@ -492,7 +508,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); @@ -740,3 +759,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 1a4711209ea..49ade2886a2 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, @@ -172,6 +173,8 @@ struct Pair { client_transport: MockSession, server_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 { @@ -211,10 +214,10 @@ 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, @@ -222,6 +225,7 @@ async fn connect(opts: Options) -> Pair { client_transport: observe, server_transport: observe_server, requests, + server_driver, } } @@ -605,6 +609,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.