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; version
21/// 10 added to every audit log the mark of the records a count made, the
22/// only ones a count adds to.
23/// A build refuses every version it does not know, so a catalog this
24/// build has opened is refused by release 0.4.16 and earlier.
25pub const SCHEMA_VERSION: i64 = 10;
26
27/// Brings server.sqlite from version 8 to 9: each access key's expiry and
28/// its last-used time, both NULL for every key there is. A key made
29/// before version 9 was made with no expiry, and keeps none.
30const KEY_LIFE: &str = "
31ALTER TABLE api_key ADD COLUMN expires_at INTEGER;
32ALTER TABLE api_key ADD COLUMN last_used_at INTEGER;
33";
34
35/// The sessions of the users who signed in, as a new registry and an
36/// upgraded one both make them (version 8): one row for each live session,
37/// found by the SHA-256 of its id. Neither the id nor the CSRF token is
38/// kept, only the hash of each. The times are in nanoseconds, as every
39/// time in the registry is. A session is removed when it ends, when its
40/// user's roles change or its user is deactivated, and with its tenant.
41pub(crate) const SESSIONS: &str = "
42CREATE TABLE session (
43    id_hash BLOB PRIMARY KEY NOT NULL CHECK (length(id_hash) = 32),
44    user BLOB NOT NULL,
45    tenant BLOB,
46    scopes TEXT NOT NULL,
47    created_at INTEGER NOT NULL,
48    last_seen_at INTEGER NOT NULL,
49    idle_expires_at INTEGER NOT NULL,
50    expires_at INTEGER NOT NULL,
51    idle_seconds INTEGER NOT NULL,
52    amr TEXT NOT NULL,
53    csrf_hash BLOB NOT NULL CHECK (length(csrf_hash) = 32)
54);
55CREATE INDEX session_of_user ON session (user);
56CREATE INDEX session_in_tenant ON session (tenant);
57";
58
59/// The users and their memberships in server.sqlite, as a new registry
60/// and an upgraded one both make them. A user is a person who signs in:
61/// a display label, and the identity an identity provider knows the
62/// person by (its issuer and the subject it gives), or neither for a local
63/// account. An identity belongs to one active user; a deactivated user
64/// keeps its row, for the logs that name its id. A membership gives a user
65/// roles in one tenant, or as an operator (no tenant): at most one for
66/// each, which the two indexes hold, since a UNIQUE over a NULL tenant
67/// holds nothing. Times are nanoseconds since the epoch.
68pub(crate) const USER_TABLES: &str = "
69CREATE TABLE user_account (
70    id BLOB PRIMARY KEY NOT NULL,
71    label TEXT NOT NULL,
72    issuer TEXT,
73    subject TEXT,
74    created_at INTEGER NOT NULL,
75    deactivated_at INTEGER,
76    CHECK ((issuer IS NULL) = (subject IS NULL))
77);
78CREATE UNIQUE INDEX user_account_identity ON user_account (issuer, subject)
79    WHERE issuer IS NOT NULL AND deactivated_at IS NULL;
80CREATE TABLE membership (
81    user BLOB NOT NULL,
82    tenant BLOB,
83    roles TEXT NOT NULL,
84    granted_at INTEGER NOT NULL
85);
86CREATE UNIQUE INDEX membership_in_tenant ON membership (user, tenant)
87    WHERE tenant IS NOT NULL;
88CREATE UNIQUE INDEX membership_as_operator ON membership (user)
89    WHERE tenant IS NULL;
90CREATE INDEX membership_of_tenant ON membership (tenant);
91";
92
93/// Brings a version-4 audit log to version 5: the same records under the
94/// same numbers, in a table whose status may be NULL, with NULL where
95/// version 4 wrote 0 for a record that answers no request
96/// (`audit::NO_ANSWER`). SQLite cannot drop a NOT NULL from a column, so
97/// the table is made again, by the text a new catalog makes it with, and
98/// the rows copied. The highest number the old log ever gave is carried
99/// over, so no number is given twice: the copy leaves the new table's
100/// counter at the highest number copied (SQLite writes the counter's row
101/// even when it copies no record), and the UPDATE raises it to the old
102/// table's, which is past that when the old log's last records are gone. A
103/// log that never held a record has no old counter, and keeps the new one.
104fn audit_without_zero() -> String {
105    format!(
106        "ALTER TABLE audit RENAME TO audit_v4;
107DROP INDEX audit_counted;
108{}
109INSERT INTO audit (seq, at, actor, action, target, version, status, count)
110    SELECT seq, at, actor, action, target, version, nullif(status, 0), count
111    FROM audit_v4 ORDER BY seq;
112UPDATE sqlite_sequence
113    SET seq = coalesce((SELECT seq FROM sqlite_sequence WHERE name = 'audit_v4'), seq)
114    WHERE name = 'audit';
115DROP TABLE audit_v4;",
116        crate::audit::SCHEMA
117    )
118}
119
120/// Brings a version-1 tenant catalog to version 2: each uuid's first store
121/// time, taken from its earliest kept version (the closest record left of
122/// it), and the index the list reads it by. The column is declared as a
123/// new catalog declares it.
124const VCON_STORED_AT: &str = "
125ALTER TABLE vcon ADD COLUMN stored_at INTEGER NOT NULL DEFAULT 0;
126UPDATE vcon SET stored_at =
127    coalesce((SELECT min(stored_at) FROM version WHERE version.uuid = vcon.uuid), 0);
128CREATE INDEX vcon_listed ON vcon (stored_at, uuid);
129";
130
131/// Brings server.sqlite from version 2 to 3: each tenant's metadata level,
132/// NULL (`none`) for every tenant there is.
133const TENANT_METADATA: &str = "ALTER TABLE tenant ADD COLUMN metadata TEXT;";
134
135/// Brings server.sqlite from version 5 to 6: each tenant's role cap, NULL
136/// (no cap: every tenant role is allowed) for every tenant there is.
137const TENANT_ROLE_CAP: &str = "ALTER TABLE tenant ADD COLUMN role_cap TEXT;";
138
139/// The settings a tenant's administrator has set, as a new registry and an
140/// upgraded one both make them (version 7): one row for each name a tenant
141/// has set, the name and the value as `crate::settings` writes them. A
142/// name with no row has its default.
143pub(crate) const TENANT_SETTINGS: &str = "
144CREATE TABLE tenant_setting (
145    tenant BLOB NOT NULL,
146    name TEXT NOT NULL,
147    value TEXT NOT NULL,
148    PRIMARY KEY (tenant, name)
149);
150";
151
152/// The tables of a tenant catalog's pack files, as a new catalog and an
153/// upgraded one both make them. A pack file's row records its UTC store
154/// date (its name holds it), its rows and the rows still kept, its length,
155/// when it was made and when the catalog stopped naming it. A purge that
156/// must still rewrite a file lists it in purge_pending, and each change of
157/// which files hold which rows takes the next manifest number, which
158/// AUTOINCREMENT never gives twice, even after a row is removed: a manifest
159/// is written once under its number's name.
160pub(crate) const PACK_TABLES: &str = "
161CREATE INDEX version_place ON version (place_file);
162CREATE TABLE parquet_file (
163    file_id BLOB PRIMARY KEY NOT NULL,
164    date TEXT NOT NULL,
165    rows INTEGER NOT NULL,
166    live_rows INTEGER NOT NULL,
167    bytes INTEGER NOT NULL,
168    created_at INTEGER NOT NULL,
169    unnamed_at INTEGER
170);
171CREATE TABLE purge_pending (
172    file_id BLOB PRIMARY KEY NOT NULL
173);
174CREATE TABLE manifest (
175    seq INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
176    published_at INTEGER
177);
178";
179
180/// Brings a version-3 tenant catalog to version 4: every version is in its
181/// object (no place), and no pack file is recorded. The columns are
182/// declared as a new catalog's version table declares them, last.
183const VERSION_PLACES: &str = "
184ALTER TABLE version ADD COLUMN place_file BLOB;
185ALTER TABLE version ADD COLUMN place_group INTEGER;
186ALTER TABLE version ADD COLUMN place_row INTEGER;
187";
188
189/// How long a statement waits for another connection's lock before it
190/// fails busy. It is rusqlite's own default, stated so it is chosen, not
191/// inherited; a caller that must not wait inside SQLite sets zero for the
192/// call and restores this.
193pub const BUSY_TIMEOUT: Duration = Duration::from_secs(5);
194
195/// How many prepared statements a catalog connection keeps for reuse.
196/// A tenant catalog's and server.sqlite's work each use fewer distinct
197/// statements than this, so none is parsed twice.
198pub(crate) const STATEMENT_CACHE: usize = 64;
199
200/// `query_row` and `execute` through the connection's cache of prepared
201/// statements: the statement is parsed on its first use and kept, reset
202/// and with its bindings cleared, for the next. The catalogs' own work
203/// runs through these; a statement that carries a key (`PRAGMA key`) is
204/// never run through them.
205pub(crate) trait Cached {
206    /// [`Connection::query_row`] on the kept statement for `sql`.
207    fn cached_row<T, P, F>(&self, sql: &str, params: P, f: F) -> rusqlite::Result<T>
208    where
209        P: rusqlite::Params,
210        F: FnOnce(&rusqlite::Row<'_>) -> rusqlite::Result<T>;
211
212    /// [`Connection::execute`] on the kept statement for `sql`.
213    fn cached_run<P: rusqlite::Params>(&self, sql: &str, params: P) -> rusqlite::Result<usize>;
214}
215
216impl Cached for Connection {
217    fn cached_row<T, P, F>(&self, sql: &str, params: P, f: F) -> rusqlite::Result<T>
218    where
219        P: rusqlite::Params,
220        F: FnOnce(&rusqlite::Row<'_>) -> rusqlite::Result<T>,
221    {
222        self.prepare_cached(sql)?.query_row(params, f)
223    }
224
225    fn cached_run<P: rusqlite::Params>(&self, sql: &str, params: P) -> rusqlite::Result<usize> {
226        self.prepare_cached(sql)?.execute(params)
227    }
228}
229
230/// Why a catalog did not open.
231#[derive(Debug)]
232pub enum CatalogError {
233    /// The key is not the one the catalog was made with.
234    WrongKey,
235    /// The catalog's schema version is not one this build knows.
236    UnknownSchema(i64),
237    /// SQLite failed.
238    Sqlite(rusqlite::Error),
239    /// A file around the catalog could not be read, written or renamed.
240    Io(std::io::Error),
241    /// This process may not read and write `path`, the catalog or the
242    /// directory that holds it (where SQLite makes its `-wal` and `-shm`
243    /// files), such as when another user owns it.
244    Access {
245        path: PathBuf,
246        error: std::io::Error,
247    },
248}
249
250impl std::fmt::Display for CatalogError {
251    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
252        match self {
253            CatalogError::WrongKey => {
254                f.write_str("the key is not the one the catalog was made with")
255            }
256            CatalogError::UnknownSchema(version) => {
257                write!(f, "schema version {version} is not one this build knows")
258            }
259            CatalogError::Sqlite(_) => f.write_str("sqlite failed"),
260            CatalogError::Io(_) => {
261                f.write_str("a file around the catalog could not be read, written or renamed")
262            }
263            CatalogError::Access { path, .. } => {
264                write!(f, "this process may not read and write {}", path.display())
265            }
266        }
267    }
268}
269
270impl std::error::Error for CatalogError {
271    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
272        match self {
273            CatalogError::Sqlite(e) => Some(e),
274            CatalogError::Io(e) | CatalogError::Access { error: e, .. } => Some(e),
275            CatalogError::WrongKey | CatalogError::UnknownSchema(_) => None,
276        }
277    }
278}
279
280impl From<rusqlite::Error> for CatalogError {
281    fn from(e: rusqlite::Error) -> CatalogError {
282        CatalogError::Sqlite(e)
283    }
284}
285
286/// Opens the catalog at `path` under `key`, making it with `schema` if it
287/// is new.
288pub fn open(path: &Path, key: &Key, schema: &str) -> Result<Connection, CatalogError> {
289    // SQLite opens a file it may not write read-only and fails later with
290    // its own code, which no longer says why; asking the system first
291    // gives the path and its error.
292    if let Some(dir) = path.parent() {
293        may_use(dir, libc::W_OK | libc::X_OK)?;
294    }
295    if path.exists() {
296        may_use(path, libc::R_OK | libc::W_OK)?;
297    } else {
298        make_file(path)?;
299    }
300    let conn = Connection::open(path)?;
301    conn.busy_timeout(BUSY_TIMEOUT)?;
302    conn.set_prepared_statement_cache_capacity(STATEMENT_CACHE);
303    // SQLCipher otherwise writes its own error lines to standard error, a
304    // wrong key among them; this program says what went wrong itself.
305    conn.pragma_update(None, "cipher_log_level", "NONE")?;
306    set_key(&conn, key)?;
307    // SQLCipher reads nothing until the first query, so a wrong key shows
308    // here, as a file that is not a database.
309    match conn.query_row("SELECT count(*) FROM sqlite_master", [], |_| Ok(())) {
310        Err(e) if e.sqlite_error_code() == Some(ErrorCode::NotADatabase) => {
311            return Err(CatalogError::WrongKey);
312        }
313        other => other?,
314    }
315    // Each setting is stated even where this build's default already
316    // matches (synchronous and secure_delete do), so a change of build
317    // flags cannot drop one; the tests read each back.
318    let mode: String = conn.pragma_update_and_check(None, "journal_mode", "WAL", |r| r.get(0))?;
319    debug_assert_eq!(mode, "wal");
320    conn.pragma_update(None, "synchronous", "FULL")?;
321    conn.pragma_update(None, "secure_delete", "ON")?;
322    conn.pragma_update(None, "temp_store", "MEMORY")?;
323    match conn.pragma_query_value(None, "user_version", |r| r.get(0))? {
324        0 => {
325            let tx = conn.unchecked_transaction()?;
326            tx.execute_batch(schema)?;
327            tx.pragma_update(None, "user_version", SCHEMA_VERSION)?;
328            tx.commit()?;
329        }
330        from @ 1..=9 => {
331            // One transaction, so a failed upgrade leaves the old version
332            // whole. A tenant catalog has a vcon table, server.sqlite a
333            // tenant table, and both an audit log.
334            let tx = conn.unchecked_transaction()?;
335            let has = |table: &str| -> rusqlite::Result<bool> {
336                tx.query_row(
337                    "SELECT count(*) > 0 FROM sqlite_master WHERE type = 'table' AND name = ?1",
338                    [table],
339                    |r| r.get(0),
340                )
341            };
342            if from < 2 && has("vcon")? {
343                tx.execute_batch(VCON_STORED_AT)?;
344            }
345            if from < 3 && has("tenant")? {
346                tx.execute_batch(TENANT_METADATA)?;
347            }
348            if from < 4 && has("version")? {
349                tx.execute_batch(VERSION_PLACES)?;
350                tx.execute_batch(PACK_TABLES)?;
351            }
352            if from < 5 && has("tenant")? {
353                tx.execute_batch(USER_TABLES)?;
354            }
355            if from < 5 && has("audit")? {
356                tx.execute_batch(&audit_without_zero())?;
357            }
358            if from < 6 && has("tenant")? {
359                tx.execute_batch(TENANT_ROLE_CAP)?;
360            }
361            if from < 7 && has("tenant")? {
362                tx.execute_batch(TENANT_SETTINGS)?;
363            }
364            if from < 8 && has("tenant")? {
365                tx.execute_batch(SESSIONS)?;
366            }
367            if from < 9 && has("api_key")? {
368                tx.execute_batch(KEY_LIFE)?;
369            }
370            if from < 10 && has("audit")? {
371                // A log older than 5 was made again above from this
372                // build's text, the column included.
373                if from >= 5 {
374                    tx.execute_batch(crate::audit::COUNTED_COLUMN)?;
375                }
376                tx.execute_batch(crate::audit::COUNTED_BEFORE_10)?;
377            }
378            tx.pragma_update(None, "user_version", SCHEMA_VERSION)?;
379            tx.commit()?;
380        }
381        SCHEMA_VERSION => {}
382        other => return Err(CatalogError::UnknownSchema(other)),
383    }
384    Ok(conn)
385}
386
387/// Whether this process, by its effective ids, may use `path` as `how`
388/// asks (`R_OK`, `W_OK`, `X_OK`); if not, the path and the system's error.
389pub(crate) fn may_use(path: &Path, how: c_int) -> Result<(), CatalogError> {
390    let denied = |error| CatalogError::Access {
391        path: path.to_owned(),
392        error,
393    };
394    let text = std::ffi::CString::new(path.as_os_str().as_encoded_bytes())
395        .map_err(|_| denied(std::io::ErrorKind::InvalidInput.into()))?;
396    // SAFETY: `text` is a NUL-terminated path that outlives the call, and
397    // faccessat reads only it and the flags.
398    if unsafe { libc::faccessat(libc::AT_FDCWD, text.as_ptr(), how, libc::AT_EACCESS) } != 0 {
399        return Err(denied(std::io::Error::last_os_error()));
400    }
401    Ok(())
402}
403
404/// Copies the catalog `source` is open on to a new file at `to`, kept
405/// under `key`, which must be the key `source` was opened with. It uses
406/// SQLite's online backup API and copies every page in one step, so the
407/// copy is the catalog as one commit left it, the WAL's committed frames
408/// included, while other connections go on writing. `to` must not exist:
409/// it is made empty first, so a file already there is never written over.
410/// The copy and its directory are synced.
411pub fn backup(source: &Connection, to: &Path, key: &Key) -> Result<(), CatalogError> {
412    let io = CatalogError::Io;
413    make_file(to)?;
414    {
415        let mut copy = Connection::open(to)?;
416        copy.pragma_update(None, "cipher_log_level", "NONE")?;
417        set_key(&copy, key)?;
418        let backup = rusqlite::backup::Backup::new(source, &mut copy)?;
419        // A negative count copies every remaining page in this one step.
420        match backup.step(-1)? {
421            rusqlite::backup::StepResult::Done => {}
422            _ => {
423                return Err(io(std::io::Error::other(
424                    "the catalog was busy and could not be copied in one step",
425                )));
426            }
427        }
428    }
429    std::fs::File::open(to)
430        .and_then(|f| f.sync_all())
431        .map_err(io)?;
432    let dir = to.parent().unwrap_or(Path::new("."));
433    std::fs::File::open(dir)
434        .and_then(|f| f.sync_all())
435        .map_err(io)?;
436    Ok(())
437}
438
439/// Re-encrypts the catalog at `path`, kept under `old`, so that it is kept
440/// under `new`: every row, the schema and its version are written to a new
441/// file under `new`, which then replaces the old one by rename. A crash
442/// leaves either the whole old file or the whole new one, and nothing of
443/// the old file's pages is carried into the new one. A file left by an
444/// interrupted run is replaced.
445pub fn reencrypt(path: &Path, old: &Key, new: &Key) -> Result<(), CatalogError> {
446    let copy = copy_under(path, old, new)?;
447    replace(path, &copy)
448}
449
450/// Writes every row, the schema and its version of the catalog at `path`,
451/// kept under `old`, to a new file beside it kept under `new`, and returns
452/// that file's path. The old file is only read. A file left there by an
453/// interrupted run is replaced.
454pub fn copy_under(path: &Path, old: &Key, new: &Key) -> Result<PathBuf, CatalogError> {
455    let target = sibling(path, ".rekey");
456    for stale in [
457        target.clone(),
458        sibling(&target, "-wal"),
459        sibling(&target, "-shm"),
460    ] {
461        remove_if_there(&stale)?;
462    }
463    make_file(&target)?;
464    let conn = open(path, old, "")?;
465    let version: i64 = conn.pragma_query_value(None, "user_version", |r| r.get(0))?;
466    let target_text = target
467        .to_str()
468        .ok_or_else(|| CatalogError::Io(std::io::Error::other("the catalog path is not UTF-8")))?;
469    conn.execute("ATTACH DATABASE ?1 AS rekeyed", [target_text])?;
470    set_key_of(&conn, c"rekeyed", new)?;
471    conn.query_row("SELECT sqlcipher_export('rekeyed')", [], |_| Ok(()))?;
472    // A pragma takes no bound parameter; the version is a number read
473    // from the catalog itself.
474    conn.execute_batch(&format!("PRAGMA rekeyed.user_version = {version}"))?;
475    conn.execute("DETACH DATABASE rekeyed", [])?;
476    Ok(target)
477}
478
479/// Makes `copy` the catalog at `path`: it is synced, renamed over `path`,
480/// and the directory synced. Every connection to either file must be
481/// closed. Their WAL files must be empty, as a last close leaves them; one
482/// still holding frames would sit beside the wrong file, so it is refused.
483pub fn replace(path: &Path, copy: &Path) -> Result<(), CatalogError> {
484    for file in [path, copy] {
485        let wal = sibling(file, "-wal");
486        if std::fs::metadata(&wal).is_ok_and(|m| m.len() > 0) {
487            return Err(CatalogError::Io(std::io::Error::other(
488                "a catalog's WAL was not emptied",
489            )));
490        }
491        remove_if_there(&wal)?;
492        remove_if_there(&sibling(file, "-shm"))?;
493    }
494    let io = CatalogError::Io;
495    std::fs::File::open(copy)
496        .and_then(|f| f.sync_all())
497        .map_err(io)?;
498    std::fs::rename(copy, path).map_err(io)?;
499    let dir = path.parent().unwrap_or(Path::new("."));
500    std::fs::File::open(dir)
501        .and_then(|f| f.sync_all())
502        .map_err(io)?;
503    Ok(())
504}
505
506/// Makes an empty file at `path`, which must not exist, with the server's
507/// file mode: SQLite then opens it as a new database, and makes its WAL
508/// and shared-memory files with the same mode.
509fn make_file(path: &Path) -> Result<(), CatalogError> {
510    use std::os::unix::fs::OpenOptionsExt;
511    std::fs::OpenOptions::new()
512        .write(true)
513        .create_new(true)
514        .mode(crate::fs::FILE_MODE)
515        .open(path)
516        .map(drop)
517        .map_err(CatalogError::Io)
518}
519
520fn remove_if_there(file: &Path) -> Result<(), CatalogError> {
521    match std::fs::remove_file(file) {
522        Err(e) if e.kind() != std::io::ErrorKind::NotFound => Err(CatalogError::Io(e)),
523        _ => Ok(()),
524    }
525}
526
527/// `path` with `suffix` added to its file name.
528pub(crate) fn sibling(path: &Path, suffix: &str) -> PathBuf {
529    let mut name = path.as_os_str().to_owned();
530    name.push(suffix);
531    PathBuf::from(name)
532}
533
534/// Keys the attached database `schema` as `set_key` keys the main one.
535fn set_key_of(conn: &Connection, schema: &std::ffi::CStr, key: &Key) -> Result<(), CatalogError> {
536    let literal = key.sqlcipher_raw();
537    let len = c_int::try_from(literal.len()).expect("a 67-byte literal");
538    // SAFETY: the handle is this open connection's; the name is a valid C
539    // string and the key pointer and length are the literal's, both of
540    // which outlive the call.
541    let rc = unsafe {
542        rusqlite::ffi::sqlite3_key_v2(conn.handle(), schema.as_ptr(), literal.as_ptr().cast(), len)
543    };
544    if rc != rusqlite::ffi::SQLITE_OK {
545        return Err(rusqlite::Error::SqliteFailure(rusqlite::ffi::Error::new(rc), None).into());
546    }
547    Ok(())
548}
549
550/// Gives SQLCipher the key as a raw key, never a passphrase. sqlite3_key
551/// takes the literal straight from its zeroing buffer; a PRAGMA would copy
552/// it into SQL text that is not zeroed.
553fn set_key(conn: &Connection, key: &Key) -> Result<(), CatalogError> {
554    let literal = key.sqlcipher_raw();
555    let len = c_int::try_from(literal.len()).expect("a 67-byte literal");
556    // SAFETY: the handle is this open connection's, and the pointer and
557    // length are the literal's, which outlives the call.
558    let rc = unsafe { rusqlite::ffi::sqlite3_key(conn.handle(), literal.as_ptr().cast(), len) };
559    // sqlite3_key does not fail on an open connection, so no test reaches
560    // this check; it stays to fail closed.
561    if rc != rusqlite::ffi::SQLITE_OK {
562        return Err(rusqlite::Error::SqliteFailure(rusqlite::ffi::Error::new(rc), None).into());
563    }
564    Ok(())
565}
566
567/// Checks on a catalog's schema, for tests.
568#[cfg(test)]
569mod v5_tests;
570
571#[cfg(test)]
572mod v6_tests;
573
574#[cfg(test)]
575mod v7_tests;
576
577#[cfg(test)]
578mod v8_tests;
579
580#[cfg(test)]
581mod v9_tests;
582
583#[cfg(test)]
584mod v10_tests;
585
586#[cfg(test)]
587pub(crate) mod testing {
588    use std::collections::BTreeMap;
589    use std::ffi::CStr;
590
591    use rusqlite::Connection;
592
593    /// The statements `conn` holds prepared: each one's address, and its
594    /// SQL with runs of white space made one space.
595    pub(crate) fn prepared(conn: &Connection) -> BTreeMap<usize, String> {
596        statements(conn)
597            .into_iter()
598            .map(|(at, (sql, _))| (at, sql))
599            .collect()
600    }
601
602    /// The statements `conn` holds that SQLite has prepared again since
603    /// their first preparation, with how many times: SQLite does so when
604    /// the schema changed, or when a new value bound to a parameter may
605    /// change the query plan, and each time parses the statement anew.
606    pub(crate) fn reprepared(conn: &Connection) -> Vec<(String, i32)> {
607        statements(conn)
608            .into_values()
609            .filter(|(_, again)| *again > 0)
610            .collect()
611    }
612
613    /// Each statement `conn` holds, by address: its SQL with runs of white
614    /// space made one space, and how many times it was prepared again.
615    fn statements(conn: &Connection) -> BTreeMap<usize, (String, i32)> {
616        let mut kept = BTreeMap::new();
617        // SAFETY: the handle is the live connection's, used only on this
618        // thread while `conn` is borrowed, and only to walk its statements.
619        let db = unsafe { conn.handle() };
620        let mut stmt = std::ptr::null_mut();
621        loop {
622            // SAFETY: `db` is a live connection and `stmt` is null or a
623            // statement it gave, which nothing finalizes while `conn` is
624            // borrowed.
625            stmt = unsafe { rusqlite::ffi::sqlite3_next_stmt(db, stmt) };
626            if stmt.is_null() {
627                return kept;
628            }
629            // SAFETY: `stmt` is a live statement of `db`; SQLite keeps its
630            // text until the statement is finalized.
631            let text = unsafe { rusqlite::ffi::sqlite3_sql(stmt) };
632            let sql = if text.is_null() {
633                String::new()
634            } else {
635                // SAFETY: a non-null sqlite3_sql is a NUL-terminated string
636                // that lives as long as the statement.
637                let sql = unsafe { CStr::from_ptr(text) };
638                sql.to_string_lossy()
639                    .split_whitespace()
640                    .collect::<Vec<_>>()
641                    .join(" ")
642            };
643            // SAFETY: `stmt` is a live statement of `db`; reading a counter
644            // without resetting it changes nothing.
645            let again = unsafe {
646                rusqlite::ffi::sqlite3_stmt_status(
647                    stmt,
648                    rusqlite::ffi::SQLITE_STMTSTATUS_REPREPARE,
649                    0,
650                )
651            };
652            kept.insert(stmt as usize, (sql, again));
653        }
654    }
655
656    /// Whether some statement `conn` keeps starts with `start`.
657    pub(crate) fn keeps(conn: &Connection, start: &str) -> bool {
658        prepared(conn).values().any(|sql| sql.starts_with(start))
659    }
660
661    /// The columns of `table` that take NULL. `row` gives a value for each
662    /// column; each column is tried as NULL in that row, and nothing is
663    /// kept. The whole row must insert, so a refusal is the column's.
664    pub(crate) fn columns_taking_null(
665        conn: &Connection,
666        table: &str,
667        row: &[(&str, &str)],
668    ) -> Vec<String> {
669        let insert = |empty: Option<&str>| {
670            let columns: Vec<&str> = row.iter().map(|(c, _)| *c).collect();
671            let values: Vec<&str> = row
672                .iter()
673                .map(|(c, v)| if Some(*c) == empty { "NULL" } else { *v })
674                .collect();
675            let sql = format!(
676                "INSERT INTO {table} ({}) VALUES ({})",
677                columns.join(", "),
678                values.join(", ")
679            );
680            let tx = conn.unchecked_transaction().expect("begin");
681            let taken = tx.execute(&sql, []).is_ok();
682            drop(tx);
683            taken
684        };
685        assert!(insert(None), "a whole {table} row inserts");
686        row.iter()
687            .filter(|(column, _)| insert(Some(column)))
688            .map(|(column, _)| format!("{table}.{column}"))
689            .collect()
690    }
691}
692
693#[cfg(test)]
694pub(crate) mod tests {
695    use super::*;
696
697    const SCHEMA: &str = "CREATE TABLE note (text TEXT NOT NULL);";
698    const MARKER: &str = "plain-record-marker-5f3c9a";
699
700    fn path(dir: &tempfile::TempDir) -> std::path::PathBuf {
701        dir.path().join("catalog.sqlite")
702    }
703
704    /// Reads one of SQLCipher's own settings.
705    pub(crate) fn cipher_setting(conn: &Connection, name: &str) -> String {
706        conn.pragma_query_value(None, name, |r| r.get(0))
707            .expect(name)
708    }
709
710    /// The SQLite in the SQLCipher this build links, as a catalog reports
711    /// it: (major, minor, patch).
712    fn linked_sqlite(conn: &Connection) -> (u32, u32, u32) {
713        let text: String = conn
714            .query_row("SELECT sqlite_version()", [], |r| r.get(0))
715            .expect("the version");
716        let mut parts = text.split('.').map(|part| part.parse().expect("a number"));
717        let mut next = || parts.next().expect("three parts");
718        (next(), next(), next())
719    }
720
721    #[test]
722    fn the_linked_sqlite_is_not_one_cve_2026_119375_affects() {
723        // RUSTSEC-2026-0459: SQLite before 3.54.0 can return uninitialized
724        // page-cache memory when a database is opened beside a -wal file of
725        // another page size. An encrypted catalog reports the SQLite that
726        // serves it, so this fails if a dependency change brings an
727        // affected one back.
728        let dir = tempfile::tempdir().expect("temp dir");
729        let key = Key::generate().expect("key");
730        let conn = open(&path(&dir), &key, SCHEMA).expect("opens");
731        let linked = linked_sqlite(&conn);
732        assert!(linked >= (3, 54, 0), "SQLite {linked:?} is before 3.54.0");
733        assert_eq!(
734            rusqlite::version_number(),
735            i32::try_from(linked.0 * 1_000_000 + linked.1 * 1_000 + linked.2).expect("fits"),
736            "the library rusqlite links is the one the catalog runs on"
737        );
738        let cipher = cipher_setting(&conn, "cipher_version");
739        assert!(
740            cipher.starts_with("4."),
741            "SQLCipher 4, whose file format release 0.4.3 wrote: {cipher}"
742        );
743    }
744
745    #[test]
746    fn a_catalog_runs_with_the_required_settings() {
747        let dir = tempfile::tempdir().expect("temp dir");
748        let key = Key::generate().expect("key");
749        let conn = open(&path(&dir), &key, SCHEMA).expect("opens");
750        let text = |p: &str| -> String { conn.pragma_query_value(None, p, |r| r.get(0)).expect(p) };
751        let number = |p: &str| -> i64 { conn.pragma_query_value(None, p, |r| r.get(0)).expect(p) };
752        assert_eq!(text("journal_mode"), "wal");
753        assert_eq!(number("synchronous"), 2, "FULL");
754        assert_eq!(number("secure_delete"), 1);
755        assert_eq!(number("temp_store"), 2, "MEMORY");
756        assert_eq!(number("busy_timeout"), 5000, "milliseconds");
757        assert_eq!(cipher_setting(&conn, "cipher_provider"), "openssl");
758        assert_eq!(
759            cipher_setting(&conn, "cipher_log_level"),
760            "NONE",
761            "SQLCipher writes no log of its own"
762        );
763    }
764
765    /// The SQLCipher settings a catalog runs with, read back through
766    /// rusqlite's pragma helpers on a second connection to the same file,
767    /// equal what plain SQL reads on the first. `open` and `cipher_setting`
768    /// use the helpers, so the values must not differ between the two ways
769    /// of setting and reading them.
770    #[test]
771    fn sqlcipher_settings_read_the_same_through_the_pragma_helpers() {
772        let dir = tempfile::tempdir().expect("temp dir");
773        let key = Key::generate().expect("key");
774        let conn = open(&path(&dir), &key, SCHEMA).expect("opens");
775        let names = ["cipher_log_level", "cipher_provider", "cipher_page_size"];
776        let plain: Vec<String> = names
777            .iter()
778            .map(|n| {
779                conn.query_row(&format!("PRAGMA {n}"), [], |r| r.get(0))
780                    .unwrap_or_else(|e| panic!("{n} as plain SQL: {e}"))
781            })
782            .collect();
783
784        let helpers = Connection::open(path(&dir)).expect("opens again");
785        // Before the key, as `open` does it: the helper must not need to
786        // read an encrypted file to take the name.
787        helpers
788            .pragma_update(None, "cipher_log_level", "NONE")
789            .expect("cipher_log_level through pragma_update");
790        set_key(&helpers, &key).expect("keyed");
791        let notes: i64 = helpers
792            .query_row("SELECT count(*) FROM note", [], |r| r.get(0))
793            .expect("the key opens the same catalog");
794        assert_eq!(notes, 0);
795        let read: Vec<String> = names
796            .iter()
797            .map(|n| {
798                helpers
799                    .pragma_query_value(None, n, |r| r.get(0))
800                    .unwrap_or_else(|e| panic!("{n} through pragma_query_value: {e}"))
801            })
802            .collect();
803        assert_eq!(read, plain);
804        assert_eq!(plain[0], "NONE");
805        let ours: Vec<String> = names.iter().map(|n| cipher_setting(&conn, n)).collect();
806        assert_eq!(ours, plain, "cipher_setting reads what plain SQL reads");
807    }
808
809    /// rusqlite's pragma helpers take SQLCipher's pragma names, which
810    /// rusqlite 0.41.0 refused with "Invalid pragma" (0.41.1 stopped
811    /// checking names in a SQLCipher build). `open` and `backup` set
812    /// `cipher_log_level` through a helper, so a rusqlite that refuses the
813    /// name again must fail here, by name, not in every test that opens a
814    /// catalog.
815    #[test]
816    fn rusqlite_takes_sqlcipher_names_in_its_pragma_helpers() {
817        let conn = Connection::open_in_memory().expect("opens");
818        let taken = conn.pragma_update(None, "cipher_log_level", "NONE");
819        assert!(
820            taken.is_ok(),
821            "this rusqlite refuses SQLCipher's pragma names ({taken:?}): catalog::open and \
822             catalog::backup set cipher_log_level through pragma_update"
823        );
824        let level: String = conn
825            .pragma_query_value(None, "cipher_log_level", |r| r.get(0))
826            .expect("cipher_log_level through pragma_query_value");
827        assert_eq!(level, "NONE", "and reads back what was set");
828    }
829
830    /// Every dependency comes from crates.io. Until rusqlite 0.41.1 the
831    /// tests used a git fork of rusqlite, with a `[patch]` for its
832    /// libsqlite3-sys, so every build fetched from github.com; these hold
833    /// the manifests, the lockfiles and the pages to the state without it.
834    mod sources {
835        use std::path::PathBuf;
836
837        fn read(relative: &str) -> String {
838            let path = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join(relative);
839            std::fs::read_to_string(&path).unwrap_or_else(|e| panic!("{}: {e}", path.display()))
840        }
841
842        fn table(text: &str) -> toml::Table {
843            text.parse().expect("toml")
844        }
845
846        /// The dependencies of `manifest` that name a git repository, as
847        /// `<table>.<name>`, from the three dependency tables.
848        fn git_dependencies(manifest: &toml::Table) -> Vec<String> {
849            ["dependencies", "dev-dependencies", "build-dependencies"]
850                .iter()
851                .filter_map(|kind| Some((kind, manifest.get(*kind)?.as_table()?)))
852                .flat_map(|(kind, deps)| {
853                    deps.iter()
854                        .filter(|(_, spec)| spec.get("git").is_some())
855                        .map(move |(name, _)| format!("{kind}.{name}"))
856                })
857                .collect()
858        }
859
860        #[test]
861        fn the_git_dependency_reader_finds_one_in_any_table() {
862            let manifest = table(
863                "[dependencies]\nplain = \"1\"\n\
864                 [dev-dependencies]\nforked = { package = \"plain\", git = \"https://example.com/forked\" }\n\
865                 [build-dependencies]\nother = { git = \"https://example.com/other\", rev = \"abc\" }\n",
866            );
867            assert_eq!(
868                git_dependencies(&manifest),
869                ["dev-dependencies.forked", "build-dependencies.other"],
870                "each git dependency, with its table"
871            );
872            assert!(
873                git_dependencies(&table("[dependencies]\nplain = \"1\"\n")).is_empty(),
874                "a crates.io dependency is not one"
875            );
876            assert!(
877                git_dependencies(&table("[package]\nname = \"none\"\n")).is_empty(),
878                "a manifest with no dependency table has none"
879            );
880        }
881
882        #[test]
883        fn no_dependency_comes_from_a_git_repository() {
884            let manifest = table(&read("Cargo.toml"));
885            assert_eq!(
886                git_dependencies(&manifest),
887                [] as [&str; 0],
888                "vcon-server's Cargo.toml"
889            );
890            let server = &manifest["dependencies"]["rusqlite"];
891            assert!(
892                server.get("version").is_some()
893                    && server.get("git").is_none()
894                    && server.get("path").is_none(),
895                "the server's rusqlite comes from crates.io"
896            );
897            assert!(
898                manifest["dev-dependencies"].get("rusqlite_fork").is_none(),
899                "the fork is gone"
900            );
901        }
902
903        #[test]
904        fn the_workspace_patches_nothing() {
905            let workspace = table(&read("../../Cargo.toml"));
906            assert!(
907                workspace.get("patch").is_none(),
908                "no [patch] table: {:?}",
909                workspace.get("patch")
910            );
911        }
912
913        #[test]
914        fn no_lockfile_names_a_git_source() {
915            for lockfile in ["../../Cargo.lock", "../../fuzz/Cargo.lock"] {
916                let lock = read(lockfile);
917                let git: Vec<&str> = lock
918                    .lines()
919                    .filter(|l| l.starts_with("source = \"git+"))
920                    .collect();
921                assert_eq!(git, [] as [&str; 0], "{lockfile}");
922            }
923        }
924
925        #[test]
926        fn the_pages_name_no_fork() {
927            let development = read("../../website/content/docs/development.md");
928            assert!(
929                !development.contains("\n## Test dependency from a fork\n"),
930                "the Development page's section on the fork is gone"
931            );
932            let install = read("../../website/content/docs/install.md");
933            let build = install
934                .split("\n## ")
935                .find(|s| s.starts_with("Build from source\n"))
936                .expect("a Build from source section");
937            assert!(
938                build.contains("mkdir -p .cargo && cargo vendor >> .cargo/config.toml\n"),
939                "the vendoring command"
940            );
941            assert!(build.contains("cargo build --release --offline\n"));
942            for page in [&development, &install] {
943                assert!(!page.contains("NormB/rusqlite"), "no page names the fork");
944                assert!(!page.contains("rusqlite fork"), "no page speaks of a fork");
945            }
946            let release = install
947                .split("\n## ")
948                .find(|s| s.starts_with("Download a release\n"))
949                .expect("a release section");
950            assert!(
951                release.contains("crates.io"),
952                "says where the release's rusqlite comes from"
953            );
954        }
955    }
956
957    #[test]
958    fn the_schema_is_made_once_at_the_current_version() {
959        let dir = tempfile::tempdir().expect("temp dir");
960        let key = Key::generate().expect("key");
961        let conn = open(&path(&dir), &key, SCHEMA).expect("opens");
962        let version: i64 = conn
963            .pragma_query_value(None, "user_version", |r| r.get(0))
964            .expect("version");
965        assert_eq!(version, SCHEMA_VERSION);
966        conn.execute("INSERT INTO note (text) VALUES ('kept')", [])
967            .expect("insert");
968        drop(conn);
969        let conn =
970            open(&path(&dir), &key, SCHEMA).expect("reopens without making the schema again");
971        let kept: String = conn
972            .query_row("SELECT text FROM note", [], |r| r.get(0))
973            .expect("row");
974        assert_eq!(kept, "kept");
975    }
976
977    #[test]
978    fn an_unknown_schema_version_is_refused() {
979        let dir = tempfile::tempdir().expect("temp dir");
980        let key = Key::generate().expect("key");
981        let conn = open(&path(&dir), &key, SCHEMA).expect("opens");
982        conn.pragma_update(None, "user_version", SCHEMA_VERSION + 1)
983            .expect("set version");
984        drop(conn);
985        assert!(matches!(
986            open(&path(&dir), &key, SCHEMA),
987            Err(CatalogError::UnknownSchema(v)) if v == SCHEMA_VERSION + 1
988        ));
989    }
990
991    /// A catalog made at version 1 opens at the current version, its rows
992    /// kept. One with no vCon table and no tenant table changes only its
993    /// number; the tenant catalog's upgrade is tested with the Store, and
994    /// server.sqlite's with the registry.
995    #[test]
996    fn a_version_1_catalog_is_upgraded_to_the_current_version() {
997        let dir = tempfile::tempdir().expect("temp dir");
998        let key = Key::generate().expect("key");
999        let conn = open(&path(&dir), &key, SCHEMA).expect("opens");
1000        conn.execute("INSERT INTO note (text) VALUES ('kept')", [])
1001            .expect("insert");
1002        conn.pragma_update(None, "user_version", 1)
1003            .expect("set version");
1004        drop(conn);
1005        let conn = open(&path(&dir), &key, "").expect("upgrades");
1006        let version: i64 = conn
1007            .pragma_query_value(None, "user_version", |r| r.get(0))
1008            .expect("version");
1009        assert_eq!(
1010            version, SCHEMA_VERSION,
1011            "the catalog is brought to the current version"
1012        );
1013        assert_eq!(notes(&conn), vec!["kept"]);
1014    }
1015
1016    /// The path a re-encryption writes before its rename.
1017    fn rekeyed(dir: &tempfile::TempDir) -> std::path::PathBuf {
1018        dir.path().join("catalog.sqlite.rekey")
1019    }
1020
1021    fn notes(conn: &Connection) -> Vec<String> {
1022        conn.prepare("SELECT text FROM note ORDER BY rowid")
1023            .expect("prepare")
1024            .query_map([], |r| r.get(0))
1025            .expect("query")
1026            .collect::<Result<_, _>>()
1027            .expect("rows")
1028    }
1029
1030    #[test]
1031    fn a_reencrypted_catalog_opens_under_the_new_key_only_and_keeps_every_row() {
1032        let dir = tempfile::tempdir().expect("temp dir");
1033        let (old, new) = (Key::generate().expect("key"), Key::generate().expect("key"));
1034        let conn = open(&path(&dir), &old, SCHEMA).expect("opens");
1035        for n in 0..300 {
1036            conn.execute("INSERT INTO note (text) VALUES (?1)", [format!("note {n}")])
1037                .expect("insert");
1038        }
1039        drop(conn);
1040        reencrypt(&path(&dir), &old, &new).expect("re-encrypted");
1041        let raw = std::fs::read(path(&dir)).expect("the file");
1042        assert!(
1043            !raw.windows(8).any(|w| w == b"note 299"),
1044            "no row is written in the clear"
1045        );
1046        assert!(matches!(
1047            open(&path(&dir), &old, SCHEMA),
1048            Err(CatalogError::WrongKey)
1049        ));
1050        let conn = open(&path(&dir), &new, SCHEMA).expect("opens under the new key");
1051        let kept = notes(&conn);
1052        assert_eq!(
1053            kept,
1054            (0..300).map(|n| format!("note {n}")).collect::<Vec<_>>(),
1055            "every row is kept, each with its own text, in order"
1056        );
1057        let version: i64 = conn
1058            .pragma_query_value(None, "user_version", |r| r.get(0))
1059            .expect("version");
1060        assert_eq!(version, SCHEMA_VERSION, "the schema version is kept");
1061        let mode: String = conn
1062            .pragma_query_value(None, "journal_mode", |r| r.get(0))
1063            .expect("mode");
1064        assert_eq!(mode, "wal");
1065        drop(conn);
1066        let mut left: Vec<String> = std::fs::read_dir(dir.path())
1067            .expect("list")
1068            .map(|e| e.expect("entry").file_name().to_string_lossy().into_owned())
1069            .collect();
1070        left.sort();
1071        assert_eq!(left, ["catalog.sqlite"], "no temporary file is left");
1072    }
1073
1074    #[test]
1075    fn a_file_left_by_an_interrupted_reencryption_is_replaced() {
1076        let dir = tempfile::tempdir().expect("temp dir");
1077        let (old, new) = (Key::generate().expect("key"), Key::generate().expect("key"));
1078        let conn = open(&path(&dir), &old, SCHEMA).expect("opens");
1079        conn.execute("INSERT INTO note (text) VALUES ('kept')", [])
1080            .expect("insert");
1081        drop(conn);
1082        std::fs::write(rekeyed(&dir), b"half a file").expect("leftover");
1083        reencrypt(&path(&dir), &old, &new).expect("re-encrypted");
1084        let conn = open(&path(&dir), &new, SCHEMA).expect("opens");
1085        assert_eq!(notes(&conn), ["kept"]);
1086        assert!(!rekeyed(&dir).exists());
1087    }
1088
1089    /// A WAL holding frames belongs to its own file: renaming that file
1090    /// without them would lose committed rows, and leaving the old one's
1091    /// beside the new file would corrupt it. Either refuses the rename.
1092    #[test]
1093    fn a_replace_refuses_while_either_wal_holds_frames() {
1094        let dir = tempfile::tempdir().expect("temp dir");
1095        let key = Key::generate().expect("key");
1096        let copy = dir.path().join("catalog.sqlite.rekey");
1097        for busy in [path(&dir), copy.clone()] {
1098            for file in [path(&dir), copy.clone()] {
1099                for leftover in ["", "-wal", "-shm"] {
1100                    let _ = std::fs::remove_file(sibling(&file, leftover));
1101                }
1102                drop(open(&file, &key, SCHEMA).expect("made"));
1103            }
1104            let held = open(&busy, &key, SCHEMA).expect("opens");
1105            held.pragma_update(None, "wal_autocheckpoint", 0)
1106                .expect("no checkpoint");
1107            held.execute("INSERT INTO note (text) VALUES ('in the wal')", [])
1108                .expect("insert");
1109            assert!(
1110                std::fs::metadata(sibling(&busy, "-wal")).is_ok_and(|m| m.len() > 0),
1111                "the WAL holds the row"
1112            );
1113            assert!(
1114                matches!(replace(&path(&dir), &copy), Err(CatalogError::Io(_))),
1115                "{}",
1116                busy.display()
1117            );
1118            assert!(copy.exists(), "nothing was renamed");
1119            drop(held);
1120        }
1121    }
1122
1123    #[test]
1124    fn reencrypting_under_the_wrong_key_changes_nothing() {
1125        let dir = tempfile::tempdir().expect("temp dir");
1126        let (old, new) = (Key::generate().expect("key"), Key::generate().expect("key"));
1127        drop(open(&path(&dir), &old, SCHEMA).expect("opens"));
1128        let other = Key::generate().expect("key");
1129        assert!(matches!(
1130            reencrypt(&path(&dir), &other, &new),
1131            Err(CatalogError::WrongKey)
1132        ));
1133        assert!(
1134            open(&path(&dir), &old, SCHEMA).is_ok(),
1135            "still under the old key"
1136        );
1137    }
1138
1139    #[test]
1140    fn a_backup_holds_every_committed_row_and_opens_under_the_same_key_only() {
1141        let dir = tempfile::tempdir().expect("temp dir");
1142        let key = Key::generate().expect("key");
1143        let source = open(&path(&dir), &key, SCHEMA).expect("opens");
1144        source
1145            .execute("INSERT INTO note (text) VALUES ('committed')", [])
1146            .expect("insert");
1147        // A second connection holds a write transaction open: its row is
1148        // not committed, so the copy must not hold it.
1149        let writer = open(&path(&dir), &key, SCHEMA).expect("opens");
1150        writer.execute_batch("BEGIN IMMEDIATE").expect("begin");
1151        writer
1152            .execute("INSERT INTO note (text) VALUES ('uncommitted')", [])
1153            .expect("insert");
1154        let copy = dir.path().join("copy.sqlite");
1155        backup(&source, &copy, &key).expect("backs up");
1156        writer.execute_batch("COMMIT").expect("commit");
1157        assert!(
1158            !sibling(&copy, "-wal").exists()
1159                || std::fs::metadata(sibling(&copy, "-wal"))
1160                    .expect("wal")
1161                    .len()
1162                    == 0,
1163            "the copy is whole in its own file"
1164        );
1165        let reopened = open(&copy, &key, "").expect("the copy opens under the same key");
1166        let notes: Vec<String> = reopened
1167            .prepare("SELECT text FROM note")
1168            .expect("prepare")
1169            .query_map([], |r| r.get(0))
1170            .expect("query")
1171            .collect::<Result<_, _>>()
1172            .expect("rows");
1173        assert_eq!(notes, ["committed"]);
1174        let version: i64 = reopened
1175            .pragma_query_value(None, "user_version", |r| r.get(0))
1176            .expect("version");
1177        assert_eq!(version, SCHEMA_VERSION);
1178        drop(reopened);
1179        let other = Key::generate().expect("key");
1180        assert!(matches!(
1181            open(&copy, &other, ""),
1182            Err(CatalogError::WrongKey)
1183        ));
1184    }
1185
1186    #[test]
1187    fn a_backup_holds_rows_still_in_the_source_wal_and_no_plain_text() {
1188        let dir = tempfile::tempdir().expect("temp dir");
1189        let key = Key::generate().expect("key");
1190        let source = open(&path(&dir), &key, SCHEMA).expect("opens");
1191        source
1192            .execute("INSERT INTO note (text) VALUES (?1)", [MARKER])
1193            .expect("insert");
1194        assert!(
1195            std::fs::metadata(sibling(&path(&dir), "-wal"))
1196                .expect("wal")
1197                .len()
1198                > 0,
1199            "the row is still in the WAL"
1200        );
1201        let copy = dir.path().join("copy.sqlite");
1202        backup(&source, &copy, &key).expect("backs up");
1203        let bytes = std::fs::read(&copy).expect("read the copy");
1204        assert!(
1205            !bytes.windows(MARKER.len()).any(|w| w == MARKER.as_bytes()),
1206            "the copy is encrypted"
1207        );
1208        let reopened = open(&copy, &key, "").expect("opens");
1209        let count: i64 = reopened
1210            .query_row("SELECT count(*) FROM note WHERE text = ?1", [MARKER], |r| {
1211                r.get(0)
1212            })
1213            .expect("count");
1214        assert_eq!(count, 1);
1215    }
1216
1217    #[test]
1218    fn a_backup_never_writes_over_a_file() {
1219        let dir = tempfile::tempdir().expect("temp dir");
1220        let key = Key::generate().expect("key");
1221        let source = open(&path(&dir), &key, SCHEMA).expect("opens");
1222        let copy = dir.path().join("copy.sqlite");
1223        std::fs::write(&copy, b"something else").expect("write");
1224        assert!(matches!(
1225            backup(&source, &copy, &key),
1226            Err(CatalogError::Io(_))
1227        ));
1228        assert_eq!(std::fs::read(&copy).expect("read"), b"something else");
1229    }
1230
1231    #[test]
1232    fn a_wrong_key_does_not_open_the_catalog() {
1233        let dir = tempfile::tempdir().expect("temp dir");
1234        let key = Key::generate().expect("key");
1235        drop(open(&path(&dir), &key, SCHEMA).expect("opens"));
1236        let other = Key::generate().expect("key");
1237        assert!(matches!(
1238            open(&path(&dir), &other, SCHEMA),
1239            Err(CatalogError::WrongKey)
1240        ));
1241        assert!(
1242            open(&path(&dir), &key, SCHEMA).is_ok(),
1243            "the right key still opens it"
1244        );
1245    }
1246
1247    /// A catalog file or directory this process may not write is named,
1248    /// with the system's error, and never taken for a wrong key.
1249    #[test]
1250    fn a_catalog_the_process_may_not_write_is_an_access_error_naming_the_path() {
1251        use std::os::unix::fs::PermissionsExt;
1252        let mode = |p: &Path, m| {
1253            std::fs::set_permissions(p, std::fs::Permissions::from_mode(m)).expect("chmod")
1254        };
1255        let dir = tempfile::tempdir().expect("temp dir");
1256        let key = Key::generate().expect("key");
1257        drop(open(&path(&dir), &key, SCHEMA).expect("opens"));
1258        for (target, read_only) in [(path(&dir), 0o400), (dir.path().to_owned(), 0o500)] {
1259            mode(&target, read_only);
1260            let refused = open(&path(&dir), &key, SCHEMA);
1261            mode(&target, if target.is_dir() { 0o700 } else { 0o600 });
1262            match refused {
1263                Err(CatalogError::Access { path, error }) => {
1264                    assert_eq!(path, target);
1265                    assert_eq!(error.kind(), std::io::ErrorKind::PermissionDenied);
1266                }
1267                other => panic!("{}: {other:?}", target.display()),
1268            }
1269        }
1270        assert!(
1271            open(&path(&dir), &key, SCHEMA).is_ok(),
1272            "opens once allowed"
1273        );
1274    }
1275
1276    /// A row that cannot insert at all would make every column look as if
1277    /// it refused NULL.
1278    #[test]
1279    #[should_panic(expected = "a whole note row inserts")]
1280    fn the_null_check_needs_a_row_that_inserts() {
1281        let dir = tempfile::tempdir().expect("temp dir");
1282        let key = Key::generate().expect("key");
1283        let conn = open(&path(&dir), &key, SCHEMA).expect("opens");
1284        testing::columns_taking_null(&conn, "note", &[("misspelt", "'a'")]);
1285    }
1286
1287    /// Run while the connection is open, so the commit is still in the WAL.
1288    #[test]
1289    fn no_plain_record_reaches_the_catalog_or_its_wal() {
1290        let dir = tempfile::tempdir().expect("temp dir");
1291        let key = Key::generate().expect("key");
1292        let conn = open(&path(&dir), &key, SCHEMA).expect("opens");
1293        conn.execute("INSERT INTO note (text) VALUES (?1)", [MARKER])
1294            .expect("insert");
1295        let wal = std::fs::metadata(dir.path().join("catalog.sqlite-wal")).expect("a WAL");
1296        assert!(wal.len() > 0, "the commit is in the WAL");
1297        for entry in std::fs::read_dir(dir.path()).expect("list") {
1298            let file = entry.expect("entry").path();
1299            let bytes = std::fs::read(&file).expect("read");
1300            assert!(
1301                !bytes.windows(MARKER.len()).any(|w| w == MARKER.as_bytes()),
1302                "plain record in {}",
1303                file.display()
1304            );
1305        }
1306        drop(conn);
1307    }
1308}