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
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
//! The node's canonical origin and the local address a tenant command
//! reaches it on.

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

use crate::error::CliError;
use crate::url::LoopbackUrl;

/// The scheme of a canonical origin.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Scheme {
    /// `http://`: only for a node whose canonical origin is itself a local
    /// plain-HTTP address, such as a test deployment.
    Http,
    /// `https://`: the public origin. The client has no TLS transport yet, so
    /// it is reached through `--connect`.
    Https,
}

impl Scheme {
    /// Returns `http` or `https`.
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Http => "http",
            Self::Https => "https",
        }
    }

    /// Returns the port a URL of this scheme means when it names none.
    fn default_port(self) -> u16 {
        match self {
            Self::Http => 80,
            Self::Https => 443,
        }
    }
}

/// A node's canonical origin: the one origin every signed tenant URL names.
///
/// The gate refuses a signed URL that does not start with exactly this text,
/// and a `Host` other than its authority, so the client keeps the origin in
/// the single spelling the node's configuration allows: `http://` or
/// `https://`, a lowercase DNS name, IPv4 literal or bracketed IPv6 literal
/// in its RFC 5952 form, an optional port that is not the scheme's default,
/// and no user information, path, query or fragment. A single trailing `/`
/// is accepted and dropped.
///
/// # Examples
///
/// ```
/// use stratum_node_cli::CanonicalOrigin;
///
/// # fn main() -> Result<(), stratum_node_cli::ParseOriginError> {
/// let origin: CanonicalOrigin = "https://stratum.visionclaw.pro/".parse()?;
/// assert_eq!(origin.as_str(), "https://stratum.visionclaw.pro");
/// assert_eq!(origin.authority(), "stratum.visionclaw.pro");
/// assert_eq!(origin.url("/pods/"), "https://stratum.visionclaw.pro/pods/");
///
/// assert!("https://Stratum.example".parse::<CanonicalOrigin>().is_err());
/// assert!("https://stratum.example:443".parse::<CanonicalOrigin>().is_err());
/// assert!("https://stratum.example/pods".parse::<CanonicalOrigin>().is_err());
/// # Ok(())
/// # }
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct CanonicalOrigin {
    scheme: Scheme,
    host: String,
    port: Option<u16>,
}

impl CanonicalOrigin {
    /// Returns the scheme.
    pub fn scheme(&self) -> Scheme {
        self.scheme
    }

    /// Returns the host as written: a DNS name, an IPv4 literal or a
    /// bracketed IPv6 literal.
    pub fn host(&self) -> &str {
        &self.host
    }

    /// Returns the port, the scheme's default when the origin names none.
    pub fn port(&self) -> u16 {
        self.port.unwrap_or_else(|| self.scheme.default_port())
    }

    /// Returns `<host>` or `<host>:<port>` exactly as the origin writes it:
    /// the value of `Host` on every request to the gate.
    pub fn authority(&self) -> String {
        match self.port {
            Some(port) => format!("{}:{port}", self.host),
            None => self.host.clone(),
        }
    }

    /// Returns the origin text, `<scheme>://<authority>`.
    pub fn as_str(&self) -> String {
        format!("{}://{}", self.scheme.as_str(), self.authority())
    }

    /// Returns the canonical URL of `path`, which should start with `/`:
    /// the URL a tenant request is signed over.
    pub fn url(&self, path: &str) -> String {
        format!("{}{path}", self.as_str())
    }
}

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

impl FromStr for CanonicalOrigin {
    type Err = ParseOriginError;

    fn from_str(text: &str) -> Result<Self, Self::Err> {
        let (scheme, rest) = if let Some(rest) = text.strip_prefix("https://") {
            (Scheme::Https, rest)
        } else if let Some(rest) = text.strip_prefix("http://") {
            (Scheme::Http, rest)
        } else {
            return Err(ParseOriginError::Scheme);
        };
        let authority = rest.strip_suffix('/').unwrap_or(rest);
        if authority.contains(['/', '?', '#']) {
            return Err(ParseOriginError::NotAnOrigin);
        }
        if authority.contains('@') {
            return Err(ParseOriginError::UserInfo);
        }
        let (host, port_text) = if let Some(inner) = authority.strip_prefix('[') {
            let (literal, after) = inner.split_once(']').ok_or(ParseOriginError::Host)?;
            let canonical = literal
                .parse::<Ipv6Addr>()
                .is_ok_and(|addr| addr.to_string() == literal);
            if !canonical {
                return Err(ParseOriginError::Host);
            }
            let port = match after {
                "" => None,
                other => Some(other.strip_prefix(':').ok_or(ParseOriginError::Port)?),
            };
            (format!("[{literal}]"), port)
        } else {
            let (host, port) = match authority.split_once(':') {
                Some((host, port)) => (host, Some(port)),
                None => (authority, None),
            };
            if !is_dns_host(host) {
                return Err(ParseOriginError::Host);
            }
            (host.to_owned(), port)
        };
        let port = match port_text {
            None => None,
            Some(digits) => {
                let valid = !digits.is_empty()
                    && digits.len() <= 5
                    && digits.bytes().all(|b| b.is_ascii_digit())
                    && !digits.starts_with('0');
                let port = digits
                    .parse::<u16>()
                    .ok()
                    .filter(|_| valid)
                    .ok_or(ParseOriginError::Port)?;
                if port == scheme.default_port() {
                    return Err(ParseOriginError::DefaultPort);
                }
                Some(port)
            }
        };
        Ok(Self { scheme, host, port })
    }
}

/// Returns `true` for a lowercase DNS name or IPv4 literal: dot-separated
/// labels of 1 to 63 characters from `a-z`, `0-9` and `-`, not starting or
/// ending with `-`. The same rule as the node's `node.canonical_origin`.
fn is_dns_host(host: &str) -> bool {
    !host.is_empty()
        && host.len() <= 253
        && host.split('.').all(|label| {
            !label.is_empty()
                && label.len() <= 63
                && !label.starts_with('-')
                && !label.ends_with('-')
                && label
                    .bytes()
                    .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-')
        })
}

/// The reasons an origin is refused by [`CanonicalOrigin`].
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum ParseOriginError {
    /// The origin does not start with `http://` or `https://`.
    #[error("origin must start with https:// or http://")]
    Scheme,
    /// The origin has a path, query or fragment.
    #[error("origin must have no path, query or fragment")]
    NotAnOrigin,
    /// The origin carries user information.
    #[error("origin must not contain user information")]
    UserInfo,
    /// The host is not a lowercase DNS name, an IPv4 literal or a canonical
    /// bracketed IPv6 literal.
    #[error("origin host must be a lowercase name or address (ipv6 in brackets, rfc 5952 form)")]
    Host,
    /// The port is not a number from 1 to 65535 without leading zeros.
    #[error("origin port must be a number from 1 to 65535")]
    Port,
    /// The port is the scheme's default, which the canonical form omits.
    #[error("origin must omit the scheme's default port")]
    DefaultPort,
}

/// Where a tenant command sends its requests: the canonical origin it signs
/// for, and the local plain-HTTP address it connects to.
///
/// The client has no TLS transport in Step 2. It opens plain HTTP to the
/// connect address, sends `Host: <canonical authority>` and signs
/// `<canonical origin><path>`, so the gate sees exactly the request it
/// would see behind the public origin. The connect address must be a
/// loopback literal (an address in `127.0.0.0/8`, `[::1]`, or `localhost`,
/// which is dialled as `127.0.0.1` without a name lookup), because a signed
/// request sent in clear text off the machine could be captured and spent.
///
/// # Examples
///
/// ```
/// use stratum_node_cli::GateTarget;
///
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let target = GateTarget::new(
///     "https://stratum.visionclaw.pro".parse()?,
///     Some("127.0.0.1:7461".parse()?),
/// )?;
/// assert_eq!(target.connect().authority(), "127.0.0.1:7461");
///
/// // The remote transport arrives with the public origin.
/// assert!(GateTarget::new("https://stratum.visionclaw.pro".parse()?, None).is_err());
///
/// // A local http:// origin is reached at its own address.
/// let local = GateTarget::new("http://127.0.0.1:7461".parse()?, None)?;
/// assert_eq!(local.connect().authority(), "127.0.0.1:7461");
/// # Ok(())
/// # }
/// ```
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct GateTarget {
    origin: CanonicalOrigin,
    connect: LoopbackUrl,
}

impl GateTarget {
    /// Builds a target from `--origin` and the optional `--connect`.
    ///
    /// # Errors
    ///
    /// [`CliError::Usage`] when an `https://` origin has no connect address
    /// (the remote transport arrives with the public origin), when an
    /// `http://` origin without one is not itself on a loopback address, or
    /// when the connect address has a path.
    pub fn new(origin: CanonicalOrigin, connect: Option<ConnectAddress>) -> Result<Self, CliError> {
        let connect = match connect {
            Some(address) => address.0,
            None => match origin.scheme() {
                Scheme::Https => {
                    return Err(CliError::Usage(format!(
                        "{origin} is an https:// origin and this client has no TLS transport yet: \
                         the remote transport arrives with the public origin. Reach the gate on \
                         this machine with --connect <host:port>"
                    )))
                }
                Scheme::Http => format!("http://{}:{}", origin.host(), origin.port())
                    .parse::<LoopbackUrl>()
                    .map_err(|_| {
                        CliError::Usage(format!(
                            "{origin} is not a loopback address; pass --connect <host:port> with \
                             a loopback address to reach the gate"
                        ))
                    })?,
            },
        };
        Ok(Self { origin, connect })
    }

    /// Returns the canonical origin requests are signed for.
    pub fn origin(&self) -> &CanonicalOrigin {
        &self.origin
    }

    /// Returns the loopback address requests are sent to.
    pub fn connect(&self) -> &LoopbackUrl {
        &self.connect
    }
}

/// A `--connect <host:port>` value: a loopback literal and an explicit
/// port.
///
/// The host follows the rules of [`LoopbackUrl`]: a canonical IPv4 address
/// in `127.0.0.0/8`, `[::1]` or `localhost`.
///
/// # Examples
///
/// ```
/// use stratum_node_cli::ConnectAddress;
///
/// assert!("127.0.0.1:7461".parse::<ConnectAddress>().is_ok());
/// assert!("[::1]:7461".parse::<ConnectAddress>().is_ok());
/// assert!("127.0.0.1".parse::<ConnectAddress>().is_err());
/// assert!("192.0.2.1:7461".parse::<ConnectAddress>().is_err());
/// ```
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ConnectAddress(LoopbackUrl);

impl ConnectAddress {
    /// Returns `<host>:<port>`.
    pub fn authority(&self) -> String {
        self.0.authority()
    }
}

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

impl FromStr for ConnectAddress {
    type Err = ParseConnectError;

    fn from_str(text: &str) -> Result<Self, Self::Err> {
        if text.contains('/') {
            return Err(ParseConnectError);
        }
        let url: LoopbackUrl = format!("http://{text}")
            .parse()
            .map_err(|_| ParseConnectError)?;
        // Equal only when the port was written and the host is canonical.
        if url.authority() != text {
            return Err(ParseConnectError);
        }
        Ok(Self(url))
    }
}

/// A `--connect` value was not `<loopback host>:<port>`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
#[error(
    "connect address must be <host>:<port> with a host in 127.0.0.0/8 (such as 127.0.0.1), [::1] or localhost"
)]
#[non_exhaustive]
pub struct ParseConnectError;

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

    #[test]
    fn origins_keep_one_spelling() {
        for (text, canonical, authority) in [
            ("https://a.example", "https://a.example", "a.example"),
            ("https://a.example/", "https://a.example", "a.example"),
            (
                "https://a.example:8443",
                "https://a.example:8443",
                "a.example:8443",
            ),
            (
                "http://127.0.0.1:7461",
                "http://127.0.0.1:7461",
                "127.0.0.1:7461",
            ),
            ("https://[::1]:9", "https://[::1]:9", "[::1]:9"),
        ] {
            let origin: CanonicalOrigin = text.parse().expect(text);
            assert_eq!(origin.as_str(), canonical, "{text}");
            assert_eq!(origin.authority(), authority, "{text}");
        }
        for bad in [
            "ftp://a.example",
            "https://A.example",
            "https://a.example:443",
            "http://a.example:80",
            "https://a.example:0",
            "https://a.example:08443",
            "https://a.example/x",
            "https://a.example?x",
            "https://u@a.example",
            "https://[0:0::1]",
            "https://a..example",
            "https://",
        ] {
            assert!(bad.parse::<CanonicalOrigin>().is_err(), "{bad}");
        }
    }

    #[test]
    fn https_without_connect_is_refused_and_http_needs_loopback() {
        let https: CanonicalOrigin = "https://a.example".parse().expect("origin");
        let err = GateTarget::new(https, None).expect_err("refused");
        assert!(
            err.to_string()
                .contains("remote transport arrives with the public origin"),
            "{err}"
        );
        let far: CanonicalOrigin = "http://a.example:7461".parse().expect("origin");
        assert!(GateTarget::new(far, None).is_err());
        let near: CanonicalOrigin = "http://localhost:7461".parse().expect("origin");
        let target = GateTarget::new(near, None).expect("loopback");
        assert_eq!(target.connect().connect_host(), "127.0.0.1");
    }
}