stratum-node-cli 0.1.0-alpha.3

The `stratum` client for Stratum pod nodes: operator key files, bootstrap, config, backup, invitations and members over the loopback API; join, pod access and export for tenants through the gate
Documentation
//! Loopback-only `http://` URLs in the one canonical form the node checks.

use std::fmt;
use std::net::Ipv4Addr;
use std::str::FromStr;

/// The non-IPv4 hosts the node's loopback request policy accepts in
/// `Host`; any IPv4 address in `127.0.0.0/8` is accepted as well.
const NAMED_LOOPBACK_HOSTS: [&str; 2] = ["[::1]", "localhost"];

/// The port assumed when a URL names none, the scheme default for `http`.
const DEFAULT_HTTP_PORT: u16 = 80;

/// A plain-HTTP URL whose host is a loopback literal, kept in canonical form.
///
/// Step 1 has no TLS, so the client refuses to talk to anything but the
/// local machine. The accepted hosts are exactly those the node accepts in
/// its `Host` header: any IPv4 address in `127.0.0.0/8` written in
/// canonical dotted-decimal form (four decimal octets, no leading zeros, so
/// `127.0.0.2` but not `127.1` or `127.000.0.1`), `[::1]` and `localhost`
/// (lowercase). `localhost` is never looked up: requests to it are
/// connected to `127.0.0.1` while `Host` and the signed URL keep
/// `localhost` (see [`connect_host`](Self::connect_host)).
/// The port is always explicit in the canonical form (`80` when omitted),
/// because the node rebuilds the URL it verifies signatures against as
/// `http://<Host header><path>` and the client sends `Host: <host>:<port>`.
///
/// A path is kept when present. Commands that talk to the API need a bare
/// origin ([`is_origin`](Self::is_origin)); `stratum sign-challenge` uses the
/// path as the exact claim URL. User information, queries, fragments,
/// percent signs, whitespace and other non-printable characters are refused.
///
/// # Examples
///
/// ```
/// use stratum_node_cli::LoopbackUrl;
///
/// # fn main() -> Result<(), stratum_node_cli::ParseUrlError> {
/// let url: LoopbackUrl = "http://localhost:7460/".parse()?;
/// assert_eq!(url.authority(), "localhost:7460");
/// assert!(url.is_origin());
/// assert_eq!(url.join("/readyz"), "http://localhost:7460/readyz");
///
/// assert!("http://127.0.0.2:7460".parse::<LoopbackUrl>().is_ok());
/// assert!("http://192.0.2.1:7460".parse::<LoopbackUrl>().is_err());
/// assert!("https://127.0.0.1:7460".parse::<LoopbackUrl>().is_err());
/// # Ok(())
/// # }
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct LoopbackUrl {
    host: String,
    port: u16,
    path: String,
}

impl LoopbackUrl {
    /// Returns the host literal: an address in `127.0.0.0/8`, `[::1]` or
    /// `localhost`.
    pub fn host(&self) -> &str {
        &self.host
    }

    /// Returns the address literal the client connects to: the host itself,
    /// except that `localhost` becomes `127.0.0.1`.
    ///
    /// `localhost` is not resolved, so neither `/etc/hosts` nor any
    /// resolver can send a request (or the bootstrap token) off the
    /// machine. `Host` and the signed URL still name `localhost`. A node
    /// listening only on `[::1]` must be addressed as `[::1]`.
    ///
    /// # Examples
    ///
    /// ```
    /// use stratum_node_cli::LoopbackUrl;
    ///
    /// # fn main() -> Result<(), stratum_node_cli::ParseUrlError> {
    /// let url: LoopbackUrl = "http://localhost:7460".parse()?;
    /// assert_eq!(url.connect_host(), "127.0.0.1");
    /// assert_eq!(url.authority(), "localhost:7460");
    /// # Ok(())
    /// # }
    /// ```
    pub fn connect_host(&self) -> &str {
        if self.host == "localhost" {
            "127.0.0.1"
        } else {
            &self.host
        }
    }

    /// Returns the port, `80` when the URL named none.
    pub fn port(&self) -> u16 {
        self.port
    }

    /// Returns `<host>:<port>`, the value the client sends as `Host`.
    pub fn authority(&self) -> String {
        format!("{}:{}", self.host, self.port)
    }

    /// Returns the path, empty for a bare origin. A lone `/` is dropped.
    pub fn path(&self) -> &str {
        &self.path
    }

    /// Returns `true` when the URL has no path beyond an optional `/`.
    pub fn is_origin(&self) -> bool {
        self.path.is_empty()
    }

    /// Returns `http://<host>:<port>` followed by `path`, ignoring any path
    /// this URL carries. `path` should start with `/`.
    pub fn join(&self, path: &str) -> String {
        format!("http://{}{path}", self.authority())
    }

    /// Returns this URL in canonical form, path included.
    pub fn to_url_string(&self) -> String {
        self.join(&self.path)
    }
}

impl fmt::Display for LoopbackUrl {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.to_url_string())
    }
}

impl FromStr for LoopbackUrl {
    type Err = ParseUrlError;

    /// Parses `http://<loopback host>[:<port>][<path>]`.
    fn from_str(text: &str) -> Result<Self, Self::Err> {
        let rest = text.strip_prefix("http://").ok_or(ParseUrlError::NotHttp)?;
        let (authority, path) = match rest.find('/') {
            Some(index) => rest.split_at(index),
            None => (rest, ""),
        };
        if authority.contains('@') {
            return Err(ParseUrlError::UserInfo);
        }
        let (host_text, port_text) = split_host_port(authority)?;
        if !is_loopback_host(host_text) {
            return Err(ParseUrlError::NotLoopback);
        }
        let port = match port_text {
            None => DEFAULT_HTTP_PORT,
            Some(digits) => parse_port(digits)?,
        };
        if !path
            .bytes()
            .all(|b| b.is_ascii_graphic() && !matches!(b, b'?' | b'#' | b'%'))
        {
            return Err(ParseUrlError::InvalidPath);
        }
        let path = if path == "/" { "" } else { path };
        Ok(Self {
            host: host_text.to_owned(),
            port,
            path: path.to_owned(),
        })
    }
}

/// Returns `true` for `[::1]`, `localhost` and a canonical dotted-decimal
/// IPv4 address in `127.0.0.0/8`.
///
/// The text must equal the address's own rendering, so abbreviated,
/// zero-padded or octal-looking forms are refused rather than rewritten:
/// the `Host` header and the signed URL carry the text exactly as given.
fn is_loopback_host(text: &str) -> bool {
    if NAMED_LOOPBACK_HOSTS.contains(&text) {
        return true;
    }
    text.parse::<Ipv4Addr>()
        .is_ok_and(|ip| ip.is_loopback() && ip.to_string() == text)
}

/// Splits an authority into host text and optional port digits.
fn split_host_port(authority: &str) -> Result<(&str, Option<&str>), ParseUrlError> {
    if authority.starts_with('[') {
        let end = authority.find(']').ok_or(ParseUrlError::NotLoopback)?;
        let (host, after) = authority.split_at(end + 1);
        return match after {
            "" => Ok((host, None)),
            _ => after
                .strip_prefix(':')
                .map(|port| (host, Some(port)))
                .ok_or(ParseUrlError::InvalidPort),
        };
    }
    Ok(match authority.split_once(':') {
        Some((host, port)) => (host, Some(port)),
        None => (authority, None),
    })
}

/// Parses 1 to 5 ASCII digits naming a port in `1..=65535`.
fn parse_port(digits: &str) -> Result<u16, ParseUrlError> {
    if digits.is_empty() || digits.len() > 5 || !digits.bytes().all(|b| b.is_ascii_digit()) {
        return Err(ParseUrlError::InvalidPort);
    }
    match digits.parse::<u16>() {
        Ok(0) | Err(_) => Err(ParseUrlError::InvalidPort),
        Ok(port) => Ok(port),
    }
}

/// The reasons a URL is refused by [`LoopbackUrl`].
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum ParseUrlError {
    /// The URL does not start with `http://`. Step 1 has no TLS.
    #[error("url must start with http:// (the loopback api has no tls)")]
    NotHttp,
    /// The host is not a canonical IPv4 address in `127.0.0.0/8`, `[::1]`
    /// or `localhost`.
    #[error("url host must be an address in 127.0.0.0/8 (such as 127.0.0.1), [::1] or localhost")]
    NotLoopback,
    /// The port is not a number from 1 to 65535.
    #[error("url port must be a number from 1 to 65535")]
    InvalidPort,
    /// The URL carries user information (`user@host`).
    #[error("url must not contain user information")]
    UserInfo,
    /// The path holds a query, fragment, percent sign, space or control
    /// character.
    #[error("url path must be printable ascii without query, fragment or percent-encoding")]
    InvalidPath,
}