haematite-cli 0.21.12

The haematite command: serve a store, its door and Studio, answer MCP, query with jq, and host the store's assistant seat
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
//! HAEMNET-003 R1: a store reached at a HAEMNET-001 network endpoint as well
//! as at its Unix socket.
//!
//! A network store is reached only over TLS, its certificate verified for
//! the `server_name` the configuration names against this machine's trust
//! roots ([`Trust::system`]); nothing turns that verification off, and no
//! peer is trusted for its address. Once the handshake is done the bytes
//! are the same haem/1 frames, hello and `session.pass` as on the socket.

use std::fmt;
use std::io::{self, Read, Write};
use std::net::{Shutdown, SocketAddr, TcpStream, ToSocketAddrs};
use std::os::unix::net::UnixStream;
use std::path::{Path, PathBuf};
use std::sync::{Arc, mpsc};
use std::time::Duration;

use rustls::pki_types::{CertificateDer, ServerName, pem::PemObject};
use rustls::{ClientConfig, ClientConnection, RootCertStore, StreamOwned};

/// The environment variable naming a PEM file of further trust roots, the
/// name every TLS stack on the machine reads for the system's bundle.
pub const CERT_FILE: &str = "SSL_CERT_FILE";

/// Where a store is reached: its socket's absolute path, or a network
/// endpoint over verified TLS.
#[derive(Clone, Debug)]
pub enum Address {
    Socket(PathBuf),
    Network(Remote),
}

impl Address {
    /// The words an operator reads for this address: the socket's path, or
    /// the endpoint.
    #[must_use]
    pub fn named(&self) -> String {
        match self {
            Self::Socket(path) => path.display().to_string(),
            Self::Network(remote) => remote.endpoint.clone(),
        }
    }
}

/// A store's HAEMNET-001 network endpoint, the name its certificate must
/// carry, and the roots it is verified against.
#[derive(Clone)]
pub struct Remote {
    endpoint: String,
    server_name: ServerName<'static>,
    trust: Trust,
}

impl fmt::Debug for Remote {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("Remote")
            .field("endpoint", &self.endpoint)
            .field("server_name", &self.server_name)
            .finish_non_exhaustive()
    }
}

impl Remote {
    /// The endpoint `endpoint` (`<host>:<port>`) verified as `server_name`
    /// against `trust`.
    ///
    /// # Errors
    ///
    /// Words naming which of the two does not parse.
    pub fn new(endpoint: &str, server_name: &str, trust: &Trust) -> Result<Self, String> {
        if !endpoint_parses(endpoint) {
            return Err(format!(
                "endpoint {endpoint:?} is not <host>:<port> with a port from 1 to 65535"
            ));
        }
        Ok(Self {
            endpoint: endpoint.to_owned(),
            server_name: name(server_name)?,
            trust: trust.clone(),
        })
    }

    /// The endpoint, as configured.
    #[must_use]
    pub fn endpoint(&self) -> &str {
        &self.endpoint
    }
}

/// The TLS server name `text` names: a DNS name or an IP address.
///
/// # Errors
///
/// Words saying it is neither.
pub fn name(text: &str) -> Result<ServerName<'static>, String> {
    ServerName::try_from(text.to_owned())
        .map_err(|_| format!("server_name {text:?} is not a DNS name or an IP address"))
}

/// Whether `text` is `<host>:<port>`: a DNS name, an IPv4 address or a
/// bracketed IPv6 address, and a port from 1 to 65535.
#[must_use]
pub fn endpoint_parses(text: &str) -> bool {
    let Some((host, port)) = text.rsplit_once(':') else {
        return false;
    };
    let port_ok = port.parse::<u16>().is_ok_and(|port| port != 0);
    let host_ok = host.strip_prefix('[').map_or_else(
        || {
            !host.is_empty()
                && host.len() <= 253
                && host
                    .bytes()
                    .all(|byte| byte.is_ascii_alphanumeric() || byte == b'-' || byte == b'.')
        },
        |inner| {
            inner
                .strip_suffix(']')
                .is_some_and(|inner| inner.parse::<std::net::Ipv6Addr>().is_ok())
        },
    );
    port_ok && host_ok
}

/// The roots a network store's certificate is verified against.
#[derive(Clone)]
pub struct Trust(Arc<ClientConfig>);

impl Trust {
    /// This machine's trust roots: the Mozilla bundle every HTTPS client in
    /// haematite already verifies against (webpki-roots, as ureq and reqwest
    /// build it), and every certificate in the PEM file `SSL_CERT_FILE`
    /// names, when it is set, for a site's own authority.
    ///
    /// # Errors
    ///
    /// `door_trust_roots_invalid`, naming the file, when `SSL_CERT_FILE` is
    /// set and cannot be read or holds no certificate.
    pub fn system() -> Result<Self, String> {
        let mut roots = mozilla();
        if let Some(file) = std::env::var_os(CERT_FILE) {
            add_file(&mut roots, Path::new(&file))?;
        }
        Self::from_roots(roots)
    }

    /// The Mozilla bundle alone, without reading `SSL_CERT_FILE`: for a
    /// door with no network store, which verifies nothing with it, so a
    /// fault in that file never stops a door of sockets.
    ///
    /// # Errors
    ///
    /// `door_trust_roots_invalid` when no safe protocol version is offered.
    pub fn mozilla() -> Result<Self, String> {
        Self::from_roots(mozilla())
    }

    /// Only the certificates in `file`, for a test's own authority.
    ///
    /// # Errors
    ///
    /// `door_trust_roots_invalid` naming the file.
    #[cfg(test)]
    pub(crate) fn only(file: &Path) -> Result<Self, String> {
        let mut roots = RootCertStore::empty();
        add_file(&mut roots, file)?;
        Self::from_roots(roots)
    }

    /// The rustls client configuration these roots verify with, for a
    /// connection that is not a store's (the assistant seat's door link).
    #[must_use]
    pub(crate) fn client_config(&self) -> Arc<ClientConfig> {
        Arc::clone(&self.0)
    }

    fn from_roots(roots: RootCertStore) -> Result<Self, String> {
        ClientConfig::builder_with_provider(Arc::new(rustls::crypto::ring::default_provider()))
            .with_safe_default_protocol_versions()
            .map(|builder| {
                Self(Arc::new(
                    builder.with_root_certificates(roots).with_no_client_auth(),
                ))
            })
            .map_err(|error| format!("door_trust_roots_invalid: protocol versions: {error}"))
    }
}

fn mozilla() -> RootCertStore {
    let mut roots = RootCertStore::empty();
    roots.extend(webpki_roots::TLS_SERVER_ROOTS.iter().cloned());
    roots
}

fn add_file(roots: &mut RootCertStore, file: &Path) -> Result<(), String> {
    let invalid =
        |why: &dyn fmt::Display| format!("door_trust_roots_invalid: {}: {why}", file.display());
    let mut added = 0_usize;
    for certificate in CertificateDer::pem_file_iter(file).map_err(|error| invalid(&error))? {
        roots
            .add(certificate.map_err(|error| invalid(&error))?)
            .map_err(|error| invalid(&error))?;
        added += 1;
    }
    if added == 0 {
        return Err(invalid(&"holds no certificate"));
    }
    Ok(())
}

/// Why a network store was not reached over verified TLS.
#[derive(Debug)]
pub enum Refused {
    /// No connection: nothing answered at the endpoint within the bound.
    Unreached(String),
    /// Something answered and did not complete a TLS handshake: a
    /// plain-TCP endpoint, or another protocol.
    NotTls(String),
    /// The endpoint's certificate is not trusted for its server name.
    Untrusted(String),
    /// A TLS endpoint refused the handshake with an alert.
    TlsRefused(String),
}

impl Refused {
    /// The name an operator reads for it.
    #[must_use]
    pub const fn code(&self) -> &'static str {
        match self {
            Self::Unreached(_) => "door_store_unreached",
            Self::NotTls(_) => "door_store_not_tls",
            Self::Untrusted(_) => "door_store_tls_untrusted",
            Self::TlsRefused(_) => "door_store_tls_refused",
        }
    }

    /// The cause in words.
    #[must_use]
    pub fn why(&self) -> &str {
        match self {
            Self::Unreached(why)
            | Self::NotTls(why)
            | Self::Untrusted(why)
            | Self::TlsRefused(why) => why,
        }
    }
}

impl fmt::Display for Refused {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(formatter, "{}: {}", self.code(), self.why())
    }
}

/// One connection to a store, on its socket or over TLS.
pub enum Stream {
    Unix(UnixStream),
    Tls(Box<StreamOwned<ClientConnection, TcpStream>>),
}

impl Stream {
    /// Bound each read by `timeout`, or by nothing with `None`.
    ///
    /// # Errors
    ///
    /// The system's refusal of the bound.
    pub fn set_read_timeout(&self, timeout: Option<Duration>) -> io::Result<()> {
        match self {
            Self::Unix(stream) => stream.set_read_timeout(timeout),
            Self::Tls(stream) => stream.sock.set_read_timeout(timeout),
        }
    }

    /// Bound each write by `timeout`.
    ///
    /// # Errors
    ///
    /// The system's refusal of the bound.
    pub fn set_write_timeout(&self, timeout: Option<Duration>) -> io::Result<()> {
        match self {
            Self::Unix(stream) => stream.set_write_timeout(timeout),
            Self::Tls(stream) => stream.sock.set_write_timeout(timeout),
        }
    }

    /// A handle that hangs this connection up from another thread.
    ///
    /// # Errors
    ///
    /// The system's refusal to duplicate the connection's descriptor.
    pub fn hangup(&self) -> io::Result<Hangup> {
        Ok(match self {
            Self::Unix(stream) => Hangup::Unix(stream.try_clone()?),
            Self::Tls(stream) => Hangup::Tcp(stream.sock.try_clone()?),
        })
    }
}

impl Read for Stream {
    fn read(&mut self, bytes: &mut [u8]) -> io::Result<usize> {
        match self {
            Self::Unix(stream) => stream.read(bytes),
            // A store that closes its socket without a TLS close_notify has
            // still closed: between frames that is the end, and inside one
            // the frame reader names the cut.
            Self::Tls(stream) => match stream.read(bytes) {
                Err(error) if error.kind() == io::ErrorKind::UnexpectedEof => Ok(0),
                read => read,
            },
        }
    }
}

impl Write for Stream {
    fn write(&mut self, bytes: &[u8]) -> io::Result<usize> {
        match self {
            Self::Unix(stream) => stream.write(bytes),
            Self::Tls(stream) => stream.write(bytes),
        }
    }

    fn flush(&mut self) -> io::Result<()> {
        match self {
            Self::Unix(stream) => stream.flush(),
            Self::Tls(stream) => stream.flush(),
        }
    }
}

/// Hangs a store connection up from another thread.
pub enum Hangup {
    Unix(UnixStream),
    Tcp(TcpStream),
}

impl Hangup {
    /// Shut the connection down in `how`.
    ///
    /// # Errors
    ///
    /// The system's refusal.
    pub fn shutdown(&self, how: Shutdown) -> io::Result<()> {
        match self {
            Self::Unix(stream) => stream.shutdown(how),
            Self::Tcp(stream) => stream.shutdown(how),
        }
    }
}

/// Connect to `remote` and complete its TLS handshake.
///
/// Each step is bounded by `timeout`. The name resolution and the connect
/// run on a thread of their own, waited for at most `timeout`, as the
/// socket's connect is.
///
/// # Errors
///
/// [`Refused`] naming where it stopped.
pub fn open(remote: &Remote, timeout: Duration) -> Result<Stream, Refused> {
    let endpoint = remote.endpoint.clone();
    let (sender, receiver) = mpsc::channel();
    let thread_endpoint = endpoint.clone();
    std::thread::Builder::new()
        .name("haem-network-connect".to_owned())
        .spawn(move || {
            // The receiver is gone only when the connect outlived the timeout.
            let _unwaited = sender.send(connect(&thread_endpoint, timeout));
        })
        .map_err(|error| Refused::Unreached(format!("the connect could not start: {error}")))?;
    let mut tcp = match receiver.recv_timeout(timeout) {
        Ok(Ok(tcp)) => tcp,
        Ok(Err(error)) => {
            return Err(Refused::Unreached(format!(
                "could not connect to {endpoint}: {error}"
            )));
        }
        Err(_) => {
            return Err(Refused::Unreached(format!(
                "could not connect to {endpoint} within {} ms",
                timeout.as_millis()
            )));
        }
    };
    let unbounded = |error: io::Error| {
        Refused::Unreached(format!(
            "could not bound the connection to {endpoint}: {error}"
        ))
    };
    tcp.set_read_timeout(Some(timeout)).map_err(unbounded)?;
    tcp.set_write_timeout(Some(timeout)).map_err(unbounded)?;
    let mut connection =
        ClientConnection::new(Arc::clone(&remote.trust.0), remote.server_name.clone()).map_err(
            |error| Refused::TlsRefused(format!("{endpoint}: TLS could not start: {error}")),
        )?;
    while connection.is_handshaking() {
        if let Err(error) = connection.complete_io(&mut tcp) {
            return Err(handshake_failed(&endpoint, &error));
        }
    }
    Ok(Stream::Tls(Box::new(StreamOwned::new(connection, tcp))))
}

fn connect(endpoint: &str, timeout: Duration) -> io::Result<TcpStream> {
    let addresses: Vec<SocketAddr> = endpoint.to_socket_addrs()?.collect();
    let mut last = io::Error::new(
        io::ErrorKind::NotFound,
        "the endpoint's name resolved to no address",
    );
    for address in addresses {
        match TcpStream::connect_timeout(&address, timeout) {
            Ok(tcp) => return Ok(tcp),
            Err(error) => last = error,
        }
    }
    Err(last)
}

/// What a failed handshake was: a certificate not trusted, an alert from a
/// TLS endpoint, a silent endpoint, or something that does not speak TLS.
fn handshake_failed(endpoint: &str, error: &io::Error) -> Refused {
    let tls = error
        .get_ref()
        .and_then(|inner| inner.downcast_ref::<rustls::Error>());
    match tls {
        Some(rustls::Error::InvalidCertificate(why)) => Refused::Untrusted(format!(
            "{endpoint}: the store's certificate is not trusted for its server_name: {why:?}"
        )),
        Some(rustls::Error::AlertReceived(alert)) => Refused::TlsRefused(format!(
            "{endpoint}: the store refused the TLS handshake: {alert:?}"
        )),
        _ if matches!(
            error.kind(),
            io::ErrorKind::WouldBlock | io::ErrorKind::TimedOut
        ) =>
        {
            Refused::Unreached(format!(
                "{endpoint}: no TLS handshake answer within the bound: {error}"
            ))
        }
        _ => Refused::NotTls(format!(
            "{endpoint}: the endpoint did not complete a TLS handshake; a network store is reached only over TLS, never plain TCP: {error}"
        )),
    }
}