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
193#[derive(Debug)]
195pub enum CatalogError {
196 WrongKey,
198 UnknownSchema(i64),
200 Sqlite(rusqlite::Error),
202 Io(std::io::Error),
204 Access {
208 path: PathBuf,
209 error: std::io::Error,
210 },
211}
212
213impl std::fmt::Display for CatalogError {
214 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
215 match self {
216 CatalogError::WrongKey => {
217 f.write_str("the key is not the one the catalog was made with")
218 }
219 CatalogError::UnknownSchema(version) => {
220 write!(f, "schema version {version} is not one this build knows")
221 }
222 CatalogError::Sqlite(_) => f.write_str("sqlite failed"),
223 CatalogError::Io(_) => {
224 f.write_str("a file around the catalog could not be read, written or renamed")
225 }
226 CatalogError::Access { path, .. } => {
227 write!(f, "this process may not read and write {}", path.display())
228 }
229 }
230 }
231}
232
233impl std::error::Error for CatalogError {
234 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
235 match self {
236 CatalogError::Sqlite(e) => Some(e),
237 CatalogError::Io(e) | CatalogError::Access { error: e, .. } => Some(e),
238 CatalogError::WrongKey | CatalogError::UnknownSchema(_) => None,
239 }
240 }
241}
242
243impl From<rusqlite::Error> for CatalogError {
244 fn from(e: rusqlite::Error) -> CatalogError {
245 CatalogError::Sqlite(e)
246 }
247}
248
249pub fn open(path: &Path, key: &Key, schema: &str) -> Result<Connection, CatalogError> {
252 if let Some(dir) = path.parent() {
256 may_use(dir, libc::W_OK | libc::X_OK)?;
257 }
258 if path.exists() {
259 may_use(path, libc::R_OK | libc::W_OK)?;
260 } else {
261 make_file(path)?;
262 }
263 let conn = Connection::open(path)?;
264 conn.busy_timeout(BUSY_TIMEOUT)?;
265 conn.pragma_update(None, "cipher_log_level", "NONE")?;
268 set_key(&conn, key)?;
269 match conn.query_row("SELECT count(*) FROM sqlite_master", [], |_| Ok(())) {
272 Err(e) if e.sqlite_error_code() == Some(ErrorCode::NotADatabase) => {
273 return Err(CatalogError::WrongKey);
274 }
275 other => other?,
276 }
277 let mode: String = conn.pragma_update_and_check(None, "journal_mode", "WAL", |r| r.get(0))?;
281 debug_assert_eq!(mode, "wal");
282 conn.pragma_update(None, "synchronous", "FULL")?;
283 conn.pragma_update(None, "secure_delete", "ON")?;
284 conn.pragma_update(None, "temp_store", "MEMORY")?;
285 match conn.pragma_query_value(None, "user_version", |r| r.get(0))? {
286 0 => {
287 let tx = conn.unchecked_transaction()?;
288 tx.execute_batch(schema)?;
289 tx.pragma_update(None, "user_version", SCHEMA_VERSION)?;
290 tx.commit()?;
291 }
292 from @ 1..=8 => {
293 let tx = conn.unchecked_transaction()?;
297 let has = |table: &str| -> rusqlite::Result<bool> {
298 tx.query_row(
299 "SELECT count(*) > 0 FROM sqlite_master WHERE type = 'table' AND name = ?1",
300 [table],
301 |r| r.get(0),
302 )
303 };
304 if from < 2 && has("vcon")? {
305 tx.execute_batch(VCON_STORED_AT)?;
306 }
307 if from < 3 && has("tenant")? {
308 tx.execute_batch(TENANT_METADATA)?;
309 }
310 if from < 4 && has("version")? {
311 tx.execute_batch(VERSION_PLACES)?;
312 tx.execute_batch(PACK_TABLES)?;
313 }
314 if from < 5 && has("tenant")? {
315 tx.execute_batch(USER_TABLES)?;
316 }
317 if from < 5 && has("audit")? {
318 tx.execute_batch(&audit_without_zero())?;
319 }
320 if from < 6 && has("tenant")? {
321 tx.execute_batch(TENANT_ROLE_CAP)?;
322 }
323 if from < 7 && has("tenant")? {
324 tx.execute_batch(TENANT_SETTINGS)?;
325 }
326 if from < 8 && has("tenant")? {
327 tx.execute_batch(SESSIONS)?;
328 }
329 if from < 9 && has("api_key")? {
330 tx.execute_batch(KEY_LIFE)?;
331 }
332 tx.pragma_update(None, "user_version", SCHEMA_VERSION)?;
333 tx.commit()?;
334 }
335 SCHEMA_VERSION => {}
336 other => return Err(CatalogError::UnknownSchema(other)),
337 }
338 Ok(conn)
339}
340
341pub(crate) fn may_use(path: &Path, how: c_int) -> Result<(), CatalogError> {
344 let denied = |error| CatalogError::Access {
345 path: path.to_owned(),
346 error,
347 };
348 let text = std::ffi::CString::new(path.as_os_str().as_encoded_bytes())
349 .map_err(|_| denied(std::io::ErrorKind::InvalidInput.into()))?;
350 if unsafe { libc::faccessat(libc::AT_FDCWD, text.as_ptr(), how, libc::AT_EACCESS) } != 0 {
353 return Err(denied(std::io::Error::last_os_error()));
354 }
355 Ok(())
356}
357
358pub fn backup(source: &Connection, to: &Path, key: &Key) -> Result<(), CatalogError> {
366 let io = CatalogError::Io;
367 make_file(to)?;
368 {
369 let mut copy = Connection::open(to)?;
370 copy.pragma_update(None, "cipher_log_level", "NONE")?;
371 set_key(©, key)?;
372 let backup = rusqlite::backup::Backup::new(source, &mut copy)?;
373 match backup.step(-1)? {
375 rusqlite::backup::StepResult::Done => {}
376 _ => {
377 return Err(io(std::io::Error::other(
378 "the catalog was busy and could not be copied in one step",
379 )));
380 }
381 }
382 }
383 std::fs::File::open(to)
384 .and_then(|f| f.sync_all())
385 .map_err(io)?;
386 let dir = to.parent().unwrap_or(Path::new("."));
387 std::fs::File::open(dir)
388 .and_then(|f| f.sync_all())
389 .map_err(io)?;
390 Ok(())
391}
392
393pub fn reencrypt(path: &Path, old: &Key, new: &Key) -> Result<(), CatalogError> {
400 let copy = copy_under(path, old, new)?;
401 replace(path, ©)
402}
403
404pub fn copy_under(path: &Path, old: &Key, new: &Key) -> Result<PathBuf, CatalogError> {
409 let target = sibling(path, ".rekey");
410 for stale in [
411 target.clone(),
412 sibling(&target, "-wal"),
413 sibling(&target, "-shm"),
414 ] {
415 remove_if_there(&stale)?;
416 }
417 make_file(&target)?;
418 let conn = open(path, old, "")?;
419 let version: i64 = conn.pragma_query_value(None, "user_version", |r| r.get(0))?;
420 let target_text = target
421 .to_str()
422 .ok_or_else(|| CatalogError::Io(std::io::Error::other("the catalog path is not UTF-8")))?;
423 conn.execute("ATTACH DATABASE ?1 AS rekeyed", [target_text])?;
424 set_key_of(&conn, c"rekeyed", new)?;
425 conn.query_row("SELECT sqlcipher_export('rekeyed')", [], |_| Ok(()))?;
426 conn.execute_batch(&format!("PRAGMA rekeyed.user_version = {version}"))?;
429 conn.execute("DETACH DATABASE rekeyed", [])?;
430 Ok(target)
431}
432
433pub fn replace(path: &Path, copy: &Path) -> Result<(), CatalogError> {
438 for file in [path, copy] {
439 let wal = sibling(file, "-wal");
440 if std::fs::metadata(&wal).is_ok_and(|m| m.len() > 0) {
441 return Err(CatalogError::Io(std::io::Error::other(
442 "a catalog's WAL was not emptied",
443 )));
444 }
445 remove_if_there(&wal)?;
446 remove_if_there(&sibling(file, "-shm"))?;
447 }
448 let io = CatalogError::Io;
449 std::fs::File::open(copy)
450 .and_then(|f| f.sync_all())
451 .map_err(io)?;
452 std::fs::rename(copy, path).map_err(io)?;
453 let dir = path.parent().unwrap_or(Path::new("."));
454 std::fs::File::open(dir)
455 .and_then(|f| f.sync_all())
456 .map_err(io)?;
457 Ok(())
458}
459
460fn make_file(path: &Path) -> Result<(), CatalogError> {
464 use std::os::unix::fs::OpenOptionsExt;
465 std::fs::OpenOptions::new()
466 .write(true)
467 .create_new(true)
468 .mode(crate::fs::FILE_MODE)
469 .open(path)
470 .map(drop)
471 .map_err(CatalogError::Io)
472}
473
474fn remove_if_there(file: &Path) -> Result<(), CatalogError> {
475 match std::fs::remove_file(file) {
476 Err(e) if e.kind() != std::io::ErrorKind::NotFound => Err(CatalogError::Io(e)),
477 _ => Ok(()),
478 }
479}
480
481fn sibling(path: &Path, suffix: &str) -> PathBuf {
483 let mut name = path.as_os_str().to_owned();
484 name.push(suffix);
485 PathBuf::from(name)
486}
487
488fn set_key_of(conn: &Connection, schema: &std::ffi::CStr, key: &Key) -> Result<(), CatalogError> {
490 let literal = key.sqlcipher_raw();
491 let len = c_int::try_from(literal.len()).expect("a 67-byte literal");
492 let rc = unsafe {
496 rusqlite::ffi::sqlite3_key_v2(conn.handle(), schema.as_ptr(), literal.as_ptr().cast(), len)
497 };
498 if rc != rusqlite::ffi::SQLITE_OK {
499 return Err(rusqlite::Error::SqliteFailure(rusqlite::ffi::Error::new(rc), None).into());
500 }
501 Ok(())
502}
503
504fn set_key(conn: &Connection, key: &Key) -> Result<(), CatalogError> {
508 let literal = key.sqlcipher_raw();
509 let len = c_int::try_from(literal.len()).expect("a 67-byte literal");
510 let rc = unsafe { rusqlite::ffi::sqlite3_key(conn.handle(), literal.as_ptr().cast(), len) };
513 if rc != rusqlite::ffi::SQLITE_OK {
516 return Err(rusqlite::Error::SqliteFailure(rusqlite::ffi::Error::new(rc), None).into());
517 }
518 Ok(())
519}
520
521#[cfg(test)]
523mod v5_tests;
524
525#[cfg(test)]
526mod v6_tests;
527
528#[cfg(test)]
529mod v7_tests;
530
531#[cfg(test)]
532mod v8_tests;
533
534#[cfg(test)]
535mod v9_tests;
536
537#[cfg(test)]
538pub(crate) mod testing {
539 use rusqlite::Connection;
540
541 pub(crate) fn columns_taking_null(
545 conn: &Connection,
546 table: &str,
547 row: &[(&str, &str)],
548 ) -> Vec<String> {
549 let insert = |empty: Option<&str>| {
550 let columns: Vec<&str> = row.iter().map(|(c, _)| *c).collect();
551 let values: Vec<&str> = row
552 .iter()
553 .map(|(c, v)| if Some(*c) == empty { "NULL" } else { *v })
554 .collect();
555 let sql = format!(
556 "INSERT INTO {table} ({}) VALUES ({})",
557 columns.join(", "),
558 values.join(", ")
559 );
560 let tx = conn.unchecked_transaction().expect("begin");
561 let taken = tx.execute(&sql, []).is_ok();
562 drop(tx);
563 taken
564 };
565 assert!(insert(None), "a whole {table} row inserts");
566 row.iter()
567 .filter(|(column, _)| insert(Some(column)))
568 .map(|(column, _)| format!("{table}.{column}"))
569 .collect()
570 }
571}
572
573#[cfg(test)]
574pub(crate) mod tests {
575 use super::*;
576
577 const SCHEMA: &str = "CREATE TABLE note (text TEXT NOT NULL);";
578 const MARKER: &str = "plain-record-marker-5f3c9a";
579
580 fn path(dir: &tempfile::TempDir) -> std::path::PathBuf {
581 dir.path().join("catalog.sqlite")
582 }
583
584 pub(crate) fn cipher_setting(conn: &Connection, name: &str) -> String {
586 conn.pragma_query_value(None, name, |r| r.get(0))
587 .expect(name)
588 }
589
590 fn linked_sqlite(conn: &Connection) -> (u32, u32, u32) {
593 let text: String = conn
594 .query_row("SELECT sqlite_version()", [], |r| r.get(0))
595 .expect("the version");
596 let mut parts = text.split('.').map(|part| part.parse().expect("a number"));
597 let mut next = || parts.next().expect("three parts");
598 (next(), next(), next())
599 }
600
601 #[test]
602 fn the_linked_sqlite_is_not_one_cve_2026_119375_affects() {
603 let dir = tempfile::tempdir().expect("temp dir");
609 let key = Key::generate().expect("key");
610 let conn = open(&path(&dir), &key, SCHEMA).expect("opens");
611 let linked = linked_sqlite(&conn);
612 assert!(linked >= (3, 54, 0), "SQLite {linked:?} is before 3.54.0");
613 assert_eq!(
614 rusqlite::version_number(),
615 i32::try_from(linked.0 * 1_000_000 + linked.1 * 1_000 + linked.2).expect("fits"),
616 "the library rusqlite links is the one the catalog runs on"
617 );
618 let cipher = cipher_setting(&conn, "cipher_version");
619 assert!(
620 cipher.starts_with("4."),
621 "SQLCipher 4, whose file format release 0.4.3 wrote: {cipher}"
622 );
623 }
624
625 #[test]
626 fn a_catalog_runs_with_the_required_settings() {
627 let dir = tempfile::tempdir().expect("temp dir");
628 let key = Key::generate().expect("key");
629 let conn = open(&path(&dir), &key, SCHEMA).expect("opens");
630 let text = |p: &str| -> String { conn.pragma_query_value(None, p, |r| r.get(0)).expect(p) };
631 let number = |p: &str| -> i64 { conn.pragma_query_value(None, p, |r| r.get(0)).expect(p) };
632 assert_eq!(text("journal_mode"), "wal");
633 assert_eq!(number("synchronous"), 2, "FULL");
634 assert_eq!(number("secure_delete"), 1);
635 assert_eq!(number("temp_store"), 2, "MEMORY");
636 assert_eq!(number("busy_timeout"), 5000, "milliseconds");
637 assert_eq!(cipher_setting(&conn, "cipher_provider"), "openssl");
638 assert_eq!(
639 cipher_setting(&conn, "cipher_log_level"),
640 "NONE",
641 "SQLCipher writes no log of its own"
642 );
643 }
644
645 #[test]
651 fn sqlcipher_settings_read_the_same_through_the_pragma_helpers() {
652 let dir = tempfile::tempdir().expect("temp dir");
653 let key = Key::generate().expect("key");
654 let conn = open(&path(&dir), &key, SCHEMA).expect("opens");
655 let names = ["cipher_log_level", "cipher_provider", "cipher_page_size"];
656 let plain: Vec<String> = names
657 .iter()
658 .map(|n| {
659 conn.query_row(&format!("PRAGMA {n}"), [], |r| r.get(0))
660 .unwrap_or_else(|e| panic!("{n} as plain SQL: {e}"))
661 })
662 .collect();
663
664 let helpers = Connection::open(path(&dir)).expect("opens again");
665 helpers
668 .pragma_update(None, "cipher_log_level", "NONE")
669 .expect("cipher_log_level through pragma_update");
670 set_key(&helpers, &key).expect("keyed");
671 let notes: i64 = helpers
672 .query_row("SELECT count(*) FROM note", [], |r| r.get(0))
673 .expect("the key opens the same catalog");
674 assert_eq!(notes, 0);
675 let read: Vec<String> = names
676 .iter()
677 .map(|n| {
678 helpers
679 .pragma_query_value(None, n, |r| r.get(0))
680 .unwrap_or_else(|e| panic!("{n} through pragma_query_value: {e}"))
681 })
682 .collect();
683 assert_eq!(read, plain);
684 assert_eq!(plain[0], "NONE");
685 let ours: Vec<String> = names.iter().map(|n| cipher_setting(&conn, n)).collect();
686 assert_eq!(ours, plain, "cipher_setting reads what plain SQL reads");
687 }
688
689 #[test]
696 fn rusqlite_takes_sqlcipher_names_in_its_pragma_helpers() {
697 let conn = Connection::open_in_memory().expect("opens");
698 let taken = conn.pragma_update(None, "cipher_log_level", "NONE");
699 assert!(
700 taken.is_ok(),
701 "this rusqlite refuses SQLCipher's pragma names ({taken:?}): catalog::open and \
702 catalog::backup set cipher_log_level through pragma_update"
703 );
704 let level: String = conn
705 .pragma_query_value(None, "cipher_log_level", |r| r.get(0))
706 .expect("cipher_log_level through pragma_query_value");
707 assert_eq!(level, "NONE", "and reads back what was set");
708 }
709
710 mod sources {
715 use std::path::PathBuf;
716
717 fn read(relative: &str) -> String {
718 let path = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join(relative);
719 std::fs::read_to_string(&path).unwrap_or_else(|e| panic!("{}: {e}", path.display()))
720 }
721
722 fn table(text: &str) -> toml::Table {
723 text.parse().expect("toml")
724 }
725
726 fn git_dependencies(manifest: &toml::Table) -> Vec<String> {
729 ["dependencies", "dev-dependencies", "build-dependencies"]
730 .iter()
731 .filter_map(|kind| Some((kind, manifest.get(*kind)?.as_table()?)))
732 .flat_map(|(kind, deps)| {
733 deps.iter()
734 .filter(|(_, spec)| spec.get("git").is_some())
735 .map(move |(name, _)| format!("{kind}.{name}"))
736 })
737 .collect()
738 }
739
740 #[test]
741 fn the_git_dependency_reader_finds_one_in_any_table() {
742 let manifest = table(
743 "[dependencies]\nplain = \"1\"\n\
744 [dev-dependencies]\nforked = { package = \"plain\", git = \"https://example.com/forked\" }\n\
745 [build-dependencies]\nother = { git = \"https://example.com/other\", rev = \"abc\" }\n",
746 );
747 assert_eq!(
748 git_dependencies(&manifest),
749 ["dev-dependencies.forked", "build-dependencies.other"],
750 "each git dependency, with its table"
751 );
752 assert!(
753 git_dependencies(&table("[dependencies]\nplain = \"1\"\n")).is_empty(),
754 "a crates.io dependency is not one"
755 );
756 assert!(
757 git_dependencies(&table("[package]\nname = \"none\"\n")).is_empty(),
758 "a manifest with no dependency table has none"
759 );
760 }
761
762 #[test]
763 fn no_dependency_comes_from_a_git_repository() {
764 let manifest = table(&read("Cargo.toml"));
765 assert_eq!(
766 git_dependencies(&manifest),
767 [] as [&str; 0],
768 "vcon-server's Cargo.toml"
769 );
770 let server = &manifest["dependencies"]["rusqlite"];
771 assert!(
772 server.get("version").is_some()
773 && server.get("git").is_none()
774 && server.get("path").is_none(),
775 "the server's rusqlite comes from crates.io"
776 );
777 assert!(
778 manifest["dev-dependencies"].get("rusqlite_fork").is_none(),
779 "the fork is gone"
780 );
781 }
782
783 #[test]
784 fn the_workspace_patches_nothing() {
785 let workspace = table(&read("../../Cargo.toml"));
786 assert!(
787 workspace.get("patch").is_none(),
788 "no [patch] table: {:?}",
789 workspace.get("patch")
790 );
791 }
792
793 #[test]
794 fn no_lockfile_names_a_git_source() {
795 for lockfile in ["../../Cargo.lock", "../../fuzz/Cargo.lock"] {
796 let lock = read(lockfile);
797 let git: Vec<&str> = lock
798 .lines()
799 .filter(|l| l.starts_with("source = \"git+"))
800 .collect();
801 assert_eq!(git, [] as [&str; 0], "{lockfile}");
802 }
803 }
804
805 #[test]
806 fn the_pages_name_no_fork() {
807 let development = read("../../website/content/docs/development.md");
808 assert!(
809 !development.contains("\n## Test dependency from a fork\n"),
810 "the Development page's section on the fork is gone"
811 );
812 let install = read("../../website/content/docs/install.md");
813 let build = install
814 .split("\n## ")
815 .find(|s| s.starts_with("Build from source\n"))
816 .expect("a Build from source section");
817 assert!(
818 build.contains("mkdir -p .cargo && cargo vendor >> .cargo/config.toml\n"),
819 "the vendoring command"
820 );
821 assert!(build.contains("cargo build --release --offline\n"));
822 for page in [&development, &install] {
823 assert!(!page.contains("NormB/rusqlite"), "no page names the fork");
824 assert!(!page.contains("rusqlite fork"), "no page speaks of a fork");
825 }
826 let release = install
827 .split("\n## ")
828 .find(|s| s.starts_with("Download a release\n"))
829 .expect("a release section");
830 assert!(
831 release.contains("crates.io"),
832 "says where the release's rusqlite comes from"
833 );
834 }
835 }
836
837 #[test]
838 fn the_schema_is_made_once_at_the_current_version() {
839 let dir = tempfile::tempdir().expect("temp dir");
840 let key = Key::generate().expect("key");
841 let conn = open(&path(&dir), &key, SCHEMA).expect("opens");
842 let version: i64 = conn
843 .pragma_query_value(None, "user_version", |r| r.get(0))
844 .expect("version");
845 assert_eq!(version, SCHEMA_VERSION);
846 conn.execute("INSERT INTO note (text) VALUES ('kept')", [])
847 .expect("insert");
848 drop(conn);
849 let conn =
850 open(&path(&dir), &key, SCHEMA).expect("reopens without making the schema again");
851 let kept: String = conn
852 .query_row("SELECT text FROM note", [], |r| r.get(0))
853 .expect("row");
854 assert_eq!(kept, "kept");
855 }
856
857 #[test]
858 fn an_unknown_schema_version_is_refused() {
859 let dir = tempfile::tempdir().expect("temp dir");
860 let key = Key::generate().expect("key");
861 let conn = open(&path(&dir), &key, SCHEMA).expect("opens");
862 conn.pragma_update(None, "user_version", SCHEMA_VERSION + 1)
863 .expect("set version");
864 drop(conn);
865 assert!(matches!(
866 open(&path(&dir), &key, SCHEMA),
867 Err(CatalogError::UnknownSchema(v)) if v == SCHEMA_VERSION + 1
868 ));
869 }
870
871 #[test]
876 fn a_version_1_catalog_is_upgraded_to_the_current_version() {
877 let dir = tempfile::tempdir().expect("temp dir");
878 let key = Key::generate().expect("key");
879 let conn = open(&path(&dir), &key, SCHEMA).expect("opens");
880 conn.execute("INSERT INTO note (text) VALUES ('kept')", [])
881 .expect("insert");
882 conn.pragma_update(None, "user_version", 1)
883 .expect("set version");
884 drop(conn);
885 let conn = open(&path(&dir), &key, "").expect("upgrades");
886 let version: i64 = conn
887 .pragma_query_value(None, "user_version", |r| r.get(0))
888 .expect("version");
889 assert_eq!(
890 version, SCHEMA_VERSION,
891 "the catalog is brought to the current version"
892 );
893 assert_eq!(notes(&conn), vec!["kept"]);
894 }
895
896 fn rekeyed(dir: &tempfile::TempDir) -> std::path::PathBuf {
898 dir.path().join("catalog.sqlite.rekey")
899 }
900
901 fn notes(conn: &Connection) -> Vec<String> {
902 conn.prepare("SELECT text FROM note ORDER BY rowid")
903 .expect("prepare")
904 .query_map([], |r| r.get(0))
905 .expect("query")
906 .collect::<Result<_, _>>()
907 .expect("rows")
908 }
909
910 #[test]
911 fn a_reencrypted_catalog_opens_under_the_new_key_only_and_keeps_every_row() {
912 let dir = tempfile::tempdir().expect("temp dir");
913 let (old, new) = (Key::generate().expect("key"), Key::generate().expect("key"));
914 let conn = open(&path(&dir), &old, SCHEMA).expect("opens");
915 for n in 0..300 {
916 conn.execute("INSERT INTO note (text) VALUES (?1)", [format!("note {n}")])
917 .expect("insert");
918 }
919 drop(conn);
920 reencrypt(&path(&dir), &old, &new).expect("re-encrypted");
921 let raw = std::fs::read(path(&dir)).expect("the file");
922 assert!(
923 !raw.windows(8).any(|w| w == b"note 299"),
924 "no row is written in the clear"
925 );
926 assert!(matches!(
927 open(&path(&dir), &old, SCHEMA),
928 Err(CatalogError::WrongKey)
929 ));
930 let conn = open(&path(&dir), &new, SCHEMA).expect("opens under the new key");
931 let kept = notes(&conn);
932 assert_eq!(
933 kept,
934 (0..300).map(|n| format!("note {n}")).collect::<Vec<_>>(),
935 "every row is kept, each with its own text, in order"
936 );
937 let version: i64 = conn
938 .pragma_query_value(None, "user_version", |r| r.get(0))
939 .expect("version");
940 assert_eq!(version, SCHEMA_VERSION, "the schema version is kept");
941 let mode: String = conn
942 .pragma_query_value(None, "journal_mode", |r| r.get(0))
943 .expect("mode");
944 assert_eq!(mode, "wal");
945 drop(conn);
946 let mut left: Vec<String> = std::fs::read_dir(dir.path())
947 .expect("list")
948 .map(|e| e.expect("entry").file_name().to_string_lossy().into_owned())
949 .collect();
950 left.sort();
951 assert_eq!(left, ["catalog.sqlite"], "no temporary file is left");
952 }
953
954 #[test]
955 fn a_file_left_by_an_interrupted_reencryption_is_replaced() {
956 let dir = tempfile::tempdir().expect("temp dir");
957 let (old, new) = (Key::generate().expect("key"), Key::generate().expect("key"));
958 let conn = open(&path(&dir), &old, SCHEMA).expect("opens");
959 conn.execute("INSERT INTO note (text) VALUES ('kept')", [])
960 .expect("insert");
961 drop(conn);
962 std::fs::write(rekeyed(&dir), b"half a file").expect("leftover");
963 reencrypt(&path(&dir), &old, &new).expect("re-encrypted");
964 let conn = open(&path(&dir), &new, SCHEMA).expect("opens");
965 assert_eq!(notes(&conn), ["kept"]);
966 assert!(!rekeyed(&dir).exists());
967 }
968
969 #[test]
973 fn a_replace_refuses_while_either_wal_holds_frames() {
974 let dir = tempfile::tempdir().expect("temp dir");
975 let key = Key::generate().expect("key");
976 let copy = dir.path().join("catalog.sqlite.rekey");
977 for busy in [path(&dir), copy.clone()] {
978 for file in [path(&dir), copy.clone()] {
979 for leftover in ["", "-wal", "-shm"] {
980 let _ = std::fs::remove_file(sibling(&file, leftover));
981 }
982 drop(open(&file, &key, SCHEMA).expect("made"));
983 }
984 let held = open(&busy, &key, SCHEMA).expect("opens");
985 held.pragma_update(None, "wal_autocheckpoint", 0)
986 .expect("no checkpoint");
987 held.execute("INSERT INTO note (text) VALUES ('in the wal')", [])
988 .expect("insert");
989 assert!(
990 std::fs::metadata(sibling(&busy, "-wal")).is_ok_and(|m| m.len() > 0),
991 "the WAL holds the row"
992 );
993 assert!(
994 matches!(replace(&path(&dir), ©), Err(CatalogError::Io(_))),
995 "{}",
996 busy.display()
997 );
998 assert!(copy.exists(), "nothing was renamed");
999 drop(held);
1000 }
1001 }
1002
1003 #[test]
1004 fn reencrypting_under_the_wrong_key_changes_nothing() {
1005 let dir = tempfile::tempdir().expect("temp dir");
1006 let (old, new) = (Key::generate().expect("key"), Key::generate().expect("key"));
1007 drop(open(&path(&dir), &old, SCHEMA).expect("opens"));
1008 let other = Key::generate().expect("key");
1009 assert!(matches!(
1010 reencrypt(&path(&dir), &other, &new),
1011 Err(CatalogError::WrongKey)
1012 ));
1013 assert!(
1014 open(&path(&dir), &old, SCHEMA).is_ok(),
1015 "still under the old key"
1016 );
1017 }
1018
1019 #[test]
1020 fn a_backup_holds_every_committed_row_and_opens_under_the_same_key_only() {
1021 let dir = tempfile::tempdir().expect("temp dir");
1022 let key = Key::generate().expect("key");
1023 let source = open(&path(&dir), &key, SCHEMA).expect("opens");
1024 source
1025 .execute("INSERT INTO note (text) VALUES ('committed')", [])
1026 .expect("insert");
1027 let writer = open(&path(&dir), &key, SCHEMA).expect("opens");
1030 writer.execute_batch("BEGIN IMMEDIATE").expect("begin");
1031 writer
1032 .execute("INSERT INTO note (text) VALUES ('uncommitted')", [])
1033 .expect("insert");
1034 let copy = dir.path().join("copy.sqlite");
1035 backup(&source, ©, &key).expect("backs up");
1036 writer.execute_batch("COMMIT").expect("commit");
1037 assert!(
1038 !sibling(©, "-wal").exists()
1039 || std::fs::metadata(sibling(©, "-wal"))
1040 .expect("wal")
1041 .len()
1042 == 0,
1043 "the copy is whole in its own file"
1044 );
1045 let reopened = open(©, &key, "").expect("the copy opens under the same key");
1046 let notes: Vec<String> = reopened
1047 .prepare("SELECT text FROM note")
1048 .expect("prepare")
1049 .query_map([], |r| r.get(0))
1050 .expect("query")
1051 .collect::<Result<_, _>>()
1052 .expect("rows");
1053 assert_eq!(notes, ["committed"]);
1054 let version: i64 = reopened
1055 .pragma_query_value(None, "user_version", |r| r.get(0))
1056 .expect("version");
1057 assert_eq!(version, SCHEMA_VERSION);
1058 drop(reopened);
1059 let other = Key::generate().expect("key");
1060 assert!(matches!(
1061 open(©, &other, ""),
1062 Err(CatalogError::WrongKey)
1063 ));
1064 }
1065
1066 #[test]
1067 fn a_backup_holds_rows_still_in_the_source_wal_and_no_plain_text() {
1068 let dir = tempfile::tempdir().expect("temp dir");
1069 let key = Key::generate().expect("key");
1070 let source = open(&path(&dir), &key, SCHEMA).expect("opens");
1071 source
1072 .execute("INSERT INTO note (text) VALUES (?1)", [MARKER])
1073 .expect("insert");
1074 assert!(
1075 std::fs::metadata(sibling(&path(&dir), "-wal"))
1076 .expect("wal")
1077 .len()
1078 > 0,
1079 "the row is still in the WAL"
1080 );
1081 let copy = dir.path().join("copy.sqlite");
1082 backup(&source, ©, &key).expect("backs up");
1083 let bytes = std::fs::read(©).expect("read the copy");
1084 assert!(
1085 !bytes.windows(MARKER.len()).any(|w| w == MARKER.as_bytes()),
1086 "the copy is encrypted"
1087 );
1088 let reopened = open(©, &key, "").expect("opens");
1089 let count: i64 = reopened
1090 .query_row("SELECT count(*) FROM note WHERE text = ?1", [MARKER], |r| {
1091 r.get(0)
1092 })
1093 .expect("count");
1094 assert_eq!(count, 1);
1095 }
1096
1097 #[test]
1098 fn a_backup_never_writes_over_a_file() {
1099 let dir = tempfile::tempdir().expect("temp dir");
1100 let key = Key::generate().expect("key");
1101 let source = open(&path(&dir), &key, SCHEMA).expect("opens");
1102 let copy = dir.path().join("copy.sqlite");
1103 std::fs::write(©, b"something else").expect("write");
1104 assert!(matches!(
1105 backup(&source, ©, &key),
1106 Err(CatalogError::Io(_))
1107 ));
1108 assert_eq!(std::fs::read(©).expect("read"), b"something else");
1109 }
1110
1111 #[test]
1112 fn a_wrong_key_does_not_open_the_catalog() {
1113 let dir = tempfile::tempdir().expect("temp dir");
1114 let key = Key::generate().expect("key");
1115 drop(open(&path(&dir), &key, SCHEMA).expect("opens"));
1116 let other = Key::generate().expect("key");
1117 assert!(matches!(
1118 open(&path(&dir), &other, SCHEMA),
1119 Err(CatalogError::WrongKey)
1120 ));
1121 assert!(
1122 open(&path(&dir), &key, SCHEMA).is_ok(),
1123 "the right key still opens it"
1124 );
1125 }
1126
1127 #[test]
1130 fn a_catalog_the_process_may_not_write_is_an_access_error_naming_the_path() {
1131 use std::os::unix::fs::PermissionsExt;
1132 let mode = |p: &Path, m| {
1133 std::fs::set_permissions(p, std::fs::Permissions::from_mode(m)).expect("chmod")
1134 };
1135 let dir = tempfile::tempdir().expect("temp dir");
1136 let key = Key::generate().expect("key");
1137 drop(open(&path(&dir), &key, SCHEMA).expect("opens"));
1138 for (target, read_only) in [(path(&dir), 0o400), (dir.path().to_owned(), 0o500)] {
1139 mode(&target, read_only);
1140 let refused = open(&path(&dir), &key, SCHEMA);
1141 mode(&target, if target.is_dir() { 0o700 } else { 0o600 });
1142 match refused {
1143 Err(CatalogError::Access { path, error }) => {
1144 assert_eq!(path, target);
1145 assert_eq!(error.kind(), std::io::ErrorKind::PermissionDenied);
1146 }
1147 other => panic!("{}: {other:?}", target.display()),
1148 }
1149 }
1150 assert!(
1151 open(&path(&dir), &key, SCHEMA).is_ok(),
1152 "opens once allowed"
1153 );
1154 }
1155
1156 #[test]
1159 #[should_panic(expected = "a whole note row inserts")]
1160 fn the_null_check_needs_a_row_that_inserts() {
1161 let dir = tempfile::tempdir().expect("temp dir");
1162 let key = Key::generate().expect("key");
1163 let conn = open(&path(&dir), &key, SCHEMA).expect("opens");
1164 testing::columns_taking_null(&conn, "note", &[("misspelt", "'a'")]);
1165 }
1166
1167 #[test]
1169 fn no_plain_record_reaches_the_catalog_or_its_wal() {
1170 let dir = tempfile::tempdir().expect("temp dir");
1171 let key = Key::generate().expect("key");
1172 let conn = open(&path(&dir), &key, SCHEMA).expect("opens");
1173 conn.execute("INSERT INTO note (text) VALUES (?1)", [MARKER])
1174 .expect("insert");
1175 let wal = std::fs::metadata(dir.path().join("catalog.sqlite-wal")).expect("a WAL");
1176 assert!(wal.len() > 0, "the commit is in the WAL");
1177 for entry in std::fs::read_dir(dir.path()).expect("list") {
1178 let file = entry.expect("entry").path();
1179 let bytes = std::fs::read(&file).expect("read");
1180 assert!(
1181 !bytes.windows(MARKER.len()).any(|w| w == MARKER.as_bytes()),
1182 "plain record in {}",
1183 file.display()
1184 );
1185 }
1186 drop(conn);
1187 }
1188}