Skip to main content

matrix_sdk_sqlite/
crypto_store.rs

1// Copyright 2022, 2026 The Matrix.org Foundation C.I.C.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use std::{
16    collections::HashMap,
17    fmt,
18    ops::Deref,
19    path::{Path, PathBuf},
20    sync::{Arc, RwLock},
21};
22
23use async_trait::async_trait;
24use deadpool::managed::PoolConfig;
25use matrix_sdk_base::cross_process_lock::CrossProcessLockGeneration;
26use matrix_sdk_crypto::{
27    Account, DeviceData, GossipRequest, GossippedSecret, SecretInfo, TrackedUser, UserIdentityData,
28    olm::{
29        InboundGroupSession, OutboundGroupSession, PickledInboundGroupSession,
30        PrivateCrossSigningIdentity, SenderDataType, Session, StaticAccountData,
31    },
32    store::{
33        CryptoStore,
34        types::{
35            BackupKeys, Changes, DehydratedDeviceKey, PendingChanges, RoomKeyCounts,
36            RoomKeyWithheldEntry, RoomPendingKeyBundleDetails, RoomSettings,
37            StoredRoomKeyBundleData,
38        },
39    },
40};
41use matrix_sdk_store_encryption::StoreCipher;
42use ruma::{
43    DeviceId, MilliSecondsSinceUnixEpoch, OwnedDeviceId, RoomId, TransactionId, UserId,
44    events::secret::request::SecretName,
45};
46use rusqlite::{OptionalExtension, named_params, params_from_iter};
47use tokio::{
48    fs,
49    sync::{Mutex, OwnedMutexGuard},
50};
51use tracing::{debug, instrument, warn};
52use vodozemac::Curve25519PublicKey;
53use zeroize::Zeroizing;
54
55use crate::{
56    OpenStoreError, RuntimeConfig, Secret, SqliteStoreConfig,
57    connection::{
58        self, Connection as SqliteAsyncConn, Pool as SqlitePool, SqliteConnections,
59        SqliteConnectionsInner,
60    },
61    error::{Error, Result},
62    utils::{
63        EncryptableStore, Key, SqliteAsyncConnExt, SqliteKeyValueStoreAsyncConnExt,
64        SqliteKeyValueStoreConnExt, map_interact_err,
65    },
66};
67
68/// The database name.
69const DATABASE_NAME: &str = "matrix-sdk-crypto.sqlite3";
70
71/// An SQLite-based crypto store.
72#[derive(Clone)]
73pub struct SqliteCryptoStore {
74    store_cipher: Option<Arc<StoreCipher>>,
75
76    /// `Some` when active, `None` when closed. The outer `Mutex` serialises
77    /// close/reopen with connection access.
78    connections: Arc<SqliteConnections>,
79
80    /// Retained so we can rebuild the pool on reopen.
81    db_path: PathBuf,
82
83    /// Retained so we can rebuild the pool on reopen.
84    pool_config: PoolConfig,
85
86    /// Retained so we can re-apply runtime config on reopen.
87    runtime_config: RuntimeConfig,
88
89    // DB values cached in memory
90    static_account: Arc<RwLock<Option<StaticAccountData>>>,
91    save_changes_lock: Arc<Mutex<()>>,
92}
93
94#[cfg(not(tarpaulin_include))]
95impl fmt::Debug for SqliteCryptoStore {
96    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
97        f.debug_struct("SqliteCryptoStore").finish_non_exhaustive()
98    }
99}
100
101impl EncryptableStore for SqliteCryptoStore {
102    fn get_cypher(&self) -> Option<&StoreCipher> {
103        self.store_cipher.as_deref()
104    }
105}
106
107impl SqliteCryptoStore {
108    /// Create an `SqliteCryptoStore` struct without trying to create the
109    /// database or migrate to a newer version. This is only for use internally,
110    /// and for testing.
111    ///
112    /// # Arguments
113    ///
114    /// - `secret` - The secret used to encrypt the data.
115    /// - `pool` - A connection pool to use for reading from the store.
116    /// - `conn` - The connection to use for writing to the store.
117    pub(crate) async fn create_raw(
118        secret: Option<Secret>,
119        pool: SqlitePool,
120        conn: SqliteAsyncConn,
121        pool_config: PoolConfig,
122        runtime_config: RuntimeConfig,
123    ) -> Result<Self, OpenStoreError> {
124        let store_cipher = match secret {
125            Some(s) => Some(Arc::new(conn.get_or_create_store_cipher(s).await?)),
126            None => None,
127        };
128
129        let db_path = pool.manager().database_path.clone();
130
131        Ok(Self {
132            store_cipher,
133            connections: Arc::new(
134                SqliteConnections::new(SqliteConnectionsInner {
135                    pool,
136                    write_connection: Arc::new(Mutex::new(conn)),
137                })
138                .await,
139            ),
140            db_path,
141            pool_config,
142            runtime_config,
143            static_account: Arc::new(RwLock::new(None)),
144            save_changes_lock: Default::default(),
145        })
146    }
147
148    /// Open the SQLite-based crypto store at the given path using the given
149    /// passphrase to encrypt private data.
150    pub async fn open(
151        path: impl AsRef<Path>,
152        passphrase: Option<&str>,
153    ) -> Result<Self, OpenStoreError> {
154        Self::open_with_config(&SqliteStoreConfig::new(path).passphrase(passphrase)).await
155    }
156
157    /// Open the SQLite-based crypto store at the given path using the given key
158    /// to encrypt private data.
159    pub async fn open_with_key(
160        path: impl AsRef<Path>,
161        key: Option<&[u8]>,
162    ) -> Result<Self, OpenStoreError> {
163        Self::open_with_config(&SqliteStoreConfig::new(path).key(key)).await
164    }
165
166    /// Open the SQLite-based crypto store with the config open config.
167    pub async fn open_with_config(config: &SqliteStoreConfig) -> Result<Self, OpenStoreError> {
168        fs::create_dir_all(&config.path).await.map_err(OpenStoreError::CreateDir)?;
169
170        let pool = config.build_pool_of_connections(DATABASE_NAME)?;
171        let pool_config = config.pool_config();
172        let runtime_config = config.runtime_config();
173
174        let this =
175            Self::open_with_pool(pool, config.secret.clone(), pool_config, runtime_config).await?;
176        this.read().await?.apply_runtime_config(runtime_config).await?;
177
178        Ok(this)
179    }
180
181    /// Create an SQLite-based crypto store using the given SQLite database
182    /// pool. The given secret will be used to encrypt private data.
183    async fn open_with_pool(
184        pool: SqlitePool,
185        secret: Option<Secret>,
186        pool_config: PoolConfig,
187        runtime_config: RuntimeConfig,
188    ) -> Result<Self, OpenStoreError> {
189        let conn = pool.get().await?;
190
191        let version = conn.db_version().await?;
192        debug!("Opened sqlite store with version {}", version);
193
194        let version = initialize_store(&conn, version).await?;
195
196        let store = Self::create_raw(secret, pool, conn, pool_config, runtime_config).await?;
197
198        run_migrations(&store, version, None).await?;
199
200        store.write().await?.wal_checkpoint().await;
201
202        Ok(store)
203    }
204
205    fn deserialize_and_unpickle_inbound_group_session(
206        &self,
207        value: Vec<u8>,
208        backed_up: bool,
209    ) -> Result<InboundGroupSession> {
210        let mut pickle: PickledInboundGroupSession = self.deserialize_value(&value)?;
211
212        // The `backed_up` SQL column is the source of truth, because we update
213        // it inside `mark_inbound_group_sessions_as_backed_up` and don't update
214        // the pickled value inside the `data` column (until now, when we are
215        // puling it out of the DB).
216        pickle.backed_up = backed_up;
217
218        Ok(InboundGroupSession::from_pickle(pickle)?)
219    }
220
221    fn deserialize_key_request(&self, value: &[u8], sent_out: bool) -> Result<GossipRequest> {
222        let mut request: GossipRequest = self.deserialize_value(value)?;
223        // sent_out SQL column is source of truth, sent_out field in serialized
224        // value needed for other stores though
225        request.sent_out = sent_out;
226        Ok(request)
227    }
228
229    fn get_static_account(&self) -> Option<StaticAccountData> {
230        self.static_account.read().unwrap().clone()
231    }
232
233    /// Acquire a connection for executing read operations.
234    #[instrument(skip_all)]
235    async fn read(&self) -> Result<SqliteAsyncConn> {
236        let pool = {
237            let guard = self.connections.lock().await;
238            let conns = guard.as_ref().ok_or(Error::StoreClosed)?;
239            conns.pool.clone()
240        };
241        Ok(pool.get().await?)
242    }
243
244    /// Acquire a connection for executing write operations.
245    #[instrument(skip_all)]
246    pub(crate) async fn write(&self) -> Result<OwnedMutexGuard<SqliteAsyncConn>> {
247        let write_connection = {
248            let guard = self.connections.lock().await;
249            let conns = guard.as_ref().ok_or(Error::StoreClosed)?;
250            conns.write_connection.clone()
251        };
252        let connection = write_connection.lock_owned().await;
253
254        // Specify a busy timeout so that operations are automatically retried,
255        // in case the database was marked as locked, which can happen
256        // under very peculiar circumstances in WAL mode.
257        //
258        // The timeout value is in milliseconds.
259        //
260        // See also https://www.sqlite.org/wal.html#sometimes_queries_return_sqlite_busy_in_wal_mode.
261        connection.execute_batch("PRAGMA busy_timeout = 2000;").await?;
262
263        Ok(connection)
264    }
265}
266
267const DATABASE_VERSION: u8 = 19;
268
269/// key for the dehydrated device pickle key in the key/value table.
270const DEHYDRATED_DEVICE_PICKLE_KEY: &str = "dehydrated_device_pickle_key";
271
272/// Initialize the database to version 1
273///
274/// This must be done before creating the store cipher, because the store cipher
275/// requires the `kv` table.
276///
277/// # Arguments
278///
279/// - `conn` - The connection to use.
280/// - `version` - the current version of the database.
281pub(crate) async fn initialize_store(conn: &SqliteAsyncConn, version: u8) -> Result<u8> {
282    if version == 0 {
283        debug!("Creating database");
284    } else if version < DATABASE_VERSION {
285        debug!(version, new_version = DATABASE_VERSION, "Upgrading database");
286    } else {
287        return Ok(version);
288    }
289
290    if version < 1 {
291        debug!("Creating database");
292        // First turn on WAL mode, this can't be done in the transaction, it
293        // fails with the error message: "cannot change into wal mode from
294        // within a transaction".
295        conn.execute_batch("PRAGMA journal_mode = wal;").await?;
296        conn.with_immediate_transaction(|txn| {
297            txn.execute_batch(include_str!("../migrations/crypto_store/001_init.sql"))?;
298            txn.set_db_version(1)
299        })
300        .await?;
301        return Ok(1);
302    }
303
304    Ok(version)
305}
306
307/// Run migrations for the given version of the database.
308///
309/// # Arguments
310///
311/// - `store` - The store to run the migrations on
312/// - `version` - The current version of the database.
313/// - `max_version` - The maximum version that the database will be migrated to.
314///   Only used for testing, so will only be checked for the versions that are
315///   needed for tests.
316pub(crate) async fn run_migrations(
317    store: &SqliteCryptoStore,
318    version: u8,
319    max_version: Option<u8>,
320) -> Result<()> {
321    let conn = store.write().await?;
322
323    if version < 2 {
324        debug!("Upgrading database to version 2");
325        conn.with_immediate_transaction(|txn| {
326            txn.execute_batch(include_str!("../migrations/crypto_store/002_reset_olm_hash.sql"))?;
327            txn.set_db_version(2)
328        })
329        .await?;
330    }
331
332    if version < 3 {
333        debug!("Upgrading database to version 3");
334        conn.with_immediate_transaction(|txn| {
335            txn.execute_batch(include_str!("../migrations/crypto_store/003_room_settings.sql"))?;
336            txn.set_db_version(3)
337        })
338        .await?;
339    }
340
341    if version < 4 {
342        debug!("Upgrading database to version 4");
343        conn.with_immediate_transaction(|txn| {
344            txn.execute_batch(include_str!(
345                "../migrations/crypto_store/004_drop_outbound_group_sessions.sql"
346            ))?;
347            txn.set_db_version(4)
348        })
349        .await?;
350    }
351
352    if version < 5 {
353        debug!("Upgrading database to version 5");
354        conn.with_immediate_transaction(|txn| {
355            txn.execute_batch(include_str!("../migrations/crypto_store/005_withheld_code.sql"))?;
356            txn.set_db_version(5)
357        })
358        .await?;
359    }
360
361    if version < 6 {
362        debug!("Upgrading database to version 6");
363        conn.with_immediate_transaction(|txn| {
364            txn.execute_batch(include_str!(
365                "../migrations/crypto_store/006_drop_outbound_group_sessions.sql"
366            ))?;
367            txn.set_db_version(6)
368        })
369        .await?;
370    }
371
372    if version < 7 {
373        debug!("Upgrading database to version 7");
374        conn.with_immediate_transaction(|txn| {
375            txn.execute_batch(include_str!("../migrations/crypto_store/007_lock_leases.sql"))?;
376            txn.set_db_version(7)
377        })
378        .await?;
379    }
380
381    if version < 8 {
382        debug!("Upgrading database to version 8");
383        conn.with_immediate_transaction(|txn| {
384            txn.execute_batch(include_str!("../migrations/crypto_store/008_secret_inbox.sql"))?;
385            txn.set_db_version(8)
386        })
387        .await?;
388    }
389
390    if version < 9 {
391        debug!("Upgrading database to version 9");
392        conn.with_immediate_transaction(|txn| {
393            txn.execute_batch(include_str!(
394                "../migrations/crypto_store/009_inbound_group_session_sender_key_sender_data_type.sql"
395            ))?;
396            txn.set_db_version(9)
397        })
398        .await?;
399    }
400
401    if version < 10 {
402        debug!("Upgrading database to version 10");
403        conn.with_immediate_transaction(|txn| {
404            txn.execute_batch(include_str!(
405                "../migrations/crypto_store/010_received_room_key_bundles.sql"
406            ))?;
407            txn.set_db_version(10)
408        })
409        .await?;
410    }
411
412    if version < 11 {
413        debug!("Upgrading database to version 11");
414        conn.with_immediate_transaction(|txn| {
415            txn.execute_batch(include_str!(
416                "../migrations/crypto_store/011_received_room_key_bundles_with_curve_key.sql"
417            ))?;
418            txn.set_db_version(11)
419        })
420        .await?;
421    }
422
423    if version < 12 {
424        debug!("Upgrading database to version 12");
425        conn.with_immediate_transaction(|txn| {
426            txn.execute_batch(include_str!(
427                "../migrations/crypto_store/012_withheld_code_by_room.sql"
428            ))?;
429            txn.set_db_version(12)
430        })
431        .await?;
432    }
433
434    if version < 13 {
435        debug!("Upgrading database to version 13");
436        conn.with_immediate_transaction(|txn| {
437            txn.execute_batch(include_str!(
438                "../migrations/crypto_store/013_lease_locks_with_generation.sql"
439            ))?;
440            txn.set_db_version(13)
441        })
442        .await?;
443    }
444
445    if version < 14 {
446        debug!("Upgrading database to version 14");
447        conn.with_immediate_transaction(|txn| {
448            txn.execute_batch(include_str!(
449                "../migrations/crypto_store/014_room_key_backups_fully_downloaded.sql"
450            ))?;
451            txn.set_db_version(14)
452        })
453        .await?;
454    }
455
456    if version < 15 {
457        debug!("Upgrading database to version 15");
458        conn.with_immediate_transaction(|txn| {
459            txn.execute_batch(include_str!(
460                "../migrations/crypto_store/015_rooms_pending_key_bundle.sql"
461            ))?;
462            txn.set_db_version(15)
463        })
464        .await?;
465    }
466
467    if version < 16 {
468        debug!("Upgrading database to version 16");
469        conn.with_immediate_transaction(|txn| {
470            txn.execute_batch(include_str!(
471                "../migrations/crypto_store/016_remove_old_generation_counter.sql"
472            ))?;
473            txn.set_db_version(16)
474        })
475        .await?;
476    }
477
478    if max_version.is_some_and(|max_version| max_version < 17) {
479        return Ok(());
480    }
481
482    if version < 17 {
483        debug!("Upgrading database to version 17");
484        let store = store.clone();
485        conn.with_immediate_transaction(move |txn| {
486            txn.execute_batch(include_str!(
487                "../migrations/crypto_store/017_add_new_secrets_inbox.sql"
488            ))?;
489            let mut select_query = txn.prepare("SELECT data FROM secrets")?;
490            let mut secrets = select_query.query([])?;
491            let mut insert_query = txn.prepare(
492                "INSERT OR IGNORE INTO secrets_inbox (secret_name, secret)
493            VALUES (?1, ?2)",
494            )?;
495            while let Some(row) = secrets.next()? {
496                let Ok(secret) =
497                    store.deserialize_json::<GossippedSecret>(row.get::<_, Vec<u8>>(0)?.as_ref())
498                else {
499                    continue;
500                };
501                let Ok(encoded_secret) = store.serialize_json(&secret.event.content.secret) else {
502                    continue;
503                };
504                insert_query.execute((
505                    store.encode_key("secrets_inbox", secret.secret_name.to_string()),
506                    &encoded_secret,
507                ))?;
508            }
509            txn.execute_batch(include_str!(
510                "../migrations/crypto_store/017_drop_old_secrets_inbox.sql"
511            ))?;
512            txn.set_db_version(17)
513        })
514        .await?;
515    }
516
517    if version < 18 {
518        debug!("Upgrading database to version 18");
519        let store = store.clone();
520        conn.with_immediate_transaction(move |txn| {
521            txn.execute_batch(include_str!(
522                "../migrations/crypto_store/018_add_gossip_request_info.sql"
523            ))?;
524            let mut select_query =
525                txn.prepare("SELECT request_id, sent_out, data FROM key_requests")?;
526            let mut requests = select_query.query([])?;
527            let mut update_query =
528                txn.prepare("UPDATE OR REPLACE key_requests SET info = ?1 WHERE request_id = ?2")?;
529            while let Some(row) = requests.next()? {
530                let Ok(request) = store.deserialize_key_request(
531                    row.get::<_, Vec<u8>>(2)?.as_ref(),
532                    row.get::<_, bool>(1)?,
533                ) else {
534                    continue;
535                };
536                let info = store.encode_key("key_requests", request.info.as_key());
537                update_query.execute((info, row.get::<_, Vec<u8>>(0)?))?;
538            }
539            txn.set_db_version(18)
540        })
541        .await?;
542    }
543
544    if version < 19 {
545        debug!("Upgrading database to version 19");
546        // Remove the sliding sync `pos` value stored in the crypto store. There
547        // was recently an event cache migration that emptied the cache but
548        // never reset the `pos` value, this fixes it.
549        let user_id = store.load_account().await?.map(|account| account.user_id.clone());
550
551        conn.with_immediate_transaction(move |txn| {
552            if let Some(user_id) = user_id {
553                txn.clear_kv(&format!("sliding_sync_store::room-list::{user_id}::instance"))?;
554            }
555            txn.set_db_version(19)
556        })
557        .await?;
558    }
559
560    Ok(())
561}
562
563trait SqliteConnectionExt {
564    fn set_session(
565        &self,
566        session_id: &[u8],
567        sender_key: &[u8],
568        data: &[u8],
569    ) -> rusqlite::Result<()>;
570
571    fn set_inbound_group_session(
572        &self,
573        room_id: &[u8],
574        session_id: &[u8],
575        data: &[u8],
576        backed_up: bool,
577        sender_key: Option<&[u8]>,
578        sender_data_type: Option<u8>,
579    ) -> rusqlite::Result<()>;
580
581    fn set_outbound_group_session(&self, room_id: &[u8], data: &[u8]) -> rusqlite::Result<()>;
582
583    fn set_device(&self, user_id: &[u8], device_id: &[u8], data: &[u8]) -> rusqlite::Result<()>;
584    fn delete_device(&self, user_id: &[u8], device_id: &[u8]) -> rusqlite::Result<()>;
585
586    fn set_identity(&self, user_id: &[u8], data: &[u8]) -> rusqlite::Result<()>;
587
588    fn add_olm_hash(&self, data: &[u8]) -> rusqlite::Result<()>;
589
590    fn set_key_request(
591        &self,
592        request_id: &[u8],
593        sent_out: bool,
594        data: &[u8],
595        info: &[u8],
596    ) -> rusqlite::Result<()>;
597
598    fn set_direct_withheld(
599        &self,
600        session_id: &[u8],
601        room_id: &[u8],
602        data: &[u8],
603    ) -> rusqlite::Result<()>;
604
605    fn set_room_settings(&self, room_id: &[u8], data: &[u8]) -> rusqlite::Result<()>;
606
607    fn set_secret(&self, request_id: &[u8], data: &[u8]) -> rusqlite::Result<()>;
608
609    fn set_received_room_key_bundle(
610        &self,
611        room_id: &[u8],
612        user_id: &[u8],
613        data: &[u8],
614    ) -> rusqlite::Result<()>;
615
616    fn set_has_downloaded_all_room_keys(&self, room_id: &[u8]) -> rusqlite::Result<()>;
617
618    fn set_room_pending_key_bundle(
619        &self,
620        room_id: &[u8],
621        details: Option<&[u8]>,
622    ) -> rusqlite::Result<()>;
623}
624
625impl SqliteConnectionExt for rusqlite::Connection {
626    fn set_session(
627        &self,
628        session_id: &[u8],
629        sender_key: &[u8],
630        data: &[u8],
631    ) -> rusqlite::Result<()> {
632        self.execute(
633            "INSERT INTO session (session_id, sender_key, data)
634             VALUES (?1, ?2, ?3)
635             ON CONFLICT (session_id) DO UPDATE SET data = ?3",
636            (session_id, sender_key, data),
637        )?;
638        Ok(())
639    }
640
641    fn set_inbound_group_session(
642        &self,
643        room_id: &[u8],
644        session_id: &[u8],
645        data: &[u8],
646        backed_up: bool,
647        sender_key: Option<&[u8]>,
648        sender_data_type: Option<u8>,
649    ) -> rusqlite::Result<()> {
650        self.execute(
651            "INSERT INTO inbound_group_session (session_id, room_id, data, backed_up, sender_key, sender_data_type) \
652             VALUES (?1, ?2, ?3, ?4, ?5, ?6)
653             ON CONFLICT (session_id) DO UPDATE SET data = ?3, backed_up = ?4, sender_key = ?5, sender_data_type = ?6",
654            (session_id, room_id, data, backed_up, sender_key, sender_data_type),
655        )?;
656        Ok(())
657    }
658
659    fn set_outbound_group_session(&self, room_id: &[u8], data: &[u8]) -> rusqlite::Result<()> {
660        self.execute(
661            "INSERT INTO outbound_group_session (room_id, data) \
662             VALUES (?1, ?2)
663             ON CONFLICT (room_id) DO UPDATE SET data = ?2",
664            (room_id, data),
665        )?;
666        Ok(())
667    }
668
669    fn set_device(&self, user_id: &[u8], device_id: &[u8], data: &[u8]) -> rusqlite::Result<()> {
670        self.execute(
671            "INSERT INTO device (user_id, device_id, data) \
672             VALUES (?1, ?2, ?3)
673             ON CONFLICT (user_id, device_id) DO UPDATE SET data = ?3",
674            (user_id, device_id, data),
675        )?;
676        Ok(())
677    }
678
679    fn delete_device(&self, user_id: &[u8], device_id: &[u8]) -> rusqlite::Result<()> {
680        self.execute(
681            "DELETE FROM device WHERE user_id = ? AND device_id = ?",
682            (user_id, device_id),
683        )?;
684        Ok(())
685    }
686
687    fn set_identity(&self, user_id: &[u8], data: &[u8]) -> rusqlite::Result<()> {
688        self.execute(
689            "INSERT INTO identity (user_id, data) \
690             VALUES (?1, ?2)
691             ON CONFLICT (user_id) DO UPDATE SET data = ?2",
692            (user_id, data),
693        )?;
694        Ok(())
695    }
696
697    fn add_olm_hash(&self, data: &[u8]) -> rusqlite::Result<()> {
698        self.execute("INSERT INTO olm_hash (data) VALUES (?) ON CONFLICT DO NOTHING", (data,))?;
699        Ok(())
700    }
701
702    fn set_key_request(
703        &self,
704        request_id: &[u8],
705        sent_out: bool,
706        data: &[u8],
707        info: &[u8],
708    ) -> rusqlite::Result<()> {
709        // The first `ON CONFLICT` cause will update a request if we try to save
710        // it again. The second `ON CONFLICT` will replace an old request for
711        // the same key/secret with the new request.
712        self.execute(
713            "INSERT INTO key_requests (request_id, sent_out, data, info)
714            VALUES (?1, ?2, ?3, ?4)
715            ON CONFLICT (request_id) DO UPDATE SET sent_out = ?2, data = ?3, info = ?4
716            ON CONFLICT (info) DO UPDATE SET request_id = ?1, sent_out = ?2, data = ?3",
717            (request_id, sent_out, data, info),
718        )?;
719        Ok(())
720    }
721
722    fn set_direct_withheld(
723        &self,
724        session_id: &[u8],
725        room_id: &[u8],
726        data: &[u8],
727    ) -> rusqlite::Result<()> {
728        self.execute(
729            "INSERT INTO direct_withheld_info (session_id, room_id, data)
730            VALUES (?1, ?2, ?3)
731            ON CONFLICT (session_id) DO UPDATE SET room_id = ?2, data = ?3",
732            (session_id, room_id, data),
733        )?;
734        Ok(())
735    }
736
737    fn set_room_settings(&self, room_id: &[u8], data: &[u8]) -> rusqlite::Result<()> {
738        self.execute(
739            "INSERT INTO room_settings (room_id, data)
740            VALUES (?1, ?2)
741            ON CONFLICT (room_id) DO UPDATE SET data = ?2",
742            (room_id, data),
743        )?;
744        Ok(())
745    }
746
747    fn set_secret(&self, secret_name: &[u8], secret: &[u8]) -> rusqlite::Result<()> {
748        // Ignore duplicate values, since we may get set the same secret
749        // multiple times.
750        self.execute(
751            "INSERT OR IGNORE INTO secrets_inbox (secret_name, secret)
752            VALUES (?1, ?2)",
753            (secret_name, secret),
754        )?;
755
756        Ok(())
757    }
758
759    fn set_received_room_key_bundle(
760        &self,
761        room_id: &[u8],
762        sender_user_id: &[u8],
763        data: &[u8],
764    ) -> rusqlite::Result<()> {
765        self.execute(
766            "INSERT INTO received_room_key_bundle(room_id, sender_user_id, bundle_data)
767            VALUES (?1, ?2, ?3)
768            ON CONFLICT (room_id, sender_user_id) DO UPDATE SET bundle_data = ?3",
769            (room_id, sender_user_id, data),
770        )?;
771        Ok(())
772    }
773
774    fn set_room_pending_key_bundle(
775        &self,
776        room_id: &[u8],
777        data: Option<&[u8]>,
778    ) -> rusqlite::Result<()> {
779        if let Some(data) = data {
780            self.execute(
781                "INSERT INTO rooms_pending_key_bundle (room_id, data)
782                 VALUES (?1, ?2)
783                 ON CONFLICT (room_id) DO UPDATE SET data = ?2",
784                (room_id, data),
785            )?;
786        } else {
787            self.execute("DELETE FROM rooms_pending_key_bundle WHERE room_id = ?1", (room_id,))?;
788        }
789        Ok(())
790    }
791
792    fn set_has_downloaded_all_room_keys(&self, room_id: &[u8]) -> rusqlite::Result<()> {
793        self.execute(
794            "INSERT INTO room_key_backups_fully_downloaded(room_id)
795             VALUES (?1)
796             ON CONFLICT(room_id) DO NOTHING",
797            (room_id,),
798        )?;
799        Ok(())
800    }
801}
802
803#[async_trait]
804trait SqliteObjectCryptoStoreExt: SqliteAsyncConnExt {
805    async fn get_sessions_for_sender_key(&self, sender_key: Key) -> Result<Vec<Vec<u8>>> {
806        Ok(self
807            .prepare("SELECT data FROM session WHERE sender_key = ?", |mut stmt| {
808                stmt.query((sender_key,))?.mapped(|row| row.get(0)).collect()
809            })
810            .await?)
811    }
812
813    async fn get_inbound_group_session(
814        &self,
815        session_id: Key,
816    ) -> Result<Option<(Vec<u8>, Vec<u8>, bool)>> {
817        Ok(self
818            .query_one(
819                "SELECT room_id, data, backed_up FROM inbound_group_session WHERE session_id = ?",
820                (session_id,),
821                |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)),
822            )
823            .await
824            .optional()?)
825    }
826
827    async fn get_inbound_group_sessions(&self) -> Result<Vec<(Vec<u8>, bool)>> {
828        Ok(self
829            .prepare("SELECT data, backed_up FROM inbound_group_session", |mut stmt| {
830                stmt.query(())?.mapped(|row| Ok((row.get(0)?, row.get(1)?))).collect()
831            })
832            .await?)
833    }
834
835    async fn get_inbound_group_session_counts(
836        &self,
837        _backup_version: Option<&str>,
838    ) -> Result<RoomKeyCounts> {
839        let total = self
840            .query_one("SELECT count(*) FROM inbound_group_session", (), |row| row.get(0))
841            .await?;
842        let backed_up = self
843            .query_one(
844                "SELECT count(*) FROM inbound_group_session WHERE backed_up = TRUE",
845                (),
846                |row| row.get(0),
847            )
848            .await?;
849        Ok(RoomKeyCounts { total, backed_up })
850    }
851
852    async fn get_inbound_group_sessions_by_room_id(
853        &self,
854        room_id: Key,
855    ) -> Result<Vec<(Vec<u8>, bool)>> {
856        Ok(self
857            .prepare(
858                "SELECT data, backed_up FROM inbound_group_session WHERE room_id = :room_id",
859                move |mut stmt| {
860                    stmt.query(named_params! {
861                        ":room_id": room_id,
862                    })?
863                    .mapped(|row| Ok((row.get(0)?, row.get(1)?)))
864                    .collect()
865                },
866            )
867            .await?)
868    }
869
870    async fn get_inbound_group_sessions_for_device_batch(
871        &self,
872        sender_key: Key,
873        sender_data_type: SenderDataType,
874        after_session_id: Option<Key>,
875        limit: usize,
876    ) -> Result<Vec<(Vec<u8>, bool)>> {
877        Ok(self
878            .prepare(
879                "
880                SELECT data, backed_up
881                FROM inbound_group_session
882                WHERE sender_key = :sender_key
883                    AND sender_data_type = :sender_data_type
884                    AND session_id > :after_session_id
885                ORDER BY session_id
886                LIMIT :limit
887                ",
888                move |mut stmt| {
889                    let sender_data_type = sender_data_type as u8;
890
891                    // If we are not provided with an `after_session_id`, use a
892                    // key which will sort before all real keys: the empty
893                    // string.
894                    let after_session_id = after_session_id.unwrap_or(Key::Plain(Vec::new()));
895
896                    stmt.query(named_params! {
897                        ":sender_key": sender_key,
898                        ":sender_data_type": sender_data_type,
899                        ":after_session_id": after_session_id,
900                        ":limit": limit,
901                    })?
902                    .mapped(|row| Ok((row.get(0)?, row.get(1)?)))
903                    .collect()
904                },
905            )
906            .await?)
907    }
908
909    async fn get_inbound_group_sessions_for_backup(&self, limit: usize) -> Result<Vec<Vec<u8>>> {
910        Ok(self
911            .prepare(
912                "SELECT data FROM inbound_group_session WHERE backed_up = FALSE LIMIT ?",
913                move |mut stmt| stmt.query((limit,))?.mapped(|row| row.get(0)).collect(),
914            )
915            .await?)
916    }
917
918    async fn mark_inbound_group_sessions_as_backed_up(&self, session_ids: Vec<Key>) -> Result<()> {
919        if session_ids.is_empty() {
920            // We are not expecting to be called with an empty list of sessions
921            warn!("No sessions to mark as backed up!");
922            return Ok(());
923        }
924
925        self.chunk_large_query_over(session_ids, None, move |txn, session_ids| {
926            // Safety: host parameters are not generated using any user input
927            // except the number of session IDs, so it is safe from injection.
928            let query = format!(
929                "UPDATE inbound_group_session SET backed_up = TRUE where session_id IN ({})",
930                session_ids.host_parameters()
931            );
932            txn.prepare(&query)?.execute(params_from_iter(session_ids))?;
933            Ok(Vec::<()>::new())
934        })
935        .await?;
936
937        Ok(())
938    }
939
940    async fn reset_inbound_group_session_backup_state(&self) -> Result<()> {
941        self.execute("UPDATE inbound_group_session SET backed_up = FALSE", ()).await?;
942        Ok(())
943    }
944
945    async fn get_outbound_group_session(&self, room_id: Key) -> Result<Option<Vec<u8>>> {
946        Ok(self
947            .query_one(
948                "SELECT data FROM outbound_group_session WHERE room_id = ?",
949                (room_id,),
950                |row| row.get(0),
951            )
952            .await
953            .optional()?)
954    }
955
956    async fn get_device(&self, user_id: Key, device_id: Key) -> Result<Option<Vec<u8>>> {
957        Ok(self
958            .query_one(
959                "SELECT data FROM device WHERE user_id = ? AND device_id = ?",
960                (user_id, device_id),
961                |row| row.get(0),
962            )
963            .await
964            .optional()?)
965    }
966
967    async fn get_user_devices(&self, user_id: Key) -> Result<Vec<Vec<u8>>> {
968        Ok(self
969            .prepare("SELECT data FROM device WHERE user_id = ?", |mut stmt| {
970                stmt.query((user_id,))?.mapped(|row| row.get(0)).collect()
971            })
972            .await?)
973    }
974
975    async fn get_user_identity(&self, user_id: Key) -> Result<Option<Vec<u8>>> {
976        Ok(self
977            .query_one("SELECT data FROM identity WHERE user_id = ?", (user_id,), |row| row.get(0))
978            .await
979            .optional()?)
980    }
981
982    async fn has_olm_hash(&self, data: Vec<u8>) -> Result<bool> {
983        Ok(self
984            .query_one("SELECT count(*) FROM olm_hash WHERE data = ?", (data,), |row| {
985                row.get::<_, i32>(0)
986            })
987            .await?
988            > 0)
989    }
990
991    async fn get_tracked_users(&self) -> Result<Vec<Vec<u8>>> {
992        Ok(self
993            .prepare("SELECT data FROM tracked_user", |mut stmt| {
994                stmt.query(())?.mapped(|row| row.get(0)).collect()
995            })
996            .await?)
997    }
998
999    async fn add_tracked_users(&self, users: Vec<(Key, Vec<u8>)>) -> Result<()> {
1000        Ok(self
1001            .prepare(
1002                "INSERT INTO tracked_user (user_id, data) \
1003                 VALUES (?1, ?2) \
1004                 ON CONFLICT (user_id) DO UPDATE SET data = ?2",
1005                |mut stmt| {
1006                    for (user_id, data) in users {
1007                        stmt.execute((user_id, data))?;
1008                    }
1009
1010                    Ok(())
1011                },
1012            )
1013            .await?)
1014    }
1015
1016    async fn get_outgoing_secret_request(
1017        &self,
1018        request_id: Key,
1019    ) -> Result<Option<(Vec<u8>, bool)>> {
1020        Ok(self
1021            .query_one(
1022                "SELECT data, sent_out FROM key_requests WHERE request_id = ?",
1023                (request_id,),
1024                |row| Ok((row.get(0)?, row.get(1)?)),
1025            )
1026            .await
1027            .optional()?)
1028    }
1029
1030    async fn get_secret_request_by_info(&self, info: Key) -> Result<Option<(Vec<u8>, bool)>> {
1031        Ok(self
1032            .query_one("SELECT data, sent_out FROM key_requests WHERE info = ?", (info,), |row| {
1033                Ok((row.get(0)?, row.get(1)?))
1034            })
1035            .await
1036            .optional()?)
1037    }
1038
1039    async fn get_unsent_secret_requests(&self) -> Result<Vec<Vec<u8>>> {
1040        Ok(self
1041            .prepare("SELECT data FROM key_requests WHERE sent_out = FALSE", |mut stmt| {
1042                stmt.query(())?.mapped(|row| row.get(0)).collect()
1043            })
1044            .await?)
1045    }
1046
1047    async fn delete_key_request(&self, request_id: Key) -> Result<()> {
1048        self.execute("DELETE FROM key_requests WHERE request_id = ?", (request_id,)).await?;
1049        Ok(())
1050    }
1051
1052    async fn get_secrets_from_inbox(&self, secret_name: Key) -> Result<Vec<Vec<u8>>> {
1053        Ok(self
1054            .prepare("SELECT secret FROM secrets_inbox WHERE secret_name = ?", |mut stmt| {
1055                stmt.query((secret_name,))?.mapped(|row| row.get(0)).collect()
1056            })
1057            .await?)
1058    }
1059
1060    async fn delete_secrets_from_inbox(&self, secret_name: Key) -> Result<()> {
1061        self.execute("DELETE FROM secrets_inbox WHERE secret_name = ?", (secret_name,)).await?;
1062        Ok(())
1063    }
1064
1065    async fn get_direct_withheld_info(
1066        &self,
1067        session_id: Key,
1068        room_id: Key,
1069    ) -> Result<Option<Vec<u8>>> {
1070        Ok(self
1071            .query_one(
1072                "SELECT data FROM direct_withheld_info WHERE session_id = ?1 AND room_id = ?2",
1073                (session_id, room_id),
1074                |row| row.get(0),
1075            )
1076            .await
1077            .optional()?)
1078    }
1079
1080    async fn get_withheld_sessions_by_room_id(&self, room_id: Key) -> Result<Vec<Vec<u8>>> {
1081        Ok(self
1082            .prepare("SELECT data FROM direct_withheld_info WHERE room_id = ?1", |mut stmt| {
1083                stmt.query((room_id,))?.mapped(|row| row.get(0)).collect()
1084            })
1085            .await?)
1086    }
1087
1088    async fn get_room_settings(&self, room_id: Key) -> Result<Option<Vec<u8>>> {
1089        Ok(self
1090            .query_one("SELECT data FROM room_settings WHERE room_id = ?", (room_id,), |row| {
1091                row.get(0)
1092            })
1093            .await
1094            .optional()?)
1095    }
1096
1097    async fn get_received_room_key_bundle(
1098        &self,
1099        room_id: Key,
1100        sender_user: Key,
1101    ) -> Result<Option<Vec<u8>>> {
1102        Ok(self
1103            .query_one(
1104                "SELECT bundle_data FROM received_room_key_bundle WHERE room_id = ? AND sender_user_id = ?",
1105                (room_id, sender_user),
1106                |row| { row.get(0) },
1107            )
1108            .await
1109            .optional()?)
1110    }
1111
1112    async fn get_room_pending_key_bundle(&self, room_id: Key) -> Result<Option<Vec<u8>>> {
1113        Ok(self
1114            .query_one(
1115                "SELECT data FROM rooms_pending_key_bundle WHERE room_id = ?",
1116                (room_id,),
1117                |row| row.get(0),
1118            )
1119            .await
1120            .optional()?)
1121    }
1122
1123    async fn get_all_rooms_pending_key_bundle(&self) -> Result<Vec<Vec<u8>>> {
1124        Ok(self
1125            .query_many("SELECT data FROM rooms_pending_key_bundle", (), |row| row.get(0))
1126            .await?)
1127    }
1128
1129    async fn has_downloaded_all_room_keys(&self, room_id: Key) -> Result<bool> {
1130        Ok(self
1131            .query_row(
1132                "SELECT EXISTS (SELECT 1 FROM room_key_backups_fully_downloaded WHERE room_id = ?)",
1133                (room_id,),
1134                |row| row.get(0),
1135            )
1136            .await?)
1137    }
1138}
1139
1140#[async_trait]
1141impl SqliteObjectCryptoStoreExt for SqliteAsyncConn {}
1142
1143#[async_trait]
1144impl CryptoStore for SqliteCryptoStore {
1145    type Error = Error;
1146
1147    async fn load_account(&self) -> Result<Option<Account>> {
1148        let conn = self.read().await?;
1149        if let Some(pickle) = conn.get_kv("account").await? {
1150            let pickle = self.deserialize_value(&pickle)?;
1151
1152            let account = Account::from_pickle(pickle).map_err(|_| Error::Unpickle)?;
1153
1154            *self.static_account.write().unwrap() = Some(account.static_data().clone());
1155
1156            Ok(Some(account))
1157        } else {
1158            Ok(None)
1159        }
1160    }
1161
1162    async fn load_identity(&self) -> Result<Option<PrivateCrossSigningIdentity>> {
1163        let conn = self.read().await?;
1164        if let Some(i) = conn.get_kv("identity").await? {
1165            let pickle = self.deserialize_value(&i)?;
1166            Ok(Some(PrivateCrossSigningIdentity::from_pickle(pickle).map_err(|_| Error::Unpickle)?))
1167        } else {
1168            Ok(None)
1169        }
1170    }
1171
1172    async fn save_pending_changes(&self, changes: PendingChanges) -> Result<()> {
1173        // Serialize calls to `save_pending_changes`; there are multiple await
1174        // points below, and we're pickling data as we go, so we don't want to
1175        // invalidate data we've previously read and overwrite it in the store.
1176        // TODO: #2000 should make this lock go away, or change its shape.
1177        let _guard = self.save_changes_lock.lock().await;
1178
1179        let pickled_account = if let Some(account) = changes.account {
1180            *self.static_account.write().unwrap() = Some(account.static_data().clone());
1181            Some(account.pickle())
1182        } else {
1183            None
1184        };
1185
1186        let this = self.clone();
1187        self.write()
1188            .await?
1189            .with_immediate_transaction(move |txn| {
1190                if let Some(pickled_account) = pickled_account {
1191                    let serialized_account = this.serialize_value(&pickled_account)?;
1192                    txn.set_kv("account", &serialized_account)?;
1193                }
1194
1195                Ok::<_, Error>(())
1196            })
1197            .await?;
1198
1199        Ok(())
1200    }
1201
1202    async fn save_changes(&self, changes: Changes) -> Result<()> {
1203        // Serialize calls to `save_changes`; there are multiple await points
1204        // below, and we're pickling data as we go, so we don't want to
1205        // invalidate data we've previously read and overwrite it in the store.
1206        // TODO: #2000 should make this lock go away, or change its shape.
1207        let _guard = self.save_changes_lock.lock().await;
1208
1209        let pickled_private_identity =
1210            if let Some(i) = changes.private_identity { Some(i.pickle().await) } else { None };
1211
1212        let mut session_changes = Vec::new();
1213
1214        for session in changes.sessions {
1215            let session_id = self.encode_key("session", session.session_id());
1216            let sender_key = self.encode_key("session", session.sender_key().to_base64());
1217            let pickle = session.pickle().await;
1218            session_changes.push((session_id, sender_key, pickle));
1219        }
1220
1221        let mut inbound_session_changes = Vec::new();
1222        for session in changes.inbound_group_sessions {
1223            let room_id = self.encode_key("inbound_group_session", session.room_id().as_bytes());
1224            let session_id = self.encode_key("inbound_group_session", session.session_id());
1225            let pickle = session.pickle().await;
1226            let sender_key =
1227                self.encode_key("inbound_group_session", session.sender_key().to_base64());
1228            inbound_session_changes.push((room_id, session_id, pickle, sender_key));
1229        }
1230
1231        let mut outbound_session_changes = Vec::new();
1232        for session in changes.outbound_group_sessions {
1233            let room_id = self.encode_key("outbound_group_session", session.room_id().as_bytes());
1234            let pickle = session.pickle().await;
1235            outbound_session_changes.push((room_id, pickle));
1236        }
1237
1238        let this = self.clone();
1239        self.write()
1240            .await?
1241            .with_immediate_transaction(move |txn| {
1242                if let Some(pickled_private_identity) = &pickled_private_identity {
1243                    let serialized_private_identity =
1244                        this.serialize_value(pickled_private_identity)?;
1245                    txn.set_kv("identity", &serialized_private_identity)?;
1246                }
1247
1248                if let Some(token) = &changes.next_batch_token {
1249                    let serialized_token = this.serialize_value(token)?;
1250                    txn.set_kv("next_batch_token", &serialized_token)?;
1251                }
1252
1253                if let Some(decryption_key) = &changes.backup_decryption_key {
1254                    let serialized_decryption_key = this.serialize_value(decryption_key)?;
1255                    txn.set_kv("recovery_key_v1", &serialized_decryption_key)?;
1256                }
1257
1258                if let Some(backup_version) = &changes.backup_version {
1259                    let serialized_backup_version = this.serialize_value(backup_version)?;
1260                    txn.set_kv("backup_version_v1", &serialized_backup_version)?;
1261                }
1262
1263                if let Some(pickle_key) = &changes.dehydrated_device_pickle_key {
1264                    let serialized_pickle_key = this.serialize_value(pickle_key)?;
1265                    txn.set_kv(DEHYDRATED_DEVICE_PICKLE_KEY, &serialized_pickle_key)?;
1266                }
1267
1268                for device in changes.devices.new.iter().chain(&changes.devices.changed) {
1269                    let user_id = this.encode_key("device", device.user_id().as_bytes());
1270                    let device_id = this.encode_key("device", device.device_id().as_bytes());
1271                    let data = this.serialize_value(&device)?;
1272                    txn.set_device(&user_id, &device_id, &data)?;
1273                }
1274
1275                for device in &changes.devices.deleted {
1276                    let user_id = this.encode_key("device", device.user_id().as_bytes());
1277                    let device_id = this.encode_key("device", device.device_id().as_bytes());
1278                    txn.delete_device(&user_id, &device_id)?;
1279                }
1280
1281                for identity in changes.identities.changed.iter().chain(&changes.identities.new) {
1282                    let user_id = this.encode_key("identity", identity.user_id().as_bytes());
1283                    let data = this.serialize_value(&identity)?;
1284                    txn.set_identity(&user_id, &data)?;
1285                }
1286
1287                for (session_id, sender_key, pickle) in &session_changes {
1288                    let serialized_session = this.serialize_value(&pickle)?;
1289                    txn.set_session(session_id, sender_key, &serialized_session)?;
1290                }
1291
1292                for (room_id, session_id, pickle, sender_key) in &inbound_session_changes {
1293                    let serialized_session = this.serialize_value(&pickle)?;
1294                    txn.set_inbound_group_session(
1295                        room_id,
1296                        session_id,
1297                        &serialized_session,
1298                        pickle.backed_up,
1299                        Some(sender_key),
1300                        Some(pickle.sender_data.to_type() as u8),
1301                    )?;
1302                }
1303
1304                for (room_id, pickle) in &outbound_session_changes {
1305                    let serialized_session = this.serialize_json(&pickle)?;
1306                    txn.set_outbound_group_session(room_id, &serialized_session)?;
1307                }
1308
1309                for hash in &changes.message_hashes {
1310                    let hash = rmp_serde::to_vec(hash)?;
1311                    txn.add_olm_hash(&hash)?;
1312                }
1313
1314                for request in changes.key_requests {
1315                    let request_id = this.encode_key("key_requests", request.request_id.as_bytes());
1316                    let serialized_request = this.serialize_value(&request)?;
1317                    let serialized_info = this.encode_key("key_requests", request.info.as_key());
1318                    txn.set_key_request(
1319                        &request_id,
1320                        request.sent_out,
1321                        &serialized_request,
1322                        &serialized_info,
1323                    )?;
1324                }
1325
1326                for (room_id, data) in changes.withheld_session_info {
1327                    for (session_id, event) in data {
1328                        let session_id = this.encode_key("direct_withheld_info", session_id);
1329                        let room_id = this.encode_key("direct_withheld_info", &room_id);
1330                        let serialized_info = this.serialize_json(&event)?;
1331                        txn.set_direct_withheld(&session_id, &room_id, &serialized_info)?;
1332                    }
1333                }
1334
1335                for (room_id, settings) in changes.room_settings {
1336                    let room_id = this.encode_key("room_settings", room_id.as_bytes());
1337                    let value = this.serialize_value(&settings)?;
1338                    txn.set_room_settings(&room_id, &value)?;
1339                }
1340
1341                for secret in changes.secrets {
1342                    let secret_name =
1343                        this.encode_key("secrets_inbox", secret.secret_name.to_string());
1344                    let value = this.serialize_json(secret.secret.deref())?;
1345                    txn.set_secret(&secret_name, &value)?;
1346                }
1347
1348                for bundle in changes.received_room_key_bundles {
1349                    let room_id =
1350                        this.encode_key("received_room_key_bundle", &bundle.bundle_data.room_id);
1351                    let user_id = this.encode_key("received_room_key_bundle", &bundle.sender_user);
1352                    let value = this.serialize_value(&bundle)?;
1353                    txn.set_received_room_key_bundle(&room_id, &user_id, &value)?;
1354                }
1355
1356                for room in changes.room_key_backups_fully_downloaded {
1357                    let room_id = this.encode_key("room_key_backups_fully_downloaded", &room);
1358                    txn.set_has_downloaded_all_room_keys(&room_id)?;
1359                }
1360
1361                for (room, details) in changes.rooms_pending_key_bundle {
1362                    let room_id = this.encode_key("rooms_pending_key_bundle", &room);
1363                    let value = details.as_ref().map(|d| this.serialize_value(d)).transpose()?;
1364                    txn.set_room_pending_key_bundle(&room_id, value.as_deref())?;
1365                }
1366
1367                Ok::<_, Error>(())
1368            })
1369            .await?;
1370
1371        Ok(())
1372    }
1373
1374    async fn save_inbound_group_sessions(
1375        &self,
1376        sessions: Vec<InboundGroupSession>,
1377        backed_up_to_version: Option<&str>,
1378    ) -> matrix_sdk_crypto::store::Result<(), Self::Error> {
1379        // Sanity-check that the data in the sessions corresponds to
1380        // backed_up_version
1381        sessions.iter().for_each(|s| {
1382            let backed_up = s.backed_up();
1383            if backed_up != backed_up_to_version.is_some() {
1384                warn!(
1385                    backed_up,
1386                    backed_up_to_version,
1387                    "Session backed-up flag does not correspond to backup version setting",
1388                );
1389            }
1390        });
1391
1392        // Currently, this store doesn't save the backup version separately, so
1393        // this just delegates to save_changes.
1394        self.save_changes(Changes { inbound_group_sessions: sessions, ..Changes::default() }).await
1395    }
1396
1397    async fn get_sessions(&self, sender_key: &str) -> Result<Option<Vec<Session>>> {
1398        let device_keys = self.get_own_device().await?.as_device_keys().clone();
1399
1400        let sessions: Vec<_> = self
1401            .read()
1402            .await?
1403            .get_sessions_for_sender_key(self.encode_key("session", sender_key.as_bytes()))
1404            .await?
1405            .into_iter()
1406            .map(|bytes| {
1407                let pickle = self.deserialize_value(&bytes)?;
1408                Session::from_pickle(device_keys.clone(), pickle).map_err(|_| Error::AccountUnset)
1409            })
1410            .collect::<Result<_>>()?;
1411
1412        if sessions.is_empty() { Ok(None) } else { Ok(Some(sessions)) }
1413    }
1414
1415    #[instrument(skip(self))]
1416    async fn get_inbound_group_session(
1417        &self,
1418        room_id: &RoomId,
1419        session_id: &str,
1420    ) -> Result<Option<InboundGroupSession>> {
1421        let session_id = self.encode_key("inbound_group_session", session_id);
1422        let Some((room_id_from_db, value, backed_up)) =
1423            self.read().await?.get_inbound_group_session(session_id).await?
1424        else {
1425            return Ok(None);
1426        };
1427
1428        let room_id = self.encode_key("inbound_group_session", room_id.as_bytes());
1429        if *room_id != room_id_from_db {
1430            warn!("expected room_id for session_id doesn't match what's in the DB");
1431            return Ok(None);
1432        }
1433
1434        Ok(Some(self.deserialize_and_unpickle_inbound_group_session(value, backed_up)?))
1435    }
1436
1437    async fn get_inbound_group_sessions(&self) -> Result<Vec<InboundGroupSession>> {
1438        self.read()
1439            .await?
1440            .get_inbound_group_sessions()
1441            .await?
1442            .into_iter()
1443            .map(|(value, backed_up)| {
1444                self.deserialize_and_unpickle_inbound_group_session(value, backed_up)
1445            })
1446            .collect()
1447    }
1448
1449    async fn get_inbound_group_sessions_by_room_id(
1450        &self,
1451        room_id: &RoomId,
1452    ) -> Result<Vec<InboundGroupSession>> {
1453        let room_id = self.encode_key("inbound_group_session", room_id.as_bytes());
1454        self.read()
1455            .await?
1456            .get_inbound_group_sessions_by_room_id(room_id)
1457            .await?
1458            .into_iter()
1459            .map(|(value, backed_up)| {
1460                self.deserialize_and_unpickle_inbound_group_session(value, backed_up)
1461            })
1462            .collect()
1463    }
1464
1465    async fn get_inbound_group_sessions_for_device_batch(
1466        &self,
1467        sender_key: Curve25519PublicKey,
1468        sender_data_type: SenderDataType,
1469        after_session_id: Option<String>,
1470        limit: usize,
1471    ) -> Result<Vec<InboundGroupSession>, Self::Error> {
1472        let after_session_id =
1473            after_session_id.map(|session_id| self.encode_key("inbound_group_session", session_id));
1474        let sender_key = self.encode_key("inbound_group_session", sender_key.to_base64());
1475
1476        self.read()
1477            .await?
1478            .get_inbound_group_sessions_for_device_batch(
1479                sender_key,
1480                sender_data_type,
1481                after_session_id,
1482                limit,
1483            )
1484            .await?
1485            .into_iter()
1486            .map(|(value, backed_up)| {
1487                self.deserialize_and_unpickle_inbound_group_session(value, backed_up)
1488            })
1489            .collect()
1490    }
1491
1492    async fn inbound_group_session_counts(
1493        &self,
1494        backup_version: Option<&str>,
1495    ) -> Result<RoomKeyCounts> {
1496        Ok(self.read().await?.get_inbound_group_session_counts(backup_version).await?)
1497    }
1498
1499    async fn inbound_group_sessions_for_backup(
1500        &self,
1501        _backup_version: &str,
1502        limit: usize,
1503    ) -> Result<Vec<InboundGroupSession>> {
1504        self.read()
1505            .await?
1506            .get_inbound_group_sessions_for_backup(limit)
1507            .await?
1508            .into_iter()
1509            .map(|value| self.deserialize_and_unpickle_inbound_group_session(value, false))
1510            .collect()
1511    }
1512
1513    async fn mark_inbound_group_sessions_as_backed_up(
1514        &self,
1515        _backup_version: &str,
1516        session_ids: &[(&RoomId, &str)],
1517    ) -> Result<()> {
1518        Ok(self
1519            .write()
1520            .await?
1521            .mark_inbound_group_sessions_as_backed_up(
1522                session_ids
1523                    .iter()
1524                    .map(|(_, s)| self.encode_key("inbound_group_session", s))
1525                    .collect(),
1526            )
1527            .await?)
1528    }
1529
1530    async fn reset_backup_state(&self) -> Result<()> {
1531        Ok(self.write().await?.reset_inbound_group_session_backup_state().await?)
1532    }
1533
1534    async fn load_backup_keys(&self) -> Result<BackupKeys> {
1535        let conn = self.read().await?;
1536
1537        let backup_version = conn
1538            .get_kv("backup_version_v1")
1539            .await?
1540            .map(|value| self.deserialize_value(&value))
1541            .transpose()?;
1542
1543        let decryption_key = conn
1544            .get_kv("recovery_key_v1")
1545            .await?
1546            .map(|value| self.deserialize_value(&value))
1547            .transpose()?;
1548
1549        Ok(BackupKeys { backup_version, decryption_key })
1550    }
1551
1552    async fn load_dehydrated_device_pickle_key(&self) -> Result<Option<DehydratedDeviceKey>> {
1553        let conn = self.read().await?;
1554
1555        conn.get_kv(DEHYDRATED_DEVICE_PICKLE_KEY)
1556            .await?
1557            .map(|value| self.deserialize_value(&value))
1558            .transpose()
1559    }
1560
1561    async fn delete_dehydrated_device_pickle_key(&self) -> Result<(), Self::Error> {
1562        Ok(self.write().await?.clear_kv(DEHYDRATED_DEVICE_PICKLE_KEY).await?)
1563    }
1564    async fn get_outbound_group_session(
1565        &self,
1566        room_id: &RoomId,
1567    ) -> Result<Option<OutboundGroupSession>> {
1568        let room_id = self.encode_key("outbound_group_session", room_id.as_bytes());
1569        let Some(value) = self.read().await?.get_outbound_group_session(room_id).await? else {
1570            return Ok(None);
1571        };
1572
1573        let account_info = self.get_static_account().ok_or(Error::AccountUnset)?;
1574
1575        let pickle = self.deserialize_json(&value)?;
1576        let session = OutboundGroupSession::from_pickle(
1577            account_info.device_id,
1578            account_info.identity_keys,
1579            pickle,
1580        )
1581        .map_err(|_| Error::Unpickle)?;
1582
1583        return Ok(Some(session));
1584    }
1585
1586    async fn load_tracked_users(&self) -> Result<Vec<TrackedUser>> {
1587        self.read()
1588            .await?
1589            .get_tracked_users()
1590            .await?
1591            .iter()
1592            .map(|value| self.deserialize_value(value))
1593            .collect()
1594    }
1595
1596    async fn save_tracked_users(&self, tracked_users: &[(&UserId, bool)]) -> Result<()> {
1597        let users: Vec<(Key, Vec<u8>)> = tracked_users
1598            .iter()
1599            .map(|(u, d)| {
1600                let user_id = self.encode_key("tracked_users", u.as_bytes());
1601                let data =
1602                    self.serialize_value(&TrackedUser { user_id: (*u).into(), dirty: *d })?;
1603                Ok((user_id, data))
1604            })
1605            .collect::<Result<_>>()?;
1606
1607        Ok(self.write().await?.add_tracked_users(users).await?)
1608    }
1609
1610    async fn get_device(
1611        &self,
1612        user_id: &UserId,
1613        device_id: &DeviceId,
1614    ) -> Result<Option<DeviceData>> {
1615        let user_id = self.encode_key("device", user_id.as_bytes());
1616        let device_id = self.encode_key("device", device_id.as_bytes());
1617        Ok(self
1618            .read()
1619            .await?
1620            .get_device(user_id, device_id)
1621            .await?
1622            .map(|value| self.deserialize_value(&value))
1623            .transpose()?)
1624    }
1625
1626    async fn get_user_devices(
1627        &self,
1628        user_id: &UserId,
1629    ) -> Result<HashMap<OwnedDeviceId, DeviceData>> {
1630        let user_id = self.encode_key("device", user_id.as_bytes());
1631        self.read()
1632            .await?
1633            .get_user_devices(user_id)
1634            .await?
1635            .into_iter()
1636            .map(|value| {
1637                let device: DeviceData = self.deserialize_value(&value)?;
1638                Ok((device.device_id().to_owned(), device))
1639            })
1640            .collect()
1641    }
1642
1643    async fn get_own_device(&self) -> Result<DeviceData> {
1644        let account_info = self.get_static_account().ok_or(Error::AccountUnset)?;
1645
1646        Ok(self
1647            .get_device(&account_info.user_id, &account_info.device_id)
1648            .await?
1649            .expect("We should be able to find our own device."))
1650    }
1651
1652    async fn get_user_identity(&self, user_id: &UserId) -> Result<Option<UserIdentityData>> {
1653        let user_id = self.encode_key("identity", user_id.as_bytes());
1654        Ok(self
1655            .read()
1656            .await?
1657            .get_user_identity(user_id)
1658            .await?
1659            .map(|value| self.deserialize_value(&value))
1660            .transpose()?)
1661    }
1662
1663    async fn is_message_known(
1664        &self,
1665        message_hash: &matrix_sdk_crypto::olm::OlmMessageHash,
1666    ) -> Result<bool> {
1667        let value = rmp_serde::to_vec(message_hash)?;
1668        Ok(self.read().await?.has_olm_hash(value).await?)
1669    }
1670
1671    async fn get_outgoing_secret_requests(
1672        &self,
1673        request_id: &TransactionId,
1674    ) -> Result<Option<GossipRequest>> {
1675        let request_id = self.encode_key("key_requests", request_id.as_bytes());
1676        Ok(self
1677            .read()
1678            .await?
1679            .get_outgoing_secret_request(request_id)
1680            .await?
1681            .map(|(value, sent_out)| self.deserialize_key_request(&value, sent_out))
1682            .transpose()?)
1683    }
1684
1685    async fn get_secret_request_by_info(
1686        &self,
1687        key_info: &SecretInfo,
1688    ) -> Result<Option<GossipRequest>> {
1689        let key_info = self.encode_key("key_requests", key_info.as_key());
1690        Ok(self
1691            .read()
1692            .await?
1693            .get_secret_request_by_info(key_info)
1694            .await?
1695            .map(|(value, sent_out)| self.deserialize_key_request(&value, sent_out))
1696            .transpose()?)
1697    }
1698
1699    async fn get_unsent_secret_requests(&self) -> Result<Vec<GossipRequest>> {
1700        self.read()
1701            .await?
1702            .get_unsent_secret_requests()
1703            .await?
1704            .iter()
1705            .map(|value| {
1706                let request = self.deserialize_key_request(value, false)?;
1707                Ok(request)
1708            })
1709            .collect()
1710    }
1711
1712    async fn delete_outgoing_secret_requests(&self, request_id: &TransactionId) -> Result<()> {
1713        let request_id = self.encode_key("key_requests", request_id.as_bytes());
1714        Ok(self.write().await?.delete_key_request(request_id).await?)
1715    }
1716
1717    async fn get_secrets_from_inbox(
1718        &self,
1719        secret_name: &SecretName,
1720    ) -> Result<Vec<Zeroizing<String>>> {
1721        let secret_name = self.encode_key("secrets_inbox", secret_name.to_string());
1722
1723        self.read()
1724            .await?
1725            .get_secrets_from_inbox(secret_name)
1726            .await?
1727            .into_iter()
1728            .map(|value| self.deserialize_json(value.as_ref()).map(|value: String| value.into()))
1729            .collect()
1730    }
1731
1732    async fn delete_secrets_from_inbox(&self, secret_name: &SecretName) -> Result<()> {
1733        let secret_name = self.encode_key("secrets_inbox", secret_name.to_string());
1734        self.write().await?.delete_secrets_from_inbox(secret_name).await
1735    }
1736
1737    async fn get_withheld_info(
1738        &self,
1739        room_id: &RoomId,
1740        session_id: &str,
1741    ) -> Result<Option<RoomKeyWithheldEntry>> {
1742        let room_id = self.encode_key("direct_withheld_info", room_id);
1743        let session_id = self.encode_key("direct_withheld_info", session_id);
1744
1745        self.read()
1746            .await?
1747            .get_direct_withheld_info(session_id, room_id)
1748            .await?
1749            .map(|value| {
1750                let info = self.deserialize_json::<RoomKeyWithheldEntry>(&value)?;
1751                Ok(info)
1752            })
1753            .transpose()
1754    }
1755
1756    async fn get_withheld_sessions_by_room_id(
1757        &self,
1758        room_id: &RoomId,
1759    ) -> matrix_sdk_crypto::store::Result<Vec<RoomKeyWithheldEntry>, Self::Error> {
1760        let room_id = self.encode_key("direct_withheld_info", room_id);
1761
1762        self.read()
1763            .await?
1764            .get_withheld_sessions_by_room_id(room_id)
1765            .await?
1766            .into_iter()
1767            .map(|value| self.deserialize_json(&value))
1768            .collect()
1769    }
1770
1771    async fn get_room_settings(&self, room_id: &RoomId) -> Result<Option<RoomSettings>> {
1772        let room_id = self.encode_key("room_settings", room_id.as_bytes());
1773        let Some(value) = self.read().await?.get_room_settings(room_id).await? else {
1774            return Ok(None);
1775        };
1776
1777        let settings = self.deserialize_value(&value)?;
1778
1779        return Ok(Some(settings));
1780    }
1781
1782    async fn get_received_room_key_bundle_data(
1783        &self,
1784        room_id: &RoomId,
1785        user_id: &UserId,
1786    ) -> Result<Option<StoredRoomKeyBundleData>> {
1787        let room_id = self.encode_key("received_room_key_bundle", room_id);
1788        let user_id = self.encode_key("received_room_key_bundle", user_id);
1789        self.read()
1790            .await?
1791            .get_received_room_key_bundle(room_id, user_id)
1792            .await?
1793            .map(|value| self.deserialize_value(&value))
1794            .transpose()
1795    }
1796
1797    async fn has_downloaded_all_room_keys(&self, room_id: &RoomId) -> Result<bool> {
1798        let room_id = self.encode_key("room_key_backups_fully_downloaded", room_id);
1799        self.read().await?.has_downloaded_all_room_keys(room_id).await
1800    }
1801
1802    async fn get_pending_key_bundle_details_for_room(
1803        &self,
1804        room_id: &RoomId,
1805    ) -> Result<Option<RoomPendingKeyBundleDetails>> {
1806        let room_id = self.encode_key("rooms_pending_key_bundle", room_id.as_bytes());
1807        let Some(value) = self.read().await?.get_room_pending_key_bundle(room_id).await? else {
1808            return Ok(None);
1809        };
1810
1811        let details = self.deserialize_value(&value)?;
1812        Ok(Some(details))
1813    }
1814
1815    async fn get_all_rooms_pending_key_bundles(&self) -> Result<Vec<RoomPendingKeyBundleDetails>> {
1816        let details = self.read().await?.get_all_rooms_pending_key_bundle().await?;
1817        let room_ids = details
1818            .into_iter()
1819            .map(|value| self.deserialize_value(&value))
1820            .collect::<Result<_, _>>()?;
1821        Ok(room_ids)
1822    }
1823
1824    async fn get_custom_value(&self, key: &str) -> Result<Option<Vec<u8>>> {
1825        let Some(serialized) = self.read().await?.get_kv(key).await? else {
1826            return Ok(None);
1827        };
1828        let value = if let Some(cipher) = &self.store_cipher {
1829            let encrypted = rmp_serde::from_slice(&serialized)?;
1830            cipher.decrypt_value_data(encrypted)?
1831        } else {
1832            serialized
1833        };
1834
1835        Ok(Some(value))
1836    }
1837
1838    async fn set_custom_value(&self, key: &str, value: Vec<u8>) -> Result<()> {
1839        let serialized = if let Some(cipher) = &self.store_cipher {
1840            let encrypted = cipher.encrypt_value_data(value)?;
1841            rmp_serde::to_vec_named(&encrypted)?
1842        } else {
1843            value
1844        };
1845
1846        self.write().await?.set_kv(key, serialized).await?;
1847        Ok(())
1848    }
1849
1850    async fn remove_custom_value(&self, key: &str) -> Result<()> {
1851        let key = key.to_owned();
1852        self.write()
1853            .await?
1854            .interact(move |conn| conn.execute("DELETE FROM kv WHERE key = ?1", (&key,)))
1855            .await
1856            .map_err(map_interact_err)
1857            .flatten()?;
1858        Ok(())
1859    }
1860
1861    #[instrument(skip(self))]
1862    async fn try_take_leased_lock(
1863        &self,
1864        lease_duration_ms: u32,
1865        key: &str,
1866        holder: &str,
1867    ) -> Result<Option<CrossProcessLockGeneration>> {
1868        let key = key.to_owned();
1869        let holder = holder.to_owned();
1870
1871        let now: u64 = MilliSecondsSinceUnixEpoch::now().get().into();
1872        let expiration = now + lease_duration_ms as u64;
1873
1874        // Learn about the `excluded` keyword in https://sqlite.org/lang_upsert.html.
1875        let generation = self
1876            .write()
1877            .await?
1878            .with_immediate_transaction(move |txn| {
1879                txn.query_one(
1880                    "INSERT INTO lease_locks (key, holder, expiration)
1881                    VALUES (?1, ?2, ?3)
1882                    ON CONFLICT (key)
1883                    DO
1884                        UPDATE SET
1885                            holder = excluded.holder,
1886                            expiration = excluded.expiration,
1887                            generation =
1888                                CASE holder
1889                                    WHEN excluded.holder THEN generation
1890                                    ELSE generation + 1
1891                                END
1892                        WHERE
1893                            holder = excluded.holder
1894                            OR expiration < ?4
1895                    RETURNING generation
1896                    ",
1897                    (key, holder, expiration, now),
1898                    |row| row.get(0),
1899                )
1900                .optional()
1901            })
1902            .await?;
1903
1904        Ok(generation)
1905    }
1906
1907    async fn next_batch_token(&self) -> Result<Option<String>, Self::Error> {
1908        let conn = self.read().await?;
1909        if let Some(token) = conn.get_kv("next_batch_token").await? {
1910            let maybe_token: Option<String> = self.deserialize_value(&token)?;
1911            Ok(maybe_token)
1912        } else {
1913            Ok(None)
1914        }
1915    }
1916
1917    async fn delete_next_batch_token(&self) -> Result<(), Self::Error> {
1918        self.remove_custom_value("next_batch_token").await
1919    }
1920
1921    async fn close(&self) -> Result<()> {
1922        connection::close_connections(&self.connections, "Crypto store").await;
1923        Ok(())
1924    }
1925
1926    async fn reopen(&self) -> Result<()> {
1927        connection::reopen_connections(
1928            &self.connections,
1929            self.db_path.clone(),
1930            self.pool_config,
1931            self.runtime_config,
1932        )
1933        .await?;
1934        Ok(())
1935    }
1936
1937    async fn get_size(&self) -> Result<Option<usize>, Self::Error> {
1938        Ok(Some(self.read().await?.get_db_size().await?))
1939    }
1940}
1941
1942#[cfg(test)]
1943mod tests {
1944    use std::{path::Path, sync::LazyLock};
1945
1946    use matrix_sdk_common::deserialized_responses::WithheldCode;
1947    use matrix_sdk_crypto::{
1948        cryptostore_integration_tests, cryptostore_integration_tests_time, olm::SenderDataType,
1949        store::CryptoStore,
1950    };
1951    use matrix_sdk_test::async_test;
1952    use ruma::{device_id, room_id, user_id};
1953    use similar_asserts::assert_eq;
1954    use tempfile::{TempDir, tempdir};
1955    use tokio::fs;
1956
1957    use super::SqliteCryptoStore;
1958    use crate::SqliteStoreConfig;
1959
1960    static TMP_DIR: LazyLock<TempDir> = LazyLock::new(|| tempdir().unwrap());
1961
1962    struct TestDb {
1963        // Needs to be kept alive because the Drop implementation for TempDir
1964        // deletes the directory.
1965        _dir: TempDir,
1966        database: SqliteCryptoStore,
1967    }
1968
1969    fn copy_db(data_path: &str) -> TempDir {
1970        let db_name = super::DATABASE_NAME;
1971
1972        let manifest_path = Path::new(env!("CARGO_MANIFEST_DIR")).join("../..");
1973        let database_path = manifest_path.join(data_path).join(db_name);
1974
1975        let tmpdir = tempdir().unwrap();
1976        let destination = tmpdir.path().join(db_name);
1977
1978        // Copy the test database to the tempdir so our test runs are
1979        // idempotent.
1980        std::fs::copy(&database_path, destination).unwrap();
1981
1982        tmpdir
1983    }
1984
1985    async fn get_test_db(data_path: &str, passphrase: Option<&str>) -> TestDb {
1986        let tmpdir = copy_db(data_path);
1987
1988        let database = SqliteCryptoStore::open(tmpdir.path(), passphrase)
1989            .await
1990            .expect("Can't open the test store");
1991
1992        TestDb { _dir: tmpdir, database }
1993    }
1994
1995    #[async_test]
1996    async fn test_pool_size() {
1997        let store_open_config =
1998            SqliteStoreConfig::new(TMP_DIR.path().join("test_pool_size")).pool_max_size(42);
1999
2000        let store = SqliteCryptoStore::open_with_config(&store_open_config).await.unwrap();
2001
2002        let guard = store.connections.lock().await;
2003        let conns = guard.as_ref().unwrap();
2004        assert_eq!(conns.pool.status().max_size, 42);
2005    }
2006
2007    /// Test that we didn't regress in our storage layer by loading data from a
2008    /// pre-filled database, or in other words use a test vector for this.
2009    #[async_test]
2010    async fn test_open_test_vector_store() {
2011        let TestDb { _dir: _, database } = get_test_db("testing/data/storage", None).await;
2012
2013        let account = database
2014            .load_account()
2015            .await
2016            .unwrap()
2017            .expect("The test database is prefilled with data, we should find an account");
2018
2019        let user_id = account.user_id();
2020        let device_id = account.device_id();
2021
2022        assert_eq!(
2023            user_id.as_str(),
2024            "@pjtest:synapse-oidc.element.dev",
2025            "The user ID should match to the one we expect."
2026        );
2027
2028        assert_eq!(
2029            device_id.as_str(),
2030            "v4TqgcuIH6",
2031            "The device ID should match to the one we expect."
2032        );
2033
2034        let device = database
2035            .get_device(user_id, device_id)
2036            .await
2037            .unwrap()
2038            .expect("Our own device should be found in the store.");
2039
2040        assert_eq!(device.device_id(), device_id);
2041        assert_eq!(device.user_id(), user_id);
2042
2043        assert_eq!(
2044            device.ed25519_key().expect("The device should have a Ed25519 key.").to_base64(),
2045            "+cxl1Gl3du5i7UJwfWnoRDdnafFF+xYdAiTYYhYLr8s"
2046        );
2047
2048        assert_eq!(
2049            device.curve25519_key().expect("The device should have a Curve25519 key.").to_base64(),
2050            "4SL9eEUlpyWSUvjljC5oMjknHQQJY7WZKo5S1KL/5VU"
2051        );
2052
2053        let identity = database
2054            .get_user_identity(user_id)
2055            .await
2056            .unwrap()
2057            .expect("The store should contain an identity.");
2058
2059        assert_eq!(identity.user_id(), user_id);
2060
2061        let identity = identity
2062            .own()
2063            .expect("The identity should be of the correct type, it should be our own identity.");
2064
2065        let master_key = identity
2066            .master_key()
2067            .get_first_key()
2068            .expect("Our own identity should have a master key");
2069
2070        assert_eq!(master_key.to_base64(), "iCUEtB1RwANeqRa5epDrblLk4mer/36sylwQ5hYY3oE");
2071    }
2072
2073    /// Test that we didn't regress in our storage layer by loading data from a
2074    /// pre-filled database, or in other words use a test vector for this.
2075    #[async_test]
2076    async fn test_open_test_vector_encrypted_store() {
2077        let TestDb { _dir: _, database } = get_test_db(
2078            "testing/data/storage/alice",
2079            Some(concat!(
2080                "/rCia2fYAJ+twCZ1Xm2mxFCYcmJdyzkdJjwtgXsziWpYS/UeNxnixuSieuwZXm+x1VsJHmWpl",
2081                "H+QIQBZpEGZtC9/S/l8xK+WOCesmET0o6yJ/KP73ofDtjBlnNpPwuHLKFpyTbyicpCgQ4UT+5E",
2082                "UBuJ08TY9Ujdf1D13k5kr5tSZUefDKKCuG1fCRqlU8ByRas1PMQsZxT2W8t7QgBrQiiGmhpo/O",
2083                "Ti4hfx97GOxncKcxTzppiYQNoHs/f15+XXQD7/oiCcqRIuUlXNsU6hRpFGmbYx2Pi1eyQViQCt",
2084                "B5dAEiSD0N8U81wXYnpynuTPtnL+hfnOJIn7Sy7mkERQeKg"
2085            )),
2086        )
2087        .await;
2088
2089        let account = database
2090            .load_account()
2091            .await
2092            .unwrap()
2093            .expect("The test database is prefilled with data, we should find an account");
2094
2095        let user_id = account.user_id();
2096        let device_id = account.device_id();
2097
2098        assert_eq!(
2099            user_id.as_str(),
2100            "@alice:localhost",
2101            "The user ID should match to the one we expect."
2102        );
2103
2104        assert_eq!(
2105            device_id.as_str(),
2106            "JVVORTHFXY",
2107            "The device ID should match to the one we expect."
2108        );
2109
2110        let tracked_users =
2111            database.load_tracked_users().await.expect("Should be tracking some users");
2112
2113        assert_eq!(tracked_users.len(), 6);
2114
2115        let known_users = vec![
2116            user_id!("@alice:localhost"),
2117            user_id!("@dehydration3:localhost"),
2118            user_id!("@eve:localhost"),
2119            user_id!("@bob:localhost"),
2120            user_id!("@malo:localhost"),
2121            user_id!("@carl:localhost"),
2122        ];
2123
2124        // load the identities
2125        for user_id in known_users {
2126            database.get_user_identity(user_id).await.expect("Should load this identity").unwrap();
2127        }
2128
2129        let carl_identity =
2130            database.get_user_identity(user_id!("@carl:localhost")).await.unwrap().unwrap();
2131
2132        assert_eq!(
2133            carl_identity.master_key().get_first_key().unwrap().to_base64(),
2134            "CdhKYYDeBDQveOioXEGWhTPCyzc63Irpar3CNyfun2Q"
2135        );
2136        assert!(!carl_identity.was_previously_verified());
2137
2138        let bob_identity =
2139            database.get_user_identity(user_id!("@bob:localhost")).await.unwrap().unwrap();
2140
2141        assert_eq!(
2142            bob_identity.master_key().get_first_key().unwrap().to_base64(),
2143            "COh2GYOJWSjem5QPRCaGp9iWV83IELG1IzLKW2S3pFY"
2144        );
2145        // Bob is verified so this flag should be set
2146        assert!(bob_identity.was_previously_verified());
2147
2148        let known_devices = vec![
2149            (device_id!("OPXQHCZSKW"), user_id!("@alice:localhost")),
2150            // a dehydrated one
2151            (
2152                device_id!("EvW+9IrGR10KVgVeZP25/KaPfx4R86FofVMcaz7VOho"),
2153                user_id!("@alice:localhost"),
2154            ),
2155            (device_id!("HEEFRFQENV"), user_id!("@alice:localhost")),
2156            (device_id!("JVVORTHFXY"), user_id!("@alice:localhost")),
2157            (device_id!("NQUWWSKKHS"), user_id!("@alice:localhost")),
2158            (device_id!("ORBLPFYCPG"), user_id!("@alice:localhost")),
2159            (device_id!("YXOWENSEGM"), user_id!("@dehydration3:localhost")),
2160            (device_id!("VXLFMYCHXC"), user_id!("@bob:localhost")),
2161            (device_id!("FDGDQAEWOW"), user_id!("@bob:localhost")),
2162            (device_id!("VXLFMYCHXC"), user_id!("@bob:localhost")),
2163            (device_id!("FDGDQAEWOW"), user_id!("@bob:localhost")),
2164            (device_id!("QKUKWJTTQC"), user_id!("@malo:localhost")),
2165            (device_id!("LOUXJECTFG"), user_id!("@malo:localhost")),
2166            (device_id!("MKKMAEVLPB"), user_id!("@carl:localhost")),
2167        ];
2168
2169        for (device_id, user_id) in known_devices {
2170            database.get_device(user_id, device_id).await.expect("Should load the device").unwrap();
2171        }
2172
2173        let known_sender_key_to_session_count = vec![
2174            ("FfYcYfDF4nWy+LHdK6CEpIMlFAQDORc30WUkghL06kM", 1),
2175            ("EvW+9IrGR10KVgVeZP25/KaPfx4R86FofVMcaz7VOho", 1),
2176            ("hAGsoA4a9M6wwEUX5Q1jux1i+tUngLi01n5AmhDoHTY", 1),
2177            ("aKqtSJymLzuoglWFwPGk1r/Vm2LE2hFESzXxn4RNjRM", 0),
2178            ("zHK1psCrgeMn0kaz8hcdvA3INyar9jg1yfrSp0p1pHo", 1),
2179            ("1QmBA316Wj5jIFRwNOti6N6Xh/vW0bsYCcR4uPfy8VQ", 1),
2180            ("g5ef2vZF3VXgSPyODIeXpyHIRkuthvLhGvd6uwYggWU", 1),
2181            ("o7hfupPd1VsNkRIvdlH6ujrEJFSKjFCGbxhAd31XxjI", 1),
2182            ("Z3RxKQLxY7xpP+ZdOGR2SiNE37SrvmRhW7GPu1UGdm8", 1),
2183            ("GDomaav8NiY3J+dNEeApJm+O0FooJ3IpVaIyJzCN4w4", 1),
2184            ("7m7fqkHyEr47V5s/KjaxtJMOr3pSHrrns2q2lWpAQi8", 0),
2185            ("9psAkPUIF8vNbWbnviX3PlwRcaeO53EHJdNtKpTY1X0", 0),
2186            ("mqanh+ztw5oRtpqYQgLGW864i6NY2zpoKMIlrcyC+Aw", 0),
2187            ("fJU/TJdbsv7tVbbpHw1Ke73ziElnM32cNhP2WIg4T10", 0),
2188            ("sUIeFeFcCZoa5IC6nJ6Vrbvztcyx09m8BBg57XKRClg", 1),
2189        ];
2190
2191        for (id, count) in known_sender_key_to_session_count {
2192            let olm_sessions =
2193                database.get_sessions(id).await.expect("Should have some olm sessions");
2194
2195            println!("### Session id: {id:?}");
2196            assert_eq!(olm_sessions.map_or(0, |v| v.len()), count);
2197        }
2198
2199        let inbound_group_sessions = database.get_inbound_group_sessions().await.unwrap();
2200        assert_eq!(inbound_group_sessions.len(), 15);
2201        let known_inbound_group_sessions = vec![
2202            (
2203                "5hNAxrLai3VI0LKBwfh3wLfksfBFWds0W1a5X5/vSXA",
2204                room_id!("!SRstFdydzrGwJYtVfm:localhost"),
2205            ),
2206            (
2207                "M6d2eU3y54gaYTbvGSlqa/xc1Az35l56Cp9sxzHWO4g",
2208                room_id!("!SRstFdydzrGwJYtVfm:localhost"),
2209            ),
2210            (
2211                "IrydwXkRk2N2AqUMIVmLL3oJgMq14R9KId0P/uSD100",
2212                room_id!("!SRstFdydzrGwJYtVfm:localhost"),
2213            ),
2214            (
2215                "Y74+l9jTo7N5UF+GQwdpgJGe4sn1+QtWITq7BxulHIE",
2216                room_id!("!SRstFdydzrGwJYtVfm:localhost"),
2217            ),
2218            (
2219                "HpJxQR57WbQGdY6w2Q+C16znVvbXGa+JvQdRoMpWbXg",
2220                room_id!("!SRstFdydzrGwJYtVfm:localhost"),
2221            ),
2222            (
2223                "Xetvi+ydFkZt8dpONGFbEusQb/Chc2V0XlLByZhsbgE",
2224                room_id!("!ZIwZcFqZVAYLAqVjfV:localhost"),
2225            ),
2226            (
2227                "wv/WN/39akyerIXczTaIpjAuLnwgXKRtbXFSEHiJqxo",
2228                room_id!("!ZIwZcFqZVAYLAqVjfV:localhost"),
2229            ),
2230            (
2231                "nA4gQwL//Cm8OdlyjABl/jChbPT/cP5V4Sd8iuE6H0s",
2232                room_id!("!ZIwZcFqZVAYLAqVjfV:localhost"),
2233            ),
2234            (
2235                "bAAgqFeRDTjfEqL6Qf/c9mk55zoNDCSlboAIRd6b0hw",
2236                room_id!("!ZIwZcFqZVAYLAqVjfV:localhost"),
2237            ),
2238            (
2239                "exPbsMMdGfAG2qmDdFtpAn+koVprfzS0Zip/RA9QRCE",
2240                room_id!("!ZIwZcFqZVAYLAqVjfV:localhost"),
2241            ),
2242            (
2243                "h+om7oSw/ZV94fcKaoe8FGXJwQXWOfKQfzbGgNWQILI",
2244                room_id!("!ZIwZcFqZVAYLAqVjfV:localhost"),
2245            ),
2246            (
2247                "ul3VXonpgk4lO2L3fEWubP/nxsTmLHqu5v8ZM9vHEcw",
2248                room_id!("!ZIwZcFqZVAYLAqVjfV:localhost"),
2249            ),
2250            (
2251                "JXY15UxC3az2mwg8uX4qwgxfvCM4aygiIWMcdNiVQoc",
2252                room_id!("!ZIwZcFqZVAYLAqVjfV:localhost"),
2253            ),
2254            (
2255                "OGB9lObr9kWUvha9tB5sMfOF/Mztk24JwQz/nwg3iFQ",
2256                room_id!("!OgRiTRMaUzLdpCeDBM:localhost"),
2257            ),
2258            (
2259                "SFkHcbxjUOYF7mUAYI/oEMDZFaXszQbCN6Jza7iemj0",
2260                room_id!("!OgRiTRMaUzLdpCeDBM:localhost"),
2261            ),
2262        ];
2263
2264        // ensure we can load them all
2265        for (session_id, room_id) in &known_inbound_group_sessions {
2266            database
2267                .get_inbound_group_session(room_id, session_id)
2268                .await
2269                .expect("Should be able to load inbound group session")
2270                .unwrap();
2271        }
2272
2273        let bob_sender_verified = database
2274            .get_inbound_group_session(
2275                room_id!("!ZIwZcFqZVAYLAqVjfV:localhost"),
2276                "exPbsMMdGfAG2qmDdFtpAn+koVprfzS0Zip/RA9QRCE",
2277            )
2278            .await
2279            .unwrap()
2280            .unwrap();
2281
2282        assert_eq!(bob_sender_verified.sender_data.to_type(), SenderDataType::SenderVerified);
2283        assert!(bob_sender_verified.backed_up());
2284        assert!(!bob_sender_verified.has_been_imported());
2285
2286        let alice_unknown_device = database
2287            .get_inbound_group_session(
2288                room_id!("!SRstFdydzrGwJYtVfm:localhost"),
2289                "IrydwXkRk2N2AqUMIVmLL3oJgMq14R9KId0P/uSD100",
2290            )
2291            .await
2292            .unwrap()
2293            .unwrap();
2294
2295        assert_eq!(alice_unknown_device.sender_data.to_type(), SenderDataType::UnknownDevice);
2296        assert!(alice_unknown_device.backed_up());
2297        assert!(alice_unknown_device.has_been_imported());
2298
2299        let carl_tofu_session = database
2300            .get_inbound_group_session(
2301                room_id!("!OgRiTRMaUzLdpCeDBM:localhost"),
2302                "OGB9lObr9kWUvha9tB5sMfOF/Mztk24JwQz/nwg3iFQ",
2303            )
2304            .await
2305            .unwrap()
2306            .unwrap();
2307
2308        assert_eq!(carl_tofu_session.sender_data.to_type(), SenderDataType::SenderUnverified);
2309        assert!(carl_tofu_session.backed_up());
2310        assert!(!carl_tofu_session.has_been_imported());
2311
2312        // Load outbound sessions
2313        database
2314            .get_outbound_group_session(room_id!("!OgRiTRMaUzLdpCeDBM:localhost"))
2315            .await
2316            .unwrap()
2317            .unwrap();
2318        database
2319            .get_outbound_group_session(room_id!("!ZIwZcFqZVAYLAqVjfV:localhost"))
2320            .await
2321            .unwrap()
2322            .unwrap();
2323        database
2324            .get_outbound_group_session(room_id!("!SRstFdydzrGwJYtVfm:localhost"))
2325            .await
2326            .unwrap()
2327            .unwrap();
2328
2329        let withheld_info = database
2330            .get_withheld_info(
2331                room_id!("!OgRiTRMaUzLdpCeDBM:localhost"),
2332                "SASgZ+EklvAF4QxJclMlDRlmL0fAMjAJJIKFMdb4Ht0",
2333            )
2334            .await
2335            .expect("This session should be withheld")
2336            .unwrap();
2337
2338        assert_eq!(withheld_info.content.withheld_code(), WithheldCode::Unverified);
2339
2340        let backup_keys = database.load_backup_keys().await.expect("backup key should be cached");
2341        assert_eq!(backup_keys.backup_version.unwrap(), "6");
2342        assert!(backup_keys.decryption_key.is_some());
2343    }
2344
2345    /// Test that we migrate the secrets inbox properly.
2346    ///
2347    /// The format for the secrets inbox changed in version 17. Previously, the
2348    /// secrets inbox stored a full `GossippedSecrets` struct. In version 17,
2349    /// the secrets inbox now stores only the secret.
2350    #[async_test]
2351    async fn test_secrets_inbox_migration() {
2352        use std::ops::Deref;
2353
2354        use matrix_sdk_crypto::{
2355            GossipRequest, GossippedSecret, SecretInfo,
2356            types::events::{
2357                olm_v1::{DecryptedSecretSendEvent, OlmV1Keys},
2358                secret_send::SecretSendContent,
2359            },
2360            vodozemac::Ed25519SecretKey,
2361        };
2362        use ruma::{TransactionId, events::secret::request::SecretName, owned_user_id};
2363
2364        use crate::utils::{EncryptableStore, SqliteAsyncConnExt};
2365
2366        // Create a database with version 16
2367        let tmpdir = tempdir().unwrap();
2368        let config = SqliteStoreConfig::new(tmpdir.path());
2369        let pool = config.build_pool_of_connections(super::DATABASE_NAME).unwrap();
2370        let conn = pool.get().await.unwrap();
2371        let version = super::initialize_store(&conn, 0).await.unwrap();
2372        let old_data_store = SqliteCryptoStore::create_raw(
2373            config.secret.clone(),
2374            pool,
2375            conn,
2376            config.pool_config(),
2377            config.runtime_config(),
2378        )
2379        .await
2380        .unwrap();
2381        super::run_migrations(&old_data_store, version, Some(16)).await.unwrap();
2382        old_data_store.write().await.unwrap().wal_checkpoint().await;
2383
2384        // Store a secret using the old format
2385        let secret = GossippedSecret {
2386            secret_name: SecretName::CrossSigningMasterKey,
2387            gossip_request: GossipRequest {
2388                request_recipient: owned_user_id!("@alice:example.com"),
2389                request_id: TransactionId::new(),
2390                info: SecretInfo::SecretRequest(SecretName::CrossSigningMasterKey),
2391                sent_out: true,
2392            },
2393            event: DecryptedSecretSendEvent {
2394                sender: owned_user_id!("@alice:example.com"),
2395                recipient: owned_user_id!("@alice:example.com"),
2396                keys: OlmV1Keys { ed25519: Ed25519SecretKey::new().public_key() },
2397                recipient_keys: OlmV1Keys { ed25519: Ed25519SecretKey::new().public_key() },
2398                sender_device_keys: None,
2399                content: SecretSendContent::new(
2400                    "abc".into(),
2401                    "It is a secret to everybody".to_owned(),
2402                ),
2403            },
2404        };
2405        let value = old_data_store.serialize_json(&secret).unwrap();
2406        old_data_store
2407            .write()
2408            .await
2409            .unwrap()
2410            .prepare("INSERT INTO secrets (secret_name, data) VALUES (?1, ?2)", |mut stmt| {
2411                stmt.execute((SecretName::CrossSigningMasterKey.to_string(), value))
2412            })
2413            .await
2414            .unwrap();
2415
2416        // After we open the store, the data will be migrated
2417        let store = SqliteCryptoStore::open_with_config(&config).await.unwrap();
2418
2419        // and we should be able to read the secrets from the inbox
2420        let secrets =
2421            store.get_secrets_from_inbox(&SecretName::CrossSigningMasterKey).await.unwrap();
2422        assert_eq!(secrets.len(), 1);
2423        assert_eq!(secrets[0].deref(), "It is a secret to everybody");
2424    }
2425
2426    /// Test that we migrate the key requests table properly.
2427    ///
2428    /// Version 18 added a new column, with a unique index on the column,
2429    /// meaning that it can now only store one request per requested secret/key.
2430    /// Test that when we migrate from an older version that has multiple
2431    /// requests for the same secret, it only keeps one.
2432    #[async_test]
2433    async fn test_key_requests_migration() {
2434        use matrix_sdk_crypto::{GossipRequest, SecretInfo};
2435        use ruma::{TransactionId, events::secret::request::SecretName, owned_user_id};
2436
2437        use crate::utils::{EncryptableStore, SqliteAsyncConnExt};
2438
2439        // Create a database with version 16
2440        let tmpdir = tempdir().unwrap();
2441        let config = SqliteStoreConfig::new(tmpdir.path());
2442        let pool = config.build_pool_of_connections(super::DATABASE_NAME).unwrap();
2443        let conn = pool.get().await.unwrap();
2444        let version = super::initialize_store(&conn, 0).await.unwrap();
2445        let old_data_store = SqliteCryptoStore::create_raw(
2446            config.secret.clone(),
2447            pool,
2448            conn,
2449            config.pool_config(),
2450            config.runtime_config(),
2451        )
2452        .await
2453        .unwrap();
2454        super::run_migrations(&old_data_store, version, Some(16)).await.unwrap();
2455        old_data_store.write().await.unwrap().wal_checkpoint().await;
2456
2457        // Store a secret using the old format
2458        let recovery_request1 = GossipRequest {
2459            request_recipient: owned_user_id!("@alice:example.com"),
2460            request_id: TransactionId::new(),
2461            info: SecretInfo::SecretRequest(SecretName::RecoveryKey),
2462            sent_out: true,
2463        };
2464        let serialized_recovery_request1 =
2465            old_data_store.serialize_value(&recovery_request1).unwrap();
2466        let recovery_request2 = GossipRequest {
2467            request_recipient: owned_user_id!("@alice:example.com"),
2468            request_id: TransactionId::new(),
2469            info: SecretInfo::SecretRequest(SecretName::RecoveryKey),
2470            sent_out: true,
2471        };
2472        let serialized_recovery_request2 =
2473            old_data_store.serialize_value(&recovery_request2).unwrap();
2474        let msk_request = GossipRequest {
2475            request_recipient: owned_user_id!("@alice:example.com"),
2476            request_id: TransactionId::new(),
2477            info: SecretInfo::SecretRequest(SecretName::CrossSigningMasterKey),
2478            sent_out: true,
2479        };
2480        let serialized_msk_request = old_data_store.serialize_value(&msk_request).unwrap();
2481        let recovery_request1_clone = recovery_request1.clone();
2482        let recovery_request2_clone = recovery_request2.clone();
2483        let msk_request_clone = msk_request.clone();
2484        old_data_store
2485            .write()
2486            .await
2487            .unwrap()
2488            .prepare(
2489                "INSERT INTO key_requests (request_id, sent_out, data) VALUES (?1, ?2, ?3)",
2490                move |mut stmt| {
2491                    stmt.execute((
2492                        old_data_store.encode_key(
2493                            "key_requests",
2494                            recovery_request1_clone.request_id.as_bytes(),
2495                        ),
2496                        recovery_request1_clone.sent_out,
2497                        serialized_recovery_request1,
2498                    ))?;
2499                    stmt.execute((
2500                        old_data_store.encode_key(
2501                            "key_requests",
2502                            recovery_request2_clone.request_id.as_bytes(),
2503                        ),
2504                        recovery_request2_clone.sent_out,
2505                        serialized_recovery_request2,
2506                    ))?;
2507                    stmt.execute((
2508                        old_data_store
2509                            .encode_key("key_requests", msk_request_clone.request_id.as_bytes()),
2510                        msk_request_clone.sent_out,
2511                        serialized_msk_request,
2512                    ))
2513                },
2514            )
2515            .await
2516            .unwrap();
2517
2518        // After we open the store, the data will be migrated
2519        let store = SqliteCryptoStore::open_with_config(&config).await.unwrap();
2520
2521        // and we should be able to read one request for the recovery key and
2522        // one request for the MSK
2523        if let Some(GossipRequest {
2524            request_id,
2525            info: SecretInfo::SecretRequest(SecretName::RecoveryKey),
2526            ..
2527        }) = store
2528            .get_secret_request_by_info(&SecretInfo::SecretRequest(SecretName::RecoveryKey))
2529            .await
2530            .unwrap()
2531        {
2532            if request_id == recovery_request1.request_id {
2533                assert!(
2534                    store
2535                        .get_outgoing_secret_requests(&recovery_request2.request_id)
2536                        .await
2537                        .unwrap()
2538                        .is_none()
2539                );
2540            } else if request_id == recovery_request2.request_id {
2541                assert!(
2542                    store
2543                        .get_outgoing_secret_requests(&recovery_request1.request_id)
2544                        .await
2545                        .unwrap()
2546                        .is_none()
2547                );
2548            } else {
2549                panic!("unexpected record found");
2550            }
2551        } else {
2552            panic!("expected to get a secret request");
2553        }
2554        if let Some(GossipRequest {
2555            request_id,
2556            info: SecretInfo::SecretRequest(SecretName::CrossSigningMasterKey),
2557            ..
2558        }) = store
2559            .get_secret_request_by_info(&SecretInfo::SecretRequest(
2560                SecretName::CrossSigningMasterKey,
2561            ))
2562            .await
2563            .unwrap()
2564        {
2565            assert_eq!(request_id, msk_request.request_id);
2566        } else {
2567            panic!("expected to get a secret request");
2568        }
2569    }
2570
2571    async fn get_store(
2572        name: &str,
2573        passphrase: Option<&str>,
2574        clear_data: bool,
2575    ) -> SqliteCryptoStore {
2576        let tmpdir_path = TMP_DIR.path().join(name);
2577
2578        if clear_data {
2579            let _ = fs::remove_dir_all(&tmpdir_path).await;
2580        }
2581
2582        SqliteCryptoStore::open(tmpdir_path.to_str().unwrap(), passphrase)
2583            .await
2584            .expect("Can't create a secret protected store")
2585    }
2586
2587    cryptostore_integration_tests!();
2588    cryptostore_integration_tests_time!();
2589}
2590
2591#[cfg(test)]
2592mod encrypted_tests {
2593    use std::sync::LazyLock;
2594
2595    use matrix_sdk_crypto::{cryptostore_integration_tests, cryptostore_integration_tests_time};
2596    use tempfile::{TempDir, tempdir};
2597    use tokio::fs;
2598
2599    use super::SqliteCryptoStore;
2600
2601    static TMP_DIR: LazyLock<TempDir> = LazyLock::new(|| tempdir().unwrap());
2602
2603    async fn get_store(
2604        name: &str,
2605        passphrase: Option<&str>,
2606        clear_data: bool,
2607    ) -> SqliteCryptoStore {
2608        let tmpdir_path = TMP_DIR.path().join(name);
2609        let pass = passphrase.unwrap_or("default_test_password");
2610
2611        if clear_data {
2612            let _ = fs::remove_dir_all(&tmpdir_path).await;
2613        }
2614
2615        SqliteCryptoStore::open(tmpdir_path.to_str().unwrap(), Some(pass))
2616            .await
2617            .expect("Can't create a secret protected store")
2618    }
2619
2620    cryptostore_integration_tests!();
2621    cryptostore_integration_tests_time!();
2622}
2623
2624#[cfg(test)]
2625mod close_reopen_tests {
2626    use std::sync::LazyLock;
2627
2628    use matrix_sdk_crypto::store::CryptoStore;
2629    use matrix_sdk_test::async_test;
2630    use tempfile::{TempDir, tempdir};
2631
2632    use super::SqliteCryptoStore;
2633
2634    static TMP_DIR: LazyLock<TempDir> = LazyLock::new(|| tempdir().unwrap());
2635
2636    async fn new_store(name: &str) -> SqliteCryptoStore {
2637        let tmpdir_path = TMP_DIR.path().join(name);
2638        SqliteCryptoStore::open(tmpdir_path, None).await.unwrap()
2639    }
2640
2641    #[async_test]
2642    async fn test_close_completes_without_timeout() {
2643        let store = new_store("close_no_timeout").await;
2644
2645        // Close should complete quickly without hitting the 5s timeout.
2646        let start = std::time::Instant::now();
2647        store.close().await.unwrap();
2648        let elapsed = start.elapsed();
2649
2650        assert!(
2651            elapsed < std::time::Duration::from_secs(2),
2652            "close() took {elapsed:?}, expected < 2s (no timeout)"
2653        );
2654
2655        // Connections should be None after close.
2656        let guard = store.connections.lock().await;
2657        assert!(guard.is_none(), "connections should be None after close");
2658    }
2659
2660    #[async_test]
2661    async fn test_reopen_restores_connections() {
2662        let store = new_store("reopen_restores").await;
2663
2664        store.close().await.unwrap();
2665
2666        {
2667            let guard = store.connections.lock().await;
2668            assert!(guard.is_none());
2669        }
2670
2671        store.reopen().await.unwrap();
2672
2673        {
2674            let guard = store.connections.lock().await;
2675            assert!(guard.is_some(), "connections should be Some after reopen");
2676        }
2677    }
2678
2679    #[async_test]
2680    async fn test_close_is_idempotent() {
2681        let store = new_store("close_idempotent").await;
2682
2683        store.close().await.unwrap();
2684        // Second close should be a no-op.
2685        store.close().await.unwrap();
2686
2687        let guard = store.connections.lock().await;
2688        assert!(guard.is_none());
2689    }
2690
2691    #[async_test]
2692    async fn test_reopen_is_idempotent() {
2693        let store = new_store("reopen_idempotent").await;
2694
2695        // Reopen on an active store should be a no-op.
2696        store.reopen().await.unwrap();
2697
2698        let guard = store.connections.lock().await;
2699        assert!(guard.is_some());
2700    }
2701
2702    #[async_test]
2703    async fn test_read_fails_when_closed() {
2704        let store = new_store("read_fails_closed").await;
2705        store.close().await.unwrap();
2706
2707        let err = store.load_account().await;
2708        assert!(err.is_err(), "read should fail when closed");
2709
2710        let err_msg = err.unwrap_err().to_string();
2711        assert!(err_msg.contains("closed"), "error should mention 'closed', got: {err_msg}");
2712    }
2713
2714    #[async_test]
2715    async fn test_operations_work_after_reopen() {
2716        let store = new_store("ops_after_reopen").await;
2717
2718        store.close().await.unwrap();
2719        store.reopen().await.unwrap();
2720
2721        // A read operation should work immediately after reopen.
2722        let account = store.load_account().await;
2723        assert!(account.is_ok(), "load_account should succeed after reopen");
2724        // No account was saved, so this should be None.
2725        assert!(account.unwrap().is_none());
2726    }
2727
2728    #[async_test]
2729    async fn test_multiple_close_reopen_cycles() {
2730        let store = new_store("multi_cycles").await;
2731
2732        for _ in 0..5 {
2733            store.close().await.unwrap();
2734            store.reopen().await.unwrap();
2735
2736            // After each cycle, the store should be fully operational.
2737            let account = store.load_account().await;
2738            assert!(account.is_ok(), "store should work after close/reopen cycle");
2739        }
2740    }
2741
2742    #[async_test]
2743    async fn test_pool_is_fully_drained_after_close() {
2744        let store = new_store("pool_drained").await;
2745
2746        // Do a few reads to exercise the pool.
2747        let _ = store.load_account().await;
2748        let _ = store.load_account().await;
2749
2750        store.close().await.unwrap();
2751
2752        // After close, the connections field should be None.
2753        let guard = store.connections.lock().await;
2754        assert!(guard.is_none(), "all connections should be released after close");
2755    }
2756
2757    #[async_test]
2758    async fn test_close_waits_for_held_read_connection_to_drain() {
2759        let store = new_store("held_read_drain").await;
2760
2761        // Acquire a read connection and hold it, simulating an in-flight read.
2762        let held_conn = store.read().await.unwrap();
2763
2764        // Spawn close in a background task — it will close the pool and then
2765        // poll-wait for pool.status().size == 0 in the drain loop.
2766        let store_clone = store.clone();
2767        let close_handle = tokio::spawn(async move {
2768            store_clone.close().await.unwrap();
2769        });
2770
2771        // Give close() a moment to close the pool and enter the drain loop.
2772        tokio::time::sleep(std::time::Duration::from_millis(200)).await;
2773
2774        // The close task should still be running because we hold a connection.
2775        assert!(!close_handle.is_finished(), "close should be waiting for the held connection");
2776
2777        // Release the held connection — this lets pool.status().size drop to 0.
2778        drop(held_conn);
2779
2780        // Now close should complete promptly (well within the 5s timeout).
2781        let timeout = tokio::time::timeout(std::time::Duration::from_secs(3), close_handle).await;
2782        assert!(timeout.is_ok(), "close should complete after the held connection is released");
2783        timeout.unwrap().unwrap();
2784
2785        // Verify the store is fully closed.
2786        let guard = store.connections.lock().await;
2787        assert!(guard.is_none(), "connections should be None after close");
2788    }
2789}