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
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
use std::{
collections::{HashMap, HashSet},
sync::Arc,
};
use async_trait::async_trait;
use dashmap::{DashMap, DashSet};
use matrix_sdk_common::locks::Mutex;
use ruma::{
DeviceId, OwnedDeviceId, OwnedTransactionId, OwnedUserId, RoomId, TransactionId, UserId,
};
use super::{
caches::{DeviceStore, GroupSessionStore, SessionStore},
BackupKeys, Changes, CryptoStore, InboundGroupSession, ReadOnlyAccount, Result, RoomKeyCounts,
Session,
};
use crate::{
gossiping::{GossipRequest, SecretInfo},
identities::{ReadOnlyDevice, ReadOnlyUserIdentities},
olm::{OutboundGroupSession, PrivateCrossSigningIdentity},
};
fn encode_key_info(info: &SecretInfo) -> String {
match info {
SecretInfo::KeyRequest(info) => {
format!("{}{}{}{}", info.room_id, info.sender_key, info.algorithm, info.session_id)
}
SecretInfo::SecretRequest(i) => i.as_ref().to_owned(),
}
}
#[derive(Debug, Clone)]
pub struct MemoryStore {
sessions: SessionStore,
inbound_group_sessions: GroupSessionStore,
tracked_users: Arc<DashSet<OwnedUserId>>,
users_for_key_query: Arc<DashSet<OwnedUserId>>,
olm_hashes: Arc<DashMap<String, DashSet<String>>>,
devices: DeviceStore,
identities: Arc<DashMap<OwnedUserId, ReadOnlyUserIdentities>>,
outgoing_key_requests: Arc<DashMap<OwnedTransactionId, GossipRequest>>,
key_requests_by_info: Arc<DashMap<String, OwnedTransactionId>>,
}
impl Default for MemoryStore {
fn default() -> Self {
MemoryStore {
sessions: SessionStore::new(),
inbound_group_sessions: GroupSessionStore::new(),
tracked_users: Default::default(),
users_for_key_query: Default::default(),
olm_hashes: Default::default(),
devices: DeviceStore::new(),
identities: Default::default(),
outgoing_key_requests: Default::default(),
key_requests_by_info: Default::default(),
}
}
}
impl MemoryStore {
pub fn new() -> Self {
Self::default()
}
pub(crate) async fn save_devices(&self, devices: Vec<ReadOnlyDevice>) {
for device in devices {
let _ = self.devices.add(device);
}
}
async fn delete_devices(&self, devices: Vec<ReadOnlyDevice>) {
for device in devices {
let _ = self.devices.remove(device.user_id(), device.device_id());
}
}
async fn save_sessions(&self, sessions: Vec<Session>) {
for session in sessions {
let _ = self.sessions.add(session.clone()).await;
}
}
async fn save_inbound_group_sessions(&self, sessions: Vec<InboundGroupSession>) {
for session in sessions {
self.inbound_group_sessions.add(session);
}
}
}
#[cfg_attr(target_arch = "wasm32", async_trait(?Send))]
#[cfg_attr(not(target_arch = "wasm32"), async_trait)]
impl CryptoStore for MemoryStore {
async fn load_account(&self) -> Result<Option<ReadOnlyAccount>> {
Ok(None)
}
async fn save_account(&self, _: ReadOnlyAccount) -> Result<()> {
Ok(())
}
async fn load_identity(&self) -> Result<Option<PrivateCrossSigningIdentity>> {
Ok(None)
}
async fn save_changes(&self, changes: Changes) -> Result<()> {
self.save_sessions(changes.sessions).await;
self.save_inbound_group_sessions(changes.inbound_group_sessions).await;
self.save_devices(changes.devices.new).await;
self.save_devices(changes.devices.changed).await;
self.delete_devices(changes.devices.deleted).await;
for identity in changes.identities.new.into_iter().chain(changes.identities.changed) {
let _ = self.identities.insert(identity.user_id().to_owned(), identity.clone());
}
for hash in changes.message_hashes {
self.olm_hashes
.entry(hash.sender_key.to_owned())
.or_default()
.insert(hash.hash.clone());
}
for key_request in changes.key_requests {
let id = key_request.request_id.clone();
let info_string = encode_key_info(&key_request.info);
self.outgoing_key_requests.insert(id.clone(), key_request);
self.key_requests_by_info.insert(info_string, id);
}
Ok(())
}
async fn get_sessions(&self, sender_key: &str) -> Result<Option<Arc<Mutex<Vec<Session>>>>> {
Ok(self.sessions.get(sender_key))
}
async fn get_inbound_group_session(
&self,
room_id: &RoomId,
sender_key: &str,
session_id: &str,
) -> Result<Option<InboundGroupSession>> {
Ok(self.inbound_group_sessions.get(room_id, sender_key, session_id))
}
async fn get_inbound_group_sessions(&self) -> Result<Vec<InboundGroupSession>> {
Ok(self.inbound_group_sessions.get_all())
}
async fn inbound_group_session_counts(&self) -> Result<RoomKeyCounts> {
let backed_up =
self.get_inbound_group_sessions().await?.into_iter().filter(|s| s.backed_up()).count();
Ok(RoomKeyCounts { total: self.inbound_group_sessions.count(), backed_up })
}
async fn inbound_group_sessions_for_backup(
&self,
limit: usize,
) -> Result<Vec<InboundGroupSession>> {
Ok(self
.get_inbound_group_sessions()
.await?
.into_iter()
.filter(|s| !s.backed_up())
.take(limit)
.collect())
}
async fn reset_backup_state(&self) -> Result<()> {
for session in self.get_inbound_group_sessions().await? {
session.reset_backup_state();
}
Ok(())
}
async fn get_outbound_group_sessions(
&self,
_: &RoomId,
) -> Result<Option<OutboundGroupSession>> {
Ok(None)
}
fn is_user_tracked(&self, user_id: &UserId) -> bool {
self.tracked_users.contains(user_id)
}
fn has_users_for_key_query(&self) -> bool {
!self.users_for_key_query.is_empty()
}
fn users_for_key_query(&self) -> HashSet<OwnedUserId> {
self.users_for_key_query.iter().map(|u| u.clone()).collect()
}
fn tracked_users(&self) -> HashSet<OwnedUserId> {
self.tracked_users.iter().map(|u| u.to_owned()).collect()
}
async fn update_tracked_user(&self, user: &UserId, dirty: bool) -> Result<bool> {
if dirty {
self.users_for_key_query.insert(user.to_owned());
} else {
self.users_for_key_query.remove(user);
}
Ok(self.tracked_users.insert(user.to_owned()))
}
async fn get_device(
&self,
user_id: &UserId,
device_id: &DeviceId,
) -> Result<Option<ReadOnlyDevice>> {
Ok(self.devices.get(user_id, device_id))
}
async fn get_user_devices(
&self,
user_id: &UserId,
) -> Result<HashMap<OwnedDeviceId, ReadOnlyDevice>> {
Ok(self.devices.user_devices(user_id))
}
async fn get_user_identity(&self, user_id: &UserId) -> Result<Option<ReadOnlyUserIdentities>> {
Ok(self.identities.get(user_id).map(|i| i.clone()))
}
async fn is_message_known(&self, message_hash: &crate::olm::OlmMessageHash) -> Result<bool> {
Ok(self
.olm_hashes
.entry(message_hash.sender_key.to_owned())
.or_default()
.contains(&message_hash.hash))
}
async fn get_outgoing_secret_requests(
&self,
request_id: &TransactionId,
) -> Result<Option<GossipRequest>> {
Ok(self.outgoing_key_requests.get(request_id).map(|r| r.clone()))
}
async fn get_secret_request_by_info(
&self,
key_info: &SecretInfo,
) -> Result<Option<GossipRequest>> {
let key_info_string = encode_key_info(key_info);
Ok(self
.key_requests_by_info
.get(&key_info_string)
.and_then(|i| self.outgoing_key_requests.get(&*i).map(|r| r.clone())))
}
async fn get_unsent_secret_requests(&self) -> Result<Vec<GossipRequest>> {
Ok(self
.outgoing_key_requests
.iter()
.filter(|i| !i.value().sent_out)
.map(|i| i.value().clone())
.collect())
}
async fn delete_outgoing_secret_requests(&self, request_id: &TransactionId) -> Result<()> {
self.outgoing_key_requests.remove(request_id).and_then(|(_, i)| {
let key_info_string = encode_key_info(&i.info);
self.key_requests_by_info.remove(&key_info_string)
});
Ok(())
}
async fn load_backup_keys(&self) -> Result<BackupKeys> {
Ok(BackupKeys::default())
}
}
#[cfg(test)]
mod tests {
use matrix_sdk_test::async_test;
use ruma::room_id;
use crate::{
identities::device::testing::get_device,
olm::{tests::get_account_and_session, InboundGroupSession, OlmMessageHash},
store::{memorystore::MemoryStore, Changes, CryptoStore},
};
#[async_test]
async fn test_session_store() {
let (account, session) = get_account_and_session().await;
let store = MemoryStore::new();
assert!(store.load_account().await.unwrap().is_none());
store.save_account(account).await.unwrap();
store.save_sessions(vec![session.clone()]).await;
let sessions = store.get_sessions(&session.sender_key.to_base64()).await.unwrap().unwrap();
let sessions = sessions.lock().await;
let loaded_session = &sessions[0];
assert_eq!(&session, loaded_session);
}
#[async_test]
async fn test_group_session_store() {
let (account, _) = get_account_and_session().await;
let room_id = room_id!("!test:localhost");
let (outbound, _) = account.create_group_session_pair_with_defaults(room_id).await;
let inbound = InboundGroupSession::new(
"test_key",
"test_key",
room_id,
outbound.session_key().await,
None,
);
let store = MemoryStore::new();
store.save_inbound_group_sessions(vec![inbound.clone()]).await;
let loaded_session = store
.get_inbound_group_session(room_id, "test_key", outbound.session_id())
.await
.unwrap()
.unwrap();
assert_eq!(inbound, loaded_session);
}
#[async_test]
async fn test_device_store() {
let device = get_device();
let store = MemoryStore::new();
store.save_devices(vec![device.clone()]).await;
let loaded_device =
store.get_device(device.user_id(), device.device_id()).await.unwrap().unwrap();
assert_eq!(device, loaded_device);
let user_devices = store.get_user_devices(device.user_id()).await.unwrap();
assert_eq!(&**user_devices.keys().next().unwrap(), device.device_id());
assert_eq!(user_devices.values().next().unwrap(), &device);
let loaded_device = user_devices.get(device.device_id()).unwrap();
assert_eq!(&device, loaded_device);
store.delete_devices(vec![device.clone()]).await;
assert!(store.get_device(device.user_id(), device.device_id()).await.unwrap().is_none());
}
#[async_test]
async fn test_tracked_users() {
let device = get_device();
let store = MemoryStore::new();
assert!(store.update_tracked_user(device.user_id(), false).await.unwrap());
assert!(!store.update_tracked_user(device.user_id(), false).await.unwrap());
assert!(store.is_user_tracked(device.user_id()));
}
#[async_test]
async fn test_message_hash() {
let store = MemoryStore::new();
let hash =
OlmMessageHash { sender_key: "test_sender".to_owned(), hash: "test_hash".to_owned() };
let mut changes = Changes::default();
changes.message_hashes.push(hash.clone());
assert!(!store.is_message_known(&hash).await.unwrap());
store.save_changes(changes).await.unwrap();
assert!(store.is_message_known(&hash).await.unwrap());
}
}