haematite-cli 0.31.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
//! Mutation identity and strict wire contracts for a single stored-format cut.

use haematite::tree::Hash;
use serde::{Deserialize, Deserializer, Serialize};

use super::protocol::{Change, Version};
use super::storage::Failure;

pub mod attribution;
pub mod envelopes;

mod receipt;
pub use receipt::Receipt;

pub(super) const FINGERPRINT_FORMAT: u32 = 1;
const FINGERPRINT_DOMAIN: &[u8] = b"haem.mutation.fingerprint\0";

/// An asserted identity, with no stored credential.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(try_from = "CallerWire")]
pub struct Caller {
    issuer: String,
    subject: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    responsible: Option<String>,
}

#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct CallerWire {
    issuer: String,
    subject: String,
    responsible: Option<String>,
}

impl Caller {
    /// Construct an asserted caller identity.
    ///
    /// # Errors
    /// Returns `invalid_identifier` when the issuer, subject or responsible person has an invalid identifier.
    pub fn new(
        issuer: impl Into<String>,
        subject: impl Into<String>,
        responsible: Option<String>,
    ) -> Result<Self, Failure> {
        let caller = Self {
            issuer: issuer.into(),
            subject: subject.into(),
            responsible,
        };
        identifier(&caller.issuer)?;
        identifier(&caller.subject)?;
        if let Some(person) = &caller.responsible {
            identifier(person)?;
        }
        Ok(caller)
    }

    /// Construct the identity of a local socket owner.
    ///
    /// # Errors
    /// Returns `invalid_identifier` for an invalid subject.
    pub fn local(subject: impl Into<String>) -> Result<Self, Failure> {
        Self::new("local", subject, None)
    }

    #[must_use]
    pub fn issuer(&self) -> &str {
        &self.issuer
    }

    #[must_use]
    pub fn subject(&self) -> &str {
        &self.subject
    }

    #[must_use]
    pub fn responsible(&self) -> Option<&str> {
        self.responsible.as_deref()
    }
}

/// The login name of this process's effective user, read once per process.
static OWNER: std::sync::OnceLock<Result<String, String>> = std::sync::OnceLock::new();

/// The owner of this process: `Caller::local` with its effective user's login name.
///
/// That user owns the service's socket and the door's listener alike
/// (docs/design/product/caller-and-access.md, "Standing alone"). The name is
/// read from the system, never from a request or the environment, and once
/// per process.
///
/// # Errors
/// `local_owner_unknown` when the system does not say the effective user's
/// login name, or `invalid_identifier` for a name no caller may carry.
pub fn local_owner() -> Result<Caller, Failure> {
    let name = OWNER
        .get_or_init(login_name)
        .as_ref()
        .map_err(|why| Failure::new("local_owner_unknown", why.clone()))?;
    Caller::local(name.clone())
}

/// The author every unit test's served context records: the local caller
/// `standalone`, as served reads were bound before ACCESS-003.
#[cfg(test)]
pub(crate) fn test_author() -> &'static Caller {
    static AUTHOR: std::sync::OnceLock<Caller> = std::sync::OnceLock::new();
    AUTHOR.get_or_init(|| Caller {
        issuer: "local".to_owned(),
        subject: "standalone".to_owned(),
        responsible: None,
    })
}

/// `id -un`: the effective user's login name, as the system's user database
/// answers it. The crate holds no unsafe code, so the lookup is the system's
/// own tool rather than a call into its C library.
fn login_name() -> Result<String, String> {
    let output = std::process::Command::new("/usr/bin/id")
        .arg("-un")
        .stdin(std::process::Stdio::null())
        .stderr(std::process::Stdio::null())
        .output()
        .map_err(|error| format!("/usr/bin/id could not be run: {error}"))?;
    if !output.status.success() {
        return Err(format!("/usr/bin/id -un answered {}", output.status));
    }
    let text = String::from_utf8(output.stdout)
        .map_err(|_| "/usr/bin/id -un answered a name that is not UTF-8".to_owned())?;
    let name = text.strip_suffix('\n').unwrap_or(&text);
    if name.is_empty() || name.contains('\n') {
        return Err("/usr/bin/id -un answered no single login name".to_owned());
    }
    Ok(name.to_owned())
}

impl TryFrom<CallerWire> for Caller {
    type Error = Failure;

    fn try_from(wire: CallerWire) -> Result<Self, Self::Error> {
        Self::new(wire.issuer, wire.subject, wire.responsible)
    }
}

/// Facts read at the contract's origin, including absent rows and interval gaps.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
pub enum ReadDependency {
    Document {
        collection: String,
        document_id: String,
    },
    Collection {
        collection: String,
    },
    /// Document ids in a lower-inclusive, upper-exclusive interval; absent bounds
    /// cover the collection boundary. Body and revision rows belong to this read.
    SourceInterval {
        collection: String,
        lower: Option<String>,
        upper: Option<String>,
    },
}

impl ReadDependency {
    fn validate(&self) -> Result<(), Failure> {
        match self {
            Self::Document {
                collection,
                document_id,
            } => {
                identifier(collection)?;
                identifier(document_id)
            }
            Self::Collection { collection } => identifier(collection),
            Self::SourceInterval {
                collection,
                lower,
                upper,
            } => {
                identifier(collection)?;
                for bound in [lower, upper].into_iter().flatten() {
                    if bound.len() > 512 || bound.contains('\0') {
                        return Err(Failure::new(
                            "invalid_dependency",
                            "interval bounds must contain at most 512 UTF-8 bytes and no NUL",
                        ));
                    }
                }
                if matches!((lower, upper), (Some(lower), Some(upper)) if lower > upper) {
                    return Err(Failure::new(
                        "invalid_dependency",
                        "interval lower bound exceeds its exclusive upper bound",
                    ));
                }
                Ok(())
            }
        }
    }
}

/// Exact-version and read-dependency semantics remain distinct.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
pub enum Contract {
    ExactVersion {
        expected: Version,
    },
    Dependencies {
        origin: Version,
        reads: Vec<ReadDependency>,
    },
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ContractKind {
    ExactVersion,
    Dependencies,
}

impl Contract {
    #[must_use]
    pub const fn origin(&self) -> Version {
        match self {
            Self::ExactVersion { expected } => *expected,
            Self::Dependencies { origin, .. } => *origin,
        }
    }

    #[must_use]
    pub const fn kind(&self) -> ContractKind {
        match self {
            Self::ExactVersion { .. } => ContractKind::ExactVersion,
            Self::Dependencies { .. } => ContractKind::Dependencies,
        }
    }

    fn validate(&self) -> Result<(), Failure> {
        if let Self::Dependencies { reads, .. } = self {
            for read in reads {
                read.validate()?;
            }
        }
        Ok(())
    }
}

/// An omitted caller is resolved by the trusted socket context, never by storage.
#[derive(Debug, Serialize, Deserialize)]
#[serde(try_from = "MutationWire")]
pub struct MutationRequest {
    request_id: String,
    branch: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    caller: Option<Caller>,
    contract: Contract,
    change: Change,
}

#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct MutationWire {
    request_id: String,
    branch: String,
    #[serde(default, deserialize_with = "present_caller")]
    caller: Option<Caller>,
    contract: Contract,
    change: Change,
}

fn present_caller<'de, D: Deserializer<'de>>(deserializer: D) -> Result<Option<Caller>, D::Error> {
    Caller::deserialize(deserializer).map(Some)
}

impl TryFrom<MutationWire> for MutationRequest {
    type Error = Failure;

    fn try_from(wire: MutationWire) -> Result<Self, Self::Error> {
        identifier(&wire.request_id)?;
        identifier(&wire.branch)?;
        wire.contract.validate()?;
        if let Change::Fork(fork) = &wire.change {
            identifier(&fork.name)?;
            placeable(&fork.name)?;
        }
        Ok(Self {
            request_id: wire.request_id,
            branch: wire.branch,
            caller: wire.caller,
            contract: wire.contract,
            change: wire.change,
        })
    }
}

impl MutationRequest {
    /// Decode and validate a mutation request.
    ///
    /// # Errors
    /// Returns `invalid_mutation` for malformed JSON, unknown members, invalid identifiers, invalid dependencies or an unplaceable fork name.
    pub fn decode(bytes: &[u8]) -> Result<Self, Failure> {
        serde_json::from_slice(bytes)
            .map_err(|error| Failure::new("invalid_mutation", error.to_string()))
    }

    /// Resolve an omitted caller from the trusted socket owner.
    ///
    /// # Errors
    /// Returns `invalid_identifier` if an omitted caller cannot be resolved from the supplied subject.
    pub fn resolve(self, socket_owner_subject: &str) -> Result<ResolvedMutation, Failure> {
        let caller = match self.caller {
            Some(caller) => caller,
            None => Caller::local(socket_owner_subject)?,
        };
        Ok(ResolvedMutation {
            request_id: self.request_id,
            branch: self.branch,
            caller,
            contract: self.contract,
            change: self.change,
        })
    }
}

/// Only a request with a resolved caller can be fingerprinted or receipted.
#[derive(Debug, Serialize)]
pub struct ResolvedMutation {
    request_id: String,
    branch: String,
    caller: Caller,
    contract: Contract,
    change: Change,
}

impl ResolvedMutation {
    #[must_use]
    pub fn request_id(&self) -> &str {
        &self.request_id
    }

    #[must_use]
    pub fn branch(&self) -> &str {
        &self.branch
    }

    #[must_use]
    pub const fn caller(&self) -> &Caller {
        &self.caller
    }

    #[must_use]
    pub const fn contract(&self) -> &Contract {
        &self.contract
    }

    #[must_use]
    pub const fn change(&self) -> &Change {
        &self.change
    }

    #[must_use]
    pub const fn origin(&self) -> Version {
        self.contract.origin()
    }

    /// Hash the versioned canonical request identity.
    ///
    /// # Errors
    /// Returns `storage_unavailable` if serializing the resolved request fails.
    pub fn fingerprint(&self) -> Result<String, Failure> {
        let mut bytes = FINGERPRINT_DOMAIN.to_vec();
        bytes.extend_from_slice(&FINGERPRINT_FORMAT.to_be_bytes());
        serde_json::to_writer(&mut bytes, self).map_err(Failure::storage)?;
        Ok(Hash::of(&bytes).to_string())
    }

    pub(super) fn destination(&self) -> &str {
        match &self.change {
            Change::Fork(fork) => &fork.name,
            _ => &self.branch,
        }
    }
}

/// A new branch is placed in Lys as `haematite.branch:<database>.<name>`, and a
/// Lys resource id holds only ASCII letters, digits, `_`, `-` and `.`. A name
/// outside that could be written but never placed, so no grant could ever
/// reach it: it is refused at the fork, by name.
pub(super) fn placeable(name: &str) -> Result<(), Failure> {
    if name
        .bytes()
        .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'-' | b'.'))
    {
        return Ok(());
    }
    Err(Failure::new(
        "branch_name_unplaceable",
        "a new branch name may hold only ASCII letters, digits, `_`, `-` and `.`, so Lys can place it",
    ))
}

pub(super) fn identifier(value: &str) -> Result<(), Failure> {
    if value.is_empty() || value.len() > 512 || value.contains('\0') {
        return Err(Failure::new(
            "invalid_identifier",
            "names must contain 1 to 512 UTF-8 bytes and no NUL",
        ));
    }
    Ok(())
}

#[cfg(test)]
#[path = "contracts/placeable_tests.rs"]
mod placeable_tests;