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