Skip to main content

moq_ext_access/
lib.rs

1//! Access control for moq nodes, independent of the transport.
2//!
3//! - [`Grant`]: what a session may subscribe to and publish.
4//! - [`SessionRequest`]: what a peer asked for when it opened a session.
5//! - [`Direction`]: which side opened a session.
6//! - [`Audience`]: who may see a publication, generic over the peer id.
7//! - [`AudienceKind`]: an [`Audience`] as a registry keeps it, the current set.
8//! - [`visible_paths`]: the paths a link may see, given its [`Viewer`].
9//! - [`policy`]: who may hold a session, and with which [`Grant`].
10//! - [`Layout`]: a path convention, which says where each peer publishes and
11//!   who owns a path.
12//!
13//! The default build carries no JWT or crypto stack. The `jwt` feature adds
14//! `policy::JwtVerifier` on moq-auth, and the `rcan` feature adds
15//! `policy::RcanVerifier` on ed25519 capability chains. A conversion between
16//! [`Grant`] and `moq_auth::Grant` is left out on purpose: expiry lives on
17//! [`policy::Authorization`], not on the grant.
18
19#![forbid(unsafe_code)]
20
21use std::{
22    collections::BTreeSet,
23    fmt::{self, Debug, Display},
24    hash::Hash,
25    sync::Arc,
26};
27
28use moq_net::{Prefix, Prefixes};
29use n0_error::stack_error;
30
31pub mod policy;
32
33/// An error returned when a path is not a valid grant prefix.
34#[stack_error(derive)]
35#[error("{path:?} is not a valid grant prefix")]
36pub struct InvalidPath {
37    /// The path that was given.
38    pub path: String,
39    #[error(source, std_err)]
40    source: moq_net::InvalidPrefix,
41}
42
43/// A peer's identity: any small, comparable, printable id.
44pub trait PeerId: Clone + Eq + Ord + Hash + Debug + Display + Send + Sync + 'static {}
45
46impl<T: Clone + Eq + Ord + Hash + Debug + Display + Send + Sync + 'static> PeerId for T {}
47
48/// What a session may subscribe to from a node, and publish into it.
49///
50/// The shape of a moq-auth grant, so a token means the same thing to a node
51/// and to a media relay. Each member is a path prefix that covers the path and
52/// every path beneath it; the empty prefix covers everything.
53#[derive(Debug, Clone, Default, PartialEq, Eq)]
54pub struct Grant {
55    /// The paths the peer may subscribe to.
56    pub subscribe: Prefixes,
57    /// The paths the peer may publish into the node's route table.
58    pub publish: Prefixes,
59}
60
61impl Grant {
62    /// Returns a grant that allows everything in both directions.
63    #[must_use]
64    pub fn everything() -> Self {
65        Self {
66            subscribe: Prefixes::all(),
67            publish: Prefixes::all(),
68        }
69    }
70
71    /// Returns a grant to subscribe to everything and publish nothing.
72    #[must_use]
73    pub fn subscribe_only() -> Self {
74        Self {
75            subscribe: Prefixes::all(),
76            publish: Prefixes::new(),
77        }
78    }
79
80    /// Returns a grant to subscribe to everything and publish only at `publish`.
81    ///
82    /// With a prefix that names the peer, such as `live/<peer id>`, no peer
83    /// can publish at another's paths.
84    #[must_use]
85    pub fn publish_under(publish: impl Into<Prefixes>) -> Self {
86        Self {
87            subscribe: Prefixes::all(),
88            publish: publish.into(),
89        }
90    }
91
92    /// Returns a grant that allows nothing in either direction.
93    #[must_use]
94    pub fn nothing() -> Self {
95        Self {
96            subscribe: Prefixes::new(),
97            publish: Prefixes::new(),
98        }
99    }
100
101    /// Returns this grant with the prefix `text` added to what the peer may
102    /// publish: the path it names and every path beneath it.
103    ///
104    /// # Errors
105    ///
106    /// Fails with [`InvalidPath`] if `text` is not a valid prefix: it holds
107    /// `*`, has an empty segment, or has too many segments.
108    pub fn with_publish_prefix(mut self, text: &str) -> Result<Self, InvalidPath> {
109        let prefix = text.parse::<Prefix>().map_err(|source| InvalidPath {
110            path: text.to_owned(),
111            source,
112        })?;
113        self.publish.insert(prefix);
114        Ok(self)
115    }
116
117    /// Returns a grant that allows what either this grant or `other` allows.
118    #[must_use]
119    pub fn union(&self, other: &Self) -> Self {
120        let mut union = self.clone();
121        union.subscribe.extend(other.subscribe.iter().cloned());
122        union.publish.extend(other.publish.iter().cloned());
123        union
124    }
125
126    /// Reports whether the peer may subscribe to `path`.
127    #[must_use]
128    pub fn allows_subscribe(&self, path: &str) -> bool {
129        self.subscribe.matches(path)
130    }
131
132    /// Reports whether the peer may publish `path`.
133    #[must_use]
134    pub fn allows_publish(&self, path: &str) -> bool {
135        self.publish.matches(path)
136    }
137}
138
139/// The wire convention for the token a dialing peer presents.
140///
141/// The SETUP of moq-lite-06 and older has no token field, so a token also
142/// rides the `jwt` query of the setup path.
143pub mod token {
144    use moq_net::setup::Token;
145
146    /// Returns `token` as the MoQ SETUP carries it.
147    #[must_use]
148    pub fn setup_token(token: &str) -> Token {
149        Token {
150            kind: Token::OUT_OF_BAND,
151            value: token.as_bytes().to_vec(),
152        }
153    }
154
155    /// Returns the setup target for `path`, with `token` in its `jwt` query.
156    ///
157    /// `path` is a URL path, without its query. Escapes it already holds stay
158    /// as they are. Characters a URL path cannot hold, such as a space or
159    /// `?`, are percent-encoded.
160    #[must_use]
161    pub fn setup_url(path: &str, token: Option<&str>) -> String {
162        let mut url = url::Url::parse("moqt://setup/").expect("a valid URL");
163        url.set_path(&format!("/{}", path.trim_start_matches('/')));
164        if let Some(token) = token {
165            url.query_pairs_mut().append_pair("jwt", token);
166        }
167        match url.query() {
168            Some(query) => format!("{}?{query}", url.path()),
169            None => url.path().to_owned(),
170        }
171    }
172}
173
174/// What a peer asked for when it opened a session.
175///
176/// Its `Debug` output names the query keys and whether a token is present,
177/// but never a query value or the token, so a request is safe to log.
178#[derive(Clone, Default)]
179pub struct SessionRequest {
180    path: String,
181    query: Vec<(String, String)>,
182    token: Option<String>,
183}
184
185impl fmt::Debug for SessionRequest {
186    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
187        let keys: Vec<&str> = self.query.iter().map(|(key, _)| key.as_str()).collect();
188        f.debug_struct("SessionRequest")
189            .field("path", &self.path)
190            .field("query_keys", &keys)
191            .field("token", &self.token().map(|_| "<redacted>"))
192            .finish()
193    }
194}
195
196impl SessionRequest {
197    /// Parses a request target, `/<path>?<query>`.
198    #[must_use]
199    pub fn new(target: &str) -> Self {
200        let (path, query) = target.split_once('?').unwrap_or((target, ""));
201        let query = url::form_urlencoded::parse(query.as_bytes())
202            .map(|(key, value)| (key.into_owned(), value.into_owned()))
203            .collect();
204        Self {
205            path: path.trim_matches('/').to_owned(),
206            query,
207            token: None,
208        }
209    }
210
211    /// Returns what a client asked for in its MoQ SETUP: a path, and maybe a token.
212    #[must_use]
213    pub fn from_handshake(handshake: &moq_net::server::Handshake) -> Self {
214        let token = handshake
215            .token()
216            .map(|token| (token.kind, token.value.as_slice()));
217        Self::from_setup(handshake.path(), token)
218    }
219
220    /// Returns the request of a SETUP with `target` and a token of the given type and bytes.
221    ///
222    /// Only an out-of-band token, type [`moq_net::setup::Token::OUT_OF_BAND`],
223    /// that is valid UTF-8 counts.
224    #[must_use]
225    pub fn from_setup(target: &str, token: Option<(u64, &[u8])>) -> Self {
226        let request = Self::new(target);
227        let token = token
228            .filter(|(kind, _)| *kind == moq_net::setup::Token::OUT_OF_BAND)
229            .and_then(|(_, value)| std::str::from_utf8(value).ok());
230        match token {
231            Some(token) => request.with_token(token),
232            None => request,
233        }
234    }
235
236    /// Sets the token the peer presented outside the target, such as in its MoQ SETUP.
237    #[must_use]
238    pub fn with_token(mut self, token: impl Into<String>) -> Self {
239        self.token = Some(token.into());
240        self
241    }
242
243    /// Returns the request path, without its query.
244    #[must_use]
245    pub fn path(&self) -> &str {
246        &self.path
247    }
248
249    /// Returns a query parameter of the request, such as `jwt`.
250    #[must_use]
251    pub fn query(&self, key: &str) -> Option<&str> {
252        self.query
253            .iter()
254            .find(|(name, _)| name == key)
255            .map(|(_, value)| value.as_str())
256    }
257
258    /// Returns the token the peer presented.
259    ///
260    /// That is the token set with [`with_token`](Self::with_token), or else the
261    /// `jwt` query parameter, or else the `token` one. Writers use `jwt`, which
262    /// moq-relay reads.
263    #[must_use]
264    pub fn token(&self) -> Option<&str> {
265        self.token
266            .as_deref()
267            .or_else(|| self.query("jwt"))
268            .or_else(|| self.query("token"))
269    }
270}
271
272/// Who may see a publication.
273#[derive(Debug, Clone)]
274pub enum Audience<P: PeerId> {
275    /// Every session whose grant covers the path, media relays included.
276    Granted,
277    /// These peers, as the set changes.
278    ///
279    /// Never offered to media relays. The publication holds the set: change it
280    /// through a clone of the watchable.
281    Peers(n0_watcher::Watchable<BTreeSet<P>>),
282}
283
284impl<P: PeerId> Audience<P> {
285    /// Returns an audience of `peers`, as a set nobody else holds.
286    ///
287    /// ```
288    /// use moq_ext_access::Audience;
289    ///
290    /// let only_bob: Audience<&str> = Audience::peers(["bob"]);
291    /// ```
292    #[must_use]
293    pub fn peers(peers: impl IntoIterator<Item = P>) -> Self {
294        Self::Peers(n0_watcher::Watchable::new(peers.into_iter().collect()))
295    }
296}
297
298#[allow(
299    clippy::derivable_impls,
300    reason = "a derived Default would require `P: Default`, which peer ids such as iroh's EndpointId are not"
301)]
302impl<P: PeerId> Default for Audience<P> {
303    fn default() -> Self {
304        Self::Granted
305    }
306}
307
308/// An [`Audience`] as a registry keeps it: the current set, not its watcher.
309#[derive(Debug, Clone, PartialEq, Eq)]
310pub enum AudienceKind<P: PeerId> {
311    /// See [`Audience::Granted`].
312    Granted,
313    /// See [`Audience::Peers`], as of now.
314    Peers(BTreeSet<P>),
315}
316
317impl<P: PeerId> From<&Audience<P>> for AudienceKind<P> {
318    fn from(audience: &Audience<P>) -> Self {
319        match audience {
320            Audience::Granted => Self::Granted,
321            Audience::Peers(peers) => Self::Peers(peers.get()),
322        }
323    }
324}
325
326/// Which side opened a session.
327#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
328pub enum Direction {
329    /// The peer dialed this node.
330    Accepted,
331    /// This node dialed the peer.
332    Dialed,
333}
334
335/// What kind of link a session or a media relay attachment is.
336///
337/// The kind decides which publications a link may be offered.
338#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
339pub enum LinkKind {
340    /// A session with a peer, dialed or accepted.
341    Direct,
342    /// A media relay, which gets the [`Audience::Granted`] publications.
343    Relay,
344}
345
346/// The link that [`visible_paths`] works out the visible publications for.
347#[derive(Debug)]
348pub enum Viewer<'a, P: PeerId> {
349    /// A session with this peer, dialed or accepted.
350    Direct(&'a P),
351    /// A media relay, which gets the [`Audience::Granted`] publications.
352    Relay,
353}
354
355/// A path convention: where each peer publishes, and which peer owns a path.
356///
357/// The two halves agree: [`owner`](Self::owner) of a path that
358/// [`scope`](Self::scope) gives a peer names that peer or no one.
359///
360/// Ownership must carry down to sub-paths: every path beneath a path a peer
361/// owns is owned by that peer or by no one. A grant is a set of prefixes,
362/// so a peer that may publish at a path it owns, such as through a ticket
363/// claim, may publish beneath it too. A layout whose owner is a later
364/// segment, such as `<name>/<peer>`, breaks this: a claim on `cam/<bob>`
365/// would let Bob publish `cam/<bob>/<carol>`, which names Carol.
366///
367/// A pair `(A, B)` is the union of two layouts.
368pub trait Layout<P: PeerId>: Debug + Send + Sync + 'static {
369    /// Returns the paths `peer` may publish its own broadcasts under.
370    fn scope(&self, peer: &P) -> Prefixes;
371
372    /// Returns the peer that owns `path`, or `None` for a path outside the layout.
373    fn owner(&self, path: &str) -> Option<P>;
374}
375
376impl<P: PeerId, T: Layout<P> + ?Sized> Layout<P> for Arc<T> {
377    fn scope(&self, peer: &P) -> Prefixes {
378        (**self).scope(peer)
379    }
380
381    fn owner(&self, path: &str) -> Option<P> {
382        (**self).owner(path)
383    }
384}
385
386impl<P: PeerId, A: Layout<P>, B: Layout<P>> Layout<P> for (A, B) {
387    fn scope(&self, peer: &P) -> Prefixes {
388        let mut scope = self.0.scope(peer);
389        scope.extend(self.1.scope(peer).iter().cloned());
390        scope
391    }
392
393    fn owner(&self, path: &str) -> Option<P> {
394        self.0.owner(path).or_else(|| self.1.owner(path))
395    }
396}
397
398/// Returns the paths of `publications` that `viewer` may see, as prefixes.
399///
400/// A publication is visible when the link's `grant` covers its path and its
401/// audience admits the link. A media relay sees `Granted` publications, and never a
402/// `Peers` one, which a media relay would forward to anyone. A direct link is in a
403/// `Peers` audience when its peer is in the set.
404///
405/// A moq grant is a set of prefixes, each covering its whole subtree, so a
406/// visible publication with a hidden one beneath it is left out too: listing
407/// it would expose the hidden one. A path that is not a valid prefix is left
408/// out as well.
409///
410/// moq bounds the result: it refuses an AUTH_OK larger than 64 KiB. A link
411/// that may see publications whose paths add up to more bytes cannot be
412/// granted them one by one.
413#[must_use]
414pub fn visible_paths<'a, P: PeerId>(
415    publications: impl IntoIterator<Item = (&'a str, &'a AudienceKind<P>)>,
416    grant: &Grant,
417    viewer: Viewer<'_, P>,
418) -> Prefixes {
419    let (shown, hidden): (Vec<_>, Vec<_>) = publications
420        .into_iter()
421        .partition(|(path, audience)| visible(path, audience, grant, &viewer));
422    shown
423        .into_iter()
424        .filter_map(|(path, _)| path.parse::<Prefix>().ok())
425        .filter(|prefix| !hidden.iter().any(|(path, _)| prefix.matches(path)))
426        .collect()
427}
428
429/// Reports whether a publication at `path` for `audience` belongs on a link.
430fn visible<P: PeerId>(
431    path: &str,
432    audience: &AudienceKind<P>,
433    grant: &Grant,
434    viewer: &Viewer<'_, P>,
435) -> bool {
436    if !grant.allows_subscribe(path) {
437        return false;
438    }
439    match (audience, viewer) {
440        (AudienceKind::Granted, _) => true,
441        (AudienceKind::Peers(peers), Viewer::Direct(peer)) => peers.contains(*peer),
442        (AudienceKind::Peers(_), Viewer::Relay) => false,
443    }
444}
445
446#[cfg(test)]
447mod tests {
448    use super::*;
449
450    /// A layout that gives each peer `<root>/<peer>`.
451    #[derive(Debug)]
452    struct Under(&'static str);
453
454    impl Layout<String> for Under {
455        fn scope(&self, peer: &String) -> Prefixes {
456            Prefixes::from(
457                format!("{}/{peer}", self.0)
458                    .parse::<Prefix>()
459                    .expect("prefix"),
460            )
461        }
462
463        fn owner(&self, path: &str) -> Option<String> {
464            let rest = path.strip_prefix(self.0)?.strip_prefix('/')?;
465            let (peer, name) = rest.split_once('/')?;
466            (!name.is_empty()).then(|| peer.to_owned())
467        }
468    }
469
470    #[test]
471    fn a_pair_of_layouts_is_their_union() {
472        let both = (Under("live"), Arc::new(Under("rooms")));
473        let bob = "bob".to_owned();
474        let scope = both.scope(&bob);
475        assert!(scope.matches("live/bob/cam"));
476        assert!(scope.matches("rooms/bob/cam"));
477        assert!(!scope.matches("live/carol/cam"));
478        assert_eq!(both.owner("live/bob/cam"), Some(bob.clone()));
479        assert_eq!(both.owner("rooms/bob/cam"), Some(bob));
480        assert_eq!(both.owner("other/bob/cam"), None);
481    }
482
483    #[test]
484    fn a_request_splits_its_path_and_query() {
485        let request = SessionRequest::new("/studio?jwt=abc%2Bdef&x=1");
486        assert_eq!(request.path(), "studio");
487        assert_eq!(request.query("jwt"), Some("abc+def"));
488        assert_eq!(request.query("x"), Some("1"));
489        assert_eq!(request.query("y"), None);
490    }
491
492    #[test]
493    fn a_setup_token_wins_over_the_query() {
494        let request = SessionRequest::new("/studio?jwt=from-query");
495        assert_eq!(request.token(), Some("from-query"));
496        let request = request.with_token("from-setup");
497        assert_eq!(request.token(), Some("from-setup"));
498        assert_eq!(SessionRequest::new("/studio").token(), None);
499    }
500
501    #[test]
502    fn a_token_rides_the_setup_path() {
503        let target = token::setup_url("", Some("a+b"));
504        assert_eq!(target, "/?jwt=a%2Bb");
505        assert_eq!(SessionRequest::new(&target).token(), Some("a+b"));
506        assert_eq!(token::setup_token("a+b").value, b"a+b");
507    }
508
509    #[test]
510    fn a_setup_url_joins_path_and_token() {
511        assert_eq!(token::setup_url("", None), "/");
512        assert_eq!(token::setup_url("studio/cam", None), "/studio/cam");
513        assert_eq!(token::setup_url("/studio", None), "/studio");
514        assert_eq!(token::setup_url("studio", Some("abc")), "/studio?jwt=abc");
515        let request = SessionRequest::new(&token::setup_url("studio", Some("abc")));
516        assert_eq!(request.path(), "studio");
517        assert_eq!(request.token(), Some("abc"));
518    }
519
520    #[test]
521    fn a_setup_url_encodes_what_a_path_cannot_hold() {
522        assert_eq!(token::setup_url("my cam?x#y", None), "/my%20cam%3Fx%23y");
523        // An escape the path already holds is not encoded twice.
524        assert_eq!(token::setup_url("my%20cam", None), "/my%20cam");
525    }
526
527    #[test]
528    fn grants_match_prefixes() {
529        let everything = Grant::everything();
530        assert!(everything.allows_subscribe("live/x/cam"));
531        assert!(everything.allows_publish("anything"));
532        let only = Grant::subscribe_only();
533        assert!(only.allows_subscribe("anything"));
534        assert!(!only.allows_publish("anything"));
535        let live: Prefix = "live".parse().expect("prefix");
536        let scoped = Grant {
537            subscribe: Prefixes::from(live),
538            publish: Prefixes::new(),
539        };
540        assert!(scoped.allows_subscribe("live/x/cam"));
541        assert!(!scoped.allows_subscribe("rooms/t/x/cam"));
542        assert!(!scoped.allows_publish("live/x/cam"));
543    }
544
545    #[test]
546    fn a_publish_prefix_that_is_not_valid_is_an_error() {
547        for path in ["a/*/b", "a/**", "a/b*c", "a//b", "/a"] {
548            let err = Grant::nothing()
549                .with_publish_prefix(path)
550                .expect_err("a path with a wildcard");
551            assert_eq!(err.path, path);
552        }
553    }
554
555    #[test]
556    fn nothing_and_union_compose() {
557        let nothing = Grant::nothing();
558        assert!(!nothing.allows_publish("a/b") && !nothing.allows_subscribe("a/b"));
559        let one = Grant::nothing()
560            .with_publish_prefix("a/b")
561            .expect("a literal path");
562        assert!(one.allows_publish("a/b") && one.allows_publish("a/b/c"));
563        assert!(!one.allows_publish("a/bc") && !one.allows_publish("a"));
564        let both = Grant::subscribe_only().union(&one);
565        assert!(both.allows_publish("a/b") && both.allows_subscribe("x"));
566        assert!(!both.allows_publish("x"));
567    }
568
569    #[test]
570    fn visibility_follows_grant_audience_and_link() {
571        let grant = Grant::everything();
572        let granted = AudienceKind::<String>::Granted;
573        let peers = AudienceKind::Peers(BTreeSet::from(["a".to_string()]));
574        let a = "a".to_string();
575        let b = "b".to_string();
576        assert!(visible("p", &granted, &grant, &Viewer::Direct(&b)));
577        assert!(visible("p", &peers, &grant, &Viewer::Direct(&a)));
578        assert!(!visible("p", &peers, &grant, &Viewer::Direct(&b)));
579        assert!(visible("p", &granted, &grant, &Viewer::Relay));
580        assert!(!visible("p", &peers, &grant, &Viewer::Relay));
581        let none = Grant::nothing();
582        assert!(!visible("p", &granted, &none, &Viewer::Direct(&a)));
583    }
584
585    #[test]
586    fn visible_paths_list_exactly_what_a_link_sees() {
587        let granted = AudienceKind::<String>::Granted;
588        let peers = AudienceKind::Peers(BTreeSet::from(["a".to_string()]));
589        let publications = [("live/x/public", &granted), ("live/x/secret", &peers)];
590        let grant = Grant::everything();
591        let (a, b) = ("a".to_string(), "b".to_string());
592
593        let for_a = visible_paths(publications, &grant, Viewer::Direct(&a));
594        assert!(for_a.matches("live/x/public"));
595        assert!(for_a.matches("live/x/secret"));
596        assert!(
597            !for_a.matches("live/y/learned"),
598            "a path nobody published here"
599        );
600
601        let for_b = visible_paths(publications, &grant, Viewer::Direct(&b));
602        assert!(for_b.matches("live/x/public"));
603        assert!(!for_b.matches("live/x/secret"));
604
605        let relay = visible_paths(publications, &grant, Viewer::Relay);
606        assert!(relay.matches("live/x/public"));
607        assert!(!relay.matches("live/x/secret"));
608    }
609
610    #[test]
611    fn visible_paths_leave_out_a_publication_above_a_hidden_one() {
612        let granted = AudienceKind::<String>::Granted;
613        let peers = AudienceKind::Peers(BTreeSet::from(["a".to_string()]));
614        let publications = [
615            ("live/x", &granted),
616            ("live/x/secret", &peers),
617            ("live/y", &granted),
618        ];
619        let grant = Grant::everything();
620        let (a, b) = ("a".to_string(), "b".to_string());
621
622        let for_a = visible_paths(publications, &grant, Viewer::Direct(&a));
623        assert!(for_a.matches("live/x") && for_a.matches("live/x/secret"));
624
625        let for_b = visible_paths(publications, &grant, Viewer::Direct(&b));
626        assert!(
627            !for_b.matches("live/x"),
628            "its prefix would cover the hidden path"
629        );
630        assert!(!for_b.matches("live/x/secret"));
631        assert!(for_b.matches("live/y"));
632    }
633
634    #[test]
635    fn a_setup_token_out_of_band_becomes_the_token() {
636        let token = token::setup_token("from-setup");
637        let request =
638            SessionRequest::from_setup("/studio?jwt=from-query", Some((token.kind, &token.value)));
639        assert_eq!(request.path(), "studio");
640        assert_eq!(request.token(), Some("from-setup"));
641    }
642
643    #[test]
644    fn a_setup_token_of_another_kind_leaves_the_query_token() {
645        let other = moq_net::setup::Token::OUT_OF_BAND + 1;
646        let request = SessionRequest::from_setup("/studio?jwt=from-query", Some((other, b"x")));
647        assert_eq!(request.token(), Some("from-query"));
648        let request = SessionRequest::from_setup("/studio", Some((other, b"x")));
649        assert_eq!(request.token(), None);
650    }
651
652    #[test]
653    fn a_setup_token_that_is_not_utf8_is_ignored() {
654        let kind = moq_net::setup::Token::OUT_OF_BAND;
655        let request = SessionRequest::from_setup("/studio?token=t", Some((kind, &[0xff, 0xfe])));
656        assert_eq!(request.token(), Some("t"));
657        assert_eq!(SessionRequest::from_setup("/studio", None).token(), None);
658    }
659
660    #[test]
661    fn debug_output_redacts_a_setup_token() {
662        let token = token::setup_token("secret-setup");
663        let request = SessionRequest::from_setup("/studio", Some((token.kind, &token.value)));
664        let printed = format!("{request:?}");
665        assert!(!printed.contains("secret"), "{printed}");
666        assert!(printed.contains("<redacted>"), "{printed}");
667        assert!(
668            !format!("{:?}", SessionRequest::new("/studio")).contains("<redacted>"),
669            "no token, nothing to redact"
670        );
671    }
672}