Skip to main content

citadel/
database.rs

1use std::fs;
2#[cfg(not(target_arch = "wasm32"))]
3use std::fs::OpenOptions;
4use std::path::{Path, PathBuf};
5
6use citadel_core::{Error, Result, KEY_FILE_SIZE, MERKLE_HASH_SIZE};
7use citadel_io::durable;
8#[cfg(not(target_arch = "wasm32"))]
9use citadel_io::mmap_io::MmapPageIO;
10use citadel_txn::integrity::IntegrityReport;
11use citadel_txn::manager::TxnManager;
12use citadel_txn::read_txn::ReadTxn;
13use citadel_txn::write_txn::WriteTxn;
14
15#[cfg(feature = "audit-log")]
16use crate::audit::{AuditEventType, AuditLog};
17
18/// Database statistics read from the current commit slot.
19#[derive(Debug, Clone)]
20pub struct DbStats {
21    pub tree_depth: u16,
22    pub entry_count: u64,
23    pub total_pages: u32,
24    pub high_water_mark: u32,
25    pub merkle_root: [u8; MERKLE_HASH_SIZE],
26}
27
28/// An open Citadel database (`Send + Sync`).
29///
30/// Exclusively locks the database file for its lifetime.
31pub struct Database {
32    manager: TxnManager,
33    data_path: PathBuf,
34    key_path: PathBuf,
35    #[cfg(feature = "audit-log")]
36    audit_log: Option<parking_lot::Mutex<AuditLog>>,
37}
38
39impl std::fmt::Debug for Database {
40    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
41        f.debug_struct("Database")
42            .field("data_path", &self.data_path)
43            .field("key_path", &self.key_path)
44            .finish()
45    }
46}
47
48// TxnManager is internally synchronized (Mutex + Atomic)
49unsafe impl Send for Database {}
50unsafe impl Sync for Database {}
51
52impl Database {
53    #[cfg(feature = "audit-log")]
54    pub(crate) fn new(
55        manager: TxnManager,
56        data_path: PathBuf,
57        key_path: PathBuf,
58        audit_log: Option<AuditLog>,
59    ) -> Self {
60        Self {
61            manager,
62            data_path,
63            key_path,
64            audit_log: audit_log.map(parking_lot::Mutex::new),
65        }
66    }
67
68    #[cfg(not(feature = "audit-log"))]
69    pub(crate) fn new(manager: TxnManager, data_path: PathBuf, key_path: PathBuf) -> Self {
70        Self {
71            manager,
72            data_path,
73            key_path,
74        }
75    }
76
77    /// Begin a read-only transaction with snapshot isolation.
78    pub fn begin_read(&self) -> ReadTxn<'_> {
79        self.manager.begin_read()
80    }
81
82    /// Begin a read-write transaction. Only one can be active at a time.
83    pub fn begin_write(&self) -> Result<WriteTxn<'_>> {
84        self.manager.begin_write()
85    }
86
87    /// Get database statistics from the current commit slot.
88    pub fn stats(&self) -> DbStats {
89        let slot = self.manager.current_slot();
90        DbStats {
91            tree_depth: slot.tree_depth,
92            entry_count: slot.tree_entries,
93            total_pages: slot.total_pages,
94            high_water_mark: slot.high_water_mark,
95            merkle_root: slot.merkle_root,
96        }
97    }
98
99    pub fn data_path(&self) -> &Path {
100        &self.data_path
101    }
102
103    pub fn key_path(&self) -> &Path {
104        &self.key_path
105    }
106
107    /// Number of currently active readers.
108    pub fn reader_count(&self) -> usize {
109        self.manager.reader_count()
110    }
111
112    /// Change the database passphrase (re-wraps REK, no page re-encryption).
113    pub fn change_passphrase(&self, old_passphrase: &[u8], new_passphrase: &[u8]) -> Result<()> {
114        use citadel_crypto::kdf::{derive_mk, generate_salt};
115        use citadel_crypto::key_manager::{unwrap_rek, wrap_rek, KeyFile};
116
117        let key_data = fs::read(&self.key_path)?;
118        if key_data.len() != KEY_FILE_SIZE {
119            return Err(Error::Io(std::io::Error::new(
120                std::io::ErrorKind::InvalidData,
121                "key file has incorrect size",
122            )));
123        }
124        let key_buf: [u8; KEY_FILE_SIZE] = key_data.try_into().unwrap();
125        let kf = KeyFile::deserialize(&key_buf)?;
126
127        let old_mk = derive_mk(
128            kf.kdf_algorithm,
129            old_passphrase,
130            &kf.argon2_salt,
131            kf.argon2_m_cost,
132            kf.argon2_t_cost,
133            kf.argon2_p_cost,
134        )?;
135        kf.verify_mac(&old_mk)?;
136
137        let rek = unwrap_rek(&old_mk, &kf.wrapped_rek).map_err(|_| Error::BadPassphrase)?;
138
139        let new_salt = generate_salt();
140        let new_mk = derive_mk(
141            kf.kdf_algorithm,
142            new_passphrase,
143            &new_salt,
144            kf.argon2_m_cost,
145            kf.argon2_t_cost,
146            kf.argon2_p_cost,
147        )?;
148
149        let new_wrapped = wrap_rek(&new_mk, &rek);
150
151        let mut new_kf = kf.clone();
152        new_kf.argon2_salt = new_salt;
153        new_kf.wrapped_rek = new_wrapped;
154        new_kf.update_mac(&new_mk);
155
156        durable::atomic_write(&self.key_path, &new_kf.serialize())?;
157
158        #[cfg(feature = "audit-log")]
159        self.log_audit(AuditEventType::PassphraseChanged, &[]);
160
161        Ok(())
162    }
163
164    pub fn integrity_check(&self) -> Result<IntegrityReport> {
165        let report = self.manager.integrity_check()?;
166
167        #[cfg(feature = "audit-log")]
168        {
169            let error_count = report.errors.len() as u32;
170            self.log_audit(
171                AuditEventType::IntegrityCheckPerformed,
172                &error_count.to_le_bytes(),
173            );
174        }
175
176        Ok(report)
177    }
178
179    /// Create a hot backup via MVCC snapshot. Also copies the key file.
180    #[cfg(not(target_arch = "wasm32"))]
181    pub fn backup(&self, dest_path: &Path) -> Result<()> {
182        let dest_file = OpenOptions::new()
183            .read(true)
184            .write(true)
185            .create_new(true)
186            .open(dest_path)?;
187        let dest_io = MmapPageIO::try_new(dest_file)?;
188        self.manager.backup_to(&dest_io)?;
189
190        let dest_key_path = resolve_key_path_for(dest_path);
191        fs::copy(&self.key_path, &dest_key_path)?;
192
193        #[cfg(feature = "audit-log")]
194        self.log_audit_with_path(AuditEventType::BackupCreated, dest_path);
195
196        Ok(())
197    }
198
199    /// Export an encrypted key backup for disaster recovery.
200    ///
201    /// Requires the current database passphrase. The backup can later restore
202    /// access via `restore_key_from_backup` if the database passphrase is lost.
203    pub fn export_key_backup(
204        &self,
205        db_passphrase: &[u8],
206        backup_passphrase: &[u8],
207        dest_path: &Path,
208    ) -> Result<()> {
209        use citadel_crypto::kdf::derive_mk;
210        use citadel_crypto::key_backup::create_key_backup;
211        use citadel_crypto::key_manager::{unwrap_rek, KeyFile};
212
213        let key_data = fs::read(&self.key_path)?;
214        if key_data.len() != KEY_FILE_SIZE {
215            return Err(Error::Io(std::io::Error::new(
216                std::io::ErrorKind::InvalidData,
217                "key file has incorrect size",
218            )));
219        }
220        let key_buf: [u8; KEY_FILE_SIZE] = key_data.try_into().unwrap();
221        let kf = KeyFile::deserialize(&key_buf)?;
222
223        let mk = derive_mk(
224            kf.kdf_algorithm,
225            db_passphrase,
226            &kf.argon2_salt,
227            kf.argon2_m_cost,
228            kf.argon2_t_cost,
229            kf.argon2_p_cost,
230        )?;
231        kf.verify_mac(&mk)?;
232
233        let rek = unwrap_rek(&mk, &kf.wrapped_rek).map_err(|_| Error::BadPassphrase)?;
234
235        let backup_data = create_key_backup(
236            &rek,
237            backup_passphrase,
238            kf.file_id,
239            kf.cipher_id,
240            kf.kdf_algorithm,
241            kf.argon2_m_cost,
242            kf.argon2_t_cost,
243            kf.argon2_p_cost,
244            kf.current_epoch,
245        )?;
246
247        durable::write_and_sync(dest_path, &backup_data)?;
248
249        #[cfg(feature = "audit-log")]
250        self.log_audit_with_path(AuditEventType::KeyBackupExported, dest_path);
251
252        Ok(())
253    }
254
255    /// Restore a key file from an encrypted backup (static - no `Database` needed).
256    ///
257    /// Unwraps the REK using `backup_passphrase`, then creates a new key file
258    /// protected by `new_db_passphrase`.
259    pub fn restore_key_from_backup(
260        backup_path: &Path,
261        backup_passphrase: &[u8],
262        new_db_passphrase: &[u8],
263        db_path: &Path,
264    ) -> Result<()> {
265        use citadel_core::{
266            KEY_BACKUP_SIZE, KEY_FILE_MAGIC, KEY_FILE_VERSION, MAC_SIZE, WRAPPED_KEY_SIZE,
267        };
268        use citadel_crypto::kdf::{derive_mk, generate_salt};
269        use citadel_crypto::key_backup::restore_rek_from_backup;
270        use citadel_crypto::key_manager::wrap_rek;
271        use citadel_crypto::key_manager::KeyFile;
272
273        let backup_data = fs::read(backup_path)?;
274        if backup_data.len() != KEY_BACKUP_SIZE {
275            return Err(Error::Io(std::io::Error::new(
276                std::io::ErrorKind::InvalidData,
277                "backup file has incorrect size",
278            )));
279        }
280        let backup_buf: [u8; KEY_BACKUP_SIZE] = backup_data.try_into().unwrap();
281
282        let restored = restore_rek_from_backup(&backup_buf, backup_passphrase)?;
283
284        let new_salt = generate_salt();
285        let new_mk = derive_mk(
286            restored.kdf_algorithm,
287            new_db_passphrase,
288            &new_salt,
289            restored.kdf_param1,
290            restored.kdf_param2,
291            restored.kdf_param3,
292        )?;
293
294        let new_wrapped = wrap_rek(&new_mk, &restored.rek);
295
296        let mut new_kf = KeyFile {
297            magic: KEY_FILE_MAGIC,
298            version: KEY_FILE_VERSION,
299            file_id: restored.file_id,
300            argon2_salt: new_salt,
301            argon2_m_cost: restored.kdf_param1,
302            argon2_t_cost: restored.kdf_param2,
303            argon2_p_cost: restored.kdf_param3,
304            cipher_id: restored.cipher_id,
305            kdf_algorithm: restored.kdf_algorithm,
306            wrapped_rek: new_wrapped,
307            current_epoch: restored.epoch,
308            prev_wrapped_rek: [0u8; WRAPPED_KEY_SIZE],
309            prev_epoch: 0,
310            rotation_active: false,
311            file_mac: [0u8; MAC_SIZE],
312        };
313        new_kf.update_mac(&new_mk);
314
315        let key_path = resolve_key_path_for(db_path);
316        durable::atomic_write(&key_path, &new_kf.serialize())?;
317
318        Ok(())
319    }
320
321    /// Compact the database into a new file. Also copies the key file.
322    #[cfg(not(target_arch = "wasm32"))]
323    pub fn compact(&self, dest_path: &Path) -> Result<()> {
324        let dest_file = OpenOptions::new()
325            .read(true)
326            .write(true)
327            .create_new(true)
328            .open(dest_path)?;
329        let dest_io = MmapPageIO::try_new(dest_file)?;
330        self.manager.compact_to(&dest_io)?;
331
332        let dest_key_path = resolve_key_path_for(dest_path);
333        fs::copy(&self.key_path, &dest_key_path)?;
334
335        #[cfg(feature = "audit-log")]
336        self.log_audit_with_path(AuditEventType::CompactionPerformed, dest_path);
337
338        Ok(())
339    }
340}
341
342impl Database {
343    #[doc(hidden)]
344    pub fn manager(&self) -> &TxnManager {
345        &self.manager
346    }
347
348    /// Path to the audit log file, if audit logging is enabled.
349    #[cfg(feature = "audit-log")]
350    pub fn audit_log_path(&self) -> Option<PathBuf> {
351        if self.audit_log.is_some() && !self.data_path.as_os_str().is_empty() {
352            Some(crate::audit::resolve_audit_path(&self.data_path))
353        } else {
354            None
355        }
356    }
357
358    /// Verify the audit log's HMAC chain integrity.
359    #[cfg(feature = "audit-log")]
360    pub fn verify_audit_log(&self) -> Result<crate::audit::AuditVerifyResult> {
361        let audit = self
362            .audit_log
363            .as_ref()
364            .ok_or_else(|| Error::Io(std::io::Error::other("audit logging is not enabled")))?;
365        let guard = audit.lock();
366        let path = crate::audit::resolve_audit_path(&self.data_path);
367        crate::audit::verify_audit_log(&path, guard.audit_key())
368    }
369
370    #[cfg(feature = "audit-log")]
371    pub(crate) fn log_audit(&self, event_type: AuditEventType, detail: &[u8]) {
372        if let Some(ref mutex) = self.audit_log {
373            let _ = mutex.lock().log(event_type, detail);
374        }
375    }
376
377    #[cfg(feature = "audit-log")]
378    fn log_audit_with_path(&self, event_type: AuditEventType, path: &Path) {
379        let path_str = path.to_string_lossy();
380        let path_bytes = path_str.as_bytes();
381        let len = (path_bytes.len() as u16).to_le_bytes();
382        let mut detail = Vec::with_capacity(2 + path_bytes.len());
383        detail.extend_from_slice(&len);
384        detail.extend_from_slice(path_bytes);
385        self.log_audit(event_type, &detail);
386    }
387}
388
389use citadel_sync::transport::SyncTransport;
390
391/// Outcome of a sync operation.
392#[derive(Debug, Clone)]
393pub struct SyncOutcome {
394    /// Per-table results: `(table_name, entries_applied)`.
395    pub tables_synced: Vec<(Vec<u8>, u64)>,
396    /// Default tree sync result (if performed).
397    pub default_tree: Option<citadel_sync::SyncOutcome>,
398}
399
400const NODE_ID_KEY: &[u8] = b"__citadel_node_id";
401
402impl Database {
403    /// Get or create a persistent NodeId for this database.
404    pub fn node_id(&self) -> Result<citadel_sync::NodeId> {
405        let mut rtx = self.manager.begin_read();
406        if let Some(data) = rtx.get(NODE_ID_KEY)? {
407            if data.len() == 8 {
408                return Ok(citadel_sync::NodeId::from_bytes(
409                    data[..8].try_into().unwrap(),
410                ));
411            }
412        }
413        drop(rtx);
414
415        let node_id = citadel_sync::NodeId::random();
416        let mut wtx = self.manager.begin_write()?;
417        wtx.insert(NODE_ID_KEY, &node_id.to_bytes())?;
418        wtx.commit()?;
419        Ok(node_id)
420    }
421
422    /// Push local named tables to a remote peer.
423    pub fn sync_to(&self, addr: &str, sync_key: &citadel_sync::SyncKey) -> Result<SyncOutcome> {
424        let node_id = self.node_id()?;
425        let transport =
426            citadel_sync::NoiseTransport::connect(addr, sync_key).map_err(sync_err_to_core)?;
427        let session = citadel_sync::SyncSession::new(citadel_sync::SyncConfig {
428            node_id,
429            direction: citadel_sync::SyncDirection::Push,
430            crdt_aware: false,
431        });
432
433        let results = session
434            .sync_tables_as_initiator(&self.manager, &transport)
435            .map_err(sync_err_to_core)?;
436
437        transport.close().map_err(sync_err_to_core)?;
438
439        Ok(SyncOutcome {
440            tables_synced: results
441                .into_iter()
442                .map(|(name, r)| (name, r.entries_applied))
443                .collect(),
444            default_tree: None,
445        })
446    }
447
448    /// Handle an incoming sync session from a remote peer.
449    pub fn handle_sync(
450        &self,
451        stream: std::net::TcpStream,
452        sync_key: &citadel_sync::SyncKey,
453    ) -> Result<SyncOutcome> {
454        let node_id = self.node_id()?;
455        let transport =
456            citadel_sync::NoiseTransport::accept(stream, sync_key).map_err(sync_err_to_core)?;
457        let session = citadel_sync::SyncSession::new(citadel_sync::SyncConfig {
458            node_id,
459            direction: citadel_sync::SyncDirection::Push,
460            crdt_aware: false,
461        });
462
463        let results = session
464            .handle_table_sync_as_responder(&self.manager, &transport)
465            .map_err(sync_err_to_core)?;
466
467        transport.close().map_err(sync_err_to_core)?;
468
469        Ok(SyncOutcome {
470            tables_synced: results
471                .into_iter()
472                .map(|(name, r)| (name, r.entries_applied))
473                .collect(),
474            default_tree: None,
475        })
476    }
477}
478
479fn sync_err_to_core(e: citadel_sync::transport::SyncError) -> Error {
480    match e {
481        citadel_sync::transport::SyncError::Io(io) => Error::Io(io),
482        other => Error::Sync(other.to_string()),
483    }
484}
485
486#[cfg(feature = "audit-log")]
487impl Drop for Database {
488    fn drop(&mut self) {
489        self.log_audit(AuditEventType::DatabaseClosed, &[]);
490    }
491}
492
493/// `{data_path}.citadel-keys`
494fn resolve_key_path_for(data_path: &Path) -> PathBuf {
495    let mut name = data_path.as_os_str().to_os_string();
496    name.push(".citadel-keys");
497    PathBuf::from(name)
498}