From 5ac3ab028342257b106d366d7bc2b6bc4f399e0e Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Sat, 7 Nov 2026 14:36:18 -0800 Subject: [PATCH 1/5] chore(quest): claim quest/m1/auth-stream-bounds.md Quest-Claim: 5fafc03227cf6b55 From 729d176873a6abad455b800fbc4260989db06bd9 Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Sat, 7 Nov 2026 14:41:12 -0800 Subject: [PATCH 2/5] fix(net): session auth replies revoke and stay bounded An AUTH_OK the driver cannot encode now withdraws its grant from the session's scope along with the AUTH_ERROR that replaces it. A newer reply replaces a grant still queued, so a peer withholding stream credit holds at most one. Tokens::set withdraws a replaced token at once unless it was granted, so sets during a failing backend never pile up retrying streams. Handing the request queue to a new acceptor refuses the queued tokens after releasing the handle's lock, which refusing takes again. Co-Authored-By: Claude Opus 5.5 --- quest/m1/README.md | 1 - quest/m1/auth-stream-bounds.md | 14 ---- rs/moq-net/src/auth.rs | 138 +++++++++++++++++++++++++++---- rs/moq-net/src/auth/tokens.rs | 33 +++++++- rs/moq-net/src/ietf/auth.rs | 14 ++-- rs/moq-net/src/lite/publisher.rs | 14 ++-- 6 files changed, 164 insertions(+), 50 deletions(-) delete mode 100644 quest/m1/auth-stream-bounds.md diff --git a/quest/m1/README.md b/quest/m1/README.md index 903693c5f1a..9dddaa0c42d 100644 --- a/quest/m1/README.md +++ b/quest/m1/README.md @@ -58,7 +58,6 @@ moves what remains of them once their claims merge. - [A cancelled dispatch lane stops its phase promptly](/quest/m1/dispatch-cancel-race.md) - a TERM landing just before a lane forks its phase's command still stops that command, instead of waiting out the phase - [Lifecycles are explicit state](/quest/m1/explicit-state/README.md) - every lifecycle the 2026-11-07 audit found implicit is one enum or union, fixing the bugs in the 11 lifecycles it redesigns, with review and agent rules against new ones - [Copies of one group identity must agree beyond their bytes](/quest/m1/copy-identity.md) - copies that differ in timestamp, object fields, or frame count fail as a protocol violation -- [Session auth grants and replies stay consistent and bounded](/quest/m1/auth-stream-bounds.md) - an AUTH_ERROR revokes its grant, queued grants and retiring tokens are bounded, and dropping queued requests cannot deadlock - [Relay settings and admin input that cannot work are refused](/quest/m1/relay-config-checks.md) - clustered stats without a node name, pin without workers, repeated filter keys, and unknown transports fail loud - [Track drop runs are forgotten below the floor](/quest/m1/drop-runs-prune.md) - a track's dropped-group record stays proportional to its window in Rust and JS diff --git a/quest/m1/auth-stream-bounds.md b/quest/m1/auth-stream-bounds.md deleted file mode 100644 index 82188051bd1..00000000000 --- a/quest/m1/auth-stream-bounds.md +++ /dev/null @@ -1,14 +0,0 @@ -# [S] Session auth grants and replies stay consistent and bounded - -## Goal - -moq-net's session-side auth (`rs/moq-net/src/auth.rs`, `auth/tokens.rs`, and the AUTH stream loops in `lite/publisher.rs` and `ietf/auth.rs`) keeps four promises it currently leaves to callers: - -- A token answered with AUTH_ERROR leaves the enforced scope at once. Today an AUTH_OK too large to encode is replaced by AUTH_ERROR and `state.done = true` without `Issue::finish`, so the grant `reply()` already recorded keeps admitting requests for the session. -- Replies queued for a peer that withholds stream credit are bounded: a newer `Reply::Grant` replaces a queued one instead of appending to the outbox. -- Tokens replaced by `Tokens::set` are withdrawn even when they were never answered; a backend failing transiently while the app rotates JWTs does not pile up retrying AUTH streams. -- `Handle::requests` never drops queued `Request`s under the state lock (dropping one re-enters it); take them out and drop them after the guard. - -## Plan - -Found by the 2026-11-07 invariant audit (lite-2, lite-5, lite-6, lite-8). Each gets a test: `allows()` is false after an oversize accept, repeated `Issued::update` on a blocked stream keeps one queued grant, two `set` calls with no answer leave one retiring generation, and swapping the acceptor with queued requests does not deadlock. diff --git a/rs/moq-net/src/auth.rs b/rs/moq-net/src/auth.rs index 8623a8acc55..2e90b5901b8 100644 --- a/rs/moq-net/src/auth.rs +++ b/rs/moq-net/src/auth.rs @@ -683,19 +683,23 @@ impl Handle { /// Called before the session's driver first polls, since that decides who answers. /// A later call hands the queue to the new [`Requests`], ending the earlier one. pub(crate) fn requests(&self) -> Requests { - let mut state = self.state.lock(); - debug_assert!( - !matches!(state.acceptor, Acceptor::Default), - "the driver already answers the peer's tokens" - ); - if let Acceptor::App(earlier) = &state.acceptor { + let queue = Pending::default(); + let (earlier, closed) = { + let mut state = self.state.lock(); + debug_assert!( + !matches!(state.acceptor, Acceptor::Default), + "the driver already answers the peer's tokens" + ); + let earlier = std::mem::replace(&mut state.acceptor, Acceptor::App(queue.clone())); + (earlier, state.closed.is_some()) + }; + // Closed once the lock is released, since refusing its tokens takes the lock again. + if let Acceptor::App(earlier) = earlier { earlier.close(); } - let queue = Pending::default(); - if state.closed.is_some() { + if closed { queue.close(); } - state.acceptor = Acceptor::App(queue.clone()); Requests { queue } } @@ -1676,10 +1680,15 @@ struct PendingState { } impl Pending { + /// Refuse every queued token and every later one. Call it without the handle's lock, + /// which refusing a token takes. fn close(&self) { - let mut state = self.state.lock(); - state.closed = true; - state.requests.clear(); + let refused = { + let mut state = self.state.lock(); + state.closed = true; + std::mem::take(&mut state.requests) + }; + drop(refused); } /// Queue the token for the application, or refuse it when closed. @@ -1734,13 +1743,14 @@ pub(crate) enum Reply { /// The acceptor's side of one peer token's stream, shared with the driver. #[derive(Default)] pub(crate) struct Issue { - /// Replies for the driver to write, in order. - pub outbox: VecDeque, + /// Replies for the driver to write, in order: at most a grant the peer has not taken yet + /// and the refusal ending it. + outbox: VecDeque, /// Request-token readers each observe the latest verdict independently. latest: Option, revision: u64, /// The app is done with the stream: the driver closes it once the outbox drains. - pub done: bool, + done: bool, /// Why the stream ended on the peer's side, once it has. pub peer: Option, /// A request token's share of its request's slot, held while the application verifies it. @@ -1764,14 +1774,44 @@ impl Issue { } self.revision += 1; if self.scoped.is_some() { - self.outbox.push_back(reply); + self.queue(reply); } else { self.latest = Some(reply); } } + /// Queue a reply for the driver to write, unless the stream is done. It replaces a grant + /// still queued, which the peer never saw, so a peer withholding stream credit cannot + /// make the outbox grow. + pub(crate) fn queue(&mut self, reply: Reply) { + if self.done { + return; + } + match self.outbox.back_mut() { + Some(queued @ Reply::Grant(_)) => *queued = reply, + _ => self.outbox.push_back(reply), + } + } + + /// The next reply for the driver to write. + pub(crate) fn next(&mut self) -> Option { + self.outbox.pop_front() + } + + /// Whether the driver has nothing to do until the acceptor replies again. + pub(crate) fn idle(&self) -> bool { + self.outbox.is_empty() && !self.done + } + + /// The driver refused the token itself, as for a grant too large to encode: nothing + /// queued goes out, and whatever the token was granted leaves the scope. + pub(crate) fn refused(&mut self) { + self.outbox.clear(); + self.finish(); + } + /// The application is done with the token: its grant leaves the scope. - fn finish(&mut self) { + pub(crate) fn finish(&mut self) { self.done = true; if let Some((handle, id)) = &self.scoped { handle.issue(*id, None); @@ -2869,6 +2909,70 @@ mod tests { assert!(handle.within_limit(Direction::Subscribe, "room")); } + /// A grant the driver refuses to send, as one too large to encode, leaves the scope with + /// the AUTH_ERROR that replaces it. + #[test] + fn a_refused_grant_leaves_the_scope() { + let handle = Link::new(true); + handle.handle().authorize(&Grant::default()); + let serving = Serving::new(handle.clone()); + let request = Request::new(Bytes::from_static(b"token"), serving.issue.clone()); + let issued = request.accept(grant(&["room"], &[])); + assert!(handle.allows(Direction::Subscribe, "room")); + serving.issue.lock().refused(); + assert!( + !handle.allows(Direction::Subscribe, "room"), + "the refused grant still admits" + ); + issued.update(grant(&["room"], &[])); + assert!( + !handle.allows(Direction::Subscribe, "room"), + "an update revived the refused grant" + ); + } + + /// Grants issued while the peer withholds the stream's credit replace the one still + /// queued, and a revocation replaces it too. + #[test] + fn a_blocked_stream_queues_one_grant() { + let handle = Link::new(true); + let serving = Serving::new(handle.clone()); + let request = Request::new(Bytes::from_static(b"token"), serving.issue.clone()); + let issued = request.accept(grant(&["0"], &[])); + for i in 1..100 { + issued.update(grant(&[&i.to_string()], &[])); + } + { + let issue = serving.issue.read(); + assert_eq!(issue.outbox.len(), 1, "grants piled up"); + assert!(matches!(issue.outbox.front(), Some(Reply::Grant(grant)) if grant.publish == patterns(&["99"]))); + } + issued.revoke(SessionError::Unauthorized, "revoked"); + let issue = serving.issue.read(); + assert!(matches!( + issue.outbox.iter().collect::>()[..], + [Reply::Refuse { .. }] + )); + } + + /// Handing the queue to a new acceptor refuses the tokens still queued without holding + /// the handle's lock, which refusing an AUTH token takes. + #[test] + fn a_new_acceptor_refuses_the_queue_without_deadlock() { + let handle = Link::new(true); + let _requests = handle.handle().requests(); + let serving = Serving::new(handle.clone()); + handle + .acceptor() + .unwrap() + .push(Request::new(Bytes::from_static(b"token"), serving.issue.clone())); + let _next = handle.handle().requests(); + assert!(matches!( + serving.issue.read().outbox.front(), + Some(Reply::Refuse { .. }) + )); + } + /// A queued request token keeps its request's slot, so the peer's request credit bounds /// how many wait; answering it gives the slot back. #[test] diff --git a/rs/moq-net/src/auth/tokens.rs b/rs/moq-net/src/auth/tokens.rs index 4bf94415663..599ddec7fca 100644 --- a/rs/moq-net/src/auth/tokens.rs +++ b/rs/moq-net/src/auth/tokens.rs @@ -401,8 +401,14 @@ impl State { if self.configured(id) { continue; } - // A refused token has nothing left to keep the grant wide. - match self.tokens.get(&id).is_some_and(|entry| entry.ended.is_none()) { + // Only a granted token keeps the grant wide; one refused or never answered, such + // as one retrying while its backend fails, is withdrawn at once so repeated sets + // never pile up retrying streams. + let granted = self + .tokens + .get(&id) + .is_some_and(|entry| entry.ended.is_none() && matches!(entry.answered, Some(Ok(Answer::Granted)))); + match granted { true => self.configured.as_mut().expect("checked configured").retiring.push(id), false => self.withdraw(id), } @@ -646,6 +652,29 @@ mod tests { assert!(!presented(&set, old), "the replaced token was never withdrawn"); } + /// A replacement replaced again before its answer added nothing to the grant, so it is + /// withdrawn at once: sets while a backend keeps failing never pile up retrying tokens. + #[test] + fn an_unanswered_replacement_is_withdrawn_when_replaced() { + let set = Tokens::new(tokens(&["connection", "old"])); + let session = dial(&set, true, false); + session.grant_credential(); + let old = id(&set, "old"); + session.link.granted(old, Grant::all()); + + set.set(tokens(&["connection", "first"])); + let first = id(&set, "first"); + session.refuse(first, SessionError::Internal); + set.set(tokens(&["connection", "second"])); + assert!(!presented(&set, first), "the unanswered replacement is still presented"); + assert!(presented(&set, old), "the granted token was withdrawn before an answer"); + assert_eq!(set.handle.state.read().configured.as_ref().unwrap().retiring, [old]); + + session.link.granted(id(&set, "second"), Grant::all()); + ok(&set); + assert!(!presented(&set, old)); + } + /// A replacement is authoritative: its refusal is the answer, and still withdraws what it /// replaced. #[test] diff --git a/rs/moq-net/src/ietf/auth.rs b/rs/moq-net/src/ietf/auth.rs index 4bb98854770..b6d50929d12 100644 --- a/rs/moq-net/src/ietf/auth.rs +++ b/rs/moq-net/src/ietf/auth.rs @@ -712,15 +712,13 @@ impl Answering { if let Some(default) = self.default.as_mut() && let Poll::Ready(grant) = default.poll(waiter) { - issue.lock().outbox.push_back(Reply::Grant(grant)); + issue.lock().queue(Reply::Grant(grant)); } - let mut issue = std::task::ready!(issue.poll(waiter, |issue| { - match issue.outbox.is_empty() && !issue.done { - true => Poll::Pending, - false => Poll::Ready(()), - } + let mut issue = std::task::ready!(issue.poll(waiter, |issue| match issue.idle() { + true => Poll::Pending, + false => Poll::Ready(()), })); - issue.outbox.pop_front() + issue.next() } AnsweringState::Unverified | AnsweringState::UnverifiedClosing { .. } | AnsweringState::Done => { unreachable!("not serving") @@ -740,7 +738,7 @@ impl Answering { // which revokes whatever this stream granted before. if let Err(err) = ok.encode(&mut Encoder::new(&mut Vec::new(), self.version.into()), self.version) { tracing::debug!(%err, "auth grant cannot be encoded as one AUTH_OK; refusing the token"); - issue.lock().done = true; + issue.lock().refused(); let refused = AuthError { code: NOT_SUPPORTED, reason: "grant cannot be encoded as one AUTH_OK".to_string(), diff --git a/rs/moq-net/src/lite/publisher.rs b/rs/moq-net/src/lite/publisher.rs index b4f12a640dc..420a6677bdd 100644 --- a/rs/moq-net/src/lite/publisher.rs +++ b/rs/moq-net/src/lite/publisher.rs @@ -578,11 +578,11 @@ impl AuthServe { // needs someone to verify it. Tell the presenter explicitly. None if !msg.token.is_empty() => { let mut state = issue.lock(); - state.outbox.push_back(crate::auth::Reply::Refuse { + state.queue(crate::auth::Reply::Refuse { code: crate::SessionError::Unsupported, reason: Error::Unsupported.to_string(), }); - state.done = true; + state.finish(); self.unsupported = true; } None => { @@ -626,24 +626,22 @@ impl AuthServe { if let Some(default) = &mut self.default && let Poll::Ready(grant) = default.poll(waiter) { - issue.lock().outbox.push_back(crate::auth::Reply::Grant(grant)); + issue.lock().queue(crate::auth::Reply::Grant(grant)); } - let mut state = match issue.poll(waiter, |issue| match issue.outbox.is_empty() && !issue.done { + let mut state = match issue.poll(waiter, |issue| match issue.idle() { true => Poll::Pending, false => Poll::Ready(()), }) { Poll::Ready(state) => state, Poll::Pending => return Poll::Pending, }; - match state.outbox.pop_front() { + match state.next() { Some(reply) => { drop(state); if !Self::write(&self.shared, stream, reply)? { self.unsupported = true; - let mut state = issue.lock(); - state.outbox.clear(); - state.done = true; + issue.lock().refused(); } } // The app is done with the grant, or refused the token: close our side. From 6682dd2cef1bd737143f8bd5af2a577a57016d3a Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Sat, 7 Nov 2026 15:42:27 -0800 Subject: [PATCH 3/5] fix(net): retire by live grant, and bound the JS auth replies too A replaced token keeps the grant wide only while it holds a grant on some session, not by its first answer. The JS IssuedGrant replaces a queued grant rather than chaining another write, and Held withdraws a replaced token that holds no grant at once, through an internal Handle.present that returns the credential before its answer. Co-Authored-By: Claude Opus 5.5 --- js/net/src/auth.test.ts | 44 +++++++++++++++++++ js/net/src/auth_session.ts | 49 +++++++++++++++++---- js/net/src/connection/tokens.test.ts | 35 ++++++++++----- js/net/src/connection/tokens.ts | 64 ++++++++++++++++------------ rs/moq-net/src/auth/tokens.rs | 30 ++++++++++--- 5 files changed, 171 insertions(+), 51 deletions(-) diff --git a/js/net/src/auth.test.ts b/js/net/src/auth.test.ts index c4705a40575..3e2a89e34da 100644 --- a/js/net/src/auth.test.ts +++ b/js/net/src/auth.test.ts @@ -1358,6 +1358,50 @@ test("withdrawn queued tokens are pruned before the next application decision", } }); +test("grants issued while a reply is blocked replace the one still queued", async () => { + const { client, server } = await connect({ publish: new OriginProducer(), protocol: Lite.ALPN_07_WIP }); + const grants = Array.from({ length: 100 }, (_, i) => grant([`${i}`], [])); + const original = LiteAuthWire.prototype.grant; + // Which of `grants` reached the wire, in order. + const sent: number[] = []; + let release!: () => void; + const blocked = new Promise((resolve) => { + release = resolve; + }); + const spy = spyOn(LiteAuthWire.prototype, "grant").mockImplementation(async function ( + this: LiteAuthWire, + stream, + grant, + ) { + const index = grants.findIndex((issued) => issued.publish === grant.publish); + if (index >= 0) sent.push(index); + if (index === 0) await blocked; + return original.call(this, stream, grant); + }); + try { + const requests = server.auth.requests(); + const setup = await requests.next(); + if (!setup) throw new Error("setup token missing"); + setup.accept(grant(["a"], [])); + const live = client.auth.add("live"); + live.catch(() => void 0); + const request = await requests.next(); + if (!request) throw new Error("live token missing"); + const issued = request.accept(grants[0]); + await settles(() => sent.length === 1); + for (const update of grants.slice(1)) issued.update(update); + release(); + await live; + await settles(() => sent.length === 2); + for (let i = 0; i < 10; i++) await yieldNow(); + expect(sent).toEqual([0, 99]); + } finally { + spy.mockRestore(); + client.abort(); + server.abort(); + } +}); + // Capture the acceptor's actual AUTH writer after a valid setup grant. The following // bytes travel through the same connection dispatcher and presenter as a real peer. describe.each([Lite.ALPN_07_WIP, Ietf.ALPN.DRAFT_22])("AUTH violations %s", (protocol) => { diff --git a/js/net/src/auth_session.ts b/js/net/src/auth_session.ts index 8fe9e9f664c..c7a879638f3 100644 --- a/js/net/src/auth_session.ts +++ b/js/net/src/auth_session.ts @@ -157,7 +157,17 @@ class Presented { } /** A token the application added to a {@link Handle}, presented on every session of it. */ -class Token implements Credential { +/** + * A token {@link Handle.present} returned before its answer. + * + * @internal + */ +export interface Pending extends Credential { + /** Resolves once a peer accepts the token, or rejects as {@link Handle.add} does. */ + readonly answered: Promise; +} + +class Token implements Pending { readonly grant = new Signal(undefined); readonly closed: Promise; readonly answered: Promise; @@ -359,13 +369,23 @@ export class Handle { * request whose route names it carries it. */ async add(token: string | Uint8Array): Promise { - // A copy, so the caller reusing its buffer never changes what a request carries. - const bytes = typeof token === "string" ? new TextEncoder().encode(token) : token.slice(); - const added = stateOf(this).add(bytes); + const added = this.present(token); await added.answered; return added; } + /** + * Present another token like {@link add}, returning it at once with its answer, so it can be + * withdrawn before the peer answers. + * + * @internal + */ + present(token: string | Uint8Array): Pending { + // A copy, so the caller reusing its buffer never changes what a request carries. + const bytes = typeof token === "string" ? new TextEncoder().encode(token) : token.slice(); + return stateOf(this).add(bytes); + } + /** * Answer every token the peer presents, instead of the default: granting what this side * publishes and consumes for the connection's own credential and refusing any other. @@ -445,6 +465,8 @@ class IssuedGrant implements Issued { #stream: Stream; #wire: AuthWire; #writes = Promise.resolve(); + /** The latest grant, until its write starts: a newer one replaces it rather than queueing. */ + #queued: Grant | undefined; #done = false; constructor(stream: Stream, wire: AuthWire) { @@ -470,20 +492,31 @@ class IssuedGrant implements Issued { // reply that fails to encode. if (!(err instanceof Unsupported)) console.warn("auth reply not sent", err); this.#done = true; + this.#queued = undefined; return this.#wire.unsupported(this.#stream, error(err).message).catch(() => void 0); }); } update(grant: Grant): void { if (this.#done) return; - const expires = grant.expires === undefined ? undefined : grant.expires - wall(); - this.#write(() => - this.#wire.grant(this.#stream, { publish: grant.publish, subscribe: grant.subscribe, expires }), - ); + // A grant still waiting to be written is replaced, so a peer withholding stream credit + // holds at most one. + const queued = this.#queued !== undefined; + this.#queued = grant; + if (queued) return; + this.#write(async () => { + const grant = this.#queued; + this.#queued = undefined; + if (grant === undefined) return; + const expires = grant.expires === undefined ? undefined : grant.expires - wall(); + await this.#wire.grant(this.#stream, { publish: grant.publish, subscribe: grant.subscribe, expires }); + }); } revoke(code: SessionCode, reason: string): void { if (this.#done) return; + // The peer never saw a grant still queued, so the refusal replaces it. + this.#queued = undefined; this.#write(() => this.#wire.refuse(this.#stream, code, reason)); this.close(); } diff --git a/js/net/src/connection/tokens.test.ts b/js/net/src/connection/tokens.test.ts index eab3da94fba..5658e43158b 100644 --- a/js/net/src/connection/tokens.test.ts +++ b/js/net/src/connection/tokens.test.ts @@ -1,7 +1,9 @@ import { expect, test } from "bun:test"; -import type { Credential, Handle } from "../auth.ts"; +import type { Grant, Handle } from "../auth.ts"; +import type { Pending } from "../auth_session.ts"; import * as Ietf from "../ietf/index.ts"; import { createMockTransportPair } from "../mock.ts"; +import * as Path from "../path.ts"; import { Reader } from "../stream.ts"; import type { Established } from "./established.ts"; import { offered } from "./extensions.ts"; @@ -55,19 +57,30 @@ test("no tokens present nothing", () => { /** A handle whose answers the test releases one token at a time. */ function handle() { - const answers = new Map void>(); + const answers = new Map void>(); const closed: string[] = []; const presented: string[] = []; const fake = { - add(token: string) { + present(token: string) { presented.push(token); - return new Promise((resolve) => answers.set(token, resolve)); + let granted: Grant | undefined; + const answered = new Promise((resolve) => + answers.set(token, () => { + granted = { publish: new Path.Patterns(), subscribe: new Path.Patterns() }; + resolve(); + }), + ); + return { + grant: { peek: () => granted }, + answered, + close: () => closed.push(token), + } as unknown as Pending; }, } as unknown as Handle; const answer = async (token: string) => { const resolve = answers.get(token); if (!resolve) throw new Error(`${token} was never presented`); - resolve({ close: () => closed.push(token) } as unknown as Credential); + resolve(); // Let the answer and the settle it schedules run. for (let i = 0; i < 3; i++) await Promise.resolve(); }; @@ -89,15 +102,17 @@ test("a replaced token is withdrawn only once its replacement answers", async () expect(closed).toEqual(["old"]); }); -test("a token replaced before its answer closes when it arrives", async () => { +test("a token replaced before its answer is withdrawn at once", async () => { const { fake, closed, answer } = handle(); const held = new Held(fake, credential(URL_, ["connection"], true)); held.update(["connection", "old"]); - held.update(["connection", "new"]); - await answer("new"); - expect(closed).toEqual([]); await answer("old"); - expect(closed).toEqual(["old"]); + held.update(["connection", "first"]); + held.update(["connection", "second"]); + // The unanswered replacement adds nothing; the granted token waits for an answer. + expect(closed).toEqual(["first"]); + await answer("second"); + expect(closed).toEqual(["first", "old"]); }); test("sessions sharing an auth handle present each configured token once", async () => { diff --git a/js/net/src/connection/tokens.ts b/js/net/src/connection/tokens.ts index 83f59bcd9aa..6079701e0a5 100644 --- a/js/net/src/connection/tokens.ts +++ b/js/net/src/connection/tokens.ts @@ -1,4 +1,5 @@ import { type Credential, type Handle, Unsupported } from "../auth.ts"; +import type { Pending } from "../auth_session.ts"; import type { Established } from "./established.ts"; /** What one dial presents, decided from its URL, the offered versions, and the tokens. @internal */ @@ -58,7 +59,8 @@ export function extra(credential: Presentation, tokens: readonly string[]): stri interface Entry { auth?: Credential; pending: boolean; - retired: boolean; + /** Withdrawn by us, so its rejected answer is no refusal. */ + withdrawn: boolean; } /** @@ -66,8 +68,8 @@ interface Entry { * latest dial's connection credential. A handle shared across reconnects keeps them on * every session it backs. * - * A change presents the new tokens at once and withdraws the ones they replace only after - * every new one has its answer, so the grant never narrows in between. + * A change presents the new tokens at once and withdraws the granted ones they replace only + * after every new one has its answer, so the grant never narrows in between. * * @internal */ @@ -95,41 +97,49 @@ export class Held { next.set(token, this.#entries.get(token) ?? this.#present(token)); } for (const [token, entry] of this.#entries) { - if (!next.has(token)) this.#retiring.push(entry); + if (next.has(token)) continue; + // Only a granted token keeps the grant wide; one refused or still unanswered, such as + // one retrying while its backend fails, is withdrawn at once so repeated updates never + // pile up retrying streams. + if (entry.auth?.grant.peek() !== undefined) this.#retiring.push(entry); + else this.#withdraw(entry); } this.#entries = next; this.#settle(); } #present(token: string): Entry { - const entry: Entry = { pending: true, retired: false }; - // Registered synchronously, so a request sent right after waits on its answer. - this.#handle - .add(token) - .then( - (auth) => { - entry.auth = auth; - // Replaced while waiting, and every replacement has answered since. - if (entry.retired) auth.close(); - }, - (err: unknown) => { - if (err instanceof Unsupported) console.debug("the peer takes no tokens in band"); - else console.warn("a configured token was refused:", err); - }, - ) - .finally(() => { - entry.pending = false; - this.#settle(); - }); + const entry: Entry = { pending: true, withdrawn: false }; + const refused = (err: unknown) => { + if (entry.withdrawn) return; + if (err instanceof Unsupported) console.debug("the peer takes no tokens in band"); + else console.warn("a configured token was refused:", err); + }; + let auth: Pending; + try { + // Registered synchronously, so a request sent right after waits on its answer. + auth = this.#handle.present(token); + } catch (err) { + refused(err); + entry.pending = false; + return entry; + } + entry.auth = auth; + auth.answered.catch(refused).finally(() => { + entry.pending = false; + this.#settle(); + }); return entry; } + #withdraw(entry: Entry) { + entry.withdrawn = true; + entry.auth?.close(); + } + #settle() { if ([...this.#entries.values()].some((entry) => entry.pending)) return; - for (const entry of this.#retiring) { - entry.retired = true; - entry.auth?.close(); - } + for (const entry of this.#retiring) this.#withdraw(entry); this.#retiring = []; } } diff --git a/rs/moq-net/src/auth/tokens.rs b/rs/moq-net/src/auth/tokens.rs index 599ddec7fca..6b458ac1d5d 100644 --- a/rs/moq-net/src/auth/tokens.rs +++ b/rs/moq-net/src/auth/tokens.rs @@ -64,8 +64,8 @@ pub struct EmptyToken; /// The first is the connection credential, which each dial carries in SETUP or its URL, /// unless the URL already has a `?jwt=`. Every other token rides its own AUTH stream on the /// sessions of [`handle`](Self::handle), widening the grant. Replacing them presents the new -/// ones on the live session at once, withdrawing the ones they replace only after every new -/// one has its answer, so the grant never narrows in between. +/// ones on the live session at once, withdrawing the granted ones they replace only after +/// every new one has its answer, so the grant never narrows in between. /// /// A reconnect loop builds each session on [`handle`](Self::handle), calls /// [`dial`](Self::dial) before each dial and [`connected`](Self::connected) once it @@ -401,13 +401,13 @@ impl State { if self.configured(id) { continue; } - // Only a granted token keeps the grant wide; one refused or never answered, such + // Only a token holding a grant keeps the grant wide; one refused or unanswered, such // as one retrying while its backend fails, is withdrawn at once so repeated sets // never pile up retrying streams. let granted = self - .tokens - .get(&id) - .is_some_and(|entry| entry.ended.is_none() && matches!(entry.answered, Some(Ok(Answer::Granted)))); + .links + .values() + .any(|link| link.slots.get(&id).is_some_and(|slot| slot.grant.is_some())); match granted { true => self.configured.as_mut().expect("checked configured").retiring.push(id), false => self.withdraw(id), @@ -675,6 +675,24 @@ mod tests { assert!(!presented(&set, old)); } + /// A token first taken only for requests, then granted on a session with AUTH, keeps the + /// grant wide until its replacement answers. + #[test] + fn a_token_granted_after_a_requests_answer_retires() { + let set = Tokens::new(tokens(&["connection", "old"])); + let first = dial(&set, false, true); + let old = id(&set, "old"); + first.lost(); + let session = dial(&set, true, false); + session.grant_credential(); + session.link.granted(old, Grant::all()); + + set.set(tokens(&["connection", "new"])); + assert!(presented(&set, old), "withdrawn before its replacement was answered"); + session.link.granted(id(&set, "new"), Grant::all()); + assert!(!presented(&set, old)); + } + /// A replacement is authoritative: its refusal is the answer, and still withdraws what it /// replaced. #[test] From 246ad5ed5182754fc03cd2c99e5b450c2c22cf38 Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Sat, 7 Nov 2026 15:55:16 -0800 Subject: [PATCH 4/5] fix(net): JS retiring counts a draining session's grant Pending.held reports a grant on any session the handle backs, so a token still granted on a session draining after a GOAWAY keeps the grant wide until its replacement answers, as Rust's State::hold does. Co-Authored-By: Claude Opus 5.5 --- js/net/src/auth.test.ts | 42 ++++++++++++++++++++++++++++ js/net/src/auth_session.ts | 16 +++++++---- js/net/src/connection/tokens.test.ts | 15 ++++------ js/net/src/connection/tokens.ts | 6 ++-- 4 files changed, 61 insertions(+), 18 deletions(-) diff --git a/js/net/src/auth.test.ts b/js/net/src/auth.test.ts index 3e2a89e34da..63b5e1485e0 100644 --- a/js/net/src/auth.test.ts +++ b/js/net/src/auth.test.ts @@ -1016,6 +1016,48 @@ test("lite-07 ignores a draining session's late refusal while its successor retr }); // moq-lite carries patterns, so every grant arrives exactly as issued. +test("lite-07 a token granted on a draining session stays held until its successor answers", async () => { + const protocol = Lite.ALPN_07_WIP; + const handle = new Handle(); + const pair = createMockTransportPair(protocol); + const [client, server] = await Promise.all([ + connectSession({ url, transport: pair.client, publish: new OriginProducer().consume(), auth: handle }), + acceptSession({ transport: pair.server, url }), + ]); + const requests = server.auth.requests(); + const setup = await requests.next(); + if (!setup) throw new Error("missing setup token"); + const issued = [setup.accept(grant([], []))]; + const token = handle.present("token"); + const request = await requests.next(); + if (!request) throw new Error("missing token"); + issued.push(request.accept(grant(["a"], []))); + await token.answered; + expect(token.held).toBe(true); + + const stream = await Stream.open(pair.server, { version: Lite.Version.DRAFT_07 }); + await stream.writer.u53(Lite.StreamId.Goaway); + await new Lite.Goaway("").encode(stream.writer, Lite.Version.DRAFT_07); + await settles(() => !wireOf(client).auth.active); + + const next = await connect({ publish: new OriginProducer(), protocol, auth: handle }); + const successorRequests = next.server.auth.requests(); + try { + const successorSetup = await successorRequests.next(); + if (!successorSetup) throw new Error("missing successor setup token"); + issued.push(successorSetup.accept(grant([], []))); + expect(await successorRequests.next()).toBeDefined(); + // The live session has not answered, but the draining one still grants it. + expect(token.grant.peek()).toBeUndefined(); + expect(token.held).toBe(true); + } finally { + client.abort(); + server.abort(); + next.client.abort(); + next.server.abort(); + } +}); + test("a fetch abandoned while its token waits never reaches the wire", async () => { const logged = spyOn(console, "debug"); const origin = new OriginProducer(); diff --git a/js/net/src/auth_session.ts b/js/net/src/auth_session.ts index c7a879638f3..eec65f8f64e 100644 --- a/js/net/src/auth_session.ts +++ b/js/net/src/auth_session.ts @@ -165,6 +165,8 @@ class Presented { export interface Pending extends Credential { /** Resolves once a peer accepts the token, or rejects as {@link Handle.add} does. */ readonly answered: Promise; + /** Whether any session holds a grant for it now, a draining one included. */ + readonly held: boolean; } class Token implements Pending { @@ -176,14 +178,14 @@ class Token implements Pending { isAnswered = false; ended = false; - #withdraw: (token: Token) => void; + #state: HandleState; #close!: (err: Error | null) => void; #answer!: () => void; #refuse!: (err: Error) => void; - constructor(bytes: Uint8Array, withdraw: (token: Token) => void) { + constructor(bytes: Uint8Array, state: HandleState) { this.bytes = bytes; - this.#withdraw = withdraw; + this.#state = state; this.closed = new Promise((resolve) => { this.#close = resolve; }); @@ -212,8 +214,12 @@ class Token implements Pending { this.#close(err); } + get held(): boolean { + return this.#state.sessions.some((session) => session.grantOf(this) !== undefined); + } + close() { - this.#withdraw(this); + this.#state.withdraw(this); } } @@ -274,7 +280,7 @@ class HandleState { if (this.own && !this.sessions.some((session) => session.active)) { throw new StreamError(StreamCode.GoingAway); } - const token = new Token(bytes, (token) => this.withdraw(token)); + const token = new Token(bytes, this); this.tokens.add(token); for (const session of [...this.sessions]) session.offer(token); return token; diff --git a/js/net/src/connection/tokens.test.ts b/js/net/src/connection/tokens.test.ts index 5658e43158b..62ef0d38b92 100644 --- a/js/net/src/connection/tokens.test.ts +++ b/js/net/src/connection/tokens.test.ts @@ -1,9 +1,8 @@ import { expect, test } from "bun:test"; -import type { Grant, Handle } from "../auth.ts"; +import type { Handle } from "../auth.ts"; import type { Pending } from "../auth_session.ts"; import * as Ietf from "../ietf/index.ts"; import { createMockTransportPair } from "../mock.ts"; -import * as Path from "../path.ts"; import { Reader } from "../stream.ts"; import type { Established } from "./established.ts"; import { offered } from "./extensions.ts"; @@ -63,18 +62,14 @@ function handle() { const fake = { present(token: string) { presented.push(token); - let granted: Grant | undefined; - const answered = new Promise((resolve) => + const pending = { held: false, answered: Promise.resolve(), close: () => closed.push(token) }; + pending.answered = new Promise((resolve) => answers.set(token, () => { - granted = { publish: new Path.Patterns(), subscribe: new Path.Patterns() }; + pending.held = true; resolve(); }), ); - return { - grant: { peek: () => granted }, - answered, - close: () => closed.push(token), - } as unknown as Pending; + return pending as unknown as Pending; }, } as unknown as Handle; const answer = async (token: string) => { diff --git a/js/net/src/connection/tokens.ts b/js/net/src/connection/tokens.ts index 6079701e0a5..1123a88d769 100644 --- a/js/net/src/connection/tokens.ts +++ b/js/net/src/connection/tokens.ts @@ -1,4 +1,4 @@ -import { type Credential, type Handle, Unsupported } from "../auth.ts"; +import { type Handle, Unsupported } from "../auth.ts"; import type { Pending } from "../auth_session.ts"; import type { Established } from "./established.ts"; @@ -57,7 +57,7 @@ export function extra(credential: Presentation, tokens: readonly string[]): stri } interface Entry { - auth?: Credential; + auth?: Pending; pending: boolean; /** Withdrawn by us, so its rejected answer is no refusal. */ withdrawn: boolean; @@ -101,7 +101,7 @@ export class Held { // Only a granted token keeps the grant wide; one refused or still unanswered, such as // one retrying while its backend fails, is withdrawn at once so repeated updates never // pile up retrying streams. - if (entry.auth?.grant.peek() !== undefined) this.#retiring.push(entry); + if (entry.auth?.held) this.#retiring.push(entry); else this.#withdraw(entry); } this.#entries = next; From 03e1aab7d092be5127d2f8ccf0cee9a335f0a90a Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Sat, 7 Nov 2026 21:03:01 -0800 Subject: [PATCH 5/5] docs(js/net): keep Token's doc comment on Token Co-Authored-By: Claude Opus 5.5 --- js/net/src/auth_session.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/js/net/src/auth_session.ts b/js/net/src/auth_session.ts index eec65f8f64e..e2871d95149 100644 --- a/js/net/src/auth_session.ts +++ b/js/net/src/auth_session.ts @@ -156,7 +156,6 @@ class Presented { } } -/** A token the application added to a {@link Handle}, presented on every session of it. */ /** * A token {@link Handle.present} returned before its answer. * @@ -169,6 +168,7 @@ export interface Pending extends Credential { readonly held: boolean; } +/** A token the application added to a {@link Handle}, presented on every session of it. */ class Token implements Pending { readonly grant = new Signal(undefined); readonly closed: Promise;