Skip to main content

iroh_live_node/
layout.rs

1//! The `<root>/<peer>/<name>` path layout.
2//!
3//! The node takes any path. [`LiveLayout`] publishes a peer's broadcasts
4//! under `<root>/<peer>/`, and lets a peer publish only there, so no peer can
5//! publish at a path that names another.
6//!
7//! Rooms paths (`rooms/...`) belong to `iroh-live-rooms`.
8
9use iroh::EndpointId;
10pub use moq_ext_access::Layout;
11use moq_net::{Path, Prefix, Prefixes, broadcast};
12use n0_error::e;
13
14use crate::{
15    Audience, BroadcastTicket, Error, Grant, Node, NodeConfig,
16    policy::{self, PeerRequest, Policy},
17};
18
19/// The root of a layout that names none.
20const DEFAULT_ROOT: &str = "live";
21
22/// The `<root>/<peer>/<name>` layout, with the root `live` by default.
23///
24/// Two peers with different roots do not see each other's broadcasts: the
25/// node reports [`NotGranted`](Error::NotGranted).
26///
27/// # Examples
28///
29/// ```
30/// use iroh_live_node::layout::LiveLayout;
31///
32/// let layout = LiveLayout::default();
33/// let peer = iroh::SecretKey::generate().public();
34/// let path = layout.path(peer, "studio")?;
35/// assert_eq!(path.as_str(), format!("live/{peer}/studio"));
36/// assert_eq!(layout.parse(&path), Some((peer, "studio")));
37/// # Ok::<(), iroh_live_node::Error>(())
38/// ```
39#[derive(Debug, Clone, PartialEq, Eq, Hash)]
40pub struct LiveLayout {
41    root: String,
42}
43
44impl Default for LiveLayout {
45    fn default() -> Self {
46        Self::new(DEFAULT_ROOT)
47    }
48}
49
50impl LiveLayout {
51    /// Creates a layout under `root`.
52    ///
53    /// # Panics
54    ///
55    /// Panics unless `root` is one valid path segment: not empty, no `/`, and
56    /// not a wildcard.
57    #[must_use]
58    pub fn new(root: impl Into<String>) -> Self {
59        let root = root.into();
60        assert!(
61            !root.is_empty() && !root.contains('/') && root.parse::<Prefix>().is_ok(),
62            "the root of a layout is one valid path segment, not {root:?}"
63        );
64        Self { root }
65    }
66
67    /// Returns the first segment of every path in this layout.
68    #[must_use]
69    pub fn root(&self) -> &str {
70        &self.root
71    }
72
73    /// Returns the path of `peer`'s broadcast `name`: `<root>/<peer>/<name>`.
74    ///
75    /// # Errors
76    ///
77    /// Fails with [`Error::InvalidPath`] if `name` is empty, has an empty
78    /// segment, or makes no valid path.
79    pub fn path(&self, peer: EndpointId, name: &str) -> Result<Path, Error> {
80        let invalid = || {
81            e!(Error::InvalidPath {
82                path: name.to_owned()
83            })
84        };
85        if name.is_empty() || name.split('/').any(str::is_empty) {
86            return Err(invalid());
87        }
88        let path = format!("{}/{peer}/{name}", self.root);
89        path.parse::<Prefix>().map_err(|_| invalid())?;
90        Path::new(&path).map_err(|_| invalid())
91    }
92
93    /// Splits a path of this layout into the peer and the name.
94    ///
95    /// The inverse of [`path`](Self::path). Returns `None` for a path
96    /// elsewhere, one whose second segment is not an endpoint id in its
97    /// canonical hex spelling, or one without a name.
98    #[must_use]
99    pub fn parse<'a>(&self, path: &'a Path) -> Option<(EndpointId, &'a str)> {
100        let (peer, name) = path
101            .as_str()
102            .strip_prefix(&self.root)?
103            .strip_prefix('/')?
104            .split_once('/')?;
105        let id: EndpointId = peer.parse().ok()?;
106        (id.to_string() == peer && !name.is_empty()).then_some((id, name))
107    }
108
109    /// Returns a policy that admits every peer with its [`grant`] under this layout.
110    ///
111    /// Narrow it with [`Policy::filter`], and call `Node::reauthorize` when
112    /// the filter's state changes. To let peers publish room broadcasts too,
113    /// pass the pair of this layout and the rooms layout to [`policy()`].
114    ///
115    /// # Examples
116    ///
117    /// Admit only contacts:
118    ///
119    /// ```
120    /// use std::collections::BTreeSet;
121    ///
122    /// use iroh_live_node::{NodeConfig, layout::LiveLayout, policy::Policy};
123    /// use n0_watcher::{Watchable, Watcher};
124    ///
125    /// let contacts = Watchable::new(BTreeSet::<iroh::EndpointId>::new());
126    /// let known = contacts.clone();
127    /// let policy = LiveLayout::default()
128    ///     .policy()
129    ///     .filter(move |request| known.get().contains(request.peer()));
130    /// let config = NodeConfig::default().with_policy(policy);
131    /// # drop((config, contacts));
132    /// ```
133    #[must_use]
134    pub fn policy(&self) -> impl Policy<EndpointId> + Clone + use<> {
135        policy(self.clone())
136    }
137
138    /// Returns the [`NodeConfig`] of a node on this layout, with its [`policy`](Self::policy).
139    ///
140    /// The config's [`layout`](NodeConfig::layout) is this layout, so ticket
141    /// claims follow its [`owner`](Layout::owner) rule.
142    #[must_use]
143    pub fn config(&self) -> NodeConfig {
144        config(self.clone())
145    }
146
147    /// Publishes a broadcast at `<root>/<this node's id>/<name>` to granted sessions, and returns it.
148    ///
149    /// `B` is built from the route table's `broadcast::Producer`: a
150    /// `LocalBroadcast`, or the producer itself. The audience is
151    /// [`Audience::Granted`], which includes attached media relays.
152    ///
153    /// The publication lasts until the broadcast closes. A `LocalBroadcast`
154    /// closes when it is closed or its last clone drops. A producer closes only
155    /// when it is closed, since the node holds the broadcast open while it is
156    /// published. To keep the [`Publication`](crate::Publication), or
157    /// to publish to another audience, use [`Node::publish_with`] with
158    /// [`path`](Self::path).
159    ///
160    /// # Errors
161    ///
162    /// Fails if something is already published under `name`, the name makes
163    /// no valid path, or `B` cannot be built from the broadcast.
164    ///
165    /// # Examples
166    ///
167    /// ```no_run
168    /// use iroh_live_node::{Node, layout::LiveLayout};
169    /// use moq_net::broadcast;
170    ///
171    /// # fn run(node: Node) -> Result<(), Box<dyn std::error::Error>> {
172    /// let layout = LiveLayout::default();
173    /// let producer: broadcast::Producer = layout.publish(&node, "studio")?;
174    /// # drop(producer);
175    /// # Ok(())
176    /// # }
177    /// ```
178    pub fn publish<B>(&self, node: &Node, name: &str) -> Result<B, Error>
179    where
180        B: TryFrom<broadcast::Producer, Error: std::error::Error + Send + Sync + 'static>,
181    {
182        let path = self.path(node.id(), name)?;
183        let (_publication, broadcast) = node.publish_with(path, Audience::Granted, |producer| {
184            B::try_from(producer.clone())
185        })?;
186        Ok(broadcast)
187    }
188
189    /// Returns the ticket of `peer`'s broadcast `name`.
190    ///
191    /// Does not check that anything is published there.
192    ///
193    /// # Errors
194    ///
195    /// Fails like [`path`](Self::path).
196    pub fn ticket(&self, peer: EndpointId, name: &str) -> Result<BroadcastTicket, Error> {
197        Ok(BroadcastTicket::at(peer, self.path(peer, name)?))
198    }
199}
200
201impl Layout<EndpointId> for LiveLayout {
202    /// Returns `<root>/<peer>`, which covers every path beneath it.
203    fn scope(&self, peer: &EndpointId) -> Prefixes {
204        let prefix: Prefix = format!("{}/{peer}", self.root)
205            .parse()
206            .expect("the root and an endpoint id are valid path segments");
207        Prefixes::from(prefix)
208    }
209
210    /// Returns the peer a path names, if [`path`](LiveLayout::path) spells it that way.
211    fn owner(&self, path: &str) -> Option<EndpointId> {
212        let path = Path::new(path).ok()?;
213        let (peer, name) = self.parse(&path)?;
214        (self.path(peer, name).ok()? == path).then_some(peer)
215    }
216}
217
218/// Returns the grant a node gives `peer` under `layout`.
219///
220/// The peer may subscribe to anything, and publish only under its
221/// [`scope`](Layout::scope) in `layout`.
222#[must_use]
223pub fn grant(layout: &impl Layout<EndpointId>, peer: EndpointId) -> Grant {
224    Grant::publish_under(layout.scope(&peer))
225}
226
227/// Returns a policy that admits every peer with its [`grant`] under `layout`.
228///
229/// A pair of layouts is their union. For example,
230/// `policy((LiveLayout::default(), RoomsLayout))` lets every peer publish its
231/// own broadcasts and its room broadcasts.
232#[must_use]
233pub fn policy(layout: impl Layout<EndpointId> + Clone) -> impl Policy<EndpointId> + Clone {
234    policy::from_fn(move |request: &PeerRequest| Ok(grant(&layout, *request.peer()).into()))
235}
236
237/// Returns the [`NodeConfig`] of a node on `layout`, with its [`policy()`].
238///
239/// The config's [`layout`](NodeConfig::layout) is `layout` too, so
240/// [`Node::claim_path`] grants a peer the paths `layout` says it owns.
241#[must_use]
242pub fn config(layout: impl Layout<EndpointId> + Clone) -> NodeConfig {
243    NodeConfig::default()
244        .with_policy(policy(layout.clone()))
245        .with_layout(layout)
246}
247
248#[cfg(test)]
249mod tests {
250    use iroh::SecretKey;
251
252    use super::*;
253    use crate::SessionRequest;
254
255    fn id() -> EndpointId {
256        SecretKey::generate().public()
257    }
258
259    /// A node configured from a layout claims only the paths that layout says a peer owns.
260    #[tokio::test]
261    async fn a_layouts_config_claims_by_its_own_owner_rule() {
262        let layout = LiveLayout::new("cams");
263        let config = layout.config();
264        assert!(config.layout.is_some(), "the config names no layout");
265        let node = Node::new(crate::test_util::endpoint().await, config);
266        let peer = id();
267
268        let inside = layout.path(peer, "cam").expect("a path");
269        node.claim_path(peer, &inside)
270            .expect("the layout's own path");
271        // The generic rule would take this path, since one segment is the peer's id.
272        let outside = Path::new(&format!("live/{peer}/cam")).expect("a path");
273        let err = node
274            .claim_path(peer, &outside)
275            .expect_err("a path outside the layout");
276        assert!(matches!(err, Error::NotOwner { .. }), "{err:#}");
277        node.shutdown().await;
278    }
279
280    #[test]
281    fn path_and_parse_invert() {
282        let layout = LiveLayout::default();
283        let peer = id();
284        for name in ["cam", "cam/hd", "call"] {
285            let path = layout.path(peer, name).expect("a path");
286            assert_eq!(layout.parse(&path), Some((peer, name)));
287        }
288        let elsewhere = Path::new(&format!("rooms/{peer}/cam")).expect("path");
289        assert_eq!(layout.parse(&elsewhere), None);
290        let other_root = LiveLayout::new("fleet").path(peer, "cam").expect("path");
291        assert_eq!(layout.parse(&other_root), None);
292        assert_eq!(
293            layout.parse(&Path::new("live/nobody/cam").expect("path")),
294            None
295        );
296        assert_eq!(
297            layout.parse(&Path::new(&format!("livestock/{peer}/cam")).expect("path")),
298            None
299        );
300    }
301
302    #[test]
303    fn parse_wants_the_canonical_id() {
304        let layout = LiveLayout::default();
305        let peer = id();
306        let base32 = data_encoding::BASE32_NOPAD
307            .encode(peer.as_bytes())
308            .to_ascii_lowercase();
309        let path = Path::new(&format!("live/{base32}/cam")).expect("path");
310        assert_eq!(layout.parse(&path), None);
311        let bare = Path::new(&format!("live/{peer}")).expect("path");
312        assert_eq!(layout.parse(&bare), None);
313    }
314
315    #[test]
316    fn the_scope_matches_only_the_peers_own_paths() {
317        let layout = LiveLayout::default();
318        let (a, b) = (id(), id());
319        let grant = grant(&layout, a);
320        assert!(grant.allows_publish(layout.path(a, "cam").expect("path").as_str()));
321        assert!(!grant.allows_publish(layout.path(b, "cam").expect("path").as_str()));
322        assert!(grant.allows_subscribe("anything/at/all"));
323    }
324
325    #[test]
326    fn the_layout_owns_what_it_scopes() {
327        let layout = LiveLayout::default();
328        let (peer, other) = (id(), id());
329        let scope = layout.scope(&peer);
330        for name in ["cam", "cam/hd"] {
331            let path = layout.path(peer, name).expect("a path");
332            assert!(scope.matches(path.as_str()), "{path}");
333            assert_eq!(layout.owner(path.as_str()), Some(peer), "{path}");
334            assert!(!layout.scope(&other).matches(path.as_str()), "{path}");
335        }
336        assert_eq!(layout.owner(&format!("live/{peer}")), None);
337        assert_eq!(layout.owner(&format!("rooms/{peer}/topic/cam")), None);
338        assert_eq!(layout.owner(&format!("fleet/{peer}/cam")), None);
339    }
340
341    #[test]
342    fn two_layouts_compose() {
343        let (a, b) = (LiveLayout::new("a"), LiveLayout::new("b"));
344        let peer = id();
345        let request = PeerRequest::new(peer, SessionRequest::default(), policy::Event::Connect);
346        let grant = n0_future::future::block_on(Policy::decide(&policy((a, b)), &request))
347            .expect("admitted")
348            .grant;
349        assert!(grant.allows_publish(&format!("a/{peer}/cam")));
350        assert!(grant.allows_publish(&format!("b/{peer}/cam")));
351        assert!(!grant.allows_publish(&format!("c/{peer}/cam")));
352    }
353
354    #[test]
355    #[should_panic(expected = "one valid path segment")]
356    fn new_panics_on_a_bad_root() {
357        let _ = LiveLayout::new("a/b");
358    }
359
360    #[test]
361    fn names_that_make_no_path_fail() {
362        let layout = LiveLayout::default();
363        let peer = id();
364        for name in ["", "a//b", "/a", "a/", "*", "a/**"] {
365            let err = layout.path(peer, name).expect_err(name);
366            assert!(matches!(err, Error::InvalidPath { .. }), "{name}: {err:#}");
367            assert!(layout.ticket(peer, name).is_err(), "{name}");
368        }
369    }
370
371    /// Returns the grant `policy` gives `peer` at its connect.
372    fn decided(policy: &impl Policy<EndpointId>, peer: EndpointId) -> Grant {
373        let request = PeerRequest::new(peer, SessionRequest::default(), policy::Event::Connect);
374        n0_future::future::block_on(Policy::decide(policy, &request))
375            .expect("admitted")
376            .grant
377    }
378
379    #[test]
380    fn the_layout_methods_match_the_free_functions() {
381        let layout = LiveLayout::new("fleet");
382        let peer = id();
383        assert_eq!(decided(&layout.policy(), peer), grant(&layout, peer));
384        let config = layout.config();
385        let policy = config.policy.expect("a policy");
386        assert_eq!(decided(&policy, peer), grant(&layout, peer));
387    }
388
389    #[test]
390    fn the_policy_gives_each_peer_its_own_scope() {
391        let layout = LiveLayout::default();
392        let policy = layout.policy();
393        let (a, b) = (id(), id());
394        let for_a = decided(&policy, a);
395        let for_b = decided(&policy, b);
396        let cam_of = |peer| layout.path(peer, "cam").expect("path");
397        assert!(for_a.allows_publish(cam_of(a).as_str()));
398        assert!(!for_a.allows_publish(cam_of(b).as_str()));
399        assert!(for_b.allows_publish(cam_of(b).as_str()));
400        assert!(!for_b.allows_publish(cam_of(a).as_str()));
401    }
402
403    #[test]
404    fn a_pair_of_layouts_grants_and_configures_both_scopes() {
405        let both = (LiveLayout::new("a"), LiveLayout::new("b"));
406        let (peer, other) = (id(), id());
407        let granted = grant(&both, peer);
408        assert!(granted.allows_publish(&format!("a/{peer}/cam")));
409        assert!(granted.allows_publish(&format!("b/{peer}/cam")));
410        assert!(!granted.allows_publish(&format!("a/{other}/cam")));
411        assert!(!granted.allows_publish(&format!("c/{peer}/cam")));
412        assert!(granted.allows_subscribe("anything"));
413        let policy = config(both).policy.expect("a policy");
414        assert_eq!(decided(&policy, peer), granted);
415    }
416
417    #[test]
418    fn a_ticket_round_trips_a_name_with_reserved_characters() {
419        let layout = LiveLayout::default();
420        let peer = id();
421        for name in [
422            "my cam",
423            "a?b=c#d",
424            "x%20y",
425            "caf\u{e9}/\u{1f600}",
426            "a+b&c",
427            "~",
428        ] {
429            let ticket = layout.ticket(peer, name).expect(name);
430            let text = ticket.to_string();
431            assert!(text.is_ascii(), "{text}");
432            let parsed: BroadcastTicket = text.parse().expect(&text);
433            assert_eq!(parsed, ticket, "{name}");
434            assert_eq!(parsed.peer(), peer);
435            assert_eq!(layout.parse(parsed.path()), Some((peer, name)), "{name}");
436            assert_eq!(layout.owner(parsed.path().as_str()), Some(peer), "{name}");
437        }
438    }
439}