1use 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
11pub 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 let declarations = match existing {
56 Some(doc) => json::parse(doc)?.get("declarations").cloned(),
57 None => None,
58 };
59 document(host, keys, declarations)
60}
61
62fn 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#[non_exhaustive]
79#[derive(Clone, Copy, Debug, PartialEq, Eq)]
80pub enum Declared {
81 Added,
83 Closed,
85 Unchanged,
87}
88
89pub 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 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#[non_exhaustive]
146#[derive(Debug)]
147pub enum DeclareError {
148 StartBeforeNow {
150 fn_name: String,
152 start: String,
154 now: String,
156 },
157 EndBeforeNow {
159 fn_name: String,
161 end: String,
163 now: String,
165 },
166 Key(Error),
168 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
189pub 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}