1#![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#[stack_error(derive)]
35#[error("{path:?} is not a valid grant prefix")]
36pub struct InvalidPath {
37 pub path: String,
39 #[error(source, std_err)]
40 source: moq_net::InvalidPrefix,
41}
42
43pub 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#[derive(Debug, Clone, Default, PartialEq, Eq)]
54pub struct Grant {
55 pub subscribe: Prefixes,
57 pub publish: Prefixes,
59}
60
61impl Grant {
62 #[must_use]
64 pub fn everything() -> Self {
65 Self {
66 subscribe: Prefixes::all(),
67 publish: Prefixes::all(),
68 }
69 }
70
71 #[must_use]
73 pub fn subscribe_only() -> Self {
74 Self {
75 subscribe: Prefixes::all(),
76 publish: Prefixes::new(),
77 }
78 }
79
80 #[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 #[must_use]
94 pub fn nothing() -> Self {
95 Self {
96 subscribe: Prefixes::new(),
97 publish: Prefixes::new(),
98 }
99 }
100
101 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 #[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 #[must_use]
128 pub fn allows_subscribe(&self, path: &str) -> bool {
129 self.subscribe.matches(path)
130 }
131
132 #[must_use]
134 pub fn allows_publish(&self, path: &str) -> bool {
135 self.publish.matches(path)
136 }
137}
138
139pub mod token {
144 use moq_net::setup::Token;
145
146 #[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 #[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#[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 #[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 #[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 #[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 #[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 #[must_use]
245 pub fn path(&self) -> &str {
246 &self.path
247 }
248
249 #[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 #[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#[derive(Debug, Clone)]
274pub enum Audience<P: PeerId> {
275 Granted,
277 Peers(n0_watcher::Watchable<BTreeSet<P>>),
282}
283
284impl<P: PeerId> Audience<P> {
285 #[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#[derive(Debug, Clone, PartialEq, Eq)]
310pub enum AudienceKind<P: PeerId> {
311 Granted,
313 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
328pub enum Direction {
329 Accepted,
331 Dialed,
333}
334
335#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
339pub enum LinkKind {
340 Direct,
342 Relay,
344}
345
346#[derive(Debug)]
348pub enum Viewer<'a, P: PeerId> {
349 Direct(&'a P),
351 Relay,
353}
354
355pub trait Layout<P: PeerId>: Debug + Send + Sync + 'static {
369 fn scope(&self, peer: &P) -> Prefixes;
371
372 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#[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
429fn 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 #[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 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}