Skip to main content

iroh_live_relay/
iroh_sessions.rs

1//! Sessions from iroh clients, decided by a policy on their endpoint id.
2//!
3//! moq-tokio's server has no iroh backend, and an iroh session's auth request
4//! would carry no peer identity anyway. So the media relay accepts iroh sessions
5//! itself with [`IrohSessions`], and asks a [`Policy`] about each. The
6//! default, [`relay_policy`], lets each client publish only at the paths that
7//! name it: `live/<its id>/...` and `rooms/<its id>/...`. Browsers come in
8//! through moq-relay's server, and [`browser_grant`] keeps them to names under
9//! [`ANON`].
10
11use std::{sync::Arc, time::Duration};
12
13use iroh::{
14    EndpointId,
15    endpoint::Connection,
16    protocol::{AcceptError, ProtocolHandler, RouterBuilder},
17};
18use iroh_live_node::{
19    BroadcastTicket, DECIDE_TIMEOUT, SessionRequest,
20    layout::LiveLayout,
21    policy::{Authorization, DynPolicy, Event, PeerRequest, Policy},
22};
23use iroh_live_rooms::RoomsLayout;
24use moq_net::{Prefix, Prefixes};
25use moq_relay::cluster::Cluster;
26use n0_error::e;
27use tokio_util::sync::CancellationToken;
28use tracing::{Instrument, debug, info, info_span, warn};
29
30use crate::pull::{Access, Client, PullGuard, Pulls};
31
32/// How long a closing session gets to tell its peer when the media relay shuts down.
33const CLOSE_GRACE: Duration = Duration::from_secs(1);
34
35/// The protocol handler that accepts iroh clients' MoQ sessions into the cluster.
36///
37/// Mount it on a router with [`mount`](Self::mount).
38#[derive(Clone, derive_more::Debug)]
39pub struct IrohSessions {
40    #[debug(skip)]
41    cluster: Cluster,
42    /// Pulls the broadcasts that sessions name by ticket, if enabled.
43    pulls: Option<Pulls>,
44    /// Decides who may hold a session, and what it may publish and read.
45    policy: Arc<dyn DynPolicy<EndpointId>>,
46    /// Decides who may pull under [`Access::Authorized`], asked at the ticket's path.
47    pull_policy: Option<Arc<dyn DynPolicy<EndpointId>>>,
48    /// Cancelled when the router shuts down, which closes every session.
49    shutdown: CancellationToken,
50}
51
52impl IrohSessions {
53    /// Creates the handler for `cluster`, deciding sessions with [`relay_policy`].
54    ///
55    /// With `pulls` set, a session that names a ticket in its path pulls the
56    /// ticket's broadcast, as a browser's does, if the pulls'
57    /// [`Access`](crate::pull::Access) lets it: see
58    /// [`with_pull_policy`](Self::with_pull_policy). A session that may not
59    /// pull, or would exceed the pulls' [`Limits`](crate::pull::Limits), is
60    /// refused.
61    #[must_use]
62    pub fn new(cluster: Cluster, pulls: Option<Pulls>) -> Self {
63        Self {
64            cluster,
65            pulls,
66            policy: Arc::new(relay_policy()),
67            pull_policy: None,
68            shutdown: CancellationToken::new(),
69        }
70    }
71
72    /// Returns this handler with `policy` deciding sessions.
73    ///
74    /// The media relay asks it after a client's MoQ SETUP. A rejection closes the
75    /// session with the rejection's code. An authorization's grant bounds
76    /// what the client publishes into the cluster and what it reads from it,
77    /// and the session closes when the authorization expires. The media relay does
78    /// not decide again: a client whose session closed reconnects.
79    #[must_use]
80    pub fn with_policy(mut self, policy: impl Policy<EndpointId>) -> Self {
81        self.policy = Arc::new(policy);
82        self
83    }
84
85    /// Returns this handler with `policy` deciding who may pull under [`Access::Authorized`].
86    ///
87    /// The media relay asks it about the session's peer and token at the path of the
88    /// ticket's broadcast, and the session may pull if the authorization lets
89    /// it read that path. Without one, no session pulls under
90    /// [`Access::Authorized`]. It should require a token, as a
91    /// [`Verify`](moq_ext_access::policy::Verify) without a fallback does,
92    /// since an open policy would let every session pull.
93    #[must_use]
94    pub fn with_pull_policy(mut self, policy: impl Policy<EndpointId>) -> Self {
95        self.pull_policy = Some(Arc::new(policy));
96        self
97    }
98
99    /// Mounts this handler on `router` under every ALPN in [`moq_transport_iroh::alpns`].
100    ///
101    /// The caller may add its own protocols, and spawns the router.
102    #[must_use]
103    pub fn mount(self, mut router: RouterBuilder) -> RouterBuilder {
104        for alpn in moq_transport_iroh::alpns() {
105            router = router.accept(alpn, self.clone());
106        }
107        router
108    }
109
110    /// Runs one session until it closes or the media relay shuts down.
111    async fn serve(&self, connection: Connection) -> Result<(), AcceptError> {
112        let Admitted {
113            session,
114            driver,
115            authorization,
116            pull,
117        } = self.admit(connection).await?;
118        // Held while the session runs.
119        let _pull = pull.map(|(pull, name)| crate::hold_pull(pull, name));
120        self.run(session, driver, &authorization).await;
121        Ok(())
122    }
123
124    /// Decides an iroh client's session and completes its handshake.
125    async fn admit(&self, connection: Connection) -> Result<Admitted, AcceptError> {
126        let peer = connection.remote_id();
127        let transport =
128            moq_transport_iroh::Transport::new(connection).map_err(AcceptError::from_err)?;
129        let handshake = tokio::time::timeout(
130            moq_transport_iroh::HANDSHAKE_TIMEOUT,
131            moq_net::Server::new().handshake(moq_net::time::Instant::now(), transport),
132        )
133        .await
134        .map_err(|_| AcceptError::from_err(moq_net::Error::Timeout))?
135        .map_err(AcceptError::from_err)?;
136        let name = requested_name(handshake.path());
137        // Logged without the query: a token rides it as `?jwt=`.
138        let session = SessionRequest::from_handshake(&handshake);
139        let path = session.path().to_owned();
140        let token = session.token().map(str::to_owned);
141        let request = PeerRequest::new(peer, session, Event::Connect);
142        let authorization =
143            match moq_ext_access::policy::decide_within(&*self.policy, &request, DECIDE_TIMEOUT)
144                .await
145            {
146                Ok(authorization) => authorization,
147                Err(rejection) => {
148                    info!(
149                        reason = rejection.reason(),
150                        code = %rejection.code(),
151                        "the policy rejected the iroh client",
152                    );
153                    handshake.close(rejection.code().clone());
154                    return Err(AcceptError::from_err(rejection));
155                }
156            };
157        let pull = match self.start_pull(peer, token, name.as_deref()).await {
158            Ok(pull) => pull,
159            Err(err) => {
160                info!(error = %err, "refusing the iroh client's pull");
161                let code = match err {
162                    crate::Error::PullDenied { .. } => moq_net::Error::Unauthorized,
163                    _ => moq_net::Error::TooManyRequests,
164                };
165                handshake.close(code);
166                return Err(AcceptError::from_err(err));
167            }
168        };
169        let grant = &authorization.grant;
170        let publish = self
171            .cluster
172            .origin
173            .scope("", &grant.publish)
174            .map_err(AcceptError::from_err)?;
175        // A session that names a ticket reads the pulled broadcast at that name.
176        let serving = name
177            .as_deref()
178            .filter(|_| self.pulls.is_some())
179            .and_then(|name| crate::pull::mounted(&self.cluster, name))
180            .map_or_else(
181                || self.cluster.origin.consume(),
182                |cluster| cluster.origin.consume(),
183            )
184            .scope("", &grant.subscribe)
185            .map_err(AcceptError::from_err)?;
186        let (session, driver) = tokio::time::timeout(
187            moq_transport_iroh::HANDSHAKE_TIMEOUT,
188            handshake
189                .with_publisher(serving)
190                .with_subscriber(publish)
191                .ok(),
192        )
193        .await
194        .map_err(|_| AcceptError::from_err(moq_net::Error::Timeout))?
195        .map_err(AcceptError::from_err)?;
196        info!(%path, grant = ?authorization.grant, expires = ?authorization.expires, "iroh client admitted");
197        Ok(Admitted {
198            session,
199            driver,
200            authorization,
201            pull,
202        })
203    }
204
205    /// Starts the pull of the ticket a session named, if pulls are on and `name` is a ticket.
206    ///
207    /// Under [`Access::Authorized`] the pull policy decides, at the ticket's
208    /// path with the session's `token`, and must grant reading that path.
209    async fn start_pull(
210        &self,
211        peer: EndpointId,
212        token: Option<String>,
213        name: Option<&str>,
214    ) -> Result<Option<(PullGuard, String)>, crate::Error> {
215        let Some((pulls, name)) = self.pulls.as_ref().zip(name) else {
216            return Ok(None);
217        };
218        let Ok(ticket) = name.parse::<BroadcastTicket>() else {
219            return Ok(None);
220        };
221        if pulls.access() == Access::Authorized {
222            let denied = || {
223                e!(crate::Error::PullDenied {
224                    path: ticket.path().clone()
225                })
226            };
227            let policy = self.pull_policy.as_deref().ok_or_else(denied)?;
228            let mut at_ticket = SessionRequest::new(ticket.path().as_str());
229            if let Some(token) = token {
230                at_ticket = at_ticket.with_token(token);
231            }
232            let request = PeerRequest::new(peer, at_ticket, Event::Connect);
233            let decision =
234                moq_ext_access::policy::decide_within(policy, &request, DECIDE_TIMEOUT).await;
235            if !decision.is_ok_and(|auth| auth.grant.allows_subscribe(ticket.path().as_str())) {
236                return Err(denied());
237            }
238        }
239        let pull = pulls.start(Client::Peer(peer), name, &ticket)?;
240        Ok(Some((pull, name.to_owned())))
241    }
242
243    /// Runs an admitted session until it ends, its authorization expires, or the media relay shuts down.
244    async fn run(
245        &self,
246        session: moq_net::Session,
247        driver: moq_net::Driver,
248        authorization: &Authorization,
249    ) {
250        let run = moq_net::time::run(driver);
251        tokio::pin!(run);
252        let expiry = expiry(authorization);
253        tokio::pin!(expiry);
254        let close = tokio::select! {
255            err = &mut run => {
256                debug!(error = %err, "iroh session ended");
257                return;
258            }
259            () = self.shutdown.cancelled() => moq_net::Error::Cancel,
260            () = &mut expiry => {
261                info!("the iroh client's authorization expired, closing its session");
262                moq_net::Error::Expired
263            }
264        };
265        // The driver keeps running, so the session can tell its peer.
266        session.abort(close);
267        if tokio::time::timeout(CLOSE_GRACE, run).await.is_err() {
268            warn!(grace = ?CLOSE_GRACE, "iroh session did not close in time");
269        }
270    }
271}
272
273/// An iroh client's session after its handshake, before it runs.
274struct Admitted {
275    session: moq_net::Session,
276    driver: moq_net::Driver,
277    authorization: Authorization,
278    /// The pull of the ticket the session named, with that name.
279    pull: Option<(PullGuard, String)>,
280}
281
282/// Waits until `authorization` expires, or forever without an expiry.
283async fn expiry(authorization: &Authorization) {
284    match authorization.expires {
285        Some(expires) => {
286            let left = expires
287                .duration_since(std::time::SystemTime::now())
288                .unwrap_or_default();
289            tokio::time::sleep(left).await;
290        }
291        None => std::future::pending().await,
292    }
293}
294
295impl ProtocolHandler for IrohSessions {
296    async fn accept(&self, connection: Connection) -> Result<(), AcceptError> {
297        let span = info_span!("iroh_client", peer = %connection.remote_id().fmt_short());
298        self.serve(connection).instrument(span).await
299    }
300
301    async fn shutdown(&self) {
302        self.shutdown.cancel();
303    }
304}
305
306/// The prefix a browser without a token publishes under, as moq-relay's
307/// anonymous rules name it.
308pub const ANON: &str = "anon";
309
310/// Returns the grant for a browser that dialed `path`: subscribe anywhere, publish under [`ANON`].
311///
312/// The rule is rooted at `/` and reduced to the dialed path, as moq-relay does
313/// with its public rules. The grant itself is rooted at the dialed path, so
314/// granting the unreduced rule would let a browser that dials `/live/<id>`
315/// publish beneath it. [`ANON`] keeps a browser out of `live/` and `rooms/`,
316/// whose paths name an iroh publisher.
317///
318/// # Errors
319///
320/// Returns an error if `path` is not a valid path.
321pub fn browser_grant(path: &str) -> Result<moq_auth::Grant, moq_auth::Error> {
322    let rules = browser_rules();
323    let rule = moq_auth::Claims::default()
324        .with_publish(rules.publish)
325        .with_subscribe(rules.subscribe);
326    let permissions = rule.authorize(path)?;
327    Ok(moq_auth::Grant::new(
328        permissions.publish,
329        permissions.subscribe,
330    ))
331}
332
333/// Returns what a browser may do without a token, rooted at `/`.
334///
335/// It may subscribe anywhere and publish under [`ANON`].
336pub(crate) fn browser_rules() -> moq_auth::Permissions {
337    moq_auth::Permissions::new(
338        ANON.parse::<Prefix>().expect("a valid prefix"),
339        Prefixes::all(),
340    )
341}
342
343/// Returns the broadcast name a session asked for in its path, if any.
344///
345/// A URL carries the name percent-encoded, so `/my%20cam` asks for `my cam`.
346/// A name that does not decode to UTF-8 is none.
347pub(crate) fn requested_name(path: &str) -> Option<String> {
348    let path = path.split('?').next().unwrap_or_default();
349    // A ticket is read from the raw path: its own escapes are part of it, and
350    // decoding them first would change what it names.
351    let raw = path.trim_start_matches('/');
352    if raw.parse::<BroadcastTicket>().is_ok() {
353        return Some(raw.to_owned());
354    }
355    let name = percent_encoding::percent_decode_str(raw)
356        .decode_utf8()
357        .ok()?;
358    (!name.is_empty()).then(|| name.into_owned())
359}
360
361/// Returns the media relay's default policy for iroh clients.
362///
363/// It admits every client to read the whole cluster and to publish its own
364/// `live/` broadcasts and its room broadcasts, at the paths that name its
365/// endpoint id. Use it as the fallback of a [`Verify`](moq_ext_access::policy::Verify)
366/// to let a token widen what a client may publish.
367#[must_use]
368pub fn relay_policy() -> impl Policy<EndpointId> + Clone {
369    iroh_live_node::layout::policy((LiveLayout::default(), RoomsLayout))
370}
371
372#[cfg(test)]
373mod tests {
374    use super::*;
375
376    #[test]
377    fn a_client_publishes_only_under_its_own_id() {
378        let id = iroh::SecretKey::from_bytes(&[5; 32]).public();
379        let other = iroh::SecretKey::from_bytes(&[6; 32]).public();
380        let request = PeerRequest::new(id, SessionRequest::default(), Event::Connect);
381        let scope = n0_future::future::block_on(Policy::decide(&relay_policy(), &request))
382            .expect("admitted")
383            .grant
384            .publish;
385        assert!(scope.matches(&format!("live/{id}/cam")));
386        assert!(scope.matches(&format!("rooms/{id}/topic/cam")));
387        assert!(!scope.matches(&format!("live/{other}/cam")));
388        assert!(!scope.matches(&format!("rooms/{other}/topic/cam")));
389        assert!(!scope.matches("cam"));
390    }
391
392    /// Returns whether [`browser_grant`] lets a browser at the root publish at `path`.
393    fn a_browser_may_publish(path: &str) -> bool {
394        browser_grant("/")
395            .expect("a grant")
396            .publish
397            .path
398            .matches(path)
399    }
400
401    #[test]
402    fn a_browser_publishes_under_anon() {
403        assert!(a_browser_may_publish("anon/hello"));
404        assert!(a_browser_may_publish("anon/hello/cam"));
405        assert!(!a_browser_may_publish("hello"));
406        assert!(
407            !a_browser_may_publish("anonx/cam"),
408            "a prefix ends at a segment"
409        );
410        assert!(!a_browser_may_publish("live/someone/cam"));
411        assert!(!a_browser_may_publish("rooms/someone/topic/cam"));
412    }
413
414    /// The grant is rooted at the dialed path, so its publish half must not reach below it.
415    #[test]
416    fn a_browser_grant_is_reduced_to_the_dialed_path() {
417        let peer = iroh::SecretKey::from_bytes(&[7; 32]).public();
418        for dialed in [
419            format!("/live/{peer}"),
420            format!("/rooms/{peer}/topic"),
421            "/live".to_owned(),
422            "/hello".to_owned(),
423        ] {
424            let grant = browser_grant(&dialed).expect("a grant");
425            assert!(
426                !grant.publish.path.matches("cam"),
427                "a browser at {dialed} may publish cam beneath it"
428            );
429            assert!(grant.subscribe.path.matches("cam"), "{dialed}");
430        }
431        // A path under the anonymous prefix may be published at and beneath.
432        let grant = browser_grant("/anon/hello").expect("a grant");
433        assert!(grant.publish.path.matches(""));
434        assert!(grant.publish.path.matches("cam"));
435        let grant = browser_grant("/anon").expect("a grant");
436        assert!(grant.publish.path.matches("cam"));
437    }
438
439    /// A browser that dials a ticket reads it, and publishes nothing beneath it.
440    #[test]
441    fn a_browser_at_a_ticket_path_publishes_nothing() {
442        let peer = iroh::SecretKey::from_bytes(&[7; 32]).public();
443        let path = LiveLayout::default().path(peer, "cam").expect("a path");
444        let ticket = BroadcastTicket::at(peer, path);
445        let grant = browser_grant(&format!("/{ticket}")).expect("a grant");
446        assert!(grant.publish.path.is_empty());
447        assert!(grant.subscribe.path.matches(""));
448    }
449
450    /// A browser cannot publish at the name a pull is read under.
451    ///
452    /// Pulls are read at the ticket's spelling, which always has a `/` between
453    /// the endpoint id and the name.
454    #[test]
455    fn a_browser_cannot_publish_at_a_pulled_name() {
456        let peer = iroh::SecretKey::from_bytes(&[7; 32]).public();
457        let path = LiveLayout::default().path(peer, "cam").expect("a path");
458        let ticket = BroadcastTicket::at(peer, path);
459        let full = ticket.to_string();
460        let bare = full.strip_prefix("ilv1:").expect("a ticket prefix");
461        assert!(!a_browser_may_publish(&full));
462        assert!(!a_browser_may_publish(bare));
463    }
464
465    #[test]
466    fn a_requested_name_drops_the_slash_and_the_query() {
467        assert_eq!(requested_name("/abc?jwt=x").as_deref(), Some("abc"));
468        assert_eq!(requested_name(""), None);
469        assert_eq!(requested_name("/"), None);
470    }
471
472    #[test]
473    fn a_requested_name_is_percent_decoded() {
474        assert_eq!(requested_name("/my%20cam").as_deref(), Some("my cam"));
475        assert_eq!(
476            requested_name("/caf%C3%A9?jwt=x").as_deref(),
477            Some("caf\u{e9}")
478        );
479        assert_eq!(requested_name("/100%25").as_deref(), Some("100%"));
480        assert_eq!(requested_name("/%FF"), None);
481    }
482}