haematite-cli 0.33.0

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
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
//! The door's configuration (ACCESS-002 R2).
//!
//! It names where the door listens, Studio's origin and files, the stores it
//! carries verbs to, and the Lys app it signs people in as. The app's secret
//! is named by its file; the door's Lys client reads it and hands it to
//! the sign-in helper.

use std::collections::BTreeMap;
use std::net::SocketAddr;
use std::num::{NonZeroU64, NonZeroUsize};
use std::path::PathBuf;
use std::time::Duration;

use serde::Deserialize;

use super::listen::Limits;
use super::packed::Packed;
use super::route::Site;
use crate::client::Address;
use crate::client::network::{Remote, Trust};

/// The store Studio keeps every person's arrangements and saved views in
/// (surface/studio useWorkspaceKeeper.ts and namedViews.ts). A door always
/// serves Studio's files, so its stores name this one (ACCESS-004 R1).
const STUDIO_STORE: &str = "studio";
/// The bound on a request's head, in bytes.
const HEAD_CAP: usize = 16 * 1024;
/// The bound on a request's body, in bytes.
const BODY_CAP: usize = 1024 * 1024;
/// The bound on each read and write of a browser's connection.
const READ_TIMEOUT: Duration = Duration::from_secs(10);

/// The whole of `haematite door`'s configuration file.
#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Config {
    /// Programs whose stdin pipes are owned by this door.
    #[serde(default)]
    pub children: Vec<super::children::Config>,
    /// A loopback address; TLS is the proxy's in front of it.
    pub listen: SocketAddr,
    /// Studio's origin, as the browser sends it.
    pub origin: String,
    /// The absolute folder holding Studio's built files.
    pub files: PathBuf,
    /// Each store by name: its socket's absolute path, or a HAEMNET-001
    /// network endpoint (HAEMNET-003 R1).
    pub stores: BTreeMap<String, Store>,
    /// The bound on each store connection's steps, in milliseconds.
    #[serde(default = "timeout")]
    pub timeout_ms: NonZeroU64,
    /// Sixty-four bounds the threads serving browser and seat connections together.
    #[serde(default = "connections")]
    pub max_connections: NonZeroUsize,
    /// The Lys app the door signs people in as. With none, the door is the
    /// person at the keyboard's alone (ACCESS-003): a loopback origin, a
    /// one-time key printed at start, and stores with no Lys.
    #[serde(default)]
    pub lys: Option<Lys>,
    /// The optional seat socket and its admission and replay bounds.
    pub assistant: Option<Assistant>,
}

/// One store the door carries verbs to (HAEMNET-003 R1).
///
/// Today's absolute socket path, or
/// `{"endpoint": "<host>:<port>", "server_name": "<TLS name>"}` naming a
/// HAEMNET-001 network endpoint, reached only over TLS verified for
/// `server_name`.
#[derive(Clone, Debug, Deserialize)]
#[serde(untagged)]
pub enum Store {
    Socket(PathBuf),
    Network(NetworkStore),
}

/// A network store entry as written, checked whole by [`Config::parse`] so
/// each fault is refused by its own name.
#[derive(Clone, Debug, Deserialize)]
pub struct NetworkStore {
    #[serde(default)]
    pub endpoint: Option<String>,
    #[serde(default)]
    pub server_name: Option<String>,
    /// Any other field, refused by name: there is no setting that serves a
    /// network store without verified TLS.
    #[serde(flatten)]
    pub other: BTreeMap<String, serde_json::Value>,
}

impl NetworkStore {
    fn check(&self, name: &str) -> Result<(), String> {
        if let Some(field) = self.other.keys().next() {
            return Err(format!(
                "door_store_field_unknown: store {name}: {field:?} is not a network store field; a network store names endpoint and server_name and is reached only over verified TLS"
            ));
        }
        let endpoint = self.endpoint.as_deref().unwrap_or_default();
        if !crate::client::network::endpoint_parses(endpoint) {
            return Err(format!(
                "door_store_endpoint_invalid: store {name}: endpoint {endpoint:?} is not <host>:<port> with a port from 1 to 65535"
            ));
        }
        let server_name = self.server_name.as_deref().unwrap_or_default();
        if server_name.is_empty() {
            return Err(format!(
                "door_store_server_name_missing: store {name}: a network store names the server_name its TLS certificate is verified for"
            ));
        }
        crate::client::network::name(server_name)
            .map(drop)
            .map_err(|why| format!("door_store_server_name_invalid: store {name}: {why}"))
    }
}

/// Bounds on seats, attached streams and outstanding operations, counted separately.
#[derive(Clone, Debug, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Assistant {
    /// Private local transport; a relative path could select another install.
    pub socket: PathBuf,
    /// 256 KiB admits bounded tool items without unbounded line allocation.
    #[serde(default = "assistant_frame")]
    pub frame_bytes: NonZeroUsize,
    /// Two seats or tabs let a person work in two stores or windows.
    #[serde(default = "assistant_person")]
    pub max_per_person: NonZeroUsize,
    /// Thirty-two limits one store's assistant and stream memory.
    #[serde(default = "assistant_store")]
    pub max_per_store: NonZeroUsize,
    /// One frame bounds each replay page and its compressed sequence coverage.
    #[serde(default = "assistant_frame")]
    pub events_after_bytes: NonZeroUsize,
}

const fn assistant_frame() -> NonZeroUsize {
    NonZeroUsize::MIN.saturating_add(262_143)
}
const fn assistant_person() -> NonZeroUsize {
    NonZeroUsize::MIN.saturating_add(1)
}
const fn assistant_store() -> NonZeroUsize {
    NonZeroUsize::MIN.saturating_add(31)
}

/// The Lys app the door signs people in as.
#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Lys {
    /// Lys's origin.
    pub issuer: String,
    /// The app's client id in Lys.
    pub client_id: String,
    /// The absolute path of the file holding the app's secret.
    pub secret_file: PathBuf,
    /// Where Lys sends the browser back: the origin's `/callback`.
    pub redirect: String,
}

const fn timeout() -> NonZeroU64 {
    NonZeroU64::MIN.saturating_add(29_999)
}

const fn connections() -> NonZeroUsize {
    NonZeroUsize::MIN.saturating_add(63)
}

impl Lys {
    /// The lys block's fields, each refused by its own name; `origin` is the
    /// door's, which the redirect returns to.
    fn check(&self, origin: &str) -> Result<(), String> {
        let issuer =
            url::Url::parse(&self.issuer).map_err(|_| "lys issuer is not an address".to_owned())?;
        if !matches!(issuer.scheme(), "http" | "https") {
            return Err("lys issuer must be an http or https address".to_owned());
        }
        if self.client_id.is_empty() || self.client_id.chars().any(char::is_control) {
            return Err("lys client_id must be a name with no control character".to_owned());
        }
        if !self.secret_file.is_absolute() {
            return Err("lys secret_file must be an absolute path".to_owned());
        }
        if self.redirect != format!("{origin}/callback") {
            return Err("lys redirect must be the origin's /callback".to_owned());
        }
        Ok(())
    }
}

/// The refusal of a door whose stores do not name [`STUDIO_STORE`]: one
/// sentence naming it, what Studio keeps there, and the line to add, shaped
/// as the configuration's own entries are: a socket beside the first socket
/// it names, or an endpoint entry when every store is on another machine.
fn studio_missing(stores: &BTreeMap<String, Store>) -> String {
    let entry = stores
        .values()
        .find_map(|store| match store {
            Store::Socket(socket) => Some(
                serde_json::Value::from(
                    socket
                        .with_file_name("studio.sock")
                        .to_string_lossy()
                        .into_owned(),
                )
                .to_string(),
            ),
            Store::Network(_) => None,
        })
        .unwrap_or_else(|| {
            "{\"endpoint\": \"<host>:<port>\", \"server_name\": \"<TLS name>\"}".to_owned()
        });
    format!(
        "Studio keeps its arrangements and saved views in a store named {STUDIO_STORE}, and this \
         door's stores name none: serve a store for Studio and add it to stores, as \
         \"{STUDIO_STORE}\": {entry}."
    )
}

impl Config {
    /// The configuration in `bytes`, checked whole.
    ///
    /// # Errors
    ///
    /// A message naming the field that is missing, unknown or unsafe.
    pub fn parse(bytes: &[u8]) -> Result<Self, String> {
        let config: Self = serde_json::from_slice(bytes)
            .map_err(|error| format!("the door configuration is not valid: {error}"))?;
        config.check()?;
        Ok(config)
    }

    fn check(&self) -> Result<(), String> {
        super::children::check(&self.children, &self.stores)?;
        if self
            .assistant
            .as_ref()
            .is_some_and(|assistant| !assistant.socket.is_absolute())
        {
            return Err("assistant.socket must be absolute".to_owned());
        }
        if !self.listen.ip().is_loopback() {
            return Err("listen must be a loopback address behind a TLS proxy".to_owned());
        }
        match &self.lys {
            Some(_) => {
                let origin = url::Url::parse(&self.origin)
                    .map_err(|_| "origin is not an address".to_owned())?;
                if origin.scheme() != "https"
                    || origin.origin().ascii_serialization() != self.origin
                {
                    return Err(
                        "origin must be an https origin with no path, as the browser sends it"
                            .to_owned(),
                    );
                }
            }
            None => local_origin(&self.origin)?,
        }
        if !self.files.is_absolute() {
            return Err("files must be an absolute folder".to_owned());
        }
        if self.stores.is_empty() {
            return Err("stores must name at least one store".to_owned());
        }
        for (name, store) in &self.stores {
            if name.is_empty()
                || !name
                    .bytes()
                    .all(|byte| byte.is_ascii_alphanumeric() || byte == b'-' || byte == b'_')
            {
                return Err(format!(
                    "store name {name:?} must be letters, digits, - or _"
                ));
            }
            match store {
                Store::Socket(socket) if !socket.is_absolute() => {
                    return Err(format!("store socket for {name} must be an absolute path"));
                }
                Store::Socket(_) => {}
                Store::Network(network) => network.check(name)?,
            }
        }
        if let Some(lys) = &self.lys {
            lys.check(&self.origin)?;
        }
        // Last, so each field's own refusal is said first (ACCESS-004 R1).
        if !self.stores.contains_key(STUDIO_STORE) {
            return Err(studio_missing(&self.stores));
        }
        Ok(())
    }

    /// Whether the door signs people in through Lys: it has a lys block.
    #[must_use]
    pub const fn through_lys(&self) -> bool {
        self.lys.is_some()
    }

    /// The bound on each store connection's steps.
    #[must_use]
    pub const fn timeout(&self) -> Duration {
        Duration::from_millis(self.timeout_ms.get())
    }

    /// Where each store is reached, a network store verified against `trust`.
    ///
    /// # Errors
    ///
    /// The entry that does not parse, which [`Config::parse`] already refused.
    pub fn addresses(&self, trust: &Trust) -> Result<BTreeMap<String, Address>, String> {
        self.stores
            .iter()
            .map(|(name, store)| {
                let address = match store {
                    Store::Socket(socket) => Address::Socket(socket.clone()),
                    Store::Network(network) => Address::Network(
                        Remote::new(
                            network.endpoint.as_deref().unwrap_or_default(),
                            network.server_name.as_deref().unwrap_or_default(),
                            trust,
                        )
                        .map_err(|why| {
                            format!("door_store_endpoint_invalid: store {name}: {why}")
                        })?,
                    ),
                };
                Ok((name.clone(), address))
            })
            .collect()
    }

    /// What the door serves, its network stores verified against `trust`.
    ///
    /// # Errors
    ///
    /// As [`Config::addresses`].
    pub fn site(&self, trust: &Trust) -> Result<Site, String> {
        Ok(Site {
            origin: self.origin.clone(),
            files: self.files.clone(),
            stores: self.addresses(trust)?,
            store_children: self
                .children
                .iter()
                .filter_map(|child| {
                    child.store.as_ref().map(|store| {
                        (
                            store.clone(),
                            (child.name.clone(), std::sync::Arc::clone(&child.given_up)),
                        )
                    })
                })
                .collect(),
            timeout: self.timeout(),
            packed: Packed::default(),
        })
    }

    /// The door's bounds on its connections.
    #[must_use]
    pub const fn limits(&self) -> Limits {
        Limits {
            max_connections: self.max_connections.get(),
            read_timeout: READ_TIMEOUT,
            head_cap: HEAD_CAP,
            body_cap: BODY_CAP,
        }
    }
}

/// A door with no lys block serves only the machine it runs on: its origin
/// is http or https on `127.0.0.1`, `localhost` or `[::1]`
/// ([`crate::loopback_http::host`]), with no path, as the browser sends it.
fn local_origin(origin: &str) -> Result<(), String> {
    let refused = || {
        format!(
            "door_local_origin_not_loopback: origin {origin} is not an http or https origin on \
             127.0.0.1, localhost or [::1] with no path; a door with no lys block serves only \
             this machine, and a lys block is needed for any other origin"
        )
    };
    let parsed = url::Url::parse(origin).map_err(|_| refused())?;
    let loopback = parsed.host_str().is_some_and(crate::loopback_http::host);
    if !matches!(parsed.scheme(), "http" | "https")
        || !loopback
        || parsed.origin().ascii_serialization() != origin
    {
        return Err(refused());
    }
    Ok(())
}

#[cfg(test)]
#[path = "config_tests.rs"]
mod tests;

/// Bounds read from the process configuration, with no environment mutation.
/// Defaults: 512 pending states, 12 hour sessions, 5 second connects and
/// 30 second whole Lys requests.
#[derive(Clone, Copy)]
pub struct SignInBounds {
    pub max_pending: NonZeroUsize,
    pub session_seconds: NonZeroU64,
    pub connect_ms: NonZeroU64,
    pub total_ms: NonZeroU64,
}

impl Default for SignInBounds {
    fn default() -> Self {
        Self {
            max_pending: NonZeroUsize::MIN.saturating_add(511),
            session_seconds: NonZeroU64::MIN.saturating_add(43_199),
            connect_ms: NonZeroU64::MIN.saturating_add(4_999),
            total_ms: timeout(),
        }
    }
}

impl SignInBounds {
    /// Read sign-in bounds from process configuration.
    ///
    /// # Errors
    ///
    /// Names an invalid bound, a connect bound beyond the total, or an unrepresentable timeout.
    pub fn from_env() -> Result<Self, String> {
        let defaults = Self::default();
        let max_pending = positive_env(
            "HAEMATITE_PENDING_SIGNINS",
            defaults.max_pending.get() as u64,
        )?;
        let bounds = Self {
            max_pending: usize::try_from(max_pending.get())
                .ok()
                .and_then(NonZeroUsize::new)
                .ok_or("HAEMATITE_PENDING_SIGNINS exceeds this machine's range")?,
            session_seconds: positive_env(
                "HAEMATITE_SESSION_SECONDS",
                defaults.session_seconds.get(),
            )?,
            connect_ms: positive_env(
                "HAEMATITE_LYS_CONNECT_TIMEOUT_MS",
                defaults.connect_ms.get(),
            )?,
            total_ms: positive_env("HAEMATITE_LYS_TIMEOUT_MS", defaults.total_ms.get())?,
        };
        if bounds.connect_ms > bounds.total_ms {
            return Err(
                "HAEMATITE_LYS_CONNECT_TIMEOUT_MS exceeds HAEMATITE_LYS_TIMEOUT_MS".to_owned(),
            );
        }
        if std::time::Instant::now()
            .checked_add(Duration::from_millis(bounds.total_ms.get()))
            .is_none()
        {
            return Err("HAEMATITE_LYS_TIMEOUT_MS exceeds the monotonic clock".to_owned());
        }
        Ok(bounds)
    }
}

pub(crate) fn positive_env(name: &str, default: u64) -> Result<NonZeroU64, String> {
    match std::env::var(name) {
        Ok(value) => value
            .parse()
            .map_err(|_| format!("{name} must be a positive integer")),
        Err(std::env::VarError::NotPresent) => {
            NonZeroU64::new(default).ok_or_else(|| format!("{name} has a zero default"))
        }
        Err(std::env::VarError::NotUnicode(_)) => Err(format!("{name} must be a positive integer")),
    }
}