Skip to main content

iroh_live_relay/
lib.rs

1//! A media relay that serves iroh-live broadcasts to browsers.
2//!
3//! Browsers connect over WebTransport, iroh clients over iroh. Anyone may
4//! subscribe to anything. An iroh client may publish only at paths that name
5//! its endpoint id ([`relay_policy`]), and a browser only at names of one
6//! segment.
7//!
8//! A session that names a broadcast ticket gets it pulled, see [`pull`]: the
9//! media relay dials the ticket's publisher over iroh. Since that makes the media relay
10//! dial an endpoint the client chose, only a session whose token grants
11//! reading the ticket's path may pull, and a media relay without `--auth-key`
12//! pulls nothing. `--open-pulls` lets any session pull, which suits a local
13//! or development media relay and is unsafe on a public one. Either way the pulls
14//! are capped in total and per client, and each client's new dials are rate
15//! limited ([`pull::Limits`]).
16//!
17//! With `--auth-key`, a session that presents a valid JWT gets what the token
18//! grants instead. A session without a token keeps the rules above, so the
19//! flag grants token holders more but does not make the media relay private. Browsers are decided by moq-auth's reference policy, and
20//! iroh clients by a [`KeyFile`]. Both read the key file again when it
21//! changes, so a rotated or removed key takes effect for new sessions without
22//! a restart. `--auth-url` and the `--auth-public` flags hand browser
23//! sessions to moq-relay's own auth, which then pulls no tickets.
24//!
25//! Another CLI can embed the media relay by flattening [`Config`] into its arguments.
26//!
27//! # Examples
28//!
29//! ```no_run
30//! use clap::Parser;
31//!
32//! #[derive(Parser)]
33//! struct Cli {
34//!     #[command(flatten)]
35//!     relay: iroh_live_relay::Config,
36//! }
37//!
38//! # async fn main_() -> Result<(), iroh_live_relay::Error> {
39//! iroh_live_relay::run(Cli::parse().relay).await
40//! # }
41//! ```
42//!
43//! [`run`] returns once a drain started by SIGINT or SIGTERM ends, after
44//! closing its listeners. Dropping its future stops the listeners and the
45//! accepted connections. The tasks that dial and hold a pull end with the
46//! last clone of their [`Pulls`](pull::Pulls): a linger window after
47//! the last session that named the ticket, or later while a dial or a resolve
48//! is in flight.
49
50#![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
78/// The bundled web viewer, embedded at build time.
79static WEB_DIR: Dir<'_> = include_dir!("$CARGO_MANIFEST_DIR/web/dist");
80
81/// Configuration for the media relay server, as clap arguments.
82#[derive(Args, Debug, Clone)]
83pub struct Config {
84    /// Bind address for WebTransport over QUIC.
85    #[arg(long, default_value = "[::]:4443")]
86    pub bind: SocketAddr,
87
88    /// Bind address for the web viewer over HTTP.
89    ///
90    /// Defaults to the --bind address, over TCP.
91    #[arg(long)]
92    pub http_bind: Option<SocketAddr>,
93
94    /// Grants token holders what their JWT allows, verified with the keys in this file.
95    ///
96    /// This does not restrict sessions without a token. They keep the public
97    /// rules: browsers and iroh clients read every broadcast, browsers publish
98    /// under `anon/`, and iroh clients publish at the paths that name
99    /// their endpoint id. A valid token replaces those rules with its claims,
100    /// and lets the session pull the tickets whose paths it may read.
101    ///
102    /// The file holds a JWK or a JWK set, as `moq auth` writes them. An
103    /// invalid token is refused. The media relay reads the file again when it
104    /// changes, so a rotated or removed key applies to new sessions without a
105    /// restart. Sessions already admitted keep their grant until their token
106    /// expires.
107    #[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    /// Asks this auth server about every browser session, as moq-relay does.
111    #[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    /// Lets every browser session publish and subscribe under these prefixes, as moq-relay does.
115    ///
116    /// A prefix covers its path and every path beneath it, and the empty
117    /// prefix `""` covers every path. A wildcard such as `anon/**` is refused.
118    #[arg(long, value_name = "PREFIX", value_delimiter = ',')]
119    pub auth_public: Vec<Prefix>,
120
121    /// Lets every browser session publish under these prefixes, as moq-relay does.
122    #[arg(long, value_name = "PREFIX", value_delimiter = ',')]
123    pub auth_public_publish: Vec<Prefix>,
124
125    /// Lets every browser session subscribe under these prefixes, as moq-relay does.
126    #[arg(long, value_name = "PREFIX", value_delimiter = ',')]
127    pub auth_public_subscribe: Vec<Prefix>,
128
129    /// Lets any session pull a ticket, with or without a token. Unsafe on a public media relay.
130    ///
131    /// A session that names a broadcast ticket makes the media relay dial the
132    /// ticket's iroh endpoint. Without this flag, only a session whose token,
133    /// verified with --auth-key, grants reading the ticket's path may do that,
134    /// so a media relay without --auth-key pulls nothing. With it, anyone who
135    /// reaches the media relay can make it dial any endpoint, within the pull
136    /// limits. Meant for local and development use.
137    #[arg(long)]
138    pub open_pulls: bool,
139
140    /// Bounds the pulls the media relay holds and starts.
141    ///
142    /// Defaults to [`pull::Limits::default`].
143    #[arg(skip)]
144    pub pull_limits: pull::Limits,
145
146    /// Decides the sessions of iroh clients, instead of the default.
147    ///
148    /// The default is [`relay_policy`], or with `--auth-key` a [`Verify`] of
149    /// the same keys with [`relay_policy`] as its fallback.
150    #[arg(skip)]
151    pub iroh_policy: Option<Arc<dyn DynPolicy<EndpointId>>>,
152}
153
154/// Runs the media relay server until a shutdown signal or an error.
155///
156/// The first SIGINT or SIGTERM drains the browser sessions, and a second one
157/// ends the media relay at once. It runs iroh and moq-relay on
158/// [`iroh_live_node::crypto_provider`], the backend the `crypto-*` features
159/// select, or on a provider the process installed before. The media relay prints
160/// its endpoint id and the addresses it listens at to stdout, for an
161/// operator and for the browser tests.
162///
163/// # Errors
164///
165/// Fails with [`Error::NoDataDir`] or [`Error::Identity`] if the media relay's
166/// identity cannot be loaded, [`Error::Bind`] if the iroh endpoint cannot
167/// bind, [`Error::Keys`] if the JWT keys cannot be read, and
168/// [`Error::Relay`] if the media relay cannot start or one of its listeners
169/// fails.
170pub async fn run(config: Config) -> Result<(), Error> {
171    // moq-relay builds its TLS configs on the process default, and moq
172    // installs rind there if nothing is installed. Install the selected
173    // backend before any of them.
174    iroh_live_node::crypto_provider();
175    // mDNS finds a ticket's publisher on this machine or LAN at once, where
176    // pkarr and DNS take seconds and need internet. `Announce`, since clients
177    // reach the relay by endpoint id.
178    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    // Browsers and iroh clients both read the file again when it changes.
192    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    // HTTP shares the QUIC port unless told otherwise. On port 0 moq-relay
205    // would draw a separate port for each, and the page, which dials the port
206    // it was served from, would find no QUIC listener there.
207    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    // Self-signed TLS. No ACME yet.
220    relay_config.listen.tls.generate = vec!["localhost".to_string()];
221    relay_config.web.http.listen = Some(http_bind);
222    // The viewer serves `/` and every other path, which the WebSocket
223    // fallback would take.
224    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    // Without an auth source of moq-relay's own, `admit` decides every
241    // browser session.
242    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    // Not moq-relay's iroh listener: `IrohSessions` accepts iroh clients,
260    // since it knows who they are.
261    let mut iroh_sessions =
262        IrohSessions::new(relay.cluster().clone(), Some(pulls)).with_policy(iroh_policy);
263    if let Some(verifier) = verifier {
264        // No fallback: a pull needs a token.
265        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    // The e2e test fixtures parse this line.
279    println!("http port: {http_port}");
280    // Plain `http`: the page pins the QUIC certificate's fingerprint from
281    // `/certificate.sha256`, so the browser never prompts.
282    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    // moq-relay's routes serve `/certificate.sha256` and apply CORS to GETs.
291    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
306/// Returns `bind` with a port that is free over both UDP and TCP, when `bind` asks for any port.
307///
308/// The probe sockets close before moq-relay binds the port, so another
309/// process can take it in between, and the media relay then fails to start rather
310/// than serve QUIC and HTTP on different ports.
311fn 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
327/// Wraps an error of moq-relay, which reports anyhow errors.
328fn relay_error(err: anyhow::Error) -> Error {
329    e!(Error::Relay {
330        source: Arc::new(AnyError::from_anyhow(err)),
331    })
332}
333
334/// Answers the media relay's admissions until the media relay drops its auth.
335///
336/// A session gets [`browser_grant`] for its path. With `keys`, moq-auth's
337/// reference policy decides it instead: a session that presents a JWT gets
338/// what the token grants until it expires, and one without a token gets the
339/// same public rule. The policy reads the key file again when it changes, so
340/// a rotated key takes effect without a restart.
341///
342/// A session whose path names a ticket reads the ticket's broadcast at that
343/// name, and is decided at the broadcast's path, so its token must reach that
344/// path. With `pulls` set it holds a pull of the broadcast while it runs, if
345/// the pulls' [`Access`](pull::Access) lets it pull and their
346/// [`Limits`](pull::Limits) have room. A session that may not pull is refused.
347///
348/// [`run`] calls it. It is public for a binary that embeds the media relay with a
349/// moq-relay of its own, and for the tests.
350pub 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        // A ticket's session reads the ticket's broadcast at its root, so it
371        // is decided where that broadcast lives.
372        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        // The session's root is the ticket it dialed, so this mounts the
388        // broadcast at that name.
389        grant
390            .mounts
391            .insert(String::new(), ticket.path().to_string());
392        debug!(path = %admission.request.path, "admitting a ticket's session");
393        // An attached admission verifies a token for a session already held.
394        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        // The lease ends with the session, and the pull's claim with it.
412        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
421/// Checks that a browser session may pull `ticket`, under the pulls' [`Access`](pull::Access).
422///
423/// Under [`Access::Authorized`](pull::Access::Authorized) the session's
424/// token, verified with `token_policy`, must grant reading the ticket's path.
425async 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    // The grant is rooted at the ticket's path, so the broadcast is its root.
443    match policy.decide(&at_ticket).await {
444        Ok(grant) if grant.subscribe.path.matches("") => Ok(()),
445        _ => Err(denied()),
446    }
447}
448
449/// Returns moq-auth's reference policy over `keys`, with the public rule of [`browser_grant`].
450fn 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
457/// Returns moq-auth's reference policy over `keys` without a public rule, so only a token passes.
458fn token_policy(keys: serve::Keys) -> serve::Policy {
459    let mut policy = serve::Policy::default();
460    policy.keys = Some(keys);
461    policy
462}
463
464/// Returns the grant of a browser session: the one `policy` decides, else [`browser_grant`].
465///
466/// The session is decided at `path` if set, else at the path it dialed. An
467/// attached admission is decided on the credential it presented in band.
468async 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
500/// Loads the JWT keys from a file that holds a JWK set or a single JWK.
501///
502/// Returns the keys, and the file as moq-auth's policy reads it again when it changes.
503fn 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
519/// Holds `pull` alongside the session that asked for `name`, and logs a failed dial.
520///
521/// Runs alongside the session, so a session that names an unreachable ticket
522/// still starts. Dropping the handle releases the session's hold on the pull.
523pub(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
538/// Loads the media relay's iroh identity, generating and storing one on first run.
539///
540/// Every ticket through this media relay names its endpoint id, so a file that does
541/// not hold a key is an error, and never a reason to make a new identity.
542fn 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
560/// Serves a file of the embedded web viewer, or a 404.
561fn 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
574/// Returns the content type for a file name, from its extension.
575fn 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    /// Any port resolves to one that UDP and TCP can both bind, and a fixed port stays.
607    #[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    /// Returns a path in the temp dir that nothing else uses.
653    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}