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