armdb 0.15.1

sharded bitcask key-value storage optimized for NVMe
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
use std::sync::Arc;

use ring::aead::{self, AES_256_GCM, Aad, LessSafeKey, Nonce, UnboundKey};
use ring::hkdf::{HKDF_SHA256, Prk, Salt};
use ring::rand::{SecureRandom, SystemRandom};

use crate::io::keys::KeyRecord;

use crate::error::{DbError, DbResult};

pub const TAG_LEN: usize = 16;
pub const PAGE_SIZE: usize = 4096;

/// Optional binary context separating encryption keys for different uses.
///
/// Contexts contain at most 255 bytes. Empty and absent contexts derive the same keys.
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub struct EncryptionContext {
    bytes: [u8; 255],
    len: u8,
}

impl EncryptionContext {
    /// Copy a context into inline storage, rejecting inputs longer than 255 bytes.
    pub fn new(bytes: &[u8]) -> DbResult<Self> {
        let len = u8::try_from(bytes.len())
            .map_err(|_| DbError::EncryptionError("encryption context exceeds 255 bytes".into()))?;
        let mut context = Self {
            bytes: [0; 255],
            len,
        };
        context.bytes[..bytes.len()].copy_from_slice(bytes);
        Ok(context)
    }

    /// Return the original context bytes.
    pub fn as_bytes(&self) -> &[u8] {
        &self.bytes[..usize::from(self.len)]
    }
}

fn encoded_context(context: Option<&EncryptionContext>) -> [u8; 256] {
    let mut encoded = [0; 256];
    if let Some(context) = context {
        encoded[0] = context.len;
        encoded[1..1 + usize::from(context.len)].copy_from_slice(context.as_bytes());
    }
    encoded
}

fn expand_key(prk: &Prk, info: &[&[u8]]) -> DbResult<[u8; 32]> {
    let okm = prk
        .expand(info, HKDF_SHA256)
        .map_err(|_| DbError::EncryptionError("hkdf expand failed".into()))?;
    let mut key = [0; 32];
    okm.fill(&mut key)
        .map_err(|_| DbError::EncryptionError("hkdf fill failed".into()))?;
    Ok(key)
}

/// A shard's key-derivation domain, retaining the HKDF PRK instead of the master key.
#[doc(hidden)]
pub struct KeyDomain {
    prk: Prk,
    context: [u8; 256],
    shard_id: u8,
}

impl KeyDomain {
    /// Extract a domain for a database salt, optional context and shard.
    pub fn new(
        master: &[u8; 32],
        salt: &[u8; 16],
        context: Option<&EncryptionContext>,
        shard_id: u8,
    ) -> DbResult<Self> {
        Ok(Self {
            prk: Salt::new(HKDF_SHA256, salt).extract(master),
            context: encoded_context(context),
            shard_id,
        })
    }

    /// Derive the page cipher for an existing range salt.
    pub fn range_cipher(&self, range_salt: &[u8; 16]) -> DbResult<PageCipher> {
        let shard = [self.shard_id];
        let context = &self.context[..1 + usize::from(self.context[0])];
        let key = expand_key(&self.prk, &[b"armdb-page-v2", context, &shard, range_salt])?;
        PageCipher::new(&key)
    }

    /// Generate a fresh range salt and its page cipher.
    pub fn new_range(&self) -> DbResult<([u8; 16], PageCipher)> {
        let mut salt = [0; 16];
        SystemRandom::new()
            .fill(&mut salt)
            .map_err(|_| DbError::EncryptionError("failed to generate range salt".into()))?;
        let cipher = self.range_cipher(&salt)?;
        Ok((salt, cipher))
    }
}

/// Derive the directory's key-admission check without retaining the master key.
pub(crate) fn key_check(
    master: &[u8; 32],
    salt: &[u8; 16],
    context: Option<&EncryptionContext>,
) -> DbResult<[u8; 32]> {
    let prk = Salt::new(HKDF_SHA256, salt).extract(master);
    let encoded = encoded_context(context);
    expand_key(
        &prk,
        &[
            b"armdb-keycheck-v1",
            &encoded[..1 + usize::from(encoded[0])],
        ],
    )
}

/// Immutable effective page-key ranges, with allocation-free binary-search lookup.
#[doc(hidden)]
#[derive(Clone)]
pub struct FileKeys {
    ranges: Vec<(u64, Arc<PageCipher>)>,
}

impl FileKeys {
    /// Replay append order, allowing later boundaries to supersede earlier ranges.
    pub(crate) fn from_records(domain: &KeyDomain, records: &[KeyRecord]) -> DbResult<Self> {
        let mut ranges: Vec<(u64, Arc<PageCipher>)> = Vec::new();
        for record in records {
            let keep = ranges.partition_point(|(boundary, _)| *boundary < record.first_page);
            ranges.truncate(keep);
            ranges.push((
                record.first_page,
                Arc::new(domain.range_cipher(&record.salt)?),
            ));
        }
        Ok(Self { ranges })
    }

    /// Build a map containing one range starting at `first_page`.
    pub fn single(first_page: u64, cipher: Arc<PageCipher>) -> Self {
        Self {
            ranges: vec![(first_page, cipher)],
        }
    }

    /// Return a new map with the range appended; existing reader maps stay unchanged.
    pub fn with_range(&self, first_page: u64, cipher: Arc<PageCipher>) -> Self {
        let keep = self
            .ranges
            .partition_point(|(boundary, _)| *boundary < first_page);
        let mut ranges = self.ranges[..keep].to_vec();
        ranges.push((first_page, cipher));
        Self { ranges }
    }

    /// Find the last effective range covering `page`, or fail closed when uncovered.
    pub fn cipher_for(&self, page: u64) -> DbResult<&PageCipher> {
        let upper = self
            .ranges
            .partition_point(|(boundary, _)| *boundary <= page);
        if upper == 0 {
            return Err(DbError::EncryptionError("no key range covers page".into()));
        }
        Ok(self.ranges[upper - 1].1.as_ref())
    }

    /// Return the number of effective ranges.
    pub fn len(&self) -> usize {
        self.ranges.len()
    }

    /// Return whether no page-key ranges are available.
    pub fn is_empty(&self) -> bool {
        self.ranges.is_empty()
    }
}

/// Test instrumentation for detecting reuse of a key and nonce across write histories.
#[cfg(any(test, feature = "test-faults"))]
#[doc(hidden)]
pub mod seal_log {
    use std::sync::{
        Mutex,
        atomic::{AtomicBool, Ordering},
    };

    /// Fingerprints of one seal operation; no raw key or plaintext is retained.
    #[derive(Clone, Copy, Debug, PartialEq, Eq)]
    pub struct SealRecord {
        pub key_fp: [u8; 16],
        pub nonce: [u8; 12],
        pub plaintext_fp: u64,
    }

    static ENABLED: AtomicBool = AtomicBool::new(false);
    static RECORDS: Mutex<Option<Vec<SealRecord>>> = Mutex::new(None);

    /// Start a fresh process-wide recording window.
    pub fn enable() {
        *RECORDS.lock().expect("seal log lock poisoned") = Some(Vec::new());
        ENABLED.store(true, Ordering::Release);
    }

    /// End the recording window and return its seal records.
    pub fn take() -> Vec<SealRecord> {
        ENABLED.store(false, Ordering::Release);
        RECORDS
            .lock()
            .expect("seal log lock poisoned")
            .take()
            .unwrap_or_default()
    }

    pub(crate) fn record(key_fp: [u8; 16], nonce: [u8; 12], plaintext: &[u8]) {
        if !ENABLED.load(Ordering::Acquire) {
            return;
        }
        let hash = ring::digest::digest(&ring::digest::SHA256, plaintext);
        let plaintext_fp =
            u64::from_le_bytes(hash.as_ref()[..8].try_into().expect("SHA256 prefix"));
        if let Some(records) = RECORDS.lock().expect("seal log lock poisoned").as_mut() {
            records.push(SealRecord {
                key_fp,
                nonce,
                plaintext_fp,
            });
        }
    }
}

/// Page-level AES-256-GCM cipher for encrypting data files.
///
/// Each 4096-byte page uses the nonce `(file_id, page_number)` and a separately
/// stored GCM tag. Fresh range keys from [`KeyDomain`] separate write sessions,
/// including histories that fork after restoring an older database copy.
pub struct PageCipher {
    key: LessSafeKey,
    #[cfg(any(test, feature = "test-faults"))]
    key_fp: [u8; 16],
}

impl PageCipher {
    /// Create a cipher from a 32-byte AES-256 key.
    pub fn new(key_bytes: &[u8; 32]) -> DbResult<Self> {
        let unbound = UnboundKey::new(&AES_256_GCM, key_bytes)
            .map_err(|e| DbError::EncryptionError(format!("invalid key: {e}")))?;
        Ok(Self {
            key: LessSafeKey::new(unbound),
            #[cfg(any(test, feature = "test-faults"))]
            key_fp: ring::digest::digest(&ring::digest::SHA256, key_bytes).as_ref()[..16]
                .try_into()
                .expect("SHA256 prefix"),
        })
    }

    /// Derive a per-shard cipher via `HKDF-SHA256(ikm = master, salt).expand([shard_id])`.
    ///
    /// Separates the AES-GCM key domain per shard, and — through the per-database
    /// `salt` — per database. The `(file_id, page)` nonce is unchanged and stays
    /// unique within each derived key, so no `(key, nonce)` pair is ever reused
    /// across shards or databases sharing one master key.
    pub fn derive(master: &[u8; 32], salt: &[u8; 16], shard_id: u8) -> DbResult<Self> {
        use ring::hkdf::{HKDF_SHA256, Salt};

        let prk = Salt::new(HKDF_SHA256, salt).extract(master);
        // Bind the info bytes to a local so the `Okm` borrow outlives `expand`.
        let shard_info = [shard_id];
        let info: [&[u8]; 1] = [&shard_info];
        // Expanding with `HKDF_SHA256` as the output KeyType yields 32 bytes
        // (SHA-256 output length) — exactly the AES-256 key size.
        let okm = prk
            .expand(&info, HKDF_SHA256)
            .map_err(|_| DbError::EncryptionError("hkdf expand failed".into()))?;
        let mut key = [0u8; 32];
        okm.fill(&mut key)
            .map_err(|_| DbError::EncryptionError("hkdf fill failed".into()))?;
        Self::new(&key)
    }

    /// Read a hex-encoded 32-byte key from an environment variable.
    pub fn key_from_env(var: &str) -> DbResult<[u8; 32]> {
        let hex = std::env::var(var)
            .map_err(|e| DbError::EncryptionError(format!("env var {var}: {e}")))?;
        let hex = hex.trim();
        if hex.len() != 64 {
            return Err(DbError::EncryptionError(format!(
                "env var {var}: expected 64 hex chars, got {}",
                hex.len()
            )));
        }
        let mut key = [0u8; 32];
        for i in 0..32 {
            key[i] = u8::from_str_radix(&hex[i * 2..i * 2 + 2], 16).map_err(|e| {
                DbError::EncryptionError(format!("env var {var}: invalid hex: {e}"))
            })?;
        }
        Ok(key)
    }

    /// Encrypt a 4096-byte page in-place, returning the 16-byte GCM tag.
    ///
    /// Nonce = `file_id(4 LE) || page_number(8 LE)`.
    pub fn encrypt_page(
        &self,
        file_id: u32,
        page_number: u64,
        page: &mut [u8],
    ) -> DbResult<[u8; TAG_LEN]> {
        debug_assert_eq!(page.len(), PAGE_SIZE);
        let nonce = make_page_nonce(file_id, page_number);
        #[cfg(any(test, feature = "test-faults"))]
        seal_log::record(self.key_fp, *nonce.as_ref(), page);
        let tag = self
            .key
            .seal_in_place_separate_tag(nonce, Aad::empty(), page)
            .map_err(|_| DbError::EncryptionError("encrypt failed".into()))?;
        let mut tag_bytes = [0u8; TAG_LEN];
        tag_bytes.copy_from_slice(tag.as_ref());
        Ok(tag_bytes)
    }

    /// Decrypt a 4096-byte page in-place using its GCM tag.
    ///
    /// Returns `Err(EncryptionError)` if authentication fails (wrong key or corrupted data).
    pub fn decrypt_page(
        &self,
        file_id: u32,
        page_number: u64,
        page: &mut [u8],
        tag: &[u8; TAG_LEN],
    ) -> DbResult<()> {
        debug_assert_eq!(page.len(), PAGE_SIZE);
        // F10: authenticate and decrypt in place. The tag is passed separately,
        // so the page never has to be copied into a `ciphertext || tag` buffer —
        // this runs once per 4 KiB of every encrypted read.
        let nonce = make_page_nonce(file_id, page_number);
        self.key
            .open_in_place_separate_tag(nonce, Aad::empty(), aead::Tag::from(*tag), page, 0..)
            .map_err(|_| DbError::EncryptionError("decryption/authentication failed".into()))?;
        Ok(())
    }
}

fn make_page_nonce(file_id: u32, page_number: u64) -> Nonce {
    let mut nonce_bytes = [0u8; aead::NONCE_LEN];
    nonce_bytes[..4].copy_from_slice(&file_id.to_le_bytes());
    nonce_bytes[4..12].copy_from_slice(&page_number.to_le_bytes());
    Nonce::assume_unique_for_key(nonce_bytes)
}

#[cfg(test)]
#[cfg(feature = "encryption")]
mod tests {
    use super::*;

    #[test]
    fn test_encrypt_decrypt_round_trip() {
        let key = [0xABu8; 32];
        let cipher = PageCipher::new(&key).unwrap();

        let original = [42u8; PAGE_SIZE];
        let mut page = original;
        let tag = cipher.encrypt_page(1, 0, &mut page).unwrap();

        // Encrypted data should differ from original
        assert_ne!(page, original);

        cipher.decrypt_page(1, 0, &mut page, &tag).unwrap();
        assert_eq!(page, original);
    }

    #[test]
    fn test_wrong_key_fails() {
        let cipher1 = PageCipher::new(&[0xAA; 32]).unwrap();
        let cipher2 = PageCipher::new(&[0xBB; 32]).unwrap();

        let mut page = [1u8; PAGE_SIZE];
        let tag = cipher1.encrypt_page(1, 0, &mut page).unwrap();

        assert!(cipher2.decrypt_page(1, 0, &mut page, &tag).is_err());
    }

    #[test]
    fn test_wrong_nonce_fails() {
        let cipher = PageCipher::new(&[0xCC; 32]).unwrap();

        let mut page = [7u8; PAGE_SIZE];
        let tag = cipher.encrypt_page(1, 0, &mut page).unwrap();

        // Different page_number
        assert!(cipher.decrypt_page(1, 1, &mut page, &tag).is_err());
    }

    #[test]
    fn test_tampered_data_fails() {
        let cipher = PageCipher::new(&[0xDD; 32]).unwrap();

        let mut page = [9u8; PAGE_SIZE];
        let tag = cipher.encrypt_page(1, 0, &mut page).unwrap();

        page[0] ^= 0xFF; // Corrupt one byte
        assert!(cipher.decrypt_page(1, 0, &mut page, &tag).is_err());
    }

    #[test]
    fn derive_distinct_shard_ids_distinct_ciphertext() {
        let master = [0x11u8; 32];
        let salt = [0x22u8; 16];
        let c0 = PageCipher::derive(&master, &salt, 0).unwrap();
        let c1 = PageCipher::derive(&master, &salt, 1).unwrap();

        let plain = [7u8; PAGE_SIZE];
        let mut p0 = plain;
        let mut p1 = plain;
        let tag0 = c0.encrypt_page(1, 0, &mut p0).unwrap();
        let _tag1 = c1.encrypt_page(1, 0, &mut p1).unwrap();

        // Одинаковый (file_id, page) под разными под-ключами шардов → разный шифртекст.
        assert_ne!(p0, p1);
        // Ключ шарда 1 не расшифровывает страницу шарда 0.
        let mut cross = p0;
        assert!(c1.decrypt_page(1, 0, &mut cross, &tag0).is_err());
    }

    #[test]
    fn derive_distinct_salts_distinct_ciphertext() {
        let master = [0x33u8; 32];
        let c_a = PageCipher::derive(&master, &[0xA0; 16], 0).unwrap();
        let c_b = PageCipher::derive(&master, &[0xB0; 16], 0).unwrap();

        let plain = [9u8; PAGE_SIZE];
        let mut pa = plain;
        let mut pb = plain;
        c_a.encrypt_page(1, 0, &mut pa).unwrap();
        c_b.encrypt_page(1, 0, &mut pb).unwrap();

        // Один мастер-ключ + shard_id, но разные соли (разные коллекции/БД) → разный шифртекст.
        assert_ne!(pa, pb);
    }

    #[test]
    fn derive_is_deterministic() {
        let master = [0x44u8; 32];
        let salt = [0x55u8; 16];
        let c1 = PageCipher::derive(&master, &salt, 3).unwrap();
        let c2 = PageCipher::derive(&master, &salt, 3).unwrap();

        let plain = [1u8; PAGE_SIZE];
        let mut p = plain;
        let tag = c1.encrypt_page(2, 5, &mut p).unwrap();
        // Тот же (salt, shard_id) → тот же ключ → c2 расшифровывает то, что запечатал c1.
        c2.decrypt_page(2, 5, &mut p, &tag).unwrap();
        assert_eq!(p, plain);
    }
}

#[cfg(test)]
#[cfg(feature = "encryption")]
mod keyrange_tests {
    use super::*;
    use crate::io::keys::KeyRecord;
    use std::sync::Arc;

    fn sealed(cipher: &PageCipher, page_number: u64) -> Vec<u8> {
        let mut page = vec![0x42; PAGE_SIZE];
        let tag = cipher.encrypt_page(7, page_number, &mut page).unwrap();
        page.extend_from_slice(&tag);
        page
    }

    #[test]
    fn keyrange_range_ciphers_differ_by_salt_and_context() {
        let a = EncryptionContext::new(b"tenant-a").unwrap();
        let b = EncryptionContext::new(b"tenant-b").unwrap();
        let domain = KeyDomain::new(&[1; 32], &[2; 16], Some(&a), 3).unwrap();
        let other = KeyDomain::new(&[1; 32], &[2; 16], Some(&b), 3).unwrap();
        let first = domain.range_cipher(&[4; 16]).unwrap();
        assert_ne!(
            sealed(&first, 0),
            sealed(&domain.range_cipher(&[5; 16]).unwrap(), 0)
        );
        assert_ne!(
            sealed(&first, 0),
            sealed(&other.range_cipher(&[4; 16]).unwrap(), 0)
        );
        assert_eq!(
            sealed(&first, 0),
            sealed(&domain.range_cipher(&[4; 16]).unwrap(), 0)
        );
        let other_shard = KeyDomain::new(&[1; 32], &[2; 16], Some(&a), 4).unwrap();
        assert_ne!(
            sealed(&first, 0),
            sealed(&other_shard.range_cipher(&[4; 16]).unwrap(), 0)
        );
        let (salt, random) = domain.new_range().unwrap();
        assert_eq!(
            sealed(&random, 0),
            sealed(&domain.range_cipher(&salt).unwrap(), 0)
        );
    }

    #[test]
    fn keyrange_absent_and_empty_context_derive_the_same_keys() {
        let empty = EncryptionContext::new(b"").unwrap();
        let absent = KeyDomain::new(&[1; 32], &[2; 16], None, 0).unwrap();
        let present = KeyDomain::new(&[1; 32], &[2; 16], Some(&empty), 0).unwrap();
        assert_eq!(
            sealed(&absent.range_cipher(&[3; 16]).unwrap(), 0),
            sealed(&present.range_cipher(&[3; 16]).unwrap(), 0)
        );
        assert_eq!(
            key_check(&[1; 32], &[2; 16], None).unwrap(),
            key_check(&[1; 32], &[2; 16], Some(&empty)).unwrap()
        );
    }

    #[test]
    fn keyrange_context_rejects_256_bytes() {
        assert!(EncryptionContext::new(&[0; 256]).is_err());
        assert_eq!(
            EncryptionContext::new(&[7; 255]).unwrap().as_bytes(),
            &[7; 255]
        );
        let binary = EncryptionContext::new(&[0xff, 0x00, 0xfe]).unwrap();
        assert_eq!(binary.as_bytes(), &[0xff, 0x00, 0xfe]);
    }

    #[test]
    fn keyrange_key_check_changes_with_master_salt_and_context() {
        let ctx = EncryptionContext::new(b"tenant").unwrap();
        let check = key_check(&[1; 32], &[2; 16], None).unwrap();
        assert_ne!(check, key_check(&[3; 32], &[2; 16], None).unwrap());
        assert_ne!(check, key_check(&[1; 32], &[3; 16], None).unwrap());
        assert_ne!(check, key_check(&[1; 32], &[2; 16], Some(&ctx)).unwrap());
        assert_eq!(check, key_check(&[1; 32], &[2; 16], None).unwrap());
    }

    #[test]
    fn keyrange_effective_map_resolves_every_page() {
        let domain = KeyDomain::new(&[1; 32], &[2; 16], None, 0).unwrap();
        let records: Vec<_> = [(0, 1), (10, 2), (10, 3), (5, 4), (20, 5)]
            .into_iter()
            .map(|(first_page, byte)| KeyRecord {
                first_page,
                salt: [byte; 16],
            })
            .collect();
        let keys = FileKeys::from_records(&domain, &records).unwrap();
        assert_eq!(keys.len(), 3);
        for page in 0..=20 {
            let salt = if page < 5 {
                1
            } else if page < 20 {
                4
            } else {
                5
            };
            assert_eq!(
                sealed(keys.cipher_for(page).unwrap(), page),
                sealed(&domain.range_cipher(&[salt; 16]).unwrap(), page)
            );
        }
        assert!(matches!(
            FileKeys::from_records(&domain, &[]).unwrap().cipher_for(0),
            Err(DbError::EncryptionError(_))
        ));
        let first = Arc::new(domain.range_cipher(&[6; 16]).unwrap());
        let old = FileKeys::single(5, first);
        assert!(old.cipher_for(4).is_err());
        let new = old.with_range(3, Arc::new(domain.range_cipher(&[7; 16]).unwrap()));
        assert_eq!(new.len(), 1);
        assert!(new.cipher_for(3).is_ok());
        assert!(old.cipher_for(3).is_err());
        assert_ne!(
            sealed(old.cipher_for(5).unwrap(), 5),
            sealed(new.cipher_for(5).unwrap(), 5)
        );
    }

    #[test]
    fn keyrange_thousand_ranges_resolve_by_binary_search() {
        let domain = KeyDomain::new(&[1; 32], &[2; 16], None, 0).unwrap();
        let records: Vec<_> = (0u64..1000)
            .map(|i| {
                let first_page = match i % 10 {
                    8 => (i - 1) * 2,
                    9 => (i - 5) * 2,
                    _ => i * 2,
                };
                let mut salt = [0; 16];
                salt[..8].copy_from_slice(&i.to_le_bytes());
                KeyRecord { first_page, salt }
            })
            .collect();
        let keys = FileKeys::from_records(&domain, &records).unwrap();
        for page in 0..2000 {
            let rec = records
                .iter()
                .rev()
                .find(|rec| rec.first_page <= page)
                .unwrap();
            let expected = domain.range_cipher(&rec.salt).unwrap();
            assert_eq!(
                sealed(keys.cipher_for(page).unwrap(), page),
                sealed(&expected, page),
                "page {page}"
            );
        }
    }

    #[test]
    fn keyrange_seal_log_records_key_nonce_and_plaintext() {
        seal_log::enable();
        let cipher = PageCipher::new(&[1; 32]).unwrap();
        let _ = sealed(&cipher, 2);
        let _ = sealed(&cipher, 3);
        let records = seal_log::take();
        assert_eq!(records.len(), 2);
        let digest = ring::digest::digest(&ring::digest::SHA256, &[1; 32]);
        assert_eq!(&records[0].key_fp, &digest.as_ref()[..16]);
        assert_eq!(records[0].nonce, [7, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0]);
        assert_ne!(records[0].nonce, records[1].nonce);
        assert_eq!(records[0].plaintext_fp, records[1].plaintext_fp);
        assert!(seal_log::take().is_empty());
    }
}