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::redact;
use crate::url::LoopbackUrl;
use crate::wire::ErrorEnvelope;
pub(crate) const MAX_RESPONSE_BYTES: u64 = 4 * 1024 * 1024;
pub(crate) const REQUEST_TIMEOUT: Duration = Duration::from_secs(30);
const USER_AGENT: &str = concat!("stratum/", env!("CARGO_PKG_VERSION"));
const JSON: &str = "application/json";
pub(crate) const BOOTSTRAP_TOKEN_HEADER: &str = "Stratum-Bootstrap-Token";
#[derive(Debug)]
pub(crate) struct Response {
pub(crate) status: u16,
pub(crate) body: Vec<u8>,
}
impl Response {
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()
}
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))
}
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))
}
}
}
}
#[derive(Debug)]
pub(crate) struct Client {
origin: LoopbackUrl,
agent: ureq::Agent,
}
impl Client {
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),
}
}
pub(crate) fn url(&self, path: &str) -> String {
self.origin.join(path)
}
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))
}
pub(crate) fn get(
&self,
path: &str,
key: Option<&NostrSecretKey>,
) -> Result<Response, CliError> {
self.get_with_timeout(path, key, REQUEST_TIMEOUT)
}
pub(crate) fn get_with_timeout(
&self,
path: &str,
key: Option<&NostrSecretKey>,
timeout: Duration,
) -> Result<Response, CliError> {
let url = self.url(path);
let mut request = self
.agent
.get(connect_url(&self.origin, path))
.config()
.timeout_global(Some(timeout))
.build()
.header("Host", self.origin.authority());
if let Some(key) = key {
let authorization = sign(key, "GET", &url, None)?;
redact::register_text_secret(&authorization);
request = request.header("Authorization", authorization);
}
Self::finish(&url, request.call())
}
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,
};
if let Some(value) = &authorization {
redact::register_text_secret(value);
}
self.post_raw(&url, body, authorization.as_deref(), None)
}
pub(crate) fn post_with_timeout(
&self,
path: &str,
body: &[u8],
key: &NostrSecretKey,
timeout: Duration,
) -> Result<Response, CliError> {
let url = self.url(path);
let authorization = sign(key, "POST", &url, Some(body))?;
redact::register_text_secret(&authorization);
let request = self
.agent
.post(self.connect_url(&url)?)
.config()
.timeout_global(Some(timeout))
.build()
.header("Host", self.origin.authority())
.header("Content-Type", JSON)
.header("Authorization", &authorization);
Self::finish(&url, request.send(body))
}
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))
}
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 })
}
}
fn connect_url(origin: &LoopbackUrl, path: &str) -> String {
format!("http://{}:{}{path}", origin.connect_host(), origin.port())
}
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,
}
}
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()))
}
fn random_bytes<const N: usize>() -> Result<[u8; N], CliError> {
let mut bytes = [0u8; N];
getrandom::fill(&mut bytes)
.map_err(|_| CliError::Local("the system random source is unavailable".to_owned()))?;
Ok(bytes)
}
pub(crate) fn random_32() -> Result<[u8; 32], CliError> {
random_bytes()
}
pub(crate) fn sign(
key: &NostrSecretKey,
method: &str,
url: &str,
body: Option<&[u8]>,
) -> Result<String, CliError> {
let created_at = now()?;
let nonce: [u8; 16] = random_bytes()?;
let aux = random_32()?;
key.sign_request_with_nonce(
&ExpectedRequest::new(method, url, body),
created_at,
&nonce,
&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);
}
}
fn event_of(authorization: &str) -> (String, Vec<Vec<String>>) {
use base64::Engine as _;
let token = authorization.strip_prefix("Nostr ").expect("scheme");
let json = base64::engine::general_purpose::STANDARD
.decode(token)
.expect("base64");
let value: serde_json::Value = serde_json::from_slice(&json).expect("event json");
(
value["id"].as_str().expect("id").to_owned(),
serde_json::from_value(value["tags"].clone()).expect("tags"),
)
}
#[test]
fn identical_requests_signed_back_to_back_are_distinct_events() {
let key = NostrSecretKey::from_hex(&"07".repeat(32)).expect("key");
let url = "https://stratum.test/api/v1/admission/operation";
let started = std::time::Instant::now();
let events: Vec<(String, Vec<Vec<String>>)> = (0..3)
.map(|_| event_of(&sign(&key, "PUT", url, Some(b"x")).expect("signed")))
.collect();
assert!(
started.elapsed() < Duration::from_secs(1),
"signing does not wait for the clock"
);
for (i, (id, tags)) in events.iter().enumerate() {
assert!(
events[..i].iter().all(|(earlier, _)| earlier != id),
"a repeated request is a new event: {events:?}"
);
let nonce = tags.last().expect("tags");
assert_eq!(nonce[0], "nonce", "the nonce tag comes last: {tags:?}");
assert_eq!(nonce.len(), 2);
assert_eq!(nonce[1].len(), 32);
assert!(nonce[1]
.bytes()
.all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)));
}
}
#[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());
}
}