Skip to main content

matrix_sdk_crypto/verification/
requests.rs

1// Copyright 2020 The Matrix.org Foundation C.I.C.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use std::{ops::Add, sync::Arc, time::Duration};
16
17use as_variant::as_variant;
18use eyeball::{ObservableWriteGuard, SharedObservable, WeakObservable};
19use futures_core::Stream;
20use futures_util::StreamExt;
21#[cfg(feature = "qrcode")]
22use matrix_sdk_qrcode::QrVerificationData;
23use ruma::{
24    DeviceId, MilliSecondsSinceUnixEpoch, OwnedDeviceId, OwnedUserId, RoomId, TransactionId,
25    UserId,
26    events::{
27        AnyMessageLikeEventContent, AnyToDeviceEventContent,
28        key::verification::{
29            VerificationMethod,
30            cancel::CancelCode,
31            ready::{KeyVerificationReadyEventContent, ToDeviceKeyVerificationReadyEventContent},
32            request::ToDeviceKeyVerificationRequestEventContent,
33            start::StartMethod,
34        },
35        relation::Reference,
36        room::message::KeyVerificationRequestEventContent,
37    },
38    time::Instant,
39    to_device::DeviceIdOrAllDevices,
40};
41use tracing::{debug, info, instrument, trace, warn};
42
43#[cfg(feature = "qrcode")]
44use super::qrcode::{QrVerification, QrVerificationState, ScanError};
45use super::{
46    CancelInfo, Cancelled, FlowId, Verification, VerificationStore,
47    cache::VerificationCache,
48    event_enums::{
49        CancelContent, DoneContent, OutgoingContent, ReadyContent, RequestContent, StartContent,
50    },
51};
52use crate::{
53    CryptoStoreError, DeviceData, Sas,
54    olm::StaticAccountData,
55    types::requests::{OutgoingVerificationRequest, RoomMessageRequest, ToDeviceRequest},
56};
57
58const SUPPORTED_METHODS: &[VerificationMethod] = &[
59    VerificationMethod::SasV1,
60    #[cfg(feature = "qrcode")]
61    VerificationMethod::QrCodeShowV1,
62    VerificationMethod::ReciprocateV1,
63];
64
65const VERIFICATION_TIMEOUT: Duration = Duration::from_secs(60 * 10);
66
67/// An Enum describing the state the verification request is in.
68#[derive(Debug, Clone)]
69pub enum VerificationRequestState {
70    /// The verification request has been newly created by us.
71    Created {
72        /// The verification methods supported by us.
73        our_methods: Vec<VerificationMethod>,
74    },
75    /// The verification request was received from the other party.
76    Requested {
77        /// The verification methods supported by the sender.
78        their_methods: Vec<VerificationMethod>,
79
80        /// The device data of the device that responded to the verification
81        /// request.
82        other_device_data: DeviceData,
83    },
84    /// The verification request is ready to start a verification flow.
85    Ready {
86        /// The verification methods supported by the other side.
87        their_methods: Vec<VerificationMethod>,
88
89        /// The verification methods supported by the us.
90        our_methods: Vec<VerificationMethod>,
91
92        /// The device data of the device that responded to the verification
93        /// request.
94        other_device_data: DeviceData,
95    },
96    /// The verification request has transitioned into a concrete verification
97    /// flow. For example it transitioned into the emoji based SAS verification.
98    Transitioned {
99        /// The concrete [`Verification`] object the verification request
100        /// transitioned into.
101        verification: Verification,
102
103        /// The device data of the device that responded to the verification
104        /// request.
105        other_device_data: DeviceData,
106    },
107    /// The verification flow that was started with this request has finished.
108    Done,
109    /// The verification process has been cancelled.
110    Cancelled(CancelInfo),
111}
112
113impl From<&InnerRequest> for VerificationRequestState {
114    fn from(value: &InnerRequest) -> Self {
115        match value {
116            InnerRequest::Created(s) => {
117                Self::Created { our_methods: s.state.our_methods.to_owned() }
118            }
119            InnerRequest::Requested(s) => Self::Requested {
120                their_methods: s.state.their_methods.to_owned(),
121                other_device_data: s.state.other_device_data.to_owned(),
122            },
123            InnerRequest::Ready(s) => Self::Ready {
124                their_methods: s.state.their_methods.to_owned(),
125                our_methods: s.state.our_methods.to_owned(),
126                other_device_data: s.state.other_device_data.to_owned(),
127            },
128            InnerRequest::Transitioned(s) => Self::Transitioned {
129                verification: s.state.verification.to_owned(),
130                other_device_data: s.state.other_device_data.to_owned(),
131            },
132            InnerRequest::Passive(_) => {
133                Self::Cancelled(Cancelled::new(true, CancelCode::Accepted).into())
134            }
135            InnerRequest::Done(_) => Self::Done,
136            InnerRequest::Cancelled(s) => Self::Cancelled(s.state.to_owned().into()),
137        }
138    }
139}
140
141/// An object controlling key verification requests.
142///
143/// Interactive verification flows usually start with a verification request,
144/// this object lets you send and reply to such a verification request.
145///
146/// After the initial handshake the verification flow transitions into one of
147/// the verification methods.
148#[derive(Clone, Debug)]
149pub struct VerificationRequest {
150    verification_cache: VerificationCache,
151    account: StaticAccountData,
152    flow_id: Arc<FlowId>,
153    other_user_id: OwnedUserId,
154    inner: SharedObservable<InnerRequest>,
155    creation_time: Arc<Instant>,
156    we_started: bool,
157    recipient_devices: Arc<Vec<OwnedDeviceId>>,
158}
159
160/// A handle to a request so child verification flows can cancel the request.
161///
162/// A verification flow can branch off into different types of verification
163/// flows after the initial request handshake is done.
164///
165/// Cancelling a QR code verification should also cancel the request. This
166/// `RequestHandle` allows the QR code verification object to cancel the parent
167/// `VerificationRequest` object.
168#[derive(Debug, Clone)]
169pub(crate) struct RequestHandle {
170    inner: WeakObservable<InnerRequest>,
171}
172
173impl RequestHandle {
174    pub fn cancel_with_code(&self, cancel_code: &CancelCode) {
175        if let Some(observable) = self.inner.upgrade() {
176            let mut guard = observable.write();
177
178            if let Some(updated) = guard.cancel(true, cancel_code) {
179                ObservableWriteGuard::set(&mut guard, updated);
180            }
181        }
182    }
183}
184
185impl From<SharedObservable<InnerRequest>> for RequestHandle {
186    fn from(inner: SharedObservable<InnerRequest>) -> Self {
187        let inner = inner.downgrade();
188
189        Self { inner }
190    }
191}
192
193impl VerificationRequest {
194    pub(crate) fn new(
195        cache: VerificationCache,
196        store: VerificationStore,
197        flow_id: FlowId,
198        other_user: &UserId,
199        recipient_devices: Vec<OwnedDeviceId>,
200        methods: Option<Vec<VerificationMethod>>,
201    ) -> Self {
202        let account = store.account.clone();
203        let inner = SharedObservable::new(InnerRequest::Created(RequestState::new(
204            cache.clone(),
205            store,
206            other_user,
207            &flow_id,
208            methods,
209        )));
210
211        Self {
212            account,
213            verification_cache: cache,
214            flow_id: flow_id.into(),
215            inner,
216            other_user_id: other_user.into(),
217            creation_time: Instant::now().into(),
218            we_started: true,
219            recipient_devices: recipient_devices.into(),
220        }
221    }
222
223    /// Create an event content that can be sent as a to-device event to request
224    /// verification from the other side. This should be used only for
225    /// self-verifications and it should be sent to the specific device that we
226    /// want to verify.
227    pub(crate) fn request_to_device(&self) -> ToDeviceRequest {
228        let inner = self.inner.read();
229
230        let methods = if let InnerRequest::Created(c) = &*inner {
231            c.state.our_methods.clone()
232        } else {
233            SUPPORTED_METHODS.to_vec()
234        };
235
236        let content = ToDeviceKeyVerificationRequestEventContent::new(
237            self.account.device_id.clone(),
238            self.flow_id().as_str().into(),
239            methods,
240            MilliSecondsSinceUnixEpoch::now(),
241        );
242
243        ToDeviceRequest::for_recipients(
244            self.other_user(),
245            self.recipient_devices.to_vec(),
246            &AnyToDeviceEventContent::KeyVerificationRequest(content),
247            TransactionId::new(),
248        )
249    }
250
251    /// Create an event content that can be sent as a room event to request
252    /// verification from the other side. This should be used only for
253    /// verifications of other users and it should be sent to a room we consider
254    /// to be a DM with the other user.
255    pub fn request(
256        own_user_id: &UserId,
257        own_device_id: &DeviceId,
258        other_user_id: &UserId,
259        methods: Option<Vec<VerificationMethod>>,
260    ) -> KeyVerificationRequestEventContent {
261        KeyVerificationRequestEventContent::new(
262            format!(
263                "{own_user_id} is requesting to verify your key, but your client does not \
264                support in-chat key verification. You will need to use legacy \
265                key verification to verify keys."
266            ),
267            methods.unwrap_or_else(|| SUPPORTED_METHODS.to_vec()),
268            own_device_id.into(),
269            other_user_id.to_owned(),
270        )
271    }
272
273    /// Our own user id.
274    pub fn own_user_id(&self) -> &UserId {
275        &self.account.user_id
276    }
277
278    /// The id of the other user that is participating in this verification
279    /// request.
280    pub fn other_user(&self) -> &UserId {
281        &self.other_user_id
282    }
283
284    /// The id of the other device that is participating in this verification.
285    pub fn other_device_id(&self) -> Option<OwnedDeviceId> {
286        match &*self.inner.read() {
287            InnerRequest::Requested(r) => Some(r.state.other_device_data.device_id().to_owned()),
288            InnerRequest::Ready(r) => Some(r.state.other_device_data.device_id().to_owned()),
289            InnerRequest::Transitioned(r) => {
290                Some(r.state.ready.other_device_data.device_id().to_owned())
291            }
292            InnerRequest::Created(_)
293            | InnerRequest::Passive(_)
294            | InnerRequest::Done(_)
295            | InnerRequest::Cancelled(_) => None,
296        }
297    }
298
299    /// Get the room id if the verification is happening inside a room.
300    pub fn room_id(&self) -> Option<&RoomId> {
301        match self.flow_id.as_ref() {
302            FlowId::ToDevice(_) => None,
303            FlowId::InRoom(r, _) => Some(r),
304        }
305    }
306
307    /// Get info about the cancellation if the verification request has been
308    /// cancelled.
309    pub fn cancel_info(&self) -> Option<CancelInfo> {
310        as_variant!(&*self.inner.read(), InnerRequest::Cancelled(c) => {
311            c.state.clone().into()
312        })
313    }
314
315    /// Has the verification request been answered by another device.
316    pub fn is_passive(&self) -> bool {
317        matches!(*self.inner.read(), InnerRequest::Passive(_))
318    }
319
320    /// Is the verification request ready to start a verification flow.
321    pub fn is_ready(&self) -> bool {
322        matches!(*self.inner.read(), InnerRequest::Ready(_))
323    }
324
325    /// Has the verification flow timed out.
326    pub fn timed_out(&self) -> bool {
327        self.creation_time.elapsed() > VERIFICATION_TIMEOUT
328    }
329
330    /// Get the time left before the verification flow will time out, without
331    /// further action.
332    pub fn time_remaining(&self) -> Duration {
333        self.creation_time
334            .add(VERIFICATION_TIMEOUT)
335            .checked_duration_since(Instant::now())
336            .unwrap_or(Duration::from_secs(0))
337    }
338
339    /// Get the supported verification methods of the other side.
340    ///
341    /// Will be present only if the other side requested the verification or if
342    /// we're in the ready state.
343    pub fn their_supported_methods(&self) -> Option<Vec<VerificationMethod>> {
344        match &*self.inner.read() {
345            InnerRequest::Requested(r) => Some(r.state.their_methods.clone()),
346            InnerRequest::Ready(r) => Some(r.state.their_methods.clone()),
347            InnerRequest::Transitioned(r) => Some(r.state.ready.their_methods.clone()),
348            InnerRequest::Created(_)
349            | InnerRequest::Passive(_)
350            | InnerRequest::Done(_)
351            | InnerRequest::Cancelled(_) => None,
352        }
353    }
354
355    /// Get our own supported verification methods that we advertised.
356    ///
357    /// Will be present only we requested the verification or if we're in the
358    /// ready state.
359    pub fn our_supported_methods(&self) -> Option<Vec<VerificationMethod>> {
360        match &*self.inner.read() {
361            InnerRequest::Created(r) => Some(r.state.our_methods.clone()),
362            InnerRequest::Ready(r) => Some(r.state.our_methods.clone()),
363            InnerRequest::Transitioned(r) => Some(r.state.ready.our_methods.clone()),
364            InnerRequest::Requested(_)
365            | InnerRequest::Passive(_)
366            | InnerRequest::Done(_)
367            | InnerRequest::Cancelled(_) => None,
368        }
369    }
370
371    /// Get the unique ID of this verification request
372    pub fn flow_id(&self) -> &FlowId {
373        &self.flow_id
374    }
375
376    /// Is this a verification that is verifying one of our own devices
377    pub fn is_self_verification(&self) -> bool {
378        self.account.user_id == self.other_user()
379    }
380
381    /// Did we initiate the verification request
382    pub fn we_started(&self) -> bool {
383        self.we_started
384    }
385
386    /// Has the verification flow that was started with this request finished.
387    pub fn is_done(&self) -> bool {
388        matches!(*self.inner.read(), InnerRequest::Done(_))
389    }
390
391    /// Has the verification flow that was started with this request been
392    /// cancelled.
393    pub fn is_cancelled(&self) -> bool {
394        matches!(*self.inner.read(), InnerRequest::Cancelled(_))
395    }
396
397    /// Generate a QR code that can be used by another client to start a QR code
398    /// based verification.
399    #[cfg(feature = "qrcode")]
400    pub async fn generate_qr_code(&self) -> Result<Option<QrVerification>, CryptoStoreError> {
401        let inner = self.inner.get();
402
403        let ret = if let Some((state, verification)) =
404            inner.generate_qr_code(self.we_started, self.inner.clone().into()).await?
405        {
406            let mut inner = self.inner.write();
407            ObservableWriteGuard::set(&mut inner, InnerRequest::Transitioned(state));
408
409            Some(verification)
410        } else {
411            None
412        };
413
414        Ok(ret)
415    }
416
417    /// Start a QR code verification by providing a scanned QR code for this
418    /// verification flow.
419    ///
420    /// Returns a `ScanError` if the QR code isn't valid, `None` if the
421    /// verification request isn't in the ready state or we don't support QR
422    /// code verification, otherwise a newly created `QrVerification` object
423    /// which will be used for the remainder of the verification flow.
424    #[cfg(feature = "qrcode")]
425    pub async fn scan_qr_code(
426        &self,
427        data: QrVerificationData,
428    ) -> Result<Option<QrVerification>, ScanError> {
429        let inner = self.inner.read().to_owned();
430
431        let (new_state, qr_verification) = match inner {
432            InnerRequest::Ready(r) => {
433                scan_qr_code(data, &r, &r.state, self.we_started, self.inner.to_owned().into())
434                    .await?
435            }
436            InnerRequest::Transitioned(r) => {
437                scan_qr_code(
438                    data,
439                    &r,
440                    &r.state.ready,
441                    self.we_started,
442                    self.inner.to_owned().into(),
443                )
444                .await?
445            }
446            _ => return Ok(None),
447        };
448
449        // We may have previously started our own QR verification (e.g. two
450        // devices displaying QR code at the same time), so we need to replace
451        // it with the newly scanned code.
452        if self
453            .verification_cache
454            .get_qr(qr_verification.other_user_id(), qr_verification.flow_id().as_str())
455            .is_some()
456        {
457            self.verification_cache.replace_qr(qr_verification.clone());
458        } else {
459            self.verification_cache.insert_qr(qr_verification.clone());
460        }
461
462        let mut guard = self.inner.write();
463        ObservableWriteGuard::set(&mut guard, InnerRequest::Transitioned(new_state));
464
465        Ok(Some(qr_verification))
466    }
467
468    pub(crate) fn from_request(
469        cache: VerificationCache,
470        store: VerificationStore,
471        sender: &UserId,
472        flow_id: FlowId,
473        content: &RequestContent<'_>,
474        device_data: DeviceData,
475    ) -> Self {
476        let account = store.account.clone();
477
478        Self {
479            verification_cache: cache.clone(),
480            inner: SharedObservable::new(InnerRequest::Requested(
481                RequestState::from_request_event(
482                    cache,
483                    store,
484                    sender,
485                    &flow_id,
486                    content,
487                    device_data,
488                ),
489            )),
490            account,
491            other_user_id: sender.into(),
492            flow_id: flow_id.into(),
493            we_started: false,
494            creation_time: Instant::now().into(),
495            recipient_devices: vec![].into(),
496        }
497    }
498
499    /// Accept the verification request signaling that our client supports the
500    /// given verification methods.
501    ///
502    /// # Arguments
503    ///
504    /// - `methods` - The methods that we should advertise as supported by us.
505    pub fn accept_with_methods(
506        &self,
507        methods: Vec<VerificationMethod>,
508    ) -> Option<OutgoingVerificationRequest> {
509        let mut guard = self.inner.write();
510        let (updated, content) = guard.accept(methods)?;
511
512        ObservableWriteGuard::set(&mut guard, updated);
513
514        let request = match content {
515            OutgoingContent::ToDevice(content) => ToDeviceRequest::with_id(
516                self.other_user(),
517                guard.other_device_id(),
518                &content,
519                TransactionId::new(),
520            )
521            .into(),
522            OutgoingContent::Room(room_id, content) => {
523                RoomMessageRequest { room_id, txn_id: TransactionId::new(), content }.into()
524            }
525        };
526
527        Some(request)
528    }
529
530    /// Accept the verification request.
531    ///
532    /// This method will accept the request and signal that it supports the
533    /// `m.sas.v1`, the `m.qr_code.show.v1`, and `m.reciprocate.v1` method.
534    ///
535    /// `m.qr_code.show.v1` will only be signaled if the `qrcode` feature is
536    /// enabled. This feature is disabled by default. If it's enabled and QR
537    /// code scanning should be supported or QR code showing shouldn't be
538    /// supported the [`accept_with_methods()`] method should be used instead.
539    ///
540    /// [`accept_with_methods()`]: #method.accept_with_methods
541    pub fn accept(&self) -> Option<OutgoingVerificationRequest> {
542        self.accept_with_methods(SUPPORTED_METHODS.to_vec())
543    }
544
545    /// Cancel the verification request
546    pub fn cancel(&self) -> Option<OutgoingVerificationRequest> {
547        self.cancel_with_code(CancelCode::User)
548    }
549
550    fn cancel_with_code(&self, cancel_code: CancelCode) -> Option<OutgoingVerificationRequest> {
551        let mut guard = self.inner.write();
552
553        let send_to_everyone = self.we_started() && matches!(*guard, InnerRequest::Created(_));
554        let other_device = guard.other_device_id();
555
556        debug!(
557            other_user = self.other_user().as_str(),
558            flow_id = self.flow_id().as_str(),
559            "Cancelling verification request",
560        );
561
562        if let Some(updated) = guard.cancel(true, &cancel_code) {
563            ObservableWriteGuard::set(&mut guard, updated);
564        }
565
566        let content = as_variant!(&*guard, InnerRequest::Cancelled(c) => {
567            c.state.as_content(self.flow_id())
568        });
569
570        let request = content.map(|c| match c {
571            OutgoingContent::ToDevice(content) => {
572                if send_to_everyone {
573                    ToDeviceRequest::for_recipients(
574                        self.other_user(),
575                        self.recipient_devices.to_vec(),
576                        &content,
577                        TransactionId::new(),
578                    )
579                    .into()
580                } else {
581                    ToDeviceRequest::with_id(
582                        self.other_user(),
583                        other_device,
584                        &content,
585                        TransactionId::new(),
586                    )
587                    .into()
588                }
589            }
590            OutgoingContent::Room(room_id, content) => {
591                RoomMessageRequest { room_id, txn_id: TransactionId::new(), content }.into()
592            }
593        });
594
595        drop(guard);
596
597        if let Some(verification) =
598            self.verification_cache.get(self.other_user(), self.flow_id().as_str())
599        {
600            match verification {
601                Verification::SasV1(s) => s.cancel_with_code(cancel_code),
602                #[cfg(feature = "qrcode")]
603                Verification::QrV1(q) => q.cancel_with_code(cancel_code),
604            };
605        }
606
607        request
608    }
609
610    pub(crate) fn cancel_if_timed_out(&self) -> Option<OutgoingVerificationRequest> {
611        if self.is_cancelled() || self.is_done() {
612            None
613        } else if self.timed_out() {
614            let request = self.cancel_with_code(CancelCode::Timeout);
615
616            if self.is_passive() {
617                None
618            } else {
619                trace!(
620                    other_user = self.other_user().as_str(),
621                    flow_id = self.flow_id().as_str(),
622                    "Timing a verification request out"
623                );
624                request
625            }
626        } else {
627            None
628        }
629    }
630
631    /// Create a key verification cancellation for devices that received the
632    /// request but either shouldn't continue in the verification or didn't get
633    /// notified that the other side cancelled.
634    ///
635    /// The spec states the following[1]: When Bob accepts or declines the
636    /// verification on one of his devices (sending either an
637    /// m.key.verification.ready or m.key.verification.cancel event), Alice will
638    /// send an m.key.verification.cancel event to Bob’s other devices with a
639    /// code of m.accepted in the case where Bob accepted the verification, or
640    /// m.user in the case where Bob rejected the verification.
641    ///
642    /// Realistically sending the cancellation to Bob's other devices is only
643    /// possible if Bob accepted the verification since we don't know the device
644    /// id of Bob's device that rejected the verification.
645    ///
646    /// Thus, we're sending the cancellation to all devices that received the
647    /// request in the rejection case.
648    ///
649    /// [1]: https://spec.matrix.org/unstable/client-server-api/#key-verification-framework
650    pub(crate) fn cancel_for_other_devices(
651        &self,
652        code: CancelCode,
653        filter_device: Option<&DeviceId>,
654    ) -> Option<ToDeviceRequest> {
655        let cancelled = Cancelled::new(true, code);
656        let cancel_content = cancelled.as_content(self.flow_id());
657
658        let OutgoingContent::ToDevice(c) = cancel_content else { return None };
659        let recip_devices: Vec<OwnedDeviceId> = self
660            .recipient_devices
661            .iter()
662            .filter(|&d| filter_device.is_none_or(|device| **d != *device))
663            .cloned()
664            .collect();
665
666        if recip_devices.is_empty() && filter_device.is_some() {
667            // We don't need to notify anyone if no recipients were present but
668            // we did have a filter device, since this means that only a single
669            // device received the `m.key.verification.request` and that device
670            // accepted the request.
671            return None;
672        }
673
674        let recipient = self.other_user();
675        Some(ToDeviceRequest::for_recipients(recipient, recip_devices, &c, TransactionId::new()))
676    }
677
678    pub(crate) fn receive_ready(
679        &self,
680        sender: &UserId,
681        content: &ReadyContent<'_>,
682        from_device_data: DeviceData,
683    ) {
684        let mut guard = self.inner.write();
685
686        match &*guard {
687            InnerRequest::Created(s) => {
688                let new_value =
689                    InnerRequest::Ready(s.clone().into_ready(sender, content, from_device_data));
690                ObservableWriteGuard::set(&mut guard, new_value);
691
692                if let Some(request) =
693                    self.cancel_for_other_devices(CancelCode::Accepted, Some(content.from_device()))
694                {
695                    self.verification_cache.add_verification_request(request.into());
696                }
697            }
698            InnerRequest::Requested(s) => {
699                if sender == self.own_user_id() && content.from_device() != self.account.device_id {
700                    let new_value = InnerRequest::Passive(s.clone().into_passive(content));
701                    ObservableWriteGuard::set(&mut guard, new_value);
702                }
703            }
704            InnerRequest::Ready(_)
705            | InnerRequest::Transitioned(_)
706            | InnerRequest::Passive(_)
707            | InnerRequest::Done(_)
708            | InnerRequest::Cancelled(_) => {}
709        }
710    }
711
712    pub(crate) async fn receive_start(
713        &self,
714        sender: &UserId,
715        content: &StartContent<'_>,
716    ) -> Result<(), CryptoStoreError> {
717        let inner = self.inner.get();
718
719        match &inner {
720            InnerRequest::Created(_)
721            | InnerRequest::Requested(_)
722            | InnerRequest::Passive(_)
723            | InnerRequest::Done(_)
724            | InnerRequest::Cancelled(_) => {
725                warn!(
726                    ?sender,
727                    device_id = content.from_device().as_str(),
728                    "Received a key verification start event but we're not yet in the ready state"
729                );
730                Ok(())
731            }
732            InnerRequest::Ready(s) => {
733                let s = s.clone();
734
735                if let Some(new_state) = s
736                    .receive_start(sender, content, self.we_started, self.inner.clone().into())
737                    .await?
738                {
739                    let mut inner = self.inner.write();
740                    ObservableWriteGuard::set(&mut inner, InnerRequest::Transitioned(new_state));
741                }
742
743                Ok(())
744            }
745            InnerRequest::Transitioned(s) => {
746                // This is the same as the `Ready` state. We need to support
747                // this in the case someone tries QR code verification and
748                // notices that they can't scan the QR code for one reason or
749                // the other, in that case they are able to transition into the
750                // emoji based SAS verification.
751                //
752                // In this case we're going to from one `Transitioned` state
753                // into another.
754                let s = s.clone();
755
756                if let Some(new_state) = s
757                    .receive_start(sender, content, self.we_started, self.inner.clone().into())
758                    .await?
759                {
760                    let mut inner = self.inner.write();
761                    ObservableWriteGuard::set(&mut inner, InnerRequest::Transitioned(new_state));
762                }
763
764                Ok(())
765            }
766        }
767    }
768
769    pub(crate) fn receive_done(&self, sender: &UserId, content: &DoneContent<'_>) {
770        if sender == self.other_user() {
771            trace!(
772                other_user = ?self.other_user(),
773                flow_id = self.flow_id().as_str(),
774                "Marking a verification request as done"
775            );
776
777            let mut guard = self.inner.write();
778            if let Some(updated) = guard.receive_done(content) {
779                ObservableWriteGuard::set(&mut guard, updated);
780            }
781        }
782    }
783
784    pub(crate) fn receive_cancel(&self, sender: &UserId, content: &CancelContent<'_>) {
785        if sender != self.other_user() {
786            return;
787        }
788
789        trace!(
790            ?sender,
791            code = content.cancel_code().as_str(),
792            "Cancelling a verification request, other user has cancelled"
793        );
794        let mut guard = self.inner.write();
795        if let Some(updated) = guard.cancel(false, content.cancel_code()) {
796            ObservableWriteGuard::set(&mut guard, updated);
797        }
798
799        if self.we_started()
800            && let Some(request) =
801                self.cancel_for_other_devices(content.cancel_code().to_owned(), None)
802        {
803            self.verification_cache.add_verification_request(request.into());
804        }
805    }
806
807    fn start_sas_helper(
808        &self,
809        new_state: RequestState<Transitioned>,
810        sas: Sas,
811        content: OutgoingContent,
812        other_device_id: DeviceIdOrAllDevices,
813    ) -> Option<(Sas, OutgoingVerificationRequest)> {
814        // We may have previously started QR verification and generated a QR
815        // code. If we now switch to SAS flow, the previous verification has to
816        // be replaced
817        cfg_select! {
818            feature = "qrcode" => {
819                if self
820                    .verification_cache
821                    .get_qr(sas.other_user_id(), sas.flow_id().as_str())
822                    .is_some()
823                {
824                    debug!(
825                        user_id = ?self.other_user(),
826                        flow_id = self.flow_id().as_str(),
827                        "We have an ongoing QR verification, replacing with SAS"
828                    );
829                    self.verification_cache.replace(sas.clone().into())
830                } else {
831                    self.verification_cache.insert_sas(sas.clone());
832                }
833            }
834            _ => {
835                self.verification_cache.insert_sas(sas.clone());
836            }
837        }
838
839        let request = match content {
840            OutgoingContent::ToDevice(content) => ToDeviceRequest::with_id(
841                self.other_user(),
842                other_device_id,
843                &content,
844                TransactionId::new(),
845            )
846            .into(),
847            OutgoingContent::Room(room_id, content) => {
848                RoomMessageRequest { room_id, txn_id: TransactionId::new(), content }.into()
849            }
850        };
851
852        let mut guard = self.inner.write();
853        ObservableWriteGuard::set(&mut guard, InnerRequest::Transitioned(new_state));
854
855        Some((sas, request))
856    }
857
858    /// Transition from this verification request into a SAS verification flow.
859    #[instrument(skip(self), fields(flow_id=self.flow_id.as_str()))]
860    pub async fn start_sas(
861        &self,
862    ) -> Result<Option<(Sas, OutgoingVerificationRequest)>, CryptoStoreError> {
863        debug!(
864            user_id = ?self.other_user_id,
865            flow_id = self.flow_id.as_str(),
866            "Choosing SAS verification for active VerificationRequest"
867        );
868        let inner = self.inner.get();
869        let other_device_id = inner.other_device_id();
870
871        Ok(match &inner {
872            InnerRequest::Ready(s) => {
873                if let Some((new_state, sas, content)) =
874                    s.start_sas(self.we_started, self.inner.clone().into()).await?
875                {
876                    self.start_sas_helper(new_state, sas, content, other_device_id)
877                } else {
878                    None
879                }
880            }
881            InnerRequest::Transitioned(s) => {
882                if let Some((new_state, sas, content)) =
883                    s.start_sas(self.we_started, self.inner.clone().into()).await?
884                {
885                    self.start_sas_helper(new_state, sas, content, other_device_id)
886                } else {
887                    None
888                }
889            }
890            _ => None,
891        })
892    }
893
894    /// Listen for changes in the verification request.
895    ///
896    /// The changes are presented as a stream of [`VerificationRequestState`]
897    /// values.
898    pub fn changes(&self) -> impl Stream<Item = VerificationRequestState> + use<> {
899        self.inner.subscribe().map(|s| (&s).into())
900    }
901
902    /// Get the current state the verification request is in.
903    ///
904    /// To listen to changes to the [`VerificationRequestState`] use the
905    /// [`VerificationRequest::changes`] method.
906    pub fn state(&self) -> VerificationRequestState {
907        (&*self.inner.read()).into()
908    }
909}
910
911#[derive(Clone, Debug)]
912enum InnerRequest {
913    Created(RequestState<Created>),
914    Requested(RequestState<Requested>),
915    Ready(RequestState<Ready>),
916    Transitioned(RequestState<Transitioned>),
917    Passive(RequestState<Passive>),
918    #[allow(dead_code)] // The `RequestState` field within `Done` is not currently used.
919    Done(RequestState<Done>),
920    Cancelled(RequestState<Cancelled>),
921}
922
923impl InnerRequest {
924    fn other_device_id(&self) -> DeviceIdOrAllDevices {
925        match self {
926            InnerRequest::Created(_) => DeviceIdOrAllDevices::AllDevices,
927            InnerRequest::Requested(r) => {
928                DeviceIdOrAllDevices::DeviceId(r.state.other_device_data.device_id().to_owned())
929            }
930            InnerRequest::Ready(r) => {
931                DeviceIdOrAllDevices::DeviceId(r.state.other_device_data.device_id().to_owned())
932            }
933            InnerRequest::Transitioned(r) => DeviceIdOrAllDevices::DeviceId(
934                r.state.ready.other_device_data.device_id().to_owned(),
935            ),
936            InnerRequest::Passive(_) => DeviceIdOrAllDevices::AllDevices,
937            InnerRequest::Done(_) => DeviceIdOrAllDevices::AllDevices,
938            InnerRequest::Cancelled(_) => DeviceIdOrAllDevices::AllDevices,
939        }
940    }
941
942    fn accept(&self, methods: Vec<VerificationMethod>) -> Option<(InnerRequest, OutgoingContent)> {
943        let InnerRequest::Requested(s) = self else { return None };
944        let (state, content) = s.clone().accept(methods);
945
946        Some((InnerRequest::Ready(state), content))
947    }
948
949    fn receive_done(&self, content: &DoneContent<'_>) -> Option<InnerRequest> {
950        let state = InnerRequest::Done(match self {
951            InnerRequest::Transitioned(s) => s.clone().into_done(content),
952            InnerRequest::Passive(s) => s.clone().into_done(content),
953            InnerRequest::Done(_)
954            | InnerRequest::Ready(_)
955            | InnerRequest::Created(_)
956            | InnerRequest::Requested(_)
957            | InnerRequest::Cancelled(_) => return None,
958        });
959
960        Some(state)
961    }
962
963    fn cancel(&self, cancelled_by_us: bool, cancel_code: &CancelCode) -> Option<InnerRequest> {
964        let print_info = || {
965            trace!(
966                cancelled_by_us,
967                code = cancel_code.as_str(),
968                "Verification request going into the cancelled state"
969            );
970        };
971
972        let state = InnerRequest::Cancelled(match self {
973            InnerRequest::Created(s) => {
974                print_info();
975                s.clone().into_canceled(cancelled_by_us, cancel_code)
976            }
977            InnerRequest::Requested(s) => {
978                print_info();
979                s.clone().into_canceled(cancelled_by_us, cancel_code)
980            }
981            InnerRequest::Ready(s) => {
982                print_info();
983                s.clone().into_canceled(cancelled_by_us, cancel_code)
984            }
985            InnerRequest::Transitioned(s) => {
986                print_info();
987                s.clone().into_canceled(cancelled_by_us, cancel_code)
988            }
989            InnerRequest::Passive(_) | InnerRequest::Done(_) | InnerRequest::Cancelled(_) => {
990                return None;
991            }
992        });
993
994        Some(state)
995    }
996
997    #[cfg(feature = "qrcode")]
998    async fn generate_qr_code(
999        &self,
1000        we_started: bool,
1001        request_handle: RequestHandle,
1002    ) -> Result<Option<(RequestState<Transitioned>, QrVerification)>, CryptoStoreError> {
1003        match self {
1004            InnerRequest::Created(_)
1005            | InnerRequest::Requested(_)
1006            | InnerRequest::Passive(_)
1007            | InnerRequest::Done(_)
1008            | InnerRequest::Cancelled(_) => Ok(None),
1009            InnerRequest::Ready(s) => s.generate_qr_code(we_started, request_handle).await,
1010            InnerRequest::Transitioned(s) => s.generate_qr_code(we_started, request_handle).await,
1011        }
1012    }
1013}
1014
1015#[derive(Clone, Debug)]
1016struct RequestState<S: Clone> {
1017    verification_cache: VerificationCache,
1018    store: VerificationStore,
1019    flow_id: Arc<FlowId>,
1020
1021    /// The id of the user which is participating in this verification request.
1022    pub other_user_id: OwnedUserId,
1023
1024    /// The verification request state we are in.
1025    state: S,
1026}
1027
1028impl<S: Clone> RequestState<S> {
1029    fn into_done(self, _: &DoneContent<'_>) -> RequestState<Done> {
1030        RequestState::<Done> {
1031            verification_cache: self.verification_cache,
1032            store: self.store,
1033            flow_id: self.flow_id,
1034            other_user_id: self.other_user_id,
1035            state: Done {},
1036        }
1037    }
1038
1039    fn into_canceled(
1040        self,
1041        cancelled_by_us: bool,
1042        cancel_code: &CancelCode,
1043    ) -> RequestState<Cancelled> {
1044        RequestState::<Cancelled> {
1045            verification_cache: self.verification_cache,
1046            store: self.store,
1047            flow_id: self.flow_id,
1048            other_user_id: self.other_user_id,
1049            state: Cancelled::new(cancelled_by_us, cancel_code.clone()),
1050        }
1051    }
1052}
1053
1054impl RequestState<Created> {
1055    fn new(
1056        cache: VerificationCache,
1057        store: VerificationStore,
1058        other_user_id: &UserId,
1059        flow_id: &FlowId,
1060        methods: Option<Vec<VerificationMethod>>,
1061    ) -> Self {
1062        let our_methods = methods.unwrap_or_else(|| SUPPORTED_METHODS.to_vec());
1063
1064        Self {
1065            other_user_id: other_user_id.to_owned(),
1066            state: Created { our_methods },
1067            verification_cache: cache,
1068            store,
1069            flow_id: flow_id.to_owned().into(),
1070        }
1071    }
1072
1073    fn into_ready(
1074        self,
1075        _sender: &UserId,
1076        content: &ReadyContent<'_>,
1077        from_device_data: DeviceData,
1078    ) -> RequestState<Ready> {
1079        // TODO check the flow id, and that the methods match what we suggested.
1080        RequestState {
1081            flow_id: self.flow_id,
1082            verification_cache: self.verification_cache,
1083            store: self.store,
1084            other_user_id: self.other_user_id,
1085            state: Ready {
1086                their_methods: content.methods().to_owned(),
1087                our_methods: self.state.our_methods,
1088                other_device_data: from_device_data,
1089            },
1090        }
1091    }
1092}
1093
1094#[derive(Clone, Debug)]
1095struct Created {
1096    /// The verification methods supported by us.
1097    pub our_methods: Vec<VerificationMethod>,
1098}
1099
1100#[derive(Clone, Debug)]
1101struct Requested {
1102    /// The verification methods supported by the sender.
1103    pub their_methods: Vec<VerificationMethod>,
1104
1105    /// The device data of the device that responded to the verification
1106    /// request.
1107    pub other_device_data: DeviceData,
1108}
1109
1110impl RequestState<Requested> {
1111    fn from_request_event(
1112        cache: VerificationCache,
1113        store: VerificationStore,
1114        sender: &UserId,
1115        flow_id: &FlowId,
1116        content: &RequestContent<'_>,
1117        device_data: DeviceData,
1118    ) -> RequestState<Requested> {
1119        // TODO only create this if we support the methods
1120        RequestState {
1121            store,
1122            verification_cache: cache,
1123            flow_id: flow_id.to_owned().into(),
1124            other_user_id: sender.to_owned(),
1125            state: Requested {
1126                their_methods: content.methods().to_owned(),
1127                other_device_data: device_data,
1128            },
1129        }
1130    }
1131
1132    fn into_passive(self, content: &ReadyContent<'_>) -> RequestState<Passive> {
1133        RequestState {
1134            flow_id: self.flow_id,
1135            verification_cache: self.verification_cache,
1136            store: self.store,
1137            other_user_id: self.other_user_id,
1138            state: Passive { other_device_id: content.from_device().to_owned() },
1139        }
1140    }
1141
1142    fn accept(self, methods: Vec<VerificationMethod>) -> (RequestState<Ready>, OutgoingContent) {
1143        let state = RequestState {
1144            store: self.store,
1145            verification_cache: self.verification_cache,
1146            flow_id: self.flow_id.clone(),
1147            other_user_id: self.other_user_id,
1148            state: Ready {
1149                their_methods: self.state.their_methods,
1150                our_methods: methods.clone(),
1151                other_device_data: self.state.other_device_data,
1152            },
1153        };
1154
1155        let content = match self.flow_id.as_ref() {
1156            FlowId::ToDevice(i) => AnyToDeviceEventContent::KeyVerificationReady(
1157                ToDeviceKeyVerificationReadyEventContent::new(
1158                    state.store.account.device_id.clone(),
1159                    methods,
1160                    i.to_owned(),
1161                ),
1162            )
1163            .into(),
1164            FlowId::InRoom(r, e) => (
1165                r.to_owned(),
1166                AnyMessageLikeEventContent::KeyVerificationReady(
1167                    KeyVerificationReadyEventContent::new(
1168                        state.store.account.device_id.clone(),
1169                        methods,
1170                        Reference::new(e.to_owned()),
1171                    ),
1172                ),
1173            )
1174                .into(),
1175        };
1176
1177        (state, content)
1178    }
1179}
1180
1181#[derive(Clone, Debug)]
1182struct Ready {
1183    /// The verification methods supported by the other side.
1184    pub their_methods: Vec<VerificationMethod>,
1185
1186    /// The verification methods supported by the us.
1187    pub our_methods: Vec<VerificationMethod>,
1188
1189    /// The device data of the device that responded to the verification
1190    /// request.
1191    pub other_device_data: DeviceData,
1192}
1193
1194#[cfg(feature = "qrcode")]
1195async fn scan_qr_code<T: Clone>(
1196    data: QrVerificationData,
1197    request_state: &RequestState<T>,
1198    state: &Ready,
1199    we_started: bool,
1200    request_handle: RequestHandle,
1201) -> Result<(RequestState<Transitioned>, QrVerification), ScanError> {
1202    let verification = QrVerification::from_scan(
1203        request_state.store.to_owned(),
1204        request_state.other_user_id.to_owned(),
1205        state.other_device_data.device_id().to_owned(),
1206        request_state.flow_id.as_ref().to_owned(),
1207        data,
1208        we_started,
1209        Some(request_handle),
1210    )
1211    .await?;
1212
1213    let new_state = RequestState {
1214        verification_cache: request_state.verification_cache.to_owned(),
1215        store: request_state.store.to_owned(),
1216        flow_id: request_state.flow_id.to_owned(),
1217        other_user_id: request_state.other_user_id.to_owned(),
1218        state: Transitioned {
1219            ready: state.to_owned(),
1220            verification: verification.to_owned().into(),
1221            other_device_data: state.other_device_data.to_owned(),
1222        },
1223    };
1224
1225    Ok((new_state, verification))
1226}
1227
1228#[cfg(feature = "qrcode")]
1229async fn generate_qr_code<T: Clone>(
1230    request_state: &RequestState<T>,
1231    state: &Ready,
1232    we_started: bool,
1233    request_handle: RequestHandle,
1234) -> Result<Option<(RequestState<Transitioned>, QrVerification)>, CryptoStoreError> {
1235    use crate::UserIdentityData;
1236
1237    // If we didn't state that we support showing QR codes or if the other side
1238    // doesn't support scanning QR codes bail early.
1239    if !state.our_methods.contains(&VerificationMethod::QrCodeShowV1)
1240        || !state.their_methods.contains(&VerificationMethod::QrCodeScanV1)
1241    {
1242        return Ok(None);
1243    }
1244
1245    let identities = request_state.store.get_identities(state.other_device_data.clone()).await?;
1246
1247    let verification = if let Some(identity) = &identities.identity_being_verified {
1248        match &identity {
1249            UserIdentityData::Own(i) => {
1250                if let Some(master_key) = i.master_key().get_first_key() {
1251                    if identities.can_sign_devices().await {
1252                        if let Some(device_key) = identities.other_device().ed25519_key() {
1253                            Some(QrVerification::new_self(
1254                                request_state.flow_id.as_ref().to_owned(),
1255                                master_key.to_owned(),
1256                                device_key.to_owned(),
1257                                identities,
1258                                we_started,
1259                                Some(request_handle),
1260                            ))
1261                        } else {
1262                            warn!(
1263                                user_id = ?request_state.other_user_id,
1264                                device_id = ?state.other_device_data.device_id(),
1265                                "Can't create a QR code, the other device \
1266                                 doesn't have a valid device key"
1267                            );
1268                            None
1269                        }
1270                    } else {
1271                        Some(QrVerification::new_self_no_master(
1272                            request_state.store.clone(),
1273                            request_state.flow_id.as_ref().to_owned(),
1274                            master_key.to_owned(),
1275                            identities,
1276                            we_started,
1277                            Some(request_handle),
1278                        ))
1279                    }
1280                } else {
1281                    warn!(
1282                        user_id = ?request_state.other_user_id,
1283                        device_id = ?state.other_device_data.device_id(),
1284                        "Can't create a QR code, our cross signing identity \
1285                         doesn't contain a valid master key"
1286                    );
1287                    None
1288                }
1289            }
1290            UserIdentityData::Other(i) => {
1291                if let Some(other_master) = i.master_key().get_first_key() {
1292                    // TODO we can get the master key from the public identity
1293                    // if we don't have the private one and we trust the public
1294                    // one.
1295                    if let Some(own_master) = identities
1296                        .private_identity
1297                        .master_public_key()
1298                        .await
1299                        .and_then(|m| m.get_first_key().map(|m| m.to_owned()))
1300                    {
1301                        Some(QrVerification::new_cross(
1302                            request_state.flow_id.as_ref().to_owned(),
1303                            own_master,
1304                            other_master.to_owned(),
1305                            identities,
1306                            we_started,
1307                            Some(request_handle),
1308                        ))
1309                    } else {
1310                        warn!(
1311                            user_id = ?request_state.other_user_id,
1312                            device_id = ?state.other_device_data.device_id(),
1313                            "Can't create a QR code, we don't trust our own \
1314                             master key"
1315                        );
1316                        None
1317                    }
1318                } else {
1319                    warn!(
1320                        user_id = ?request_state.other_user_id,
1321                        device_id = ?state.other_device_data.device_id(),
1322                        "Can't create a QR code, the user's identity \
1323                         doesn't have a valid master key"
1324                    );
1325                    None
1326                }
1327            }
1328        }
1329    } else {
1330        warn!(
1331            user_id = ?request_state.other_user_id,
1332            device_id = ?state.other_device_data.device_id(),
1333            "Can't create a QR code, the user doesn't have a valid cross \
1334             signing identity."
1335        );
1336
1337        None
1338    };
1339
1340    if let Some(verification) = verification {
1341        let new_state = RequestState {
1342            verification_cache: request_state.verification_cache.to_owned(),
1343            store: request_state.store.to_owned(),
1344            flow_id: request_state.flow_id.to_owned(),
1345            other_user_id: request_state.other_user_id.to_owned(),
1346            state: Transitioned {
1347                ready: state.to_owned(),
1348                verification: verification.to_owned().into(),
1349                other_device_data: state.other_device_data.to_owned(),
1350            },
1351        };
1352
1353        request_state.verification_cache.insert_qr(verification.to_owned());
1354
1355        Ok(Some((new_state, verification)))
1356    } else {
1357        Ok(None)
1358    }
1359}
1360
1361async fn receive_start<T: Clone>(
1362    sender: &UserId,
1363    content: &StartContent<'_>,
1364    we_started: bool,
1365    request_handle: RequestHandle,
1366    request_state: &RequestState<T>,
1367    state: &Ready,
1368) -> Result<Option<RequestState<Transitioned>>, CryptoStoreError> {
1369    info!(
1370        ?sender,
1371        device = ?content.from_device(),
1372        method = ?content.method(),
1373        "Received a new verification start event",
1374    );
1375
1376    let other_device_data = state.other_device_data.clone();
1377    let identities = request_state.store.get_identities(other_device_data.clone()).await?;
1378    let own_user_id = &request_state.store.account.user_id;
1379    let own_device_id = &request_state.store.account.device_id;
1380
1381    match content.method() {
1382        StartMethod::SasV1(_) => {
1383            match Sas::from_start_event(
1384                (*request_state.flow_id).to_owned(),
1385                content,
1386                identities,
1387                Some(request_handle),
1388                we_started,
1389            ) {
1390                Ok(new) => {
1391                    let old_verification = request_state
1392                        .verification_cache
1393                        .get(sender, request_state.flow_id.as_str());
1394                    match old_verification {
1395                        Some(Verification::SasV1(_old)) => {
1396                            // If there is already a SAS verification, i.e. we
1397                            // already started one before the other side tried
1398                            // to do the same; ignore it if we did and we're the
1399                            // lexicographically smaller user ID (or device ID
1400                            // if equal).
1401                            use std::cmp::Ordering;
1402                            if !matches!(
1403                                (
1404                                    sender.cmp(own_user_id),
1405                                    other_device_data.device_id().cmp(own_device_id)
1406                                ),
1407                                (Ordering::Greater, _) | (Ordering::Equal, Ordering::Greater)
1408                            ) {
1409                                info!(
1410                                    "Started a new SAS verification, replacing an already started one."
1411                                );
1412                                request_state.verification_cache.replace_sas(new.to_owned());
1413                                Ok(Some(state.to_transitioned(request_state, new.into())))
1414                            } else {
1415                                info!(
1416                                    "Ignored incoming SAS verification from lexicographically larger user/device ID."
1417                                );
1418                                Ok(None)
1419                            }
1420                        }
1421                        #[cfg(feature = "qrcode")]
1422                        Some(Verification::QrV1(old)) => {
1423                            // If there is already a QR verification, our
1424                            // ability to transition to SAS depends on how far
1425                            // we got through the QR flow.
1426                            if let QrVerificationState::Started = old.state() {
1427                                // it is legit to transition from QR display to
1428                                // SAS
1429                                info!("Transitioned from QR display to SAS");
1430                                request_state.verification_cache.replace_sas(new.to_owned());
1431                                Ok(Some(state.to_transitioned(request_state, new.into())))
1432                            } else {
1433                                // otherwise, we've either scanned their QR
1434                                // code, or they have scanned ours -- i.e., an
1435                                // `m.key.verification.start` with method
1436                                // `m.reciprocate.v1` has already been
1437                                // sent/received and, per the spec, it is too
1438                                // late to switch to SAS.
1439                                warn!(qr_state = ?old.state(), "Invalid transition from QR to SAS");
1440                                request_state.verification_cache.insert_sas(new.to_owned());
1441                                Ok(Some(state.to_transitioned(request_state, new.into())))
1442                            }
1443                        }
1444                        None => {
1445                            info!("Started a new SAS verification.");
1446                            request_state.verification_cache.insert_sas(new.to_owned());
1447                            Ok(Some(state.to_transitioned(request_state, new.into())))
1448                        }
1449                    }
1450                }
1451                Err(c) => {
1452                    warn!(
1453                        user_id = ?other_device_data.user_id(),
1454                        device_id = ?other_device_data.device_id(),
1455                        content = ?c,
1456                        "Can't start key verification, canceling.",
1457                    );
1458                    request_state.verification_cache.queue_up_content(
1459                        other_device_data.user_id(),
1460                        other_device_data.device_id(),
1461                        c,
1462                        None,
1463                    );
1464
1465                    Ok(None)
1466                }
1467            }
1468        }
1469        #[cfg(feature = "qrcode")]
1470        StartMethod::ReciprocateV1(_) => {
1471            if let Some(qr_verification) =
1472                request_state.verification_cache.get_qr(sender, content.flow_id())
1473            {
1474                if let Some(request) = qr_verification.receive_reciprocation(content) {
1475                    request_state.verification_cache.add_request(request.into())
1476                }
1477                debug!(
1478                    sender = ?identities.device_being_verified.user_id(),
1479                    device_id = ?identities.device_being_verified.device_id(),
1480                    verification = ?qr_verification,
1481                    "Received a QR code reciprocation"
1482                );
1483
1484                Ok(None)
1485            } else {
1486                warn!("Received a QR code reciprocation for an unknown flow");
1487                Ok(None)
1488            }
1489        }
1490        m => {
1491            warn!(method = ?m, "Received a key verification start event with an unsupported method");
1492            Ok(None)
1493        }
1494    }
1495}
1496
1497async fn start_sas<T: Clone>(
1498    request_state: &RequestState<T>,
1499    state: &Ready,
1500    we_started: bool,
1501    request_handle: RequestHandle,
1502) -> Result<Option<(RequestState<Transitioned>, Sas, OutgoingContent)>, CryptoStoreError> {
1503    if !state.their_methods.contains(&VerificationMethod::SasV1) {
1504        return Ok(None);
1505    }
1506
1507    let identities = request_state.store.get_identities(state.other_device_data.clone()).await?;
1508
1509    let (state, sas, content) = match request_state.flow_id.as_ref() {
1510        FlowId::ToDevice(t) => {
1511            let (sas, content) =
1512                Sas::start(identities, t.to_owned(), we_started, Some(request_handle), None);
1513
1514            let state = Transitioned {
1515                ready: state.to_owned(),
1516                verification: sas.to_owned().into(),
1517                other_device_data: state.other_device_data.to_owned(),
1518            };
1519
1520            (state, sas, content)
1521        }
1522        FlowId::InRoom(r, e) => {
1523            let (sas, content) = Sas::start_in_room(
1524                e.to_owned(),
1525                r.to_owned(),
1526                identities,
1527                we_started,
1528                request_handle,
1529            );
1530            let state = Transitioned {
1531                ready: state.to_owned(),
1532                verification: sas.to_owned().into(),
1533                other_device_data: state.other_device_data.to_owned(),
1534            };
1535            (state, sas, content)
1536        }
1537    };
1538
1539    let state = RequestState {
1540        verification_cache: request_state.verification_cache.to_owned(),
1541        store: request_state.store.to_owned(),
1542        flow_id: request_state.flow_id.to_owned(),
1543        other_user_id: request_state.other_user_id.to_owned(),
1544        state,
1545    };
1546
1547    Ok(Some((state, sas, content)))
1548}
1549
1550impl RequestState<Ready> {
1551    #[cfg(feature = "qrcode")]
1552    async fn generate_qr_code(
1553        &self,
1554        we_started: bool,
1555        request_handle: RequestHandle,
1556    ) -> Result<Option<(RequestState<Transitioned>, QrVerification)>, CryptoStoreError> {
1557        generate_qr_code(self, &self.state, we_started, request_handle).await
1558    }
1559
1560    async fn receive_start(
1561        &self,
1562        sender: &UserId,
1563        content: &StartContent<'_>,
1564        we_started: bool,
1565        request_handle: RequestHandle,
1566    ) -> Result<Option<RequestState<Transitioned>>, CryptoStoreError> {
1567        receive_start(sender, content, we_started, request_handle, self, &self.state).await
1568    }
1569
1570    async fn start_sas(
1571        &self,
1572        we_started: bool,
1573        request_handle: RequestHandle,
1574    ) -> Result<Option<(RequestState<Transitioned>, Sas, OutgoingContent)>, CryptoStoreError> {
1575        start_sas(self, &self.state, we_started, request_handle).await
1576    }
1577}
1578
1579impl Ready {
1580    fn to_transitioned<T: Clone>(
1581        &self,
1582        request_state: &RequestState<T>,
1583        verification: Verification,
1584    ) -> RequestState<Transitioned> {
1585        RequestState {
1586            verification_cache: request_state.verification_cache.to_owned(),
1587            store: request_state.store.to_owned(),
1588            flow_id: request_state.flow_id.to_owned(),
1589            other_user_id: request_state.other_user_id.to_owned(),
1590            state: Transitioned {
1591                ready: self.clone(),
1592                verification,
1593                other_device_data: self.other_device_data.clone(),
1594            },
1595        }
1596    }
1597}
1598
1599#[derive(Clone, Debug)]
1600struct Transitioned {
1601    ready: Ready,
1602    verification: Verification,
1603    other_device_data: DeviceData,
1604}
1605
1606impl RequestState<Transitioned> {
1607    #[cfg(feature = "qrcode")]
1608    async fn generate_qr_code(
1609        &self,
1610        we_started: bool,
1611        request_handle: RequestHandle,
1612    ) -> Result<Option<(RequestState<Transitioned>, QrVerification)>, CryptoStoreError> {
1613        generate_qr_code(self, &self.state.ready, we_started, request_handle).await
1614    }
1615
1616    async fn receive_start(
1617        &self,
1618        sender: &UserId,
1619        content: &StartContent<'_>,
1620        we_started: bool,
1621        request_handle: RequestHandle,
1622    ) -> Result<Option<RequestState<Transitioned>>, CryptoStoreError> {
1623        receive_start(sender, content, we_started, request_handle, self, &self.state.ready).await
1624    }
1625
1626    async fn start_sas(
1627        &self,
1628        we_started: bool,
1629        request_handle: RequestHandle,
1630    ) -> Result<Option<(RequestState<Transitioned>, Sas, OutgoingContent)>, CryptoStoreError> {
1631        start_sas(self, &self.state.ready, we_started, request_handle).await
1632    }
1633}
1634
1635#[derive(Clone, Debug)]
1636struct Passive {
1637    /// The device ID of the device that responded to the verification request.
1638    #[allow(dead_code)]
1639    pub other_device_id: OwnedDeviceId,
1640}
1641
1642#[derive(Clone, Debug)]
1643struct Done {}
1644
1645#[cfg(test)]
1646mod tests {
1647
1648    use std::time::Duration;
1649
1650    use assert_matches::assert_matches;
1651    #[cfg(feature = "qrcode")]
1652    use matrix_sdk_qrcode::QrVerificationData;
1653    use matrix_sdk_test::async_test;
1654    use ruma::{
1655        UserId, event_id, events::key::verification::VerificationMethod, owned_event_id,
1656        owned_room_id, room_id, to_device::DeviceIdOrAllDevices,
1657    };
1658    use strass::assert_let;
1659
1660    use super::VerificationRequest;
1661    use crate::{
1662        DeviceData, VerificationRequestState,
1663        types::requests::OutgoingVerificationRequest,
1664        verification::{
1665            FlowId, Verification, VerificationStore,
1666            cache::VerificationCache,
1667            event_enums::{
1668                CancelContent, OutgoingContent, ReadyContent, RequestContent, StartContent,
1669            },
1670            tests::{alice_id, bob_id, setup_stores},
1671        },
1672    };
1673
1674    #[async_test]
1675    async fn test_request_accepting() {
1676        let event_id = owned_event_id!("$1234localhost");
1677        let room_id = owned_room_id!("!test:localhost");
1678
1679        let (alice, alice_store, bob, bob_store) = setup_stores().await;
1680
1681        let alice_device_data = DeviceData::from_account(&alice);
1682        let bob_device_data = DeviceData::from_account(&bob);
1683
1684        let content = VerificationRequest::request(
1685            &bob_store.account.user_id,
1686            &bob_store.account.device_id,
1687            alice_id(),
1688            None,
1689        );
1690
1691        let flow_id = FlowId::InRoom(room_id, event_id);
1692
1693        let bob_request = VerificationRequest::new(
1694            VerificationCache::new(),
1695            bob_store,
1696            flow_id.clone(),
1697            alice_id(),
1698            vec![],
1699            None,
1700        );
1701
1702        assert_matches!(bob_request.state(), VerificationRequestState::Created { .. });
1703        assert!(bob_request.time_remaining() <= Duration::from_secs(600)); // 10 minutes
1704        assert!(bob_request.time_remaining() > Duration::from_secs(540)); // 9 minutes
1705
1706        #[allow(clippy::needless_borrow)]
1707        let alice_request = VerificationRequest::from_request(
1708            VerificationCache::new(),
1709            alice_store,
1710            bob_id(),
1711            flow_id,
1712            &(&content).into(),
1713            bob_device_data,
1714        );
1715
1716        assert_matches!(alice_request.state(), VerificationRequestState::Requested { .. });
1717
1718        let content: OutgoingContent = alice_request.accept().unwrap().try_into().unwrap();
1719        let content = ReadyContent::try_from(&content).unwrap();
1720
1721        bob_request.receive_ready(alice_id(), &content, alice_device_data);
1722
1723        assert_matches!(bob_request.state(), VerificationRequestState::Ready { .. });
1724        assert_matches!(alice_request.state(), VerificationRequestState::Ready { .. });
1725        assert!(bob_request.is_ready());
1726        assert!(alice_request.is_ready());
1727    }
1728
1729    #[async_test]
1730    async fn test_request_refusal_to_device() {
1731        // test what happens when we cancel() a request that we have just
1732        // received over to-device messages.
1733        let (_alice, alice_store, bob, bob_store) = setup_stores().await;
1734        let bob_device = DeviceData::from_account(&bob);
1735
1736        // Set up the pair of verification requests
1737        let bob_request = build_test_request(&bob_store, alice_id(), None);
1738        let alice_request = build_incoming_verification_request(&alice_store, &bob_request).await;
1739
1740        let outgoing_request = alice_request.cancel().unwrap();
1741
1742        // the outgoing message should target bob's device specifically
1743        {
1744            assert_let!(
1745                OutgoingVerificationRequest::ToDevice(to_device_request) = &outgoing_request
1746            );
1747
1748            assert_eq!(to_device_request.messages.len(), 1);
1749            let device_ids: Vec<&DeviceIdOrAllDevices> =
1750                to_device_request.messages.values().next().unwrap().keys().collect();
1751            assert_eq!(device_ids.len(), 1);
1752
1753            assert_let!(DeviceIdOrAllDevices::DeviceId(device_id) = &device_ids[0]);
1754            assert_eq!(device_id, bob_device.device_id());
1755        }
1756
1757        let content = OutgoingContent::try_from(outgoing_request).unwrap();
1758        let content = CancelContent::try_from(&content).unwrap();
1759
1760        bob_request.receive_cancel(alice_id(), &content);
1761
1762        assert_matches!(bob_request.state(), VerificationRequestState::Cancelled { .. });
1763        assert_matches!(alice_request.state(), VerificationRequestState::Cancelled { .. });
1764    }
1765
1766    #[async_test]
1767    async fn test_requesting_until_sas() {
1768        let event_id = event_id!("$1234localhost");
1769        let room_id = room_id!("!test:localhost");
1770
1771        let (alice, alice_store, bob, bob_store) = setup_stores().await;
1772
1773        let alice_device_data = DeviceData::from_account(&alice);
1774        let bob_device_data = DeviceData::from_account(&bob);
1775
1776        let content = VerificationRequest::request(
1777            &bob_store.account.user_id,
1778            &bob_store.account.device_id,
1779            alice_id(),
1780            None,
1781        );
1782
1783        let flow_id = FlowId::from((room_id, event_id));
1784
1785        let bob_request = VerificationRequest::new(
1786            VerificationCache::new(),
1787            bob_store,
1788            flow_id.clone(),
1789            alice_id(),
1790            vec![],
1791            None,
1792        );
1793
1794        #[allow(clippy::needless_borrow)]
1795        let alice_request = VerificationRequest::from_request(
1796            VerificationCache::new(),
1797            alice_store,
1798            bob_id(),
1799            flow_id,
1800            &(&content).into(),
1801            bob_device_data.clone(),
1802        );
1803
1804        do_accept_request(&alice_request, alice_device_data.clone(), &bob_request, None);
1805
1806        let (bob_sas, request) = bob_request.start_sas().await.unwrap().unwrap();
1807
1808        let content: OutgoingContent = request.try_into().unwrap();
1809        let content = StartContent::try_from(&content).unwrap();
1810        let flow_id = content.flow_id().to_owned();
1811        alice_request.receive_start(bob_device_data.user_id(), &content).await.unwrap();
1812        let alice_sas =
1813            alice_request.verification_cache.get_sas(bob_device_data.user_id(), &flow_id).unwrap();
1814
1815        assert_let!(
1816            VerificationRequestState::Transitioned {
1817                verification: Verification::SasV1(_),
1818                other_device_data
1819            } = alice_request.state()
1820        );
1821
1822        assert_eq!(bob_device_data, other_device_data);
1823
1824        assert_let!(
1825            VerificationRequestState::Transitioned {
1826                verification: Verification::SasV1(_),
1827                other_device_data
1828            } = bob_request.state()
1829        );
1830
1831        assert_eq!(alice_device_data, other_device_data);
1832
1833        assert!(!bob_sas.is_cancelled());
1834        assert!(!alice_sas.is_cancelled());
1835    }
1836
1837    #[async_test]
1838    async fn test_requesting_until_sas_to_device() {
1839        let (alice, alice_store, bob, bob_store) = setup_stores().await;
1840
1841        let alice_device_data = DeviceData::from_account(&alice);
1842        let bob_device_data = DeviceData::from_account(&bob);
1843
1844        // Set up the pair of verification requests
1845        let bob_request = build_test_request(&bob_store, alice_id(), None);
1846        let alice_request = build_incoming_verification_request(&alice_store, &bob_request).await;
1847        do_accept_request(&alice_request, alice_device_data.clone(), &bob_request, None);
1848
1849        let (bob_sas, request) = bob_request.start_sas().await.unwrap().unwrap();
1850
1851        let content: OutgoingContent = request.try_into().unwrap();
1852        let content = StartContent::try_from(&content).unwrap();
1853        let flow_id = content.flow_id().to_owned();
1854        alice_request.receive_start(bob_device_data.user_id(), &content).await.unwrap();
1855        let alice_sas =
1856            alice_request.verification_cache.get_sas(bob_device_data.user_id(), &flow_id).unwrap();
1857
1858        assert_let!(
1859            VerificationRequestState::Transitioned {
1860                verification: Verification::SasV1(_),
1861                other_device_data
1862            } = alice_request.state()
1863        );
1864
1865        assert_eq!(bob_device_data, other_device_data);
1866
1867        assert_let!(
1868            VerificationRequestState::Transitioned {
1869                verification: Verification::SasV1(_),
1870                other_device_data
1871            } = bob_request.state()
1872        );
1873
1874        assert_eq!(alice_device_data, other_device_data);
1875
1876        assert!(!bob_sas.is_cancelled());
1877        assert!(!alice_sas.is_cancelled());
1878        assert!(alice_sas.started_from_request());
1879        assert!(bob_sas.started_from_request());
1880    }
1881
1882    #[async_test]
1883    #[cfg(feature = "qrcode")]
1884    async fn test_can_scan_another_qr_after_creating_mine() {
1885        let (alice, alice_store, bob, bob_store) = setup_stores().await;
1886
1887        let alice_device_data = DeviceData::from_account(&alice);
1888        let bob_device_data = DeviceData::from_account(&bob);
1889
1890        // Set up the pair of verification requests
1891        let bob_request = build_test_request(
1892            &bob_store,
1893            alice_id(),
1894            Some(vec![VerificationMethod::QrCodeScanV1, VerificationMethod::QrCodeShowV1]),
1895        );
1896        let alice_request = build_incoming_verification_request(&alice_store, &bob_request).await;
1897        do_accept_request(
1898            &alice_request,
1899            alice_device_data.clone(),
1900            &bob_request,
1901            Some(vec![VerificationMethod::QrCodeScanV1, VerificationMethod::QrCodeShowV1]),
1902        );
1903
1904        // Each side can start its own QR verification flow by generating QR
1905        // code
1906        let alice_verification = alice_request.generate_qr_code().await.unwrap();
1907        let bob_verification = bob_request.generate_qr_code().await.unwrap();
1908
1909        assert_let!(
1910            VerificationRequestState::Transitioned {
1911                verification: Verification::QrV1(_),
1912                other_device_data
1913            } = alice_request.state()
1914        );
1915
1916        assert_eq!(bob_device_data, other_device_data);
1917
1918        assert_let!(
1919            VerificationRequestState::Transitioned {
1920                verification: Verification::QrV1(_),
1921                other_device_data
1922            } = bob_request.state()
1923        );
1924
1925        assert_eq!(alice_device_data, other_device_data);
1926
1927        assert!(alice_verification.is_some());
1928        assert!(bob_verification.is_some());
1929
1930        // Now only Alice scans Bob's code
1931        let bob_qr_code = bob_verification.unwrap().to_bytes().unwrap();
1932        let bob_qr_code = QrVerificationData::from_bytes(bob_qr_code).unwrap();
1933        let _ = alice_request.scan_qr_code(bob_qr_code).await.unwrap().unwrap();
1934
1935        assert_let!(
1936            VerificationRequestState::Transitioned {
1937                verification: Verification::QrV1(alice_verification),
1938                other_device_data
1939            } = alice_request.state()
1940        );
1941
1942        assert_eq!(bob_device_data, other_device_data);
1943
1944        // Finally we assert that the verification has been reciprocated rather
1945        // than cancelled due to a duplicate verification flow
1946        assert!(!alice_verification.is_cancelled());
1947        assert!(alice_verification.reciprocated());
1948    }
1949
1950    #[async_test]
1951    #[cfg(feature = "qrcode")]
1952    async fn test_can_start_sas_after_generating_qr_code() {
1953        let (alice, alice_store, bob, bob_store) = setup_stores().await;
1954
1955        let alice_device_data = DeviceData::from_account(&alice);
1956        let bob_device_data = DeviceData::from_account(&bob);
1957
1958        // Set up the pair of verification requests
1959        let bob_request = build_test_request(&bob_store, alice_id(), Some(all_methods()));
1960        let alice_request = build_incoming_verification_request(&alice_store, &bob_request).await;
1961        do_accept_request(
1962            &alice_request,
1963            alice_device_data.clone(),
1964            &bob_request,
1965            Some(all_methods()),
1966        );
1967
1968        // Each side can start its own QR verification flow by generating QR
1969        // code
1970        let alice_verification = alice_request.generate_qr_code().await.unwrap();
1971        let bob_verification = bob_request.generate_qr_code().await.unwrap();
1972
1973        assert_let!(
1974            VerificationRequestState::Transitioned {
1975                verification: Verification::QrV1(_),
1976                other_device_data
1977            } = alice_request.state()
1978        );
1979
1980        assert_eq!(bob_device_data, other_device_data);
1981
1982        assert!(alice_verification.is_some());
1983        assert!(bob_verification.is_some());
1984
1985        // Alice can now start SAS verification flow instead of QR without
1986        // cancelling the request
1987        let (sas, request) = alice_request.start_sas().await.unwrap().unwrap();
1988        assert_let!(
1989            VerificationRequestState::Transitioned {
1990                verification: Verification::SasV1(_),
1991                other_device_data
1992            } = alice_request.state()
1993        );
1994
1995        assert_eq!(bob_device_data, other_device_data);
1996        assert!(!sas.is_cancelled());
1997
1998        // Bob receives the SAS start
1999        let content: OutgoingContent = request.try_into().unwrap();
2000        let content = StartContent::try_from(&content).unwrap();
2001        bob_request.receive_start(alice_id(), &content).await.unwrap();
2002
2003        // Bob should now have transitioned to SAS...
2004        assert_let!(
2005            VerificationRequestState::Transitioned {
2006                verification: Verification::SasV1(bob_sas),
2007                other_device_data
2008            } = bob_request.state()
2009        );
2010
2011        assert_eq!(alice_device_data, other_device_data);
2012
2013        // ... and, more to the point, it should not be cancelled.
2014        assert!(!bob_sas.is_cancelled());
2015    }
2016
2017    #[async_test]
2018    #[cfg(feature = "qrcode")]
2019    async fn test_start_sas_after_scan_cancels_request() {
2020        let (alice, alice_store, bob, bob_store) = setup_stores().await;
2021
2022        let alice_device_data = DeviceData::from_account(&alice);
2023        let bob_device_data = DeviceData::from_account(&bob);
2024
2025        // Set up the pair of verification requests
2026        let bob_request = build_test_request(&bob_store, alice_id(), Some(all_methods()));
2027        let alice_request = build_incoming_verification_request(&alice_store, &bob_request).await;
2028        do_accept_request(
2029            &alice_request,
2030            alice_device_data.clone(),
2031            &bob_request,
2032            Some(all_methods()),
2033        );
2034
2035        // Bob generates a QR code
2036        let bob_verification = bob_request.generate_qr_code().await.unwrap().unwrap();
2037        assert_let!(
2038            VerificationRequestState::Transitioned {
2039                verification: Verification::QrV1(_),
2040                other_device_data
2041            } = bob_request.state()
2042        );
2043
2044        assert_eq!(alice_device_data, other_device_data);
2045
2046        // Now Alice scans Bob's code
2047        let bob_qr_code = bob_verification.to_bytes().unwrap();
2048        let bob_qr_code = QrVerificationData::from_bytes(bob_qr_code).unwrap();
2049        let _ = alice_request.scan_qr_code(bob_qr_code).await.unwrap().unwrap();
2050
2051        assert_let!(
2052            VerificationRequestState::Transitioned {
2053                verification: Verification::QrV1(alice_qr),
2054                other_device_data
2055            } = alice_request.state()
2056        );
2057
2058        assert_eq!(bob_device_data, other_device_data);
2059        assert!(alice_qr.reciprocated());
2060
2061        // But Bob wants to do an SAS verification!
2062        let (_, request) = bob_request.start_sas().await.unwrap().unwrap();
2063        assert_let!(
2064            VerificationRequestState::Transitioned {
2065                verification: Verification::SasV1(_),
2066                other_device_data
2067            } = bob_request.state()
2068        );
2069
2070        assert_eq!(alice_device_data, other_device_data);
2071
2072        // Alice receives the SAS start
2073        let content: OutgoingContent = request.try_into().unwrap();
2074        let content = StartContent::try_from(&content).unwrap();
2075        alice_request.receive_start(bob_id(), &content).await.unwrap();
2076
2077        // ... which should mean that her Qr is cancelled
2078        assert!(alice_qr.is_cancelled());
2079
2080        // and she should now have a *cancelled* SAS verification
2081        assert_let!(
2082            VerificationRequestState::Transitioned {
2083                verification: Verification::SasV1(alice_sas),
2084                other_device_data
2085            } = alice_request.state()
2086        );
2087
2088        assert_eq!(bob_device_data, other_device_data);
2089        assert!(alice_sas.is_cancelled());
2090    }
2091
2092    /// Build an outgoing Verification request
2093    ///
2094    /// # Arguments
2095    ///
2096    /// - `verification_store` - The `VerificationStore` for the user making the
2097    ///   request.
2098    /// - `other_user_id` - The ID of the user we want to verify
2099    /// - `methods` - A list of `VerificationMethods` to say we support. If
2100    ///   `None`, will use the default list.
2101    fn build_test_request(
2102        verification_store: &VerificationStore,
2103        other_user_id: &UserId,
2104        methods: Option<Vec<VerificationMethod>>,
2105    ) -> VerificationRequest {
2106        VerificationRequest::new(
2107            VerificationCache::new(),
2108            verification_store.clone(),
2109            FlowId::ToDevice("TEST_FLOW_ID".into()),
2110            other_user_id,
2111            vec![],
2112            methods,
2113        )
2114    }
2115
2116    /// Given an outgoing `VerificationRequest`, create an incoming
2117    /// `VerificationRequest` for the other side.
2118    ///
2119    /// Tells the outgoing request to generate an `m.key.verification.request`
2120    /// to-device message, and uses it to build a new request for the incoming
2121    /// side.
2122    async fn build_incoming_verification_request(
2123        verification_store: &VerificationStore,
2124        outgoing_request: &VerificationRequest,
2125    ) -> VerificationRequest {
2126        let request = outgoing_request.request_to_device();
2127        let content: OutgoingContent = request.try_into().unwrap();
2128        let content = RequestContent::try_from(&content).unwrap();
2129
2130        let device_data = verification_store
2131            .get_device(outgoing_request.own_user_id(), content.from_device())
2132            .await
2133            .unwrap()
2134            .expect("Missing device data");
2135
2136        VerificationRequest::from_request(
2137            VerificationCache::new(),
2138            verification_store.clone(),
2139            outgoing_request.own_user_id(),
2140            outgoing_request.flow_id().clone(),
2141            &content,
2142            device_data,
2143        )
2144    }
2145
2146    /// Have a `VerificationRequest` generate an `m.key.verification.ready` and
2147    /// feed it into another `VerificationRequest`.
2148    ///
2149    /// # Arguments
2150    ///
2151    /// - `accepting_request` - The request which should send the acceptance.
2152    /// - `initiating_request` - The request which initiated the flow -- i.e.,
2153    ///   the one that should _receive_ the acceptance.
2154    /// - `methods` - The list of methods to say we support. If `None`, the
2155    ///   default list of methods will be used.
2156    fn do_accept_request(
2157        accepting_request: &VerificationRequest,
2158        accepting_device_data: DeviceData,
2159        initiating_request: &VerificationRequest,
2160        methods: Option<Vec<VerificationMethod>>,
2161    ) {
2162        let request = match methods {
2163            Some(methods) => accepting_request.accept_with_methods(methods),
2164            None => accepting_request.accept(),
2165        };
2166        let content: OutgoingContent = request.unwrap().try_into().unwrap();
2167        let content = ReadyContent::try_from(&content).unwrap();
2168        initiating_request.receive_ready(
2169            accepting_request.own_user_id(),
2170            &content,
2171            accepting_device_data,
2172        );
2173
2174        assert!(initiating_request.is_ready());
2175        assert!(accepting_request.is_ready());
2176    }
2177
2178    /// Get a list of all the verification methods, including those used for QR
2179    /// codes.
2180    #[cfg(feature = "qrcode")]
2181    fn all_methods() -> Vec<VerificationMethod> {
2182        vec![
2183            VerificationMethod::SasV1,
2184            VerificationMethod::QrCodeScanV1,
2185            VerificationMethod::QrCodeShowV1,
2186            VerificationMethod::ReciprocateV1,
2187        ]
2188    }
2189}