Skip to main content

nibkeep_log/
keys.rs

1//! The keys of a space: the space keys that encrypt changes, the secrets keys, the wrapped
2//! record keys of secret values, and the wrapped keys of blobs.
3
4use std::collections::BTreeMap;
5
6use nibkeep_base::cbor::{self, FromCbor, ToCbor, Value as Cbor};
7use nibkeep_base::{Hash, SpaceId, StatementId};
8use nibkeep_crypto::rand_core::CryptoRng;
9use nibkeep_crypto::{Envelope, Key, Zeroizing};
10use zeroize::Zeroize;
11
12/// The context of the key, derived from a space key, that wraps change keys.
13const CHANGE_KEYS_CONTEXT: &str = "nibkeep 2026-10 change keys";
14
15/// The context of the key, derived from a secrets key, that wraps record keys.
16const RECORD_KEYS_CONTEXT: &str = "nibkeep 2026-10 record keys";
17
18/// The context of the key, derived from a space key, that wraps blob keys.
19const BLOB_KEYS_CONTEXT: &str = "nibkeep 2026-10 blob keys";
20
21/// The context of the key, derived from a secrets key, that wraps the keys of blobs of
22/// secret fields, inside the space key.
23const SECRET_BLOB_KEYS_CONTEXT: &str = "nibkeep 2026-10 secret blob keys";
24
25/// The keys of a space that a replica has, by their numbers: 0 for a space's first key, and
26/// a random one for each key that a rotation brings, so that two rotations made at once
27/// differ; the numbers do not tell which key is newer. New changes use the newest key whose
28/// rotation counts, which the replica chooses; older changes keep the key they were made
29/// with.
30///
31/// Besides the space keys, a replica that the person chose holds the space's secrets keys
32/// while its secrets are unlocked.
33#[derive(Clone, Debug)]
34pub struct SpaceKeys {
35	keys: BTreeMap<u64, Key>,
36	secrets: BTreeMap<u64, Key>,
37	/// The key new changes and blob keys are wrapped with, if not the newest.
38	writing: Option<u64>,
39	/// The secrets key new secret values are sealed with, if not the one of the highest
40	/// number.
41	secrets_writing: Option<u64>,
42}
43
44impl SpaceKeys {
45	/// Returns the keys of a space with this one space key so far, and no secrets key.
46	#[must_use]
47	pub fn new(epoch: u64, key: Key) -> Self {
48		Self {
49			keys: BTreeMap::from([(epoch, key)]),
50			secrets: BTreeMap::new(),
51			writing: None,
52			secrets_writing: None,
53		}
54	}
55
56	/// Wraps new changes and blob keys with the key of this number from now on, or with the
57	/// one of the highest number if `None` or if there is no key of this number. A replica
58	/// writes with the newest key whose rotation counts, which a key it got may not be, and
59	/// which the numbers, random ones, do not tell.
60	pub fn write_with(&mut self, epoch: Option<u64>) {
61		self.writing = epoch;
62	}
63
64	/// The same keys, wrapping new changes with the key of this number, if there is one.
65	#[must_use]
66	pub fn writing_with(&self, epoch: u64) -> Self {
67		let mut keys = self.clone();
68		keys.writing = Some(epoch);
69		keys
70	}
71
72	/// The numbers of the space keys, in order.
73	pub fn epochs(&self) -> impl Iterator<Item = u64> + '_ {
74		self.keys.keys().copied()
75	}
76
77	/// The space keys with their numbers, in order.
78	pub fn space_keys(&self) -> impl Iterator<Item = (u64, &Key)> {
79		self.keys.iter().map(|(&epoch, key)| (epoch, key))
80	}
81
82	/// Adds a space key, after the space's key has changed.
83	pub fn insert(&mut self, epoch: u64, key: Key) {
84		self.keys.insert(epoch, key);
85	}
86
87	/// The space key with this number.
88	#[must_use]
89	pub fn get(&self, epoch: u64) -> Option<&Key> {
90		self.keys.get(&epoch)
91	}
92
93	/// The space key that new changes and blob keys are wrapped with, with its number: the
94	/// one [`SpaceKeys::write_with`] chose, or else the one of the highest number.
95	#[must_use]
96	pub fn newest(&self) -> (u64, &Key) {
97		if let Some(epoch) = self.writing
98			&& let Some(key) = self.keys.get(&epoch)
99		{
100			return (epoch, key);
101		}
102		let Some((&epoch, key)) = self.keys.last_key_value() else {
103			unreachable!("there is always at least one space key");
104		};
105		(epoch, key)
106	}
107
108	/// Adds a secrets key, once the person has confirmed, on a replica chosen to hold the
109	/// space's secrets.
110	pub fn insert_secrets(&mut self, epoch: u64, key: Key) {
111		self.secrets.insert(epoch, key);
112	}
113
114	/// Forgets the secrets keys, when the replica locks its secrets.
115	pub fn forget_secrets(&mut self) {
116		self.secrets.clear();
117	}
118
119	/// The secrets key with this number.
120	#[must_use]
121	pub fn secrets(&self, epoch: u64) -> Option<&Key> {
122		self.secrets.get(&epoch)
123	}
124
125	/// The secrets keys, with their numbers, while the secrets are unlocked.
126	pub fn secrets_keys(&self) -> impl Iterator<Item = (u64, &Key)> {
127		self.secrets.iter().map(|(&epoch, key)| (epoch, key))
128	}
129
130	/// Seals new secret values with the secrets key of this number from now on, or with the
131	/// one of the highest number if `None` or if there is no key of this number. A replica
132	/// seals with the newest secrets key whose rotation knew of every departure, which the
133	/// numbers, random ones, do not tell.
134	pub fn write_secrets_with(&mut self, epoch: Option<u64>) {
135		self.secrets_writing = epoch;
136	}
137
138	/// The secrets key that new secret values are sealed with, with its number, if the
139	/// replica holds one: the one [`SpaceKeys::write_secrets_with`] chose, or else the one of
140	/// the highest number.
141	#[must_use]
142	pub fn newest_secrets(&self) -> Option<(u64, &Key)> {
143		if let Some(epoch) = self.secrets_writing
144			&& let Some(key) = self.secrets.get(&epoch)
145		{
146			return Some((epoch, key));
147		}
148		self.secrets
149			.last_key_value()
150			.map(|(&epoch, key)| (epoch, key))
151	}
152}
153
154/// The key that wraps change keys, derived from a space key.
155pub(crate) fn change_keys_key(space_key: &Key) -> Key {
156	space_key.derive(CHANGE_KEYS_CONTEXT)
157}
158
159/// The associated data that ties an envelope to its place: the space, and what the
160/// envelope belongs to, such as the ID of a secret statement or the sealed hash of a blob.
161pub(crate) fn associated_data(space: SpaceId, owner: &impl ToCbor) -> Vec<u8> {
162	cbor::encode(&Cbor::Array(vec![space.to_cbor(), owner.to_cbor()]))
163}
164
165/// A wrapped key in CBOR: `[epoch, envelope]`, where `epoch` is the number of the key that
166/// wraps it.
167fn wrapped_to_cbor(epoch: u64, envelope: &Envelope) -> Cbor {
168	Cbor::Array(vec![epoch.to_cbor(), envelope.to_cbor()])
169}
170
171/// Reads a wrapped key in CBOR: `[epoch, envelope]`.
172fn wrapped_from_cbor(value: &Cbor, expected: &'static str) -> Result<(u64, Envelope), cbor::Error> {
173	let Cbor::Array(items) = value else {
174		return Err(cbor::Error::Expected(expected));
175	};
176	let [epoch, envelope] = items.as_slice() else {
177		return Err(cbor::Error::Expected(expected));
178	};
179	Ok((u64::from_cbor(epoch)?, Envelope::from_cbor(envelope)?))
180}
181
182/// The record key of a secret statement, wrapped with the space's secrets key.
183///
184/// In CBOR, a wrapped key is the array `[epoch, envelope]`, where `epoch` is the number of
185/// the secrets key. Wrapped keys are stored apart from changes, so that purging can
186/// destroy them.
187#[derive(Clone, Debug, PartialEq, Eq)]
188pub struct WrappedKey {
189	epoch: u64,
190	envelope: Envelope,
191}
192
193impl WrappedKey {
194	/// Wraps the record key of `statement` with the newest secrets key.
195	pub(crate) fn wrap(
196		space: SpaceId,
197		statement: StatementId,
198		record_key: &Key,
199		(epoch, secrets_key): (u64, &Key),
200		rng: &mut impl CryptoRng,
201	) -> Self {
202		Self {
203			epoch,
204			envelope: Envelope::seal_key(
205				&secrets_key.derive(RECORD_KEYS_CONTEXT),
206				record_key,
207				&associated_data(space, &statement),
208				rng,
209			),
210		}
211	}
212
213	/// Unwraps the record key of `statement`, if `keys` hold the secrets key it needs.
214	pub(crate) fn unwrap(
215		&self,
216		space: SpaceId,
217		statement: StatementId,
218		keys: &SpaceKeys,
219	) -> Option<Key> {
220		let secrets_key = keys.secrets(self.epoch)?;
221		self.envelope
222			.open_key(
223				&secrets_key.derive(RECORD_KEYS_CONTEXT),
224				&associated_data(space, &statement),
225			)
226			.ok()
227	}
228
229	/// The number of the secrets key that wraps the record key.
230	#[must_use]
231	pub const fn epoch(&self) -> u64 {
232		self.epoch
233	}
234}
235
236impl ToCbor for WrappedKey {
237	fn to_cbor(&self) -> Cbor {
238		wrapped_to_cbor(self.epoch, &self.envelope)
239	}
240}
241
242impl FromCbor for WrappedKey {
243	fn from_cbor(value: &Cbor) -> Result<Self, cbor::Error> {
244		let (epoch, envelope) = wrapped_from_cbor(value, "a wrapped key: [epoch, envelope]")?;
245		Ok(Self { epoch, envelope })
246	}
247}
248
249/// The key of a blob, wrapped with a space key together with the blob's content hash, so
250/// that the content hash stays as secret as the content. The key of a blob of a secret
251/// field is wrapped with a secrets key first, so that only a replica that holds both opens
252/// it.
253///
254/// In CBOR, a wrapped blob key is the array `[epoch, envelope]`, where `epoch` is the
255/// number of the space key. The envelope holds `[content hash, blob key]`, or, for a
256/// secret blob key, `[secrets epoch, envelope]`, whose envelope holds them, wrapped with
257/// the secrets key of that number. It is known by the sealed hash of its blob, and stored
258/// apart from changes, so that purging can destroy it.
259#[derive(Clone, Debug, PartialEq, Eq)]
260pub struct WrappedBlobKey {
261	epoch: u64,
262	envelope: Envelope,
263}
264
265impl WrappedBlobKey {
266	/// Wraps the key of the blob with the newest space key.
267	pub(crate) fn wrap(
268		space: SpaceId,
269		sealed: &Hash,
270		content: &Hash,
271		blob_key: &Key,
272		keys: &SpaceKeys,
273		rng: &mut impl CryptoRng,
274	) -> Self {
275		Self::wrap_plaintext(
276			space,
277			sealed,
278			&blob_key_plaintext(content, blob_key),
279			keys,
280			rng,
281		)
282	}
283
284	/// Wraps the key of a blob of a secret field with the newest secrets key, then with the
285	/// newest space key; `None` if `keys` hold no secrets key.
286	pub(crate) fn wrap_secret(
287		space: SpaceId,
288		sealed: &Hash,
289		content: &Hash,
290		blob_key: &Key,
291		keys: &SpaceKeys,
292		rng: &mut impl CryptoRng,
293	) -> Option<Self> {
294		let (secrets_epoch, secrets_key) = keys.newest_secrets()?;
295		let inner = Envelope::seal(
296			&secrets_key.derive(SECRET_BLOB_KEYS_CONTEXT),
297			&blob_key_plaintext(content, blob_key),
298			&associated_data(space, sealed),
299			rng,
300		);
301		let plaintext = cbor::encode(&wrapped_to_cbor(secrets_epoch, &inner));
302		Some(Self::wrap_plaintext(space, sealed, &plaintext, keys, rng))
303	}
304
305	/// Wraps what a wrapped blob key holds with the newest space key.
306	fn wrap_plaintext(
307		space: SpaceId,
308		sealed: &Hash,
309		plaintext: &[u8],
310		keys: &SpaceKeys,
311		rng: &mut impl CryptoRng,
312	) -> Self {
313		let (epoch, space_key) = keys.newest();
314		Self {
315			epoch,
316			envelope: Envelope::seal(
317				&space_key.derive(BLOB_KEYS_CONTEXT),
318				plaintext,
319				&associated_data(space, sealed),
320				rng,
321			),
322		}
323	}
324
325	/// Unwraps the content hash and the key of the blob with the sealed hash `sealed`, if
326	/// `keys` hold the space key it needs, and for a secret blob key the secrets key too:
327	/// `None` if the replica lacks the space key, or the key does not open.
328	pub(crate) fn unwrap(
329		&self,
330		space: SpaceId,
331		sealed: &Hash,
332		keys: &SpaceKeys,
333	) -> Option<Unwrapped> {
334		let space_key = keys.get(self.epoch)?;
335		let plaintext = self
336			.envelope
337			.open(
338				&space_key.derive(BLOB_KEYS_CONTEXT),
339				&associated_data(space, sealed),
340			)
341			.ok()?;
342		let (secrets_epoch, inner) = match read_outer_plaintext(&plaintext)? {
343			Outer::Ordinary(content, key) => {
344				return Some(Unwrapped::Key {
345					content,
346					key,
347					secret: false,
348				});
349			}
350			Outer::Secret(secrets_epoch, inner) => (secrets_epoch, inner),
351		};
352		let Some(secrets_key) = keys.secrets(secrets_epoch) else {
353			return Some(Unwrapped::Secret);
354		};
355		let plaintext = inner
356			.open(
357				&secrets_key.derive(SECRET_BLOB_KEYS_CONTEXT),
358				&associated_data(space, sealed),
359			)
360			.ok()?;
361		let (content, key) = read_blob_key_plaintext(&plaintext)?;
362		Some(Unwrapped::Key {
363			content,
364			key,
365			secret: true,
366		})
367	}
368
369	/// The number of the space key that wraps the blob key.
370	#[must_use]
371	pub const fn epoch(&self) -> u64 {
372		self.epoch
373	}
374}
375
376impl ToCbor for WrappedBlobKey {
377	fn to_cbor(&self) -> Cbor {
378		wrapped_to_cbor(self.epoch, &self.envelope)
379	}
380}
381
382impl FromCbor for WrappedBlobKey {
383	fn from_cbor(value: &Cbor) -> Result<Self, cbor::Error> {
384		let (epoch, envelope) = wrapped_from_cbor(value, "a wrapped blob key: [epoch, envelope]")?;
385		Ok(Self { epoch, envelope })
386	}
387}
388
389/// What a wrapped blob key gave when it was opened.
390pub(crate) enum Unwrapped {
391	/// The content hash of the blob and its key, and whether the key is a secret blob key,
392	/// which the replica forgets when it locks its secrets.
393	Key {
394		content: Hash,
395		key: Key,
396		secret: bool,
397	},
398	/// A secret blob key, whose inner envelope needs a secrets key that the replica lacks,
399	/// so that it can be neither opened nor checked yet.
400	Secret,
401}
402
403/// What a wrapped blob key holds: `[content hash, blob key]` in CBOR, encoded without
404/// leaving copies of the key behind.
405fn blob_key_plaintext(content: &Hash, blob_key: &Key) -> Zeroizing<Vec<u8>> {
406	let mut value = Cbor::Array(vec![
407		content.to_cbor(),
408		Cbor::Bytes(blob_key.expose_bytes().to_vec()),
409	]);
410	let mut plaintext = Zeroizing::new(Vec::with_capacity(cbor::encoded_len(&value)));
411	cbor::encode_into(&value, &mut plaintext);
412	wipe(&mut value);
413	plaintext
414}
415
416/// What the outer envelope of a wrapped blob key holds.
417enum Outer {
418	/// The content hash and the key of a blob.
419	Ordinary(Hash, Key),
420	/// The number of a secrets key, and the envelope it opens.
421	Secret(u64, Envelope),
422}
423
424/// Reads what the outer envelope of a wrapped blob key holds, decoded once, and wipes the
425/// copies of the key it made: `[content hash, blob key]`, or `[secrets epoch, envelope]`.
426fn read_outer_plaintext(plaintext: &[u8]) -> Option<Outer> {
427	let mut value = cbor::decode(plaintext).ok()?;
428	let read = match &value {
429		Cbor::Array(items) => match items.as_slice() {
430			[content, Cbor::Bytes(key)] => Hash::from_cbor(content)
431				.ok()
432				.zip(Key::from_slice(key))
433				.map(|(content, key)| Outer::Ordinary(content, key))
434				.or_else(|| {
435					wrapped_from_cbor(&value, "a secret blob key: [secrets epoch, envelope]")
436						.ok()
437						.map(|(epoch, inner)| Outer::Secret(epoch, inner))
438				}),
439			_ => wrapped_from_cbor(&value, "a secret blob key: [secrets epoch, envelope]")
440				.ok()
441				.map(|(epoch, inner)| Outer::Secret(epoch, inner)),
442		},
443		_ => None,
444	};
445	wipe(&mut value);
446	read
447}
448
449/// Reads what a wrapped blob key holds, and wipes the copies of the key it made.
450fn read_blob_key_plaintext(plaintext: &[u8]) -> Option<(Hash, Key)> {
451	let mut value = cbor::decode(plaintext).ok()?;
452	let read = match &value {
453		Cbor::Array(items) => match items.as_slice() {
454			[content, Cbor::Bytes(key)] => Hash::from_cbor(content).ok().zip(Key::from_slice(key)),
455			_ => None,
456		},
457		_ => None,
458	};
459	wipe(&mut value);
460	read
461}
462
463/// Overwrites the byte strings of a value, where keys are.
464fn wipe(value: &mut Cbor) {
465	match value {
466		Cbor::Bytes(bytes) => bytes.zeroize(),
467		Cbor::Array(items) => items.iter_mut().for_each(wipe),
468		_ => {}
469	}
470}