1use std::cmp::Reverse;
2use std::fmt;
3use std::io::Read;
4use std::str::FromStr;
5
6use age::x25519::{Identity, Recipient};
7use anyhow::{Context, Result, anyhow, ensure};
8use ed25519_dalek::VerifyingKey;
9use serde::{Deserialize, Deserializer, Serialize, Serializer};
10use sha2::{Digest, Sha256};
11use zeroize::Zeroizing;
12
13use super::{KeyGuard, hex, unhex};
14
15const KEY_ID_DOMAIN: &[u8] = b"second-brain identity key id v1";
16const TAG_DOMAIN: &[u8] = b"second-brain identity tag v1";
17const ENVELOPE_DOMAIN: &[u8] = b"second-brain K_id envelope v1";
18const KEY_LEN: usize = 32;
19
20pub struct IdentityKey(KeyGuard<[u8; KEY_LEN]>);
21
22impl IdentityKey {
23 pub fn generate() -> Result<Self> {
24 Ok(Self(
25 KeyGuard::<[u8; KEY_LEN]>::random().context("generating an identity key")?,
26 ))
27 }
28
29 pub fn from_bytes(bytes: KeyGuard<[u8; KEY_LEN]>) -> Self {
30 Self(bytes)
31 }
32
33 pub fn expose(&self) -> &[u8; KEY_LEN] {
34 self.0.expose()
35 }
36
37 pub fn key_id(&self) -> KeyId {
38 let digest = Sha256::new()
39 .chain_update(KEY_ID_DOMAIN)
40 .chain_update(self.expose())
41 .finalize();
42 let mut id = [0u8; 8];
43 id.copy_from_slice(&digest[..8]);
44 KeyId(id)
45 }
46}
47
48impl fmt::Debug for IdentityKey {
49 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
50 f.debug_struct("IdentityKey")
51 .field("key_id", &self.key_id())
52 .finish_non_exhaustive()
53 }
54}
55
56#[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
57pub struct KeyId(pub [u8; 8]);
58
59impl fmt::Display for KeyId {
60 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
61 f.write_str(&hex(&self.0))
62 }
63}
64
65impl fmt::Debug for KeyId {
66 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
67 write!(f, "KeyId({self})")
68 }
69}
70
71impl FromStr for KeyId {
72 type Err = anyhow::Error;
73
74 fn from_str(s: &str) -> Result<Self> {
75 unhex(s)
76 .map(KeyId)
77 .ok_or_else(|| anyhow!("a key id is 16 hex characters"))
78 }
79}
80
81impl Serialize for KeyId {
82 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
83 serializer.collect_str(self)
84 }
85}
86
87impl<'de> Deserialize<'de> for KeyId {
88 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
89 let text = String::deserialize(deserializer)?;
90 text.parse().map_err(serde::de::Error::custom)
91 }
92}
93
94#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
95pub struct Epoch {
96 pub number: u32,
97 pub key_id: KeyId,
98}
99
100pub fn newest_epoch<'a>(epochs: impl IntoIterator<Item = &'a Epoch>) -> Option<Epoch> {
102 epochs
103 .into_iter()
104 .max_by_key(|e| (e.number, Reverse(e.key_id)))
105 .copied()
106}
107
108#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
109#[serde(transparent)]
110pub struct IdentityTag(String);
111
112impl IdentityTag {
113 pub fn migrated(epoch0: &KeyId) -> Self {
114 Self(format!("m-{epoch0}"))
115 }
116
117 pub fn founded(first: &KeyId, founder: &VerifyingKey) -> Self {
118 let digest = Sha256::new()
119 .chain_update(TAG_DOMAIN)
120 .chain_update(first.0)
121 .chain_update(founder.as_bytes())
122 .finalize();
123 Self(format!("f-{}", hex(&digest[..16])))
124 }
125
126 pub fn as_str(&self) -> &str {
127 &self.0
128 }
129}
130
131impl From<String> for IdentityTag {
132 fn from(tag: String) -> Self {
133 Self(tag)
134 }
135}
136
137#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
138pub struct Envelope {
139 pub identity_tag: IdentityTag,
140 pub epoch: Epoch,
141 pub recipient: String,
142 pub machine_id: Option<String>,
143 pub ciphertext: Vec<u8>,
144}
145
146pub fn wrap(
147 key: &IdentityKey,
148 epoch_number: u32,
149 tag: &IdentityTag,
150 recipient: &Recipient,
151 machine_id: Option<String>,
152) -> Result<Envelope> {
153 let plaintext = envelope_plaintext(key, epoch_number, tag)?;
154 let ciphertext = age::encrypt(recipient, plaintext.as_slice())
155 .map_err(|e| anyhow!("sealing the identity key envelope: {e}"))?;
156 Ok(Envelope {
157 identity_tag: tag.clone(),
158 epoch: Epoch {
159 number: epoch_number,
160 key_id: key.key_id(),
161 },
162 recipient: recipient.to_string(),
163 machine_id,
164 ciphertext,
165 })
166}
167
168impl Envelope {
169 pub fn open(&self, identity: &Identity) -> Result<IdentityKey> {
170 let opening = || {
171 format!(
172 "opening the identity key envelope for epoch {}",
173 self.epoch.number
174 )
175 };
176 let decryptor = age::Decryptor::new_buffered(self.ciphertext.as_slice())
177 .map_err(|e| anyhow!("{}: {e}", opening()))?;
178 let mut reader = decryptor
179 .decrypt(std::iter::once(identity as &dyn age::Identity))
180 .map_err(|e| anyhow!("{}: {e}", opening()))?;
181 let expected = plaintext_len(&self.identity_tag);
182 let mut plaintext = Zeroizing::new(vec![0u8; expected + 1]);
183 let mut filled = 0;
184 while filled < plaintext.len() {
185 let read = reader
186 .read(&mut plaintext[filled..])
187 .with_context(opening)?;
188 if read == 0 {
189 break;
190 }
191 filled += read;
192 }
193 let key = parse_plaintext(&plaintext[..filled], &self.identity_tag, self.epoch.number)?;
194 ensure!(
195 key.key_id() == self.epoch.key_id,
196 "the key in the envelope for epoch {} does not have key id {}",
197 self.epoch.number,
198 self.epoch.key_id
199 );
200 Ok(key)
201 }
202}
203
204fn envelope_plaintext(
205 key: &IdentityKey,
206 epoch_number: u32,
207 tag_label: &IdentityTag,
208) -> Result<Zeroizing<Vec<u8>>> {
209 let tag = tag_label.as_str().as_bytes();
210 let tag_len = u32::try_from(tag.len()).context("identity tag is too long")?;
211 let mut out = Zeroizing::new(Vec::with_capacity(plaintext_len(tag_label)));
212 out.extend_from_slice(ENVELOPE_DOMAIN);
213 out.extend_from_slice(&tag_len.to_be_bytes());
214 out.extend_from_slice(tag);
215 out.extend_from_slice(&epoch_number.to_be_bytes());
216 out.extend_from_slice(key.expose());
217 Ok(out)
218}
219
220fn plaintext_len(tag: &IdentityTag) -> usize {
221 ENVELOPE_DOMAIN.len() + 4 + tag.as_str().len() + 4 + KEY_LEN
222}
223
224fn parse_plaintext(plaintext: &[u8], tag: &IdentityTag, epoch_number: u32) -> Result<IdentityKey> {
225 let rest = plaintext
226 .strip_prefix(ENVELOPE_DOMAIN)
227 .context("envelope plaintext lacks its domain tag")?;
228 let (tag_len, rest) = rest
229 .split_first_chunk::<4>()
230 .context("envelope plaintext is truncated")?;
231 let tag_len =
232 usize::try_from(u32::from_be_bytes(*tag_len)).context("envelope tag length overflows")?;
233 ensure!(
234 Some(rest.len()) == tag_len.checked_add(4 + KEY_LEN),
235 "envelope plaintext has the wrong length"
236 );
237 let (sealed_tag, rest) = rest.split_at(tag_len);
238 ensure!(
239 sealed_tag == tag.as_str().as_bytes(),
240 "envelope was sealed for a different identity than its label {}",
241 tag.as_str()
242 );
243 let (sealed_number, key_bytes) = rest
244 .split_first_chunk::<4>()
245 .context("envelope plaintext is truncated")?;
246 ensure!(
247 u32::from_be_bytes(*sealed_number) == epoch_number,
248 "envelope was sealed for a different epoch than its label {epoch_number}"
249 );
250 let mut guard = KeyGuard::new([0u8; KEY_LEN]);
251 guard.expose_mut().copy_from_slice(key_bytes);
252 Ok(IdentityKey(guard))
253}
254
255#[cfg(test)]
256mod tests {
257 use ed25519_dalek::SigningKey;
258
259 use super::*;
260
261 fn key(byte: u8) -> IdentityKey {
262 IdentityKey::from_bytes(KeyGuard::new([byte; KEY_LEN]))
263 }
264
265 fn tag() -> IdentityTag {
266 IdentityTag::migrated(&key(9).key_id())
267 }
268
269 fn founder(byte: u8) -> VerifyingKey {
270 SigningKey::from_bytes(&[byte; 32]).verifying_key()
271 }
272
273 #[test]
274 fn each_device_opens_only_its_own_envelope() {
275 let k = key(1);
276 let alpha = Identity::generate();
277 let beta = Identity::generate();
278 let for_alpha = wrap(&k, 1, &tag(), &alpha.to_public(), Some("a".into())).unwrap();
279 let for_beta = wrap(&k, 1, &tag(), &beta.to_public(), None).unwrap();
280
281 assert!(for_alpha.open(&beta).is_err());
282 assert!(for_beta.open(&alpha).is_err());
283 assert_eq!(for_alpha.open(&alpha).unwrap().expose(), k.expose());
284 assert_eq!(for_beta.open(&beta).unwrap().expose(), k.expose());
285 }
286
287 #[test]
288 fn opening_returns_the_wrapped_key_and_labels() {
289 let k = key(2);
290 let device = Identity::generate();
291 let envelope = wrap(&k, 3, &tag(), &device.to_public(), Some("m1".into())).unwrap();
292
293 assert_eq!(envelope.identity_tag, tag());
294 assert_eq!(envelope.epoch.number, 3);
295 assert_eq!(envelope.epoch.key_id, k.key_id());
296 assert_eq!(envelope.recipient, device.to_public().to_string());
297 assert_eq!(envelope.machine_id.as_deref(), Some("m1"));
298
299 let opened = envelope.open(&device).unwrap();
300 assert_eq!(opened.expose(), k.expose());
301 assert_eq!(opened.key_id(), k.key_id());
302 }
303
304 #[test]
305 fn a_relabelled_envelope_does_not_open() {
306 let k = key(3);
307 let device = Identity::generate();
308 let envelope = wrap(&k, 2, &tag(), &device.to_public(), None).unwrap();
309
310 let mut other_number = envelope.clone();
311 other_number.epoch.number = 3;
312 assert!(other_number.open(&device).is_err());
313
314 let mut other_tag = envelope.clone();
315 other_tag.identity_tag = IdentityTag::from("m-0000000000000000".to_string());
316 assert!(other_tag.open(&device).is_err());
317
318 let mut other_key_id = envelope.clone();
319 other_key_id.epoch.key_id = key(4).key_id();
320 assert!(other_key_id.open(&device).is_err());
321
322 assert!(envelope.open(&device).is_ok());
323 }
324
325 #[test]
326 fn plaintext_parsing_is_exact() {
327 let k = key(5);
328 let plaintext = envelope_plaintext(&k, 7, &tag()).unwrap();
329 assert_eq!(
330 parse_plaintext(&plaintext, &tag(), 7).unwrap().expose(),
331 k.expose()
332 );
333
334 let mut longer = plaintext.to_vec();
335 longer.push(0);
336 assert!(parse_plaintext(&longer, &tag(), 7).is_err());
337 assert!(parse_plaintext(&plaintext[..plaintext.len() - 1], &tag(), 7).is_err());
338
339 let mut other_domain = plaintext.to_vec();
340 other_domain[0] ^= 1;
341 assert!(parse_plaintext(&other_domain, &tag(), 7).is_err());
342 }
343
344 #[test]
345 fn key_ids_are_stable_and_distinct() {
346 assert_eq!(key(1).key_id(), key(1).key_id());
347 assert_ne!(key(1).key_id(), key(2).key_id());
348 let generated = IdentityKey::generate().unwrap();
349 assert_ne!(generated.key_id(), key(0).key_id());
350 }
351
352 #[test]
353 fn key_id_hex_round_trips() {
354 let id = key(6).key_id();
355 let text = id.to_string();
356 assert_eq!(text.len(), 16);
357 assert!(
358 text.bytes()
359 .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
360 );
361 assert_eq!(text.parse::<KeyId>().unwrap(), id);
362 assert_eq!(text.to_uppercase().parse::<KeyId>().unwrap(), id);
363
364 let json = serde_json::to_string(&id).unwrap();
365 assert_eq!(json, format!("\"{text}\""));
366 assert_eq!(serde_json::from_str::<KeyId>(&json).unwrap(), id);
367
368 for bad in [
369 "",
370 "0123456789abcde",
371 "0123456789abcdef0",
372 "0123456789abcdeg",
373 "+123456789abcdef",
374 ] {
375 assert!(bad.parse::<KeyId>().is_err(), "{bad:?} parsed");
376 }
377 }
378
379 #[test]
380 fn tags_are_deterministic_and_distinct() {
381 let first = key(7).key_id();
382 let migrated = IdentityTag::migrated(&first);
383 assert_eq!(migrated, IdentityTag::migrated(&first));
384 assert_eq!(migrated.as_str(), format!("m-{first}"));
385
386 let founded = IdentityTag::founded(&first, &founder(1));
387 assert_eq!(founded, IdentityTag::founded(&first, &founder(1)));
388 assert!(founded.as_str().starts_with("f-"));
389 assert_eq!(founded.as_str().len(), 2 + 32);
390 assert_ne!(founded, migrated);
391 assert_ne!(founded, IdentityTag::founded(&first, &founder(2)));
392 assert_ne!(founded, IdentityTag::founded(&key(8).key_id(), &founder(1)));
393
394 let json = serde_json::to_string(&founded).unwrap();
395 assert_eq!(json, format!("\"{}\"", founded.as_str()));
396 assert_eq!(serde_json::from_str::<IdentityTag>(&json).unwrap(), founded);
397 }
398
399 #[test]
400 fn envelope_serde_round_trips() {
401 let device = Identity::generate();
402 let envelope = wrap(&key(1), 4, &tag(), &device.to_public(), None).unwrap();
403 let json = serde_json::to_string(&envelope).unwrap();
404 let back: Envelope = serde_json::from_str(&json).unwrap();
405 assert_eq!(back, envelope);
406 assert_eq!(back.open(&device).unwrap().expose(), key(1).expose());
407 }
408
409 #[test]
410 fn debug_output_hides_the_key() {
411 let shown = format!("{:?}", key(0xab));
412 assert!(!shown.contains("171"), "{shown}");
413 assert!(!shown.to_lowercase().contains("abab"), "{shown}");
414 assert!(shown.contains(&key(0xab).key_id().to_string()));
415 }
416}