1use datumesh_core::json::{self, Value};
5use datumesh_core::{
6 key_document_from_response, keys_from_response, Declaration, Declarations, Error, KeyDocument, SigningKey,
7};
8
9pub 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 let declarations = match existing {
54 Some(doc) => json::parse(doc)?.get("declarations").cloned(),
55 None => None,
56 };
57 document(host, keys, declarations)
58}
59
60fn 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#[non_exhaustive]
77#[derive(Clone, Copy, Debug, PartialEq, Eq)]
78pub enum Declared {
79 Added,
81 Closed,
83 Unchanged,
85}
86
87pub 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 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}