Skip to main content

vcon_server/
catalog.rs

1//! An SQLite catalog, encrypted with SQLCipher under its catalog key.
2
3use std::ffi::c_int;
4use std::path::{Path, PathBuf};
5use std::time::Duration;
6
7use rusqlite::{Connection, ErrorCode};
8
9use crate::envelope::Key;
10
11/// The schema version this build makes and reads. Version 2 added the
12/// time each uuid was first stored to a tenant catalog's vcon table;
13/// version 3 added each tenant's metadata level to server.sqlite; version
14/// 4 added the places of packed versions and the pack tables to a tenant
15/// catalog.
16pub const SCHEMA_VERSION: i64 = 4;
17
18/// Brings a version-1 tenant catalog to version 2: each uuid's first store
19/// time, taken from its earliest kept version (the closest record left of
20/// it), and the index the list reads it by. The column is declared as a
21/// new catalog declares it.
22const VCON_STORED_AT: &str = "
23ALTER TABLE vcon ADD COLUMN stored_at INTEGER NOT NULL DEFAULT 0;
24UPDATE vcon SET stored_at =
25    coalesce((SELECT min(stored_at) FROM version WHERE version.uuid = vcon.uuid), 0);
26CREATE INDEX vcon_listed ON vcon (stored_at, uuid);
27";
28
29/// Brings server.sqlite from version 2 to 3: each tenant's metadata level,
30/// NULL (`none`) for every tenant there is.
31const TENANT_METADATA: &str = "ALTER TABLE tenant ADD COLUMN metadata TEXT;";
32
33/// The tables of a tenant catalog's pack files, as a new catalog and an
34/// upgraded one both make them. A pack file's row records its UTC store
35/// date (its name holds it), its rows and the rows still kept, its length,
36/// when it was made and when the catalog stopped naming it. A purge that
37/// must still rewrite a file lists it in purge_pending, and each change of
38/// which files hold which rows takes the next manifest number, which
39/// AUTOINCREMENT never gives twice, even after a row is removed: a manifest
40/// is written once under its number's name.
41pub(crate) const PACK_TABLES: &str = "
42CREATE INDEX version_place ON version (place_file);
43CREATE TABLE parquet_file (
44    file_id BLOB PRIMARY KEY NOT NULL,
45    date TEXT NOT NULL,
46    rows INTEGER NOT NULL,
47    live_rows INTEGER NOT NULL,
48    bytes INTEGER NOT NULL,
49    created_at INTEGER NOT NULL,
50    unnamed_at INTEGER
51);
52CREATE TABLE purge_pending (
53    file_id BLOB PRIMARY KEY NOT NULL
54);
55CREATE TABLE manifest (
56    seq INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
57    published_at INTEGER
58);
59";
60
61/// Brings a version-3 tenant catalog to version 4: every version is in its
62/// object (no place), and no pack file is recorded. The columns are
63/// declared as a new catalog's version table declares them, last.
64const VERSION_PLACES: &str = "
65ALTER TABLE version ADD COLUMN place_file BLOB;
66ALTER TABLE version ADD COLUMN place_group INTEGER;
67ALTER TABLE version ADD COLUMN place_row INTEGER;
68";
69
70/// How long a statement waits for another connection's lock before it
71/// fails busy. It is rusqlite's own default, stated so it is chosen, not
72/// inherited; a caller that must not wait inside SQLite sets zero for the
73/// call and restores this.
74pub const BUSY_TIMEOUT: Duration = Duration::from_secs(5);
75
76/// Why a catalog did not open.
77#[derive(Debug)]
78pub enum CatalogError {
79    /// The key is not the one the catalog was made with.
80    WrongKey,
81    /// The catalog's schema version is not one this build knows.
82    UnknownSchema(i64),
83    /// SQLite failed.
84    Sqlite(rusqlite::Error),
85    /// A file around the catalog could not be read, written or renamed.
86    Io(std::io::Error),
87    /// This process may not read and write `path`, the catalog or the
88    /// directory that holds it (where SQLite makes its `-wal` and `-shm`
89    /// files), such as when another user owns it.
90    Access {
91        path: PathBuf,
92        error: std::io::Error,
93    },
94}
95
96impl std::fmt::Display for CatalogError {
97    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
98        match self {
99            CatalogError::WrongKey => {
100                f.write_str("the key is not the one the catalog was made with")
101            }
102            CatalogError::UnknownSchema(version) => {
103                write!(f, "schema version {version} is not one this build knows")
104            }
105            CatalogError::Sqlite(_) => f.write_str("sqlite failed"),
106            CatalogError::Io(_) => {
107                f.write_str("a file around the catalog could not be read, written or renamed")
108            }
109            CatalogError::Access { path, .. } => {
110                write!(f, "this process may not read and write {}", path.display())
111            }
112        }
113    }
114}
115
116impl std::error::Error for CatalogError {
117    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
118        match self {
119            CatalogError::Sqlite(e) => Some(e),
120            CatalogError::Io(e) | CatalogError::Access { error: e, .. } => Some(e),
121            CatalogError::WrongKey | CatalogError::UnknownSchema(_) => None,
122        }
123    }
124}
125
126impl From<rusqlite::Error> for CatalogError {
127    fn from(e: rusqlite::Error) -> CatalogError {
128        CatalogError::Sqlite(e)
129    }
130}
131
132/// Opens the catalog at `path` under `key`, making it with `schema` if it
133/// is new.
134pub fn open(path: &Path, key: &Key, schema: &str) -> Result<Connection, CatalogError> {
135    // SQLite opens a file it may not write read-only and fails later with
136    // its own code, which no longer says why; asking the system first
137    // gives the path and its error.
138    if let Some(dir) = path.parent() {
139        may_use(dir, libc::W_OK | libc::X_OK)?;
140    }
141    if path.exists() {
142        may_use(path, libc::R_OK | libc::W_OK)?;
143    } else {
144        make_file(path)?;
145    }
146    let conn = Connection::open(path)?;
147    conn.busy_timeout(BUSY_TIMEOUT)?;
148    // SQLCipher otherwise writes its own error lines to standard error, a
149    // wrong key among them; this program says what went wrong itself.
150    conn.pragma_update(None, "cipher_log_level", "NONE")?;
151    set_key(&conn, key)?;
152    // SQLCipher reads nothing until the first query, so a wrong key shows
153    // here, as a file that is not a database.
154    match conn.query_row("SELECT count(*) FROM sqlite_master", [], |_| Ok(())) {
155        Err(e) if e.sqlite_error_code() == Some(ErrorCode::NotADatabase) => {
156            return Err(CatalogError::WrongKey);
157        }
158        other => other?,
159    }
160    // Each setting is stated even where this build's default already
161    // matches (synchronous and secure_delete do), so a change of build
162    // flags cannot drop one; the tests read each back.
163    let mode: String = conn.pragma_update_and_check(None, "journal_mode", "WAL", |r| r.get(0))?;
164    debug_assert_eq!(mode, "wal");
165    conn.pragma_update(None, "synchronous", "FULL")?;
166    conn.pragma_update(None, "secure_delete", "ON")?;
167    conn.pragma_update(None, "temp_store", "MEMORY")?;
168    match conn.pragma_query_value(None, "user_version", |r| r.get(0))? {
169        0 => {
170            let tx = conn.unchecked_transaction()?;
171            tx.execute_batch(schema)?;
172            tx.pragma_update(None, "user_version", SCHEMA_VERSION)?;
173            tx.commit()?;
174        }
175        from @ 1..=3 => {
176            // One transaction, so a failed upgrade leaves the old version
177            // whole. A tenant catalog has a vcon table, server.sqlite a
178            // tenant table.
179            let tx = conn.unchecked_transaction()?;
180            let has = |table: &str| -> rusqlite::Result<bool> {
181                tx.query_row(
182                    "SELECT count(*) > 0 FROM sqlite_master WHERE type = 'table' AND name = ?1",
183                    [table],
184                    |r| r.get(0),
185                )
186            };
187            if from < 2 && has("vcon")? {
188                tx.execute_batch(VCON_STORED_AT)?;
189            }
190            if from < 3 && has("tenant")? {
191                tx.execute_batch(TENANT_METADATA)?;
192            }
193            if from < 4 && has("version")? {
194                tx.execute_batch(VERSION_PLACES)?;
195                tx.execute_batch(PACK_TABLES)?;
196            }
197            tx.pragma_update(None, "user_version", SCHEMA_VERSION)?;
198            tx.commit()?;
199        }
200        SCHEMA_VERSION => {}
201        other => return Err(CatalogError::UnknownSchema(other)),
202    }
203    Ok(conn)
204}
205
206/// Whether this process, by its effective ids, may use `path` as `how`
207/// asks (`R_OK`, `W_OK`, `X_OK`); if not, the path and the system's error.
208pub(crate) fn may_use(path: &Path, how: c_int) -> Result<(), CatalogError> {
209    let denied = |error| CatalogError::Access {
210        path: path.to_owned(),
211        error,
212    };
213    let text = std::ffi::CString::new(path.as_os_str().as_encoded_bytes())
214        .map_err(|_| denied(std::io::ErrorKind::InvalidInput.into()))?;
215    // SAFETY: `text` is a NUL-terminated path that outlives the call, and
216    // faccessat reads only it and the flags.
217    if unsafe { libc::faccessat(libc::AT_FDCWD, text.as_ptr(), how, libc::AT_EACCESS) } != 0 {
218        return Err(denied(std::io::Error::last_os_error()));
219    }
220    Ok(())
221}
222
223/// Copies the catalog `source` is open on to a new file at `to`, kept
224/// under `key`, which must be the key `source` was opened with. It uses
225/// SQLite's online backup API and copies every page in one step, so the
226/// copy is the catalog as one commit left it, the WAL's committed frames
227/// included, while other connections go on writing. `to` must not exist:
228/// it is made empty first, so a file already there is never written over.
229/// The copy and its directory are synced.
230pub fn backup(source: &Connection, to: &Path, key: &Key) -> Result<(), CatalogError> {
231    let io = CatalogError::Io;
232    make_file(to)?;
233    {
234        let mut copy = Connection::open(to)?;
235        copy.pragma_update(None, "cipher_log_level", "NONE")?;
236        set_key(&copy, key)?;
237        let backup = rusqlite::backup::Backup::new(source, &mut copy)?;
238        // A negative count copies every remaining page in this one step.
239        match backup.step(-1)? {
240            rusqlite::backup::StepResult::Done => {}
241            _ => {
242                return Err(io(std::io::Error::other(
243                    "the catalog was busy and could not be copied in one step",
244                )));
245            }
246        }
247    }
248    std::fs::File::open(to)
249        .and_then(|f| f.sync_all())
250        .map_err(io)?;
251    let dir = to.parent().unwrap_or(Path::new("."));
252    std::fs::File::open(dir)
253        .and_then(|f| f.sync_all())
254        .map_err(io)?;
255    Ok(())
256}
257
258/// Re-encrypts the catalog at `path`, kept under `old`, so that it is kept
259/// under `new`: every row, the schema and its version are written to a new
260/// file under `new`, which then replaces the old one by rename. A crash
261/// leaves either the whole old file or the whole new one, and nothing of
262/// the old file's pages is carried into the new one. A file left by an
263/// interrupted run is replaced.
264pub fn reencrypt(path: &Path, old: &Key, new: &Key) -> Result<(), CatalogError> {
265    let copy = copy_under(path, old, new)?;
266    replace(path, &copy)
267}
268
269/// Writes every row, the schema and its version of the catalog at `path`,
270/// kept under `old`, to a new file beside it kept under `new`, and returns
271/// that file's path. The old file is only read. A file left there by an
272/// interrupted run is replaced.
273pub fn copy_under(path: &Path, old: &Key, new: &Key) -> Result<PathBuf, CatalogError> {
274    let target = sibling(path, ".rekey");
275    for stale in [
276        target.clone(),
277        sibling(&target, "-wal"),
278        sibling(&target, "-shm"),
279    ] {
280        remove_if_there(&stale)?;
281    }
282    make_file(&target)?;
283    let conn = open(path, old, "")?;
284    let version: i64 = conn.pragma_query_value(None, "user_version", |r| r.get(0))?;
285    let target_text = target
286        .to_str()
287        .ok_or_else(|| CatalogError::Io(std::io::Error::other("the catalog path is not UTF-8")))?;
288    conn.execute("ATTACH DATABASE ?1 AS rekeyed", [target_text])?;
289    set_key_of(&conn, c"rekeyed", new)?;
290    conn.query_row("SELECT sqlcipher_export('rekeyed')", [], |_| Ok(()))?;
291    // A pragma takes no bound parameter; the version is a number read
292    // from the catalog itself.
293    conn.execute_batch(&format!("PRAGMA rekeyed.user_version = {version}"))?;
294    conn.execute("DETACH DATABASE rekeyed", [])?;
295    Ok(target)
296}
297
298/// Makes `copy` the catalog at `path`: it is synced, renamed over `path`,
299/// and the directory synced. Every connection to either file must be
300/// closed. Their WAL files must be empty, as a last close leaves them; one
301/// still holding frames would sit beside the wrong file, so it is refused.
302pub fn replace(path: &Path, copy: &Path) -> Result<(), CatalogError> {
303    for file in [path, copy] {
304        let wal = sibling(file, "-wal");
305        if std::fs::metadata(&wal).is_ok_and(|m| m.len() > 0) {
306            return Err(CatalogError::Io(std::io::Error::other(
307                "a catalog's WAL was not emptied",
308            )));
309        }
310        remove_if_there(&wal)?;
311        remove_if_there(&sibling(file, "-shm"))?;
312    }
313    let io = CatalogError::Io;
314    std::fs::File::open(copy)
315        .and_then(|f| f.sync_all())
316        .map_err(io)?;
317    std::fs::rename(copy, path).map_err(io)?;
318    let dir = path.parent().unwrap_or(Path::new("."));
319    std::fs::File::open(dir)
320        .and_then(|f| f.sync_all())
321        .map_err(io)?;
322    Ok(())
323}
324
325/// Makes an empty file at `path`, which must not exist, with the server's
326/// file mode: SQLite then opens it as a new database, and makes its WAL
327/// and shared-memory files with the same mode.
328fn make_file(path: &Path) -> Result<(), CatalogError> {
329    use std::os::unix::fs::OpenOptionsExt;
330    std::fs::OpenOptions::new()
331        .write(true)
332        .create_new(true)
333        .mode(crate::fs::FILE_MODE)
334        .open(path)
335        .map(drop)
336        .map_err(CatalogError::Io)
337}
338
339fn remove_if_there(file: &Path) -> Result<(), CatalogError> {
340    match std::fs::remove_file(file) {
341        Err(e) if e.kind() != std::io::ErrorKind::NotFound => Err(CatalogError::Io(e)),
342        _ => Ok(()),
343    }
344}
345
346/// `path` with `suffix` added to its file name.
347fn sibling(path: &Path, suffix: &str) -> PathBuf {
348    let mut name = path.as_os_str().to_owned();
349    name.push(suffix);
350    PathBuf::from(name)
351}
352
353/// Keys the attached database `schema` as `set_key` keys the main one.
354fn set_key_of(conn: &Connection, schema: &std::ffi::CStr, key: &Key) -> Result<(), CatalogError> {
355    let literal = key.sqlcipher_raw();
356    let len = c_int::try_from(literal.len()).expect("a 67-byte literal");
357    // SAFETY: the handle is this open connection's; the name is a valid C
358    // string and the key pointer and length are the literal's, both of
359    // which outlive the call.
360    let rc = unsafe {
361        rusqlite::ffi::sqlite3_key_v2(conn.handle(), schema.as_ptr(), literal.as_ptr().cast(), len)
362    };
363    if rc != rusqlite::ffi::SQLITE_OK {
364        return Err(rusqlite::Error::SqliteFailure(rusqlite::ffi::Error::new(rc), None).into());
365    }
366    Ok(())
367}
368
369/// Gives SQLCipher the key as a raw key, never a passphrase. sqlite3_key
370/// takes the literal straight from its zeroing buffer; a PRAGMA would copy
371/// it into SQL text that is not zeroed.
372fn set_key(conn: &Connection, key: &Key) -> Result<(), CatalogError> {
373    let literal = key.sqlcipher_raw();
374    let len = c_int::try_from(literal.len()).expect("a 67-byte literal");
375    // SAFETY: the handle is this open connection's, and the pointer and
376    // length are the literal's, which outlives the call.
377    let rc = unsafe { rusqlite::ffi::sqlite3_key(conn.handle(), literal.as_ptr().cast(), len) };
378    // sqlite3_key does not fail on an open connection, so no test reaches
379    // this check; it stays to fail closed.
380    if rc != rusqlite::ffi::SQLITE_OK {
381        return Err(rusqlite::Error::SqliteFailure(rusqlite::ffi::Error::new(rc), None).into());
382    }
383    Ok(())
384}
385
386/// Checks on a catalog's schema, for tests.
387#[cfg(test)]
388pub(crate) mod testing {
389    use rusqlite::Connection;
390
391    /// The columns of `table` that take NULL. `row` gives a value for each
392    /// column; each column is tried as NULL in that row, and nothing is
393    /// kept. The whole row must insert, so a refusal is the column's.
394    pub(crate) fn columns_taking_null(
395        conn: &Connection,
396        table: &str,
397        row: &[(&str, &str)],
398    ) -> Vec<String> {
399        let insert = |empty: Option<&str>| {
400            let columns: Vec<&str> = row.iter().map(|(c, _)| *c).collect();
401            let values: Vec<&str> = row
402                .iter()
403                .map(|(c, v)| if Some(*c) == empty { "NULL" } else { *v })
404                .collect();
405            let sql = format!(
406                "INSERT INTO {table} ({}) VALUES ({})",
407                columns.join(", "),
408                values.join(", ")
409            );
410            let tx = conn.unchecked_transaction().expect("begin");
411            let taken = tx.execute(&sql, []).is_ok();
412            drop(tx);
413            taken
414        };
415        assert!(insert(None), "a whole {table} row inserts");
416        row.iter()
417            .filter(|(column, _)| insert(Some(column)))
418            .map(|(column, _)| format!("{table}.{column}"))
419            .collect()
420    }
421}
422
423#[cfg(test)]
424pub(crate) mod tests {
425    use super::*;
426
427    const SCHEMA: &str = "CREATE TABLE note (text TEXT NOT NULL);";
428    const MARKER: &str = "plain-record-marker-5f3c9a";
429
430    fn path(dir: &tempfile::TempDir) -> std::path::PathBuf {
431        dir.path().join("catalog.sqlite")
432    }
433
434    /// Reads one of SQLCipher's own settings.
435    pub(crate) fn cipher_setting(conn: &Connection, name: &str) -> String {
436        conn.pragma_query_value(None, name, |r| r.get(0))
437            .expect(name)
438    }
439
440    #[test]
441    fn a_catalog_runs_with_the_required_settings() {
442        let dir = tempfile::tempdir().expect("temp dir");
443        let key = Key::generate().expect("key");
444        let conn = open(&path(&dir), &key, SCHEMA).expect("opens");
445        let text = |p: &str| -> String { conn.pragma_query_value(None, p, |r| r.get(0)).expect(p) };
446        let number = |p: &str| -> i64 { conn.pragma_query_value(None, p, |r| r.get(0)).expect(p) };
447        assert_eq!(text("journal_mode"), "wal");
448        assert_eq!(number("synchronous"), 2, "FULL");
449        assert_eq!(number("secure_delete"), 1);
450        assert_eq!(number("temp_store"), 2, "MEMORY");
451        assert_eq!(number("busy_timeout"), 5000, "milliseconds");
452        assert_eq!(cipher_setting(&conn, "cipher_provider"), "openssl");
453        assert_eq!(
454            cipher_setting(&conn, "cipher_log_level"),
455            "NONE",
456            "SQLCipher writes no log of its own"
457        );
458    }
459
460    /// The SQLCipher settings a catalog runs with, read back through
461    /// rusqlite's pragma helpers on a second connection to the same file,
462    /// equal what plain SQL reads on the first. `open` and `cipher_setting`
463    /// use the helpers, so the values must not differ between the two ways
464    /// of setting and reading them.
465    #[test]
466    fn sqlcipher_settings_read_the_same_through_the_pragma_helpers() {
467        let dir = tempfile::tempdir().expect("temp dir");
468        let key = Key::generate().expect("key");
469        let conn = open(&path(&dir), &key, SCHEMA).expect("opens");
470        let names = ["cipher_log_level", "cipher_provider", "cipher_page_size"];
471        let plain: Vec<String> = names
472            .iter()
473            .map(|n| {
474                conn.query_row(&format!("PRAGMA {n}"), [], |r| r.get(0))
475                    .unwrap_or_else(|e| panic!("{n} as plain SQL: {e}"))
476            })
477            .collect();
478
479        let helpers = Connection::open(path(&dir)).expect("opens again");
480        // Before the key, as `open` does it: the helper must not need to
481        // read an encrypted file to take the name.
482        helpers
483            .pragma_update(None, "cipher_log_level", "NONE")
484            .expect("cipher_log_level through pragma_update");
485        set_key(&helpers, &key).expect("keyed");
486        let notes: i64 = helpers
487            .query_row("SELECT count(*) FROM note", [], |r| r.get(0))
488            .expect("the key opens the same catalog");
489        assert_eq!(notes, 0);
490        let read: Vec<String> = names
491            .iter()
492            .map(|n| {
493                helpers
494                    .pragma_query_value(None, n, |r| r.get(0))
495                    .unwrap_or_else(|e| panic!("{n} through pragma_query_value: {e}"))
496            })
497            .collect();
498        assert_eq!(read, plain);
499        assert_eq!(plain[0], "NONE");
500        let ours: Vec<String> = names.iter().map(|n| cipher_setting(&conn, n)).collect();
501        assert_eq!(ours, plain, "cipher_setting reads what plain SQL reads");
502    }
503
504    /// rusqlite's pragma helpers take SQLCipher's pragma names, which
505    /// rusqlite 0.41.0 refused with "Invalid pragma" (0.41.1 stopped
506    /// checking names in a SQLCipher build). `open` and `backup` set
507    /// `cipher_log_level` through a helper, so a rusqlite that refuses the
508    /// name again must fail here, by name, not in every test that opens a
509    /// catalog.
510    #[test]
511    fn rusqlite_takes_sqlcipher_names_in_its_pragma_helpers() {
512        let conn = Connection::open_in_memory().expect("opens");
513        let taken = conn.pragma_update(None, "cipher_log_level", "NONE");
514        assert!(
515            taken.is_ok(),
516            "this rusqlite refuses SQLCipher's pragma names ({taken:?}): catalog::open and \
517             catalog::backup set cipher_log_level through pragma_update"
518        );
519        let level: String = conn
520            .pragma_query_value(None, "cipher_log_level", |r| r.get(0))
521            .expect("cipher_log_level through pragma_query_value");
522        assert_eq!(level, "NONE", "and reads back what was set");
523    }
524
525    /// Every dependency comes from crates.io. Until rusqlite 0.41.1 the
526    /// tests used a git fork of rusqlite, with a `[patch]` for its
527    /// libsqlite3-sys, so every build fetched from github.com; these hold
528    /// the manifests, the lockfiles and the pages to the state without it.
529    mod sources {
530        use std::path::PathBuf;
531
532        fn read(relative: &str) -> String {
533            let path = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join(relative);
534            std::fs::read_to_string(&path).unwrap_or_else(|e| panic!("{}: {e}", path.display()))
535        }
536
537        fn table(text: &str) -> toml::Table {
538            text.parse().expect("toml")
539        }
540
541        /// The dependencies of `manifest` that name a git repository, as
542        /// `<table>.<name>`, from the three dependency tables.
543        fn git_dependencies(manifest: &toml::Table) -> Vec<String> {
544            ["dependencies", "dev-dependencies", "build-dependencies"]
545                .iter()
546                .filter_map(|kind| Some((kind, manifest.get(*kind)?.as_table()?)))
547                .flat_map(|(kind, deps)| {
548                    deps.iter()
549                        .filter(|(_, spec)| spec.get("git").is_some())
550                        .map(move |(name, _)| format!("{kind}.{name}"))
551                })
552                .collect()
553        }
554
555        #[test]
556        fn the_git_dependency_reader_finds_one_in_any_table() {
557            let manifest = table(
558                "[dependencies]\nplain = \"1\"\n\
559                 [dev-dependencies]\nforked = { package = \"plain\", git = \"https://example.com/forked\" }\n\
560                 [build-dependencies]\nother = { git = \"https://example.com/other\", rev = \"abc\" }\n",
561            );
562            assert_eq!(
563                git_dependencies(&manifest),
564                ["dev-dependencies.forked", "build-dependencies.other"],
565                "each git dependency, with its table"
566            );
567            assert!(
568                git_dependencies(&table("[dependencies]\nplain = \"1\"\n")).is_empty(),
569                "a crates.io dependency is not one"
570            );
571            assert!(
572                git_dependencies(&table("[package]\nname = \"none\"\n")).is_empty(),
573                "a manifest with no dependency table has none"
574            );
575        }
576
577        #[test]
578        fn no_dependency_comes_from_a_git_repository() {
579            let manifest = table(&read("Cargo.toml"));
580            assert_eq!(
581                git_dependencies(&manifest),
582                [] as [&str; 0],
583                "vcon-server's Cargo.toml"
584            );
585            let server = &manifest["dependencies"]["rusqlite"];
586            assert!(
587                server.get("version").is_some()
588                    && server.get("git").is_none()
589                    && server.get("path").is_none(),
590                "the server's rusqlite comes from crates.io"
591            );
592            assert!(
593                manifest["dev-dependencies"].get("rusqlite_fork").is_none(),
594                "the fork is gone"
595            );
596        }
597
598        #[test]
599        fn the_workspace_patches_nothing() {
600            let workspace = table(&read("../../Cargo.toml"));
601            assert!(
602                workspace.get("patch").is_none(),
603                "no [patch] table: {:?}",
604                workspace.get("patch")
605            );
606        }
607
608        #[test]
609        fn no_lockfile_names_a_git_source() {
610            for lockfile in ["../../Cargo.lock", "../../fuzz/Cargo.lock"] {
611                let lock = read(lockfile);
612                let git: Vec<&str> = lock
613                    .lines()
614                    .filter(|l| l.starts_with("source = \"git+"))
615                    .collect();
616                assert_eq!(git, [] as [&str; 0], "{lockfile}");
617            }
618        }
619
620        #[test]
621        fn the_pages_name_no_fork() {
622            let development = read("../../website/content/docs/development.md");
623            assert!(
624                !development.contains("\n## Test dependency from a fork\n"),
625                "the Development page's section on the fork is gone"
626            );
627            let install = read("../../website/content/docs/install.md");
628            let build = install
629                .split("\n## ")
630                .find(|s| s.starts_with("Build from source\n"))
631                .expect("a Build from source section");
632            assert!(
633                build.contains("mkdir -p .cargo && cargo vendor >> .cargo/config.toml\n"),
634                "the vendoring command"
635            );
636            assert!(build.contains("cargo build --release --offline\n"));
637            for page in [&development, &install] {
638                assert!(!page.contains("NormB/rusqlite"), "no page names the fork");
639                assert!(!page.contains("rusqlite fork"), "no page speaks of a fork");
640            }
641            let release = install
642                .split("\n## ")
643                .find(|s| s.starts_with("Download a release\n"))
644                .expect("a release section");
645            assert!(
646                release.contains("crates.io"),
647                "says where the release's rusqlite comes from"
648            );
649        }
650    }
651
652    #[test]
653    fn the_schema_is_made_once_at_the_current_version() {
654        let dir = tempfile::tempdir().expect("temp dir");
655        let key = Key::generate().expect("key");
656        let conn = open(&path(&dir), &key, SCHEMA).expect("opens");
657        let version: i64 = conn
658            .pragma_query_value(None, "user_version", |r| r.get(0))
659            .expect("version");
660        assert_eq!(version, SCHEMA_VERSION);
661        conn.execute("INSERT INTO note (text) VALUES ('kept')", [])
662            .expect("insert");
663        drop(conn);
664        let conn =
665            open(&path(&dir), &key, SCHEMA).expect("reopens without making the schema again");
666        let kept: String = conn
667            .query_row("SELECT text FROM note", [], |r| r.get(0))
668            .expect("row");
669        assert_eq!(kept, "kept");
670    }
671
672    #[test]
673    fn an_unknown_schema_version_is_refused() {
674        let dir = tempfile::tempdir().expect("temp dir");
675        let key = Key::generate().expect("key");
676        let conn = open(&path(&dir), &key, SCHEMA).expect("opens");
677        conn.pragma_update(None, "user_version", SCHEMA_VERSION + 1)
678            .expect("set version");
679        drop(conn);
680        assert!(matches!(
681            open(&path(&dir), &key, SCHEMA),
682            Err(CatalogError::UnknownSchema(v)) if v == SCHEMA_VERSION + 1
683        ));
684    }
685
686    /// A catalog made at version 1 opens at the current version, its rows
687    /// kept. One with no vCon table and no tenant table changes only its
688    /// number; the tenant catalog's upgrade is tested with the Store, and
689    /// server.sqlite's with the registry.
690    #[test]
691    fn a_version_1_catalog_is_upgraded_to_the_current_version() {
692        let dir = tempfile::tempdir().expect("temp dir");
693        let key = Key::generate().expect("key");
694        let conn = open(&path(&dir), &key, SCHEMA).expect("opens");
695        conn.execute("INSERT INTO note (text) VALUES ('kept')", [])
696            .expect("insert");
697        conn.pragma_update(None, "user_version", 1)
698            .expect("set version");
699        drop(conn);
700        let conn = open(&path(&dir), &key, "").expect("upgrades");
701        let version: i64 = conn
702            .pragma_query_value(None, "user_version", |r| r.get(0))
703            .expect("version");
704        assert_eq!(
705            version, SCHEMA_VERSION,
706            "the catalog is brought to the current version"
707        );
708        assert_eq!(notes(&conn), vec!["kept"]);
709    }
710
711    /// The path a re-encryption writes before its rename.
712    fn rekeyed(dir: &tempfile::TempDir) -> std::path::PathBuf {
713        dir.path().join("catalog.sqlite.rekey")
714    }
715
716    fn notes(conn: &Connection) -> Vec<String> {
717        conn.prepare("SELECT text FROM note ORDER BY rowid")
718            .expect("prepare")
719            .query_map([], |r| r.get(0))
720            .expect("query")
721            .collect::<Result<_, _>>()
722            .expect("rows")
723    }
724
725    #[test]
726    fn a_reencrypted_catalog_opens_under_the_new_key_only_and_keeps_every_row() {
727        let dir = tempfile::tempdir().expect("temp dir");
728        let (old, new) = (Key::generate().expect("key"), Key::generate().expect("key"));
729        let conn = open(&path(&dir), &old, SCHEMA).expect("opens");
730        for n in 0..300 {
731            conn.execute("INSERT INTO note (text) VALUES (?1)", [format!("note {n}")])
732                .expect("insert");
733        }
734        drop(conn);
735        reencrypt(&path(&dir), &old, &new).expect("re-encrypted");
736        let raw = std::fs::read(path(&dir)).expect("the file");
737        assert!(
738            !raw.windows(8).any(|w| w == b"note 299"),
739            "no row is written in the clear"
740        );
741        assert!(matches!(
742            open(&path(&dir), &old, SCHEMA),
743            Err(CatalogError::WrongKey)
744        ));
745        let conn = open(&path(&dir), &new, SCHEMA).expect("opens under the new key");
746        let kept = notes(&conn);
747        assert_eq!(
748            kept,
749            (0..300).map(|n| format!("note {n}")).collect::<Vec<_>>(),
750            "every row is kept, each with its own text, in order"
751        );
752        let version: i64 = conn
753            .pragma_query_value(None, "user_version", |r| r.get(0))
754            .expect("version");
755        assert_eq!(version, SCHEMA_VERSION, "the schema version is kept");
756        let mode: String = conn
757            .pragma_query_value(None, "journal_mode", |r| r.get(0))
758            .expect("mode");
759        assert_eq!(mode, "wal");
760        drop(conn);
761        let mut left: Vec<String> = std::fs::read_dir(dir.path())
762            .expect("list")
763            .map(|e| e.expect("entry").file_name().to_string_lossy().into_owned())
764            .collect();
765        left.sort();
766        assert_eq!(left, ["catalog.sqlite"], "no temporary file is left");
767    }
768
769    #[test]
770    fn a_file_left_by_an_interrupted_reencryption_is_replaced() {
771        let dir = tempfile::tempdir().expect("temp dir");
772        let (old, new) = (Key::generate().expect("key"), Key::generate().expect("key"));
773        let conn = open(&path(&dir), &old, SCHEMA).expect("opens");
774        conn.execute("INSERT INTO note (text) VALUES ('kept')", [])
775            .expect("insert");
776        drop(conn);
777        std::fs::write(rekeyed(&dir), b"half a file").expect("leftover");
778        reencrypt(&path(&dir), &old, &new).expect("re-encrypted");
779        let conn = open(&path(&dir), &new, SCHEMA).expect("opens");
780        assert_eq!(notes(&conn), ["kept"]);
781        assert!(!rekeyed(&dir).exists());
782    }
783
784    /// A WAL holding frames belongs to its own file: renaming that file
785    /// without them would lose committed rows, and leaving the old one's
786    /// beside the new file would corrupt it. Either refuses the rename.
787    #[test]
788    fn a_replace_refuses_while_either_wal_holds_frames() {
789        let dir = tempfile::tempdir().expect("temp dir");
790        let key = Key::generate().expect("key");
791        let copy = dir.path().join("catalog.sqlite.rekey");
792        for busy in [path(&dir), copy.clone()] {
793            for file in [path(&dir), copy.clone()] {
794                for leftover in ["", "-wal", "-shm"] {
795                    let _ = std::fs::remove_file(sibling(&file, leftover));
796                }
797                drop(open(&file, &key, SCHEMA).expect("made"));
798            }
799            let held = open(&busy, &key, SCHEMA).expect("opens");
800            held.pragma_update(None, "wal_autocheckpoint", 0)
801                .expect("no checkpoint");
802            held.execute("INSERT INTO note (text) VALUES ('in the wal')", [])
803                .expect("insert");
804            assert!(
805                std::fs::metadata(sibling(&busy, "-wal")).is_ok_and(|m| m.len() > 0),
806                "the WAL holds the row"
807            );
808            assert!(
809                matches!(replace(&path(&dir), &copy), Err(CatalogError::Io(_))),
810                "{}",
811                busy.display()
812            );
813            assert!(copy.exists(), "nothing was renamed");
814            drop(held);
815        }
816    }
817
818    #[test]
819    fn reencrypting_under_the_wrong_key_changes_nothing() {
820        let dir = tempfile::tempdir().expect("temp dir");
821        let (old, new) = (Key::generate().expect("key"), Key::generate().expect("key"));
822        drop(open(&path(&dir), &old, SCHEMA).expect("opens"));
823        let other = Key::generate().expect("key");
824        assert!(matches!(
825            reencrypt(&path(&dir), &other, &new),
826            Err(CatalogError::WrongKey)
827        ));
828        assert!(
829            open(&path(&dir), &old, SCHEMA).is_ok(),
830            "still under the old key"
831        );
832    }
833
834    #[test]
835    fn a_backup_holds_every_committed_row_and_opens_under_the_same_key_only() {
836        let dir = tempfile::tempdir().expect("temp dir");
837        let key = Key::generate().expect("key");
838        let source = open(&path(&dir), &key, SCHEMA).expect("opens");
839        source
840            .execute("INSERT INTO note (text) VALUES ('committed')", [])
841            .expect("insert");
842        // A second connection holds a write transaction open: its row is
843        // not committed, so the copy must not hold it.
844        let writer = open(&path(&dir), &key, SCHEMA).expect("opens");
845        writer.execute_batch("BEGIN IMMEDIATE").expect("begin");
846        writer
847            .execute("INSERT INTO note (text) VALUES ('uncommitted')", [])
848            .expect("insert");
849        let copy = dir.path().join("copy.sqlite");
850        backup(&source, &copy, &key).expect("backs up");
851        writer.execute_batch("COMMIT").expect("commit");
852        assert!(
853            !sibling(&copy, "-wal").exists()
854                || std::fs::metadata(sibling(&copy, "-wal"))
855                    .expect("wal")
856                    .len()
857                    == 0,
858            "the copy is whole in its own file"
859        );
860        let reopened = open(&copy, &key, "").expect("the copy opens under the same key");
861        let notes: Vec<String> = reopened
862            .prepare("SELECT text FROM note")
863            .expect("prepare")
864            .query_map([], |r| r.get(0))
865            .expect("query")
866            .collect::<Result<_, _>>()
867            .expect("rows");
868        assert_eq!(notes, ["committed"]);
869        let version: i64 = reopened
870            .pragma_query_value(None, "user_version", |r| r.get(0))
871            .expect("version");
872        assert_eq!(version, SCHEMA_VERSION);
873        drop(reopened);
874        let other = Key::generate().expect("key");
875        assert!(matches!(
876            open(&copy, &other, ""),
877            Err(CatalogError::WrongKey)
878        ));
879    }
880
881    #[test]
882    fn a_backup_holds_rows_still_in_the_source_wal_and_no_plain_text() {
883        let dir = tempfile::tempdir().expect("temp dir");
884        let key = Key::generate().expect("key");
885        let source = open(&path(&dir), &key, SCHEMA).expect("opens");
886        source
887            .execute("INSERT INTO note (text) VALUES (?1)", [MARKER])
888            .expect("insert");
889        assert!(
890            std::fs::metadata(sibling(&path(&dir), "-wal"))
891                .expect("wal")
892                .len()
893                > 0,
894            "the row is still in the WAL"
895        );
896        let copy = dir.path().join("copy.sqlite");
897        backup(&source, &copy, &key).expect("backs up");
898        let bytes = std::fs::read(&copy).expect("read the copy");
899        assert!(
900            !bytes.windows(MARKER.len()).any(|w| w == MARKER.as_bytes()),
901            "the copy is encrypted"
902        );
903        let reopened = open(&copy, &key, "").expect("opens");
904        let count: i64 = reopened
905            .query_row("SELECT count(*) FROM note WHERE text = ?1", [MARKER], |r| {
906                r.get(0)
907            })
908            .expect("count");
909        assert_eq!(count, 1);
910    }
911
912    #[test]
913    fn a_backup_never_writes_over_a_file() {
914        let dir = tempfile::tempdir().expect("temp dir");
915        let key = Key::generate().expect("key");
916        let source = open(&path(&dir), &key, SCHEMA).expect("opens");
917        let copy = dir.path().join("copy.sqlite");
918        std::fs::write(&copy, b"something else").expect("write");
919        assert!(matches!(
920            backup(&source, &copy, &key),
921            Err(CatalogError::Io(_))
922        ));
923        assert_eq!(std::fs::read(&copy).expect("read"), b"something else");
924    }
925
926    #[test]
927    fn a_wrong_key_does_not_open_the_catalog() {
928        let dir = tempfile::tempdir().expect("temp dir");
929        let key = Key::generate().expect("key");
930        drop(open(&path(&dir), &key, SCHEMA).expect("opens"));
931        let other = Key::generate().expect("key");
932        assert!(matches!(
933            open(&path(&dir), &other, SCHEMA),
934            Err(CatalogError::WrongKey)
935        ));
936        assert!(
937            open(&path(&dir), &key, SCHEMA).is_ok(),
938            "the right key still opens it"
939        );
940    }
941
942    /// A catalog file or directory this process may not write is named,
943    /// with the system's error, and never taken for a wrong key.
944    #[test]
945    fn a_catalog_the_process_may_not_write_is_an_access_error_naming_the_path() {
946        use std::os::unix::fs::PermissionsExt;
947        let mode = |p: &Path, m| {
948            std::fs::set_permissions(p, std::fs::Permissions::from_mode(m)).expect("chmod")
949        };
950        let dir = tempfile::tempdir().expect("temp dir");
951        let key = Key::generate().expect("key");
952        drop(open(&path(&dir), &key, SCHEMA).expect("opens"));
953        for (target, read_only) in [(path(&dir), 0o400), (dir.path().to_owned(), 0o500)] {
954            mode(&target, read_only);
955            let refused = open(&path(&dir), &key, SCHEMA);
956            mode(&target, if target.is_dir() { 0o700 } else { 0o600 });
957            match refused {
958                Err(CatalogError::Access { path, error }) => {
959                    assert_eq!(path, target);
960                    assert_eq!(error.kind(), std::io::ErrorKind::PermissionDenied);
961                }
962                other => panic!("{}: {other:?}", target.display()),
963            }
964        }
965        assert!(
966            open(&path(&dir), &key, SCHEMA).is_ok(),
967            "opens once allowed"
968        );
969    }
970
971    /// A row that cannot insert at all would make every column look as if
972    /// it refused NULL.
973    #[test]
974    #[should_panic(expected = "a whole note row inserts")]
975    fn the_null_check_needs_a_row_that_inserts() {
976        let dir = tempfile::tempdir().expect("temp dir");
977        let key = Key::generate().expect("key");
978        let conn = open(&path(&dir), &key, SCHEMA).expect("opens");
979        testing::columns_taking_null(&conn, "note", &[("misspelt", "'a'")]);
980    }
981
982    /// Run while the connection is open, so the commit is still in the WAL.
983    #[test]
984    fn no_plain_record_reaches_the_catalog_or_its_wal() {
985        let dir = tempfile::tempdir().expect("temp dir");
986        let key = Key::generate().expect("key");
987        let conn = open(&path(&dir), &key, SCHEMA).expect("opens");
988        conn.execute("INSERT INTO note (text) VALUES (?1)", [MARKER])
989            .expect("insert");
990        let wal = std::fs::metadata(dir.path().join("catalog.sqlite-wal")).expect("a WAL");
991        assert!(wal.len() > 0, "the commit is in the WAL");
992        for entry in std::fs::read_dir(dir.path()).expect("list") {
993            let file = entry.expect("entry").path();
994            let bytes = std::fs::read(&file).expect("read");
995            assert!(
996                !bytes.windows(MARKER.len()).any(|w| w == MARKER.as_bytes()),
997                "plain record in {}",
998                file.display()
999            );
1000        }
1001        drop(conn);
1002    }
1003}