Skip to main content

stratum_node_cli/
origin.rs

1//! The node's canonical origin and the local address a tenant command
2//! reaches it on.
3
4use std::fmt;
5use std::net::Ipv6Addr;
6use std::str::FromStr;
7
8use crate::error::CliError;
9use crate::url::LoopbackUrl;
10
11/// The scheme of a canonical origin.
12#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
13#[non_exhaustive]
14pub enum Scheme {
15    /// `http://`: only for a node whose canonical origin is itself a local
16    /// plain-HTTP address, such as a test deployment.
17    Http,
18    /// `https://`: the public origin. The client has no TLS transport yet, so
19    /// it is reached through `--connect`.
20    Https,
21}
22
23impl Scheme {
24    /// Returns `http` or `https`.
25    pub fn as_str(self) -> &'static str {
26        match self {
27            Self::Http => "http",
28            Self::Https => "https",
29        }
30    }
31
32    /// Returns the port a URL of this scheme means when it names none.
33    fn default_port(self) -> u16 {
34        match self {
35            Self::Http => 80,
36            Self::Https => 443,
37        }
38    }
39}
40
41/// A node's canonical origin: the one origin every signed tenant URL names.
42///
43/// The gate refuses a signed URL that does not start with exactly this text,
44/// and a `Host` other than its authority, so the client keeps the origin in
45/// the single spelling the node's configuration allows: `http://` or
46/// `https://`, a lowercase DNS name, IPv4 literal or bracketed IPv6 literal
47/// in its RFC 5952 form, an optional port that is not the scheme's default,
48/// and no user information, path, query or fragment. A single trailing `/`
49/// is accepted and dropped.
50///
51/// # Examples
52///
53/// ```
54/// use stratum_node_cli::CanonicalOrigin;
55///
56/// # fn main() -> Result<(), stratum_node_cli::ParseOriginError> {
57/// let origin: CanonicalOrigin = "https://stratum.visionclaw.pro/".parse()?;
58/// assert_eq!(origin.as_str(), "https://stratum.visionclaw.pro");
59/// assert_eq!(origin.authority(), "stratum.visionclaw.pro");
60/// assert_eq!(origin.url("/pods/"), "https://stratum.visionclaw.pro/pods/");
61///
62/// assert!("https://Stratum.example".parse::<CanonicalOrigin>().is_err());
63/// assert!("https://stratum.example:443".parse::<CanonicalOrigin>().is_err());
64/// assert!("https://stratum.example/pods".parse::<CanonicalOrigin>().is_err());
65/// # Ok(())
66/// # }
67/// ```
68#[derive(Debug, Clone, PartialEq, Eq, Hash)]
69pub struct CanonicalOrigin {
70    scheme: Scheme,
71    host: String,
72    port: Option<u16>,
73}
74
75impl CanonicalOrigin {
76    /// Returns the scheme.
77    pub fn scheme(&self) -> Scheme {
78        self.scheme
79    }
80
81    /// Returns the host as written: a DNS name, an IPv4 literal or a
82    /// bracketed IPv6 literal.
83    pub fn host(&self) -> &str {
84        &self.host
85    }
86
87    /// Returns the port, the scheme's default when the origin names none.
88    pub fn port(&self) -> u16 {
89        self.port.unwrap_or_else(|| self.scheme.default_port())
90    }
91
92    /// Returns `<host>` or `<host>:<port>` exactly as the origin writes it:
93    /// the value of `Host` on every request to the gate.
94    pub fn authority(&self) -> String {
95        match self.port {
96            Some(port) => format!("{}:{port}", self.host),
97            None => self.host.clone(),
98        }
99    }
100
101    /// Returns the origin text, `<scheme>://<authority>`.
102    pub fn as_str(&self) -> String {
103        format!("{}://{}", self.scheme.as_str(), self.authority())
104    }
105
106    /// Returns the canonical URL of `path`, which should start with `/`:
107    /// the URL a tenant request is signed over.
108    pub fn url(&self, path: &str) -> String {
109        format!("{}{path}", self.as_str())
110    }
111}
112
113impl fmt::Display for CanonicalOrigin {
114    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
115        f.write_str(&self.as_str())
116    }
117}
118
119impl FromStr for CanonicalOrigin {
120    type Err = ParseOriginError;
121
122    fn from_str(text: &str) -> Result<Self, Self::Err> {
123        let (scheme, rest) = if let Some(rest) = text.strip_prefix("https://") {
124            (Scheme::Https, rest)
125        } else if let Some(rest) = text.strip_prefix("http://") {
126            (Scheme::Http, rest)
127        } else {
128            return Err(ParseOriginError::Scheme);
129        };
130        let authority = rest.strip_suffix('/').unwrap_or(rest);
131        if authority.contains(['/', '?', '#']) {
132            return Err(ParseOriginError::NotAnOrigin);
133        }
134        if authority.contains('@') {
135            return Err(ParseOriginError::UserInfo);
136        }
137        let (host, port_text) = if let Some(inner) = authority.strip_prefix('[') {
138            let (literal, after) = inner.split_once(']').ok_or(ParseOriginError::Host)?;
139            let canonical = literal
140                .parse::<Ipv6Addr>()
141                .is_ok_and(|addr| addr.to_string() == literal);
142            if !canonical {
143                return Err(ParseOriginError::Host);
144            }
145            let port = match after {
146                "" => None,
147                other => Some(other.strip_prefix(':').ok_or(ParseOriginError::Port)?),
148            };
149            (format!("[{literal}]"), port)
150        } else {
151            let (host, port) = match authority.split_once(':') {
152                Some((host, port)) => (host, Some(port)),
153                None => (authority, None),
154            };
155            if !is_dns_host(host) {
156                return Err(ParseOriginError::Host);
157            }
158            (host.to_owned(), port)
159        };
160        let port = match port_text {
161            None => None,
162            Some(digits) => {
163                let valid = !digits.is_empty()
164                    && digits.len() <= 5
165                    && digits.bytes().all(|b| b.is_ascii_digit())
166                    && !digits.starts_with('0');
167                let port = digits
168                    .parse::<u16>()
169                    .ok()
170                    .filter(|_| valid)
171                    .ok_or(ParseOriginError::Port)?;
172                if port == scheme.default_port() {
173                    return Err(ParseOriginError::DefaultPort);
174                }
175                Some(port)
176            }
177        };
178        Ok(Self { scheme, host, port })
179    }
180}
181
182/// Returns `true` for a lowercase DNS name or IPv4 literal: dot-separated
183/// labels of 1 to 63 characters from `a-z`, `0-9` and `-`, not starting or
184/// ending with `-`. The same rule as the node's `node.canonical_origin`.
185fn is_dns_host(host: &str) -> bool {
186    !host.is_empty()
187        && host.len() <= 253
188        && host.split('.').all(|label| {
189            !label.is_empty()
190                && label.len() <= 63
191                && !label.starts_with('-')
192                && !label.ends_with('-')
193                && label
194                    .bytes()
195                    .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-')
196        })
197}
198
199/// The reasons an origin is refused by [`CanonicalOrigin`].
200#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
201#[non_exhaustive]
202pub enum ParseOriginError {
203    /// The origin does not start with `http://` or `https://`.
204    #[error("origin must start with https:// or http://")]
205    Scheme,
206    /// The origin has a path, query or fragment.
207    #[error("origin must have no path, query or fragment")]
208    NotAnOrigin,
209    /// The origin carries user information.
210    #[error("origin must not contain user information")]
211    UserInfo,
212    /// The host is not a lowercase DNS name, an IPv4 literal or a canonical
213    /// bracketed IPv6 literal.
214    #[error("origin host must be a lowercase name or address (ipv6 in brackets, rfc 5952 form)")]
215    Host,
216    /// The port is not a number from 1 to 65535 without leading zeros.
217    #[error("origin port must be a number from 1 to 65535")]
218    Port,
219    /// The port is the scheme's default, which the canonical form omits.
220    #[error("origin must omit the scheme's default port")]
221    DefaultPort,
222}
223
224/// Where a tenant command sends its requests: the canonical origin it signs
225/// for, and the local plain-HTTP address it connects to.
226///
227/// The client has no TLS transport in Step 2. It opens plain HTTP to the
228/// connect address, sends `Host: <canonical authority>` and signs
229/// `<canonical origin><path>`, so the gate sees exactly the request it
230/// would see behind the public origin. The connect address must be a
231/// loopback literal (an address in `127.0.0.0/8`, `[::1]`, or `localhost`,
232/// which is dialled as `127.0.0.1` without a name lookup), because a signed
233/// request sent in clear text off the machine could be captured and spent.
234///
235/// # Examples
236///
237/// ```
238/// use stratum_node_cli::GateTarget;
239///
240/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
241/// let target = GateTarget::new(
242///     "https://stratum.visionclaw.pro".parse()?,
243///     Some("127.0.0.1:7461".parse()?),
244/// )?;
245/// assert_eq!(target.connect().authority(), "127.0.0.1:7461");
246///
247/// // The remote transport arrives with the public origin.
248/// assert!(GateTarget::new("https://stratum.visionclaw.pro".parse()?, None).is_err());
249///
250/// // A local http:// origin is reached at its own address.
251/// let local = GateTarget::new("http://127.0.0.1:7461".parse()?, None)?;
252/// assert_eq!(local.connect().authority(), "127.0.0.1:7461");
253/// # Ok(())
254/// # }
255/// ```
256#[derive(Debug, Clone, PartialEq, Eq)]
257pub struct GateTarget {
258    origin: CanonicalOrigin,
259    connect: LoopbackUrl,
260}
261
262impl GateTarget {
263    /// Builds a target from `--origin` and the optional `--connect`.
264    ///
265    /// # Errors
266    ///
267    /// [`CliError::Usage`] when an `https://` origin has no connect address
268    /// (the remote transport arrives with the public origin), when an
269    /// `http://` origin without one is not itself on a loopback address, or
270    /// when the connect address has a path.
271    pub fn new(origin: CanonicalOrigin, connect: Option<ConnectAddress>) -> Result<Self, CliError> {
272        let connect = match connect {
273            Some(address) => address.0,
274            None => match origin.scheme() {
275                Scheme::Https => {
276                    return Err(CliError::Usage(format!(
277                        "{origin} is an https:// origin and this client has no TLS transport yet: \
278                         the remote transport arrives with the public origin. Reach the gate on \
279                         this machine with --connect <host:port>"
280                    )))
281                }
282                Scheme::Http => format!("http://{}:{}", origin.host(), origin.port())
283                    .parse::<LoopbackUrl>()
284                    .map_err(|_| {
285                        CliError::Usage(format!(
286                            "{origin} is not a loopback address; pass --connect <host:port> with \
287                             a loopback address to reach the gate"
288                        ))
289                    })?,
290            },
291        };
292        Ok(Self { origin, connect })
293    }
294
295    /// Returns the canonical origin requests are signed for.
296    pub fn origin(&self) -> &CanonicalOrigin {
297        &self.origin
298    }
299
300    /// Returns the loopback address requests are sent to.
301    pub fn connect(&self) -> &LoopbackUrl {
302        &self.connect
303    }
304}
305
306/// A `--connect <host:port>` value: a loopback literal and an explicit
307/// port.
308///
309/// The host follows the rules of [`LoopbackUrl`]: a canonical IPv4 address
310/// in `127.0.0.0/8`, `[::1]` or `localhost`.
311///
312/// # Examples
313///
314/// ```
315/// use stratum_node_cli::ConnectAddress;
316///
317/// assert!("127.0.0.1:7461".parse::<ConnectAddress>().is_ok());
318/// assert!("[::1]:7461".parse::<ConnectAddress>().is_ok());
319/// assert!("127.0.0.1".parse::<ConnectAddress>().is_err());
320/// assert!("192.0.2.1:7461".parse::<ConnectAddress>().is_err());
321/// ```
322#[derive(Debug, Clone, PartialEq, Eq)]
323pub struct ConnectAddress(LoopbackUrl);
324
325impl ConnectAddress {
326    /// Returns `<host>:<port>`.
327    pub fn authority(&self) -> String {
328        self.0.authority()
329    }
330}
331
332impl fmt::Display for ConnectAddress {
333    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
334        f.write_str(&self.0.authority())
335    }
336}
337
338impl FromStr for ConnectAddress {
339    type Err = ParseConnectError;
340
341    fn from_str(text: &str) -> Result<Self, Self::Err> {
342        if text.contains('/') {
343            return Err(ParseConnectError);
344        }
345        let url: LoopbackUrl = format!("http://{text}")
346            .parse()
347            .map_err(|_| ParseConnectError)?;
348        // Equal only when the port was written and the host is canonical.
349        if url.authority() != text {
350            return Err(ParseConnectError);
351        }
352        Ok(Self(url))
353    }
354}
355
356/// A `--connect` value was not `<loopback host>:<port>`.
357#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
358#[error(
359    "connect address must be <host>:<port> with a host in 127.0.0.0/8 (such as 127.0.0.1), [::1] or localhost"
360)]
361#[non_exhaustive]
362pub struct ParseConnectError;
363
364#[cfg(test)]
365mod tests {
366    use super::*;
367
368    #[test]
369    fn origins_keep_one_spelling() {
370        for (text, canonical, authority) in [
371            ("https://a.example", "https://a.example", "a.example"),
372            ("https://a.example/", "https://a.example", "a.example"),
373            (
374                "https://a.example:8443",
375                "https://a.example:8443",
376                "a.example:8443",
377            ),
378            (
379                "http://127.0.0.1:7461",
380                "http://127.0.0.1:7461",
381                "127.0.0.1:7461",
382            ),
383            ("https://[::1]:9", "https://[::1]:9", "[::1]:9"),
384        ] {
385            let origin: CanonicalOrigin = text.parse().expect(text);
386            assert_eq!(origin.as_str(), canonical, "{text}");
387            assert_eq!(origin.authority(), authority, "{text}");
388        }
389        for bad in [
390            "ftp://a.example",
391            "https://A.example",
392            "https://a.example:443",
393            "http://a.example:80",
394            "https://a.example:0",
395            "https://a.example:08443",
396            "https://a.example/x",
397            "https://a.example?x",
398            "https://u@a.example",
399            "https://[0:0::1]",
400            "https://a..example",
401            "https://",
402        ] {
403            assert!(bad.parse::<CanonicalOrigin>().is_err(), "{bad}");
404        }
405    }
406
407    #[test]
408    fn https_without_connect_is_refused_and_http_needs_loopback() {
409        let https: CanonicalOrigin = "https://a.example".parse().expect("origin");
410        let err = GateTarget::new(https, None).expect_err("refused");
411        assert!(
412            err.to_string()
413                .contains("remote transport arrives with the public origin"),
414            "{err}"
415        );
416        let far: CanonicalOrigin = "http://a.example:7461".parse().expect("origin");
417        assert!(GateTarget::new(far, None).is_err());
418        let near: CanonicalOrigin = "http://localhost:7461".parse().expect("origin");
419        let target = GateTarget::new(near, None).expect("loopback");
420        assert_eq!(target.connect().connect_host(), "127.0.0.1");
421    }
422}