Skip to main content

moq_net/auth/
tokens.rs

1//! The tokens a reconnecting connection presents on each session, and the peer's answer.
2
3use std::task::Poll;
4
5use bytes::Bytes;
6use url::Url;
7
8use super::{Answer, Handle, State};
9use crate::{Error, Result};
10
11/// A credential to present when dialing, such as a JWT.
12///
13/// Its `Debug` shows only the length, so a dumped config never leaks it.
14#[derive(Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
15#[serde(try_from = "String", into = "String")]
16pub struct Token(String);
17
18impl Token {
19	/// The credential itself.
20	pub fn as_str(&self) -> &str {
21		&self.0
22	}
23}
24
25impl std::fmt::Debug for Token {
26	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
27		write!(f, "Token(<{} bytes>)", self.0.len())
28	}
29}
30
31impl std::str::FromStr for Token {
32	type Err = EmptyToken;
33
34	fn from_str(token: &str) -> std::result::Result<Self, Self::Err> {
35		Self::try_from(token.to_string())
36	}
37}
38
39impl TryFrom<String> for Token {
40	type Error = EmptyToken;
41
42	fn try_from(token: String) -> std::result::Result<Self, Self::Error> {
43		match token.is_empty() {
44			true => Err(EmptyToken),
45			false => Ok(Self(token)),
46		}
47	}
48}
49
50impl From<Token> for String {
51	fn from(token: Token) -> Self {
52		token.0
53	}
54}
55
56/// An empty token, which presents no credential.
57#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)]
58#[error("a token cannot be empty")]
59#[non_exhaustive]
60pub struct EmptyToken;
61
62/// The tokens a connection presents on every session it dials, and the peer's answer to them.
63///
64/// The first is the connection credential, which each dial carries in SETUP or its URL,
65/// unless the URL already has a `?jwt=`. Every other token rides its own AUTH stream on the
66/// sessions of [`handle`](Self::handle), widening the grant. Replacing them presents the new
67/// ones on the live session at once, withdrawing the granted ones they replace only after
68/// every new one has its answer, so the grant never narrows in between.
69///
70/// [`Reconnect::with_tokens`](crate::Reconnect::with_tokens) presents them on every dial,
71/// whose [`Attempt::client`](crate::reconnect::Attempt::client) builds each session on
72/// [`handle`](Self::handle); aborting the handle ends the policy.
73///
74/// Cheap to clone; every clone shares one set.
75#[derive(Clone)]
76pub struct Tokens {
77	handle: Handle,
78}
79
80/// What one dial presents, from [`Tokens::preview`].
81pub(crate) struct Dial {
82	/// The connection credential to present in SETUP and, where an offered version cannot
83	/// carry it there, the URL's query ([`locate`]), unless the URL brought its own.
84	pub(crate) token: Option<String>,
85	/// The connection credential, held out of band rather than in an AUTH stream.
86	connection: Option<String>,
87	/// The set a [`Dials`](crate::reconnect::Dials) answer signed for this dial alone, which
88	/// replaces every token once it is committed.
89	signed: Option<Vec<Token>>,
90}
91
92impl Tokens {
93	/// Present `tokens` on the sessions of a new [`handle`](Self::handle).
94	pub fn new(tokens: Vec<Token>) -> Self {
95		let handle = Handle::new();
96		handle.state.lock().configured = Some(Configured {
97			fresh: dedup(&tokens),
98			tokens,
99			..Default::default()
100		});
101		Self { handle }
102	}
103
104	/// The handle each session is built on, with [`Client::with_auth`](crate::Client::with_auth).
105	pub fn handle(&self) -> Handle {
106		self.handle.clone()
107	}
108
109	/// Replace every token, reaching the live session at once and every later dial.
110	pub fn set(&self, tokens: Vec<Token>) {
111		let mut state = self.handle.state.lock();
112		if state.replace(tokens) {
113			state.hold();
114		}
115	}
116
117	/// The peer's first verdict on the tokens the last [`set`](Self::set) newly presented,
118	/// or on the initial tokens before any set: `Ok` once each is granted, in band or as the
119	/// connection credential a later dial carried.
120	///
121	/// A token the set kept, the connection credential included, counts only once the peer
122	/// refuses it. Nothing is re-checked after the answer: a later revocation, or a new
123	/// session that refuses a token an earlier one granted, does not change it.
124	///
125	/// # Errors
126	///
127	/// The peer's refusal of a token as [`Error::Session`], [`Error::Unsupported`] when the
128	/// session cannot carry an in-band token, or the connection's end, such as a refused dial.
129	#[cfg_attr(feature = "async", kio::wrapper)]
130	pub fn poll_answered(&self, waiter: &kio::Waiter) -> Poll<Result<()>> {
131		let answer = |state: &State| {
132			state
133				.configured
134				.as_ref()
135				.and_then(|configured| configured.answer(state))
136		};
137		let mut state = match self.handle.state.poll(waiter, |state| match answer(state) {
138			Some(_) => Poll::Ready(()),
139			None => Poll::Pending,
140		}) {
141			Poll::Ready(state) => state,
142			Poll::Pending => return Poll::Pending,
143		};
144		state.record();
145		Poll::Ready(answer(&state).expect("checked answered"))
146	}
147
148	/// Decide what a dial to `url` would present, leaving the live session's tokens untouched
149	/// until [`commit`](Self::commit).
150	pub(crate) fn preview(&self, url: &Url) -> Dial {
151		let state = self.handle.state.read();
152		let configured = state.configured.as_ref().expect("built by Tokens::new");
153		let (token, connection) = credential(url, &configured.tokens);
154		Dial {
155			token,
156			connection,
157			signed: None,
158		}
159	}
160
161	/// What a dial to `url` presenting `tokens`, signed for it alone, would present. Committing
162	/// it replaces every token, under the same lock that makes it the latest dial, so its
163	/// connection credential never rides AUTH on a session still draining.
164	pub(crate) fn preview_signed(url: &Url, tokens: Vec<Token>) -> Dial {
165		let (token, connection) = credential(url, &tokens);
166		Dial {
167			token,
168			connection,
169			signed: Some(tokens),
170		}
171	}
172
173	/// Make `dial` the latest, holding every token but its connection credential in band on the
174	/// session it builds.
175	pub(crate) fn commit(&self, dial: &Dial) {
176		let mut state = self.handle.state.lock();
177		// The verdict so far belongs to the set being replaced, so it is recorded first.
178		state.record();
179		if let Some(tokens) = &dial.signed {
180			state.replace(tokens.clone());
181		}
182		let configured = state.configured.as_mut().expect("built by Tokens::new");
183		configured.dialed = Some(dial.connection.clone());
184		configured.session = None;
185		configured.unsupported = false;
186		state.hold();
187	}
188
189	/// The session the latest [`commit`](Self::commit)ted dial built on [`handle`](Self::handle), once it
190	/// connected, whose own answer to the connection credential then counts. A session built
191	/// on another handle answers nothing here.
192	#[cfg(feature = "async")]
193	pub(crate) fn connected(&self, session: &crate::Session) {
194		if session.auth().state.is_clone(&self.handle.state) {
195			self.connect(session.link().id(), session.credential());
196		}
197	}
198
199	/// Bind the session on `link`, even one that already closed: that close may be its answer.
200	fn connect(&self, link: u64, credential: Option<&super::Credential>) {
201		let mut state = self.handle.state.lock();
202		state.record();
203		let connected = match credential {
204			Some(auth) => Connected::Slot {
205				link,
206				id: auth.presented.id,
207			},
208			None => Connected::Accepted { link },
209		};
210		state.configured.as_mut().expect("built by Tokens::new").session = Some(connected);
211		// A session that closed before this bound it has its answer already.
212		state.record();
213	}
214}
215
216/// The configured tokens a [`Tokens`] presents, kept on its handle's state so each verdict
217/// a session records reaches them under the same lock.
218#[derive(Default)]
219pub(super) struct Configured {
220	tokens: Vec<Token>,
221	/// The latest dial's connection credential, never also held in band. `None` before the
222	/// first dial.
223	dialed: Option<Option<String>>,
224	/// The tokens held on their own AUTH streams, by their id among the handle's tokens.
225	held: Vec<(Token, u64)>,
226	/// Tokens a change replaced, kept presented until every held token has its answer.
227	retiring: Vec<u64>,
228	/// The latest dial's session, once it connected.
229	session: Option<Connected>,
230	/// The tokens the latest sets newly presented whose verdict is not yet known.
231	fresh: Vec<Token>,
232	/// The first verdict on the latest set.
233	answer: Option<Result<()>>,
234	/// Whether the latest dial already logged that its session takes no tokens in band.
235	unsupported: bool,
236}
237
238/// How the latest dial's session answers its connection credential.
239enum Connected {
240	/// The version has no AUTH, so the peer accepted it with its handshake, or with its
241	/// SETUP when the session [awaits it](super::Link::await_acceptance).
242	Accepted { link: u64 },
243	/// Its own AUTH stream on that session.
244	Slot { link: u64, id: u64 },
245}
246
247impl Configured {
248	/// The latest dial's connection credential, when the tokens still name it.
249	fn named(&self) -> Option<&str> {
250		let connection = self.dialed.as_ref()?.as_deref()?;
251		self.tokens
252			.iter()
253			.any(|token| token.as_str() == connection)
254			.then_some(connection)
255	}
256
257	/// The peer's verdict on the connection credential, `None` while it has none or no
258	/// session is live.
259	fn credential(&self, state: &State) -> Option<Result<()>> {
260		let (link, id) = match self.session.as_ref()? {
261			Connected::Slot { link, id } => (link, id),
262			Connected::Accepted { link } => {
263				let link = state.links.get(link)?;
264				let awaiting = link.acceptance == super::Acceptance::Awaiting;
265				return match (awaiting, &link.closed) {
266					// Accepted, or a version that never answers, whose live session counts as accepting it.
267					(false, _) => Some(Ok(())),
268					// Closed before accepting it: the close is the answer, since the connection
269					// keeps redialing with the same credential and nothing else would answer.
270					(true, Some(err)) => Some(Err(err.clone())),
271					(true, None) => None,
272				};
273			}
274		};
275		let link = state.links.get(link)?;
276		if let Some(err) = &link.closed {
277			// Cut off unanswered, like a session that closed before accepting it.
278			return link.cut.contains(id).then(|| Err(err.clone()));
279		}
280		let slot = link.slots.get(id)?;
281		match slot.phase.ended() {
282			// The moq-transport SETUP that carried it accepted it before the peer declined AUTH.
283			Some(Error::Unsupported) => Some(Ok(())),
284			Some(err) => Some(Err(err.clone())),
285			None if slot.phase.answered() => Some(Ok(())),
286			// Unanswered, or waiting out a refusal that may pass.
287			None => None,
288		}
289	}
290
291	/// The peer's verdict on a token the set newly presented, `None` while it has none.
292	fn verdict(&self, state: &State, token: &Token) -> Option<Result<()>> {
293		if let Some((_, id)) = self.held.iter().find(|(held, _)| held == token) {
294			return match state.tokens.get(id)?.answered.clone()? {
295				Ok(Answer::Granted) => Some(Ok(())),
296				// Taken only for the requests that name it, and a configured token rides none.
297				Ok(Answer::Requests) => Some(Err(Error::Unsupported)),
298				Err(err) => Some(Err(err)),
299			};
300		}
301		match self.named() == Some(token.as_str()) {
302			true => self.credential(state),
303			// Not presented until the first dial.
304			false => None,
305		}
306	}
307
308	/// The answer to the latest set: the first refusal of any token it names, or `Ok` once
309	/// every fresh token is granted. `None` while one still waits.
310	fn answer(&self, state: &State) -> Option<Result<()>> {
311		if let Some(answer) = &self.answer {
312			return Some(answer.clone());
313		}
314		if let Some(err) = &state.closed {
315			return Some(Err(err.clone()));
316		}
317		let held = self
318			.held
319			.iter()
320			.filter_map(|(_, id)| state.tokens.get(id)?.ended.clone());
321		let credential = self.named().and_then(|_| self.credential(state)?.err());
322		if let Some(err) = held.chain(credential).next() {
323			return Some(Err(err));
324		}
325		let mut waiting = false;
326		for token in &self.fresh {
327			match self.verdict(state, token) {
328				Some(Ok(())) => {}
329				Some(Err(err)) => return Some(Err(err)),
330				None => waiting = true,
331			}
332		}
333		(!waiting).then_some(Ok(()))
334	}
335}
336
337impl State {
338	/// Replace every configured token with `tokens`, returning whether that changed them. A
339	/// token still waiting on its verdict stays fresh when the new set keeps it.
340	fn replace(&mut self, tokens: Vec<Token>) -> bool {
341		let configured = self.configured.as_ref().expect("built by Tokens::new");
342		if configured.tokens == tokens {
343			return false;
344		}
345		let fresh = dedup(&tokens)
346			.into_iter()
347			.filter(|token| {
348				!configured.tokens.contains(token)
349					|| (configured.fresh.contains(token) && configured.verdict(self, token).is_none())
350			})
351			.collect();
352		let configured = self.configured.as_mut().expect("built by Tokens::new");
353		configured.fresh = fresh;
354		configured.tokens = tokens;
355		configured.answer = None;
356		true
357	}
358
359	/// Whether token `id` is one a [`Tokens`] holds in band.
360	pub(super) fn configured(&self, id: u64) -> bool {
361		self.configured
362			.as_ref()
363			.is_some_and(|configured| configured.held.iter().any(|(_, held)| *held == id))
364	}
365
366	/// Configured token `id` rides nothing on this session, which the latest dial logs once.
367	pub(super) fn unsupported(&mut self, id: u64) {
368		if !self.configured(id) {
369			return;
370		}
371		let configured = self.configured.as_mut().expect("checked configured");
372		if !std::mem::replace(&mut configured.unsupported, true) {
373			tracing::debug!("the peer takes no tokens in band; presenting only the connection credential");
374		}
375	}
376
377	/// Keep each verdict the latest set has so far, before a dial, a new session, or a
378	/// dropped one takes away where it came from.
379	pub(super) fn record(&mut self) {
380		let Some(configured) = &self.configured else { return };
381		if configured.answer.is_some() {
382			return;
383		}
384		let answer = configured.answer(self);
385		let granted: Vec<Token> = configured
386			.fresh
387			.iter()
388			.filter(|token| matches!(configured.verdict(self, token), Some(Ok(()))))
389			.cloned()
390			.collect();
391		let configured = self.configured.as_mut().expect("checked configured");
392		match answer {
393			Some(answer) => {
394				if answer.is_ok() {
395					configured.fresh.clear();
396				}
397				configured.answer = Some(answer);
398			}
399			None => configured.fresh.retain(|token| !granted.contains(token)),
400		}
401	}
402
403	/// Hold every configured token but the latest dial's connection credential in band,
404	/// presenting the new ones and retiring the ones no longer configured.
405	pub(super) fn hold(&mut self) {
406		let Some(configured) = &self.configured else { return };
407		let Some(connection) = configured.dialed.clone() else {
408			return;
409		};
410		let tokens: Vec<Token> = dedup(&configured.tokens)
411			.into_iter()
412			.filter(|token| Some(token.as_str()) != connection.as_deref())
413			.collect();
414		let mut held = Vec::with_capacity(tokens.len());
415		let mut presented = Vec::new();
416		for token in tokens {
417			let configured = self.configured.as_ref().expect("checked configured");
418			let id = match configured.held.iter().find(|(kept, _)| *kept == token) {
419				Some((_, id)) => *id,
420				None => {
421					let id = self.present(Bytes::from(token.as_str().to_string()));
422					presented.push(id);
423					id
424				}
425			};
426			held.push((token, id));
427		}
428		let configured = self.configured.as_mut().expect("checked configured");
429		let old = std::mem::replace(&mut configured.held, held);
430		for (_, id) in old {
431			if self.configured(id) {
432				continue;
433			}
434			// Only a token holding a grant keeps the grant wide; one refused or unanswered, such
435			// as one retrying while its backend fails, is withdrawn at once so repeated sets
436			// never pile up retrying streams.
437			let granted = self
438				.links
439				.values()
440				.any(|link| link.slots.get(&id).is_some_and(|slot| slot.phase.grant().is_some()));
441
442			match granted {
443				true => self.configured.as_mut().expect("checked configured").retiring.push(id),
444				false => self.withdraw(id),
445			}
446		}
447		// A session without AUTH answers a new token at once, before it was held.
448		for id in presented {
449			let answered = self.tokens.get(&id).and_then(|entry| entry.answered.as_ref());
450			if let Some(Ok(Answer::Requests) | Err(Error::Unsupported)) = answered {
451				self.unsupported(id);
452			}
453		}
454		self.settle();
455	}
456
457	/// Withdraw the replaced tokens once every held token has its answer.
458	pub(super) fn settle(&mut self) {
459		let Some(configured) = &self.configured else { return };
460		if configured.retiring.is_empty()
461			|| configured
462				.held
463				.iter()
464				.any(|(_, id)| self.tokens.get(id).is_some_and(|entry| entry.answered.is_none()))
465		{
466			return;
467		}
468		let retiring = std::mem::take(&mut self.configured.as_mut().expect("checked configured").retiring);
469		for id in retiring {
470			self.withdraw(id);
471		}
472	}
473}
474
475/// Each of `tokens` once, in order.
476fn dedup(tokens: &[Token]) -> Vec<Token> {
477	let mut unique: Vec<Token> = Vec::with_capacity(tokens.len());
478	for token in tokens {
479		if !unique.contains(token) {
480			unique.push(token.clone());
481		}
482	}
483	unique
484}
485
486/// What a dial to `url` presents: the URL to dial, the token SETUP carries, and the
487/// connection credential, which is never also held in band.
488fn credential(url: &Url, tokens: &[Token]) -> (Option<String>, Option<String>) {
489	if let Some(jwt) = jwt(url) {
490		// The URL's own credential (a cluster's per-peer `?jwt=`) wins, so the tokens all
491		// ride AUTH and no second credential reaches SETUP or the query.
492		return (None, Some(jwt));
493	}
494	let first = tokens.first().map(|first| first.as_str().to_string());
495	(first.clone(), first)
496}
497
498/// `url` for a dial offering `versions` that presents `credential`. The URL is fixed before
499/// the version is negotiated, so it carries the credential whenever a version that may be
500/// picked could not carry it in SETUP.
501#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
502pub(crate) fn locate(url: &Url, credential: &str, versions: &crate::Versions) -> Url {
503	match versions.iter().all(|version| version.has_setup_token()) {
504		true => url.clone(),
505		false => with_jwt(url, credential),
506	}
507}
508
509/// The request target's query: the URL's own, or for `unix:` the one inside `?path=`.
510fn target_query(url: &Url) -> Option<String> {
511	match url.scheme() {
512		"unix" => url
513			.query_pairs()
514			.find(|(k, _)| k == "path")
515			.and_then(|(_, path)| path.split_once('?').map(|(_, query)| query.to_string())),
516		_ => url.query().map(str::to_string),
517	}
518}
519
520/// The non-empty `jwt` the URL's request target already carries.
521fn jwt(url: &Url) -> Option<String> {
522	let query = target_query(url)?;
523	url::form_urlencoded::parse(query.as_bytes())
524		.find(|(k, v)| k == "jwt" && !v.is_empty())
525		.map(|(_, v)| v.into_owned())
526}
527
528/// `url` with `jwt` appended to its request target's query.
529#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
530fn with_jwt(url: &Url, jwt: &str) -> Url {
531	let mut url = url.clone();
532	if url.scheme() != "unix" {
533		url.query_pairs_mut().append_pair("jwt", jwt);
534		return url;
535	}
536	// A unix socket's request target is one form-encoded `?path=` value, so the
537	// credential joins the query inside it.
538	let pairs: Vec<(String, String)> = url.query_pairs().into_owned().collect();
539	let mut serializer = url::form_urlencoded::Serializer::new(String::new());
540	let mut found = false;
541	for (k, v) in &pairs {
542		match k == "path" {
543			true => {
544				found = true;
545				let mut target = url::form_urlencoded::Serializer::new(String::new());
546				target.append_pair("jwt", jwt);
547				let separator = if v.contains('?') { '&' } else { '?' };
548				serializer.append_pair(k, &format!("{v}{separator}{}", target.finish()));
549			}
550			false => {
551				serializer.append_pair(k, v);
552			}
553		}
554	}
555	if !found {
556		let mut target = url::form_urlencoded::Serializer::new(String::new());
557		target.append_pair("jwt", jwt);
558		serializer.append_pair("path", &format!("?{}", target.finish()));
559	}
560	url.set_query(Some(&serializer.finish()));
561	url
562}
563
564#[cfg(test)]
565mod tests {
566	use super::*;
567	use crate::{
568		SessionError,
569		auth::{Credential, Grant, Link},
570	};
571
572	fn tokens(names: &[&str]) -> Vec<Token> {
573		names.iter().map(|name| name.parse().unwrap()).collect()
574	}
575
576	fn versions(names: &[&str]) -> crate::Versions {
577		names
578			.iter()
579			.map(|name| name.parse::<crate::Version>().unwrap())
580			.collect::<Vec<_>>()
581			.into()
582	}
583
584	/// One session a dial built on the handle, with AUTH when `supported`, and moq-transport
585	/// requests when `requests`.
586	struct Session {
587		link: Link,
588		credential: Option<Credential>,
589	}
590
591	fn dial(set: &Tokens, supported: bool, requests: bool) -> Session {
592		let presented = set.preview(&"moqt://relay.example.com/".parse().unwrap());
593		set.commit(&presented);
594		let link = Link::attach(&set.handle, supported, requests).unwrap();
595		let credential = supported.then(|| link.present(Bytes::new(), true).unwrap());
596		set.connect(link.id(), credential.as_ref());
597		Session { link, credential }
598	}
599
600	impl Session {
601		fn credential(&self) -> u64 {
602			self.credential.as_ref().unwrap().id()
603		}
604
605		fn grant_credential(&self) {
606			self.link.grant(self.credential(), Grant::all());
607		}
608
609		/// The peer refuses or revokes the token presented as `id`, as the driver reports it.
610		fn refuse(&self, id: u64, code: SessionError) {
611			let reply = crate::lite::AuthError {
612				code: crate::lite::error::to_session_code(&code).into(),
613				reason: String::new(),
614			};
615			let err = Error::Session(code);
616			self.link.open(id);
617			self.link.refused(id, reply.undecided());
618			if self.link.retry(id, &err).is_none() {
619				self.link.ended(id, err);
620			}
621		}
622
623		fn lost(self) {
624			self.link.close(Error::Transport("lost".into()));
625		}
626	}
627
628	/// The id a configured token is held under.
629	fn id(set: &Tokens, name: &str) -> u64 {
630		let state = set.handle.state.read();
631		let held = &state.configured.as_ref().unwrap().held;
632		held.iter()
633			.find(|(token, _)| token.as_str() == name)
634			.expect("not held")
635			.1
636	}
637
638	fn held(set: &Tokens) -> Vec<String> {
639		let state = set.handle.state.read();
640		let held = &state.configured.as_ref().unwrap().held;
641		held.iter().map(|(token, _)| token.as_str().to_string()).collect()
642	}
643
644	fn presented(set: &Tokens, id: u64) -> bool {
645		set.handle.state.read().tokens.contains_key(&id)
646	}
647
648	fn answered(set: &Tokens) -> Poll<Result<()>> {
649		set.poll_answered(&kio::Waiter::noop())
650	}
651
652	fn ok(set: &Tokens) {
653		let answer = answered(set);
654		assert!(matches!(answer, Poll::Ready(Ok(()))), "{answer:?}");
655	}
656
657	fn refused(set: &Tokens, code: SessionError) {
658		let answer = answered(set);
659		assert!(
660			matches!(&answer, Poll::Ready(Err(Error::Session(refused))) if *refused == code),
661			"{answer:?}"
662		);
663	}
664
665	/// Every token but the connection credential is held in band, each once.
666	#[test]
667	fn only_the_extra_tokens_ride_auth() {
668		let set = Tokens::new(tokens(&["connection", "a", "b", "a"]));
669		let _session = dial(&set, true, false);
670		assert_eq!(held(&set), ["a", "b"]);
671	}
672
673	/// A replaced token is withdrawn only once its replacement has an answer, so the grant
674	/// never narrows in between, and that answer is the set's.
675	#[test]
676	fn a_replacement_retires_what_it_replaced_once_answered() {
677		let set = Tokens::new(tokens(&["connection", "old"]));
678		let session = dial(&set, true, false);
679		session.grant_credential();
680		let old = id(&set, "old");
681		session.link.grant(old, Grant::all());
682		ok(&set);
683
684		set.set(tokens(&["connection", "new"]));
685		assert!(answered(&set).is_pending(), "answered before the replacement was");
686		assert!(presented(&set, old), "withdrawn before its replacement was answered");
687
688		session.link.grant(id(&set, "new"), Grant::all());
689		ok(&set);
690		assert!(!presented(&set, old), "the replaced token was never withdrawn");
691	}
692
693	/// A dial built on a signed set, as [`dial`] is on the configured one.
694	fn signed(set: &Tokens, names: &[&str]) -> Session {
695		let url = "moqt://relay.example.com/".parse().unwrap();
696		set.commit(&Tokens::preview_signed(&url, tokens(names)));
697		let link = Link::attach(&set.handle, true, false).unwrap();
698		let credential = Some(link.present(Bytes::new(), true).unwrap());
699		set.connect(link.id(), credential.as_ref());
700		Session { link, credential }
701	}
702
703	/// A refusal of the set a signed dial replaced stays that set's: the new one is judged alone.
704	#[test]
705	fn a_signed_set_is_judged_apart_from_the_set_it_replaced() {
706		let set = Tokens::new(Vec::new());
707		let first = signed(&set, &["first", "extra-1"]);
708		first.grant_credential();
709		first.refuse(id(&set, "extra-1"), SessionError::Unauthorized);
710		refused(&set, SessionError::Unauthorized);
711		first.lost();
712
713		let second = signed(&set, &["second", "extra-2"]);
714		assert!(
715			answered(&set).is_pending(),
716			"the replaced set's refusal answered the new one"
717		);
718		second.grant_credential();
719		second.link.grant(id(&set, "extra-2"), Grant::all());
720		ok(&set);
721	}
722
723	/// A signed set replaces the tokens only as its dial commits, so a session still draining
724	/// never takes the new connection credential in band, and its own was never held.
725	#[test]
726	fn a_signed_dial_replaces_the_tokens_as_it_commits() {
727		let set = Tokens::new(Vec::new());
728		let _draining = dial(&set, true, false);
729		let url = "moqt://relay.example.com/".parse().unwrap();
730		let signed = Tokens::preview_signed(&url, tokens(&["proof-2", "extra"]));
731		assert_eq!(signed.token.as_deref(), Some("proof-2"));
732		assert!(held(&set).is_empty(), "a preview changed the held tokens");
733
734		set.commit(&signed);
735		assert_eq!(held(&set), ["extra"], "the connection credential rode AUTH");
736		let state = set.handle.state.read();
737		assert_eq!(state.configured.as_ref().unwrap().tokens, tokens(&["proof-2", "extra"]));
738	}
739
740	/// Previewing a dial, as a probe does, leaves the live session's grant alone: a rotated
741	/// connection credential it holds in band stays presented until the dial is committed.
742	#[test]
743	fn a_preview_leaves_the_live_grant_alone() {
744		let set = Tokens::new(tokens(&["first", "extra"]));
745		let session = dial(&set, true, false);
746		session.grant_credential();
747		set.set(tokens(&["second", "extra"]));
748		let second = id(&set, "second");
749		session.link.grant(second, Grant::all());
750
751		let url = "moqt://relay.example.com/".parse().unwrap();
752		let preview = set.preview(&url);
753		assert!(presented(&set, second), "a preview withdrew a granted token");
754		assert_eq!(held(&set), ["second", "extra"]);
755
756		set.commit(&preview);
757		assert_eq!(
758			held(&set),
759			["extra"],
760			"the committed dial carries the credential itself"
761		);
762	}
763
764	/// A replacement replaced again before its answer added nothing to the grant, so it is
765	/// withdrawn at once: sets while a backend keeps failing never pile up retrying tokens.
766	#[test]
767	fn an_unanswered_replacement_is_withdrawn_when_replaced() {
768		let set = Tokens::new(tokens(&["connection", "old"]));
769		let session = dial(&set, true, false);
770		session.grant_credential();
771		let old = id(&set, "old");
772		session.link.grant(old, Grant::all());
773
774		set.set(tokens(&["connection", "first"]));
775		let first = id(&set, "first");
776		session.refuse(first, SessionError::Internal);
777		set.set(tokens(&["connection", "second"]));
778		assert!(!presented(&set, first), "the unanswered replacement is still presented");
779		assert!(presented(&set, old), "the granted token was withdrawn before an answer");
780		assert_eq!(set.handle.state.read().configured.as_ref().unwrap().retiring, [old]);
781
782		session.link.grant(id(&set, "second"), Grant::all());
783		ok(&set);
784		assert!(!presented(&set, old));
785	}
786
787	/// A token first taken only for requests, then granted on a session with AUTH, keeps the
788	/// grant wide until its replacement answers.
789	#[test]
790	fn a_token_granted_after_a_requests_answer_retires() {
791		let set = Tokens::new(tokens(&["connection", "old"]));
792		let first = dial(&set, false, true);
793		let old = id(&set, "old");
794		first.lost();
795		let session = dial(&set, true, false);
796		session.grant_credential();
797		session.link.grant(old, Grant::all());
798
799		set.set(tokens(&["connection", "new"]));
800		assert!(presented(&set, old), "withdrawn before its replacement was answered");
801		session.link.grant(id(&set, "new"), Grant::all());
802		assert!(!presented(&set, old));
803	}
804
805	/// A replacement is authoritative: its refusal is the answer, and still withdraws what it
806	/// replaced.
807	#[test]
808	fn a_refused_replacement_still_retires_what_it_replaced() {
809		let set = Tokens::new(tokens(&["connection", "old"]));
810		let session = dial(&set, true, false);
811		session.grant_credential();
812		let old = id(&set, "old");
813		session.link.grant(old, Grant::all());
814
815		set.set(tokens(&["connection", "new"]));
816		session.refuse(id(&set, "new"), SessionError::Unauthorized);
817		refused(&set, SessionError::Unauthorized);
818		assert!(
819			!presented(&set, old),
820			"the replaced token outlived its refused replacement"
821		);
822	}
823
824	/// An extra token granted first is no answer to a fresh connection credential, whose own
825	/// refusal is the answer even while its session stays open.
826	#[test]
827	fn the_connection_credential_answers_for_itself() {
828		let set = Tokens::new(tokens(&["connection", "a"]));
829		let session = dial(&set, true, false);
830		session.link.grant(id(&set, "a"), Grant::all());
831		assert!(answered(&set).is_pending(), "answered before the credential was");
832
833		session.refuse(session.credential(), SessionError::Unauthorized);
834		refused(&set, SessionError::Unauthorized);
835	}
836
837	/// A refusal that may pass presents the credential again, which answers nothing until
838	/// the retry is answered.
839	#[test]
840	fn a_transient_refusal_of_the_credential_waits_for_its_retry() {
841		let set = Tokens::new(tokens(&["connection"]));
842		let session = dial(&set, true, false);
843		session.refuse(session.credential(), SessionError::Internal);
844		assert!(answered(&set).is_pending(), "answered before the retry was");
845
846		session.link.reopen(session.credential()).unwrap();
847		session.grant_credential();
848		ok(&set);
849	}
850
851	/// The first verdict is the answer even when nothing polled it before a revocation or
852	/// the connection's end.
853	#[test]
854	fn a_granted_set_keeps_its_answer_when_revoked_before_it_is_read() {
855		let set = Tokens::new(tokens(&["connection", "a"]));
856		let session = dial(&set, true, false);
857		session.grant_credential();
858		session.link.grant(id(&set, "a"), Grant::all());
859		session.refuse(id(&set, "a"), SessionError::Unauthorized);
860		ok(&set);
861
862		set.set(tokens(&["connection", "b"]));
863		session.link.grant(id(&set, "b"), Grant::all());
864		set.handle().abort(Error::Session(SessionError::Unauthorized));
865		ok(&set);
866	}
867
868	/// A session without AUTH that awaits the server's SETUP, as a moq-lite-05/06 client does.
869	fn dial_awaiting_setup(set: &Tokens) -> Link {
870		let presented = set.preview(&"moqt://relay.example.com/".parse().unwrap());
871		set.commit(&presented);
872		let link = Link::attach(&set.handle, false, false).unwrap();
873		link.await_acceptance();
874		set.connect(link.id(), None);
875		link
876	}
877
878	/// Without AUTH, the server's SETUP is what accepts the connection credential.
879	#[test]
880	fn a_credential_without_auth_is_accepted_by_the_server_setup() {
881		let set = Tokens::new(tokens(&["connection"]));
882		let link = dial_awaiting_setup(&set);
883		assert!(answered(&set).is_pending(), "accepted before the server's SETUP");
884		link.accepted();
885		ok(&set);
886	}
887
888	/// A server that refuses the credential before its SETUP grants nothing, even though
889	/// the session was live.
890	#[test]
891	fn a_credential_refused_before_the_server_setup_is_no_grant() {
892		let set = Tokens::new(tokens(&["connection"]));
893		let link = dial_awaiting_setup(&set);
894		link.close(Error::Session(SessionError::Unauthorized));
895		refused(&set, SessionError::Unauthorized);
896	}
897
898	/// A refusal that closes the session before the reconnect loop binds it still answers.
899	#[test]
900	fn a_credential_refused_before_the_session_is_bound_is_no_grant() {
901		let set = Tokens::new(tokens(&["connection"]));
902		let presented = set.preview(&"moqt://relay.example.com/".parse().unwrap());
903		set.commit(&presented);
904		let link = Link::attach(&set.handle, false, false).unwrap();
905		link.await_acceptance();
906		link.close(Error::Session(SessionError::Unauthorized));
907		set.connect(link.id(), None);
908		refused(&set, SessionError::Unauthorized);
909	}
910
911	/// The connection credential revoked after its grant refuses a later set that keeps it.
912	#[test]
913	fn a_kept_credential_revoked_after_its_grant_refuses_the_next_set() {
914		let set = Tokens::new(tokens(&["connection", "a", "b"]));
915		let session = dial(&set, true, false);
916		session.grant_credential();
917		session.link.grant(id(&set, "a"), Grant::all());
918		session.link.grant(id(&set, "b"), Grant::all());
919		ok(&set);
920
921		session.refuse(session.credential(), SessionError::Unauthorized);
922		set.set(tokens(&["connection", "a"]));
923		refused(&set, SessionError::Unauthorized);
924	}
925
926	/// A kept token revoked after its grant refuses a later set that keeps it.
927	#[test]
928	fn a_kept_token_revoked_after_its_grant_refuses_the_next_set() {
929		let set = Tokens::new(tokens(&["connection", "a", "b"]));
930		let session = dial(&set, true, false);
931		session.grant_credential();
932		session.link.grant(id(&set, "a"), Grant::all());
933		session.link.grant(id(&set, "b"), Grant::all());
934		ok(&set);
935
936		session.refuse(id(&set, "a"), SessionError::Unauthorized);
937		set.set(tokens(&["connection", "a"]));
938		refused(&set, SessionError::Unauthorized);
939	}
940
941	/// A set that only keeps tokens answers at once after reconnecting to a moq-transport
942	/// peer without AUTH, which grants nothing in band.
943	#[test]
944	fn a_kept_set_answers_at_once_on_a_session_without_auth() {
945		let set = Tokens::new(tokens(&["connection", "a", "b"]));
946		let first = dial(&set, true, false);
947		first.grant_credential();
948		first.link.grant(id(&set, "a"), Grant::all());
949		first.link.grant(id(&set, "b"), Grant::all());
950		first.lost();
951
952		let _second = dial(&set, false, true);
953		set.set(tokens(&["connection", "a"]));
954		ok(&set);
955	}
956
957	/// A kept token counts only by refusal: one a moq-transport session without AUTH took
958	/// only for requests is no refusal once a later session grants it.
959	#[test]
960	fn a_kept_token_is_judged_only_by_refusal() {
961		let set = Tokens::new(tokens(&["connection", "a", "b"]));
962		let first = dial(&set, false, true);
963		let answer = answered(&set);
964		assert!(
965			matches!(answer, Poll::Ready(Err(Error::Unsupported))),
966			"a session without AUTH carried a token in band: {answer:?}"
967		);
968		first.lost();
969
970		let second = dial(&set, true, false);
971		second.grant_credential();
972		second.link.grant(id(&set, "a"), Grant::all());
973		set.set(tokens(&["connection", "a"]));
974		ok(&set);
975	}
976
977	/// A token set while offline becomes the next dial's connection credential, never also
978	/// held in band, and that session's answer to it is the set's.
979	#[test]
980	fn a_set_while_offline_is_answered_by_the_next_credential() {
981		let set = Tokens::new(tokens(&["old"]));
982		let first = dial(&set, true, false);
983		first.grant_credential();
984		first.lost();
985
986		set.set(tokens(&["new"]));
987		assert!(answered(&set).is_pending(), "answered while offline");
988		let second = dial(&set, true, false);
989		assert!(held(&set).is_empty(), "the credential is also held in band");
990		assert!(answered(&set).is_pending(), "answered before the credential was");
991		second.grant_credential();
992		ok(&set);
993	}
994
995	/// A token granted in band keeps its verdict when a later dial moves it to SETUP.
996	#[test]
997	fn a_granted_token_keeps_its_verdict_as_the_next_credential() {
998		let set = Tokens::new(tokens(&["old"]));
999		let first = dial(&set, true, false);
1000		first.grant_credential();
1001		set.set(tokens(&["new", "pending"]));
1002		first.link.grant(id(&set, "new"), Grant::all());
1003		first.lost();
1004
1005		let second = dial(&set, true, false);
1006		assert_eq!(held(&set), ["pending"]);
1007		second.link.grant(id(&set, "pending"), Grant::all());
1008		ok(&set);
1009	}
1010
1011	/// A session that takes no token in band answers a new one as unsupported.
1012	#[test]
1013	fn a_session_without_auth_is_unsupported() {
1014		for requests in [false, true] {
1015			let set = Tokens::new(tokens(&["connection"]));
1016			let _session = dial(&set, false, requests);
1017			ok(&set);
1018			set.set(tokens(&["connection", "a"]));
1019			let answer = answered(&set);
1020			assert!(
1021				matches!(answer, Poll::Ready(Err(Error::Unsupported))),
1022				"requests {requests}: {answer:?}"
1023			);
1024		}
1025	}
1026
1027	/// The connection's end answers a set no session will.
1028	#[test]
1029	fn the_connection_end_answers_a_waiting_set() {
1030		let set = Tokens::new(tokens(&["connection"]));
1031		assert!(answered(&set).is_pending());
1032		set.handle().abort(Error::Session(SessionError::Unauthorized));
1033		refused(&set, SessionError::Unauthorized);
1034	}
1035
1036	/// The first token is the connection credential, presented in SETUP.
1037	#[test]
1038	fn the_first_token_is_the_connection_credential() {
1039		let url: Url = "https://relay.example.com/room".parse().unwrap();
1040		let (setup, connection) = credential(&url, &tokens(&["a", "b"]));
1041		assert_eq!(setup.as_deref(), Some("a"));
1042		assert_eq!(connection.as_deref(), Some("a"));
1043	}
1044
1045	/// Only lite-07 and moq-transport carry the credential in SETUP, so the URL stays clean.
1046	#[test]
1047	fn setup_versions_keep_the_credential_out_of_the_url() {
1048		let url: Url = "https://relay.example.com/room".parse().unwrap();
1049		let dialed = locate(&url, "a", &versions(&["moq-lite-07-wip", "moq-transport-18"]));
1050		assert_eq!(dialed, url);
1051	}
1052
1053	/// An offered version without a SETUP token needs the credential in the query.
1054	#[test]
1055	fn an_older_version_puts_the_credential_in_the_url() {
1056		let url: Url = "https://relay.example.com/room?x=1".parse().unwrap();
1057		let dialed = locate(&url, "a b", &crate::Versions::all());
1058		assert_eq!(dialed.as_str(), "https://relay.example.com/room?x=1&jwt=a+b");
1059	}
1060
1061	/// A URL credential stays the connection credential, so every token rides AUTH, except
1062	/// one equal to it, which would be granted twice.
1063	#[test]
1064	fn a_url_credential_sends_every_token_on_auth() {
1065		let url: Url = "moqt://relay.example.com/room?jwt=peer".parse().unwrap();
1066		let set = Tokens::new(tokens(&["a", "peer", "a"]));
1067		let dial = set.preview(&url);
1068		set.commit(&dial);
1069		assert_eq!(dial.token, None);
1070		assert_eq!(held(&set), ["a"]);
1071	}
1072
1073	#[test]
1074	fn no_tokens_present_nothing() {
1075		let url: Url = "https://relay.example.com/room".parse().unwrap();
1076		assert_eq!(credential(&url, &[]), (None, None));
1077	}
1078
1079	/// A unix socket's request target lives in `?path=`, so the credential goes inside it.
1080	#[test]
1081	fn a_unix_credential_joins_the_path_target() {
1082		for (url, expected) in [
1083			("unix:///tmp/moq.sock?path=%2Froom", "/room?jwt=a"),
1084			("unix:///tmp/moq.sock?path=%2Froom%3Fx%3D1", "/room?x=1&jwt=a"),
1085			("unix:///tmp/moq.sock", "?jwt=a"),
1086		] {
1087			let url: Url = url.parse().unwrap();
1088			let dialed = locate(&url, "a", &crate::Versions::all());
1089			let path = dialed
1090				.query_pairs()
1091				.find(|(k, _)| k == "path")
1092				.map(|(_, v)| v.into_owned());
1093			assert_eq!(path.as_deref(), Some(expected), "{url}");
1094			// The rewritten target is read back as already carrying the credential.
1095			assert_eq!(jwt(&dialed).as_deref(), Some("a"));
1096		}
1097	}
1098
1099	#[test]
1100	fn a_token_never_logs_its_value() {
1101		let token: Token = "secret".parse().unwrap();
1102		assert_eq!(format!("{token:?}"), "Token(<6 bytes>)");
1103		assert!("".parse::<Token>().is_err());
1104	}
1105}