1use std::ffi::c_int;
4use std::path::{Path, PathBuf};
5use std::time::Duration;
6
7use rusqlite::{Connection, ErrorCode};
8
9use crate::envelope::Key;
10
11pub const SCHEMA_VERSION: i64 = 11;
27
28const TENANT_KEY_WRAP: &str = "
35ALTER TABLE tenant ADD COLUMN wrap_ref TEXT;
36ALTER TABLE tenant ADD COLUMN wrapped_kek BLOB CHECK ((wrap_ref IS NULL) = (wrapped_kek IS NULL));
37ALTER TABLE tenant ADD COLUMN pending_wrap_ref TEXT;
38ALTER TABLE tenant ADD COLUMN pending_wrapped_kek BLOB CHECK ((pending_wrap_ref IS NULL) = (pending_wrapped_kek IS NULL));
39";
40
41const KEY_LIFE: &str = "
45ALTER TABLE api_key ADD COLUMN expires_at INTEGER;
46ALTER TABLE api_key ADD COLUMN last_used_at INTEGER;
47";
48
49pub(crate) const SESSIONS: &str = "
56CREATE TABLE session (
57 id_hash BLOB PRIMARY KEY NOT NULL CHECK (length(id_hash) = 32),
58 user BLOB NOT NULL,
59 tenant BLOB,
60 scopes TEXT NOT NULL,
61 created_at INTEGER NOT NULL,
62 last_seen_at INTEGER NOT NULL,
63 idle_expires_at INTEGER NOT NULL,
64 expires_at INTEGER NOT NULL,
65 idle_seconds INTEGER NOT NULL,
66 amr TEXT NOT NULL,
67 csrf_hash BLOB NOT NULL CHECK (length(csrf_hash) = 32)
68);
69CREATE INDEX session_of_user ON session (user);
70CREATE INDEX session_in_tenant ON session (tenant);
71";
72
73pub(crate) const USER_TABLES: &str = "
83CREATE TABLE user_account (
84 id BLOB PRIMARY KEY NOT NULL,
85 label TEXT NOT NULL,
86 issuer TEXT,
87 subject TEXT,
88 created_at INTEGER NOT NULL,
89 deactivated_at INTEGER,
90 CHECK ((issuer IS NULL) = (subject IS NULL))
91);
92CREATE UNIQUE INDEX user_account_identity ON user_account (issuer, subject)
93 WHERE issuer IS NOT NULL AND deactivated_at IS NULL;
94CREATE TABLE membership (
95 user BLOB NOT NULL,
96 tenant BLOB,
97 roles TEXT NOT NULL,
98 granted_at INTEGER NOT NULL
99);
100CREATE UNIQUE INDEX membership_in_tenant ON membership (user, tenant)
101 WHERE tenant IS NOT NULL;
102CREATE UNIQUE INDEX membership_as_operator ON membership (user)
103 WHERE tenant IS NULL;
104CREATE INDEX membership_of_tenant ON membership (tenant);
105";
106
107fn audit_without_zero() -> String {
119 format!(
120 "ALTER TABLE audit RENAME TO audit_v4;
121DROP INDEX audit_counted;
122{}
123INSERT INTO audit (seq, at, actor, action, target, version, status, count)
124 SELECT seq, at, actor, action, target, version, nullif(status, 0), count
125 FROM audit_v4 ORDER BY seq;
126UPDATE sqlite_sequence
127 SET seq = coalesce((SELECT seq FROM sqlite_sequence WHERE name = 'audit_v4'), seq)
128 WHERE name = 'audit';
129DROP TABLE audit_v4;",
130 crate::audit::SCHEMA
131 )
132}
133
134const VCON_STORED_AT: &str = "
139ALTER TABLE vcon ADD COLUMN stored_at INTEGER NOT NULL DEFAULT 0;
140UPDATE vcon SET stored_at =
141 coalesce((SELECT min(stored_at) FROM version WHERE version.uuid = vcon.uuid), 0);
142CREATE INDEX vcon_listed ON vcon (stored_at, uuid);
143";
144
145const TENANT_METADATA: &str = "ALTER TABLE tenant ADD COLUMN metadata TEXT;";
148
149const TENANT_ROLE_CAP: &str = "ALTER TABLE tenant ADD COLUMN role_cap TEXT;";
152
153pub(crate) const TENANT_SETTINGS: &str = "
158CREATE TABLE tenant_setting (
159 tenant BLOB NOT NULL,
160 name TEXT NOT NULL,
161 value TEXT NOT NULL,
162 PRIMARY KEY (tenant, name)
163);
164";
165
166pub(crate) const PACK_TABLES: &str = "
175CREATE INDEX version_place ON version (place_file);
176CREATE TABLE parquet_file (
177 file_id BLOB PRIMARY KEY NOT NULL,
178 date TEXT NOT NULL,
179 rows INTEGER NOT NULL,
180 live_rows INTEGER NOT NULL,
181 bytes INTEGER NOT NULL,
182 created_at INTEGER NOT NULL,
183 unnamed_at INTEGER
184);
185CREATE TABLE purge_pending (
186 file_id BLOB PRIMARY KEY NOT NULL
187);
188CREATE TABLE manifest (
189 seq INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
190 published_at INTEGER
191);
192";
193
194const VERSION_PLACES: &str = "
198ALTER TABLE version ADD COLUMN place_file BLOB;
199ALTER TABLE version ADD COLUMN place_group INTEGER;
200ALTER TABLE version ADD COLUMN place_row INTEGER;
201";
202
203pub const BUSY_TIMEOUT: Duration = Duration::from_secs(5);
208
209pub(crate) const STATEMENT_CACHE: usize = 64;
213
214pub(crate) trait Cached {
220 fn cached_row<T, P, F>(&self, sql: &str, params: P, f: F) -> rusqlite::Result<T>
222 where
223 P: rusqlite::Params,
224 F: FnOnce(&rusqlite::Row<'_>) -> rusqlite::Result<T>;
225
226 fn cached_run<P: rusqlite::Params>(&self, sql: &str, params: P) -> rusqlite::Result<usize>;
228}
229
230impl Cached for Connection {
231 fn cached_row<T, P, F>(&self, sql: &str, params: P, f: F) -> rusqlite::Result<T>
232 where
233 P: rusqlite::Params,
234 F: FnOnce(&rusqlite::Row<'_>) -> rusqlite::Result<T>,
235 {
236 self.prepare_cached(sql)?.query_row(params, f)
237 }
238
239 fn cached_run<P: rusqlite::Params>(&self, sql: &str, params: P) -> rusqlite::Result<usize> {
240 self.prepare_cached(sql)?.execute(params)
241 }
242}
243
244#[derive(Debug)]
246pub enum CatalogError {
247 WrongKey,
249 UnknownSchema(i64),
251 Sqlite(rusqlite::Error),
253 Io(std::io::Error),
255 Access {
259 path: PathBuf,
260 error: std::io::Error,
261 },
262}
263
264impl std::fmt::Display for CatalogError {
265 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
266 match self {
267 CatalogError::WrongKey => {
268 f.write_str("the key is not the one the catalog was made with")
269 }
270 CatalogError::UnknownSchema(version) => {
271 write!(f, "schema version {version} is not one this build knows")
272 }
273 CatalogError::Sqlite(_) => f.write_str("sqlite failed"),
274 CatalogError::Io(_) => {
275 f.write_str("a file around the catalog could not be read, written or renamed")
276 }
277 CatalogError::Access { path, .. } => {
278 write!(f, "this process may not read and write {}", path.display())
279 }
280 }
281 }
282}
283
284impl std::error::Error for CatalogError {
285 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
286 match self {
287 CatalogError::Sqlite(e) => Some(e),
288 CatalogError::Io(e) | CatalogError::Access { error: e, .. } => Some(e),
289 CatalogError::WrongKey | CatalogError::UnknownSchema(_) => None,
290 }
291 }
292}
293
294impl From<rusqlite::Error> for CatalogError {
295 fn from(e: rusqlite::Error) -> CatalogError {
296 CatalogError::Sqlite(e)
297 }
298}
299
300pub fn open(path: &Path, key: &Key, schema: &str) -> Result<Connection, CatalogError> {
303 if let Some(dir) = path.parent() {
307 may_use(dir, libc::W_OK | libc::X_OK)?;
308 }
309 if path.exists() {
310 may_use(path, libc::R_OK | libc::W_OK)?;
311 } else {
312 make_file(path)?;
313 }
314 let conn = Connection::open(path)?;
315 conn.busy_timeout(BUSY_TIMEOUT)?;
316 conn.set_prepared_statement_cache_capacity(STATEMENT_CACHE);
317 conn.pragma_update(None, "cipher_log_level", "NONE")?;
320 set_key(&conn, key)?;
321 match conn.query_row("SELECT count(*) FROM sqlite_master", [], |_| Ok(())) {
324 Err(e) if e.sqlite_error_code() == Some(ErrorCode::NotADatabase) => {
325 return Err(CatalogError::WrongKey);
326 }
327 other => other?,
328 }
329 let mode: String = conn.pragma_update_and_check(None, "journal_mode", "WAL", |r| r.get(0))?;
333 debug_assert_eq!(mode, "wal");
334 conn.pragma_update(None, "synchronous", "FULL")?;
335 conn.pragma_update(None, "secure_delete", "ON")?;
336 conn.pragma_update(None, "temp_store", "MEMORY")?;
337 match conn.pragma_query_value(None, "user_version", |r| r.get(0))? {
338 0 => {
339 let tx = conn.unchecked_transaction()?;
340 tx.execute_batch(schema)?;
341 tx.pragma_update(None, "user_version", SCHEMA_VERSION)?;
342 tx.commit()?;
343 }
344 from @ 1..=10 => {
345 let tx = conn.unchecked_transaction()?;
349 let has = |table: &str| -> rusqlite::Result<bool> {
350 tx.query_row(
351 "SELECT count(*) > 0 FROM sqlite_master WHERE type = 'table' AND name = ?1",
352 [table],
353 |r| r.get(0),
354 )
355 };
356 if from < 2 && has("vcon")? {
357 tx.execute_batch(VCON_STORED_AT)?;
358 }
359 if from < 3 && has("tenant")? {
360 tx.execute_batch(TENANT_METADATA)?;
361 }
362 if from < 4 && has("version")? {
363 tx.execute_batch(VERSION_PLACES)?;
364 tx.execute_batch(PACK_TABLES)?;
365 }
366 if from < 5 && has("tenant")? {
367 tx.execute_batch(USER_TABLES)?;
368 }
369 if from < 5 && has("audit")? {
370 tx.execute_batch(&audit_without_zero())?;
371 }
372 if from < 6 && has("tenant")? {
373 tx.execute_batch(TENANT_ROLE_CAP)?;
374 }
375 if from < 7 && has("tenant")? {
376 tx.execute_batch(TENANT_SETTINGS)?;
377 }
378 if from < 8 && has("tenant")? {
379 tx.execute_batch(SESSIONS)?;
380 }
381 if from < 9 && has("api_key")? {
382 tx.execute_batch(KEY_LIFE)?;
383 }
384 if from < 10 && has("audit")? {
385 if from >= 5 {
388 tx.execute_batch(crate::audit::COUNTED_COLUMN)?;
389 }
390 tx.execute_batch(crate::audit::COUNTED_BEFORE_10)?;
391 }
392 if from < 11 && has("tenant")? {
393 tx.execute_batch(TENANT_KEY_WRAP)?;
394 }
395 tx.pragma_update(None, "user_version", SCHEMA_VERSION)?;
396 tx.commit()?;
397 }
398 SCHEMA_VERSION => {}
399 other => return Err(CatalogError::UnknownSchema(other)),
400 }
401 Ok(conn)
402}
403
404pub(crate) fn may_use(path: &Path, how: c_int) -> Result<(), CatalogError> {
407 let denied = |error| CatalogError::Access {
408 path: path.to_owned(),
409 error,
410 };
411 let text = std::ffi::CString::new(path.as_os_str().as_encoded_bytes())
412 .map_err(|_| denied(std::io::ErrorKind::InvalidInput.into()))?;
413 if unsafe { libc::faccessat(libc::AT_FDCWD, text.as_ptr(), how, libc::AT_EACCESS) } != 0 {
416 return Err(denied(std::io::Error::last_os_error()));
417 }
418 Ok(())
419}
420
421pub fn backup(source: &Connection, to: &Path, key: &Key) -> Result<(), CatalogError> {
429 let io = CatalogError::Io;
430 make_file(to)?;
431 {
432 let mut copy = Connection::open(to)?;
433 copy.pragma_update(None, "cipher_log_level", "NONE")?;
434 set_key(©, key)?;
435 let backup = rusqlite::backup::Backup::new(source, &mut copy)?;
436 match backup.step(-1)? {
438 rusqlite::backup::StepResult::Done => {}
439 _ => {
440 return Err(io(std::io::Error::other(
441 "the catalog was busy and could not be copied in one step",
442 )));
443 }
444 }
445 }
446 std::fs::File::open(to)
447 .and_then(|f| f.sync_all())
448 .map_err(io)?;
449 let dir = to.parent().unwrap_or(Path::new("."));
450 std::fs::File::open(dir)
451 .and_then(|f| f.sync_all())
452 .map_err(io)?;
453 Ok(())
454}
455
456pub fn reencrypt(path: &Path, old: &Key, new: &Key) -> Result<(), CatalogError> {
463 let copy = copy_under(path, old, new)?;
464 replace(path, ©)
465}
466
467pub fn copy_under(path: &Path, old: &Key, new: &Key) -> Result<PathBuf, CatalogError> {
472 let target = sibling(path, ".rekey");
473 for stale in [
474 target.clone(),
475 sibling(&target, "-wal"),
476 sibling(&target, "-shm"),
477 ] {
478 remove_if_there(&stale)?;
479 }
480 make_file(&target)?;
481 let conn = open(path, old, "")?;
482 let version: i64 = conn.pragma_query_value(None, "user_version", |r| r.get(0))?;
483 let target_text = target
484 .to_str()
485 .ok_or_else(|| CatalogError::Io(std::io::Error::other("the catalog path is not UTF-8")))?;
486 conn.execute("ATTACH DATABASE ?1 AS rekeyed", [target_text])?;
487 set_key_of(&conn, c"rekeyed", new)?;
488 conn.query_row("SELECT sqlcipher_export('rekeyed')", [], |_| Ok(()))?;
489 conn.execute_batch(&format!("PRAGMA rekeyed.user_version = {version}"))?;
492 conn.execute("DETACH DATABASE rekeyed", [])?;
493 Ok(target)
494}
495
496pub fn replace(path: &Path, copy: &Path) -> Result<(), CatalogError> {
501 for file in [path, copy] {
502 let wal = sibling(file, "-wal");
503 if std::fs::metadata(&wal).is_ok_and(|m| m.len() > 0) {
504 return Err(CatalogError::Io(std::io::Error::other(
505 "a catalog's WAL was not emptied",
506 )));
507 }
508 remove_if_there(&wal)?;
509 remove_if_there(&sibling(file, "-shm"))?;
510 }
511 let io = CatalogError::Io;
512 std::fs::File::open(copy)
513 .and_then(|f| f.sync_all())
514 .map_err(io)?;
515 std::fs::rename(copy, path).map_err(io)?;
516 let dir = path.parent().unwrap_or(Path::new("."));
517 std::fs::File::open(dir)
518 .and_then(|f| f.sync_all())
519 .map_err(io)?;
520 Ok(())
521}
522
523fn make_file(path: &Path) -> Result<(), CatalogError> {
527 use std::os::unix::fs::OpenOptionsExt;
528 std::fs::OpenOptions::new()
529 .write(true)
530 .create_new(true)
531 .mode(crate::fs::FILE_MODE)
532 .open(path)
533 .map(drop)
534 .map_err(CatalogError::Io)
535}
536
537fn remove_if_there(file: &Path) -> Result<(), CatalogError> {
538 match std::fs::remove_file(file) {
539 Err(e) if e.kind() != std::io::ErrorKind::NotFound => Err(CatalogError::Io(e)),
540 _ => Ok(()),
541 }
542}
543
544pub(crate) fn sibling(path: &Path, suffix: &str) -> PathBuf {
546 let mut name = path.as_os_str().to_owned();
547 name.push(suffix);
548 PathBuf::from(name)
549}
550
551fn set_key_of(conn: &Connection, schema: &std::ffi::CStr, key: &Key) -> Result<(), CatalogError> {
553 let literal = key.sqlcipher_raw();
554 let len = c_int::try_from(literal.len()).expect("a 67-byte literal");
555 let rc = unsafe {
559 rusqlite::ffi::sqlite3_key_v2(conn.handle(), schema.as_ptr(), literal.as_ptr().cast(), len)
560 };
561 if rc != rusqlite::ffi::SQLITE_OK {
562 return Err(rusqlite::Error::SqliteFailure(rusqlite::ffi::Error::new(rc), None).into());
563 }
564 Ok(())
565}
566
567fn set_key(conn: &Connection, key: &Key) -> Result<(), CatalogError> {
571 let literal = key.sqlcipher_raw();
572 let len = c_int::try_from(literal.len()).expect("a 67-byte literal");
573 let rc = unsafe { rusqlite::ffi::sqlite3_key(conn.handle(), literal.as_ptr().cast(), len) };
576 if rc != rusqlite::ffi::SQLITE_OK {
579 return Err(rusqlite::Error::SqliteFailure(rusqlite::ffi::Error::new(rc), None).into());
580 }
581 Ok(())
582}
583
584#[cfg(test)]
586mod v5_tests;
587
588#[cfg(test)]
589mod v6_tests;
590
591#[cfg(test)]
592mod v7_tests;
593
594#[cfg(test)]
595mod v8_tests;
596
597#[cfg(test)]
598mod v9_tests;
599
600#[cfg(test)]
601mod v10_tests;
602
603#[cfg(test)]
604mod v11_tests;
605
606#[cfg(test)]
607pub(crate) mod testing {
608 use std::collections::BTreeMap;
609 use std::ffi::CStr;
610
611 use rusqlite::Connection;
612
613 pub(crate) fn prepared(conn: &Connection) -> BTreeMap<usize, String> {
616 statements(conn)
617 .into_iter()
618 .map(|(at, (sql, _))| (at, sql))
619 .collect()
620 }
621
622 pub(crate) fn reprepared(conn: &Connection) -> Vec<(String, i32)> {
627 statements(conn)
628 .into_values()
629 .filter(|(_, again)| *again > 0)
630 .collect()
631 }
632
633 fn statements(conn: &Connection) -> BTreeMap<usize, (String, i32)> {
636 let mut kept = BTreeMap::new();
637 let db = unsafe { conn.handle() };
640 let mut stmt = std::ptr::null_mut();
641 loop {
642 stmt = unsafe { rusqlite::ffi::sqlite3_next_stmt(db, stmt) };
646 if stmt.is_null() {
647 return kept;
648 }
649 let text = unsafe { rusqlite::ffi::sqlite3_sql(stmt) };
652 let sql = if text.is_null() {
653 String::new()
654 } else {
655 let sql = unsafe { CStr::from_ptr(text) };
658 sql.to_string_lossy()
659 .split_whitespace()
660 .collect::<Vec<_>>()
661 .join(" ")
662 };
663 let again = unsafe {
666 rusqlite::ffi::sqlite3_stmt_status(
667 stmt,
668 rusqlite::ffi::SQLITE_STMTSTATUS_REPREPARE,
669 0,
670 )
671 };
672 kept.insert(stmt as usize, (sql, again));
673 }
674 }
675
676 pub(crate) fn keeps(conn: &Connection, start: &str) -> bool {
678 prepared(conn).values().any(|sql| sql.starts_with(start))
679 }
680
681 pub(crate) fn columns_taking_null(
685 conn: &Connection,
686 table: &str,
687 row: &[(&str, &str)],
688 ) -> Vec<String> {
689 let insert = |empty: Option<&str>| {
690 let columns: Vec<&str> = row.iter().map(|(c, _)| *c).collect();
691 let values: Vec<&str> = row
692 .iter()
693 .map(|(c, v)| if Some(*c) == empty { "NULL" } else { *v })
694 .collect();
695 let sql = format!(
696 "INSERT INTO {table} ({}) VALUES ({})",
697 columns.join(", "),
698 values.join(", ")
699 );
700 let tx = conn.unchecked_transaction().expect("begin");
701 let taken = tx.execute(&sql, []).is_ok();
702 drop(tx);
703 taken
704 };
705 assert!(insert(None), "a whole {table} row inserts");
706 row.iter()
707 .filter(|(column, _)| insert(Some(column)))
708 .map(|(column, _)| format!("{table}.{column}"))
709 .collect()
710 }
711}
712
713#[cfg(test)]
714pub(crate) mod tests {
715 use super::*;
716
717 const SCHEMA: &str = "CREATE TABLE note (text TEXT NOT NULL);";
718 const MARKER: &str = "plain-record-marker-5f3c9a";
719
720 fn path(dir: &tempfile::TempDir) -> std::path::PathBuf {
721 dir.path().join("catalog.sqlite")
722 }
723
724 pub(crate) fn cipher_setting(conn: &Connection, name: &str) -> String {
726 conn.pragma_query_value(None, name, |r| r.get(0))
727 .expect(name)
728 }
729
730 fn linked_sqlite(conn: &Connection) -> (u32, u32, u32) {
733 let text: String = conn
734 .query_row("SELECT sqlite_version()", [], |r| r.get(0))
735 .expect("the version");
736 let mut parts = text.split('.').map(|part| part.parse().expect("a number"));
737 let mut next = || parts.next().expect("three parts");
738 (next(), next(), next())
739 }
740
741 #[test]
742 fn the_linked_sqlite_is_not_one_cve_2026_119375_affects() {
743 let dir = tempfile::tempdir().expect("temp dir");
749 let key = Key::generate().expect("key");
750 let conn = open(&path(&dir), &key, SCHEMA).expect("opens");
751 let linked = linked_sqlite(&conn);
752 assert!(linked >= (3, 54, 0), "SQLite {linked:?} is before 3.54.0");
753 assert_eq!(
754 rusqlite::version_number(),
755 i32::try_from(linked.0 * 1_000_000 + linked.1 * 1_000 + linked.2).expect("fits"),
756 "the library rusqlite links is the one the catalog runs on"
757 );
758 let cipher = cipher_setting(&conn, "cipher_version");
759 assert!(
760 cipher.starts_with("4."),
761 "SQLCipher 4, whose file format release 0.4.3 wrote: {cipher}"
762 );
763 }
764
765 #[test]
766 fn a_catalog_runs_with_the_required_settings() {
767 let dir = tempfile::tempdir().expect("temp dir");
768 let key = Key::generate().expect("key");
769 let conn = open(&path(&dir), &key, SCHEMA).expect("opens");
770 let text = |p: &str| -> String { conn.pragma_query_value(None, p, |r| r.get(0)).expect(p) };
771 let number = |p: &str| -> i64 { conn.pragma_query_value(None, p, |r| r.get(0)).expect(p) };
772 assert_eq!(text("journal_mode"), "wal");
773 assert_eq!(number("synchronous"), 2, "FULL");
774 assert_eq!(number("secure_delete"), 1);
775 assert_eq!(number("temp_store"), 2, "MEMORY");
776 assert_eq!(number("busy_timeout"), 5000, "milliseconds");
777 assert_eq!(cipher_setting(&conn, "cipher_provider"), "openssl");
778 assert_eq!(
779 cipher_setting(&conn, "cipher_log_level"),
780 "NONE",
781 "SQLCipher writes no log of its own"
782 );
783 }
784
785 #[test]
791 fn sqlcipher_settings_read_the_same_through_the_pragma_helpers() {
792 let dir = tempfile::tempdir().expect("temp dir");
793 let key = Key::generate().expect("key");
794 let conn = open(&path(&dir), &key, SCHEMA).expect("opens");
795 let names = ["cipher_log_level", "cipher_provider", "cipher_page_size"];
796 let plain: Vec<String> = names
797 .iter()
798 .map(|n| {
799 conn.query_row(&format!("PRAGMA {n}"), [], |r| r.get(0))
800 .unwrap_or_else(|e| panic!("{n} as plain SQL: {e}"))
801 })
802 .collect();
803
804 let helpers = Connection::open(path(&dir)).expect("opens again");
805 helpers
808 .pragma_update(None, "cipher_log_level", "NONE")
809 .expect("cipher_log_level through pragma_update");
810 set_key(&helpers, &key).expect("keyed");
811 let notes: i64 = helpers
812 .query_row("SELECT count(*) FROM note", [], |r| r.get(0))
813 .expect("the key opens the same catalog");
814 assert_eq!(notes, 0);
815 let read: Vec<String> = names
816 .iter()
817 .map(|n| {
818 helpers
819 .pragma_query_value(None, n, |r| r.get(0))
820 .unwrap_or_else(|e| panic!("{n} through pragma_query_value: {e}"))
821 })
822 .collect();
823 assert_eq!(read, plain);
824 assert_eq!(plain[0], "NONE");
825 let ours: Vec<String> = names.iter().map(|n| cipher_setting(&conn, n)).collect();
826 assert_eq!(ours, plain, "cipher_setting reads what plain SQL reads");
827 }
828
829 #[test]
836 fn rusqlite_takes_sqlcipher_names_in_its_pragma_helpers() {
837 let conn = Connection::open_in_memory().expect("opens");
838 let taken = conn.pragma_update(None, "cipher_log_level", "NONE");
839 assert!(
840 taken.is_ok(),
841 "this rusqlite refuses SQLCipher's pragma names ({taken:?}): catalog::open and \
842 catalog::backup set cipher_log_level through pragma_update"
843 );
844 let level: String = conn
845 .pragma_query_value(None, "cipher_log_level", |r| r.get(0))
846 .expect("cipher_log_level through pragma_query_value");
847 assert_eq!(level, "NONE", "and reads back what was set");
848 }
849
850 mod sources {
855 use std::path::PathBuf;
856
857 fn read(relative: &str) -> String {
858 let path = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join(relative);
859 std::fs::read_to_string(&path).unwrap_or_else(|e| panic!("{}: {e}", path.display()))
860 }
861
862 fn table(text: &str) -> toml::Table {
863 text.parse().expect("toml")
864 }
865
866 fn git_dependencies(manifest: &toml::Table) -> Vec<String> {
869 ["dependencies", "dev-dependencies", "build-dependencies"]
870 .iter()
871 .filter_map(|kind| Some((kind, manifest.get(*kind)?.as_table()?)))
872 .flat_map(|(kind, deps)| {
873 deps.iter()
874 .filter(|(_, spec)| spec.get("git").is_some())
875 .map(move |(name, _)| format!("{kind}.{name}"))
876 })
877 .collect()
878 }
879
880 #[test]
881 fn the_git_dependency_reader_finds_one_in_any_table() {
882 let manifest = table(
883 "[dependencies]\nplain = \"1\"\n\
884 [dev-dependencies]\nforked = { package = \"plain\", git = \"https://example.com/forked\" }\n\
885 [build-dependencies]\nother = { git = \"https://example.com/other\", rev = \"abc\" }\n",
886 );
887 assert_eq!(
888 git_dependencies(&manifest),
889 ["dev-dependencies.forked", "build-dependencies.other"],
890 "each git dependency, with its table"
891 );
892 assert!(
893 git_dependencies(&table("[dependencies]\nplain = \"1\"\n")).is_empty(),
894 "a crates.io dependency is not one"
895 );
896 assert!(
897 git_dependencies(&table("[package]\nname = \"none\"\n")).is_empty(),
898 "a manifest with no dependency table has none"
899 );
900 }
901
902 #[test]
903 fn no_dependency_comes_from_a_git_repository() {
904 let manifest = table(&read("Cargo.toml"));
905 assert_eq!(
906 git_dependencies(&manifest),
907 [] as [&str; 0],
908 "vcon-server's Cargo.toml"
909 );
910 let server = &manifest["dependencies"]["rusqlite"];
911 assert!(
912 server.get("version").is_some()
913 && server.get("git").is_none()
914 && server.get("path").is_none(),
915 "the server's rusqlite comes from crates.io"
916 );
917 assert!(
918 manifest["dev-dependencies"].get("rusqlite_fork").is_none(),
919 "the fork is gone"
920 );
921 }
922
923 #[test]
924 fn the_workspace_patches_nothing() {
925 let workspace = table(&read("../../Cargo.toml"));
926 assert!(
927 workspace.get("patch").is_none(),
928 "no [patch] table: {:?}",
929 workspace.get("patch")
930 );
931 }
932
933 #[test]
934 fn no_lockfile_names_a_git_source() {
935 for lockfile in ["../../Cargo.lock", "../../fuzz/Cargo.lock"] {
936 let lock = read(lockfile);
937 let git: Vec<&str> = lock
938 .lines()
939 .filter(|l| l.starts_with("source = \"git+"))
940 .collect();
941 assert_eq!(git, [] as [&str; 0], "{lockfile}");
942 }
943 }
944
945 #[test]
946 fn the_pages_name_no_fork() {
947 let development = read("../../website/content/docs/development.md");
948 assert!(
949 !development.contains("\n## Test dependency from a fork\n"),
950 "the Development page's section on the fork is gone"
951 );
952 let install = read("../../website/content/docs/install.md");
953 let build = install
954 .split("\n## ")
955 .find(|s| s.starts_with("Build from source\n"))
956 .expect("a Build from source section");
957 assert!(
958 build.contains("mkdir -p .cargo && cargo vendor >> .cargo/config.toml\n"),
959 "the vendoring command"
960 );
961 assert!(build.contains("cargo build --release --offline\n"));
962 for page in [&development, &install] {
963 assert!(!page.contains("NormB/rusqlite"), "no page names the fork");
964 assert!(!page.contains("rusqlite fork"), "no page speaks of a fork");
965 }
966 let release = install
967 .split("\n## ")
968 .find(|s| s.starts_with("Download a release\n"))
969 .expect("a release section");
970 assert!(
971 release.contains("crates.io"),
972 "says where the release's rusqlite comes from"
973 );
974 }
975 }
976
977 #[test]
978 fn the_schema_is_made_once_at_the_current_version() {
979 let dir = tempfile::tempdir().expect("temp dir");
980 let key = Key::generate().expect("key");
981 let conn = open(&path(&dir), &key, SCHEMA).expect("opens");
982 let version: i64 = conn
983 .pragma_query_value(None, "user_version", |r| r.get(0))
984 .expect("version");
985 assert_eq!(version, SCHEMA_VERSION);
986 conn.execute("INSERT INTO note (text) VALUES ('kept')", [])
987 .expect("insert");
988 drop(conn);
989 let conn =
990 open(&path(&dir), &key, SCHEMA).expect("reopens without making the schema again");
991 let kept: String = conn
992 .query_row("SELECT text FROM note", [], |r| r.get(0))
993 .expect("row");
994 assert_eq!(kept, "kept");
995 }
996
997 #[test]
998 fn an_unknown_schema_version_is_refused() {
999 let dir = tempfile::tempdir().expect("temp dir");
1000 let key = Key::generate().expect("key");
1001 let conn = open(&path(&dir), &key, SCHEMA).expect("opens");
1002 conn.pragma_update(None, "user_version", SCHEMA_VERSION + 1)
1003 .expect("set version");
1004 drop(conn);
1005 assert!(matches!(
1006 open(&path(&dir), &key, SCHEMA),
1007 Err(CatalogError::UnknownSchema(v)) if v == SCHEMA_VERSION + 1
1008 ));
1009 }
1010
1011 #[test]
1016 fn a_version_1_catalog_is_upgraded_to_the_current_version() {
1017 let dir = tempfile::tempdir().expect("temp dir");
1018 let key = Key::generate().expect("key");
1019 let conn = open(&path(&dir), &key, SCHEMA).expect("opens");
1020 conn.execute("INSERT INTO note (text) VALUES ('kept')", [])
1021 .expect("insert");
1022 conn.pragma_update(None, "user_version", 1)
1023 .expect("set version");
1024 drop(conn);
1025 let conn = open(&path(&dir), &key, "").expect("upgrades");
1026 let version: i64 = conn
1027 .pragma_query_value(None, "user_version", |r| r.get(0))
1028 .expect("version");
1029 assert_eq!(
1030 version, SCHEMA_VERSION,
1031 "the catalog is brought to the current version"
1032 );
1033 assert_eq!(notes(&conn), vec!["kept"]);
1034 }
1035
1036 fn rekeyed(dir: &tempfile::TempDir) -> std::path::PathBuf {
1038 dir.path().join("catalog.sqlite.rekey")
1039 }
1040
1041 fn notes(conn: &Connection) -> Vec<String> {
1042 conn.prepare("SELECT text FROM note ORDER BY rowid")
1043 .expect("prepare")
1044 .query_map([], |r| r.get(0))
1045 .expect("query")
1046 .collect::<Result<_, _>>()
1047 .expect("rows")
1048 }
1049
1050 #[test]
1051 fn a_reencrypted_catalog_opens_under_the_new_key_only_and_keeps_every_row() {
1052 let dir = tempfile::tempdir().expect("temp dir");
1053 let (old, new) = (Key::generate().expect("key"), Key::generate().expect("key"));
1054 let conn = open(&path(&dir), &old, SCHEMA).expect("opens");
1055 for n in 0..300 {
1056 conn.execute("INSERT INTO note (text) VALUES (?1)", [format!("note {n}")])
1057 .expect("insert");
1058 }
1059 drop(conn);
1060 reencrypt(&path(&dir), &old, &new).expect("re-encrypted");
1061 let raw = std::fs::read(path(&dir)).expect("the file");
1062 assert!(
1063 !raw.windows(8).any(|w| w == b"note 299"),
1064 "no row is written in the clear"
1065 );
1066 assert!(matches!(
1067 open(&path(&dir), &old, SCHEMA),
1068 Err(CatalogError::WrongKey)
1069 ));
1070 let conn = open(&path(&dir), &new, SCHEMA).expect("opens under the new key");
1071 let kept = notes(&conn);
1072 assert_eq!(
1073 kept,
1074 (0..300).map(|n| format!("note {n}")).collect::<Vec<_>>(),
1075 "every row is kept, each with its own text, in order"
1076 );
1077 let version: i64 = conn
1078 .pragma_query_value(None, "user_version", |r| r.get(0))
1079 .expect("version");
1080 assert_eq!(version, SCHEMA_VERSION, "the schema version is kept");
1081 let mode: String = conn
1082 .pragma_query_value(None, "journal_mode", |r| r.get(0))
1083 .expect("mode");
1084 assert_eq!(mode, "wal");
1085 drop(conn);
1086 let mut left: Vec<String> = std::fs::read_dir(dir.path())
1087 .expect("list")
1088 .map(|e| e.expect("entry").file_name().to_string_lossy().into_owned())
1089 .collect();
1090 left.sort();
1091 assert_eq!(left, ["catalog.sqlite"], "no temporary file is left");
1092 }
1093
1094 #[test]
1095 fn a_file_left_by_an_interrupted_reencryption_is_replaced() {
1096 let dir = tempfile::tempdir().expect("temp dir");
1097 let (old, new) = (Key::generate().expect("key"), Key::generate().expect("key"));
1098 let conn = open(&path(&dir), &old, SCHEMA).expect("opens");
1099 conn.execute("INSERT INTO note (text) VALUES ('kept')", [])
1100 .expect("insert");
1101 drop(conn);
1102 std::fs::write(rekeyed(&dir), b"half a file").expect("leftover");
1103 reencrypt(&path(&dir), &old, &new).expect("re-encrypted");
1104 let conn = open(&path(&dir), &new, SCHEMA).expect("opens");
1105 assert_eq!(notes(&conn), ["kept"]);
1106 assert!(!rekeyed(&dir).exists());
1107 }
1108
1109 #[test]
1113 fn a_replace_refuses_while_either_wal_holds_frames() {
1114 let dir = tempfile::tempdir().expect("temp dir");
1115 let key = Key::generate().expect("key");
1116 let copy = dir.path().join("catalog.sqlite.rekey");
1117 for busy in [path(&dir), copy.clone()] {
1118 for file in [path(&dir), copy.clone()] {
1119 for leftover in ["", "-wal", "-shm"] {
1120 let _ = std::fs::remove_file(sibling(&file, leftover));
1121 }
1122 drop(open(&file, &key, SCHEMA).expect("made"));
1123 }
1124 let held = open(&busy, &key, SCHEMA).expect("opens");
1125 held.pragma_update(None, "wal_autocheckpoint", 0)
1126 .expect("no checkpoint");
1127 held.execute("INSERT INTO note (text) VALUES ('in the wal')", [])
1128 .expect("insert");
1129 assert!(
1130 std::fs::metadata(sibling(&busy, "-wal")).is_ok_and(|m| m.len() > 0),
1131 "the WAL holds the row"
1132 );
1133 assert!(
1134 matches!(replace(&path(&dir), ©), Err(CatalogError::Io(_))),
1135 "{}",
1136 busy.display()
1137 );
1138 assert!(copy.exists(), "nothing was renamed");
1139 drop(held);
1140 }
1141 }
1142
1143 #[test]
1144 fn reencrypting_under_the_wrong_key_changes_nothing() {
1145 let dir = tempfile::tempdir().expect("temp dir");
1146 let (old, new) = (Key::generate().expect("key"), Key::generate().expect("key"));
1147 drop(open(&path(&dir), &old, SCHEMA).expect("opens"));
1148 let other = Key::generate().expect("key");
1149 assert!(matches!(
1150 reencrypt(&path(&dir), &other, &new),
1151 Err(CatalogError::WrongKey)
1152 ));
1153 assert!(
1154 open(&path(&dir), &old, SCHEMA).is_ok(),
1155 "still under the old key"
1156 );
1157 }
1158
1159 #[test]
1160 fn a_backup_holds_every_committed_row_and_opens_under_the_same_key_only() {
1161 let dir = tempfile::tempdir().expect("temp dir");
1162 let key = Key::generate().expect("key");
1163 let source = open(&path(&dir), &key, SCHEMA).expect("opens");
1164 source
1165 .execute("INSERT INTO note (text) VALUES ('committed')", [])
1166 .expect("insert");
1167 let writer = open(&path(&dir), &key, SCHEMA).expect("opens");
1170 writer.execute_batch("BEGIN IMMEDIATE").expect("begin");
1171 writer
1172 .execute("INSERT INTO note (text) VALUES ('uncommitted')", [])
1173 .expect("insert");
1174 let copy = dir.path().join("copy.sqlite");
1175 backup(&source, ©, &key).expect("backs up");
1176 writer.execute_batch("COMMIT").expect("commit");
1177 assert!(
1178 !sibling(©, "-wal").exists()
1179 || std::fs::metadata(sibling(©, "-wal"))
1180 .expect("wal")
1181 .len()
1182 == 0,
1183 "the copy is whole in its own file"
1184 );
1185 let reopened = open(©, &key, "").expect("the copy opens under the same key");
1186 let notes: Vec<String> = reopened
1187 .prepare("SELECT text FROM note")
1188 .expect("prepare")
1189 .query_map([], |r| r.get(0))
1190 .expect("query")
1191 .collect::<Result<_, _>>()
1192 .expect("rows");
1193 assert_eq!(notes, ["committed"]);
1194 let version: i64 = reopened
1195 .pragma_query_value(None, "user_version", |r| r.get(0))
1196 .expect("version");
1197 assert_eq!(version, SCHEMA_VERSION);
1198 drop(reopened);
1199 let other = Key::generate().expect("key");
1200 assert!(matches!(
1201 open(©, &other, ""),
1202 Err(CatalogError::WrongKey)
1203 ));
1204 }
1205
1206 #[test]
1207 fn a_backup_holds_rows_still_in_the_source_wal_and_no_plain_text() {
1208 let dir = tempfile::tempdir().expect("temp dir");
1209 let key = Key::generate().expect("key");
1210 let source = open(&path(&dir), &key, SCHEMA).expect("opens");
1211 source
1212 .execute("INSERT INTO note (text) VALUES (?1)", [MARKER])
1213 .expect("insert");
1214 assert!(
1215 std::fs::metadata(sibling(&path(&dir), "-wal"))
1216 .expect("wal")
1217 .len()
1218 > 0,
1219 "the row is still in the WAL"
1220 );
1221 let copy = dir.path().join("copy.sqlite");
1222 backup(&source, ©, &key).expect("backs up");
1223 let bytes = std::fs::read(©).expect("read the copy");
1224 assert!(
1225 !bytes.windows(MARKER.len()).any(|w| w == MARKER.as_bytes()),
1226 "the copy is encrypted"
1227 );
1228 let reopened = open(©, &key, "").expect("opens");
1229 let count: i64 = reopened
1230 .query_row("SELECT count(*) FROM note WHERE text = ?1", [MARKER], |r| {
1231 r.get(0)
1232 })
1233 .expect("count");
1234 assert_eq!(count, 1);
1235 }
1236
1237 #[test]
1238 fn a_backup_never_writes_over_a_file() {
1239 let dir = tempfile::tempdir().expect("temp dir");
1240 let key = Key::generate().expect("key");
1241 let source = open(&path(&dir), &key, SCHEMA).expect("opens");
1242 let copy = dir.path().join("copy.sqlite");
1243 std::fs::write(©, b"something else").expect("write");
1244 assert!(matches!(
1245 backup(&source, ©, &key),
1246 Err(CatalogError::Io(_))
1247 ));
1248 assert_eq!(std::fs::read(©).expect("read"), b"something else");
1249 }
1250
1251 #[test]
1252 fn a_wrong_key_does_not_open_the_catalog() {
1253 let dir = tempfile::tempdir().expect("temp dir");
1254 let key = Key::generate().expect("key");
1255 drop(open(&path(&dir), &key, SCHEMA).expect("opens"));
1256 let other = Key::generate().expect("key");
1257 assert!(matches!(
1258 open(&path(&dir), &other, SCHEMA),
1259 Err(CatalogError::WrongKey)
1260 ));
1261 assert!(
1262 open(&path(&dir), &key, SCHEMA).is_ok(),
1263 "the right key still opens it"
1264 );
1265 }
1266
1267 #[test]
1270 fn a_catalog_the_process_may_not_write_is_an_access_error_naming_the_path() {
1271 use std::os::unix::fs::PermissionsExt;
1272 let mode = |p: &Path, m| {
1273 std::fs::set_permissions(p, std::fs::Permissions::from_mode(m)).expect("chmod")
1274 };
1275 let dir = tempfile::tempdir().expect("temp dir");
1276 let key = Key::generate().expect("key");
1277 drop(open(&path(&dir), &key, SCHEMA).expect("opens"));
1278 for (target, read_only) in [(path(&dir), 0o400), (dir.path().to_owned(), 0o500)] {
1279 mode(&target, read_only);
1280 let refused = open(&path(&dir), &key, SCHEMA);
1281 mode(&target, if target.is_dir() { 0o700 } else { 0o600 });
1282 match refused {
1283 Err(CatalogError::Access { path, error }) => {
1284 assert_eq!(path, target);
1285 assert_eq!(error.kind(), std::io::ErrorKind::PermissionDenied);
1286 }
1287 other => panic!("{}: {other:?}", target.display()),
1288 }
1289 }
1290 assert!(
1291 open(&path(&dir), &key, SCHEMA).is_ok(),
1292 "opens once allowed"
1293 );
1294 }
1295
1296 #[test]
1299 #[should_panic(expected = "a whole note row inserts")]
1300 fn the_null_check_needs_a_row_that_inserts() {
1301 let dir = tempfile::tempdir().expect("temp dir");
1302 let key = Key::generate().expect("key");
1303 let conn = open(&path(&dir), &key, SCHEMA).expect("opens");
1304 testing::columns_taking_null(&conn, "note", &[("misspelt", "'a'")]);
1305 }
1306
1307 #[test]
1309 fn no_plain_record_reaches_the_catalog_or_its_wal() {
1310 let dir = tempfile::tempdir().expect("temp dir");
1311 let key = Key::generate().expect("key");
1312 let conn = open(&path(&dir), &key, SCHEMA).expect("opens");
1313 conn.execute("INSERT INTO note (text) VALUES (?1)", [MARKER])
1314 .expect("insert");
1315 let wal = std::fs::metadata(dir.path().join("catalog.sqlite-wal")).expect("a WAL");
1316 assert!(wal.len() > 0, "the commit is in the WAL");
1317 for entry in std::fs::read_dir(dir.path()).expect("list") {
1318 let file = entry.expect("entry").path();
1319 let bytes = std::fs::read(&file).expect("read");
1320 assert!(
1321 !bytes.windows(MARKER.len()).any(|w| w == MARKER.as_bytes()),
1322 "plain record in {}",
1323 file.display()
1324 );
1325 }
1326 drop(conn);
1327 }
1328}