stratum-node-cli 0.1.0-alpha.4

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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
//! 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::redact;
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.
pub(crate) 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 mut details: Vec<String> = envelope
                    .error
                    .errors
                    .iter()
                    .chain(&envelope.errors)
                    .map(|entry| match &entry.path {
                        Some(path) => sanitize(&format!("{path}: {}", entry.message)),
                        None => sanitize(&entry.message),
                    })
                    .collect();
                if let Some(field) = &envelope.error.field {
                    details.push(sanitize(&format!("field: {field}")));
                }
                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> {
        self.get_with_timeout(path, key, REQUEST_TIMEOUT)
    }

    /// As [`get`](Self::get), allowing `timeout` for the whole exchange
    /// instead of the usual 30 seconds; for a read inside a bounded wait,
    /// which must not outlast the wait.
    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())
    }

    /// 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,
        };
        if let Some(value) = &authorization {
            redact::register_text_secret(value);
        }
        self.post_raw(&url, body, authorization.as_deref(), None)
    }

    /// As [`post`](Self::post), allowing `timeout` for the whole exchange
    /// instead of the usual 30 seconds; for a request the node may
    /// legitimately hold for longer, such as a backup.
    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))
    }

    /// 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 `N` bytes from the operating system's random source.
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)
}

/// Returns 32 bytes from the operating system's random source.
pub(crate) fn random_32() -> Result<[u8; 32], CliError> {
    random_bytes()
}

/// Signs a request with the current time, a fresh random nonce and fresh
/// auxiliary randomness, and returns the `Authorization` header value.
///
/// A signed request's event ID covers the key, the time in whole seconds,
/// the method, the URL and the body digest, but not the signature. Two
/// identical requests signed in the same second would otherwise be the
/// same event, which a server keeping event IDs for replay protection
/// refuses. The event therefore carries a `nonce` tag of 16 bytes from the
/// operating system's random source
/// ([`NostrSecretKey::sign_request_with_nonce`]), so every signing is a new
/// event and nothing waits for the clock. A request that must be resent as
/// the same event (the claim from a resume file, the single `join` resend)
/// reuses the header it already has rather than signing again.
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);
        }
    }

    /// Returns the `id` and tags of the event inside an `Authorization`
    /// value.
    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());
    }
}