citadeldb 0.10.0

Citadel: encrypted-first embedded database engine that outperforms unencrypted SQLite
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
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
//! Integration test: full encryption round-trip through all layers.
//!
//! Creates a database file, writes encrypted pages via buffer pool,
//! flushes to disk, reads back, verifies data integrity.

use citadel_buffer::pool::BufferPool;
use citadel_core::types::*;
use citadel_core::*;
use citadel_crypto::key_manager::{create_key_file, open_key_file};
use citadel_crypto::page_cipher;
use citadel_io::file_manager::*;
use citadel_io::mmap_io::MmapPageIO;
use citadel_io::traits::PageIO;
use citadel_page::page::Page;

use std::fs::File;

#[test]
fn full_encryption_roundtrip() {
    let dir = tempfile::tempdir().unwrap();
    let db_path = dir.path().join("test.citadel");
    let key_path = dir.path().join("test.citadel-keys");

    let passphrase = b"integration-test-passphrase";
    let file_id: u64 = 0xDEAD_CAFE_1234;

    let (key_file, keys) = create_key_file(
        passphrase,
        file_id,
        CipherId::Aes256Ctr,
        KdfAlgorithm::Argon2id,
        64,
        1,
        1, // minimal params for test speed
    )
    .unwrap();
    let key_buf = key_file.serialize();
    std::fs::write(&key_path, key_buf).unwrap();

    let file = File::options()
        .read(true)
        .write(true)
        .create(true)
        .truncate(false)
        .open(&db_path)
        .unwrap();
    let io = MmapPageIO::try_new(file).unwrap();

    let dek_id = page_cipher::compute_dek_id(&keys.mac_key, &keys.dek);
    let header = FileHeader::new(file_id, dek_id);
    write_file_header(&io, &header).unwrap();
    io.fsync().unwrap();

    let mut pool = BufferPool::new(64);
    let epoch = 1u32;

    for i in 0..10u32 {
        let mut page = Page::new(PageId(i), PageType::Leaf, TxnId(1));
        let cell = format!("key-{i}:value-{i}");
        page.write_cell(cell.as_bytes()).unwrap();
        page.update_checksum();

        let offset = page_offset(PageId(i));
        ensure_file_size(&io, offset).unwrap();
        pool.insert_new(PageId(i), page).unwrap();
    }

    assert_eq!(pool.dirty_count(), 10);

    pool.flush_dirty(&io, &keys.dek, &keys.mac_key, epoch)
        .unwrap();
    io.fsync().unwrap();
    assert_eq!(pool.dirty_count(), 0);

    let raw_bytes = std::fs::read(&db_path).unwrap();
    for i in 0..10u32 {
        let needle = format!("key-{i}:value-{i}");
        let found = raw_bytes
            .windows(needle.len())
            .any(|w| w == needle.as_bytes());
        assert!(!found, "Plaintext found on disk for page {i}!");
    }

    let mut pool2 = BufferPool::new(64);

    for i in 0..10u32 {
        let page = pool2
            .fetch(&io, PageId(i), &keys.dek, &keys.mac_key, epoch)
            .unwrap();
        assert_eq!(page.page_id(), PageId(i));
        assert_eq!(page.page_type(), Some(PageType::Leaf));
        assert_eq!(page.txn_id(), TxnId(1));
        assert_eq!(page.num_cells(), 1);
        assert!(page.verify_checksum());

        let offset = page.cell_offset(0);
        let expected = format!("key-{i}:value-{i}");
        let data = page.cell_data(offset, expected.len());
        assert_eq!(data, expected.as_bytes());
    }

    {
        let tamper_offset = page_offset(PageId(5));
        let mut encrypted = [0u8; PAGE_SIZE];
        io.read_page(tamper_offset, &mut encrypted).unwrap();
        encrypted[100] ^= 0x01; // flip bit in ciphertext
        io.write_page(tamper_offset, &encrypted).unwrap();
    }

    let mut pool3 = BufferPool::new(64);
    let result = pool3.fetch(&io, PageId(5), &keys.dek, &keys.mac_key, epoch);
    assert!(matches!(result, Err(Error::PageTampered(PageId(5)))));

    let page0 = pool3
        .fetch(&io, PageId(0), &keys.dek, &keys.mac_key, epoch)
        .unwrap();
    assert_eq!(page0.page_id(), PageId(0));

    let key_bytes: [u8; KEY_FILE_SIZE] = key_buf;
    let (_kf2, keys2) = open_key_file(&key_bytes, passphrase, file_id).unwrap();
    assert_eq!(keys2.dek, keys.dek);
    assert_eq!(keys2.mac_key, keys.mac_key);

    let result = open_key_file(&key_bytes, b"wrong-password", file_id);
    assert!(result.is_err());

    let result = open_key_file(&key_bytes, passphrase, 0xBAAD);
    assert!(matches!(result, Err(Error::KeyFileMismatch)));
}

#[test]
fn file_header_and_recovery() {
    let dir = tempfile::tempdir().unwrap();
    let db_path = dir.path().join("recovery.citadel");

    let file = File::options()
        .read(true)
        .write(true)
        .create(true)
        .truncate(false)
        .open(&db_path)
        .unwrap();
    let io = MmapPageIO::try_new(file).unwrap();

    let dek_id = [0xAAu8; MAC_SIZE];
    let header = FileHeader::new(0x42, dek_id);
    write_file_header(&io, &header).unwrap();
    io.fsync().unwrap();

    let (slot_idx, slot) = recover(&io).unwrap();
    assert_eq!(slot_idx, 0);
    assert_eq!(slot.txn_id, TxnId(0));

    let new_slot = CommitSlot {
        txn_id: TxnId(1),
        tree_root: PageId(0),
        tree_depth: 1,
        tree_entries: 100,
        catalog_root: PageId(0),
        total_pages: 10,
        high_water_mark: 9,
        pending_free_root: PageId::INVALID,
        encryption_epoch: 1,
        dek_id,
        checksum: 0,
        merkle_root: [0u8; citadel_core::MERKLE_HASH_SIZE],
        named_table_entries: Vec::new(),
    };

    write_commit_slot(&io, 1, &new_slot).unwrap(); // write to inactive slot 1
    io.fsync().unwrap();
    write_god_byte(&io, GOD_BIT_ACTIVE_SLOT).unwrap(); // flip to slot 1
    io.fsync().unwrap();

    let (slot_idx, slot) = recover(&io).unwrap();
    assert_eq!(slot_idx, 1);
    assert_eq!(slot.txn_id, TxnId(1));
    assert_eq!(slot.tree_entries, 100);
}

#[test]
fn recovery_rejects_tree_root_at_high_water_mark() {
    let dir = tempfile::tempdir().unwrap();
    let db_path = dir.path().join("hwm.citadel");

    let file = File::options()
        .read(true)
        .write(true)
        .create(true)
        .truncate(false)
        .open(&db_path)
        .unwrap();
    let io = MmapPageIO::try_new(file).unwrap();

    let dek_id = [0xBBu8; MAC_SIZE];
    let header = FileHeader::new(0x99, dek_id);
    write_file_header(&io, &header).unwrap();
    io.fsync().unwrap();

    // HWM is one past highest allocated, so tree_root == HWM is out of bounds
    let slot = CommitSlot {
        txn_id: TxnId(1),
        tree_root: PageId(5),
        tree_depth: 1,
        tree_entries: 10,
        catalog_root: PageId(0),
        total_pages: 5,
        high_water_mark: 5,
        pending_free_root: PageId::INVALID,
        encryption_epoch: 1,
        dek_id,
        checksum: 0,
        merkle_root: [0u8; citadel_core::MERKLE_HASH_SIZE],
        named_table_entries: Vec::new(),
    };

    write_commit_slot(&io, 0, &slot).unwrap();
    io.fsync().unwrap();

    let result = recover(&io);
    assert!(
        matches!(result, Err(Error::PageOutOfBounds(PageId(5)))),
        "tree_root == high_water_mark should be rejected, got: {result:?}"
    );
}

#[test]
fn recovery_rejects_pending_free_at_high_water_mark() {
    let dir = tempfile::tempdir().unwrap();
    let db_path = dir.path().join("hwm2.citadel");

    let file = File::options()
        .read(true)
        .write(true)
        .create(true)
        .truncate(false)
        .open(&db_path)
        .unwrap();
    let io = MmapPageIO::try_new(file).unwrap();

    let dek_id = [0xCCu8; MAC_SIZE];
    let header = FileHeader::new(0xAA, dek_id);
    write_file_header(&io, &header).unwrap();
    io.fsync().unwrap();

    // pending_free_root == high_water_mark is invalid
    let slot = CommitSlot {
        txn_id: TxnId(1),
        tree_root: PageId(1),
        tree_depth: 1,
        tree_entries: 10,
        catalog_root: PageId(0),
        total_pages: 8,
        high_water_mark: 8,
        pending_free_root: PageId(8),
        encryption_epoch: 1,
        dek_id,
        checksum: 0,
        merkle_root: [0u8; citadel_core::MERKLE_HASH_SIZE],
        named_table_entries: Vec::new(),
    };

    write_commit_slot(&io, 0, &slot).unwrap();
    io.fsync().unwrap();

    let result = recover(&io);
    assert!(
        matches!(result, Err(Error::PageOutOfBounds(PageId(8)))),
        "pending_free_root == high_water_mark should be rejected, got: {result:?}"
    );
}

#[test]
fn sieve_eviction_dirty_never_evicted() {
    use citadel_buffer::sieve::SieveCache;

    let mut cache = SieveCache::<String>::new(3);

    cache.insert(1, "one".into()).unwrap();
    cache.insert(2, "two".into()).unwrap();
    cache.insert(3, "three".into()).unwrap();

    // Mark entry 2 as dirty (pinned - must never be evicted)
    cache.set_dirty(2);

    // Insert multiple entries - dirty entry 2 must survive all evictions
    for i in 10..15 {
        cache.insert(i, format!("val-{i}")).unwrap();
        assert!(cache.contains(2), "dirty entry 2 should never be evicted");
        assert_eq!(cache.get(2), Some(&"two".to_string()));
    }

    assert_eq!(cache.dirty_count(), 1);
    assert!(cache.is_dirty(2));
}

#[test]
fn wrong_epoch_detected_on_fetch() {
    let dir = tempfile::tempdir().unwrap();
    let db_path = dir.path().join("epoch.citadel");

    let (key_file, keys) = create_key_file(
        b"password",
        0x1111,
        CipherId::Aes256Ctr,
        KdfAlgorithm::Argon2id,
        64,
        1,
        1,
    )
    .unwrap();
    let _ = key_file;

    let file = File::options()
        .read(true)
        .write(true)
        .create(true)
        .truncate(false)
        .open(&db_path)
        .unwrap();
    let io = MmapPageIO::try_new(file).unwrap();

    let dek_id = page_cipher::compute_dek_id(&keys.mac_key, &keys.dek);
    let header = FileHeader::new(0x1111, dek_id);
    write_file_header(&io, &header).unwrap();

    let mut page = Page::new(PageId(0), PageType::Leaf, TxnId(1));
    page.update_checksum();
    let mut encrypted = [0u8; PAGE_SIZE];
    page_cipher::encrypt_page(
        &keys.dek,
        &keys.mac_key,
        PageId(0),
        1,
        page.as_bytes(),
        &mut encrypted,
    );
    let offset = page_offset(PageId(0));
    ensure_file_size(&io, offset).unwrap();
    io.write_page(offset, &encrypted).unwrap();
    io.fsync().unwrap();

    // Read with wrong epoch (epoch 2) - HMAC includes epoch, so it should fail
    let mut pool = BufferPool::new(64);
    let result = pool.fetch(&io, PageId(0), &keys.dek, &keys.mac_key, 2);
    assert!(
        matches!(result, Err(Error::PageTampered(PageId(0)))),
        "wrong epoch should be detected as tampered"
    );

    let page_back = pool
        .fetch(&io, PageId(0), &keys.dek, &keys.mac_key, 1)
        .unwrap();
    assert_eq!(page_back.page_id(), PageId(0));
}

#[test]
fn buffer_pool_eviction_under_pressure() {
    let dir = tempfile::tempdir().unwrap();
    let db_path = dir.path().join("pressure.citadel");

    let (_, keys) = create_key_file(
        b"pass",
        0x2222,
        CipherId::Aes256Ctr,
        KdfAlgorithm::Argon2id,
        64,
        1,
        1,
    )
    .unwrap();

    let file = File::options()
        .read(true)
        .write(true)
        .create(true)
        .truncate(false)
        .open(&db_path)
        .unwrap();
    let io = MmapPageIO::try_new(file).unwrap();

    let dek_id = page_cipher::compute_dek_id(&keys.mac_key, &keys.dek);
    let header = FileHeader::new(0x2222, dek_id);
    write_file_header(&io, &header).unwrap();

    let epoch = 1u32;
    for i in 0..50u32 {
        let mut page = Page::new(PageId(i), PageType::Leaf, TxnId(1));
        let cell = format!("data-{i:04}");
        page.write_cell(cell.as_bytes()).unwrap();
        page.update_checksum();
        let offset = page_offset(PageId(i));
        ensure_file_size(&io, offset).unwrap();
        let mut encrypted = [0u8; PAGE_SIZE];
        page_cipher::encrypt_page(
            &keys.dek,
            &keys.mac_key,
            PageId(i),
            epoch,
            page.as_bytes(),
            &mut encrypted,
        );
        io.write_page(offset, &encrypted).unwrap();
    }
    io.fsync().unwrap();

    // Create pool with capacity 10 (much less than 50 pages)
    let mut pool = BufferPool::new(10);

    // Fetch all 50 pages - forces eviction of older pages
    for i in 0..50u32 {
        let page = pool
            .fetch(&io, PageId(i), &keys.dek, &keys.mac_key, epoch)
            .unwrap();
        assert_eq!(page.page_id(), PageId(i));
    }

    // Re-fetch first page (was evicted, must re-read from disk)
    let page0 = pool
        .fetch(&io, PageId(0), &keys.dek, &keys.mac_key, epoch)
        .unwrap();
    assert_eq!(page0.page_id(), PageId(0));
    assert_eq!(page0.num_cells(), 1);
}

#[test]
fn tamper_iv_region_detected() {
    let dir = tempfile::tempdir().unwrap();
    let db_path = dir.path().join("tamper_iv.citadel");

    let (_, keys) = create_key_file(
        b"pass",
        0x3333,
        CipherId::Aes256Ctr,
        KdfAlgorithm::Argon2id,
        64,
        1,
        1,
    )
    .unwrap();

    let file = File::options()
        .read(true)
        .write(true)
        .create(true)
        .truncate(false)
        .open(&db_path)
        .unwrap();
    let io = MmapPageIO::try_new(file).unwrap();

    let dek_id = page_cipher::compute_dek_id(&keys.mac_key, &keys.dek);
    let header = FileHeader::new(0x3333, dek_id);
    write_file_header(&io, &header).unwrap();

    let mut page = Page::new(PageId(0), PageType::Leaf, TxnId(1));
    page.update_checksum();
    let mut encrypted = [0u8; PAGE_SIZE];
    page_cipher::encrypt_page(
        &keys.dek,
        &keys.mac_key,
        PageId(0),
        1,
        page.as_bytes(),
        &mut encrypted,
    );
    let offset = page_offset(PageId(0));
    ensure_file_size(&io, offset).unwrap();
    io.write_page(offset, &encrypted).unwrap();
    io.fsync().unwrap();

    // Tamper with the IV region (first 16 bytes of the on-disk page)
    let mut tampered = [0u8; PAGE_SIZE];
    io.read_page(offset, &mut tampered).unwrap();
    tampered[0] ^= 0xFF; // Flip bits in IV
    io.write_page(offset, &tampered).unwrap();

    let mut pool = BufferPool::new(64);
    let result = pool.fetch(&io, PageId(0), &keys.dek, &keys.mac_key, 1);
    assert!(
        matches!(result, Err(Error::PageTampered(PageId(0)))),
        "tampered IV should be detected by HMAC"
    );
}

#[test]
fn tamper_mac_region_detected() {
    let dir = tempfile::tempdir().unwrap();
    let db_path = dir.path().join("tamper_mac.citadel");

    let (_, keys) = create_key_file(
        b"pass",
        0x4444,
        CipherId::Aes256Ctr,
        KdfAlgorithm::Argon2id,
        64,
        1,
        1,
    )
    .unwrap();

    let file = File::options()
        .read(true)
        .write(true)
        .create(true)
        .truncate(false)
        .open(&db_path)
        .unwrap();
    let io = MmapPageIO::try_new(file).unwrap();

    let dek_id = page_cipher::compute_dek_id(&keys.mac_key, &keys.dek);
    let header = FileHeader::new(0x4444, dek_id);
    write_file_header(&io, &header).unwrap();

    let mut page = Page::new(PageId(0), PageType::Leaf, TxnId(1));
    page.update_checksum();
    let mut encrypted = [0u8; PAGE_SIZE];
    page_cipher::encrypt_page(
        &keys.dek,
        &keys.mac_key,
        PageId(0),
        1,
        page.as_bytes(),
        &mut encrypted,
    );
    let offset = page_offset(PageId(0));
    ensure_file_size(&io, offset).unwrap();
    io.write_page(offset, &encrypted).unwrap();
    io.fsync().unwrap();

    // Tamper with the MAC region (last 32 bytes)
    let mut tampered = [0u8; PAGE_SIZE];
    io.read_page(offset, &mut tampered).unwrap();
    tampered[PAGE_SIZE - 1] ^= 0x01; // Flip last byte of MAC
    io.write_page(offset, &tampered).unwrap();

    let mut pool = BufferPool::new(64);
    let result = pool.fetch(&io, PageId(0), &keys.dek, &keys.mac_key, 1);
    assert!(
        matches!(result, Err(Error::PageTampered(PageId(0)))),
        "tampered MAC should be detected"
    );
}

#[test]
fn different_keys_produce_different_ciphertext() {
    let (_, keys1) = create_key_file(
        b"password1",
        0x5555,
        CipherId::Aes256Ctr,
        KdfAlgorithm::Argon2id,
        64,
        1,
        1,
    )
    .unwrap();
    let (_, keys2) = create_key_file(
        b"password2",
        0x5555,
        CipherId::Aes256Ctr,
        KdfAlgorithm::Argon2id,
        64,
        1,
        1,
    )
    .unwrap();

    let mut page = Page::new(PageId(0), PageType::Leaf, TxnId(1));
    page.update_checksum();

    let mut enc1 = [0u8; PAGE_SIZE];
    let mut enc2 = [0u8; PAGE_SIZE];
    page_cipher::encrypt_page(
        &keys1.dek,
        &keys1.mac_key,
        PageId(0),
        1,
        page.as_bytes(),
        &mut enc1,
    );
    page_cipher::encrypt_page(
        &keys2.dek,
        &keys2.mac_key,
        PageId(0),
        1,
        page.as_bytes(),
        &mut enc2,
    );

    assert_ne!(
        &enc1[16..PAGE_SIZE - 32],
        &enc2[16..PAGE_SIZE - 32],
        "different DEKs must produce different ciphertext"
    );
    assert_ne!(
        &enc1[PAGE_SIZE - 32..],
        &enc2[PAGE_SIZE - 32..],
        "different MAC keys must produce different MACs"
    );
}

#[test]
fn same_page_encrypted_differently_each_write() {
    let (_, keys) = create_key_file(
        b"pass",
        0x6666,
        CipherId::Aes256Ctr,
        KdfAlgorithm::Argon2id,
        64,
        1,
        1,
    )
    .unwrap();

    let mut page = Page::new(PageId(0), PageType::Leaf, TxnId(1));
    page.update_checksum();

    let mut enc1 = [0u8; PAGE_SIZE];
    let mut enc2 = [0u8; PAGE_SIZE];
    page_cipher::encrypt_page(
        &keys.dek,
        &keys.mac_key,
        PageId(0),
        1,
        page.as_bytes(),
        &mut enc1,
    );
    page_cipher::encrypt_page(
        &keys.dek,
        &keys.mac_key,
        PageId(0),
        1,
        page.as_bytes(),
        &mut enc2,
    );

    // Random IV means same plaintext encrypts differently each time
    assert_ne!(
        &enc1[0..16],
        &enc2[0..16],
        "IVs should be different (random)"
    );
    assert_ne!(
        &enc1[16..PAGE_SIZE - 32],
        &enc2[16..PAGE_SIZE - 32],
        "ciphertext should differ due to different random IV"
    );
}

#[test]
fn cache_hit_returns_identical_data() {
    let dir = tempfile::tempdir().unwrap();
    let db_path = dir.path().join("cache_hit.citadel");

    let (_, keys) = create_key_file(
        b"pass",
        0x7777,
        CipherId::Aes256Ctr,
        KdfAlgorithm::Argon2id,
        64,
        1,
        1,
    )
    .unwrap();

    let file = File::options()
        .read(true)
        .write(true)
        .create(true)
        .truncate(false)
        .open(&db_path)
        .unwrap();
    let io = MmapPageIO::try_new(file).unwrap();

    let dek_id = page_cipher::compute_dek_id(&keys.mac_key, &keys.dek);
    let header = FileHeader::new(0x7777, dek_id);
    write_file_header(&io, &header).unwrap();

    let mut page = Page::new(PageId(0), PageType::Leaf, TxnId(1));
    let cell = b"test-cell-data";
    page.write_cell(cell).unwrap();
    page.update_checksum();
    let offset = page_offset(PageId(0));
    ensure_file_size(&io, offset).unwrap();
    let mut encrypted = [0u8; PAGE_SIZE];
    page_cipher::encrypt_page(
        &keys.dek,
        &keys.mac_key,
        PageId(0),
        1,
        page.as_bytes(),
        &mut encrypted,
    );
    io.write_page(offset, &encrypted).unwrap();
    io.fsync().unwrap();

    let mut pool = BufferPool::new(64);

    let p1 = pool
        .fetch(&io, PageId(0), &keys.dek, &keys.mac_key, 1)
        .unwrap()
        .clone();
    let p2 = pool
        .fetch(&io, PageId(0), &keys.dek, &keys.mac_key, 1)
        .unwrap();

    assert_eq!(p1.page_id(), p2.page_id());
    assert_eq!(p1.num_cells(), p2.num_cells());
    assert_eq!(p1.as_bytes(), p2.as_bytes());
}

#[test]
fn multiple_page_types_all_encrypted() {
    let dir = tempfile::tempdir().unwrap();
    let db_path = dir.path().join("types.citadel");

    let (_, keys) = create_key_file(
        b"pass",
        0x8888,
        CipherId::Aes256Ctr,
        KdfAlgorithm::Argon2id,
        64,
        1,
        1,
    )
    .unwrap();

    let file = File::options()
        .read(true)
        .write(true)
        .create(true)
        .truncate(false)
        .open(&db_path)
        .unwrap();
    let io = MmapPageIO::try_new(file).unwrap();

    let dek_id = page_cipher::compute_dek_id(&keys.mac_key, &keys.dek);
    let header = FileHeader::new(0x8888, dek_id);
    write_file_header(&io, &header).unwrap();

    let epoch = 1u32;
    let page_types = [(PageId(0), PageType::Leaf), (PageId(1), PageType::Branch)];

    for &(page_id, page_type) in &page_types {
        let mut page = Page::new(page_id, page_type, TxnId(1));
        page.update_checksum();
        let offset = page_offset(page_id);
        ensure_file_size(&io, offset).unwrap();
        let mut encrypted = [0u8; PAGE_SIZE];
        page_cipher::encrypt_page(
            &keys.dek,
            &keys.mac_key,
            page_id,
            epoch,
            page.as_bytes(),
            &mut encrypted,
        );
        io.write_page(offset, &encrypted).unwrap();
    }
    io.fsync().unwrap();

    let mut pool = BufferPool::new(64);
    for &(page_id, page_type) in &page_types {
        let page = pool
            .fetch(&io, page_id, &keys.dek, &keys.mac_key, epoch)
            .unwrap();
        assert_eq!(
            page.page_type(),
            Some(page_type),
            "page type should survive encrypt/decrypt for {:?}",
            page_id
        );
    }
}

#[test]
fn page_swap_attack_detected() {
    // Real attack vector: an adversary with disk access swaps two encrypted
    // pages on disk. The HMAC includes page_id, so swapping page 0 and page 1
    // positions should cause HMAC verification to fail for both.
    let dir = tempfile::tempdir().unwrap();
    let db_path = dir.path().join("swap.citadel");

    let (_, keys) = create_key_file(
        b"pass",
        0xAAAA,
        CipherId::Aes256Ctr,
        KdfAlgorithm::Argon2id,
        64,
        1,
        1,
    )
    .unwrap();

    let file = File::options()
        .read(true)
        .write(true)
        .create(true)
        .truncate(false)
        .open(&db_path)
        .unwrap();
    let io = MmapPageIO::try_new(file).unwrap();

    let dek_id = page_cipher::compute_dek_id(&keys.mac_key, &keys.dek);
    let header = FileHeader::new(0xAAAA, dek_id);
    write_file_header(&io, &header).unwrap();

    let epoch = 1u32;

    for i in 0..2u32 {
        let mut page = Page::new(PageId(i), PageType::Leaf, TxnId(1));
        let cell = format!("page-{i}-data");
        page.write_cell(cell.as_bytes()).unwrap();
        page.update_checksum();
        let offset = page_offset(PageId(i));
        ensure_file_size(&io, offset).unwrap();
        let mut encrypted = [0u8; PAGE_SIZE];
        page_cipher::encrypt_page(
            &keys.dek,
            &keys.mac_key,
            PageId(i),
            epoch,
            page.as_bytes(),
            &mut encrypted,
        );
        io.write_page(offset, &encrypted).unwrap();
    }
    io.fsync().unwrap();

    let offset0 = page_offset(PageId(0));
    let offset1 = page_offset(PageId(1));
    let mut raw0 = [0u8; PAGE_SIZE];
    let mut raw1 = [0u8; PAGE_SIZE];
    io.read_page(offset0, &mut raw0).unwrap();
    io.read_page(offset1, &mut raw1).unwrap();

    io.write_page(offset0, &raw1).unwrap();
    io.write_page(offset1, &raw0).unwrap();
    io.fsync().unwrap();

    // Try to read - HMAC verification should fail because:
    // Page at offset0 has MAC computed with page_id=1, but we pass page_id=0
    let mut pool = BufferPool::new(64);
    let result0 = pool.fetch(&io, PageId(0), &keys.dek, &keys.mac_key, epoch);
    assert!(
        matches!(result0, Err(Error::PageTampered(PageId(0)))),
        "page swap attack should be detected for page 0: {:?}",
        result0
    );

    let result1 = pool.fetch(&io, PageId(1), &keys.dek, &keys.mac_key, epoch);
    assert!(
        matches!(result1, Err(Error::PageTampered(PageId(1)))),
        "page swap attack should be detected for page 1: {:?}",
        result1
    );
}

#[test]
fn iv_uniqueness_across_many_writes() {
    // AES-CTR with the same IV and key produces the same keystream.
    // Verify that every encryption generates a unique random IV.
    let (_, keys) = create_key_file(
        b"pass",
        0xBBBB,
        CipherId::Aes256Ctr,
        KdfAlgorithm::Argon2id,
        64,
        1,
        1,
    )
    .unwrap();

    let mut page = Page::new(PageId(0), PageType::Leaf, TxnId(1));
    page.update_checksum();

    let mut seen_ivs = std::collections::HashSet::new();
    let num_encryptions = 1000;

    for _ in 0..num_encryptions {
        let mut encrypted = [0u8; PAGE_SIZE];
        page_cipher::encrypt_page(
            &keys.dek,
            &keys.mac_key,
            PageId(0),
            1,
            page.as_bytes(),
            &mut encrypted,
        );
        let iv: [u8; 16] = encrypted[0..16].try_into().unwrap();
        let is_new = seen_ivs.insert(iv);
        assert!(
            is_new,
            "IV must be unique across all encryptions - duplicate detected!"
        );
    }

    assert_eq!(
        seen_ivs.len(),
        num_encryptions,
        "all {num_encryptions} IVs should be unique"
    );
}

#[test]
fn ctr_bit_flip_caught_before_decrypt() {
    // AES-CTR is a stream cipher: flipping bit N in ciphertext flips bit N
    // in plaintext. Without HMAC-before-decrypt, an attacker could control
    // plaintext changes. This test verifies the HMAC catches the tamper.
    let dir = tempfile::tempdir().unwrap();
    let db_path = dir.path().join("bitflip.citadel");

    let (_, keys) = create_key_file(
        b"pass",
        0xCCCC,
        CipherId::Aes256Ctr,
        KdfAlgorithm::Argon2id,
        64,
        1,
        1,
    )
    .unwrap();

    let file = File::options()
        .read(true)
        .write(true)
        .create(true)
        .truncate(false)
        .open(&db_path)
        .unwrap();
    let io = MmapPageIO::try_new(file).unwrap();

    let dek_id = page_cipher::compute_dek_id(&keys.mac_key, &keys.dek);
    let header = FileHeader::new(0xCCCC, dek_id);
    write_file_header(&io, &header).unwrap();

    let mut page = Page::new(PageId(0), PageType::Leaf, TxnId(1));
    page.write_cell(b"sensitive-data").unwrap();
    page.update_checksum();
    let offset = page_offset(PageId(0));
    ensure_file_size(&io, offset).unwrap();
    let mut encrypted = [0u8; PAGE_SIZE];
    page_cipher::encrypt_page(
        &keys.dek,
        &keys.mac_key,
        PageId(0),
        1,
        page.as_bytes(),
        &mut encrypted,
    );
    io.write_page(offset, &encrypted).unwrap();
    io.fsync().unwrap();

    // Flip various bits in the ciphertext region (bytes 16..PAGE_SIZE-32)
    // Each should be caught by HMAC - the MAC covers the ciphertext
    let ciphertext_offsets = [16, 100, 500, 4000, PAGE_SIZE - 33];
    for &flip_offset in &ciphertext_offsets {
        let mut tampered = [0u8; PAGE_SIZE];
        io.read_page(offset, &mut tampered).unwrap();
        tampered[flip_offset] ^= 0x01; // Single bit flip
        io.write_page(offset, &tampered).unwrap();

        let mut pool = BufferPool::new(64);
        let result = pool.fetch(&io, PageId(0), &keys.dek, &keys.mac_key, 1);
        assert!(
            matches!(result, Err(Error::PageTampered(PageId(0)))),
            "bit flip at offset {flip_offset} should be detected by HMAC"
        );

        io.write_page(offset, &encrypted).unwrap();
    }
}