Skip to main content

rings_transport/
network_config.rs

1//! Transport network configuration and UDP port range invariants (#1291).
2
3use std::fmt;
4#[cfg(any(
5    all(feature = "dummy", not(target_family = "wasm")),
6    all(feature = "native-webrtc", not(target_family = "wasm")),
7    all(feature = "web-sys-webrtc", target_family = "wasm")
8))]
9use std::sync::Arc;
10
11use crate::core::transport::SharedTransport;
12
13/// A validated inclusive local UDP port range `[min, max]`.
14///
15/// `None` at the caller boundary means "use the OS/default ephemeral UDP port range".
16/// A present [`UdpPortRange`] always carries two non-zero bounds with `min <= max`.
17///
18/// # Invariant
19///
20/// `1 <= min <= max <= u16::MAX`.
21#[derive(Clone, Copy, Debug, Eq, PartialEq)]
22pub struct UdpPortRange {
23    /// Inclusive lower UDP port bound (`>= 1`).
24    min: u16,
25    /// Inclusive upper UDP port bound (`>= min`).
26    max: u16,
27}
28
29impl UdpPortRange {
30    /// Build a validated inclusive UDP port range `[min, max]`.
31    ///
32    /// # Errors
33    ///
34    /// - [`UdpPortRangeError::ZeroBound`] if either `min` or `max` is `0`.
35    /// - [`UdpPortRangeError::Inverted`] if `min > max`.
36    pub const fn new(min: u16, max: u16) -> Result<Self, UdpPortRangeError> {
37        if min == 0 || max == 0 {
38            return Err(UdpPortRangeError::ZeroBound { min, max });
39        }
40        if min > max {
41            return Err(UdpPortRangeError::Inverted { min, max });
42        }
43
44        Ok(Self { min, max })
45    }
46
47    /// Parse an optional `(min, max)` pair into a validated [`UdpPortRange`], rejecting
48    /// half-specified bounds where only one of `min` or `max` is present.
49    ///
50    /// # Errors
51    ///
52    /// - [`UdpPortRangeError::IncompleteBounds`] if only one of `min` or `max` is `Some`.
53    /// - [`UdpPortRangeError::ZeroBound`] or [`UdpPortRangeError::Inverted`] if both bounds are
54    ///   present but violate `1 <= min <= max`.
55    pub const fn from_optional_bounds(
56        min: Option<u16>,
57        max: Option<u16>,
58    ) -> Result<Option<Self>, UdpPortRangeError> {
59        match (min, max) {
60            (None, None) => Ok(None),
61            (Some(min), Some(max)) => match Self::new(min, max) {
62                Ok(range) => Ok(Some(range)),
63                Err(err) => Err(err),
64            },
65            (min, max) => Err(UdpPortRangeError::IncompleteBounds { min, max }),
66        }
67    }
68
69    /// The inclusive lower UDP port bound.
70    pub const fn min(self) -> u16 {
71        self.min
72    }
73
74    /// The inclusive upper UDP port bound.
75    pub const fn max(self) -> u16 {
76        self.max
77    }
78}
79
80/// Error returned when a UDP port range cannot witness the range invariant `1 <= min <= max`.
81#[derive(Clone, Copy, Debug, Eq, PartialEq)]
82pub enum UdpPortRangeError {
83    /// At least one bound is zero. Zero is reserved for the absent/default case.
84    ZeroBound {
85        /// Rejected lower bound.
86        min: u16,
87        /// Rejected upper bound.
88        max: u16,
89    },
90    /// The lower bound is greater than the upper bound.
91    Inverted {
92        /// Rejected lower bound.
93        min: u16,
94        /// Rejected upper bound.
95        max: u16,
96    },
97    /// Only one side of the port range was provided.
98    IncompleteBounds {
99        /// Provided lower bound, if any.
100        min: Option<u16>,
101        /// Provided upper bound, if any.
102        max: Option<u16>,
103    },
104}
105
106impl fmt::Display for UdpPortRangeError {
107    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
108        match self {
109            Self::ZeroBound { min, max } => write!(
110                f,
111                "UDP port range bounds must be non-zero: min={min}, max={max}"
112            ),
113            Self::Inverted { min, max } => {
114                write!(f, "UDP port range min must be <= max: min={min}, max={max}")
115            }
116            Self::IncompleteBounds { min, max } => write!(
117                f,
118                "Both UDP port range bounds must be set together: min={min:?}, max={max:?}"
119            ),
120        }
121    }
122}
123
124impl std::error::Error for UdpPortRangeError {}
125
126/// Default network configuration for the built-in traversal-assisted transport backend.
127///
128/// Holds the traversal/relay server specification (`traversal_servers`), optional advertised
129/// external endpoint locator (`endpoint_hint`), and optional local UDP ephemeral port range
130/// (`udp_port_range`).
131#[derive(Clone, Debug, Default, Eq, PartialEq)]
132pub struct TransportNetworkConfig {
133    /// Traversal/relay server specification string (used as the session credential template).
134    traversal_servers: String,
135    /// Optional external endpoint locator advertised by this node.
136    endpoint_hint: Option<String>,
137    /// Optional validated inclusive local UDP ephemeral port range `[min, max]`.
138    udp_port_range: Option<UdpPortRange>,
139}
140
141impl TransportNetworkConfig {
142    /// Construct a new [`TransportNetworkConfig`] from a traversal server specification string,
143    /// an optional advertised external endpoint locator, and an optional validated [`UdpPortRange`].
144    pub fn new(
145        traversal_servers: impl Into<String>,
146        endpoint_hint: Option<String>,
147        udp_port_range: Option<UdpPortRange>,
148    ) -> Self {
149        Self {
150            traversal_servers: traversal_servers.into(),
151            endpoint_hint,
152            udp_port_range,
153        }
154    }
155
156    /// Set the optional external endpoint hint advertised by this node.
157    pub fn with_endpoint_hint(mut self, endpoint_hint: Option<String>) -> Self {
158        self.endpoint_hint = endpoint_hint;
159        self
160    }
161
162    /// Set the optional local UDP port range constraint `[min, max]`.
163    pub const fn with_udp_port_range(mut self, udp_port_range: Option<UdpPortRange>) -> Self {
164        self.udp_port_range = udp_port_range;
165        self
166    }
167
168    /// Return the configured external endpoint hint, if any.
169    pub fn endpoint_hint(&self) -> Option<&str> {
170        self.endpoint_hint.as_deref()
171    }
172
173    /// Return the configured local UDP port range constraint, if any.
174    pub const fn udp_port_range(&self) -> Option<UdpPortRange> {
175        self.udp_port_range
176    }
177
178    /// Return the configured traversal server specification string.
179    pub fn traversal_servers(&self) -> &str {
180        &self.traversal_servers
181    }
182
183    /// Instantiate the active platform's production [`SharedTransport`] using
184    /// `initial_session_credential` (falling back to the raw `traversal_servers` specification
185    /// when no signed credential is supplied).
186    ///
187    /// Unlike Cargo feature unification, enabling `rings-transport/dummy` elsewhere in a workspace
188    /// dependency graph never overrides `WebrtcTransport` when `native-webrtc` is present; callers
189    /// that explicitly want the deterministic in-memory backend call `Self::build_dummy_transport`.
190    #[cfg(any(
191        all(
192            not(target_family = "wasm"),
193            any(feature = "native-webrtc", feature = "dummy")
194        ),
195        all(target_family = "wasm", feature = "web-sys-webrtc")
196    ))]
197    pub fn build_shared_transport(
198        &self,
199        initial_session_credential: Option<&str>,
200    ) -> SharedTransport {
201        let credentials = initial_session_credential.unwrap_or(&self.traversal_servers);
202        #[cfg(all(feature = "native-webrtc", not(target_family = "wasm")))]
203        {
204            Arc::new(crate::connections::WebrtcTransport::new(
205                credentials,
206                self.endpoint_hint.clone(),
207                self.udp_port_range,
208            ))
209        }
210        #[cfg(all(
211            feature = "dummy",
212            not(feature = "native-webrtc"),
213            not(target_family = "wasm")
214        ))]
215        {
216            Arc::new(crate::connections::DummyTransport::new(
217                credentials,
218                self.endpoint_hint.clone(),
219                self.udp_port_range,
220            ))
221        }
222        #[cfg(all(feature = "web-sys-webrtc", target_family = "wasm"))]
223        {
224            // Browser wasm32 is single-threaded; `SharedTransport` unifies native and browser
225            // behind `Arc<dyn DynTransportInterface>`.
226            #[allow(clippy::arc_with_non_send_sync)]
227            Arc::new(crate::connections::WebSysWebrtcTransport::new(
228                credentials,
229                self.endpoint_hint.clone(),
230                self.udp_port_range,
231            ))
232        }
233    }
234
235    /// Strictly parse and instantiate the active platform's production [`SharedTransport`],
236    /// failing closed with [`crate::error::Error::IceServer`] if the traversal server
237    /// specification or `initial_session_credential` is malformed.
238    #[cfg(any(
239        all(
240            not(target_family = "wasm"),
241            any(feature = "native-webrtc", feature = "dummy")
242        ),
243        all(target_family = "wasm", feature = "web-sys-webrtc")
244    ))]
245    pub fn try_build_shared_transport(
246        &self,
247        initial_session_credential: Option<&str>,
248    ) -> crate::error::Result<SharedTransport> {
249        let credentials = initial_session_credential.unwrap_or(&self.traversal_servers);
250        #[cfg(all(feature = "native-webrtc", not(target_family = "wasm")))]
251        {
252            Ok(Arc::new(crate::connections::WebrtcTransport::new_strict(
253                credentials,
254                self.endpoint_hint.clone(),
255                self.udp_port_range,
256            )?))
257        }
258        #[cfg(all(
259            feature = "dummy",
260            not(feature = "native-webrtc"),
261            not(target_family = "wasm")
262        ))]
263        {
264            Ok(Arc::new(crate::connections::DummyTransport::new_strict(
265                credentials,
266                self.endpoint_hint.clone(),
267                self.udp_port_range,
268            )?))
269        }
270        #[cfg(all(feature = "web-sys-webrtc", target_family = "wasm"))]
271        {
272            #[allow(clippy::arc_with_non_send_sync)]
273            let transport = Arc::new(crate::connections::WebSysWebrtcTransport::new_strict(
274                credentials,
275                self.endpoint_hint.clone(),
276                self.udp_port_range,
277            )?);
278            Ok(transport)
279        }
280    }
281
282    /// Explicitly instantiate the deterministic in-memory [`DummyTransport`](crate::connections::DummyTransport)
283    /// regardless of whether `native-webrtc` is also unified in the Cargo feature graph.
284    #[cfg(all(feature = "dummy", not(target_family = "wasm")))]
285    pub fn build_dummy_transport(
286        &self,
287        initial_session_credential: Option<&str>,
288    ) -> SharedTransport {
289        let credentials = initial_session_credential.unwrap_or(&self.traversal_servers);
290        Arc::new(crate::connections::DummyTransport::new(
291            credentials,
292            self.endpoint_hint.clone(),
293            self.udp_port_range,
294        ))
295    }
296
297    /// Strictly parse and instantiate the deterministic in-memory
298    /// [`DummyTransport`](crate::connections::DummyTransport), failing closed when the traversal
299    /// server specification or `initial_session_credential` is malformed.
300    #[cfg(all(feature = "dummy", not(target_family = "wasm")))]
301    pub fn try_build_dummy_transport(
302        &self,
303        initial_session_credential: Option<&str>,
304    ) -> crate::error::Result<SharedTransport> {
305        let credentials = initial_session_credential.unwrap_or(&self.traversal_servers);
306        Ok(Arc::new(crate::connections::DummyTransport::new_strict(
307            credentials,
308            self.endpoint_hint.clone(),
309            self.udp_port_range,
310        )?))
311    }
312
313    /// Inspect the currently committed session-bound credential string on a built-in transport
314    /// (`WebrtcTransport`, `DummyTransport`, or `WebSysWebrtcTransport`), returning `None` for
315    /// custom external transports that do not carry ICE server state.
316    pub fn session_credentials_of(transport: &SharedTransport) -> Option<String> {
317        let any = transport.as_any();
318        #[cfg(all(feature = "native-webrtc", not(target_family = "wasm")))]
319        if let Some(webrtc) = any.downcast_ref::<crate::connections::WebrtcTransport>() {
320            return Some(webrtc.session_credentials());
321        }
322        #[cfg(all(feature = "dummy", not(target_family = "wasm")))]
323        if let Some(dummy) = any.downcast_ref::<crate::connections::DummyTransport>() {
324            return Some(dummy.session_credentials());
325        }
326        #[cfg(all(feature = "web-sys-webrtc", target_family = "wasm"))]
327        if let Some(web_sys) = any.downcast_ref::<crate::connections::WebSysWebrtcTransport>() {
328            return Some(web_sys.session_credentials());
329        }
330        let _ = any;
331        None
332    }
333
334    /// Phase-1 preparation for two-phase session-key rotation on a built-in ICE-backed transport:
335    /// strictly parses `credentials` into `Vec<IceServer>` and verifies that `transport` is a
336    /// supported built-in backend **before** mutating any state, returning an infallible phase-2
337    /// commit closure that atomically swaps `(raw_credentials, parsed_ice_servers)`.
338    pub fn prepare_ice_server_rotation(
339        transport: &SharedTransport,
340        credentials: String,
341    ) -> crate::error::Result<Box<dyn FnOnce()>> {
342        let parsed = crate::ice_server::parse_ice_servers_strict(&credentials)?;
343        let any = transport.as_any();
344        #[cfg(all(feature = "native-webrtc", not(target_family = "wasm")))]
345        if any.is::<crate::connections::WebrtcTransport>() {
346            let handle = Arc::clone(transport);
347            return Ok(Box::new(move || {
348                if let Some(webrtc) = handle
349                    .as_any()
350                    .downcast_ref::<crate::connections::WebrtcTransport>()
351                {
352                    webrtc.commit_prepared_ice_servers(credentials, parsed);
353                }
354            }));
355        }
356        #[cfg(all(feature = "dummy", not(target_family = "wasm")))]
357        if any.is::<crate::connections::DummyTransport>() {
358            let handle = Arc::clone(transport);
359            return Ok(Box::new(move || {
360                if let Some(dummy) = handle
361                    .as_any()
362                    .downcast_ref::<crate::connections::DummyTransport>()
363                {
364                    dummy.commit_prepared_ice_servers(credentials, parsed);
365                }
366            }));
367        }
368        #[cfg(all(feature = "web-sys-webrtc", target_family = "wasm"))]
369        if any.is::<crate::connections::WebSysWebrtcTransport>() {
370            let handle = Arc::clone(transport);
371            return Ok(Box::new(move || {
372                if let Some(web_sys) = handle
373                    .as_any()
374                    .downcast_ref::<crate::connections::WebSysWebrtcTransport>()
375                {
376                    web_sys.commit_prepared_ice_servers(credentials, parsed);
377                }
378            }));
379        }
380        let _ = (any, parsed);
381        Err(crate::error::Error::UnsupportedOperation(
382            "transport backend does not support ICE server credential rotation".to_string(),
383        ))
384    }
385}
386
387#[cfg(test)]
388mod tests {
389    use super::*;
390
391    #[test]
392    fn test_udp_port_range_preserves_valid_bounds() {
393        let range = UdpPortRange::new(49160, 49200);
394
395        assert_eq!(
396            range,
397            Ok(UdpPortRange {
398                min: 49160,
399                max: 49200
400            })
401        );
402    }
403
404    #[test]
405    fn test_udp_port_range_rejects_zero_bound() {
406        let range = UdpPortRange::new(0, 49200);
407
408        assert_eq!(
409            range,
410            Err(UdpPortRangeError::ZeroBound { min: 0, max: 49200 })
411        );
412    }
413
414    #[test]
415    fn test_udp_port_range_rejects_inverted_bounds() {
416        let range = UdpPortRange::new(49200, 49160);
417
418        assert_eq!(
419            range,
420            Err(UdpPortRangeError::Inverted {
421                min: 49200,
422                max: 49160
423            })
424        );
425    }
426
427    #[test]
428    fn test_udp_port_range_rejects_incomplete_optional_bounds() {
429        assert_eq!(
430            UdpPortRange::from_optional_bounds(Some(49160), None),
431            Err(UdpPortRangeError::IncompleteBounds {
432                min: Some(49160),
433                max: None,
434            })
435        );
436        assert_eq!(UdpPortRange::from_optional_bounds(None, None), Ok(None));
437    }
438}