mirror of
https://github.com/n0-computer/iroh.git
synced 2026-12-03 16:01:53 +00:00
feat(iroh-relay): keep the relay URL's path prefix (#4617)
<!-- Attention agents and contributors using AI, please see our AI policy before opening a PR: https://github.com/n0-computer/iroh/blob/main/AI_POLICY.md --> <!-- Any PRs violating this policy will be closed. --> <!-- As per our contributor guidelines, all PRs that do not link to an issue with the label `ready-for-pr` will be closed: https://github.com/n0-computer/iroh/blob/main/CONTRIBUTING.md --> ## Description Fixes: #2440 * Adds `RELAY_RELATIVE_PATH` (`"relay"`) and `RELAY_PROBE_RELATIVE_PATH` (`"ping"`), which join onto a relay URL that carries a path prefix (`https://example.com/prefix/`) instead of landing on the host's root. * `RELAY_PATH` and `RELAY_PROBE_PATH` keep their values and are deprecated. * The client and the HTTPS probe join the relative paths onto the relay URL with `Url::join`; the relay server routes `/{RELAY_RELATIVE_PATH}` and `/{RELAY_PROBE_RELATIVE_PATH}`. * `RelayUrl`'s `From<Url>` (and so `FromStr` and `Deserialize`) adds a trailing `/` to a path that lacks one, with an INFO message, so `https://example.com/prefix` works too. `iroh-base` now depends on `tracing` (with the `relay` feature). * Relay URLs without a path behave as before. ## Breaking Changes None. ## Notes & open questions A `RelayUrl` without the trailing slash, serialised before this change, gains it when read back. ## Change checklist - [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. --------- Co-authored-by: Floris Bruynooghe <flub@n0.computer>
This commit is contained in:
co-authored by
Floris Bruynooghe
parent
ebdaaefecc
commit
5b98ddbaeb
Generated
+2
-1
@@ -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",
|
||||
|
||||
@@ -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]
|
||||
|
||||
@@ -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<Url>` implementation.
|
||||
/// To create a [`RelayUrl`] use the `From<Url>` 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<Url>);
|
||||
|
||||
impl From<Url> 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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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"
|
||||
|
||||
@@ -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<Client, ConnectError> {
|
||||
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
|
||||
|
||||
+48
-2
@@ -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
|
||||
|
||||
@@ -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<Request<Incoming>> 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<String> =
|
||||
std::sync::LazyLock::new(|| format!("/{RELAY_PROBE_RELATIVE_PATH}"));
|
||||
ROUTE.as_str()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::{net::Ipv4Addr, sync::Arc, time::Duration};
|
||||
|
||||
@@ -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<Request<Incoming>> for RelayServiceWithNotify {
|
||||
|
||||
fn call(&self, req: Request<Incoming>) -> 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")
|
||||
|
||||
@@ -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?;
|
||||
|
||||
@@ -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<Incoming>, service: RelayService) -> Response<BytesBody> {
|
||||
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),
|
||||
|
||||
@@ -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<HttpsProbeReport, MeasureHttpsLatencyError> {
|
||||
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:
|
||||
|
||||
Reference in New Issue
Block a user