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};
8
9/// The key document of `host` publishing `key` from `valid_from`, after the keys of
10/// `existing` (a document already published for `host`, if any): rotation as SPEC 9.5 says,
11/// each existing key without a `valid_to` (or with a later one) ending at `valid_from`. A key
12/// already in `existing` is not added again. The result is canonical JSON, checked by 9.2.
13pub fn with_key(host: &str, existing: Option<&[u8]>, key: &SigningKey, valid_from: &str) -> Result<Vec<u8>, Error> {
14    let public = datumesh_core::lexical::to_hex(&key.public_key());
15    let mut keys: Vec<Value> = Vec::new();
16    let mut present = false;
17    if let Some(doc) = existing {
18        keys_from_response(host, 200, Some(doc))?;
19        let v = json::parse(doc)?;
20        if let Some(Value::Array(ks)) = v.get("keys") {
21            for k in ks {
22                let Value::Object(members) = k else { continue };
23                if k.get("id").and_then(Value::as_str) == Some(key.key_id()) {
24                    present = true;
25                    keys.push(k.clone());
26                    continue;
27                }
28                let ends_later = match k.get("valid_to").and_then(Value::as_str) {
29                    None => true,
30                    Some(t) => t > valid_from,
31                };
32                let starts_before = k.get("valid_from").and_then(Value::as_str).is_some_and(|f| f < valid_from);
33                if ends_later && starts_before {
34                    let mut m: Vec<(String, Value)> =
35                        members.iter().filter(|(n, _)| n != "valid_to").cloned().collect();
36                    m.push(("valid_to".into(), Value::String(valid_from.to_string())));
37                    keys.push(Value::Object(m));
38                } else {
39                    keys.push(k.clone());
40                }
41            }
42        }
43    }
44    if !present {
45        keys.push(Value::Object(vec![
46            ("alg".into(), Value::String("ed25519".into())),
47            ("id".into(), Value::String(key.key_id().to_string())),
48            ("public".into(), Value::String(public)),
49            ("valid_from".into(), Value::String(valid_from.to_string())),
50        ]));
51    }
52    // Since 0.2.1: the existing document's `declarations` (spec-0.4.3) are kept as they are.
53    let declarations = match existing {
54        Some(doc) => json::parse(doc)?.get("declarations").cloned(),
55        None => None,
56    };
57    document(host, keys, declarations)
58}
59
60/// The canonical key document of `host` from its `keys` and optional `declarations`
61/// members, checked by 9.2 (declarations included).
62fn document(host: &str, keys: Vec<Value>, declarations: Option<Value>) -> Result<Vec<u8>, Error> {
63    let mut members = Vec::new();
64    if let Some(d) = declarations {
65        members.push(("declarations".into(), d));
66    }
67    members.push(("host".into(), Value::String(host.to_string())));
68    members.push(("keys".into(), Value::Array(keys)));
69    members.push(("proto".into(), Value::String("datumesh/1".into())));
70    let doc = Value::Object(members).to_jcs();
71    key_document_from_response(host, 200, Some(&doc))?;
72    Ok(doc)
73}
74
75/// What [`with_declaration`] did to the key document.
76#[non_exhaustive]
77#[derive(Clone, Copy, Debug, PartialEq, Eq)]
78pub enum Declared {
79    /// The entry was added.
80    Added,
81    /// An open entry with the same `licence` and `valid_from` was closed at `valid_to`.
82    Closed,
83    /// The document already has exactly this entry: unchanged (the same bytes).
84    Unchanged,
85}
86
87/// The key document `existing` of `host` with a declaration (SPEC 9.2, spec-0.4.3): `fn_name`
88/// (a full function name under `host`) may be computed over inputs under the restricted
89/// `licence` from `valid_from` (an instant) until `valid_to` (absent: open-ended), the result
90/// carrying that licence (SPEC 8.5). Since 0.2.1.
91///
92/// Entries are never removed, only closed: an entry exactly as given leaves the document
93/// unchanged (so a declaration step can run again); an open entry with the same `licence` and
94/// `valid_from`, given a `valid_to`, is closed then; any other entry with the same `licence`
95/// and `valid_from` is refused (`E_KEY_DOC`), as is anything 9.2 rejects (a name under another
96/// host, a bad licence or instant, more than 64 names or 16 entries). The keys are kept as
97/// they are. The result is canonical JSON, checked by 9.2.
98pub fn with_declaration(
99    host: &str,
100    existing: &[u8],
101    fn_name: &str,
102    licence: &str,
103    valid_from: &str,
104    valid_to: Option<&str>,
105) -> Result<(Vec<u8>, Declared), Error> {
106    let doc = KeyDocument::from_json(host, existing)?;
107    let entry = Declaration::new(licence, valid_from, valid_to)?;
108    let mut declarations = doc.declarations.unwrap_or_default();
109    let same_start = declarations.get(fn_name).iter().position(|e| e.licence == licence && e.valid_from == valid_from);
110    let (declarations, what) = match same_start {
111        Some(i) if declarations.get(fn_name)[i] == entry => return Ok((existing.to_vec(), Declared::Unchanged)),
112        Some(i) if declarations.get(fn_name)[i].valid_to.is_none() && valid_to.is_some() => {
113            // Rebuilt with that entry closed, every other entry as it was.
114            let mut out = Declarations::new();
115            for (name, entries) in declarations.iter() {
116                for (j, e) in entries.iter().enumerate() {
117                    let e = if name == fn_name && j == i { entry.clone() } else { e.clone() };
118                    out.insert(name, e)?;
119                }
120            }
121            (out, Declared::Closed)
122        }
123        Some(_) => {
124            return Err(Error::new(
125                datumesh_core::ErrorCode::KeyDoc,
126                "$.declarations",
127                format!("{fn_name} already has an entry for {licence} from {valid_from}: entries are never removed, only closed"),
128            ))
129        }
130        None => {
131            declarations.insert(fn_name, entry)?;
132            (declarations, Declared::Added)
133        }
134    };
135    let keys = match json::parse(existing)?.get("keys") {
136        Some(Value::Array(k)) => k.clone(),
137        _ => Vec::new(),
138    };
139    Ok((document(host, keys, Some(declarations.to_value()))?, what))
140}