mirror of
https://github.com/n0-computer/iroh.git
synced 2026-11-30 00:01:16 +00:00
feat: update relay protocol to iroh-relay-v2, add new Health frame, test protocol update mechanism (#3955)
## Description This commit adds a `iroh-relay-v2` protocol. The only changes to the `iroh-relay-v1` protocol are: * removed `Health` frame (id 11) with string payload * added `Status` frame (id 13) with binary-encoded enum payload that can be extended with further variants or payloads * From now on, unknown frames will be ignored in iroh (instead of erroring out) The actual change is thus quite minor, but serves as a real-world test for our protocol negotiation. The PR also fixes a bug in how the relay server parsed the supported protocols; it is harmless because all existing deployments support a single version anyway, but good to fix now. Everything is fully backwards-compatible on the wire (old clients can talk to new relays, and new clients can talk to old relays). ## Breaking Changes * `iroh_relay::http::RELAY_PROTOCOL_VERSION` has been removed. The relay protocol now supports version negotiation between client and server. Use `iroh_relay::http::ProtocolVersion` instead. For the previous constant value, use `ProtocolVersion::V1.to_str()`. * `iroh_relay::server::client::Config` has a new field `protocol_version: ProtocolVersion`. * `iroh_relay::protos::relay::RelayToClientMsg` has a new `Status(Status)` variant and the existing `Health` variant is deprecated. Clients should handle `RelayToClientMsg::Status` for connection health information. The `Health` variant is still sent by V1 relay servers but should not be relied upon going forward. ## Notes & open questions <!-- Any notes, remarks or open questions you have to make about the PR. --> ## 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
+3
-3
@@ -4424,9 +4424,9 @@ checksum = "f87165f0995f63a9fbeea62b64d10b4d9d8e78ec6d7d51fb2125fda7bb36788f"
|
||||
|
||||
[[package]]
|
||||
name = "rustls-webpki"
|
||||
version = "0.103.10"
|
||||
version = "0.103.12"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "df33b2b81ac578cabaf06b89b0631153a3f416b0a886e8a7a1707fb51abbd1ef"
|
||||
checksum = "8279bb85272c9f10811ae6a6c547ff594d6a7f3c6c6b02ee9726d1d0dcfcdd06"
|
||||
dependencies = [
|
||||
"aws-lc-rs",
|
||||
"ring",
|
||||
@@ -5025,7 +5025,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd"
|
||||
dependencies = [
|
||||
"fastrand",
|
||||
"getrandom 0.3.4",
|
||||
"getrandom 0.4.2",
|
||||
"once_cell",
|
||||
"rustix",
|
||||
"windows-sys 0.61.2",
|
||||
|
||||
@@ -25,7 +25,7 @@ pub use self::conn::{RecvError, SendError};
|
||||
use crate::dns::{DnsError, DnsResolver};
|
||||
use crate::{
|
||||
KeyCache,
|
||||
http::RELAY_PATH,
|
||||
http::{ProtocolVersion, RELAY_PATH},
|
||||
protos::{
|
||||
handshake,
|
||||
relay::{ClientToRelayMsg, RelayToClientMsg},
|
||||
@@ -230,7 +230,7 @@ impl ClientBuilder {
|
||||
use tls::MaybeTlsStreamBuilder;
|
||||
|
||||
use crate::{
|
||||
http::{CLIENT_AUTH_HEADER, RELAY_PROTOCOL_VERSION},
|
||||
http::CLIENT_AUTH_HEADER,
|
||||
protos::{handshake::KeyMaterialClientAuth, relay::MAX_FRAME_SIZE},
|
||||
};
|
||||
|
||||
@@ -277,7 +277,7 @@ impl ClientBuilder {
|
||||
})?
|
||||
.add_header(
|
||||
SEC_WEBSOCKET_PROTOCOL,
|
||||
http::HeaderValue::from_static(RELAY_PROTOCOL_VERSION),
|
||||
ProtocolVersion::all_as_header_value(),
|
||||
)
|
||||
.expect("valid header name and value")
|
||||
.limits(tokio_websockets::Limits::default().max_payload_len(Some(MAX_FRAME_SIZE)))
|
||||
@@ -334,8 +334,6 @@ 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.
|
||||
@@ -354,9 +352,11 @@ impl ClientBuilder {
|
||||
|
||||
debug!(%dial_url, "Dialing relay by websocket");
|
||||
|
||||
let (_, ws_stream) =
|
||||
ws_stream_wasm::WsMeta::connect(dial_url.as_str(), Some(vec![RELAY_PROTOCOL_VERSION]))
|
||||
.await?;
|
||||
let (_, ws_stream) = ws_stream_wasm::WsMeta::connect(
|
||||
dial_url.as_str(),
|
||||
Some(ProtocolVersion::all().collect()),
|
||||
)
|
||||
.await?;
|
||||
let conn = Conn::new(ws_stream, self.key_cache.clone(), &self.secret_key).await?;
|
||||
|
||||
event!(
|
||||
|
||||
+89
-6
@@ -1,6 +1,8 @@
|
||||
//! HTTP-specific constants for the relay server and client.
|
||||
|
||||
use http::HeaderName;
|
||||
use http::{HeaderName, HeaderValue};
|
||||
use n0_error::stack_error;
|
||||
use strum::VariantArray;
|
||||
|
||||
#[cfg(feature = "server")]
|
||||
pub(crate) const WEBSOCKET_UPGRADE_PROTOCOL: &str = "websocket";
|
||||
@@ -13,10 +15,91 @@ 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");
|
||||
|
||||
/// The relay protocol version negotiated between client and server.
|
||||
///
|
||||
/// Sent as the websocket sub-protocol header `Sec-Websocket-Protocol` from
|
||||
/// the client. The server picks the best supported version and replies with it.
|
||||
///
|
||||
/// Variants are ordered by preference (highest first), so the [`Ord`] impl
|
||||
/// can be used during negotiation to pick the best version.
|
||||
#[derive(
|
||||
Clone,
|
||||
Copy,
|
||||
Debug,
|
||||
PartialEq,
|
||||
Eq,
|
||||
PartialOrd,
|
||||
Ord,
|
||||
Default,
|
||||
strum::VariantArray,
|
||||
strum::EnumString,
|
||||
strum::Display,
|
||||
strum::IntoStaticStr,
|
||||
)]
|
||||
#[strum(parse_err_ty = UnsupportedRelayProtocolVersion, parse_err_fn = strum_err_fn)]
|
||||
// Needs to be ordered with latest version last, so that the `Ord` impl orders by latest version as max.
|
||||
pub enum ProtocolVersion {
|
||||
/// Version 1 (the only version supported until iroh 0.98.0)
|
||||
#[strum(serialize = "iroh-relay-v1")]
|
||||
V1,
|
||||
/// Version 2 (added in iroh 0.98.0)
|
||||
/// - Removed `Health` frame (id 11)
|
||||
/// - Added new `Status` frame (id 13)
|
||||
/// - Changed behavior such that unknown frames are ignored instead of
|
||||
/// being treated as an error
|
||||
#[default]
|
||||
#[strum(serialize = "iroh-relay-v2")]
|
||||
V2,
|
||||
}
|
||||
|
||||
impl ProtocolVersion {
|
||||
/// Returns an iterator of all supported protocol version identifiers, in order of preference.
|
||||
pub fn all() -> impl Iterator<Item = &'static str> {
|
||||
Self::VARIANTS
|
||||
.iter()
|
||||
.map(ProtocolVersion::to_str)
|
||||
// We reverse the order so that the latest version comes first:
|
||||
// `Self::VARIANTS` is ordered in definition order, where the latest version comes last
|
||||
// so that the `Ord` derive correctly orders by "latest is max".
|
||||
.rev()
|
||||
}
|
||||
|
||||
/// Returns a comma-separated string of all supported protocol version identifiers.
|
||||
pub fn all_joined() -> String {
|
||||
Self::all().collect::<Vec<_>>().join(", ")
|
||||
}
|
||||
|
||||
/// Returns all supported protocol versions in a comma-seperated string as an HTTP header value.
|
||||
pub fn all_as_header_value() -> HeaderValue {
|
||||
HeaderValue::from_bytes(Self::all_joined().as_bytes()).expect("valid header name")
|
||||
}
|
||||
|
||||
/// Returns the protocol version identifier string.
|
||||
pub fn to_str(&self) -> &'static str {
|
||||
self.into()
|
||||
}
|
||||
|
||||
/// Tries to parse a [`ProtocolVersion`] from `s`.
|
||||
///
|
||||
/// Returns `None` if `s` is not a valid protocol version string.
|
||||
pub fn match_from_str(s: &str) -> Option<Self> {
|
||||
Self::try_from(s).ok()
|
||||
}
|
||||
|
||||
/// Returns this protocol version as an HTTP header value.
|
||||
pub fn to_header_value(&self) -> HeaderValue {
|
||||
HeaderValue::from_static(self.to_str())
|
||||
}
|
||||
}
|
||||
|
||||
/// Error returned when the relay protocol version is not recognized.
|
||||
#[stack_error(derive)]
|
||||
#[error("Relay protocol version is not supported")]
|
||||
pub struct UnsupportedRelayProtocolVersion;
|
||||
|
||||
fn strum_err_fn(_item: &str) -> UnsupportedRelayProtocolVersion {
|
||||
UnsupportedRelayProtocolVersion::new()
|
||||
}
|
||||
|
||||
@@ -46,6 +46,8 @@ pub enum FrameType {
|
||||
Ping = 9,
|
||||
/// 8 byte payload, the contents of ping being replied to
|
||||
Pong = 10,
|
||||
/// REMOVED since relay-protocol-v2, use `Self::Status` instead.
|
||||
///
|
||||
/// Sent from server to client to tell the client if their connection is unhealthy somehow.
|
||||
/// Contains only UTF-8 bytes.
|
||||
Health = 11,
|
||||
@@ -54,6 +56,15 @@ pub enum FrameType {
|
||||
/// Payload is two big endian u32 durations in milliseconds: when to reconnect,
|
||||
/// and how long to try total.
|
||||
Restarting = 12,
|
||||
|
||||
/// Sent from server to client to declare the connection health state.
|
||||
///
|
||||
/// Added in `iroh-relay-v2` protocol. May not be sent to `iroh-relay-v1` clients.
|
||||
///
|
||||
/// Uses a binary-encoded [`Status`] payload.
|
||||
///
|
||||
/// [`Status`]: super::relay::Status
|
||||
Status = 13,
|
||||
}
|
||||
|
||||
#[stack_error(derive, add_meta)]
|
||||
|
||||
@@ -71,7 +71,7 @@ pub enum Error {
|
||||
}
|
||||
|
||||
/// The messages that a relay sends to clients or the clients receive from the relay.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
#[derive(Debug, Clone, PartialEq, Eq, strum::Display)]
|
||||
#[non_exhaustive]
|
||||
pub enum RelayToClientMsg {
|
||||
/// Represents datagrams sent from relays (originally sent to them by another client).
|
||||
@@ -85,15 +85,7 @@ pub enum RelayToClientMsg {
|
||||
/// packet but has now disconnected from the relay.
|
||||
EndpointGone(EndpointId),
|
||||
/// A one-way message from relay 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 relay doesn't broadcast a [`RelayToClientMsg::Health`]
|
||||
/// until a problem exists.
|
||||
problem: String,
|
||||
},
|
||||
Status(Status),
|
||||
/// A one-way message from relay to client, advertising that the relay is restarting.
|
||||
Restarting {
|
||||
/// An advisory duration that the client should wait before attempting to reconnect.
|
||||
@@ -111,6 +103,64 @@ pub enum RelayToClientMsg {
|
||||
/// Reply to a [`ClientToRelayMsg::Ping`] from a client
|
||||
/// with the payload sent previously in the ping.
|
||||
Pong([u8; 8]),
|
||||
|
||||
// -- Deprecated variants --
|
||||
// We don't use `#[deprecated]` because this would throw warnings for the derived serde impls.
|
||||
/// Removed since relay-protocol-v2:
|
||||
/// A one-way message from relay to client, declaring the connection health state.
|
||||
///
|
||||
/// Use [`Self::Status`] instead.
|
||||
Health {
|
||||
/// Description of why the connection is unhealthy.
|
||||
///
|
||||
/// The default condition is healthy, so the relay doesn't broadcast a [`RelayToClientMsg::Health`]
|
||||
/// until a problem exists.
|
||||
problem: String,
|
||||
},
|
||||
}
|
||||
|
||||
/// One-way message from server to client indicating issues with the relay connection.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, derive_more::Display)]
|
||||
#[non_exhaustive]
|
||||
pub enum Status {
|
||||
/// The connection is healthy and recovered from previous problems.
|
||||
#[display("The connection is healthy and has recovered from previous problems")]
|
||||
Healthy,
|
||||
/// Another endpoint connected with the same endpoint id. No more messages will be received.
|
||||
#[display(
|
||||
"Another endpoint connected with the same endpoint id. No more messages will be received."
|
||||
)]
|
||||
SameEndpointIdConnected,
|
||||
/// Placeholder for backwards-compatibility for future new health status variants.
|
||||
#[display("Unsupported health message ({_0})")]
|
||||
Unknown(u8),
|
||||
}
|
||||
|
||||
impl Status {
|
||||
#[cfg(feature = "server")]
|
||||
fn write_to<O: BufMut>(&self, mut dst: O) -> O {
|
||||
match self {
|
||||
Status::Healthy => dst.put_u8(0),
|
||||
Status::SameEndpointIdConnected => dst.put_u8(1),
|
||||
Status::Unknown(discriminant) => dst.put_u8(*discriminant),
|
||||
}
|
||||
dst
|
||||
}
|
||||
|
||||
#[cfg(feature = "server")]
|
||||
fn encoded_len(&self) -> usize {
|
||||
1
|
||||
}
|
||||
|
||||
fn from_bytes(mut bytes: Bytes) -> Result<Self, Error> {
|
||||
ensure!(!bytes.is_empty(), Error::InvalidFrame);
|
||||
let discriminant = bytes.get_u8();
|
||||
match discriminant {
|
||||
0 => Ok(Self::Healthy),
|
||||
1 => Ok(Self::SameEndpointIdConnected),
|
||||
n => Ok(Self::Unknown(n)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Messages that clients send to relays.
|
||||
@@ -259,8 +309,9 @@ impl RelayToClientMsg {
|
||||
Self::EndpointGone { .. } => FrameType::EndpointGone,
|
||||
Self::Ping { .. } => FrameType::Ping,
|
||||
Self::Pong { .. } => FrameType::Pong,
|
||||
Self::Health { .. } => FrameType::Health,
|
||||
Self::Status { .. } => FrameType::Status,
|
||||
Self::Restarting { .. } => FrameType::Restarting,
|
||||
Self::Health { .. } => FrameType::Health,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -302,6 +353,9 @@ impl RelayToClientMsg {
|
||||
dst.put_u32(reconnect_in.as_millis() as u32);
|
||||
dst.put_u32(try_for.as_millis() as u32);
|
||||
}
|
||||
Self::Status(status) => {
|
||||
dst = status.write_to(dst);
|
||||
}
|
||||
}
|
||||
dst
|
||||
}
|
||||
@@ -315,11 +369,12 @@ impl RelayToClientMsg {
|
||||
}
|
||||
Self::EndpointGone(_) => 32,
|
||||
Self::Ping(_) | Self::Pong(_) => 8,
|
||||
Self::Health { problem } => problem.len(),
|
||||
Self::Status(status) => status.encoded_len(),
|
||||
Self::Restarting { .. } => {
|
||||
4 // u32
|
||||
+ 4 // u32
|
||||
}
|
||||
Self::Health { problem } => problem.len(),
|
||||
};
|
||||
self.typ().encoded_len() + payload_len
|
||||
}
|
||||
@@ -390,6 +445,10 @@ impl RelayToClientMsg {
|
||||
try_for,
|
||||
}
|
||||
}
|
||||
FrameType::Status => {
|
||||
let status = Status::from_bytes(content)?;
|
||||
Self::Status(status)
|
||||
}
|
||||
_ => {
|
||||
return Err(e!(Error::InvalidFrameType { frame_type }));
|
||||
}
|
||||
@@ -601,6 +660,10 @@ mod tests {
|
||||
.write_to(Vec::new()),
|
||||
"0c 00 00 00 0a 00 00 00 14",
|
||||
),
|
||||
(
|
||||
RelayToClientMsg::Status(Status::SameEndpointIdConnected).write_to(Vec::new()),
|
||||
"0d 01",
|
||||
),
|
||||
]);
|
||||
|
||||
Ok(())
|
||||
@@ -721,18 +784,27 @@ mod proptests {
|
||||
let endpoint_gone = key().prop_map(RelayToClientMsg::EndpointGone);
|
||||
let ping = prop::array::uniform8(any::<u8>()).prop_map(RelayToClientMsg::Ping);
|
||||
let pong = prop::array::uniform8(any::<u8>()).prop_map(RelayToClientMsg::Pong);
|
||||
let health = ".{0,65536}"
|
||||
let v1health = ".{0,65536}"
|
||||
.prop_filter("exceeds MAX_PACKET_SIZE", |s| {
|
||||
s.len() < MAX_PACKET_SIZE // a single unicode character can match a regex "." but take up multiple bytes
|
||||
})
|
||||
.prop_map(|problem| RelayToClientMsg::Health { problem });
|
||||
let health = Just(Status::SameEndpointIdConnected).prop_map(RelayToClientMsg::Status);
|
||||
let restarting = (any::<u32>(), any::<u32>()).prop_map(|(reconnect_in, try_for)| {
|
||||
RelayToClientMsg::Restarting {
|
||||
reconnect_in: Duration::from_millis(reconnect_in.into()),
|
||||
try_for: Duration::from_millis(try_for.into()),
|
||||
}
|
||||
});
|
||||
prop_oneof![recv_packet, endpoint_gone, ping, pong, health, restarting]
|
||||
prop_oneof![
|
||||
recv_packet,
|
||||
endpoint_gone,
|
||||
ping,
|
||||
pong,
|
||||
v1health,
|
||||
restarting,
|
||||
health
|
||||
]
|
||||
}
|
||||
|
||||
fn client_server_frame() -> impl Strategy<Value = ClientToRelayMsg> {
|
||||
|
||||
@@ -16,8 +16,9 @@ use tracing::{Instrument, debug, trace, warn};
|
||||
|
||||
use crate::{
|
||||
PingTracker,
|
||||
http::ProtocolVersion,
|
||||
protos::{
|
||||
relay::{ClientToRelayMsg, Datagrams, PING_INTERVAL, RelayToClientMsg},
|
||||
relay::{ClientToRelayMsg, Datagrams, PING_INTERVAL, RelayToClientMsg, Status},
|
||||
streams::BytesStreamSink,
|
||||
},
|
||||
server::{
|
||||
@@ -49,6 +50,8 @@ pub struct Config<S> {
|
||||
pub write_timeout: Duration,
|
||||
/// Channel capacity for internal message queues
|
||||
pub channel_capacity: usize,
|
||||
/// Protocol version negotiated for this client
|
||||
pub protocol_version: ProtocolVersion,
|
||||
}
|
||||
|
||||
/// The [`Server`] side representation of a [`Client`]'s connection.
|
||||
@@ -69,6 +72,8 @@ pub struct Client {
|
||||
packet_queue: mpsc::Sender<Packet>,
|
||||
/// Channel to send non-packet messages to the client.
|
||||
message_queue: mpsc::Sender<RelayToClientMsg>,
|
||||
/// Relay protocol version negotiated for this client.
|
||||
protocol_version: ProtocolVersion,
|
||||
}
|
||||
|
||||
impl Client {
|
||||
@@ -89,6 +94,7 @@ impl Client {
|
||||
stream,
|
||||
write_timeout,
|
||||
channel_capacity,
|
||||
protocol_version,
|
||||
} = config;
|
||||
|
||||
let (packet_send_queue_s, packet_send_queue_r) = mpsc::channel(channel_capacity);
|
||||
@@ -123,6 +129,7 @@ impl Client {
|
||||
done,
|
||||
packet_queue: packet_send_queue_s,
|
||||
message_queue: message_send_queue_s,
|
||||
protocol_version,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -166,10 +173,15 @@ impl Client {
|
||||
|
||||
pub(super) fn try_send_health(
|
||||
&self,
|
||||
problem: String,
|
||||
status: Status,
|
||||
) -> Result<(), TrySendError<RelayToClientMsg>> {
|
||||
self.message_queue
|
||||
.try_send(RelayToClientMsg::Health { problem })
|
||||
let message = match self.protocol_version {
|
||||
ProtocolVersion::V2 => RelayToClientMsg::Status(status),
|
||||
ProtocolVersion::V1 => RelayToClientMsg::Health {
|
||||
problem: status.to_string(),
|
||||
},
|
||||
};
|
||||
self.message_queue.try_send(message)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -510,7 +522,12 @@ mod tests {
|
||||
use tracing::info;
|
||||
|
||||
use super::*;
|
||||
use crate::{client::conn::Conn, protos::common::FrameType};
|
||||
use crate::{
|
||||
client::conn::Conn,
|
||||
http::ProtocolVersion,
|
||||
protos::{common::FrameType, relay::Status, streams::WsBytesFramed},
|
||||
server::streams::{MaybeTlsStream, RateLimited, ServerRelayedStream},
|
||||
};
|
||||
|
||||
async fn recv_frame<
|
||||
E: std::error::Error + Sync + Send + 'static,
|
||||
@@ -633,6 +650,137 @@ mod tests {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn test_client_builder(
|
||||
key: EndpointId,
|
||||
protocol_version: ProtocolVersion,
|
||||
) -> (Config<WsBytesFramed<RateLimited<MaybeTlsStream>>>, Conn) {
|
||||
let (server, client) = tokio::io::duplex(1024);
|
||||
(
|
||||
Config {
|
||||
endpoint_id: key,
|
||||
stream: ServerRelayedStream::test(server),
|
||||
write_timeout: Duration::from_secs(1),
|
||||
channel_capacity: 10,
|
||||
protocol_version,
|
||||
},
|
||||
Conn::test(client),
|
||||
)
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[traced_test]
|
||||
async fn test_client_v1_protocol() -> Result {
|
||||
let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(42u64);
|
||||
let a_key = SecretKey::from_bytes(&rng.random()).public();
|
||||
let b_key = SecretKey::from_bytes(&rng.random()).public();
|
||||
|
||||
let (builder_a, mut a_rw) = test_client_builder(a_key, ProtocolVersion::V1);
|
||||
|
||||
let clients = Clients::default();
|
||||
let metrics = Arc::new(Metrics::default());
|
||||
clients.register(builder_a, metrics.clone());
|
||||
|
||||
// Verify basic packet delivery works with V1.
|
||||
let data = b"hello world v1!";
|
||||
clients.send_packet(a_key, Datagrams::from(&data[..]), b_key, &metrics)?;
|
||||
let frame = recv_frame(FrameType::RelayToClientDatagram, &mut a_rw).await?;
|
||||
assert_eq!(
|
||||
frame,
|
||||
RelayToClientMsg::Datagrams {
|
||||
remote_endpoint_id: b_key,
|
||||
datagrams: data.to_vec().into(),
|
||||
}
|
||||
);
|
||||
|
||||
clients.shutdown().await;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[traced_test]
|
||||
async fn test_client_v2_protocol() -> Result {
|
||||
let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(42u64);
|
||||
let a_key = SecretKey::from_bytes(&rng.random()).public();
|
||||
let b_key = SecretKey::from_bytes(&rng.random()).public();
|
||||
|
||||
let (builder_a, mut a_rw) = test_client_builder(a_key, ProtocolVersion::V2);
|
||||
|
||||
let clients = Clients::default();
|
||||
let metrics = Arc::new(Metrics::default());
|
||||
clients.register(builder_a, metrics.clone());
|
||||
|
||||
// Verify basic packet delivery works with V2.
|
||||
let data = b"hello world v2!";
|
||||
clients.send_packet(a_key, Datagrams::from(&data[..]), b_key, &metrics)?;
|
||||
let frame = recv_frame(FrameType::RelayToClientDatagram, &mut a_rw).await?;
|
||||
assert_eq!(
|
||||
frame,
|
||||
RelayToClientMsg::Datagrams {
|
||||
remote_endpoint_id: b_key,
|
||||
datagrams: data.to_vec().into(),
|
||||
}
|
||||
);
|
||||
|
||||
clients.shutdown().await;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Test for versioned protocol: v1 client should receive V1Health frame.
|
||||
#[tokio::test]
|
||||
#[traced_test]
|
||||
async fn test_duplicate_endpoint_v1_receives_v1health() -> Result {
|
||||
let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(42u64);
|
||||
let key = SecretKey::from_bytes(&rng.random()).public();
|
||||
|
||||
let (builder_first, mut first_rw) = test_client_builder(key, ProtocolVersion::V1);
|
||||
|
||||
let clients = Clients::default();
|
||||
let metrics = Arc::new(Metrics::default());
|
||||
clients.register(builder_first, metrics.clone());
|
||||
|
||||
// Register a second client with the same endpoint ID.
|
||||
// The first client should receive a V1Health message.
|
||||
let (builder_second, _second_rw) = test_client_builder(key, ProtocolVersion::V1);
|
||||
clients.register(builder_second, metrics.clone());
|
||||
|
||||
let frame = recv_frame(FrameType::Health, &mut first_rw).await?;
|
||||
assert!(
|
||||
matches!(frame, RelayToClientMsg::Health { .. }),
|
||||
"expected V1Health frame for V1 client, got {frame:?}"
|
||||
);
|
||||
|
||||
clients.shutdown().await;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Test for versioned protocol: v2 client should receive V2Health frame.
|
||||
#[tokio::test]
|
||||
#[traced_test]
|
||||
async fn test_duplicate_endpoint_v2_receives_health() -> Result {
|
||||
let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(42u64);
|
||||
let key = SecretKey::from_bytes(&rng.random()).public();
|
||||
|
||||
let (builder_first, mut first_rw) = test_client_builder(key, ProtocolVersion::V2);
|
||||
|
||||
let clients = Clients::default();
|
||||
let metrics = Arc::new(Metrics::default());
|
||||
clients.register(builder_first, metrics.clone());
|
||||
|
||||
// Register a second client with the same endpoint ID.
|
||||
// The first client should receive a Health message (V2 frame).
|
||||
let (builder_second, _second_rw) = test_client_builder(key, ProtocolVersion::V2);
|
||||
clients.register(builder_second, metrics.clone());
|
||||
|
||||
let frame = recv_frame(FrameType::Status, &mut first_rw).await?;
|
||||
assert_eq!(
|
||||
frame,
|
||||
RelayToClientMsg::Status(Status::SameEndpointIdConnected)
|
||||
);
|
||||
|
||||
clients.shutdown().await;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
#[traced_test]
|
||||
async fn test_rate_limit() -> Result {
|
||||
|
||||
@@ -17,7 +17,10 @@ use tracing::{debug, trace};
|
||||
|
||||
use super::client::{Client, Config, ForwardPacketError};
|
||||
use crate::{
|
||||
protos::{relay::Datagrams, streams::BytesStreamSink},
|
||||
protos::{
|
||||
relay::{Datagrams, Status},
|
||||
streams::BytesStreamSink,
|
||||
},
|
||||
server::{client::SendError, metrics::Metrics},
|
||||
};
|
||||
|
||||
@@ -88,7 +91,7 @@ impl Clients {
|
||||
"multiple connections found, deactivating old connection",
|
||||
);
|
||||
old_client
|
||||
.try_send_health("Another endpoint connected with the same endpoint id. No more messages will be received".to_string())
|
||||
.try_send_health(Status::SameEndpointIdConnected)
|
||||
.ok();
|
||||
state.inactive.push(old_client);
|
||||
metrics.clients_inactive_added.inc();
|
||||
@@ -131,6 +134,8 @@ impl Clients {
|
||||
metrics.clients_inactive_removed.inc();
|
||||
// There is an inactive client, promote to active again.
|
||||
state.active = last_inactive_client;
|
||||
// Inform the old client that it is healthy again.
|
||||
state.active.try_send_health(Status::Healthy).ok();
|
||||
// Don't remove the entry from client map.
|
||||
false
|
||||
} else {
|
||||
@@ -271,6 +276,7 @@ mod tests {
|
||||
stream: ServerRelayedStream::test(server),
|
||||
write_timeout: Duration::from_secs(1),
|
||||
channel_capacity: 10,
|
||||
protocol_version: Default::default(),
|
||||
},
|
||||
Conn::test(client),
|
||||
)
|
||||
@@ -359,7 +365,11 @@ mod tests {
|
||||
assert!(a2_conn_id != a1_conn_id);
|
||||
|
||||
// a1 is marked inactive and should receive a health frame
|
||||
let _frame = recv_frame(FrameType::Health, &mut a1_rw).await?;
|
||||
let frame = recv_frame(FrameType::Status, &mut a1_rw).await?;
|
||||
assert_eq!(
|
||||
frame,
|
||||
RelayToClientMsg::Status(Status::SameEndpointIdConnected)
|
||||
);
|
||||
|
||||
// send packet and verify it is send to a2
|
||||
clients.send_packet(a_key, Datagrams::from(&data[..]), b_key, &metrics)?;
|
||||
@@ -394,8 +404,14 @@ mod tests {
|
||||
.await
|
||||
.std_context("timeout")?;
|
||||
|
||||
// a1 should be marked active again now, and receive sent messages
|
||||
// a1 should be marked active again now
|
||||
assert_eq!(clients.active_connection_id(a_key), Some(a1_conn_id));
|
||||
|
||||
// a1 is marked active again and should receive a health frame
|
||||
let frame = recv_frame(FrameType::Status, &mut a1_rw).await?;
|
||||
assert_eq!(frame, RelayToClientMsg::Status(Status::Healthy));
|
||||
|
||||
// a1 should receive packets
|
||||
clients.send_packet(a_key, Datagrams::from(&data[..]), b_key, &metrics)?;
|
||||
let frame = recv_frame(FrameType::RelayToClientDatagram, &mut a1_rw).await?;
|
||||
assert_eq!(
|
||||
|
||||
@@ -36,7 +36,7 @@ use crate::{
|
||||
KeyCache,
|
||||
defaults::{DEFAULT_KEY_CACHE_CAPACITY, timeouts::SERVER_WRITE_TIMEOUT},
|
||||
http::{
|
||||
CLIENT_AUTH_HEADER, RELAY_PATH, RELAY_PROTOCOL_VERSION, SUPPORTED_WEBSOCKET_VERSION,
|
||||
CLIENT_AUTH_HEADER, ProtocolVersion, RELAY_PATH, SUPPORTED_WEBSOCKET_VERSION,
|
||||
WEBSOCKET_UPGRADE_PROTOCOL,
|
||||
},
|
||||
protos::{
|
||||
@@ -542,7 +542,7 @@ enum RelayUpgradeReqError {
|
||||
"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,
|
||||
we_support: String,
|
||||
you_support: String,
|
||||
},
|
||||
}
|
||||
@@ -596,16 +596,17 @@ impl RelayServiceWithNotify {
|
||||
details: "header value is not ascii".to_string()
|
||||
})
|
||||
})?;
|
||||
let supports_our_version = subprotocols
|
||||
.split_whitespace()
|
||||
.any(|p| p == RELAY_PROTOCOL_VERSION);
|
||||
ensure!(
|
||||
supports_our_version,
|
||||
RelayUpgradeReqError::UnsupportedRelayVersion {
|
||||
we_support: RELAY_PROTOCOL_VERSION,
|
||||
you_support: subprotocols.to_string()
|
||||
}
|
||||
);
|
||||
let protocol_version = subprotocols
|
||||
.split(",")
|
||||
.map(|s| s.trim())
|
||||
.filter_map(ProtocolVersion::match_from_str)
|
||||
.max()
|
||||
.ok_or_else(|| {
|
||||
e!(RelayUpgradeReqError::UnsupportedRelayVersion {
|
||||
we_support: ProtocolVersion::all_joined(),
|
||||
you_support: subprotocols.to_string()
|
||||
})
|
||||
})?;
|
||||
|
||||
let client_auth_header = req.headers().get(CLIENT_AUTH_HEADER).cloned();
|
||||
|
||||
@@ -624,7 +625,11 @@ impl RelayServiceWithNotify {
|
||||
if let Err(err) = this
|
||||
.service
|
||||
.0
|
||||
.relay_connection_handler(upgraded, client_auth_header)
|
||||
.relay_connection_handler(
|
||||
upgraded,
|
||||
client_auth_header,
|
||||
protocol_version,
|
||||
)
|
||||
.await
|
||||
{
|
||||
warn!("error accepting upgraded connection: {err:#}",);
|
||||
@@ -652,10 +657,7 @@ impl RelayServiceWithNotify {
|
||||
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(SEC_WEBSOCKET_PROTOCOL, protocol_version.to_header_value())
|
||||
.header(CONNECTION, "upgrade")
|
||||
.body(body_full("switching to websocket protocol"))
|
||||
.expect("valid body"))
|
||||
@@ -767,6 +769,7 @@ impl Inner {
|
||||
&self,
|
||||
upgraded: Upgraded,
|
||||
client_auth_header: Option<HeaderValue>,
|
||||
protocol_version: ProtocolVersion,
|
||||
) -> Result<(), ConnectionHandlerError> {
|
||||
debug!("relay_connection upgraded");
|
||||
let (io, read_buf) = downcast_upgrade(upgraded)?;
|
||||
@@ -774,7 +777,8 @@ impl Inner {
|
||||
return Err(e!(ConnectionHandlerError::BufferNotEmpty { buf: read_buf }));
|
||||
}
|
||||
|
||||
self.accept(io, client_auth_header).await?;
|
||||
self.accept(io, client_auth_header, protocol_version)
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -792,6 +796,7 @@ impl Inner {
|
||||
&self,
|
||||
io: MaybeTlsStream,
|
||||
client_auth_header: Option<HeaderValue>,
|
||||
protocol_version: ProtocolVersion,
|
||||
) -> Result<(), AcceptError> {
|
||||
trace!("accept: start");
|
||||
|
||||
@@ -829,6 +834,7 @@ impl Inner {
|
||||
stream: io,
|
||||
write_timeout: self.write_timeout,
|
||||
channel_capacity: PER_CLIENT_SEND_QUEUE_DEPTH,
|
||||
protocol_version,
|
||||
};
|
||||
trace!("accept: create client");
|
||||
let endpoint_id = client_conn_builder.endpoint_id;
|
||||
@@ -1279,6 +1285,43 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[traced_test]
|
||||
async fn test_subprotocol_negotiation_picks_latest() -> Result {
|
||||
let server = ServerBuilder::new("127.0.0.1:0".parse().unwrap())
|
||||
.spawn()
|
||||
.await?;
|
||||
let addr = server.addr();
|
||||
|
||||
for offered in [
|
||||
"iroh-relay-v2,iroh-relay-v1",
|
||||
"iroh-relay-v1,iroh-relay-v2",
|
||||
"baz, iroh-relay-v1, iroh-relay-v2, boo",
|
||||
"foo, iroh-relay-v2, bar",
|
||||
] {
|
||||
let ws_uri = format!("ws://{addr}{RELAY_PATH}");
|
||||
let (_stream, response) = tokio_websockets::ClientBuilder::new()
|
||||
.uri(&ws_uri)
|
||||
.expect("valid websocket URI")
|
||||
.add_header(
|
||||
SEC_WEBSOCKET_PROTOCOL,
|
||||
HeaderValue::from_str(offered).expect("valid subprotocol header value"),
|
||||
)
|
||||
.expect("header accepted by websocket client")
|
||||
.connect()
|
||||
.await
|
||||
.expect("websocket upgrade succeeds");
|
||||
let negotiated = response
|
||||
.headers()
|
||||
.get(SEC_WEBSOCKET_PROTOCOL)
|
||||
.expect("Sec-WebSocket-Protocol response header is present");
|
||||
assert_eq!(negotiated, "iroh-relay-v2", "offered={offered}");
|
||||
}
|
||||
|
||||
server.shutdown();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[traced_test]
|
||||
async fn test_https_clients_and_server() -> Result {
|
||||
@@ -1391,8 +1434,10 @@ mod tests {
|
||||
let public_key_a = key_a.public();
|
||||
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), None).await });
|
||||
let handler_task = tokio::spawn(async move {
|
||||
s.0.accept(MaybeTlsStream::Test(rw_a), None, Default::default())
|
||||
.await
|
||||
});
|
||||
let mut client_a = make_test_client(client_a, &key_a).await?;
|
||||
handler_task.await.std_context("join")??;
|
||||
|
||||
@@ -1401,8 +1446,10 @@ mod tests {
|
||||
let public_key_b = key_b.public();
|
||||
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), None).await });
|
||||
let handler_task = tokio::spawn(async move {
|
||||
s.0.accept(MaybeTlsStream::Test(rw_b), None, Default::default())
|
||||
.await
|
||||
});
|
||||
let mut client_b = make_test_client(client_b, &key_b).await?;
|
||||
handler_task.await.std_context("join")??;
|
||||
|
||||
@@ -1491,8 +1538,10 @@ mod tests {
|
||||
let public_key_a = key_a.public();
|
||||
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), None).await });
|
||||
let handler_task = tokio::spawn(async move {
|
||||
s.0.accept(MaybeTlsStream::Test(rw_a), None, Default::default())
|
||||
.await
|
||||
});
|
||||
let mut client_a = make_test_client(client_a, &key_a).await?;
|
||||
handler_task.await.std_context("join")??;
|
||||
|
||||
@@ -1501,8 +1550,10 @@ mod tests {
|
||||
let public_key_b = key_b.public();
|
||||
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), None).await });
|
||||
let handler_task = tokio::spawn(async move {
|
||||
s.0.accept(MaybeTlsStream::Test(rw_b), None, Default::default())
|
||||
.await
|
||||
});
|
||||
let mut client_b = make_test_client(client_b, &key_b).await?;
|
||||
handler_task.await.std_context("join")??;
|
||||
|
||||
@@ -1551,8 +1602,10 @@ mod tests {
|
||||
info!("Create client B and connect it to the server");
|
||||
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), None).await });
|
||||
let handler_task = tokio::spawn(async move {
|
||||
s.0.accept(MaybeTlsStream::Test(new_rw_b), None, Default::default())
|
||||
.await
|
||||
});
|
||||
let mut new_client_b = make_test_client(new_client_b, &key_b).await?;
|
||||
handler_task.await.std_context("join")??;
|
||||
|
||||
|
||||
@@ -42,7 +42,7 @@ use iroh_base::{EndpointId, RelayUrl, SecretKey};
|
||||
use iroh_relay::{
|
||||
self as relay, PingTracker,
|
||||
client::{Client, ConnectError, RecvError, SendError},
|
||||
protos::relay::{ClientToRelayMsg, Datagrams, RelayToClientMsg},
|
||||
protos::relay::{ClientToRelayMsg, Datagrams, RelayToClientMsg, Status},
|
||||
};
|
||||
use n0_error::{e, stack_error};
|
||||
use n0_future::{
|
||||
@@ -681,14 +681,19 @@ impl ActiveRelayActor {
|
||||
state.ping_tracker.pong_received(data);
|
||||
state.established = true;
|
||||
}
|
||||
RelayToClientMsg::Health { problem } => {
|
||||
warn!("Relay server reports problem: {problem}");
|
||||
}
|
||||
RelayToClientMsg::Status(status) => match status {
|
||||
Status::Healthy => info!("Relay server reports: {status}"),
|
||||
_ => warn!("Relay server reports problem: {status}"),
|
||||
},
|
||||
RelayToClientMsg::Restarting { .. } => {
|
||||
trace!("Ignoring {msg:?}")
|
||||
}
|
||||
_ => {
|
||||
warn!("Ignoring unknown relay message: {msg:?}")
|
||||
// Deprecated variants, kept for backwards compatibility with older relay protocol versions.
|
||||
RelayToClientMsg::Health { problem } => {
|
||||
warn!("Relay server reports problem: {problem}");
|
||||
}
|
||||
frame => {
|
||||
warn!("Ignoring unknown relay message: {frame:?}")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user