matrix_sdk_ffi/
session_verification.rs

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
use std::sync::{Arc, RwLock};

use futures_util::StreamExt;
use matrix_sdk::{
    encryption::{
        identities::UserIdentity,
        verification::{SasState, SasVerification, VerificationRequest, VerificationRequestState},
        Encryption,
    },
    ruma::events::{key::verification::VerificationMethod, AnyToDeviceEvent},
};
use ruma::UserId;
use tracing::{error, info};

use super::RUNTIME;
use crate::{error::ClientError, utils::Timestamp};

#[derive(uniffi::Object)]
pub struct SessionVerificationEmoji {
    symbol: String,
    description: String,
}

#[matrix_sdk_ffi_macros::export]
impl SessionVerificationEmoji {
    pub fn symbol(&self) -> String {
        self.symbol.clone()
    }

    pub fn description(&self) -> String {
        self.description.clone()
    }
}

#[derive(uniffi::Enum)]
pub enum SessionVerificationData {
    Emojis { emojis: Vec<Arc<SessionVerificationEmoji>>, indices: Vec<u8> },
    Decimals { values: Vec<u16> },
}

/// Details about the incoming verification request
#[derive(Debug, uniffi::Record)]
pub struct SessionVerificationRequestDetails {
    sender_id: String,
    flow_id: String,
    device_id: String,
    display_name: Option<String>,
    /// First time this device was seen in milliseconds since epoch.
    first_seen_timestamp: Timestamp,
}

#[matrix_sdk_ffi_macros::export(callback_interface)]
pub trait SessionVerificationControllerDelegate: Sync + Send {
    fn did_receive_verification_request(&self, details: SessionVerificationRequestDetails);
    fn did_accept_verification_request(&self);
    fn did_start_sas_verification(&self);
    fn did_receive_verification_data(&self, data: SessionVerificationData);
    fn did_fail(&self);
    fn did_cancel(&self);
    fn did_finish(&self);
}

pub type Delegate = Arc<RwLock<Option<Box<dyn SessionVerificationControllerDelegate>>>>;

#[derive(Clone, uniffi::Object)]
pub struct SessionVerificationController {
    encryption: Encryption,
    user_identity: UserIdentity,
    delegate: Delegate,
    verification_request: Arc<RwLock<Option<VerificationRequest>>>,
    sas_verification: Arc<RwLock<Option<SasVerification>>>,
}

#[matrix_sdk_ffi_macros::export]
impl SessionVerificationController {
    pub fn set_delegate(&self, delegate: Option<Box<dyn SessionVerificationControllerDelegate>>) {
        *self.delegate.write().unwrap() = delegate;
    }

    /// Set this particular request as the currently active one and register for
    /// events pertaining it.
    /// * `sender_id` - The user requesting verification.
    /// * `flow_id` - - The ID that uniquely identifies the verification flow.
    pub async fn acknowledge_verification_request(
        &self,
        sender_id: String,
        flow_id: String,
    ) -> Result<(), ClientError> {
        let sender_id = UserId::parse(sender_id.clone())?;

        let verification_request = self
            .encryption
            .get_verification_request(&sender_id, flow_id)
            .await
            .ok_or(ClientError::new("Unknown session verification request"))?;

        *self.verification_request.write().unwrap() = Some(verification_request.clone());

        RUNTIME.spawn(Self::listen_to_verification_request_changes(
            verification_request,
            self.sas_verification.clone(),
            self.delegate.clone(),
        ));

        Ok(())
    }

    /// Accept the previously acknowledged verification request
    pub async fn accept_verification_request(&self) -> Result<(), ClientError> {
        let verification_request = self.verification_request.read().unwrap().clone();

        if let Some(verification_request) = verification_request {
            let methods = vec![VerificationMethod::SasV1];
            verification_request.accept_with_methods(methods).await?;
        }

        Ok(())
    }

    /// Request verification for the current device
    pub async fn request_verification(&self) -> Result<(), ClientError> {
        let methods = vec![VerificationMethod::SasV1];
        let verification_request = self
            .user_identity
            .request_verification_with_methods(methods)
            .await
            .map_err(anyhow::Error::from)?;

        *self.verification_request.write().unwrap() = Some(verification_request.clone());

        RUNTIME.spawn(Self::listen_to_verification_request_changes(
            verification_request,
            self.sas_verification.clone(),
            self.delegate.clone(),
        ));

        Ok(())
    }

    /// Transition the current verification request into a SAS verification
    /// flow.
    pub async fn start_sas_verification(&self) -> Result<(), ClientError> {
        let verification_request = self.verification_request.read().unwrap().clone();

        let Some(verification_request) = verification_request else {
            return Err(ClientError::new("Verification request missing."));
        };

        match verification_request.start_sas().await {
            Ok(Some(verification)) => {
                *self.sas_verification.write().unwrap() = Some(verification.clone());

                if let Some(delegate) = &*self.delegate.read().unwrap() {
                    delegate.did_start_sas_verification()
                }

                let delegate = self.delegate.clone();
                RUNTIME.spawn(Self::listen_to_sas_verification_changes(verification, delegate));
            }
            _ => {
                if let Some(delegate) = &*self.delegate.read().unwrap() {
                    delegate.did_fail()
                }
            }
        }

        Ok(())
    }

    /// Confirm that the short auth strings match on both sides.
    pub async fn approve_verification(&self) -> Result<(), ClientError> {
        let sas_verification = self.sas_verification.read().unwrap().clone();

        let Some(sas_verification) = sas_verification else {
            return Err(ClientError::new("SAS verification missing"));
        };

        Ok(sas_verification.confirm().await?)
    }

    /// Reject the short auth string
    pub async fn decline_verification(&self) -> Result<(), ClientError> {
        let sas_verification = self.sas_verification.read().unwrap().clone();

        let Some(sas_verification) = sas_verification else {
            return Err(ClientError::new("SAS verification missing"));
        };

        Ok(sas_verification.mismatch().await?)
    }

    /// Cancel the current verification request
    pub async fn cancel_verification(&self) -> Result<(), ClientError> {
        let verification_request = self.verification_request.read().unwrap().clone();

        let Some(verification_request) = verification_request else {
            return Err(ClientError::new("Verification request missing."));
        };

        Ok(verification_request.cancel().await?)
    }
}

impl SessionVerificationController {
    pub(crate) fn new(encryption: Encryption, user_identity: UserIdentity) -> Self {
        SessionVerificationController {
            encryption,
            user_identity,
            delegate: Arc::new(RwLock::new(None)),
            verification_request: Arc::new(RwLock::new(None)),
            sas_verification: Arc::new(RwLock::new(None)),
        }
    }

    pub(crate) async fn process_to_device_message(&self, event: AnyToDeviceEvent) {
        if let AnyToDeviceEvent::KeyVerificationRequest(event) = event {
            info!("Received verification request: {:}", event.sender);

            let Some(request) = self
                .encryption
                .get_verification_request(&event.sender, &event.content.transaction_id)
                .await
            else {
                error!("Failed retrieving verification request");
                return;
            };

            if !request.is_self_verification() {
                info!("Received non-self verification request. Ignoring.");
                return;
            }

            let VerificationRequestState::Requested { other_device_data, .. } = request.state()
            else {
                error!("Received key verification event but the request is in the wrong state.");
                return;
            };

            if let Some(delegate) = &*self.delegate.read().unwrap() {
                delegate.did_receive_verification_request(SessionVerificationRequestDetails {
                    sender_id: request.other_user_id().into(),
                    flow_id: request.flow_id().into(),
                    device_id: other_device_data.device_id().into(),
                    display_name: other_device_data.display_name().map(str::to_string),
                    first_seen_timestamp: other_device_data.first_time_seen_ts().into(),
                });
            }
        }
    }

    async fn listen_to_verification_request_changes(
        verification_request: VerificationRequest,
        sas_verification: Arc<RwLock<Option<SasVerification>>>,
        delegate: Delegate,
    ) {
        let mut stream = verification_request.changes();

        while let Some(state) = stream.next().await {
            match state {
                VerificationRequestState::Transitioned { verification } => {
                    let Some(verification) = verification.sas() else {
                        error!("Invalid, non-sas verification flow. Returning.");
                        return;
                    };

                    *sas_verification.write().unwrap() = Some(verification.clone());

                    if verification.accept().await.is_ok() {
                        if let Some(delegate) = &*delegate.read().unwrap() {
                            delegate.did_start_sas_verification()
                        }

                        let delegate = delegate.clone();
                        RUNTIME.spawn(Self::listen_to_sas_verification_changes(
                            verification,
                            delegate,
                        ));
                    } else if let Some(delegate) = &*delegate.read().unwrap() {
                        delegate.did_fail()
                    }
                }
                VerificationRequestState::Ready { .. } => {
                    if let Some(delegate) = &*delegate.read().unwrap() {
                        delegate.did_accept_verification_request()
                    }
                }
                VerificationRequestState::Cancelled(..) => {
                    if let Some(delegate) = &*delegate.read().unwrap() {
                        delegate.did_cancel();
                    }
                }
                _ => {}
            }
        }
    }

    async fn listen_to_sas_verification_changes(sas: SasVerification, delegate: Delegate) {
        let mut stream = sas.changes();

        while let Some(state) = stream.next().await {
            match state {
                SasState::KeysExchanged { emojis, decimals } => {
                    if let Some(delegate) = &*delegate.read().unwrap() {
                        if let Some(emojis) = emojis {
                            delegate.did_receive_verification_data(
                                SessionVerificationData::Emojis {
                                    emojis: emojis
                                        .emojis
                                        .into_iter()
                                        .map(|emoji| {
                                            Arc::new(SessionVerificationEmoji {
                                                symbol: emoji.symbol.to_owned(),
                                                description: emoji.description.to_owned(),
                                            })
                                        })
                                        .collect(),
                                    indices: emojis.indices.to_vec(),
                                },
                            );
                        } else {
                            delegate.did_receive_verification_data(
                                SessionVerificationData::Decimals {
                                    values: vec![decimals.0, decimals.1, decimals.2],
                                },
                            )
                        }
                    }
                }
                SasState::Done { .. } => {
                    if let Some(delegate) = &*delegate.read().unwrap() {
                        delegate.did_finish()
                    }
                    break;
                }
                SasState::Cancelled(_cancel_info) => {
                    // TODO: The cancel_info is usable, we should tell the user why we were
                    // cancelled.
                    if let Some(delegate) = &*delegate.read().unwrap() {
                        delegate.did_cancel()
                    }
                    break;
                }
                SasState::Created { .. }
                | SasState::Started { .. }
                | SasState::Accepted { .. }
                | SasState::Confirmed => (),
            }
        }
    }
}