mirror of
https://github.com/n0-computer/iroh.git
synced 2026-11-29 00:01:42 +00:00
feat(iroh-relay)!: Implement new handshake protocol, refactor frame types (#3331)
## Description This PR changes the iroh relay handshake and relaying protocol. The main goals are: - Actually authenticate the client by verifying a signed challenge (previously only the client info was signed) - We also allow using TLS extracted keying material as the subject to sign and sending it in an HTTP header, if that is available. When this works (it does so most of the time), it's 1RTT faster. - Use a better encoding for messages (we now use QUIC varints for frame type, use websocket framing for the protocol) - Remove outdated and unused frames (KeepAlive, NotePreferred) There's also some secondary changes: - Conceptually, the relay handshake and relaying protocols are now split: There's a `protos::handshake` module for the handshake, and a `protos::relay` for the send/recv protocol. - I've refactored the streams we have in iroh-relay. We now use this stack: - On the client, we establish TLS streams using `MaybeTlsStream<ProxyStream>`. `MaybeTlsStream` gives us the TLS handshake and `ProxyStream` gives us HTTPS proxy support. - On the server we establish rate-limited TLS streams using `RateLimit<MaybeTlsStream>`. - On top of these two, we stack `WsBytesFramed`, which internally uses `tokio_websockets::WebSocketStream` natively and on the server and `ws_stream_wasm::WsStream` in browsers. This wrapper does the websocket framing and translates opaque `Bytes` messages into websocket bytes frames. - This `WsBytesFramed` is then directly used with the `handshake` protocol on the server and client side. - For the `send_recv` protocol, we then upgrade the server side to `RelayedStream` and the client side to the `Conn` type. - Instead of having `Frame`, `ReceivedMessage` and `SendMessage` as types, we now only have `RelayToClientMsg` and `ClientToRelayMsg` for the send/recv protocol. ## Breaking Changes In iroh: - Connections to older relays don't work anymore. In iroh-relay: - Removed `iroh_relay::client::SendMessage` and `iroh_relay::client::ReceivedMessage` in favor of `ClientToRelayMsg` and `RelayToClientMsg` respectively. - `impl Stream for Client` now produces `RelayToClientMsg` instead of `ReceivedMessage` - `Client` now `impl Sink<ClientToRelayMsg>` instead of `impl Sink<SendMessage>` - Removed `ClientBuilder::is_prober` - Moved `protos::relay::FrameType` to `protos::common::FrameType` and adjusted frame types to those of the current set of protocols ## Change checklist <!-- Remove any that are not relevant. --> - [x] Self-review. - [x] Documentation updates following the [style guide](https://rust-lang.github.io/rfcs/1574-more-api-documentation-conventions.html#appendix-a-full-conventions-text), if relevant. - [x] Tests if relevant. - [x] All breaking changes documented.
This commit is contained in:
Generated
+33
@@ -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",
|
||||
|
||||
@@ -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]
|
||||
|
||||
@@ -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 }
|
||||
|
||||
@@ -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 { .. }
|
||||
+49
-27
@@ -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<Arc<dyn Fn() -> 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<Client, ConnectError> {
|
||||
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<Client, ConnectError> {
|
||||
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<ReceivedMessage, RecvError>;
|
||||
type Item = Result<RelayToClientMsg, RecvError>;
|
||||
|
||||
fn poll_next(mut self: Pin<&mut Self>, cx: &mut task::Context<'_>) -> Poll<Option<Self::Item>> {
|
||||
Pin::new(&mut self.conn).poll_next(cx)
|
||||
}
|
||||
}
|
||||
|
||||
impl Sink<SendMessage> for Client {
|
||||
impl Sink<ClientToRelayMsg> for Client {
|
||||
type Error = SendError;
|
||||
|
||||
fn poll_ready(
|
||||
mut self: Pin<&mut Self>,
|
||||
cx: &mut task::Context<'_>,
|
||||
) -> Poll<Result<(), Self::Error>> {
|
||||
<Conn as Sink<SendMessage>>::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<SendMessage> for Client {
|
||||
mut self: Pin<&mut Self>,
|
||||
cx: &mut task::Context<'_>,
|
||||
) -> Poll<Result<(), Self::Error>> {
|
||||
<Conn as Sink<SendMessage>>::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<Result<(), Self::Error>> {
|
||||
<Conn as Sink<SendMessage>>::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<Conn, SendMessage>,
|
||||
sink: SplitSink<Conn, ClientToRelayMsg>,
|
||||
}
|
||||
|
||||
impl Sink<SendMessage> for ClientSink {
|
||||
impl Sink<ClientToRelayMsg> for ClientSink {
|
||||
type Error = SendError;
|
||||
|
||||
fn poll_ready(
|
||||
@@ -402,7 +424,7 @@ impl Sink<SendMessage> 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<ReceivedMessage, RecvError>;
|
||||
type Item = Result<RelayToClientMsg, RecvError>;
|
||||
|
||||
fn poll_next(mut self: Pin<&mut Self>, cx: &mut task::Context<'_>) -> Poll<Option<Self::Item>> {
|
||||
Pin::new(&mut self.stream).poll_next(cx)
|
||||
|
||||
+52
-242
@@ -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<MaybeTlsStream<ProxyStream>>,
|
||||
pub(crate) conn: WsBytesFramed<MaybeTlsStream<ProxyStream>>,
|
||||
#[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<ProxyStream>,
|
||||
>,
|
||||
#[cfg(wasm_browser)] conn: ws_stream_wasm::WsStream,
|
||||
#[cfg(wasm_browser)] io: ws_stream_wasm::WsStream,
|
||||
key_cache: KeyCache,
|
||||
secret_key: &SecretKey,
|
||||
) -> Result<Self, SendRelayError> {
|
||||
let mut conn = Self { conn, key_cache };
|
||||
) -> Result<Self, handshake::Error> {
|
||||
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<ReceivedMessage, RecvError>;
|
||||
type Item = Result<RelayToClientMsg, RecvError>;
|
||||
|
||||
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
|
||||
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<Frame> for Conn {
|
||||
impl Sink<ClientToRelayMsg> for Conn {
|
||||
type Error = SendError;
|
||||
|
||||
fn poll_ready(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
|
||||
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<Result<(), Self::Error>> {
|
||||
Pin::new(&mut self.conn).poll_flush(cx).map_err(Into::into)
|
||||
}
|
||||
|
||||
fn poll_close(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
|
||||
Pin::new(&mut self.conn).poll_close(cx).map_err(Into::into)
|
||||
}
|
||||
}
|
||||
|
||||
impl Sink<SendMessage> for Conn {
|
||||
type Error = SendError;
|
||||
|
||||
fn poll_ready(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
|
||||
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<Result<(), Self::Error>> {
|
||||
@@ -238,119 +164,3 @@ impl Sink<SendMessage> 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<String>,
|
||||
},
|
||||
/// 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<Frame> for ReceivedMessage {
|
||||
type Error = RecvError;
|
||||
|
||||
fn try_from(frame: Frame) -> std::result::Result<Self, Self::Error> {
|
||||
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<SendMessage> 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 },
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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<SocketAddr> {
|
||||
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<SocketAddr> {
|
||||
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<IO> {
|
||||
Raw(IO),
|
||||
Tls(tokio_rustls::client::TlsStream<IO>),
|
||||
#[cfg(test)]
|
||||
#[cfg(all(test, feature = "server"))]
|
||||
Test(tokio::io::DuplexStream),
|
||||
}
|
||||
|
||||
impl<IO> ExportKeyingMaterial for MaybeTlsStream<IO> {
|
||||
fn export_keying_material<T: AsMut<[u8]>>(
|
||||
&self,
|
||||
output: T,
|
||||
label: &[u8],
|
||||
context: Option<&[u8]>,
|
||||
) -> Option<T> {
|
||||
let Self::Tls(ref tls) = self else {
|
||||
return None;
|
||||
};
|
||||
tls.get_ref()
|
||||
.1
|
||||
.export_keying_material(output, label, context)
|
||||
.ok()
|
||||
}
|
||||
}
|
||||
|
||||
impl<IO: AsyncRead + AsyncWrite + Unpin> AsyncRead for MaybeTlsStream<IO> {
|
||||
fn poll_read(
|
||||
mut self: Pin<&mut Self>,
|
||||
@@ -109,7 +135,7 @@ impl<IO: AsyncRead + AsyncWrite + Unpin> AsyncRead for MaybeTlsStream<IO> {
|
||||
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<IO: AsyncRead + AsyncWrite + Unpin> AsyncWrite for MaybeTlsStream<IO> {
|
||||
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<IO: AsyncRead + AsyncWrite + Unpin> AsyncWrite for MaybeTlsStream<IO> {
|
||||
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<IO: AsyncRead + AsyncWrite + Unpin> AsyncWrite for MaybeTlsStream<IO> {
|
||||
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<IO: AsyncRead + AsyncWrite + Unpin> AsyncWrite for MaybeTlsStream<IO> {
|
||||
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<TcpStream> {
|
||||
pub fn local_addr(&self) -> std::io::Result<SocketAddr> {
|
||||
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<SocketAddr> {
|
||||
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<IO> AsRef<IO> for MaybeTlsStream<IO> {
|
||||
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"),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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");
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
@@ -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<T: AsMut<[u8]>>(
|
||||
&self,
|
||||
output: T,
|
||||
label: &[u8],
|
||||
context: Option<&[u8]>,
|
||||
) -> Option<T>;
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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<Backtrace>,
|
||||
#[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<O: BufMut>(&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<Self, FrameTypeError> {
|
||||
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<FrameType> for VarInt {
|
||||
fn from(value: FrameType) -> Self {
|
||||
(value as u32).into()
|
||||
}
|
||||
}
|
||||
@@ -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<T: Frame> 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<Backtrace>,
|
||||
#[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<FrameType>,
|
||||
},
|
||||
#[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<u8>,
|
||||
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<VerificationError>> {
|
||||
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<Self> {
|
||||
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<VerificationError>> {
|
||||
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<ServerConfirmsAuth, Error> {
|
||||
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<HeaderValue>,
|
||||
rng: impl RngCore + CryptoRng,
|
||||
) -> Result<SuccessfulAuthentication, Error> {
|
||||
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<PublicKey, Error> {
|
||||
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<F: serde::Serialize + 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<F: Frame + serde::de::DeserializeOwned>(frame: Bytes) -> Result<F, Error> {
|
||||
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<IO> {
|
||||
shared_secret: Option<u64>,
|
||||
inner: IO,
|
||||
}
|
||||
|
||||
trait WithTlsSharedSecret: Sized {
|
||||
fn with_shared_secret(self, shared_secret: Option<u64>) -> TestKeyingMaterial<Self>;
|
||||
}
|
||||
|
||||
impl<T: Sized> WithTlsSharedSecret for T {
|
||||
fn with_shared_secret(self, shared_secret: Option<u64>) -> TestKeyingMaterial<Self> {
|
||||
TestKeyingMaterial {
|
||||
shared_secret,
|
||||
inner: self,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<IO> ExportKeyingMaterial for TestKeyingMaterial<IO> {
|
||||
fn export_keying_material<T: AsMut<[u8]>>(
|
||||
&self,
|
||||
mut output: T,
|
||||
label: &[u8],
|
||||
context: Option<&[u8]>,
|
||||
) -> Option<T> {
|
||||
// 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<V, IO: Stream<Item = V> + Unpin> Stream for TestKeyingMaterial<IO> {
|
||||
type Item = V;
|
||||
|
||||
fn poll_next(
|
||||
mut self: std::pin::Pin<&mut Self>,
|
||||
cx: &mut std::task::Context<'_>,
|
||||
) -> std::task::Poll<Option<Self::Item>> {
|
||||
std::pin::Pin::new(&mut self.inner).poll_next(cx)
|
||||
}
|
||||
}
|
||||
|
||||
impl<V, E, IO: Sink<V, Error = E> + Unpin> Sink<V> for TestKeyingMaterial<IO> {
|
||||
type Error = E;
|
||||
|
||||
fn poll_ready(
|
||||
mut self: std::pin::Pin<&mut Self>,
|
||||
cx: &mut std::task::Context<'_>,
|
||||
) -> std::task::Poll<Result<(), Self::Error>> {
|
||||
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<Result<(), Self::Error>> {
|
||||
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<Result<(), Self::Error>> {
|
||||
std::pin::Pin::new(&mut self.inner).poll_close(cx)
|
||||
}
|
||||
}
|
||||
|
||||
async fn simulate_handshake(
|
||||
secret_key: &SecretKey,
|
||||
client_shared_secret: Option<u64>,
|
||||
server_shared_secret: Option<u64>,
|
||||
restricted_to: Option<PublicKey>,
|
||||
) -> (Result<ServerConfirmsAuth>, 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(())
|
||||
}
|
||||
}
|
||||
+349
-572
File diff suppressed because it is too large
Load Diff
@@ -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<T> {
|
||||
#[debug("WebSocketStream<T>")]
|
||||
pub(crate) io: tokio_websockets::WebSocketStream<T>,
|
||||
}
|
||||
|
||||
#[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<Item = Result<Bytes, StreamError>> + Sink<Bytes, Error = StreamError> + Unpin
|
||||
{
|
||||
}
|
||||
|
||||
impl<T> BytesStreamSink for T where
|
||||
T: Stream<Item = Result<Bytes, StreamError>> + Sink<Bytes, Error = StreamError> + Unpin
|
||||
{
|
||||
}
|
||||
|
||||
#[cfg(not(wasm_browser))]
|
||||
impl<IO: ExportKeyingMaterial + AsyncRead + AsyncWrite + Unpin> ExportKeyingMaterial
|
||||
for WsBytesFramed<IO>
|
||||
{
|
||||
fn export_keying_material<T: AsMut<[u8]>>(
|
||||
&self,
|
||||
output: T,
|
||||
label: &[u8],
|
||||
context: Option<&[u8]>,
|
||||
) -> Option<T> {
|
||||
self.io
|
||||
.get_ref()
|
||||
.export_keying_material(output, label, context)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(wasm_browser)]
|
||||
impl ExportKeyingMaterial for WsBytesFramed {
|
||||
fn export_keying_material<T: AsMut<[u8]>>(
|
||||
&self,
|
||||
_output: T,
|
||||
_label: &[u8],
|
||||
_context: Option<&[u8]>,
|
||||
) -> Option<T> {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(wasm_browser))]
|
||||
impl<T: AsyncRead + AsyncWrite + Unpin> Stream for WsBytesFramed<T> {
|
||||
type Item = Result<Bytes, StreamError>;
|
||||
|
||||
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
|
||||
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<Bytes, StreamError>;
|
||||
|
||||
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
|
||||
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<T: AsyncRead + AsyncWrite + Unpin> Sink<Bytes> for WsBytesFramed<T> {
|
||||
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<Result<(), Self::Error>> {
|
||||
Pin::new(&mut self.io).poll_ready(cx).map_err(Into::into)
|
||||
}
|
||||
|
||||
fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
|
||||
Pin::new(&mut self.io).poll_flush(cx).map_err(Into::into)
|
||||
}
|
||||
|
||||
fn poll_close(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
|
||||
Pin::new(&mut self.io).poll_close(cx).map_err(Into::into)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(wasm_browser)]
|
||||
impl Sink<Bytes> 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<Result<(), Self::Error>> {
|
||||
Pin::new(&mut self.io).poll_ready(cx).map_err(Into::into)
|
||||
}
|
||||
|
||||
fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
|
||||
Pin::new(&mut self.io).poll_flush(cx).map_err(Into::into)
|
||||
}
|
||||
|
||||
fn poll_close(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
|
||||
Pin::new(&mut self.io).poll_close(cx).map_err(Into::into)
|
||||
}
|
||||
}
|
||||
@@ -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();
|
||||
|
||||
+33
-45
@@ -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<Server, SpawnError> {
|
||||
@@ -788,11 +792,14 @@ mod tests {
|
||||
client_b: &mut crate::client::Client,
|
||||
b_key: NodeId,
|
||||
msg: Bytes,
|
||||
) -> Result<ReceivedMessage> {
|
||||
) -> Result<RelayToClientMsg> {
|
||||
// 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(())
|
||||
|
||||
@@ -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<Backtrace>,
|
||||
})]
|
||||
@@ -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<Backtrace>,
|
||||
})]
|
||||
#[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<Result<Frame, StreamError>>,
|
||||
maybe_frame: Option<Result<ClientToRelayMsg, RelayRecvError>>,
|
||||
) -> 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<Item = Result<RelayToClientMsg, E>> + Unpin,
|
||||
>(
|
||||
frame_type: FrameType,
|
||||
mut stream: S,
|
||||
) -> Result<RelayToClientMsg> {
|
||||
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(),
|
||||
};
|
||||
|
||||
@@ -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<Item = Result<RelayToClientMsg, E>> + Unpin,
|
||||
>(
|
||||
frame_type: FrameType,
|
||||
mut stream: S,
|
||||
) -> Result<RelayToClientMsg> {
|
||||
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(),
|
||||
}
|
||||
|
||||
@@ -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<hyper::body::Bytes>) -> 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<Metrics>,
|
||||
}
|
||||
|
||||
#[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<Incoming>,
|
||||
) -> Pin<Box<dyn Future<Output = Result<Response<BytesBody>, 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<Response<BytesBody>, RelayUpgradeReqError> {
|
||||
fn expect_header(
|
||||
req: &Request<Incoming>,
|
||||
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<Request<Incoming>> 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<HeaderValue>,
|
||||
) -> 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<HeaderValue>,
|
||||
) -> 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<Result<ReceivedMessage, crate::client::RecvError>>,
|
||||
msg: Option<Result<RelayToClientMsg, crate::client::RecvError>>,
|
||||
) -> 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());
|
||||
|
||||
@@ -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<RateLimited<MaybeTlsStream>>,
|
||||
pub(crate) inner: WsBytesFramed<RateLimited<MaybeTlsStream>>,
|
||||
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<Frame> for RelayedStream {
|
||||
type Error = std::io::Error;
|
||||
impl Sink<RelayToClientMsg> for RelayedStream {
|
||||
type Error = SendError;
|
||||
|
||||
fn poll_ready(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
|
||||
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<Result<(), Self::Error>> {
|
||||
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<Result<(), Self::Error>> {
|
||||
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<Frame, StreamError>;
|
||||
type Item = Result<ClientToRelayMsg, RecvError>;
|
||||
|
||||
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
|
||||
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<T: AsMut<[u8]>>(
|
||||
&self,
|
||||
output: T,
|
||||
label: &[u8],
|
||||
context: Option<&[u8]>,
|
||||
) -> Option<T> {
|
||||
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<S> RateLimited<S> {
|
||||
metrics,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<S> RateLimited<S> {
|
||||
/// 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<S> RateLimited<S> {
|
||||
}
|
||||
}
|
||||
|
||||
impl<S: ExportKeyingMaterial> ExportKeyingMaterial for RateLimited<S> {
|
||||
fn export_keying_material<T: AsMut<[u8]>>(
|
||||
&self,
|
||||
output: T,
|
||||
label: &[u8],
|
||||
context: Option<&[u8]>,
|
||||
) -> Option<T> {
|
||||
self.inner.export_keying_material(output, label, context)
|
||||
}
|
||||
}
|
||||
|
||||
impl<S: AsyncRead + Unpin> AsyncRead for RateLimited<S> {
|
||||
#[instrument(name = "rate_limited_poll_read", skip_all)]
|
||||
fn poll_read(
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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<usize>) -> Transmit<'_> {
|
||||
Transmit {
|
||||
ecn: None,
|
||||
contents,
|
||||
segment_size,
|
||||
}
|
||||
}
|
||||
fn mk_expected(parts: impl IntoIterator<Item = &'static str>) -> 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;
|
||||
|
||||
@@ -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<RelaySendItem>,
|
||||
rx: &mut mpsc::Receiver<RelayRecvDatagram>,
|
||||
) -> 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 {
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user