diff --git a/pr/3384/docs/iroh_relay/protos/relay/index.html b/pr/3384/docs/iroh_relay/protos/relay/index.html index 96ee5b91f3..a0f04598ff 100644 --- a/pr/3384/docs/iroh_relay/protos/relay/index.html +++ b/pr/3384/docs/iroh_relay/protos/relay/index.html @@ -1,4 +1,4 @@ -iroh_relay::protos::relay - Rust

Module relay

Source
Expand description

This module implements the relaying protocol used by the server and client.

+iroh_relay::protos::relay - Rust

Module relay

Source
Expand description

This module implements the relaying protocol used by the server and client.

Protocol flow:

Login:

    diff --git a/pr/3384/docs/src/iroh_relay/client/tls.rs.html b/pr/3384/docs/src/iroh_relay/client/tls.rs.html index bbcd933ca4..d76fdfccfa 100644 --- a/pr/3384/docs/src/iroh_relay/client/tls.rs.html +++ b/pr/3384/docs/src/iroh_relay/client/tls.rs.html @@ -13,267 +13,268 @@ 13use n0_future::{task, time}; 14use rustls::client::Resumption; 15use snafu::{OptionExt, ResultExt}; -16 -17use super::{ -18 streams::{MaybeTlsStream, ProxyStream}, -19 *, -20}; -21use crate::defaults::timeouts::*; -22 -23#[derive(Debug, Clone)] -24pub struct MaybeTlsStreamBuilder { -25 url: Url, -26 dns_resolver: DnsResolver, -27 proxy_url: Option<Url>, -28 prefer_ipv6: bool, -29 #[cfg(any(test, feature = "test-utils"))] -30 insecure_skip_cert_verify: bool, -31} -32 -33impl MaybeTlsStreamBuilder { -34 pub fn new(url: Url, dns_resolver: DnsResolver) -> Self { -35 Self { -36 url, -37 dns_resolver, -38 proxy_url: None, -39 prefer_ipv6: false, -40 #[cfg(any(test, feature = "test-utils"))] -41 insecure_skip_cert_verify: false, -42 } -43 } -44 -45 pub fn proxy_url(mut self, proxy_url: Option<Url>) -> Self { -46 self.proxy_url = proxy_url; -47 self -48 } -49 -50 pub fn prefer_ipv6(mut self, prefer: bool) -> Self { -51 self.prefer_ipv6 = prefer; -52 self -53 } -54 -55 #[cfg(any(test, feature = "test-utils"))] -56 pub fn insecure_skip_cert_verify(mut self, skip: bool) -> Self { -57 self.insecure_skip_cert_verify = skip; -58 self -59 } -60 -61 pub async fn connect(self) -> Result<MaybeTlsStream<ProxyStream>, ConnectError> { -62 let roots = rustls::RootCertStore { -63 roots: webpki_roots::TLS_SERVER_ROOTS.to_vec(), -64 }; -65 let mut config = rustls::client::ClientConfig::builder_with_provider(Arc::new( -66 rustls::crypto::ring::default_provider(), -67 )) -68 .with_safe_default_protocol_versions() -69 .expect("protocols supported by ring") -70 .with_root_certificates(roots) -71 .with_no_client_auth(); -72 #[cfg(any(test, feature = "test-utils"))] -73 if self.insecure_skip_cert_verify { -74 warn!("Insecure config: SSL certificates from relay servers not verified"); -75 config -76 .dangerous() -77 .set_certificate_verifier(Arc::new(NoCertVerifier)); -78 } -79 config.resumption = Resumption::default(); -80 let tls_connector: tokio_rustls::TlsConnector = Arc::new(config).into(); -81 -82 let tcp_stream = self.dial_url(&tls_connector).await?; -83 -84 let local_addr = tcp_stream -85 .local_addr() -86 .map_err(|_| NoLocalAddrSnafu.build())?; -87 -88 debug!(server_addr = ?tcp_stream.peer_addr(), %local_addr, "TCP stream connected"); -89 -90 if self.use_tls() { -91 debug!("Starting TLS handshake"); -92 let hostname = self -93 .tls_servername() -94 .ok_or_else(|| InvalidTlsServernameSnafu.build())?; -95 -96 let hostname = hostname.to_owned(); -97 let tls_stream = tls_connector -98 .connect(hostname, tcp_stream) -99 .await -100 .context(TlsSnafu)?; -101 debug!("tls_connector connect success"); -102 Ok(MaybeTlsStream::Tls(tls_stream)) -103 } else { -104 debug!("Starting handshake"); -105 Ok(MaybeTlsStream::Raw(tcp_stream)) -106 } -107 } -108 -109 fn use_tls(&self) -> bool { -110 // only disable tls if we are explicitly dialing a http url -111 #[allow(clippy::match_like_matches_macro)] -112 match self.url.scheme() { -113 "http" => false, -114 "ws" => false, -115 _ => true, -116 } -117 } -118 -119 fn tls_servername(&self) -> Option<rustls::pki_types::ServerName<'_>> { -120 let host_str = self.url.host_str()?; -121 let servername = rustls::pki_types::ServerName::try_from(host_str).ok()?; -122 Some(servername) -123 } -124 -125 async fn dial_url( -126 &self, -127 tls_connector: &tokio_rustls::TlsConnector, -128 ) -> Result<ProxyStream, DialError> { -129 if let Some(ref proxy) = self.proxy_url { -130 let stream = self.dial_url_proxy(proxy.clone(), tls_connector).await?; -131 Ok(ProxyStream::Proxied(stream)) -132 } else { -133 let stream = self.dial_url_direct().await?; -134 Ok(ProxyStream::Raw(stream)) -135 } -136 } -137 -138 async fn dial_url_direct(&self) -> Result<tokio::net::TcpStream, DialError> { -139 use tokio::net::TcpStream; -140 debug!(%self.url, "dial url"); -141 let dst_ip = self -142 .dns_resolver -143 .resolve_host(&self.url, self.prefer_ipv6, DNS_TIMEOUT) -144 .await?; -145 -146 let port = url_port(&self.url).context(InvalidTargetPortSnafu)?; -147 let addr = SocketAddr::new(dst_ip, port); -148 -149 debug!("connecting to {}", addr); -150 let tcp_stream = time::timeout( -151 DIAL_NODE_TIMEOUT, -152 async move { TcpStream::connect(addr).await }, -153 ) -154 .await??; -155 -156 tcp_stream.set_nodelay(true)?; -157 -158 Ok(tcp_stream) -159 } -160 -161 async fn dial_url_proxy( -162 &self, -163 proxy_url: Url, -164 tls_connector: &tokio_rustls::TlsConnector, -165 ) -> Result<util::Chain<std::io::Cursor<Bytes>, MaybeTlsStream<tokio::net::TcpStream>>, DialError> -166 { -167 use hyper_util::rt::TokioIo; -168 use tokio::net::TcpStream; -169 debug!(%self.url, %proxy_url, "dial url via proxy"); -170 -171 // Resolve proxy DNS -172 let proxy_ip = self -173 .dns_resolver -174 .resolve_host(&proxy_url, self.prefer_ipv6, DNS_TIMEOUT) -175 .await?; -176 -177 let proxy_port = url_port(&proxy_url).context(ProxyInvalidTargetPortSnafu)?; -178 let proxy_addr = SocketAddr::new(proxy_ip, proxy_port); -179 -180 debug!(%proxy_addr, "connecting to proxy"); -181 -182 let tcp_stream = time::timeout(DIAL_NODE_TIMEOUT, async move { -183 TcpStream::connect(proxy_addr).await -184 }) -185 .await??; -186 -187 tcp_stream.set_nodelay(true)?; -188 -189 // Setup TLS if necessary -190 let io = if proxy_url.scheme() == "http" { -191 MaybeTlsStream::Raw(tcp_stream) -192 } else { -193 let hostname = proxy_url.host_str().context(ProxyInvalidUrlSnafu { -194 proxy_url: proxy_url.clone(), -195 })?; -196 let hostname = -197 rustls::pki_types::ServerName::try_from(hostname.to_string()).map_err(|_| { -198 ProxyInvalidTlsServernameSnafu { -199 proxy_hostname: hostname.to_string(), -200 } -201 .build() -202 })?; -203 let tls_stream = tls_connector.connect(hostname, tcp_stream).await?; -204 MaybeTlsStream::Tls(tls_stream) -205 }; -206 let io = TokioIo::new(io); -207 -208 let target_host = self.url.host_str().context(InvalidUrlSnafu { -209 url: self.url.clone(), -210 })?; -211 -212 let port = url_port(&self.url).context(InvalidTargetPortSnafu)?; -213 -214 // Establish Proxy Tunnel -215 let mut req_builder = Request::builder() -216 .uri(format!("{target_host}:{port}")) -217 .method("CONNECT") -218 .header("Host", target_host) -219 .header("Proxy-Connection", "Keep-Alive"); -220 if !proxy_url.username().is_empty() { -221 // Passthrough authorization -222 // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Proxy-Authorization -223 debug!( -224 "setting proxy-authorization: username={}", -225 proxy_url.username() -226 ); -227 let to_encode = format!( -228 "{}:{}", -229 proxy_url.username(), -230 proxy_url.password().unwrap_or_default() -231 ); -232 let encoded = BASE64URL.encode(to_encode.as_bytes()); -233 req_builder = req_builder.header("Proxy-Authorization", format!("Basic {encoded}")); -234 } -235 let req = req_builder -236 .body(Empty::<Bytes>::new()) -237 .expect("fixed config"); -238 -239 debug!("Sending proxy request: {:?}", req); -240 -241 let (mut sender, conn) = hyper::client::conn::http1::handshake(io) -242 .await -243 .context(ProxyConnectSnafu)?; -244 task::spawn(async move { -245 if let Err(err) = conn.with_upgrades().await { -246 tracing::error!("Proxy connection failed: {:?}", err); -247 } -248 }); -249 -250 let res = sender.send_request(req).await.context(ProxyConnectSnafu)?; -251 if !res.status().is_success() { -252 return Err(ProxyConnectInvalidStatusSnafu { -253 status: res.status(), -254 } -255 .build()); -256 } -257 -258 let upgraded = hyper::upgrade::on(res).await.context(ProxyConnectSnafu)?; -259 let Parts { io, read_buf, .. } = upgraded -260 .downcast::<TokioIo<MaybeTlsStream<tokio::net::TcpStream>>>() -261 .expect("only this upgrade used"); -262 -263 let res = util::chain(std::io::Cursor::new(read_buf), io.into_inner()); -264 -265 Ok(res) -266 } -267} -268 -269fn url_port(url: &Url) -> Option<u16> { -270 if let Some(port) = url.port() { -271 return Some(port); -272 } -273 -274 match url.scheme() { -275 "http" | "ws" => Some(80), -276 "https" | "wss" => Some(443), -277 _ => None, -278 } -279}
\ No newline at end of file +16use tracing::error; +17 +18use super::{ +19 streams::{MaybeTlsStream, ProxyStream}, +20 *, +21}; +22use crate::defaults::timeouts::*; +23 +24#[derive(Debug, Clone)] +25pub struct MaybeTlsStreamBuilder { +26 url: Url, +27 dns_resolver: DnsResolver, +28 proxy_url: Option<Url>, +29 prefer_ipv6: bool, +30 #[cfg(any(test, feature = "test-utils"))] +31 insecure_skip_cert_verify: bool, +32} +33 +34impl MaybeTlsStreamBuilder { +35 pub fn new(url: Url, dns_resolver: DnsResolver) -> Self { +36 Self { +37 url, +38 dns_resolver, +39 proxy_url: None, +40 prefer_ipv6: false, +41 #[cfg(any(test, feature = "test-utils"))] +42 insecure_skip_cert_verify: false, +43 } +44 } +45 +46 pub fn proxy_url(mut self, proxy_url: Option<Url>) -> Self { +47 self.proxy_url = proxy_url; +48 self +49 } +50 +51 pub fn prefer_ipv6(mut self, prefer: bool) -> Self { +52 self.prefer_ipv6 = prefer; +53 self +54 } +55 +56 #[cfg(any(test, feature = "test-utils"))] +57 pub fn insecure_skip_cert_verify(mut self, skip: bool) -> Self { +58 self.insecure_skip_cert_verify = skip; +59 self +60 } +61 +62 pub async fn connect(self) -> Result<MaybeTlsStream<ProxyStream>, ConnectError> { +63 let roots = rustls::RootCertStore { +64 roots: webpki_roots::TLS_SERVER_ROOTS.to_vec(), +65 }; +66 let mut config = rustls::client::ClientConfig::builder_with_provider(Arc::new( +67 rustls::crypto::ring::default_provider(), +68 )) +69 .with_safe_default_protocol_versions() +70 .expect("protocols supported by ring") +71 .with_root_certificates(roots) +72 .with_no_client_auth(); +73 #[cfg(any(test, feature = "test-utils"))] +74 if self.insecure_skip_cert_verify { +75 warn!("Insecure config: SSL certificates from relay servers not verified"); +76 config +77 .dangerous() +78 .set_certificate_verifier(Arc::new(NoCertVerifier)); +79 } +80 config.resumption = Resumption::default(); +81 let tls_connector: tokio_rustls::TlsConnector = Arc::new(config).into(); +82 +83 let tcp_stream = self.dial_url(&tls_connector).await?; +84 +85 let local_addr = tcp_stream +86 .local_addr() +87 .map_err(|_| NoLocalAddrSnafu.build())?; +88 +89 debug!(server_addr = ?tcp_stream.peer_addr(), %local_addr, "TCP stream connected"); +90 +91 if self.use_tls() { +92 debug!("Starting TLS handshake"); +93 let hostname = self +94 .tls_servername() +95 .ok_or_else(|| InvalidTlsServernameSnafu.build())?; +96 +97 let hostname = hostname.to_owned(); +98 let tls_stream = tls_connector +99 .connect(hostname, tcp_stream) +100 .await +101 .context(TlsSnafu)?; +102 debug!("tls_connector connect success"); +103 Ok(MaybeTlsStream::Tls(tls_stream)) +104 } else { +105 debug!("Starting handshake"); +106 Ok(MaybeTlsStream::Raw(tcp_stream)) +107 } +108 } +109 +110 fn use_tls(&self) -> bool { +111 // only disable tls if we are explicitly dialing a http url +112 #[allow(clippy::match_like_matches_macro)] +113 match self.url.scheme() { +114 "http" => false, +115 "ws" => false, +116 _ => true, +117 } +118 } +119 +120 fn tls_servername(&self) -> Option<rustls::pki_types::ServerName<'_>> { +121 let host_str = self.url.host_str()?; +122 let servername = rustls::pki_types::ServerName::try_from(host_str).ok()?; +123 Some(servername) +124 } +125 +126 async fn dial_url( +127 &self, +128 tls_connector: &tokio_rustls::TlsConnector, +129 ) -> Result<ProxyStream, DialError> { +130 if let Some(ref proxy) = self.proxy_url { +131 let stream = self.dial_url_proxy(proxy.clone(), tls_connector).await?; +132 Ok(ProxyStream::Proxied(stream)) +133 } else { +134 let stream = self.dial_url_direct().await?; +135 Ok(ProxyStream::Raw(stream)) +136 } +137 } +138 +139 async fn dial_url_direct(&self) -> Result<tokio::net::TcpStream, DialError> { +140 use tokio::net::TcpStream; +141 debug!(%self.url, "dial url"); +142 let dst_ip = self +143 .dns_resolver +144 .resolve_host(&self.url, self.prefer_ipv6, DNS_TIMEOUT) +145 .await?; +146 +147 let port = url_port(&self.url).context(InvalidTargetPortSnafu)?; +148 let addr = SocketAddr::new(dst_ip, port); +149 +150 debug!("connecting to {}", addr); +151 let tcp_stream = time::timeout( +152 DIAL_NODE_TIMEOUT, +153 async move { TcpStream::connect(addr).await }, +154 ) +155 .await??; +156 +157 tcp_stream.set_nodelay(true)?; +158 +159 Ok(tcp_stream) +160 } +161 +162 async fn dial_url_proxy( +163 &self, +164 proxy_url: Url, +165 tls_connector: &tokio_rustls::TlsConnector, +166 ) -> Result<util::Chain<std::io::Cursor<Bytes>, MaybeTlsStream<tokio::net::TcpStream>>, DialError> +167 { +168 use hyper_util::rt::TokioIo; +169 use tokio::net::TcpStream; +170 debug!(%self.url, %proxy_url, "dial url via proxy"); +171 +172 // Resolve proxy DNS +173 let proxy_ip = self +174 .dns_resolver +175 .resolve_host(&proxy_url, self.prefer_ipv6, DNS_TIMEOUT) +176 .await?; +177 +178 let proxy_port = url_port(&proxy_url).context(ProxyInvalidTargetPortSnafu)?; +179 let proxy_addr = SocketAddr::new(proxy_ip, proxy_port); +180 +181 debug!(%proxy_addr, "connecting to proxy"); +182 +183 let tcp_stream = time::timeout(DIAL_NODE_TIMEOUT, async move { +184 TcpStream::connect(proxy_addr).await +185 }) +186 .await??; +187 +188 tcp_stream.set_nodelay(true)?; +189 +190 // Setup TLS if necessary +191 let io = if proxy_url.scheme() == "http" { +192 MaybeTlsStream::Raw(tcp_stream) +193 } else { +194 let hostname = proxy_url.host_str().context(ProxyInvalidUrlSnafu { +195 proxy_url: proxy_url.clone(), +196 })?; +197 let hostname = +198 rustls::pki_types::ServerName::try_from(hostname.to_string()).map_err(|_| { +199 ProxyInvalidTlsServernameSnafu { +200 proxy_hostname: hostname.to_string(), +201 } +202 .build() +203 })?; +204 let tls_stream = tls_connector.connect(hostname, tcp_stream).await?; +205 MaybeTlsStream::Tls(tls_stream) +206 }; +207 let io = TokioIo::new(io); +208 +209 let target_host = self.url.host_str().context(InvalidUrlSnafu { +210 url: self.url.clone(), +211 })?; +212 +213 let port = url_port(&self.url).context(InvalidTargetPortSnafu)?; +214 +215 // Establish Proxy Tunnel +216 let mut req_builder = Request::builder() +217 .uri(format!("{target_host}:{port}")) +218 .method("CONNECT") +219 .header("Host", target_host) +220 .header("Proxy-Connection", "Keep-Alive"); +221 if !proxy_url.username().is_empty() { +222 // Passthrough authorization +223 // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Proxy-Authorization +224 debug!( +225 "setting proxy-authorization: username={}", +226 proxy_url.username() +227 ); +228 let to_encode = format!( +229 "{}:{}", +230 proxy_url.username(), +231 proxy_url.password().unwrap_or_default() +232 ); +233 let encoded = BASE64URL.encode(to_encode.as_bytes()); +234 req_builder = req_builder.header("Proxy-Authorization", format!("Basic {encoded}")); +235 } +236 let req = req_builder +237 .body(Empty::<Bytes>::new()) +238 .expect("fixed config"); +239 +240 debug!("Sending proxy request: {:?}", req); +241 +242 let (mut sender, conn) = hyper::client::conn::http1::handshake(io) +243 .await +244 .context(ProxyConnectSnafu)?; +245 task::spawn(async move { +246 if let Err(err) = conn.with_upgrades().await { +247 error!("Proxy connection failed: {:?}", err); +248 } +249 }); +250 +251 let res = sender.send_request(req).await.context(ProxyConnectSnafu)?; +252 if !res.status().is_success() { +253 return Err(ProxyConnectInvalidStatusSnafu { +254 status: res.status(), +255 } +256 .build()); +257 } +258 +259 let upgraded = hyper::upgrade::on(res).await.context(ProxyConnectSnafu)?; +260 let Parts { io, read_buf, .. } = upgraded +261 .downcast::<TokioIo<MaybeTlsStream<tokio::net::TcpStream>>>() +262 .expect("only this upgrade used"); +263 +264 let res = util::chain(std::io::Cursor::new(read_buf), io.into_inner()); +265 +266 Ok(res) +267 } +268} +269 +270fn url_port(url: &Url) -> Option<u16> { +271 if let Some(port) = url.port() { +272 return Some(port); +273 } +274 +275 match url.scheme() { +276 "http" | "ws" => Some(80), +277 "https" | "wss" => Some(443), +278 _ => None, +279 } +280}
\ No newline at end of file diff --git a/pr/3384/docs/src/iroh_relay/http.rs.html b/pr/3384/docs/src/iroh_relay/http.rs.html index 8a2dd50924..f37324f419 100644 --- a/pr/3384/docs/src/iroh_relay/http.rs.html +++ b/pr/3384/docs/src/iroh_relay/http.rs.html @@ -1,6 +1,6 @@ http.rs - source

iroh_relay/
http.rs

1//! HTTP-specific constants for the relay server and client.
 2
-3#[cfg(not(wasm_browser))]
+3#[cfg(feature = "server")]
 4pub(crate) const WEBSOCKET_UPGRADE_PROTOCOL: &str = "websocket";
 5#[cfg(feature = "server")] // only used in the server for now
 6pub(crate) const SUPPORTED_WEBSOCKET_VERSION: &str = "13";
diff --git a/pr/3384/docs/src/iroh_relay/protos/relay.rs.html b/pr/3384/docs/src/iroh_relay/protos/relay.rs.html
index 736562a9b0..89f2e1b0f5 100644
--- a/pr/3384/docs/src/iroh_relay/protos/relay.rs.html
+++ b/pr/3384/docs/src/iroh_relay/protos/relay.rs.html
@@ -525,182 +525,202 @@
 525    }
 526}
 527
-528#[cfg(test)]
+528#[cfg(all(test, feature = "server"))]
 529mod tests {
 530    use bytes::BytesMut;
 531    use data_encoding::HEXLOWER;
 532    use iroh_base::SecretKey;
 533    use n0_snafu::{Result, ResultExt};
 534
-535    use super::*;
+535    use crate::server::streams::RelayedStream;
 536
-537    #[test]
-538    fn test_frame_snapshot() -> Result {
-539        let client_key = SecretKey::from_bytes(&[42u8; 32]);
-540        let client_info = ClientInfo {
-541            version: PROTOCOL_VERSION,
-542        };
-543        let message = postcard::to_stdvec(&client_info).context("encode")?;
-544        let signature = client_key.sign(&message);
-545
-546        let frames = vec![
-547            (
-548                Frame::ClientInfo {
-549                    client_public_key: client_key.public(),
-550                    message: Bytes::from(message),
-551                    signature,
-552                },
-553                "02 52 45 4c 41 59 f0 9f 94 91 19 7f 6b 23 e1 6c
-554                85 32 c6 ab c8 38 fa cd 5e a7 89 be 0c 76 b2 92
-555                03 34 03 9b fa 8b 3d 36 8d 61 88 e7 7b 22 f2 92
-556                ab 37 43 5d a8 de 0b c8 cb 84 e2 88 f4 e7 3b 35
-557                82 a5 27 31 e9 ff 98 65 46 5c 87 e0 5e 8d 42 7d
-558                f4 22 bb 6e 85 e1 c0 5f 6f 74 98 37 ba a4 a5 c7
-559                eb a3 23 0d 77 56 99 10 43 0e 03",
-560            ),
-561            (
-562                Frame::Health {
-563                    problem: "Hello? Yes this is dog.".into(),
-564                },
-565                "0e 48 65 6c 6c 6f 3f 20 59 65 73 20 74 68 69 73
-566                20 69 73 20 64 6f 67 2e",
-567            ),
-568            (Frame::KeepAlive, "06"),
-569            (Frame::NotePreferred { preferred: true }, "07 01"),
-570            (
-571                Frame::NodeGone {
-572                    node_id: client_key.public(),
-573                },
-574                "08 19 7f 6b 23 e1 6c 85 32 c6 ab c8 38 fa cd 5e
-575                a7 89 be 0c 76 b2 92 03 34 03 9b fa 8b 3d 36 8d
-576                61",
-577            ),
-578            (
-579                Frame::Ping { data: [42u8; 8] },
-580                "0c 2a 2a 2a 2a 2a 2a 2a 2a",
-581            ),
-582            (
-583                Frame::Pong { data: [42u8; 8] },
-584                "0d 2a 2a 2a 2a 2a 2a 2a 2a",
-585            ),
-586            (
-587                Frame::RecvPacket {
-588                    src_key: client_key.public(),
-589                    content: "Hello World!".into(),
-590                },
-591                "05 19 7f 6b 23 e1 6c 85 32 c6 ab c8 38 fa cd 5e
-592                a7 89 be 0c 76 b2 92 03 34 03 9b fa 8b 3d 36 8d
-593                61 48 65 6c 6c 6f 20 57 6f 72 6c 64 21",
-594            ),
-595            (
-596                Frame::SendPacket {
-597                    dst_key: client_key.public(),
-598                    packet: "Goodbye!".into(),
-599                },
-600                "04 19 7f 6b 23 e1 6c 85 32 c6 ab c8 38 fa cd 5e
-601                a7 89 be 0c 76 b2 92 03 34 03 9b fa 8b 3d 36 8d
-602                61 47 6f 6f 64 62 79 65 21",
-603            ),
-604            (
-605                Frame::Restarting {
-606                    reconnect_in: 10,
-607                    try_for: 20,
-608                },
-609                "0f 00 00 00 0a 00 00 00 14",
-610            ),
-611        ];
-612
-613        for (frame, expected_hex) in frames {
-614            let bytes = frame.write_to(BytesMut::new()).freeze();
-615            let stripped: Vec<u8> = expected_hex
-616                .chars()
-617                .filter_map(|s| {
-618                    if s.is_ascii_whitespace() {
-619                        None
-620                    } else {
-621                        Some(s as u8)
-622                    }
-623                })
-624                .collect();
-625            let expected_bytes = HEXLOWER.decode(&stripped).unwrap();
-626            assert_eq!(bytes, expected_bytes);
-627        }
-628
-629        Ok(())
-630    }
-631}
+537    use super::*;
+538
+539    #[tokio::test]
+540    async fn test_send_recv_client_key() -> Result {
+541        let (reader, writer) = tokio::io::duplex(1024);
+542        let mut reader = RelayedStream::test_client(reader);
+543        let mut writer = RelayedStream::test_server(writer).sink_err_into();
+544
+545        let client_key = SecretKey::generate(rand::thread_rng());
+546        let client_info = ClientInfo {
+547            version: PROTOCOL_VERSION,
+548        };
+549        println!("client_key pub {:?}", client_key.public());
+550        send_client_key(&mut writer, &client_key, &client_info).await?;
+551        let (client_pub_key, got_client_info) = recv_client_key(&mut reader).await?;
+552        assert_eq!(client_key.public(), client_pub_key);
+553        assert_eq!(client_info, got_client_info);
+554        Ok(())
+555    }
+556
+557    #[test]
+558    fn test_frame_snapshot() -> Result {
+559        let client_key = SecretKey::from_bytes(&[42u8; 32]);
+560        let client_info = ClientInfo {
+561            version: PROTOCOL_VERSION,
+562        };
+563        let message = postcard::to_stdvec(&client_info).context("encode")?;
+564        let signature = client_key.sign(&message);
+565
+566        let frames = vec![
+567            (
+568                Frame::ClientInfo {
+569                    client_public_key: client_key.public(),
+570                    message: Bytes::from(message),
+571                    signature,
+572                },
+573                "02 52 45 4c 41 59 f0 9f 94 91 19 7f 6b 23 e1 6c
+574                85 32 c6 ab c8 38 fa cd 5e a7 89 be 0c 76 b2 92
+575                03 34 03 9b fa 8b 3d 36 8d 61 88 e7 7b 22 f2 92
+576                ab 37 43 5d a8 de 0b c8 cb 84 e2 88 f4 e7 3b 35
+577                82 a5 27 31 e9 ff 98 65 46 5c 87 e0 5e 8d 42 7d
+578                f4 22 bb 6e 85 e1 c0 5f 6f 74 98 37 ba a4 a5 c7
+579                eb a3 23 0d 77 56 99 10 43 0e 03",
+580            ),
+581            (
+582                Frame::Health {
+583                    problem: "Hello? Yes this is dog.".into(),
+584                },
+585                "0e 48 65 6c 6c 6f 3f 20 59 65 73 20 74 68 69 73
+586                20 69 73 20 64 6f 67 2e",
+587            ),
+588            (Frame::KeepAlive, "06"),
+589            (Frame::NotePreferred { preferred: true }, "07 01"),
+590            (
+591                Frame::NodeGone {
+592                    node_id: client_key.public(),
+593                },
+594                "08 19 7f 6b 23 e1 6c 85 32 c6 ab c8 38 fa cd 5e
+595                a7 89 be 0c 76 b2 92 03 34 03 9b fa 8b 3d 36 8d
+596                61",
+597            ),
+598            (
+599                Frame::Ping { data: [42u8; 8] },
+600                "0c 2a 2a 2a 2a 2a 2a 2a 2a",
+601            ),
+602            (
+603                Frame::Pong { data: [42u8; 8] },
+604                "0d 2a 2a 2a 2a 2a 2a 2a 2a",
+605            ),
+606            (
+607                Frame::RecvPacket {
+608                    src_key: client_key.public(),
+609                    content: "Hello World!".into(),
+610                },
+611                "05 19 7f 6b 23 e1 6c 85 32 c6 ab c8 38 fa cd 5e
+612                a7 89 be 0c 76 b2 92 03 34 03 9b fa 8b 3d 36 8d
+613                61 48 65 6c 6c 6f 20 57 6f 72 6c 64 21",
+614            ),
+615            (
+616                Frame::SendPacket {
+617                    dst_key: client_key.public(),
+618                    packet: "Goodbye!".into(),
+619                },
+620                "04 19 7f 6b 23 e1 6c 85 32 c6 ab c8 38 fa cd 5e
+621                a7 89 be 0c 76 b2 92 03 34 03 9b fa 8b 3d 36 8d
+622                61 47 6f 6f 64 62 79 65 21",
+623            ),
+624            (
+625                Frame::Restarting {
+626                    reconnect_in: 10,
+627                    try_for: 20,
+628                },
+629                "0f 00 00 00 0a 00 00 00 14",
+630            ),
+631        ];
 632
-633#[cfg(test)]
-634mod proptests {
-635    use bytes::BytesMut;
-636    use iroh_base::SecretKey;
-637    use proptest::prelude::*;
-638
-639    use super::*;
-640
-641    fn secret_key() -> impl Strategy<Value = SecretKey> {
-642        prop::array::uniform32(any::<u8>()).prop_map(SecretKey::from)
-643    }
-644
-645    fn key() -> impl Strategy<Value = PublicKey> {
-646        secret_key().prop_map(|key| key.public())
-647    }
+633        for (frame, expected_hex) in frames {
+634            let bytes = frame.write_to(BytesMut::new()).freeze();
+635            let stripped: Vec<u8> = expected_hex
+636                .chars()
+637                .filter_map(|s| {
+638                    if s.is_ascii_whitespace() {
+639                        None
+640                    } else {
+641                        Some(s as u8)
+642                    }
+643                })
+644                .collect();
+645            let expected_bytes = HEXLOWER.decode(&stripped).unwrap();
+646            assert_eq!(bytes, expected_bytes);
+647        }
 648
-649    /// Generates random data, up to the maximum packet size minus the given number of bytes
-650    fn data(consumed: usize) -> impl Strategy<Value = Bytes> {
-651        let len = MAX_PACKET_SIZE - consumed;
-652        prop::collection::vec(any::<u8>(), 0..len).prop_map(Bytes::from)
-653    }
-654
-655    /// Generates a random valid frame
-656    fn frame() -> impl Strategy<Value = Frame> {
-657        let client_info = (secret_key()).prop_map(|secret_key| {
-658            let info = ClientInfo {
-659                version: PROTOCOL_VERSION,
-660            };
-661            let msg = postcard::to_stdvec(&info).expect("using default ClientInfo");
-662            let signature = secret_key.sign(&msg);
-663            Frame::ClientInfo {
-664                client_public_key: secret_key.public(),
-665                message: msg.into(),
-666                signature,
-667            }
-668        });
-669        let send_packet =
-670            (key(), data(32)).prop_map(|(dst_key, packet)| Frame::SendPacket { dst_key, packet });
-671        let recv_packet =
-672            (key(), data(32)).prop_map(|(src_key, content)| Frame::RecvPacket { src_key, content });
-673        let keep_alive = Just(Frame::KeepAlive);
-674        let note_preferred = any::<bool>().prop_map(|preferred| Frame::NotePreferred { preferred });
-675        let peer_gone = key().prop_map(|peer| Frame::NodeGone { node_id: peer });
-676        let ping = prop::array::uniform8(any::<u8>()).prop_map(|data| Frame::Ping { data });
-677        let pong = prop::array::uniform8(any::<u8>()).prop_map(|data| Frame::Pong { data });
-678        let health = data(0).prop_map(|problem| Frame::Health { problem });
-679        let restarting =
-680            (any::<u32>(), any::<u32>()).prop_map(|(reconnect_in, try_for)| Frame::Restarting {
-681                reconnect_in,
-682                try_for,
-683            });
-684        prop_oneof![
-685            client_info,
-686            send_packet,
-687            recv_packet,
-688            keep_alive,
-689            note_preferred,
-690            peer_gone,
-691            ping,
-692            pong,
-693            health,
-694            restarting,
-695        ]
-696    }
-697
-698    proptest! {
-699        #[test]
-700        fn frame_ws_roundtrip(frame in frame()) {
-701            let encoded = frame.write_to(BytesMut::new()).freeze();
-702            let decoded = Frame::from_bytes(encoded, &KeyCache::test()).unwrap();
-703            prop_assert_eq!(frame, decoded);
-704        }
-705    }
-706}
\ No newline at end of file +649 Ok(()) +650 } +651} +652 +653#[cfg(test)] +654mod proptests { +655 use bytes::BytesMut; +656 use iroh_base::SecretKey; +657 use proptest::prelude::*; +658 +659 use super::*; +660 +661 fn secret_key() -> impl Strategy<Value = SecretKey> { +662 prop::array::uniform32(any::<u8>()).prop_map(SecretKey::from) +663 } +664 +665 fn key() -> impl Strategy<Value = PublicKey> { +666 secret_key().prop_map(|key| key.public()) +667 } +668 +669 /// Generates random data, up to the maximum packet size minus the given number of bytes +670 fn data(consumed: usize) -> impl Strategy<Value = Bytes> { +671 let len = MAX_PACKET_SIZE - consumed; +672 prop::collection::vec(any::<u8>(), 0..len).prop_map(Bytes::from) +673 } +674 +675 /// Generates a random valid frame +676 fn frame() -> impl Strategy<Value = Frame> { +677 let client_info = (secret_key()).prop_map(|secret_key| { +678 let info = ClientInfo { +679 version: PROTOCOL_VERSION, +680 }; +681 let msg = postcard::to_stdvec(&info).expect("using default ClientInfo"); +682 let signature = secret_key.sign(&msg); +683 Frame::ClientInfo { +684 client_public_key: secret_key.public(), +685 message: msg.into(), +686 signature, +687 } +688 }); +689 let send_packet = +690 (key(), data(32)).prop_map(|(dst_key, packet)| Frame::SendPacket { dst_key, packet }); +691 let recv_packet = +692 (key(), data(32)).prop_map(|(src_key, content)| Frame::RecvPacket { src_key, content }); +693 let keep_alive = Just(Frame::KeepAlive); +694 let note_preferred = any::<bool>().prop_map(|preferred| Frame::NotePreferred { preferred }); +695 let peer_gone = key().prop_map(|peer| Frame::NodeGone { node_id: peer }); +696 let ping = prop::array::uniform8(any::<u8>()).prop_map(|data| Frame::Ping { data }); +697 let pong = prop::array::uniform8(any::<u8>()).prop_map(|data| Frame::Pong { data }); +698 let health = data(0).prop_map(|problem| Frame::Health { problem }); +699 let restarting = +700 (any::<u32>(), any::<u32>()).prop_map(|(reconnect_in, try_for)| Frame::Restarting { +701 reconnect_in, +702 try_for, +703 }); +704 prop_oneof![ +705 client_info, +706 send_packet, +707 recv_packet, +708 keep_alive, +709 note_preferred, +710 peer_gone, +711 ping, +712 pong, +713 health, +714 restarting, +715 ] +716 } +717 +718 proptest! { +719 #[test] +720 fn frame_ws_roundtrip(frame in frame()) { +721 let encoded = frame.write_to(BytesMut::new()).freeze(); +722 let decoded = Frame::from_bytes(encoded, &KeyCache::test()).unwrap(); +723 prop_assert_eq!(frame, decoded); +724 } +725 } +726} \ No newline at end of file