citadeldb 1.0.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
#[cfg(not(target_arch = "wasm32"))]
use std::fs::{self, OpenOptions};
#[cfg(not(target_arch = "wasm32"))]
use std::io::{Read, Seek, SeekFrom};
use std::path::PathBuf;

use citadel_core::types::{Argon2Profile, CipherId, KdfAlgorithm, SyncMode};
use citadel_core::{Error, Result, DEFAULT_BUFFER_POOL_SIZE, PBKDF2_MIN_ITERATIONS};
#[cfg(not(target_arch = "wasm32"))]
use citadel_core::{FILE_HEADER_SIZE, KEY_FILE_SIZE};
use citadel_crypto::hkdf_utils::RegionWrapKeys;
use citadel_crypto::key_manager::{create_key_file, create_key_file_with_region_keys};
#[cfg(not(target_arch = "wasm32"))]
use citadel_crypto::key_manager::{open_key_file, open_key_file_with_region_keys};
use citadel_crypto::page_cipher::compute_dek_id;
#[cfg(not(target_arch = "wasm32"))]
use citadel_io::durable;
#[cfg(not(target_arch = "wasm32"))]
use citadel_io::file_lock;
#[cfg(not(target_arch = "wasm32"))]
use citadel_io::file_manager::FileHeader;
#[cfg(not(target_arch = "wasm32"))]
use citadel_io::mmap_io::MmapPageIO;
use citadel_io::traits::PageIO;
use citadel_txn::manager::TxnManager;

use crate::database::Database;

/// Builder for creating or opening a Citadel database.
///
/// # Examples
///
/// ```no_run
/// use citadel::{DatabaseBuilder, Argon2Profile};
///
/// let db = DatabaseBuilder::new("mydb.citadel")
///     .passphrase(b"secret")
///     .cache_size(512)
///     .create()
///     .unwrap();
/// ```
pub struct DatabaseBuilder {
    path: PathBuf,
    key_path: Option<PathBuf>,
    passphrase: Option<Vec<u8>>,
    argon2_profile: Argon2Profile,
    cache_size: usize,
    cipher: CipherId,
    kdf_algorithm: KdfAlgorithm,
    pbkdf2_iterations: u32,
    sync_mode: SyncMode,
    enable_region_keys: bool,
    secure_delete: bool,
    #[cfg(feature = "audit-log")]
    audit_config: crate::audit::AuditConfig,
}

impl DatabaseBuilder {
    pub fn new(path: impl Into<PathBuf>) -> Self {
        Self {
            path: path.into(),
            key_path: None,
            passphrase: None,
            argon2_profile: Argon2Profile::Desktop,
            cache_size: DEFAULT_BUFFER_POOL_SIZE,
            cipher: CipherId::Aes256Ctr,
            kdf_algorithm: KdfAlgorithm::Argon2id,
            pbkdf2_iterations: PBKDF2_MIN_ITERATIONS,
            sync_mode: SyncMode::Full,
            enable_region_keys: false,
            secure_delete: false,
            #[cfg(feature = "audit-log")]
            audit_config: crate::audit::AuditConfig::default(),
        }
    }

    pub fn passphrase(mut self, passphrase: &[u8]) -> Self {
        self.passphrase = Some(passphrase.to_vec());
        self
    }

    pub fn key_path(mut self, path: impl Into<PathBuf>) -> Self {
        self.key_path = Some(path.into());
        self
    }

    pub fn argon2_profile(mut self, profile: Argon2Profile) -> Self {
        self.argon2_profile = profile;
        self
    }

    pub fn cache_size(mut self, pages: usize) -> Self {
        self.cache_size = pages;
        self
    }

    pub fn cipher(mut self, cipher: CipherId) -> Self {
        self.cipher = cipher;
        self
    }

    /// Set the key derivation function algorithm.
    ///
    /// Default: `Argon2id`. Use `Pbkdf2HmacSha256` for FIPS 140-3 compliance.
    /// When using PBKDF2, the Argon2 profile is ignored and iterations are
    /// controlled by `pbkdf2_iterations()`.
    pub fn kdf_algorithm(mut self, algorithm: KdfAlgorithm) -> Self {
        self.kdf_algorithm = algorithm;
        self
    }

    /// Set the number of PBKDF2 iterations (only used when KDF is PBKDF2).
    ///
    /// Default: 600,000 (OWASP 2024 minimum for PBKDF2-HMAC-SHA256).
    pub fn pbkdf2_iterations(mut self, iterations: u32) -> Self {
        self.pbkdf2_iterations = iterations;
        self
    }

    pub fn sync_mode(mut self, mode: SyncMode) -> Self {
        self.sync_mode = mode;
        self
    }

    /// Enable per-region cryptographic erasure (used by citadel-mem).
    ///
    /// When set, a region wrap key is derived from the REK at create/open and
    /// retained for the database lifetime so encrypted memory regions can be
    /// sealed under random per-region keys and erased on `forget`. Off by
    /// default; the plaintext storage path is unaffected either way.
    pub fn enable_region_keys(mut self, enable: bool) -> Self {
        self.enable_region_keys = enable;
        self
    }

    /// Zero-fill freed B+ tree pages once they are past all readers, so a passphrase holder
    /// with disk access cannot recover deleted-row residue from stale pages. Off by default
    /// (a small write cost on delete-heavy workloads).
    pub fn enable_secure_delete(mut self, enable: bool) -> Self {
        self.secure_delete = enable;
        self
    }

    /// Configure the audit log.
    ///
    /// Default: enabled with 10 MB max file size and 3 rotated files.
    #[cfg(feature = "audit-log")]
    pub fn audit_config(mut self, config: crate::audit::AuditConfig) -> Self {
        self.audit_config = config;
        self
    }

    /// Default key file path: `{data_path}.citadel-keys`
    #[cfg(not(target_arch = "wasm32"))]
    fn resolve_key_path(&self) -> PathBuf {
        self.key_path.clone().unwrap_or_else(|| {
            let mut name = self.path.as_os_str().to_os_string();
            name.push(".citadel-keys");
            PathBuf::from(name)
        })
    }

    #[cfg(not(target_arch = "wasm32"))]
    fn create_page_io(file: std::fs::File) -> Box<dyn PageIO> {
        #[cfg(all(target_os = "linux", feature = "io-uring"))]
        {
            if let Some(uring) = citadel_io::uring_io::UringPageIO::try_new(
                file.try_clone().expect("failed to clone file handle"),
            ) {
                return Box::new(uring);
            }
        }
        Box::new(MmapPageIO::try_new(file).expect("mmap init failed"))
    }

    /// Resolve KDF parameters: (m_cost, t_cost, p_cost) for Argon2id,
    /// or (iterations, 0, 0) for PBKDF2.
    fn resolve_kdf_params(&self) -> (u32, u32, u32) {
        match self.kdf_algorithm {
            KdfAlgorithm::Argon2id => {
                let profile = self.argon2_profile;
                (profile.m_cost(), profile.t_cost(), profile.p_cost())
            }
            KdfAlgorithm::Pbkdf2HmacSha256 => (self.pbkdf2_iterations, 0, 0),
        }
    }

    /// Validate configuration against FIPS constraints (when fips feature enabled).
    #[cfg(feature = "fips")]
    fn validate_fips(&self) -> Result<()> {
        if self.kdf_algorithm != KdfAlgorithm::Pbkdf2HmacSha256 {
            return Err(Error::FipsViolation(
                "FIPS mode requires PBKDF2-HMAC-SHA256 (Argon2id is not NIST approved)".into(),
            ));
        }
        if self.cipher == CipherId::ChaCha20 {
            return Err(Error::FipsViolation(
                "FIPS mode requires AES-256-CTR (ChaCha20 is not NIST approved)".into(),
            ));
        }
        Ok(())
    }

    /// Build a `Database` from a `TxnManager`, optionally creating or opening
    /// an audit log. Centralizes the audit-log feature gating.
    #[cfg(feature = "audit-log")]
    fn finish(
        self,
        manager: TxnManager,
        key_path: PathBuf,
        file_id: u64,
        audit_key: [u8; citadel_core::KEY_SIZE],
        region_keys: Option<RegionWrapKeys>,
        initial_event: Option<(crate::audit::AuditEventType, Vec<u8>)>,
    ) -> Result<Database> {
        use crate::audit;

        let audit_log = if self.audit_config.enabled && !self.path.as_os_str().is_empty() {
            let audit_path = audit::resolve_audit_path(&self.path);
            let log = if audit_path.exists() {
                audit::AuditLog::open_existing(&audit_path, file_id, audit_key, self.audit_config)?
            } else {
                audit::AuditLog::create(&audit_path, file_id, audit_key, self.audit_config)?
            };
            Some(log)
        } else {
            None
        };

        manager.set_secure_delete(self.secure_delete);
        let db = Database::new(
            manager,
            self.path,
            key_path,
            file_id,
            region_keys,
            audit_log,
        );

        if let Some((event, detail)) = initial_event {
            db.log_audit(event, &detail);
        }

        Ok(db)
    }

    #[cfg(not(feature = "audit-log"))]
    fn finish(
        self,
        manager: TxnManager,
        key_path: PathBuf,
        file_id: u64,
        _audit_key: [u8; citadel_core::KEY_SIZE],
        region_keys: Option<RegionWrapKeys>,
        _initial_event: Option<((), Vec<u8>)>,
    ) -> Result<Database> {
        manager.set_secure_delete(self.secure_delete);
        Ok(Database::new(
            manager,
            self.path,
            key_path,
            file_id,
            region_keys,
        ))
    }

    /// Create a new database. Fails if the data file already exists.
    #[cfg(not(target_arch = "wasm32"))]
    pub fn create(self) -> Result<Database> {
        #[cfg(feature = "fips")]
        self.validate_fips()?;

        let passphrase = self
            .passphrase
            .as_deref()
            .ok_or(Error::PassphraseRequired)?;

        let key_path = self.resolve_key_path();
        let file_id: u64 = rand::random();

        let (kf, keys, region_keys) = self.create_keys(passphrase, file_id)?;

        durable::write_and_sync(&key_path, &kf.serialize())?;

        let file = OpenOptions::new()
            .read(true)
            .write(true)
            .create_new(true)
            .open(&self.path)?;

        file_lock::try_lock_exclusive(&file)?;

        let dek_id = compute_dek_id(&keys.mac_key, &keys.dek);
        let io = Self::create_page_io(file);

        let manager = TxnManager::create_with_sync(
            io,
            keys.dek,
            keys.mac_key,
            kf.current_epoch,
            file_id,
            dek_id,
            self.cache_size,
            self.sync_mode,
        )?;

        #[cfg(feature = "audit-log")]
        let event = {
            let detail = vec![self.cipher as u8, self.kdf_algorithm as u8];
            Some((crate::audit::AuditEventType::DatabaseCreated, detail))
        };
        #[cfg(not(feature = "audit-log"))]
        let event: Option<((), Vec<u8>)> = None;

        self.finish(
            manager,
            key_path,
            file_id,
            keys.audit_key,
            region_keys,
            event,
        )
    }

    /// Create a new in-memory database (volatile, no file I/O).
    ///
    /// Data exists only for the lifetime of the returned `Database`.
    /// Useful for testing, caching, and WASM environments.
    pub fn create_in_memory(mut self) -> Result<Database> {
        #[cfg(feature = "fips")]
        self.validate_fips()?;

        // Per-region cryptographic erasure needs a durable overwrite-in-place sidecar,
        // which an in-memory database cannot provide; reject the combination up front.
        if self.enable_region_keys {
            return Err(Error::RegionKeysRequireFile);
        }

        let passphrase = self
            .passphrase
            .as_deref()
            .ok_or(Error::PassphraseRequired)?;

        let file_id: u64 = rand::random();

        let (_kf, keys, region_keys) = self.create_keys(passphrase, file_id)?;

        let dek_id = compute_dek_id(&keys.mac_key, &keys.dek);
        let io: Box<dyn PageIO> = Box::new(citadel_io::memory_io::MemoryPageIO::new());

        let manager = TxnManager::create_with_sync(
            io,
            keys.dek,
            keys.mac_key,
            1,
            file_id,
            dek_id,
            self.cache_size,
            self.sync_mode,
        )?;

        // Clear path so finish() won't create an audit log file on disk
        self.path = PathBuf::new();
        self.finish(
            manager,
            PathBuf::new(),
            file_id,
            keys.audit_key,
            region_keys,
            None,
        )
    }

    /// Open an existing database. Fails if the data file does not exist.
    #[cfg(not(target_arch = "wasm32"))]
    pub fn open(self) -> Result<Database> {
        let passphrase = self
            .passphrase
            .as_deref()
            .ok_or(Error::PassphraseRequired)?;

        let key_path = self.resolve_key_path();

        let mut file = OpenOptions::new().read(true).write(true).open(&self.path)?;

        file_lock::try_lock_exclusive(&file)?;

        let mut header_buf = [0u8; FILE_HEADER_SIZE];
        file.seek(SeekFrom::Start(0))?;
        file.read_exact(&mut header_buf)?;
        let header = FileHeader::deserialize(&header_buf)?;

        let key_data = fs::read(&key_path)?;
        if key_data.len() != KEY_FILE_SIZE {
            return Err(Error::Io(std::io::Error::new(
                std::io::ErrorKind::InvalidData,
                "key file has incorrect size",
            )));
        }
        let key_buf: [u8; KEY_FILE_SIZE] = key_data.try_into().unwrap();
        let (kf, keys, region_keys) = self.open_keys(&key_buf, passphrase, header.file_id)?;

        let dek_id = compute_dek_id(&keys.mac_key, &keys.dek);

        let io = Self::create_page_io(file);

        let manager = TxnManager::open_with_sync(
            io,
            keys.dek,
            keys.mac_key,
            kf.current_epoch,
            self.cache_size,
            self.sync_mode,
        )?;

        let slot = manager.current_slot();
        if slot.dek_id != dek_id {
            return Err(Error::BadPassphrase);
        }

        #[cfg(feature = "audit-log")]
        let event = Some((crate::audit::AuditEventType::DatabaseOpened, vec![]));
        #[cfg(not(feature = "audit-log"))]
        let event: Option<((), Vec<u8>)> = None;

        self.finish(
            manager,
            key_path,
            header.file_id,
            keys.audit_key,
            region_keys,
            event,
        )
    }

    /// Create a key file, deriving region wrap keys only when `enable_region_keys`
    /// is set. Returns the wrap keys to retain (`Some`) or `None` so the plaintext
    /// path holds no region key material.
    #[allow(clippy::type_complexity)]
    fn create_keys(
        &self,
        passphrase: &[u8],
        file_id: u64,
    ) -> Result<(
        citadel_crypto::key_manager::KeyFile,
        citadel_crypto::hkdf_utils::DerivedKeys,
        Option<RegionWrapKeys>,
    )> {
        let (m_cost, t_cost, p_cost) = self.resolve_kdf_params();
        if self.enable_region_keys {
            let (kf, keys, region) = create_key_file_with_region_keys(
                passphrase,
                file_id,
                self.cipher,
                self.kdf_algorithm,
                m_cost,
                t_cost,
                p_cost,
            )?;
            Ok((kf, keys, Some(region)))
        } else {
            let (kf, keys) = create_key_file(
                passphrase,
                file_id,
                self.cipher,
                self.kdf_algorithm,
                m_cost,
                t_cost,
                p_cost,
            )?;
            Ok((kf, keys, None))
        }
    }

    /// Open a key file, deriving region wrap keys only when `enable_region_keys`.
    #[cfg(not(target_arch = "wasm32"))]
    #[allow(clippy::type_complexity)]
    fn open_keys(
        &self,
        key_buf: &[u8; KEY_FILE_SIZE],
        passphrase: &[u8],
        expected_file_id: u64,
    ) -> Result<(
        citadel_crypto::key_manager::KeyFile,
        citadel_crypto::hkdf_utils::DerivedKeys,
        Option<RegionWrapKeys>,
    )> {
        if self.enable_region_keys {
            let (kf, keys, region) =
                open_key_file_with_region_keys(key_buf, passphrase, expected_file_id)?;
            Ok((kf, keys, Some(region)))
        } else {
            let (kf, keys) = open_key_file(key_buf, passphrase, expected_file_id)?;
            Ok((kf, keys, None))
        }
    }
}