Skip to main content

core_crypto_keystore/connection/
mod.rs

1pub(crate) mod encryption;
2mod fetch_from_database;
3#[cfg(feature = "cross-process-lock")]
4mod file_lock;
5mod filesystem;
6#[cfg(target_os = "unknown")]
7pub(crate) mod idb_migration;
8#[cfg(target_os = "ios")]
9pub(crate) mod ios_wal_compat;
10#[cfg(target_os = "unknown")]
11mod legacy_opfs;
12mod mls;
13#[cfg(target_os = "unknown")]
14mod os_unknown;
15mod transaction;
16mod transaction_lock;
17
18use std::sync::Arc;
19
20use async_lock::{Mutex, MutexGuardArc};
21use rusqlite::Connection;
22#[cfg(feature = "log-queries")]
23use rusqlite::trace::{TraceEvent, TraceEventCodes};
24
25#[cfg(target_os = "unknown")]
26pub use self::idb_migration::{delete_legacy_idb, legacy_idb_exists};
27pub use self::mls::{deser, ser};
28pub(crate) use self::{
29    filesystem::Filesystem,
30    transaction_lock::{TransactionGuard, TransactionLock},
31};
32pub use crate::migrations::migrate_db_key_type_to_bytes;
33use crate::{CryptoKeystoreResult, DatabaseKey, Transaction, migrations::MigrationTarget, unique_arc::UniqueWeak};
34
35#[cfg(feature = "log-queries")]
36fn log_query(event: TraceEvent) {
37    if let TraceEvent::Stmt(_, sql) = event {
38        log::info!("{sql}")
39    }
40}
41
42// Intentionally not `Clone`; outer users should wrap this entire thing in an `Arc` (or `Arc<Mutex<Option<Self>>>`
43// etc) as required for their desired semantics.
44#[derive(derive_more::Debug)]
45pub struct Database {
46    // internal connection; mutexed in order to ensure unique access
47    // and provide `Sync`. `Arc` allows us to hand out lifetime-free
48    // lock guards to the connection.
49    //
50    // Note: it is important for the correctness of `Self::take` that
51    // nobody ever actually clones this `Arc`, other than through a lock guard
52    // which is gone by the time `take` runs. For now I don't believe it's
53    // worth the effort of making a `UniqueArc` work here, but if this proves
54    // to be a problem, we might make that effort in the future.
55    conn: Arc<Mutex<Connection>>,
56    // handler with which to delete the database;
57    // mutexed to provide `Sync`
58    pub(crate) filesystem: Mutex<Box<dyn Filesystem>>,
59    #[debug(skip)]
60    pub(crate) transaction: Mutex<Option<UniqueWeak<Transaction>>>,
61    // ensures at most one transaction is in flight against this database at a time
62    transaction_lock: TransactionLock,
63    // `PRAGMA data_version` as of the start of the last transaction, if there was one.
64    // Only `update_data_version` uses it, while the transaction holds the connection.
65    last_data_version: parking_lot::Mutex<Option<i64>>,
66}
67
68impl Database {
69    /// Open an encrypted `Database` at the provided location.
70    ///
71    /// This function is the internal implementation for [`Self::open`]; that method should be generally preferred.
72    #[cfg_attr(not(target_os = "unknown"), expect(clippy::unused_async))]
73    async fn open_internal(
74        path: &str,
75        database_key: &DatabaseKey,
76    ) -> CryptoKeystoreResult<(Connection, Box<dyn Filesystem>)> {
77        #[cfg(target_os = "unknown")]
78        let (conn, filesystem) = { os_unknown::open(path, database_key).await? };
79
80        #[cfg(not(target_os = "unknown"))]
81        let (conn, filesystem) = {
82            let exists = std::fs::exists(path)?;
83            let mut conn = Connection::open(path)?;
84            if exists {
85                encryption::decrypt(&mut conn, database_key)?;
86            } else {
87                encryption::key(&mut conn, database_key)?;
88            }
89
90            // ? iOS WAL journaling fix; see details here: https://github.com/sqlcipher/sqlcipher/issues/255
91            // Use the caller-provided path here rather than `Connection::path()`, which SQLite
92            // canonicalizes. The iOS WAL compatibility salt is keyed by the path, so changing a
93            // relative path into an absolute one would make existing databases use the wrong salt.
94            #[cfg(target_os = "ios")]
95            if !path.is_empty() {
96                ios_wal_compat::handle_ios_wal_compat(&conn, path)?;
97            }
98
99            (conn, filesystem::NativeFs)
100        };
101
102        let filesystem = Box::new(filesystem);
103        Ok((conn, filesystem))
104    }
105
106    /// Set up the database from a connection
107    ///
108    /// The connection must already be configured for encryption if appropriate.
109    ///
110    /// Sets appropriate pragmas and performs migrations and general initialization work.
111    #[cfg(test)]
112    async fn init(
113        conn: Connection,
114        filesystem: Box<dyn Filesystem>,
115        migration_target: MigrationTarget,
116    ) -> CryptoKeystoreResult<Self> {
117        let transaction_lock = TransactionLock::new(conn.path().unwrap_or_default())?;
118        // SQL migrations and their meta migrations commit separately. Keep other processes
119        // out for the entire initialization, including reading the current schema version.
120        let _guard = transaction_lock.acquire().await?;
121        Self::init_with_lock(conn, filesystem, migration_target, transaction_lock)
122    }
123
124    /// Initialize while holding `transaction_lock`, or with a private in-memory connection.
125    fn init_with_lock(
126        mut conn: Connection,
127        filesystem: Box<dyn Filesystem>,
128        migration_target: MigrationTarget,
129        transaction_lock: TransactionLock,
130    ) -> CryptoKeystoreResult<Self> {
131        #[cfg(feature = "log-queries")]
132        conn.trace_v2(TraceEventCodes::SQLITE_TRACE_STMT, Some(log_query))?;
133        conn.pragma_update(None, "foreign_keys", "ON")?;
134
135        // path is an empty string for in-memory databases
136        if let Some(path) = conn.path()
137            && !path.is_empty()
138        {
139            // Enable WAL journaling mode when not in memory
140            conn.pragma_update(None, "journal_mode", "wal")?;
141        }
142
143        crate::migrations::run_migrations(&mut conn, migration_target)?;
144
145        let conn = Arc::new(Mutex::new(conn));
146
147        Ok(Self {
148            conn,
149            filesystem: filesystem.into(),
150            transaction: Default::default(),
151            transaction_lock,
152            last_data_version: Default::default(),
153        })
154    }
155
156    /// Open an encrypted Sqlite `Database` at the provided location.
157    ///
158    /// The database is encrypted via sqlcipher. When compiled with `target_os = "unknown"`,
159    /// it is stored in OPFS, and WAL uses exclusive locking and an in-memory index.
160    /// Otherwise, it is stored at a path in the local filesystem.
161    pub async fn open(path: &str, database_key: &DatabaseKey) -> CryptoKeystoreResult<Arc<Self>> {
162        let transaction_lock = TransactionLock::new(path)?;
163        // SQL migrations and their meta migrations commit separately. Keep other processes
164        // out for the entire initialization, including reading the current schema version.
165        let _guard = transaction_lock.acquire().await?;
166        let (conn, filesystem) = Self::open_internal(path, database_key).await?;
167        Self::init_with_lock(conn, filesystem, MigrationTarget::Latest, transaction_lock).map(Into::into)
168    }
169
170    /// Open an in-memory `Database`.
171    ///
172    /// In-memory databases are never encrypted.
173    pub fn open_in_memory() -> CryptoKeystoreResult<Arc<Self>> {
174        let connection = Connection::open_in_memory()?;
175        Self::init_with_lock(
176            connection,
177            Box::new(filesystem::Nop),
178            MigrationTarget::Composite,
179            TransactionLock::new("")?,
180        )
181        .map(Into::into)
182    }
183
184    /// Open an encrypted `Database` at the provided location.
185    ///
186    /// Acts as `open`, but only migrates to the specified schema version.
187    ///
188    /// Note: this is known to work because `Self::open_internal` will only ever perform
189    /// a partial migration when `target_os = "unknown"`, where this function is not defined.
190    /// Use caution when adjusting the cfg flags here!
191    #[cfg(all(test, not(target_os = "unknown")))]
192    pub(crate) async fn open_at_schema_version(
193        path: &str,
194        database_key: &DatabaseKey,
195        migration_target: MigrationTarget,
196    ) -> CryptoKeystoreResult<Self> {
197        let (conn, filesystem) = Self::open_internal(path, database_key).await?;
198        Self::init(conn, filesystem, migration_target).await
199    }
200
201    /// Change the encryption key for this database.
202    pub async fn update_key(&self, new_key: &DatabaseKey) -> CryptoKeystoreResult<()> {
203        let mut guard = self.conn.lock().await;
204        encryption::rekey(&mut guard, new_key)
205    }
206
207    /// Wait for any running transaction to finish, then take the connection out of this database,
208    /// preventing this from being used again.
209    ///
210    /// The returned guard keeps other processes out for as long as the caller holds it, so that
211    /// teardown is not interleaved with somebody else's transaction.
212    async fn take(self) -> CryptoKeystoreResult<(Connection, Box<dyn Filesystem>, TransactionGuard)> {
213        // Nobody ever clones `self.conn`; the Arc is only so we can have a lifetime-free guard over
214        // the interior mutex, so the strong count here is 1.
215        let conn = Arc::into_inner(self.conn)
216            .expect("nobody holds a guard over self.conn")
217            .into_inner();
218        let guard = self.transaction_lock.acquire().await?;
219        Ok((conn, self.filesystem.into_inner(), guard))
220    }
221
222    // Close this database connection
223    pub async fn close(self) -> CryptoKeystoreResult<()> {
224        let (conn, _fs, _guard) = self.take().await?;
225        conn.close().map_err(|(_conn, err)| err)?;
226        Ok(())
227    }
228
229    /// Close and remove this database.
230    ///
231    /// This deletes the database, including its encryption key.
232    /// Future opens will always succeed with any arbitrary encryption key; they will
233    /// simply open an empty database.
234    pub async fn wipe(self) -> CryptoKeystoreResult<()> {
235        let (conn, fs, _guard) = self.take().await?;
236        conn.execute_batch(
237            "
238            PRAGMA writable_schema = 1;
239            DELETE FROM sqlite_master WHERE type IN ('table', 'index', 'trigger');
240            PRAGMA writable_schema = 0;
241            VACUUM;
242        ",
243        )?;
244        let location = conn.path().map(ToOwned::to_owned);
245        conn.close().map_err(|(_conn, err)| err)?;
246        if let Some(path) = location {
247            // not in-memory
248            fs.delete(&path).await?;
249            // `_guard` is still alive, so we unlink the lock file while still holding it; that
250            // keeps a peer from acquiring the fresh lock file before the database is really gone.
251            #[cfg(feature = "cross-process-lock")]
252            file_lock::remove_lock_file(&path).await?;
253        }
254        Ok(())
255    }
256
257    /// Get a reference to this database's connection without checking if a transaction is in flight.
258    ///
259    /// **CAUTION**: this will block until the in-flight transaction completes, if one exists.
260    ///
261    /// Most users should prefer [`Self::conn`].
262    pub(crate) async fn raw_conn(&self) -> MutexGuardArc<Connection> {
263        self.conn.lock_arc().await
264    }
265
266    /// Get the value of SQLite's `PRAGMA data_version` and compute `externally_modified` from it.
267    ///
268    /// Returns `true` when the database knows that an external connection changed database state
269    /// since the last time this was called.
270    ///
271    /// `conn` must be this database's connection.
272    ///
273    /// See: <https://www.sqlite.org/pragma.html#pragma_data_version>
274    pub(crate) fn update_data_version(&self, conn: &Connection) -> rusqlite::Result<bool> {
275        let data_version = conn.pragma_query_one(None, "data_version")?;
276        let mut last_data_version = self.last_data_version.lock();
277        let externally_modified =
278            last_data_version.is_some_and(|stored_data_version| stored_data_version != data_version);
279        *last_data_version = Some(data_version);
280        Ok(externally_modified)
281    }
282
283    /// Get the location of the database.
284    ///
285    /// Returns None if the database is in-memory.
286    pub async fn location(&self) -> Option<String> {
287        self.conn()
288            .await
289            .path()
290            .filter(|s| !s.is_empty())
291            .map(ToString::to_string)
292    }
293}