stratum-node-cli 0.1.0-alpha.2

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
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
//! A small blocking HTTP client for the gate: plain HTTP to a loopback
//! address, `Host` and signed URLs naming the canonical origin.

use std::io::{self, Read as _, Write};
use std::thread;
use std::time::Duration;

use serde::de::DeserializeOwned;
use sha2::{Digest as _, Sha256};
use stratum_node_core::{NostrSecretKey, Sha256Digest};

use crate::client::{self, MAX_RESPONSE_BYTES};
use crate::error::CliError;
use crate::origin::GateTarget;
use crate::output::{sanitize, Output};
use crate::redact;
use crate::wire::ErrorEnvelope;

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

/// The media type of admission request and response bodies.
pub(crate) const JSON: &str = "application/json";

/// The media type asked for when reading a container listing. The pod
/// server answers JSON-LD whatever is asked, so this only states intent.
pub(crate) const LD_JSON: &str = "application/ld+json";

/// What is asked for when reading a resource: anything, so content
/// negotiation never hands back a converted form instead of the bytes that
/// were written.
pub(crate) const ANY: &str = "*/*";

/// The largest resource body read or written: the ceiling of
/// `limits.max_pod_body_bytes`, so no resource the gate accepted can be
/// larger.
pub(crate) const MAX_RESOURCE_BYTES: u64 = 1024 * 1024 * 1024;

/// The largest container listing read. A listing names each child in well
/// under 200 bytes, so 64 MiB holds far more children than an export walks.
pub(crate) const MAX_LISTING_BYTES: u64 = 64 * 1024 * 1024;

/// Time allowed to connect.
const CONNECT_TIMEOUT: Duration = Duration::from_secs(10);
/// Time allowed for the response head once the request is sent.
const RESPONSE_TIMEOUT: Duration = Duration::from_secs(60);
/// Time allowed to send or receive one whole body.
const BODY_TIMEOUT: Duration = Duration::from_secs(600);

/// Which side of the gate answered a route, for reading error bodies.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Route {
    /// `/api/v1/admission/…`: the controller, which always sends the error
    /// envelope.
    Admission,
    /// `/pods/…`: the pod server, whose own error bodies are not the
    /// envelope; only the gate's own refusals carry it.
    Pod,
}

/// A conditional-write header for a `PUT`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Precondition<'a> {
    /// No condition.
    None,
    /// `If-Match: <etag>`.
    IfMatch(&'a str),
    /// `If-None-Match: *`: only create.
    CreateOnly,
}

/// The headers of a gate response the client reads.
#[derive(Debug, Clone, Default)]
pub(crate) struct Head {
    pub(crate) status: u16,
    pub(crate) content_type: Option<String>,
    pub(crate) etag: Option<String>,
    pub(crate) retry_after: Option<String>,
}

impl Head {
    /// Returns `true` for a 2xx status.
    pub(crate) fn is_success(&self) -> bool {
        (200..300).contains(&self.status)
    }

    /// Returns `true` for a 3xx status, which is never followed.
    pub(crate) fn is_redirect(&self) -> bool {
        (300..400).contains(&self.status)
    }
}

/// A response whose body was read into memory, capped.
#[derive(Debug)]
pub(crate) struct Buffered {
    pub(crate) head: Head,
    pub(crate) body: Vec<u8>,
}

impl Buffered {
    /// Parses a 2xx body as `T`, or turns any other status into an error.
    pub(crate) fn into_json<T: DeserializeOwned>(
        self,
        route: Route,
    ) -> Result<(T, serde_json::Value), CliError> {
        if !self.head.is_success() {
            return Err(self.into_error(route));
        }
        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.head.status
            ))
        })?;
        let typed = T::deserialize(&value).map_err(|err| {
            CliError::Protocol(format!(
                "HTTP {} body does not match the API contract: {}",
                self.head.status,
                sanitize(&err.to_string())
            ))
        })?;
        Ok((typed, value))
    }

    /// Turns a non-success response into an error; see [`error_from`].
    pub(crate) fn into_error(self, route: Route) -> CliError {
        error_from(&self.head, &self.body, route)
    }
}

/// Turns a non-success response into a [`CliError::Server`].
///
/// A body in the error envelope gives its code and message. On a pod route
/// any other body is the pod server's own, so the code is named after the
/// HTTP status; on an admission route a body without the envelope breaks
/// the contract and is a [`CliError::Protocol`]. Bodies that are not the
/// envelope are never echoed.
pub(crate) fn error_from(head: &Head, body: &[u8], route: Route) -> CliError {
    let retry = head
        .retry_after
        .as_deref()
        .map(|value| format!(" (retry after {})", sanitize(value)))
        .unwrap_or_default();
    if let Ok(envelope) = serde_json::from_slice::<ErrorEnvelope>(body) {
        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();
        return CliError::Server {
            status: head.status,
            code: sanitize(&envelope.error.code),
            message: format!("{}{retry}", sanitize(&envelope.error.message)),
            details,
        };
    }
    match route {
        Route::Admission => {
            CliError::Protocol(format!("HTTP {} without the error envelope", head.status))
        }
        Route::Pod => CliError::Server {
            status: head.status,
            code: code_for_status(head.status),
            message: format!("HTTP {} from the pod server{retry}", head.status),
            details: Vec::new(),
        },
    }
}

/// Names a bare HTTP status with the error code the contract uses for it.
fn code_for_status(status: u16) -> String {
    match status {
        400 => "bad_request",
        401 => "unauthorized",
        403 => "forbidden",
        404 => "not_found",
        405 => "method_not_allowed",
        408 => "request_timeout",
        409 => "conflict",
        412 => "precondition_failed",
        413 => "payload_too_large",
        415 => "unsupported_media_type",
        421 => "misdirected_request",
        429 => "too_many_requests",
        500 => "internal",
        502 => "bad_gateway",
        504 => "gateway_timeout",
        507 => "insufficient_storage",
        other => return format!("http_{other}"),
    }
    .to_owned()
}

/// What a streamed body came to.
#[derive(Debug, Clone, Copy)]
pub(crate) struct Streamed {
    pub(crate) size: u64,
    pub(crate) sha256: Sha256Digest,
}

/// A request to send through the gate.
#[derive(Debug, Clone, Copy)]
pub(crate) struct Request<'a> {
    pub(crate) method: &'a str,
    pub(crate) path: &'a str,
    pub(crate) accept: &'a str,
    /// The body and its content type.
    pub(crate) body: Option<(&'a [u8], &'a str)>,
    pub(crate) precondition: Precondition<'a>,
}

impl<'a> Request<'a> {
    /// A request without a body.
    pub(crate) fn new(method: &'a str, path: &'a str, accept: &'a str) -> Self {
        Self {
            method,
            path,
            accept,
            body: None,
            precondition: Precondition::None,
        }
    }

    /// Adds a body.
    pub(crate) fn with_body(mut self, body: &'a [u8], content_type: &'a str) -> Self {
        self.body = Some((body, content_type));
        self
    }

    /// Adds a precondition.
    pub(crate) fn with_precondition(mut self, precondition: Precondition<'a>) -> Self {
        self.precondition = precondition;
        self
    }
}

/// A client bound to one [`GateTarget`].
///
/// As for the loopback API client: proxies, redirects, compression and TLS
/// are off, so a signed request goes only to the address it was meant for
/// and a `3xx` is returned to the caller, never followed. The URL handed to
/// ureq names the connect address literal (never resolved); `Host` and the
/// signed URL name the canonical origin. Bodies are always sent from memory,
/// so every request carries `Content-Length` and never `Transfer-Encoding`,
/// which the gate refuses.
#[derive(Debug)]
pub(crate) struct GateClient {
    target: GateTarget,
    agent: ureq::Agent,
    busy: Option<BusyRetries>,
}

/// How a client retries a request the gate refused as busy.
#[derive(Debug, Clone, Copy)]
struct BusyRetries {
    attempts: u32,
    output: Output,
}

/// How many times a request refused with 503 and `Retry-After` is sent again.
pub(crate) const BUSY_RETRIES: u32 = 3;

/// The longest wait honoured from a `Retry-After`.
const MAX_RETRY_DELAY: Duration = Duration::from_secs(30);

/// The wait used when `Retry-After` is an HTTP date rather than seconds.
const DATE_RETRY_DELAY: Duration = Duration::from_secs(5);

impl GateClient {
    /// Builds a client for `target`.
    pub(crate) fn new(target: GateTarget) -> 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(ureq::config::AutoHeaderValue::None)
            .accept_encoding(ureq::config::AutoHeaderValue::None)
            .timeout_connect(Some(CONNECT_TIMEOUT))
            .timeout_recv_response(Some(RESPONSE_TIMEOUT))
            .timeout_send_body(Some(BODY_TIMEOUT))
            .timeout_recv_body(Some(BODY_TIMEOUT))
            .max_idle_connections(0)
            .build();
        Self {
            target,
            agent: ureq::Agent::new_with_config(config),
            busy: None,
        }
    }

    /// Makes [`fetch`](Self::fetch) and [`stream`](Self::stream) send a
    /// request again, at most [`BUSY_RETRIES`] times, when the gate refuses
    /// it with 503 and a `Retry-After`: such a refusal has not spent the
    /// event, but every retry is signed afresh all the same. Each wait is
    /// noted through `output`.
    pub(crate) fn with_busy_retries(mut self, output: Output) -> Self {
        self.busy = Some(BusyRetries {
            attempts: BUSY_RETRIES,
            output,
        });
        self
    }

    /// Returns how long to wait before retrying after `head`, or `None`
    /// when the response is final. Notes the wait.
    fn retry_delay(&self, head: &Head, attempt: u32) -> Result<Option<Duration>, CliError> {
        let Some(busy) = self.busy else {
            return Ok(None);
        };
        if head.status != 503 || attempt >= busy.attempts {
            return Ok(None);
        }
        let Some(value) = head.retry_after.as_deref() else {
            return Ok(None);
        };
        let delay = value
            .trim()
            .parse::<u64>()
            .map_or(DATE_RETRY_DELAY, Duration::from_secs)
            .min(MAX_RETRY_DELAY);
        busy.output.note(&format!(
            "the gate is busy (503); retrying in {} s, signed afresh (retry {} of {})",
            delay.as_secs(),
            attempt + 1,
            busy.attempts
        ))?;
        Ok(Some(delay))
    }

    /// Returns the target.
    pub(crate) fn target(&self) -> &GateTarget {
        &self.target
    }

    /// Returns the canonical URL of `path`.
    pub(crate) fn url(&self, path: &str) -> String {
        self.target.origin().url(path)
    }

    /// Signs `request` with `key`, with a fresh nonce, fresh randomness and
    /// the current time, and returns the `Authorization` value. The value is registered
    /// for redaction, so it never reaches the terminal.
    pub(crate) fn sign(
        &self,
        key: &NostrSecretKey,
        request: &Request<'_>,
    ) -> Result<String, CliError> {
        let url = self.url(request.path);
        let authorization = client::sign(
            key,
            request.method,
            &url,
            request.body.map(|(bytes, _)| bytes),
        )?;
        redact::register_text_secret(&authorization);
        Ok(authorization)
    }

    /// Sends `request`, signed by `key` when given, and reads the body into
    /// memory, at most `limit` bytes. With busy retries enabled, a 503 with
    /// `Retry-After` is retried with a fresh signature.
    pub(crate) fn fetch(
        &self,
        request: &Request<'_>,
        key: Option<&NostrSecretKey>,
        limit: u64,
    ) -> Result<Buffered, CliError> {
        let mut attempt = 0;
        loop {
            let authorization = match key {
                Some(key) => Some(self.sign(key, request)?),
                None => None,
            };
            let response = self.fetch_with(request, authorization.as_deref(), limit)?;
            match self.retry_delay(&response.head, attempt)? {
                Some(delay) => {
                    thread::sleep(delay);
                    attempt += 1;
                }
                None => return Ok(response),
            }
        }
    }

    /// Sends `request` with exactly the given `Authorization` value and
    /// reads the body into memory; used to resend an identical request.
    pub(crate) fn fetch_with(
        &self,
        request: &Request<'_>,
        authorization: Option<&str>,
        limit: u64,
    ) -> Result<Buffered, CliError> {
        let url = self.url(request.path);
        let mut response = self.send(request, authorization)?;
        let head = head_of(&response);
        let mut body = Vec::new();
        copy_capped(&mut response, &url, &mut body, limit)?;
        Ok(Buffered { head, body })
    }

    /// Sends `request` signed by `key`. A 2xx body is streamed into `sink`,
    /// at most `limit` bytes, and hashed on the way; any other body is read
    /// into memory (capped) for the error report. With busy retries
    /// enabled, a 503 with `Retry-After` is retried with a fresh signature;
    /// nothing reaches `sink` until a 2xx arrives.
    pub(crate) fn stream(
        &self,
        request: &Request<'_>,
        key: &NostrSecretKey,
        sink: &mut dyn Write,
        limit: u64,
    ) -> Result<(Head, Result<Streamed, Vec<u8>>), CliError> {
        let url = self.url(request.path);
        let mut attempt = 0;
        loop {
            let authorization = self.sign(key, request)?;
            let mut response = self.send(request, Some(&authorization))?;
            let head = head_of(&response);
            if head.is_success() {
                let streamed = copy_capped(&mut response, &url, sink, limit)?;
                return Ok((head, Ok(streamed)));
            }
            let mut body = Vec::new();
            copy_capped(&mut response, &url, &mut body, MAX_RESPONSE_BYTES)?;
            match self.retry_delay(&head, attempt)? {
                Some(delay) => {
                    thread::sleep(delay);
                    attempt += 1;
                }
                None => return Ok((head, Err(body))),
            }
        }
    }

    /// Builds and sends one request.
    fn send(
        &self,
        request: &Request<'_>,
        authorization: Option<&str>,
    ) -> Result<ureq::http::Response<ureq::Body>, CliError> {
        let url = self.url(request.path);
        let connect = format!(
            "http://{}:{}{}",
            self.target.connect().connect_host(),
            self.target.connect().port(),
            request.path
        );
        let builder = ureq::http::Request::builder()
            .method(request.method)
            .uri(&connect)
            .header("Host", self.target.origin().authority())
            .header("Accept", request.accept);
        let builder = match authorization {
            Some(value) => builder.header("Authorization", value),
            None => builder,
        };
        let builder = match request.precondition {
            Precondition::None => builder,
            Precondition::IfMatch(etag) => builder.header("If-Match", etag),
            Precondition::CreateOnly => builder.header("If-None-Match", "*"),
        };
        let result = if let Some((bytes, content_type)) = request.body {
            let built = builder
                .header("Content-Type", content_type)
                .body(bytes)
                .map_err(|err| CliError::Local(format!("building the request failed: {err}")))?;
            self.agent.run(built)
        } else {
            let built = builder
                .body(())
                .map_err(|err| CliError::Local(format!("building the request failed: {err}")))?;
            self.agent.run(built)
        };
        result.map_err(|err| transport_error(&url, &err))
    }
}

/// Reads the headers the client uses.
fn head_of(response: &ureq::http::Response<ureq::Body>) -> Head {
    let header = |name: &str| {
        response
            .headers()
            .get(name)
            .and_then(|value| value.to_str().ok())
            .map(str::to_owned)
    };
    Head {
        status: response.status().as_u16(),
        content_type: header("content-type"),
        etag: header("etag"),
        retry_after: header("retry-after"),
    }
}

/// Copies the body into `sink`, refusing more than `limit` bytes, and
/// returns its size and SHA-256.
fn copy_capped(
    response: &mut ureq::http::Response<ureq::Body>,
    url: &str,
    sink: &mut dyn Write,
    limit: u64,
) -> Result<Streamed, CliError> {
    let mut reader = response.body_mut().with_config().limit(u64::MAX).reader();
    let mut hasher = Sha256::new();
    let mut size: u64 = 0;
    let mut buffer = vec![0u8; 64 * 1024];
    loop {
        let read = match reader.read(&mut buffer) {
            Ok(0) => break,
            Ok(read) => read,
            Err(err) if err.kind() == io::ErrorKind::Interrupted => continue,
            Err(err) => return Err(body_error(url, &err, limit)),
        };
        size = size.saturating_add(u64::try_from(read).unwrap_or(u64::MAX));
        if size > limit {
            return Err(CliError::Protocol(format!(
                "response body is larger than {limit} bytes"
            )));
        }
        let chunk = &buffer[..read];
        hasher.update(chunk);
        sink.write_all(chunk)
            .map_err(|err| CliError::Local(format!("writing the response body failed: {err}")))?;
    }
    let digest: [u8; 32] = hasher.finalize().into();
    Ok(Streamed {
        size,
        sha256: Sha256Digest::from_bytes(digest),
    })
}

/// Maps a failure while reading a body.
fn body_error(url: &str, err: &io::Error, limit: u64) -> CliError {
    let text = err.to_string();
    if text.contains("limit") {
        return CliError::Protocol(format!("response body is larger than {limit} bytes"));
    }
    CliError::Unreachable {
        url: url.to_owned(),
        message: format!("reading the response failed: {}", err.kind()),
    }
}

/// 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(),
        ureq::Error::Protocol(_) => "the connection closed without a valid response".to_owned(),
        other => return CliError::Protocol(sanitize(&other.to_string())),
    };
    CliError::Unreachable {
        url: url.to_owned(),
        message,
    }
}

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

    #[test]
    fn bare_statuses_are_named_on_pod_routes_only() {
        let head = Head {
            status: 412,
            ..Head::default()
        };
        let err = error_from(&head, b"precondition failed", Route::Pod);
        assert_eq!(err.code(), "precondition_failed");
        let err = error_from(&head, b"precondition failed", Route::Admission);
        assert_eq!(err.code(), "protocol");
        let head = Head {
            status: 503,
            retry_after: Some("5".to_owned()),
            ..Head::default()
        };
        let err = error_from(
            &head,
            br#"{"error":{"code":"gate_unavailable","message":"paused"}}"#,
            Route::Pod,
        );
        assert_eq!(err.code(), "gate_unavailable");
        assert_eq!(err.to_string(), "gate_unavailable: paused (retry after 5)");
    }
}