stratum-node-cli 0.1.0-alpha.1

The `stratum` operator client for Stratum pod nodes: operator key files, bootstrap claim, signed config apply, audit checkpoint and backup over the loopback API
Documentation
//! A small blocking HTTP client for the node's loopback API.

use std::time::{Duration, SystemTime, UNIX_EPOCH};

use serde::de::DeserializeOwned;
use stratum_node_core::{ExpectedRequest, NostrSecretKey, UnixTime};

use crate::error::CliError;
use crate::output::sanitize;
use crate::url::LoopbackUrl;
use crate::wire::ErrorEnvelope;

/// The largest response body read. A preview carries the edited text and a
/// diff of it, each bounded by the 256 KiB document limit, plus JSON
/// escaping, so 4 MiB leaves ample room while bounding memory.
pub(crate) const MAX_RESPONSE_BYTES: u64 = 4 * 1024 * 1024;

/// The time allowed for one whole request and response.
const REQUEST_TIMEOUT: Duration = Duration::from_secs(30);

/// The `User-Agent` sent with every request.
const USER_AGENT: &str = concat!("stratum/", env!("CARGO_PKG_VERSION"));

/// The media type of every request and response body.
const JSON: &str = "application/json";

/// The header carrying the bootstrap token on the claim request.
pub(crate) const BOOTSTRAP_TOKEN_HEADER: &str = "Stratum-Bootstrap-Token";

/// A response: its status and at most [`MAX_RESPONSE_BYTES`] of body.
#[derive(Debug)]
pub(crate) struct Response {
    pub(crate) status: u16,
    pub(crate) body: Vec<u8>,
}

impl Response {
    /// Parses a 2xx body as `T`, or turns any other status into the
    /// matching [`CliError`].
    pub(crate) fn into_json<T: DeserializeOwned>(self) -> Result<(T, serde_json::Value), CliError> {
        if !(200..300).contains(&self.status) {
            return Err(self.into_error());
        }
        self.parse()
    }

    /// Parses the body as `T` and as a generic JSON value, whatever the
    /// status.
    pub(crate) fn parse<T: DeserializeOwned>(&self) -> Result<(T, serde_json::Value), CliError> {
        let value: serde_json::Value = serde_json::from_slice(&self.body).map_err(|_| {
            CliError::Protocol(format!("HTTP {} with a body that is not JSON", self.status))
        })?;
        let typed = T::deserialize(&value).map_err(|err| {
            CliError::Protocol(format!(
                "HTTP {} body does not match the API contract: {}",
                self.status,
                sanitize(&err.to_string())
            ))
        })?;
        Ok((typed, value))
    }

    /// Turns a non-success response into a [`CliError::Server`], or a
    /// [`CliError::Protocol`] when the body is not the error envelope.
    pub(crate) fn into_error(self) -> CliError {
        match serde_json::from_slice::<ErrorEnvelope>(&self.body) {
            Ok(envelope) => {
                let details = envelope
                    .error
                    .errors
                    .iter()
                    .chain(&envelope.errors)
                    .map(|entry| match &entry.path {
                        Some(path) => sanitize(&format!("{path}: {}", entry.message)),
                        None => sanitize(&entry.message),
                    })
                    .collect();
                CliError::Server {
                    status: self.status,
                    code: sanitize(&envelope.error.code),
                    message: sanitize(&envelope.error.message),
                    details,
                }
            }
            Err(_) => {
                CliError::Protocol(format!("HTTP {} without the error envelope", self.status))
            }
        }
    }
}

/// A client bound to one loopback origin.
///
/// Proxies, redirects, compression and TLS are all off: requests go
/// straight to the loopback socket, and a signed request is never replayed
/// to another URL. `Host` is always sent as `<host>:<port>` so the URL the
/// node rebuilds from it equals the URL that was signed.
///
/// The URL handed to ureq names the address literal from
/// [`LoopbackUrl::connect_host`], never `localhost`, so no name lookup
/// happens: the default resolver turns a literal into its address without
/// asking the system resolver. The signed URL and `Host` keep the host as
/// the operator wrote it.
#[derive(Debug)]
pub(crate) struct Client {
    origin: LoopbackUrl,
    agent: ureq::Agent,
}

impl Client {
    /// Builds a client for `origin`; its path, if any, is ignored.
    pub(crate) fn new(origin: LoopbackUrl) -> Self {
        let config = ureq::Agent::config_builder()
            .proxy(None)
            .max_redirects(0)
            .http_status_as_error(false)
            .https_only(false)
            .user_agent(USER_AGENT)
            .accept(JSON)
            .accept_encoding(ureq::config::AutoHeaderValue::None)
            .timeout_global(Some(REQUEST_TIMEOUT))
            .max_idle_connections(0)
            .build();
        Self {
            origin,
            agent: ureq::Agent::new_with_config(config),
        }
    }

    /// Returns the absolute URL of `path` on this origin, as signed and as
    /// the node rebuilds it from `Host`.
    pub(crate) fn url(&self, path: &str) -> String {
        self.origin.join(path)
    }

    /// Returns the URL to dial for `url`, a URL on this origin: the same
    /// path on the address literal the origin connects to.
    fn connect_url(&self, url: &str) -> Result<String, CliError> {
        let origin = self.origin.join("");
        let path = url
            .strip_prefix(&origin)
            .filter(|path| path.starts_with('/'))
            .ok_or_else(|| {
                CliError::Local(format!(
                    "refusing to send a request for {} through a client for {origin}",
                    sanitize(url)
                ))
            })?;
        Ok(connect_url(&self.origin, path))
    }

    /// Sends `GET path`, signed by `key` when given.
    pub(crate) fn get(
        &self,
        path: &str,
        key: Option<&NostrSecretKey>,
    ) -> Result<Response, CliError> {
        let url = self.url(path);
        let mut request = self
            .agent
            .get(connect_url(&self.origin, path))
            .header("Host", self.origin.authority());
        if let Some(key) = key {
            let authorization = sign(key, "GET", &url, None)?;
            request = request.header("Authorization", authorization);
        }
        Self::finish(&url, request.call())
    }

    /// Sends `POST path` with a JSON `body`, signed by `key` when given.
    pub(crate) fn post(
        &self,
        path: &str,
        body: &[u8],
        key: Option<&NostrSecretKey>,
    ) -> Result<Response, CliError> {
        let url = self.url(path);
        let authorization = match key {
            Some(key) => Some(sign(key, "POST", &url, Some(body))?),
            None => None,
        };
        self.post_raw(&url, body, authorization.as_deref(), None)
    }

    /// Sends `POST url` with `body` and the given headers exactly; used for
    /// the claim, whose URL and headers may come from a resume file.
    pub(crate) fn post_raw(
        &self,
        url: &str,
        body: &[u8],
        authorization: Option<&str>,
        bootstrap_token: Option<&str>,
    ) -> Result<Response, CliError> {
        let mut request = self
            .agent
            .post(self.connect_url(url)?)
            .header("Host", self.origin.authority())
            .header("Content-Type", JSON);
        if let Some(value) = authorization {
            request = request.header("Authorization", value);
        }
        if let Some(value) = bootstrap_token {
            request = request.header(BOOTSTRAP_TOKEN_HEADER, value);
        }
        Self::finish(url, request.send(body))
    }

    /// Reads a capped body and maps transport errors.
    fn finish(
        url: &str,
        result: Result<ureq::http::Response<ureq::Body>, ureq::Error>,
    ) -> Result<Response, CliError> {
        let mut response = result.map_err(|err| transport_error(url, &err))?;
        let status = response.status().as_u16();
        let body = response
            .body_mut()
            .with_config()
            .limit(MAX_RESPONSE_BYTES)
            .read_to_vec()
            .map_err(|err| match err {
                ureq::Error::BodyExceedsLimit(_) => CliError::Protocol(format!(
                    "response body is larger than {MAX_RESPONSE_BYTES} bytes"
                )),
                other => transport_error(url, &other),
            })?;
        Ok(Response { status, body })
    }
}

/// Returns `http://<connect host>:<port><path>` for `origin`.
fn connect_url(origin: &LoopbackUrl, path: &str) -> String {
    format!("http://{}:{}{path}", origin.connect_host(), origin.port())
}

/// Maps a transport failure; nothing but the URL and the error kind is kept.
fn transport_error(url: &str, err: &ureq::Error) -> CliError {
    let message = match err {
        ureq::Error::Timeout(_) => "timed out".to_owned(),
        ureq::Error::ConnectionFailed => "connection failed".to_owned(),
        ureq::Error::HostNotFound => "host not found".to_owned(),
        ureq::Error::Io(io) => io.kind().to_string(),
        other => return CliError::Protocol(sanitize(&other.to_string())),
    };
    CliError::Unreachable {
        url: url.to_owned(),
        message,
    }
}

/// Returns the current time as Unix seconds.
pub(crate) fn now() -> Result<UnixTime, CliError> {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map(|elapsed| UnixTime::from_secs(elapsed.as_secs()))
        .map_err(|_| CliError::Local("the system clock is before 1970".to_owned()))
}

/// Returns 32 bytes from the operating system's random source.
pub(crate) fn random_32() -> Result<[u8; 32], CliError> {
    let mut bytes = [0u8; 32];
    getrandom::fill(&mut bytes)
        .map_err(|_| CliError::Local("the system random source is unavailable".to_owned()))?;
    Ok(bytes)
}

/// Signs a request with fresh auxiliary randomness and the current time and
/// returns the `Authorization` header value.
pub(crate) fn sign(
    key: &NostrSecretKey,
    method: &str,
    url: &str,
    body: Option<&[u8]>,
) -> Result<String, CliError> {
    let aux = random_32()?;
    key.sign_request(&ExpectedRequest::new(method, url, body), now()?, &aux)
        .map_err(|err| CliError::Local(format!("signing the request failed: {err}")))
}

#[cfg(test)]
mod tests {
    use super::*;

    fn client(url: &str) -> Client {
        Client::new(url.parse().expect("valid url"))
    }

    #[test]
    fn localhost_is_dialled_as_127_0_0_1_and_signed_as_localhost() {
        let client = client("http://localhost:7460");
        assert_eq!(client.url("/readyz"), "http://localhost:7460/readyz");
        assert_eq!(
            client
                .connect_url("http://localhost:7460/api/v1/bootstrap/claim")
                .expect("same origin"),
            "http://127.0.0.1:7460/api/v1/bootstrap/claim"
        );
    }

    #[test]
    fn literals_are_dialled_as_written() {
        for (origin, url) in [
            ("http://127.0.0.2:80", "http://127.0.0.2:80/readyz"),
            ("http://[::1]:7460", "http://[::1]:7460/readyz"),
        ] {
            let client = client(origin);
            assert_eq!(client.connect_url(url).expect("same origin"), url);
        }
    }

    #[test]
    fn a_url_on_another_origin_is_never_dialled() {
        let client = client("http://localhost:7460");
        assert!(client
            .connect_url("http://localhost:7461/api/v1/bootstrap/claim")
            .is_err());
        assert!(client
            .connect_url("http://localhost:74601/api/v1/bootstrap/claim")
            .is_err());
        assert!(client.connect_url("http://192.0.2.1:7460/x").is_err());
    }
}