From eebb60fef928d822a822adecdea092f2eaa00053 Mon Sep 17 00:00:00 2001 From: Franz Heinzmann Date: Tue, 5 May 2026 12:02:44 +0200 Subject: [PATCH] refactor!: Mark more items as non-exhaustive (#4226) ## Description Adds `#[non_exhaustive]` to more public structs and enums, so that fields and variants can be added without a breaking change. For each struct that has at least one field without a reasonable default a `new()` constructor is added that takes those required values and leaves the rest at their defaults. Remaining fields are then assigned through their public field directly. Structs that already had a `Default` impl keep it. Internal callers (the `iroh-relay` binary, `iroh::test_utils`, and the patchbay integration tests) are updated to use the new constructors and field assignment instead of struct literals. ## Breaking changes `iroh-base`: - `iroh_base::endpoint_addr::CustomAddrParseError` is now `#[non_exhaustive]`. `iroh`: - `iroh::endpoint::BeforeConnectOutcome` is now `#[non_exhaustive]`. - `iroh::endpoint::AfterHandshakeOutcome` is now `#[non_exhaustive]`. `iroh-relay`: - `iroh_relay::server::ServerConfig` is now `#[non_exhaustive]`. Already had a `Default` impl; construct via `ServerConfig::default()` and assign fields, e.g. `let mut c = ServerConfig::default(); c.relay = Some(...);`. - `iroh_relay::server::RelayConfig` is now `#[non_exhaustive]`. Added `RelayConfig::new(http_bind_addr: impl Into) -> Self`, which leaves `tls = None`, `limits = Limits::default()`, `key_cache_capacity = None`, and `access = AccessConfig::Everyone`. - `iroh_relay::server::AccessConfig` is now `#[non_exhaustive]`. - `iroh_relay::server::QuicConfig` is now `#[non_exhaustive]`. Added `QuicConfig::new(bind_addr: impl Into) -> Self`. - `iroh_relay::server::TlsConfig` is now `#[non_exhaustive]`. Added `TlsConfig::new(https_bind_addr: impl Into, cert: CertConfig) -> Self`. - `iroh_relay::server::Limits` is now `#[non_exhaustive]`. Use the `Default` impl and then set fields as needed. - `iroh_relay::server::ClientRateLimit` is now `#[non_exhaustive]`. Added `ClientRateLimit::new(bytes_per_second: NonZeroU32) -> Self`, which leaves `max_burst_bytes = None`. - `iroh_relay::server::CertConfig` is now `#[non_exhaustive]`. - `iroh_relay::server::client::Config` is now `#[non_exhaustive]`. Added `Config::new(endpoint_id: EndpointId, stream: RelayedStream, protocol_version: ProtocolVersion) -> Self`, which fills `write_timeout` from `defaults::timeouts::SERVER_WRITE_TIMEOUT` and `channel_capacity` from `protos::relay::PER_CLIENT_SEND_QUEUE_DEPTH`. - `iroh_relay::http::ProtocolVersion` is now `#[non_exhaustive]`. - `iroh_relay::protos::handshake::Mechanism` (cfg `server`) is now `#[non_exhaustive]`. `iroh-dns-server`: - `iroh_dns_server::config::DnsConfig` is now `#[non_exhaustive]`. Added `DnsConfig::new(port: u16, default_soa: String, default_ttl: u32, origins: Vec) -> Self`, which leaves `bind_addr = None` and the apex `rr_a`, `rr_aaaa`, `rr_ns` records at `None`. There is no `Default` impl: SOA, origins and port are deployment-specific and have no neutral default. ## Change checklist - [x] Self-review. - [x] Documentation updates following the [style guide](https://rust-lang.github.io/rfcs/1574-more-api-documentation-conventions.html#appendix-a-full-conventions-text), if relevant. - [x] All breaking changes documented. --- iroh-dns-server/src/dns.rs | 20 +++++++++ iroh-relay/src/http.rs | 1 + iroh-relay/src/main.rs | 66 +++++++++++++++--------------- iroh-relay/src/protos/handshake.rs | 2 + iroh-relay/src/server.rs | 58 ++++++++++++++++++++++++++ iroh-relay/src/server/client.rs | 24 ++++++++++- iroh/src/test_utils.rs | 39 +++++++----------- iroh/tests/patchbay/util.rs | 36 ++++++---------- 8 files changed, 163 insertions(+), 83 deletions(-) diff --git a/iroh-dns-server/src/dns.rs b/iroh-dns-server/src/dns.rs index 62a2291d60..dd8e17d58f 100644 --- a/iroh-dns-server/src/dns.rs +++ b/iroh-dns-server/src/dns.rs @@ -42,6 +42,7 @@ const DEFAULT_A_TTL: u32 = 60 * 60; // 1h /// Configuration for the DNS listener. #[derive(Clone, Debug, Serialize, Deserialize)] +#[non_exhaustive] pub struct DnsConfig { /// Port to bind the DNS listener to, for both UDP and TCP. pub port: u16, @@ -65,6 +66,25 @@ pub struct DnsConfig { pub rr_ns: Option, } +impl DnsConfig { + /// Creates a new [`DnsConfig`] with the given required fields. + /// + /// The optional `bind_addr` and apex resource records (`rr_a`, `rr_aaaa`, `rr_ns`) + /// default to `None`. Assign them after construction to override. + pub fn new(port: u16, default_soa: String, default_ttl: u32, origins: Vec) -> Self { + Self { + port, + bind_addr: None, + default_soa, + default_ttl, + origins, + rr_a: None, + rr_aaaa: None, + rr_ns: None, + } + } +} + /// A DNS server that serves pkarr signed packets. pub(crate) struct DnsServer { local_addr: SocketAddr, diff --git a/iroh-relay/src/http.rs b/iroh-relay/src/http.rs index b5bf134135..92b6132d90 100644 --- a/iroh-relay/src/http.rs +++ b/iroh-relay/src/http.rs @@ -40,6 +40,7 @@ pub const CLIENT_AUTH_HEADER: HeaderName = HeaderName::from_static("x-iroh-relay // Only used by the `all_is_exhaustive` to validate that `Self::ALL` is up to date. #[cfg_attr(test, derive(strum::EnumCount))] #[strum(parse_err_ty = UnsupportedRelayProtocolVersion, parse_err_fn = strum_err_fn)] +#[non_exhaustive] // Needs to be ordered with newest version last, so that the `Ord` impl orders by latest version as max. pub enum ProtocolVersion { /// Version 1 (the only version supported until iroh 0.98.0) diff --git a/iroh-relay/src/main.rs b/iroh-relay/src/main.rs index 1e8b224cb6..387eea94ba 100644 --- a/iroh-relay/src/main.rs +++ b/iroh-relay/src/main.rs @@ -605,11 +605,10 @@ async fn build_relay_config(cfg: Config) -> Result { let (tls_config, quic_config) = if let Some(cfg_tls) = &cfg.tls { let cert = load_cert_config(cfg_tls).await?; - let quic_config = cfg.enable_quic_addr_discovery.then(|| QuicConfig { - bind_addr: cfg_tls.quic_bind_addr(&cfg), - // Use the server config from the relay::TlsConfig - server_config: None, - }); + // Use the server config from the relay::TlsConfig + let quic_config = cfg + .enable_quic_addr_discovery + .then(|| QuicConfig::new(cfg_tls.quic_bind_addr(&cfg))); if cfg_tls.dangerous_http_only { // When `dangerous_http_only` is set through the --dev argument, @@ -624,16 +623,14 @@ async fn build_relay_config(cfg: Config) -> Result { relay::CertConfig::LetsEncrypt { .. } => { bail_any!("--dev is incompatible with cert_mode LetsEncrypt") } + _ => bail_any!("--dev is incompatible with this cert_mode"), }; Some(quic_config) } }; (None, quic_config) } else { - let tls_config = relay::TlsConfig { - https_bind_addr: cfg_tls.https_bind_addr(&cfg), - cert, - }; + let tls_config = relay::TlsConfig::new(cfg_tls.https_bind_addr(&cfg), cert); (Some(tls_config), quic_config) } } else if cfg.enable_quic_addr_discovery { @@ -650,49 +647,52 @@ async fn build_relay_config(cfg: Config) -> Result { bail_any!("bytes_per_seconds must be specified to enable the rate-limiter"); } match rx.bytes_per_second { - Some(bps) => Some(ClientRateLimit { - bytes_per_second: TryInto::::try_into(bps) - .std_context("bytes_per_second must be non-zero u32")?, - max_burst_bytes: rx + Some(bps) => { + let bps = TryInto::::try_into(bps) + .std_context("bytes_per_second must be non-zero u32")?; + let mut limit = ClientRateLimit::new(bps); + limit.max_burst_bytes = rx .max_burst_bytes .map(|v| { TryInto::::try_into(v) .std_context("max_burst_bytes must be non-zero u32") }) - .transpose()?, - }), + .transpose()?; + Some(limit) + } 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, - } + let mut out = relay::Limits::default(); + out.accept_conn_limit = limits.accept_conn_limit; + out.accept_conn_burst = limits.accept_conn_burst; + out.client_rx = client_rx; + out } None => Default::default(), }; let relay_config = if cfg.enable_relay { - Some(relay::RelayConfig { - http_bind_addr: cfg.http_bind_addr(), - tls: tls_config, - limits, - key_cache_capacity: cfg.key_cache_capacity, - access: cfg.access.clone().into(), - }) + let mut relay_config = relay::RelayConfig::new(cfg.http_bind_addr()); + relay_config.tls = tls_config; + relay_config.limits = limits; + relay_config.key_cache_capacity = cfg.key_cache_capacity; + relay_config.access = cfg.access.clone().into(); + Some(relay_config) } else { None }; - Ok(relay::ServerConfig { - relay: relay_config, - quic: quic_config, - #[cfg(feature = "metrics")] - metrics_addr: Some(cfg.metrics_bind_addr()).filter(|_| cfg.enable_metrics), - }) + let mut server_config = relay::ServerConfig::default(); + server_config.relay = relay_config; + server_config.quic = quic_config; + #[cfg(feature = "metrics")] + { + server_config.metrics_addr = Some(cfg.metrics_bind_addr()).filter(|_| cfg.enable_metrics); + } + Ok(server_config) } #[cfg(test)] diff --git a/iroh-relay/src/protos/handshake.rs b/iroh-relay/src/protos/handshake.rs index f18b979e1c..fceb000526 100644 --- a/iroh-relay/src/protos/handshake.rs +++ b/iroh-relay/src/protos/handshake.rs @@ -170,6 +170,7 @@ pub enum Error { #[cfg(feature = "server")] #[stack_error(derive, add_meta)] +#[non_exhaustive] pub(crate) enum VerificationError { #[error("Couldn't export TLS keying material on our end")] NoKeyingMaterial, @@ -385,6 +386,7 @@ pub struct SuccessfulAuthentication { /// The mechanism that was used for authentication. #[cfg(feature = "server")] #[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[non_exhaustive] pub enum Mechanism { /// Authentication was performed by verifying a signature of a challenge we sent SignedChallenge, diff --git a/iroh-relay/src/server.rs b/iroh-relay/src/server.rs index f0fca5d7fa..7afb009da9 100644 --- a/iroh-relay/src/server.rs +++ b/iroh-relay/src/server.rs @@ -97,6 +97,7 @@ fn body_empty() -> BytesBody { /// Be aware the generic parameters are for when using the Let's Encrypt TLS configuration. /// If not used dummy ones need to be provided, e.g. `ServerConfig::<(), ()>::default()`. #[derive(Debug, Default)] +#[non_exhaustive] pub struct ServerConfig { /// Configuration for the Relay server, disabled if `None`. pub relay: Option, @@ -112,6 +113,7 @@ pub struct ServerConfig { /// This includes the HTTP services hosted by the Relay server, the Relay `/relay` HTTP /// endpoint is only one of the services served. #[derive(Debug)] +#[non_exhaustive] pub struct RelayConfig { /// The socket address on which the Relay HTTP server should bind. /// @@ -134,6 +136,23 @@ pub struct RelayConfig { pub access: AccessConfig, } +impl RelayConfig { + /// Creates a new [`RelayConfig`] bound to `http_bind_addr` with default settings. + /// + /// TLS is disabled, default [`Limits`] are used, the key cache capacity is unset, and + /// access defaults to [`AccessConfig::Everyone`]. Adjust any of these by assigning to + /// the corresponding fields after construction. + pub fn new(http_bind_addr: impl Into) -> Self { + Self { + http_bind_addr: http_bind_addr.into(), + tls: None, + limits: Limits::default(), + key_cache_capacity: None, + access: AccessConfig::Everyone, + } + } +} + /// Details about an incoming relay client connection. /// /// Passed to the [`AccessConfig::Restricted`] callback to decide whether to @@ -226,6 +245,7 @@ pub enum Access { /// Configuration for the QUIC server. #[derive(Debug)] +#[non_exhaustive] pub struct QuicConfig { /// The socket address on which the QUIC server should bind. /// @@ -241,10 +261,23 @@ pub struct QuicConfig { pub server_config: Option, } +impl QuicConfig { + /// Creates a new [`QuicConfig`] bound to `bind_addr`. + /// + /// The TLS server config is left unset and inherited from [`RelayConfig::tls`]. + pub fn new(bind_addr: impl Into) -> Self { + Self { + bind_addr: bind_addr.into(), + server_config: None, + } + } +} + /// TLS configuration for Relay server. /// /// Normally the Relay server accepts connections on both HTTPS and HTTP. #[derive(Debug)] +#[non_exhaustive] pub struct TlsConfig { /// The socket address on which to serve the HTTPS server. /// @@ -258,9 +291,20 @@ pub struct TlsConfig { pub cert: CertConfig, } +impl TlsConfig { + /// Creates a new [`TlsConfig`] with the given bind address and certificate configuration. + pub fn new(https_bind_addr: impl Into, cert: CertConfig) -> Self { + Self { + https_bind_addr: https_bind_addr.into(), + cert, + } + } +} + /// Rate limits. // TODO: accept_conn_limit and accept_conn_burst are not currently implemented. #[derive(Debug, Default)] +#[non_exhaustive] pub struct Limits { /// Rate limit for accepting new connection. Unlimited if not set. pub accept_conn_limit: Option, @@ -272,6 +316,7 @@ pub struct Limits { /// Per-client rate limit configuration. #[derive(Debug, Copy, Clone)] +#[non_exhaustive] pub struct ClientRateLimit { /// Max number of bytes per second to read from the client connection. pub bytes_per_second: NonZeroU32, @@ -279,8 +324,21 @@ pub struct ClientRateLimit { pub max_burst_bytes: Option, } +impl ClientRateLimit { + /// Creates a new [`ClientRateLimit`] with the given byte rate. + /// + /// `max_burst_bytes` is left unset; assign it after construction to allow bursting. + pub fn new(bytes_per_second: NonZeroU32) -> Self { + Self { + bytes_per_second, + max_burst_bytes: None, + } + } +} + /// TLS certificate configuration. #[derive(Debug)] +#[non_exhaustive] pub enum CertConfig { /// Use Let's Encrypt. LetsEncrypt { diff --git a/iroh-relay/src/server/client.rs b/iroh-relay/src/server/client.rs index 7a07b0a454..fddd792353 100644 --- a/iroh-relay/src/server/client.rs +++ b/iroh-relay/src/server/client.rs @@ -16,9 +16,13 @@ use tracing::{Instrument, debug, trace, warn}; use crate::{ PingTracker, + defaults::timeouts::SERVER_WRITE_TIMEOUT, http::ProtocolVersion, protos::{ - relay::{ClientToRelayMsg, Datagrams, PING_INTERVAL, RelayToClientMsg, Status}, + relay::{ + ClientToRelayMsg, Datagrams, PER_CLIENT_SEND_QUEUE_DEPTH, PING_INTERVAL, + RelayToClientMsg, Status, + }, streams::BytesStreamSink, }, server::{ @@ -41,6 +45,7 @@ pub(super) struct Packet { /// /// Generic over the stream type to support different WebSocket implementations. #[derive(Debug)] +#[non_exhaustive] pub struct Config { /// The endpoint ID of the client pub endpoint_id: EndpointId, @@ -54,6 +59,23 @@ pub struct Config { pub protocol_version: ProtocolVersion, } +impl Config { + /// Creates a new config with sensible default values for `write_timeout` and `channel_capacity`. + pub fn new( + endpoint_id: EndpointId, + stream: RelayedStream, + protocol_version: ProtocolVersion, + ) -> Self { + Self { + endpoint_id, + stream, + protocol_version, + write_timeout: SERVER_WRITE_TIMEOUT, + channel_capacity: PER_CLIENT_SEND_QUEUE_DEPTH, + } + } +} + /// The [`Server`] side representation of a [`Client`]'s connection. /// /// [`Server`]: crate::server::Server diff --git a/iroh/src/test_utils.rs b/iroh/src/test_utils.rs index 703d8f72c7..1f262dbb29 100644 --- a/iroh/src/test_utils.rs +++ b/iroh/src/test_utils.rs @@ -44,31 +44,20 @@ pub async fn run_relay_server() -> Result<(RelayMap, RelayUrl, Server), SpawnErr pub async fn run_relay_server_with(quic: bool) -> Result<(RelayMap, RelayUrl, Server), SpawnError> { let (_certs, server_config) = iroh_relay::server::testing::self_signed_tls_certs_and_config(); - let tls = TlsConfig { - cert: CertConfig::Manual { - server_config: server_config.clone(), - }, - https_bind_addr: (Ipv4Addr::LOCALHOST, 0).into(), - }; - let quic = if quic { - Some(QuicConfig { - bind_addr: (Ipv4Addr::LOCALHOST, 0).into(), - server_config: None, - }) - } else { - None - }; - let config = ServerConfig { - relay: Some(RelayServerConfig { - http_bind_addr: (Ipv4Addr::LOCALHOST, 0).into(), - tls: Some(tls), - limits: Default::default(), - key_cache_capacity: Some(1024), - access: AccessConfig::Everyone, - }), - quic, - ..Default::default() - }; + let tls = TlsConfig::new( + (Ipv4Addr::LOCALHOST, 0), + CertConfig::Manual { server_config }, + ); + + let mut relay = RelayServerConfig::new((Ipv4Addr::LOCALHOST, 0)); + relay.tls = Some(tls); + relay.key_cache_capacity = Some(1024); + relay.access = AccessConfig::Everyone; + + let mut config = ServerConfig::default(); + config.relay = Some(relay); + config.quic = quic.then(|| QuicConfig::new((Ipv4Addr::LOCALHOST, 0))); + let server = Server::spawn(config).await?; let url: RelayUrl = format!("https://{}", server.https_addr().expect("configured")) .parse() diff --git a/iroh/tests/patchbay/util.rs b/iroh/tests/patchbay/util.rs index a11e1173c2..a01ec865f6 100644 --- a/iroh/tests/patchbay/util.rs +++ b/iroh/tests/patchbay/util.rs @@ -500,7 +500,7 @@ mod relay { RelayConfig, RelayMap, RelayQuicConfig, server::{ AccessConfig, CertConfig, QuicConfig, RelayConfig as RelayServerConfig, Server, - ServerConfig, SpawnError, TlsConfig, + ServerConfig, SpawnError, TlsConfig, testing::self_signed_tls_certs_and_config, }, }; @@ -512,30 +512,18 @@ mod relay { pub async fn run_relay_server() -> Result<(RelayMap, Server), SpawnError> { let bind_ip: IpAddr = Ipv6Addr::UNSPECIFIED.into(); - let (_certs, server_config) = - iroh_relay::server::testing::self_signed_tls_certs_and_config(); + let (_certs, server_config) = self_signed_tls_certs_and_config(); + + let tls = TlsConfig::new((bind_ip, 443), CertConfig::Manual { server_config }); + let mut relay = RelayServerConfig::new((bind_ip, 80)); + relay.tls = Some(tls); + relay.key_cache_capacity = Some(1024); + relay.access = AccessConfig::Everyone; + + let mut config = ServerConfig::default(); + config.relay = Some(relay); + config.quic = Some(QuicConfig::new((bind_ip, 7842))); - let tls = TlsConfig { - cert: CertConfig::Manual { - server_config: server_config.clone(), - }, - https_bind_addr: (bind_ip, 443).into(), - }; - let quic = Some(QuicConfig { - bind_addr: (bind_ip, 7842).into(), - server_config: None, - }); - let config = ServerConfig { - relay: Some(RelayServerConfig { - http_bind_addr: (bind_ip, 80).into(), - tls: Some(tls), - limits: Default::default(), - key_cache_capacity: Some(1024), - access: AccessConfig::Everyone, - }), - quic, - ..Default::default() - }; let server = Server::spawn(config).await?; let url: RelayUrl = "https://relay.test".parse().expect("valid relay url");