1use std::{
16 collections::HashMap,
17 fmt,
18 path::Path,
19 sync::{Arc, RwLock},
20};
21
22use async_trait::async_trait;
23use matrix_sdk_base::{cross_process_lock::CrossProcessLockGeneration, timer};
24use matrix_sdk_crypto::{
25 olm::{
26 InboundGroupSession, OutboundGroupSession, PickledInboundGroupSession,
27 PrivateCrossSigningIdentity, SenderDataType, Session, StaticAccountData,
28 },
29 store::{
30 types::{
31 BackupKeys, Changes, DehydratedDeviceKey, PendingChanges, RoomKeyCounts,
32 RoomKeyWithheldEntry, RoomSettings, StoredRoomKeyBundleData,
33 },
34 CryptoStore,
35 },
36 Account, DeviceData, GossipRequest, GossippedSecret, SecretInfo, TrackedUser, UserIdentityData,
37};
38use matrix_sdk_store_encryption::StoreCipher;
39use ruma::{
40 events::secret::request::SecretName, DeviceId, MilliSecondsSinceUnixEpoch, OwnedDeviceId,
41 RoomId, TransactionId, UserId,
42};
43use rusqlite::{named_params, params_from_iter, OptionalExtension};
44use tokio::{fs, sync::Mutex};
45use tracing::{debug, instrument, warn};
46use vodozemac::Curve25519PublicKey;
47
48use crate::{
49 connection::{Connection as SqliteAsyncConn, Pool as SqlitePool},
50 error::{Error, Result},
51 utils::{
52 repeat_vars, EncryptableStore, Key, SqliteAsyncConnExt, SqliteKeyValueStoreAsyncConnExt,
53 SqliteKeyValueStoreConnExt,
54 },
55 OpenStoreError, Secret, SqliteStoreConfig,
56};
57
58const DATABASE_NAME: &str = "matrix-sdk-crypto.sqlite3";
60
61#[derive(Clone)]
63pub struct SqliteCryptoStore {
64 store_cipher: Option<Arc<StoreCipher>>,
65 pool: SqlitePool,
66
67 static_account: Arc<RwLock<Option<StaticAccountData>>>,
69 save_changes_lock: Arc<Mutex<()>>,
70}
71
72#[cfg(not(tarpaulin_include))]
73impl fmt::Debug for SqliteCryptoStore {
74 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
75 f.debug_struct("SqliteCryptoStore").finish_non_exhaustive()
76 }
77}
78
79impl EncryptableStore for SqliteCryptoStore {
80 fn get_cypher(&self) -> Option<&StoreCipher> {
81 self.store_cipher.as_deref()
82 }
83}
84
85impl SqliteCryptoStore {
86 pub async fn open(
89 path: impl AsRef<Path>,
90 passphrase: Option<&str>,
91 ) -> Result<Self, OpenStoreError> {
92 Self::open_with_config(SqliteStoreConfig::new(path).passphrase(passphrase)).await
93 }
94
95 pub async fn open_with_key(
98 path: impl AsRef<Path>,
99 key: Option<&[u8; 32]>,
100 ) -> Result<Self, OpenStoreError> {
101 Self::open_with_config(SqliteStoreConfig::new(path).key(key)).await
102 }
103
104 pub async fn open_with_config(config: SqliteStoreConfig) -> Result<Self, OpenStoreError> {
106 fs::create_dir_all(&config.path).await.map_err(OpenStoreError::CreateDir)?;
107
108 let pool = config.build_pool_of_connections(DATABASE_NAME)?;
109
110 let this = Self::open_with_pool(pool, config.secret).await?;
111 this.pool.get().await?.apply_runtime_config(config.runtime_config).await?;
112
113 Ok(this)
114 }
115
116 async fn open_with_pool(
119 pool: SqlitePool,
120 secret: Option<Secret>,
121 ) -> Result<Self, OpenStoreError> {
122 let conn = pool.get().await?;
123
124 let version = conn.db_version().await?;
125 debug!("Opened sqlite store with version {}", version);
126 run_migrations(&conn, version).await?;
127
128 let store_cipher = match secret {
129 Some(s) => Some(Arc::new(conn.get_or_create_store_cipher(s).await?)),
130 None => None,
131 };
132
133 Ok(SqliteCryptoStore {
134 store_cipher,
135 pool,
136 static_account: Arc::new(RwLock::new(None)),
137 save_changes_lock: Default::default(),
138 })
139 }
140
141 fn deserialize_and_unpickle_inbound_group_session(
142 &self,
143 value: Vec<u8>,
144 backed_up: bool,
145 ) -> Result<InboundGroupSession> {
146 let mut pickle: PickledInboundGroupSession = self.deserialize_value(&value)?;
147
148 pickle.backed_up = backed_up;
153
154 Ok(InboundGroupSession::from_pickle(pickle)?)
155 }
156
157 fn deserialize_key_request(&self, value: &[u8], sent_out: bool) -> Result<GossipRequest> {
158 let mut request: GossipRequest = self.deserialize_value(value)?;
159 request.sent_out = sent_out;
162 Ok(request)
163 }
164
165 fn get_static_account(&self) -> Option<StaticAccountData> {
166 self.static_account.read().unwrap().clone()
167 }
168
169 async fn acquire(&self) -> Result<SqliteAsyncConn> {
170 Ok(self.pool.get().await?)
171 }
172}
173
174const DATABASE_VERSION: u8 = 13;
175
176const DEHYDRATED_DEVICE_PICKLE_KEY: &str = "dehydrated_device_pickle_key";
178
179async fn run_migrations(conn: &SqliteAsyncConn, version: u8) -> Result<()> {
181 if version == 0 {
182 debug!("Creating database");
183 } else if version < DATABASE_VERSION {
184 debug!(version, new_version = DATABASE_VERSION, "Upgrading database");
185 } else {
186 return Ok(());
187 }
188
189 if version < 1 {
190 conn.execute_batch("PRAGMA journal_mode = wal;").await?;
193 conn.with_transaction(|txn| {
194 txn.execute_batch(include_str!("../migrations/crypto_store/001_init.sql"))?;
195 txn.set_db_version(1)
196 })
197 .await?;
198 }
199
200 if version < 2 {
201 conn.with_transaction(|txn| {
202 txn.execute_batch(include_str!("../migrations/crypto_store/002_reset_olm_hash.sql"))?;
203 txn.set_db_version(2)
204 })
205 .await?;
206 }
207
208 if version < 3 {
209 conn.with_transaction(|txn| {
210 txn.execute_batch(include_str!("../migrations/crypto_store/003_room_settings.sql"))?;
211 txn.set_db_version(3)
212 })
213 .await?;
214 }
215
216 if version < 4 {
217 conn.with_transaction(|txn| {
218 txn.execute_batch(include_str!(
219 "../migrations/crypto_store/004_drop_outbound_group_sessions.sql"
220 ))?;
221 txn.set_db_version(4)
222 })
223 .await?;
224 }
225
226 if version < 5 {
227 conn.with_transaction(|txn| {
228 txn.execute_batch(include_str!("../migrations/crypto_store/005_withheld_code.sql"))?;
229 txn.set_db_version(5)
230 })
231 .await?;
232 }
233
234 if version < 6 {
235 conn.with_transaction(|txn| {
236 txn.execute_batch(include_str!(
237 "../migrations/crypto_store/006_drop_outbound_group_sessions.sql"
238 ))?;
239 txn.set_db_version(6)
240 })
241 .await?;
242 }
243
244 if version < 7 {
245 conn.with_transaction(|txn| {
246 txn.execute_batch(include_str!("../migrations/crypto_store/007_lock_leases.sql"))?;
247 txn.set_db_version(7)
248 })
249 .await?;
250 }
251
252 if version < 8 {
253 conn.with_transaction(|txn| {
254 txn.execute_batch(include_str!("../migrations/crypto_store/008_secret_inbox.sql"))?;
255 txn.set_db_version(8)
256 })
257 .await?;
258 }
259
260 if version < 9 {
261 conn.with_transaction(|txn| {
262 txn.execute_batch(include_str!(
263 "../migrations/crypto_store/009_inbound_group_session_sender_key_sender_data_type.sql"
264 ))?;
265 txn.set_db_version(9)
266 })
267 .await?;
268 }
269
270 if version < 10 {
271 conn.with_transaction(|txn| {
272 txn.execute_batch(include_str!(
273 "../migrations/crypto_store/010_received_room_key_bundles.sql"
274 ))?;
275 txn.set_db_version(10)
276 })
277 .await?;
278 }
279
280 if version < 11 {
281 conn.with_transaction(|txn| {
282 txn.execute_batch(include_str!(
283 "../migrations/crypto_store/011_received_room_key_bundles_with_curve_key.sql"
284 ))?;
285 txn.set_db_version(11)
286 })
287 .await?;
288 }
289
290 if version < 12 {
291 conn.with_transaction(|txn| {
292 txn.execute_batch(include_str!(
293 "../migrations/crypto_store/012_withheld_code_by_room.sql"
294 ))?;
295 txn.set_db_version(12)
296 })
297 .await?;
298 }
299
300 if version < 13 {
301 conn.with_transaction(|txn| {
302 txn.execute_batch(include_str!(
303 "../migrations/crypto_store/013_lease_locks_with_generation.sql"
304 ))?;
305 txn.set_db_version(13)
306 })
307 .await?;
308 }
309
310 Ok(())
311}
312
313trait SqliteConnectionExt {
314 fn set_session(
315 &self,
316 session_id: &[u8],
317 sender_key: &[u8],
318 data: &[u8],
319 ) -> rusqlite::Result<()>;
320
321 fn set_inbound_group_session(
322 &self,
323 room_id: &[u8],
324 session_id: &[u8],
325 data: &[u8],
326 backed_up: bool,
327 sender_key: Option<&[u8]>,
328 sender_data_type: Option<u8>,
329 ) -> rusqlite::Result<()>;
330
331 fn set_outbound_group_session(&self, room_id: &[u8], data: &[u8]) -> rusqlite::Result<()>;
332
333 fn set_device(&self, user_id: &[u8], device_id: &[u8], data: &[u8]) -> rusqlite::Result<()>;
334 fn delete_device(&self, user_id: &[u8], device_id: &[u8]) -> rusqlite::Result<()>;
335
336 fn set_identity(&self, user_id: &[u8], data: &[u8]) -> rusqlite::Result<()>;
337
338 fn add_olm_hash(&self, data: &[u8]) -> rusqlite::Result<()>;
339
340 fn set_key_request(
341 &self,
342 request_id: &[u8],
343 sent_out: bool,
344 data: &[u8],
345 ) -> rusqlite::Result<()>;
346
347 fn set_direct_withheld(
348 &self,
349 session_id: &[u8],
350 room_id: &[u8],
351 data: &[u8],
352 ) -> rusqlite::Result<()>;
353
354 fn set_room_settings(&self, room_id: &[u8], data: &[u8]) -> rusqlite::Result<()>;
355
356 fn set_secret(&self, request_id: &[u8], data: &[u8]) -> rusqlite::Result<()>;
357
358 fn set_received_room_key_bundle(
359 &self,
360 room_id: &[u8],
361 user_id: &[u8],
362 data: &[u8],
363 ) -> rusqlite::Result<()>;
364}
365
366impl SqliteConnectionExt for rusqlite::Connection {
367 fn set_session(
368 &self,
369 session_id: &[u8],
370 sender_key: &[u8],
371 data: &[u8],
372 ) -> rusqlite::Result<()> {
373 self.execute(
374 "INSERT INTO session (session_id, sender_key, data)
375 VALUES (?1, ?2, ?3)
376 ON CONFLICT (session_id) DO UPDATE SET data = ?3",
377 (session_id, sender_key, data),
378 )?;
379 Ok(())
380 }
381
382 fn set_inbound_group_session(
383 &self,
384 room_id: &[u8],
385 session_id: &[u8],
386 data: &[u8],
387 backed_up: bool,
388 sender_key: Option<&[u8]>,
389 sender_data_type: Option<u8>,
390 ) -> rusqlite::Result<()> {
391 self.execute(
392 "INSERT INTO inbound_group_session (session_id, room_id, data, backed_up, sender_key, sender_data_type) \
393 VALUES (?1, ?2, ?3, ?4, ?5, ?6)
394 ON CONFLICT (session_id) DO UPDATE SET data = ?3, backed_up = ?4, sender_key = ?5, sender_data_type = ?6",
395 (session_id, room_id, data, backed_up, sender_key, sender_data_type),
396 )?;
397 Ok(())
398 }
399
400 fn set_outbound_group_session(&self, room_id: &[u8], data: &[u8]) -> rusqlite::Result<()> {
401 self.execute(
402 "INSERT INTO outbound_group_session (room_id, data) \
403 VALUES (?1, ?2)
404 ON CONFLICT (room_id) DO UPDATE SET data = ?2",
405 (room_id, data),
406 )?;
407 Ok(())
408 }
409
410 fn set_device(&self, user_id: &[u8], device_id: &[u8], data: &[u8]) -> rusqlite::Result<()> {
411 self.execute(
412 "INSERT INTO device (user_id, device_id, data) \
413 VALUES (?1, ?2, ?3)
414 ON CONFLICT (user_id, device_id) DO UPDATE SET data = ?3",
415 (user_id, device_id, data),
416 )?;
417 Ok(())
418 }
419
420 fn delete_device(&self, user_id: &[u8], device_id: &[u8]) -> rusqlite::Result<()> {
421 self.execute(
422 "DELETE FROM device WHERE user_id = ? AND device_id = ?",
423 (user_id, device_id),
424 )?;
425 Ok(())
426 }
427
428 fn set_identity(&self, user_id: &[u8], data: &[u8]) -> rusqlite::Result<()> {
429 self.execute(
430 "INSERT INTO identity (user_id, data) \
431 VALUES (?1, ?2)
432 ON CONFLICT (user_id) DO UPDATE SET data = ?2",
433 (user_id, data),
434 )?;
435 Ok(())
436 }
437
438 fn add_olm_hash(&self, data: &[u8]) -> rusqlite::Result<()> {
439 self.execute("INSERT INTO olm_hash (data) VALUES (?) ON CONFLICT DO NOTHING", (data,))?;
440 Ok(())
441 }
442
443 fn set_key_request(
444 &self,
445 request_id: &[u8],
446 sent_out: bool,
447 data: &[u8],
448 ) -> rusqlite::Result<()> {
449 self.execute(
450 "INSERT INTO key_requests (request_id, sent_out, data)
451 VALUES (?1, ?2, ?3)
452 ON CONFLICT (request_id) DO UPDATE SET sent_out = ?2, data = ?3",
453 (request_id, sent_out, data),
454 )?;
455 Ok(())
456 }
457
458 fn set_direct_withheld(
459 &self,
460 session_id: &[u8],
461 room_id: &[u8],
462 data: &[u8],
463 ) -> rusqlite::Result<()> {
464 self.execute(
465 "INSERT INTO direct_withheld_info (session_id, room_id, data)
466 VALUES (?1, ?2, ?3)
467 ON CONFLICT (session_id) DO UPDATE SET room_id = ?2, data = ?3",
468 (session_id, room_id, data),
469 )?;
470 Ok(())
471 }
472
473 fn set_room_settings(&self, room_id: &[u8], data: &[u8]) -> rusqlite::Result<()> {
474 self.execute(
475 "INSERT INTO room_settings (room_id, data)
476 VALUES (?1, ?2)
477 ON CONFLICT (room_id) DO UPDATE SET data = ?2",
478 (room_id, data),
479 )?;
480 Ok(())
481 }
482
483 fn set_secret(&self, secret_name: &[u8], data: &[u8]) -> rusqlite::Result<()> {
484 self.execute(
485 "INSERT INTO secrets (secret_name, data)
486 VALUES (?1, ?2)",
487 (secret_name, data),
488 )?;
489
490 Ok(())
491 }
492
493 fn set_received_room_key_bundle(
494 &self,
495 room_id: &[u8],
496 sender_user_id: &[u8],
497 data: &[u8],
498 ) -> rusqlite::Result<()> {
499 self.execute(
500 "INSERT INTO received_room_key_bundle(room_id, sender_user_id, bundle_data)
501 VALUES (?1, ?2, ?3)
502 ON CONFLICT (room_id, sender_user_id) DO UPDATE SET bundle_data = ?3",
503 (room_id, sender_user_id, data),
504 )?;
505 Ok(())
506 }
507}
508
509#[async_trait]
510trait SqliteObjectCryptoStoreExt: SqliteAsyncConnExt {
511 async fn get_sessions_for_sender_key(&self, sender_key: Key) -> Result<Vec<Vec<u8>>> {
512 Ok(self
513 .prepare("SELECT data FROM session WHERE sender_key = ?", |mut stmt| {
514 stmt.query((sender_key,))?.mapped(|row| row.get(0)).collect()
515 })
516 .await?)
517 }
518
519 async fn get_inbound_group_session(
520 &self,
521 session_id: Key,
522 ) -> Result<Option<(Vec<u8>, Vec<u8>, bool)>> {
523 Ok(self
524 .query_row(
525 "SELECT room_id, data, backed_up FROM inbound_group_session WHERE session_id = ?",
526 (session_id,),
527 |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)),
528 )
529 .await
530 .optional()?)
531 }
532
533 async fn get_inbound_group_sessions(&self) -> Result<Vec<(Vec<u8>, bool)>> {
534 Ok(self
535 .prepare("SELECT data, backed_up FROM inbound_group_session", |mut stmt| {
536 stmt.query(())?.mapped(|row| Ok((row.get(0)?, row.get(1)?))).collect()
537 })
538 .await?)
539 }
540
541 async fn get_inbound_group_session_counts(
542 &self,
543 _backup_version: Option<&str>,
544 ) -> Result<RoomKeyCounts> {
545 let total = self
546 .query_row("SELECT count(*) FROM inbound_group_session", (), |row| row.get(0))
547 .await?;
548 let backed_up = self
549 .query_row(
550 "SELECT count(*) FROM inbound_group_session WHERE backed_up = TRUE",
551 (),
552 |row| row.get(0),
553 )
554 .await?;
555 Ok(RoomKeyCounts { total, backed_up })
556 }
557
558 async fn get_inbound_group_sessions_by_room_id(
559 &self,
560 room_id: Key,
561 ) -> Result<Vec<(Vec<u8>, bool)>> {
562 Ok(self
563 .prepare(
564 "SELECT data, backed_up FROM inbound_group_session WHERE room_id = :room_id",
565 move |mut stmt| {
566 stmt.query(named_params! {
567 ":room_id": room_id,
568 })?
569 .mapped(|row| Ok((row.get(0)?, row.get(1)?)))
570 .collect()
571 },
572 )
573 .await?)
574 }
575
576 async fn get_inbound_group_sessions_for_device_batch(
577 &self,
578 sender_key: Key,
579 sender_data_type: SenderDataType,
580 after_session_id: Option<Key>,
581 limit: usize,
582 ) -> Result<Vec<(Vec<u8>, bool)>> {
583 Ok(self
584 .prepare(
585 "
586 SELECT data, backed_up
587 FROM inbound_group_session
588 WHERE sender_key = :sender_key
589 AND sender_data_type = :sender_data_type
590 AND session_id > :after_session_id
591 ORDER BY session_id
592 LIMIT :limit
593 ",
594 move |mut stmt| {
595 let sender_data_type = sender_data_type as u8;
596
597 let after_session_id = after_session_id.unwrap_or(Key::Plain(Vec::new()));
600
601 stmt.query(named_params! {
602 ":sender_key": sender_key,
603 ":sender_data_type": sender_data_type,
604 ":after_session_id": after_session_id,
605 ":limit": limit,
606 })?
607 .mapped(|row| Ok((row.get(0)?, row.get(1)?)))
608 .collect()
609 },
610 )
611 .await?)
612 }
613
614 async fn get_inbound_group_sessions_for_backup(&self, limit: usize) -> Result<Vec<Vec<u8>>> {
615 Ok(self
616 .prepare(
617 "SELECT data FROM inbound_group_session WHERE backed_up = FALSE LIMIT ?",
618 move |mut stmt| stmt.query((limit,))?.mapped(|row| row.get(0)).collect(),
619 )
620 .await?)
621 }
622
623 async fn mark_inbound_group_sessions_as_backed_up(&self, session_ids: Vec<Key>) -> Result<()> {
624 if session_ids.is_empty() {
625 warn!("No sessions to mark as backed up!");
627 return Ok(());
628 }
629
630 let session_ids_len = session_ids.len();
631
632 self.chunk_large_query_over(session_ids, None, move |txn, session_ids| {
633 let sql_params = repeat_vars(session_ids_len);
636 let query = format!("UPDATE inbound_group_session SET backed_up = TRUE where session_id IN ({sql_params})");
637 txn.prepare(&query)?.execute(params_from_iter(session_ids.iter()))?;
638 Ok(Vec::<()>::new())
639 }).await?;
640
641 Ok(())
642 }
643
644 async fn reset_inbound_group_session_backup_state(&self) -> Result<()> {
645 self.execute("UPDATE inbound_group_session SET backed_up = FALSE", ()).await?;
646 Ok(())
647 }
648
649 async fn get_outbound_group_session(&self, room_id: Key) -> Result<Option<Vec<u8>>> {
650 Ok(self
651 .query_row(
652 "SELECT data FROM outbound_group_session WHERE room_id = ?",
653 (room_id,),
654 |row| row.get(0),
655 )
656 .await
657 .optional()?)
658 }
659
660 async fn get_device(&self, user_id: Key, device_id: Key) -> Result<Option<Vec<u8>>> {
661 Ok(self
662 .query_row(
663 "SELECT data FROM device WHERE user_id = ? AND device_id = ?",
664 (user_id, device_id),
665 |row| row.get(0),
666 )
667 .await
668 .optional()?)
669 }
670
671 async fn get_user_devices(&self, user_id: Key) -> Result<Vec<Vec<u8>>> {
672 Ok(self
673 .prepare("SELECT data FROM device WHERE user_id = ?", |mut stmt| {
674 stmt.query((user_id,))?.mapped(|row| row.get(0)).collect()
675 })
676 .await?)
677 }
678
679 async fn get_user_identity(&self, user_id: Key) -> Result<Option<Vec<u8>>> {
680 Ok(self
681 .query_row("SELECT data FROM identity WHERE user_id = ?", (user_id,), |row| row.get(0))
682 .await
683 .optional()?)
684 }
685
686 async fn has_olm_hash(&self, data: Vec<u8>) -> Result<bool> {
687 Ok(self
688 .query_row("SELECT count(*) FROM olm_hash WHERE data = ?", (data,), |row| {
689 row.get::<_, i32>(0)
690 })
691 .await?
692 > 0)
693 }
694
695 async fn get_tracked_users(&self) -> Result<Vec<Vec<u8>>> {
696 Ok(self
697 .prepare("SELECT data FROM tracked_user", |mut stmt| {
698 stmt.query(())?.mapped(|row| row.get(0)).collect()
699 })
700 .await?)
701 }
702
703 async fn add_tracked_users(&self, users: Vec<(Key, Vec<u8>)>) -> Result<()> {
704 Ok(self
705 .prepare(
706 "INSERT INTO tracked_user (user_id, data) \
707 VALUES (?1, ?2) \
708 ON CONFLICT (user_id) DO UPDATE SET data = ?2",
709 |mut stmt| {
710 for (user_id, data) in users {
711 stmt.execute((user_id, data))?;
712 }
713
714 Ok(())
715 },
716 )
717 .await?)
718 }
719
720 async fn get_outgoing_secret_request(
721 &self,
722 request_id: Key,
723 ) -> Result<Option<(Vec<u8>, bool)>> {
724 Ok(self
725 .query_row(
726 "SELECT data, sent_out FROM key_requests WHERE request_id = ?",
727 (request_id,),
728 |row| Ok((row.get(0)?, row.get(1)?)),
729 )
730 .await
731 .optional()?)
732 }
733
734 async fn get_outgoing_secret_requests(&self) -> Result<Vec<(Vec<u8>, bool)>> {
735 Ok(self
736 .prepare("SELECT data, sent_out FROM key_requests", |mut stmt| {
737 stmt.query(())?.mapped(|row| Ok((row.get(0)?, row.get(1)?))).collect()
738 })
739 .await?)
740 }
741
742 async fn get_unsent_secret_requests(&self) -> Result<Vec<Vec<u8>>> {
743 Ok(self
744 .prepare("SELECT data FROM key_requests WHERE sent_out = FALSE", |mut stmt| {
745 stmt.query(())?.mapped(|row| row.get(0)).collect()
746 })
747 .await?)
748 }
749
750 async fn delete_key_request(&self, request_id: Key) -> Result<()> {
751 self.execute("DELETE FROM key_requests WHERE request_id = ?", (request_id,)).await?;
752 Ok(())
753 }
754
755 async fn get_secrets_from_inbox(&self, secret_name: Key) -> Result<Vec<Vec<u8>>> {
756 Ok(self
757 .prepare("SELECT data FROM secrets WHERE secret_name = ?", |mut stmt| {
758 stmt.query((secret_name,))?.mapped(|row| row.get(0)).collect()
759 })
760 .await?)
761 }
762
763 async fn delete_secrets_from_inbox(&self, secret_name: Key) -> Result<()> {
764 self.execute("DELETE FROM secrets WHERE secret_name = ?", (secret_name,)).await?;
765 Ok(())
766 }
767
768 async fn get_direct_withheld_info(
769 &self,
770 session_id: Key,
771 room_id: Key,
772 ) -> Result<Option<Vec<u8>>> {
773 Ok(self
774 .query_row(
775 "SELECT data FROM direct_withheld_info WHERE session_id = ?1 AND room_id = ?2",
776 (session_id, room_id),
777 |row| row.get(0),
778 )
779 .await
780 .optional()?)
781 }
782
783 async fn get_withheld_sessions_by_room_id(&self, room_id: Key) -> Result<Vec<Vec<u8>>> {
784 Ok(self
785 .prepare("SELECT data FROM direct_withheld_info WHERE room_id = ?1", |mut stmt| {
786 stmt.query((room_id,))?.mapped(|row| row.get(0)).collect()
787 })
788 .await?)
789 }
790
791 async fn get_room_settings(&self, room_id: Key) -> Result<Option<Vec<u8>>> {
792 Ok(self
793 .query_row("SELECT data FROM room_settings WHERE room_id = ?", (room_id,), |row| {
794 row.get(0)
795 })
796 .await
797 .optional()?)
798 }
799
800 async fn get_received_room_key_bundle(
801 &self,
802 room_id: Key,
803 sender_user: Key,
804 ) -> Result<Option<Vec<u8>>> {
805 Ok(self
806 .query_row(
807 "SELECT bundle_data FROM received_room_key_bundle WHERE room_id = ? AND sender_user_id = ?",
808 (room_id, sender_user),
809 |row| { row.get(0) },
810 )
811 .await
812 .optional()?)
813 }
814}
815
816#[async_trait]
817impl SqliteObjectCryptoStoreExt for SqliteAsyncConn {}
818
819#[async_trait]
820impl CryptoStore for SqliteCryptoStore {
821 type Error = Error;
822
823 async fn load_account(&self) -> Result<Option<Account>> {
824 let conn = self.acquire().await?;
825 if let Some(pickle) = conn.get_kv("account").await? {
826 let pickle = self.deserialize_value(&pickle)?;
827
828 let account = Account::from_pickle(pickle).map_err(|_| Error::Unpickle)?;
829
830 *self.static_account.write().unwrap() = Some(account.static_data().clone());
831
832 Ok(Some(account))
833 } else {
834 Ok(None)
835 }
836 }
837
838 async fn load_identity(&self) -> Result<Option<PrivateCrossSigningIdentity>> {
839 let conn = self.acquire().await?;
840 if let Some(i) = conn.get_kv("identity").await? {
841 let pickle = self.deserialize_value(&i)?;
842 Ok(Some(PrivateCrossSigningIdentity::from_pickle(pickle).map_err(|_| Error::Unpickle)?))
843 } else {
844 Ok(None)
845 }
846 }
847
848 async fn save_pending_changes(&self, changes: PendingChanges) -> Result<()> {
849 let _guard = self.save_changes_lock.lock().await;
854
855 let pickled_account = if let Some(account) = changes.account {
856 *self.static_account.write().unwrap() = Some(account.static_data().clone());
857 Some(account.pickle())
858 } else {
859 None
860 };
861
862 let this = self.clone();
863 self.acquire()
864 .await?
865 .with_transaction(move |txn| {
866 if let Some(pickled_account) = pickled_account {
867 let serialized_account = this.serialize_value(&pickled_account)?;
868 txn.set_kv("account", &serialized_account)?;
869 }
870
871 Ok::<_, Error>(())
872 })
873 .await?;
874
875 Ok(())
876 }
877
878 async fn save_changes(&self, changes: Changes) -> Result<()> {
879 let _guard = self.save_changes_lock.lock().await;
884
885 let pickled_private_identity =
886 if let Some(i) = changes.private_identity { Some(i.pickle().await) } else { None };
887
888 let mut session_changes = Vec::new();
889
890 for session in changes.sessions {
891 let session_id = self.encode_key("session", session.session_id());
892 let sender_key = self.encode_key("session", session.sender_key().to_base64());
893 let pickle = session.pickle().await;
894 session_changes.push((session_id, sender_key, pickle));
895 }
896
897 let mut inbound_session_changes = Vec::new();
898 for session in changes.inbound_group_sessions {
899 let room_id = self.encode_key("inbound_group_session", session.room_id().as_bytes());
900 let session_id = self.encode_key("inbound_group_session", session.session_id());
901 let pickle = session.pickle().await;
902 let sender_key =
903 self.encode_key("inbound_group_session", session.sender_key().to_base64());
904 inbound_session_changes.push((room_id, session_id, pickle, sender_key));
905 }
906
907 let mut outbound_session_changes = Vec::new();
908 for session in changes.outbound_group_sessions {
909 let room_id = self.encode_key("outbound_group_session", session.room_id().as_bytes());
910 let pickle = session.pickle().await;
911 outbound_session_changes.push((room_id, pickle));
912 }
913
914 let this = self.clone();
915 self.acquire()
916 .await?
917 .with_transaction(move |txn| {
918 if let Some(pickled_private_identity) = &pickled_private_identity {
919 let serialized_private_identity =
920 this.serialize_value(pickled_private_identity)?;
921 txn.set_kv("identity", &serialized_private_identity)?;
922 }
923
924 if let Some(token) = &changes.next_batch_token {
925 let serialized_token = this.serialize_value(token)?;
926 txn.set_kv("next_batch_token", &serialized_token)?;
927 }
928
929 if let Some(decryption_key) = &changes.backup_decryption_key {
930 let serialized_decryption_key = this.serialize_value(decryption_key)?;
931 txn.set_kv("recovery_key_v1", &serialized_decryption_key)?;
932 }
933
934 if let Some(backup_version) = &changes.backup_version {
935 let serialized_backup_version = this.serialize_value(backup_version)?;
936 txn.set_kv("backup_version_v1", &serialized_backup_version)?;
937 }
938
939 if let Some(pickle_key) = &changes.dehydrated_device_pickle_key {
940 let serialized_pickle_key = this.serialize_value(pickle_key)?;
941 txn.set_kv(DEHYDRATED_DEVICE_PICKLE_KEY, &serialized_pickle_key)?;
942 }
943
944 for device in changes.devices.new.iter().chain(&changes.devices.changed) {
945 let user_id = this.encode_key("device", device.user_id().as_bytes());
946 let device_id = this.encode_key("device", device.device_id().as_bytes());
947 let data = this.serialize_value(&device)?;
948 txn.set_device(&user_id, &device_id, &data)?;
949 }
950
951 for device in &changes.devices.deleted {
952 let user_id = this.encode_key("device", device.user_id().as_bytes());
953 let device_id = this.encode_key("device", device.device_id().as_bytes());
954 txn.delete_device(&user_id, &device_id)?;
955 }
956
957 for identity in changes.identities.changed.iter().chain(&changes.identities.new) {
958 let user_id = this.encode_key("identity", identity.user_id().as_bytes());
959 let data = this.serialize_value(&identity)?;
960 txn.set_identity(&user_id, &data)?;
961 }
962
963 for (session_id, sender_key, pickle) in &session_changes {
964 let serialized_session = this.serialize_value(&pickle)?;
965 txn.set_session(session_id, sender_key, &serialized_session)?;
966 }
967
968 for (room_id, session_id, pickle, sender_key) in &inbound_session_changes {
969 let serialized_session = this.serialize_value(&pickle)?;
970 txn.set_inbound_group_session(
971 room_id,
972 session_id,
973 &serialized_session,
974 pickle.backed_up,
975 Some(sender_key),
976 Some(pickle.sender_data.to_type() as u8),
977 )?;
978 }
979
980 for (room_id, pickle) in &outbound_session_changes {
981 let serialized_session = this.serialize_json(&pickle)?;
982 txn.set_outbound_group_session(room_id, &serialized_session)?;
983 }
984
985 for hash in &changes.message_hashes {
986 let hash = rmp_serde::to_vec(hash)?;
987 txn.add_olm_hash(&hash)?;
988 }
989
990 for request in changes.key_requests {
991 let request_id = this.encode_key("key_requests", request.request_id.as_bytes());
992 let serialized_request = this.serialize_value(&request)?;
993 txn.set_key_request(&request_id, request.sent_out, &serialized_request)?;
994 }
995
996 for (room_id, data) in changes.withheld_session_info {
997 for (session_id, event) in data {
998 let session_id = this.encode_key("direct_withheld_info", session_id);
999 let room_id = this.encode_key("direct_withheld_info", &room_id);
1000 let serialized_info = this.serialize_json(&event)?;
1001 txn.set_direct_withheld(&session_id, &room_id, &serialized_info)?;
1002 }
1003 }
1004
1005 for (room_id, settings) in changes.room_settings {
1006 let room_id = this.encode_key("room_settings", room_id.as_bytes());
1007 let value = this.serialize_value(&settings)?;
1008 txn.set_room_settings(&room_id, &value)?;
1009 }
1010
1011 for secret in changes.secrets {
1012 let secret_name = this.encode_key("secrets", secret.secret_name.to_string());
1013 let value = this.serialize_json(&secret)?;
1014 txn.set_secret(&secret_name, &value)?;
1015 }
1016
1017 for bundle in changes.received_room_key_bundles {
1018 let room_id =
1019 this.encode_key("received_room_key_bundle", &bundle.bundle_data.room_id);
1020 let user_id = this.encode_key("received_room_key_bundle", &bundle.sender_user);
1021 let value = this.serialize_value(&bundle)?;
1022 txn.set_received_room_key_bundle(&room_id, &user_id, &value)?;
1023 }
1024
1025 Ok::<_, Error>(())
1026 })
1027 .await?;
1028
1029 Ok(())
1030 }
1031
1032 async fn save_inbound_group_sessions(
1033 &self,
1034 sessions: Vec<InboundGroupSession>,
1035 backed_up_to_version: Option<&str>,
1036 ) -> matrix_sdk_crypto::store::Result<(), Self::Error> {
1037 sessions.iter().for_each(|s| {
1039 let backed_up = s.backed_up();
1040 if backed_up != backed_up_to_version.is_some() {
1041 warn!(
1042 backed_up,
1043 backed_up_to_version,
1044 "Session backed-up flag does not correspond to backup version setting",
1045 );
1046 }
1047 });
1048
1049 self.save_changes(Changes { inbound_group_sessions: sessions, ..Changes::default() }).await
1052 }
1053
1054 async fn get_sessions(&self, sender_key: &str) -> Result<Option<Vec<Session>>> {
1055 let device_keys = self.get_own_device().await?.as_device_keys().clone();
1056
1057 let sessions: Vec<_> = self
1058 .acquire()
1059 .await?
1060 .get_sessions_for_sender_key(self.encode_key("session", sender_key.as_bytes()))
1061 .await?
1062 .into_iter()
1063 .map(|bytes| {
1064 let pickle = self.deserialize_value(&bytes)?;
1065 Session::from_pickle(device_keys.clone(), pickle).map_err(|_| Error::AccountUnset)
1066 })
1067 .collect::<Result<_>>()?;
1068
1069 if sessions.is_empty() {
1070 Ok(None)
1071 } else {
1072 Ok(Some(sessions))
1073 }
1074 }
1075
1076 #[instrument(skip(self))]
1077 async fn get_inbound_group_session(
1078 &self,
1079 room_id: &RoomId,
1080 session_id: &str,
1081 ) -> Result<Option<InboundGroupSession>> {
1082 let session_id = self.encode_key("inbound_group_session", session_id);
1083 let Some((room_id_from_db, value, backed_up)) =
1084 self.acquire().await?.get_inbound_group_session(session_id).await?
1085 else {
1086 return Ok(None);
1087 };
1088
1089 let room_id = self.encode_key("inbound_group_session", room_id.as_bytes());
1090 if *room_id != room_id_from_db {
1091 warn!("expected room_id for session_id doesn't match what's in the DB");
1092 return Ok(None);
1093 }
1094
1095 Ok(Some(self.deserialize_and_unpickle_inbound_group_session(value, backed_up)?))
1096 }
1097
1098 async fn get_inbound_group_sessions(&self) -> Result<Vec<InboundGroupSession>> {
1099 self.acquire()
1100 .await?
1101 .get_inbound_group_sessions()
1102 .await?
1103 .into_iter()
1104 .map(|(value, backed_up)| {
1105 self.deserialize_and_unpickle_inbound_group_session(value, backed_up)
1106 })
1107 .collect()
1108 }
1109
1110 async fn get_inbound_group_sessions_by_room_id(
1111 &self,
1112 room_id: &RoomId,
1113 ) -> Result<Vec<InboundGroupSession>> {
1114 let room_id = self.encode_key("inbound_group_session", room_id.as_bytes());
1115 self.acquire()
1116 .await?
1117 .get_inbound_group_sessions_by_room_id(room_id)
1118 .await?
1119 .into_iter()
1120 .map(|(value, backed_up)| {
1121 self.deserialize_and_unpickle_inbound_group_session(value, backed_up)
1122 })
1123 .collect()
1124 }
1125
1126 async fn get_inbound_group_sessions_for_device_batch(
1127 &self,
1128 sender_key: Curve25519PublicKey,
1129 sender_data_type: SenderDataType,
1130 after_session_id: Option<String>,
1131 limit: usize,
1132 ) -> Result<Vec<InboundGroupSession>, Self::Error> {
1133 let after_session_id =
1134 after_session_id.map(|session_id| self.encode_key("inbound_group_session", session_id));
1135 let sender_key = self.encode_key("inbound_group_session", sender_key.to_base64());
1136
1137 self.acquire()
1138 .await?
1139 .get_inbound_group_sessions_for_device_batch(
1140 sender_key,
1141 sender_data_type,
1142 after_session_id,
1143 limit,
1144 )
1145 .await?
1146 .into_iter()
1147 .map(|(value, backed_up)| {
1148 self.deserialize_and_unpickle_inbound_group_session(value, backed_up)
1149 })
1150 .collect()
1151 }
1152
1153 async fn inbound_group_session_counts(
1154 &self,
1155 backup_version: Option<&str>,
1156 ) -> Result<RoomKeyCounts> {
1157 Ok(self.acquire().await?.get_inbound_group_session_counts(backup_version).await?)
1158 }
1159
1160 async fn inbound_group_sessions_for_backup(
1161 &self,
1162 _backup_version: &str,
1163 limit: usize,
1164 ) -> Result<Vec<InboundGroupSession>> {
1165 self.acquire()
1166 .await?
1167 .get_inbound_group_sessions_for_backup(limit)
1168 .await?
1169 .into_iter()
1170 .map(|value| self.deserialize_and_unpickle_inbound_group_session(value, false))
1171 .collect()
1172 }
1173
1174 async fn mark_inbound_group_sessions_as_backed_up(
1175 &self,
1176 _backup_version: &str,
1177 session_ids: &[(&RoomId, &str)],
1178 ) -> Result<()> {
1179 Ok(self
1180 .acquire()
1181 .await?
1182 .mark_inbound_group_sessions_as_backed_up(
1183 session_ids
1184 .iter()
1185 .map(|(_, s)| self.encode_key("inbound_group_session", s))
1186 .collect(),
1187 )
1188 .await?)
1189 }
1190
1191 async fn reset_backup_state(&self) -> Result<()> {
1192 Ok(self.acquire().await?.reset_inbound_group_session_backup_state().await?)
1193 }
1194
1195 async fn load_backup_keys(&self) -> Result<BackupKeys> {
1196 let conn = self.acquire().await?;
1197
1198 let backup_version = conn
1199 .get_kv("backup_version_v1")
1200 .await?
1201 .map(|value| self.deserialize_value(&value))
1202 .transpose()?;
1203
1204 let decryption_key = conn
1205 .get_kv("recovery_key_v1")
1206 .await?
1207 .map(|value| self.deserialize_value(&value))
1208 .transpose()?;
1209
1210 Ok(BackupKeys { backup_version, decryption_key })
1211 }
1212
1213 async fn load_dehydrated_device_pickle_key(&self) -> Result<Option<DehydratedDeviceKey>> {
1214 let conn = self.acquire().await?;
1215
1216 conn.get_kv(DEHYDRATED_DEVICE_PICKLE_KEY)
1217 .await?
1218 .map(|value| self.deserialize_value(&value))
1219 .transpose()
1220 }
1221
1222 async fn delete_dehydrated_device_pickle_key(&self) -> Result<(), Self::Error> {
1223 let conn = self.acquire().await?;
1224 conn.clear_kv(DEHYDRATED_DEVICE_PICKLE_KEY).await?;
1225
1226 Ok(())
1227 }
1228 async fn get_outbound_group_session(
1229 &self,
1230 room_id: &RoomId,
1231 ) -> Result<Option<OutboundGroupSession>> {
1232 let room_id = self.encode_key("outbound_group_session", room_id.as_bytes());
1233 let Some(value) = self.acquire().await?.get_outbound_group_session(room_id).await? else {
1234 return Ok(None);
1235 };
1236
1237 let account_info = self.get_static_account().ok_or(Error::AccountUnset)?;
1238
1239 let pickle = self.deserialize_json(&value)?;
1240 let session = OutboundGroupSession::from_pickle(
1241 account_info.device_id,
1242 account_info.identity_keys,
1243 pickle,
1244 )
1245 .map_err(|_| Error::Unpickle)?;
1246
1247 return Ok(Some(session));
1248 }
1249
1250 async fn load_tracked_users(&self) -> Result<Vec<TrackedUser>> {
1251 self.acquire()
1252 .await?
1253 .get_tracked_users()
1254 .await?
1255 .iter()
1256 .map(|value| self.deserialize_value(value))
1257 .collect()
1258 }
1259
1260 async fn save_tracked_users(&self, tracked_users: &[(&UserId, bool)]) -> Result<()> {
1261 let users: Vec<(Key, Vec<u8>)> = tracked_users
1262 .iter()
1263 .map(|(u, d)| {
1264 let user_id = self.encode_key("tracked_users", u.as_bytes());
1265 let data =
1266 self.serialize_value(&TrackedUser { user_id: (*u).into(), dirty: *d })?;
1267 Ok((user_id, data))
1268 })
1269 .collect::<Result<_>>()?;
1270
1271 Ok(self.acquire().await?.add_tracked_users(users).await?)
1272 }
1273
1274 async fn get_device(
1275 &self,
1276 user_id: &UserId,
1277 device_id: &DeviceId,
1278 ) -> Result<Option<DeviceData>> {
1279 let user_id = self.encode_key("device", user_id.as_bytes());
1280 let device_id = self.encode_key("device", device_id.as_bytes());
1281 Ok(self
1282 .acquire()
1283 .await?
1284 .get_device(user_id, device_id)
1285 .await?
1286 .map(|value| self.deserialize_value(&value))
1287 .transpose()?)
1288 }
1289
1290 async fn get_user_devices(
1291 &self,
1292 user_id: &UserId,
1293 ) -> Result<HashMap<OwnedDeviceId, DeviceData>> {
1294 let user_id = self.encode_key("device", user_id.as_bytes());
1295 self.acquire()
1296 .await?
1297 .get_user_devices(user_id)
1298 .await?
1299 .into_iter()
1300 .map(|value| {
1301 let device: DeviceData = self.deserialize_value(&value)?;
1302 Ok((device.device_id().to_owned(), device))
1303 })
1304 .collect()
1305 }
1306
1307 async fn get_own_device(&self) -> Result<DeviceData> {
1308 let account_info = self.get_static_account().ok_or(Error::AccountUnset)?;
1309
1310 Ok(self
1311 .get_device(&account_info.user_id, &account_info.device_id)
1312 .await?
1313 .expect("We should be able to find our own device."))
1314 }
1315
1316 async fn get_user_identity(&self, user_id: &UserId) -> Result<Option<UserIdentityData>> {
1317 let user_id = self.encode_key("identity", user_id.as_bytes());
1318 Ok(self
1319 .acquire()
1320 .await?
1321 .get_user_identity(user_id)
1322 .await?
1323 .map(|value| self.deserialize_value(&value))
1324 .transpose()?)
1325 }
1326
1327 async fn is_message_known(
1328 &self,
1329 message_hash: &matrix_sdk_crypto::olm::OlmMessageHash,
1330 ) -> Result<bool> {
1331 let value = rmp_serde::to_vec(message_hash)?;
1332 Ok(self.acquire().await?.has_olm_hash(value).await?)
1333 }
1334
1335 async fn get_outgoing_secret_requests(
1336 &self,
1337 request_id: &TransactionId,
1338 ) -> Result<Option<GossipRequest>> {
1339 let request_id = self.encode_key("key_requests", request_id.as_bytes());
1340 Ok(self
1341 .acquire()
1342 .await?
1343 .get_outgoing_secret_request(request_id)
1344 .await?
1345 .map(|(value, sent_out)| self.deserialize_key_request(&value, sent_out))
1346 .transpose()?)
1347 }
1348
1349 async fn get_secret_request_by_info(
1350 &self,
1351 key_info: &SecretInfo,
1352 ) -> Result<Option<GossipRequest>> {
1353 let requests = self.acquire().await?.get_outgoing_secret_requests().await?;
1354 for (request, sent_out) in requests {
1355 let request = self.deserialize_key_request(&request, sent_out)?;
1356 if request.info == *key_info {
1357 return Ok(Some(request));
1358 }
1359 }
1360 Ok(None)
1361 }
1362
1363 async fn get_unsent_secret_requests(&self) -> Result<Vec<GossipRequest>> {
1364 self.acquire()
1365 .await?
1366 .get_unsent_secret_requests()
1367 .await?
1368 .iter()
1369 .map(|value| {
1370 let request = self.deserialize_key_request(value, false)?;
1371 Ok(request)
1372 })
1373 .collect()
1374 }
1375
1376 async fn delete_outgoing_secret_requests(&self, request_id: &TransactionId) -> Result<()> {
1377 let request_id = self.encode_key("key_requests", request_id.as_bytes());
1378 Ok(self.acquire().await?.delete_key_request(request_id).await?)
1379 }
1380
1381 async fn get_secrets_from_inbox(
1382 &self,
1383 secret_name: &SecretName,
1384 ) -> Result<Vec<GossippedSecret>> {
1385 let secret_name = self.encode_key("secrets", secret_name.to_string());
1386
1387 self.acquire()
1388 .await?
1389 .get_secrets_from_inbox(secret_name)
1390 .await?
1391 .into_iter()
1392 .map(|value| self.deserialize_json(value.as_ref()))
1393 .collect()
1394 }
1395
1396 async fn delete_secrets_from_inbox(&self, secret_name: &SecretName) -> Result<()> {
1397 let secret_name = self.encode_key("secrets", secret_name.to_string());
1398 self.acquire().await?.delete_secrets_from_inbox(secret_name).await
1399 }
1400
1401 async fn get_withheld_info(
1402 &self,
1403 room_id: &RoomId,
1404 session_id: &str,
1405 ) -> Result<Option<RoomKeyWithheldEntry>> {
1406 let room_id = self.encode_key("direct_withheld_info", room_id);
1407 let session_id = self.encode_key("direct_withheld_info", session_id);
1408
1409 self.acquire()
1410 .await?
1411 .get_direct_withheld_info(session_id, room_id)
1412 .await?
1413 .map(|value| {
1414 let info = self.deserialize_json::<RoomKeyWithheldEntry>(&value)?;
1415 Ok(info)
1416 })
1417 .transpose()
1418 }
1419
1420 async fn get_withheld_sessions_by_room_id(
1421 &self,
1422 room_id: &RoomId,
1423 ) -> matrix_sdk_crypto::store::Result<Vec<RoomKeyWithheldEntry>, Self::Error> {
1424 let room_id = self.encode_key("direct_withheld_info", room_id);
1425
1426 self.acquire()
1427 .await?
1428 .get_withheld_sessions_by_room_id(room_id)
1429 .await?
1430 .into_iter()
1431 .map(|value| self.deserialize_json(&value))
1432 .collect()
1433 }
1434
1435 async fn get_room_settings(&self, room_id: &RoomId) -> Result<Option<RoomSettings>> {
1436 let room_id = self.encode_key("room_settings", room_id.as_bytes());
1437 let Some(value) = self.acquire().await?.get_room_settings(room_id).await? else {
1438 return Ok(None);
1439 };
1440
1441 let settings = self.deserialize_value(&value)?;
1442
1443 return Ok(Some(settings));
1444 }
1445
1446 async fn get_received_room_key_bundle_data(
1447 &self,
1448 room_id: &RoomId,
1449 user_id: &UserId,
1450 ) -> Result<Option<StoredRoomKeyBundleData>> {
1451 let room_id = self.encode_key("received_room_key_bundle", room_id);
1452 let user_id = self.encode_key("received_room_key_bundle", user_id);
1453 self.acquire()
1454 .await?
1455 .get_received_room_key_bundle(room_id, user_id)
1456 .await?
1457 .map(|value| self.deserialize_value(&value))
1458 .transpose()
1459 }
1460
1461 async fn get_custom_value(&self, key: &str) -> Result<Option<Vec<u8>>> {
1462 let Some(serialized) = self.acquire().await?.get_kv(key).await? else {
1463 return Ok(None);
1464 };
1465 let value = if let Some(cipher) = &self.store_cipher {
1466 let encrypted = rmp_serde::from_slice(&serialized)?;
1467 cipher.decrypt_value_data(encrypted)?
1468 } else {
1469 serialized
1470 };
1471
1472 Ok(Some(value))
1473 }
1474
1475 async fn set_custom_value(&self, key: &str, value: Vec<u8>) -> Result<()> {
1476 let serialized = if let Some(cipher) = &self.store_cipher {
1477 let encrypted = cipher.encrypt_value_data(value)?;
1478 rmp_serde::to_vec_named(&encrypted)?
1479 } else {
1480 value
1481 };
1482
1483 self.acquire().await?.set_kv(key, serialized).await?;
1484 Ok(())
1485 }
1486
1487 async fn remove_custom_value(&self, key: &str) -> Result<()> {
1488 let key = key.to_owned();
1489 self.acquire()
1490 .await?
1491 .interact(move |conn| conn.execute("DELETE FROM kv WHERE key = ?1", (&key,)))
1492 .await
1493 .unwrap()?;
1494 Ok(())
1495 }
1496
1497 #[instrument(skip(self))]
1498 async fn try_take_leased_lock(
1499 &self,
1500 lease_duration_ms: u32,
1501 key: &str,
1502 holder: &str,
1503 ) -> Result<Option<CrossProcessLockGeneration>> {
1504 let _timer = timer!("method");
1505
1506 let key = key.to_owned();
1507 let holder = holder.to_owned();
1508
1509 let now: u64 = MilliSecondsSinceUnixEpoch::now().get().into();
1510 let expiration = now + lease_duration_ms as u64;
1511
1512 let generation = self
1514 .acquire()
1515 .await?
1516 .with_transaction(move |txn| {
1517 txn.query_row(
1518 "INSERT INTO lease_locks (key, holder, expiration)
1519 VALUES (?1, ?2, ?3)
1520 ON CONFLICT (key)
1521 DO
1522 UPDATE SET
1523 holder = excluded.holder,
1524 expiration = excluded.expiration,
1525 generation =
1526 CASE holder
1527 WHEN excluded.holder THEN generation
1528 ELSE generation + 1
1529 END
1530 WHERE
1531 holder = excluded.holder
1532 OR expiration < ?4
1533 RETURNING generation
1534 ",
1535 (key, holder, expiration, now),
1536 |row| row.get(0),
1537 )
1538 .optional()
1539 })
1540 .await?;
1541
1542 Ok(generation)
1543 }
1544
1545 async fn next_batch_token(&self) -> Result<Option<String>, Self::Error> {
1546 let conn = self.acquire().await?;
1547 if let Some(token) = conn.get_kv("next_batch_token").await? {
1548 let maybe_token: Option<String> = self.deserialize_value(&token)?;
1549 Ok(maybe_token)
1550 } else {
1551 Ok(None)
1552 }
1553 }
1554}
1555
1556#[cfg(test)]
1557mod tests {
1558 use std::path::Path;
1559
1560 use matrix_sdk_common::deserialized_responses::WithheldCode;
1561 use matrix_sdk_crypto::{
1562 cryptostore_integration_tests, cryptostore_integration_tests_time, olm::SenderDataType,
1563 store::CryptoStore,
1564 };
1565 use matrix_sdk_test::async_test;
1566 use once_cell::sync::Lazy;
1567 use ruma::{device_id, room_id, user_id};
1568 use similar_asserts::assert_eq;
1569 use tempfile::{tempdir, TempDir};
1570 use tokio::fs;
1571
1572 use super::SqliteCryptoStore;
1573 use crate::SqliteStoreConfig;
1574
1575 static TMP_DIR: Lazy<TempDir> = Lazy::new(|| tempdir().unwrap());
1576
1577 struct TestDb {
1578 _dir: TempDir,
1581 database: SqliteCryptoStore,
1582 }
1583
1584 fn copy_db(data_path: &str) -> TempDir {
1585 let db_name = super::DATABASE_NAME;
1586
1587 let manifest_path = Path::new(env!("CARGO_MANIFEST_DIR")).join("../..");
1588 let database_path = manifest_path.join(data_path).join(db_name);
1589
1590 let tmpdir = tempdir().unwrap();
1591 let destination = tmpdir.path().join(db_name);
1592
1593 std::fs::copy(&database_path, destination).unwrap();
1595
1596 tmpdir
1597 }
1598
1599 async fn get_test_db(data_path: &str, passphrase: Option<&str>) -> TestDb {
1600 let tmpdir = copy_db(data_path);
1601
1602 let database = SqliteCryptoStore::open(tmpdir.path(), passphrase)
1603 .await
1604 .expect("Can't open the test store");
1605
1606 TestDb { _dir: tmpdir, database }
1607 }
1608
1609 #[async_test]
1610 async fn test_pool_size() {
1611 let store_open_config =
1612 SqliteStoreConfig::new(TMP_DIR.path().join("test_pool_size")).pool_max_size(42);
1613
1614 let store = SqliteCryptoStore::open_with_config(store_open_config).await.unwrap();
1615
1616 assert_eq!(store.pool.status().max_size, 42);
1617 }
1618
1619 #[async_test]
1622 async fn test_open_test_vector_store() {
1623 let TestDb { _dir: _, database } = get_test_db("testing/data/storage", None).await;
1624
1625 let account = database
1626 .load_account()
1627 .await
1628 .unwrap()
1629 .expect("The test database is prefilled with data, we should find an account");
1630
1631 let user_id = account.user_id();
1632 let device_id = account.device_id();
1633
1634 assert_eq!(
1635 user_id.as_str(),
1636 "@pjtest:synapse-oidc.element.dev",
1637 "The user ID should match to the one we expect."
1638 );
1639
1640 assert_eq!(
1641 device_id.as_str(),
1642 "v4TqgcuIH6",
1643 "The device ID should match to the one we expect."
1644 );
1645
1646 let device = database
1647 .get_device(user_id, device_id)
1648 .await
1649 .unwrap()
1650 .expect("Our own device should be found in the store.");
1651
1652 assert_eq!(device.device_id(), device_id);
1653 assert_eq!(device.user_id(), user_id);
1654
1655 assert_eq!(
1656 device.ed25519_key().expect("The device should have a Ed25519 key.").to_base64(),
1657 "+cxl1Gl3du5i7UJwfWnoRDdnafFF+xYdAiTYYhYLr8s"
1658 );
1659
1660 assert_eq!(
1661 device.curve25519_key().expect("The device should have a Curve25519 key.").to_base64(),
1662 "4SL9eEUlpyWSUvjljC5oMjknHQQJY7WZKo5S1KL/5VU"
1663 );
1664
1665 let identity = database
1666 .get_user_identity(user_id)
1667 .await
1668 .unwrap()
1669 .expect("The store should contain an identity.");
1670
1671 assert_eq!(identity.user_id(), user_id);
1672
1673 let identity = identity
1674 .own()
1675 .expect("The identity should be of the correct type, it should be our own identity.");
1676
1677 let master_key = identity
1678 .master_key()
1679 .get_first_key()
1680 .expect("Our own identity should have a master key");
1681
1682 assert_eq!(master_key.to_base64(), "iCUEtB1RwANeqRa5epDrblLk4mer/36sylwQ5hYY3oE");
1683 }
1684
1685 #[async_test]
1688 async fn test_open_test_vector_encrypted_store() {
1689 let TestDb { _dir: _, database } = get_test_db(
1690 "testing/data/storage/alice",
1691 Some(concat!(
1692 "/rCia2fYAJ+twCZ1Xm2mxFCYcmJdyzkdJjwtgXsziWpYS/UeNxnixuSieuwZXm+x1VsJHmWpl",
1693 "H+QIQBZpEGZtC9/S/l8xK+WOCesmET0o6yJ/KP73ofDtjBlnNpPwuHLKFpyTbyicpCgQ4UT+5E",
1694 "UBuJ08TY9Ujdf1D13k5kr5tSZUefDKKCuG1fCRqlU8ByRas1PMQsZxT2W8t7QgBrQiiGmhpo/O",
1695 "Ti4hfx97GOxncKcxTzppiYQNoHs/f15+XXQD7/oiCcqRIuUlXNsU6hRpFGmbYx2Pi1eyQViQCt",
1696 "B5dAEiSD0N8U81wXYnpynuTPtnL+hfnOJIn7Sy7mkERQeKg"
1697 )),
1698 )
1699 .await;
1700
1701 let account = database
1702 .load_account()
1703 .await
1704 .unwrap()
1705 .expect("The test database is prefilled with data, we should find an account");
1706
1707 let user_id = account.user_id();
1708 let device_id = account.device_id();
1709
1710 assert_eq!(
1711 user_id.as_str(),
1712 "@alice:localhost",
1713 "The user ID should match to the one we expect."
1714 );
1715
1716 assert_eq!(
1717 device_id.as_str(),
1718 "JVVORTHFXY",
1719 "The device ID should match to the one we expect."
1720 );
1721
1722 let tracked_users =
1723 database.load_tracked_users().await.expect("Should be tracking some users");
1724
1725 assert_eq!(tracked_users.len(), 6);
1726
1727 let known_users = vec![
1728 user_id!("@alice:localhost"),
1729 user_id!("@dehydration3:localhost"),
1730 user_id!("@eve:localhost"),
1731 user_id!("@bob:localhost"),
1732 user_id!("@malo:localhost"),
1733 user_id!("@carl:localhost"),
1734 ];
1735
1736 for user_id in known_users {
1738 database.get_user_identity(user_id).await.expect("Should load this identity").unwrap();
1739 }
1740
1741 let carl_identity =
1742 database.get_user_identity(user_id!("@carl:localhost")).await.unwrap().unwrap();
1743
1744 assert_eq!(
1745 carl_identity.master_key().get_first_key().unwrap().to_base64(),
1746 "CdhKYYDeBDQveOioXEGWhTPCyzc63Irpar3CNyfun2Q"
1747 );
1748 assert!(!carl_identity.was_previously_verified());
1749
1750 let bob_identity =
1751 database.get_user_identity(user_id!("@bob:localhost")).await.unwrap().unwrap();
1752
1753 assert_eq!(
1754 bob_identity.master_key().get_first_key().unwrap().to_base64(),
1755 "COh2GYOJWSjem5QPRCaGp9iWV83IELG1IzLKW2S3pFY"
1756 );
1757 assert!(bob_identity.was_previously_verified());
1759
1760 let known_devices = vec![
1761 (device_id!("OPXQHCZSKW"), user_id!("@alice:localhost")),
1762 (
1764 device_id!("EvW+9IrGR10KVgVeZP25/KaPfx4R86FofVMcaz7VOho"),
1765 user_id!("@alice:localhost"),
1766 ),
1767 (device_id!("HEEFRFQENV"), user_id!("@alice:localhost")),
1768 (device_id!("JVVORTHFXY"), user_id!("@alice:localhost")),
1769 (device_id!("NQUWWSKKHS"), user_id!("@alice:localhost")),
1770 (device_id!("ORBLPFYCPG"), user_id!("@alice:localhost")),
1771 (device_id!("YXOWENSEGM"), user_id!("@dehydration3:localhost")),
1772 (device_id!("VXLFMYCHXC"), user_id!("@bob:localhost")),
1773 (device_id!("FDGDQAEWOW"), user_id!("@bob:localhost")),
1774 (device_id!("VXLFMYCHXC"), user_id!("@bob:localhost")),
1775 (device_id!("FDGDQAEWOW"), user_id!("@bob:localhost")),
1776 (device_id!("QKUKWJTTQC"), user_id!("@malo:localhost")),
1777 (device_id!("LOUXJECTFG"), user_id!("@malo:localhost")),
1778 (device_id!("MKKMAEVLPB"), user_id!("@carl:localhost")),
1779 ];
1780
1781 for (device_id, user_id) in known_devices {
1782 database.get_device(user_id, device_id).await.expect("Should load the device").unwrap();
1783 }
1784
1785 let known_sender_key_to_session_count = vec![
1786 ("FfYcYfDF4nWy+LHdK6CEpIMlFAQDORc30WUkghL06kM", 1),
1787 ("EvW+9IrGR10KVgVeZP25/KaPfx4R86FofVMcaz7VOho", 1),
1788 ("hAGsoA4a9M6wwEUX5Q1jux1i+tUngLi01n5AmhDoHTY", 1),
1789 ("aKqtSJymLzuoglWFwPGk1r/Vm2LE2hFESzXxn4RNjRM", 0),
1790 ("zHK1psCrgeMn0kaz8hcdvA3INyar9jg1yfrSp0p1pHo", 1),
1791 ("1QmBA316Wj5jIFRwNOti6N6Xh/vW0bsYCcR4uPfy8VQ", 1),
1792 ("g5ef2vZF3VXgSPyODIeXpyHIRkuthvLhGvd6uwYggWU", 1),
1793 ("o7hfupPd1VsNkRIvdlH6ujrEJFSKjFCGbxhAd31XxjI", 1),
1794 ("Z3RxKQLxY7xpP+ZdOGR2SiNE37SrvmRhW7GPu1UGdm8", 1),
1795 ("GDomaav8NiY3J+dNEeApJm+O0FooJ3IpVaIyJzCN4w4", 1),
1796 ("7m7fqkHyEr47V5s/KjaxtJMOr3pSHrrns2q2lWpAQi8", 0),
1797 ("9psAkPUIF8vNbWbnviX3PlwRcaeO53EHJdNtKpTY1X0", 0),
1798 ("mqanh+ztw5oRtpqYQgLGW864i6NY2zpoKMIlrcyC+Aw", 0),
1799 ("fJU/TJdbsv7tVbbpHw1Ke73ziElnM32cNhP2WIg4T10", 0),
1800 ("sUIeFeFcCZoa5IC6nJ6Vrbvztcyx09m8BBg57XKRClg", 1),
1801 ];
1802
1803 for (id, count) in known_sender_key_to_session_count {
1804 let olm_sessions =
1805 database.get_sessions(id).await.expect("Should have some olm sessions");
1806
1807 println!("### Session id: {id:?}");
1808 assert_eq!(olm_sessions.map_or(0, |v| v.len()), count);
1809 }
1810
1811 let inbound_group_sessions = database.get_inbound_group_sessions().await.unwrap();
1812 assert_eq!(inbound_group_sessions.len(), 15);
1813 let known_inbound_group_sessions = vec![
1814 (
1815 "5hNAxrLai3VI0LKBwfh3wLfksfBFWds0W1a5X5/vSXA",
1816 room_id!("!SRstFdydzrGwJYtVfm:localhost"),
1817 ),
1818 (
1819 "M6d2eU3y54gaYTbvGSlqa/xc1Az35l56Cp9sxzHWO4g",
1820 room_id!("!SRstFdydzrGwJYtVfm:localhost"),
1821 ),
1822 (
1823 "IrydwXkRk2N2AqUMIVmLL3oJgMq14R9KId0P/uSD100",
1824 room_id!("!SRstFdydzrGwJYtVfm:localhost"),
1825 ),
1826 (
1827 "Y74+l9jTo7N5UF+GQwdpgJGe4sn1+QtWITq7BxulHIE",
1828 room_id!("!SRstFdydzrGwJYtVfm:localhost"),
1829 ),
1830 (
1831 "HpJxQR57WbQGdY6w2Q+C16znVvbXGa+JvQdRoMpWbXg",
1832 room_id!("!SRstFdydzrGwJYtVfm:localhost"),
1833 ),
1834 (
1835 "Xetvi+ydFkZt8dpONGFbEusQb/Chc2V0XlLByZhsbgE",
1836 room_id!("!ZIwZcFqZVAYLAqVjfV:localhost"),
1837 ),
1838 (
1839 "wv/WN/39akyerIXczTaIpjAuLnwgXKRtbXFSEHiJqxo",
1840 room_id!("!ZIwZcFqZVAYLAqVjfV:localhost"),
1841 ),
1842 (
1843 "nA4gQwL//Cm8OdlyjABl/jChbPT/cP5V4Sd8iuE6H0s",
1844 room_id!("!ZIwZcFqZVAYLAqVjfV:localhost"),
1845 ),
1846 (
1847 "bAAgqFeRDTjfEqL6Qf/c9mk55zoNDCSlboAIRd6b0hw",
1848 room_id!("!ZIwZcFqZVAYLAqVjfV:localhost"),
1849 ),
1850 (
1851 "exPbsMMdGfAG2qmDdFtpAn+koVprfzS0Zip/RA9QRCE",
1852 room_id!("!ZIwZcFqZVAYLAqVjfV:localhost"),
1853 ),
1854 (
1855 "h+om7oSw/ZV94fcKaoe8FGXJwQXWOfKQfzbGgNWQILI",
1856 room_id!("!ZIwZcFqZVAYLAqVjfV:localhost"),
1857 ),
1858 (
1859 "ul3VXonpgk4lO2L3fEWubP/nxsTmLHqu5v8ZM9vHEcw",
1860 room_id!("!ZIwZcFqZVAYLAqVjfV:localhost"),
1861 ),
1862 (
1863 "JXY15UxC3az2mwg8uX4qwgxfvCM4aygiIWMcdNiVQoc",
1864 room_id!("!ZIwZcFqZVAYLAqVjfV:localhost"),
1865 ),
1866 (
1867 "OGB9lObr9kWUvha9tB5sMfOF/Mztk24JwQz/nwg3iFQ",
1868 room_id!("!OgRiTRMaUzLdpCeDBM:localhost"),
1869 ),
1870 (
1871 "SFkHcbxjUOYF7mUAYI/oEMDZFaXszQbCN6Jza7iemj0",
1872 room_id!("!OgRiTRMaUzLdpCeDBM:localhost"),
1873 ),
1874 ];
1875
1876 for (session_id, room_id) in &known_inbound_group_sessions {
1878 database
1879 .get_inbound_group_session(room_id, session_id)
1880 .await
1881 .expect("Should be able to load inbound group session")
1882 .unwrap();
1883 }
1884
1885 let bob_sender_verified = database
1886 .get_inbound_group_session(
1887 room_id!("!ZIwZcFqZVAYLAqVjfV:localhost"),
1888 "exPbsMMdGfAG2qmDdFtpAn+koVprfzS0Zip/RA9QRCE",
1889 )
1890 .await
1891 .unwrap()
1892 .unwrap();
1893
1894 assert_eq!(bob_sender_verified.sender_data.to_type(), SenderDataType::SenderVerified);
1895 assert!(bob_sender_verified.backed_up());
1896 assert!(!bob_sender_verified.has_been_imported());
1897
1898 let alice_unknown_device = database
1899 .get_inbound_group_session(
1900 room_id!("!SRstFdydzrGwJYtVfm:localhost"),
1901 "IrydwXkRk2N2AqUMIVmLL3oJgMq14R9KId0P/uSD100",
1902 )
1903 .await
1904 .unwrap()
1905 .unwrap();
1906
1907 assert_eq!(alice_unknown_device.sender_data.to_type(), SenderDataType::UnknownDevice);
1908 assert!(alice_unknown_device.backed_up());
1909 assert!(alice_unknown_device.has_been_imported());
1910
1911 let carl_tofu_session = database
1912 .get_inbound_group_session(
1913 room_id!("!OgRiTRMaUzLdpCeDBM:localhost"),
1914 "OGB9lObr9kWUvha9tB5sMfOF/Mztk24JwQz/nwg3iFQ",
1915 )
1916 .await
1917 .unwrap()
1918 .unwrap();
1919
1920 assert_eq!(carl_tofu_session.sender_data.to_type(), SenderDataType::SenderUnverified);
1921 assert!(carl_tofu_session.backed_up());
1922 assert!(!carl_tofu_session.has_been_imported());
1923
1924 database
1926 .get_outbound_group_session(room_id!("!OgRiTRMaUzLdpCeDBM:localhost"))
1927 .await
1928 .unwrap()
1929 .unwrap();
1930 database
1931 .get_outbound_group_session(room_id!("!ZIwZcFqZVAYLAqVjfV:localhost"))
1932 .await
1933 .unwrap()
1934 .unwrap();
1935 database
1936 .get_outbound_group_session(room_id!("!SRstFdydzrGwJYtVfm:localhost"))
1937 .await
1938 .unwrap()
1939 .unwrap();
1940
1941 let withheld_info = database
1942 .get_withheld_info(
1943 room_id!("!OgRiTRMaUzLdpCeDBM:localhost"),
1944 "SASgZ+EklvAF4QxJclMlDRlmL0fAMjAJJIKFMdb4Ht0",
1945 )
1946 .await
1947 .expect("This session should be withheld")
1948 .unwrap();
1949
1950 assert_eq!(withheld_info.content.withheld_code(), WithheldCode::Unverified);
1951
1952 let backup_keys = database.load_backup_keys().await.expect("backup key should be cached");
1953 assert_eq!(backup_keys.backup_version.unwrap(), "6");
1954 assert!(backup_keys.decryption_key.is_some());
1955 }
1956
1957 async fn get_store(
1958 name: &str,
1959 passphrase: Option<&str>,
1960 clear_data: bool,
1961 ) -> SqliteCryptoStore {
1962 let tmpdir_path = TMP_DIR.path().join(name);
1963
1964 if clear_data {
1965 let _ = fs::remove_dir_all(&tmpdir_path).await;
1966 }
1967
1968 SqliteCryptoStore::open(tmpdir_path.to_str().unwrap(), passphrase)
1969 .await
1970 .expect("Can't create a secret protected store")
1971 }
1972
1973 cryptostore_integration_tests!();
1974 cryptostore_integration_tests_time!();
1975}
1976
1977#[cfg(test)]
1978mod encrypted_tests {
1979 use matrix_sdk_crypto::{cryptostore_integration_tests, cryptostore_integration_tests_time};
1980 use once_cell::sync::Lazy;
1981 use tempfile::{tempdir, TempDir};
1982 use tokio::fs;
1983
1984 use super::SqliteCryptoStore;
1985
1986 static TMP_DIR: Lazy<TempDir> = Lazy::new(|| tempdir().unwrap());
1987
1988 async fn get_store(
1989 name: &str,
1990 passphrase: Option<&str>,
1991 clear_data: bool,
1992 ) -> SqliteCryptoStore {
1993 let tmpdir_path = TMP_DIR.path().join(name);
1994 let pass = passphrase.unwrap_or("default_test_password");
1995
1996 if clear_data {
1997 let _ = fs::remove_dir_all(&tmpdir_path).await;
1998 }
1999
2000 SqliteCryptoStore::open(tmpdir_path.to_str().unwrap(), Some(pass))
2001 .await
2002 .expect("Can't create a secret protected store")
2003 }
2004
2005 cryptostore_integration_tests!();
2006 cryptostore_integration_tests_time!();
2007}