iroh_relay/protos/
relay.rs

1//! This module implements the send/recv relaying protocol.
2//!
3//! Protocol flow:
4//!  * server occasionally sends [`FrameType::Ping`]
5//!  * client responds to any [`FrameType::Ping`] with a [`FrameType::Pong`]
6//!  * clients sends [`FrameType::ClientToRelayDatagram`] or [`FrameType::ClientToRelayDatagramBatch`]
7//!  * server then sends [`FrameType::RelayToClientDatagram`] or [`FrameType::RelayToClientDatagramBatch`] to recipient
8//!  * server sends [`FrameType::EndpointGone`] when the other client disconnects
9
10use std::num::NonZeroU16;
11
12use bytes::{Buf, BufMut, Bytes, BytesMut};
13use iroh_base::{EndpointId, KeyParsingError};
14use n0_error::{e, ensure, stack_error};
15use n0_future::time::Duration;
16
17use super::common::{FrameType, FrameTypeError};
18use crate::{KeyCache, http::ProtocolVersion};
19
20/// The maximum size of a packet sent over relay.
21/// (This only includes the data bytes visible to the socket, not
22/// including its on-wire framing overhead)
23pub const MAX_PACKET_SIZE: usize = 64 * 1024;
24
25/// The maximum frame size.
26///
27/// This is also the minimum burst size that a rate-limiter has to accept.
28#[cfg(not(wasm_browser))]
29pub(crate) const MAX_FRAME_SIZE: usize = 1024 * 1024;
30
31/// Interval in which we ping the relay server to ensure the connection is alive.
32///
33/// The default QUIC max_idle_timeout is 30s, so setting that to half this time gives some
34/// chance of recovering.
35#[cfg(feature = "server")]
36pub(crate) const PING_INTERVAL: Duration = Duration::from_secs(15);
37
38/// The number of packets buffered for sending per client
39#[cfg(feature = "server")]
40pub const PER_CLIENT_SEND_QUEUE_DEPTH: usize = 512;
41
42/// Protocol send errors.
43#[stack_error(derive, add_meta, from_sources)]
44#[allow(missing_docs)]
45#[non_exhaustive]
46pub enum Error {
47    #[error("unexpected frame: got {got:?}, expected {expected:?}")]
48    UnexpectedFrame { got: FrameType, expected: FrameType },
49    #[error("Frame is too large, has {frame_len} bytes")]
50    FrameTooLarge { frame_len: usize },
51    #[error(transparent)]
52    FrameTypeError { source: FrameTypeError },
53    #[error("Invalid public key")]
54    InvalidPublicKey { source: KeyParsingError },
55    #[error("Invalid frame encoding")]
56    InvalidFrame {},
57    #[error("Invalid frame type: {frame_type:?}")]
58    InvalidFrameType { frame_type: FrameType },
59    #[error("Invalid protocol message encoding")]
60    InvalidProtocolMessageEncoding {
61        #[error(std_err)]
62        source: std::str::Utf8Error,
63    },
64    #[error("Received a frame not allowed in this protocol version.")]
65    FrameNotAllowedInVersion,
66    #[error("Too few bytes")]
67    TooSmall {},
68}
69
70/// The messages that a relay sends to clients or the clients receive from the relay.
71#[derive(Debug, Clone, PartialEq, Eq, strum::Display)]
72#[non_exhaustive]
73pub enum RelayToClientMsg {
74    /// Represents datagrams sent from relays (originally sent to them by another client).
75    Datagrams {
76        /// The [`EndpointId`] of the original sender.
77        remote_endpoint_id: EndpointId,
78        /// The datagrams and related metadata.
79        datagrams: Datagrams,
80    },
81    /// Indicates that the client identified by the underlying public key had previously sent you a
82    /// packet but has now disconnected from the relay.
83    EndpointGone(EndpointId),
84    /// A one-way message from relay to client, declaring the connection health state.
85    Status(Status),
86    /// A one-way message from relay to client, advertising that the relay is restarting.
87    Restarting {
88        /// An advisory duration that the client should wait before attempting to reconnect.
89        /// It might be zero. It exists for the relay to smear out the reconnects.
90        reconnect_in: Duration,
91        /// An advisory duration for how long the client should attempt to reconnect
92        /// before giving up and proceeding with its normal connection failure logic. The interval
93        /// between retries is undefined for now. A relay should not send a `try_for` duration more
94        /// than a few seconds.
95        try_for: Duration,
96    },
97    /// Request from the relay to reply to the
98    /// other side with a [`ClientToRelayMsg::Pong`] with the given payload.
99    Ping([u8; 8]),
100    /// Reply to a [`ClientToRelayMsg::Ping`] from a client
101    /// with the payload sent previously in the ping.
102    Pong([u8; 8]),
103
104    // -- Deprecated variants --
105    // We don't use `#[deprecated]` because this would throw warnings for the derived serde impls.
106    /// Removed since relay-protocol-v2:
107    /// A one-way message from relay to client, declaring the connection health state.
108    ///
109    /// Use [`Self::Status`] instead.
110    Health {
111        /// Description of why the connection is unhealthy.
112        ///
113        /// The default condition is healthy, so the relay doesn't broadcast a [`RelayToClientMsg::Health`]
114        /// until a problem exists.
115        problem: String,
116    },
117}
118
119/// One-way message from server to client indicating issues with the relay connection.
120#[derive(Debug, Clone, PartialEq, Eq, derive_more::Display)]
121#[non_exhaustive]
122pub enum Status {
123    /// The connection is healthy and recovered from previous problems.
124    #[display("The connection is healthy and has recovered from previous problems")]
125    Healthy,
126    /// Another endpoint connected with the same endpoint id. No more messages will be received.
127    #[display(
128        "Another endpoint connected with the same endpoint id. No more messages will be received."
129    )]
130    SameEndpointIdConnected,
131    /// The relay is rate-limiting traffic received from this endpoint.
132    ///
133    /// Sent once per connection when the relay first throttles reading from the client.
134    #[display(
135        "The relay is rate-limiting this endpoint; outbound relay traffic is being throttled. \
136        Send less data over the relay, or, if you operate this relay, raise Limits::client_rx. \
137        Read more about rate limiting at https://docs.iroh.computer/relays/rate-limiting"
138    )]
139    RateLimited,
140    /// Placeholder for backwards-compatibility for future new health status variants.
141    #[display("Unsupported health message ({_0})")]
142    Unknown(u8),
143}
144
145impl Status {
146    #[cfg(feature = "server")]
147    fn write_to<O: BufMut>(&self, mut dst: O) -> O {
148        match self {
149            Status::Healthy => dst.put_u8(0),
150            Status::SameEndpointIdConnected => dst.put_u8(1),
151            Status::RateLimited => dst.put_u8(2),
152            Status::Unknown(discriminant) => dst.put_u8(*discriminant),
153        }
154        dst
155    }
156
157    #[cfg(feature = "server")]
158    fn encoded_len(&self) -> usize {
159        1
160    }
161
162    fn from_bytes(mut bytes: Bytes) -> Result<Self, Error> {
163        ensure!(!bytes.is_empty(), Error::InvalidFrame);
164        let discriminant = bytes.get_u8();
165        match discriminant {
166            0 => Ok(Self::Healthy),
167            1 => Ok(Self::SameEndpointIdConnected),
168            2 => Ok(Self::RateLimited),
169            n => Ok(Self::Unknown(n)),
170        }
171    }
172}
173
174/// Messages that clients send to relays.
175#[derive(Debug, Clone, PartialEq, Eq)]
176#[non_exhaustive]
177pub enum ClientToRelayMsg {
178    /// Request from the client to the server to reply to the
179    /// other side with a [`RelayToClientMsg::Pong`] with the given payload.
180    Ping([u8; 8]),
181    /// Reply to a [`RelayToClientMsg::Ping`] from a server
182    /// with the payload sent previously in the ping.
183    Pong([u8; 8]),
184    /// Request from the client to relay datagrams to given remote endpoint.
185    Datagrams {
186        /// The remote endpoint to relay to.
187        dst_endpoint_id: EndpointId,
188        /// The datagrams and related metadata to relay.
189        datagrams: Datagrams,
190    },
191}
192
193/// One or multiple datagrams being transferred via the relay.
194///
195/// This type is modeled after [`noq_proto::Transmit`]
196/// (or even more similarly `noq_udp::Transmit`, but we don't depend on that library here).
197#[derive(derive_more::Debug, Clone, PartialEq, Eq)]
198pub struct Datagrams {
199    /// Explicit congestion notification bits
200    pub ecn: Option<noq_proto::EcnCodepoint>,
201    /// The segment size if this transmission contains multiple datagrams.
202    /// This is `None` if the transmit only contains a single datagram
203    pub segment_size: Option<NonZeroU16>,
204    /// The contents of the datagram(s)
205    #[debug(skip)]
206    pub contents: Bytes,
207}
208
209impl<T: AsRef<[u8]>> From<T> for Datagrams {
210    fn from(bytes: T) -> Self {
211        Self {
212            ecn: None,
213            segment_size: None,
214            contents: Bytes::copy_from_slice(bytes.as_ref()),
215        }
216    }
217}
218
219impl Datagrams {
220    /// Splits the current datagram into at maximum `num_segments` segments, returning
221    /// the batch with at most `num_segments` and leaving only the rest in `self`.
222    ///
223    /// Calling this on a datagram batch that only contains a single datagram (`segment_size == None`)
224    /// will result in returning essentially a clone of `self`, while making `self` empty afterwards.
225    ///
226    /// Calling this on a datagram batch with e.g. 15 datagrams with `num_segments == 10` will
227    /// result in returning a datagram batch that contains the first 10 datagrams and leave `self`
228    /// containing the remaining 5 datagrams.
229    ///
230    /// Calling this on a datagram batch with less than `num_segments` datagrams will result in
231    /// making `self` empty and returning essentially a clone of `self`.
232    pub fn take_segments(&mut self, num_segments: usize) -> Datagrams {
233        let Some(segment_size) = self.segment_size else {
234            let contents = std::mem::take(&mut self.contents);
235            return Datagrams {
236                ecn: self.ecn,
237                segment_size: None,
238                contents,
239            };
240        };
241
242        let usize_segment_size = usize::from(u16::from(segment_size));
243        let max_content_len = num_segments * usize_segment_size;
244        let contents = self
245            .contents
246            .split_to(std::cmp::min(max_content_len, self.contents.len()));
247
248        let is_datagram_batch = num_segments > 1 && usize_segment_size < contents.len();
249
250        // If this left our batch with only one more datagram, then remove the segment size
251        // to uphold the invariant that single-datagram batches don't have a segment size set.
252        if self.contents.len() <= usize_segment_size {
253            self.segment_size = None;
254        }
255
256        Datagrams {
257            ecn: self.ecn,
258            segment_size: is_datagram_batch.then_some(segment_size),
259            contents,
260        }
261    }
262
263    fn write_to<O: BufMut>(&self, mut dst: O) -> O {
264        let ecn = self.ecn.map_or(0, |ecn| ecn as u8);
265        dst.put_u8(ecn);
266        if let Some(segment_size) = self.segment_size {
267            dst.put_u16(segment_size.into());
268        }
269        dst.put(self.contents.as_ref());
270        dst
271    }
272
273    fn encoded_len(&self) -> usize {
274        1 // ECN byte
275        + self.segment_size.map_or(0, |_| 2) // segment size, when None, then a packed representation is assumed
276        + self.contents.len()
277    }
278
279    #[allow(clippy::len_zero, clippy::result_large_err)]
280    fn from_bytes(mut bytes: Bytes, is_batch: bool) -> Result<Self, Error> {
281        if is_batch {
282            // 1 bytes ECN, 2 bytes segment size
283            ensure!(bytes.len() >= 3, Error::InvalidFrame);
284        } else {
285            ensure!(bytes.len() >= 1, Error::InvalidFrame);
286        }
287
288        let ecn_byte = bytes.get_u8();
289        let ecn = noq_proto::EcnCodepoint::from_bits(ecn_byte);
290
291        let segment_size = if is_batch {
292            let segment_size = bytes.get_u16(); // length checked above
293            NonZeroU16::new(segment_size)
294        } else {
295            None
296        };
297
298        Ok(Self {
299            ecn,
300            segment_size,
301            contents: bytes,
302        })
303    }
304}
305
306impl RelayToClientMsg {
307    /// Returns this frame's corresponding frame type.
308    pub fn typ(&self) -> FrameType {
309        match self {
310            Self::Datagrams { datagrams, .. } => {
311                if datagrams.segment_size.is_some() {
312                    FrameType::RelayToClientDatagramBatch
313                } else {
314                    FrameType::RelayToClientDatagram
315                }
316            }
317            Self::EndpointGone { .. } => FrameType::EndpointGone,
318            Self::Ping { .. } => FrameType::Ping,
319            Self::Pong { .. } => FrameType::Pong,
320            Self::Status { .. } => FrameType::Status,
321            Self::Restarting { .. } => FrameType::Restarting,
322            Self::Health { .. } => FrameType::Health,
323        }
324    }
325
326    #[cfg(feature = "server")]
327    pub(crate) fn to_bytes(&self) -> BytesMut {
328        self.write_to(BytesMut::with_capacity(self.encoded_len()))
329    }
330
331    /// Encodes this frame for sending over websockets.
332    ///
333    /// Specifically meant for being put into a binary websocket message frame.
334    #[cfg(feature = "server")]
335    pub(crate) fn write_to<O: BufMut>(&self, mut dst: O) -> O {
336        dst = self.typ().write_to(dst);
337        match self {
338            Self::Datagrams {
339                remote_endpoint_id,
340                datagrams,
341            } => {
342                dst.put(remote_endpoint_id.as_ref());
343                dst = datagrams.write_to(dst);
344            }
345            Self::EndpointGone(endpoint_id) => {
346                dst.put(endpoint_id.as_ref());
347            }
348            Self::Ping(data) => {
349                dst.put(&data[..]);
350            }
351            Self::Pong(data) => {
352                dst.put(&data[..]);
353            }
354            Self::Health { problem } => {
355                dst.put(problem.as_ref());
356            }
357            Self::Restarting {
358                reconnect_in,
359                try_for,
360            } => {
361                dst.put_u32(reconnect_in.as_millis() as u32);
362                dst.put_u32(try_for.as_millis() as u32);
363            }
364            Self::Status(status) => {
365                dst = status.write_to(dst);
366            }
367        }
368        dst
369    }
370
371    #[cfg(feature = "server")]
372    pub(crate) fn encoded_len(&self) -> usize {
373        let payload_len = match self {
374            Self::Datagrams { datagrams, .. } => {
375                32 // endpointid
376                + datagrams.encoded_len()
377            }
378            Self::EndpointGone(_) => 32,
379            Self::Ping(_) | Self::Pong(_) => 8,
380            Self::Status(status) => status.encoded_len(),
381            Self::Restarting { .. } => {
382                4 // u32
383                + 4 // u32
384            }
385            Self::Health { problem } => problem.len(),
386        };
387        self.typ().encoded_len() + payload_len
388    }
389
390    /// Tries to decode a frame received over websockets.
391    ///
392    /// Specifically, bytes received from a binary websocket message frame.
393    ///
394    /// `protocol_version` is the negotiated protocol version for this connection.
395    #[allow(clippy::result_large_err)]
396    pub(crate) fn from_bytes(
397        mut content: Bytes,
398        cache: &KeyCache,
399        protocol_version: ProtocolVersion,
400    ) -> Result<Self, Error> {
401        let frame_type = FrameType::from_bytes(&mut content)?;
402        let frame_len = content.len();
403        ensure!(
404            frame_len <= MAX_PACKET_SIZE,
405            Error::FrameTooLarge { frame_len }
406        );
407
408        let res = match frame_type {
409            FrameType::RelayToClientDatagram | FrameType::RelayToClientDatagramBatch => {
410                ensure!(content.len() >= EndpointId::LENGTH, Error::InvalidFrame);
411
412                let remote_endpoint_id = cache.key_from_slice(&content[..EndpointId::LENGTH])?;
413                let datagrams = Datagrams::from_bytes(
414                    content.slice(EndpointId::LENGTH..),
415                    frame_type == FrameType::RelayToClientDatagramBatch,
416                )?;
417                Self::Datagrams {
418                    remote_endpoint_id,
419                    datagrams,
420                }
421            }
422            FrameType::EndpointGone => {
423                ensure!(content.len() == EndpointId::LENGTH, Error::InvalidFrame);
424                let endpoint_id = cache.key_from_slice(content.as_ref())?;
425                Self::EndpointGone(endpoint_id)
426            }
427            FrameType::Ping => {
428                ensure!(content.len() == 8, Error::InvalidFrame);
429                let mut data = [0u8; 8];
430                data.copy_from_slice(&content[..8]);
431                Self::Ping(data)
432            }
433            FrameType::Pong => {
434                ensure!(content.len() == 8, Error::InvalidFrame);
435                let mut data = [0u8; 8];
436                data.copy_from_slice(&content[..8]);
437                Self::Pong(data)
438            }
439            FrameType::Health => {
440                ensure!(
441                    protocol_version == ProtocolVersion::V1,
442                    Error::FrameNotAllowedInVersion
443                );
444                let problem = std::str::from_utf8(&content)?.to_owned();
445                Self::Health { problem }
446            }
447            FrameType::Restarting => {
448                ensure!(content.len() == 4 + 4, Error::InvalidFrame);
449                let reconnect_in = u32::from_be_bytes(
450                    content[..4]
451                        .try_into()
452                        .map_err(|_| e!(Error::InvalidFrame))?,
453                );
454                let try_for = u32::from_be_bytes(
455                    content[4..]
456                        .try_into()
457                        .map_err(|_| e!(Error::InvalidFrame))?,
458                );
459                let reconnect_in = Duration::from_millis(reconnect_in as u64);
460                let try_for = Duration::from_millis(try_for as u64);
461                Self::Restarting {
462                    reconnect_in,
463                    try_for,
464                }
465            }
466            FrameType::Status => {
467                ensure!(
468                    protocol_version >= ProtocolVersion::V2,
469                    Error::FrameNotAllowedInVersion
470                );
471                let status = Status::from_bytes(content)?;
472                Self::Status(status)
473            }
474            _ => {
475                return Err(e!(Error::InvalidFrameType { frame_type }));
476            }
477        };
478        Ok(res)
479    }
480}
481
482impl ClientToRelayMsg {
483    pub(crate) fn typ(&self) -> FrameType {
484        match self {
485            Self::Datagrams { datagrams, .. } => {
486                if datagrams.segment_size.is_some() {
487                    FrameType::ClientToRelayDatagramBatch
488                } else {
489                    FrameType::ClientToRelayDatagram
490                }
491            }
492            Self::Ping { .. } => FrameType::Ping,
493            Self::Pong { .. } => FrameType::Pong,
494        }
495    }
496
497    pub(crate) fn to_bytes(&self) -> BytesMut {
498        self.write_to(BytesMut::with_capacity(self.encoded_len()))
499    }
500
501    /// Encodes this frame for sending over websockets.
502    ///
503    /// Specifically meant for being put into a binary websocket message frame.
504    pub(crate) fn write_to<O: BufMut>(&self, mut dst: O) -> O {
505        dst = self.typ().write_to(dst);
506        match self {
507            Self::Datagrams {
508                dst_endpoint_id,
509                datagrams,
510            } => {
511                dst.put(dst_endpoint_id.as_ref());
512                dst = datagrams.write_to(dst);
513            }
514            Self::Ping(data) => {
515                dst.put(&data[..]);
516            }
517            Self::Pong(data) => {
518                dst.put(&data[..]);
519            }
520        }
521        dst
522    }
523
524    pub(crate) fn encoded_len(&self) -> usize {
525        let payload_len = match self {
526            Self::Ping(_) | Self::Pong(_) => 8,
527            Self::Datagrams { datagrams, .. } => {
528                32 // endpoint id
529                + datagrams.encoded_len()
530            }
531        };
532        self.typ().encoded_len() + payload_len
533    }
534
535    /// Tries to decode a frame received over websockets.
536    ///
537    /// Specifically, bytes received from a binary websocket message frame.
538    #[allow(clippy::result_large_err)]
539    #[cfg(feature = "server")]
540    pub(crate) fn from_bytes(mut content: Bytes, cache: &KeyCache) -> Result<Self, Error> {
541        // Check the full frame, including the frame type, so that the limit matches
542        // `encoded_len()` as checked by the client and by the server when forwarding.
543        let frame_len = content.len();
544        ensure!(
545            frame_len <= MAX_PACKET_SIZE,
546            Error::FrameTooLarge { frame_len }
547        );
548        let frame_type = FrameType::from_bytes(&mut content)?;
549
550        let res = match frame_type {
551            FrameType::ClientToRelayDatagram | FrameType::ClientToRelayDatagramBatch => {
552                ensure!(content.len() >= EndpointId::LENGTH, Error::InvalidFrame);
553
554                let dst_endpoint_id = cache.key_from_slice(&content[..EndpointId::LENGTH])?;
555                let datagrams = Datagrams::from_bytes(
556                    content.slice(EndpointId::LENGTH..),
557                    frame_type == FrameType::ClientToRelayDatagramBatch,
558                )?;
559                Self::Datagrams {
560                    dst_endpoint_id,
561                    datagrams,
562                }
563            }
564            FrameType::Ping => {
565                ensure!(content.len() == 8, Error::InvalidFrame);
566                let mut data = [0u8; 8];
567                data.copy_from_slice(&content[..8]);
568                Self::Ping(data)
569            }
570            FrameType::Pong => {
571                ensure!(content.len() == 8, Error::InvalidFrame);
572                let mut data = [0u8; 8];
573                data.copy_from_slice(&content[..8]);
574                Self::Pong(data)
575            }
576            _ => {
577                return Err(e!(Error::InvalidFrameType { frame_type }));
578            }
579        };
580        Ok(res)
581    }
582}
583
584#[cfg(test)]
585#[cfg(feature = "server")]
586mod tests {
587    use data_encoding::HEXLOWER;
588    use iroh_base::SecretKey;
589    use n0_error::Result;
590
591    use super::*;
592
593    fn check_expected_bytes(frames: Vec<(Vec<u8>, &str)>) {
594        for (bytes, expected_hex) in frames {
595            let stripped: Vec<u8> = expected_hex
596                .chars()
597                .filter_map(|s| {
598                    if s.is_ascii_whitespace() {
599                        None
600                    } else {
601                        Some(s as u8)
602                    }
603                })
604                .collect();
605            let expected_bytes = HEXLOWER.decode(&stripped).unwrap();
606            assert_eq!(HEXLOWER.encode(&bytes), HEXLOWER.encode(&expected_bytes));
607        }
608    }
609
610    #[test]
611    fn test_relay_client_frames_snapshot() -> Result {
612        let client_key = SecretKey::from_bytes(&[42u8; 32]);
613
614        check_expected_bytes(vec![
615            (
616                RelayToClientMsg::Health {
617                    problem: "Hello? Yes this is dog.".into(),
618                }
619                .write_to(Vec::new()),
620                "0b 48 65 6c 6c 6f 3f 20 59 65 73 20 74 68 69 73
621                20 69 73 20 64 6f 67 2e",
622            ),
623            (
624                RelayToClientMsg::EndpointGone(client_key.public()).write_to(Vec::new()),
625                "08 19 7f 6b 23 e1 6c 85 32 c6 ab c8 38 fa cd 5e
626                a7 89 be 0c 76 b2 92 03 34 03 9b fa 8b 3d 36 8d
627                61",
628            ),
629            (
630                RelayToClientMsg::Ping([42u8; 8]).write_to(Vec::new()),
631                "09 2a 2a 2a 2a 2a 2a 2a 2a",
632            ),
633            (
634                RelayToClientMsg::Pong([42u8; 8]).write_to(Vec::new()),
635                "0a 2a 2a 2a 2a 2a 2a 2a 2a",
636            ),
637            (
638                RelayToClientMsg::Datagrams {
639                    remote_endpoint_id: client_key.public(),
640                    datagrams: Datagrams {
641                        ecn: Some(noq::EcnCodepoint::Ce),
642                        segment_size: NonZeroU16::new(6),
643                        contents: "Hello World!".into(),
644                    },
645                }
646                .write_to(Vec::new()),
647                // frame type
648                // public key first 16 bytes
649                // public key second 16 bytes
650                // ECN byte
651                // segment size
652                // hello world contents bytes
653                "07
654                19 7f 6b 23 e1 6c 85 32 c6 ab c8 38 fa cd 5e a7
655                89 be 0c 76 b2 92 03 34 03 9b fa 8b 3d 36 8d 61
656                03
657                00 06
658                48 65 6c 6c 6f 20 57 6f 72 6c 64 21",
659            ),
660            (
661                RelayToClientMsg::Datagrams {
662                    remote_endpoint_id: client_key.public(),
663                    datagrams: Datagrams {
664                        ecn: Some(noq::EcnCodepoint::Ce),
665                        segment_size: None,
666                        contents: "Hello World!".into(),
667                    },
668                }
669                .write_to(Vec::new()),
670                // frame type
671                // public key first 16 bytes
672                // public key second 16 bytes
673                // ECN byte
674                // hello world contents bytes
675                "06
676                19 7f 6b 23 e1 6c 85 32 c6 ab c8 38 fa cd 5e a7
677                89 be 0c 76 b2 92 03 34 03 9b fa 8b 3d 36 8d 61
678                03
679                48 65 6c 6c 6f 20 57 6f 72 6c 64 21",
680            ),
681            (
682                RelayToClientMsg::Restarting {
683                    reconnect_in: Duration::from_millis(10),
684                    try_for: Duration::from_millis(20),
685                }
686                .write_to(Vec::new()),
687                "0c 00 00 00 0a 00 00 00 14",
688            ),
689            (
690                RelayToClientMsg::Status(Status::SameEndpointIdConnected).write_to(Vec::new()),
691                "0d 01",
692            ),
693            (
694                RelayToClientMsg::Status(Status::RateLimited).write_to(Vec::new()),
695                "0d 02",
696            ),
697        ]);
698
699        Ok(())
700    }
701
702    #[test]
703    fn test_client_relay_frames_snapshot() -> Result {
704        let client_key = SecretKey::from_bytes(&[42u8; 32]);
705
706        check_expected_bytes(vec![
707            (
708                ClientToRelayMsg::Ping([42u8; 8]).write_to(Vec::new()),
709                "09 2a 2a 2a 2a 2a 2a 2a 2a",
710            ),
711            (
712                ClientToRelayMsg::Pong([42u8; 8]).write_to(Vec::new()),
713                "0a 2a 2a 2a 2a 2a 2a 2a 2a",
714            ),
715            (
716                ClientToRelayMsg::Datagrams {
717                    dst_endpoint_id: client_key.public(),
718                    datagrams: Datagrams {
719                        ecn: Some(noq::EcnCodepoint::Ce),
720                        segment_size: NonZeroU16::new(6),
721                        contents: "Hello World!".into(),
722                    },
723                }
724                .write_to(Vec::new()),
725                // frame type
726                // public key first 16 bytes
727                // public key second 16 bytes
728                // ECN byte
729                // Segment size
730                // hello world contents
731                "05
732                19 7f 6b 23 e1 6c 85 32 c6 ab c8 38 fa cd 5e a7
733                89 be 0c 76 b2 92 03 34 03 9b fa 8b 3d 36 8d 61
734                03
735                00 06
736                48 65 6c 6c 6f 20 57 6f 72 6c 64 21",
737            ),
738            (
739                ClientToRelayMsg::Datagrams {
740                    dst_endpoint_id: client_key.public(),
741                    datagrams: Datagrams {
742                        ecn: Some(noq::EcnCodepoint::Ce),
743                        segment_size: None,
744                        contents: "Hello World!".into(),
745                    },
746                }
747                .write_to(Vec::new()),
748                // frame type
749                // public key first 16 bytes
750                // public key second 16 bytes
751                // ECN byte
752                // hello world contents
753                "04
754                19 7f 6b 23 e1 6c 85 32 c6 ab c8 38 fa cd 5e a7
755                89 be 0c 76 b2 92 03 34 03 9b fa 8b 3d 36 8d 61
756                03
757                48 65 6c 6c 6f 20 57 6f 72 6c 64 21",
758            ),
759        ]);
760
761        Ok(())
762    }
763
764    /// A datagram frame must contain at least an EndpointId (32 bytes) after
765    /// the frame type. A frame consisting only of the frame type byte used to
766    /// panic when slicing the destination endpoint id.
767    #[test]
768    fn regression_client_to_relay_undersized_datagram_rejected() {
769        for frame_type in [
770            FrameType::ClientToRelayDatagram,
771            FrameType::ClientToRelayDatagramBatch,
772        ] {
773            let encoded = frame_type.write_to(BytesMut::new()).freeze();
774            let result = ClientToRelayMsg::from_bytes(encoded, &KeyCache::test());
775            assert!(
776                matches!(result, Err(Error::InvalidFrame { .. })),
777                "expected InvalidFrame for {:?}, got {:?}",
778                frame_type,
779                result
780            );
781        }
782    }
783
784    /// A frame may be at most `MAX_PACKET_SIZE` bytes including its frame type, which is
785    /// the same limit that applies when a frame is encoded.
786    #[test]
787    fn client_to_relay_frame_size_limit() {
788        let dst = SecretKey::from_bytes(&[1u8; 32]).public();
789        for frame_type in [
790            FrameType::ClientToRelayDatagram,
791            FrameType::ClientToRelayDatagramBatch,
792        ] {
793            let frame_of_len = |len: usize| {
794                let mut buf = frame_type.write_to(BytesMut::with_capacity(len));
795                buf.put(dst.as_ref());
796                buf.put_u8(0); // ECN
797                if frame_type == FrameType::ClientToRelayDatagramBatch {
798                    buf.put_u16(1200); // segment size
799                }
800                buf.resize(len, 0);
801                buf.freeze()
802            };
803
804            let result =
805                ClientToRelayMsg::from_bytes(frame_of_len(MAX_PACKET_SIZE), &KeyCache::test());
806            match result {
807                Ok(msg) => assert_eq!(msg.encoded_len(), MAX_PACKET_SIZE),
808                Err(err) => panic!("expected {frame_type:?} to be accepted, got {err:?}"),
809            }
810
811            let result =
812                ClientToRelayMsg::from_bytes(frame_of_len(MAX_PACKET_SIZE + 1), &KeyCache::test());
813            assert!(
814                matches!(result, Err(Error::FrameTooLarge { .. })),
815                "expected FrameTooLarge for {frame_type:?}, got {result:?}"
816            );
817        }
818    }
819}
820
821#[cfg(all(test, feature = "server"))]
822mod proptests {
823    use iroh_base::SecretKey;
824    use proptest::{collection::vec, prelude::*};
825    use test_strategy::proptest;
826
827    use super::*;
828
829    fn secret_key() -> impl Strategy<Value = SecretKey> {
830        prop::array::uniform32(any::<u8>()).prop_map(SecretKey::from)
831    }
832
833    fn key() -> impl Strategy<Value = EndpointId> {
834        secret_key().prop_map(|key| key.public())
835    }
836
837    fn ecn() -> impl Strategy<Value = Option<noq_proto::EcnCodepoint>> {
838        (0..=3).prop_map(|n| match n {
839            1 => Some(noq_proto::EcnCodepoint::Ce),
840            2 => Some(noq_proto::EcnCodepoint::Ect0),
841            3 => Some(noq_proto::EcnCodepoint::Ect1),
842            _ => None,
843        })
844    }
845
846    fn datagrams() -> impl Strategy<Value = Datagrams> {
847        // The max payload size (conservatively, since with segment_size = 0 we'd have slightly more space)
848        const MAX_PAYLOAD_SIZE: usize = MAX_PACKET_SIZE - EndpointId::LENGTH - 1 /* ECN bytes */ - 2 /* segment size */;
849        (
850            ecn(),
851            prop::option::of(MAX_PAYLOAD_SIZE / 20..MAX_PAYLOAD_SIZE),
852            vec(any::<u8>(), 0..MAX_PAYLOAD_SIZE),
853        )
854            .prop_map(|(ecn, segment_size, data)| Datagrams {
855                ecn,
856                segment_size: segment_size
857                    .map(|ss| std::cmp::min(data.len(), ss) as u16)
858                    .and_then(NonZeroU16::new),
859                contents: Bytes::from(data),
860            })
861    }
862
863    /// Generates a random valid frame
864    fn relay_client_frame() -> impl Strategy<Value = RelayToClientMsg> {
865        let recv_packet = (key(), datagrams()).prop_map(|(remote_endpoint_id, datagrams)| {
866            RelayToClientMsg::Datagrams {
867                remote_endpoint_id,
868                datagrams,
869            }
870        });
871        let endpoint_gone = key().prop_map(RelayToClientMsg::EndpointGone);
872        let ping = prop::array::uniform8(any::<u8>()).prop_map(RelayToClientMsg::Ping);
873        let pong = prop::array::uniform8(any::<u8>()).prop_map(RelayToClientMsg::Pong);
874        let v1health = ".{0,65536}"
875            .prop_filter("exceeds MAX_PACKET_SIZE", |s| {
876                s.len() < MAX_PACKET_SIZE // a single unicode character can match a regex "." but take up multiple bytes
877            })
878            .prop_map(|problem| RelayToClientMsg::Health { problem });
879        let health = prop_oneof![
880            Just(Status::Healthy),
881            Just(Status::SameEndpointIdConnected),
882            Just(Status::RateLimited),
883        ]
884        .prop_map(RelayToClientMsg::Status);
885        let restarting = (any::<u32>(), any::<u32>()).prop_map(|(reconnect_in, try_for)| {
886            RelayToClientMsg::Restarting {
887                reconnect_in: Duration::from_millis(reconnect_in.into()),
888                try_for: Duration::from_millis(try_for.into()),
889            }
890        });
891        prop_oneof![
892            recv_packet,
893            endpoint_gone,
894            ping,
895            pong,
896            v1health,
897            restarting,
898            health
899        ]
900        .boxed()
901    }
902
903    fn client_relay_frame() -> impl Strategy<Value = ClientToRelayMsg> {
904        let send_packet = (key(), datagrams()).prop_map(|(dst_endpoint_id, datagrams)| {
905            ClientToRelayMsg::Datagrams {
906                dst_endpoint_id,
907                datagrams,
908            }
909        });
910        let ping = prop::array::uniform8(any::<u8>()).prop_map(ClientToRelayMsg::Ping);
911        let pong = prop::array::uniform8(any::<u8>()).prop_map(ClientToRelayMsg::Pong);
912        prop_oneof![send_packet, ping, pong]
913    }
914
915    /// The earliest protocol version in which `frame` is allowed.
916    fn allowed_version(frame: &RelayToClientMsg) -> ProtocolVersion {
917        match frame {
918            RelayToClientMsg::Health { .. } => ProtocolVersion::V1,
919            _ => ProtocolVersion::V2,
920        }
921    }
922
923    #[test]
924    fn v1health_rejected_in_v2() {
925        let frame = RelayToClientMsg::Health {
926            problem: "test".into(),
927        };
928        let encoded = frame.to_bytes().freeze();
929        let result = RelayToClientMsg::from_bytes(encoded, &KeyCache::test(), ProtocolVersion::V2);
930        assert!(matches!(
931            result,
932            Err(Error::FrameNotAllowedInVersion { .. })
933        ));
934    }
935
936    #[test]
937    fn status_rejected_in_v1() {
938        let frame = RelayToClientMsg::Status(Status::SameEndpointIdConnected);
939        let encoded = frame.to_bytes().freeze();
940        let result = RelayToClientMsg::from_bytes(encoded, &KeyCache::test(), ProtocolVersion::V1);
941        assert!(matches!(
942            result,
943            Err(Error::FrameNotAllowedInVersion { .. })
944        ));
945    }
946
947    #[proptest]
948    fn relay_client_frame_roundtrip(#[strategy(relay_client_frame())] frame: RelayToClientMsg) {
949        let version = allowed_version(&frame);
950        let encoded = frame.to_bytes().freeze();
951        let decoded = RelayToClientMsg::from_bytes(encoded, &KeyCache::test(), version).unwrap();
952        prop_assert_eq!(frame, decoded);
953    }
954
955    #[proptest]
956    fn client_relay_frame_roundtrip(#[strategy(client_relay_frame())] frame: ClientToRelayMsg) {
957        let encoded = frame.to_bytes().freeze();
958        let decoded = ClientToRelayMsg::from_bytes(encoded, &KeyCache::test()).unwrap();
959        prop_assert_eq!(frame, decoded);
960    }
961
962    #[proptest]
963    fn relay_client_frame_encoded_len(#[strategy(relay_client_frame())] frame: RelayToClientMsg) {
964        let claimed_encoded_len = frame.encoded_len();
965        let actual_encoded_len = frame.to_bytes().len();
966        prop_assert_eq!(claimed_encoded_len, actual_encoded_len);
967    }
968
969    #[proptest]
970    fn client_relay_frame_encoded_len(#[strategy(client_relay_frame())] frame: ClientToRelayMsg) {
971        let claimed_encoded_len = frame.encoded_len();
972        let actual_encoded_len = frame.to_bytes().len();
973        prop_assert_eq!(claimed_encoded_len, actual_encoded_len);
974    }
975
976    #[proptest]
977    fn datagrams_encoded_len(#[strategy(datagrams())] datagrams: Datagrams) {
978        let claimed_encoded_len = datagrams.encoded_len();
979        let actual_encoded_len = datagrams.write_to(Vec::new()).len();
980        prop_assert_eq!(claimed_encoded_len, actual_encoded_len);
981    }
982
983    const MAX_TEST_MSG_SIZE: usize = 100_000;
984
985    fn perturb_encoding(
986        inner: impl Strategy<Value = BytesMut> + Clone + 'static,
987    ) -> impl Strategy<Value = Bytes> + 'static {
988        #[derive(Debug, test_strategy::Arbitrary)]
989        enum GenStrategy {
990            ArbitraryBytes,
991            FlipBits,
992            Truncate,
993        }
994
995        any::<GenStrategy>().prop_ind_flat_map(move |strategy| match strategy {
996            GenStrategy::ArbitraryBytes => vec(any::<u8>(), 0..MAX_TEST_MSG_SIZE)
997                .prop_map(Bytes::from)
998                .boxed(),
999            GenStrategy::FlipBits => (vec(any::<u16>(), 0..20), any::<u8>(), inner.clone())
1000                .prop_map(|(byte_positions, mask, mut bytes)| {
1001                    let len = bytes.len();
1002                    for pos in byte_positions {
1003                        bytes[(pos as usize).min(len.saturating_sub(1))] ^= mask;
1004                    }
1005                    bytes.freeze()
1006                })
1007                .boxed(),
1008            GenStrategy::Truncate => (vec(any::<u16>(), 0..20), inner.clone())
1009                .prop_map(|(mut truncations, mut bytes)| {
1010                    truncations.sort();
1011                    let mut bytes_truncated = 0;
1012                    for [trunc_start, trunc_end] in truncations.as_chunks::<2>().0 {
1013                        let len = bytes.len();
1014                        let start = usize::from(*trunc_start).saturating_sub(bytes_truncated);
1015                        let end = usize::from(*trunc_end).saturating_sub(bytes_truncated);
1016                        let rest = bytes.split_off(end.min(len));
1017                        bytes.truncate(start.min(len));
1018                        bytes.extend_from_slice(&rest);
1019                        bytes_truncated += end - start;
1020                    }
1021                    bytes.freeze()
1022                })
1023                .boxed(),
1024        })
1025    }
1026
1027    #[proptest]
1028    fn client_relay_frame_decode_no_panic(
1029        #[strategy(perturb_encoding(client_relay_frame().boxed().prop_map(|msg| msg.to_bytes())))]
1030        bytes: Bytes,
1031    ) {
1032        let _ = ClientToRelayMsg::from_bytes(bytes, &KeyCache::test()); // only assert no panic
1033    }
1034
1035    #[proptest]
1036    fn relay_client_frame_decode_no_panic(
1037        #[strategy(perturb_encoding(relay_client_frame().boxed().prop_map(|msg| msg.to_bytes())))]
1038        bytes: Bytes,
1039        version: ProtocolVersion,
1040    ) {
1041        let _ = RelayToClientMsg::from_bytes(bytes, &KeyCache::test(), version); // only assert no panic
1042    }
1043}