diff --git a/Cargo.lock b/Cargo.lock index 2b392560ed..409a3466d1 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -162,6 +162,18 @@ version = "1.7.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "69f7f8c3906b62b754cd5326047894316021dcfe5a194c8ea52bdd94934a3457" +[[package]] +name = "arrayref" +version = "0.3.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "76a2e8124351fda1ef8aaaa3bbd7ebbcb486bbcd4225aca0aa0d84bb2db8fecb" + +[[package]] +name = "arrayvec" +version = "0.7.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7c02d123df017efcdfbd739ef81735b36c5ba83ec3c59c80a9d7ecc718f92e50" + [[package]] name = "asn1-rs" version = "0.6.2" @@ -451,6 +463,19 @@ version = "2.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5c8214115b7bf84099f1309324e63141d4c5d7cc26862f97a0a857dbefe165bd" +[[package]] +name = "blake3" +version = "1.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3888aaa89e4b2a40fca9848e400f6a658a5a3978de7be858e209cafa8be9a4a0" +dependencies = [ + "arrayref", + "arrayvec", + "cc", + "cfg-if", + "constant_time_eq", +] + [[package]] name = "block-buffer" version = "0.10.4" @@ -687,6 +712,12 @@ version = "0.9.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c2459377285ad874054d797f3ccebf984978aa39129f6eafde5cdc8315b612f8" +[[package]] +name = "constant_time_eq" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7c74b8349d32d297c9134b8c88677813a227df8f779daa29bfc29c183fe3dca6" + [[package]] name = "cordyceps" version = "0.3.3" @@ -2483,6 +2514,7 @@ name = "iroh-relay" version = "0.90.0" dependencies = [ "ahash", + "blake3", "bytes", "cfg_aliases", "clap", @@ -2524,6 +2556,7 @@ dependencies = [ "rustls-pki-types", "rustls-webpki", "serde", + "serde_bytes", "serde_json", "sha1", "simdutf8", diff --git a/iroh-relay/Cargo.toml b/iroh-relay/Cargo.toml index be80149453..26b0b54f82 100644 --- a/iroh-relay/Cargo.toml +++ b/iroh-relay/Cargo.toml @@ -95,6 +95,8 @@ toml = { version = "0.8", optional = true } tracing-subscriber = { version = "0.3", features = [ "env-filter", ], optional = true } +blake3 = "1.8.2" +serde_bytes = "0.11.17" # non-wasm-in-browser dependencies [target.'cfg(not(all(target_family = "wasm", target_os = "unknown")))'.dependencies] diff --git a/iroh-relay/proptest-regressions/protos/relay.txt b/iroh-relay/proptest-regressions/protos/relay.txt index e718aef9a1..38aafe254c 100644 --- a/iroh-relay/proptest-regressions/protos/relay.txt +++ b/iroh-relay/proptest-regressions/protos/relay.txt @@ -5,3 +5,4 @@ # It is recommended to check this file in to source control so that # everyone who runs the test benefits from these saved cases. cc 9295f5287162dfb180e5826e563c2cea08b477b803ef412ff8351eb5c3eb45ef # shrinks to frame = KeepAlive +cc 753aabcf8ae2b4e4a52f451d58339aab85a4b61108afdf4b9600f97b3a33bf42 # shrinks to frame = Health { problem: None } diff --git a/iroh-relay/proptest-regressions/protos/send_recv.txt b/iroh-relay/proptest-regressions/protos/send_recv.txt new file mode 100644 index 0000000000..7ceca20bbb --- /dev/null +++ b/iroh-relay/proptest-regressions/protos/send_recv.txt @@ -0,0 +1,9 @@ +# Seeds for failure cases proptest has generated in the past. It is +# automatically read and these particular cases re-run before any +# novel cases are generated. +# +# It is recommended to check this file in to source control so that +# everyone who runs the test benefits from these saved cases. +cc 8f4f94b7c917bb0f52d31b529c3d580728ea57954ca45d91768cf4ae745e6eb9 # shrinks to frame = ReceivedDatagrams { remote_node_id: PublicKey(3b6a27bcceb6a42d62a3a8d02a6f0d73653215771de243a63ac048a18b59da29), datagrams: Datagrams { ecn: None, segment_size: Some(43846), .. } } +cc e40ca61e22386f1c76f717f2a6dbba367ea05d906317b3f979b46031567edbca # shrinks to frame = SendDatagrams { dst_node_id: PublicKey(3b6a27bcceb6a42d62a3a8d02a6f0d73653215771de243a63ac048a18b59da29), datagrams: Datagrams { ecn: None, segment_size: Some(44811), .. } } +cc 435ec32fc803db22bf4688a6356878073752b58fcd0b4422876fb3ab2a622684 # shrinks to a huge frame = Health { .. } diff --git a/iroh-relay/src/client.rs b/iroh-relay/src/client.rs index 582722d947..bcceb64bb3 100644 --- a/iroh-relay/src/client.rs +++ b/iroh-relay/src/client.rs @@ -22,10 +22,17 @@ use tracing::warn; use tracing::{debug, event, trace, Level}; use url::Url; -pub use self::conn::{ReceivedMessage, RecvError, SendError, SendMessage}; +pub use self::conn::{RecvError, SendError}; #[cfg(not(wasm_browser))] use crate::dns::{DnsError, DnsResolver}; -use crate::{http::RELAY_PATH, protos::relay::SendError as SendRelayError, KeyCache}; +use crate::{ + http::RELAY_PATH, + protos::{ + handshake, + relay::{ClientToRelayMsg, RelayToClientMsg}, + }, + KeyCache, +}; pub(crate) mod conn; #[cfg(not(wasm_browser))] @@ -60,7 +67,7 @@ pub enum ConnectError { source: ws_stream_wasm::WsErr, }, #[snafu(transparent)] - Handshake { source: SendRelayError }, + Handshake { source: handshake::Error }, #[snafu(transparent)] Dial { source: DialError }, #[snafu(display("Unexpected status during upgrade: {code}"))] @@ -117,8 +124,6 @@ pub struct ClientBuilder { /// Default is None #[debug("address family selector callback")] address_family_selector: Option bool + Send + Sync>>, - /// Default is false - is_prober: bool, /// Server url. url: RelayUrl, /// Allow self-signed certificates from relay servers @@ -144,7 +149,6 @@ impl ClientBuilder { ) -> Self { ClientBuilder { address_family_selector: None, - is_prober: false, url: url.into(), #[cfg(any(test, feature = "test-utils"))] @@ -172,12 +176,6 @@ impl ClientBuilder { self } - /// Indicates this client is a prober - pub fn is_prober(mut self, is: bool) -> Self { - self.is_prober = is; - self - } - /// Skip the verification of the relay server's SSL certificates. /// /// May only be used in tests. @@ -202,9 +200,13 @@ impl ClientBuilder { /// Establishes a new connection to the relay server. #[cfg(not(wasm_browser))] pub async fn connect(&self) -> Result { + use http::header::SEC_WEBSOCKET_PROTOCOL; use tls::MaybeTlsStreamBuilder; - use crate::protos::relay::MAX_FRAME_SIZE; + use crate::{ + http::{CLIENT_AUTH_HEADER, RELAY_PROTOCOL_VERSION}, + protos::{handshake::KeyMaterialClientAuth, relay::MAX_FRAME_SIZE}, + }; let mut dial_url = (*self.url).clone(); dial_url.set_path(RELAY_PATH); @@ -240,7 +242,7 @@ impl ClientBuilder { .as_ref() .local_addr() .map_err(|_| NoLocalAddrSnafu.build())?; - let (conn, response) = tokio_websockets::ClientBuilder::new() + let mut builder = tokio_websockets::ClientBuilder::new() .uri(dial_url.as_str()) .map_err(|_| { InvalidRelayUrlSnafu { @@ -248,9 +250,25 @@ impl ClientBuilder { } .build() })? + .add_header( + SEC_WEBSOCKET_PROTOCOL, + http::HeaderValue::from_static(RELAY_PROTOCOL_VERSION), + ) + .expect("valid header name and value") .limits(tokio_websockets::Limits::default().max_payload_len(Some(MAX_FRAME_SIZE))) - .connect_on(stream) - .await?; + // We turn off automatic flushing after a threshold (the default would be after 8KB). + // This means we need to flush manually, which we do by calling `Sink::send_all` or + // `Sink::send` (which calls `Sink::flush`) in the `ActiveRelayActor`. + .config(tokio_websockets::Config::default().flush_threshold(usize::MAX)); + if let Some(client_auth) = KeyMaterialClientAuth::new(&self.secret_key, &stream) { + debug!("Using TLS key export for relay client authentication"); + builder = builder + .add_header(CLIENT_AUTH_HEADER, client_auth.into_header_value()) + .expect( + "impossible: CLIENT_AUTH_HEADER isn't a disallowed header value for websockets", + ); + } + let (conn, response) = builder.connect_on(stream).await?; if response.status() != hyper::StatusCode::SWITCHING_PROTOCOLS { UnexpectedUpgradeStatusSnafu { @@ -291,6 +309,8 @@ impl ClientBuilder { /// Establishes a new connection to the relay server. #[cfg(wasm_browser)] pub async fn connect(&self) -> Result { + use crate::http::RELAY_PROTOCOL_VERSION; + let mut dial_url = (*self.url).clone(); dial_url.set_path(RELAY_PATH); // The relay URL is exchanged with the http(s) scheme in tickets and similar. @@ -310,7 +330,9 @@ impl ClientBuilder { debug!(%dial_url, "Dialing relay by websocket"); - let (_, ws_stream) = ws_stream_wasm::WsMeta::connect(dial_url.as_str(), None).await?; + let (_, ws_stream) = + ws_stream_wasm::WsMeta::connect(dial_url.as_str(), Some(vec![RELAY_PROTOCOL_VERSION])) + .await?; let conn = Conn::new(ws_stream, self.key_cache.clone(), &self.secret_key).await?; event!( @@ -350,24 +372,24 @@ impl Client { } impl Stream for Client { - type Item = Result; + type Item = Result; fn poll_next(mut self: Pin<&mut Self>, cx: &mut task::Context<'_>) -> Poll> { Pin::new(&mut self.conn).poll_next(cx) } } -impl Sink for Client { +impl Sink for Client { type Error = SendError; fn poll_ready( mut self: Pin<&mut Self>, cx: &mut task::Context<'_>, ) -> Poll> { - >::poll_ready(Pin::new(&mut self.conn), cx) + Pin::new(&mut self.conn).poll_ready(cx) } - fn start_send(mut self: Pin<&mut Self>, item: SendMessage) -> Result<(), Self::Error> { + fn start_send(mut self: Pin<&mut Self>, item: ClientToRelayMsg) -> Result<(), Self::Error> { Pin::new(&mut self.conn).start_send(item) } @@ -375,24 +397,24 @@ impl Sink for Client { mut self: Pin<&mut Self>, cx: &mut task::Context<'_>, ) -> Poll> { - >::poll_flush(Pin::new(&mut self.conn), cx) + Pin::new(&mut self.conn).poll_flush(cx) } fn poll_close( mut self: Pin<&mut Self>, cx: &mut task::Context<'_>, ) -> Poll> { - >::poll_close(Pin::new(&mut self.conn), cx) + Pin::new(&mut self.conn).poll_close(cx) } } /// The send half of a relay client. #[derive(Debug)] pub struct ClientSink { - sink: SplitSink, + sink: SplitSink, } -impl Sink for ClientSink { +impl Sink for ClientSink { type Error = SendError; fn poll_ready( @@ -402,7 +424,7 @@ impl Sink for ClientSink { Pin::new(&mut self.sink).poll_ready(cx) } - fn start_send(mut self: Pin<&mut Self>, item: SendMessage) -> Result<(), Self::Error> { + fn start_send(mut self: Pin<&mut Self>, item: ClientToRelayMsg) -> Result<(), Self::Error> { Pin::new(&mut self.sink).start_send(item) } @@ -436,7 +458,7 @@ impl ClientStream { } impl Stream for ClientStream { - type Item = Result; + type Item = Result; fn poll_next(mut self: Pin<&mut Self>, cx: &mut task::Context<'_>) -> Poll> { Pin::new(&mut self.stream).poll_next(cx) diff --git a/iroh-relay/src/client/conn.rs b/iroh-relay/src/client/conn.rs index d7f5031243..39621482af 100644 --- a/iroh-relay/src/client/conn.rs +++ b/iroh-relay/src/client/conn.rs @@ -3,26 +3,24 @@ //! based on tailscale/derp/derp_client.go use std::{ - io, pin::Pin, - str::Utf8Error, task::{ready, Context, Poll}, }; -use bytes::Bytes; -use iroh_base::{NodeId, SecretKey}; -use n0_future::{time::Duration, Sink, Stream}; +use iroh_base::SecretKey; +use n0_future::{Sink, Stream}; use nested_enum_utils::common_fields; -use snafu::{Backtrace, ResultExt, Snafu}; -use tracing::{debug, warn}; +use snafu::{Backtrace, Snafu}; +use tracing::debug; use super::KeyCache; #[cfg(not(wasm_browser))] use crate::client::streams::{MaybeTlsStream, ProxyStream}; use crate::{ - protos::relay::{ - ClientInfo, Frame, RecvError as RecvRelayError, SendError as SendRelayError, - PROTOCOL_VERSION, + protos::{ + handshake, + relay::{ClientToRelayMsg, Error as ProtoError, RelayToClientMsg}, + streams::WsBytesFramed, }, MAX_PACKET_SIZE, }; @@ -37,11 +35,8 @@ use crate::{ #[derive(Debug, Snafu)] #[non_exhaustive] pub enum SendError { - #[cfg(not(wasm_browser))] #[snafu(transparent)] - RelayIo { source: io::Error }, - #[snafu(transparent)] - WebsocketIo { + StreamError { #[cfg(not(wasm_browser))] source: tokio_websockets::Error, #[cfg(wasm_browser)] @@ -49,6 +44,8 @@ pub enum SendError { }, #[snafu(display("Exceeds max packet size ({MAX_PACKET_SIZE}): {size}"))] ExceedsMaxPacketSize { size: usize }, + #[snafu(display("Attempted to send empty packet"))] + EmptyPacket {}, } /// Errors when receiving messages from the relay server. @@ -62,172 +59,101 @@ pub enum SendError { #[non_exhaustive] pub enum RecvError { #[snafu(transparent)] - Io { source: io::Error }, + Protocol { source: ProtoError }, #[snafu(transparent)] - ProtocolSend { source: SendRelayError }, - #[snafu(transparent)] - ProtocolRecv { source: RecvRelayError }, - #[snafu(transparent)] - Websocket { + StreamError { #[cfg(not(wasm_browser))] source: tokio_websockets::Error, #[cfg(wasm_browser)] source: ws_stream_wasm::WsErr, }, - #[snafu(display("invalid protocol message encoding"))] - InvalidProtocolMessageEncoding { source: Utf8Error }, - #[snafu(display("Unexpected frame received: {frame_type}"))] - UnexpectedFrame { - frame_type: crate::protos::relay::FrameType, - }, } /// A connection to a relay server. /// /// This holds a connection to a relay server. It is: /// -/// - A [`Stream`] for [`ReceivedMessage`] to receive from the server. -/// - A [`Sink`] for [`SendMessage`] to send to the server. -/// - A [`Sink`] for [`Frame`] to send to the server. -/// -/// The [`Frame`] sink is a more internal interface, it allows performing the handshake. -/// The [`SendMessage`] and [`ReceivedMessage`] are safer wrappers enforcing some protocol -/// invariants. +/// - A [`Stream`] for [`RelayToClientMsg`] to receive from the server. +/// - A [`Sink`] for [`ClientToRelayMsg`] to send to the server. #[derive(derive_more::Debug)] pub(crate) struct Conn { #[cfg(not(wasm_browser))] #[debug("tokio_websockets::WebSocketStream")] - pub(crate) conn: tokio_websockets::WebSocketStream>, + pub(crate) conn: WsBytesFramed>, #[cfg(wasm_browser)] - #[debug("WsStream")] - pub(crate) conn: ws_stream_wasm::WsStream, + #[debug("ws_stream_wasm::WsStream")] + pub(crate) conn: WsBytesFramed, pub(crate) key_cache: KeyCache, } impl Conn { /// Constructs a new websocket connection, including the initial server handshake. pub(crate) async fn new( - #[cfg(not(wasm_browser))] conn: tokio_websockets::WebSocketStream< + #[cfg(not(wasm_browser))] io: tokio_websockets::WebSocketStream< MaybeTlsStream, >, - #[cfg(wasm_browser)] conn: ws_stream_wasm::WsStream, + #[cfg(wasm_browser)] io: ws_stream_wasm::WsStream, key_cache: KeyCache, secret_key: &SecretKey, - ) -> Result { - let mut conn = Self { conn, key_cache }; + ) -> Result { + let mut conn = WsBytesFramed { io }; // exchange information with the server - server_handshake(&mut conn, secret_key).await?; + debug!("server_handshake: started"); + handshake::clientside(&mut conn, secret_key).await?; + debug!("server_handshake: done"); - Ok(conn) + Ok(Self { conn, key_cache }) + } + + #[cfg(all(test, feature = "server"))] + pub(crate) fn test(io: tokio::io::DuplexStream) -> Self { + use crate::protos::relay::MAX_FRAME_SIZE; + Self { + conn: WsBytesFramed { + io: tokio_websockets::ClientBuilder::new() + .limits( + tokio_websockets::Limits::default().max_payload_len(Some(MAX_FRAME_SIZE)), + ) + .take_over(MaybeTlsStream::Test(io)), + }, + key_cache: KeyCache::test(), + } } } -/// Sends the server handshake message. -async fn server_handshake(writer: &mut Conn, secret_key: &SecretKey) -> Result<(), SendRelayError> { - debug!("server_handshake: started"); - let client_info = ClientInfo { - version: PROTOCOL_VERSION, - }; - debug!("server_handshake: sending client_key: {:?}", &client_info); - crate::protos::relay::send_client_key(&mut *writer, secret_key, &client_info).await?; - - debug!("server_handshake: done"); - Ok(()) -} - impl Stream for Conn { - type Item = Result; + type Item = Result; fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { match ready!(Pin::new(&mut self.conn).poll_next(cx)) { - #[cfg(not(wasm_browser))] Some(Ok(msg)) => { - if msg.is_close() { - // Indicate the stream is done when we receive a close message. - // Note: We don't have to poll the stream to completion for it to close gracefully. - return Poll::Ready(None); - } - if !msg.is_binary() { - warn!(?msg, "Got websocket message of unsupported type, skipping."); - return Poll::Pending; - } - let frame = Frame::from_bytes(msg.into_payload().into(), &self.key_cache)?; - let message = ReceivedMessage::try_from(frame); - Poll::Ready(Some(message)) + let message = RelayToClientMsg::from_bytes(msg, &self.key_cache); + Poll::Ready(Some(message.map_err(Into::into))) } - #[cfg(not(wasm_browser))] Some(Err(e)) => Poll::Ready(Some(Err(e.into()))), - #[cfg(wasm_browser)] - Some(ws_stream_wasm::WsMessage::Binary(vec)) => { - let frame = Frame::from_bytes(Bytes::from(vec), &self.key_cache)?; - Poll::Ready(Some(ReceivedMessage::try_from(frame))) - } - #[cfg(wasm_browser)] - Some(msg) => { - warn!(?msg, "Got websocket message of unsupported type, skipping."); - Poll::Pending - } None => Poll::Ready(None), } } } -impl Sink for Conn { +impl Sink for Conn { type Error = SendError; fn poll_ready(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { Pin::new(&mut self.conn).poll_ready(cx).map_err(Into::into) } - fn start_send(mut self: Pin<&mut Self>, frame: Frame) -> Result<(), Self::Error> { - if let Frame::SendPacket { dst_key: _, packet } = &frame { - if packet.len() > MAX_PACKET_SIZE { - return Err(ExceedsMaxPacketSizeSnafu { size: packet.len() }.build()); - } - } - - #[cfg(not(wasm_browser))] - let msg = tokio_websockets::Message::binary(tokio_websockets::Payload::from( - frame.to_bytes().freeze(), - )); - #[cfg(wasm_browser)] - let msg = ws_stream_wasm::WsMessage::Binary(frame.to_vec()); - - Pin::new(&mut self.conn).start_send(msg).map_err(Into::into) - } - - fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { - Pin::new(&mut self.conn).poll_flush(cx).map_err(Into::into) - } - - fn poll_close(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { - Pin::new(&mut self.conn).poll_close(cx).map_err(Into::into) - } -} - -impl Sink for Conn { - type Error = SendError; - - fn poll_ready(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { - Pin::new(&mut self.conn).poll_ready(cx).map_err(Into::into) - } - - fn start_send(mut self: Pin<&mut Self>, item: SendMessage) -> Result<(), Self::Error> { - if let SendMessage::SendPacket(_, bytes) = &item { - let size = bytes.len(); + fn start_send(mut self: Pin<&mut Self>, frame: ClientToRelayMsg) -> Result<(), Self::Error> { + if let ClientToRelayMsg::SendPacket { packet, .. } = &frame { + let size = packet.len(); snafu::ensure!(size <= MAX_PACKET_SIZE, ExceedsMaxPacketSizeSnafu { size }); + snafu::ensure!(size != 0, EmptyPacketSnafu); } - let frame = Frame::from(item); - #[cfg(not(wasm_browser))] - let msg = tokio_websockets::Message::binary(tokio_websockets::Payload::from( - frame.to_bytes().freeze(), - )); - #[cfg(wasm_browser)] - let msg = ws_stream_wasm::WsMessage::Binary(frame.to_vec()); - - Pin::new(&mut self.conn).start_send(msg).map_err(Into::into) + Pin::new(&mut self.conn) + .start_send(frame.to_bytes().freeze()) + .map_err(Into::into) } fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { @@ -238,119 +164,3 @@ impl Sink for Conn { Pin::new(&mut self.conn).poll_close(cx).map_err(Into::into) } } - -/// The messages received from a framed relay stream. -/// -/// This is a type-validated version of the `Frame`s on the `RelayCodec`. -#[derive(derive_more::Debug, Clone)] -pub enum ReceivedMessage { - /// Represents an incoming packet. - ReceivedPacket { - /// The [`NodeId`] of the packet sender. - remote_node_id: NodeId, - /// The received packet bytes. - #[debug(skip)] - data: Bytes, // TODO: ref - }, - /// Indicates that the client identified by the underlying public key had previously sent you a - /// packet but has now disconnected from the server. - NodeGone(NodeId), - /// Request from a client or server to reply to the - /// other side with a [`ReceivedMessage::Pong`] with the given payload. - Ping([u8; 8]), - /// Reply to a [`ReceivedMessage::Ping`] from a client or server - /// with the payload sent previously in the ping. - Pong([u8; 8]), - /// A one-way empty message from server to client, just to - /// keep the connection alive. It's like a [`ReceivedMessage::Ping`], but doesn't solicit - /// a reply from the client. - KeepAlive, - /// A one-way message from server to client, declaring the connection health state. - Health { - /// If set, is a description of why the connection is unhealthy. - /// - /// If `None` means the connection is healthy again. - /// - /// The default condition is healthy, so the server doesn't broadcast a [`ReceivedMessage::Health`] - /// until a problem exists. - problem: Option, - }, - /// A one-way message from server to client, advertising that the server is restarting. - ServerRestarting { - /// An advisory duration that the client should wait before attempting to reconnect. - /// It might be zero. It exists for the server to smear out the reconnects. - reconnect_in: Duration, - /// An advisory duration for how long the client should attempt to reconnect - /// before giving up and proceeding with its normal connection failure logic. The interval - /// between retries is undefined for now. A server should not send a TryFor duration more - /// than a few seconds. - try_for: Duration, - }, -} - -impl TryFrom for ReceivedMessage { - type Error = RecvError; - - fn try_from(frame: Frame) -> std::result::Result { - match frame { - Frame::KeepAlive => { - // A one-way keep-alive message that doesn't require an ack. - // This predated FrameType::Ping/FrameType::Pong. - Ok(ReceivedMessage::KeepAlive) - } - Frame::NodeGone { node_id } => Ok(ReceivedMessage::NodeGone(node_id)), - Frame::RecvPacket { src_key, content } => { - let packet = ReceivedMessage::ReceivedPacket { - remote_node_id: src_key, - data: content, - }; - Ok(packet) - } - Frame::Ping { data } => Ok(ReceivedMessage::Ping(data)), - Frame::Pong { data } => Ok(ReceivedMessage::Pong(data)), - Frame::Health { problem } => { - let problem = std::str::from_utf8(&problem) - .context(InvalidProtocolMessageEncodingSnafu)? - .to_owned(); - let problem = Some(problem); - Ok(ReceivedMessage::Health { problem }) - } - Frame::Restarting { - reconnect_in, - try_for, - } => { - let reconnect_in = Duration::from_millis(reconnect_in as u64); - let try_for = Duration::from_millis(try_for as u64); - Ok(ReceivedMessage::ServerRestarting { - reconnect_in, - try_for, - }) - } - _ => Err(UnexpectedFrameSnafu { - frame_type: frame.typ(), - } - .build()), - } - } -} - -/// Messages we can send to a relay server. -#[derive(Debug)] -pub enum SendMessage { - /// Send a packet of data to the [`NodeId`]. - SendPacket(NodeId, Bytes), - /// Sends a ping message to the connected relay server. - Ping([u8; 8]), - /// Sends a pong message to the connected relay server. - Pong([u8; 8]), -} - -impl From for Frame { - fn from(source: SendMessage) -> Self { - match source { - SendMessage::SendPacket(dst_key, packet) => Frame::SendPacket { dst_key, packet }, - SendMessage::Ping(data) => Frame::Ping { data }, - SendMessage::Pong(data) => Frame::Pong { data }, - } - } -} diff --git a/iroh-relay/src/client/streams.rs b/iroh-relay/src/client/streams.rs index 64608d51d8..4e584c08e5 100644 --- a/iroh-relay/src/client/streams.rs +++ b/iroh-relay/src/client/streams.rs @@ -11,6 +11,7 @@ use tokio::{ }; use super::util; +use crate::ExportKeyingMaterial; #[derive(Debug)] #[allow(clippy::large_enum_variant)] @@ -63,6 +64,7 @@ impl AsyncWrite for ProxyStream { Self::Proxied(stream) => Pin::new(stream.get_mut().1).poll_shutdown(cx), } } + fn poll_write_vectored( mut self: Pin<&mut Self>, cx: &mut Context<'_>, @@ -73,20 +75,27 @@ impl AsyncWrite for ProxyStream { Self::Proxied(stream) => Pin::new(stream.get_mut().1).poll_write_vectored(cx, bufs), } } + + fn is_write_vectored(&self) -> bool { + match self { + ProxyStream::Raw(stream) => stream.is_write_vectored(), + ProxyStream::Proxied(stream) => stream.get_ref().1.is_write_vectored(), + } + } } impl ProxyStream { pub fn local_addr(&self) -> std::io::Result { match self { Self::Raw(s) => s.local_addr(), - Self::Proxied(s) => s.get_ref().1.local_addr(), + Self::Proxied(s) => s.get_ref().1.as_ref().local_addr(), } } pub fn peer_addr(&self) -> std::io::Result { match self { Self::Raw(s) => s.peer_addr(), - Self::Proxied(s) => s.get_ref().1.peer_addr(), + Self::Proxied(s) => s.get_ref().1.as_ref().peer_addr(), } } } @@ -96,10 +105,27 @@ impl ProxyStream { pub enum MaybeTlsStream { Raw(IO), Tls(tokio_rustls::client::TlsStream), - #[cfg(test)] + #[cfg(all(test, feature = "server"))] Test(tokio::io::DuplexStream), } +impl ExportKeyingMaterial for MaybeTlsStream { + fn export_keying_material>( + &self, + output: T, + label: &[u8], + context: Option<&[u8]>, + ) -> Option { + let Self::Tls(ref tls) = self else { + return None; + }; + tls.get_ref() + .1 + .export_keying_material(output, label, context) + .ok() + } +} + impl AsyncRead for MaybeTlsStream { fn poll_read( mut self: Pin<&mut Self>, @@ -109,7 +135,7 @@ impl AsyncRead for MaybeTlsStream { match &mut *self { Self::Raw(stream) => Pin::new(stream).poll_read(cx, buf), Self::Tls(stream) => Pin::new(stream).poll_read(cx, buf), - #[cfg(test)] + #[cfg(all(test, feature = "server"))] Self::Test(stream) => Pin::new(stream).poll_read(cx, buf), } } @@ -124,7 +150,7 @@ impl AsyncWrite for MaybeTlsStream { match &mut *self { Self::Raw(stream) => Pin::new(stream).poll_write(cx, buf), Self::Tls(stream) => Pin::new(stream).poll_write(cx, buf), - #[cfg(test)] + #[cfg(all(test, feature = "server"))] Self::Test(stream) => Pin::new(stream).poll_write(cx, buf), } } @@ -136,7 +162,7 @@ impl AsyncWrite for MaybeTlsStream { match &mut *self { Self::Raw(stream) => Pin::new(stream).poll_flush(cx), Self::Tls(stream) => Pin::new(stream).poll_flush(cx), - #[cfg(test)] + #[cfg(all(test, feature = "server"))] Self::Test(stream) => Pin::new(stream).poll_flush(cx), } } @@ -148,10 +174,11 @@ impl AsyncWrite for MaybeTlsStream { match &mut *self { Self::Raw(stream) => Pin::new(stream).poll_shutdown(cx), Self::Tls(stream) => Pin::new(stream).poll_shutdown(cx), - #[cfg(test)] + #[cfg(all(test, feature = "server"))] Self::Test(stream) => Pin::new(stream).poll_shutdown(cx), } } + fn poll_write_vectored( mut self: Pin<&mut Self>, cx: &mut Context<'_>, @@ -160,28 +187,17 @@ impl AsyncWrite for MaybeTlsStream { match &mut *self { Self::Raw(stream) => Pin::new(stream).poll_write_vectored(cx, bufs), Self::Tls(stream) => Pin::new(stream).poll_write_vectored(cx, bufs), - #[cfg(test)] + #[cfg(all(test, feature = "server"))] Self::Test(stream) => Pin::new(stream).poll_write_vectored(cx, bufs), } } -} -impl MaybeTlsStream { - pub fn local_addr(&self) -> std::io::Result { + fn is_write_vectored(&self) -> bool { match self { - Self::Raw(s) => s.local_addr(), - Self::Tls(s) => s.get_ref().0.local_addr(), - #[cfg(test)] - Self::Test(_) => Ok(SocketAddr::new(std::net::Ipv4Addr::LOCALHOST.into(), 1337)), - } - } - - pub fn peer_addr(&self) -> std::io::Result { - match self { - Self::Raw(s) => s.peer_addr(), - Self::Tls(s) => s.get_ref().0.peer_addr(), - #[cfg(test)] - Self::Test(_) => Ok(SocketAddr::new(std::net::Ipv4Addr::LOCALHOST.into(), 1337)), + Self::Raw(stream) => stream.is_write_vectored(), + Self::Tls(stream) => stream.is_write_vectored(), + #[cfg(all(test, feature = "server"))] + Self::Test(stream) => stream.is_write_vectored(), } } } @@ -191,7 +207,7 @@ impl AsRef for MaybeTlsStream { match self { Self::Raw(s) => s, Self::Tls(s) => s.get_ref().0, - #[cfg(test)] + #[cfg(all(test, feature = "server"))] Self::Test(_) => unimplemented!("can't grab underlying IO in MaybeTlsStream::Test"), } } diff --git a/iroh-relay/src/http.rs b/iroh-relay/src/http.rs index cca8c82aee..c3fe7d40aa 100644 --- a/iroh-relay/src/http.rs +++ b/iroh-relay/src/http.rs @@ -1,5 +1,7 @@ //! HTTP-specific constants for the relay server and client. +use http::HeaderName; + #[cfg(feature = "server")] pub(crate) const WEBSOCKET_UPGRADE_PROTOCOL: &str = "websocket"; #[cfg(feature = "server")] // only used in the server for now @@ -10,3 +12,11 @@ pub(crate) const SUPPORTED_WEBSOCKET_VERSION: &str = "13"; pub const RELAY_PATH: &str = "/relay"; /// The HTTP path under which the relay allows doing latency queries for testing. pub const RELAY_PROBE_PATH: &str = "/ping"; + +/// The websocket sub-protocol version that we currently support. +/// +/// This is sent as the websocket sub-protocol header `Sec-Websocket-Protocol` from +/// the client and answered from the server. +pub const RELAY_PROTOCOL_VERSION: &str = "iroh-relay-v1"; +/// The HTTP header name for relay client authentication +pub const CLIENT_AUTH_HEADER: HeaderName = HeaderName::from_static("x-iroh-relay-client-auth-v1"); diff --git a/iroh-relay/src/key_cache.rs b/iroh-relay/src/key_cache.rs index f802326802..165cada24c 100644 --- a/iroh-relay/src/key_cache.rs +++ b/iroh-relay/src/key_cache.rs @@ -26,7 +26,7 @@ pub enum KeyCache { impl KeyCache { /// Key cache to be used in tests. - #[cfg(test)] + #[cfg(all(test, feature = "server"))] pub fn test() -> Self { Self::Disabled } diff --git a/iroh-relay/src/lib.rs b/iroh-relay/src/lib.rs index e561ddaf4a..76565b9cf5 100644 --- a/iroh-relay/src/lib.rs +++ b/iroh-relay/src/lib.rs @@ -54,3 +54,31 @@ pub use self::{ ping_tracker::PingTracker, relay_map::{RelayMap, RelayNode, RelayQuicConfig}, }; + +/// This trait allows anything that ends up potentially +/// wrapping a TLS stream use the underlying [`export_keying_material`] +/// function. +/// +/// [`export_keying_material`]: rustls::ConnectionCommon::export_keying_material +pub(crate) trait ExportKeyingMaterial { + /// If this type ends up wrapping a TLS stream, then this tries + /// to export keying material by calling the underlying [`export_keying_material`] + /// function. + /// + /// However unlike that function, this returns `Option`, in case the + /// underlying stream might not be wrapping TLS, e.g. as in the case of + /// [`MaybeTlsStream`]. + /// + /// For more information on what this function does, see the + /// [`export_keying_material`] documentation. + /// + /// [`export_keying_material`]: rustls::ConnectionCommon::export_keying_material + /// [`MaybeTlsStream`]: crate::client::streams::MaybeTlsStream + #[cfg_attr(wasm_browser, allow(unused))] + fn export_keying_material>( + &self, + output: T, + label: &[u8], + context: Option<&[u8]>, + ) -> Option; +} diff --git a/iroh-relay/src/protos.rs b/iroh-relay/src/protos.rs index 6e268a5f58..043e9de434 100644 --- a/iroh-relay/src/protos.rs +++ b/iroh-relay/src/protos.rs @@ -1,4 +1,7 @@ //! Protocols used by the iroh-relay +pub mod common; pub mod disco; +pub mod handshake; pub mod relay; +pub mod streams; diff --git a/iroh-relay/src/protos/common.rs b/iroh-relay/src/protos/common.rs new file mode 100644 index 0000000000..4129760cc2 --- /dev/null +++ b/iroh-relay/src/protos/common.rs @@ -0,0 +1,107 @@ +//! Common types between the [`super::handshake`] and [`super::relay`] protocols. +//! +//! Hosts the [`FrameType`] enum to make sure we're not accidentally reusing frame type +//! integers for different frames. + +use bytes::{Buf, BufMut}; +use nested_enum_utils::common_fields; +use quinn_proto::{coding::Codec, VarInt}; +use snafu::{Backtrace, OptionExt, Snafu}; + +/// Possible frame types during handshaking +#[repr(u32)] +#[derive( + Copy, Clone, PartialEq, Eq, Debug, num_enum::IntoPrimitive, num_enum::TryFromPrimitive, +)] +// needs to be pub due to being exposed in error types +pub enum FrameType { + /// The server frame type for the challenge response + ServerChallenge = 0, + /// The client frame type for the authentication frame + ClientAuth = 1, + /// The server frame type for authentication confirmation + ServerConfirmsAuth = 2, + /// The server frame type for authentication denial + ServerDeniesAuth = 3, + /// 32B dest pub key + content + SendPacket = 4, + /// 32B src pub key + content + RecvPacket = 6, + /// Sent from server to client to signal that a previous sender is no longer connected. + /// + /// That is, if A sent to B, and then if A disconnects, the server sends `FrameType::PeerGone` + /// to B so B can forget that a reverse path exists on that connection to get back to A + /// + /// 32B pub key of peer that's gone + NodeGone = 8, + /// Messages with these frames will be ignored. + /// 8 byte ping payload, to be echoed back in FrameType::Pong + Ping = 9, + /// 8 byte payload, the contents of ping being replied to + Pong = 10, + /// Sent from server to client to tell the client if their connection is unhealthy somehow. + /// Contains only UTF-8 bytes. + Health = 11, + + /// Sent from server to client for the server to declare that it's restarting. + /// Payload is two big endian u32 durations in milliseconds: when to reconnect, + /// and how long to try total. + Restarting = 12, +} + +#[common_fields({ + backtrace: Option, + #[snafu(implicit)] + span_trace: n0_snafu::SpanTrace, +})] +#[allow(missing_docs)] +#[derive(Debug, Snafu)] +#[non_exhaustive] +pub enum FrameTypeError { + #[snafu(display("not enough bytes to parse frame type"))] + UnexpectedEnd {}, + #[snafu(display("frame type unknown"))] + UnknownFrameType { tag: VarInt }, +} + +impl FrameType { + /// Writes the frame type to the buffer (as a QUIC-encoded varint). + pub(crate) fn write_to(&self, mut dst: O) -> O { + VarInt::from(*self).encode(&mut dst); + dst + } + + /// Returns the amount of bytes that [`Self::write_to`] would write. + pub(crate) fn encoded_len(&self) -> usize { + // Copied implementation from `VarInt::size` + let x: u32 = (*self).into(); + if x < 2u32.pow(6) { + 1 // this will pretty much always be the case + } else if x < 2u32.pow(14) { + 2 + } else if x < 2u32.pow(30) { + 4 + } else { + unreachable!("Impossible FrameType primitive representation") + } + } + + /// Parses the frame type (as a QUIC-encoded varint) from the first couple of bytes given + /// and returns the frame type and the rest. + pub(crate) fn from_bytes(buf: &mut impl Buf) -> Result { + let tag = VarInt::decode(buf).ok().context(UnexpectedEndSnafu)?; + let tag_u32 = u32::try_from(u64::from(tag)) + .ok() + .context(UnknownFrameTypeSnafu { tag })?; + let frame_type = FrameType::try_from(tag_u32) + .ok() + .context(UnknownFrameTypeSnafu { tag })?; + Ok(frame_type) + } +} + +impl From for VarInt { + fn from(value: FrameType) -> Self { + (value as u32).into() + } +} diff --git a/iroh-relay/src/protos/handshake.rs b/iroh-relay/src/protos/handshake.rs new file mode 100644 index 0000000000..e03305a10e --- /dev/null +++ b/iroh-relay/src/protos/handshake.rs @@ -0,0 +1,806 @@ +//! Implements the handshake protocol that authenticates and authorizes clients connecting to the relays. +//! +//! The purpose of the handshake is to +//! 1. Inform the relay of the client's NodeId +//! 2. Check that the connecting client owns the secret key for its NodeId ("is authentic"/"authentication") +//! 3. Possibly check that the client has access to this relay, if the relay requires authorization. +//! +//! Additional complexity comes from the fact that there's two ways that clients can authenticate with +//! relays. +//! +//! One way is via an explicitly sent challenge: +//! +//! 1. Once a websocket connection is opened, a client receives a challenge (the `ServerChallenge` frame) +//! 2. The client sends back what is essentially a signature of that challenge with their secret key +//! that matches the NodeId they have, as well as the NodeId (the `ClientAuth` frame) +//! +//! The second way is very similar to the [Concealed HTTP Auth RFC], and involves send a header that +//! contains a signature of some shared keying material extracted from TLS ([RFC 5705]). +//! +//! The second way can save a full round trip, because the challenge doesn't have to be sent to the client +//! first, however, it won't always work, as it relies on the keying material extraction feature of TLS, +//! which is not available in browsers (but might be in the future?) and might break when there's an +//! HTTPS proxy that doesn't properly deal with this TLS feature. +//! +//! [Concealed HTTP Auth RFC]: https://datatracker.ietf.org/doc/rfc9729/ +//! [RFC 5705]: https://datatracker.ietf.org/doc/html/rfc5705 +use bytes::{BufMut, Bytes, BytesMut}; +use data_encoding::BASE32HEX_NOPAD as HEX; +use http::HeaderValue; +#[cfg(feature = "server")] +use iroh_base::Signature; +use iroh_base::{PublicKey, SecretKey}; +use n0_future::{SinkExt, TryStreamExt}; +use nested_enum_utils::common_fields; +#[cfg(feature = "server")] +use rand::{CryptoRng, RngCore}; +use snafu::{Backtrace, ResultExt, Snafu}; +use tracing::trace; + +use super::{ + common::{FrameType, FrameTypeError}, + streams::BytesStreamSink, +}; +use crate::ExportKeyingMaterial; + +/// Domain separation string for the [`ServerChallenge`] signature +const DOMAIN_SEP_CHALLENGE: &str = "iroh-relay handshake v1 challenge signature"; + +/// Domain separation label for [`KeyMaterialClientAuth`]'s use of [`ExportKeyingMaterial`] +const DOMAIN_SEP_TLS_EXPORT_LABEL: &[u8] = b"iroh-relay handshake v1"; + +/// Authentication message from the client. +#[derive(derive_more::Debug, serde::Serialize, serde::Deserialize)] +#[cfg_attr(wasm_browser, allow(unused))] +pub(crate) struct KeyMaterialClientAuth { + /// The client's public key + pub(crate) public_key: PublicKey, + /// A signature of (a hash of) extracted key material. + #[serde(with = "serde_bytes")] + #[debug("{}", HEX.encode(signature))] + pub(crate) signature: [u8; 64], + /// Part of the extracted key material. + /// + /// Allows making sure we have the same underlying key material. + #[debug("{}", HEX.encode(key_material_suffix))] + pub(crate) key_material_suffix: [u8; 16], +} + +/// A challenge for the client to sign with their secret key for NodeId authentication. +#[derive(derive_more::Debug, serde::Serialize, serde::Deserialize)] +pub(crate) struct ServerChallenge { + /// The challenge to sign. + /// Must be randomly generated with an RNG that is safe to use for crypto. + #[debug("{}", HEX.encode(challenge))] + pub(crate) challenge: [u8; 16], +} + +/// Authentication message from the client. +/// +/// Used when authentication via [`KeyMaterialClientAuth`] didn't work. +#[derive(derive_more::Debug, serde::Serialize, serde::Deserialize)] +pub(crate) struct ClientAuth { + /// The client's public key, a.k.a. the `NodeId` + pub(crate) public_key: PublicKey, + /// A signature of (a hash of) the [`ServerChallenge`]. + /// + /// This is what provides the authentication. + #[serde(with = "serde_bytes")] + #[debug("{}", HEX.encode(signature))] + pub(crate) signature: [u8; 64], +} + +/// Confirmation of successful connection. +#[derive(derive_more::Debug, serde::Serialize, serde::Deserialize)] +pub(crate) struct ServerConfirmsAuth; + +/// Denial of connection. The client couldn't be verified as authentic. +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +pub(crate) struct ServerDeniesAuth { + reason: String, +} + +/// Trait for getting the frame type tag for a frame. +/// +/// Used only in the handshake, as the frame we expect next +/// is fairly stateful. +/// Not used in the send/recv protocol, as any frame is +/// allowed to happen at any time there. +trait Frame { + /// The frame type this frame is identified by and prefixed with + const TAG: FrameType; +} + +impl Frame for &T { + const TAG: FrameType = T::TAG; +} + +impl Frame for ServerChallenge { + const TAG: FrameType = FrameType::ServerChallenge; +} + +impl Frame for ClientAuth { + const TAG: FrameType = FrameType::ClientAuth; +} + +impl Frame for ServerConfirmsAuth { + const TAG: FrameType = FrameType::ServerConfirmsAuth; +} + +impl Frame for ServerDeniesAuth { + const TAG: FrameType = FrameType::ServerDeniesAuth; +} + +#[common_fields({ + backtrace: Option, + #[snafu(implicit)] + span_trace: n0_snafu::SpanTrace, +})] +#[allow(missing_docs)] +#[derive(Debug, Snafu)] +#[non_exhaustive] +pub enum Error { + #[snafu(transparent)] + Websocket { + #[cfg(not(wasm_browser))] + source: tokio_websockets::Error, + #[cfg(wasm_browser)] + source: ws_stream_wasm::WsErr, + }, + #[snafu(display("Handshake stream ended prematurely"))] + UnexpectedEnd {}, + #[snafu(transparent)] + FrameTypeError { source: FrameTypeError }, + #[snafu(display("The relay denied our authentication ({reason})"))] + ServerDeniedAuth { reason: String }, + #[snafu(display( + "Unexpected tag, got {frame_type:?}, but expected one of {expected_types:?}" + ))] + UnexpectedFrameType { + frame_type: FrameType, + expected_types: Vec, + }, + #[snafu(display("Handshake failed while deserializing {frame_type:?} frame"))] + DeserializationError { + frame_type: FrameType, + source: postcard::Error, + }, + #[cfg(feature = "server")] + /// Failed to deserialize client auth header + ClientAuthHeaderInvalid { value: HeaderValue }, +} + +#[cfg(feature = "server")] +#[derive(Debug, Snafu)] +pub(crate) enum VerificationError { + #[snafu(display("Couldn't export TLS keying material on our end"))] + NoKeyingMaterial, + #[snafu(display("Client didn't extract the same keying material, the suffix mismatched: expected {expected:X?} but got {actual:X?}"))] + MismatchedSuffix { + expected: [u8; 16], + actual: [u8; 16], + }, + #[snafu(display("Client signature {signature:X?} for message {message:X?} invalid for public key {public_key}"))] + SignatureInvalid { + source: iroh_base::SignatureError, + message: Vec, + signature: [u8; 64], + public_key: PublicKey, + }, +} + +impl ServerChallenge { + /// Generates a new challenge. + #[cfg(feature = "server")] + pub(crate) fn new(mut rng: impl RngCore + CryptoRng) -> Self { + let mut challenge = [0u8; 16]; + rng.fill_bytes(&mut challenge); + Self { challenge } + } + + /// The actual message bytes to sign (and verify against) for this challenge. + fn message_to_sign(&self) -> [u8; 32] { + // We're signing a key instead of the direct challenge. + // This gives us domain separation protecting from multiple possible attacks, + // but especially this one: + // Assume a malicious relay. If the protocol required the client to sign the + // challenge directly, this would allow the relay to obtain an arbitrary 16-byte + // signature, if it maliciously choses the challenge instead of generating it + // randomly. + // Deriving a key to sign instead mitigates this attack. + blake3::derive_key(DOMAIN_SEP_CHALLENGE, &self.challenge) + } +} + +impl ClientAuth { + /// Generates a signature for the given challenge from the server. + pub(crate) fn new(secret_key: &SecretKey, challenge: &ServerChallenge) -> Self { + Self { + public_key: secret_key.public(), + signature: secret_key.sign(&challenge.message_to_sign()).to_bytes(), + } + } + + /// Verifies this client's authentication given the challenge this was sent in response to. + #[cfg(feature = "server")] + pub(crate) fn verify(&self, challenge: &ServerChallenge) -> Result<(), Box> { + let message = challenge.message_to_sign(); + self.public_key + .verify(&message, &Signature::from_bytes(&self.signature)) + .with_context(|_| SignatureInvalidSnafu { + message: message.to_vec(), + signature: self.signature, + public_key: self.public_key, + }) + .map_err(Box::new) + } +} + +#[cfg(not(wasm_browser))] +impl KeyMaterialClientAuth { + /// Generates a client's authentication, similar to [`ClientAuth`], but by using TLS keying material + /// instead of a received challenge. + pub(crate) fn new(secret_key: &SecretKey, io: &impl ExportKeyingMaterial) -> Option { + let public_key = secret_key.public(); + let key_material = io.export_keying_material( + [0u8; 32], + DOMAIN_SEP_TLS_EXPORT_LABEL, + Some(secret_key.public().as_bytes()), + )?; + // We split the export and only sign the first 16 bytes, and + // pass through the last 16 bytes. See also the note in [Self::verify]. + let (message, suffix) = key_material.split_at(16); + Some(Self { + public_key, + signature: secret_key.sign(message).to_bytes(), + key_material_suffix: suffix.try_into().expect("hardcoded length"), + }) + } + + /// Generate the base64url-nopad-encoded header value. + pub(crate) fn into_header_value(self) -> HeaderValue { + HeaderValue::from_str( + &data_encoding::BASE64URL_NOPAD + .encode(&postcard::to_allocvec(&self).expect("encoding never fails")), + ) + .expect("BASE64URL_NOPAD encoding contained invisible ascii characters") + } + + /// Verifies this client auth on the server side using the same key material. + /// + /// This might return false for a couple of reasons: + /// 1. The exported keying material might not be the same between both ends of the TLS session + /// (e.g. there's an HTTPS proxy in between that doesn't think/care about the TLS keying material exporter). + /// This situation is detected when the key material suffix mismatches. + /// 2. The signature itself doesn't verify. + #[cfg(feature = "server")] + pub(crate) fn verify( + &self, + io: &impl ExportKeyingMaterial, + ) -> Result<(), Box> { + use snafu::OptionExt; + + let key_material = io + .export_keying_material( + [0u8; 32], + DOMAIN_SEP_TLS_EXPORT_LABEL, + Some(self.public_key.as_bytes()), + ) + .context(NoKeyingMaterialSnafu)?; + // We split the export and only sign the first 16 bytes, and + // pass through the last 16 bytes. + // Passing on the suffix helps the verifying end figure out what + // went wrong: If there's a suffix mismatch, then the exported keying + // material on both ends wasn't the same - so perhaps there was a + // TLS proxy in between or similar. + // If the suffix does match, but the signature doesn't verify, then + // there must be something wrong with the client's secret key or signature. + let (message, suffix) = key_material.split_at(16); + let suffix: [u8; 16] = suffix.try_into().expect("hardcoded length"); + snafu::ensure!( + suffix == self.key_material_suffix, + MismatchedSuffixSnafu { + expected: self.key_material_suffix, + actual: suffix + } + ); + // NOTE: We don't blake3-hash here as we do it in [`ServerChallenge::message_to_sign`], + // because we already have a domain separation string and keyed hashing step in + // the TLS export keying material above. + self.public_key + .verify(message, &Signature::from_bytes(&self.signature)) + .with_context(|_| SignatureInvalidSnafu { + message: message.to_vec(), + public_key: self.public_key, + signature: self.signature, + }) + .map_err(Box::new) + } +} + +/// Runs the client side of the handshake protocol. +/// +/// See the module docs for details on the protocol. +/// This is already after having potentially transferred a [`KeyMaterialClientAuth`], +/// but before having received a response for whether that worked or not. +/// +/// This requires access to the client's secret key to sign a challenge. +pub(crate) async fn clientside( + io: &mut (impl BytesStreamSink + ExportKeyingMaterial), + secret_key: &SecretKey, +) -> Result { + let (tag, frame) = read_frame(io, &[ServerChallenge::TAG, ServerConfirmsAuth::TAG]).await?; + + let (tag, frame) = if tag == ServerChallenge::TAG { + let challenge: ServerChallenge = deserialize_frame(frame)?; + + let client_info = ClientAuth::new(secret_key, &challenge); + write_frame(io, client_info).await?; + + read_frame(io, &[ServerConfirmsAuth::TAG, ServerDeniesAuth::TAG]).await? + } else { + (tag, frame) + }; + + match tag { + FrameType::ServerConfirmsAuth => { + let confirmation: ServerConfirmsAuth = deserialize_frame(frame)?; + Ok(confirmation) + } + FrameType::ServerDeniesAuth => { + let denial: ServerDeniesAuth = deserialize_frame(frame)?; + Err(ServerDeniedAuthSnafu { + reason: denial.reason, + } + .build()) + } + _ => unreachable!(), + } +} + +/// This represents successful authentication for the client with the `client_key` public key +/// via the authentication [`Mechanism`] `mechanism`. +/// +/// You must call [`SuccessfulAuthentication::authorize_if`] to finish the protocol. +#[cfg(feature = "server")] +#[derive(Debug)] +#[must_use = "the protocol is not finished unless `authorize_if` is called"] +pub(crate) struct SuccessfulAuthentication { + pub(crate) client_key: PublicKey, + pub(crate) mechanism: Mechanism, +} + +/// The mechanism that was used for authentication. +#[cfg(feature = "server")] +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum Mechanism { + /// Authentication was performed by verifying a signature of a challenge we sent + SignedChallenge, + /// Authentication was performed by verifying a signature of shared extracted TLS keying material + SignedKeyMaterial, +} + +/// Runs the server side of the handshaking protocol. +/// +/// See the module documentation for an overview of the handshaking protocol. +/// +/// This takes `rng` to generate cryptographic randomness for the authentication challenge. +/// +/// This also takes the `client_auth_header`, if present, to perform authentication without +/// requiring sending a challenge, saving a round-trip, if possible. +/// +/// If this fails, the protocol falls back to doing a normal extra round trip with a challenge. +/// +/// The return value [`SuccessfulAuthentication`] still needs to be resolved by calling +/// [`SuccessfulAuthentication::authorize_if`] to finish the whole authorization protocol +/// (otherwise the client won't be notified about auth success or failure). +#[cfg(feature = "server")] +pub(crate) async fn serverside( + io: &mut (impl BytesStreamSink + ExportKeyingMaterial), + client_auth_header: Option, + rng: impl RngCore + CryptoRng, +) -> Result { + if let Some(client_auth_header) = client_auth_header { + let client_auth_bytes = data_encoding::BASE64URL_NOPAD + .decode(client_auth_header.as_ref()) + .map_err(|_| { + ClientAuthHeaderInvalidSnafu { + value: client_auth_header.clone(), + } + .build() + })?; + + let client_auth: KeyMaterialClientAuth = + postcard::from_bytes(&client_auth_bytes).map_err(|_| { + ClientAuthHeaderInvalidSnafu { + value: client_auth_header.clone(), + } + .build() + })?; + + if let Ok(()) = client_auth.verify(io) { + trace!(?client_auth.public_key, "authentication succeeded via keying material"); + return Ok(SuccessfulAuthentication { + client_key: client_auth.public_key, + mechanism: Mechanism::SignedKeyMaterial, + }); + } + // Verification not succeeding is part of normal operation: The TLS exporter isn't required to match. + // We'll fall back to verification that takes another round trip more time. + } + + let challenge = ServerChallenge::new(rng); + write_frame(io, &challenge).await?; + + let (_, frame) = read_frame(io, &[ClientAuth::TAG]).await?; + let client_auth: ClientAuth = deserialize_frame(frame)?; + + if let Err(err) = client_auth.verify(&challenge) { + trace!(?client_auth.public_key, ?err, "authentication failed"); + let denial = ServerDeniesAuth { + reason: "signature invalid".into(), + }; + write_frame(io, denial.clone()).await?; + ServerDeniedAuthSnafu { + reason: denial.reason, + } + .fail() + } else { + trace!(?client_auth.public_key, "authentication succeeded via challenge"); + Ok(SuccessfulAuthentication { + client_key: client_auth.public_key, + mechanism: Mechanism::SignedChallenge, + }) + } +} + +#[cfg(feature = "server")] +impl SuccessfulAuthentication { + pub async fn authorize_if( + self, + is_authorized: bool, + io: &mut (impl BytesStreamSink + ExportKeyingMaterial), + ) -> Result { + if is_authorized { + trace!("authorizing client"); + write_frame(io, ServerConfirmsAuth).await?; + Ok(self.client_key) + } else { + trace!("denying client auth"); + let denial = ServerDeniesAuth { + reason: "not authorized".into(), + }; + write_frame(io, denial.clone()).await?; + ServerDeniedAuthSnafu { + reason: denial.reason, + } + .fail() + } + } +} + +async fn write_frame( + io: &mut impl BytesStreamSink, + frame: F, +) -> Result<(), Error> { + let mut bytes = BytesMut::new(); + trace!(frame_type = ?F::TAG, "Writing frame"); + F::TAG.write_to(&mut bytes); + let bytes = postcard::to_io(&frame, bytes.writer()) + .expect("serialization failed") // buffer can't become "full" without being a critical failure, datastructures shouldn't ever fail serialization + .into_inner() + .freeze(); + io.send(bytes).await?; + io.flush().await?; + Ok(()) +} + +async fn read_frame( + io: &mut impl BytesStreamSink, + expected_types: &[FrameType], +) -> Result<(FrameType, Bytes), Error> { + let mut payload = io + .try_next() + .await? + .ok_or_else(|| UnexpectedEndSnafu.build())?; + + let frame_type = FrameType::from_bytes(&mut payload)?; + trace!(?frame_type, "Reading frame"); + snafu::ensure!( + expected_types.contains(&frame_type), + UnexpectedFrameTypeSnafu { + frame_type, + expected_types: expected_types.to_vec() + } + ); + + Ok((frame_type, payload)) +} + +fn deserialize_frame(frame: Bytes) -> Result { + postcard::from_bytes(&frame).context(DeserializationSnafu { frame_type: F::TAG }) +} + +#[cfg(all(test, feature = "server"))] +mod tests { + use bytes::BytesMut; + use iroh_base::{PublicKey, SecretKey}; + use n0_future::{Sink, SinkExt, Stream, TryStreamExt}; + use n0_snafu::{Result, ResultExt}; + use tokio_util::codec::{Framed, LengthDelimitedCodec}; + use tracing::{info_span, Instrument}; + use tracing_test::traced_test; + + use super::{ + ClientAuth, KeyMaterialClientAuth, Mechanism, ServerChallenge, ServerConfirmsAuth, + }; + use crate::ExportKeyingMaterial; + + struct TestKeyingMaterial { + shared_secret: Option, + inner: IO, + } + + trait WithTlsSharedSecret: Sized { + fn with_shared_secret(self, shared_secret: Option) -> TestKeyingMaterial; + } + + impl WithTlsSharedSecret for T { + fn with_shared_secret(self, shared_secret: Option) -> TestKeyingMaterial { + TestKeyingMaterial { + shared_secret, + inner: self, + } + } + } + + impl ExportKeyingMaterial for TestKeyingMaterial { + fn export_keying_material>( + &self, + mut output: T, + label: &[u8], + context: Option<&[u8]>, + ) -> Option { + // we simulate something like exporting keying material using blake3 + + let label_key = blake3::hash(label); + let context_key = blake3::keyed_hash(label_key.as_bytes(), context.unwrap_or(&[])); + let mut hasher = blake3::Hasher::new_keyed(context_key.as_bytes()); + hasher.update(&self.shared_secret?.to_le_bytes()); + hasher.finalize_xof().fill(output.as_mut()); + + Some(output) + } + } + + impl + Unpin> Stream for TestKeyingMaterial { + type Item = V; + + fn poll_next( + mut self: std::pin::Pin<&mut Self>, + cx: &mut std::task::Context<'_>, + ) -> std::task::Poll> { + std::pin::Pin::new(&mut self.inner).poll_next(cx) + } + } + + impl + Unpin> Sink for TestKeyingMaterial { + type Error = E; + + fn poll_ready( + mut self: std::pin::Pin<&mut Self>, + cx: &mut std::task::Context<'_>, + ) -> std::task::Poll> { + std::pin::Pin::new(&mut self.inner).poll_ready(cx) + } + + fn start_send(mut self: std::pin::Pin<&mut Self>, item: V) -> Result<(), Self::Error> { + std::pin::Pin::new(&mut self.inner).start_send(item) + } + + fn poll_flush( + mut self: std::pin::Pin<&mut Self>, + cx: &mut std::task::Context<'_>, + ) -> std::task::Poll> { + std::pin::Pin::new(&mut self.inner).poll_flush(cx) + } + + fn poll_close( + mut self: std::pin::Pin<&mut Self>, + cx: &mut std::task::Context<'_>, + ) -> std::task::Poll> { + std::pin::Pin::new(&mut self.inner).poll_close(cx) + } + } + + async fn simulate_handshake( + secret_key: &SecretKey, + client_shared_secret: Option, + server_shared_secret: Option, + restricted_to: Option, + ) -> (Result, Result<(PublicKey, Mechanism)>) { + let (client, server) = tokio::io::duplex(1024); + + let mut client_io = Framed::new(client, LengthDelimitedCodec::new()) + .map_ok(BytesMut::freeze) + .map_err(tokio_websockets::Error::Io) + .sink_map_err(tokio_websockets::Error::Io) + .with_shared_secret(client_shared_secret); + let mut server_io = Framed::new(server, LengthDelimitedCodec::new()) + .map_ok(BytesMut::freeze) + .map_err(tokio_websockets::Error::Io) + .sink_map_err(tokio_websockets::Error::Io) + .with_shared_secret(server_shared_secret); + + let client_auth_header = KeyMaterialClientAuth::new(secret_key, &client_io) + .map(KeyMaterialClientAuth::into_header_value); + + n0_future::future::zip( + async { + super::clientside(&mut client_io, secret_key) + .await + .context("clientside") + } + .instrument(info_span!("clientside")), + async { + let auth_n = + super::serverside(&mut server_io, client_auth_header, rand::rngs::OsRng) + .await + .context("serverside")?; + let mechanism = auth_n.mechanism; + let is_authorized = restricted_to.is_none_or(|key| key == auth_n.client_key); + let key = auth_n.authorize_if(is_authorized, &mut server_io).await?; + Ok((key, mechanism)) + } + .instrument(info_span!("serverside")), + ) + .await + } + + #[tokio::test] + #[traced_test] + async fn test_handshake_via_shared_secrets() -> Result { + let secret_key = SecretKey::generate(rand::rngs::OsRng); + let (client, server) = simulate_handshake(&secret_key, Some(42), Some(42), None).await; + client?; + let (public_key, auth) = server?; + assert_eq!(public_key, secret_key.public()); + assert_eq!(auth, Mechanism::SignedKeyMaterial); // it got verified via shared key material + Ok(()) + } + + #[tokio::test] + #[traced_test] + async fn test_handshake_via_challenge() -> Result { + let secret_key = SecretKey::generate(rand::rngs::OsRng); + let (client, server) = simulate_handshake(&secret_key, None, None, None).await; + client?; + let (public_key, auth) = server?; + assert_eq!(public_key, secret_key.public()); + assert_eq!(auth, Mechanism::SignedChallenge); + Ok(()) + } + + #[tokio::test] + #[traced_test] + async fn test_handshake_mismatching_shared_secrets() -> Result { + let secret_key = SecretKey::generate(rand::rngs::OsRng); + // mismatching shared secrets *might* happen with HTTPS proxies that don't also middle-man the shared secret + let (client, server) = simulate_handshake(&secret_key, Some(10), Some(99), None).await; + client?; + let (public_key, auth) = server?; + assert_eq!(public_key, secret_key.public()); + assert_eq!(auth, Mechanism::SignedChallenge); + Ok(()) + } + + #[tokio::test] + #[traced_test] + async fn test_handshake_challenge_fallback() -> Result { + let secret_key = SecretKey::generate(rand::rngs::OsRng); + // clients might not have access to shared secrets + let (client, server) = simulate_handshake(&secret_key, None, Some(99), None).await; + client?; + let (public_key, auth) = server?; + assert_eq!(public_key, secret_key.public()); + assert_eq!(auth, Mechanism::SignedChallenge); + Ok(()) + } + + #[tokio::test] + #[traced_test] + async fn test_handshake_with_auth_positive() -> Result { + let secret_key = SecretKey::generate(rand::rngs::OsRng); + let public_key = secret_key.public(); + let (client, server) = simulate_handshake(&secret_key, None, None, Some(public_key)).await; + client?; + let (public_key, _) = server?; + assert_eq!(public_key, secret_key.public()); + Ok(()) + } + + #[tokio::test] + #[traced_test] + async fn test_handshake_with_auth_negative() -> Result { + let secret_key = SecretKey::generate(rand::rngs::OsRng); + let public_key = secret_key.public(); + let wrong_secret_key = SecretKey::generate(rand::rngs::OsRng); + let (client, server) = + simulate_handshake(&wrong_secret_key, None, None, Some(public_key)).await; + assert!(client.is_err()); + assert!(server.is_err()); + Ok(()) + } + + #[tokio::test] + #[traced_test] + async fn test_handshake_via_shared_secret_with_auth_negative() -> Result { + let secret_key = SecretKey::generate(rand::rngs::OsRng); + let public_key = secret_key.public(); + let wrong_secret_key = SecretKey::generate(rand::rngs::OsRng); + let (client, server) = + simulate_handshake(&wrong_secret_key, Some(42), Some(42), Some(public_key)).await; + assert!(client.is_err()); + assert!(server.is_err()); + Ok(()) + } + + #[test] + fn test_client_auth_roundtrip() -> Result { + let secret_key = SecretKey::generate(rand::rngs::OsRng); + let challenge = ServerChallenge::new(rand::rngs::OsRng); + let client_auth = ClientAuth::new(&secret_key, &challenge); + + let bytes = postcard::to_allocvec(&client_auth).e()?; + let decoded: ClientAuth = postcard::from_bytes(&bytes).e()?; + + assert_eq!(client_auth.public_key, decoded.public_key); + assert_eq!(client_auth.signature, decoded.signature); + + Ok(()) + } + + #[test] + fn test_km_client_auth_roundtrip() -> Result { + let secret_key = SecretKey::generate(rand::rngs::OsRng); + let client_auth = KeyMaterialClientAuth::new( + &secret_key, + &TestKeyingMaterial { + inner: (), + shared_secret: Some(42), + }, + ) + .e()?; + + let bytes = postcard::to_allocvec(&client_auth).e()?; + let decoded: KeyMaterialClientAuth = postcard::from_bytes(&bytes).e()?; + + assert_eq!(client_auth.public_key, decoded.public_key); + assert_eq!(client_auth.signature, decoded.signature); + + Ok(()) + } + + #[test] + fn test_challenge_verification() -> Result { + let secret_key = SecretKey::generate(rand::rngs::OsRng); + let challenge = ServerChallenge::new(rand::rngs::OsRng); + let client_auth = ClientAuth::new(&secret_key, &challenge); + assert!(client_auth.verify(&challenge).is_ok()); + + Ok(()) + } + + #[test] + fn test_key_material_verification() -> Result { + let secret_key = SecretKey::generate(rand::rngs::OsRng); + let io = TestKeyingMaterial { + inner: (), + shared_secret: Some(42), + }; + let client_auth = KeyMaterialClientAuth::new(&secret_key, &io).e()?; + assert!(client_auth.verify(&io).is_ok()); + + Ok(()) + } +} diff --git a/iroh-relay/src/protos/relay.rs b/iroh-relay/src/protos/relay.rs index 5c9c2e6520..4f85f602d7 100644 --- a/iroh-relay/src/protos/relay.rs +++ b/iroh-relay/src/protos/relay.rs @@ -1,32 +1,20 @@ -//! This module implements the relaying protocol used by the `server` and `client`. +//! This module implements the send/recv relaying protocol. //! //! Protocol flow: -//! -//! Login: -//! * client connects -//! * -> client sends `FrameType::ClientInfo` -//! -//! Steady state: -//! * server occasionally sends `FrameType::KeepAlive` (or `FrameType::Ping`) -//! * client responds to any `FrameType::Ping` with a `FrameType::Pong` -//! * clients sends `FrameType::SendPacket` -//! * server then sends `FrameType::RecvPacket` to recipient +//! * server occasionally sends [`FrameType::Ping`] +//! * client responds to any [`FrameType::Ping`] with a [`FrameType::Pong`] +//! * clients sends [`FrameType::SendPacket`] +//! * server then sends [`FrameType::RecvPacket`] to recipient +//! * server sends [`FrameType::NodeGone`] when the other client disconnects -#[cfg(not(wasm_browser))] -use bytes::BytesMut; -use bytes::{BufMut, Bytes}; -use iroh_base::{PublicKey, SecretKey, Signature, SignatureError}; -#[cfg(feature = "server")] +use bytes::{BufMut, Bytes, BytesMut}; +use iroh_base::{NodeId, SignatureError}; use n0_future::time::Duration; -use n0_future::{time, Sink, SinkExt}; -#[cfg(any(test, feature = "server"))] -use n0_future::{Stream, StreamExt}; use nested_enum_utils::common_fields; -use postcard::experimental::max_size::MaxSize; -use serde::{Deserialize, Serialize}; -use snafu::{Backtrace, Snafu}; +use snafu::{Backtrace, ResultExt, Snafu}; -use crate::{client::conn::SendError as ConnSendError, KeyCache}; +use super::common::{FrameType, FrameTypeError}; +use crate::KeyCache; /// The maximum size of a packet sent over relay. /// (This only includes the data bytes visible to magicsock, not @@ -39,9 +27,6 @@ pub const MAX_PACKET_SIZE: usize = 64 * 1024; #[cfg(not(wasm_browser))] pub(crate) const MAX_FRAME_SIZE: usize = 1024 * 1024; -/// The Relay magic number, sent in the FrameType::ClientInfo frame upon initial connection. -const MAGIC: &str = "RELAY🔑"; - /// Interval in which we ping the relay server to ensure the connection is alive. /// /// The default QUIC max_idle_timeout is 30s, so setting that to half this time gives some @@ -51,84 +36,7 @@ pub(crate) const PING_INTERVAL: Duration = Duration::from_secs(15); /// The number of packets buffered for sending per client #[cfg(feature = "server")] -pub(crate) const PER_CLIENT_SEND_QUEUE_DEPTH: usize = 512; //32; - -/// ProtocolVersion is bumped whenever there's a wire-incompatible change. -/// - version 1 (zero on wire): consistent box headers, in use by employee dev nodes a bit -/// - version 2: received packets have src addrs in FrameType::RecvPacket at beginning. -/// -/// NOTE: we are technically running a modified version of the protocol. -/// `FrameType::PeerPresent`, `FrameType::WatchConn`, `FrameType::ClosePeer`, have been removed. -/// The server will error on that connection if a client sends one of these frames. -/// We have split with the DERP protocol significantly starting with our relay protocol 3 -/// `FrameType::PeerPresent`, `FrameType::WatchConn`, `FrameType::ClosePeer`, `FrameType::ServerKey`, and `FrameType::ServerInfo` have been removed. -/// The server will error on that connection if a client sends one of these frames. -/// This materially affects the handshake protocol, and so relay nodes on version 3 will be unable to communicate -/// with nodes running earlier protocol versions. -pub(crate) const PROTOCOL_VERSION: usize = 3; - -/// Indicates this IS the client's home node -const PREFERRED: u8 = 1u8; -/// Indicates this IS NOT the client's home node -const NOT_PREFERRED: u8 = 0u8; - -/// The one byte frame type at the beginning of the frame -/// header. The second field is a big-endian u32 describing the -/// length of the remaining frame (not including the initial 5 bytes) -#[derive(Debug, PartialEq, Eq, num_enum::IntoPrimitive, num_enum::FromPrimitive, Clone, Copy)] -#[repr(u8)] -pub enum FrameType { - /// magic + 32b pub key + 24B nonce + bytes - ClientInfo = 2, - /// 32B dest pub key + packet bytes - SendPacket = 4, - /// v0/1 packet bytes, v2: 32B src pub key + packet bytes - RecvPacket = 5, - /// no payload, no-op (to be replaced with ping/pong) - KeepAlive = 6, - /// 1 byte payload: 0x01 or 0x00 for whether this is client's home node - NotePreferred = 7, - /// Sent from server to client to signal that a previous sender is no longer connected. - /// - /// That is, if A sent to B, and then if A disconnects, the server sends `FrameType::PeerGone` - /// to B so B can forget that a reverse path exists on that connection to get back to A - /// - /// 32B pub key of peer that's gone - PeerGone = 8, - /// Frames 9-11 concern meshing, which we have eliminated from our version of the protocol. - /// Messages with these frames will be ignored. - /// 8 byte ping payload, to be echoed back in FrameType::Pong - Ping = 12, - /// 8 byte payload, the contents of ping being replied to - Pong = 13, - /// Sent from server to client to tell the client if their connection is - /// unhealthy somehow. - /// - /// Currently this is used to indicate that the connection was closed because of authentication issues. - Health = 14, - - /// Sent from server to client for the server to declare that it's restarting. - /// Payload is two big endian u32 durations in milliseconds: when to reconnect, - /// and how long to try total. - /// - /// Handled on the `[relay::Client]`, but currently never sent on the `[relay::Server]` - Restarting = 15, - /// Unknown frame type - #[num_enum(default)] - Unknown = 255, -} - -impl std::fmt::Display for FrameType { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - write!(f, "{self:?}") - } -} - -#[derive(Debug, Serialize, Deserialize, MaxSize, PartialEq, Eq)] -pub(crate) struct ClientInfo { - /// The relay protocol version that the client was built with. - pub(crate) version: usize, -} +pub(crate) const PER_CLIENT_SEND_QUEUE_DEPTH: usize = 512; /// Protocol send errors. #[common_fields({ @@ -139,380 +47,210 @@ pub(crate) struct ClientInfo { #[allow(missing_docs)] #[derive(Debug, Snafu)] #[non_exhaustive] -pub enum SendError { - #[snafu(transparent)] - Io { source: std::io::Error }, - #[snafu(transparent)] - Timeout { source: time::Elapsed }, - #[snafu(transparent)] - ConnSend { source: ConnSendError }, - #[snafu(transparent)] - SerDe { source: postcard::Error }, -} - -/// Protocol send errors. -#[common_fields({ - backtrace: Option, - #[snafu(implicit)] - span_trace: n0_snafu::SpanTrace, -})] -#[allow(missing_docs)] -#[derive(Debug, Snafu)] -#[non_exhaustive] -pub enum RecvError { - #[snafu(transparent)] - Io { source: std::io::Error }, - #[snafu(display("unexpected frame: got {got}, expected {expected}"))] +pub enum Error { + #[snafu(display("unexpected frame: got {got:?}, expected {expected:?}"))] UnexpectedFrame { got: FrameType, expected: FrameType }, #[snafu(display("Frame is too large, has {frame_len} bytes"))] FrameTooLarge { frame_len: usize }, #[snafu(transparent)] - Timeout { source: time::Elapsed }, - #[snafu(transparent)] SerDe { source: postcard::Error }, #[snafu(transparent)] - InvalidSignature { source: SignatureError }, + FrameTypeError { source: FrameTypeError }, + #[snafu(display("Invalid public key"))] + InvalidPublicKey { source: SignatureError }, #[snafu(display("Invalid frame encoding"))] InvalidFrame {}, - #[snafu(display("Invalid frame type: {frame_type}"))] + #[snafu(display("Invalid frame type: {frame_type:?}"))] InvalidFrameType { frame_type: FrameType }, + #[snafu(display("Invalid protocol message encoding"))] + InvalidProtocolMessageEncoding { source: std::str::Utf8Error }, #[snafu(display("Too few bytes"))] TooSmall {}, } -/// Writes complete frame, errors if it is unable to write within the given `timeout`. -/// Ignores the timeout if `None` -/// -/// Does not flush. -#[cfg(feature = "server")] -pub(crate) async fn write_frame + Unpin>( - mut writer: S, - frame: Frame, - timeout: Option, -) -> Result<(), SendError> { - if let Some(duration) = timeout { - tokio::time::timeout(duration, writer.send(frame)).await??; - } else { - writer.send(frame).await?; - } - - Ok(()) -} - -/// Writes a `FrameType::ClientInfo`, including the client's [`PublicKey`], -/// and the client's [`ClientInfo`], sealed using the server's [`PublicKey`]. -/// -/// Flushes after writing. -pub(crate) async fn send_client_key + Unpin>( - mut writer: S, - client_secret_key: &SecretKey, - client_info: &ClientInfo, -) -> Result<(), SendError> { - let msg = postcard::to_stdvec(client_info)?; - let signature = client_secret_key.sign(&msg); - - writer - .send(Frame::ClientInfo { - client_public_key: client_secret_key.public(), - message: msg.into(), - signature, - }) - .await?; - writer.flush().await?; - Ok(()) -} - -/// Reads the `FrameType::ClientInfo` frame from the client (its proof of identity) -/// upon it's initial connection. -#[cfg(feature = "server")] -pub(crate) async fn recv_client_key> + Unpin>( - stream: S, -) -> Result<(PublicKey, ClientInfo), E> -where - E: From, -{ - // the client is untrusted at this point, limit the input size even smaller than our usual - // maximum frame size, and give a timeout - - // TODO: variable recv size: 256 * 1024 - let buf = tokio::time::timeout( - std::time::Duration::from_secs(10), - recv_frame(FrameType::ClientInfo, stream), - ) - .await - .map_err(RecvError::from)??; - - if let Frame::ClientInfo { - client_public_key, - message, - signature, - } = buf - { - client_public_key - .verify(&message, &signature) - .map_err(RecvError::from)?; - - let info: ClientInfo = postcard::from_bytes(&message).map_err(RecvError::from)?; - Ok((client_public_key, info)) - } else { - Err(UnexpectedFrameSnafu { - got: buf.typ(), - expected: FrameType::ClientInfo, - } - .build() - .into()) - } -} - -/// The relay protocol frames. -#[derive(Debug, Clone, PartialEq, Eq)] -pub(crate) enum Frame { - ClientInfo { - client_public_key: PublicKey, - message: Bytes, - signature: Signature, - }, - SendPacket { - dst_key: PublicKey, - packet: Bytes, - }, - RecvPacket { - src_key: PublicKey, +/// The messages that a relay sends to clients or the clients receive from the relay. +#[derive(derive_more::Debug, Clone, PartialEq, Eq)] +pub enum RelayToClientMsg { + /// Represents datagrams sent from relays (originally sent to them by another client). + ReceivedPacket { + /// The [`NodeId`] of the original sender. + src_key: NodeId, + /// The received packet bytes. + #[debug(skip)] content: Bytes, }, - KeepAlive, - NotePreferred { - preferred: bool, - }, - NodeGone { - node_id: PublicKey, - }, - Ping { - data: [u8; 8], - }, - Pong { - data: [u8; 8], - }, + /// Indicates that the client identified by the underlying public key had previously sent you a + /// packet but has now disconnected from the relay. + NodeGone(NodeId), + /// A one-way message from relay to client, declaring the connection health state. Health { - problem: Bytes, + /// If set, is a description of why the connection is unhealthy. + /// + /// If `None` means the connection is healthy again. + /// + /// The default condition is healthy, so the relay doesn't broadcast a [`RelayToClientMsg::Health`] + /// until a problem exists. + problem: String, }, + /// A one-way message from relay to client, advertising that the relay is restarting. Restarting { - reconnect_in: u32, - try_for: u32, + /// An advisory duration that the client should wait before attempting to reconnect. + /// It might be zero. It exists for the relay to smear out the reconnects. + reconnect_in: Duration, + /// An advisory duration for how long the client should attempt to reconnect + /// before giving up and proceeding with its normal connection failure logic. The interval + /// between retries is undefined for now. A relay should not send a `try_for` duration more + /// than a few seconds. + try_for: Duration, + }, + /// Request from the relay to reply to the + /// other side with a [`ClientToRelayMsg::Pong`] with the given payload. + Ping([u8; 8]), + /// Reply to a [`ClientToRelayMsg::Ping`] from a client + /// with the payload sent previously in the ping. + Pong([u8; 8]), +} + +/// Messages that clients send to relays. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum ClientToRelayMsg { + /// Request from the client to the server to reply to the + /// other side with a [`RelayToClientMsg::Pong`] with the given payload. + Ping([u8; 8]), + /// Reply to a [`RelayToClientMsg::Ping`] from a server + /// with the payload sent previously in the ping. + Pong([u8; 8]), + /// Request from the client to relay datagrams to given remote node. + SendPacket { + /// The remote node to relay to. + dst_key: NodeId, + /// The datagrams and related metadata to relay. + packet: Bytes, }, } -impl Frame { - pub(crate) fn typ(&self) -> FrameType { +impl RelayToClientMsg { + /// Returns this frame's corresponding frame type. + pub fn typ(&self) -> FrameType { match self { - Frame::ClientInfo { .. } => FrameType::ClientInfo, - Frame::SendPacket { .. } => FrameType::SendPacket, - Frame::RecvPacket { .. } => FrameType::RecvPacket, - Frame::KeepAlive => FrameType::KeepAlive, - Frame::NotePreferred { .. } => FrameType::NotePreferred, - Frame::NodeGone { .. } => FrameType::PeerGone, - Frame::Ping { .. } => FrameType::Ping, - Frame::Pong { .. } => FrameType::Pong, - Frame::Health { .. } => FrameType::Health, - Frame::Restarting { .. } => FrameType::Restarting, + Self::ReceivedPacket { .. } => FrameType::RecvPacket, + Self::NodeGone { .. } => FrameType::NodeGone, + Self::Ping { .. } => FrameType::Ping, + Self::Pong { .. } => FrameType::Pong, + Self::Health { .. } => FrameType::Health, + Self::Restarting { .. } => FrameType::Restarting, } } - #[cfg(not(wasm_browser))] + #[cfg(feature = "server")] pub(crate) fn to_bytes(&self) -> BytesMut { self.write_to(BytesMut::with_capacity(self.encoded_len())) } - #[cfg(wasm_browser)] - pub(crate) fn to_vec(&self) -> Vec { - self.write_to(Vec::with_capacity(self.encoded_len())) - } - - /// Writes it self to the given buffer. + /// Encodes this frame for sending over websockets. + /// + /// Specifically meant for being put into a binary websocket message frame. + #[cfg(feature = "server")] pub(crate) fn write_to(&self, mut dst: O) -> O { - dst.put_u8(self.typ().into()); + dst = self.typ().write_to(dst); match self { - Frame::ClientInfo { - client_public_key, - message, - signature, + Self::ReceivedPacket { + src_key: remote_node_id, + content, } => { - dst.put(MAGIC.as_bytes()); - dst.put(client_public_key.as_ref()); - dst.put(&signature.to_bytes()[..]); - dst.put(&message[..]); - } - Frame::SendPacket { dst_key, packet } => { - dst.put(dst_key.as_ref()); - dst.put(packet.as_ref()); - } - Frame::RecvPacket { src_key, content } => { - dst.put(src_key.as_ref()); + dst.put(remote_node_id.as_ref()); dst.put(content.as_ref()); } - Frame::KeepAlive => {} - Frame::NotePreferred { preferred } => { - if *preferred { - dst.put_u8(PREFERRED); - } else { - dst.put_u8(NOT_PREFERRED); - } + Self::NodeGone(node_id) => { + dst.put(node_id.as_ref()); } - Frame::NodeGone { node_id: peer } => { - dst.put(peer.as_ref()); - } - Frame::Ping { data } => { + Self::Ping(data) => { dst.put(&data[..]); } - Frame::Pong { data } => { + Self::Pong(data) => { dst.put(&data[..]); } - Frame::Health { problem } => { + Self::Health { problem } => { dst.put(problem.as_ref()); } - Frame::Restarting { + Self::Restarting { reconnect_in, try_for, } => { - dst.put_u32(*reconnect_in); - dst.put_u32(*try_for); + dst.put_u32(reconnect_in.as_millis() as u32); + dst.put_u32(try_for.as_millis() as u32); } } dst } + #[cfg(feature = "server")] pub(crate) fn encoded_len(&self) -> usize { let payload_len = match self { - Self::ClientInfo { message, .. } => { - MAGIC.len() - + 32 // node id - + 64 // signature - + message.len() - } - Self::SendPacket { packet, .. } => { - 32 // node id - + packet.len() - } - Self::RecvPacket { content, .. } => { - 32 // node id + Self::ReceivedPacket { content, .. } => { + 32 // nodeid + content.len() } - Self::KeepAlive => 0, - Self::NotePreferred { .. } => 1, - Self::NodeGone { .. } => 32, - Self::Ping { .. } | Self::Pong { .. } => 8, + Self::NodeGone(_) => 32, + Self::Ping(_) | Self::Pong(_) => 8, Self::Health { problem } => problem.len(), Self::Restarting { .. } => { 4 // u32 + 4 // u32 } }; - 1 // frame type - + payload_len + self.typ().encoded_len() + payload_len } + /// Tries to decode a frame received over websockets. + /// + /// Specifically, bytes received from a binary websocket message frame. #[allow(clippy::result_large_err)] - pub(crate) fn from_bytes(bytes: Bytes, cache: &KeyCache) -> Result { - if bytes.is_empty() { - return Err(TooSmallSnafu.build()); - } - let frame_type = FrameType::from(bytes[0]); - let content = bytes.slice(1..); + pub(crate) fn from_bytes(mut content: Bytes, cache: &KeyCache) -> Result { + let frame_type = FrameType::from_bytes(&mut content)?; + let frame_len = content.len(); + snafu::ensure!( + frame_len <= MAX_PACKET_SIZE, + FrameTooLargeSnafu { frame_len } + ); + let res = match frame_type { - FrameType::ClientInfo => { - if content.len() < PublicKey::LENGTH + Signature::BYTE_SIZE + MAGIC.len() { - return Err(InvalidFrameSnafu.build()); - } - if &content[..MAGIC.len()] != MAGIC.as_bytes() { - return Err(InvalidFrameSnafu.build()); - } - - let start = MAGIC.len(); - let client_public_key = - cache.key_from_slice(&content[start..start + PublicKey::LENGTH])?; - let start = start + PublicKey::LENGTH; - let signature = - Signature::from_slice(&content[start..start + Signature::BYTE_SIZE])?; - let start = start + Signature::BYTE_SIZE; - let message = content.slice(start..); - Self::ClientInfo { - client_public_key, - message, - signature, - } - } - FrameType::SendPacket => { - if content.len() < PublicKey::LENGTH { - return Err(InvalidFrameSnafu.build()); - } - let frame_len = content.len() - PublicKey::LENGTH; - if frame_len > MAX_PACKET_SIZE { - return Err(FrameTooLargeSnafu { frame_len }.build()); - } - - let dst_key = cache.key_from_slice(&content[..PublicKey::LENGTH])?; - let packet = content.slice(PublicKey::LENGTH..); - Self::SendPacket { dst_key, packet } - } FrameType::RecvPacket => { - if content.len() < PublicKey::LENGTH { - return Err(InvalidFrameSnafu.build()); - } + snafu::ensure!(content.len() > NodeId::LENGTH, InvalidFrameSnafu); - let frame_len = content.len() - PublicKey::LENGTH; - if frame_len > MAX_PACKET_SIZE { - return Err(FrameTooLargeSnafu { frame_len }.build()); - } - - let src_key = cache.key_from_slice(&content[..PublicKey::LENGTH])?; - let content = content.slice(PublicKey::LENGTH..); - Self::RecvPacket { src_key, content } + let src_key = cache + .key_from_slice(&content[..NodeId::LENGTH]) + .context(InvalidPublicKeySnafu)?; + let content = content.slice(NodeId::LENGTH..); + Self::ReceivedPacket { src_key, content } } - FrameType::KeepAlive => { - if !content.is_empty() { - return Err(InvalidFrameSnafu.build()); - } - Self::KeepAlive - } - FrameType::NotePreferred => { - if content.len() != 1 { - return Err(InvalidFrameSnafu.build()); - } - let preferred = match content[0] { - PREFERRED => true, - NOT_PREFERRED => false, - _ => return Err(InvalidFrameSnafu.build()), - }; - Self::NotePreferred { preferred } - } - FrameType::PeerGone => { - if content.len() != PublicKey::LENGTH { - return Err(InvalidFrameSnafu.build()); - } - let peer = cache.key_from_slice(&content[..32])?; - Self::NodeGone { node_id: peer } + FrameType::NodeGone => { + snafu::ensure!(content.len() == NodeId::LENGTH, InvalidFrameSnafu); + let node_id = cache + .key_from_slice(content.as_ref()) + .context(InvalidPublicKeySnafu)?; + Self::NodeGone(node_id) } FrameType::Ping => { - if content.len() != 8 { - return Err(InvalidFrameSnafu.build()); - } + snafu::ensure!(content.len() == 8, InvalidFrameSnafu); let mut data = [0u8; 8]; data.copy_from_slice(&content[..8]); - Self::Ping { data } + Self::Ping(data) } FrameType::Pong => { - if content.len() != 8 { - return Err(InvalidFrameSnafu.build()); - } + snafu::ensure!(content.len() == 8, InvalidFrameSnafu); let mut data = [0u8; 8]; data.copy_from_slice(&content[..8]); - Self::Pong { data } + Self::Pong(data) + } + FrameType::Health => { + let problem = std::str::from_utf8(&content) + .context(InvalidProtocolMessageEncodingSnafu)? + .to_owned(); + Self::Health { problem } } - FrameType::Health => Self::Health { problem: content }, FrameType::Restarting => { - if content.len() != 4 + 4 { - return Err(InvalidFrameSnafu.build()); - } + snafu::ensure!(content.len() == 4 + 4, InvalidFrameSnafu); let reconnect_in = u32::from_be_bytes( content[..4] .try_into() @@ -523,6 +261,8 @@ impl Frame { .try_into() .map_err(|_| InvalidFrameSnafu.build())?, ); + let reconnect_in = Duration::from_millis(reconnect_in as u64); + let try_for = Duration::from_millis(try_for as u64); Self::Restarting { reconnect_in, try_for, @@ -536,142 +276,103 @@ impl Frame { } } -/// Receives the next frame and matches the frame type. If the correct type is found returns the content, -/// otherwise an error. -#[cfg(any(test, feature = "server"))] -pub(crate) async fn recv_frame> + Unpin>( - frame_type: FrameType, - mut stream: S, -) -> Result -where - RecvError: Into, -{ - match stream.next().await { - Some(Ok(frame)) => { - if frame_type != frame.typ() { - return Err(UnexpectedFrameSnafu { - got: frame.typ(), - expected: frame_type, - } - .build() - .into()); - } - Ok(frame) +impl ClientToRelayMsg { + pub(crate) fn typ(&self) -> FrameType { + match self { + Self::SendPacket { .. } => FrameType::SendPacket, + Self::Ping { .. } => FrameType::Ping, + Self::Pong { .. } => FrameType::Pong, } - Some(Err(err)) => Err(err), - None => Err(RecvError::from(std::io::Error::new( - std::io::ErrorKind::UnexpectedEof, - "expected frame".to_string(), - )) - .into()), + } + + pub(crate) fn to_bytes(&self) -> BytesMut { + self.write_to(BytesMut::with_capacity(self.encoded_len())) + } + + /// Encodes this frame for sending over websockets. + /// + /// Specifically meant for being put into a binary websocket message frame. + pub(crate) fn write_to(&self, mut dst: O) -> O { + dst = self.typ().write_to(dst); + match self { + Self::SendPacket { dst_key, packet } => { + dst.put(dst_key.as_ref()); + dst.put(packet.as_ref()); + } + Self::Ping(data) => { + dst.put(&data[..]); + } + Self::Pong(data) => { + dst.put(&data[..]); + } + } + dst + } + + pub(crate) fn encoded_len(&self) -> usize { + let payload_len = match self { + Self::Ping(_) | Self::Pong(_) => 8, + Self::SendPacket { packet, .. } => { + 32 // node id + + packet.len() + } + }; + self.typ().encoded_len() + payload_len + } + + /// Tries to decode a frame received over websockets. + /// + /// Specifically, bytes received from a binary websocket message frame. + #[allow(clippy::result_large_err)] + #[cfg(feature = "server")] + pub(crate) fn from_bytes(mut content: Bytes, cache: &KeyCache) -> Result { + let frame_type = FrameType::from_bytes(&mut content)?; + let frame_len = content.len(); + snafu::ensure!( + frame_len <= MAX_PACKET_SIZE, + FrameTooLargeSnafu { frame_len } + ); + + let res = match frame_type { + FrameType::SendPacket => { + snafu::ensure!(content.len() > NodeId::LENGTH, InvalidFrameSnafu); + let dst_key = cache + .key_from_slice(&content[..NodeId::LENGTH]) + .context(InvalidPublicKeySnafu)?; + let packet = content.slice(NodeId::LENGTH..); + Self::SendPacket { dst_key, packet } + } + FrameType::Ping => { + snafu::ensure!(content.len() == 8, InvalidFrameSnafu); + let mut data = [0u8; 8]; + data.copy_from_slice(&content[..8]); + Self::Ping(data) + } + FrameType::Pong => { + snafu::ensure!(content.len() == 8, InvalidFrameSnafu); + let mut data = [0u8; 8]; + data.copy_from_slice(&content[..8]); + Self::Pong(data) + } + _ => { + return Err(InvalidFrameTypeSnafu { frame_type }.build()); + } + }; + Ok(res) } } -#[cfg(all(test, feature = "server"))] +#[cfg(test)] +#[cfg(feature = "server")] mod tests { use data_encoding::HEXLOWER; use iroh_base::SecretKey; - use n0_snafu::{Result, ResultExt}; + use n0_snafu::Result; use super::*; - use crate::server::streams::RelayedStream; - #[tokio::test] - async fn test_send_recv_client_key() -> Result { - let (reader, writer) = tokio::io::duplex(1024); - let mut reader = RelayedStream::test_client(reader); - let mut writer = RelayedStream::test_server(writer).sink_err_into(); - - let client_key = SecretKey::generate(rand::thread_rng()); - let client_info = ClientInfo { - version: PROTOCOL_VERSION, - }; - println!("client_key pub {:?}", client_key.public()); - send_client_key(&mut writer, &client_key, &client_info).await?; - let (client_pub_key, got_client_info) = recv_client_key(&mut reader).await?; - assert_eq!(client_key.public(), client_pub_key); - assert_eq!(client_info, got_client_info); - Ok(()) - } - - #[test] - fn test_frame_snapshot() -> Result { - let client_key = SecretKey::from_bytes(&[42u8; 32]); - let client_info = ClientInfo { - version: PROTOCOL_VERSION, - }; - let message = postcard::to_stdvec(&client_info).context("encode")?; - let signature = client_key.sign(&message); - - let frames = vec![ - ( - Frame::ClientInfo { - client_public_key: client_key.public(), - message: Bytes::from(message), - signature, - }, - "02 52 45 4c 41 59 f0 9f 94 91 19 7f 6b 23 e1 6c - 85 32 c6 ab c8 38 fa cd 5e a7 89 be 0c 76 b2 92 - 03 34 03 9b fa 8b 3d 36 8d 61 88 e7 7b 22 f2 92 - ab 37 43 5d a8 de 0b c8 cb 84 e2 88 f4 e7 3b 35 - 82 a5 27 31 e9 ff 98 65 46 5c 87 e0 5e 8d 42 7d - f4 22 bb 6e 85 e1 c0 5f 6f 74 98 37 ba a4 a5 c7 - eb a3 23 0d 77 56 99 10 43 0e 03", - ), - ( - Frame::Health { - problem: "Hello? Yes this is dog.".into(), - }, - "0e 48 65 6c 6c 6f 3f 20 59 65 73 20 74 68 69 73 - 20 69 73 20 64 6f 67 2e", - ), - (Frame::KeepAlive, "06"), - (Frame::NotePreferred { preferred: true }, "07 01"), - ( - Frame::NodeGone { - node_id: client_key.public(), - }, - "08 19 7f 6b 23 e1 6c 85 32 c6 ab c8 38 fa cd 5e - a7 89 be 0c 76 b2 92 03 34 03 9b fa 8b 3d 36 8d - 61", - ), - ( - Frame::Ping { data: [42u8; 8] }, - "0c 2a 2a 2a 2a 2a 2a 2a 2a", - ), - ( - Frame::Pong { data: [42u8; 8] }, - "0d 2a 2a 2a 2a 2a 2a 2a 2a", - ), - ( - Frame::RecvPacket { - src_key: client_key.public(), - content: "Hello World!".into(), - }, - "05 19 7f 6b 23 e1 6c 85 32 c6 ab c8 38 fa cd 5e - a7 89 be 0c 76 b2 92 03 34 03 9b fa 8b 3d 36 8d - 61 48 65 6c 6c 6f 20 57 6f 72 6c 64 21", - ), - ( - Frame::SendPacket { - dst_key: client_key.public(), - packet: "Goodbye!".into(), - }, - "04 19 7f 6b 23 e1 6c 85 32 c6 ab c8 38 fa cd 5e - a7 89 be 0c 76 b2 92 03 34 03 9b fa 8b 3d 36 8d - 61 47 6f 6f 64 62 79 65 21", - ), - ( - Frame::Restarting { - reconnect_in: 10, - try_for: 20, - }, - "0f 00 00 00 0a 00 00 00 14", - ), - ]; - - for (frame, expected_hex) in frames { - let bytes = frame.to_bytes().freeze(); + fn check_expected_bytes(frames: Vec<(Vec, &str)>) { + for (bytes, expected_hex) in frames { let stripped: Vec = expected_hex .chars() .filter_map(|s| { @@ -683,14 +384,90 @@ mod tests { }) .collect(); let expected_bytes = HEXLOWER.decode(&stripped).unwrap(); - assert_eq!(bytes, expected_bytes); + assert_eq!(HEXLOWER.encode(&bytes), HEXLOWER.encode(&expected_bytes)); } + } + + #[test] + fn test_server_client_frames_snapshot() -> Result { + let client_key = SecretKey::from_bytes(&[42u8; 32]); + + check_expected_bytes(vec![ + ( + RelayToClientMsg::Health { + problem: "Hello? Yes this is dog.".into(), + } + .write_to(Vec::new()), + "0b 48 65 6c 6c 6f 3f 20 59 65 73 20 74 68 69 73 + 20 69 73 20 64 6f 67 2e", + ), + ( + RelayToClientMsg::NodeGone(client_key.public()).write_to(Vec::new()), + "08 19 7f 6b 23 e1 6c 85 32 c6 ab c8 38 fa cd 5e + a7 89 be 0c 76 b2 92 03 34 03 9b fa 8b 3d 36 8d + 61", + ), + ( + RelayToClientMsg::Ping([42u8; 8]).write_to(Vec::new()), + "09 2a 2a 2a 2a 2a 2a 2a 2a", + ), + ( + RelayToClientMsg::Pong([42u8; 8]).write_to(Vec::new()), + "0a 2a 2a 2a 2a 2a 2a 2a 2a", + ), + ( + RelayToClientMsg::ReceivedPacket { + src_key: client_key.public(), + content: "Hello World!".into(), + } + .write_to(Vec::new()), + "06 19 7f 6b 23 e1 6c 85 32 c6 ab c8 38 fa cd 5e + a7 89 be 0c 76 b2 92 03 34 03 9b fa 8b 3d 36 8d + 61 48 65 6c 6c 6f 20 57 6f 72 6c 64 21", + ), + ( + RelayToClientMsg::Restarting { + reconnect_in: Duration::from_millis(10), + try_for: Duration::from_millis(20), + } + .write_to(Vec::new()), + "0c 00 00 00 0a 00 00 00 14", + ), + ]); + + Ok(()) + } + + #[test] + fn test_client_server_frames_snapshot() -> Result { + let client_key = SecretKey::from_bytes(&[42u8; 32]); + + check_expected_bytes(vec![ + ( + ClientToRelayMsg::Ping([42u8; 8]).write_to(Vec::new()), + "09 2a 2a 2a 2a 2a 2a 2a 2a", + ), + ( + ClientToRelayMsg::Pong([42u8; 8]).write_to(Vec::new()), + "0a 2a 2a 2a 2a 2a 2a 2a 2a", + ), + ( + ClientToRelayMsg::SendPacket { + dst_key: client_key.public(), + packet: "Goodbye!".into(), + } + .write_to(Vec::new()), + "04 19 7f 6b 23 e1 6c 85 32 c6 ab c8 38 fa cd 5e + a7 89 be 0c 76 b2 92 03 34 03 9b fa 8b 3d 36 8d + 61 47 6f 6f 64 62 79 65 21", + ), + ]); Ok(()) } } -#[cfg(test)] +#[cfg(all(test, feature = "server"))] mod proptests { use iroh_base::SecretKey; use proptest::prelude::*; @@ -701,7 +478,7 @@ mod proptests { prop::array::uniform32(any::()).prop_map(SecretKey::from) } - fn key() -> impl Strategy { + fn key() -> impl Strategy { secret_key().prop_map(|key| key.public()) } @@ -712,58 +489,58 @@ mod proptests { } /// Generates a random valid frame - fn frame() -> impl Strategy { - let client_info = (secret_key()).prop_map(|secret_key| { - let info = ClientInfo { - version: PROTOCOL_VERSION, - }; - let msg = postcard::to_stdvec(&info).expect("using default ClientInfo"); - let signature = secret_key.sign(&msg); - Frame::ClientInfo { - client_public_key: secret_key.public(), - message: msg.into(), - signature, + fn server_client_frame() -> impl Strategy { + let recv_packet = (key(), data(32)) + .prop_map(|(src_key, content)| RelayToClientMsg::ReceivedPacket { src_key, content }); + let node_gone = key().prop_map(RelayToClientMsg::NodeGone); + let ping = prop::array::uniform8(any::()).prop_map(RelayToClientMsg::Ping); + let pong = prop::array::uniform8(any::()).prop_map(RelayToClientMsg::Pong); + let health = ".{0,65536}" + .prop_filter("exceeds max payload size", |s| { + s.len() < 65536 // a single unicode character can match a regex "." but take up multiple bytes + }) + .prop_map(|problem| RelayToClientMsg::Health { problem }); + let restarting = (any::(), any::()).prop_map(|(reconnect_in, try_for)| { + RelayToClientMsg::Restarting { + reconnect_in: Duration::from_millis(reconnect_in.into()), + try_for: Duration::from_millis(try_for.into()), } }); - let send_packet = - (key(), data(32)).prop_map(|(dst_key, packet)| Frame::SendPacket { dst_key, packet }); - let recv_packet = - (key(), data(32)).prop_map(|(src_key, content)| Frame::RecvPacket { src_key, content }); - let keep_alive = Just(Frame::KeepAlive); - let note_preferred = any::().prop_map(|preferred| Frame::NotePreferred { preferred }); - let peer_gone = key().prop_map(|peer| Frame::NodeGone { node_id: peer }); - let ping = prop::array::uniform8(any::()).prop_map(|data| Frame::Ping { data }); - let pong = prop::array::uniform8(any::()).prop_map(|data| Frame::Pong { data }); - let health = data(0).prop_map(|problem| Frame::Health { problem }); - let restarting = - (any::(), any::()).prop_map(|(reconnect_in, try_for)| Frame::Restarting { - reconnect_in, - try_for, - }); - prop_oneof![ - client_info, - send_packet, - recv_packet, - keep_alive, - note_preferred, - peer_gone, - ping, - pong, - health, - restarting, - ] + prop_oneof![recv_packet, node_gone, ping, pong, health, restarting] + } + + fn client_server_frame() -> impl Strategy { + let send_packet = (key(), data(32)) + .prop_map(|(dst_key, packet)| ClientToRelayMsg::SendPacket { dst_key, packet }); + let ping = prop::array::uniform8(any::()).prop_map(ClientToRelayMsg::Ping); + let pong = prop::array::uniform8(any::()).prop_map(ClientToRelayMsg::Pong); + prop_oneof![send_packet, ping, pong] } proptest! { #[test] - fn frame_roundtrip(frame in frame()) { + fn server_client_frame_roundtrip(frame in server_client_frame()) { let encoded = frame.to_bytes().freeze(); - let decoded = Frame::from_bytes(encoded, &KeyCache::test()).unwrap(); + let decoded = RelayToClientMsg::from_bytes(encoded, &KeyCache::test()).unwrap(); prop_assert_eq!(frame, decoded); } #[test] - fn frame_encoded_len(frame in frame()) { + fn client_server_frame_roundtrip(frame in client_server_frame()) { + let encoded = frame.to_bytes().freeze(); + let decoded = ClientToRelayMsg::from_bytes(encoded, &KeyCache::test()).unwrap(); + prop_assert_eq!(frame, decoded); + } + + #[test] + fn server_client_frame_encoded_len(frame in server_client_frame()) { + let claimed_encoded_len = frame.encoded_len(); + let actual_encoded_len = frame.to_bytes().len(); + prop_assert_eq!(claimed_encoded_len, actual_encoded_len); + } + + #[test] + fn client_server_frame_encoded_len(frame in client_server_frame()) { let claimed_encoded_len = frame.encoded_len(); let actual_encoded_len = frame.to_bytes().len(); prop_assert_eq!(claimed_encoded_len, actual_encoded_len); diff --git a/iroh-relay/src/protos/streams.rs b/iroh-relay/src/protos/streams.rs new file mode 100644 index 0000000000..1ed9015434 --- /dev/null +++ b/iroh-relay/src/protos/streams.rs @@ -0,0 +1,166 @@ +//! Implements logic for abstracting over a websocket stream that allows sending only [`Bytes`]-based +//! messages. +use std::{ + pin::Pin, + task::{Context, Poll}, +}; + +use bytes::Bytes; +use n0_future::{ready, Sink, Stream}; +#[cfg(not(wasm_browser))] +use tokio::io::{AsyncRead, AsyncWrite}; +use tracing::warn; + +use crate::ExportKeyingMaterial; + +#[cfg(not(wasm_browser))] +#[derive(derive_more::Debug)] +pub(crate) struct WsBytesFramed { + #[debug("WebSocketStream")] + pub(crate) io: tokio_websockets::WebSocketStream, +} + +#[cfg(wasm_browser)] +#[derive(derive_more::Debug)] +pub(crate) struct WsBytesFramed { + #[debug("WebSocketStream")] + pub(crate) io: ws_stream_wasm::WsStream, +} + +#[cfg(not(wasm_browser))] +pub(crate) type StreamError = tokio_websockets::Error; + +#[cfg(wasm_browser)] +pub(crate) type StreamError = ws_stream_wasm::WsErr; + +/// Shorthand for a type that implements both a websocket-based stream & sink for [`Bytes`]. +pub(crate) trait BytesStreamSink: + Stream> + Sink + Unpin +{ +} + +impl BytesStreamSink for T where + T: Stream> + Sink + Unpin +{ +} + +#[cfg(not(wasm_browser))] +impl ExportKeyingMaterial + for WsBytesFramed +{ + fn export_keying_material>( + &self, + output: T, + label: &[u8], + context: Option<&[u8]>, + ) -> Option { + self.io + .get_ref() + .export_keying_material(output, label, context) + } +} + +#[cfg(wasm_browser)] +impl ExportKeyingMaterial for WsBytesFramed { + fn export_keying_material>( + &self, + _output: T, + _label: &[u8], + _context: Option<&[u8]>, + ) -> Option { + None + } +} + +#[cfg(not(wasm_browser))] +impl Stream for WsBytesFramed { + type Item = Result; + + fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + loop { + match ready!(Pin::new(&mut self.io).poll_next(cx)) { + None => return Poll::Ready(None), + Some(Err(e)) => return Poll::Ready(Some(Err(e))), + Some(Ok(msg)) => { + if msg.is_close() { + // Indicate the stream is done when we receive a close message. + // Note: We don't have to poll the stream to completion for it to close gracefully. + return Poll::Ready(None); + } + if msg.is_ping() || msg.is_pong() { + continue; // Responding appropriately to these is done inside of tokio_websockets/browser impls + } + if !msg.is_binary() { + warn!(?msg, "Got websocket message of unsupported type, skipping."); + continue; + } + return Poll::Ready(Some(Ok(msg.into_payload().into()))); + } + } + } + } +} + +#[cfg(wasm_browser)] +impl Stream for WsBytesFramed { + type Item = Result; + + fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + loop { + match ready!(Pin::new(&mut self.io).poll_next(cx)) { + None => return Poll::Ready(None), + Some(ws_stream_wasm::WsMessage::Binary(msg)) => { + return Poll::Ready(Some(Ok(msg.into()))) + } + Some(msg) => { + warn!(?msg, "Got websocket message of unsupported type, skipping."); + continue; + } + } + } + } +} + +#[cfg(not(wasm_browser))] +impl Sink for WsBytesFramed { + type Error = StreamError; + + fn start_send(mut self: Pin<&mut Self>, bytes: Bytes) -> Result<(), Self::Error> { + let msg = tokio_websockets::Message::binary(tokio_websockets::Payload::from(bytes)); + Pin::new(&mut self.io).start_send(msg) + } + + fn poll_ready(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + Pin::new(&mut self.io).poll_ready(cx).map_err(Into::into) + } + + fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + Pin::new(&mut self.io).poll_flush(cx).map_err(Into::into) + } + + fn poll_close(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + Pin::new(&mut self.io).poll_close(cx).map_err(Into::into) + } +} + +#[cfg(wasm_browser)] +impl Sink for WsBytesFramed { + type Error = StreamError; + + fn start_send(mut self: Pin<&mut Self>, bytes: Bytes) -> Result<(), Self::Error> { + let msg = ws_stream_wasm::WsMessage::Binary(Vec::from(bytes)); + Pin::new(&mut self.io).start_send(msg).map_err(Into::into) + } + + fn poll_ready(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + Pin::new(&mut self.io).poll_ready(cx).map_err(Into::into) + } + + fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + Pin::new(&mut self.io).poll_flush(cx).map_err(Into::into) + } + + fn poll_close(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + Pin::new(&mut self.io).poll_close(cx).map_err(Into::into) + } +} diff --git a/iroh-relay/src/quic.rs b/iroh-relay/src/quic.rs index 2f6c0d277f..97ac5b9987 100644 --- a/iroh-relay/src/quic.rs +++ b/iroh-relay/src/quic.rs @@ -297,7 +297,7 @@ impl QuicClient { /// and estimated latency of the connection. /// /// Consumes and gracefully closes the connection. - #[cfg(test)] + #[cfg(all(test, feature = "server"))] async fn get_addr_and_latency( &self, server_addr: SocketAddr, @@ -368,14 +368,14 @@ mod tests { use tracing_test::traced_test; use webpki_types::PrivatePkcs8KeyDer; - use super::{ - server::{QuicConfig, QuicServer}, - *, - }; + use super::*; #[tokio::test] #[traced_test] + #[cfg(feature = "test-utils")] async fn quic_endpoint_basic() -> Result { + use super::server::{QuicConfig, QuicServer}; + let host: Ipv4Addr = "127.0.0.1".parse().unwrap(); // create a server config with self signed certificates let (_, server_config) = super::super::server::testing::self_signed_tls_certs_and_config(); diff --git a/iroh-relay/src/server.rs b/iroh-relay/src/server.rs index 3b4ce30fb5..3660760f4a 100644 --- a/iroh-relay/src/server.rs +++ b/iroh-relay/src/server.rs @@ -754,7 +754,7 @@ mod tests { use http::StatusCode; use iroh_base::{NodeId, RelayUrl, SecretKey}; use n0_future::{FutureExt, SinkExt, StreamExt}; - use n0_snafu::{Result, ResultExt}; + use n0_snafu::Result; use tracing::{info, instrument}; use tracing_test::traced_test; @@ -763,8 +763,12 @@ mod tests { NO_CONTENT_CHALLENGE_HEADER, NO_CONTENT_RESPONSE_HEADER, }; use crate::{ - client::{conn::ReceivedMessage, ClientBuilder, SendMessage}, + client::{ClientBuilder, ConnectError}, dns::DnsResolver, + protos::{ + handshake, + relay::{ClientToRelayMsg, RelayToClientMsg}, + }, }; async fn spawn_local_relay() -> std::result::Result { @@ -788,11 +792,14 @@ mod tests { client_b: &mut crate::client::Client, b_key: NodeId, msg: Bytes, - ) -> Result { + ) -> Result { // try resend 10 times for _ in 0..10 { client_a - .send(SendMessage::SendPacket(b_key, msg.clone())) + .send(ClientToRelayMsg::SendPacket { + dst_key: b_key, + packet: msg.clone(), + }) .await?; let Ok(res) = tokio::time::timeout(Duration::from_millis(500), client_b.next()).await else { @@ -905,34 +912,26 @@ mod tests { info!("sending a -> b"); // send message from a to b - let msg = Bytes::from("hello, b"); + let msg = Bytes::from_static(b"hello, b"); let res = try_send_recv(&mut client_a, &mut client_b, b_key, msg.clone()).await?; - let ReceivedMessage::ReceivedPacket { - remote_node_id, - data, - } = res - else { + let RelayToClientMsg::ReceivedPacket { src_key, content } = res else { panic!("client_b received unexpected message {res:?}"); }; - assert_eq!(a_key, remote_node_id); - assert_eq!(msg, data); + assert_eq!(a_key, src_key); + assert_eq!(msg, content); info!("sending b -> a"); // send message from b to a - let msg = Bytes::from("howdy, a"); + let msg = Bytes::from_static(b"howdy, a"); let res = try_send_recv(&mut client_b, &mut client_a, a_key, msg.clone()).await?; - let ReceivedMessage::ReceivedPacket { - remote_node_id, - data, - } = res - else { + let RelayToClientMsg::ReceivedPacket { src_key, content } = res else { panic!("client_a received unexpected message {res:?}"); }; - assert_eq!(b_key, remote_node_id); - assert_eq!(msg, data); + assert_eq!(b_key, src_key); + assert_eq!(msg, content); Ok(()) } @@ -975,23 +974,13 @@ mod tests { // set up client a let resolver = dns_resolver(); - let mut client_a = ClientBuilder::new(relay_url.clone(), a_secret_key, resolver) + let result = ClientBuilder::new(relay_url.clone(), a_secret_key, resolver) .connect() - .await?; + .await; - // the next message should be the rejection of the connection - tokio::time::timeout(Duration::from_millis(500), async move { - match client_a.next().await.unwrap().unwrap() { - ReceivedMessage::Health { problem } => { - assert_eq!(problem, Some("not authenticated".to_string())); - } - msg => { - panic!("other msg: {msg:?}"); - } - } - }) - .await - .context("timeout")?; + assert!( + matches!(result, Err(ConnectError::Handshake { source: handshake::Error::ServerDeniedAuth { reason, .. }, .. }) if reason == "not authorized") + ); // test that another client has access @@ -1014,16 +1003,12 @@ mod tests { .await?; // send message from b to c - let msg = Bytes::from("hello, c"); + let msg = Bytes::from_static(b"hello, c"); let res = try_send_recv(&mut client_b, &mut client_c, c_key, msg.clone()).await?; - if let ReceivedMessage::ReceivedPacket { - remote_node_id, - data, - } = res - { - assert_eq!(b_key, remote_node_id); - assert_eq!(msg, data); + if let RelayToClientMsg::ReceivedPacket { src_key, content } = res { + assert_eq!(b_key, src_key); + assert_eq!(msg, content); } else { panic!("client_c received unexpected message {res:?}"); } @@ -1055,10 +1040,13 @@ mod tests { // send messages from a to b, without b receiving anything. // we should still keep succeeding to send, even if the packet won't be forwarded // by the relay server because the server's send queue for b fills up. - let msg = Bytes::from("hello, b"); + let msg = Bytes::from_static(b"hello, b"); for _i in 0..1000 { client_a - .send(SendMessage::SendPacket(b_key, msg.clone())) + .send(ClientToRelayMsg::SendPacket { + dst_key: b_key, + packet: msg.clone(), + }) .await?; } Ok(()) diff --git a/iroh-relay/src/server/client.rs b/iroh-relay/src/server/client.rs index f661ec53fd..b2d480ac17 100644 --- a/iroh-relay/src/server/client.rs +++ b/iroh-relay/src/server/client.rs @@ -19,12 +19,12 @@ use tracing::{debug, trace, warn, Instrument}; use crate::{ protos::{ disco, - relay::{write_frame, Frame, SendError as SendRelayError, PING_INTERVAL}, + relay::{ClientToRelayMsg, RelayToClientMsg, PING_INTERVAL}, }, server::{ clients::Clients, metrics::Metrics, - streams::{RelayedStream, StreamError}, + streams::{RecvError as RelayRecvError, RelayedStream, SendError as RelaySendError}, }, PingTracker, }; @@ -109,7 +109,7 @@ impl Client { // start io loop let io_done = done.clone(); let handle = tokio::task::spawn(actor.run(io_done).instrument(tracing::info_span!( - "client connection actor", + "client-connection-actor", remote_node = %node_id.fmt_short(), connection_id = connection_id ))); @@ -168,7 +168,7 @@ impl Client { } } -/// Handle frame error +/// Error for [`Actor::handle_frame`] #[common_fields({ backtrace: Option, })] @@ -178,21 +178,26 @@ impl Client { pub enum HandleFrameError { #[snafu(transparent)] ForwardPacket { source: ForwardPacketError }, - #[snafu(transparent)] - Streams { source: StreamError }, #[snafu(display("Stream terminated"))] - StreamTerminated { - #[snafu(implicit)] - span_trace: n0_snafu::SpanTrace, - }, + StreamTerminated {}, #[snafu(transparent)] - Relay { source: SendRelayError }, - #[snafu(display("Server issue: {problem:?}"))] - Health { - problem: Bytes, - #[snafu(implicit)] - span_trace: n0_snafu::SpanTrace, - }, + Recv { source: RelayRecvError }, + #[snafu(transparent)] + Send { source: WriteFrameError }, +} + +/// Error for [`Actor::write_frame`] +#[common_fields({ + backtrace: Option, +})] +#[allow(missing_docs)] +#[derive(Debug, Snafu)] +#[non_exhaustive] +pub enum WriteFrameError { + #[snafu(transparent)] + Stream { source: RelaySendError }, + #[snafu(transparent)] + Timeout { source: tokio::time::error::Elapsed }, } /// Run error @@ -219,7 +224,7 @@ pub enum RunError { }, #[snafu(display("Failed to send disco packet"))] DiscoPacketSend { - source: SendRelayError, + source: WriteFrameError, #[snafu(implicit)] span_trace: n0_snafu::SpanTrace, }, @@ -230,7 +235,7 @@ pub enum RunError { }, #[snafu(display("Failed to send packet"))] PacketSend { - source: SendRelayError, + source: WriteFrameError, #[snafu(implicit)] span_trace: n0_snafu::SpanTrace, }, @@ -241,13 +246,13 @@ pub enum RunError { }, #[snafu(display("NodeGone write frame failed"))] NodeGoneWriteFrame { - source: SendRelayError, + source: WriteFrameError, #[snafu(implicit)] span_trace: n0_snafu::SpanTrace, }, #[snafu(display("Keep alive write frame failed"))] KeepAliveWriteFrame { - source: SendRelayError, + source: WriteFrameError, #[snafu(implicit)] span_trace: n0_snafu::SpanTrace, }, @@ -364,7 +369,7 @@ impl Actor { node_id = self.node_gone.recv() => { let node_id = node_id.ok_or(NodeGoneDropSnafu.build())?; trace!("node_id gone: {:?}", node_id); - self.write_frame(Frame::NodeGone { node_id }).await.context(NodeGoneWriteFrameSnafu)?; + self.write_frame(RelayToClientMsg::NodeGone(node_id)).await.context(NodeGoneWriteFrameSnafu)?; } _ = self.ping_tracker.timeout() => { trace!("pong timed out"); @@ -375,7 +380,7 @@ impl Actor { // new interval ping_interval.reset_after(next_interval()); let data = self.ping_tracker.new_ping(); - self.write_frame(Frame::Ping { data }).await.context(KeepAliveWriteFrameSnafu)?; + self.write_frame(RelayToClientMsg::Ping(data)).await.context(KeepAliveWriteFrameSnafu)?; } } @@ -390,26 +395,27 @@ impl Actor { /// Writes the given frame to the connection. /// /// Errors if the send does not happen within the `timeout` duration - async fn write_frame(&mut self, frame: Frame) -> Result<(), SendRelayError> { - write_frame(&mut self.stream, frame, Some(self.timeout)).await + async fn write_frame(&mut self, frame: RelayToClientMsg) -> Result<(), WriteFrameError> { + tokio::time::timeout(self.timeout, self.stream.send(frame)).await??; + Ok(()) } /// Writes contents to the client in a `RECV_PACKET` frame. /// /// Errors if the send does not happen within the `timeout` duration /// Does not flush. - async fn send_raw(&mut self, packet: Packet) -> Result<(), SendRelayError> { + async fn send_raw(&mut self, packet: Packet) -> Result<(), WriteFrameError> { let src_key = packet.src; let content = packet.data; if let Ok(len) = content.len().try_into() { self.metrics.bytes_sent.inc_by(len); } - self.write_frame(Frame::RecvPacket { src_key, content }) + self.write_frame(RelayToClientMsg::ReceivedPacket { src_key, content }) .await } - async fn send_packet(&mut self, packet: Packet) -> Result<(), SendRelayError> { + async fn send_packet(&mut self, packet: Packet) -> Result<(), WriteFrameError> { trace!("send packet"); match self.send_raw(packet).await { Ok(()) => { @@ -423,7 +429,7 @@ impl Actor { } } - async fn send_disco_packet(&mut self, packet: Packet) -> Result<(), SendRelayError> { + async fn send_disco_packet(&mut self, packet: Packet) -> Result<(), WriteFrameError> { trace!("send disco packet"); match self.send_raw(packet).await { Ok(()) => { @@ -440,7 +446,7 @@ impl Actor { /// Handles frame read results. async fn handle_frame( &mut self, - maybe_frame: Option>, + maybe_frame: Option>, ) -> Result<(), HandleFrameError> { trace!(?maybe_frame, "handle incoming frame"); let frame = match maybe_frame { @@ -449,7 +455,7 @@ impl Actor { }; match frame { - Frame::SendPacket { dst_key, packet } => { + ClientToRelayMsg::SendPacket { dst_key, packet } => { let packet_len = packet.len(); if let Err(err @ ForwardPacketError { .. }) = self.handle_frame_send_packet(dst_key, packet) @@ -458,19 +464,15 @@ impl Actor { } self.metrics.bytes_recv.inc_by(packet_len as u64); } - Frame::Ping { data } => { + ClientToRelayMsg::Ping(data) => { self.metrics.got_ping.inc(); // TODO: add rate limiter - self.write_frame(Frame::Pong { data }).await?; + self.write_frame(RelayToClientMsg::Pong(data)).await?; self.metrics.sent_pong.inc(); } - Frame::Pong { data } => { + ClientToRelayMsg::Pong(data) => { self.ping_tracker.pong_received(data); } - Frame::Health { problem } => return Err(HealthSnafu { problem }.build()), - _ => { - self.metrics.unknown_frames.inc(); - } } Ok(()) } @@ -553,14 +555,37 @@ impl ClientCounter { #[cfg(test)] mod tests { - use bytes::Bytes; use iroh_base::SecretKey; + use n0_future::Stream; use n0_snafu::{Result, ResultExt}; use tracing::info; use tracing_test::traced_test; use super::*; - use crate::protos::relay::{recv_frame, FrameType}; + use crate::{client::conn::Conn, protos::common::FrameType}; + + async fn recv_frame< + E: snafu::Error + Sync + Send + 'static, + S: Stream> + Unpin, + >( + frame_type: FrameType, + mut stream: S, + ) -> Result { + match stream.next().await { + Some(Ok(frame)) => { + if frame_type != frame.typ() { + snafu::whatever!( + "Unexpected frame, got {:?}, but expected {:?}", + frame.typ(), + frame_type + ); + } + Ok(frame) + } + Some(Err(err)) => Err(err).e(), + None => snafu::whatever!("Unexpected EOF, expected frame {frame_type:?}"), + } + } #[tokio::test] #[traced_test] @@ -571,8 +596,8 @@ mod tests { let node_id = SecretKey::generate(rand::thread_rng()).public(); let (io, io_rw) = tokio::io::duplex(1024); - let mut io_rw = RelayedStream::test_client(io_rw); - let stream = RelayedStream::test_server(io); + let mut io_rw = Conn::test(io_rw); + let stream = RelayedStream::test(io); let clients = Clients::default(); let metrics = Arc::new(Metrics::default()); @@ -605,10 +630,10 @@ mod tests { data: Bytes::from(&data[..]), }; send_queue_s.send(packet.clone()).await.context("send")?; - let frame = recv_frame(FrameType::RecvPacket, &mut io_rw).await?; + let frame = recv_frame(FrameType::RecvPacket, &mut io_rw).await.e()?; assert_eq!( frame, - Frame::RecvPacket { + RelayToClientMsg::ReceivedPacket { src_key: node_id, content: data.to_vec().into() } @@ -620,10 +645,10 @@ mod tests { .send(packet.clone()) .await .context("send")?; - let frame = recv_frame(FrameType::RecvPacket, &mut io_rw).await?; + let frame = recv_frame(FrameType::RecvPacket, &mut io_rw).await.e()?; assert_eq!( frame, - Frame::RecvPacket { + RelayToClientMsg::ReceivedPacket { src_key: node_id, content: data.to_vec().into() } @@ -632,20 +657,20 @@ mod tests { // send peer_gone println!("send peer gone"); peer_gone_s.send(node_id).await.context("send")?; - let frame = recv_frame(FrameType::PeerGone, &mut io_rw).await?; - assert_eq!(frame, Frame::NodeGone { node_id }); + let frame = recv_frame(FrameType::NodeGone, &mut io_rw).await.e()?; + assert_eq!(frame, RelayToClientMsg::NodeGone(node_id)); // Read tests println!("--read"); // send ping, expect pong let data = b"pingpong"; - write_frame(&mut io_rw, Frame::Ping { data: *data }, None).await?; + io_rw.send(ClientToRelayMsg::Ping(*data)).await?; // recv pong println!(" recv pong"); let frame = recv_frame(FrameType::Pong, &mut io_rw).await?; - assert_eq!(frame, Frame::Pong { data: *data }); + assert_eq!(frame, RelayToClientMsg::Pong(*data)); let target = SecretKey::generate(rand::thread_rng()).public(); @@ -653,7 +678,7 @@ mod tests { println!(" send packet"); let data = b"hello world!"; io_rw - .send(Frame::SendPacket { + .send(ClientToRelayMsg::SendPacket { dst_key: target, packet: Bytes::from_static(data), }) @@ -667,7 +692,7 @@ mod tests { disco_data.extend_from_slice(target.as_bytes()); disco_data.extend_from_slice(data); io_rw - .send(Frame::SendPacket { + .send(ClientToRelayMsg::SendPacket { dst_key: target, packet: disco_data.clone().into(), }) @@ -687,14 +712,14 @@ mod tests { // Build the rate limited stream. let (io_read, io_write) = tokio::io::duplex((LIMIT * MAX_FRAMES) as _); - let mut frame_writer = RelayedStream::test_client(io_write); + let mut frame_writer = Conn::test(io_write); // Rate limiter allowing LIMIT bytes/s - let mut stream = RelayedStream::test_server_limited(io_read, LIMIT / 10, LIMIT)?; + let mut stream = RelayedStream::test_limited(io_read, LIMIT / 10, LIMIT)?; // Prepare a frame to send, assert its size. - let data = Bytes::from_static(b"hello world!!1elf"); + let data = Bytes::from_static(b"hello world!1eins"); let target = SecretKey::generate(rand::thread_rng()).public(); - let frame = Frame::SendPacket { + let frame = ClientToRelayMsg::SendPacket { dst_key: target, packet: data.clone(), }; diff --git a/iroh-relay/src/server/clients.rs b/iroh-relay/src/server/clients.rs index f863d268f5..ab94ca8732 100644 --- a/iroh-relay/src/server/clients.rs +++ b/iroh-relay/src/server/clients.rs @@ -192,26 +192,50 @@ impl Clients { mod tests { use std::time::Duration; - use bytes::Bytes; use iroh_base::SecretKey; + use n0_future::{Stream, StreamExt}; use n0_snafu::{Result, ResultExt}; use super::*; use crate::{ - protos::relay::{recv_frame, Frame, FrameType}, + client::conn::Conn, + protos::{common::FrameType, relay::RelayToClientMsg}, server::streams::RelayedStream, }; - fn test_client_builder(key: NodeId) -> (Config, RelayedStream) { + async fn recv_frame< + E: snafu::Error + Sync + Send + 'static, + S: Stream> + Unpin, + >( + frame_type: FrameType, + mut stream: S, + ) -> Result { + match stream.next().await { + Some(Ok(frame)) => { + if frame_type != frame.typ() { + snafu::whatever!( + "Unexpected frame, got {:?}, but expected {:?}", + frame.typ(), + frame_type + ); + } + Ok(frame) + } + Some(Err(err)) => Err(err).e(), + None => snafu::whatever!("Unexpected EOF, expected frame {frame_type:?}"), + } + } + + fn test_client_builder(key: NodeId) -> (Config, Conn) { let (server, client) = tokio::io::duplex(1024); ( Config { node_id: key, - stream: RelayedStream::test_client(client), + stream: RelayedStream::test(server), write_timeout: Duration::from_secs(1), channel_capacity: 10, }, - RelayedStream::test_server(server), + Conn::test(client), ) } @@ -228,22 +252,22 @@ mod tests { // send packet let data = b"hello world!"; - clients.send_packet(a_key, Bytes::from(&data[..]), b_key, &metrics)?; + clients.send_packet(a_key, Bytes::from_static(&data[..]), b_key, &metrics)?; let frame = recv_frame(FrameType::RecvPacket, &mut a_rw).await?; assert_eq!( frame, - Frame::RecvPacket { + RelayToClientMsg::ReceivedPacket { src_key: b_key, content: data.to_vec().into(), } ); // send disco packet - clients.send_disco_packet(a_key, Bytes::from(&data[..]), b_key, &metrics)?; + clients.send_disco_packet(a_key, Bytes::from_static(&data[..]), b_key, &metrics)?; let frame = recv_frame(FrameType::RecvPacket, &mut a_rw).await?; assert_eq!( frame, - Frame::RecvPacket { + RelayToClientMsg::ReceivedPacket { src_key: b_key, content: data.to_vec().into(), } diff --git a/iroh-relay/src/server/http_server.rs b/iroh-relay/src/server/http_server.rs index 6a1f60dde3..5628990e7a 100644 --- a/iroh-relay/src/server/http_server.rs +++ b/iroh-relay/src/server/http_server.rs @@ -4,7 +4,10 @@ use std::{ use bytes::Bytes; use derive_more::Debug; -use http::{header::CONNECTION, response::Builder as ResponseBuilder}; +use http::{ + header::{CONNECTION, SEC_WEBSOCKET_KEY, SEC_WEBSOCKET_PROTOCOL, SEC_WEBSOCKET_VERSION}, + response::Builder as ResponseBuilder, +}; use hyper::{ body::Incoming, header::{HeaderValue, SEC_WEBSOCKET_ACCEPT, UPGRADE}, @@ -12,25 +15,25 @@ use hyper::{ upgrade::Upgraded, HeaderMap, Method, Request, Response, StatusCode, }; -use iroh_base::PublicKey; -use n0_future::{time::Elapsed, FutureExt, SinkExt}; +use n0_future::time::Elapsed; use nested_enum_utils::common_fields; -use snafu::{Backtrace, ResultExt, Snafu}; +use snafu::{Backtrace, OptionExt, ResultExt, Snafu}; use tokio::net::{TcpListener, TcpStream}; use tokio_rustls_acme::AcmeAcceptor; use tokio_util::{sync::CancellationToken, task::AbortOnDropHandle}; use tracing::{debug, debug_span, error, info, info_span, trace, warn, Instrument}; -use super::{ - clients::Clients, - streams::{InvalidBucketConfig, StreamError}, - AccessConfig, SpawnError, -}; +use super::{clients::Clients, streams::InvalidBucketConfig, AccessConfig, SpawnError}; use crate::{ defaults::{timeouts::SERVER_WRITE_TIMEOUT, DEFAULT_KEY_CACHE_CAPACITY}, - http::{RELAY_PATH, SUPPORTED_WEBSOCKET_VERSION, WEBSOCKET_UPGRADE_PROTOCOL}, - protos::relay::{ - recv_client_key, Frame, MAX_FRAME_SIZE, PER_CLIENT_SEND_QUEUE_DEPTH, PROTOCOL_VERSION, + http::{ + CLIENT_AUTH_HEADER, RELAY_PATH, RELAY_PROTOCOL_VERSION, SUPPORTED_WEBSOCKET_VERSION, + WEBSOCKET_UPGRADE_PROTOCOL, + }, + protos::{ + handshake, + relay::{MAX_FRAME_SIZE, PER_CLIENT_SEND_QUEUE_DEPTH}, + streams::WsBytesFramed, }, server::{ client::Config, @@ -65,11 +68,6 @@ fn derive_accept_key(client_key: &HeaderValue) -> String { data_encoding::BASE64.encode(&sha1.finalize()) } -/// Creates a new [`BytesBody`] with no content. -fn body_empty() -> BytesBody { - http_body_util::Full::new(hyper::body::Bytes::new()) -} - /// Creates a new [`BytesBody`] with given content. fn body_full(content: impl Into) -> BytesBody { http_body_util::Full::new(content.into()) @@ -161,7 +159,7 @@ pub(super) struct TlsConfig { #[non_exhaustive] pub enum ServeConnectionError { #[snafu(display("TLS[acme] handshake"))] - Handshake { + TlsHandshake { source: std::io::Error, #[snafu(implicit)] span_trace: n0_snafu::SpanTrace, @@ -212,28 +210,8 @@ pub enum ServeConnectionError { #[derive(Debug, Snafu)] #[non_exhaustive] pub enum AcceptError { - #[snafu(display("Unable to receive client information"))] - RecvClientKey { - #[allow(clippy::result_large_err)] - source: StreamError, - #[snafu(implicit)] - span_trace: n0_snafu::SpanTrace, - }, - #[snafu(display("Unexpected client version {version}, expected {expected_version}"))] - UnexpectedClientVersion { - version: usize, - expected_version: usize, - #[snafu(implicit)] - span_trace: n0_snafu::SpanTrace, - }, #[snafu(transparent)] - Io { source: std::io::Error }, - #[snafu(display("Client not authenticated: {key:?}"))] - ClientNotAuthenticated { - key: PublicKey, - #[snafu(implicit)] - span_trace: n0_snafu::SpanTrace, - }, + Handshake { source: handshake::Error }, #[snafu(display("rate limiting misconfigured"))] RateLimitingMisconfigured { source: InvalidBucketConfig }, } @@ -454,97 +432,133 @@ struct Inner { metrics: Arc, } +#[derive(Debug, Snafu)] +enum RelayUpgradeReqError { + #[snafu(display("missing header: {header}"))] + MissingHeader { header: http::HeaderName }, + #[snafu(display("invalid header value for {header}: {details}"))] + InvalidHeader { + header: http::HeaderName, + details: String, + }, + #[snafu(display( + "invalid header value for {SEC_WEBSOCKET_VERSION}: unsupported websocket version, only supporting {SUPPORTED_WEBSOCKET_VERSION}" + ))] + UnsupportedWebsocketVersion, + #[snafu(display( + "invalid header value for {SEC_WEBSOCKET_PROTOCOL}: unsupported relay version: we support {we_support} but you only provide {you_support}" + ))] + UnsupportedRelayVersion { + we_support: &'static str, + you_support: String, + }, +} + impl RelayService { + fn build_response(&self) -> http::response::Builder { + let mut res = Response::builder(); + for (key, value) in self.0.headers.iter() { + res = res.header(key, value); + } + res + } + /// Upgrades the HTTP connection to the relay protocol, runs relay client. - fn call_client_conn( + fn handle_relay_ws_upgrade( &self, mut req: Request, - ) -> Pin, hyper::Error>> + Send>> { - // TODO: soooo much cloning. See if there is an alternative - let this = self.clone(); - let mut builder = Response::builder(); - for (key, value) in self.0.headers.iter() { - builder = builder.header(key, value); + ) -> Result, RelayUpgradeReqError> { + fn expect_header( + req: &Request, + header: http::HeaderName, + ) -> Result<&HeaderValue, RelayUpgradeReqError> { + req.headers() + .get(&header) + .context(MissingHeaderSnafu { header }) } - async move { - { - // Send a 400 to any request that doesn't have an `Upgrade` header. - if req.headers().get(UPGRADE) - != Some(&HeaderValue::from_static(WEBSOCKET_UPGRADE_PROTOCOL)) - { - return Ok(builder - .status(StatusCode::BAD_REQUEST) - .body(body_empty()) - .expect("valid body")); - }; - - let Some(key) = req.headers().get("Sec-WebSocket-Key").cloned() else { - warn!("missing header Sec-WebSocket-Key for websocket relay protocol"); - return Ok(builder - .status(StatusCode::BAD_REQUEST) - .body(body_empty()) - .expect("valid body")); - }; - - let Some(version) = req.headers().get("Sec-WebSocket-Version").cloned() else { - warn!("missing header Sec-WebSocket-Version for websocket relay protocol"); - return Ok(builder - .status(StatusCode::BAD_REQUEST) - .body(body_empty()) - .expect("valid body")); - }; - - if version.as_bytes() != SUPPORTED_WEBSOCKET_VERSION.as_bytes() { - warn!("invalid header Sec-WebSocket-Version: {:?}", version); - return Ok(builder - .status(StatusCode::BAD_REQUEST) - // It's convention to send back the version(s) we *do* support - .header("Sec-WebSocket-Version", SUPPORTED_WEBSOCKET_VERSION) - .body(body_empty()) - .expect("valid body")); - } - - debug!("upgrading connection"); - - // Setup a future that will eventually receive the upgraded - // connection and talk a new protocol, and spawn the future - // into the runtime. - // - // Note: This can't possibly be fulfilled until the 101 response - // is returned below, so it's better to spawn this future instead - // waiting for it to complete to then return a response. - tokio::task::spawn( - async move { - match hyper::upgrade::on(&mut req).await { - Ok(upgraded) => { - if let Err(err) = this.0.relay_connection_handler(upgraded).await { - warn!("error accepting upgraded connection: {err:#}",); - } else { - debug!("upgraded connection completed"); - }; - } - Err(err) => warn!("upgrade error: {err:#}"), - } - } - .instrument(debug_span!("handler")), - ); - - // Now return a 101 Response saying we agree to the upgrade to the - // websocket upgrade protocol - builder = builder.status(StatusCode::SWITCHING_PROTOCOLS).header( - UPGRADE, - HeaderValue::from_static(WEBSOCKET_UPGRADE_PROTOCOL), - ); - - Ok(builder - .header(SEC_WEBSOCKET_ACCEPT, derive_accept_key(&key)) - .header(CONNECTION, "upgrade") - .body(body_full("switching to websocket protocol")) - .expect("valid body")) + let upgrade_header = expect_header(&req, UPGRADE)?; + snafu::ensure!( + upgrade_header == HeaderValue::from_static(WEBSOCKET_UPGRADE_PROTOCOL), + InvalidHeaderSnafu { + header: UPGRADE, + details: format!("value must be {WEBSOCKET_UPGRADE_PROTOCOL}"), } - } - .boxed() + ); + + let key = expect_header(&req, SEC_WEBSOCKET_KEY)?.clone(); + let version = expect_header(&req, SEC_WEBSOCKET_VERSION)?.clone(); + + snafu::ensure!( + version.as_bytes() == SUPPORTED_WEBSOCKET_VERSION.as_bytes(), + UnsupportedWebsocketVersionSnafu + ); + + let subprotocols = expect_header(&req, SEC_WEBSOCKET_PROTOCOL)? + .to_str() + .ok() + .context(InvalidHeaderSnafu { + header: SEC_WEBSOCKET_PROTOCOL, + details: "header value is not ascii".to_string(), + })?; + let supports_our_version = subprotocols + .split_whitespace() + .any(|p| p == RELAY_PROTOCOL_VERSION); + snafu::ensure!( + supports_our_version, + UnsupportedRelayVersionSnafu { + we_support: RELAY_PROTOCOL_VERSION, + you_support: subprotocols.to_string(), + } + ); + + let client_auth_header = req.headers().get(CLIENT_AUTH_HEADER).cloned(); + + // Setup a future that will eventually receive the upgraded + // connection and talk a new protocol, and spawn the future + // into the runtime. + // + // Note: This can't possibly be fulfilled until the 101 response + // is returned below, so it's better to spawn this future instead + // waiting for it to complete to then return a response. + tokio::task::spawn({ + let this = self.clone(); + async move { + match hyper::upgrade::on(&mut req).await { + Ok(upgraded) => { + if let Err(err) = this + .0 + .relay_connection_handler(upgraded, client_auth_header) + .await + { + warn!("error accepting upgraded connection: {err:#}",); + } else { + debug!("upgraded connection completed"); + }; + } + Err(err) => warn!("upgrade error: {err:#}"), + } + } + .instrument(debug_span!("handler")) + }); + + // Now return a 101 Response saying we agree to the upgrade to the + // websocket upgrade protocol + Ok(self + .build_response() + .status(StatusCode::SWITCHING_PROTOCOLS) + .header( + UPGRADE, + HeaderValue::from_static(WEBSOCKET_UPGRADE_PROTOCOL), + ) + .header(SEC_WEBSOCKET_ACCEPT, derive_accept_key(&key)) + .header( + SEC_WEBSOCKET_PROTOCOL, + HeaderValue::from_static(RELAY_PROTOCOL_VERSION), + ) + .header(CONNECTION, "upgrade") + .body(body_full("switching to websocket protocol")) + .expect("valid body")) } } @@ -559,8 +573,21 @@ impl Service> for RelayService { (req.method(), req.uri().path()), (&hyper::Method::GET, RELAY_PATH) ) { - let this = self.clone(); - return Box::pin(async move { this.call_client_conn(req).await.map_err(Into::into) }); + let res = match self.handle_relay_ws_upgrade(req) { + Ok(response) => Ok(response), + // It's convention to send back the version(s) we *do* support + Err(e @ RelayUpgradeReqError::UnsupportedWebsocketVersion) => self + .build_response() + .status(StatusCode::BAD_REQUEST) + .header(SEC_WEBSOCKET_VERSION, SUPPORTED_WEBSOCKET_VERSION) + .body(body_full(e.to_string())), + Err(e) => self + .build_response() + .status(StatusCode::BAD_REQUEST) + .body(body_full(e.to_string())), + } + .map_err(Into::into); + return Box::pin(async move { res }); } // Otherwise handle the relay connection as normal. @@ -606,6 +633,7 @@ impl Inner { async fn relay_connection_handler( &self, upgraded: Upgraded, + client_auth_header: Option, ) -> Result<(), ConnectionHandlerError> { debug!("relay_connection upgraded"); let (io, read_buf) = downcast_upgrade(upgraded)?; @@ -613,7 +641,7 @@ impl Inner { return Err(BufferNotEmptySnafu { buf: read_buf }.build()); } - self.accept(io).await?; + self.accept(io, client_auth_header).await?; Ok(()) } @@ -627,9 +655,11 @@ impl Inner { /// /// [`AsyncRead`]: tokio::io::AsyncRead /// [`AsyncWrite`]: tokio::io::AsyncWrite - async fn accept(&self, io: MaybeTlsStream) -> Result<(), AcceptError> { - use snafu::ResultExt; - + async fn accept( + &self, + io: MaybeTlsStream, + client_auth_header: Option, + ) -> Result<(), AcceptError> { trace!("accept: start"); let io = RateLimited::from_cfg(self.rate_limit, io, self.metrics.clone()) @@ -641,31 +671,23 @@ impl Inner { .limits(tokio_websockets::Limits::default().max_payload_len(Some(MAX_FRAME_SIZE))) // Serve will create a WebSocketStream on an already upgraded connection .serve(io); - let mut io = RelayedStream { - inner: websocket, + + let mut io = WsBytesFramed { io: websocket }; + + let authentication = + handshake::serverside(&mut io, client_auth_header, rand::rngs::OsRng).await?; + + trace!(?authentication.mechanism, "accept: verified authentication"); + + let is_authorized = self.access.is_allowed(authentication.client_key).await; + let client_key = authentication.authorize_if(is_authorized, &mut io).await?; + + trace!("accept: verified authorization"); + + let io = RelayedStream { + inner: io, key_cache: self.key_cache.clone(), }; - trace!("accept: recv client key"); - let (client_key, info) = recv_client_key(&mut io).await.context(RecvClientKeySnafu)?; - - trace!("accept: checking access: {:?}", self.access); - if !self.access.is_allowed(client_key).await { - io.send(Frame::Health { - problem: Bytes::from_static(b"not authenticated"), - }) - .await?; - io.flush().await?; - - return Err(ClientNotAuthenticatedSnafu { key: client_key }.build()); - } - - if info.version != PROTOCOL_VERSION { - return Err(UnexpectedClientVersionSnafu { - version: info.version, - expected_version: PROTOCOL_VERSION, - } - .build()); - } trace!("accept: build client conn"); let client_conn_builder = Config { @@ -780,7 +802,7 @@ impl RelayService { let tls_stream = start_handshake .into_stream(config) .await - .context(HandshakeSnafu)?; + .context(TlsHandshakeSnafu)?; self.serve_connection(MaybeTlsStream::Tls(tls_stream)) .await .context(HttpsSnafu)?; @@ -845,7 +867,6 @@ impl std::ops::DerefMut for Handlers { mod tests { use std::sync::Arc; - use bytes::Bytes; use iroh_base::{PublicKey, SecretKey}; use n0_future::{SinkExt, StreamExt}; use n0_snafu::{Result, ResultExt}; @@ -856,11 +877,9 @@ mod tests { use super::*; use crate::{ - client::{ - conn::{Conn, ReceivedMessage, SendMessage}, - Client, ClientBuilder, ConnectError, - }, + client::{conn::Conn, Client, ClientBuilder, ConnectError}, dns::DnsResolver, + protos::relay::{ClientToRelayMsg, RelayToClientMsg}, }; pub(crate) fn make_tls_config() -> TlsConfig { @@ -918,19 +937,22 @@ mod tests { info!("created client {b_key:?}"); info!("ping a"); - client_a.send(SendMessage::Ping([1u8; 8])).await?; + client_a.send(ClientToRelayMsg::Ping([1u8; 8])).await?; let pong = client_a.next().await.expect("eos")?; - assert!(matches!(pong, ReceivedMessage::Pong(_))); + assert!(matches!(pong, RelayToClientMsg::Pong { .. })); info!("ping b"); - client_b.send(SendMessage::Ping([2u8; 8])).await?; + client_b.send(ClientToRelayMsg::Ping([2u8; 8])).await?; let pong = client_b.next().await.expect("eos")?; - assert!(matches!(pong, ReceivedMessage::Pong(_))); + assert!(matches!(pong, RelayToClientMsg::Pong { .. })); info!("sending message from a to b"); let msg = Bytes::from_static(b"hi there, client b!"); client_a - .send(SendMessage::SendPacket(b_key, msg.clone())) + .send(ClientToRelayMsg::SendPacket { + dst_key: b_key, + packet: msg.clone(), + }) .await?; info!("waiting for message from a on b"); let (got_key, got_msg) = @@ -941,7 +963,10 @@ mod tests { info!("sending message from b to a"); let msg = Bytes::from_static(b"right back at ya, client b!"); client_b - .send(SendMessage::SendPacket(a_key, msg.clone())) + .send(ClientToRelayMsg::SendPacket { + dst_key: a_key, + packet: msg.clone(), + }) .await?; info!("waiting for message b on a"); let (got_key, got_msg) = @@ -970,7 +995,7 @@ mod tests { } fn process_msg( - msg: Option>, + msg: Option>, ) -> Option<(PublicKey, Bytes)> { match msg { Some(Err(e)) => { @@ -979,12 +1004,12 @@ mod tests { } Some(Ok(msg)) => { info!("got message on: {msg:?}"); - if let ReceivedMessage::ReceivedPacket { - remote_node_id: source, - data, + if let RelayToClientMsg::ReceivedPacket { + src_key: source, + content, } = msg { - Some((source, data)) + Some((source, content)) } else { None } @@ -1032,19 +1057,22 @@ mod tests { info!("created client {b_key:?}"); info!("ping a"); - client_a.send(SendMessage::Ping([1u8; 8])).await?; + client_a.send(ClientToRelayMsg::Ping([1u8; 8])).await?; let pong = client_a.next().await.expect("eos")?; - assert!(matches!(pong, ReceivedMessage::Pong(_))); + assert!(matches!(pong, RelayToClientMsg::Pong { .. })); info!("ping b"); - client_b.send(SendMessage::Ping([2u8; 8])).await?; + client_b.send(ClientToRelayMsg::Ping([2u8; 8])).await?; let pong = client_b.next().await.expect("eos")?; - assert!(matches!(pong, ReceivedMessage::Pong(_))); + assert!(matches!(pong, RelayToClientMsg::Pong { .. })); info!("sending message from a to b"); let msg = Bytes::from_static(b"hi there, client b!"); client_a - .send(SendMessage::SendPacket(b_key, msg.clone())) + .send(ClientToRelayMsg::SendPacket { + dst_key: b_key, + packet: msg.clone(), + }) .await?; info!("waiting for message from a on b"); let (got_key, got_msg) = @@ -1055,7 +1083,10 @@ mod tests { info!("sending message from b to a"); let msg = Bytes::from_static(b"right back at ya, client b!"); client_b - .send(SendMessage::SendPacket(a_key, msg.clone())) + .send(ClientToRelayMsg::SendPacket { + dst_key: a_key, + packet: msg.clone(), + }) .await?; info!("waiting for message b on a"); let (got_key, got_msg) = @@ -1098,7 +1129,7 @@ mod tests { let (client_a, rw_a) = tokio::io::duplex(10); let s = service.clone(); let handler_task = - tokio::spawn(async move { s.0.accept(MaybeTlsStream::Test(rw_a)).await }); + tokio::spawn(async move { s.0.accept(MaybeTlsStream::Test(rw_a), None).await }); let mut client_a = make_test_client(client_a, &key_a).await?; handler_task.await.context("join")??; @@ -1108,43 +1139,43 @@ mod tests { let (client_b, rw_b) = tokio::io::duplex(10); let s = service.clone(); let handler_task = - tokio::spawn(async move { s.0.accept(MaybeTlsStream::Test(rw_b)).await }); + tokio::spawn(async move { s.0.accept(MaybeTlsStream::Test(rw_b), None).await }); let mut client_b = make_test_client(client_b, &key_b).await?; handler_task.await.context("join")??; info!("Send message from A to B."); let msg = Bytes::from_static(b"hello client b!!"); client_a - .send(SendMessage::SendPacket(public_key_b, msg.clone())) + .send(ClientToRelayMsg::SendPacket { + dst_key: public_key_b, + packet: msg.clone(), + }) .await?; match client_b.next().await.unwrap()? { - ReceivedMessage::ReceivedPacket { - remote_node_id, - data, - } => { - assert_eq!(public_key_a, remote_node_id); - assert_eq!(&msg[..], data); + RelayToClientMsg::ReceivedPacket { src_key, content } => { + assert_eq!(public_key_a, src_key); + assert_eq!(msg, content); } msg => { - whatever!("expected ReceivedPacket msg, got {msg:?}"); + whatever!("expected ReceivedDatagrams msg, got {msg:?}"); } } info!("Send message from B to A."); let msg = Bytes::from_static(b"nice to meet you client a!!"); client_b - .send(SendMessage::SendPacket(public_key_a, msg.clone())) + .send(ClientToRelayMsg::SendPacket { + dst_key: public_key_a, + packet: msg.clone(), + }) .await?; match client_a.next().await.unwrap()? { - ReceivedMessage::ReceivedPacket { - remote_node_id, - data, - } => { - assert_eq!(public_key_b, remote_node_id); - assert_eq!(&msg[..], data); + RelayToClientMsg::ReceivedPacket { src_key, content } => { + assert_eq!(public_key_b, src_key); + assert_eq!(msg, content); } msg => { - whatever!("expected ReceivedPacket msg, got {msg:?}"); + whatever!("expected ReceivedDatagrams msg, got {msg:?}"); } } @@ -1154,10 +1185,10 @@ mod tests { info!("Fail to send message from A to B."); let res = client_a - .send(SendMessage::SendPacket( - public_key_b, - Bytes::from_static(b"try to send"), - )) + .send(ClientToRelayMsg::SendPacket { + dst_key: public_key_b, + packet: Bytes::from_static(b"try to send"), + }) .await; assert!(res.is_err()); assert!(client_b.next().await.is_none()); @@ -1182,7 +1213,7 @@ mod tests { let (client_a, rw_a) = tokio::io::duplex(10); let s = service.clone(); let handler_task = - tokio::spawn(async move { s.0.accept(MaybeTlsStream::Test(rw_a)).await }); + tokio::spawn(async move { s.0.accept(MaybeTlsStream::Test(rw_a), None).await }); let mut client_a = make_test_client(client_a, &key_a).await?; handler_task.await.context("join")??; @@ -1192,43 +1223,43 @@ mod tests { let (client_b, rw_b) = tokio::io::duplex(10); let s = service.clone(); let handler_task = - tokio::spawn(async move { s.0.accept(MaybeTlsStream::Test(rw_b)).await }); + tokio::spawn(async move { s.0.accept(MaybeTlsStream::Test(rw_b), None).await }); let mut client_b = make_test_client(client_b, &key_b).await?; handler_task.await.context("join")??; info!("Send message from A to B."); let msg = Bytes::from_static(b"hello client b!!"); client_a - .send(SendMessage::SendPacket(public_key_b, msg.clone())) + .send(ClientToRelayMsg::SendPacket { + dst_key: public_key_b, + packet: msg.clone(), + }) .await?; match client_b.next().await.expect("eos")? { - ReceivedMessage::ReceivedPacket { - remote_node_id, - data, - } => { - assert_eq!(public_key_a, remote_node_id); - assert_eq!(&msg[..], data); + RelayToClientMsg::ReceivedPacket { src_key, content } => { + assert_eq!(public_key_a, src_key); + assert_eq!(msg, content); } msg => { - whatever!("expected ReceivedPacket msg, got {msg:?}"); + whatever!("expected ReceivedDatagrams msg, got {msg:?}"); } } info!("Send message from B to A."); let msg = Bytes::from_static(b"nice to meet you client a!!"); client_b - .send(SendMessage::SendPacket(public_key_a, msg.clone())) + .send(ClientToRelayMsg::SendPacket { + dst_key: public_key_a, + packet: msg.clone(), + }) .await?; match client_a.next().await.expect("eos")? { - ReceivedMessage::ReceivedPacket { - remote_node_id, - data, - } => { - assert_eq!(public_key_b, remote_node_id); - assert_eq!(&msg[..], data); + RelayToClientMsg::ReceivedPacket { src_key, content } => { + assert_eq!(public_key_b, src_key); + assert_eq!(msg, content); } msg => { - whatever!("expected ReceivedPacket msg, got {msg:?}"); + whatever!("expected ReceivedDatagrams msg, got {msg:?}"); } } @@ -1236,7 +1267,7 @@ mod tests { let (new_client_b, new_rw_b) = tokio::io::duplex(10); let s = service.clone(); let handler_task = - tokio::spawn(async move { s.0.accept(MaybeTlsStream::Test(new_rw_b)).await }); + tokio::spawn(async move { s.0.accept(MaybeTlsStream::Test(new_rw_b), None).await }); let mut new_client_b = make_test_client(new_client_b, &key_b).await?; handler_task.await.context("join")??; @@ -1245,36 +1276,36 @@ mod tests { info!("Send message from A to B."); let msg = Bytes::from_static(b"are you still there, b?!"); client_a - .send(SendMessage::SendPacket(public_key_b, msg.clone())) + .send(ClientToRelayMsg::SendPacket { + dst_key: public_key_b, + packet: msg.clone(), + }) .await?; match new_client_b.next().await.expect("eos")? { - ReceivedMessage::ReceivedPacket { - remote_node_id, - data, - } => { - assert_eq!(public_key_a, remote_node_id); - assert_eq!(&msg[..], data); + RelayToClientMsg::ReceivedPacket { src_key, content } => { + assert_eq!(public_key_a, src_key); + assert_eq!(msg, content); } msg => { - whatever!("expected ReceivedPacket msg, got {msg:?}"); + whatever!("expected ReceivedDatagrams msg, got {msg:?}"); } } info!("Send message from B to A."); let msg = Bytes::from_static(b"just had a spot of trouble but I'm back now,a!!"); new_client_b - .send(SendMessage::SendPacket(public_key_a, msg.clone())) + .send(ClientToRelayMsg::SendPacket { + dst_key: public_key_a, + packet: msg.clone(), + }) .await?; match client_a.next().await.expect("eos")? { - ReceivedMessage::ReceivedPacket { - remote_node_id, - data, - } => { - assert_eq!(public_key_b, remote_node_id); - assert_eq!(&msg[..], data); + RelayToClientMsg::ReceivedPacket { src_key, content } => { + assert_eq!(public_key_b, src_key); + assert_eq!(msg, content); } msg => { - whatever!("expected ReceivedPacket msg, got {msg:?}"); + whatever!("expected ReceivedDatagrams msg, got {msg:?}"); } } @@ -1283,10 +1314,10 @@ mod tests { info!("Sending message from A to B fails"); let res = client_a - .send(SendMessage::SendPacket( - public_key_b, - Bytes::from_static(b"try to send"), - )) + .send(ClientToRelayMsg::SendPacket { + dst_key: public_key_b, + packet: Bytes::from_static(b"try to send"), + }) .await; assert!(res.is_err()); assert!(new_client_b.next().await.is_none()); diff --git a/iroh-relay/src/server/streams.rs b/iroh-relay/src/server/streams.rs index ee912bf69d..2d74939089 100644 --- a/iroh-relay/src/server/streams.rs +++ b/iroh-relay/src/server/streams.rs @@ -9,49 +9,44 @@ use std::{ use n0_future::{ready, time, FutureExt, Sink, Stream}; use snafu::{Backtrace, Snafu}; use tokio::io::{AsyncRead, AsyncWrite}; -use tokio_websockets::WebSocketStream; use tracing::instrument; use super::{ClientRateLimit, Metrics}; use crate::{ - protos::relay::{Frame, RecvError}, - KeyCache, + protos::{ + relay::{ClientToRelayMsg, Error as ProtoError, RelayToClientMsg}, + streams::{StreamError, WsBytesFramed}, + }, + ExportKeyingMaterial, KeyCache, MAX_PACKET_SIZE, }; -/// A Stream and Sink for [`Frame`]s connected to a single relay client. +/// The relay's connection to a client. /// -/// The stream receives message from the client while the sink sends them to the client. +/// This implements +/// - a [`Stream`] of [`ClientToRelayMsg`]s that are received from the client, +/// - a [`Sink`] of [`RelayToClientMsg`]s that can be sent to the client. #[derive(Debug)] pub(crate) struct RelayedStream { - pub(crate) inner: WebSocketStream>, + pub(crate) inner: WsBytesFramed>, pub(crate) key_cache: KeyCache, } #[cfg(test)] impl RelayedStream { - pub(crate) fn test_client(stream: tokio::io::DuplexStream) -> Self { + pub(crate) fn test(stream: tokio::io::DuplexStream) -> Self { let stream = MaybeTlsStream::Test(stream); let stream = RateLimited::unlimited(stream, Arc::new(Metrics::default())); Self { - inner: tokio_websockets::ClientBuilder::new() - .limits(Self::limits()) - .take_over(stream), + inner: WsBytesFramed { + io: tokio_websockets::ServerBuilder::new() + .limits(Self::limits()) + .serve(stream), + }, key_cache: KeyCache::test(), } } - pub(crate) fn test_server(stream: tokio::io::DuplexStream) -> Self { - let stream = MaybeTlsStream::Test(stream); - let stream = RateLimited::unlimited(stream, Arc::new(Metrics::default())); - Self { - inner: tokio_websockets::ServerBuilder::new() - .limits(Self::limits()) - .serve(stream), - key_cache: KeyCache::test(), - } - } - - pub(crate) fn test_server_limited( + pub(crate) fn test_limited( stream: tokio::io::DuplexStream, max_burst_bytes: u32, bytes_per_second: u32, @@ -64,9 +59,11 @@ impl RelayedStream { Arc::new(Metrics::default()), )?; Ok(Self { - inner: tokio_websockets::ServerBuilder::new() - .limits(Self::limits()) - .serve(stream), + inner: WsBytesFramed { + io: tokio_websockets::ServerBuilder::new() + .limits(Self::limits()) + .serve(stream), + }, key_cache: KeyCache::test(), }) } @@ -77,77 +74,67 @@ impl RelayedStream { } } -fn ws_to_io_err(e: tokio_websockets::Error) -> std::io::Error { - match e { - tokio_websockets::Error::Io(io_err) => io_err, - _ => std::io::Error::other(e.to_string()), - } +/// Relay send errors +#[derive(Debug, Snafu)] +#[non_exhaustive] +pub enum SendError { + #[snafu(transparent)] + StreamError { source: StreamError }, + #[snafu(display("Packet exceeds max packet size"))] + ExceedsMaxPacketSize { size: usize }, + #[snafu(display("Attempted to send empty packet"))] + EmptyPacket {}, } -impl Sink for RelayedStream { - type Error = std::io::Error; +impl Sink for RelayedStream { + type Error = SendError; fn poll_ready(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { - Pin::new(&mut self.inner) - .poll_ready(cx) - .map_err(ws_to_io_err) + Pin::new(&mut self.inner).poll_ready(cx).map_err(Into::into) } - fn start_send(mut self: Pin<&mut Self>, item: Frame) -> Result<(), Self::Error> { + fn start_send(mut self: Pin<&mut Self>, item: RelayToClientMsg) -> Result<(), Self::Error> { + if let RelayToClientMsg::ReceivedPacket { content, .. } = &item { + let size = content.len(); + snafu::ensure!(size <= MAX_PACKET_SIZE, ExceedsMaxPacketSizeSnafu { size }); + snafu::ensure!(size != 0, EmptyPacketSnafu); + } + Pin::new(&mut self.inner) - .start_send(tokio_websockets::Message::binary( - tokio_websockets::Payload::from(item.to_bytes().freeze()), - )) - .map_err(ws_to_io_err) + .start_send(item.to_bytes().freeze()) + .map_err(Into::into) } fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { - Pin::new(&mut self.inner) - .poll_flush(cx) - .map_err(ws_to_io_err) + Pin::new(&mut self.inner).poll_flush(cx).map_err(Into::into) } fn poll_close(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { - Pin::new(&mut self.inner) - .poll_close(cx) - .map_err(ws_to_io_err) + Pin::new(&mut self.inner).poll_close(cx).map_err(Into::into) } } -/// Relay stream errors +/// Relay receive errors #[derive(Debug, Snafu)] #[non_exhaustive] -pub enum StreamError { +pub enum RecvError { #[snafu(transparent)] - Proto { source: RecvError }, + Proto { source: ProtoError }, #[snafu(transparent)] - Ws { source: tokio_websockets::Error }, + StreamError { source: StreamError }, } impl Stream for RelayedStream { - type Item = Result; + type Item = Result; fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { - match Pin::new(&mut self.inner).poll_next(cx) { - Poll::Ready(Some(Ok(msg))) => { - if msg.is_close() { - // Indicate the stream is done when we receive a close message. - // Note: We don't have to poll the stream to completion for it to close gracefully. - return Poll::Ready(None); - } - if !msg.is_binary() { - tracing::warn!(?msg, "Got websocket message of unsupported type, skipping."); - return Poll::Pending; - } - Poll::Ready(Some( - Frame::from_bytes(msg.into_payload().into(), &self.key_cache) - .map_err(Into::into), - )) + Poll::Ready(match ready!(Pin::new(&mut self.inner).poll_next(cx)) { + Some(Ok(msg)) => { + Some(ClientToRelayMsg::from_bytes(msg, &self.key_cache).map_err(Into::into)) } - Poll::Ready(Some(Err(e))) => Poll::Ready(Some(Err(e.into()))), - Poll::Ready(None) => Poll::Ready(None), - Poll::Pending => Poll::Pending, - } + Some(Err(e)) => Some(Err(e.into())), + None => None, + }) } } @@ -166,6 +153,24 @@ pub enum MaybeTlsStream { Test(tokio::io::DuplexStream), } +impl ExportKeyingMaterial for MaybeTlsStream { + fn export_keying_material>( + &self, + output: T, + label: &[u8], + context: Option<&[u8]>, + ) -> Option { + let Self::Tls(ref tls) = self else { + return None; + }; + + tls.get_ref() + .1 + .export_keying_material(output, label, context) + .ok() + } +} + impl AsyncRead for MaybeTlsStream { fn poll_read( mut self: Pin<&mut Self>, @@ -231,6 +236,15 @@ impl AsyncWrite for MaybeTlsStream { MaybeTlsStream::Test(ref mut s) => Pin::new(s).poll_write_vectored(cx, bufs), } } + + fn is_write_vectored(&self) -> bool { + match self { + MaybeTlsStream::Plain(s) => s.is_write_vectored(), + MaybeTlsStream::Tls(s) => s.is_write_vectored(), + #[cfg(test)] + MaybeTlsStream::Test(s) => s.is_write_vectored(), + } + } } /// Rate limiter for reading from a [`RelayedStream`]. @@ -379,9 +393,7 @@ impl RateLimited { metrics, } } -} -impl RateLimited { /// Records metrics about being rate-limited. fn record_rate_limited(&mut self, bytes: usize) { // TODO: add a label for the frame type. @@ -393,6 +405,17 @@ impl RateLimited { } } +impl ExportKeyingMaterial for RateLimited { + fn export_keying_material>( + &self, + output: T, + label: &[u8], + context: Option<&[u8]>, + ) -> Option { + self.inner.export_keying_material(output, label, context) + } +} + impl AsyncRead for RateLimited { #[instrument(name = "rate_limited_poll_read", skip_all)] fn poll_read( diff --git a/iroh/src/defaults.rs b/iroh/src/defaults.rs index cb6327f9f4..6d3fa70d62 100644 --- a/iroh/src/defaults.rs +++ b/iroh/src/defaults.rs @@ -86,11 +86,9 @@ pub mod staging { use super::*; /// Hostname of the default NA relay. - // TODO(ramfox): for `0.91` release, make sure we have canary staging relays - pub const NA_RELAY_HOSTNAME: &str = "use1-1.relay.n0.iroh-canary.iroh.link."; + pub const NA_RELAY_HOSTNAME: &str = "staging-use1-1.relay.iroh.network."; /// Hostname of the default EU relay. - // TODO(ramfox): for `0.91` release, make sure we have canary staging relays - pub const EU_RELAY_HOSTNAME: &str = "euc1-1.relay.n0.iroh-canary.iroh.link."; + pub const EU_RELAY_HOSTNAME: &str = "staging-euw1-1.relay.iroh.network."; /// Get the default [`RelayMap`]. pub fn default_relay_map() -> RelayMap { diff --git a/iroh/src/magicsock/transports/relay.rs b/iroh/src/magicsock/transports/relay.rs index 9345bed6af..db5dea3437 100644 --- a/iroh/src/magicsock/transports/relay.rs +++ b/iroh/src/magicsock/transports/relay.rs @@ -337,43 +337,6 @@ mod tests { use super::*; use crate::defaults::staging; - #[test] - fn test_split_packets() { - fn mk_transmit(contents: &[u8], segment_size: Option) -> Transmit<'_> { - Transmit { - ecn: None, - contents, - segment_size, - } - } - fn mk_expected(parts: impl IntoIterator) -> RelayContents { - parts - .into_iter() - .map(|p| p.as_bytes().to_vec().into()) - .collect() - } - // no split - assert_eq!( - split_packets(&mk_transmit(b"hello", None)), - mk_expected(["hello"]) - ); - // split without rest - assert_eq!( - split_packets(&mk_transmit(b"helloworld", Some(5))), - mk_expected(["hello", "world"]) - ); - // split with rest and second transmit - assert_eq!( - split_packets(&mk_transmit(b"hello world", Some(5))), - mk_expected(["hello", " worl", "d"]) // spellchecker:disable-line - ); - // split that results in 1 packet - assert_eq!( - split_packets(&mk_transmit(b"hello world", Some(1000))), - mk_expected(["hello world"]) - ); - } - #[tokio::test(flavor = "multi_thread")] async fn test_relay_datagram_queue() { let capacity = 16; diff --git a/iroh/src/magicsock/transports/relay/actor.rs b/iroh/src/magicsock/transports/relay/actor.rs index 7eb4514ef7..dbfaa75ad9 100644 --- a/iroh/src/magicsock/transports/relay/actor.rs +++ b/iroh/src/magicsock/transports/relay/actor.rs @@ -42,7 +42,8 @@ use bytes::{Bytes, BytesMut}; use iroh_base::{NodeId, PublicKey, RelayUrl, SecretKey}; use iroh_relay::{ self as relay, - client::{Client, ConnectError, ReceivedMessage, RecvError, SendError, SendMessage}, + client::{Client, ConnectError, RecvError, SendError}, + protos::relay::{ClientToRelayMsg, RelayToClientMsg}, PingTracker, MAX_PACKET_SIZE, }; use n0_future::{ @@ -550,7 +551,7 @@ impl ActiveRelayActor { let res = loop { if let Some(data) = state.pong_pending.take() { - let fut = client_sink.send(SendMessage::Pong(data)); + let fut = client_sink.send(ClientToRelayMsg::Pong(data)); self.run_sending(fut, &mut state, &mut client_stream) .await?; } @@ -577,7 +578,7 @@ impl ActiveRelayActor { } _ = ping_interval.tick() => { let data = state.ping_tracker.new_ping(); - let fut = client_sink.send(SendMessage::Ping(data)); + let fut = client_sink.send(ClientToRelayMsg::Ping(data)); self.run_sending(fut, &mut state, &mut client_stream).await?; } msg = self.inbox.recv() => { @@ -593,7 +594,7 @@ impl ActiveRelayActor { match client_stream.local_addr() { Some(addr) if local_ips.contains(&addr.ip()) => { let data = state.ping_tracker.new_ping(); - let fut = client_sink.send(SendMessage::Ping(data)); + let fut = client_sink.send(ClientToRelayMsg::Ping(data)); self.run_sending(fut, &mut state, &mut client_stream).await?; } Some(_) => break Err(LocalIpInvalidSnafu.build()), @@ -609,7 +610,7 @@ impl ActiveRelayActor { ActiveRelayMessage::PingServer(sender) => { let data = rand::random(); state.test_pong = Some((data, sender)); - let fut = client_sink.send(SendMessage::Ping(data)); + let fut = client_sink.send(ClientToRelayMsg::Ping(data)); self.run_sending(fut, &mut state, &mut client_stream).await?; } } @@ -637,11 +638,11 @@ impl ActiveRelayActor { datagrams.datagrams.clone(), ) .map(|p| { - Ok(SendMessage::SendPacket(p.node_id, p.payload)) + Ok(ClientToRelayMsg::SendPacket { dst_key: p.node_id, packet: p.payload }) }) }); let mut packet_stream = n0_future::stream::iter(packet_iter).inspect(|m| { - if let Ok(SendMessage::SendPacket(_node_id, payload)) = m { + if let Ok(ClientToRelayMsg::SendPacket { dst_key: _node_id, packet: payload }) = m { metrics.send_relay.inc_by(payload.len() as _); } }); @@ -677,13 +678,13 @@ impl ActiveRelayActor { res.map_err(|err| state.map_err(err)) } - fn handle_relay_msg(&mut self, msg: ReceivedMessage, state: &mut ConnectedRelayState) { + fn handle_relay_msg(&mut self, msg: RelayToClientMsg, state: &mut ConnectedRelayState) { match msg { - ReceivedMessage::ReceivedPacket { - remote_node_id, - data, + RelayToClientMsg::ReceivedPacket { + src_key: remote_node_id, + content, } => { - trace!(len = %data.len(), "received msg"); + trace!(len = %content.len(), "received msg"); // If this is a new sender, register a route for this peer. if state .last_packet_src @@ -695,7 +696,7 @@ impl ActiveRelayActor { state.last_packet_src = Some(remote_node_id); state.nodes_present.insert(remote_node_id); } - for datagram in PacketSplitIter::new(self.url.clone(), remote_node_id, data) { + for datagram in PacketSplitIter::new(self.url.clone(), remote_node_id, content) { let Ok(datagram) = datagram else { warn!("Invalid packet split"); break; @@ -705,11 +706,11 @@ impl ActiveRelayActor { } } } - ReceivedMessage::NodeGone(node_id) => { + RelayToClientMsg::NodeGone(node_id) => { state.nodes_present.remove(&node_id); } - ReceivedMessage::Ping(data) => state.pong_pending = Some(data), - ReceivedMessage::Pong(data) => { + RelayToClientMsg::Ping(data) => state.pong_pending = Some(data), + RelayToClientMsg::Pong(data) => { #[cfg(test)] { if let Some((expected_data, sender)) = state.test_pong.take() { @@ -723,11 +724,10 @@ impl ActiveRelayActor { state.ping_tracker.pong_received(data); state.established = true; } - ReceivedMessage::Health { problem } => { - let problem = problem.as_deref().unwrap_or("unknown"); + RelayToClientMsg::Health { problem } => { warn!("Relay server reports problem: {problem}"); } - ReceivedMessage::KeepAlive | ReceivedMessage::ServerRestarting { .. } => { + RelayToClientMsg::Restarting { .. } => { trace!("Ignoring {msg:?}") } } @@ -1311,7 +1311,7 @@ where } } -/// Splits a single [`ReceivedMessage::ReceivedPacket`] frame into datagrams. +/// Splits a single [`RelayToClientMsg::ReceivedPacket`] frame into datagrams. /// /// This splits packets joined by [`PacketizeIter`] back into individual datagrams. See /// that struct for more details. @@ -1361,7 +1361,6 @@ impl Iterator for PacketSplitIter { } } } - #[cfg(test)] mod tests { use std::{ @@ -1516,7 +1515,6 @@ mod tests { tx: &mpsc::Sender, rx: &mut mpsc::Receiver, ) -> Result<()> { - assert!(item.datagrams.len() == 1); tokio::time::timeout(Duration::from_secs(10), async move { loop { let res = tokio::time::timeout(UNDELIVERABLE_DATAGRAM_TIMEOUT, async { diff --git a/iroh/tests/integration.rs b/iroh/tests/integration.rs index e181bdf374..e48909603a 100644 --- a/iroh/tests/integration.rs +++ b/iroh/tests/integration.rs @@ -11,7 +11,7 @@ //! we won't hit these with only this integration test. use iroh::{ discovery::{pkarr::PkarrResolver, Discovery}, - Endpoint, + Endpoint, RelayMode, }; use n0_future::{ task, @@ -37,8 +37,13 @@ async fn simple_node_id_based_connection_transfer() -> Result { std::panic::set_hook(Box::new(console_error_panic_hook::hook)); setup_logging(); - let client = Endpoint::builder().discovery_n0().bind().await?; + let client = Endpoint::builder() + .relay_mode(RelayMode::Staging) + .discovery_n0() + .bind() + .await?; let server = Endpoint::builder() + .relay_mode(RelayMode::Staging) .discovery_n0() .alpns(vec![ECHO_ALPN.to_vec()]) .bind() @@ -119,7 +124,10 @@ async fn simple_node_id_based_connection_transfer() -> Result { #[cfg(wasm_browser)] fn setup_logging() { + use std::str::FromStr; + tracing_subscriber::fmt() + .with_env_filter(tracing_subscriber::EnvFilter::from_str("trace").expect("hardcoded")) .with_max_level(tracing::level_filters::LevelFilter::DEBUG) .with_writer( // To avoide trace events in the browser from showing their JS backtrace @@ -134,5 +142,7 @@ fn setup_logging() { #[cfg(not(wasm_browser))] fn setup_logging() { - tracing_subscriber::fmt().init(); + tracing_subscriber::fmt() + .with_env_filter(tracing_subscriber::EnvFilter::from_default_env()) + .init(); }