Skip to main content

moq_net/
auth.rs

1//! In-band authorization: present tokens to the peer and learn what they grant.
2//!
3//! Each side of a session presents the credential its connection
4//! already carried (the URL, a client certificate, or nothing) right after
5//! setup, and learns the [`Grant`] it earned. `Session::auth`
6//! returns the [`Handle`]: [`grant`](Handle::grant) is the union of every token
7//! this side presented, and `add` presents another without
8//! reconnecting. The returned [`Credential`] is cloneable; dropping its last clone withdraws it.
9//! A [`Route`](crate::origin::RouteInfo) can name it, so the request advertising the route
10//! carries it too, and swapping it renews that request in place.
11//!
12//! A handle passed to `Client::with_auth` outlives its sessions: each session built on it
13//! presents every token it holds, so a route naming one of its [`Credential`]s keeps it across a
14//! reconnect. Only the peer's verdict ends such a token; a session ending leaves it for the
15//! next. It backs one active session at a time, plus the ones draining after a GOAWAY.
16//!
17//! The other direction, answering the peer's tokens, is automatic: the session
18//! grants what its own origin handles allow. A server that verifies tokens itself
19//! takes the client's from `server::Handshake::requests` before accepting, and then
20//! answers every token the client presents. Either way,
21//! [`authorize`](Handle::authorize) re-authorizes the peer on a live session, narrower
22//! or wider, on every version, whether or not it speaks AUTH.
23//!
24//! Every token the peer presents is one kind of [`Request`], answered on the same queue,
25//! wherever it rode: its own AUTH stream, or a moq-transport `AUTHORIZATION TOKEN` on a
26//! request. Requests naming the same token on one session share its verification and lifetime.
27//! The session enforces each grant it issues. A request
28//! that carried a token is held to that token's grant alone and ends with it; any other
29//! request is held to the session's scope, which a token carried by a request never joins.
30//!
31//! Older moq-lite versions and moq-transport carry no AUTH exchange: there the grant stays
32//! `None`. On moq-transport a [`Credential`] is still answered, with a grant that stays
33//! unknown, since a request that names it carries its token; on moq-lite without AUTH its
34//! answer is [`Error::Unsupported`]. moq-lite carries a grant's prefixes as they are, and refuses one
35//! too large for a single AUTH_OK rather than trim it.
36
37use std::{
38	collections::{BTreeMap, VecDeque},
39	task::Poll,
40	time::Duration,
41};
42
43use bytes::Bytes;
44
45use crate::{Error, Prefixes, Result, SessionError, time::Instant};
46
47mod tokens;
48
49pub(crate) use tokens::{Dial, locate};
50pub use tokens::{EmptyToken, Token, Tokens};
51
52/// Classify malformed AUTH messages separately from transport and local failures.
53pub(crate) fn protocol_error(err: Error) -> Error {
54	match err {
55		Error::Decode(_)
56		| Error::BoundsExceeded(_)
57		| Error::WrongSize
58		| Error::UnexpectedMessage
59		| Error::UnexpectedStream => Error::ProtocolViolation,
60		err => err,
61	}
62}
63
64/// `ready!` for a `kio::Shared` poll, which yields a guard rather than a result.
65macro_rules! ready_or {
66	($e:expr) => {
67		match $e {
68			Poll::Ready(guard) => guard,
69			Poll::Pending => return Poll::Pending,
70		}
71	};
72}
73
74/// How a peer accepted a token [`Handle::add`] presented.
75#[derive(Clone, Copy, Debug, PartialEq, Eq)]
76pub(crate) enum Answer {
77	/// Granted on its AUTH stream: its grant joins the union.
78	Granted,
79	/// Taken only for the requests that name it, on moq-transport without AUTH.
80	Requests,
81}
82
83/// What a peer lets this side do, in this side's own paths.
84///
85/// The paths are relative to the session's root, the same paths the session
86/// announces and subscribes with. Each is a set of prefixes, each covering its whole
87/// subtree: the empty prefix grants everything. `Grant::default()` grants nothing; set
88/// the fields on it to grant more.
89#[derive(Clone, Debug, Default, PartialEq, Eq)]
90#[non_exhaustive]
91pub struct Grant {
92	/// The broadcasts this side may publish to the peer.
93	pub publish: Prefixes,
94	/// The broadcasts this side may subscribe to from the peer.
95	pub subscribe: Prefixes,
96	/// When the grant lapses, or `None` for never.
97	pub expires: Option<Instant>,
98}
99
100impl Grant {
101	/// A grant of everything that never expires.
102	pub fn all() -> Self {
103		Self {
104			publish: Prefixes::all(),
105			subscribe: Prefixes::all(),
106			expires: None,
107		}
108	}
109
110	/// The paths any of `grants` allows, lapsing at the earliest expiry, which is when
111	/// the union next shrinks. Reduced once over all of them, not pairwise.
112	fn union<'a>(grants: impl IntoIterator<Item = &'a Self>) -> Self {
113		let mut publish = Vec::new();
114		let mut subscribe = Vec::new();
115		let mut expires = None;
116		for grant in grants {
117			publish.extend(grant.publish.iter().cloned());
118			subscribe.extend(grant.subscribe.iter().cloned());
119			expires = earliest(expires, grant.expires);
120		}
121		Self {
122			publish: publish.into_iter().collect(),
123			subscribe: subscribe.into_iter().collect(),
124			expires,
125		}
126	}
127
128	/// The paths both grants allow, lapsing at the earlier expiry.
129	fn intersect(&self, other: &Self) -> Self {
130		Self {
131			publish: self.publish.intersect(&other.publish),
132			subscribe: self.subscribe.intersect(&other.subscribe),
133			expires: earliest(self.expires, other.expires),
134		}
135	}
136}
137
138/// The earlier of two optional deadlines, where `None` is never.
139fn earliest(a: Option<Instant>, b: Option<Instant>) -> Option<Instant> {
140	match (a, b) {
141		(Some(a), Some(b)) => Some(a.min(b)),
142		(a, b) => a.or(b),
143	}
144}
145
146/// How long a token refused for a reason that may pass waits before its session presents it
147/// again, doubling on each refusal up to [`RETRY_MAX`]. A moq-transport refusal that may pass
148/// asks its peer to wait as long.
149pub(crate) const RETRY_INITIAL: Duration = Duration::from_secs(1);
150const RETRY_MAX: Duration = Duration::from_secs(30);
151
152/// Whether a token's stream ending with `err` is the peer's verdict on it: a final refusal,
153/// [`Error::Unsupported`], or a clean close after a grant. Anything else left the token
154/// undecided.
155fn verdict(phase: &Phase, err: &Error) -> bool {
156	matches!(phase, Phase::Refused { undecided: false, .. })
157		|| matches!(err, Error::Unsupported)
158		// The peer ended the grant without revoking it.
159		|| (matches!(err, Error::Cancel) && matches!(phase, Phase::Granted(_)))
160}
161
162/// The shared state behind one [`Handle`]: the tokens it presents, and every session
163/// it backs.
164#[derive(Default)]
165pub(crate) struct State {
166	/// Created by a session for itself, so it ends with that session.
167	bound: bool,
168	/// Set once the handle ends; every waiter resolves with it.
169	closed: Option<Error>,
170	next_id: u64,
171	/// Every token the application added that it has not withdrawn.
172	tokens: BTreeMap<u64, Entry>,
173	next_link: u64,
174	/// Every session built on this handle that has not dropped, oldest first. Boxed because
175	/// a map holds one entry almost always, and a B-tree leaf reserves eleven inline slots.
176	links: BTreeMap<u64, Box<Attached>>,
177	/// What the peer's connection credential lets it do, in the peer's terms: `None` (only
178	/// the origin handles bound it) until [`Handle::authorize`] sets it; the grant it was
179	/// last called with.
180	limit: Option<Grant>,
181	next_issue: u64,
182	acceptor: Acceptor,
183	/// The tokens a [`Tokens`] presents on this handle's sessions, when it was built by one.
184	configured: Option<tokens::Configured>,
185}
186
187/// A token the application added, presented on every session of its handle.
188struct Entry {
189	value: Bytes,
190	/// The first verdict any session's peer gave: how it accepted the token, or why it ended.
191	answered: Option<Result<Answer>>,
192	/// Why the token ended for good: a peer's refusal or revocation, or the handle's end.
193	ended: Option<Error>,
194}
195
196/// One session's side of a handle.
197struct Attached {
198	/// Whether the negotiated version carries AUTH at all.
199	supported: bool,
200	/// Whether a request can carry a token itself (moq-transport), so an auth needs no
201	/// AUTH stream to be named.
202	requests: bool,
203	/// Set once the session ends.
204	closed: Option<Error>,
205	/// The tokens still unanswered when the session ended, whose answer is that end.
206	cut: Vec<u64>,
207	/// The session's GOAWAY: once either side sends one, the session is draining.
208	goaway: Option<std::sync::Arc<crate::goaway::Handle>>,
209	/// Every token this session presented that has not been withdrawn.
210	slots: BTreeMap<u64, Slot>,
211	/// Tokens waiting for the driver to open their stream.
212	opening: VecDeque<u64>,
213	/// The union of every open token's grant, `None` until the peer first replies.
214	union: Option<Grant>,
215	/// The peer replied to some token, so the union is known even when empty.
216	replied: bool,
217	/// The grants the application issued to the peer's AUTH tokens, by stream, in the
218	/// peer's terms. A token on a single request never joins them.
219	issued: BTreeMap<u64, Grant>,
220	/// The session's scope for the peer: the limit and every issued grant, `None` while the
221	/// limit is.
222	scope: Option<Grant>,
223	/// Bumped whenever the union or the scope changes, so the session's per-stream
224	/// gates can skip re-matching paths on every wakeup.
225	epoch: u64,
226	/// Whether the peer has accepted the connection, credential included: at once, unless
227	/// the session [awaits its answer](Link::await_acceptance) or the version
228	/// [has none](Link::silent).
229	acceptance: Acceptance,
230}
231
232/// Whether a session's peer accepted the connection credential.
233#[derive(Clone, Copy, Debug, PartialEq, Eq)]
234enum Acceptance {
235	/// With its handshake, or with the answer the session awaited.
236	Accepted,
237	/// Not yet: the peer's SETUP (a client without AUTH) or its AUTH_OK to the connection's
238	/// own credential (a lite-07 client) is still to come, and the peer can still refuse.
239	Awaiting,
240	/// Never said: the version has no answer, so the peer refuses only by closing the
241	/// session (a lite-03/04 client).
242	Silent,
243}
244
245/// One token as one session presents it.
246struct Slot {
247	token: Bytes,
248	/// Presented by the session itself at setup, so enforcement waits on it.
249	setup: bool,
250	phase: Phase,
251}
252
253/// Where one session is with one token. Each `backoff` is the delay before the last retry,
254/// which the next one doubles.
255enum Phase {
256	/// Waiting for the driver to open its AUTH stream: first presented, or between retries.
257	Queued { backoff: Option<Duration> },
258	/// Its stream is open and the driver owns ending it, but the peer has not replied.
259	Pending { backoff: Option<Duration> },
260	/// The peer's latest reply on the open stream is this AUTH_OK.
261	Granted(Grant),
262	/// The peer refused the current attempt with an AUTH_ERROR; the driver retries or ends it.
263	/// `undecided` when its code says the acceptor failed to decide, so the token is
264	/// presented again rather than ended.
265	Refused { backoff: Option<Duration>, undecided: bool },
266	/// The last [`Credential`] clone dropped while its stream was open: the driver closes the
267	/// stream, and any grant holds until then.
268	Withdrawn { grant: Option<Grant> },
269	/// Only requests carry it, on a version without AUTH, so nothing will answer.
270	Requests,
271	/// Over on this session, and why.
272	Ended(Error),
273}
274
275impl Phase {
276	/// The grant the token adds to the union.
277	fn grant(&self) -> Option<&Grant> {
278		match self {
279			Self::Granted(grant) | Self::Withdrawn { grant: Some(grant) } => Some(grant),
280			_ => None,
281		}
282	}
283
284	/// Whether the token has its answer: a grant, an end, or none to wait for.
285	fn answered(&self) -> bool {
286		!matches!(
287			self,
288			Self::Queued { .. } | Self::Pending { .. } | Self::Refused { .. } | Self::Withdrawn { grant: None }
289		)
290	}
291
292	/// Why the token ended here, once it has.
293	fn ended(&self) -> Option<&Error> {
294		match self {
295			Self::Ended(err) => Some(err),
296			_ => None,
297		}
298	}
299
300	/// Still wanted and not over: neither withdrawn nor ended.
301	fn live(&self) -> bool {
302		!matches!(self, Self::Withdrawn { .. } | Self::Ended(_))
303	}
304}
305
306/// Who answers the peer's tokens. Decided once, when a driver first runs.
307#[derive(Default)]
308enum Acceptor {
309	/// Nobody asked yet; the app may still take [`Handle::requests`].
310	#[default]
311	Undecided,
312	/// The app answers every token.
313	App(Pending),
314	/// The session answers from its own origin handles.
315	Default,
316}
317
318impl Attached {
319	fn new(supported: bool, requests: bool, limit: Option<&Grant>) -> Self {
320		let mut attached = Self {
321			supported,
322			requests,
323			closed: None,
324			cut: Vec::new(),
325			goaway: None,
326			slots: BTreeMap::new(),
327			opening: VecDeque::new(),
328			union: None,
329			replied: false,
330			issued: BTreeMap::new(),
331			scope: None,
332			epoch: 0,
333			acceptance: Acceptance::Accepted,
334		};
335		attached.rescope(limit);
336		attached
337	}
338
339	/// Whether the session still takes new work: open, with no GOAWAY sent or received.
340	fn active(&self) -> bool {
341		self.closed.is_none() && !self.goaway.as_ref().is_some_and(|goaway| goaway.draining())
342	}
343
344	/// Present the handle's token `id` on this session, returning the answer when the
345	/// session settles it at once: `Ok` when only a request can carry it, so nothing will
346	/// answer, and [`Error::Unsupported`] when nothing can.
347	///
348	/// A draining session takes no new tokens, so its verdict never ends one its successor
349	/// carries.
350	fn offer(&mut self, id: u64, token: &Bytes) -> Option<Result<()>> {
351		if !self.active() {
352			return None;
353		}
354		let (phase, answered) = match (self.supported, self.requests) {
355			(true, _) => (Phase::Queued { backoff: None }, None),
356			(false, true) => (Phase::Requests, Some(Ok(()))),
357			(false, false) => (Phase::Ended(Error::Unsupported), Some(Err(Error::Unsupported))),
358		};
359		self.slots.insert(
360			id,
361			Slot {
362				token: token.clone(),
363				setup: false,
364				phase,
365			},
366		);
367		if self.supported {
368			self.opening.push_back(id);
369		}
370		answered
371	}
372
373	/// End token `id` on this session, if it is still live here.
374	fn end(&mut self, id: u64, err: &Error) {
375		let Some(slot) = self.slots.get_mut(&id) else {
376			return;
377		};
378		match slot.phase {
379			Phase::Ended(_) => return,
380			// Nothing will read a withdrawn slot again, and its driver finds it gone.
381			Phase::Withdrawn { .. } => {
382				self.slots.remove(&id);
383			}
384			_ => slot.phase = Phase::Ended(err.clone()),
385		}
386		self.epoch += 1;
387		self.recompute();
388	}
389
390	/// The last [`Credential`] clone for token `id` dropped.
391	fn withdraw(&mut self, id: u64) {
392		let Some(slot) = self.slots.get_mut(&id) else {
393			return;
394		};
395		slot.phase = match &mut slot.phase {
396			// The open stream's close is what ends it, and its grant holds until then.
397			Phase::Pending { .. } | Phase::Refused { .. } => Phase::Withdrawn { grant: None },
398			Phase::Granted(grant) => Phase::Withdrawn {
399				grant: Some(std::mem::take(grant)),
400			},
401			Phase::Withdrawn { .. } => return,
402			// Already over, or no stream whose close would end it: nothing left to close.
403			Phase::Queued { .. } | Phase::Requests | Phase::Ended(_) => {
404				self.opening.retain(|opening| *opening != id);
405				self.slots.remove(&id);
406				self.recompute();
407				return;
408			}
409		};
410	}
411
412	fn recompute(&mut self) {
413		let mut granted = self.slots.values().filter_map(|slot| slot.phase.grant()).peekable();
414		if granted.peek().is_none() && !self.replied {
415			return;
416		}
417		let union = Grant::union(granted);
418		if self.union.as_ref() != Some(&union) {
419			self.union = Some(union);
420			self.epoch += 1;
421		}
422	}
423
424	/// Re-derive the scope from the handle's limit and the issued grants.
425	fn rescope(&mut self, limit: Option<&Grant>) {
426		let scope = limit.map(|limit| Grant::union(std::iter::once(limit).chain(self.issued.values())));
427		if self.scope != scope {
428			self.scope = scope;
429			self.epoch += 1;
430		}
431	}
432
433	/// The union's and the scope's prefixes for `direction`, each `None` while
434	/// unrestricted.
435	fn parts(&self, direction: Direction) -> (Option<&Prefixes>, Option<&Prefixes>) {
436		// The peer's grant names what we may do; the scope names what the peer may,
437		// so what we send is what the peer may subscribe to, and the other way around.
438		match direction {
439			Direction::Publish => (
440				self.union.as_ref().map(|union| &union.publish),
441				self.scope.as_ref().map(|scope| &scope.subscribe),
442			),
443			Direction::Subscribe => (
444				self.union.as_ref().map(|union| &union.subscribe),
445				self.scope.as_ref().map(|scope| &scope.publish),
446			),
447		}
448	}
449
450	/// What `direction` allows right now.
451	fn permit(&self, direction: Direction) -> Permit {
452		let (granted, limit) = self.parts(direction);
453		Permit {
454			granted: granted.cloned(),
455			limit: limit.cloned(),
456		}
457	}
458
459	/// Whether `direction` allows `path` right now, without copying the prefixes.
460	fn allows(&self, direction: Direction, path: &str) -> bool {
461		let (granted, limit) = self.parts(direction);
462		granted.is_none_or(|granted| granted.matches(path)) && limit.is_none_or(|limit| limit.matches(path))
463	}
464}
465
466impl State {
467	/// The session the handle backs now: the newest one still open.
468	fn live(&self) -> Option<&Attached> {
469		self.links
470			.values()
471			.rev()
472			.map(|link| &**link)
473			.find(|link| link.closed.is_none())
474	}
475
476	/// Record a session's answer to token `id`: an acceptance settles [`Credential::answered`],
477	/// and a refusal is the verdict that ends the token on every session.
478	fn answer(&mut self, id: u64, answer: Result<Answer>) {
479		match answer {
480			Ok(answer) => {
481				if let Some(token) = self.tokens.get_mut(&id) {
482					token.answered.get_or_insert(Ok(answer));
483				}
484				if answer == Answer::Requests {
485					self.unsupported(id);
486				}
487				self.settle();
488			}
489			Err(err) => self.end_token(id, err),
490		}
491	}
492
493	/// End token `id` for good, closing its stream on every session.
494	fn end_token(&mut self, id: u64, err: Error) {
495		let Some(token) = self.tokens.get_mut(&id) else {
496			return;
497		};
498		if token.ended.is_some() {
499			return;
500		}
501		token.answered.get_or_insert(Err(err.clone()));
502		token.ended = Some(err.clone());
503		for link in self.links.values_mut() {
504			link.end(id, &err);
505		}
506		if self.closed.is_none() && self.configured(id) {
507			match err {
508				Error::Unsupported => self.unsupported(id),
509				err => tracing::warn!(%err, "a configured token was refused"),
510			}
511		}
512		self.settle();
513	}
514
515	/// Register a token and offer it to every open session.
516	fn present(&mut self, token: Bytes) -> u64 {
517		let id = self.next_id;
518		self.next_id += 1;
519		self.tokens.insert(
520			id,
521			Entry {
522				value: token.clone(),
523				answered: None,
524				ended: None,
525			},
526		);
527		let answers: Vec<_> = self
528			.links
529			.values_mut()
530			.filter_map(|link| link.offer(id, &token))
531			.collect();
532		for answer in answers {
533			self.answer(id, answer.map(|()| Answer::Requests));
534		}
535		id
536	}
537
538	/// Stop presenting token `id` on every session.
539	fn withdraw(&mut self, id: u64) {
540		self.tokens.remove(&id);
541		for link in self.links.values_mut() {
542			link.withdraw(id);
543		}
544	}
545
546	/// End the handle, returning the application's queue for the caller to close once the
547	/// lock is released, since refusing its tokens takes the lock again.
548	fn abort(&mut self, err: Error) -> Option<Pending> {
549		if self.closed.is_some() {
550			return None;
551		}
552		self.record();
553		self.closed = Some(err.clone());
554		let ids: Vec<u64> = self.tokens.keys().copied().collect();
555		for id in ids {
556			self.end_token(id, err.clone());
557		}
558		match &self.acceptor {
559			Acceptor::App(queue) => Some(queue.clone()),
560			_ => None,
561		}
562	}
563}
564
565/// What one direction of a session allows: the grant the peer gave this side (the
566/// union of its tokens) and the limit this side set on the peer, each `None`
567/// while unrestricted.
568#[derive(Clone, Debug, Default, PartialEq, Eq)]
569pub(crate) struct Permit {
570	granted: Option<Prefixes>,
571	limit: Option<Prefixes>,
572}
573
574impl Permit {
575	/// A permit limiting the peer to `limit`, with no grant of its own.
576	#[cfg(test)]
577	pub(crate) fn limited(limit: Prefixes) -> Self {
578		Self {
579			granted: None,
580			limit: Some(limit),
581		}
582	}
583
584	/// A permit the peer granted `granted`, with no limit of our own.
585	#[cfg(test)]
586	pub(crate) fn granting(granted: Prefixes) -> Self {
587		Self {
588			granted: Some(granted),
589			limit: None,
590		}
591	}
592
593	/// Whether both allow `path`, and so every path beneath it.
594	pub(crate) fn matches(&self, path: &str) -> bool {
595		self.granted(path) && self.within_limit(path)
596	}
597
598	/// The paths `scope` holds that both allow too.
599	#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
600	pub(crate) fn within(&self, scope: Prefixes) -> Prefixes {
601		[&self.granted, &self.limit]
602			.into_iter()
603			.flatten()
604			.fold(scope, |scope, prefixes| scope.intersect(prefixes))
605	}
606
607	/// The paths `scope` holds that the limit allows too: what the peer may offer us there.
608	#[cfg(feature = "async")]
609	pub(crate) fn limiting(&self, scope: Prefixes) -> Prefixes {
610		match &self.limit {
611			Some(limit) => scope.intersect(limit),
612			None => scope,
613		}
614	}
615
616	/// Whether the peer's grant alone allows `path`.
617	pub(crate) fn granted(&self, path: &str) -> bool {
618		self.granted.as_ref().is_none_or(|granted| granted.matches(path))
619	}
620
621	/// Whether the limit alone allows `path`: for what the peer offers us, which our
622	/// own grant does not decide.
623	pub(crate) fn within_limit(&self, path: &str) -> bool {
624		self.limit.as_ref().is_none_or(|limit| limit.matches(path))
625	}
626
627	/// The prefixes the peer's grant confines this direction to, or `None` while it
628	/// grants everything: asking for one of them, rather than a prefix above it, is a
629	/// request the peer's floors can certify.
630	#[cfg(feature = "async")]
631	pub(crate) fn granted_regions(&self) -> Option<Vec<crate::Path>> {
632		confining(self.granted.as_ref()?)
633	}
634
635	/// The prefixes the grant and the limit together confine this direction to, or `None`
636	/// while neither does: every path both allow lies within one of them.
637	#[cfg(feature = "async")]
638	pub(crate) fn regions(&self) -> Option<Vec<crate::Path>> {
639		// Neither confining anything leaves every path; otherwise what both allow can never
640		// be every path.
641		fn confines(prefixes: &Option<Prefixes>) -> Option<&Prefixes> {
642			prefixes.as_ref().filter(|prefixes| !prefixes.matches(""))
643		}
644		match (confines(&self.granted), confines(&self.limit)) {
645			(None, None) => None,
646			(Some(one), None) | (None, Some(one)) => confining(one),
647			(Some(granted), Some(limit)) => confining(&granted.intersect(limit)),
648		}
649	}
650
651	/// What the peer granted, or `None` when it grants everything.
652	#[cfg(feature = "async")]
653	pub(crate) fn grant(&self) -> Option<&Prefixes> {
654		self.granted.as_ref()
655	}
656
657	/// The prefixes of the grant that `covered` does not cover, each as the path holding
658	/// what it shows. `None` covers everything.
659	#[cfg(feature = "async")]
660	pub(crate) fn beyond(&self, covered: Option<&Prefixes>) -> Vec<(crate::Prefix, crate::Path)> {
661		let Some(covered) = covered else {
662			return Vec::new();
663		};
664		let granted = match &self.granted {
665			Some(granted) => granted.clone(),
666			None => Prefixes::all(),
667		};
668		(granted.into_iter())
669			.filter(|prefix| !covered.matches(prefix.as_str()))
670			.filter_map(|prefix| {
671				// A prefix too long for a path covers nothing a peer could name.
672				let region = crate::Path::new(prefix.as_str()).ok()?;
673				Some((prefix, region))
674			})
675			.collect()
676	}
677
678	/// Whether the peer granted both the same, whatever limit either set.
679	#[cfg(feature = "async")]
680	pub(crate) fn same_grant(&self, other: &Self) -> bool {
681		self.granted == other.granted
682	}
683
684	/// Whether both set the same limit on the peer, whatever either was granted.
685	#[cfg(feature = "async")]
686	pub(crate) fn same_limit(&self, other: &Self) -> bool {
687		self.limit == other.limit
688	}
689
690	/// Whether this allows everything `other` does.
691	pub(crate) fn covers(&self, other: &Self) -> bool {
692		let covers = |this: &Option<Prefixes>, other: &Option<Prefixes>| match (this, other) {
693			(None, _) => true,
694			(Some(_), None) => false,
695			(Some(this), Some(other)) => this.covers(other),
696		};
697		covers(&self.granted, &other.granted) && covers(&self.limit, &other.limit)
698	}
699}
700
701/// The paths `prefixes` confine every path to, or `None` when they allow every path. A
702/// prefix too long for a path confines to nothing a peer could name, so it drops.
703#[cfg(feature = "async")]
704fn confining(prefixes: &Prefixes) -> Option<Vec<crate::Path>> {
705	match prefixes.matches("") {
706		true => None,
707		false => Some(
708			prefixes
709				.iter()
710				.filter_map(|prefix| crate::Path::new(prefix.as_str()).ok())
711				.collect(),
712		),
713	}
714}
715
716/// The tokens this side presents and the grant they earn, across every session built on it.
717///
718/// A session made without one creates its own, returned by `Session::auth`, which ends
719/// with that session. Pass one to `Client::with_auth` instead and it outlives its
720/// sessions: each presents every token the handle holds, so a [`Credential`] it issued keeps
721/// riding a route's announcements across a reconnect. It backs one active session at a
722/// time, plus the ones draining after a GOAWAY.
723///
724/// Cheap to clone; every clone shares the same tokens.
725#[derive(Clone, Default)]
726pub struct Handle {
727	state: kio::Shared<State>,
728}
729
730impl Handle {
731	/// A handle backing no session yet, for `Client::with_auth`.
732	pub fn new() -> Self {
733		Self::default()
734	}
735
736	/// The union of every grant this side holds on the live session: `None` until its peer
737	/// first answers a token (with a grant or a refusal), while no session is live, and
738	/// forever on a version without AUTH.
739	pub fn grant(&self) -> Watch {
740		Watch::new(self.state.clone(), Selector::Union)
741	}
742
743	/// Present another token on every session of this handle, returning it at once.
744	///
745	/// The grant joins the union while any clone of the returned [`Credential`] lives;
746	/// dropping the last withdraws it, answered or not. With no session live it waits for the
747	/// next one. [`Credential::answered`] resolves on the first verdict. A refusal that may
748	/// pass, such as an unreachable auth server, is presented again after a backoff, and so is
749	/// a token whose stream the peer drops without a verdict.
750	///
751	/// # Errors
752	///
753	/// The handle's end, or [`Error::GoingAway`] when its one session is draining.
754	pub fn add(&self, token: impl Into<Bytes>) -> Result<Credential> {
755		let token = token.into();
756		let mut guard = self.state.lock();
757		let state = &mut *guard;
758		if let Some(err) = &state.closed {
759			return Err(err.clone());
760		}
761		// A draining session takes no new tokens, and a handle of its own has no successor.
762		if state.bound && !state.links.values().any(|link| link.active()) {
763			return Err(Error::GoingAway);
764		}
765		let id = state.present(token);
766		Ok(Credential {
767			presented: std::sync::Arc::new(Presented {
768				state: self.state.clone(),
769				id,
770				link: None,
771			}),
772		})
773	}
774
775	/// Answer every token the peer presents, instead of the default acceptor; see
776	/// [`Handshake::requests`](crate::server::Handshake::requests).
777	///
778	/// Called before the session's driver first polls, since that decides who answers.
779	/// A later call hands the queue to the new [`Requests`], ending the earlier one.
780	pub(crate) fn requests(&self) -> Requests {
781		let queue = Pending::default();
782		let (earlier, closed) = {
783			let mut state = self.state.lock();
784			debug_assert!(
785				!matches!(state.acceptor, Acceptor::Default),
786				"the driver already answers the peer's tokens"
787			);
788			let earlier = std::mem::replace(&mut state.acceptor, Acceptor::App(queue.clone()));
789			(earlier, state.closed.is_some())
790		};
791		// Closed once the lock is released, since refusing its tokens takes the lock again.
792		if let Acceptor::App(earlier) = earlier {
793			earlier.close();
794		}
795		if closed {
796			queue.close();
797		}
798		Requests { queue }
799	}
800
801	/// Authorize the peer's connection credential for `grant` on every session of this
802	/// handle, in the session's own paths. Calling it again re-authorizes, narrower or
803	/// wider, replacing the last grant. The session's origin handles still bound it, so it
804	/// never grants more than they allow.
805	///
806	/// The session's scope for the peer is this grant and every grant issued to one of its
807	/// AUTH tokens through `server::Handshake::requests`; a session never authorized is bound
808	/// only by its origin handles. A request that carries its own token is decided by that
809	/// token instead, inside the scope or not.
810	///
811	/// A narrower scope ends what falls outside at once, with [`Error::Unauthorized`]
812	/// where it has a reader: announcements to the peer retract, its new requests are
813	/// refused, its subscriptions reset, and the broadcasts it published abort. A wider
814	/// one brings back what the old scope held back: announcements to the peer are made
815	/// again, and so are the peer's announcements it withheld from the origin, and new
816	/// requests are accepted. The rest of the session carries on. It works on every
817	/// version, since the session enforces it without the peer's help.
818	///
819	/// When the session answers the peer's connection credential itself, the peer is
820	/// told the grant, within what the origin handles allow, `expires` included. An
821	/// application answering tokens through `server::Handshake::requests` updates its own
822	/// [`Issued`] grants.
823	pub fn authorize(&self, grant: &Grant) {
824		let mut guard = self.state.lock();
825		let state = &mut *guard;
826		if state.limit.as_ref() == Some(grant) {
827			return;
828		}
829		state.limit = Some(grant.clone());
830		for link in state.links.values_mut() {
831			link.epoch += 1;
832			link.rescope(state.limit.as_ref());
833		}
834	}
835
836	/// End the handle with `err`: every token ends, its sessions stop presenting them, and
837	/// the peer's queued tokens are refused. A handle a session created for itself ends
838	/// with that session.
839	pub fn abort(&self, err: Error) {
840		let queue = self.state.lock().abort(err);
841		if let Some(queue) = queue {
842			queue.close();
843		}
844	}
845
846	/// Decide who answers the peer's tokens: the app if it took the requests,
847	/// otherwise the session itself (`None`). Idempotent.
848	fn acceptor(&self) -> Option<Pending> {
849		let mut state = self.state.lock();
850		match &state.acceptor {
851			Acceptor::App(queue) => Some(queue.clone()),
852			Acceptor::Default => None,
853			Acceptor::Undecided => {
854				state.acceptor = Acceptor::Default;
855				None
856			}
857		}
858	}
859}
860
861/// One session's side of a [`Handle`]: the tokens its driver presents, the peer's tokens
862/// it answers, and the grants it enforces.
863///
864/// Cheap to clone; the session leaves its handle when the last clone drops.
865#[derive(Clone)]
866pub(crate) struct Link {
867	handle: Handle,
868	attached: std::sync::Arc<Detach>,
869}
870
871/// Removes a session from its handle once nothing holds its [`Link`].
872struct Detach {
873	state: kio::Shared<State>,
874	id: u64,
875	/// Request tokens, indexed only while at least one naming request holds them. Kept out of
876	/// the handle's state, whose every lock wakes everything waiting on the session's permits.
877	request_tokens: std::sync::Mutex<BTreeMap<Bytes, std::sync::Weak<RequestLifetime>>>,
878}
879
880impl Drop for Detach {
881	fn drop(&mut self) {
882		let queue = {
883			let mut state = self.state.lock();
884			// The link's credential may hold the answer a token set still waits on.
885			state.record();
886			state.links.remove(&self.id);
887			// Dropped without closing, such as a driver dropped mid-session.
888			match state.bound {
889				true => state.abort(Error::Cancel),
890				false => None,
891			}
892		};
893		if let Some(queue) = queue {
894			queue.close();
895		}
896	}
897}
898
899impl Link {
900	/// A session that speaks AUTH (`supported`) or never will, on a handle of its own.
901	pub(crate) fn new(supported: bool) -> Self {
902		Self::bound(supported, false)
903	}
904
905	/// A moq-transport session: it speaks no AUTH, but a request can carry a token itself,
906	/// so a token needs no AUTH to be presented.
907	pub(crate) fn ietf() -> Self {
908		Self::bound(false, true)
909	}
910
911	fn bound(supported: bool, requests: bool) -> Self {
912		let handle = Handle {
913			state: kio::Shared::new(State {
914				bound: true,
915				..Default::default()
916			}),
917		};
918		Self::attach(&handle, supported, requests).expect("a fresh handle backs no session")
919	}
920
921	/// Build a session on `handle`, the moq-transport flavor when `requests`.
922	///
923	/// # Errors
924	///
925	/// [`Error::Duplicate`] while the handle backs another active session, or the
926	/// handle's end.
927	pub(crate) fn attach(handle: &Handle, supported: bool, requests: bool) -> Result<Self> {
928		let mut guard = handle.state.lock();
929		let state = &mut *guard;
930		if let Some(err) = &state.closed {
931			return Err(err.clone());
932		}
933		if state.links.values().any(|link| link.active()) {
934			return Err(Error::Duplicate);
935		}
936		let id = state.next_link;
937		state.next_link += 1;
938		let mut link = Attached::new(supported, requests, state.limit.as_ref());
939		let answers: Vec<_> = state
940			.tokens
941			.iter()
942			.filter(|(_, token)| token.ended.is_none())
943			.filter_map(|(token_id, token)| Some((*token_id, link.offer(*token_id, &token.value)?)))
944			.collect();
945		state.links.insert(id, Box::new(link));
946		for (token_id, answer) in answers {
947			state.answer(token_id, answer.map(|()| Answer::Requests));
948		}
949		Ok(Self {
950			handle: handle.clone(),
951			attached: std::sync::Arc::new(Detach {
952				state: handle.state.clone(),
953				id,
954				request_tokens: Default::default(),
955			}),
956		})
957	}
958
959	/// The handle this session is built on.
960	pub(crate) fn handle(&self) -> &Handle {
961		&self.handle
962	}
963
964	fn state(&self) -> &kio::Shared<State> {
965		&self.handle.state
966	}
967
968	pub(crate) fn id(&self) -> u64 {
969		self.attached.id
970	}
971
972	/// Run `f` on this session's side of the handle.
973	fn with<R>(&self, f: impl FnOnce(&mut Attached) -> R) -> R {
974		self.with_state(|state, id| f(attached(&mut state.links, id)))
975	}
976
977	/// Run `f` on the handle's state, with this session's id.
978	fn with_state<R>(&self, f: impl FnOnce(&mut State, u64) -> R) -> R {
979		f(&mut self.state().lock(), self.id())
980	}
981
982	/// Read this session's side of the handle, and the handle's state.
983	fn read<R>(&self, f: impl FnOnce(&Attached, &State) -> R) -> R {
984		let state = self.state().read();
985		let link = state
986			.links
987			.get(&self.id())
988			.expect("a link outlives its session's state");
989		f(link, &state)
990	}
991
992	/// Retire the session to draining once `goaway` is sent or received, freeing the
993	/// handle for a replacement.
994	pub(crate) fn drain_with(&self, goaway: std::sync::Arc<crate::goaway::Handle>) {
995		self.with(|link| link.goaway = Some(goaway));
996	}
997
998	/// Whether the session still takes new work: open, with no GOAWAY sent or received.
999	pub(crate) fn active(&self) -> bool {
1000		self.read(|link, _| link.active())
1001	}
1002
1003	/// Present a token: the session's own credential at setup, presented on this session
1004	/// alone, or else one of the handle's, presented on every session.
1005	pub(crate) fn present(&self, token: Bytes, setup: bool) -> Result<Credential> {
1006		if !setup {
1007			return self.handle.add(token);
1008		}
1009		let id = self.with_state(|state, link| {
1010			let id = state.next_id;
1011			let link = attached(&mut state.links, link);
1012			if !link.supported && !link.requests {
1013				return Err(Error::Unsupported);
1014			}
1015			if let Some(err) = &link.closed {
1016				return Err(err.clone());
1017			}
1018			// Without AUTH only a request presents it, so nothing will answer.
1019			let phase = match link.supported {
1020				true => {
1021					link.opening.push_back(id);
1022					Phase::Queued { backoff: None }
1023				}
1024				false => Phase::Requests,
1025			};
1026			link.slots.insert(
1027				id,
1028				Slot {
1029					token,
1030					setup: true,
1031					phase,
1032				},
1033			);
1034			state.next_id += 1;
1035			Ok(id)
1036		})?;
1037		Ok(Credential {
1038			presented: std::sync::Arc::new(Presented {
1039				state: self.state().clone(),
1040				id,
1041				link: Some(self.id()),
1042			}),
1043		})
1044	}
1045
1046	/// The token a request carries for `auth`, or `None` when the request goes out unnamed
1047	/// under the session's scope: `auth` came from another handle, it ended here, or
1048	/// requests carry no token on this version.
1049	pub(crate) fn token(&self, auth: &Credential) -> Option<Bytes> {
1050		if !auth.presented.state.is_clone(self.state()) {
1051			return None;
1052		}
1053		self.read(|link, _| {
1054			if !link.requests {
1055				return None;
1056			}
1057			let slot = link.slots.get(&auth.presented.id)?;
1058			slot.phase.ended().is_none().then(|| slot.token.clone())
1059		})
1060	}
1061
1062	/// Verify a request token once per session while any naming request remains open.
1063	pub(crate) fn verify_request(&self, token: crate::setup::Token, hold: Option<Hold>) -> RequestVerdict {
1064		let unsupported = || RequestVerdict {
1065			issue: None,
1066			_lifetime: None,
1067			seen: Default::default(),
1068		};
1069		if token.kind != crate::setup::Token::OUT_OF_BAND || token.value.is_empty() {
1070			return unsupported();
1071		}
1072		let Some(queue) = self.acceptor() else {
1073			return unsupported();
1074		};
1075		let token = Bytes::from(token.value);
1076		// A lifetime this upgrades is dropped only once the index is unlocked, since the last
1077		// one out removes its entry.
1078		let mut stale = None;
1079		let (lifetime, fresh) = {
1080			let mut tokens = self.attached.request_tokens.lock().unwrap();
1081			match tokens.get(&token).and_then(std::sync::Weak::upgrade) {
1082				// A verdict the acceptor already finished with is not shared: the token verifies
1083				// again.
1084				Some(lifetime) if !lifetime.issue.read().done => (lifetime, false),
1085				existing => {
1086					stale = existing;
1087					let lifetime = std::sync::Arc::new(RequestLifetime {
1088						issue: kio::Shared::new(Issue {
1089							hold,
1090							..Default::default()
1091						}),
1092						handle: self.clone(),
1093						token: token.clone(),
1094					});
1095					tokens.insert(token.clone(), std::sync::Arc::downgrade(&lifetime));
1096					(lifetime, true)
1097				}
1098			}
1099		};
1100		drop(stale);
1101		if fresh {
1102			queue.push(Request::new(token, lifetime.issue.clone()));
1103		}
1104		RequestVerdict {
1105			issue: Some(lifetime.issue.clone()),
1106			_lifetime: Some(lifetime),
1107			seen: Default::default(),
1108		}
1109	}
1110
1111	/// Decide who answers the peer's tokens: the app if it took the requests,
1112	/// otherwise the session itself (`None`). Idempotent.
1113	pub(crate) fn acceptor(&self) -> Option<Pending> {
1114		self.handle.acceptor()
1115	}
1116
1117	/// The next token to open a stream for, or `Ready(None)` once the session ends.
1118	pub(crate) fn poll_opening(&self, waiter: &kio::Waiter) -> Poll<Option<(u64, Bytes)>> {
1119		let id = self.id();
1120		loop {
1121			let mut guard = ready_or!(self.state().poll(waiter, |state| {
1122				match state.links.get(&id) {
1123					Some(link) if link.opening.is_empty() && link.closed.is_none() => Poll::Pending,
1124					_ => Poll::Ready(()),
1125				}
1126			}));
1127			let Some(link) = guard.links.get_mut(&id) else {
1128				return Poll::Ready(None);
1129			};
1130			if link.closed.is_some() {
1131				return Poll::Ready(None);
1132			}
1133			let token = link.opening.pop_front().expect("checked non-empty");
1134			// Withdrawn or ended before its stream opened: nothing to present.
1135			if let Some(slot) = link.slots.get_mut(&token)
1136				&& let Phase::Queued { backoff } = slot.phase
1137			{
1138				slot.phase = Phase::Pending { backoff };
1139				return Poll::Ready(Some((token, slot.token.clone())));
1140			}
1141		}
1142	}
1143
1144	/// Whether the token's stream should close: its handle dropped, or it ended, here or
1145	/// for good on another session.
1146	pub(crate) fn poll_withdrawn(&self, id: u64, waiter: &kio::Waiter) -> Poll<()> {
1147		let link = self.id();
1148		let _ = ready_or!(self.state().poll(waiter, |state| {
1149			match state.links.get(&link).and_then(|link| link.slots.get(&id)) {
1150				Some(slot) if slot.phase.live() => Poll::Pending,
1151				_ => Poll::Ready(()),
1152			}
1153		}));
1154		Poll::Ready(())
1155	}
1156
1157	/// Record an AUTH_OK on the token's open stream.
1158	pub(crate) fn granted(&self, id: u64, grant: Grant) {
1159		// One parseable line per AUTH_OK, so the grant the peer actually sent is observable
1160		// without an API; the interop harness checks it against the token it minted.
1161		let list = |prefixes: &Prefixes| format!("{:?}", prefixes.iter().map(|p| p.to_string()).collect::<Vec<_>>());
1162		tracing::debug!(
1163			publish = %list(&grant.publish),
1164			subscribe = %list(&grant.subscribe),
1165			"auth granted"
1166		);
1167		self.with_state(|state, link| {
1168			let link = attached(&mut state.links, link);
1169			let Some(slot) = link.slots.get_mut(&id) else {
1170				return;
1171			};
1172			// Only an open stream carries a reply, and a withdrawn token's grant no longer widens.
1173			if !matches!(slot.phase, Phase::Pending { .. } | Phase::Granted(_)) {
1174				return;
1175			}
1176			// The answer to the connection's own credential accepts the session.
1177			if slot.setup && link.acceptance == Acceptance::Awaiting {
1178				link.acceptance = Acceptance::Accepted;
1179			}
1180			slot.phase = Phase::Granted(grant);
1181			link.replied = true;
1182			link.recompute();
1183			state.answer(id, Ok(Answer::Granted));
1184			// Latch a set this grant completed, before a later revocation can replace its answer.
1185			state.record();
1186		});
1187	}
1188
1189	/// Open the token's stream as the driver does, if it is still queued.
1190	#[cfg(test)]
1191	pub(crate) fn open(&self, id: u64) {
1192		self.with(|link| {
1193			if let Some(slot) = link.slots.get_mut(&id)
1194				&& let Phase::Queued { backoff } = slot.phase
1195			{
1196				link.opening.retain(|opening| *opening != id);
1197				slot.phase = Phase::Pending { backoff };
1198			}
1199		});
1200	}
1201
1202	/// Record an AUTH_OK for the token as the driver does: on its stream, opened first if it
1203	/// is still queued.
1204	#[cfg(test)]
1205	pub(crate) fn grant(&self, id: u64, grant: Grant) {
1206		self.open(id);
1207		self.granted(id, grant);
1208	}
1209
1210	/// Record an AUTH_ERROR for the token: a reply that grants nothing, so a refused
1211	/// setup token leaves an empty union rather than an unknown (unrestricted) one.
1212	/// `undecided` is what its code says (see `lite::AuthError::undecided`): the acceptor
1213	/// failed to decide, so the token is presented again rather than ended.
1214	/// The driver then calls [`retry`](Self::retry), as on every end of the token's stream.
1215	pub(crate) fn refused(&self, id: u64, undecided: bool) {
1216		self.with(|link| {
1217			let Some(slot) = link.slots.get_mut(&id) else {
1218				return;
1219			};
1220			link.replied = true;
1221			slot.phase = match slot.phase {
1222				Phase::Pending { backoff } | Phase::Refused { backoff, .. } => Phase::Refused { backoff, undecided },
1223				// A refusal after a grant revokes it.
1224				Phase::Granted(_) => Phase::Refused {
1225					backoff: None,
1226					undecided,
1227				},
1228				_ => return,
1229			};
1230			link.recompute();
1231		});
1232	}
1233
1234	/// The delay before presenting a token again once its stream ended with `err`, or `None`
1235	/// when the driver should end it instead.
1236	///
1237	/// A token still wanted on an active session is presented again when the peer's refusal
1238	/// left it undecided, or, on a shared handle, when its stream was lost without a
1239	/// verdict, so the session never runs on without it. A session's own handle ends a lost
1240	/// token instead, which tells the application. Both back off from [`RETRY_INITIAL`],
1241	/// doubling until a grant resets it.
1242	pub(crate) fn retry(&self, id: u64, err: &Error) -> Option<Duration> {
1243		self.with_state(|state, link| {
1244			let bound = state.bound;
1245			let link = attached(&mut state.links, link);
1246			if !link.active() {
1247				return None;
1248			}
1249			let slot = link.slots.get_mut(&id)?;
1250			// Only an open stream is presented again; a grant resets the backoff.
1251			let backoff = match slot.phase {
1252				Phase::Pending { backoff } | Phase::Refused { backoff, .. } => backoff,
1253				Phase::Granted(_) => None,
1254				_ => return None,
1255			};
1256			// A protocol violation ends the session anyway.
1257			if verdict(&slot.phase, err) || matches!(err, Error::ProtocolViolation) {
1258				return None;
1259			}
1260			if bound && !matches!(slot.phase, Phase::Refused { .. }) {
1261				return None;
1262			}
1263			let delay = backoff.map_or(RETRY_INITIAL, |delay| (delay * 2).min(RETRY_MAX));
1264			// Unanswered again, as on its first presentation: a request or publication the
1265			// token might cover waits for the retry's verdict rather than being judged without it.
1266			slot.phase = Phase::Queued { backoff: Some(delay) };
1267			link.epoch += 1;
1268			link.recompute();
1269			Some(delay)
1270		})
1271	}
1272
1273	/// The token to present again once a [`retry`](Self::retry) delay passes.
1274	///
1275	/// # Errors
1276	///
1277	/// [`Error::GoingAway`] once the session is draining, so a successor presents it instead
1278	/// and a handle of the session's own never reads it as the peer's clean close, or
1279	/// [`Error::Cancel`] when it is no longer wanted here.
1280	pub(crate) fn reopen(&self, id: u64) -> Result<Bytes> {
1281		self.with(|link| {
1282			if !link.active() {
1283				return Err(Error::GoingAway);
1284			}
1285			match link.slots.get_mut(&id) {
1286				Some(slot) if let Phase::Queued { backoff } = slot.phase => {
1287					slot.phase = Phase::Pending { backoff };
1288					Ok(slot.token.clone())
1289				}
1290				_ => Err(Error::Cancel),
1291			}
1292		})
1293	}
1294
1295	/// End the token on this session, once [`retry`](Self::retry) declined to present it
1296	/// again: refused or revoked by the peer, withdrawn by us, or its stream lost while the
1297	/// session drains. A token that was never answered records `err` as its answer. The
1298	/// peer's verdict ends one of the handle's tokens on every session; anything else
1299	/// leaves it for the next session to present, except on a handle of the session's own.
1300	pub(crate) fn ended(&self, id: u64, err: Error) {
1301		self.with_state(|state, link_id| {
1302			// Latch a set already complete, so this end never replaces its answer.
1303			state.record();
1304			// A draining session's verdict is stale while an active session still presents the
1305			// token: that session's own answer decides, even mid-retry with no grant right now.
1306			let superseded = !attached(&mut state.links, link_id).active()
1307				&& state.links.iter().any(|(other, link)| {
1308					*other != link_id && link.active() && link.slots.get(&id).is_some_and(|slot| slot.phase.live())
1309				});
1310			// A handle of the session's own has no next session to present it, so any end is final.
1311			let bound = state.bound;
1312			let link = attached(&mut state.links, link_id);
1313			let Some(slot) = link.slots.get_mut(&id) else {
1314				return;
1315			};
1316			let settled = !slot.setup
1317				&& !superseded
1318				&& link.closed.is_none()
1319				&& slot.phase.live()
1320				&& (bound || verdict(&slot.phase, &err));
1321			match slot.phase {
1322				Phase::Ended(_) => {}
1323				// The handle is gone and the token is over: nothing will read the slot again.
1324				Phase::Withdrawn { .. } => {
1325					link.slots.remove(&id);
1326				}
1327				_ => slot.phase = Phase::Ended(err.clone()),
1328			}
1329			// Even with the union unchanged, a request carrying this token must drop it.
1330			link.epoch += 1;
1331			link.recompute();
1332			if settled {
1333				state.end_token(id, err);
1334			}
1335		});
1336	}
1337
1338	/// Resolve once every token the session presented at setup has its first
1339	/// reply, so enforcement never waits on a token the app added later.
1340	pub(crate) fn poll_setup_answered(&self, waiter: &kio::Waiter) -> Poll<()> {
1341		let id = self.id();
1342		let _ = ready_or!(self.state().poll(waiter, |state| {
1343			let pending = state
1344				.links
1345				.get(&id)
1346				.is_some_and(|link| link.slots.values().any(|slot| slot.setup && !slot.phase.answered()));
1347			match pending {
1348				true => Poll::Pending,
1349				false => Poll::Ready(()),
1350			}
1351		}));
1352		Poll::Ready(())
1353	}
1354
1355	/// Wait only when a token already presented might widen the grant for this path.
1356	fn poll_presented(&self, direction: Direction, path: &str, waiter: &kio::Waiter) -> Poll<()> {
1357		let id = self.id();
1358		let _ = ready_or!(self.state().poll(waiter, |state| {
1359			let Some(link) = state.links.get(&id) else {
1360				return Poll::Ready(());
1361			};
1362			let (granted, _) = link.parts(direction);
1363			if granted.is_some_and(|grant| grant.matches(path))
1364				|| !link
1365					.slots
1366					.values()
1367					.any(|slot| !slot.token.is_empty() && !slot.phase.answered() && slot.phase.live())
1368			{
1369				Poll::Ready(())
1370			} else {
1371				Poll::Pending
1372			}
1373		}));
1374		Poll::Ready(())
1375	}
1376
1377	/// Record the grant an application issued to the peer's AUTH token `id`, or forget it with
1378	/// `None`, resizing the scope.
1379	fn issue(&self, id: u64, grant: Option<Grant>) {
1380		self.with_state(|state, link| {
1381			let link = attached(&mut state.links, link);
1382			match grant {
1383				Some(grant) => link.issued.insert(id, grant),
1384				None => link.issued.remove(&id),
1385			};
1386			link.rescope(state.limit.as_ref());
1387		});
1388	}
1389
1390	/// The union once it changed since `epoch` last saw it, advancing `epoch`. It
1391	/// only ever changes into `Some`: no answer yet is the initial state.
1392	pub(crate) fn poll_union(&self, epoch: &mut u64, waiter: &kio::Waiter) -> Poll<Option<Grant>> {
1393		let state = ready_or!(self.poll_epoch(*epoch, waiter));
1394		let link = &state.links[&self.id()];
1395		*epoch = link.epoch;
1396		Poll::Ready(link.union.clone())
1397	}
1398
1399	/// What `direction` allows once it may have changed since `epoch` last saw it,
1400	/// advancing `epoch`.
1401	pub(crate) fn poll_permit(&self, direction: Direction, epoch: &mut u64, waiter: &kio::Waiter) -> Poll<Permit> {
1402		let state = ready_or!(self.poll_epoch(*epoch, waiter));
1403		let link = &state.links[&self.id()];
1404		*epoch = link.epoch;
1405		Poll::Ready(link.permit(direction))
1406	}
1407
1408	/// What `direction` allows right now.
1409	#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
1410	pub(crate) fn permit(&self, direction: Direction) -> Permit {
1411		self.read(|link, _| link.permit(direction))
1412	}
1413
1414	/// Whether the scope set for the peer leaves out no path in either direction, as when
1415	/// none was set and only the origin handles bound it.
1416	#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
1417	pub(crate) fn admits_whole(&self) -> bool {
1418		[Direction::Publish, Direction::Subscribe]
1419			.into_iter()
1420			.all(|direction| self.within_limit(direction, ""))
1421	}
1422
1423	/// The limit once it may have changed since `epoch` last saw it, advancing `epoch`.
1424	pub(crate) fn poll_limit(&self, epoch: &mut u64, waiter: &kio::Waiter) -> Poll<Option<Grant>> {
1425		let state = ready_or!(self.poll_epoch(*epoch, waiter));
1426		*epoch = state.links[&self.id()].epoch;
1427		Poll::Ready(state.limit.clone())
1428	}
1429
1430	fn poll_epoch(&self, seen: u64, waiter: &kio::Waiter) -> Poll<kio::Mut<'_, State>> {
1431		let id = self.id();
1432		self.state().poll(waiter, |state| match state.links[&id].epoch != seen {
1433			true => Poll::Ready(()),
1434			false => Poll::Pending,
1435		})
1436	}
1437
1438	/// Whether `direction` allows `path` right now: the union (allowing everything
1439	/// while it is `None`, before an answer or on a version without AUTH) and the
1440	/// limit both.
1441	pub(crate) fn allows(&self, direction: Direction, path: &str) -> bool {
1442		self.read(|link, _| link.allows(direction, path))
1443	}
1444
1445	/// Whether a request token decides the request carrying it, rather than the session's
1446	/// scope: the application verifies every token, or the request is refused as unsupported
1447	/// without an acceptor, even where the scope already covers it. A token admitted unread
1448	/// would leave the peer believing it backs a request this side holds to its scope. A side
1449	/// that neither scopes the peer nor answers tokens has nothing to check one against, and
1450	/// admits as it would without it.
1451	pub(crate) fn token_decides(&self, direction: Direction) -> bool {
1452		self.read(|link, state| {
1453			let (_, scope) = link.parts(direction);
1454			scope.is_some() || matches!(state.acceptor, Acceptor::App(_))
1455		})
1456	}
1457
1458	/// Whether the peer's grant alone allows `direction` at `path`, allowing everything
1459	/// while it is `None`: what bounds this side whatever authorized the request.
1460	pub(crate) fn within_grant(&self, direction: Direction, path: &str) -> bool {
1461		self.read(|link, _| {
1462			let (granted, _) = link.parts(direction);
1463			granted.is_none_or(|granted| granted.matches(path))
1464		})
1465	}
1466
1467	/// Whether the scope alone allows `direction` at `path`: for a route the peer
1468	/// offers us, which our own grant does not decide.
1469	pub(crate) fn within_limit(&self, direction: Direction, path: &str) -> bool {
1470		self.read(|link, _| {
1471			let (_, scope) = link.parts(direction);
1472			scope.is_none_or(|scope| scope.matches(path))
1473		})
1474	}
1475
1476	/// Why the session ended, once it has.
1477	fn closed(&self) -> Option<Error> {
1478		self.read(|link, _| link.closed.clone())
1479	}
1480
1481	/// The peer accepts the connection credential only with an answer this client reads after
1482	/// the session is live, while the server can still refuse it: its SETUP on a version
1483	/// without AUTH, or the AUTH_OK to the connection's own credential on one with it.
1484	pub(crate) fn await_acceptance(&self) {
1485		self.with(|link| link.acceptance = Acceptance::Awaiting);
1486	}
1487
1488	/// The version never answers the connection credential: the peer refuses it only by
1489	/// closing the session, however soon.
1490	pub(crate) fn silent(&self) {
1491		self.with(|link| link.acceptance = Acceptance::Silent);
1492	}
1493
1494	/// Whether the version never answers the connection credential, so only uptime can
1495	/// suggest the peer took it.
1496	pub(crate) fn is_silent(&self) -> bool {
1497		self.read(|link, _| link.acceptance == Acceptance::Silent)
1498	}
1499
1500	/// The peer's SETUP arrived, so it accepted the connection credential.
1501	pub(crate) fn accepted(&self) {
1502		self.with_state(|state, link| {
1503			let link = attached(&mut state.links, link);
1504			if link.acceptance == Acceptance::Awaiting {
1505				link.acceptance = Acceptance::Accepted;
1506			}
1507			// Latch a set this acceptance completed, before a later end can replace its answer.
1508			state.record();
1509		});
1510	}
1511
1512	/// Ready once the peer said it accepts the connection credential, which a version without
1513	/// that answer never does. A close afterward leaves it accepted.
1514	pub(crate) fn poll_accepted(&self, waiter: &kio::Waiter) -> Poll<()> {
1515		let id = self.id();
1516		let _ = ready_or!(self.state().poll(waiter, |state| {
1517			match state.links.get(&id).map(|link| link.acceptance) {
1518				Some(Acceptance::Accepted) => Poll::Ready(()),
1519				_ => Poll::Pending,
1520			}
1521		}));
1522		Poll::Ready(())
1523	}
1524
1525	/// End the session: fail every pending token here, leaving the handle's tokens for the
1526	/// next session. A handle the session created for itself ends with it.
1527	pub(crate) fn close(&self, err: Error) {
1528		let closing = self.with_state(|state, link| {
1529			if state.links[&link].closed.is_some() {
1530				return None;
1531			}
1532			// The session's credential may hold the answer a token set still waits on.
1533			state.record();
1534			let link = attached(&mut state.links, link);
1535			link.closed = Some(err.clone());
1536			link.opening.clear();
1537			link.cut = link
1538				.slots
1539				.iter()
1540				.filter(|(_, slot)| !slot.phase.answered())
1541				.map(|(id, _)| *id)
1542				.collect();
1543			for slot in link.slots.values_mut() {
1544				if !matches!(slot.phase, Phase::Ended(_)) {
1545					slot.phase = Phase::Ended(err.clone());
1546				}
1547			}
1548			link.recompute();
1549			Some(match state.bound {
1550				true => state.abort(err.clone()),
1551				false => None,
1552			})
1553		});
1554		let Some(queue) = closing else {
1555			return;
1556		};
1557		// Collected first: a lifetime dropped here removes its own entry.
1558		let lifetimes: Vec<_> = (self.attached.request_tokens.lock().unwrap().values())
1559			.filter_map(std::sync::Weak::upgrade)
1560			.collect();
1561		for lifetime in &lifetimes {
1562			lifetime.issue.lock().peer.get_or_insert(err.clone());
1563		}
1564		drop(lifetimes);
1565		// Refusing the queued tokens takes the lock again, to drop them from the scope.
1566		if let Some(queue) = queue {
1567			queue.close();
1568		}
1569	}
1570}
1571
1572/// A session's side of the handle, which lives as long as any [`Link`] to it.
1573fn attached(links: &mut BTreeMap<u64, Box<Attached>>, id: u64) -> &mut Attached {
1574	links.get_mut(&id).expect("a link outlives its session's state")
1575}
1576
1577/// One credential this side presented, returned by [`Handle`]'s `add`.
1578///
1579/// Cheap to clone, and every clone names the same credential. It stays presented on
1580/// every session of its handle until the last clone drops, which closes its streams and
1581/// removes its grant from the union. A [`Route`](crate::origin::RouteInfo) holding one keeps
1582/// it presented while the route stands, across the handle's sessions.
1583#[derive(Clone)]
1584pub struct Credential {
1585	presented: std::sync::Arc<Presented>,
1586}
1587
1588#[cfg(test)]
1589impl Credential {
1590	/// The id the session presents this credential under.
1591	pub(crate) fn id(&self) -> u64 {
1592		self.presented.id
1593	}
1594}
1595
1596/// The token every clone of one [`Credential`] shares, withdrawn when the last drops.
1597struct Presented {
1598	state: kio::Shared<State>,
1599	id: u64,
1600	/// The one session that presents it: a session's own credential. `None` for a
1601	/// handle's token, presented on every session.
1602	link: Option<u64>,
1603}
1604
1605impl Presented {
1606	fn selector(&self) -> Selector {
1607		match self.link {
1608			Some(link) => Selector::Setup { link, id: self.id },
1609			None => Selector::Token(self.id),
1610		}
1611	}
1612}
1613
1614impl Credential {
1615	/// This credential's own grant on the live session: `None` until its peer answers,
1616	/// while no session is live, forever on moq-transport without AUTH, and again once
1617	/// the credential ends.
1618	pub fn grant(&self) -> Watch {
1619		Watch::new(self.presented.state.clone(), self.presented.selector())
1620	}
1621
1622	/// Wait for the credential to end for good: a peer's refusal or revocation as
1623	/// [`Error::Session`], [`Error::Cancel`] when the peer closed it without one, or the
1624	/// handle's end. A session ending is not one: the next session presents it again.
1625	#[cfg(feature = "async")]
1626	pub async fn closed(&self) -> Error {
1627		kio::wait(|waiter| self.poll_closed(waiter)).await
1628	}
1629
1630	/// See [`Self::closed`].
1631	fn poll_closed(&self, waiter: &kio::Waiter) -> Poll<Error> {
1632		let selector = self.presented.selector();
1633		let state = ready_or!(self.presented.state.poll(waiter, |state| {
1634			match selector.ended(state) {
1635				Some(_) => Poll::Ready(()),
1636				None => Poll::Pending,
1637			}
1638		}));
1639		Poll::Ready(selector.ended(&state).unwrap_or(Error::Cancel))
1640	}
1641
1642	/// Wait for the peer's first verdict on the token: `Ok` once a peer accepts it, at once on
1643	/// moq-transport without AUTH, where only a request that names it carries the token.
1644	///
1645	/// # Errors
1646	///
1647	/// [`Error::Unsupported`] when neither the session nor its requests can carry a token
1648	/// (moq-lite without AUTH, or a peer that takes no tokens in band), the peer's refusal as
1649	/// [`Error::Session`], or the handle's end.
1650	#[cfg_attr(feature = "async", kio::wrapper)]
1651	pub fn poll_answered(&self, waiter: &kio::Waiter) -> Poll<Result<()>> {
1652		self.poll_answer(waiter).map(|answer| answer.map(drop))
1653	}
1654
1655	/// Poll for the first verdict on a handle's token: a grant on any session, or the
1656	/// refusal or end that settles it.
1657	fn poll_answer(&self, waiter: &kio::Waiter) -> Poll<Result<Answer>> {
1658		let id = self.presented.id;
1659		let answered = |state: &State| match state.tokens.get(&id) {
1660			Some(token) => token.answered.clone(),
1661			None => Some(Err(Error::Cancel)),
1662		};
1663		let state = ready_or!(self.presented.state.poll(waiter, |state| match answered(state) {
1664			Some(_) => Poll::Ready(()),
1665			None => Poll::Pending,
1666		}));
1667		Poll::Ready(answered(&state).unwrap_or(Err(Error::Cancel)))
1668	}
1669}
1670
1671impl PartialEq for Credential {
1672	fn eq(&self, other: &Self) -> bool {
1673		std::sync::Arc::ptr_eq(&self.presented, &other.presented)
1674	}
1675}
1676
1677impl Eq for Credential {}
1678
1679impl std::fmt::Debug for Credential {
1680	// Never the token: routes are logged, and a credential must not be.
1681	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1682		f.debug_tuple("Credential").field(&self.presented.id).finish()
1683	}
1684}
1685
1686impl Drop for Presented {
1687	fn drop(&mut self) {
1688		let mut guard = self.state.lock();
1689		let state = &mut *guard;
1690		match self.link {
1691			Some(link) => {
1692				if let Some(link) = state.links.get_mut(&link) {
1693					link.withdraw(self.id);
1694				}
1695			}
1696			None => state.withdraw(self.id),
1697		}
1698	}
1699}
1700
1701/// Which grant a [`Watch`] follows.
1702#[derive(Clone, Copy)]
1703enum Selector {
1704	/// The live session's union.
1705	Union,
1706	/// A handle's token, on the live session.
1707	Token(u64),
1708	/// A session's own credential, on that session.
1709	Setup { link: u64, id: u64 },
1710}
1711
1712impl Selector {
1713	fn current<'a>(&self, state: &'a State) -> Option<&'a Grant> {
1714		match *self {
1715			Self::Union => state.live()?.union.as_ref(),
1716			Self::Token(id) => state.live()?.slots.get(&id)?.phase.grant(),
1717			Self::Setup { link, id } => state.links.get(&link)?.slots.get(&id)?.phase.grant(),
1718		}
1719	}
1720
1721	/// Why nothing will change the grant again, once nothing will.
1722	fn ended(&self, state: &State) -> Option<Error> {
1723		if let Some(err) = &state.closed {
1724			return Some(err.clone());
1725		}
1726		match *self {
1727			Self::Union => None,
1728			Self::Token(id) => match state.tokens.get(&id) {
1729				Some(token) => token.ended.clone(),
1730				None => Some(Error::Cancel),
1731			},
1732			Self::Setup { link, id } => match state.links.get(&link).and_then(|link| link.slots.get(&id)) {
1733				Some(slot) => slot.phase.ended().cloned(),
1734				None => Some(Error::Cancel),
1735			},
1736		}
1737	}
1738}
1739
1740/// Watches a grant: the live session's union, or one credential's.
1741///
1742/// Created by [`Handle::grant`] and [`Credential::grant`].
1743pub struct Watch {
1744	state: kio::Shared<State>,
1745	selector: Selector,
1746	last: Option<Grant>,
1747}
1748
1749impl Watch {
1750	fn new(state: kio::Shared<State>, selector: Selector) -> Self {
1751		let mut watch = Self {
1752			state,
1753			selector,
1754			last: None,
1755		};
1756		watch.last = watch.peek();
1757		watch
1758	}
1759
1760	/// The grant right now.
1761	pub fn peek(&self) -> Option<Grant> {
1762		self.selector.current(&self.state.read()).cloned()
1763	}
1764
1765	/// The grant once it differs from the last one this watch returned (or saw at
1766	/// creation).
1767	///
1768	/// # Errors
1769	///
1770	/// Once nothing will change it again: the handle ended, or for a token's watch, the
1771	/// token ended for good.
1772	#[cfg_attr(feature = "async", kio::wrapper)]
1773	pub fn poll_changed(&mut self, waiter: &kio::Waiter) -> Poll<Result<Option<Grant>>> {
1774		let last = &self.last;
1775		let selector = self.selector;
1776		let state = ready_or!(self.state.poll(waiter, |state| {
1777			match selector.current(state) != last.as_ref() || selector.ended(state).is_some() {
1778				true => Poll::Ready(()),
1779				false => Poll::Pending,
1780			}
1781		}));
1782		let current = selector.current(&state).cloned();
1783		if current != self.last {
1784			self.last = current.clone();
1785			return Poll::Ready(Ok(current));
1786		}
1787		Poll::Ready(Err(selector.ended(&state).unwrap_or(Error::Cancel)))
1788	}
1789}
1790
1791/// The tokens the peer presents, for an application that answers them itself.
1792///
1793/// Returned by `server::Handshake::requests`. Dropping it refuses every later token.
1794pub struct Requests {
1795	queue: Pending,
1796}
1797
1798impl Requests {
1799	/// The next token the peer presents, or `None` once the handle ends.
1800	#[cfg_attr(feature = "async", kio::wrapper)]
1801	pub fn poll_next(&mut self, waiter: &kio::Waiter) -> Poll<Option<Request>> {
1802		self.queue.poll_next(waiter)
1803	}
1804}
1805
1806impl Drop for Requests {
1807	fn drop(&mut self) {
1808		self.queue.close();
1809	}
1810}
1811
1812/// Pending application decisions, bounded by the stream and request credit each one holds.
1813#[derive(Clone, Default)]
1814pub(crate) struct Pending {
1815	state: kio::Shared<PendingState>,
1816}
1817
1818#[derive(Default)]
1819struct PendingState {
1820	requests: VecDeque<Request>,
1821	/// How many requests survived the last prune: pruning again only once the queue doubles
1822	/// keeps a push amortized O(1).
1823	survivors: usize,
1824	closed: bool,
1825}
1826
1827impl Pending {
1828	/// Refuse every queued token and every later one. Call it without the handle's lock,
1829	/// which refusing a token takes.
1830	fn close(&self) {
1831		let refused = {
1832			let mut state = self.state.lock();
1833			state.closed = true;
1834			std::mem::take(&mut state.requests)
1835		};
1836		drop(refused);
1837	}
1838
1839	/// Queue the token for the application, or refuse it when closed.
1840	pub(crate) fn push(&self, request: Request) {
1841		let mut state = self.state.lock();
1842		// Dropping the request refuses it as unanswered.
1843		if state.closed {
1844			return;
1845		}
1846		// A withdrawn token gave its credit back, so it must not stay queued while the
1847		// acceptor is busy: that would let a peer that keeps withdrawing grow the queue.
1848		if state.requests.len() >= 2 * state.survivors.max(1) {
1849			state.requests.retain(|request| request.issue().read().peer.is_none());
1850			state.survivors = state.requests.len();
1851		}
1852		state.requests.push_back(request);
1853	}
1854
1855	fn poll_next(&self, waiter: &kio::Waiter) -> Poll<Option<Request>> {
1856		loop {
1857			let mut state = std::task::ready!(self.state.poll(waiter, |state| {
1858				if state.closed || !state.requests.is_empty() {
1859					Poll::Ready(())
1860				} else {
1861					Poll::Pending
1862				}
1863			}));
1864			while let Some(request) = state.requests.pop_front() {
1865				// Taken under the same lock its withdrawal checks, so from here the application
1866				// owns the request's slot until it answers.
1867				let mut issue = request.issue().lock();
1868				if issue.peer.is_none() {
1869					issue.taken = true;
1870					drop(issue);
1871					return Poll::Ready(Some(request));
1872				}
1873			}
1874			if state.closed {
1875				return Poll::Ready(None);
1876			}
1877		}
1878	}
1879}
1880
1881/// What the acceptor writes on one peer token's stream.
1882#[derive(Clone)]
1883pub(crate) enum Reply {
1884	Grant(Grant),
1885	Refuse { code: SessionError, reason: String },
1886}
1887
1888/// The acceptor's side of one peer token's stream, shared with the driver.
1889#[derive(Default)]
1890pub(crate) struct Issue {
1891	/// Replies for the driver to write, in order: at most a grant the peer has not taken yet
1892	/// and the refusal ending it.
1893	outbox: VecDeque<Reply>,
1894	/// Request-token readers each observe the latest verdict independently.
1895	latest: Option<Reply>,
1896	revision: u64,
1897	/// The app is done with the stream: the driver closes it once the outbox drains.
1898	done: bool,
1899	/// Why the stream ended on the peer's side, once it has.
1900	pub peer: Option<Error>,
1901	/// A request token's share of its request's slot, held while the application verifies it.
1902	hold: Option<Hold>,
1903	/// The application took the token off the queue.
1904	taken: bool,
1905	/// An AUTH token's place in the session's scope, which its grant joins. A token that rode
1906	/// on a request has none: its grant covers only that request.
1907	scoped: Option<(Link, u64)>,
1908}
1909
1910impl Issue {
1911	/// Push a reply, keeping the session's scope in step with the grant an AUTH token holds.
1912	/// Called under the issue's lock, so a withdrawal recorded under it is never undone.
1913	fn reply(&mut self, reply: Reply) {
1914		if let Some((handle, id)) = &self.scoped {
1915			match &reply {
1916				Reply::Grant(grant) if self.peer.is_none() => handle.issue(*id, Some(grant.clone())),
1917				_ => handle.issue(*id, None),
1918			}
1919		}
1920		self.revision += 1;
1921		if self.scoped.is_some() {
1922			self.queue(reply);
1923		} else {
1924			self.latest = Some(reply);
1925		}
1926	}
1927
1928	/// Queue a reply for the driver to write, unless the stream is done. It replaces a grant
1929	/// still queued, which the peer never saw, so a peer withholding stream credit cannot
1930	/// make the outbox grow.
1931	pub(crate) fn queue(&mut self, reply: Reply) {
1932		if self.done {
1933			return;
1934		}
1935		match self.outbox.back_mut() {
1936			Some(queued @ Reply::Grant(_)) => *queued = reply,
1937			_ => self.outbox.push_back(reply),
1938		}
1939	}
1940
1941	/// The next reply for the driver to write.
1942	pub(crate) fn next(&mut self) -> Option<Reply> {
1943		self.outbox.pop_front()
1944	}
1945
1946	/// Whether the driver has nothing to do until the acceptor replies again.
1947	pub(crate) fn idle(&self) -> bool {
1948		self.outbox.is_empty() && !self.done
1949	}
1950
1951	/// The driver refused the token itself, as for a grant too large to encode: nothing
1952	/// queued goes out, and whatever the token was granted leaves the scope.
1953	pub(crate) fn refused(&mut self) {
1954		self.outbox.clear();
1955		self.finish();
1956	}
1957
1958	/// The application is done with the token: its grant leaves the scope.
1959	pub(crate) fn finish(&mut self) {
1960		self.done = true;
1961		if let Some((handle, id)) = &self.scoped {
1962			handle.issue(*id, None);
1963		}
1964	}
1965}
1966
1967/// A request's slot in the session's count, shared with the application's verification of its
1968/// token so work still in flight stays counted after the request ends. Opaque here: auth only
1969/// keeps it alive.
1970pub(crate) type Hold = std::sync::Arc<dyn std::any::Any + Send + Sync>;
1971
1972/// The serving task's hold on one peer token's [`Issue`].
1973///
1974/// Dropping it settles [`Issued::closed`] with the session's error, unless the task
1975/// already recorded why the stream ended, so no exit path leaves the acceptor waiting.
1976pub(crate) struct Serving {
1977	pub issue: kio::Shared<Issue>,
1978	handle: Link,
1979}
1980
1981impl Serving {
1982	/// A fresh stream's shared state, settled by the session `handle` if the task drops.
1983	pub(crate) fn new(handle: Link) -> Self {
1984		let id = {
1985			let mut state = handle.state().lock();
1986			state.next_issue += 1;
1987			state.next_issue
1988		};
1989		Self {
1990			issue: kio::Shared::new(Issue {
1991				scoped: Some((handle.clone(), id)),
1992				..Default::default()
1993			}),
1994			handle,
1995		}
1996	}
1997
1998	/// Record why the stream ended on the peer's side; the first reason wins. Whatever it
1999	/// granted leaves the scope.
2000	pub(crate) fn end(&self, err: Error) {
2001		let mut issue = self.issue.lock();
2002		issue.peer.get_or_insert(err);
2003		if let Some((handle, id)) = &issue.scoped {
2004			handle.issue(*id, None);
2005		}
2006	}
2007}
2008
2009impl Drop for Serving {
2010	fn drop(&mut self) {
2011		let err = self.handle.closed().unwrap_or(Error::Cancel);
2012		self.end(err);
2013	}
2014}
2015
2016/// A token the peer presented, waiting for an answer.
2017///
2018/// It arrived on its own AUTH stream, or on one of the peer's moq-transport requests. Either
2019/// way the grant it earns is enforced by the session: an AUTH token's joins the session's
2020/// scope, while one that rode on requests admits only those naming it, which end with it.
2021///
2022/// Dropping it unanswered refuses the token with [`SessionError::Unauthorized`].
2023pub struct Request {
2024	token: Bytes,
2025	issue: Option<kio::Shared<Issue>>,
2026}
2027
2028impl Request {
2029	pub(crate) fn new(token: Bytes, issue: kio::Shared<Issue>) -> Self {
2030		Self {
2031			token,
2032			issue: Some(issue),
2033		}
2034	}
2035
2036	fn issue(&self) -> &kio::Shared<Issue> {
2037		self.issue.as_ref().expect("unanswered request")
2038	}
2039
2040	/// The token the peer presented. Empty means the credential its connection
2041	/// already carried, or none.
2042	pub fn token(&self) -> &Bytes {
2043		&self.token
2044	}
2045
2046	/// Wait for the peer to withdraw this unanswered token, end the request it rode on, or
2047	/// close the session.
2048	#[cfg(feature = "async")]
2049	pub async fn closed(&self) -> Error {
2050		kio::wait(|waiter| poll_closed(self.issue(), waiter)).await
2051	}
2052
2053	/// Grant the token. The grant holds until the returned [`Issued`] is revoked
2054	/// or dropped, or the peer withdraws the token or ends its last naming request.
2055	///
2056	/// Revoking an AUTH token's grant once `expires` passes is the acceptor's job; a grant
2057	/// on a request lapses at `expires` by itself.
2058	pub fn accept(mut self, grant: Grant) -> Issued {
2059		let issue = self.issue.take().expect("answered once");
2060		let mut locked = issue.lock();
2061		locked.reply(Reply::Grant(grant));
2062		locked.hold = None;
2063		drop(locked);
2064		Issued { issue }
2065	}
2066
2067	/// Refuse the token with a session error code and a reason for the peer.
2068	///
2069	/// [`SessionError::Internal`], [`SessionError::TooManyRequests`], and
2070	/// [`SessionError::Timeout`] say this side failed to decide, such as with its auth backend
2071	/// down, so a moq-lite peer presents the token again after a backoff; any other code ends it.
2072	pub fn reject(mut self, code: SessionError, reason: impl Into<String>) {
2073		let issue = self.issue.take().expect("answered once");
2074		refuse(&issue, code, reason.into());
2075		issue.lock().hold = None;
2076	}
2077}
2078
2079impl Drop for Request {
2080	fn drop(&mut self) {
2081		if let Some(issue) = self.issue.take() {
2082			refuse(&issue, SessionError::Unauthorized, "unanswered".to_string());
2083			issue.lock().hold = None;
2084		}
2085	}
2086}
2087
2088fn refuse(issue: &kio::Shared<Issue>, code: SessionError, reason: String) {
2089	let mut issue = issue.lock();
2090	if !issue.done {
2091		issue.reply(Reply::Refuse { code, reason });
2092		issue.finish();
2093	}
2094}
2095
2096/// Which kind of moq-transport request a token rode on, and so which part of the [`Grant`]
2097/// must cover it.
2098#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
2099pub(crate) enum RequestKind {
2100	/// The peer reads a track: a SUBSCRIBE, a FETCH, or a TRACK_STATUS. Covered by the
2101	/// grant's `subscribe` prefixes.
2102	Subscribe,
2103	/// A PUBLISH_NAMESPACE: the peer announces a namespace it will publish under. Its
2104	/// `publish` prefixes must cover the whole namespace.
2105	PublishNamespace,
2106	/// A SUBSCRIBE_NAMESPACE: the peer discovers only the broadcasts the token allows
2107	/// beneath the requested prefix.
2108	Discover,
2109	/// A PUBLISH: the peer offers a track. Covered by the grant's `publish` prefixes.
2110	Publish,
2111}
2112
2113impl RequestKind {
2114	/// Whether `grant`, issued to the peer that presented the token, covers this request at
2115	/// `path`. A grant names what its holder may do, so a request to read is covered by its
2116	/// `subscribe` prefixes and a request to announce by its `publish` prefixes. An announce
2117	/// routes everything beneath its namespace, which a prefix covering the namespace covers
2118	/// too.
2119	pub(crate) fn covers(self, grant: &Grant, path: &str) -> bool {
2120		match self {
2121			Self::Subscribe => grant.subscribe.matches(path),
2122			Self::Discover => !grant.subscribe.is_empty(),
2123			Self::Publish | Self::PublishNamespace => grant.publish.matches(path),
2124		}
2125	}
2126}
2127
2128/// The verdict on a request-borne token, from [`Link::verify_request`].
2129///
2130/// Holding it keeps the request's grant alive; dropping it tells the acceptor the request
2131/// is over, so the grant lives exactly as long as the request and never outlives it.
2132pub(crate) struct RequestVerdict {
2133	issue: Option<kio::Shared<Issue>>,
2134	// Each request owns one reference, independent of its reader's progress.
2135	_lifetime: Option<std::sync::Arc<RequestLifetime>>,
2136	seen: std::sync::Mutex<u64>,
2137}
2138
2139struct RequestLifetime {
2140	issue: kio::Shared<Issue>,
2141	handle: Link,
2142	token: Bytes,
2143}
2144
2145impl Drop for RequestLifetime {
2146	fn drop(&mut self) {
2147		let mut tokens = self.handle.attached.request_tokens.lock().unwrap();
2148		if tokens.get(&self.token).is_some_and(|token| token.strong_count() == 0) {
2149			tokens.remove(&self.token);
2150		}
2151		drop(tokens);
2152		let mut issue = self.issue.lock();
2153		issue.peer.get_or_insert(Error::Cancel);
2154		if !issue.taken {
2155			issue.hold = None;
2156		}
2157	}
2158}
2159
2160/// Why a request token did not authorize its request: the error whose code the peer is
2161/// sent, and the reason phrase with it, which the acceptor chose when it refused.
2162#[derive(Debug, Clone)]
2163pub(crate) struct Refusal {
2164	pub error: Error,
2165	pub reason: String,
2166}
2167
2168impl Refusal {
2169	fn new(error: Error, reason: &str) -> Self {
2170		Self {
2171			error,
2172			reason: reason.to_string(),
2173		}
2174	}
2175}
2176
2177impl From<Error> for Refusal {
2178	fn from(error: Error) -> Self {
2179		let reason = error.to_string();
2180		Self { error, reason }
2181	}
2182}
2183
2184impl RequestVerdict {
2185	/// Wait for the acceptor's first answer. See [`poll_grant`](Self::poll_grant).
2186	#[cfg(test)]
2187	pub(crate) async fn grant(&self) -> std::result::Result<Grant, Refusal> {
2188		kio::wait(|waiter| self.poll_grant(waiter)).await
2189	}
2190
2191	/// Poll for the acceptor's first answer: the grant it issued, or its refusal, which the
2192	/// caller sends the peer. No consumer is [`Error::Unsupported`]; an unanswered (dropped)
2193	/// request is [`SessionError::Unauthorized`]. Whatever the acceptor did since accepting
2194	/// is folded in, so a grant already updated, revoked or dropped is never admitted as it
2195	/// first stood.
2196	pub(crate) fn poll_grant(&self, waiter: &kio::Waiter) -> Poll<std::result::Result<Grant, Refusal>> {
2197		let Some(issue) = &self.issue else {
2198			return Poll::Ready(Err(Error::Unsupported.into()));
2199		};
2200		let guard = ready_or!(issue.poll(waiter, |issue| {
2201			if issue.latest.is_none() && !issue.done {
2202				Poll::Pending
2203			} else {
2204				Poll::Ready(())
2205			}
2206		}));
2207		*self.seen.lock().unwrap() = guard.revision;
2208		Poll::Ready(match (&guard.latest, guard.done) {
2209			(Some(Reply::Refuse { code, reason }), _) => Err(Refusal::new(Error::Session(code.clone()), reason)),
2210			(Some(Reply::Grant(grant)), false) => Ok(grant.clone()),
2211			_ => Err(Refusal::new(
2212				Error::Session(SessionError::Unauthorized),
2213				"grant dropped",
2214			)),
2215		})
2216	}
2217
2218	/// Each naming request independently observes replacements and revocation.
2219	fn poll_reply(&self, waiter: &kio::Waiter) -> Poll<Option<Reply>> {
2220		let Some(issue) = &self.issue else {
2221			return Poll::Ready(None);
2222		};
2223		let mut seen = self.seen.lock().unwrap();
2224		let guard = ready_or!(issue.poll(waiter, |issue| {
2225			if issue.revision == *seen && !issue.done {
2226				Poll::Pending
2227			} else {
2228				Poll::Ready(())
2229			}
2230		}));
2231		if guard.revision != *seen {
2232			*seen = guard.revision;
2233			return Poll::Ready(guard.latest.clone());
2234		}
2235		Poll::Ready(None)
2236	}
2237}
2238
2239/// A request-borne grant, held for the life of the request it authorized (a SUBSCRIBE or a
2240/// PUBLISH_NAMESPACE). It carries the acceptor's grant and a deadline armed at the grant's
2241/// expiry, and ends the request when the deadline lapses or the acceptor revokes or drops the
2242/// grant. A REQUEST_UPDATE the acceptor accepts [`renew`](Self::renew)s it with a fresh grant
2243/// and expiry; one it refuses is not applied here, and the serve loop ends the request.
2244///
2245/// Clones share the grant: the request's [`until`] watches it end while the request renews it.
2246/// Ending a request grant never touches the session: only that one request ends.
2247#[derive(Clone)]
2248pub(crate) struct RequestGrant(std::sync::Arc<std::sync::Mutex<Held>>);
2249
2250struct Held {
2251	verdict: RequestVerdict,
2252	grant: Grant,
2253	deadline: crate::time::Deadline,
2254	/// The request this grant must keep covering: a replacement that no longer does ends it.
2255	path: crate::Path,
2256	kind: RequestKind,
2257	/// The request's slot, shared with a renewal's verification.
2258	hold: Option<Hold>,
2259	/// The token of the renewal being verified, until the serve loop applies its verdict.
2260	renewing: Option<kio::Shared<Issue>>,
2261	clock: crate::time::Deadlines,
2262	epoch: u64,
2263	/// Why the request ended, once it has. A channel, so every clone waiting on the grant
2264	/// wakes when [`RequestGrant::end`] latches it.
2265	ended: kio::Producer<Option<Refusal>>,
2266}
2267
2268impl Held {
2269	/// See [`RequestGrant::poll_ended`].
2270	fn poll_end(&mut self, waiter: &kio::Waiter) -> Poll<Refusal> {
2271		loop {
2272			if let Some(err) = self.verdict.issue.as_ref().and_then(|issue| issue.read().peer.clone()) {
2273				return Poll::Ready(err.into());
2274			}
2275			// The acceptor granted a renewal the serve loop has yet to apply: it takes over rather
2276			// than the request ending between the two, whether the old grant lapsed or dropped.
2277			// Watched, so a request that abandons the renewal, such as one cancelled while a
2278			// joined FETCH outlives it, falls back to the old grant's end.
2279			let handover = self.renewing.as_ref().is_some_and(|issue| {
2280				issue
2281					.poll(waiter, |issue| match granted(issue) {
2282						true => Poll::Pending,
2283						false => Poll::Ready(()),
2284					})
2285					.is_pending()
2286			});
2287			// A grant the acceptor sent is read before the deadline, so an extension that arrived
2288			// before the old expiry keeps the request even when it is polled only after.
2289			let ended = match self.verdict.poll_reply(waiter) {
2290				Poll::Ready(Some(Reply::Grant(grant))) => {
2291					if !self.kind.covers(&grant, self.path.as_str()) {
2292						return Poll::Ready(Refusal::new(Error::Unauthorized, "request token no longer granted"));
2293					}
2294					self.deadline.set(grant.expires);
2295					self.grant = grant;
2296					self.epoch += 1;
2297					// Re-poll: the new deadline may already have lapsed, or another reply may
2298					// be waiting.
2299					continue;
2300				}
2301				Poll::Ready(None) if handover => None,
2302				Poll::Ready(None) => Some(Refusal::new(
2303					Error::Session(SessionError::Unauthorized),
2304					"grant dropped",
2305				)),
2306				Poll::Ready(Some(Reply::Refuse { code, reason })) => Some(Refusal::new(Error::Session(code), &reason)),
2307				Poll::Pending => None,
2308			};
2309			// Any other end comes after an expiry that already passed, which it reports.
2310			if self.deadline.poll(waiter).is_ready() {
2311				if handover {
2312					return Poll::Pending;
2313				}
2314				return Poll::Ready(Refusal::new(Error::Expired, "request token expired"));
2315			}
2316			return match ended {
2317				Some(refusal) => Poll::Ready(refusal),
2318				None => Poll::Pending,
2319			};
2320		}
2321	}
2322}
2323
2324impl RequestGrant {
2325	/// Hold the acceptor's first answer `res` for the request's life, armed to lapse at its
2326	/// expiry, or the refusal to answer the request with: the acceptor's own, or
2327	/// [`Error::Unauthorized`] for a grant that does not cover it or has already expired.
2328	pub(crate) fn new(
2329		clock: &crate::time::Deadlines,
2330		verdict: RequestVerdict,
2331		res: std::result::Result<Grant, Refusal>,
2332		path: crate::Path,
2333		kind: RequestKind,
2334		hold: Option<Hold>,
2335	) -> std::result::Result<Self, Refusal> {
2336		let grant = res?;
2337		if !live(clock, kind, path.as_str(), &grant) {
2338			return Err(Refusal::new(Error::Unauthorized, "request token not granted"));
2339		}
2340		let mut deadline = crate::time::Deadline::new(clock);
2341		deadline.set(grant.expires);
2342		Ok(Self(std::sync::Arc::new(std::sync::Mutex::new(Held {
2343			verdict,
2344			grant,
2345			deadline,
2346			path,
2347			kind,
2348			hold,
2349			renewing: None,
2350			clock: clock.clone(),
2351			epoch: 1,
2352			ended: kio::Producer::new(None),
2353		}))))
2354	}
2355
2356	fn held(&self) -> std::sync::MutexGuard<'_, Held> {
2357		self.0.lock().unwrap_or_else(std::sync::PoisonError::into_inner)
2358	}
2359
2360	/// The grant in force right now. Observed by the lifecycle tests.
2361	#[cfg(test)]
2362	pub(crate) fn grant(&self) -> Grant {
2363		self.held().grant.clone()
2364	}
2365
2366	/// The request's slot, for re-attaching what it authorized without taking another.
2367	#[cfg(test)]
2368	pub(crate) fn hold(&self) -> Option<Hold> {
2369		self.held().hold.clone()
2370	}
2371
2372	/// Start verifying a renewal's token, holding the request's slot while it runs.
2373	pub(crate) fn verify_renewal(&self, handle: &Link, token: crate::setup::Token) -> RequestVerdict {
2374		let hold = self.held().hold.clone();
2375		self.verify_renewal_holding(handle, token, hold)
2376	}
2377
2378	/// [`Self::verify_renewal`], holding `hold` instead while it runs. Until the serve loop
2379	/// applies a granted renewal, it takes over rather than the request ending between the two.
2380	pub(crate) fn verify_renewal_holding(
2381		&self,
2382		handle: &Link,
2383		token: crate::setup::Token,
2384		hold: Option<Hold>,
2385	) -> RequestVerdict {
2386		let mut held = self.held();
2387		let verdict = handle.verify_request(token, hold);
2388		held.renewing = verdict.issue.clone();
2389		verdict
2390	}
2391
2392	/// Apply a renewal's verdict, or return the refusal that ends the request.
2393	///
2394	/// A live grant that still covers the request replaces this one: the new verdict is
2395	/// adopted (dropping the old, which ends the old token) and the deadline re-armed at the
2396	/// new expiry. A refusal, or a grant that no longer covers the request or has already
2397	/// expired, changes nothing here; the caller ends only that request.
2398	pub(crate) fn renew(
2399		&self,
2400		verdict: RequestVerdict,
2401		res: std::result::Result<Grant, Refusal>,
2402	) -> std::result::Result<(), Refusal> {
2403		let mut held = self.held();
2404		held.renewing = None;
2405		let grant = res?;
2406		if !live(&held.clock, held.kind, held.path.as_str(), &grant) {
2407			return Err(Refusal::new(Error::Unauthorized, "renewal not granted"));
2408		}
2409		held.verdict = verdict;
2410		held.deadline.set(grant.expires);
2411		held.grant = grant;
2412		held.epoch += 1;
2413		Ok(())
2414	}
2415
2416	/// End the grant with `refusal`, waking every clone still watching it, unless it already
2417	/// ended. A refused renewal ends the request without the grant ending itself, so the serve
2418	/// loop calls this to end anything else serving under the grant, such as a joining FETCH
2419	/// that outlives its subscription.
2420	pub(crate) fn end(&self, refusal: Refusal) {
2421		latch(&self.held().ended, refusal);
2422	}
2423
2424	/// Resolve with the refusal that ends the request: the deadline lapsing
2425	/// ([`Error::Expired`]), the acceptor revoking or dropping the grant (its code and
2426	/// reason), or an acceptor-side update that no longer covers the request
2427	/// ([`Error::Unauthorized`]). A covering update, such as a lowered expiry, is folded in and
2428	/// polling continues. Never resolves while the grant still stands.
2429	pub(crate) fn poll_ended(&self, waiter: &kio::Waiter) -> Poll<Refusal> {
2430		let held = &mut *self.held();
2431		// Latched, as each acceptor reply is read once: every clone watching the grant sees
2432		// the same end, whichever polled first.
2433		let latched = match held.ended.poll_ref(waiter, |ended| match &**ended {
2434			Some(ended) => Poll::Ready(ended.clone()),
2435			None => Poll::Pending,
2436		}) {
2437			Poll::Ready(Ok(ended)) => Some(ended),
2438			// Never closed: the grant owns its only producer.
2439			Poll::Ready(Err(_)) | Poll::Pending => None,
2440		};
2441		if let Some(ended) = latched {
2442			return Poll::Ready(ended);
2443		}
2444		let ended = std::task::ready!(held.poll_end(waiter));
2445		latch(&held.ended, ended.clone());
2446		Poll::Ready(ended)
2447	}
2448}
2449
2450/// Record `refusal` as why a request grant ended, unless an earlier end already is.
2451fn latch(ended: &kio::Producer<Option<Refusal>>, refusal: Refusal) {
2452	if let Ok(mut ended) = ended.write()
2453		&& ended.is_none()
2454	{
2455		*ended = Some(refusal);
2456	}
2457}
2458
2459/// Whether `grant` covers a `kind` request at `path` and has not already expired: admitting
2460/// an expired one until its deadline fires would let others act on it meanwhile.
2461fn live(clock: &crate::time::Deadlines, kind: RequestKind, path: &str, grant: &Grant) -> bool {
2462	kind.covers(grant, path) && grant.expires.is_none_or(|expires| expires > clock.now())
2463}
2464
2465/// Whether the acceptor granted the token behind `issue` and still holds the grant, for a
2466/// request still waiting to apply it.
2467fn granted(issue: &Issue) -> bool {
2468	issue.peer.is_none() && !issue.done && matches!(issue.latest, Some(Reply::Grant(_)))
2469}
2470
2471/// A grant issued to one of the peer's tokens, which the session enforces. Dropping it
2472/// ends the grant: an AUTH token's leaves the scope, and a request's token ends the request.
2473pub struct Issued {
2474	issue: kio::Shared<Issue>,
2475}
2476
2477impl Issued {
2478	/// Replace the grant, such as with a lowered expiry. A request's token whose new grant
2479	/// no longer covers the request ends it.
2480	pub fn update(&self, grant: Grant) {
2481		let mut issue = self.issue.lock();
2482		if !issue.done {
2483			issue.reply(Reply::Grant(grant));
2484		}
2485	}
2486
2487	/// Revoke the grant with a session error code and a reason for the peer.
2488	pub fn revoke(self, code: SessionError, reason: impl Into<String>) {
2489		refuse(&self.issue, code, reason.into());
2490	}
2491
2492	/// Wait for the peer to withdraw the token ([`Error::Cancel`]), the request it rode on
2493	/// to end ([`Error::Cancel`]), or its stream or the session to end.
2494	///
2495	/// The future holds the issue, not the grant, so dropping the grant still ends it.
2496	#[cfg(feature = "async")]
2497	pub fn closed(&self) -> impl Future<Output = Error> + Send + 'static {
2498		let issue = self.issue.clone();
2499		kio::wait(move |waiter| poll_closed(&issue, waiter))
2500	}
2501}
2502
2503impl Drop for Issued {
2504	fn drop(&mut self) {
2505		self.issue.lock().finish();
2506	}
2507}
2508
2509/// Resolve with why the peer ended the token behind `issue`.
2510fn poll_closed(issue: &kio::Shared<Issue>, waiter: &kio::Waiter) -> Poll<Error> {
2511	let issue = ready_or!(issue.poll(waiter, |issue| {
2512		if issue.peer.is_some() {
2513			Poll::Ready(())
2514		} else {
2515			Poll::Pending
2516		}
2517	}));
2518	Poll::Ready(issue.peer.clone().expect("checked above"))
2519}
2520
2521/// Which way media flows, from this side's view.
2522#[derive(Clone, Copy)]
2523pub(crate) enum Direction {
2524	/// This side sends to the peer: our grant's `publish`, and the limit's `subscribe`.
2525	Publish,
2526	/// The peer sends to this side: our grant's `subscribe`, and the limit's `publish`.
2527	Subscribe,
2528}
2529
2530/// Watches whether the session still allows one path, for a request that must end
2531/// once it does not.
2532///
2533/// Create it at the request's first check and hold it to the end, so a change
2534/// landing in between is never missed. Cheap to poll on every wakeup: the path is
2535/// only re-matched when the union or the limit changes.
2536pub(crate) struct Gate {
2537	handle: Link,
2538	path: crate::Path,
2539	direction: Direction,
2540	epoch: u64,
2541	part: Part,
2542	token: Option<RequestGrant>,
2543	discovery: bool,
2544	/// Whether the scope allowed the path at the last permit.
2545	within_limit: bool,
2546	admitted: bool,
2547	waiting: Option<Waiting>,
2548}
2549
2550/// Log the whole wait once, including when its request is cancelled.
2551struct Waiting {
2552	path: crate::Path,
2553	started: Instant,
2554}
2555
2556impl Drop for Waiting {
2557	fn drop(&mut self) {
2558		tracing::debug!(path = %self.path, waited = ?self.started.elapsed(), "request waited for authorization");
2559	}
2560}
2561
2562/// Which part of a [`Permit`] a [`Gate`] watches.
2563enum Part {
2564	/// The peer's grant and the scope both.
2565	Both,
2566	/// The peer's grant alone: a token the peer presented stands in for the scope.
2567	Granted,
2568	/// The peer's grant, and the scope once the announce that stood in for it closes.
2569	Announced(kio::Consumer<()>),
2570}
2571
2572impl Gate {
2573	pub(crate) fn new(handle: Link, path: crate::Path, direction: Direction) -> Self {
2574		let within_limit = handle.within_limit(direction, path.as_str());
2575		Self {
2576			handle,
2577			path,
2578			direction,
2579			epoch: 0,
2580			part: Part::Both,
2581			token: None,
2582			discovery: false,
2583			within_limit,
2584			admitted: false,
2585			waiting: None,
2586		}
2587	}
2588
2589	/// Hold the request to the peer's grant alone, once its own token authorized it.
2590	pub(crate) fn name(&mut self) {
2591		self.part = Part::Granted;
2592	}
2593
2594	/// Filter a discovery request by the token rather than requiring its whole prefix.
2595	pub(crate) fn discovery(mut self) -> Self {
2596		self.discovery = true;
2597		self
2598	}
2599
2600	/// Admit the verifier's answer under the request's path and role.
2601	pub(crate) fn admit(
2602		&mut self,
2603		clock: &crate::time::Deadlines,
2604		answer: (RequestVerdict, std::result::Result<Grant, Refusal>),
2605	) -> std::result::Result<(), Refusal> {
2606		let (verdict, answer) = answer;
2607		if let Some(token) = &self.token {
2608			return token.renew(verdict, answer);
2609		}
2610		let token = RequestGrant::new(clock, verdict, answer, self.path.clone(), self.kind(), None)?;
2611		self.bind(token);
2612		Ok(())
2613	}
2614
2615	/// The kind of request this gate admits, for its token's grant to cover. A gate on what
2616	/// the peer publishes to us verifies only a PUBLISH_NAMESPACE's token; a PUBLISH's goes
2617	/// straight to [`Link::verify_request`].
2618	fn kind(&self) -> RequestKind {
2619		match (self.discovery, self.direction) {
2620			(true, _) => RequestKind::Discover,
2621			(false, Direction::Publish) => RequestKind::Subscribe,
2622			(false, Direction::Subscribe) => RequestKind::PublishNamespace,
2623		}
2624	}
2625
2626	/// Replace the session's authority with this request's token alone.
2627	pub(crate) fn bind(&mut self, token: RequestGrant) {
2628		self.token = Some(token);
2629		self.part = Part::Both;
2630		self.epoch = 0;
2631	}
2632
2633	/// Hold this request's current token across its serving future, including renewals.
2634	pub(crate) fn token_guard(&self) -> Option<RequestGrant> {
2635		self.token.clone()
2636	}
2637
2638	/// Start another request under this session gate, without inheriting a request token.
2639	pub(crate) fn unnamed(&self) -> Self {
2640		let mut gate = Self::new(self.handle.clone(), self.path.clone(), self.direction);
2641		gate.part = match &self.part {
2642			Part::Both => Part::Both,
2643			Part::Granted => Part::Granted,
2644			Part::Announced(live) => Part::Announced(live.clone()),
2645		};
2646		gate
2647	}
2648
2649	/// The token ended, independently of whether its discovery prefix matches a grant.
2650	pub(crate) fn poll_token_ended(&self, waiter: &kio::Waiter) -> Poll<Refusal> {
2651		match &self.token {
2652			Some(token) => token.poll_ended(waiter),
2653			None => Poll::Pending,
2654		}
2655	}
2656
2657	/// A gate for a request under a namespace the peer announced, while `live` stays open:
2658	/// the announce stands in for the scope, as its own token may have authorized it.
2659	pub(crate) fn announced(handle: Link, path: crate::Path, direction: Direction, live: kio::Consumer<()>) -> Self {
2660		Self {
2661			part: Part::Announced(live),
2662			..Self::new(handle, path, direction)
2663		}
2664	}
2665
2666	/// Whether the session allows the path right now.
2667	pub(crate) fn allows(&self) -> bool {
2668		let path = self.path.as_str();
2669		self.handle.within_grant(self.direction, path)
2670			&& match &self.part {
2671				Part::Both => match &self.token {
2672					Some(token) => {
2673						let token = token.held();
2674						match self.direction {
2675							Direction::Publish => token.grant.subscribe.matches(path),
2676							Direction::Subscribe => token.grant.publish.matches(path),
2677						}
2678					}
2679					None => self.within_limit,
2680				},
2681				Part::Granted => true,
2682				Part::Announced(live) => self.within_limit || !live.is_closed(),
2683			}
2684	}
2685
2686	/// Whether the peer's request token must be verified separately from session scope.
2687	pub(crate) fn token_decides(&self) -> bool {
2688		self.handle.token_decides(self.direction)
2689	}
2690
2691	/// Verify an incoming request's token against the local acceptor, holding `hold` while it
2692	/// runs. Once a token bound the gate, another is verified as that grant's renewal, so a
2693	/// granted replacement takes over rather than the old grant ending before it is admitted.
2694	pub(crate) fn verify(&self, token: crate::setup::Token, hold: Option<Hold>) -> RequestVerdict {
2695		match &self.token {
2696			Some(grant) => grant.verify_renewal_holding(&self.handle, token, hold),
2697			None => self.handle.verify_request(token, hold),
2698		}
2699	}
2700
2701	/// What the session allows in this gate's direction, once it may have changed since `epoch`.
2702	pub(crate) fn poll_permit(&self, epoch: &mut u64, waiter: &kio::Waiter) -> Poll<Permit> {
2703		let Some(token) = &self.token else {
2704			return self.handle.poll_permit(self.direction, epoch, waiter);
2705		};
2706		let ended = token.poll_ended(waiter).is_ready();
2707		let token = token.held();
2708		// Read the session's permit with the epoch it stands at, under one lock, then poll again
2709		// to register the wakeup even when only the token changed this time. A session change
2710		// between the two is read too, so no epoch is counted without its permit.
2711		let mut version = u64::MAX;
2712		let mut permit = None;
2713		while let Poll::Ready(next) = self.handle.poll_permit(self.direction, &mut version, waiter) {
2714			permit = Some(next);
2715		}
2716		let mut permit = permit.expect("a session epoch is never u64::MAX");
2717		permit.limit = Some(if ended {
2718			Prefixes::new()
2719		} else {
2720			match self.direction {
2721				Direction::Publish => token.grant.subscribe.clone(),
2722				Direction::Subscribe => token.grant.publish.clone(),
2723			}
2724		});
2725		// The token ending empties the limit, so it counts as a change too.
2726		version += token.epoch + u64::from(ended);
2727		if version == *epoch {
2728			return Poll::Pending;
2729		}
2730		*epoch = version;
2731		Poll::Ready(permit)
2732	}
2733
2734	/// Preserve setup ordering before the first discovery snapshot.
2735	pub(crate) fn poll_setup_answered(&self, waiter: &kio::Waiter) -> Poll<()> {
2736		self.handle.poll_setup_answered(waiter)
2737	}
2738
2739	/// Settle tokens that might admit this request before its first wire operation.
2740	pub(crate) fn poll_ready(&mut self, waiter: &kio::Waiter) -> Poll<()> {
2741		if self.admitted {
2742			return Poll::Ready(());
2743		}
2744		// A withdrawn route ends the wait too: the request is then judged against the union
2745		// as it stands, so routing can recover instead of parking on a token.
2746		let withdrawn = matches!(&self.part, Part::Announced(live) if live.poll_closed(waiter).is_ready());
2747		if !withdrawn
2748			&& self
2749				.handle
2750				.poll_presented(self.direction, self.path.as_str(), waiter)
2751				.is_pending()
2752		{
2753			self.waiting.get_or_insert_with(|| Waiting {
2754				path: self.path.clone(),
2755				started: Instant::now(),
2756			});
2757			return Poll::Pending;
2758		}
2759		drop(self.waiting.take());
2760		self.admitted = true;
2761		Poll::Ready(())
2762	}
2763
2764	/// Resolve with why an admitted request must stop: its token's refusal once it ended, or
2765	/// [`Error::Unauthorized`] once the session no longer allows the path.
2766	pub(crate) fn poll_refused(&mut self, waiter: &kio::Waiter) -> Poll<Error> {
2767		// Ahead of the gate it also closes, so a lapsed token is refused as expired.
2768		if let Poll::Ready(refusal) = self.poll_token_ended(waiter) {
2769			return Poll::Ready(refusal.error);
2770		}
2771		self.poll_denied(waiter).map(|()| Error::Unauthorized)
2772	}
2773
2774	/// Resolve once the session no longer allows the path. A union that is still
2775	/// `None` (no answer yet, or a version without AUTH) and a session never limited
2776	/// allow everything.
2777	pub(crate) fn poll_denied(&mut self, waiter: &kio::Waiter) -> Poll<()> {
2778		if self.poll_token_ended(waiter).is_ready() {
2779			return Poll::Ready(());
2780		}
2781		let mut epoch = self.epoch;
2782		while let Poll::Ready(permit) = self.poll_permit(&mut epoch, waiter) {
2783			self.epoch = epoch;
2784			let path = self.path.as_str();
2785			self.within_limit = permit.within_limit(path);
2786			let allowed = match self.part {
2787				Part::Both => permit.matches(path),
2788				Part::Granted | Part::Announced(_) => permit.granted(path),
2789			};
2790			if !allowed {
2791				return Poll::Ready(());
2792			}
2793		}
2794		match &self.part {
2795			Part::Announced(live) if !self.within_limit => live.poll_closed(waiter),
2796			_ => Poll::Pending,
2797		}
2798	}
2799}
2800
2801/// The default acceptor's answer to the peer's connection credential: the grant
2802/// the session's origin handles allow, within the limit as it changes.
2803pub(crate) struct DefaultGrant {
2804	handle: Link,
2805	base: Grant,
2806	epoch: u64,
2807	limit: Option<Grant>,
2808	/// The grant last handed out, so an unrelated wakeup sends nothing.
2809	sent: Option<Grant>,
2810}
2811
2812impl DefaultGrant {
2813	pub(crate) fn new(handle: Link, base: Grant) -> Self {
2814		let limit = handle.state().read().limit.clone();
2815		Self {
2816			handle,
2817			base,
2818			epoch: 0,
2819			limit,
2820			sent: None,
2821		}
2822	}
2823
2824	/// The grant to send next: the first, then each one a new limit changes.
2825	pub(crate) fn poll(&mut self, waiter: &kio::Waiter) -> Poll<Grant> {
2826		while let Poll::Ready(limit) = self.handle.poll_limit(&mut self.epoch, waiter) {
2827			self.limit = limit;
2828		}
2829		let grant = match &self.limit {
2830			Some(limit) => self.base.intersect(limit),
2831			None => self.base.clone(),
2832		};
2833		if self.sent.as_ref() == Some(&grant) {
2834			return Poll::Pending;
2835		}
2836		self.sent = Some(grant.clone());
2837		Poll::Ready(grant)
2838	}
2839}
2840
2841/// The close reason naming a broadcast published outside the grant. [`Error`] carries
2842/// no payload, so the path travels here, in the session's own terms.
2843pub(crate) fn unauthorized_reason(path: &crate::Path) -> String {
2844	format!("unauthorized: {path}")
2845}
2846
2847/// Finds a broadcast this side publishes that its grant never covered, so the session
2848/// can fail loudly instead of waiting for a subscription that never comes.
2849///
2850/// Waits until the tokens the session presented at setup are answered, then checks
2851/// each broadcast when it is first announced. A grant that later shrinks withdraws what
2852/// it no longer covers without aborting: the union is processed before new
2853/// announcements, so a revocation is never mistaken for a new unauthorized
2854/// publication. Only the dialing side enforces: a server's publish origin is everything
2855/// the peer may read, not what it intends to push.
2856#[derive(Default)]
2857pub(crate) struct Enforce {
2858	epoch: u64,
2859	permit: Option<Prefixes>,
2860	/// Every broadcast admitted so far, still announced.
2861	live: std::collections::HashSet<crate::Path>,
2862	setup: bool,
2863	/// Broadcasts outside the union, still announced, waiting on tokens that might cover
2864	/// them, in announcement order.
2865	pending: Vec<Gate>,
2866}
2867
2868impl Enforce {
2869	/// Resolve with the first broadcast announced outside the union, or `None` once the
2870	/// origin ends.
2871	pub(crate) fn poll(
2872		&mut self,
2873		handle: &Link,
2874		announced: &mut crate::origin::Routes,
2875		waiter: &kio::Waiter,
2876	) -> Poll<Option<crate::Path>> {
2877		if !self.setup {
2878			ready_or!(handle.poll_setup_answered(waiter));
2879			self.setup = true;
2880		}
2881		while let Poll::Ready(union) = handle.poll_union(&mut self.epoch, waiter) {
2882			self.permit = union.map(|grant| grant.publish);
2883		}
2884		// No grant yet (the peer never answered with one): nothing to check against.
2885		if self.permit.is_none() {
2886			return Poll::Pending;
2887		}
2888
2889		// Withdrawals queued behind a wait apply before it is judged, so a broadcast that is
2890		// no longer published never closes the session.
2891		while let Poll::Ready(event) = announced.poll_next(waiter) {
2892			let Some(event) = event else {
2893				return Poll::Ready(None);
2894			};
2895			match event {
2896				crate::origin::RouteEvent {
2897					kind: crate::origin::RouteKind::Start | crate::origin::RouteKind::Update,
2898					announce: update,
2899				} if !self.live.contains(&update.prefix) => {
2900					if self.pending.iter().any(|gate| gate.path == update.prefix) {
2901						continue;
2902					}
2903					let mut gate = Gate::new(handle.clone(), update.prefix, Direction::Publish);
2904					if gate.poll_ready(waiter).is_pending() {
2905						self.pending.push(gate);
2906						continue;
2907					}
2908					if !handle.within_grant(Direction::Publish, gate.path.as_str()) {
2909						return Poll::Ready(Some(gate.path));
2910					}
2911					self.live.insert(gate.path);
2912				}
2913				crate::origin::RouteEvent {
2914					kind: crate::origin::RouteKind::End | crate::origin::RouteKind::Offline,
2915					announce: update,
2916				} => {
2917					self.live.remove(&update.prefix);
2918					self.pending.retain(|gate| gate.path != update.prefix);
2919				}
2920				_ => {}
2921			}
2922		}
2923
2924		while let Some(index) = self
2925			.pending
2926			.iter_mut()
2927			.position(|gate| gate.poll_ready(waiter).is_ready())
2928		{
2929			let gate = self.pending.remove(index);
2930			if !handle.within_grant(Direction::Publish, gate.path.as_str()) {
2931				return Poll::Ready(Some(gate.path));
2932			}
2933			self.live.insert(gate.path);
2934		}
2935		Poll::Pending
2936	}
2937}
2938
2939#[cfg(test)]
2940mod tests {
2941	use super::*;
2942
2943	#[kio::test]
2944	async fn a_request_waits_for_an_unanswered_token() {
2945		let handle = Link::new(true);
2946		let setup = handle.present(Bytes::new(), true).unwrap();
2947		handle.grant(setup.presented.id, Grant::default());
2948		let token = handle.present(Bytes::from_static(b"new"), false).unwrap();
2949		let mut gate = Gate::new(handle.clone(), crate::Path::from_static("room"), Direction::Subscribe);
2950		let waiter = kio::Waiter::noop();
2951		assert!(
2952			gate.poll_ready(&waiter).is_pending(),
2953			"request refused before token answered"
2954		);
2955		handle.grant(token.presented.id, Grant::all());
2956		assert!(gate.poll_ready(&waiter).is_ready());
2957		assert!(gate.poll_denied(&waiter).is_pending());
2958	}
2959
2960	/// A token waiting out a transient refusal is unanswered, so a publication it might
2961	/// cover waits for the retry instead of being judged unauthorized.
2962	#[test]
2963	fn a_retrying_token_holds_a_publication() {
2964		let handle = Link::new(true);
2965		let _token = handle.present(Bytes::from_static(b"jwt"), false).unwrap();
2966		let id = opened(&handle);
2967		handle.refused(id, true);
2968		let busy = Error::Session(SessionError::TooManyRequests);
2969		assert_eq!(handle.retry(id, &busy), Some(RETRY_INITIAL));
2970
2971		let mut gate = Gate::new(handle.clone(), crate::Path::from_static("room"), Direction::Publish);
2972		let waiter = kio::Waiter::noop();
2973		assert!(
2974			gate.poll_ready(&waiter).is_pending(),
2975			"judged before the retry answered"
2976		);
2977		handle.reopen(id).unwrap();
2978		handle.grant(id, Grant::all());
2979		assert!(gate.poll_ready(&waiter).is_ready());
2980		assert!(handle.within_grant(Direction::Publish, "room"));
2981	}
2982
2983	/// A route withdrawn while its request waits on a token ends the wait, and the request
2984	/// is refused against the union as it stands.
2985	#[test]
2986	fn a_withdrawn_route_ends_the_wait() {
2987		let handle = Link::new(true);
2988		let setup = handle.present(Bytes::new(), true).unwrap();
2989		handle.grant(setup.presented.id, Grant::default());
2990		let _unanswered = handle.present(Bytes::from_static(b"new"), false).unwrap();
2991		let route = kio::Producer::<()>::default();
2992		let mut gate = Gate::announced(
2993			handle,
2994			crate::Path::from_static("room"),
2995			Direction::Subscribe,
2996			route.consume(),
2997		);
2998		let waiter = kio::Waiter::noop();
2999		assert!(gate.poll_ready(&waiter).is_pending(), "waits while the route stands");
3000		drop(route);
3001		assert!(gate.poll_ready(&waiter).is_ready(), "a withdrawn route kept the wait");
3002		assert!(gate.poll_denied(&waiter).is_ready());
3003	}
3004
3005	#[test]
3006	fn an_empty_token_never_holds_a_request() {
3007		let handle = Link::new(true);
3008		let _setup = handle.present(Bytes::new(), true).unwrap();
3009		let mut gate = Gate::new(handle, crate::Path::from_static("room"), Direction::Subscribe);
3010		assert!(gate.poll_ready(&kio::Waiter::noop()).is_ready());
3011	}
3012
3013	#[test]
3014	fn a_covered_request_never_waits_for_an_unanswered_token() {
3015		let handle = Link::new(true);
3016		let first = handle.present(Bytes::from_static(b"first"), false).unwrap();
3017		handle.grant(first.presented.id, Grant::all());
3018		let _unanswered = handle.present(Bytes::from_static(b"renewal"), false).unwrap();
3019		let mut gate = Gate::new(handle, crate::Path::from_static("room"), Direction::Subscribe);
3020		assert!(gate.poll_ready(&kio::Waiter::noop()).is_ready());
3021	}
3022
3023	#[test]
3024	fn an_auth_ok_is_queued_after_its_scope_widens() {
3025		let handle = Link::new(true);
3026		handle.handle().authorize(&Grant::default());
3027		let serving = Serving::new(handle.clone());
3028		let request = Request::new(Bytes::from_static(b"token"), serving.issue.clone());
3029		let _issued = request.accept(Grant::all());
3030		let issue = serving.issue.read();
3031		assert!(matches!(issue.outbox.front(), Some(Reply::Grant(_))));
3032		assert!(handle.within_limit(Direction::Subscribe, "room"));
3033	}
3034
3035	/// A grant the driver refuses to send, as one too large to encode, leaves the scope with
3036	/// the AUTH_ERROR that replaces it.
3037	#[test]
3038	fn a_refused_grant_leaves_the_scope() {
3039		let handle = Link::new(true);
3040		handle.handle().authorize(&Grant::default());
3041		let serving = Serving::new(handle.clone());
3042		let request = Request::new(Bytes::from_static(b"token"), serving.issue.clone());
3043		let issued = request.accept(grant(&["room"], &[]));
3044		assert!(handle.allows(Direction::Subscribe, "room"));
3045		serving.issue.lock().refused();
3046		assert!(
3047			!handle.allows(Direction::Subscribe, "room"),
3048			"the refused grant still admits"
3049		);
3050		issued.update(grant(&["room"], &[]));
3051		assert!(
3052			!handle.allows(Direction::Subscribe, "room"),
3053			"an update revived the refused grant"
3054		);
3055	}
3056
3057	/// Grants issued while the peer withholds the stream's credit replace the one still
3058	/// queued, and a revocation replaces it too.
3059	#[test]
3060	fn a_blocked_stream_queues_one_grant() {
3061		let handle = Link::new(true);
3062		let serving = Serving::new(handle.clone());
3063		let request = Request::new(Bytes::from_static(b"token"), serving.issue.clone());
3064		let issued = request.accept(grant(&["0"], &[]));
3065		for i in 1..100 {
3066			issued.update(grant(&[&i.to_string()], &[]));
3067		}
3068		{
3069			let issue = serving.issue.read();
3070			assert_eq!(issue.outbox.len(), 1, "grants piled up");
3071			assert!(matches!(issue.outbox.front(), Some(Reply::Grant(grant)) if grant.publish == prefixes(&["99"])));
3072		}
3073		issued.revoke(SessionError::Unauthorized, "revoked");
3074		let issue = serving.issue.read();
3075		assert!(matches!(
3076			issue.outbox.iter().collect::<Vec<_>>()[..],
3077			[Reply::Refuse { .. }]
3078		));
3079	}
3080
3081	/// Handing the queue to a new acceptor refuses the tokens still queued without holding
3082	/// the handle's lock, which refusing an AUTH token takes.
3083	#[test]
3084	fn a_new_acceptor_refuses_the_queue_without_deadlock() {
3085		let handle = Link::new(true);
3086		let _requests = handle.handle().requests();
3087		let serving = Serving::new(handle.clone());
3088		handle
3089			.acceptor()
3090			.unwrap()
3091			.push(Request::new(Bytes::from_static(b"token"), serving.issue.clone()));
3092		let _next = handle.handle().requests();
3093		assert!(matches!(
3094			serving.issue.read().outbox.front(),
3095			Some(Reply::Refuse { .. })
3096		));
3097	}
3098
3099	/// A queued request token keeps its request's slot, so the peer's request credit bounds
3100	/// how many wait; answering it gives the slot back.
3101	#[test]
3102	fn a_queued_request_token_holds_its_slot() {
3103		let handle = Link::new(true);
3104		let mut requests = handle.handle().requests();
3105		let slot: Hold = std::sync::Arc::new(());
3106		let token = crate::setup::Token {
3107			kind: crate::setup::Token::OUT_OF_BAND,
3108			value: b"jwt".to_vec(),
3109		};
3110		let _verdict = handle.verify_request(token, Some(slot.clone()));
3111		assert_eq!(
3112			std::sync::Arc::strong_count(&slot),
3113			2,
3114			"queued, the token holds the slot"
3115		);
3116		let Poll::Ready(Some(request)) = requests.poll_next(&kio::Waiter::noop()) else {
3117			panic!("request token missing")
3118		};
3119		assert_eq!(
3120			std::sync::Arc::strong_count(&slot),
3121			2,
3122			"taken, the token still holds the slot"
3123		);
3124		let _issued = request.accept(Grant::all());
3125		assert_eq!(std::sync::Arc::strong_count(&slot), 1, "answered, the slot is released");
3126	}
3127
3128	/// Withdrawn tokens leave the queue as it grows, so a peer that keeps presenting and
3129	/// withdrawing cannot grow it past what its credit holds open.
3130	#[test]
3131	fn withdrawn_tokens_leave_the_queue() {
3132		let handle = Link::new(true);
3133		let mut requests = handle.handle().requests();
3134		let queue = handle.acceptor().unwrap();
3135		queue.push(Request::new(Bytes::from_static(b"live"), Default::default()));
3136		let withdrawn = kio::Shared::<Issue>::default();
3137		withdrawn.lock().peer = Some(Error::Cancel);
3138		for _ in 0..1000 {
3139			queue.push(Request::new(Bytes::from_static(b"withdrawn"), withdrawn.clone()));
3140			assert!(queue.state.read().requests.len() <= 3, "withdrawn tokens piled up");
3141		}
3142		let Poll::Ready(Some(request)) = requests.poll_next(&kio::Waiter::noop()) else {
3143			panic!("live request missing")
3144		};
3145		assert_eq!(request.token().as_ref(), b"live");
3146		assert!(requests.poll_next(&kio::Waiter::noop()).is_pending());
3147	}
3148
3149	fn prefixes(texts: &[&str]) -> Prefixes {
3150		texts
3151			.iter()
3152			.map(|text| crate::Prefix::try_from(*text).unwrap())
3153			.collect()
3154	}
3155
3156	fn grant(publish: &[&str], subscribe: &[&str]) -> Grant {
3157		Grant {
3158			publish: prefixes(publish),
3159			subscribe: prefixes(subscribe),
3160			expires: None,
3161		}
3162	}
3163
3164	/// What the peer granted confines the prefixes asked of it, whatever the limit is.
3165	#[cfg(feature = "async")]
3166	#[test]
3167	fn the_granted_regions_follow_the_grant_alone() {
3168		let permit = |granted: Option<&[&str]>, limit: Option<&[&str]>| Permit {
3169			granted: granted.map(prefixes),
3170			limit: limit.map(prefixes),
3171		};
3172		let path = crate::Path::from_static;
3173		assert_eq!(permit(None, None).granted_regions(), None);
3174		assert_eq!(permit(None, Some(&["a/b"])).granted_regions(), None);
3175		assert_eq!(
3176			permit(Some(&[""]), Some(&["a"])).granted_regions(),
3177			None,
3178			"a root grant"
3179		);
3180		assert_eq!(permit(Some(&["a"]), None).granted_regions(), Some(vec![path("a")]));
3181		assert_eq!(
3182			permit(Some(&["a", "b"]), Some(&["c"])).granted_regions(),
3183			Some(vec![path("a"), path("b")])
3184		);
3185	}
3186
3187	/// What a publisher shows its peer lies within the regions of the grant and the limit
3188	/// together, the deeper of any two nested.
3189	#[cfg(feature = "async")]
3190	#[test]
3191	fn the_regions_follow_the_grant_and_the_limit() {
3192		let permit = |granted: Option<&[&str]>, limit: Option<&[&str]>| Permit {
3193			granted: granted.map(prefixes),
3194			limit: limit.map(prefixes),
3195		};
3196		let path = crate::Path::from_static;
3197		assert_eq!(permit(None, None).regions(), None);
3198		assert_eq!(permit(None, Some(&["a/b"])).regions(), Some(vec![path("a/b")]));
3199		assert_eq!(permit(Some(&[""]), Some(&["a"])).regions(), Some(vec![path("a")]));
3200		assert_eq!(
3201			permit(Some(&["a", "c/d"]), Some(&["a/b", "c", "e"])).regions(),
3202			Some(vec![path("a/b"), path("c/d")])
3203		);
3204		assert_eq!(permit(Some(&[""]), Some(&[""])).regions(), None, "neither confines");
3205		assert_eq!(
3206			permit(Some(&["a"]), Some(&["b"])).regions(),
3207			Some(vec![]),
3208			"nothing in both"
3209		);
3210	}
3211
3212	/// A permit allows within a scope what the scope, the grant, and the limit all allow:
3213	/// the deepest of any nested prefixes.
3214	#[test]
3215	fn a_permit_allows_what_all_three_allow() {
3216		let permit = |granted: Option<&[&str]>, limit: Option<&[&str]>| Permit {
3217			granted: granted.map(prefixes),
3218			limit: limit.map(prefixes),
3219		};
3220		let within = |permit: Permit, scope: &[&str]| permit.within(prefixes(scope));
3221		assert_eq!(within(permit(Some(&["a/b"]), None), &[""]), prefixes(&["a/b"]));
3222		assert_eq!(within(permit(None, Some(&["a"])), &["a/b", "c"]), prefixes(&["a/b"]));
3223		assert_eq!(
3224			within(permit(Some(&["a"]), Some(&["a/b/c"])), &["a/b"]),
3225			prefixes(&["a/b/c"])
3226		);
3227		assert!(within(permit(Some(&["a/x"]), Some(&["a/y"])), &["a"]).is_empty());
3228		assert_eq!(within(permit(None, None), &["a"]), prefixes(&["a"]));
3229	}
3230
3231	/// A limit replaces the last one, narrower or wider, and applies to a version
3232	/// without AUTH too.
3233	#[test]
3234	fn a_limit_replaces_the_last() {
3235		let handle = Link::new(false);
3236		assert!(handle.allows(Direction::Publish, "room/alice/audio"));
3237
3238		handle.handle().authorize(&grant(&["room/bob"], &["room/alice"]));
3239		// What we send is what the peer may subscribe to, and the other way around.
3240		assert!(handle.allows(Direction::Publish, "room/alice/audio"));
3241		assert!(!handle.allows(Direction::Publish, "room/bob/cam"));
3242		assert!(handle.allows(Direction::Subscribe, "room/bob/cam"));
3243		assert!(!handle.allows(Direction::Subscribe, "room/alice/audio"));
3244
3245		handle.handle().authorize(&grant(&[""], &["room/alice/video"]));
3246		assert!(!handle.allows(Direction::Publish, "room/alice/audio"));
3247		assert!(handle.allows(Direction::Publish, "room/alice/video"));
3248		assert!(handle.allows(Direction::Subscribe, "other"));
3249
3250		handle.handle().authorize(&Grant::all());
3251		assert!(handle.allows(Direction::Publish, "room/alice/audio"));
3252		assert!(handle.allows(Direction::Subscribe, "other"));
3253	}
3254
3255	/// A session admits the whole tree while no scope bounds the peer, or one covers
3256	/// every path in both directions, and not once either leaves a path out.
3257	#[test]
3258	fn a_scope_admits_whole_only_when_it_leaves_nothing_out() {
3259		let handle = Link::new(false);
3260		assert!(handle.admits_whole());
3261
3262		handle.handle().authorize(&grant(&["tenant-a"], &["tenant-a"]));
3263		assert!(!handle.admits_whole());
3264		handle.handle().authorize(&grant(&[""], &["tenant-a"]));
3265		assert!(!handle.admits_whole());
3266		handle.handle().authorize(&grant(&["tenant-a"], &[""]));
3267		assert!(!handle.admits_whole());
3268		handle.handle().authorize(&Grant::default());
3269		assert!(!handle.admits_whole());
3270
3271		handle.handle().authorize(&grant(&[""], &[""]));
3272		assert!(handle.admits_whole());
3273	}
3274
3275	/// Our own grant does not decide what the peer may offer us, only the limit does.
3276	#[test]
3277	fn the_limit_alone_decides_what_the_peer_offers() {
3278		let handle = Link::new(true);
3279		let token = handle.present(Bytes::new(), true).unwrap();
3280		handle.grant(0, grant(&[], &[]));
3281		assert!(!handle.allows(Direction::Subscribe, "room/bob/cam"));
3282		assert!(handle.within_limit(Direction::Subscribe, "room/bob/cam"));
3283
3284		handle.handle().authorize(&grant(&["room/alice"], &[]));
3285		assert!(!handle.within_limit(Direction::Subscribe, "room/bob/cam"));
3286		assert!(handle.within_limit(Direction::Subscribe, "room/alice/cam"));
3287		drop(token);
3288	}
3289
3290	/// The default acceptor answers with its base grant, then with each grant a new
3291	/// limit changes, narrower or wider, and stays quiet on a change that leaves it alone.
3292	#[test]
3293	fn the_default_grant_follows_the_limit() {
3294		let handle = Link::new(true);
3295		let mut default = DefaultGrant::new(handle.clone(), grant(&["room"], &["room"]));
3296		let waiter = kio::Waiter::noop();
3297
3298		assert_eq!(default.poll(&waiter), Poll::Ready(grant(&["room"], &["room"])));
3299		assert!(default.poll(&waiter).is_pending());
3300
3301		handle.handle().authorize(&grant(&["room"], &["room/alice"]));
3302		assert_eq!(default.poll(&waiter), Poll::Ready(grant(&["room"], &["room/alice"])));
3303
3304		// Wider again, but never past what the origin handles allow.
3305		handle.handle().authorize(&Grant::all());
3306		assert_eq!(default.poll(&waiter), Poll::Ready(grant(&["room"], &["room"])));
3307
3308		// A limit that leaves the grant as it is: nothing to tell the peer.
3309		handle.handle().authorize(&grant(&[""], &[""]));
3310		assert!(default.poll(&waiter).is_pending());
3311	}
3312
3313	/// On moq-transport without AUTH an auth needs no answer: it is kept for the requests
3314	/// that name it, with a grant that stays unknown. moq-lite without AUTH has nothing that
3315	/// could carry it.
3316	#[test]
3317	fn a_request_carries_an_auth_without_the_auth_stream() {
3318		let ietf = Link::ietf();
3319		let auth = ietf.present(Bytes::from_static(b"jwt"), false).unwrap();
3320		assert!(matches!(
3321			auth.poll_answer(&kio::Waiter::noop()),
3322			Poll::Ready(Ok(Answer::Requests))
3323		));
3324		assert_eq!(auth.grant().peek(), None);
3325		assert_eq!(ietf.token(&auth).as_deref(), Some(b"jwt".as_slice()));
3326		assert!(
3327			ietf.read(|link, _| link.opening.is_empty()),
3328			"nothing to open a stream for"
3329		);
3330
3331		let lite = Link::new(false);
3332		let auth = lite.present(Bytes::from_static(b"jwt"), false).unwrap();
3333		assert!(matches!(
3334			auth.poll_answer(&kio::Waiter::noop()),
3335			Poll::Ready(Err(Error::Unsupported))
3336		));
3337	}
3338
3339	/// Only the handle that issued an auth carries it: a route naming another session's
3340	/// auth goes out under this session's scope.
3341	#[test]
3342	fn another_handle_does_not_carry_an_auth() {
3343		let issuer = Link::ietf();
3344		let auth = issuer.present(Bytes::from_static(b"jwt"), false).unwrap();
3345		assert_eq!(Link::ietf().token(&auth), None);
3346	}
3347
3348	/// Every clone names one credential, which stays presented until the last drops.
3349	#[test]
3350	fn the_last_clone_withdraws_the_auth() {
3351		let handle = Link::new(true);
3352		let auth = handle.present(Bytes::from_static(b"jwt"), false).unwrap();
3353		let Poll::Ready(Some((id, _))) = handle.poll_opening(&kio::Waiter::noop()) else {
3354			panic!("nothing to open");
3355		};
3356		let clone = auth.clone();
3357		assert_eq!(clone, auth, "a clone is the same auth");
3358		assert_ne!(
3359			handle.present(Bytes::from_static(b"jwt"), false).unwrap(),
3360			auth,
3361			"the same bytes presented again are another auth"
3362		);
3363
3364		drop(auth);
3365		assert!(
3366			handle.poll_withdrawn(id, &kio::Waiter::noop()).is_pending(),
3367			"withdrawn while a clone lives"
3368		);
3369		drop(clone);
3370		assert!(handle.poll_withdrawn(id, &kio::Waiter::noop()).is_ready());
3371	}
3372
3373	/// An AUTH_OK racing the withdrawal of its token reaches a stream that is closing: it
3374	/// never widens what the session may do.
3375	#[test]
3376	fn a_withdrawn_token_takes_no_grant() {
3377		let handle = Link::new(true);
3378		let setup = handle.present(Bytes::new(), true).unwrap();
3379		handle.grant(setup.presented.id, Grant::default());
3380		let auth = handle.present(Bytes::from_static(b"jwt"), false).unwrap();
3381		let id = opened(&handle);
3382		drop(auth);
3383		assert!(handle.poll_withdrawn(id, &kio::Waiter::noop()).is_ready());
3384		handle.granted(id, Grant::all());
3385		assert!(!handle.within_grant(Direction::Publish, "room"));
3386	}
3387
3388	fn opened(link: &Link) -> u64 {
3389		match link.poll_opening(&kio::Waiter::noop()) {
3390			Poll::Ready(Some((id, _))) => id,
3391			_ => panic!("nothing to open"),
3392		}
3393	}
3394
3395	/// Only the peer's verdict ends a handle's token for good: a session ending leaves it for
3396	/// the next session, which presents it again, and one active session at a time.
3397	#[test]
3398	fn only_a_verdict_ends_a_shared_token() {
3399		let handle = Handle::new();
3400		let first = Link::attach(&handle, true, false).unwrap();
3401		assert!(matches!(Link::attach(&handle, true, false), Err(Error::Duplicate)));
3402		let auth = handle.add(Bytes::from_static(b"jwt")).unwrap();
3403		let id = opened(&first);
3404		first.grant(id, Grant::all());
3405		assert!(matches!(
3406			auth.poll_answer(&kio::Waiter::noop()),
3407			Poll::Ready(Ok(Answer::Granted))
3408		));
3409		assert_eq!(auth.grant().peek(), Some(Grant::all()));
3410
3411		first.close(Error::Cancel);
3412		assert_eq!(auth.grant().peek(), None, "no session is live");
3413		assert!(Selector::Token(id).ended(&handle.state.read()).is_none());
3414
3415		let second = Link::attach(&handle, true, false).unwrap();
3416		assert_eq!(opened(&second), id, "the next session presents it again");
3417		second.refused(id, false);
3418		let refused = Error::Session(SessionError::Unauthorized);
3419		assert_eq!(second.retry(id, &refused), None);
3420		second.ended(id, refused);
3421		assert!(matches!(
3422			Selector::Token(id).ended(&handle.state.read()),
3423			Some(Error::Session(SessionError::Unauthorized))
3424		));
3425
3426		second.close(Error::Cancel);
3427		let third = Link::attach(&handle, true, false).unwrap();
3428		assert!(
3429			third.poll_opening(&kio::Waiter::noop()).is_pending(),
3430			"a refused token stays ended"
3431		);
3432	}
3433
3434	/// The answer records how the peer accepted a token, so a grant whose session drops before
3435	/// the caller reads it is still told apart from a token only requests carry.
3436	#[test]
3437	fn the_answer_outlives_its_session() {
3438		let handle = Handle::new();
3439		let session = Link::attach(&handle, true, false).unwrap();
3440		let auth = handle.add(Bytes::from_static(b"jwt")).unwrap();
3441		session.grant(opened(&session), Grant::all());
3442		session.close(Error::Cancel);
3443		assert_eq!(auth.grant().peek(), None);
3444		assert!(matches!(
3445			auth.poll_answer(&kio::Waiter::noop()),
3446			Poll::Ready(Ok(Answer::Granted))
3447		));
3448
3449		let handle = Handle::new();
3450		let _session = Link::attach(&handle, false, true).unwrap();
3451		let auth = handle.add(Bytes::from_static(b"jwt")).unwrap();
3452		assert!(matches!(
3453			auth.poll_answer(&kio::Waiter::noop()),
3454			Poll::Ready(Ok(Answer::Requests))
3455		));
3456	}
3457
3458	/// A session's own handle has no successor: a token added after its GOAWAY fails at once,
3459	/// and one whose stream ends without a verdict ends for good.
3460	#[test]
3461	fn a_sessions_own_handle_ends_its_tokens() {
3462		let link = Link::new(true);
3463		let auth = link.present(Bytes::from_static(b"jwt"), false).unwrap();
3464		let id = opened(&link);
3465		let lost = Error::Stream(crate::StreamError::Internal);
3466		assert_eq!(link.retry(id, &lost), None, "the application hears of a lost token");
3467		link.ended(id, lost);
3468		assert!(matches!(
3469			auth.poll_answer(&kio::Waiter::noop()),
3470			Poll::Ready(Err(Error::Stream(_)))
3471		));
3472
3473		let (goaway, _protocol) = crate::goaway::Handle::new(false);
3474		goaway.send(crate::goaway::Goaway::new()).unwrap();
3475		link.drain_with(std::sync::Arc::new(goaway));
3476		assert!(matches!(
3477			link.present(Bytes::from_static(b"late"), false),
3478			Err(Error::GoingAway)
3479		));
3480	}
3481
3482	/// A token added while a session without AUTH drains rides only its successor, so the
3483	/// draining session cannot end it as unsupported.
3484	#[test]
3485	fn a_draining_session_takes_no_new_token() {
3486		let handle = Handle::new();
3487		let draining = Link::attach(&handle, false, false).unwrap();
3488		let (goaway, _protocol) = crate::goaway::Handle::new(false);
3489		goaway.send(crate::goaway::Goaway::new()).unwrap();
3490		draining.drain_with(std::sync::Arc::new(goaway));
3491		let successor = Link::attach(&handle, true, false).unwrap();
3492
3493		let auth = handle.add(Bytes::from_static(b"jwt")).unwrap();
3494		assert!(Selector::Token(auth.id()).ended(&handle.state.read()).is_none());
3495		let id = opened(&successor);
3496		successor.grant(id, Grant::all());
3497		assert!(matches!(
3498			auth.poll_answer(&kio::Waiter::noop()),
3499			Poll::Ready(Ok(Answer::Granted))
3500		));
3501	}
3502
3503	/// A draining session's late refusal ends the token there alone while its successor
3504	/// presents it, so a stale verdict never withdraws a live grant.
3505	#[test]
3506	fn a_draining_refusal_leaves_the_successors_grant() {
3507		let handle = Handle::new();
3508		let draining = Link::attach(&handle, true, false).unwrap();
3509		let auth = handle.add(Bytes::from_static(b"jwt")).unwrap();
3510		let id = opened(&draining);
3511		let (goaway, _protocol) = crate::goaway::Handle::new(false);
3512		goaway.send(crate::goaway::Goaway::new()).unwrap();
3513		draining.drain_with(std::sync::Arc::new(goaway));
3514
3515		let successor = Link::attach(&handle, true, false).unwrap();
3516		assert_eq!(opened(&successor), id);
3517		successor.grant(id, Grant::all());
3518		draining.refused(id, false);
3519		draining.ended(id, Error::Session(SessionError::Unauthorized));
3520		assert!(Selector::Token(id).ended(&handle.state.read()).is_none());
3521		assert_eq!(auth.grant().peek(), Some(Grant::all()));
3522	}
3523
3524	/// A draining session's late refusal leaves a token its successor is still deciding,
3525	/// including one the successor granted and then transiently refused.
3526	#[test]
3527	fn a_draining_refusal_defers_to_the_successors_retry() {
3528		let handle = Handle::new();
3529		let draining = Link::attach(&handle, true, false).unwrap();
3530		let auth = handle.add(Bytes::from_static(b"jwt")).unwrap();
3531		let id = opened(&draining);
3532		let (goaway, _protocol) = crate::goaway::Handle::new(false);
3533		goaway.send(crate::goaway::Goaway::new()).unwrap();
3534		draining.drain_with(std::sync::Arc::new(goaway));
3535
3536		let successor = Link::attach(&handle, true, false).unwrap();
3537		assert_eq!(opened(&successor), id);
3538		successor.grant(id, Grant::all());
3539		successor.refused(id, true);
3540		let busy = Error::Session(SessionError::TooManyRequests);
3541		assert_eq!(successor.retry(id, &busy), Some(RETRY_INITIAL));
3542
3543		draining.refused(id, false);
3544		draining.ended(id, Error::Session(SessionError::Unauthorized));
3545		assert!(Selector::Token(id).ended(&handle.state.read()).is_none());
3546
3547		assert_eq!(successor.reopen(id).unwrap().as_ref(), b"jwt");
3548		successor.grant(id, Grant::all());
3549		assert_eq!(auth.grant().peek(), Some(Grant::all()));
3550	}
3551
3552	/// A retry that wakes after this side sent a GOAWAY opens nothing: a successor presents
3553	/// it, and on a session's own handle the token ends as going away, not as a clean close.
3554	#[test]
3555	fn a_draining_session_presents_no_retry() {
3556		let link = Link::new(true);
3557		let (goaway, _protocol) = crate::goaway::Handle::new(false);
3558		let goaway = std::sync::Arc::new(goaway);
3559		link.drain_with(goaway.clone());
3560		let auth = link.present(Bytes::from_static(b"jwt"), false).unwrap();
3561		let id = opened(&link);
3562		link.refused(id, true);
3563		let busy = Error::Session(SessionError::TooManyRequests);
3564		assert_eq!(link.retry(id, &busy), Some(RETRY_INITIAL));
3565
3566		goaway.send(crate::goaway::Goaway::new()).unwrap();
3567		assert!(!link.active());
3568		let err = link.reopen(id).unwrap_err();
3569		assert!(matches!(err, Error::GoingAway), "{err:?}");
3570		link.ended(id, err);
3571		assert!(matches!(
3572			Selector::Token(auth.id()).ended(&link.state().read()),
3573			Some(Error::GoingAway)
3574		));
3575	}
3576
3577	/// A shared handle's token whose stream is lost without a verdict is presented again on the
3578	/// same session, doubling its backoff until a grant resets it. A request keeps carrying it
3579	/// meanwhile, and a request it might cover waits for the retry's answer.
3580	#[test]
3581	fn a_lost_stream_is_presented_again() {
3582		let handle = Handle::new();
3583		let link = Link::attach(&handle, true, true).unwrap();
3584		let auth = handle.add(Bytes::from_static(b"jwt")).unwrap();
3585		let id = opened(&link);
3586		let lost = Error::Stream(crate::StreamError::Internal);
3587
3588		link.grant(id, Grant::all());
3589		assert_eq!(link.retry(id, &lost), Some(RETRY_INITIAL));
3590		assert_eq!(auth.grant().peek(), None, "the lost stream's grant is gone");
3591		assert_eq!(link.token(&auth).as_deref(), Some(&b"jwt"[..]));
3592		let mut gate = Gate::new(link.clone(), crate::Path::from_static("room"), Direction::Publish);
3593		assert!(gate.poll_ready(&kio::Waiter::noop()).is_pending());
3594
3595		assert_eq!(link.reopen(id).unwrap().as_ref(), b"jwt");
3596		assert_eq!(link.retry(id, &lost), Some(RETRY_INITIAL * 2));
3597		link.reopen(id).unwrap();
3598		link.grant(id, Grant::all());
3599		assert!(gate.poll_ready(&kio::Waiter::noop()).is_ready());
3600		assert_eq!(link.retry(id, &lost), Some(RETRY_INITIAL), "a grant resets the backoff");
3601		assert!(Selector::Token(id).ended(&handle.state.read()).is_none());
3602
3603		// A clean close after a grant is the peer's verdict, not a lost stream.
3604		link.reopen(id).unwrap();
3605		link.grant(id, Grant::all());
3606		assert_eq!(link.retry(id, &Error::Cancel), None);
3607		link.ended(id, Error::Cancel);
3608		assert!(matches!(
3609			Selector::Token(id).ended(&handle.state.read()),
3610			Some(Error::Cancel)
3611		));
3612	}
3613
3614	/// A draining session presents nothing again, and a transient refusal there is no verdict:
3615	/// the token waits for the successor.
3616	#[test]
3617	fn a_draining_session_leaves_an_undecided_token() {
3618		let handle = Handle::new();
3619		let draining = Link::attach(&handle, true, false).unwrap();
3620		let _auth = handle.add(Bytes::from_static(b"jwt")).unwrap();
3621		let id = opened(&draining);
3622		let (goaway, _protocol) = crate::goaway::Handle::new(false);
3623		goaway.send(crate::goaway::Goaway::new()).unwrap();
3624		draining.drain_with(std::sync::Arc::new(goaway));
3625
3626		let busy = Error::Session(SessionError::TooManyRequests);
3627		draining.refused(id, true);
3628		assert_eq!(draining.retry(id, &busy), None);
3629		draining.ended(id, busy);
3630		assert!(Selector::Token(id).ended(&handle.state.read()).is_none());
3631
3632		let successor = Link::attach(&handle, true, false).unwrap();
3633		assert_eq!(opened(&successor), id, "the successor presents it");
3634	}
3635
3636	/// A refusal that may pass is presented again after a doubling backoff, and settles nothing.
3637	#[test]
3638	fn a_transient_refusal_backs_off() {
3639		let link = Link::new(true);
3640		let auth = link.present(Bytes::from_static(b"jwt"), false).unwrap();
3641		let id = opened(&link);
3642		let busy = Error::Session(SessionError::TooManyRequests);
3643
3644		link.refused(id, true);
3645		assert_eq!(link.retry(id, &busy), Some(RETRY_INITIAL));
3646		assert!(auth.poll_answer(&kio::Waiter::noop()).is_pending());
3647		assert_eq!(link.reopen(id).unwrap().as_ref(), b"jwt");
3648		link.refused(id, true);
3649		assert_eq!(link.retry(id, &busy), Some(RETRY_INITIAL * 2));
3650		assert_eq!(link.retry(id, &busy), None, "only a refusal retries");
3651
3652		link.reopen(id).unwrap();
3653		link.grant(id, Grant::all());
3654		assert!(matches!(
3655			auth.poll_answer(&kio::Waiter::noop()),
3656			Poll::Ready(Ok(Answer::Granted))
3657		));
3658	}
3659}
3660
3661#[cfg(all(test, feature = "async"))]
3662mod request_token_tests {
3663	use super::*;
3664	use futures::FutureExt;
3665
3666	fn token(value: &[u8], kind: u64) -> crate::setup::Token {
3667		crate::setup::Token {
3668			kind,
3669			value: value.to_vec(),
3670		}
3671	}
3672
3673	fn subscribe_path() -> crate::Path {
3674		crate::Path::from_static("room/alice")
3675	}
3676
3677	/// A request token reaches the app's acceptor like any other token, and the grant the
3678	/// app answers is what the verdict resolves to.
3679	#[kio::test]
3680	async fn a_request_token_reaches_the_acceptor() {
3681		let handle = Link::new(true);
3682		let mut requests = handle.handle().requests();
3683		let verdict = handle.verify_request(token(b"jwt", 0), None);
3684
3685		let request = requests.next().await.expect("a request");
3686		assert_eq!(request.token().as_ref(), b"jwt");
3687		let _issued = request.accept(Grant::all());
3688
3689		let grant = verdict.grant().await.expect("granted");
3690		assert!(grant.publish.matches("room/alice"));
3691	}
3692
3693	#[kio::test]
3694	async fn naming_requests_share_verification_and_withdraw_together() {
3695		let handle = Link::new(true);
3696		let mut requests = handle.handle().requests();
3697		let first = handle.verify_request(token(b"shared", 0), None);
3698		let second = handle.verify_request(token(b"shared", 0), None);
3699		let issued = requests.next().await.unwrap().accept(Grant::all());
3700		assert!(requests.poll_next(&kio::Waiter::noop()).is_pending());
3701		first.grant().await.unwrap();
3702		second.grant().await.unwrap();
3703		drop(first);
3704		assert!(issued.closed().now_or_never().is_none());
3705		drop(second);
3706		assert!(matches!(issued.closed().await, Error::Cancel));
3707		let later = handle.verify_request(token(b"shared", 0), None);
3708		let _issued = requests.next().await.unwrap().accept(Grant::default());
3709		assert_eq!(later.grant().await.unwrap(), Grant::default());
3710	}
3711
3712	/// A request naming a token whose grant the acceptor already dropped verifies it again,
3713	/// rather than sharing the finished verdict with a naming request still on its way out.
3714	#[kio::test]
3715	async fn a_token_the_acceptor_dropped_verifies_again() {
3716		let handle = Link::new(true);
3717		let mut requests = handle.handle().requests();
3718		let first = handle.verify_request(token(b"shared", 0), None);
3719		let issued = requests.next().await.unwrap().accept(Grant::all());
3720		first.grant().await.unwrap();
3721		drop(issued);
3722		let later = handle.verify_request(token(b"shared", 0), None);
3723		let _issued = requests.next().await.unwrap().accept(Grant::default());
3724		assert_eq!(later.grant().await.unwrap(), Grant::default());
3725		drop(first);
3726		let again = handle.verify_request(token(b"shared", 0), None);
3727		assert!(
3728			requests.poll_next(&kio::Waiter::noop()).is_pending(),
3729			"the live verdict is shared"
3730		);
3731		assert_eq!(again.grant().await.unwrap(), Grant::default());
3732	}
3733
3734	#[kio::test]
3735	async fn every_naming_request_observes_updates_revocation_and_expiry() {
3736		for revoke in [false, true] {
3737			let runtime = crate::time::sim();
3738			let handle = Link::new(true);
3739			let mut requests = handle.handle().requests();
3740			let first = handle.verify_request(token(b"shared", 0), None);
3741			let second = handle.verify_request(token(b"shared", 0), None);
3742			let issued = requests.next().await.unwrap().accept(grant_in(&runtime, 60));
3743			let mut grants = Vec::new();
3744			for verdict in [first, second] {
3745				let answer = verdict.grant().await;
3746				grants.push(
3747					RequestGrant::new(
3748						&runtime,
3749						verdict,
3750						answer,
3751						subscribe_path(),
3752						RequestKind::Subscribe,
3753						None,
3754					)
3755					.unwrap(),
3756				);
3757			}
3758			issued.update(grant_in(&runtime, 30));
3759			for grant in &grants {
3760				assert!(grant.poll_ended(&kio::Waiter::noop()).is_pending());
3761				assert_eq!(grant.grant(), grant_in(&runtime, 30));
3762			}
3763			if revoke {
3764				issued.revoke(SessionError::Unauthorized, "revoked");
3765			} else {
3766				kio::clock::sleep(Duration::from_secs(30)).await;
3767			}
3768			for grant in grants {
3769				let Poll::Ready(refusal) = grant.poll_ended(&kio::Waiter::noop()) else {
3770					panic!("token stayed live");
3771				};
3772				if revoke {
3773					assert_eq!(refusal.reason, "revoked");
3774				} else {
3775					assert!(matches!(refusal.error, Error::Expired));
3776				}
3777			}
3778		}
3779	}
3780
3781	#[kio::test]
3782	async fn discovery_uses_its_token_alone() {
3783		let runtime = crate::time::sim();
3784		let handle = Link::new(true);
3785		handle.handle().authorize(&Grant::all());
3786		let mut requests = handle.handle().requests();
3787		let mut gate = Gate::new(handle.clone(), crate::Path::default(), Direction::Publish).discovery();
3788		let verdict = gate.verify(token(b"room", 0), None);
3789		let issued = requests.next().await.unwrap().accept(subscribe_only("room"));
3790		let answer = verdict.grant().await;
3791		gate.admit(&runtime, (verdict, answer)).unwrap();
3792		let mut epoch = 0;
3793		let Poll::Ready(permit) = gate.poll_permit(&mut epoch, &kio::Waiter::noop()) else {
3794			panic!("no initial permit");
3795		};
3796		assert!(permit.matches("room/alice"));
3797		assert!(!permit.matches("elsewhere"));
3798		issued.update(subscribe_only("room/bob"));
3799		let Poll::Ready(permit) = gate.poll_permit(&mut epoch, &kio::Waiter::noop()) else {
3800			panic!("update missed");
3801		};
3802		assert!(permit.matches("room/bob"));
3803		assert!(!permit.matches("room/alice"));
3804		drop(gate);
3805		assert!(matches!(issued.closed().await, Error::Cancel));
3806	}
3807
3808	/// A gate bound to a token reports the token ending as a permit that allows nothing, so a
3809	/// caller reading permits alone stops too.
3810	#[kio::test]
3811	async fn a_bound_token_ending_is_a_new_permit() {
3812		let runtime = crate::time::sim();
3813		let handle = Link::new(true);
3814		handle.handle().authorize(&Grant::all());
3815		let mut requests = handle.handle().requests();
3816		let mut gate = Gate::new(handle.clone(), crate::Path::default(), Direction::Publish).discovery();
3817		let verdict = gate.verify(token(b"room", 0), None);
3818		let issued = requests.next().await.unwrap().accept(subscribe_only("room"));
3819		let answer = verdict.grant().await;
3820		gate.admit(&runtime, (verdict, answer)).unwrap();
3821		let mut epoch = 0;
3822		let Poll::Ready(permit) = gate.poll_permit(&mut epoch, &kio::Waiter::noop()) else {
3823			panic!("no initial permit");
3824		};
3825		assert!(permit.matches("room/alice"));
3826		issued.revoke(SessionError::Unauthorized, "revoked");
3827		let Poll::Ready(permit) = gate.poll_permit(&mut epoch, &kio::Waiter::noop()) else {
3828			panic!("the token's end went unreported");
3829		};
3830		assert!(!permit.matches("room/alice"));
3831		assert!(gate.poll_permit(&mut epoch, &kio::Waiter::noop()).is_pending());
3832	}
3833
3834	/// A gate its token bound verifies another token as that grant's renewal: one the acceptor
3835	/// granted takes over, rather than the old grant lapsing before the gate admits it.
3836	#[kio::test]
3837	async fn a_bound_gate_hands_over_to_a_granted_replacement() {
3838		let runtime = crate::time::sim();
3839		let handle = Link::new(true);
3840		handle.handle().authorize(&Grant::all());
3841		let mut requests = handle.handle().requests();
3842		let mut gate = Gate::new(handle.clone(), crate::Path::default(), Direction::Publish).discovery();
3843		let verdict = gate.verify(token(b"jwt", 0), None);
3844		let _issued = requests.next().await.unwrap().accept(grant_in(&runtime, 60));
3845		let answer = verdict.grant().await;
3846		gate.admit(&runtime, (verdict, answer)).unwrap();
3847
3848		let renewal = gate.verify(token(b"jwt2", 0), None);
3849		let _issued2 = requests.next().await.unwrap().accept(grant_in(&runtime, 600));
3850		kio::clock::sleep(Duration::from_secs(61)).await;
3851		let pending = kio::wait(|waiter| Poll::Ready(gate.poll_token_ended(waiter).is_pending())).await;
3852		assert!(pending, "the old grant lapsed ahead of its granted replacement");
3853
3854		let answer = renewal.grant().await;
3855		gate.admit(&runtime, (renewal, answer)).unwrap();
3856		let pending = kio::wait(|waiter| Poll::Ready(gate.poll_token_ended(waiter).is_pending())).await;
3857		assert!(pending, "the replacement holds the gate");
3858	}
3859
3860	/// Naming and releasing a request token touches nothing the session's permits watch, so
3861	/// it wakes none of the requests waiting on them: a session with many announces would
3862	/// otherwise poll every one for each token.
3863	#[kio::test]
3864	async fn request_tokens_do_not_wake_permit_waiters() {
3865		struct Woken(std::sync::atomic::AtomicBool);
3866		impl std::task::Wake for Woken {
3867			fn wake(self: std::sync::Arc<Self>) {
3868				self.0.store(true, std::sync::atomic::Ordering::SeqCst);
3869			}
3870		}
3871		let handle = Link::new(true);
3872		let mut requests = handle.handle().requests();
3873		let first = handle.verify_request(token(b"warm", 0), None);
3874		let _first = requests.next().await.unwrap().accept(Grant::all());
3875		first.grant().await.unwrap();
3876
3877		let woken = std::sync::Arc::new(Woken(Default::default()));
3878		let waiter = kio::Waiter::new(std::task::Waker::from(woken.clone()));
3879		let mut epoch = 0;
3880		while handle.poll_permit(Direction::Publish, &mut epoch, &waiter).is_ready() {}
3881		let second = handle.verify_request(token(b"shared", 0), None);
3882		let third = handle.verify_request(token(b"shared", 0), None);
3883		drop((second, third));
3884		assert!(
3885			!woken.0.load(std::sync::atomic::Ordering::SeqCst),
3886			"a request token woke the permit waiters"
3887		);
3888	}
3889
3890	#[kio::test]
3891	async fn request_tokens_are_scoped_to_one_session_on_a_shared_handle() {
3892		let handle = Handle::new();
3893		let first = Link::attach(&handle, false, true).unwrap();
3894		let mut requests = handle.requests();
3895		let verdict = first.verify_request(token(b"token", 0), None);
3896		let issued = requests.next().await.unwrap().accept(Grant::all());
3897		verdict.grant().await.unwrap();
3898		first.close(Error::Cancel);
3899		let second = Link::attach(&handle, false, true).unwrap();
3900		let next = second.verify_request(token(b"token", 0), None);
3901		let _next = requests.next().await.unwrap().accept(Grant::default());
3902		assert_eq!(next.grant().await.unwrap(), Grant::default());
3903		assert!(matches!(issued.closed().await, Error::Cancel));
3904	}
3905
3906	/// An AUTH token has no type, so a request token of any type but out-of-band cannot reach
3907	/// the acceptor as one: it is unsupported, never handed over as if it were a plain token.
3908	#[kio::test]
3909	async fn a_typed_request_token_is_unsupported() {
3910		let handle = Link::new(true);
3911		let mut requests = handle.handle().requests();
3912		let verdict = handle.verify_request(token(b"cat", 1), None);
3913		let err = verdict.grant().await.expect_err("a typed token");
3914		assert!(matches!(err.error, Error::Unsupported), "{err:?}");
3915		assert!(
3916			requests.poll_next(&kio::Waiter::noop()).is_pending(),
3917			"nothing reached the acceptor"
3918		);
3919	}
3920
3921	/// An empty request token is refused before the acceptor, which would read it as the
3922	/// connection's own credential.
3923	#[test]
3924	fn an_empty_request_token_is_unsupported() {
3925		let handle = Link::new(true);
3926		let mut requests = handle.handle().requests();
3927		let verdict = handle.verify_request(token(b"", crate::setup::Token::OUT_OF_BAND), None);
3928		assert!(matches!(
3929			verdict.poll_grant(&kio::Waiter::noop()),
3930			Poll::Ready(Err(Refusal {
3931				error: Error::Unsupported,
3932				..
3933			}))
3934		));
3935		assert!(
3936			requests.poll_next(&kio::Waiter::noop()).is_pending(),
3937			"nothing reached the acceptor"
3938		);
3939	}
3940
3941	/// A request-borne token is verified without AUTH: it rides the request message, so
3942	/// `requests()` stays live on a session that speaks no AUTH, as on moq-transport.
3943	#[kio::test]
3944	async fn a_request_token_is_verified_without_the_auth_stream() {
3945		let handle = Link::new(false);
3946		let mut requests = handle.handle().requests();
3947		let verdict = handle.verify_request(token(b"jwt", 0), None);
3948		let request = requests.next().await.expect("a request reaches the acceptor");
3949		let _issued = request.accept(Grant::all());
3950		assert!(
3951			verdict.grant().await.expect("granted").publish.matches("room/alice"),
3952			"admitted without AUTH"
3953		);
3954	}
3955
3956	/// With no `requests()` consumer, a request token cannot be verified in band, so the verdict
3957	/// is Unsupported and the caller refuses the request NOT_SUPPORTED.
3958	#[kio::test]
3959	async fn no_consumer_refuses_a_request_token_as_unsupported() {
3960		let handle = Link::new(true);
3961		let verdict = handle.verify_request(token(b"jwt", 0), None);
3962		let err = verdict.grant().await.expect_err("no verifier");
3963		assert!(matches!(err.error, Error::Unsupported), "{err:?}");
3964	}
3965
3966	/// A refused request token resolves to the refusal, which the caller sends the peer as
3967	/// UNAUTHORIZED.
3968	#[kio::test]
3969	async fn a_refused_request_token_is_unauthorized() {
3970		let handle = Link::new(true);
3971		let mut requests = handle.handle().requests();
3972		let verdict = handle.verify_request(token(b"jwt", 0), None);
3973		requests.next().await.unwrap().reject(SessionError::Unauthorized, "no");
3974		let err = verdict.grant().await.expect_err("refused");
3975		assert!(
3976			matches!(err.error, Error::Session(SessionError::Unauthorized)),
3977			"{err:?}"
3978		);
3979	}
3980
3981	/// A grant the acceptor revoked, dropped or replaced before the verdict was read is admitted
3982	/// as it stands now, never as first issued.
3983	#[kio::test]
3984	async fn a_grant_ended_before_admission_is_refused() {
3985		let handle = Link::new(true);
3986		let mut requests = handle.handle().requests();
3987
3988		let verdict = handle.verify_request(token(b"jwt", 0), None);
3989		let issued = requests.next().await.unwrap().accept(Grant::all());
3990		issued.revoke(SessionError::Unauthorized, "revoked");
3991		let err = verdict.grant().await.expect_err("revoked before admission");
3992		assert_eq!(err.reason, "revoked");
3993		drop(verdict);
3994
3995		let verdict = handle.verify_request(token(b"jwt", 0), None);
3996		drop(requests.next().await.unwrap().accept(Grant::all()));
3997		let err = verdict.grant().await.expect_err("dropped before admission");
3998		assert!(
3999			matches!(err.error, Error::Session(SessionError::Unauthorized)),
4000			"{err:?}"
4001		);
4002		drop(verdict);
4003
4004		let verdict = handle.verify_request(token(b"jwt", 0), None);
4005		let issued = requests.next().await.unwrap().accept(Grant::all());
4006		issued.update(Grant::default());
4007		let grant = verdict.grant().await.expect("still granted");
4008		assert!(
4009			!grant.publish.matches("room/alice"),
4010			"the replacement is what is admitted"
4011		);
4012	}
4013
4014	/// The grant lives exactly as long as the request: dropping the verdict ends the
4015	/// acceptor's issued grant, so it never outlives the request nor joins the union.
4016	#[kio::test]
4017	async fn dropping_the_verdict_ends_the_grant() {
4018		let handle = Link::new(true);
4019		let mut requests = handle.handle().requests();
4020		let verdict = handle.verify_request(token(b"jwt", 0), None);
4021		let issued = requests.next().await.unwrap().accept(Grant::all());
4022		verdict.grant().await.expect("granted");
4023		drop(verdict);
4024		let err = issued.closed().await;
4025		assert!(matches!(err, Error::Cancel), "{err:?}");
4026	}
4027
4028	/// A request token never joins the session union: the union stays what the connection
4029	/// credential earned, not what a request token granted.
4030	#[kio::test]
4031	async fn a_request_token_never_joins_the_union() {
4032		let handle = Link::new(true);
4033		let mut requests = handle.handle().requests();
4034		let verdict = handle.verify_request(token(b"jwt", 0), None);
4035		let _issued = requests.next().await.unwrap().accept(Grant::all());
4036		verdict.grant().await.expect("granted");
4037		// The union only reflects tokens presented on this side (none here), never a
4038		// request token the acceptor answered.
4039		assert_eq!(
4040			handle.handle().grant().peek(),
4041			None,
4042			"a request token must not widen the union"
4043		);
4044	}
4045
4046	fn subscribe_only(prefix: &str) -> Grant {
4047		Grant {
4048			publish: Prefixes::new(),
4049			subscribe: crate::Prefix::try_from(prefix).unwrap().into(),
4050			expires: None,
4051		}
4052	}
4053
4054	/// The session's scope for unnamed requests is the connection credential's grant and every
4055	/// grant issued to an AUTH token, and nothing a request token earned: a token on one
4056	/// request never widens what tokenless requests may do.
4057	#[kio::test]
4058	async fn the_scope_is_session_tokens_only() {
4059		let handle = Link::new(true);
4060		let mut requests = handle.handle().requests();
4061		handle.handle().authorize(&subscribe_only("room/alice"));
4062		assert!(!handle.allows(Direction::Publish, "room/bob"));
4063
4064		// A token on a request admits that request, and nothing else.
4065		let verdict = handle.verify_request(token(b"request", 0), None);
4066		let _request = requests.next().await.unwrap().accept(subscribe_only("room/bob"));
4067		verdict.grant().await.expect("granted");
4068		assert!(
4069			!handle.allows(Direction::Publish, "room/bob"),
4070			"a request token widened the scope"
4071		);
4072
4073		// An AUTH token joins the scope while its grant stands.
4074		let serving = Serving::new(handle.clone());
4075		requests
4076			.queue
4077			.push(Request::new(Bytes::from_static(b"auth"), serving.issue.clone()));
4078		let issued = requests.next().await.unwrap().accept(subscribe_only("room/carol"));
4079		assert!(handle.allows(Direction::Publish, "room/carol"));
4080		assert!(
4081			handle.allows(Direction::Publish, "room/alice"),
4082			"the connection grant still stands"
4083		);
4084
4085		issued.update(subscribe_only("room/dave"));
4086		assert!(
4087			!handle.allows(Direction::Publish, "room/carol"),
4088			"the update replaced it"
4089		);
4090		assert!(handle.allows(Direction::Publish, "room/dave"));
4091
4092		// Withdrawn by the peer, the grant leaves the scope, and a late update cannot bring it back.
4093		serving.end(Error::Cancel);
4094		assert!(!handle.allows(Direction::Publish, "room/dave"));
4095		issued.update(subscribe_only("room/dave"));
4096		assert!(
4097			!handle.allows(Direction::Publish, "room/dave"),
4098			"a withdrawn token rejoined the scope"
4099		);
4100	}
4101
4102	/// Revoking or dropping an AUTH token's grant takes it out of the scope.
4103	#[kio::test]
4104	async fn an_ended_auth_grant_leaves_the_scope() {
4105		let handle = Link::new(true);
4106		let mut requests = handle.handle().requests();
4107		handle.handle().authorize(&Grant::default());
4108		for revoke in [true, false] {
4109			let serving = Serving::new(handle.clone());
4110			requests
4111				.queue
4112				.push(Request::new(Bytes::from_static(b"auth"), serving.issue.clone()));
4113			let issued = requests.next().await.unwrap().accept(subscribe_only("room"));
4114			assert!(handle.allows(Direction::Publish, "room/alice"));
4115			match revoke {
4116				true => issued.revoke(SessionError::Unauthorized, "revoked"),
4117				false => drop(issued),
4118			}
4119			assert!(!handle.allows(Direction::Publish, "room/alice"), "revoke={revoke}");
4120		}
4121	}
4122
4123	/// A session never authorized is bound by its origin handles alone, whatever its AUTH
4124	/// tokens were granted: the scope only exists once the connection credential has a grant.
4125	#[kio::test]
4126	async fn an_unauthorized_session_has_no_scope() {
4127		let handle = Link::new(true);
4128		let mut requests = handle.handle().requests();
4129		let serving = Serving::new(handle.clone());
4130		requests
4131			.queue
4132			.push(Request::new(Bytes::from_static(b"auth"), serving.issue.clone()));
4133		let _issued = requests.next().await.unwrap().accept(subscribe_only("room"));
4134		assert!(handle.allows(Direction::Publish, "other"));
4135	}
4136
4137	use std::time::Duration;
4138
4139	fn grant_in(runtime: &crate::time::Deadlines, secs: u64) -> Grant {
4140		Grant {
4141			publish: Prefixes::new(),
4142			subscribe: Prefixes::all(),
4143			expires: runtime.now().checked_add(Duration::from_secs(secs)),
4144		}
4145	}
4146
4147	/// The request grant carries the acceptor's expiry, which is the deadline it lapses at.
4148	#[kio::test]
4149	async fn a_request_grant_has_the_acceptors_expiry() {
4150		let runtime = crate::time::sim();
4151		let handle = Link::new(true);
4152		let mut requests = handle.handle().requests();
4153		let verdict = handle.verify_request(token(b"jwt", 0), None);
4154		let grant = grant_in(&runtime, 60);
4155		let expires = grant.expires;
4156		let _issued = requests.next().await.unwrap().accept(grant);
4157		let answered = verdict.grant().await.unwrap();
4158		let request_grant = RequestGrant::new(
4159			&runtime,
4160			verdict,
4161			Ok(answered),
4162			subscribe_path(),
4163			RequestKind::Subscribe,
4164			None,
4165		)
4166		.unwrap();
4167		assert_eq!(request_grant.grant().expires, expires);
4168		assert!(expires.is_some());
4169	}
4170
4171	/// A grant that has already expired never admits the request or renews it, even for the
4172	/// moment before its deadline would fire.
4173	#[kio::test]
4174	async fn an_already_expired_grant_is_refused() {
4175		let runtime = crate::time::sim();
4176		let handle = Link::new(true);
4177		let mut requests = handle.handle().requests();
4178		let expired = || Grant {
4179			expires: Some(runtime.now()),
4180			..grant_in(&runtime, 0)
4181		};
4182
4183		let verdict = handle.verify_request(token(b"old", 0), None);
4184		let _issued = requests.next().await.unwrap().accept(expired());
4185		let answered = verdict.grant().await;
4186		let refused = RequestGrant::new(
4187			&runtime,
4188			verdict,
4189			answered,
4190			subscribe_path(),
4191			RequestKind::Subscribe,
4192			None,
4193		);
4194		assert!(
4195			matches!(&refused, Err(refusal) if matches!(refusal.error, Error::Unauthorized)),
4196			"an expired grant admits nothing"
4197		);
4198
4199		let verdict = handle.verify_request(token(b"jwt", 0), None);
4200		let _issued = requests.next().await.unwrap().accept(grant_in(&runtime, 60));
4201		let answered = verdict.grant().await;
4202		let request_grant = RequestGrant::new(
4203			&runtime,
4204			verdict,
4205			answered,
4206			subscribe_path(),
4207			RequestKind::Subscribe,
4208			None,
4209		)
4210		.unwrap();
4211		let renewal = handle.verify_request(token(b"old2", 0), None);
4212		let _issued = requests.next().await.unwrap().accept(expired());
4213		let renewed = renewal.grant().await;
4214		assert!(
4215			request_grant.renew(renewal, renewed).is_err(),
4216			"an expired grant renews nothing"
4217		);
4218	}
4219
4220	/// An accepted REQUEST_UPDATE replaces the grant and its expiry.
4221	#[kio::test]
4222	async fn a_renewal_token_replaces_the_grant_and_expiry() {
4223		let runtime = crate::time::sim();
4224		let handle = Link::new(true);
4225		let mut requests = handle.handle().requests();
4226
4227		let verdict = handle.verify_request(token(b"jwt", 0), None);
4228		let first = grant_in(&runtime, 60);
4229		let first_expires = first.expires;
4230		let _issued = requests.next().await.unwrap().accept(first);
4231		let answered = verdict.grant().await.unwrap();
4232		let request_grant = RequestGrant::new(
4233			&runtime,
4234			verdict,
4235			Ok(answered),
4236			subscribe_path(),
4237			RequestKind::Subscribe,
4238			None,
4239		)
4240		.unwrap();
4241
4242		// A REQUEST_UPDATE carrying a fresh token the acceptor accepts with a later expiry.
4243		let renewal = handle.verify_request(token(b"jwt2", 0), None);
4244		let second = grant_in(&runtime, 600);
4245		let second_expires = second.expires;
4246		let _issued2 = requests.next().await.unwrap().accept(second);
4247		let renewed = renewal.grant().await;
4248		assert!(
4249			request_grant.renew(renewal, renewed).is_ok(),
4250			"a covering renewal renews"
4251		);
4252
4253		assert_eq!(request_grant.grant().expires, second_expires);
4254		assert_ne!(second_expires, first_expires);
4255	}
4256
4257	/// With no accepted renewal, the deadline ends the request as Expired, and the
4258	/// session is not closed by it.
4259	#[kio::test]
4260	async fn the_deadline_expires_the_request_without_renewal() {
4261		let runtime = crate::time::sim();
4262		let handle = Link::new(true);
4263		let mut requests = handle.handle().requests();
4264		let verdict = handle.verify_request(token(b"jwt", 0), None);
4265		// Held for the request's life, so only the deadline (not a drop) ends it.
4266		let _issued = requests.next().await.unwrap().accept(grant_in(&runtime, 60));
4267		let answered = verdict.grant().await.unwrap();
4268		let request_grant = RequestGrant::new(
4269			&runtime,
4270			verdict,
4271			Ok(answered),
4272			subscribe_path(),
4273			RequestKind::Subscribe,
4274			None,
4275		)
4276		.unwrap();
4277
4278		let err = kio::wait(|waiter| request_grant.poll_ended(waiter)).await.error;
4279		assert!(matches!(err, Error::Expired), "{err:?}");
4280		assert_eq!(handle.handle().grant().peek(), None, "the session grant is untouched");
4281	}
4282
4283	/// A renewal the acceptor granted before the old deadline lapsed keeps the request, even
4284	/// when the serve loop applies it only after the deadline.
4285	/// An extension the acceptor sent before the old expiry keeps the request, even when the
4286	/// request reads it only after that expiry passed.
4287	#[kio::test]
4288	async fn an_extension_read_after_the_old_expiry_keeps_the_request() {
4289		let runtime = crate::time::sim();
4290		let handle = Link::new(true);
4291		let mut requests = handle.handle().requests();
4292		let verdict = handle.verify_request(token(b"jwt", 0), None);
4293		let issued = requests.next().await.unwrap().accept(grant_in(&runtime, 60));
4294		let answered = verdict.grant().await.unwrap();
4295		let request_grant = RequestGrant::new(
4296			&runtime,
4297			verdict,
4298			Ok(answered),
4299			subscribe_path(),
4300			RequestKind::Subscribe,
4301			None,
4302		)
4303		.unwrap();
4304		let pending = kio::wait(|waiter| Poll::Ready(request_grant.poll_ended(waiter).is_pending())).await;
4305		assert!(pending, "the first grant stands");
4306
4307		// Extended before the old expiry, and read only after it.
4308		let extended = grant_in(&runtime, 600);
4309		let expires = extended.expires;
4310		issued.update(extended);
4311		kio::clock::sleep(Duration::from_secs(61)).await;
4312
4313		let pending = kio::wait(|waiter| Poll::Ready(request_grant.poll_ended(waiter).is_pending())).await;
4314		assert!(pending, "the old expiry ended a request its acceptor had extended");
4315		assert_eq!(request_grant.grant().expires, expires);
4316
4317		// The extension's own expiry still ends it.
4318		kio::clock::sleep(Duration::from_secs(600)).await;
4319		let ended = kio::wait(|waiter| Poll::Ready(request_grant.poll_ended(waiter))).await;
4320		assert!(matches!(ended, Poll::Ready(refusal) if matches!(refusal.error, Error::Expired)));
4321	}
4322
4323	#[kio::test]
4324	async fn a_granted_renewal_outlives_the_old_deadline() {
4325		let runtime = crate::time::sim();
4326		let handle = Link::new(true);
4327		let mut requests = handle.handle().requests();
4328		let verdict = handle.verify_request(token(b"jwt", 0), None);
4329		let _issued = requests.next().await.unwrap().accept(grant_in(&runtime, 60));
4330		let answered = verdict.grant().await.unwrap();
4331		let request_grant = RequestGrant::new(
4332			&runtime,
4333			verdict,
4334			Ok(answered),
4335			subscribe_path(),
4336			RequestKind::Subscribe,
4337			None,
4338		)
4339		.unwrap();
4340
4341		let renewal = request_grant.verify_renewal(&handle, token(b"jwt2", 0));
4342		let second = grant_in(&runtime, 600);
4343		let second_expires = second.expires;
4344		let _issued2 = requests.next().await.unwrap().accept(second);
4345		kio::clock::sleep(Duration::from_secs(61)).await;
4346
4347		let pending = kio::wait(|waiter| Poll::Ready(request_grant.poll_ended(waiter).is_pending())).await;
4348		assert!(pending, "the lapsed deadline ended a request whose renewal was granted");
4349
4350		let renewed = renewal.grant().await;
4351		assert!(request_grant.renew(renewal, renewed).is_ok());
4352		assert_eq!(request_grant.grant().expires, second_expires);
4353		let pending = kio::wait(|waiter| Poll::Ready(request_grant.poll_ended(waiter).is_pending())).await;
4354		assert!(pending, "the renewal holds the request");
4355	}
4356
4357	/// A refused renewal verdict is not applied: the request grant it already holds stands
4358	/// untouched and ends only when its own deadline lapses. The serve loops end the request on
4359	/// a refusal separately (a refused renewal ends only that request); this covers only that
4360	/// the grant object is not mutated.
4361	#[kio::test]
4362	async fn a_refused_renewal_leaves_the_grant() {
4363		let runtime = crate::time::sim();
4364		let handle = Link::new(true);
4365		let mut requests = handle.handle().requests();
4366		let verdict = handle.verify_request(token(b"jwt", 0), None);
4367		let first = grant_in(&runtime, 60);
4368		let first_expires = first.expires;
4369		let _issued = requests.next().await.unwrap().accept(first);
4370		let answered = verdict.grant().await.unwrap();
4371		let request_grant = RequestGrant::new(
4372			&runtime,
4373			verdict,
4374			Ok(answered),
4375			subscribe_path(),
4376			RequestKind::Subscribe,
4377			None,
4378		)
4379		.unwrap();
4380
4381		// The renewal token is refused, so it renews nothing and the old grant is untouched.
4382		let renewal = handle.verify_request(token(b"bad", 0), None);
4383		requests
4384			.next()
4385			.await
4386			.unwrap()
4387			.reject(SessionError::Unauthorized, "bad token");
4388		let refused = renewal.grant().await;
4389		assert!(
4390			matches!(&refused, Err(refusal) if matches!(refusal.error, Error::Session(SessionError::Unauthorized)) && refusal.reason == "bad token"),
4391			"the acceptor's code and reason reach the caller: {refused:?}"
4392		);
4393		assert!(
4394			request_grant.renew(renewal, refused).is_err(),
4395			"a refusal does not renew"
4396		);
4397
4398		// The old grant still stands with its original expiry, and the request ends only
4399		// when that lapses.
4400		assert_eq!(request_grant.grant().expires, first_expires);
4401		let err = kio::wait(|waiter| request_grant.poll_ended(waiter)).await.error;
4402		assert!(matches!(err, Error::Expired), "{err:?}");
4403	}
4404
4405	/// An acceptor-side update that no longer covers the request ends it, even when the
4406	/// replacement has no expiry to lapse at; one that still covers it is folded in.
4407	#[kio::test]
4408	async fn an_update_that_stops_covering_ends_the_request() {
4409		let runtime = crate::time::sim();
4410		let handle = Link::new(true);
4411		let mut requests = handle.handle().requests();
4412		let verdict = handle.verify_request(token(b"jwt", 0), None);
4413		let issued = requests.next().await.unwrap().accept(Grant::all());
4414		let answered = verdict.grant().await.unwrap();
4415		let request_grant = RequestGrant::new(
4416			&runtime,
4417			verdict,
4418			Ok(answered),
4419			subscribe_path(),
4420			RequestKind::Subscribe,
4421			None,
4422		)
4423		.unwrap();
4424
4425		// A covering update (everything, still unexpiring) leaves the request standing.
4426		issued.update(Grant::all());
4427		let pending = kio::wait(|waiter| Poll::Ready(request_grant.poll_ended(waiter).is_pending())).await;
4428		assert!(pending, "a covering update keeps the request");
4429
4430		issued.update(Grant::default());
4431		let err = kio::clock::timeout(
4432			Duration::from_secs(1),
4433			kio::wait(|waiter| request_grant.poll_ended(waiter)),
4434		)
4435		.await
4436		.expect("an uncovering update must end the request")
4437		.error;
4438		assert!(matches!(err, Error::Unauthorized), "{err:?}");
4439	}
4440
4441	/// The grant is the presenting peer's: a read is covered by `subscribe`, an announce by
4442	/// `publish`, never the other way around.
4443	#[test]
4444	fn request_coverage_is_from_the_presenters_side() {
4445		let read_only = Grant {
4446			publish: Prefixes::new(),
4447			subscribe: Prefixes::all(),
4448			expires: None,
4449		};
4450		let write_only = Grant {
4451			publish: Prefixes::all(),
4452			subscribe: Prefixes::new(),
4453			expires: None,
4454		};
4455		assert!(RequestKind::Subscribe.covers(&read_only, "room"));
4456		assert!(!RequestKind::Subscribe.covers(&write_only, "room"));
4457		assert!(RequestKind::PublishNamespace.covers(&write_only, "room"));
4458		assert!(!RequestKind::PublishNamespace.covers(&read_only, "room"));
4459	}
4460
4461	/// An announce routes its whole namespace, which the prefix naming it covers, and a
4462	/// namespace beneath it too, but not one above it or beside it.
4463	#[test]
4464	fn an_announce_needs_its_whole_subtree() {
4465		let room = Grant {
4466			publish: crate::Prefix::try_from("room").unwrap().into(),
4467			subscribe: Prefixes::new(),
4468			expires: None,
4469		};
4470		assert!(RequestKind::PublishNamespace.covers(&room, "room"));
4471		assert!(RequestKind::PublishNamespace.covers(&room, "room/cam"));
4472		assert!(!RequestKind::PublishNamespace.covers(&room, ""));
4473		assert!(!RequestKind::PublishNamespace.covers(&room, "other"));
4474		assert!(!RequestKind::PublishNamespace.covers(&room, "roomy"));
4475		// A path no prefix can spell is still covered by the prefix above it.
4476		assert!(RequestKind::PublishNamespace.covers(&room, "room/cam-*"));
4477	}
4478
4479	/// An acceptor-side revoke ends the request before the deadline, and does not close the
4480	/// session.
4481	#[kio::test]
4482	async fn an_acceptor_revoke_ends_the_request() {
4483		let runtime = crate::time::sim();
4484		let handle = Link::new(true);
4485		let mut requests = handle.handle().requests();
4486		let verdict = handle.verify_request(token(b"jwt", 0), None);
4487		// A grant that never expires, so only the revoke can end the request.
4488		let issued = requests.next().await.unwrap().accept(Grant::all());
4489		let answered = verdict.grant().await.unwrap();
4490		let request_grant = RequestGrant::new(
4491			&runtime,
4492			verdict,
4493			Ok(answered),
4494			subscribe_path(),
4495			RequestKind::Subscribe,
4496			None,
4497		)
4498		.unwrap();
4499
4500		issued.revoke(SessionError::Unauthorized, "revoked");
4501		let refusal = kio::wait(|waiter| request_grant.poll_ended(waiter)).await;
4502		assert!(
4503			matches!(refusal.error, Error::Session(SessionError::Unauthorized)),
4504			"{refusal:?}"
4505		);
4506		assert_eq!(refusal.reason, "revoked", "the acceptor's reason is kept");
4507		assert_eq!(handle.handle().grant().peek(), None, "the session grant is untouched");
4508	}
4509}