Skip to main content

deedar/
lib.rs

1//! One-writer deed store. Clients speak the Cap'n schema via [`Client`].
2//!
3//! ```text
4//! just deedar / any client
5//!           |
6//!      Client::create|get|list|find|trail|evidence|delete|leave|timestamp|current|migrate
7//!           |  Cap'n  (schema/deedar.capnp)
8//!           v
9//!        FsStore  -- write-once bytes + frozen deed + evidence
10//! ```
11
12use std::path::{Path, PathBuf};
13
14mod attest;
15mod current;
16mod digest;
17mod fs;
18mod host;
19mod import;
20mod leave;
21pub mod log;
22mod lookup;
23mod migrate;
24pub mod receipt;
25mod timestamp;
26mod url;
27pub mod vouch;
28mod wire;
29
30pub use attest::{Demand, Policy};
31pub use current::Walk;
32pub use deed::{
33    walk_trail, Body, Deed, DeedId, Draft, Error, Evidence, Face, FormField, Grant, Kind,
34    MailMessageId, Measure, ProducedBy, Result, Source, Step,
35};
36pub use digest::{deed_digest, resolve};
37pub use fs::{is_write_once_addr, FsStore};
38pub use fs::{Audit, Exporter, Missing};
39pub use import::{Imported, UnsignedHead};
40pub use log::{Entry as LogEntry, Head as LogHead};
41pub use lookup::{explain_accession, prefix_matches, PREFIX_CANDIDATES_SHOWN};
42pub use receipt::{
43    check_handover, check_since, kept_head, sign_head, Bridge, Handover, Receipt, SignedHead,
44};
45pub use timestamp::{imprint_hash, timestamp_req};
46pub use url::{default_store, open, StoreUrl};
47pub use vouch::{Checked, Vouch};
48pub use wire::{
49    decode_request, decode_response, encode_request, encode_response, Request, Response,
50};
51
52/// Status of `deedar check` and `deedar vouch check` when the check finished
53/// and the signer was not one the reader accepts.
54///
55/// 1 means the check did not finish: the bag does not check out, or the
56/// signature does not cover the bytes. This is the next status, so a script
57/// can tell those apart. The report is still printed, and the warning is
58/// still on stderr.
59pub const EXIT_UNTRUSTED_SIGNER: u8 = 2;
60
61/// Which rows of [`Client::list`] to keep.
62///
63/// An unset field does not constrain. Fields that are set all have to match.
64/// `kind` is the deed's kind and `agent` is the agent id the writer stamped,
65/// both compared exactly: an agent id is an identifier, not prose.
66/// `text` is a case-insensitive substring of the name or of the body's
67/// excerpt, title, subject, step text or url. An edition, a form value, a
68/// table measure and an event's where are not those fields, so they do not
69/// count. Nothing is ranked, indexed or capped.
70#[derive(Clone, Debug, Default, PartialEq, Eq)]
71pub struct Filter {
72    pub kind: Option<Kind>,
73    pub agent: Option<String>,
74    pub text: Option<String>,
75}
76
77impl Filter {
78    fn matches(&self, deed: &Deed) -> bool {
79        if self.kind.as_ref().is_some_and(|kind| deed.kind != *kind) {
80            return false;
81        }
82        if self
83            .agent
84            .as_ref()
85            .is_some_and(|agent| deed.produced_by.agent_id != *agent)
86        {
87            return false;
88        }
89        if self
90            .text
91            .as_ref()
92            .is_some_and(|text| !text_matches(deed, text))
93        {
94            return false;
95        }
96        true
97    }
98}
99
100/// The empty substring is contained in every string, so an empty `text`
101/// keeps every deed. Any other needle matches when one searched field
102/// contains it on its own: the name and a body's fields are not joined
103/// into one string. Case follows [`str::to_lowercase`], the standard
104/// library's Unicode case fold, so a title matches the way a seat typed it.
105fn text_matches(deed: &Deed, needle: &str) -> bool {
106    if needle.is_empty() {
107        return true;
108    }
109    let needle = needle.to_lowercase();
110    let hit = |hay: &str| hay.to_lowercase().contains(&needle);
111    if hit(&deed.name) {
112        return true;
113    }
114    match &deed.body {
115        Body::Quote { excerpt, urls, .. } => hit(excerpt) || urls.iter().any(|url| hit(url)),
116        Body::Set { title, .. } => hit(title),
117        Body::MailDraft { subject, .. } => hit(subject),
118        Body::Page { url, .. } => hit(url),
119        Body::Procedure { steps } => steps.iter().any(|step| hit(&step.text)),
120        Body::File { .. }
121        | Body::Patch { .. }
122        | Body::Clip { .. }
123        | Body::Form { .. }
124        | Body::Table { .. }
125        | Body::Event { .. } => false,
126    }
127}
128
129/// Agent and grants the writer stamps onto the deed.
130pub struct CreateRequest {
131    pub id: Option<DeedId>,
132    pub name: String,
133    pub sources: Vec<Source>,
134    pub agent_id: String,
135    pub activity_id: Option<String>,
136    pub grants: Vec<Grant>,
137    pub body: Body,
138    /// Prior accession this take replaces. Sidecar only; not a Deed field.
139    pub supersedes: Option<DeedId>,
140}
141
142/// Cap'n client. Same path the `deedar` command uses.
143pub struct Client {
144    store: FsStore,
145}
146
147impl Client {
148    pub fn open(url: &str) -> Result<Self> {
149        Ok(Self {
150            store: crate::url::open(url)?,
151        })
152    }
153
154    /// The store directory this client acts on.
155    pub fn dir(&self) -> &std::path::Path {
156        self.store.dir()
157    }
158
159    /// See [`FsStore::signer_public`].
160    #[must_use]
161    pub fn signer_public(&self) -> Option<String> {
162        self.store.signer_public()
163    }
164
165    /// See [`FsStore::unaccepted_signer`].
166    #[must_use]
167    pub fn unaccepted_signer(&self) -> Option<String> {
168        self.store.unaccepted_signer()
169    }
170
171    pub fn create(&mut self, req: CreateRequest) -> Result<(Deed, deed::Evidence)> {
172        let bytes = wire::encode_request(&Request::Create(Box::new(req)))?;
173        match wire::decode_response(&self.store.handle(&bytes)?)? {
174            Response::Created { deed, evidence } => Ok((deed, evidence)),
175            Response::Err(e) => Err(map_err(&e)),
176            _ => Err(deed::Error::Decode("create response".into())),
177        }
178    }
179
180    pub fn resolve(&mut self, raw: &str) -> Result<DeedId> {
181        crate::digest::resolve(&self.store, raw)
182    }
183
184    /// The head over everything the store has logged.
185    ///
186    /// Read straight off the store rather than through the wire, because the
187    /// log is about what this store holds and a reader asking a store to
188    /// summarise itself over a protocol has learned nothing it did not
189    /// already have to trust.
190    ///
191    /// # Errors
192    ///
193    /// Fails when the log cannot be read.
194    pub fn log_head(&self) -> Result<log::Head> {
195        self.store.log_head()
196    }
197
198    /// Every entry in the log, oldest first.
199    ///
200    /// # Errors
201    ///
202    /// Fails when the log cannot be read.
203    pub fn log_entries(&self) -> Result<Vec<log::Entry>> {
204        self.store.log_entries()
205    }
206
207    /// Where a deed sits in the log, and the audit path to the root.
208    ///
209    /// # Errors
210    ///
211    /// Fails when the log cannot be read or holds no entry for `id`.
212    pub fn log_proof(&self, id: &DeedId) -> Result<(usize, Vec<[u8; 32]>)> {
213        self.store.log_proof(id)
214    }
215
216    /// The checkable record for one deed: its place in the log, the path to
217    /// the head, and the rest of what the leaf hashes over.
218    ///
219    /// # Errors
220    ///
221    /// Fails when the deed is absent or the log holds no entry for it.
222    pub fn receipt(&self, id: &DeedId) -> Result<Receipt> {
223        self.store.receipt(id)
224    }
225
226    /// The record joining a head somebody already holds to this log's own.
227    ///
228    /// # Errors
229    ///
230    /// Fails when `from` is zero or larger than this log.
231    pub fn bridge(&self, from: usize) -> Result<Bridge> {
232        self.store.bridge(from)
233    }
234
235    /// This log's head, signed when the store holds a key.
236    ///
237    /// # Errors
238    ///
239    /// Fails when the log cannot be read or a configured key cannot be used.
240    pub fn signed_head(&self) -> Result<Option<SignedHead>> {
241        self.store.signed_head()
242    }
243
244    /// One reading of the log for a handover of many deeds; see
245    /// [`FsStore::exporter`].
246    ///
247    /// # Errors
248    ///
249    /// Fails when the log cannot be read.
250    pub fn exporter(&self) -> Result<Exporter<'_>> {
251        self.store.exporter()
252    }
253
254    /// Write one deed into a satchel with the proof it was already logged.
255    ///
256    /// # Errors
257    ///
258    /// Fails when the deed is absent, unlogged, or `into` cannot be written.
259    pub fn export_into(&self, id: &DeedId, into: &Path) -> Result<Vec<PathBuf>> {
260        self.store.export_into(id, into)
261    }
262
263    /// Check a handover and add the deeds it carried to this store; see
264    /// [`FsStore::import_handover`].
265    ///
266    /// # Errors
267    ///
268    /// Fails, having written nothing, when the bag does not check out, its
269    /// head is not one `unsigned` lets through, or a deed in it cannot be held
270    /// here as the sender held it.
271    pub fn import_handover(&mut self, dir: &Path, unsigned: UnsignedHead) -> Result<Imported> {
272        self.store.import_handover(dir, unsigned)
273    }
274
275    /// What the log says the store holds, against what it will hand over.
276    ///
277    /// # Errors
278    ///
279    /// Fails when the log cannot be read.
280    pub fn log_audit(&self) -> Result<Audit> {
281        self.store.log_audit()
282    }
283
284    /// Log every deed the store serves that the log does not name.
285    ///
286    /// # Errors
287    ///
288    /// Fails when the store or the log cannot be read or appended to.
289    pub fn log_backfill(&self) -> Result<Vec<String>> {
290        self.store.log_backfill()
291    }
292
293    pub fn get(&mut self, id: &DeedId) -> Result<Deed> {
294        let bytes = wire::encode_request(&Request::Get(id.clone()))?;
295        match wire::decode_response(&self.store.handle(&bytes)?)? {
296            Response::Deed(d) => Ok(d),
297            Response::Err(e) => Err(map_err(&e)),
298            _ => Err(deed::Error::Decode("get response".into())),
299        }
300    }
301
302    pub fn list(&mut self) -> Result<Vec<Deed>> {
303        let bytes = wire::encode_request(&Request::List)?;
304        match wire::decode_response(&self.store.handle(&bytes)?)? {
305            Response::Deeds(ds) => Ok(ds),
306            Response::Err(e) => Err(map_err(&e)),
307            _ => Err(deed::Error::Decode("list response".into())),
308        }
309    }
310
311    /// The deeds [`Self::list`] would return that match `filter`, in that
312    /// same accession order.
313    ///
314    /// # Errors
315    ///
316    /// Fails when the shelf cannot be read, as [`Self::list`] does.
317    pub fn find(&mut self, filter: &Filter) -> Result<Vec<Deed>> {
318        let deeds = self.list()?;
319        Ok(deeds
320            .into_iter()
321            .filter(|deed| filter.matches(deed))
322            .collect())
323    }
324
325    pub fn trail(&mut self, id: &DeedId) -> Result<Vec<Deed>> {
326        let bytes = wire::encode_request(&Request::Trail(id.clone()))?;
327        match wire::decode_response(&self.store.handle(&bytes)?)? {
328            Response::Deeds(ds) => Ok(ds),
329            Response::Err(e) => Err(map_err(&e)),
330            _ => Err(deed::Error::Decode("trail response".into())),
331        }
332    }
333
334    pub fn delete(&mut self, id: &DeedId) -> Result<()> {
335        let bytes = wire::encode_request(&Request::Delete(id.clone()))?;
336        match wire::decode_response(&self.store.handle(&bytes)?)? {
337            Response::Ok => Ok(()),
338            Response::Err(e) => Err(map_err(&e)),
339            _ => Err(deed::Error::Decode("delete response".into())),
340        }
341    }
342
343    pub fn evidence(&mut self, id: &DeedId) -> Result<deed::Evidence> {
344        let bytes = wire::encode_request(&Request::Evidence(id.clone()))?;
345        match wire::decode_response(&self.store.handle(&bytes)?)? {
346            Response::Evidence(ev) => Ok(ev),
347            Response::Err(e) => Err(map_err(&e)),
348            _ => Err(deed::Error::Decode("evidence response".into())),
349        }
350    }
351
352    pub fn leave(&mut self, id: &DeedId, dest: &Path) -> Result<PathBuf> {
353        let bytes = wire::encode_request(&Request::Leave {
354            id: id.clone(),
355            dest: dest.to_path_buf(),
356        })?;
357        match wire::decode_response(&self.store.handle(&bytes)?)? {
358            Response::Ok => Ok(dest.join(id.as_str())),
359            Response::Err(e) => Err(map_err(&e)),
360            _ => Err(deed::Error::Decode("leave response".into())),
361        }
362    }
363
364    pub fn timestamp(&mut self, id: &DeedId) -> Result<PathBuf> {
365        let bytes = wire::encode_request(&Request::Timestamp(id.clone()))?;
366        match wire::decode_response(&self.store.handle(&bytes)?)? {
367            Response::Ok => {
368                let deeds = self.store.dir().join("deeds");
369                let tsr = deeds.join(format!("{id}.tsr"));
370                if tsr.exists() {
371                    Ok(tsr)
372                } else {
373                    Ok(deeds.join(format!("{id}.tsq")))
374                }
375            }
376            Response::Err(e) => Err(map_err(&e)),
377            _ => Err(deed::Error::Decode("timestamp response".into())),
378        }
379    }
380
381    pub fn current(&mut self, id: &DeedId) -> Result<Deed> {
382        let bytes = wire::encode_request(&Request::Current(id.clone()))?;
383        match wire::decode_response(&self.store.handle(&bytes)?)? {
384            Response::Deed(d) => Ok(d),
385            Response::Err(e) => Err(map_err(&e)),
386            _ => Err(deed::Error::Decode("current response".into())),
387        }
388    }
389
390    /// Where the supersede walk from `id` ended.
391    ///
392    /// Read straight off the store rather than through the wire. The wire
393    /// carries a fork or a cycle as `invalid body:` text, and
394    /// [`Self::current`] returns that as `InvalidBody`. The command prints
395    /// it and exits 0. This returns the accessions the walk found, in
396    /// accession order.
397    ///
398    /// # Errors
399    ///
400    /// `NotFound` when the deed the walk ends on is missing, and
401    /// `Tombstoned` when that deed is tombstoned. A sidecar that does not
402    /// parse, or a deeds directory that cannot be read, returns that error.
403    /// A fork or a cycle is [`Walk::Fork`] or [`Walk::Cycle`], not an error.
404    pub fn current_walk(&self, id: &DeedId) -> Result<Walk> {
405        self.store.current_walk(id)
406    }
407
408    pub fn migrate(&mut self) -> Result<()> {
409        self.store.migrate()
410    }
411
412    /// See [`FsStore::accept_host_signer`].
413    pub fn accept_host_signer(&mut self) -> Result<Option<(String, bool)>> {
414        self.store.accept_host_signer()
415    }
416}
417
418fn map_err(msg: &str) -> deed::Error {
419    if let Some(s) = msg.strip_prefix("deed frozen: ") {
420        deed::Error::Frozen(s.into())
421    } else if let Some(s) = msg.strip_prefix("deed tombstoned: ") {
422        deed::Error::Tombstoned(s.into())
423    } else if let Some(s) = msg.strip_prefix("deed not found: ") {
424        deed::Error::NotFound(s.into())
425    } else if let Some(s) = msg.strip_prefix("evidence: ") {
426        deed::Error::Evidence(s.into())
427    } else if let Some(s) = msg.strip_prefix("invalid deed id: ") {
428        deed::Error::InvalidId(s.into())
429    } else if let Some(s) = msg.strip_prefix("invalid kind: ") {
430        deed::Error::InvalidKind(s.into())
431    } else if let Some(s) = msg.strip_prefix("invalid url: ") {
432        deed::Error::InvalidUrl(s.into())
433    } else if let Some(s) = msg.strip_prefix("invalid message-id: ") {
434        deed::Error::InvalidMessageId(s.into())
435    } else if let Some(s) = msg.strip_prefix("invalid body: ") {
436        deed::Error::InvalidBody(s.into())
437    } else if let Some(s) = msg.strip_prefix("store decode: ") {
438        deed::Error::Decode(s.into())
439    } else if let Some(s) = msg.strip_prefix("store io: ") {
440        deed::Error::Io(s.into())
441    } else {
442        deed::Error::Io(msg.into())
443    }
444}
445
446pub fn store_dir(url: &str) -> Result<PathBuf> {
447    StoreUrl::parse(url).map(|u| u.dir().to_path_buf())
448}
449
450pub fn ensure_dir(dir: impl AsRef<Path>) -> Result<PathBuf> {
451    let dir = dir.as_ref();
452    std::fs::create_dir_all(dir).map_err(|e| deed::Error::Io(e.to_string()))?;
453    Ok(dir.to_path_buf())
454}