diff --git a/Cargo.lock b/Cargo.lock index 402774b3e2..b0cfe613d0 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2279,6 +2279,7 @@ dependencies = [ "serde", "serde_json", "serde_test", + "tracing", "url", "zeroize", ] @@ -2422,7 +2423,7 @@ dependencies = [ [[package]] name = "iroh-relay" -version = "1.4.1" +version = "1.5.0" dependencies = [ "axum", "blake3", diff --git a/iroh-base/Cargo.toml b/iroh-base/Cargo.toml index 9535de7a4b..155d5c25b3 100644 --- a/iroh-base/Cargo.toml +++ b/iroh-base/Cargo.toml @@ -25,6 +25,7 @@ rand = { version = "0.10", optional = true } serde = { version = "1", features = ["derive", "rc"] } n0-error = "1.0.0" zeroize = { version = "1.9", optional = true, features = ["derive"] } +tracing = { version = "0.1", optional = true } # wasm-in-browser dependencies [target.'cfg(all(target_family = "wasm", target_os = "unknown"))'.dependencies] @@ -55,6 +56,7 @@ key = [ relay = [ "dep:url", "dep:derive_more", + "dep:tracing", ] [package.metadata.docs.rs] diff --git a/iroh-base/src/relay_url.rs b/iroh-base/src/relay_url.rs index ef7195e6f7..e67e4d66a9 100644 --- a/iroh-base/src/relay_url.rs +++ b/iroh-base/src/relay_url.rs @@ -9,7 +9,9 @@ use url::Url; /// It is cheaply clonable, as the underlying type is wrapped into an `Arc`. The main type /// under the hood though is [`Url`]. /// -/// To create a [`RelayUrl`] use the `From` implementation. +/// To create a [`RelayUrl`] use the `From` implementation. It adds a trailing `/` to +/// a path that lacks one, so the relay's own paths are joined under it: `https://example.com/prefix` +/// becomes `https://example.com/prefix/`. Deserialising goes through it too. /// /// It is encouraged to use a fully-qualified DNS domain name in the URL. Meaning a DNS /// name which ends in a `.`, e.g, in `relay.example.com.`. Otherwise the DNS resolution of @@ -18,10 +20,16 @@ use url::Url; #[derive( Clone, derive_more::Display, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize, )] +#[serde(from = "Url")] pub struct RelayUrl(Arc); impl From for RelayUrl { - fn from(url: Url) -> Self { + fn from(mut url: Url) -> Self { + if !url.cannot_be_a_base() && !url.path().ends_with('/') { + let path = format!("{}/", url.path()); + url.set_path(&path); + tracing::info!(%url, "Added a trailing slash to the relay URL's path"); + } Self(Arc::new(url)) } } @@ -113,4 +121,30 @@ mod tests { let url3 = RelayUrl::from(Url::parse("https://example.com/").unwrap()); assert_eq!(url3.domain(), Some("example.com")); } + + #[test] + fn test_relay_url_path_trailing_slash() { + let url = RelayUrl::from(Url::parse("https://example.com/prefix").unwrap()); + assert_eq!(url.as_str(), "https://example.com/prefix/"); + + let url: RelayUrl = "https://example.com/a/b?x=1".parse().unwrap(); + assert_eq!(url.as_str(), "https://example.com/a/b/?x=1"); + + let url = RelayUrl::from(Url::parse("https://example.com/prefix/").unwrap()); + assert_eq!(url.as_str(), "https://example.com/prefix/"); + + let url = RelayUrl::from(Url::parse("https://example.com").unwrap()); + assert_eq!(url.as_str(), "https://example.com/"); + } + + #[test] + fn test_relay_url_deserialize_trailing_slash() { + let url: RelayUrl = serde_json::from_str(r#""https://example.com/prefix""#).unwrap(); + assert_eq!(url.as_str(), "https://example.com/prefix/"); + + let url = RelayUrl::from(Url::parse("https://example.com/prefix/").unwrap()); + let bytes = postcard::to_stdvec(&url).unwrap(); + let back: RelayUrl = postcard::from_bytes(&bytes).unwrap(); + assert_eq!(back, url); + } } diff --git a/iroh-relay/Cargo.toml b/iroh-relay/Cargo.toml index 295897799a..e8a816bbc1 100644 --- a/iroh-relay/Cargo.toml +++ b/iroh-relay/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "iroh-relay" -version = "1.4.1" +version = "1.5.0" edition = "2024" readme = "README.md" description = "Iroh's relay server and client" diff --git a/iroh-relay/src/client.rs b/iroh-relay/src/client.rs index a61890f2f6..a2ebc2f671 100644 --- a/iroh-relay/src/client.rs +++ b/iroh-relay/src/client.rs @@ -27,7 +27,7 @@ use url::Url; pub use self::conn::{RecvError, SendError}; use crate::{ KeyCache, - http::{ProtocolVersion, RELAY_PATH}, + http::{ProtocolVersion, RELAY_RELATIVE_PATH}, protos::{ handshake, relay::{ClientToRelayMsg, RelayToClientMsg}, @@ -264,8 +264,11 @@ impl ClientBuilder { protos::{handshake::KeyMaterialClientAuth, relay::MAX_FRAME_SIZE}, }; - let mut dial_url = (*self.url).clone(); - dial_url.set_path(RELAY_PATH); + let mut dial_url = self.url.join(RELAY_RELATIVE_PATH).map_err(|_| { + e!(ConnectError::InvalidRelayUrl { + url: (*self.url).clone() + }) + })?; // The relay URL is exchanged with the http(s) scheme in tickets and similar. // We need to use the ws:// or wss:// schemes when connecting with websockets, though. dial_url @@ -388,8 +391,11 @@ impl ClientBuilder { pub async fn connect(&self) -> Result { use crate::http::AUTH_TOKEN_URL_QUERY_PARAM; - let mut dial_url = (*self.url).clone(); - dial_url.set_path(RELAY_PATH); + let mut dial_url = self.url.join(RELAY_RELATIVE_PATH).map_err(|_| { + e!(ConnectError::InvalidRelayUrl { + url: (*self.url).clone() + }) + })?; // The relay URL is exchanged with the http(s) scheme in tickets and similar. // We need to use the ws:// or wss:// schemes when connecting with websockets, though. dial_url diff --git a/iroh-relay/src/http.rs b/iroh-relay/src/http.rs index be84cddb84..94dd0b215f 100644 --- a/iroh-relay/src/http.rs +++ b/iroh-relay/src/http.rs @@ -8,12 +8,31 @@ pub(crate) const WEBSOCKET_UPGRADE_PROTOCOL: &str = "websocket"; #[cfg(feature = "server")] // only used in the server for now pub(crate) const SUPPORTED_WEBSOCKET_VERSION: &str = "13"; -/// The HTTP path under which the relay accepts relaying connections -/// (over websockets and a custom upgrade protocol). +/// The HTTP path under which the relay accepts relaying connections. +/// +/// Relaying connections are made over websockets and a custom upgrade protocol. +#[deprecated( + since = "1.4.0", + note = "Use `RELAY_RELATIVE_PATH`, joined onto the relay URL" +)] pub const RELAY_PATH: &str = "/relay"; /// The HTTP path under which the relay allows doing latency queries for testing. +#[deprecated( + since = "1.4.0", + note = "Use `RELAY_PROBE_RELATIVE_PATH`, joined onto the relay URL" +)] pub const RELAY_PROBE_PATH: &str = "/ping"; +/// The path relaying connections are made on, relative to the relay URL. +/// +/// Clients join it onto the relay URL, so a relay served under a path prefix +/// keeps it: `https://example.com/prefix/` gives `https://example.com/prefix/relay`. +pub const RELAY_RELATIVE_PATH: &str = "relay"; +/// The path latency probes are made on, relative to the relay URL. +/// +/// It is joined onto the relay URL in the same way as [`RELAY_RELATIVE_PATH`]. +pub const RELAY_PROBE_RELATIVE_PATH: &str = "ping"; + /// The HTTP header name for relay client authentication pub const CLIENT_AUTH_HEADER: HeaderName = HeaderName::from_static("x-iroh-relay-client-auth-v1"); @@ -117,6 +136,33 @@ mod tests { use super::*; + #[test] + fn paths_join_onto_the_relay_url() { + let join = |base: &str, path| { + url::Url::parse(base) + .unwrap() + .join(path) + .unwrap() + .to_string() + }; + assert_eq!( + join("https://example.com", RELAY_RELATIVE_PATH), + "https://example.com/relay" + ); + assert_eq!( + join("https://example.com/", RELAY_PROBE_RELATIVE_PATH), + "https://example.com/ping" + ); + assert_eq!( + join("https://example.com/prefix/", RELAY_RELATIVE_PATH), + "https://example.com/prefix/relay" + ); + assert_eq!( + join("https://example.com/a/b/", RELAY_PROBE_RELATIVE_PATH), + "https://example.com/a/b/ping" + ); + } + #[test] fn all_is_exhaustive() { // `EnumCount::COUNT` is the actual variant count, derived at compile diff --git a/iroh-relay/src/server.rs b/iroh-relay/src/server.rs index b8206d8876..5720001306 100644 --- a/iroh-relay/src/server.rs +++ b/iroh-relay/src/server.rs @@ -57,7 +57,7 @@ use tracing::{Instrument, debug, error, info, info_span, instrument}; use self::http_server::{BytesBody, HyperError, HyperResult}; use crate::{ defaults::DEFAULT_KEY_CACHE_CAPACITY, - http::{AUTH_TOKEN_URL_QUERY_PARAM, ProtocolVersion, RELAY_PROBE_PATH}, + http::{AUTH_TOKEN_URL_QUERY_PARAM, ProtocolVersion, RELAY_PROBE_RELATIVE_PATH}, quic::server::{QuicServer, QuicSpawnError, ServerHandle as QuicServerHandle}, tls::CaTlsConfig, }; @@ -736,7 +736,7 @@ impl Server { .access(relay_config.access) .request_handler(Method::GET, "/", Box::new(root_handler)) .request_handler(Method::GET, "/index.html", Box::new(root_handler)) - .request_handler(Method::GET, RELAY_PROBE_PATH, Box::new(probe_handler)) + .request_handler(Method::GET, probe_route(), Box::new(probe_handler)) .request_handler(Method::GET, "/robots.txt", Box::new(robots_handler)) .request_handler(Method::GET, "/healthz", Box::new(healthz_handler)); if let Some(cfg) = relay_config.limits.client_rx { @@ -1187,6 +1187,17 @@ impl hyper::service::Service> for CaptivePortalService { } } +/// The route latency probes are served on: [`RELAY_PROBE_RELATIVE_PATH`] at the root. +/// +/// Built once and kept in a static only because [`Handlers`] keys its routes by +/// `&'static str`. Changing [`Handlers`] to take a `String` would remove the need +/// for this. +fn probe_route() -> &'static str { + static ROUTE: std::sync::LazyLock = + std::sync::LazyLock::new(|| format!("/{RELAY_PROBE_RELATIVE_PATH}")); + ROUTE.as_str() +} + #[cfg(test)] mod tests { use std::{net::Ipv4Addr, sync::Arc, time::Duration}; diff --git a/iroh-relay/src/server/http_server.rs b/iroh-relay/src/server/http_server.rs index 9f018cbf38..42786ece5e 100644 --- a/iroh-relay/src/server/http_server.rs +++ b/iroh-relay/src/server/http_server.rs @@ -40,7 +40,7 @@ use crate::{ KeyCache, defaults::{DEFAULT_KEY_CACHE_CAPACITY, timeouts::SERVER_WRITE_TIMEOUT}, http::{ - CLIENT_AUTH_HEADER, ProtocolVersion, RELAY_PATH, SUPPORTED_WEBSOCKET_VERSION, + CLIENT_AUTH_HEADER, ProtocolVersion, RELAY_RELATIVE_PATH, SUPPORTED_WEBSOCKET_VERSION, WEBSOCKET_UPGRADE_PROTOCOL, }, protos::{handshake, relay::MAX_FRAME_SIZE, streams::WsBytesFramed}, @@ -779,10 +779,9 @@ impl Service> for RelayServiceWithNotify { fn call(&self, req: Request) -> Self::Future { // Create a client if the request hits the relay endpoint. - if matches!( - (req.method(), req.uri().path()), - (&hyper::Method::GET, RELAY_PATH) - ) { + if req.method() == hyper::Method::GET + && req.uri().path().strip_prefix('/') == Some(RELAY_RELATIVE_PATH) + { let response = match self.handle_relay_ws_upgrade(req) { Ok(response) => Ok(response), // It's convention to send back the version(s) we *do* support @@ -1396,7 +1395,7 @@ mod tests { "baz, iroh-relay-v1, iroh-relay-v2, boo", "foo, iroh-relay-v2, bar", ] { - let ws_uri = format!("ws://{addr}{RELAY_PATH}"); + let ws_uri = format!("ws://{addr}/{RELAY_RELATIVE_PATH}"); let (_stream, response) = tokio_websockets::ClientBuilder::new() .uri(&ws_uri) .expect("valid websocket URI") diff --git a/iroh-relay/tests/relay_axum.rs b/iroh-relay/tests/relay_axum.rs index 7e6d8a4dd6..4b52eec69d 100644 --- a/iroh-relay/tests/relay_axum.rs +++ b/iroh-relay/tests/relay_axum.rs @@ -33,7 +33,7 @@ use iroh_dns::dns::DnsResolver; use iroh_relay::{ ExportKeyingMaterial, KeyCache, client::ClientBuilder, - http::{CLIENT_AUTH_HEADER, ProtocolVersion, RELAY_PATH, RELAY_PROBE_PATH}, + http::{CLIENT_AUTH_HEADER, ProtocolVersion, RELAY_PROBE_RELATIVE_PATH, RELAY_RELATIVE_PATH}, protos::{handshake, streams::StreamError}, server::{ AllowAll, ClientRequest, DynAccessControl, Metrics, client::Config, clients::Clients, @@ -70,8 +70,8 @@ impl RelayState { async fn serve_axum() -> Result<(SocketAddr, AbortOnDropHandle<()>)> { let state = RelayState::new(); let router = Router::new() - .route(RELAY_PATH, get(relay_handler)) - .route(RELAY_PROBE_PATH, get(ping_handler)) + .route(&format!("/{RELAY_RELATIVE_PATH}"), get(relay_handler)) + .route(&format!("/{RELAY_PROBE_RELATIVE_PATH}"), get(ping_handler)) .with_state(state); let listener = TcpListener::bind("127.0.0.1:0").await?; diff --git a/iroh-relay/tests/relay_hyper.rs b/iroh-relay/tests/relay_hyper.rs index 7dd452febf..bd1be2f4bf 100644 --- a/iroh-relay/tests/relay_hyper.rs +++ b/iroh-relay/tests/relay_hyper.rs @@ -21,7 +21,7 @@ use iroh_dns::dns::DnsResolver; use iroh_relay::{ KeyCache, client::ClientBuilder, - http::{RELAY_PATH, RELAY_PROBE_PATH}, + http::{RELAY_PROBE_RELATIVE_PATH, RELAY_RELATIVE_PATH}, server::{ AllowAll, Metrics, http_server::{BytesBody, Handlers, RelayService, RelayServiceWithNotify}, @@ -36,13 +36,13 @@ use rand::{RngExt, SeedableRng}; use tokio::{net::TcpListener, sync::Notify}; async fn dispatch(req: Request, service: RelayService) -> Response { - match (req.method(), req.uri().path()) { - (&Method::GET, RELAY_PROBE_PATH) => Response::builder() + match (req.method(), req.uri().path().strip_prefix('/')) { + (&Method::GET, Some(RELAY_PROBE_RELATIVE_PATH)) => Response::builder() .status(StatusCode::OK) .header(ACCESS_CONTROL_ALLOW_ORIGIN, "*") .body(Box::new(Full::new(Bytes::new())) as BytesBody) .expect("valid response"), - (&Method::GET, RELAY_PATH) => RelayServiceWithNotify::with_timeout( + (&Method::GET, Some(RELAY_RELATIVE_PATH)) => RelayServiceWithNotify::with_timeout( service, Arc::new(Notify::new()), Duration::from_secs(30), diff --git a/iroh/src/net_report/reportgen.rs b/iroh/src/net_report/reportgen.rs index d531901dea..4dc6b1db1a 100644 --- a/iroh/src/net_report/reportgen.rs +++ b/iroh/src/net_report/reportgen.rs @@ -30,7 +30,7 @@ use iroh_dns::dns::{DnsError, DnsResolver, StaggeredError}; #[cfg(not(wasm_browser))] use iroh_relay::quic::QuicClient; use iroh_relay::{ - RelayConfig, RelayMap, defaults::DEFAULT_RELAY_QUIC_PORT, http::RELAY_PROBE_PATH, + RelayConfig, RelayMap, defaults::DEFAULT_RELAY_QUIC_PORT, http::RELAY_PROBE_RELATIVE_PATH, }; use n0_error::{e, stack_error}; #[cfg(wasm_browser)] @@ -821,7 +821,7 @@ async fn run_https_probe( #[cfg(not(wasm_browser))] proxy_url: Option<&Url>, ) -> Result { trace!("HTTPS probe start"); - let url = relay.join(RELAY_PROBE_PATH)?; + let url = relay.join(RELAY_PROBE_RELATIVE_PATH)?; // This should also use same connection establishment as relay client itself, which // needs to be more configurable so users can do more crazy things: