tapirus 1.2.1

Embedded multi-model database with SQL, vector search and local AI memory
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
//! # Native Page-Level Cryptographic Encryption for TapirusDB.
//!
//! Implements ChaCha20-Poly1305 Authenticated Encryption with Associated Data (AEAD).
//! Provides page-level encryption for `.tapir` and `.tapir-wal` files, key derivation
//! via SHA-256, and constant-time Key Check Value (KCV) verification.

use crate::error::{Error, Result};
use crate::pager::PageId;
use chacha20poly1305::aead::{Aead, Payload};
use chacha20poly1305::{ChaCha20Poly1305, Key, KeyInit, Nonce, XChaCha20Poly1305, XNonce};
use sha2::{Digest, Sha256};
use subtle::ConstantTimeEq;
use zeroize::Zeroize;

/// Poly1305 MAC authentication tag size in bytes
pub const TAG_SIZE: usize = 16;

/// XChaCha20 extended nonce size in bytes (192-bit)
pub const XNONCE_SIZE: usize = 24;

/// Total reserved trailer size in bytes at the end of each page (24-byte Nonce + 16-byte Tag)
pub const CRYPTO_TRAILER_SIZE: usize = XNONCE_SIZE + TAG_SIZE; // 40 bytes

/// 256-bit AES / ChaCha20 encryption key size in bytes
pub const KEY_SIZE: usize = 32;

/// Database salt size in bytes
pub const SALT_SIZE: usize = 16;

/// Constant verification payload for Key Check Value (KCV)
pub const KCV_MAGIC: &[u8] = b"TAPIRUS_CIPHER_KCV_V1";

/// Usable unencrypted slotted page content size when encryption is enabled
pub const ENCRYPTED_PAGE_USABLE_SIZE: usize = 4096 - CRYPTO_TRAILER_SIZE; // 4056 bytes

/// Standard iterations for PBKDF2-HMAC-SHA256 password key derivation in production.
/// Compliant with OWASP 2023 Password Storage Guidelines (minimum 600,000 iterations).
pub const PBKDF2_RECOMMENDED_ITERATIONS: u32 = 600_000;
/// Lightweight iterations for PBKDF2-HMAC-SHA256 used in development and fast unit testing
pub const PBKDF2_FAST_ITERATIONS: u32 = 10_000;

/// Compute standard HMAC-SHA256 (RFC 2104)
pub fn hmac_sha256(key: &[u8], data: &[u8]) -> [u8; 32] {
    let mut k_block = [0u8; 64];
    if key.len() > 64 {
        let hashed = Sha256::digest(key);
        k_block[0..32].copy_from_slice(&hashed);
    } else {
        k_block[0..key.len()].copy_from_slice(key);
    }

    let mut ipad = [0u8; 64];
    let mut opad = [0u8; 64];
    for i in 0..64 {
        ipad[i] = k_block[i] ^ 0x36;
        opad[i] = k_block[i] ^ 0x5c;
    }

    let mut inner_hasher = Sha256::new();
    inner_hasher.update(ipad);
    inner_hasher.update(data);
    let inner_hash = inner_hasher.finalize();

    let mut outer_hasher = Sha256::new();
    outer_hasher.update(opad);
    outer_hasher.update(inner_hash);
    let outer_hash = outer_hasher.finalize();

    let mut out = [0u8; 32];
    out.copy_from_slice(&outer_hash);
    k_block.zeroize();
    ipad.zeroize();
    opad.zeroize();
    out
}

/// Derive a 256-bit cryptographic key using PBKDF2-HMAC-SHA256 (RFC 2898 / RFC 6070)
pub fn pbkdf2_hmac_sha256(passphrase: &[u8], salt: &[u8], iterations: u32) -> [u8; 32] {
    assert!(iterations >= 1);
    let mut salt_and_int = Vec::with_capacity(salt.len() + 4);
    salt_and_int.extend_from_slice(salt);
    salt_and_int.extend_from_slice(&1u32.to_be_bytes());

    let mut u_prev = hmac_sha256(passphrase, &salt_and_int);
    let mut result = u_prev;

    for _ in 1..iterations {
        u_prev = hmac_sha256(passphrase, &u_prev);
        for j in 0..32 {
            result[j] ^= u_prev[j];
        }
    }

    u_prev.zeroize();
    salt_and_int.zeroize();
    result
}

/// Derive a 256-bit cryptographic key from a user passphrase and database salt using PBKDF2.
///
/// Uses `PBKDF2_RECOMMENDED_ITERATIONS` (600,000) per OWASP 2023 guidelines for
/// production brute-force resistance. Use `derive_key_with_iterations` for test/dev fast mode.
pub fn derive_key(passphrase: &str, salt: &[u8; 16]) -> [u8; 32] {
    pbkdf2_hmac_sha256(passphrase.as_bytes(), salt, PBKDF2_RECOMMENDED_ITERATIONS)
}

/// Derive a 256-bit cryptographic key with explicitly specified PBKDF2 iteration count
pub fn derive_key_with_iterations(passphrase: &str, salt: &[u8; 16], iterations: u32) -> [u8; 32] {
    pbkdf2_hmac_sha256(passphrase.as_bytes(), salt, iterations)
}

/// Generate a cryptographically secure 16-byte random salt using the OS CSPRNG.
///
/// Uses `getrandom` which delegates to the platform's secure entropy source
/// (e.g. `getrandom(2)` on Linux, `BCryptGenRandom` on Windows). This is
/// indistinguishable from random even if the creation timestamp is known.
pub fn generate_random_salt() -> [u8; 16] {
    let mut salt = [0u8; 16];
    getrandom::fill(&mut salt).expect("OS CSPRNG unavailable — cannot generate secure salt");
    salt
}

/// Cryptographic engine managing page-level encryption and verification.
///
/// Deliberately does not implement `Clone` so raw key material is never
/// silently duplicated in memory; sensitive key and salt bytes are scrubbed via
/// `zeroize` on [`Drop`].
pub struct DatabaseCipher {
    key: [u8; 32],
    salt: [u8; 16],
    epoch: u32,
}

impl Zeroize for DatabaseCipher {
    fn zeroize(&mut self) {
        self.key.zeroize();
        self.salt.zeroize();
        self.epoch = 0;
    }
}

impl Drop for DatabaseCipher {
    fn drop(&mut self) {
        self.zeroize();
    }
}

fn build_page_aad(page_id: PageId, page_bytes: &[u8]) -> ([u8; 49], usize) {
    let mut aad = [0u8; 49];
    aad[0..4].copy_from_slice(&page_id.to_le_bytes());
    if page_id == 1 && page_bytes.len() >= 81 {
        // Authenticate immutable Page 1 header metadata (magic, page_size, version,
        // encryption_flags, salt, kcv) with Poly1305 AEAD while allowing mutable
        // commit counters in [12..48] to flush independently.
        aad[4..16].copy_from_slice(&page_bytes[0..12]);
        aad[16..49].copy_from_slice(&page_bytes[48..81]);
        (aad, 49)
    } else {
        (aad, 4)
    }
}

impl DatabaseCipher {
    /// Initialize cipher with raw 256-bit key and 16-byte salt
    pub fn new(key: [u8; 32], salt: [u8; 16]) -> Self {
        Self {
            key,
            salt,
            epoch: 1,
        }
    }

    /// Initialize cipher by deriving 256-bit key from passphrase and salt via PBKDF2
    pub fn from_passphrase(passphrase: &str, salt: [u8; 16]) -> Self {
        let key = derive_key(passphrase, &salt);
        Self {
            key,
            salt,
            epoch: 1,
        }
    }

    /// Initialize cipher with custom PBKDF2 iteration count
    pub fn from_passphrase_with_iterations(
        passphrase: &str,
        salt: [u8; 16],
        iterations: u32,
    ) -> Self {
        let key = derive_key_with_iterations(passphrase, &salt, iterations);
        Self {
            key,
            salt,
            epoch: 1,
        }
    }

    /// Return reference to database salt
    pub fn salt(&self) -> &[u8; 16] {
        &self.salt
    }

    /// Return raw key bytes
    pub fn key(&self) -> &[u8; 32] {
        &self.key
    }

    /// Return database epoch
    pub fn epoch(&self) -> u32 {
        self.epoch
    }

    /// Set database epoch (e.g. incremented after major checkpoints / rollbacks)
    pub fn set_epoch(&mut self, epoch: u32) {
        self.epoch = epoch;
    }

    /// Derive unique 12-byte AEAD nonce with monotonic write sequence and epoch
    /// Formally satisfies RFC 8439 Nonce Uniqueness Requirement:
    /// Nonce = Epoch (4B) || PageId (4B) || Sequence (4B)
    pub fn derive_nonce_with_seq(&self, page_id: PageId, sequence: u32, epoch: u32) -> [u8; 12] {
        let mut nonce = [0u8; 12];
        nonce[0..4].copy_from_slice(&epoch.to_le_bytes());
        nonce[4..8].copy_from_slice(&page_id.to_le_bytes());
        nonce[8..12].copy_from_slice(&sequence.to_le_bytes());
        nonce
    }

    /// Default 12-byte nonce for backward compatibility (sequence 0, epoch 1)
    pub fn derive_nonce(&self, page_id: PageId) -> [u8; 12] {
        self.derive_nonce_with_seq(page_id, 0, self.epoch)
    }

    /// Generate 16-byte Key Check Value (KCV) tag for header validation.
    ///
    /// Returns `Err` if the ChaCha20-Poly1305 cipher fails, so callers always
    /// know when KCV generation is impossible rather than silently receiving a
    /// zeroed tag that would bypass authentication checks.
    pub fn generate_kcv(&self) -> Result<[u8; 16]> {
        let mut key = Key::from(self.key);
        let cipher = ChaCha20Poly1305::new(&key);
        key.as_mut_slice().zeroize();
        let nonce = Nonce::try_from(&self.salt[0..12])
            .map_err(|_| Error::Corrupted("Invalid salt slice for KCV nonce".into()))?;
        let ciphertext = cipher.encrypt(&nonce, KCV_MAGIC).map_err(|_| {
            Error::Corrupted("KCV generation failed: ChaCha20-Poly1305 encryption error".into())
        })?;
        if ciphertext.len() < 16 {
            return Err(Error::Corrupted("KCV ciphertext too short".into()));
        }
        let mut tag = [0u8; 16];
        tag.copy_from_slice(&ciphertext[ciphertext.len() - 16..]);
        Ok(tag)
    }

    /// Constant-time verification of stored KCV against candidate key.
    /// Uses the audited `subtle` crate (`ConstantTimeEq`) to prevent timing side-channel leakage.
    /// Returns `false` (not-equal) on internal error rather than panicking.
    pub fn verify_kcv(&self, stored_kcv: &[u8; 16]) -> bool {
        let expected = match self.generate_kcv() {
            Ok(v) => v,
            Err(_) => return false,
        };
        expected.ct_eq(stored_kcv).into()
    }

    /// Encrypt a 4,096-byte in-memory page into a 4,096-byte disk page using XChaCha20-Poly1305
    /// with a cryptographically secure 24-byte (192-bit) random nonce from the OS CSPRNG.
    ///
    /// Every write produces a completely distinct ciphertext even if page contents are identical,
    /// guaranteeing absolute immunity against nonce reuse attacks per RFC 8439.
    pub fn encrypt_page(&self, page_id: PageId, plaintext: &[u8]) -> Result<Vec<u8>> {
        let mut nonce_bytes = [0u8; XNONCE_SIZE];
        getrandom::fill(&mut nonce_bytes)
            .expect("OS CSPRNG unavailable — cannot generate secure nonce");
        self.encrypt_page_with_nonce(page_id, &nonce_bytes, plaintext)
    }

    /// Encrypt a 4,096-byte in-memory page with an explicitly provided 24-byte nonce (useful for deterministic tests)
    pub fn encrypt_page_with_nonce(
        &self,
        page_id: PageId,
        nonce_bytes: &[u8; XNONCE_SIZE],
        plaintext: &[u8],
    ) -> Result<Vec<u8>> {
        if plaintext.len() != 4096 {
            return Err(Error::Corrupted(format!(
                "Expected 4096 byte page, got {}",
                plaintext.len()
            )));
        }

        let mut key = Key::from(self.key);
        let cipher = XChaCha20Poly1305::new(&key);
        key.as_mut_slice().zeroize();
        let nonce = XNonce::from(*nonce_bytes);

        let (pt_start, pt_end) = if page_id == 1 {
            (100, ENCRYPTED_PAGE_USABLE_SIZE)
        } else {
            (0, ENCRYPTED_PAGE_USABLE_SIZE)
        };

        let pt_slice = &plaintext[pt_start..pt_end];
        let (aad_buf, aad_len) = build_page_aad(page_id, plaintext);
        let payload = Payload {
            msg: pt_slice,
            aad: &aad_buf[..aad_len],
        };

        let ct = cipher
            .encrypt(&nonce, payload)
            .map_err(|e| Error::Corrupted(format!("Encryption error: {e}")))?;

        let tag_offset = ct.len() - TAG_SIZE;
        let actual_ct = &ct[..tag_offset];
        let tag = &ct[tag_offset..];

        let mut out_page = vec![0u8; 4096];
        if page_id == 1 {
            out_page[0..100].copy_from_slice(&plaintext[0..100]);
        }
        // Copy encrypted ciphertext
        out_page[pt_start..pt_end].copy_from_slice(actual_ct);
        // Store 24-byte random XNonce in trailer [4056..4080]
        out_page[ENCRYPTED_PAGE_USABLE_SIZE..ENCRYPTED_PAGE_USABLE_SIZE + XNONCE_SIZE]
            .copy_from_slice(nonce_bytes);
        // Store 16-byte Poly1305 authentication tag in trailer [4080..4096]
        out_page[ENCRYPTED_PAGE_USABLE_SIZE + XNONCE_SIZE..4096].copy_from_slice(tag);

        Ok(out_page)
    }

    /// Legacy compatibility wrapper: forwards to `encrypt_page_with_nonce` using a 24-byte padded nonce
    pub fn encrypt_page_with_seq(
        &self,
        page_id: PageId,
        sequence: u32,
        epoch: u32,
        plaintext: &[u8],
    ) -> Result<Vec<u8>> {
        let mut nonce = [0u8; XNONCE_SIZE];
        nonce[0..4].copy_from_slice(&epoch.to_le_bytes());
        nonce[4..8].copy_from_slice(&page_id.to_le_bytes());
        nonce[8..12].copy_from_slice(&sequence.to_le_bytes());
        self.encrypt_page_with_nonce(page_id, &nonce, plaintext)
    }

    /// Decrypt a 4,096-byte disk page back into an in-memory page using XChaCha20-Poly1305.
    ///
    /// Reads the 24-byte random XNonce from bytes [4056..4080] and the 16-byte Poly1305 tag
    /// from bytes [4080..4096]. Authenticates Associated Data against `page_id`.
    pub fn decrypt_page(&self, page_id: PageId, disk_page: &[u8]) -> Result<Vec<u8>> {
        if disk_page.len() != 4096 {
            return Err(Error::Corrupted(format!(
                "Expected 4096 byte page, got {}",
                disk_page.len()
            )));
        }

        let mut key = Key::from(self.key);
        let cipher = XChaCha20Poly1305::new(&key);
        key.as_mut_slice().zeroize();

        let (pt_start, pt_end) = if page_id == 1 {
            (100, ENCRYPTED_PAGE_USABLE_SIZE)
        } else {
            (0, ENCRYPTED_PAGE_USABLE_SIZE)
        };

        let ct_slice = &disk_page[pt_start..pt_end];
        let nonce_slice =
            &disk_page[ENCRYPTED_PAGE_USABLE_SIZE..ENCRYPTED_PAGE_USABLE_SIZE + XNONCE_SIZE];
        let tag_slice = &disk_page[ENCRYPTED_PAGE_USABLE_SIZE + XNONCE_SIZE..4096];

        let nonce = XNonce::try_from(nonce_slice).map_err(|_| Error::DecryptionFailed(page_id))?;

        let mut combined = Vec::with_capacity(ct_slice.len() + tag_slice.len());
        combined.extend_from_slice(ct_slice);
        combined.extend_from_slice(tag_slice);

        let (aad_buf, aad_len) = build_page_aad(page_id, disk_page);
        let payload = Payload {
            msg: &combined,
            aad: &aad_buf[..aad_len],
        };

        let pt = cipher
            .decrypt(&nonce, payload)
            .map_err(|_| Error::DecryptionFailed(page_id))?;

        let mut out_page = vec![0u8; 4096];
        if page_id == 1 {
            out_page[0..100].copy_from_slice(&disk_page[0..100]);
        }
        out_page[pt_start..pt_end].copy_from_slice(&pt);

        Ok(out_page)
    }

    /// Legacy compatibility wrapper: forwards directly to self-contained `decrypt_page`
    pub fn decrypt_page_with_seq(
        &self,
        page_id: PageId,
        _sequence: u32,
        _epoch: u32,
        disk_page: &[u8],
    ) -> Result<Vec<u8>> {
        self.decrypt_page(page_id, disk_page)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_cipher_roundtrip_page() {
        let salt = [7u8; 16];
        let cipher = DatabaseCipher::from_passphrase_with_iterations(
            "super-secret-robot-key",
            salt,
            PBKDF2_FAST_ITERATIONS,
        );

        // Test KCV verification
        let kcv = cipher.generate_kcv().unwrap();
        assert!(cipher.verify_kcv(&kcv));

        let wrong_cipher = DatabaseCipher::from_passphrase_with_iterations(
            "wrong-password",
            salt,
            PBKDF2_FAST_ITERATIONS,
        );
        assert!(!wrong_cipher.verify_kcv(&kcv));

        // Test Page 2 encryption
        let mut original_page = vec![0u8; 4096];
        original_page[10] = 42;
        original_page[500] = 99;
        original_page[4000] = 123;

        let encrypted = cipher.encrypt_page(2, &original_page).unwrap();
        assert_ne!(encrypted, original_page);
        assert_eq!(encrypted.len(), 4096);

        // Decrypt with correct key
        let decrypted = cipher.decrypt_page(2, &encrypted).unwrap();
        assert_eq!(decrypted[10], 42);
        assert_eq!(decrypted[500], 99);
        assert_eq!(decrypted[4000], 123);

        // Decrypt with wrong key fails
        let fail = wrong_cipher.decrypt_page(2, &encrypted);
        assert!(fail.is_err());
    }

    #[test]
    fn test_cipher_roundtrip_page1() {
        let salt = [3u8; 16];
        let cipher = DatabaseCipher::from_passphrase_with_iterations(
            "mars-rover-mission",
            salt,
            PBKDF2_FAST_ITERATIONS,
        );

        let mut page1 = vec![0u8; 4096];
        page1[0..8].copy_from_slice(b"TAPIRUS\0"); // Plaintext header preserved
        page1[200] = 88;

        let encrypted = cipher.encrypt_page(1, &page1).unwrap();
        assert_eq!(&encrypted[0..8], b"TAPIRUS\0"); // Header remains readable
        assert_ne!(encrypted[200], 88); // Payload is encrypted

        let decrypted = cipher.decrypt_page(1, &encrypted).unwrap();
        assert_eq!(&decrypted[0..8], b"TAPIRUS\0");
        assert_eq!(decrypted[200], 88);
    }

    #[test]
    fn test_pbkdf2_rfc6070_vectors() {
        // RFC 6070 Test Vector 1: c = 1
        let p = b"password";
        let s = b"salt";
        let key_c1 = pbkdf2_hmac_sha256(p, s, 1);
        let expected_c1 = [
            0x12, 0x0f, 0xb6, 0xcf, 0xfc, 0xf8, 0xb3, 0x2c, 0x43, 0xe7, 0x22, 0x52, 0x56, 0xc4,
            0xf8, 0x37, 0xa8, 0x65, 0x48, 0xc9, 0x2c, 0xcc, 0x35, 0x48, 0x08, 0x05, 0x98, 0x7c,
            0xb7, 0x0b, 0xe1, 0x7b,
        ];
        assert_eq!(key_c1, expected_c1);

        // RFC 6070 Test Vector 2: c = 2
        let key_c2 = pbkdf2_hmac_sha256(p, s, 2);
        let expected_c2 = [
            0xae, 0x4d, 0x0c, 0x95, 0xaf, 0x6b, 0x46, 0xd3, 0x2d, 0x0a, 0xdf, 0xf9, 0x28, 0xf0,
            0x6d, 0xd0, 0x2a, 0x30, 0x3f, 0x8e, 0xf3, 0xc2, 0x51, 0xdf, 0xd6, 0xe2, 0xd8, 0x5a,
            0x95, 0x47, 0x4c, 0x43,
        ];
        assert_eq!(key_c2, expected_c2);
    }

    #[test]
    fn test_random_nonce_uniqueness() {
        let salt = [11u8; 16];
        let cipher = DatabaseCipher::from_passphrase_with_iterations(
            "quantum_encryption_2026",
            salt,
            PBKDF2_FAST_ITERATIONS,
        );

        let page_data = vec![0xaau8; 4096];

        // Encrypt the identical page twice with standard encrypt_page
        let ct1 = cipher.encrypt_page(4, &page_data).unwrap();
        let ct2 = cipher.encrypt_page(4, &page_data).unwrap();

        // Distinct random nonces guarantee completely different ciphertexts, nonces, and auth tags
        assert_ne!(ct1, ct2);
        // Nonce slices must be completely different
        assert_ne!(
            &ct1[ENCRYPTED_PAGE_USABLE_SIZE..ENCRYPTED_PAGE_USABLE_SIZE + XNONCE_SIZE],
            &ct2[ENCRYPTED_PAGE_USABLE_SIZE..ENCRYPTED_PAGE_USABLE_SIZE + XNONCE_SIZE]
        );

        // Both decrypt back to the exact identical plaintext without needing external sequence numbers!
        let pt1 = cipher.decrypt_page(4, &ct1).unwrap();
        let pt2 = cipher.decrypt_page(4, &ct2).unwrap();
        assert_eq!(
            &pt1[0..ENCRYPTED_PAGE_USABLE_SIZE],
            &page_data[0..ENCRYPTED_PAGE_USABLE_SIZE]
        );
        assert_eq!(
            &pt2[0..ENCRYPTED_PAGE_USABLE_SIZE],
            &page_data[0..ENCRYPTED_PAGE_USABLE_SIZE]
        );

        // Decrypt with mismatched PageId fails authentication (AAD protection against page-swapping attacks)
        let swap_fail = cipher.decrypt_page(5, &ct1);
        assert!(swap_fail.is_err());

        // Single-bit tampering in ciphertext fails authentication
        let mut tampered_ct = ct1.clone();
        tampered_ct[50] ^= 0x01;
        assert!(cipher.decrypt_page(4, &tampered_ct).is_err());

        // Single-bit tampering in nonce fails authentication
        let mut tampered_nonce = ct1.clone();
        tampered_nonce[ENCRYPTED_PAGE_USABLE_SIZE + 2] ^= 0x01;
        assert!(cipher.decrypt_page(4, &tampered_nonce).is_err());

        // Single-bit tampering in Poly1305 tag fails authentication
        let mut tampered_tag = ct1.clone();
        tampered_tag[4090] ^= 0x01;
        assert!(cipher.decrypt_page(4, &tampered_tag).is_err());
    }

    #[test]
    fn test_database_cipher_zeroize_scrubs_key_and_salt() {
        let mut cipher = DatabaseCipher::new([0xA5u8; 32], [0x5Au8; 16]);
        cipher.set_epoch(9);
        assert_eq!(cipher.key(), &[0xA5u8; 32]);
        assert_eq!(cipher.salt(), &[0x5Au8; 16]);
        assert_eq!(cipher.epoch(), 9);

        cipher.zeroize();
        assert_eq!(cipher.key(), &[0u8; 32]);
        assert_eq!(cipher.salt(), &[0u8; 16]);
        assert_eq!(cipher.epoch(), 0);
        assert!(core::mem::needs_drop::<DatabaseCipher>());
    }

    #[test]
    fn test_page1_immutable_header_authenticated_by_aead() {
        let salt = [9u8; 16];
        let cipher = DatabaseCipher::from_passphrase_with_iterations(
            "header-auth-secret",
            salt,
            PBKDF2_FAST_ITERATIONS,
        );
        let mut page1 = vec![0u8; 4096];
        page1[0..8].copy_from_slice(b"TAPIRUS\0");
        page1[8..10].copy_from_slice(&4096u16.to_le_bytes());
        page1[10..12].copy_from_slice(&1u16.to_le_bytes());
        page1[48] = 1;
        page1[49..65].copy_from_slice(&salt);
        page1[65..81].copy_from_slice(&cipher.generate_kcv().unwrap());
        page1[200] = 0x7E;

        let encrypted = cipher.encrypt_page(1, &page1).unwrap();
        assert!(cipher.decrypt_page(1, &encrypted).is_ok());

        // Tampering with plaintext Page 1 security/format header fields must fail AEAD
        for offset in [0usize, 8, 10, 48, 50, 70] {
            let mut tampered = encrypted.clone();
            tampered[offset] ^= 0x01;
            assert!(
                cipher.decrypt_page(1, &tampered).is_err(),
                "Page 1 header tampering at byte {offset} must fail AEAD"
            );
        }
    }
}