1#![forbid(unsafe_code)]
51
52use std::{net::SocketAddr, path::PathBuf, sync::Arc};
53
54use axum::{extract::Path, response::IntoResponse, routing::get};
55use clap::Args;
56use include_dir::{Dir, include_dir};
57use iroh::{EndpointId, SecretKey, protocol::Router};
58use iroh_live_node::{BroadcastTicket, EndpointConfig, Mdns, policy::DynPolicy};
59use moq_auth::{KeySet, lease, serve};
60use moq_ext_access::policy::Verify;
61use moq_net::Prefix;
62use moq_relay::auth::Admissions;
63use n0_error::{AnyError, e};
64use n0_future::task::{AbortOnDropHandle, JoinSet};
65use tracing::{debug, info, warn};
66
67mod error;
68mod iroh_sessions;
69mod keys;
70pub mod pull;
71
72pub use self::{
73 error::Error,
74 iroh_sessions::{ANON, IrohSessions, browser_grant, relay_policy},
75 keys::KeyFile,
76};
77
78static WEB_DIR: Dir<'_> = include_dir!("$CARGO_MANIFEST_DIR/web/dist");
80
81#[derive(Args, Debug, Clone)]
83pub struct Config {
84 #[arg(long, default_value = "[::]:4443")]
86 pub bind: SocketAddr,
87
88 #[arg(long)]
92 pub http_bind: Option<SocketAddr>,
93
94 #[arg(long, value_name = "PATH", conflicts_with_all = ["auth_url", "auth_public", "auth_public_publish", "auth_public_subscribe"])]
108 pub auth_key: Option<PathBuf>,
109
110 #[arg(long, value_name = "URL", conflicts_with_all = ["auth_public", "auth_public_publish", "auth_public_subscribe"])]
112 pub auth_url: Option<url::Url>,
113
114 #[arg(long, value_name = "PREFIX", value_delimiter = ',')]
119 pub auth_public: Vec<Prefix>,
120
121 #[arg(long, value_name = "PREFIX", value_delimiter = ',')]
123 pub auth_public_publish: Vec<Prefix>,
124
125 #[arg(long, value_name = "PREFIX", value_delimiter = ',')]
127 pub auth_public_subscribe: Vec<Prefix>,
128
129 #[arg(long)]
138 pub open_pulls: bool,
139
140 #[arg(skip)]
144 pub pull_limits: pull::Limits,
145
146 #[arg(skip)]
151 pub iroh_policy: Option<Arc<dyn DynPolicy<EndpointId>>>,
152}
153
154pub async fn run(config: Config) -> Result<(), Error> {
171 iroh_live_node::crypto_provider();
175 let iroh_endpoint = EndpointConfig::default()
179 .with_secret_key(secret_key()?)
180 .with_mdns(Mdns::Announce)
181 .bind()
182 .await
183 .map_err(|source| {
184 e!(Error::Bind {
185 source: Arc::new(source)
186 })
187 })?;
188 info!(endpoint_id = %iroh_endpoint.id(), "iroh endpoint bound");
189 println!("iroh endpoint: {}", iroh_endpoint.id());
190
191 let key_source = config
193 .auth_key
194 .as_deref()
195 .map(load_keys)
196 .transpose()?
197 .map(|(_, source)| source);
198 let verifier = config.auth_key.clone().map(KeyFile::load).transpose()?;
199 let mut relay_config = moq_relay::Config::default();
200 relay_config.auth.url = config.auth_url.clone();
201 relay_config.auth.public = config.auth_public.clone();
202 relay_config.auth.public_publish = config.auth_public_publish.clone();
203 relay_config.auth.public_subscribe = config.auth_public_subscribe.clone();
204 let (quic_bind, http_bind) = match config.http_bind {
208 Some(http_bind) => (config.bind, http_bind),
209 None => {
210 let bind = shared_port(config.bind).map_err(|err| {
211 relay_error(
212 anyhow::Error::new(err).context("no port is free for both QUIC and HTTP"),
213 )
214 })?;
215 (bind, bind)
216 }
217 };
218 relay_config.listen.bind = Some(moq_tokio::listen::Bind::Addr(quic_bind));
219 relay_config.listen.tls.generate = vec!["localhost".to_string()];
221 relay_config.web.http.listen = Some(http_bind);
222 relay_config.web.ws = false;
225 let mut relay = moq_relay::Relay::load(relay_config)
226 .await
227 .map_err(relay_error)?;
228 let access = if config.open_pulls {
229 warn!("--open-pulls: any session may make the relay dial an iroh endpoint");
230 pull::Access::Open
231 } else {
232 pull::Access::Authorized
233 };
234 if access == pull::Access::Authorized && config.auth_key.is_none() {
235 info!("without --auth-key or --open-pulls, the relay pulls no tickets");
236 }
237 let pulls = pull::Pulls::new(iroh_endpoint.clone(), relay.cluster().clone())
238 .with_access(access)
239 .with_limits(config.pull_limits);
240 let _admit_task = match relay.admissions() {
243 Some(admissions) => Some(AbortOnDropHandle::new(tokio::spawn(admit(
244 admissions,
245 Some(pulls.clone()),
246 key_source,
247 )))),
248 None => {
249 info!("moq-relay's auth decides browser sessions, which pull no tickets");
250 None
251 }
252 };
253 let iroh_policy = config
254 .iroh_policy
255 .unwrap_or_else(|| match verifier.clone() {
256 Some(verifier) => Arc::new(Verify::new(verifier).with_fallback(relay_policy())),
257 None => Arc::new(relay_policy()),
258 });
259 let mut iroh_sessions =
262 IrohSessions::new(relay.cluster().clone(), Some(pulls)).with_policy(iroh_policy);
263 if let Some(verifier) = verifier {
264 iroh_sessions = iroh_sessions.with_pull_policy(Verify::new(verifier));
266 }
267 let iroh_router = iroh_sessions.mount(Router::builder(iroh_endpoint)).spawn();
268
269 let quic_port = relay
270 .quic_addr()
271 .ok_or_else(|| relay_error(anyhow::anyhow!("the QUIC listener is not bound")))?
272 .port();
273 let http_port = relay
274 .web_addrs()
275 .http
276 .ok_or_else(|| relay_error(anyhow::anyhow!("the HTTP listener is not bound")))?
277 .port();
278 println!("http port: {http_port}");
280 println!("iroh-live relay listening at http://localhost:{http_port}");
283 if quic_port == http_port {
284 println!(" WebTransport on UDP {quic_port}; the page above connects to it for you");
285 } else {
286 println!(" WebTransport on UDP {quic_port}, web viewer on TCP {http_port}");
287 }
288 println!(" needs a browser with WebTransport: Chromium, or Firefox 153+");
289
290 let routes = relay
292 .web()
293 .routes()
294 .route("/", get(|| async { serve_embedded_file("index.html") }))
295 .route(
296 "/{*path}",
297 get(|Path(path): Path<String>| async move { serve_embedded_file(&path) }),
298 );
299 let result = relay.with_web(routes).run().await.map_err(relay_error);
300 if let Err(err) = iroh_router.shutdown().await {
301 warn!(error = %err, "the iroh router did not shut down cleanly");
302 }
303 result
304}
305
306fn shared_port(bind: SocketAddr) -> std::io::Result<SocketAddr> {
312 if bind.port() != 0 {
313 return Ok(bind);
314 }
315 let mut last_err = None;
316 for _ in 0..16 {
317 let udp = std::net::UdpSocket::bind(bind)?;
318 let addr = udp.local_addr()?;
319 match std::net::TcpListener::bind(addr) {
320 Ok(_) => return Ok(addr),
321 Err(err) => last_err = Some(err),
322 }
323 }
324 Err(last_err.unwrap_or_else(|| std::io::ErrorKind::AddrInUse.into()))
325}
326
327fn relay_error(err: anyhow::Error) -> Error {
329 e!(Error::Relay {
330 source: Arc::new(AnyError::from_anyhow(err)),
331 })
332}
333
334pub async fn admit(
351 mut admissions: Admissions,
352 pulls: Option<pull::Pulls>,
353 keys: Option<serve::Keys>,
354) {
355 let policy = keys.clone().map(browser_policy);
356 let token_policy = keys.map(token_policy);
357 let mut held = JoinSet::new();
358 loop {
359 let admission = tokio::select! {
360 admission = admissions.next() => match admission {
361 Some(admission) => admission,
362 None => break,
363 },
364 Some(_) = held.join_next(), if !held.is_empty() => continue,
365 };
366 let name = iroh_sessions::requested_name(&admission.request.path);
367 let ticket = name
368 .as_deref()
369 .and_then(|name| name.parse::<BroadcastTicket>().ok());
370 let decided_at = ticket.as_ref().map(|ticket| format!("/{}", ticket.path()));
373 let grant = browser_session_grant(&admission, policy.as_ref(), decided_at.as_deref()).await;
374 let mut grant = match grant {
375 Ok(grant) => grant,
376 Err(err) => {
377 info!(path = %admission.request.path, error = %err, "refusing a browser session");
378 admission.refuse(err);
379 continue;
380 }
381 };
382 let Some((ticket, name)) = ticket.zip(name) else {
383 debug!(path = %admission.request.path, "admitting a session");
384 admission.grant(lease::Consumer::fixed(grant));
385 continue;
386 };
387 grant
390 .mounts
391 .insert(String::new(), ticket.path().to_string());
392 debug!(path = %admission.request.path, "admitting a ticket's session");
393 let Some(pulls) = pulls.as_ref().filter(|_| !admission.attached()) else {
395 admission.grant(lease::Consumer::fixed(grant));
396 continue;
397 };
398 let request = &admission.request;
399 let pull = match may_pull(pulls, token_policy.as_ref(), request, &ticket).await {
400 Ok(()) => pulls.start(pull::Client::from_addr(request.remote), &name, &ticket),
401 Err(err) => Err(err),
402 };
403 let pull = match pull {
404 Ok(pull) => hold_pull(pull, name),
405 Err(err) => {
406 info!(path = %request.path, error = %err, "refusing a browser session's pull");
407 admission.refuse(moq_relay::auth::Error::Forbidden(err.to_string()));
408 continue;
409 }
410 };
411 let (lease, consumer) = lease::Producer::new(grant);
413 admission.grant(consumer);
414 held.spawn(async move {
415 let _pull = pull;
416 lease.closed().await;
417 });
418 }
419}
420
421async fn may_pull(
426 pulls: &pull::Pulls,
427 token_policy: Option<&serve::Policy>,
428 request: &moq_auth::Request,
429 ticket: &BroadcastTicket,
430) -> Result<(), Error> {
431 if pulls.access() == pull::Access::Open {
432 return Ok(());
433 }
434 let denied = || {
435 e!(Error::PullDenied {
436 path: ticket.path().clone()
437 })
438 };
439 let policy = token_policy.ok_or_else(denied)?;
440 let mut at_ticket = request.clone();
441 at_ticket.path = format!("/{}", ticket.path());
442 match policy.decide(&at_ticket).await {
444 Ok(grant) if grant.subscribe.path.matches("") => Ok(()),
445 _ => Err(denied()),
446 }
447}
448
449fn browser_policy(keys: serve::Keys) -> serve::Policy {
451 let mut policy = serve::Policy::default();
452 policy.keys = Some(keys);
453 policy.public = iroh_sessions::browser_rules();
454 policy
455}
456
457fn token_policy(keys: serve::Keys) -> serve::Policy {
459 let mut policy = serve::Policy::default();
460 policy.keys = Some(keys);
461 policy
462}
463
464async fn browser_session_grant(
469 admission: &moq_relay::auth::Admission,
470 policy: Option<&serve::Policy>,
471 path: Option<&str>,
472) -> Result<moq_auth::Grant, moq_relay::auth::Error> {
473 let request = &admission.request;
474 let Some(policy) = policy else {
475 return browser_grant(path.unwrap_or(&request.path))
476 .map_err(|err| moq_relay::auth::Error::Forbidden(err.to_string()));
477 };
478 let mut request = request.clone();
479 if let Some(path) = path {
480 path.clone_into(&mut request.path);
481 }
482 if let Some(token) = request
483 .event
484 .auth()
485 .map(str::to_owned)
486 .filter(|_| admission.attached())
487 {
488 request.token = Some(moq_auth::Token {
489 kind: moq_auth::Token::OUT_OF_BAND,
490 value: token.into_bytes(),
491 });
492 request.query = None;
493 }
494 policy
495 .decide(&request)
496 .await
497 .map_err(|denial| moq_relay::auth::Error::Forbidden(denial.to_string()))
498}
499
500fn load_keys(path: &std::path::Path) -> Result<(KeySet, serve::Keys), Error> {
504 if let Ok(keys) = KeySet::from_file(path) {
505 return Ok((keys, serve::Keys::Set(path.to_owned())));
506 }
507 let key = moq_auth::Key::from_file(path).map_err(|source| {
508 e!(Error::Keys {
509 path: path.to_owned(),
510 source: Arc::new(source),
511 })
512 })?;
513 let keys = KeySet {
514 keys: vec![Arc::new(key)],
515 };
516 Ok((keys, serve::Keys::File(path.to_owned())))
517}
518
519pub(crate) fn hold_pull(
524 pull: pull::PullGuard,
525 name: String,
526) -> AbortOnDropHandle<Option<pull::PullGuard>> {
527 AbortOnDropHandle::new(tokio::spawn(async move {
528 match pull.connected().await {
529 Ok(()) => Some(pull),
530 Err(err) => {
531 warn!(%name, error = format_args!("{err:#}"), "pull failed for the ticket in the URL");
532 None
533 }
534 }
535 }))
536}
537
538fn secret_key() -> Result<SecretKey, Error> {
543 let dir = match std::env::var_os("IROH_LIVE_RELAY_DATA") {
544 Some(dir) => PathBuf::from(dir),
545 None => dirs::data_dir()
546 .ok_or_else(|| e!(Error::NoDataDir))?
547 .join("iroh-live-relay"),
548 };
549 let path = dir.join("iroh_secret_key");
550 std::fs::create_dir_all(&dir)
551 .and_then(|()| iroh_live_node::load_or_create_secret_key(&path))
552 .map_err(|source| {
553 e!(Error::Identity {
554 path,
555 source: Arc::new(source)
556 })
557 })
558}
559
560fn serve_embedded_file(path: &str) -> axum::response::Response {
562 let mime = mime_from_path(path);
563 match WEB_DIR.get_file(path) {
564 Some(file) => (
565 axum::http::StatusCode::OK,
566 [(axum::http::header::CONTENT_TYPE, mime)],
567 file.contents(),
568 )
569 .into_response(),
570 None => axum::http::StatusCode::NOT_FOUND.into_response(),
571 }
572}
573
574fn mime_from_path(path: &str) -> &'static str {
576 match path.rsplit('.').next() {
577 Some("html") => "text/html; charset=utf-8",
578 Some("js") => "application/javascript; charset=utf-8",
579 Some("css") => "text/css; charset=utf-8",
580 Some("json") => "application/json",
581 Some("wasm") => "application/wasm",
582 Some("svg") => "image/svg+xml",
583 Some("png") => "image/png",
584 Some("ico") => "image/x-icon",
585 _ => "application/octet-stream",
586 }
587}
588
589#[cfg(test)]
590mod tests {
591 use clap::{CommandFactory, Parser};
592
593 use super::*;
594
595 #[derive(Parser)]
596 struct Cli {
597 #[command(flatten)]
598 relay: Config,
599 }
600
601 fn parse(args: &[&str]) -> Result<Config, clap::Error> {
602 Cli::try_parse_from(std::iter::once("relay").chain(args.iter().copied()))
603 .map(|cli| cli.relay)
604 }
605
606 #[test]
608 fn any_port_resolves_to_one_free_for_quic_and_http() {
609 let bind = shared_port("127.0.0.1:0".parse().unwrap()).expect("a free port");
610 assert_ne!(bind.port(), 0);
611 let _udp = std::net::UdpSocket::bind(bind).expect("UDP binds the port");
612 let _tcp = std::net::TcpListener::bind(bind).expect("TCP binds the port");
613 let fixed: SocketAddr = "127.0.0.1:4443".parse().unwrap();
614 assert_eq!(shared_port(fixed).unwrap(), fixed);
615 }
616
617 #[test]
618 fn the_auth_flags_parse() {
619 Cli::command().debug_assert();
620 let config = parse(&[]).expect("no flags");
621 assert!(config.auth_key.is_none() && config.auth_public.is_empty());
622 let config = parse(&["--auth-key", "keys.jwk"]).expect("a key");
623 assert_eq!(
624 config.auth_key.as_deref(),
625 Some(std::path::Path::new("keys.jwk"))
626 );
627 let config = parse(&["--auth-public", "anon,demo"]).expect("prefixes");
628 assert_eq!(config.auth_public.len(), 2);
629 assert!(
630 parse(&["--auth-public", "anon/**"]).is_err(),
631 "a wildcard is no prefix"
632 );
633 let config = parse(&["--auth-public", ""]).expect("the empty prefix");
634 assert_eq!(config.auth_public, [Prefix::all()]);
635 }
636
637 #[test]
638 fn a_key_and_another_auth_source_conflict() {
639 assert!(parse(&["--auth-key", "k", "--auth-url", "https://auth.example"]).is_err());
640 assert!(parse(&["--auth-key", "k", "--auth-public", "anon"]).is_err());
641 assert!(
642 parse(&[
643 "--auth-url",
644 "https://auth.example",
645 "--auth-public",
646 "anon"
647 ])
648 .is_err()
649 );
650 }
651
652 fn scratch() -> PathBuf {
654 std::env::temp_dir().join(format!(
655 "iroh-live-relay-keys-{}",
656 SecretKey::generate().public()
657 ))
658 }
659
660 fn generated() -> moq_auth::Key {
661 moq_auth::Key::generate(moq_auth::Algorithm::HS256, None).expect("a key")
662 }
663
664 #[test]
665 fn a_missing_key_file_is_a_keys_error() {
666 let path = scratch();
667 let Err(err) = load_keys(&path) else {
668 panic!("a missing file loaded");
669 };
670 assert!(
671 matches!(&err, Error::Keys { path: named, .. } if *named == path),
672 "{err:#}"
673 );
674 }
675
676 #[test]
677 fn a_file_that_holds_no_key_is_a_keys_error() {
678 let path = scratch();
679 std::fs::write(&path, b"nowhere near a key").expect("writes the scratch file");
680 let result = load_keys(&path);
681 std::fs::remove_file(&path).expect("removes the scratch file");
682 let Err(err) = result else {
683 panic!("a file without a key loaded");
684 };
685 assert!(matches!(err, Error::Keys { .. }), "{err:#}");
686 }
687
688 #[test]
689 fn a_single_key_and_a_key_set_both_load() {
690 let path = scratch();
691 let key = generated();
692 key.to_file(&path).expect("writes the key");
693 let single = load_keys(&path);
694 let set = KeySet {
695 keys: vec![Arc::new(generated()), Arc::new(generated())],
696 };
697 set.to_file(&path).expect("writes the set");
698 let both = load_keys(&path);
699 std::fs::remove_file(&path).expect("removes the scratch file");
700 let (single, source) = single.expect("one key");
701 assert_eq!(single.keys.len(), 1);
702 assert!(matches!(source, serve::Keys::File(named) if named == path));
703 let (both, source) = both.expect("a set");
704 assert_eq!(both.keys.len(), 2);
705 assert!(matches!(source, serve::Keys::Set(named) if named == path));
706 }
707}