Skip to main content

iroh_live_node/
ticket.rs

1//! Tickets that name a broadcast by its publisher and its path.
2//!
3//! A ticket holds no socket addresses. Subscribers look them up from the
4//! endpoint id over pkarr and mDNS, which keeps the ticket short enough for a
5//! QR code on a small screen.
6
7use std::{fmt, str::FromStr};
8
9use iroh::EndpointId;
10use moq_net::Path;
11use n0_error::e;
12use percent_encoding::{AsciiSet, NON_ALPHANUMERIC, percent_decode_str, utf8_percent_encode};
13use serde::{Deserialize, Serialize};
14
15use crate::{Error, publish::check_path};
16
17/// The scheme of a ticket string, with its version.
18const SCHEME: &str = "ilv1:";
19
20/// The segment that stands for the publisher's own id.
21const SELF_SEGMENT: &str = "~";
22
23/// A publisher's endpoint id and the path of one of its broadcasts.
24///
25/// The string form is `ilv1:<peer>/<path>`. `<peer>` is the endpoint id in
26/// lowercase base32. Any segment of the path that equals the peer's own id is
27/// written as `~`, and every other byte outside `[A-Za-z0-9._-]` is
28/// percent-encoded. Parsing accepts the id in base32 of either case, or in
29/// lowercase hex. Serde uses the string form.
30///
31/// A ticket says nothing about layouts: the path is whatever the publisher
32/// published at.
33///
34/// # Examples
35///
36/// ```
37/// use iroh_live_node::BroadcastTicket;
38/// use moq_net::Path;
39///
40/// let peer = iroh::SecretKey::generate().public();
41/// let path = Path::new(&format!("live/{peer}/studio"))?;
42/// let ticket = BroadcastTicket::at(peer, path);
43/// assert!(ticket.to_string().ends_with("/live/~/studio"));
44/// let parsed: BroadcastTicket = ticket.to_string().parse()?;
45/// assert_eq!(parsed, ticket);
46/// # Ok::<(), Box<dyn std::error::Error>>(())
47/// ```
48#[derive(Debug, Clone, PartialEq, Eq, Hash)]
49pub struct BroadcastTicket {
50    peer: EndpointId,
51    path: Path,
52}
53
54impl BroadcastTicket {
55    /// The most bytes a ticket string may have.
56    ///
57    /// A media relay mounts the string as one path, and moq allows 4096 bytes in one.
58    pub const MAX_LEN: usize = 4000;
59
60    /// The most path segments a ticket may have.
61    ///
62    /// A media relay mounts the string as one more segment, and moq allows 32.
63    pub const MAX_PARTS: usize = 31;
64
65    /// Creates a ticket for the broadcast at `path` of `peer`.
66    ///
67    /// A path that is too long for the string form still displays, but does
68    /// not parse back.
69    #[must_use]
70    pub fn at(peer: EndpointId, path: Path) -> Self {
71        Self { peer, path }
72    }
73
74    /// Returns the publisher's endpoint id.
75    #[must_use]
76    pub fn peer(&self) -> EndpointId {
77        self.peer
78    }
79
80    /// Returns the path the broadcast is published at.
81    #[must_use]
82    pub fn path(&self) -> &Path {
83        &self.path
84    }
85}
86
87/// Returns the [`Error::InvalidTicket`] for `reason`.
88fn invalid(reason: &'static str) -> Error {
89    e!(Error::InvalidTicket { reason })
90}
91
92/// The bytes a ticket path percent-encodes: all but `[A-Za-z0-9._-]`.
93const ENCODED: &AsciiSet = &NON_ALPHANUMERIC.remove(b'.').remove(b'_').remove(b'-');
94
95/// Reads one percent-encoded segment, exactly once.
96///
97/// Fails on a malformed escape, on bytes that are not UTF-8, and on an
98/// escape that decodes to `/`, which would split the segment in two.
99fn decode_segment(segment: &str) -> Result<String, Error> {
100    let bytes = segment.as_bytes();
101    for (at, _) in segment.match_indices('%') {
102        let escape = bytes.get(at + 1..at + 3);
103        if !escape.is_some_and(|hex| hex.iter().all(u8::is_ascii_hexdigit)) {
104            return Err(invalid("invalid percent escape"));
105        }
106    }
107    let decoded = percent_decode_str(segment)
108        .decode_utf8()
109        .map_err(|_| invalid("path is not UTF-8"))?;
110    if decoded.contains('/') {
111        return Err(invalid("encoded slash in a path segment"));
112    }
113    Ok(decoded.into_owned())
114}
115
116impl fmt::Display for BroadcastTicket {
117    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
118        let id = data_encoding::BASE32_NOPAD
119            .encode(self.peer.as_bytes())
120            .to_ascii_lowercase();
121        let own = self.peer.to_string();
122        let mut path = String::new();
123        for (index, segment) in self.path.as_str().split('/').enumerate() {
124            if index > 0 {
125                path.push('/');
126            }
127            if segment == own {
128                path.push_str(SELF_SEGMENT);
129            } else {
130                path.extend(utf8_percent_encode(segment, ENCODED));
131            }
132        }
133        write!(f, "{SCHEME}{id}/{path}")
134    }
135}
136
137impl FromStr for BroadcastTicket {
138    type Err = Error;
139
140    /// Parses the string form, with a case-insensitive scheme and peer id.
141    ///
142    /// Fails with [`Error::InvalidTicket`] if the string is not a ticket, has
143    /// more than [`MAX_PARTS`](Self::MAX_PARTS) path segments or
144    /// [`MAX_LEN`](Self::MAX_LEN) bytes, or its path is not valid.
145    fn from_str(s: &str) -> Result<Self, Self::Err> {
146        let s = s.trim();
147        if s.len() > Self::MAX_LEN {
148            return Err(invalid("ticket is too long"));
149        }
150        let rest = s
151            .get(..SCHEME.len())
152            .filter(|scheme| scheme.eq_ignore_ascii_case(SCHEME))
153            .map(|_| &s[SCHEME.len()..])
154            .ok_or_else(|| invalid("missing ilv1: scheme"))?;
155        let (id, path) = rest
156            .split_once('/')
157            .ok_or_else(|| invalid("missing / separator"))?;
158        let peer = EndpointId::from_str(id).map_err(|_| invalid("invalid endpoint id"))?;
159        let own = peer.to_string();
160        let segments = path
161            .split('/')
162            .map(|segment| {
163                if segment.is_empty() {
164                    Err(invalid("empty path segment"))
165                } else if segment == SELF_SEGMENT {
166                    Ok(own.clone())
167                } else {
168                    decode_segment(segment)
169                }
170            })
171            .collect::<Result<Vec<_>, Error>>()?;
172        let path = Path::new(&segments.join("/")).map_err(|_| invalid("invalid path"))?;
173        if path.as_str().split('/').count() > Self::MAX_PARTS {
174            return Err(invalid("too many path segments"));
175        }
176        check_path(&path).map_err(|_| invalid("invalid path"))?;
177        Ok(Self { peer, path })
178    }
179}
180
181impl Serialize for BroadcastTicket {
182    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
183        serializer.collect_str(self)
184    }
185}
186
187impl<'de> Deserialize<'de> for BroadcastTicket {
188    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
189        let s = String::deserialize(deserializer)?;
190        s.parse().map_err(serde::de::Error::custom)
191    }
192}
193
194#[cfg(test)]
195mod tests {
196    use iroh::SecretKey;
197    use serde::de::{IntoDeserializer, value::Error};
198
199    use super::*;
200
201    fn ticket(peer: EndpointId, path: &str) -> BroadcastTicket {
202        BroadcastTicket::at(peer, Path::new(path).expect("a path"))
203    }
204
205    fn id() -> EndpointId {
206        SecretKey::generate().public()
207    }
208
209    #[test]
210    fn a_ticket_round_trips() {
211        let peer = id();
212        let original = ticket(peer, &format!("live/{peer}/studio"));
213        let text = original.to_string();
214        assert!(text.starts_with("ilv1:"), "{text}");
215        assert!(text.ends_with("/live/~/studio"), "{text}");
216        assert_eq!(text.len(), 5 + 52 + "/live/~/studio".len());
217        assert_eq!(text.parse::<BroadcastTicket>().expect("parse"), original);
218    }
219
220    #[test]
221    fn reserved_characters_round_trip() {
222        let peer = id();
223        let other = id();
224        for path in [
225            "a/b c/d%e".to_string(),
226            "tilde/~/x".to_string(),
227            "uni/caf\u{e9}/\u{1f600}".to_string(),
228            format!("rooms/{other}/{peer}/cam"),
229            "q/a?b=c#d/e+f".to_string(),
230        ] {
231            let original = ticket(peer, &path);
232            let text = original.to_string();
233            assert!(text.is_ascii(), "{text}");
234            let parsed = text.parse::<BroadcastTicket>().expect(&text);
235            assert_eq!(parsed, original, "{text}");
236        }
237        let tilde = ticket(peer, "tilde/~/x").to_string();
238        assert!(tilde.ends_with("/tilde/%7E/x"), "{tilde}");
239    }
240
241    #[test]
242    fn the_peer_reads_in_base32_of_either_case_and_in_hex() {
243        let peer = id();
244        let canonical = ticket(peer, "a/b").to_string();
245        let (_, path) = canonical.split_once('/').expect("separator");
246        for spelling in [
247            peer.to_string(),
248            data_encoding::BASE32_NOPAD
249                .encode(peer.as_bytes())
250                .to_ascii_lowercase(),
251            data_encoding::BASE32_NOPAD.encode(peer.as_bytes()),
252        ] {
253            let text = format!("ILV1:{spelling}/{path}");
254            assert_eq!(text.parse::<BroadcastTicket>().expect(&text).peer(), peer);
255        }
256    }
257
258    #[test]
259    fn a_decoded_escape_stays_a_literal() {
260        let peer = id();
261        let text = format!("ilv1:{}/a/%7E/b", &ticket(peer, "x").to_string()[5..57]);
262        let parsed = text.parse::<BroadcastTicket>().expect("parse");
263        assert_eq!(parsed.path().as_str(), "a/~/b");
264    }
265
266    #[test]
267    fn garbage_is_rejected() {
268        let peer = id();
269        let good = ticket(peer, "a/b").to_string();
270        let id_part = &good[5..57];
271        for bad in [
272            "not-a-ticket".to_string(),
273            "iroh-live:abc/x".to_string(),
274            format!("ilv1:{id_part}"),
275            format!("ilv1:{id_part}/"),
276            format!("ilv1:{id_part}/a//b"),
277            format!("ilv1:{id_part}/a/%zz"),
278            format!("ilv1:{id_part}/a/%4"),
279            format!("ilv1:{id_part}/a/*/b"),
280            format!("ilv1:{id_part}/%FF"),
281            "ilv1:short/a".to_string(),
282        ] {
283            assert!(bad.parse::<BroadcastTicket>().is_err(), "{bad}");
284        }
285    }
286
287    /// Returns the id part of a ticket string for `peer`.
288    fn id_part(peer: EndpointId) -> String {
289        ticket(peer, "x").to_string()[5..57].to_owned()
290    }
291
292    #[test]
293    fn a_signed_escape_is_rejected() {
294        let text = format!("ilv1:{}/a/%+1", id_part(id()));
295        assert!(text.parse::<BroadcastTicket>().is_err(), "{text}");
296    }
297
298    #[test]
299    fn an_encoded_slash_is_rejected() {
300        let id = id_part(id());
301        for text in [format!("ilv1:{id}/a%2Fb"), format!("ilv1:{id}/a/%2f")] {
302            assert!(text.parse::<BroadcastTicket>().is_err(), "{text}");
303        }
304    }
305
306    #[test]
307    fn a_trailing_percent_is_rejected() {
308        let id = id_part(id());
309        for text in [format!("ilv1:{id}/a/b%"), format!("ilv1:{id}/a%/b")] {
310            assert!(text.parse::<BroadcastTicket>().is_err(), "{text}");
311        }
312    }
313
314    #[test]
315    fn a_path_with_spaces_and_unicode_round_trips() {
316        let original = ticket(id(), "my cam/caf\u{e9} \u{1f600}/x");
317        let text = original.to_string();
318        assert!(text.is_ascii(), "{text}");
319        assert!(text.contains("my%20cam"), "{text}");
320        assert_eq!(text.parse::<BroadcastTicket>().expect(&text), original);
321    }
322
323    #[test]
324    fn the_part_limit_counts_the_decoded_path() {
325        let id = id_part(id());
326        let at_limit = vec!["s"; 31].join("/");
327        let text = format!("ilv1:{id}/{at_limit}");
328        assert!(text.parse::<BroadcastTicket>().is_ok(), "{text}");
329        // An encoded slash must not smuggle in a 32nd segment.
330        let text = format!("ilv1:{id}/{at_limit}%2Fs");
331        assert!(text.parse::<BroadcastTicket>().is_err(), "{text}");
332    }
333
334    #[test]
335    fn a_ticket_over_the_cap_displays_but_does_not_parse() {
336        let peer = id();
337        let deep = vec!["s"; 32].join("/");
338        let long = ticket(peer, &deep);
339        assert!(long.to_string().parse::<BroadcastTicket>().is_err());
340        let ok = ticket(peer, &vec!["s"; 31].join("/"));
341        assert_eq!(
342            ok.to_string().parse::<BroadcastTicket>().expect("parse"),
343            ok
344        );
345        let wide = ticket(peer, &vec!["\u{e9}".repeat(100); 10].join("/"));
346        assert!(wide.to_string().len() > BroadcastTicket::MAX_LEN);
347        assert!(wide.to_string().parse::<BroadcastTicket>().is_err());
348    }
349
350    #[test]
351    fn the_peers_own_segment_is_a_tilde() {
352        let peer = SecretKey::from_bytes(&[7; 32]).public();
353        let text = ticket(peer, &format!("live/{peer}/studio")).to_string();
354        let id = data_encoding::BASE32_NOPAD
355            .encode(peer.as_bytes())
356            .to_ascii_lowercase();
357        assert_eq!(text, format!("ilv1:{id}/live/~/studio"));
358    }
359
360    #[test]
361    fn serde_reads_the_string_form() {
362        let original = ticket(id(), "cam");
363        let text = original.to_string();
364        let back = BroadcastTicket::deserialize(IntoDeserializer::<Error>::into_deserializer(
365            text.as_str(),
366        ))
367        .expect("deserialize");
368        assert_eq!(back, original);
369    }
370}