iroh-relay 0.35.0

Iroh's relay server and client
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
//! The relay server for iroh.
//!
//! This handles only the CLI and config file loading, the server implementation lives in
//! [`iroh::relay::server`].

use std::{
    net::{Ipv6Addr, SocketAddr},
    path::{Path, PathBuf},
    sync::Arc,
};

use anyhow::{anyhow, bail, Context as _, Result};
use clap::Parser;
use http::StatusCode;
use iroh_base::NodeId;
use iroh_relay::{
    defaults::{
        DEFAULT_HTTPS_PORT, DEFAULT_HTTP_PORT, DEFAULT_METRICS_PORT, DEFAULT_RELAY_QUIC_PORT,
        DEFAULT_STUN_PORT,
    },
    server::{self as relay, ClientRateLimit, QuicConfig},
};
use n0_future::FutureExt;
use serde::{Deserialize, Serialize};
use tokio_rustls_acme::{caches::DirCache, AcmeConfig};
use tracing::{debug, warn};
use tracing_subscriber::{prelude::*, EnvFilter};
use url::Url;

/// The default `http_bind_port` when using `--dev`.
const DEV_MODE_HTTP_PORT: u16 = 3340;
/// The header name for setting the node id in HTTP auth requests.
const X_IROH_NODE_ID: &str = "X-Iroh-NodeId";
/// Environment variable to read a bearer token for HTTP auth requests from.
const ENV_HTTP_BEARER_TOKEN: &str = "IROH_RELAY_HTTP_BEARER_TOKEN";

/// A relay server for iroh.
#[derive(Parser, Debug, Clone)]
#[clap(version, about, long_about = None)]
struct Cli {
    /// Run in localhost development mode over plain HTTP.
    ///
    /// Defaults to running the relay server on port 3340.
    ///
    /// Running in dev mode will ignore any config file fields pertaining to TLS.
    #[clap(long, default_value_t = false)]
    dev: bool,
    /// Path to the configuration file.
    ///
    /// If provided and no configuration file exists the default configuration will be
    /// written to the file.
    #[clap(long, short)]
    config_path: Option<PathBuf>,
}

#[derive(clap::ValueEnum, Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
enum CertMode {
    Manual,
    LetsEncrypt,
    #[cfg(feature = "server")]
    Reloading,
}

fn load_certs(
    filename: impl AsRef<Path>,
) -> Result<Vec<rustls::pki_types::CertificateDer<'static>>> {
    let certfile = std::fs::File::open(filename).context("cannot open certificate file")?;
    let mut reader = std::io::BufReader::new(certfile);

    let certs: Result<Vec<_>, std::io::Error> = rustls_pemfile::certs(&mut reader).collect();
    let certs = certs?;

    Ok(certs)
}

fn load_secret_key(
    filename: impl AsRef<Path>,
) -> Result<rustls::pki_types::PrivateKeyDer<'static>> {
    let filename = filename.as_ref();
    let keyfile = std::fs::File::open(filename)
        .with_context(|| format!("cannot open secret key file {}", filename.display()))?;
    let mut reader = std::io::BufReader::new(keyfile);

    loop {
        match rustls_pemfile::read_one(&mut reader).context("cannot parse secret key .pem file")? {
            Some(rustls_pemfile::Item::Pkcs1Key(key)) => {
                return Ok(rustls::pki_types::PrivateKeyDer::Pkcs1(key));
            }
            Some(rustls_pemfile::Item::Pkcs8Key(key)) => {
                return Ok(rustls::pki_types::PrivateKeyDer::Pkcs8(key));
            }
            Some(rustls_pemfile::Item::Sec1Key(key)) => {
                return Ok(rustls::pki_types::PrivateKeyDer::Sec1(key));
            }
            None => break,
            _ => {}
        }
    }

    bail!(
        "no keys found in {} (encrypted keys not supported)",
        filename.display()
    );
}

/// Configuration for the relay-server.
///
/// This is (de)serialised to/from a TOML config file.
#[derive(Debug, Clone, Serialize, Deserialize)]
struct Config {
    /// Whether to enable the Relay server.
    ///
    /// Defaults to `true`.
    ///
    /// Disabling will leave only the STUN server.  The `http_bind_addr` and `tls`
    /// configuration options will be ignored.
    #[serde(default = "cfg_defaults::enable_relay")]
    enable_relay: bool,
    /// The socket address to bind the Relay HTTP server on.
    ///
    /// Defaults to `[::]:80`.
    ///
    /// When running with `--dev` defaults to `[::]:3340`.  If specified overrides these
    /// defaults.
    ///
    /// The Relay server always starts an HTTP server, this specifies the socket this will
    /// be bound on.  If there is no `tls` configuration set all the HTTP relay services
    /// will be bound on this socket.  Otherwise most Relay HTTP services will run on the
    /// `https_bind_addr` of the `tls` configuration section and only the captive portal
    /// will be served from the HTTP socket.
    http_bind_addr: Option<SocketAddr>,
    /// TLS specific configuration.
    ///
    /// TLS is disabled if not present and the Relay server will serve all services over
    /// plain HTTP.
    ///
    /// If disabled all services will run on plain HTTP.
    ///
    /// Must exist if `enable_quic_addr_discovery` is `true`.
    tls: Option<TlsConfig>,
    /// Whether to run a STUN server. It will bind to the same IP as the `addr` field.
    ///
    /// Defaults to `true`.
    #[serde(default = "cfg_defaults::enable_stun")]
    enable_stun: bool,
    /// The socket address to bind the STUN server on.
    ///
    /// Defaults to using the `http_bind_addr` with the port set to [`DEFAULT_STUN_PORT`].
    stun_bind_addr: Option<SocketAddr>,
    /// Whether to allow QUIC connections for QUIC address discovery
    ///
    /// If no `tls` is set, this will error.
    ///
    /// Defaults to `false`
    #[serde(default = "cfg_defaults::enable_quic_addr_discovery")]
    enable_quic_addr_discovery: bool,
    /// Rate limiting configuration.
    ///
    /// Disabled if not present.
    limits: Option<Limits>,
    /// Whether to run the metrics server.
    ///
    /// Defaults to `true`, when the metrics feature is enabled.
    #[serde(default = "cfg_defaults::enable_metrics")]
    enable_metrics: bool,
    /// Metrics serve address.
    ///
    /// Defaults to `http_bind_addr` with the port set to [`DEFAULT_METRICS_PORT`]
    /// (`[::]:9090` when `http_bind_addr` is set to the default).
    metrics_bind_addr: Option<SocketAddr>,
    /// The capacity of the key cache.
    key_cache_capacity: Option<usize>,
    /// Access control for relaying connections.
    ///
    /// This controls which nodes are allowed to relay connections, other endpoints, like STUN are not controlled by this.
    #[serde(default)]
    access: AccessConfig,
}

#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
enum AccessConfig {
    /// Allows everyone
    #[default]
    Everyone,
    /// Allows only these nodes.
    Allowlist(Vec<NodeId>),
    /// Allows everyone, except these nodes.
    Denylist(Vec<NodeId>),
    /// Performs a HTTP POST request to determine access for each node that connects to the relay.
    ///
    /// The request will have a header `X-Iroh-Node-Id` set to the hex-encoded node id attempting
    /// to connect to the relay.
    ///
    /// To grant access, the HTTP endpoint must return a `200` response with `true` as the response text.
    /// In all other cases, the node will be denied access.
    Http(HttpAccessConfig),
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
struct HttpAccessConfig {
    /// The URL to send the `POST` request to.
    url: Url,
    /// Optional bearer token for authorizing to the HTTP endpoint.
    ///
    /// If set, an `Authorization: Bearer {token}` header will be set on the HTTP request.
    /// The bearer token can also be set via the `IROH_RELAY_HTTP_BEARER_TOKEN` environment variable.
    /// If both the config and the environment variable are set, the value from the environment variable
    /// is used.
    bearer_token: Option<String>,
}

impl From<AccessConfig> for iroh_relay::server::AccessConfig {
    fn from(cfg: AccessConfig) -> Self {
        match cfg {
            AccessConfig::Everyone => iroh_relay::server::AccessConfig::Everyone,
            AccessConfig::Allowlist(allow_list) => {
                let allow_list = Arc::new(allow_list);
                iroh_relay::server::AccessConfig::Restricted(Box::new(move |node_id| {
                    let allow_list = allow_list.clone();
                    async move {
                        if allow_list.contains(&node_id) {
                            iroh_relay::server::Access::Allow
                        } else {
                            iroh_relay::server::Access::Deny
                        }
                    }
                    .boxed()
                }))
            }
            AccessConfig::Denylist(deny_list) => {
                let deny_list = Arc::new(deny_list);
                iroh_relay::server::AccessConfig::Restricted(Box::new(move |node_id| {
                    let deny_list = deny_list.clone();
                    async move {
                        if deny_list.contains(&node_id) {
                            iroh_relay::server::Access::Deny
                        } else {
                            iroh_relay::server::Access::Allow
                        }
                    }
                    .boxed()
                }))
            }
            AccessConfig::Http(mut config) => {
                let client = reqwest::Client::default();
                // Allow to set bearer token via environment variable as well.
                if let Ok(token) = std::env::var(ENV_HTTP_BEARER_TOKEN) {
                    config.bearer_token = Some(token);
                }
                let config = Arc::new(config);
                iroh_relay::server::AccessConfig::Restricted(Box::new(move |node_id| {
                    let client = client.clone();
                    let config = config.clone();
                    async move { http_access_check(&client, &config, node_id).await }.boxed()
                }))
            }
        }
    }
}

#[tracing::instrument("http-access-check", skip_all, fields(node_id=%node_id.fmt_short()))]
async fn http_access_check(
    client: &reqwest::Client,
    config: &HttpAccessConfig,
    node_id: NodeId,
) -> iroh_relay::server::Access {
    use iroh_relay::server::Access;
    debug!(url=%config.url, "Check relay access via HTTP POST");

    match http_access_check_inner(client, config, node_id).await {
        Ok(()) => {
            debug!("HTTP access check OK: Allow access");
            Access::Allow
        }
        Err(err) => {
            debug!("HTTP access check failed: Deny access (reason: {err:#})");
            Access::Deny
        }
    }
}

async fn http_access_check_inner(
    client: &reqwest::Client,
    config: &HttpAccessConfig,
    node_id: NodeId,
) -> Result<()> {
    let mut request = client
        .post(config.url.clone())
        .header(X_IROH_NODE_ID, node_id.to_string());
    if let Some(token) = config.bearer_token.as_ref() {
        request = request.header(http::header::AUTHORIZATION, format!("Bearer {token}"));
    }

    match request.send().await {
        Err(err) => {
            warn!("Failed to retrieve response for HTTP access check: {err:#}");
            Err(err).context("Failed to fetch response")
        }
        Ok(res) if res.status() == StatusCode::OK => match res.text().await {
            Ok(text) if text == "true" => Ok(()),
            Ok(_) => Err(anyhow!("Invalid response text (must be 'true')")),
            Err(err) => Err(err).context("Failed to read response"),
        },
        Ok(res) => Err(anyhow!("Received invalid status code ({})", res.status())),
    }
}

impl Config {
    fn http_bind_addr(&self) -> SocketAddr {
        self.http_bind_addr
            .unwrap_or((Ipv6Addr::UNSPECIFIED, DEFAULT_HTTP_PORT).into())
    }

    fn stun_bind_addr(&self) -> SocketAddr {
        self.stun_bind_addr
            .unwrap_or_else(|| SocketAddr::new(self.http_bind_addr().ip(), DEFAULT_STUN_PORT))
    }

    fn metrics_bind_addr(&self) -> SocketAddr {
        self.metrics_bind_addr
            .unwrap_or_else(|| SocketAddr::new(self.http_bind_addr().ip(), DEFAULT_METRICS_PORT))
    }
}

impl Default for Config {
    fn default() -> Self {
        Self {
            enable_relay: cfg_defaults::enable_relay(),
            http_bind_addr: None,
            tls: None,
            enable_stun: cfg_defaults::enable_stun(),
            stun_bind_addr: None,
            enable_quic_addr_discovery: cfg_defaults::enable_quic_addr_discovery(),
            limits: None,
            enable_metrics: cfg_defaults::enable_metrics(),
            metrics_bind_addr: None,
            key_cache_capacity: Default::default(),
            access: AccessConfig::Everyone,
        }
    }
}

/// Defaults for fields from [`Config`] [`TlsConfig`].
///
/// These are the defaults that serde will fill in.  Other defaults depends on each other
/// and can not immediately be substituted by serde.
mod cfg_defaults {
    pub(crate) fn enable_relay() -> bool {
        true
    }

    pub(crate) fn enable_stun() -> bool {
        true
    }

    pub(crate) fn enable_quic_addr_discovery() -> bool {
        false
    }

    pub(crate) fn enable_metrics() -> bool {
        true
    }

    pub(crate) mod tls_config {
        pub(crate) fn prod_tls() -> bool {
            true
        }

        pub(crate) fn dangerous_http_only() -> bool {
            false
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
struct TlsConfig {
    /// The socket address to bind the Relay HTTPS server on.
    ///
    /// Defaults to the `http_bind_addr` with the port set to `443`.
    https_bind_addr: Option<SocketAddr>,
    /// The socket address to bind the QUIC server one.
    ///
    /// Defaults to the `https_bind_addr` with the port set to [`iroh_relay::defaults::DEFAULT_RELAY_QUIC_PORT`].
    ///
    /// If `https_bind_addr` is not set, defaults to `http_bind_addr` with the
    /// port set to [`iroh_relay::defaults::DEFAULT_RELAY_QUIC_PORT`]
    quic_bind_addr: Option<SocketAddr>,
    /// Certificate hostname when using LetsEncrypt.
    hostname: Option<String>,
    /// Mode for getting a cert.
    ///
    /// Possible options: 'Manual', 'LetsEncrypt'.
    cert_mode: CertMode,
    /// Directory to store LetsEncrypt certs or read manual certificates from.
    ///
    /// Defaults to the servers' current working directory.
    cert_dir: Option<PathBuf>,
    /// Path of where to read the certificate from for the `Manual` and `Reloading` `cert_mode`.
    ///
    /// Defaults to `<cert_dir>/default.crt`.
    ///
    /// Only used when `cert_mode` is `Manual`.
    manual_cert_path: Option<PathBuf>,
    /// Path of where to read the private key from for the `Manual` `cert_mode`.
    ///
    /// Defaults to `<cert_dir>/default.key`.
    ///
    /// Only used when `cert_mode` is `Manual`.
    manual_key_path: Option<PathBuf>,
    /// Whether to use the LetsEncrypt production or staging server.
    ///
    /// Default is `true`.
    ///
    /// Only used when `cert_mode` is `LetsEncrypt`.
    ///
    /// While in development, LetsEncrypt prefers you to use the staging server. However,
    /// the staging server seems to only use `ECDSA` keys. In their current set up, you can
    /// only get intermediate certificates for `ECDSA` keys if you are on their
    /// "allowlist". The production server uses `RSA` keys, which allow for issuing
    /// intermediate certificates in all normal circumstances.  So, to have valid
    /// certificates, we must use the LetsEncrypt production server.  Read more here:
    /// <https://letsencrypt.org/certificates/#intermediate-certificates>.
    #[serde(default = "cfg_defaults::tls_config::prod_tls")]
    prod_tls: bool,
    /// The contact email for the tls certificate.
    ///
    /// Used when `cert_mode` is `LetsEncrypt`.
    contact: Option<String>,
    /// **This field should never be manually set**
    ///
    /// When `true`, it will force the relay to ignore binding to https. It is only
    /// ever used internally when the `--dev` flag is used on the CLI.
    ///
    /// Default is `false`.
    #[serde(default = "cfg_defaults::tls_config::dangerous_http_only")]
    dangerous_http_only: bool,
}

impl TlsConfig {
    fn https_bind_addr(&self, cfg: &Config) -> SocketAddr {
        self.https_bind_addr
            .unwrap_or_else(|| SocketAddr::new(cfg.http_bind_addr().ip(), DEFAULT_HTTPS_PORT))
    }

    fn quic_bind_addr(&self, cfg: &Config) -> SocketAddr {
        self.quic_bind_addr.unwrap_or_else(|| {
            SocketAddr::new(self.https_bind_addr(cfg).ip(), DEFAULT_RELAY_QUIC_PORT)
        })
    }

    fn cert_dir(&self) -> PathBuf {
        self.cert_dir.clone().unwrap_or_else(|| PathBuf::from("."))
    }

    fn cert_path(&self) -> PathBuf {
        self.manual_cert_path
            .clone()
            .unwrap_or_else(|| self.cert_dir().join("default.crt"))
    }

    fn key_path(&self) -> PathBuf {
        self.manual_key_path
            .clone()
            .unwrap_or_else(|| self.cert_dir().join("default.key"))
    }
}

#[derive(Debug, Clone, Default, Serialize, Deserialize)]
struct Limits {
    /// Rate limit for accepting new connection. Unlimited if not set.
    accept_conn_limit: Option<f64>,
    /// Burst limit for accepting new connection. Unlimited if not set.
    accept_conn_burst: Option<usize>,
    /// Rate limiting configuration per client.
    client: Option<PerClientRateLimitConfig>,
}

/// Rate limit configuration for each connected client.
///
/// The rate limiting uses a token-bucket style algorithm:
///
/// - The base rate limit uses a steady-stream rate of bytes allowed.
/// - Additionally a burst quota allows sending bytes over this steady-stream rate
///   limit, as long as the maximum burst quota is not exceeded.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
struct PerClientRateLimitConfig {
    /// Rate limit configuration for the incoming data from the client.
    rx: Option<RateLimitConfig>,
}

#[derive(Debug, Clone, Default, Serialize, Deserialize)]
struct RateLimitConfig {
    /// Maximum number of bytes per second.
    bytes_per_second: Option<u32>,
    /// Maximum number of bytes to read in a single burst.
    max_burst_bytes: Option<u32>,
}

impl Config {
    async fn load(opts: &Cli) -> Result<Self> {
        let config_path = if let Some(config_path) = &opts.config_path {
            config_path
        } else {
            return Ok(Config::default());
        };

        if config_path.exists() {
            Self::read_from_file(&config_path).await
        } else {
            Ok(Config::default())
        }
    }

    fn from_str(config: &str) -> Result<Self> {
        toml::from_str(config).context("config must be valid toml")
    }

    async fn read_from_file(path: impl AsRef<Path>) -> Result<Self> {
        if !path.as_ref().is_file() {
            bail!("config-path must be a file");
        }
        let config_ser = tokio::fs::read_to_string(&path)
            .await
            .context("unable to read config")?;
        Self::from_str(&config_ser)
    }
}

#[tokio::main]
async fn main() -> Result<()> {
    tracing_subscriber::registry()
        .with(tracing_subscriber::fmt::layer().with_writer(std::io::stderr))
        .with(EnvFilter::from_default_env())
        .init();

    let cli = Cli::parse();
    let mut cfg = Config::load(&cli).await?;
    if cfg.enable_quic_addr_discovery && cfg.tls.is_none() {
        bail!("TLS must be configured in order to spawn a QUIC endpoint");
    }
    if cli.dev {
        // When in `--dev` mode, do not use https, even when tls is configured.
        if let Some(ref mut tls) = cfg.tls {
            tls.dangerous_http_only = true;
        }
        if cfg.http_bind_addr.is_none() {
            cfg.http_bind_addr = Some((Ipv6Addr::UNSPECIFIED, DEV_MODE_HTTP_PORT).into());
        }
    }
    if cfg.tls.is_none() && cfg.enable_quic_addr_discovery {
        bail!("If QUIC address discovery is enabled, TLS must also be configured");
    };
    let relay_config = build_relay_config(cfg).await?;
    debug!("{relay_config:#?}");

    let mut relay = relay::Server::spawn(relay_config).await?;

    tokio::select! {
        biased;
        _ = tokio::signal::ctrl_c() => (),
        _ = relay.task_handle() => (),
    }

    relay.shutdown().await
}

async fn maybe_load_tls(
    cfg: &Config,
) -> Result<Option<relay::TlsConfig<std::io::Error, std::io::Error>>> {
    let Some(ref tls) = cfg.tls else {
        return Ok(None);
    };
    let server_config = rustls::ServerConfig::builder_with_provider(std::sync::Arc::new(
        rustls::crypto::ring::default_provider(),
    ))
    .with_safe_default_protocol_versions()
    .expect("protocols supported by ring")
    .with_no_client_auth();
    let (cert_config, server_config) = match tls.cert_mode {
        CertMode::Manual => {
            let cert_path = tls.cert_path();
            let key_path = tls.key_path();
            // Could probably just do this blocking, we're only starting up.
            let (private_key, certs) = tokio::task::spawn_blocking(move || {
                let key = load_secret_key(key_path)?;
                let certs = load_certs(cert_path)?;
                anyhow::Ok((key, certs))
            })
            .await??;
            let server_config = server_config.with_single_cert(certs.clone(), private_key)?;
            (relay::CertConfig::Manual { certs }, server_config)
        }
        CertMode::LetsEncrypt => {
            let hostname = tls
                .hostname
                .clone()
                .context("LetsEncrypt needs a hostname")?;
            let contact = tls
                .contact
                .clone()
                .context("LetsEncrypt needs a contact email")?;
            let config = AcmeConfig::new(vec![hostname.clone()])
                .contact([format!("mailto:{}", contact)])
                .cache_option(Some(DirCache::new(tls.cert_dir())))
                .directory_lets_encrypt(tls.prod_tls);
            let state = config.state();
            let resolver = state.resolver().clone();
            let server_config = server_config.with_cert_resolver(resolver);
            (relay::CertConfig::LetsEncrypt { state }, server_config)
        }
        #[cfg(feature = "server")]
        CertMode::Reloading => {
            use rustls_cert_file_reader::FileReader;
            use rustls_cert_reloadable_resolver::{key_provider::Dyn, CertifiedKeyLoader};
            use webpki::types::{CertificateDer, PrivateKeyDer};

            let cert_path = tls.cert_path();
            let key_path = tls.key_path();
            let interval = relay::DEFAULT_CERT_RELOAD_INTERVAL;

            let key_reader = rustls_cert_file_reader::FileReader::new(
                key_path,
                rustls_cert_file_reader::Format::PEM,
            );
            let certs_reader = rustls_cert_file_reader::FileReader::new(
                cert_path,
                rustls_cert_file_reader::Format::PEM,
            );

            let loader: CertifiedKeyLoader<
                Dyn,
                FileReader<PrivateKeyDer<'_>>,
                FileReader<Vec<CertificateDer<'_>>>,
            > = CertifiedKeyLoader {
                key_provider: Dyn(server_config.crypto_provider().key_provider),
                key_reader,
                certs_reader,
            };

            let resolver = Arc::new(relay::ReloadingResolver::init(loader, interval).await?);
            let server_config = server_config.with_cert_resolver(resolver);
            (relay::CertConfig::Reloading, server_config)
        }
    };
    Ok(Some(relay::TlsConfig {
        https_bind_addr: tls.https_bind_addr(cfg),
        cert: cert_config,
        server_config,
        quic_bind_addr: tls.quic_bind_addr(cfg),
    }))
}

/// Convert the TOML-loaded config to the [`relay::RelayConfig`] format.
async fn build_relay_config(cfg: Config) -> Result<relay::ServerConfig<std::io::Error>> {
    // Don't bind to https, even if tls configuration is available.
    // Is really only relevant if we are in `--dev` mode & we also have TLS configuration
    // enabled to use QUIC address discovery locally.
    let dangerous_http_only = cfg.tls.as_ref().is_some_and(|tls| tls.dangerous_http_only);
    let relay_tls = maybe_load_tls(&cfg).await?;

    let mut quic_config = None;
    if cfg.enable_quic_addr_discovery {
        if let Some(ref tls) = relay_tls {
            quic_config = Some(QuicConfig {
                server_config: tls.server_config.clone(),
                bind_addr: tls.quic_bind_addr,
            });
        } else {
            bail!("Must have a valid TLS configuration to enable a QUIC server for QUIC address discovery")
        }
    };
    let limits = match cfg.limits {
        Some(ref limits) => {
            let client_rx = match &limits.client {
                Some(PerClientRateLimitConfig { rx: Some(rx) }) => {
                    if rx.bytes_per_second.is_none() && rx.max_burst_bytes.is_some() {
                        bail!("bytes_per_seconds must be specified to enable the rate-limiter");
                    }
                    match rx.bytes_per_second {
                        Some(bps) => Some(ClientRateLimit {
                            bytes_per_second: bps
                                .try_into()
                                .context("bytes_per_second must be non-zero u32")?,
                            max_burst_bytes: rx
                                .max_burst_bytes
                                .map(|v| {
                                    v.try_into().context("max_burst_bytes must be non-zero u32")
                                })
                                .transpose()?,
                        }),
                        None => None,
                    }
                }
                Some(PerClientRateLimitConfig { rx: None }) | None => None,
            };
            relay::Limits {
                accept_conn_limit: limits.accept_conn_limit,
                accept_conn_burst: limits.accept_conn_burst,
                client_rx,
            }
        }
        None => Default::default(),
    };

    let relay_config = relay::RelayConfig {
        http_bind_addr: cfg.http_bind_addr(),
        // if `dangerous_http_only` is set, do not pass in any tls configuration
        tls: relay_tls.and_then(|tls| if dangerous_http_only { None } else { Some(tls) }),
        limits,
        key_cache_capacity: cfg.key_cache_capacity,
        access: cfg.access.clone().into(),
    };

    let stun_config = relay::StunConfig {
        bind_addr: cfg.stun_bind_addr(),
    };
    Ok(relay::ServerConfig {
        relay: Some(relay_config),
        stun: Some(stun_config).filter(|_| cfg.enable_stun),
        quic: quic_config,
        #[cfg(feature = "metrics")]
        metrics_addr: Some(cfg.metrics_bind_addr()).filter(|_| cfg.enable_metrics),
    })
}

#[cfg(test)]
mod tests {
    use std::num::NonZeroU32;

    use iroh_base::SecretKey;
    use rand::SeedableRng;
    use rand_chacha::ChaCha8Rng;
    use testresult::TestResult;

    use super::*;

    #[tokio::test]
    async fn test_rate_limit_config() -> TestResult {
        let config = "
            [limits.client.rx]
            bytes_per_second = 400
            max_burst_bytes = 800
        ";
        let config = Config::from_str(config)?;
        let relay_config = build_relay_config(config).await?;

        let relay = relay_config.relay.expect("no relay config");
        assert_eq!(
            relay.limits.client_rx.expect("ratelimit").bytes_per_second,
            NonZeroU32::try_from(400).unwrap()
        );
        assert_eq!(
            relay.limits.client_rx.expect("ratelimit").max_burst_bytes,
            Some(NonZeroU32::try_from(800).unwrap())
        );

        Ok(())
    }

    #[tokio::test]
    async fn test_rate_limit_default() -> TestResult {
        let config = Config::from_str("")?;
        let relay_config = build_relay_config(config).await?;

        let relay = relay_config.relay.expect("no relay config");
        assert!(relay.limits.client_rx.is_none());

        Ok(())
    }

    #[tokio::test]
    async fn test_access_config() -> TestResult {
        let config = "
            access = \"everyone\"
        ";
        let config = Config::from_str(config)?;
        assert_eq!(config.access, AccessConfig::Everyone);

        let mut rng = ChaCha8Rng::seed_from_u64(0);
        let node_id = SecretKey::generate(&mut rng).public();

        let config = format!(
            "
            access.allowlist = [
              \"{node_id}\",
            ]
        "
        );
        let config = Config::from_str(dbg!(&config))?;
        assert_eq!(config.access, AccessConfig::Allowlist(vec![node_id]));

        let config = r#"
            access.http.url = "https://example.com/foo/bar?boo=baz"
        "#
        .to_string();
        let config = Config::from_str(dbg!(&config))?;
        assert_eq!(
            config.access,
            AccessConfig::Http(HttpAccessConfig {
                url: "https://example.com/foo/bar?boo=baz".parse().unwrap(),
                bearer_token: None
            })
        );
        let config = r#"
            access.http.url = "https://example.com/foo/bar?boo=baz"
            access.http.bearer_token = "foo"
        "#
        .to_string();
        let config = Config::from_str(dbg!(&config))?;
        assert_eq!(
            config.access,
            AccessConfig::Http(HttpAccessConfig {
                url: "https://example.com/foo/bar?boo=baz".parse().unwrap(),
                bearer_token: Some("foo".to_string())
            })
        );

        let config = r#"
            access.http = { url = "https://example.com/foo" }
        "#
        .to_string();
        let config = Config::from_str(dbg!(&config))?;
        assert_eq!(
            config.access,
            AccessConfig::Http(HttpAccessConfig {
                url: "https://example.com/foo".parse().unwrap(),
                bearer_token: None
            })
        );

        let config = r#"
            access.http = { url = "https://example.com/foo", bearer_token = "foo" }
        "#
        .to_string();
        let config = Config::from_str(dbg!(&config))?;
        assert_eq!(
            config.access,
            AccessConfig::Http(HttpAccessConfig {
                url: "https://example.com/foo".parse().unwrap(),
                bearer_token: Some("foo".to_string())
            })
        );
        Ok(())
    }
}