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 if std::fs::metadata(path)?.len() > 16 * 1024 {
49 return Err(bad_key("the file is larger than a key"));
50 }
51 let text = std::fs::read_to_string(path).map_err(|_| bad_key("the file is not text"))?;
52 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"))?;
53 let der = b64().decode(body.split_whitespace().collect::<String>()).map_err(|_| bad_key("the PEM body is not base64"))?;
54 Ed25519KeyPair::from_pkcs8(&der).map_err(|_| bad_key("not an Ed25519 key in PKCS#8"))
55}
56
57fn public_of(text: &str) -> kute::Result<Vec<u8>> {
58 let key = b64().decode(text.trim()).map_err(|_| KuteError::InvalidInput(format!("a trusted key is not base64: {text:?}")))?;
59 if key.len() != 32 {
60 return Err(KuteError::InvalidInput(format!("a trusted key is {} bytes; an Ed25519 public key is 32", key.len())));
61 }
62 Ok(key)
63}
64
65pub fn keygen(output: &Path) -> kute::Result<Value> {
67 let random = ring::rand::SystemRandom::new();
68 let document = Ed25519KeyPair::generate_pkcs8(&random).map_err(|_| KuteError::Backend("the system gave no randomness".into()))?;
69 let pair = Ed25519KeyPair::from_pkcs8(document.as_ref()).map_err(|_| KuteError::Backend("the key just made cannot be read back".into()))?;
70 let encoded = b64().encode(document.as_ref());
71 let mut pem = String::from(PEM_HEAD);
72 pem.push('\n');
73 for line in encoded.as_bytes().chunks(64) {
74 pem.push_str(std::str::from_utf8(line).expect("base64 is ASCII"));
75 pem.push('\n');
76 }
77 pem.push_str(PEM_TAIL);
78 pem.push('\n');
79 let mut options = std::fs::OpenOptions::new();
80 options.write(true).create_new(true);
81 #[cfg(unix)]
82 {
83 use std::os::unix::fs::OpenOptionsExt;
84 options.mode(0o600);
85 }
86 use std::io::Write;
87 options.open(output)?.write_all(pem.as_bytes())?;
88 let public = pair.public_key().as_ref();
89 Ok(json!({
90 "private_key_file": output,
91 "public_key": b64().encode(public),
92 "key_id": key_id(public),
93 "algorithm": ALGORITHM,
94 "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.",
95 }))
96}
97
98pub fn sign(vocab_path: &Path, key_path: &Path, output: &Path, force: bool) -> kute::Result<Value> {
100 let pair = load_key(key_path)?;
101 let mut vocabulary = vocab::load(vocab_path)?;
102 let digest = vocabulary.compute_digest()?;
104 vocabulary.seal()?;
105 let id = key_id(pair.public_key().as_ref());
106 let integrity = vocabulary.integrity.as_mut().expect("sealed");
107 let signature = b64().encode(pair.sign(&message(&digest)).as_ref());
113 let before = integrity.signatures.len();
114 let already = integrity.signatures.iter().any(|s| s.key_id == id && s.algorithm == ALGORITHM && s.signature == signature);
115 integrity.signatures.retain(|s| s.key_id != id);
116 let replaced = before - integrity.signatures.len() - usize::from(already);
117 if integrity.signatures.len() >= MAX_SIGNATURES {
118 return Err(KuteError::LimitExceeded(format!("the vocabulary already carries {MAX_SIGNATURES} signatures")));
119 }
120 integrity.signatures.push(kute::Signature { key_id: id.clone(), algorithm: ALGORITHM.into(), signature });
121 vocab::save(&vocabulary, output, force)?;
122 let written = vocab::load(output)?;
123 Ok(json!({
124 "output": output,
125 "digest": digest,
126 "digest_unchanged": written.digest()? == digest,
127 "key_id": id,
128 "already_signed_by_this_key": already,
129 "entries_under_this_key_replaced": replaced,
130 "signatures": written.integrity.map_or(0, |i| i.signatures.len()),
131 }))
132}
133
134pub fn verify(vocab_path: &Path, trusted: &[String]) -> kute::Result<(Value, bool)> {
137 if trusted.is_empty() {
138 return Err(KuteError::InvalidConfig("verify needs at least one --trusted-key: a signature is only worth the key it is checked against".into()));
139 }
140 let keys = trusted.iter().map(|t| public_of(t)).collect::<kute::Result<Vec<_>>>()?;
141 let vocabulary = vocab::load(vocab_path)?;
142 let (digest, rows, held) = check(&vocabulary, &keys)?;
143 let verified = held > 0;
144 Ok((
145 json!({
146 "vocabulary": vocab_path,
147 "digest": digest,
148 "signatures": rows,
149 "trusted_keys_given": keys.iter().map(|k| key_id(k)).collect::<Vec<_>>(),
150 "trusted_keys_with_a_valid_signature": held,
151 "verified": verified,
152 "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.",
153 }),
154 verified,
155 ))
156}
157
158pub fn gate(trusted: &[String]) -> kute::Result<impl Fn(&kute::Vocabulary) -> Result<(), String> + Send + 'static> {
161 let keys = trusted.iter().map(|t| public_of(t)).collect::<kute::Result<Vec<_>>>()?;
162 Ok(move |vocabulary: &kute::Vocabulary| match check(vocabulary, &keys) {
163 Ok((_, _, held)) if held > 0 => Ok(()),
164 Ok((_, rows, _)) if rows.is_empty() => Err("it carries no signature, and this peer requires one from a key it trusts".to_string()),
165 Ok(_) => Err("none of its signatures is a valid one from a key this peer trusts".to_string()),
166 Err(e) => Err(e.to_string()),
167 })
168}
169
170fn check(vocabulary: &kute::Vocabulary, keys: &[Vec<u8>]) -> kute::Result<(String, Vec<Value>, usize)> {
173 let digest = vocabulary.compute_digest()?;
174 let signatures = vocabulary.integrity.as_ref().map(|i| i.signatures.clone()).unwrap_or_default();
175 if signatures.len() > MAX_SIGNATURES {
176 return Err(KuteError::LimitExceeded(format!("the vocabulary carries {} signatures; at most {MAX_SIGNATURES} are read", signatures.len())));
177 }
178 let mut rows = Vec::new();
179 let mut holding: Vec<&Vec<u8>> = Vec::new();
182 for signature in &signatures {
183 let status = if signature.algorithm != ALGORITHM {
184 "unsupported algorithm"
185 } else {
186 match keys.iter().find(|k| key_id(k) == signature.key_id) {
187 None => "not from a trusted key",
188 Some(key) => match b64().decode(&signature.signature) {
189 Ok(bytes) if UnparsedPublicKey::new(&ED25519, key).verify(&message(&digest), &bytes).is_ok() => {
190 if holding.contains(&key) {
191 "valid, repeats an earlier entry"
192 } else {
193 holding.push(key);
194 "valid"
195 }
196 }
197 _ => "INVALID",
198 },
199 }
200 };
201 rows.push(json!({ "key_id": signature.key_id, "algorithm": signature.algorithm, "status": status }));
202 }
203 let held = holding.len();
204 Ok((digest, rows, held))
205}