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    /// The name is under a path the mesh reserves (`E_NAME_RESERVED`, CONTRACT-0.4.9 H8).
171    Reserved(String),
172}
173
174impl std::fmt::Display for DeclareError {
175    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
176        match self {
177            DeclareError::StartBeforeNow { fn_name, start, now } => {
178                write!(f, "declaration start {start} of {fn_name} is earlier than the mesh clock {now} (rule A)")
179            }
180            DeclareError::EndBeforeNow { fn_name, end, now } => {
181                write!(f, "declaration end {end} of {fn_name} is earlier than the mesh clock {now} (rule A)")
182            }
183            DeclareError::Key(e) => write!(f, "{e}"),
184            DeclareError::Store(e) => f.write_str(e),
185            DeclareError::Reserved(e) => f.write_str(e),
186        }
187    }
188}
189
190impl std::error::Error for DeclareError {}
191
192/// As [`with_declaration`], for the store's key document of `host` (since CONTRACT-1.8b H1): the
193/// declaration is written with `put_namespace` at the clock's now. Rule A: an explicit
194/// `valid_from` or `valid_to` earlier than the clock's now is refused, with nothing written; with
195/// no `valid_from` it is now. The document is read from `store`, which must hold one.
196pub fn declare_at<S: Store + ?Sized>(
197    store: &S,
198    host: &str,
199    fn_name: &str,
200    licence: &str,
201    valid_from: Option<&str>,
202    valid_to: Option<&str>,
203    clock: &dyn Clock,
204) -> Result<Declared, DeclareError> {
205    let now = clock.now();
206    crate::reserved::check(host, fn_name, None).map_err(DeclareError::Reserved)?;
207    if let Some(start) = valid_from.filter(|f| *f < now.as_str()) {
208        return Err(DeclareError::StartBeforeNow { fn_name: fn_name.into(), start: start.into(), now });
209    }
210    if let Some(end) = valid_to.filter(|t| *t < now.as_str()) {
211        return Err(DeclareError::EndBeforeNow { fn_name: fn_name.into(), end: end.into(), now });
212    }
213    let existing = store
214        .namespace(host)
215        .map_err(|e| DeclareError::Store(e.to_string()))?
216        .ok_or_else(|| DeclareError::Store(format!("the store holds no key document of {host}")))?
217        .keydoc;
218    let from = valid_from.unwrap_or(now.as_str());
219    let (doc, what) = with_declaration(host, &existing, fn_name, licence, from, valid_to).map_err(DeclareError::Key)?;
220    if what != Declared::Unchanged {
221        store.put_namespace(host, &doc, &now).map_err(|e| DeclareError::Store(e.to_string()))?;
222    }
223    Ok(what)
224}
225
226/// The key document `existing` of `host` with the key `public` registered from `valid_from` (QUESTIONS-build2
227/// D39): the key is added beside the keys there are, and no key is rotated or closed. `None` when the document
228/// holds that key already (then nothing is to be written). The declarations are kept. Checked by 9.2.
229pub fn with_registered(
230    host: &str,
231    existing: &[u8],
232    public: &[u8; 32],
233    valid_from: &str,
234) -> Result<Option<Vec<u8>>, Error> {
235    keys_from_response(host, 200, Some(existing))?;
236    let v = json::parse(existing)?;
237    let id = datumesh_core::key_id(public);
238    let mut keys: Vec<Value> = match v.get("keys") {
239        Some(Value::Array(ks)) => ks.clone(),
240        _ => Vec::new(),
241    };
242    if keys.iter().any(|k| k.get("id").and_then(Value::as_str) == Some(id.as_str())) {
243        return Ok(None);
244    }
245    keys.push(Value::Object(vec![
246        ("alg".into(), Value::String("ed25519".into())),
247        ("id".into(), Value::String(id)),
248        ("public".into(), Value::String(datumesh_core::lexical::to_hex(public))),
249        ("valid_from".into(), Value::String(valid_from.to_string())),
250    ]));
251    let declarations = v.get("declarations").cloned();
252    document(host, keys, declarations).map(Some)
253}