1use 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
12const CHANGE_KEYS_CONTEXT: &str = "nibkeep 2026-10 change keys";
14
15const RECORD_KEYS_CONTEXT: &str = "nibkeep 2026-10 record keys";
17
18const BLOB_KEYS_CONTEXT: &str = "nibkeep 2026-10 blob keys";
20
21const SECRET_BLOB_KEYS_CONTEXT: &str = "nibkeep 2026-10 secret blob keys";
24
25#[derive(Clone, Debug)]
34pub struct SpaceKeys {
35 keys: BTreeMap<u64, Key>,
36 secrets: BTreeMap<u64, Key>,
37 writing: Option<u64>,
39 secrets_writing: Option<u64>,
42}
43
44impl SpaceKeys {
45 #[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 pub fn write_with(&mut self, epoch: Option<u64>) {
61 self.writing = epoch;
62 }
63
64 #[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 pub fn epochs(&self) -> impl Iterator<Item = u64> + '_ {
74 self.keys.keys().copied()
75 }
76
77 pub fn space_keys(&self) -> impl Iterator<Item = (u64, &Key)> {
79 self.keys.iter().map(|(&epoch, key)| (epoch, key))
80 }
81
82 pub fn insert(&mut self, epoch: u64, key: Key) {
84 self.keys.insert(epoch, key);
85 }
86
87 #[must_use]
89 pub fn get(&self, epoch: u64) -> Option<&Key> {
90 self.keys.get(&epoch)
91 }
92
93 #[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 pub fn insert_secrets(&mut self, epoch: u64, key: Key) {
111 self.secrets.insert(epoch, key);
112 }
113
114 pub fn forget_secrets(&mut self) {
116 self.secrets.clear();
117 }
118
119 #[must_use]
121 pub fn secrets(&self, epoch: u64) -> Option<&Key> {
122 self.secrets.get(&epoch)
123 }
124
125 pub fn secrets_keys(&self) -> impl Iterator<Item = (u64, &Key)> {
127 self.secrets.iter().map(|(&epoch, key)| (epoch, key))
128 }
129
130 pub fn write_secrets_with(&mut self, epoch: Option<u64>) {
135 self.secrets_writing = epoch;
136 }
137
138 #[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
154pub(crate) fn change_keys_key(space_key: &Key) -> Key {
156 space_key.derive(CHANGE_KEYS_CONTEXT)
157}
158
159pub(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
165fn wrapped_to_cbor(epoch: u64, envelope: &Envelope) -> Cbor {
168 Cbor::Array(vec![epoch.to_cbor(), envelope.to_cbor()])
169}
170
171fn 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#[derive(Clone, Debug, PartialEq, Eq)]
188pub struct WrappedKey {
189 epoch: u64,
190 envelope: Envelope,
191}
192
193impl WrappedKey {
194 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 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 #[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#[derive(Clone, Debug, PartialEq, Eq)]
260pub struct WrappedBlobKey {
261 epoch: u64,
262 envelope: Envelope,
263}
264
265impl WrappedBlobKey {
266 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 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 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 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 #[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
389pub(crate) enum Unwrapped {
391 Key {
394 content: Hash,
395 key: Key,
396 secret: bool,
397 },
398 Secret,
401}
402
403fn 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
416enum Outer {
418 Ordinary(Hash, Key),
420 Secret(u64, Envelope),
422}
423
424fn 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
449fn 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
463fn 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}