1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
use std::sync::Arc;
#[cfg(feature = "e2e-encryption")]
use cryptostore::CryptostoreData;
use helpers::{BorrowedSqlType, SqlType};
use matrix_sdk_base::store::StoreConfig;
#[cfg(feature = "e2e-encryption")]
use matrix_sdk_store_encryption::StoreCipher;
mod helpers;
pub use helpers::SupportedDatabase;
use matrix_sdk_base::{deserialized_responses::MemberEvent, MinimalRoomMemberEvent, RoomInfo};
use ruma::{
events::{
presence::PresenceEvent,
receipt::Receipt,
room::member::{StrippedRoomMemberEvent, SyncRoomMemberEvent},
AnyGlobalAccountDataEvent, AnyRoomAccountDataEvent, AnyStrippedStateEvent,
AnySyncStateEvent,
},
serde::Raw,
};
use sqlx::{
database::HasArguments, migrate::Migrate, types::Json, ColumnIndex, Database, Executor,
IntoArguments, Pool, Transaction,
};
use thiserror::Error;
#[cfg(feature = "e2e-encryption")]
mod cryptostore;
mod statestore;
#[derive(Debug, Error)]
#[non_exhaustive]
pub enum SQLStoreError {
#[error("Database error: {0}")]
Database(#[from] sqlx::Error),
#[error("Migration for database failed: {0}")]
Migration(#[from] sqlx::migrate::MigrateError),
#[cfg(feature = "e2e-encryption")]
#[error("A cryptostore access ocurred without the database being unlocked")]
DatabaseLocked,
#[error("Data failed to decode: UTF-8 error {0}")]
DecodeUtf8(#[from] std::string::FromUtf8Error),
#[error("Data failed to decode: ID decoding error {0}")]
DecodeId(#[from] ruma::IdParseError),
#[cfg(feature = "e2e-encryption")]
#[error("Failed to encrypt/decrypt data: {0}")]
Crypto(#[from] matrix_sdk_store_encryption::Error),
#[cfg(feature = "e2e-encryption")]
#[error("Failed to encode/decode data as bincode: {0}")]
Bincode(#[from] bincode::Error),
#[cfg(feature = "e2e-encryption")]
#[error("Failed to encode/decode data as json: {0}")]
Json(#[from] serde_json::Error),
#[cfg(feature = "e2e-encryption")]
#[error("Failed to pickle data: {0}")]
Pickle(#[from] vodozemac::PickleError),
#[cfg(feature = "e2e-encryption")]
#[error("Failed to verify data: {0}")]
Sign(Box<dyn std::error::Error + Send + Sync>),
#[cfg(feature = "e2e-encryption")]
#[error("Account info was not found")]
MissingAccountInfo,
}
pub type Result<T, E = SQLStoreError> = std::result::Result<T, E>;
#[allow(single_use_lifetimes)]
#[derive(Debug)]
pub struct StateStore<DB: SupportedDatabase> {
db: Arc<Pool<DB>>,
#[cfg(feature = "e2e-encryption")]
cryptostore: Option<CryptostoreData>,
}
#[allow(single_use_lifetimes)]
impl<DB: SupportedDatabase> StateStore<DB> {
pub async fn new(db: &Arc<Pool<DB>>) -> Result<Self>
where
<DB as Database>::Connection: Migrate,
{
let db = Arc::clone(db);
let migrator = DB::get_migrator();
migrator.run(&*db).await?;
#[cfg(not(feature = "e2e-encryption"))]
{
Ok(Self { db })
}
#[cfg(feature = "e2e-encryption")]
{
Ok(Self {
db,
cryptostore: None,
})
}
}
#[cfg(feature = "e2e-encryption")]
pub(crate) fn ensure_e2e(&self) -> Result<&CryptostoreData> {
self.cryptostore
.as_ref()
.ok_or(SQLStoreError::DatabaseLocked)
}
#[cfg(feature = "e2e-encryption")]
pub async fn unlock(&mut self) -> Result<()>
where
for<'a> <DB as HasArguments<'a>>::Arguments: IntoArguments<'a, DB>,
for<'c> &'c mut <DB as sqlx::Database>::Connection: Executor<'c, Database = DB>,
for<'c, 'a> &'a mut Transaction<'c, DB>: Executor<'a, Database = DB>,
for<'a> &'a [u8]: BorrowedSqlType<'a, DB>,
for<'a> &'a str: BorrowedSqlType<'a, DB>,
Vec<u8>: SqlType<DB>,
String: SqlType<DB>,
bool: SqlType<DB>,
Vec<u8>: SqlType<DB>,
Option<String>: SqlType<DB>,
Json<Raw<AnyGlobalAccountDataEvent>>: SqlType<DB>,
Json<Raw<PresenceEvent>>: SqlType<DB>,
Json<SyncRoomMemberEvent>: SqlType<DB>,
Json<MinimalRoomMemberEvent>: SqlType<DB>,
Json<Raw<AnySyncStateEvent>>: SqlType<DB>,
Json<Raw<AnyRoomAccountDataEvent>>: SqlType<DB>,
Json<RoomInfo>: SqlType<DB>,
Json<Receipt>: SqlType<DB>,
Json<Raw<AnyStrippedStateEvent>>: SqlType<DB>,
Json<StrippedRoomMemberEvent>: SqlType<DB>,
Json<MemberEvent>: SqlType<DB>,
for<'a> &'a str: ColumnIndex<<DB as Database>::Row>,
{
self.cryptostore = Some(CryptostoreData::new_unencrypted());
self.load_tracked_users().await?;
Ok(())
}
#[cfg(feature = "e2e-encryption")]
pub async fn unlock_with_passphrase(&mut self, passphrase: &str) -> Result<()>
where
for<'a> <DB as HasArguments<'a>>::Arguments: IntoArguments<'a, DB>,
for<'c> &'c mut <DB as sqlx::Database>::Connection: Executor<'c, Database = DB>,
for<'c, 'a> &'a mut Transaction<'c, DB>: Executor<'a, Database = DB>,
for<'a> &'a [u8]: BorrowedSqlType<'a, DB>,
for<'a> &'a str: BorrowedSqlType<'a, DB>,
Vec<u8>: SqlType<DB>,
String: SqlType<DB>,
bool: SqlType<DB>,
Vec<u8>: SqlType<DB>,
Option<String>: SqlType<DB>,
Json<Raw<AnyGlobalAccountDataEvent>>: SqlType<DB>,
Json<Raw<PresenceEvent>>: SqlType<DB>,
Json<SyncRoomMemberEvent>: SqlType<DB>,
Json<MinimalRoomMemberEvent>: SqlType<DB>,
Json<Raw<AnySyncStateEvent>>: SqlType<DB>,
Json<Raw<AnyRoomAccountDataEvent>>: SqlType<DB>,
Json<RoomInfo>: SqlType<DB>,
Json<Receipt>: SqlType<DB>,
Json<Raw<AnyStrippedStateEvent>>: SqlType<DB>,
Json<StrippedRoomMemberEvent>: SqlType<DB>,
Json<MemberEvent>: SqlType<DB>,
for<'a> &'a str: ColumnIndex<<DB as Database>::Row>,
{
let cipher_export = self.get_kv(b"cipher").await?;
if let Some(cipher) = cipher_export {
self.cryptostore = Some(CryptostoreData::new(StoreCipher::import(
passphrase, &cipher,
)?));
} else {
let cipher = StoreCipher::new()?;
self.insert_kv(b"cipher", &cipher.export(passphrase)?)
.await?;
self.cryptostore = Some(CryptostoreData::new(cipher));
}
self.load_tracked_users().await?;
Ok(())
}
}
pub async fn store_config<DB: SupportedDatabase>(
db: &Arc<Pool<DB>>,
passphrase: Option<&str>,
) -> Result<StoreConfig>
where
<DB as Database>::Connection: Migrate,
for<'a> <DB as HasArguments<'a>>::Arguments: IntoArguments<'a, DB>,
for<'c> &'c mut <DB as sqlx::Database>::Connection: Executor<'c, Database = DB>,
for<'c, 'a> &'a mut Transaction<'c, DB>: Executor<'a, Database = DB>,
for<'a> &'a [u8]: BorrowedSqlType<'a, DB>,
for<'a> &'a str: BorrowedSqlType<'a, DB>,
Vec<u8>: SqlType<DB>,
String: SqlType<DB>,
bool: SqlType<DB>,
Vec<u8>: SqlType<DB>,
Option<String>: SqlType<DB>,
Json<Raw<AnyGlobalAccountDataEvent>>: SqlType<DB>,
Json<Raw<PresenceEvent>>: SqlType<DB>,
Json<SyncRoomMemberEvent>: SqlType<DB>,
Json<MinimalRoomMemberEvent>: SqlType<DB>,
Json<Raw<AnySyncStateEvent>>: SqlType<DB>,
Json<Raw<AnyRoomAccountDataEvent>>: SqlType<DB>,
Json<RoomInfo>: SqlType<DB>,
Json<Receipt>: SqlType<DB>,
Json<Raw<AnyStrippedStateEvent>>: SqlType<DB>,
Json<StrippedRoomMemberEvent>: SqlType<DB>,
Json<MemberEvent>: SqlType<DB>,
for<'a> &'a str: ColumnIndex<<DB as Database>::Row>,
{
#[cfg(not(feature = "e2e-encryption"))]
{
let _ = passphrase;
let state_store = StateStore::new(db).await?;
Ok(StoreConfig::new().state_store(state_store))
}
#[cfg(feature = "e2e-encryption")]
{
let state_store = StateStore::new(db).await?;
let mut crypto_store = StateStore::new(db).await?;
if let Some(passphrase) = passphrase {
crypto_store.unlock_with_passphrase(passphrase).await?;
} else {
crypto_store.unlock().await?;
}
Ok(StoreConfig::new()
.state_store(state_store)
.crypto_store(crypto_store))
}
}