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