Skip to main content

datumesh_http/
keydoc.rs

1//! Key documents (SPEC 9.2) for the mesh's own host, rotation (SPEC 9.5), and since 0.2.1
2//! their declarations (spec-0.4.3).
3
4use datumesh_core::json::{self, Value};
5use datumesh_core::{
6    key_document_from_response, keys_from_response, Declaration, Declarations, Error, KeyDocument, SigningKey,
7};
8use datumesh_engine::Clock;
9use datumesh_store::Store;
10
11/// The key document of `host` publishing `key` from `valid_from`, after the keys of
12/// `existing` (a document already published for `host`, if any): rotation as SPEC 9.5 says,
13/// each existing key without a `valid_to` (or with a later one) ending at `valid_from`. A key
14/// already in `existing` is not added again. The result is canonical JSON, checked by 9.2.
15pub fn with_key(host: &str, existing: Option<&[u8]>, key: &SigningKey, valid_from: &str) -> Result<Vec<u8>, Error> {
16    let public = datumesh_core::lexical::to_hex(&key.public_key());
17    let mut keys: Vec<Value> = Vec::new();
18    let mut present = false;
19    if let Some(doc) = existing {
20        keys_from_response(host, 200, Some(doc))?;
21        let v = json::parse(doc)?;
22        if let Some(Value::Array(ks)) = v.get("keys") {
23            for k in ks {
24                let Value::Object(members) = k else { continue };
25                if k.get("id").and_then(Value::as_str) == Some(key.key_id()) {
26                    present = true;
27                    keys.push(k.clone());
28                    continue;
29                }
30                let ends_later = match k.get("valid_to").and_then(Value::as_str) {
31                    None => true,
32                    Some(t) => t > valid_from,
33                };
34                let starts_before = k.get("valid_from").and_then(Value::as_str).is_some_and(|f| f < valid_from);
35                if ends_later && starts_before {
36                    let mut m: Vec<(String, Value)> =
37                        members.iter().filter(|(n, _)| n != "valid_to").cloned().collect();
38                    m.push(("valid_to".into(), Value::String(valid_from.to_string())));
39                    keys.push(Value::Object(m));
40                } else {
41                    keys.push(k.clone());
42                }
43            }
44        }
45    }
46    if !present {
47        keys.push(Value::Object(vec![
48            ("alg".into(), Value::String("ed25519".into())),
49            ("id".into(), Value::String(key.key_id().to_string())),
50            ("public".into(), Value::String(public)),
51            ("valid_from".into(), Value::String(valid_from.to_string())),
52        ]));
53    }
54    // Since 0.2.1: the existing document's `declarations` (spec-0.4.3) are kept as they are.
55    let declarations = match existing {
56        Some(doc) => json::parse(doc)?.get("declarations").cloned(),
57        None => None,
58    };
59    document(host, keys, declarations)
60}
61
62/// The canonical key document of `host` from its `keys` and optional `declarations`
63/// members, checked by 9.2 (declarations included).
64fn document(host: &str, keys: Vec<Value>, declarations: Option<Value>) -> Result<Vec<u8>, Error> {
65    let mut members = Vec::new();
66    if let Some(d) = declarations {
67        members.push(("declarations".into(), d));
68    }
69    members.push(("host".into(), Value::String(host.to_string())));
70    members.push(("keys".into(), Value::Array(keys)));
71    members.push(("proto".into(), Value::String("datumesh/1".into())));
72    let doc = Value::Object(members).to_jcs();
73    key_document_from_response(host, 200, Some(&doc))?;
74    Ok(doc)
75}
76
77/// What [`with_declaration`] did to the key document.
78#[non_exhaustive]
79#[derive(Clone, Copy, Debug, PartialEq, Eq)]
80pub enum Declared {
81    /// The entry was added.
82    Added,
83    /// An open entry with the same `licence` and `valid_from` was closed at `valid_to`.
84    Closed,
85    /// The document already has exactly this entry: unchanged (the same bytes).
86    Unchanged,
87}
88
89/// The key document `existing` of `host` with a declaration (SPEC 9.2, spec-0.4.3): `fn_name`
90/// (a full function name under `host`) may be computed over inputs under the restricted
91/// `licence` from `valid_from` (an instant) until `valid_to` (absent: open-ended), the result
92/// carrying that licence (SPEC 8.5). Since 0.2.1.
93///
94/// Entries are never removed, only closed: an entry exactly as given leaves the document
95/// unchanged (so a declaration step can run again); an open entry with the same `licence` and
96/// `valid_from`, given a `valid_to`, is closed then; any other entry with the same `licence`
97/// and `valid_from` is refused (`E_KEY_DOC`), as is anything 9.2 rejects (a name under another
98/// host, a bad licence or instant, more than 64 names or 16 entries). The keys are kept as
99/// they are. The result is canonical JSON, checked by 9.2.
100pub fn with_declaration(
101    host: &str,
102    existing: &[u8],
103    fn_name: &str,
104    licence: &str,
105    valid_from: &str,
106    valid_to: Option<&str>,
107) -> Result<(Vec<u8>, Declared), Error> {
108    let doc = KeyDocument::from_json(host, existing)?;
109    let entry = Declaration::new(licence, valid_from, valid_to)?;
110    let mut declarations = doc.declarations.unwrap_or_default();
111    let same_start = declarations.get(fn_name).iter().position(|e| e.licence == licence && e.valid_from == valid_from);
112    let (declarations, what) = match same_start {
113        Some(i) if declarations.get(fn_name)[i] == entry => return Ok((existing.to_vec(), Declared::Unchanged)),
114        Some(i) if declarations.get(fn_name)[i].valid_to.is_none() && valid_to.is_some() => {
115            // Rebuilt with that entry closed, every other entry as it was.
116            let mut out = Declarations::new();
117            for (name, entries) in declarations.iter() {
118                for (j, e) in entries.iter().enumerate() {
119                    let e = if name == fn_name && j == i { entry.clone() } else { e.clone() };
120                    out.insert(name, e)?;
121                }
122            }
123            (out, Declared::Closed)
124        }
125        Some(_) => {
126            return Err(Error::new(
127                datumesh_core::ErrorCode::KeyDoc,
128                "$.declarations",
129                format!("{fn_name} already has an entry for {licence} from {valid_from}: entries are never removed, only closed"),
130            ))
131        }
132        None => {
133            declarations.insert(fn_name, entry)?;
134            (declarations, Declared::Added)
135        }
136    };
137    let keys = match json::parse(existing)?.get("keys") {
138        Some(Value::Array(k)) => k.clone(),
139        _ => Vec::new(),
140    };
141    Ok((document(host, keys, Some(declarations.to_value()))?, what))
142}
143
144/// Why [`declare_at`] refused a declaration.
145#[non_exhaustive]
146#[derive(Debug)]
147pub enum DeclareError {
148    /// An explicit `valid_from` earlier than the mesh clock (rule A, CONTRACT-1.8b H1).
149    StartBeforeNow {
150        /// The function.
151        fn_name: String,
152        /// The `valid_from`.
153        start: String,
154        /// The mesh clock.
155        now: String,
156    },
157    /// A `valid_to` earlier than the mesh clock (rule A).
158    EndBeforeNow {
159        /// The function.
160        fn_name: String,
161        /// The `valid_to`.
162        end: String,
163        /// The mesh clock.
164        now: String,
165    },
166    /// The key document refuses the declaration (SPEC 9.2, as [`with_declaration`] says).
167    Key(Error),
168    /// The store refused: no key document of the host, or a write failed.
169    Store(String),
170}
171
172impl std::fmt::Display for DeclareError {
173    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
174        match self {
175            DeclareError::StartBeforeNow { fn_name, start, now } => {
176                write!(f, "declaration start {start} of {fn_name} is earlier than the mesh clock {now} (rule A)")
177            }
178            DeclareError::EndBeforeNow { fn_name, end, now } => {
179                write!(f, "declaration end {end} of {fn_name} is earlier than the mesh clock {now} (rule A)")
180            }
181            DeclareError::Key(e) => write!(f, "{e}"),
182            DeclareError::Store(e) => f.write_str(e),
183        }
184    }
185}
186
187impl std::error::Error for DeclareError {}
188
189/// As [`with_declaration`], for the store's key document of `host` (since CONTRACT-1.8b H1): the
190/// declaration is written with `put_namespace` at the clock's now. Rule A: an explicit
191/// `valid_from` or `valid_to` earlier than the clock's now is refused, with nothing written; with
192/// no `valid_from` it is now. The document is read from `store`, which must hold one.
193pub fn declare_at<S: Store + ?Sized>(
194    store: &S,
195    host: &str,
196    fn_name: &str,
197    licence: &str,
198    valid_from: Option<&str>,
199    valid_to: Option<&str>,
200    clock: &dyn Clock,
201) -> Result<Declared, DeclareError> {
202    let now = clock.now();
203    if let Some(start) = valid_from.filter(|f| *f < now.as_str()) {
204        return Err(DeclareError::StartBeforeNow { fn_name: fn_name.into(), start: start.into(), now });
205    }
206    if let Some(end) = valid_to.filter(|t| *t < now.as_str()) {
207        return Err(DeclareError::EndBeforeNow { fn_name: fn_name.into(), end: end.into(), now });
208    }
209    let existing = store
210        .namespace(host)
211        .map_err(|e| DeclareError::Store(e.to_string()))?
212        .ok_or_else(|| DeclareError::Store(format!("the store holds no key document of {host}")))?
213        .keydoc;
214    let from = valid_from.unwrap_or(now.as_str());
215    let (doc, what) = with_declaration(host, &existing, fn_name, licence, from, valid_to).map_err(DeclareError::Key)?;
216    if what != Declared::Unchanged {
217        store.put_namespace(host, &doc, &now).map_err(|e| DeclareError::Store(e.to_string()))?;
218    }
219    Ok(what)
220}