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 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
192pub 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
226pub 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}