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
use std::{collections::BTreeMap, fmt, sync::Arc};
use matrix_sdk_common::locks::Mutex;
use ruma::{
events::{
room::encrypted::{
CiphertextInfo, EncryptedEventScheme, OlmV1Curve25519AesSha2Content,
ToDeviceRoomEncryptedEventContent,
},
AnyToDeviceEventContent, EventContent,
},
DeviceId, SecondsSinceUnixEpoch, UserId,
};
use serde::{Deserialize, Serialize};
use serde_json::json;
use vodozemac::{
olm::{DecryptionError, OlmMessage, Session as InnerSession, SessionPickle},
Curve25519PublicKey,
};
use super::IdentityKeys;
use crate::{
error::{EventError, OlmResult},
ReadOnlyDevice,
};
#[derive(Clone)]
pub struct Session {
pub user_id: Arc<UserId>,
pub device_id: Arc<DeviceId>,
pub our_identity_keys: Arc<IdentityKeys>,
pub inner: Arc<Mutex<InnerSession>>,
pub session_id: Arc<str>,
pub sender_key: Curve25519PublicKey,
pub created_using_fallback_key: bool,
pub creation_time: SecondsSinceUnixEpoch,
pub last_use_time: SecondsSinceUnixEpoch,
}
#[cfg(not(tarpaulin_include))]
impl fmt::Debug for Session {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Session")
.field("session_id", &self.session_id())
.field("sender_key", &self.sender_key)
.finish()
}
}
impl Session {
pub async fn decrypt(&mut self, message: &OlmMessage) -> Result<String, DecryptionError> {
let plaintext = self.inner.lock().await.decrypt(message)?;
self.last_use_time = SecondsSinceUnixEpoch::now();
Ok(plaintext)
}
pub fn sender_key(&self) -> Curve25519PublicKey {
self.sender_key
}
pub(crate) async fn encrypt_helper(&mut self, plaintext: &str) -> OlmMessage {
let message = self.inner.lock().await.encrypt(plaintext);
self.last_use_time = SecondsSinceUnixEpoch::now();
message
}
pub async fn encrypt(
&mut self,
recipient_device: &ReadOnlyDevice,
content: AnyToDeviceEventContent,
) -> OlmResult<ToDeviceRoomEncryptedEventContent> {
let recipient_signing_key =
recipient_device.ed25519_key().ok_or(EventError::MissingSigningKey)?;
let event_type = content.event_type();
let payload = json!({
"sender": self.user_id.as_str(),
"sender_device": self.device_id.as_ref(),
"keys": {
"ed25519": self.our_identity_keys.ed25519.to_base64(),
},
"recipient": recipient_device.user_id(),
"recipient_keys": {
"ed25519": recipient_signing_key.to_base64(),
},
"type": event_type,
"content": content,
});
let plaintext = serde_json::to_string(&payload)?;
let ciphertext = self.encrypt_helper(&plaintext).await.to_parts();
let message_type = ciphertext.0;
let ciphertext = CiphertextInfo::new(ciphertext.1, (message_type as u32).into());
let mut content = BTreeMap::new();
content.insert(self.sender_key.to_base64(), ciphertext);
Ok(EncryptedEventScheme::OlmV1Curve25519AesSha2(OlmV1Curve25519AesSha2Content::new(
content,
self.our_identity_keys.curve25519.to_base64(),
))
.into())
}
pub fn session_id(&self) -> &str {
&self.session_id
}
pub async fn pickle(&self) -> PickledSession {
let pickle = self.inner.lock().await.pickle();
PickledSession {
pickle,
sender_key: self.sender_key,
created_using_fallback_key: self.created_using_fallback_key,
creation_time: self.creation_time,
last_use_time: self.last_use_time,
}
}
pub fn from_pickle(
user_id: Arc<UserId>,
device_id: Arc<DeviceId>,
our_identity_keys: Arc<IdentityKeys>,
pickle: PickledSession,
) -> Self {
let session: vodozemac::olm::Session = pickle.pickle.into();
let session_id = session.session_id();
Session {
user_id,
device_id,
our_identity_keys,
inner: Arc::new(Mutex::new(session)),
session_id: session_id.into(),
created_using_fallback_key: pickle.created_using_fallback_key,
sender_key: pickle.sender_key,
creation_time: pickle.creation_time,
last_use_time: pickle.last_use_time,
}
}
}
impl PartialEq for Session {
fn eq(&self, other: &Self) -> bool {
self.session_id() == other.session_id()
}
}
#[derive(Serialize, Deserialize)]
#[allow(missing_debug_implementations)]
pub struct PickledSession {
pub pickle: SessionPickle,
pub sender_key: Curve25519PublicKey,
#[serde(default)]
pub created_using_fallback_key: bool,
pub creation_time: SecondsSinceUnixEpoch,
pub last_use_time: SecondsSinceUnixEpoch,
}