iroh_relay/http.rs
1//! HTTP-specific constants for the relay server and client.
2
3use http::{HeaderName, HeaderValue};
4use n0_error::stack_error;
5
6#[cfg(feature = "server")]
7pub(crate) const WEBSOCKET_UPGRADE_PROTOCOL: &str = "websocket";
8#[cfg(feature = "server")] // only used in the server for now
9pub(crate) const SUPPORTED_WEBSOCKET_VERSION: &str = "13";
10
11/// The HTTP path under which the relay accepts relaying connections.
12///
13/// Relaying connections are made over websockets and a custom upgrade protocol.
14#[deprecated(
15 since = "1.4.0",
16 note = "Use `RELAY_RELATIVE_PATH`, joined onto the relay URL"
17)]
18pub const RELAY_PATH: &str = "/relay";
19/// The HTTP path under which the relay allows doing latency queries for testing.
20#[deprecated(
21 since = "1.4.0",
22 note = "Use `RELAY_PROBE_RELATIVE_PATH`, joined onto the relay URL"
23)]
24pub const RELAY_PROBE_PATH: &str = "/ping";
25
26/// The path relaying connections are made on, relative to the relay URL.
27///
28/// Clients join it onto the relay URL, so a relay served under a path prefix
29/// keeps it: `https://example.com/prefix/` gives `https://example.com/prefix/relay`.
30pub const RELAY_RELATIVE_PATH: &str = "relay";
31/// The path latency probes are made on, relative to the relay URL.
32///
33/// It is joined onto the relay URL in the same way as [`RELAY_RELATIVE_PATH`].
34pub const RELAY_PROBE_RELATIVE_PATH: &str = "ping";
35
36/// The HTTP header name for relay client authentication
37pub const CLIENT_AUTH_HEADER: HeaderName = HeaderName::from_static("x-iroh-relay-client-auth-v1");
38
39/// The URL query parameter name used to pass the authorization token when
40/// HTTP headers are not available (notably, in browsers).
41#[cfg(any(wasm_browser, feature = "server"))]
42pub(crate) const AUTH_TOKEN_URL_QUERY_PARAM: &str = "token";
43
44/// The relay protocol version negotiated between client and server.
45///
46/// Sent as the websocket sub-protocol header `Sec-Websocket-Protocol` from
47/// the client. The server picks the best supported version and replies with it.
48///
49/// Variants are ordered by preference (highest first), so the [`Ord`] impl
50/// can be used during negotiation to pick the best version.
51#[derive(
52 Clone,
53 Copy,
54 Debug,
55 PartialEq,
56 Eq,
57 PartialOrd,
58 Ord,
59 Default,
60 strum::EnumString,
61 strum::Display,
62 strum::IntoStaticStr,
63)]
64// Only used by the `all_is_exhaustive` to validate that `Self::ALL` is up to date.
65#[cfg_attr(test, derive(strum::EnumCount, test_strategy::Arbitrary))]
66#[strum(parse_err_ty = UnsupportedRelayProtocolVersion, parse_err_fn = strum_err_fn)]
67#[non_exhaustive]
68// Needs to be ordered with newest version last, so that the `Ord` impl orders by latest version as max.
69pub enum ProtocolVersion {
70 /// Version 1 (the only version supported until iroh 0.98.0)
71 #[strum(serialize = "iroh-relay-v1")]
72 V1,
73 /// Version 2 (added in iroh 0.98.0)
74 /// - Removed `Health` frame (id 11)
75 /// - Added `Status` frame (id 13)
76 #[default]
77 #[strum(serialize = "iroh-relay-v2")]
78 V2,
79}
80
81impl ProtocolVersion {
82 /// All supported protocol versions, in order of preference (newest first).
83 //
84 // This list needs to be maintained by hand; the `all_is_exhaustive` test in this module
85 // asserts that the length matches the actual variant count via a `cfg(test)`-only
86 // `strum::EnumCount` derive.
87 pub const ALL: &'static [Self] = &[Self::V2, Self::V1];
88
89 /// Returns an iterator of all supported protocol version identifiers, in order of preference.
90 pub fn all() -> impl Iterator<Item = &'static str> {
91 Self::ALL.iter().map(ProtocolVersion::to_str)
92 }
93
94 /// Returns a comma-separated string of all supported protocol version identifiers.
95 pub fn all_joined() -> String {
96 Self::all().collect::<Vec<_>>().join(", ")
97 }
98
99 /// Returns all supported protocol versions in a comma-separated string as an HTTP header value.
100 pub fn all_as_header_value() -> HeaderValue {
101 HeaderValue::from_bytes(Self::all_joined().as_bytes()).expect("valid header name")
102 }
103
104 /// Returns the protocol version identifier string.
105 pub fn to_str(&self) -> &'static str {
106 self.into()
107 }
108
109 /// Tries to parse a [`ProtocolVersion`] from `s`.
110 ///
111 /// Returns `None` if `s` is not a valid protocol version string.
112 pub fn match_from_str(s: &str) -> Option<Self> {
113 Self::try_from(s).ok()
114 }
115
116 /// Returns this protocol version as an HTTP header value.
117 pub fn to_header_value(&self) -> HeaderValue {
118 HeaderValue::from_static(self.to_str())
119 }
120}
121
122/// Error returned when the relay protocol version is not recognized.
123#[stack_error(derive)]
124#[error("Relay protocol version is not supported")]
125pub struct UnsupportedRelayProtocolVersion;
126
127fn strum_err_fn(_item: &str) -> UnsupportedRelayProtocolVersion {
128 UnsupportedRelayProtocolVersion::new()
129}
130
131#[cfg(test)]
132mod tests {
133 use std::str::FromStr;
134
135 use strum::EnumCount;
136
137 use super::*;
138
139 #[test]
140 fn paths_join_onto_the_relay_url() {
141 let join = |base: &str, path| {
142 url::Url::parse(base)
143 .unwrap()
144 .join(path)
145 .unwrap()
146 .to_string()
147 };
148 assert_eq!(
149 join("https://example.com", RELAY_RELATIVE_PATH),
150 "https://example.com/relay"
151 );
152 assert_eq!(
153 join("https://example.com/", RELAY_PROBE_RELATIVE_PATH),
154 "https://example.com/ping"
155 );
156 assert_eq!(
157 join("https://example.com/prefix/", RELAY_RELATIVE_PATH),
158 "https://example.com/prefix/relay"
159 );
160 assert_eq!(
161 join("https://example.com/a/b/", RELAY_PROBE_RELATIVE_PATH),
162 "https://example.com/a/b/ping"
163 );
164 }
165
166 #[test]
167 fn all_is_exhaustive() {
168 // `EnumCount::COUNT` is the actual variant count, derived at compile
169 // time. If a new variant is added without being listed in `ALL`, the
170 // lengths diverge and this test fails.
171 assert_eq!(ProtocolVersion::ALL.len(), ProtocolVersion::COUNT);
172 for &v in ProtocolVersion::ALL {
173 assert_eq!(ProtocolVersion::from_str(v.to_str()).unwrap(), v);
174 }
175 }
176}