Skip to main content

stratum_node_cli/
url.rs

1//! Loopback-only `http://` URLs in the one canonical form the node checks.
2
3use std::fmt;
4use std::net::Ipv4Addr;
5use std::str::FromStr;
6
7/// The non-IPv4 hosts the node's loopback request policy accepts in
8/// `Host`; any IPv4 address in `127.0.0.0/8` is accepted as well.
9const NAMED_LOOPBACK_HOSTS: [&str; 2] = ["[::1]", "localhost"];
10
11/// The port assumed when a URL names none, the scheme default for `http`.
12const DEFAULT_HTTP_PORT: u16 = 80;
13
14/// A plain-HTTP URL whose host is a loopback literal, kept in canonical form.
15///
16/// Step 1 has no TLS, so the client refuses to talk to anything but the
17/// local machine. The accepted hosts are exactly those the node accepts in
18/// its `Host` header: any IPv4 address in `127.0.0.0/8` written in
19/// canonical dotted-decimal form (four decimal octets, no leading zeros, so
20/// `127.0.0.2` but not `127.1` or `127.000.0.1`), `[::1]` and `localhost`
21/// (lowercase). `localhost` is never looked up: requests to it are
22/// connected to `127.0.0.1` while `Host` and the signed URL keep
23/// `localhost` (see [`connect_host`](Self::connect_host)).
24/// The port is always explicit in the canonical form (`80` when omitted),
25/// because the node rebuilds the URL it verifies signatures against as
26/// `http://<Host header><path>` and the client sends `Host: <host>:<port>`.
27///
28/// A path is kept when present. Commands that talk to the API need a bare
29/// origin ([`is_origin`](Self::is_origin)); `stratum sign-challenge` uses the
30/// path as the exact claim URL. User information, queries, fragments,
31/// percent signs, whitespace and other non-printable characters are refused.
32///
33/// # Examples
34///
35/// ```
36/// use stratum_node_cli::LoopbackUrl;
37///
38/// # fn main() -> Result<(), stratum_node_cli::ParseUrlError> {
39/// let url: LoopbackUrl = "http://localhost:7460/".parse()?;
40/// assert_eq!(url.authority(), "localhost:7460");
41/// assert!(url.is_origin());
42/// assert_eq!(url.join("/readyz"), "http://localhost:7460/readyz");
43///
44/// assert!("http://127.0.0.2:7460".parse::<LoopbackUrl>().is_ok());
45/// assert!("http://192.0.2.1:7460".parse::<LoopbackUrl>().is_err());
46/// assert!("https://127.0.0.1:7460".parse::<LoopbackUrl>().is_err());
47/// # Ok(())
48/// # }
49/// ```
50#[derive(Debug, Clone, PartialEq, Eq, Hash)]
51pub struct LoopbackUrl {
52    host: String,
53    port: u16,
54    path: String,
55}
56
57impl LoopbackUrl {
58    /// Returns the host literal: an address in `127.0.0.0/8`, `[::1]` or
59    /// `localhost`.
60    pub fn host(&self) -> &str {
61        &self.host
62    }
63
64    /// Returns the address literal the client connects to: the host itself,
65    /// except that `localhost` becomes `127.0.0.1`.
66    ///
67    /// `localhost` is not resolved, so neither `/etc/hosts` nor any
68    /// resolver can send a request (or the bootstrap token) off the
69    /// machine. `Host` and the signed URL still name `localhost`. A node
70    /// listening only on `[::1]` must be addressed as `[::1]`.
71    ///
72    /// # Examples
73    ///
74    /// ```
75    /// use stratum_node_cli::LoopbackUrl;
76    ///
77    /// # fn main() -> Result<(), stratum_node_cli::ParseUrlError> {
78    /// let url: LoopbackUrl = "http://localhost:7460".parse()?;
79    /// assert_eq!(url.connect_host(), "127.0.0.1");
80    /// assert_eq!(url.authority(), "localhost:7460");
81    /// # Ok(())
82    /// # }
83    /// ```
84    pub fn connect_host(&self) -> &str {
85        if self.host == "localhost" {
86            "127.0.0.1"
87        } else {
88            &self.host
89        }
90    }
91
92    /// Returns the port, `80` when the URL named none.
93    pub fn port(&self) -> u16 {
94        self.port
95    }
96
97    /// Returns `<host>:<port>`, the value the client sends as `Host`.
98    pub fn authority(&self) -> String {
99        format!("{}:{}", self.host, self.port)
100    }
101
102    /// Returns the path, empty for a bare origin. A lone `/` is dropped.
103    pub fn path(&self) -> &str {
104        &self.path
105    }
106
107    /// Returns `true` when the URL has no path beyond an optional `/`.
108    pub fn is_origin(&self) -> bool {
109        self.path.is_empty()
110    }
111
112    /// Returns `http://<host>:<port>` followed by `path`, ignoring any path
113    /// this URL carries. `path` should start with `/`.
114    pub fn join(&self, path: &str) -> String {
115        format!("http://{}{path}", self.authority())
116    }
117
118    /// Returns this URL in canonical form, path included.
119    pub fn to_url_string(&self) -> String {
120        self.join(&self.path)
121    }
122}
123
124impl fmt::Display for LoopbackUrl {
125    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
126        f.write_str(&self.to_url_string())
127    }
128}
129
130impl FromStr for LoopbackUrl {
131    type Err = ParseUrlError;
132
133    /// Parses `http://<loopback host>[:<port>][<path>]`.
134    fn from_str(text: &str) -> Result<Self, Self::Err> {
135        let rest = text.strip_prefix("http://").ok_or(ParseUrlError::NotHttp)?;
136        let (authority, path) = match rest.find('/') {
137            Some(index) => rest.split_at(index),
138            None => (rest, ""),
139        };
140        if authority.contains('@') {
141            return Err(ParseUrlError::UserInfo);
142        }
143        let (host_text, port_text) = split_host_port(authority)?;
144        if !is_loopback_host(host_text) {
145            return Err(ParseUrlError::NotLoopback);
146        }
147        let port = match port_text {
148            None => DEFAULT_HTTP_PORT,
149            Some(digits) => parse_port(digits)?,
150        };
151        if !path
152            .bytes()
153            .all(|b| b.is_ascii_graphic() && !matches!(b, b'?' | b'#' | b'%'))
154        {
155            return Err(ParseUrlError::InvalidPath);
156        }
157        let path = if path == "/" { "" } else { path };
158        Ok(Self {
159            host: host_text.to_owned(),
160            port,
161            path: path.to_owned(),
162        })
163    }
164}
165
166/// Returns `true` for `[::1]`, `localhost` and a canonical dotted-decimal
167/// IPv4 address in `127.0.0.0/8`.
168///
169/// The text must equal the address's own rendering, so abbreviated,
170/// zero-padded or octal-looking forms are refused rather than rewritten:
171/// the `Host` header and the signed URL carry the text exactly as given.
172fn is_loopback_host(text: &str) -> bool {
173    if NAMED_LOOPBACK_HOSTS.contains(&text) {
174        return true;
175    }
176    text.parse::<Ipv4Addr>()
177        .is_ok_and(|ip| ip.is_loopback() && ip.to_string() == text)
178}
179
180/// Splits an authority into host text and optional port digits.
181fn split_host_port(authority: &str) -> Result<(&str, Option<&str>), ParseUrlError> {
182    if authority.starts_with('[') {
183        let end = authority.find(']').ok_or(ParseUrlError::NotLoopback)?;
184        let (host, after) = authority.split_at(end + 1);
185        return match after {
186            "" => Ok((host, None)),
187            _ => after
188                .strip_prefix(':')
189                .map(|port| (host, Some(port)))
190                .ok_or(ParseUrlError::InvalidPort),
191        };
192    }
193    Ok(match authority.split_once(':') {
194        Some((host, port)) => (host, Some(port)),
195        None => (authority, None),
196    })
197}
198
199/// Parses 1 to 5 ASCII digits naming a port in `1..=65535`.
200fn parse_port(digits: &str) -> Result<u16, ParseUrlError> {
201    if digits.is_empty() || digits.len() > 5 || !digits.bytes().all(|b| b.is_ascii_digit()) {
202        return Err(ParseUrlError::InvalidPort);
203    }
204    match digits.parse::<u16>() {
205        Ok(0) | Err(_) => Err(ParseUrlError::InvalidPort),
206        Ok(port) => Ok(port),
207    }
208}
209
210/// The reasons a URL is refused by [`LoopbackUrl`].
211#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
212#[non_exhaustive]
213pub enum ParseUrlError {
214    /// The URL does not start with `http://`. Step 1 has no TLS.
215    #[error("url must start with http:// (the loopback api has no tls)")]
216    NotHttp,
217    /// The host is not a canonical IPv4 address in `127.0.0.0/8`, `[::1]`
218    /// or `localhost`.
219    #[error("url host must be an address in 127.0.0.0/8 (such as 127.0.0.1), [::1] or localhost")]
220    NotLoopback,
221    /// The port is not a number from 1 to 65535.
222    #[error("url port must be a number from 1 to 65535")]
223    InvalidPort,
224    /// The URL carries user information (`user@host`).
225    #[error("url must not contain user information")]
226    UserInfo,
227    /// The path holds a query, fragment, percent sign, space or control
228    /// character.
229    #[error("url path must be printable ascii without query, fragment or percent-encoding")]
230    InvalidPath,
231}