1use 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
32const CLOSE_GRACE: Duration = Duration::from_secs(1);
34
35#[derive(Clone, derive_more::Debug)]
39pub struct IrohSessions {
40 #[debug(skip)]
41 cluster: Cluster,
42 pulls: Option<Pulls>,
44 policy: Arc<dyn DynPolicy<EndpointId>>,
46 pull_policy: Option<Arc<dyn DynPolicy<EndpointId>>>,
48 shutdown: CancellationToken,
50}
51
52impl IrohSessions {
53 #[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 #[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 #[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 #[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 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 let _pull = pull.map(|(pull, name)| crate::hold_pull(pull, name));
120 self.run(session, driver, &authorization).await;
121 Ok(())
122 }
123
124 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 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 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 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 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 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
273struct Admitted {
275 session: moq_net::Session,
276 driver: moq_net::Driver,
277 authorization: Authorization,
278 pull: Option<(PullGuard, String)>,
280}
281
282async 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
306pub const ANON: &str = "anon";
309
310pub 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
333pub(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
343pub(crate) fn requested_name(path: &str) -> Option<String> {
348 let path = path.split('?').next().unwrap_or_default();
349 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#[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 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 #[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 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 #[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 #[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}