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; version 5 added the users and memberships tables to
16/// server.sqlite, and lets every catalog's audit log hold no status;
17/// version 6 added each tenant's role cap to server.sqlite; version 7 added
18/// the table of the settings a tenant's administrator sets; version 8
19/// added the table of the sessions of users who signed in; version 9 added
20/// each access key's expiry and last-used time to server.sqlite.
21/// A build refuses every version it does not know, so a catalog this
22/// build has opened is refused by release 0.4.3 and earlier.
23pub const SCHEMA_VERSION: i64 = 9;
24
25/// Brings server.sqlite from version 8 to 9: each access key's expiry and
26/// its last-used time, both NULL for every key there is. A key made
27/// before version 9 was made with no expiry, and keeps none.
28const KEY_LIFE: &str = "
29ALTER TABLE api_key ADD COLUMN expires_at INTEGER;
30ALTER TABLE api_key ADD COLUMN last_used_at INTEGER;
31";
32
33/// The sessions of the users who signed in, as a new registry and an
34/// upgraded one both make them (version 8): one row for each live session,
35/// found by the SHA-256 of its id. Neither the id nor the CSRF token is
36/// kept, only the hash of each. The times are in nanoseconds, as every
37/// time in the registry is. A session is removed when it ends, when its
38/// user's roles change or its user is deactivated, and with its tenant.
39pub(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
57/// The users and their memberships in server.sqlite, as a new registry
58/// and an upgraded one both make them. A user is a person who signs in:
59/// a display label, and the identity an identity provider knows the
60/// person by (its issuer and the subject it gives), or neither for a local
61/// account. An identity belongs to one active user; a deactivated user
62/// keeps its row, for the logs that name its id. A membership gives a user
63/// roles in one tenant, or as an operator (no tenant): at most one for
64/// each, which the two indexes hold, since a UNIQUE over a NULL tenant
65/// holds nothing. Times are nanoseconds since the epoch.
66pub(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
91/// Brings a version-4 audit log to version 5: the same records under the
92/// same numbers, in a table whose status may be NULL, with NULL where
93/// version 4 wrote 0 for a record that answers no request
94/// (`audit::NO_ANSWER`). SQLite cannot drop a NOT NULL from a column, so
95/// the table is made again, by the text a new catalog makes it with, and
96/// the rows copied. The highest number the old log ever gave is carried
97/// over, so no number is given twice: the copy leaves the new table's
98/// counter at the highest number copied (SQLite writes the counter's row
99/// even when it copies no record), and the UPDATE raises it to the old
100/// table's, which is past that when the old log's last records are gone. A
101/// log that never held a record has no old counter, and keeps the new one.
102fn 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
118/// Brings a version-1 tenant catalog to version 2: each uuid's first store
119/// time, taken from its earliest kept version (the closest record left of
120/// it), and the index the list reads it by. The column is declared as a
121/// new catalog declares it.
122const 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
129/// Brings server.sqlite from version 2 to 3: each tenant's metadata level,
130/// NULL (`none`) for every tenant there is.
131const TENANT_METADATA: &str = "ALTER TABLE tenant ADD COLUMN metadata TEXT;";
132
133/// Brings server.sqlite from version 5 to 6: each tenant's role cap, NULL
134/// (no cap: every tenant role is allowed) for every tenant there is.
135const TENANT_ROLE_CAP: &str = "ALTER TABLE tenant ADD COLUMN role_cap TEXT;";
136
137/// The settings a tenant's administrator has set, as a new registry and an
138/// upgraded one both make them (version 7): one row for each name a tenant
139/// has set, the name and the value as `crate::settings` writes them. A
140/// name with no row has its default.
141pub(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
150/// The tables of a tenant catalog's pack files, as a new catalog and an
151/// upgraded one both make them. A pack file's row records its UTC store
152/// date (its name holds it), its rows and the rows still kept, its length,
153/// when it was made and when the catalog stopped naming it. A purge that
154/// must still rewrite a file lists it in purge_pending, and each change of
155/// which files hold which rows takes the next manifest number, which
156/// AUTOINCREMENT never gives twice, even after a row is removed: a manifest
157/// is written once under its number's name.
158pub(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
178/// Brings a version-3 tenant catalog to version 4: every version is in its
179/// object (no place), and no pack file is recorded. The columns are
180/// declared as a new catalog's version table declares them, last.
181const 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
187/// How long a statement waits for another connection's lock before it
188/// fails busy. It is rusqlite's own default, stated so it is chosen, not
189/// inherited; a caller that must not wait inside SQLite sets zero for the
190/// call and restores this.
191pub const BUSY_TIMEOUT: Duration = Duration::from_secs(5);
192
193/// How many prepared statements a catalog connection keeps for reuse.
194/// A tenant catalog's and server.sqlite's work each use fewer distinct
195/// statements than this, so none is parsed twice.
196pub(crate) const STATEMENT_CACHE: usize = 64;
197
198/// `query_row` and `execute` through the connection's cache of prepared
199/// statements: the statement is parsed on its first use and kept, reset
200/// and with its bindings cleared, for the next. The catalogs' own work
201/// runs through these; a statement that carries a key (`PRAGMA key`) is
202/// never run through them.
203pub(crate) trait Cached {
204    /// [`Connection::query_row`] on the kept statement for `sql`.
205    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    /// [`Connection::execute`] on the kept statement for `sql`.
211    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/// Why a catalog did not open.
229#[derive(Debug)]
230pub enum CatalogError {
231    /// The key is not the one the catalog was made with.
232    WrongKey,
233    /// The catalog's schema version is not one this build knows.
234    UnknownSchema(i64),
235    /// SQLite failed.
236    Sqlite(rusqlite::Error),
237    /// A file around the catalog could not be read, written or renamed.
238    Io(std::io::Error),
239    /// This process may not read and write `path`, the catalog or the
240    /// directory that holds it (where SQLite makes its `-wal` and `-shm`
241    /// files), such as when another user owns it.
242    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
284/// Opens the catalog at `path` under `key`, making it with `schema` if it
285/// is new.
286pub fn open(path: &Path, key: &Key, schema: &str) -> Result<Connection, CatalogError> {
287    // SQLite opens a file it may not write read-only and fails later with
288    // its own code, which no longer says why; asking the system first
289    // gives the path and its error.
290    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    // SQLCipher otherwise writes its own error lines to standard error, a
302    // wrong key among them; this program says what went wrong itself.
303    conn.pragma_update(None, "cipher_log_level", "NONE")?;
304    set_key(&conn, key)?;
305    // SQLCipher reads nothing until the first query, so a wrong key shows
306    // here, as a file that is not a database.
307    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    // Each setting is stated even where this build's default already
314    // matches (synchronous and secure_delete do), so a change of build
315    // flags cannot drop one; the tests read each back.
316    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            // One transaction, so a failed upgrade leaves the old version
330            // whole. A tenant catalog has a vcon table, server.sqlite a
331            // tenant table, and both an audit log.
332            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
377/// Whether this process, by its effective ids, may use `path` as `how`
378/// asks (`R_OK`, `W_OK`, `X_OK`); if not, the path and the system's error.
379pub(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    // SAFETY: `text` is a NUL-terminated path that outlives the call, and
387    // faccessat reads only it and the flags.
388    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
394/// Copies the catalog `source` is open on to a new file at `to`, kept
395/// under `key`, which must be the key `source` was opened with. It uses
396/// SQLite's online backup API and copies every page in one step, so the
397/// copy is the catalog as one commit left it, the WAL's committed frames
398/// included, while other connections go on writing. `to` must not exist:
399/// it is made empty first, so a file already there is never written over.
400/// The copy and its directory are synced.
401pub 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(&copy, key)?;
408        let backup = rusqlite::backup::Backup::new(source, &mut copy)?;
409        // A negative count copies every remaining page in this one step.
410        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
429/// Re-encrypts the catalog at `path`, kept under `old`, so that it is kept
430/// under `new`: every row, the schema and its version are written to a new
431/// file under `new`, which then replaces the old one by rename. A crash
432/// leaves either the whole old file or the whole new one, and nothing of
433/// the old file's pages is carried into the new one. A file left by an
434/// interrupted run is replaced.
435pub fn reencrypt(path: &Path, old: &Key, new: &Key) -> Result<(), CatalogError> {
436    let copy = copy_under(path, old, new)?;
437    replace(path, &copy)
438}
439
440/// Writes every row, the schema and its version of the catalog at `path`,
441/// kept under `old`, to a new file beside it kept under `new`, and returns
442/// that file's path. The old file is only read. A file left there by an
443/// interrupted run is replaced.
444pub 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    // A pragma takes no bound parameter; the version is a number read
463    // from the catalog itself.
464    conn.execute_batch(&format!("PRAGMA rekeyed.user_version = {version}"))?;
465    conn.execute("DETACH DATABASE rekeyed", [])?;
466    Ok(target)
467}
468
469/// Makes `copy` the catalog at `path`: it is synced, renamed over `path`,
470/// and the directory synced. Every connection to either file must be
471/// closed. Their WAL files must be empty, as a last close leaves them; one
472/// still holding frames would sit beside the wrong file, so it is refused.
473pub 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
496/// Makes an empty file at `path`, which must not exist, with the server's
497/// file mode: SQLite then opens it as a new database, and makes its WAL
498/// and shared-memory files with the same mode.
499fn 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
517/// `path` with `suffix` added to its file name.
518fn 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
524/// Keys the attached database `schema` as `set_key` keys the main one.
525fn 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    // SAFETY: the handle is this open connection's; the name is a valid C
529    // string and the key pointer and length are the literal's, both of
530    // which outlive the call.
531    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
540/// Gives SQLCipher the key as a raw key, never a passphrase. sqlite3_key
541/// takes the literal straight from its zeroing buffer; a PRAGMA would copy
542/// it into SQL text that is not zeroed.
543fn 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    // SAFETY: the handle is this open connection's, and the pointer and
547    // length are the literal's, which outlives the call.
548    let rc = unsafe { rusqlite::ffi::sqlite3_key(conn.handle(), literal.as_ptr().cast(), len) };
549    // sqlite3_key does not fail on an open connection, so no test reaches
550    // this check; it stays to fail closed.
551    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/// Checks on a catalog's schema, for tests.
558#[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    /// The statements `conn` holds prepared: each one's address, and its
581    /// SQL with runs of white space made one space.
582    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    /// The statements `conn` holds that SQLite has prepared again since
590    /// their first preparation, with how many times: SQLite does so when
591    /// the schema changed, or when a new value bound to a parameter may
592    /// change the query plan, and each time parses the statement anew.
593    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    /// Each statement `conn` holds, by address: its SQL with runs of white
601    /// space made one space, and how many times it was prepared again.
602    fn statements(conn: &Connection) -> BTreeMap<usize, (String, i32)> {
603        let mut kept = BTreeMap::new();
604        // SAFETY: the handle is the live connection's, used only on this
605        // thread while `conn` is borrowed, and only to walk its statements.
606        let db = unsafe { conn.handle() };
607        let mut stmt = std::ptr::null_mut();
608        loop {
609            // SAFETY: `db` is a live connection and `stmt` is null or a
610            // statement it gave, which nothing finalizes while `conn` is
611            // borrowed.
612            stmt = unsafe { rusqlite::ffi::sqlite3_next_stmt(db, stmt) };
613            if stmt.is_null() {
614                return kept;
615            }
616            // SAFETY: `stmt` is a live statement of `db`; SQLite keeps its
617            // text until the statement is finalized.
618            let text = unsafe { rusqlite::ffi::sqlite3_sql(stmt) };
619            let sql = if text.is_null() {
620                String::new()
621            } else {
622                // SAFETY: a non-null sqlite3_sql is a NUL-terminated string
623                // that lives as long as the statement.
624                let sql = unsafe { CStr::from_ptr(text) };
625                sql.to_string_lossy()
626                    .split_whitespace()
627                    .collect::<Vec<_>>()
628                    .join(" ")
629            };
630            // SAFETY: `stmt` is a live statement of `db`; reading a counter
631            // without resetting it changes nothing.
632            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    /// Whether some statement `conn` keeps starts with `start`.
644    pub(crate) fn keeps(conn: &Connection, start: &str) -> bool {
645        prepared(conn).values().any(|sql| sql.starts_with(start))
646    }
647
648    /// The columns of `table` that take NULL. `row` gives a value for each
649    /// column; each column is tried as NULL in that row, and nothing is
650    /// kept. The whole row must insert, so a refusal is the column's.
651    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    /// Reads one of SQLCipher's own settings.
692    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    /// The SQLite in the SQLCipher this build links, as a catalog reports
698    /// it: (major, minor, patch).
699    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        // RUSTSEC-2026-0459: SQLite before 3.54.0 can return uninitialized
711        // page-cache memory when a database is opened beside a -wal file of
712        // another page size. An encrypted catalog reports the SQLite that
713        // serves it, so this fails if a dependency change brings an
714        // affected one back.
715        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    /// The SQLCipher settings a catalog runs with, read back through
753    /// rusqlite's pragma helpers on a second connection to the same file,
754    /// equal what plain SQL reads on the first. `open` and `cipher_setting`
755    /// use the helpers, so the values must not differ between the two ways
756    /// of setting and reading them.
757    #[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        // Before the key, as `open` does it: the helper must not need to
773        // read an encrypted file to take the name.
774        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    /// rusqlite's pragma helpers take SQLCipher's pragma names, which
797    /// rusqlite 0.41.0 refused with "Invalid pragma" (0.41.1 stopped
798    /// checking names in a SQLCipher build). `open` and `backup` set
799    /// `cipher_log_level` through a helper, so a rusqlite that refuses the
800    /// name again must fail here, by name, not in every test that opens a
801    /// catalog.
802    #[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    /// Every dependency comes from crates.io. Until rusqlite 0.41.1 the
818    /// tests used a git fork of rusqlite, with a `[patch]` for its
819    /// libsqlite3-sys, so every build fetched from github.com; these hold
820    /// the manifests, the lockfiles and the pages to the state without it.
821    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        /// The dependencies of `manifest` that name a git repository, as
834        /// `<table>.<name>`, from the three dependency tables.
835        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    /// A catalog made at version 1 opens at the current version, its rows
979    /// kept. One with no vCon table and no tenant table changes only its
980    /// number; the tenant catalog's upgrade is tested with the Store, and
981    /// server.sqlite's with the registry.
982    #[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    /// The path a re-encryption writes before its rename.
1004    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    /// A WAL holding frames belongs to its own file: renaming that file
1077    /// without them would lose committed rows, and leaving the old one's
1078    /// beside the new file would corrupt it. Either refuses the rename.
1079    #[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), &copy), 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        // A second connection holds a write transaction open: its row is
1135        // not committed, so the copy must not hold it.
1136        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, &copy, &key).expect("backs up");
1143        writer.execute_batch("COMMIT").expect("commit");
1144        assert!(
1145            !sibling(&copy, "-wal").exists()
1146                || std::fs::metadata(sibling(&copy, "-wal"))
1147                    .expect("wal")
1148                    .len()
1149                    == 0,
1150            "the copy is whole in its own file"
1151        );
1152        let reopened = open(&copy, &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(&copy, &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, &copy, &key).expect("backs up");
1190        let bytes = std::fs::read(&copy).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(&copy, &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(&copy, b"something else").expect("write");
1211        assert!(matches!(
1212            backup(&source, &copy, &key),
1213            Err(CatalogError::Io(_))
1214        ));
1215        assert_eq!(std::fs::read(&copy).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    /// A catalog file or directory this process may not write is named,
1235    /// with the system's error, and never taken for a wrong key.
1236    #[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    /// A row that cannot insert at all would make every column look as if
1264    /// it refused NULL.
1265    #[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    /// Run while the connection is open, so the commit is still in the WAL.
1275    #[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}