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