Expand description
This module implements the relaying protocol used by the server and client.
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}
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}