1use base64::Engine as _;
15use kute::{vocab, KuteError};
16use ring::signature::{Ed25519KeyPair, KeyPair, UnparsedPublicKey, ED25519};
17use serde_json::{json, Value};
18use std::path::Path;
19
20pub const ALGORITHM: &str = "ed25519";
21pub const MAX_SIGNATURES: usize = 16;
23const CONTEXT: &str = "kute-vocabulary-signature-v1\n";
27const PEM_HEAD: &str = "-----BEGIN PRIVATE KEY-----";
28const PEM_TAIL: &str = "-----END PRIVATE KEY-----";
29
30fn b64() -> base64::engine::GeneralPurpose {
31 base64::engine::general_purpose::STANDARD
32}
33
34fn message(digest: &str) -> Vec<u8> {
35 format!("{CONTEXT}{digest}").into_bytes()
36}
37
38pub fn key_id(public: &[u8]) -> String {
40 format!("{ALGORITHM}:{}", kute::sha256_tagged(public).trim_start_matches("sha256:"))
41}
42
43fn bad_key(why: &str) -> KuteError {
44 KuteError::InvalidInput(format!("not a usable signing key: {why}"))
45}
46
47fn load_key(path: &Path) -> kute::Result<Ed25519KeyPair> {
48 let size = std::fs::metadata(path).map_err(|e| KuteError::InvalidConfig(format!("the private key {}: {e}", path.display())))?.len();
51 if size > 16 * 1024 {
52 return Err(bad_key("the file is larger than a key"));
53 }
54 let text = std::fs::read_to_string(path).map_err(|_| bad_key("the file is not text"))?;
55 let body = text.trim().strip_prefix(PEM_HEAD).and_then(|rest| rest.strip_suffix(PEM_TAIL)).ok_or_else(|| bad_key("expected one PEM block labelled PRIVATE KEY"))?;
56 let der = b64().decode(body.split_whitespace().collect::<String>()).map_err(|_| bad_key("the PEM body is not base64"))?;
57 Ed25519KeyPair::from_pkcs8(&der).map_err(|_| bad_key("not an Ed25519 key in PKCS#8"))
58}
59
60fn public_of(text: &str) -> kute::Result<Vec<u8>> {
61 let key = b64().decode(text.trim()).map_err(|_| KuteError::InvalidInput(format!("a trusted key is not base64: {text:?}")))?;
62 if key.len() != 32 {
63 return Err(KuteError::InvalidInput(format!("a trusted key is {} bytes; an Ed25519 public key is 32", key.len())));
64 }
65 Ok(key)
66}
67
68pub fn keygen(output: &Path) -> kute::Result<Value> {
70 let random = ring::rand::SystemRandom::new();
71 let document = Ed25519KeyPair::generate_pkcs8(&random).map_err(|_| KuteError::Backend("the system gave no randomness".into()))?;
72 let pair = Ed25519KeyPair::from_pkcs8(document.as_ref()).map_err(|_| KuteError::Backend("the key just made cannot be read back".into()))?;
73 let encoded = b64().encode(document.as_ref());
74 let mut pem = String::from(PEM_HEAD);
75 pem.push('\n');
76 for line in encoded.as_bytes().chunks(64) {
77 pem.push_str(std::str::from_utf8(line).expect("base64 is ASCII"));
78 pem.push('\n');
79 }
80 pem.push_str(PEM_TAIL);
81 pem.push('\n');
82 let mut options = std::fs::OpenOptions::new();
83 options.write(true).create_new(true);
84 #[cfg(unix)]
85 {
86 use std::os::unix::fs::OpenOptionsExt;
87 options.mode(0o600);
88 }
89 use std::io::Write;
90 options.open(output)?.write_all(pem.as_bytes())?;
91 let public = pair.public_key().as_ref();
92 Ok(json!({
93 "private_key_file": output,
94 "public_key": b64().encode(public),
95 "key_id": key_id(public),
96 "algorithm": ALGORITHM,
97 "keep": "the private key file is not encrypted. On Unix it is readable by its owner only; on Windows it has the permissions of its folder.",
98 }))
99}
100
101struct Signed {
106 digest: String,
107 key_id: String,
108 already: bool,
109 replaced: usize,
110}
111
112fn attach(vocabulary: &mut kute::Vocabulary, pair: &Ed25519KeyPair) -> kute::Result<Signed> {
114 let digest = vocabulary.compute_digest()?;
116 vocabulary.seal()?;
117 let id = key_id(pair.public_key().as_ref());
118 let integrity = vocabulary.integrity.as_mut().expect("sealed");
119 let signature = b64().encode(pair.sign(&message(&digest)).as_ref());
125 let before = integrity.signatures.len();
126 let already = integrity.signatures.iter().any(|s| s.key_id == id && s.algorithm == ALGORITHM && s.signature == signature);
127 integrity.signatures.retain(|s| s.key_id != id);
128 let replaced = before - integrity.signatures.len() - usize::from(already);
129 if integrity.signatures.len() >= MAX_SIGNATURES {
130 return Err(KuteError::LimitExceeded(format!("the vocabulary already carries {MAX_SIGNATURES} signatures")));
131 }
132 integrity.signatures.push(kute::Signature { key_id: id.clone(), algorithm: ALGORITHM.into(), signature });
133 Ok(Signed { digest, key_id: id, already, replaced })
134}
135
136pub fn signer(key_path: &Path) -> kute::Result<impl Fn(&mut kute::Vocabulary) -> kute::Result<()> + use<>> {
140 let pair = load_key(key_path)?;
141 Ok(move |vocabulary: &mut kute::Vocabulary| attach(vocabulary, &pair).map(|_| ()))
142}
143
144pub fn sign(vocab_path: &Path, key_path: &Path, output: &Path, force: bool) -> kute::Result<Value> {
145 let pair = load_key(key_path)?;
146 let mut vocabulary = vocab::load(vocab_path)?;
147 let Signed { digest, key_id: id, already, replaced } = attach(&mut vocabulary, &pair)?;
148 vocab::save(&vocabulary, output, force)?;
149 let written = vocab::load(output)?;
150 Ok(json!({
151 "output": output,
152 "digest": digest,
153 "digest_unchanged": written.digest()? == digest,
154 "key_id": id,
155 "already_signed_by_this_key": already,
156 "entries_under_this_key_replaced": replaced,
157 "signatures": written.integrity.map_or(0, |i| i.signatures.len()),
158 }))
159}
160
161pub fn verify(vocab_path: &Path, trusted: &[String]) -> kute::Result<(Value, bool)> {
164 if trusted.is_empty() {
165 return Err(KuteError::InvalidConfig("verify needs at least one --trusted-key: a signature is only worth the key it is checked against".into()));
166 }
167 let keys = trusted.iter().map(|t| public_of(t)).collect::<kute::Result<Vec<_>>>()?;
168 let vocabulary = vocab::load(vocab_path)?;
169 let (digest, rows, held) = check(&vocabulary, &keys)?;
170 let verified = held > 0;
171 Ok((
172 json!({
173 "vocabulary": vocab_path,
174 "digest": digest,
175 "signatures": rows,
176 "trusted_keys_given": keys.iter().map(|k| key_id(k)).collect::<Vec<_>>(),
177 "trusted_keys_with_a_valid_signature": held,
178 "verified": verified,
179 "means": "a valid signature says the holder of that key signed this exact content. It says nothing about whether the content is good, and nothing about who holds the key.",
180 }),
181 verified,
182 ))
183}
184
185pub fn gate(trusted: &[String]) -> kute::Result<impl Fn(&kute::Vocabulary) -> Result<(), String> + Send + 'static + use<>> {
188 let keys = trusted.iter().map(|t| public_of(t)).collect::<kute::Result<Vec<_>>>()?;
189 Ok(move |vocabulary: &kute::Vocabulary| match check(vocabulary, &keys) {
190 Ok((_, _, held)) if held > 0 => Ok(()),
191 Ok((_, rows, _)) if rows.is_empty() => Err("it carries no signature, and this peer requires one from a key it trusts".to_string()),
192 Ok(_) => Err("none of its signatures is a valid one from a key this peer trusts".to_string()),
193 Err(e) => Err(e.to_string()),
194 })
195}
196
197fn check(vocabulary: &kute::Vocabulary, keys: &[Vec<u8>]) -> kute::Result<(String, Vec<Value>, usize)> {
200 let digest = vocabulary.compute_digest()?;
201 let signatures = vocabulary.integrity.as_ref().map(|i| i.signatures.clone()).unwrap_or_default();
202 if signatures.len() > MAX_SIGNATURES {
203 return Err(KuteError::LimitExceeded(format!("the vocabulary carries {} signatures; at most {MAX_SIGNATURES} are read", signatures.len())));
204 }
205 let mut rows = Vec::new();
206 let mut holding: Vec<&Vec<u8>> = Vec::new();
209 for signature in &signatures {
210 let status = if signature.algorithm != ALGORITHM {
211 "unsupported algorithm"
212 } else {
213 match keys.iter().find(|k| key_id(k) == signature.key_id) {
214 None => "not from a trusted key",
215 Some(key) => match b64().decode(&signature.signature) {
216 Ok(bytes) if UnparsedPublicKey::new(&ED25519, key).verify(&message(&digest), &bytes).is_ok() => {
217 if holding.contains(&key) {
218 "valid, repeats an earlier entry"
219 } else {
220 holding.push(key);
221 "valid"
222 }
223 }
224 _ => "INVALID",
225 },
226 }
227 };
228 rows.push(json!({ "key_id": signature.key_id, "algorithm": signature.algorithm, "status": status }));
229 }
230 let held = holding.len();
231 Ok((digest, rows, held))
232}