matrix_sdk_crypto/identities/
user.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::{
16    collections::HashMap,
17    ops::{Deref, DerefMut},
18    sync::{
19        Arc,
20        atomic::{AtomicBool, Ordering},
21    },
22};
23
24use as_variant::as_variant;
25use matrix_sdk_common::locks::RwLock;
26use ruma::{
27    DeviceId, EventId, OwnedDeviceId, OwnedUserId, RoomId, UserId,
28    api::client::keys::upload_signatures::v3::Request as SignatureUploadRequest,
29    events::{key::verification::VerificationMethod, room::message::MessageType},
30};
31use serde::{Deserialize, Deserializer, Serialize};
32use serde_json::Value;
33use tracing::{error, info};
34
35use crate::{
36    CryptoStoreError, DeviceData, VerificationRequest,
37    error::SignatureError,
38    store::{
39        Store,
40        types::{Changes, IdentityChanges},
41    },
42    types::{
43        MasterPubkey, SelfSigningPubkey, UserSigningPubkey, requests::OutgoingVerificationRequest,
44    },
45    verification::VerificationMachine,
46};
47
48/// Enum over the different user identity types we can have.
49#[derive(Debug, Clone)]
50pub enum UserIdentity {
51    /// Our own user identity.
52    Own(OwnUserIdentity),
53    /// An identity belonging to another user.
54    Other(OtherUserIdentity),
55}
56
57impl UserIdentity {
58    /// Destructure the enum into an [`OwnUserIdentity`] if it's of the correct
59    /// type.
60    pub fn own(self) -> Option<OwnUserIdentity> {
61        as_variant!(self, Self::Own)
62    }
63
64    /// Destructure the enum into an [`OtherUserIdentity`] if it's of the
65    /// correct type.
66    pub fn other(self) -> Option<OtherUserIdentity> {
67        as_variant!(self, Self::Other)
68    }
69
70    /// Get the ID of the user this identity belongs to.
71    pub fn user_id(&self) -> &UserId {
72        match self {
73            UserIdentity::Own(u) => u.user_id(),
74            UserIdentity::Other(u) => u.user_id(),
75        }
76    }
77
78    pub(crate) fn new(
79        store: Store,
80        identity: UserIdentityData,
81        verification_machine: VerificationMachine,
82        own_identity: Option<OwnUserIdentityData>,
83    ) -> Self {
84        match identity {
85            UserIdentityData::Own(i) => {
86                Self::Own(OwnUserIdentity { inner: i, verification_machine, store })
87            }
88            UserIdentityData::Other(i) => {
89                Self::Other(OtherUserIdentity { inner: i, own_identity, verification_machine })
90            }
91        }
92    }
93
94    /// Check if this user identity is verified.
95    ///
96    /// For our own identity, this means either that we have checked the public
97    /// keys in the identity against the private keys; or that the identity
98    /// has been manually marked as verified via
99    /// [`OwnUserIdentity::verify`].
100    ///
101    /// For another user's identity, it means that we have verified our own
102    /// identity as above, *and* that the other user's identity has been signed
103    /// by our own user-signing key.
104    pub fn is_verified(&self) -> bool {
105        match self {
106            UserIdentity::Own(u) => u.is_verified(),
107            UserIdentity::Other(u) => u.is_verified(),
108        }
109    }
110
111    /// True if we verified this identity at some point in the past.
112    ///
113    /// To reset this latch back to `false`, one must call
114    /// [`UserIdentity::withdraw_verification()`].
115    pub fn was_previously_verified(&self) -> bool {
116        match self {
117            UserIdentity::Own(u) => u.was_previously_verified(),
118            UserIdentity::Other(u) => u.was_previously_verified(),
119        }
120    }
121
122    /// Reset the flag that records that the identity has been verified, thus
123    /// clearing [`UserIdentity::was_previously_verified`] and
124    /// [`UserIdentity::has_verification_violation`].
125    pub async fn withdraw_verification(&self) -> Result<(), CryptoStoreError> {
126        match self {
127            UserIdentity::Own(u) => u.withdraw_verification().await,
128            UserIdentity::Other(u) => u.withdraw_verification().await,
129        }
130    }
131
132    /// Remember this identity, ensuring it does not result in a pin violation.
133    ///
134    /// When we first see a user, we assume their cryptographic identity has not
135    /// been tampered with by the homeserver or another entity with
136    /// man-in-the-middle capabilities. We remember this identity and call this
137    /// action "pinning".
138    ///
139    /// If the identity presented for the user changes later on, the newly
140    /// presented identity is considered to be in "pin violation". This
141    /// method explicitly accepts the new identity, allowing it to replace
142    /// the previously pinned one and bringing it out of pin violation.
143    ///
144    /// UIs should display a warning to the user when encountering an identity
145    /// which is not verified and is in pin violation. See
146    /// [`OtherUserIdentity::identity_needs_user_approval`].
147    pub async fn pin(&self) -> Result<(), CryptoStoreError> {
148        match self {
149            UserIdentity::Own(_) => {
150                // Nothing to be done for our own identity: we already
151                // consider it trusted in this sense.
152                Ok(())
153            }
154            UserIdentity::Other(u) => u.pin_current_master_key().await,
155        }
156    }
157
158    /// Was this identity previously verified, and is no longer?
159    pub fn has_verification_violation(&self) -> bool {
160        match self {
161            UserIdentity::Own(u) => u.has_verification_violation(),
162            UserIdentity::Other(u) => u.has_verification_violation(),
163        }
164    }
165}
166
167impl From<OwnUserIdentity> for UserIdentity {
168    fn from(i: OwnUserIdentity) -> Self {
169        Self::Own(i)
170    }
171}
172
173impl From<OtherUserIdentity> for UserIdentity {
174    fn from(i: OtherUserIdentity) -> Self {
175        Self::Other(i)
176    }
177}
178
179/// Struct representing a cross signing identity of a user.
180///
181/// This is the user identity of a user that is our own. Other users will
182/// only contain a master key and a self signing key, meaning that only device
183/// signatures can be checked with this identity.
184///
185/// This struct wraps the [`OwnUserIdentityData`] type and allows a verification
186/// to be requested to verify our own device with the user identity.
187#[derive(Debug, Clone)]
188pub struct OwnUserIdentity {
189    pub(crate) inner: OwnUserIdentityData,
190    pub(crate) verification_machine: VerificationMachine,
191    store: Store,
192}
193
194impl Deref for OwnUserIdentity {
195    type Target = OwnUserIdentityData;
196
197    fn deref(&self) -> &Self::Target {
198        &self.inner
199    }
200}
201
202impl DerefMut for OwnUserIdentity {
203    fn deref_mut(&mut self) -> &mut <Self as Deref>::Target {
204        &mut self.inner
205    }
206}
207
208impl OwnUserIdentity {
209    /// Mark our user identity as verified.
210    ///
211    /// This will mark the identity locally as verified and sign it with our own
212    /// device.
213    ///
214    /// Returns a signature upload request that needs to be sent out.
215    pub async fn verify(&self) -> Result<SignatureUploadRequest, SignatureError> {
216        self.mark_as_verified();
217
218        let changes = Changes {
219            identities: IdentityChanges {
220                changed: vec![self.inner.clone().into()],
221                new: vec![],
222                unchanged: vec![],
223            },
224            ..Default::default()
225        };
226
227        if let Err(e) = self.verification_machine.store.save_changes(changes).await {
228            error!(error = ?e, "Couldn't store our own user identity after marking it as verified");
229        }
230
231        let cache = self.store.cache().await?;
232        let account = cache.account().await?;
233        account.sign_master_key(&self.master_key)
234    }
235
236    /// Send a verification request to our other devices.
237    pub async fn request_verification(
238        &self,
239    ) -> Result<(VerificationRequest, OutgoingVerificationRequest), CryptoStoreError> {
240        self.request_verification_helper(None).await
241    }
242
243    /// Send a verification request to our other devices while specifying our
244    /// supported methods.
245    ///
246    /// # Arguments
247    ///
248    /// * `methods` - The verification methods that we're supporting.
249    pub async fn request_verification_with_methods(
250        &self,
251        methods: Vec<VerificationMethod>,
252    ) -> Result<(VerificationRequest, OutgoingVerificationRequest), CryptoStoreError> {
253        self.request_verification_helper(Some(methods)).await
254    }
255
256    /// Does our user identity trust our own device, i.e. have we signed our
257    /// own device keys with our self-signing key.
258    pub async fn trusts_our_own_device(&self) -> Result<bool, CryptoStoreError> {
259        Ok(if let Some(signatures) = self.verification_machine.store.device_signatures().await? {
260            let mut device_keys = self.store.cache().await?.account().await?.device_keys();
261            device_keys.signatures = signatures;
262
263            self.inner.self_signing_key().verify_device_keys(&device_keys).is_ok()
264        } else {
265            false
266        })
267    }
268
269    async fn request_verification_helper(
270        &self,
271        methods: Option<Vec<VerificationMethod>>,
272    ) -> Result<(VerificationRequest, OutgoingVerificationRequest), CryptoStoreError> {
273        let all_devices = self.verification_machine.store.get_user_devices(self.user_id()).await?;
274        let devices = self
275            .inner
276            .filter_devices_to_request(all_devices, self.verification_machine.own_device_id());
277
278        Ok(self.verification_machine.request_to_device_verification(
279            self.user_id(),
280            devices,
281            methods,
282        ))
283    }
284
285    /// Remove the requirement for this identity to be verified.
286    pub async fn withdraw_verification(&self) -> Result<(), CryptoStoreError> {
287        self.inner.withdraw_verification();
288        let to_save = UserIdentityData::Own(self.inner.clone());
289        let changes = Changes {
290            identities: IdentityChanges { changed: vec![to_save], ..Default::default() },
291            ..Default::default()
292        };
293        self.verification_machine.store.inner().save_changes(changes).await?;
294        Ok(())
295    }
296}
297
298/// Struct representing a cross signing identity of a user.
299///
300/// This is the user identity of a user that isn't our own. Other users will
301/// only contain a master key and a self signing key, meaning that only device
302/// signatures can be checked with this identity.
303///
304/// This struct wraps a read-only version of the struct and allows verifications
305/// to be requested to verify our own device with the user identity.
306#[derive(Debug, Clone)]
307pub struct OtherUserIdentity {
308    pub(crate) inner: OtherUserIdentityData,
309    pub(crate) own_identity: Option<OwnUserIdentityData>,
310    pub(crate) verification_machine: VerificationMachine,
311}
312
313impl Deref for OtherUserIdentity {
314    type Target = OtherUserIdentityData;
315
316    fn deref(&self) -> &Self::Target {
317        &self.inner
318    }
319}
320
321impl DerefMut for OtherUserIdentity {
322    fn deref_mut(&mut self) -> &mut <Self as Deref>::Target {
323        &mut self.inner
324    }
325}
326
327impl OtherUserIdentity {
328    /// Is this user identity verified.
329    pub fn is_verified(&self) -> bool {
330        self.own_identity
331            .as_ref()
332            .is_some_and(|own_identity| own_identity.is_identity_verified(&self.inner))
333    }
334
335    /// Manually verify this user.
336    ///
337    /// This method will attempt to sign the user identity using our private
338    /// cross signing key.
339    ///
340    /// This method fails if we don't have the private part of our user-signing
341    /// key.
342    ///
343    /// Returns a request that needs to be sent out for the user to be marked
344    /// as verified.
345    pub async fn verify(&self) -> Result<SignatureUploadRequest, SignatureError> {
346        if self.user_id() != self.verification_machine.own_user_id() {
347            Ok(self
348                .verification_machine
349                .store
350                .private_identity
351                .lock()
352                .await
353                .sign_user(&self.inner)
354                .await?)
355        } else {
356            Err(SignatureError::UserIdMismatch)
357        }
358    }
359
360    /// Create a [`VerificationRequest`] object after the verification request
361    /// content returned by [`OtherUserIdentity::verification_request_content`]
362    /// has been sent out.
363    pub fn request_verification(
364        &self,
365        room_id: &RoomId,
366        request_event_id: &EventId,
367        methods: Option<Vec<VerificationMethod>>,
368    ) -> VerificationRequest {
369        self.verification_machine.request_verification(
370            &self.inner,
371            room_id,
372            request_event_id,
373            methods,
374        )
375    }
376
377    /// Create a verification request to send to the given user.
378    ///
379    /// The returned content needs to be sent out into a DM room with the user.
380    ///
381    /// After the content has been sent out a [`VerificationRequest`] can be
382    /// started with the [`OtherUserIdentity::request_verification()`] method.
383    pub fn verification_request_content(
384        &self,
385        methods: Option<Vec<VerificationMethod>>,
386    ) -> MessageType {
387        MessageType::VerificationRequest(VerificationRequest::request(
388            self.verification_machine.own_user_id(),
389            self.verification_machine.own_device_id(),
390            self.user_id(),
391            methods,
392        ))
393    }
394
395    /// Pin the current identity (public part of the master signing key).
396    pub async fn pin_current_master_key(&self) -> Result<(), CryptoStoreError> {
397        info!(master_key = ?self.master_key.get_first_key(), "Pinning current identity for user '{}'", self.user_id());
398        self.inner.pin();
399        let to_save = UserIdentityData::Other(self.inner.clone());
400        let changes = Changes {
401            identities: IdentityChanges { changed: vec![to_save], ..Default::default() },
402            ..Default::default()
403        };
404        self.verification_machine.store.inner().save_changes(changes).await?;
405        Ok(())
406    }
407
408    /// Has the identity changed in a way that requires approval from the user?
409    ///
410    /// A user identity needs approval if it changed after the crypto machine
411    /// has already observed ("pinned") a different identity for that user,
412    /// unless it is an explicitly verified identity (using for example
413    /// interactive verification).
414    ///
415    /// This situation can be resolved by:
416    ///
417    /// - Verifying the new identity with
418    ///   [`OtherUserIdentity::request_verification`], or:
419    /// - Updating the pin to the new identity with
420    ///   [`OtherUserIdentity::pin_current_master_key`].
421    pub fn identity_needs_user_approval(&self) -> bool {
422        // First check if the current identity is verified.
423        if self.is_verified() {
424            return false;
425        }
426        // If not we can check the pinned identity. Verification always have
427        // higher priority than pinning.
428        self.inner.has_pin_violation()
429    }
430
431    /// Remove the requirement for this identity to be verified.
432    pub async fn withdraw_verification(&self) -> Result<(), CryptoStoreError> {
433        info!(
434            master_key = ?self.master_key.get_first_key(),
435            user = ?self.user_id(),
436            "Withdrawing verification status and pinning current identity"
437        );
438        self.inner.withdraw_verification();
439        let to_save = UserIdentityData::Other(self.inner.clone());
440        let changes = Changes {
441            identities: IdentityChanges { changed: vec![to_save], ..Default::default() },
442            ..Default::default()
443        };
444        self.verification_machine.store.inner().save_changes(changes).await?;
445        Ok(())
446    }
447
448    /// Test helper that marks that an identity has been previously verified and
449    /// persist the change in the store.
450    #[cfg(test)]
451    pub async fn mark_as_previously_verified(&self) -> Result<(), CryptoStoreError> {
452        self.inner.mark_as_previously_verified();
453
454        let to_save = UserIdentityData::Other(self.inner.clone());
455        let changes = Changes {
456            identities: IdentityChanges { changed: vec![to_save], ..Default::default() },
457            ..Default::default()
458        };
459
460        self.verification_machine.store.inner().save_changes(changes).await?;
461
462        Ok(())
463    }
464
465    /// Was this identity verified since initial observation and is not anymore?
466    ///
467    /// Such a violation should be reported to the local user by the
468    /// application, and resolved by
469    ///
470    /// - Verifying the new identity with
471    ///   [`OtherUserIdentity::request_verification`]
472    /// - Or by withdrawing the verification requirement
473    ///   [`OtherUserIdentity::withdraw_verification`].
474    pub fn has_verification_violation(&self) -> bool {
475        if !self.inner.was_previously_verified() {
476            // If that identity has never been verified it cannot be in violation.
477            return false;
478        }
479
480        !self.is_verified()
481    }
482}
483
484/// Enum over the different user identity types we can have.
485#[derive(Debug, Clone, Serialize, Deserialize)]
486pub enum UserIdentityData {
487    /// Our own user identity.
488    Own(OwnUserIdentityData),
489    /// The identity of another user.
490    Other(OtherUserIdentityData),
491}
492
493impl From<OwnUserIdentityData> for UserIdentityData {
494    fn from(identity: OwnUserIdentityData) -> Self {
495        UserIdentityData::Own(identity)
496    }
497}
498
499impl From<OtherUserIdentityData> for UserIdentityData {
500    fn from(identity: OtherUserIdentityData) -> Self {
501        UserIdentityData::Other(identity)
502    }
503}
504
505impl UserIdentityData {
506    /// The unique user id of this identity.
507    pub fn user_id(&self) -> &UserId {
508        match self {
509            UserIdentityData::Own(i) => i.user_id(),
510            UserIdentityData::Other(i) => i.user_id(),
511        }
512    }
513
514    /// Get the master key of the identity.
515    pub fn master_key(&self) -> &MasterPubkey {
516        match self {
517            UserIdentityData::Own(i) => i.master_key(),
518            UserIdentityData::Other(i) => i.master_key(),
519        }
520    }
521
522    /// Get the [`SelfSigningPubkey`] key of the identity.
523    pub fn self_signing_key(&self) -> &SelfSigningPubkey {
524        match self {
525            UserIdentityData::Own(i) => &i.self_signing_key,
526            UserIdentityData::Other(i) => &i.self_signing_key,
527        }
528    }
529
530    /// Get the user-signing key of the identity, this is only present for our
531    /// own user identity..
532    pub fn user_signing_key(&self) -> Option<&UserSigningPubkey> {
533        match self {
534            UserIdentityData::Own(i) => Some(&i.user_signing_key),
535            UserIdentityData::Other(_) => None,
536        }
537    }
538
539    /// True if we verified our own identity at some point in the past.
540    ///
541    /// To reset this latch back to `false`, one must call
542    /// [`UserIdentity::withdraw_verification()`].
543    pub fn was_previously_verified(&self) -> bool {
544        match self {
545            UserIdentityData::Own(i) => i.was_previously_verified(),
546            UserIdentityData::Other(i) => i.was_previously_verified(),
547        }
548    }
549
550    /// Convert the enum into a reference [`OwnUserIdentityData`] if it's of
551    /// the correct type.
552    pub fn own(&self) -> Option<&OwnUserIdentityData> {
553        as_variant!(self, Self::Own)
554    }
555
556    /// Convert the enum into an [`OwnUserIdentityData`] if it's of the correct
557    /// type.
558    pub(crate) fn into_own(self) -> Option<OwnUserIdentityData> {
559        as_variant!(self, Self::Own)
560    }
561
562    /// Convert the enum into a reference to [`OtherUserIdentityData`] if
563    /// it's of the correct type.
564    pub fn other(&self) -> Option<&OtherUserIdentityData> {
565        as_variant!(self, Self::Other)
566    }
567}
568
569/// Struct representing a cross signing identity of a user.
570///
571/// This is the user identity of a user that isn't our own. Other users will
572/// only contain a master key and a self signing key, meaning that only device
573/// signatures can be checked with this identity.
574///
575/// This struct also contains the currently pinned user identity (public master
576/// key) for that user and a local flag that serves as a latch to remember if an
577/// identity was verified once.
578///
579/// The first time a cryptographic user identity is seen for a given user, it
580/// will be associated with that user ("pinned"). Future interactions
581/// will expect this identity to stay the same, to avoid MITM attacks from the
582/// homeserver.
583///
584/// The user can explicitly pin the new identity to allow for legitimate
585/// identity changes (for example, in case of key material or device loss).
586///
587/// As soon as the cryptographic identity is verified (i.e. signed by our own
588/// trusted identity), a flag is set to remember it (`previously_verified`).
589/// Future interactions will expect this user to stay verified, in case of
590/// violation the user should be notified with a blocking warning when sending a
591/// message.
592#[derive(Debug, Clone, Deserialize, Serialize)]
593#[serde(try_from = "OtherUserIdentityDataSerializer", into = "OtherUserIdentityDataSerializer")]
594pub struct OtherUserIdentityData {
595    user_id: OwnedUserId,
596    pub(crate) master_key: Arc<MasterPubkey>,
597    self_signing_key: Arc<SelfSigningPubkey>,
598    pinned_master_key: Arc<RwLock<MasterPubkey>>,
599    /// This tracks whether this olm machine has already seen this user as
600    /// verified. To use it in the future to detect cases where the user has
601    /// become unverified for any reason. This can be reset using
602    /// [`OtherUserIdentityData::withdraw_verification()`].
603    previously_verified: Arc<AtomicBool>,
604}
605
606/// Intermediate struct to help serialize OtherUserIdentityData and support
607/// versioning and migration.
608///
609/// Version v1 is adding support for identity pinning (`pinned_master_key`), as
610/// part of migration we just pin the currently known public master key.
611#[derive(Deserialize, Serialize)]
612struct OtherUserIdentityDataSerializer {
613    version: Option<String>,
614    #[serde(flatten)]
615    other: Value,
616}
617
618#[derive(Debug, Deserialize, Serialize)]
619struct OtherUserIdentityDataSerializerV0 {
620    user_id: OwnedUserId,
621    master_key: MasterPubkey,
622    self_signing_key: SelfSigningPubkey,
623}
624
625#[derive(Debug, Deserialize, Serialize)]
626struct OtherUserIdentityDataSerializerV1 {
627    user_id: OwnedUserId,
628    master_key: MasterPubkey,
629    self_signing_key: SelfSigningPubkey,
630    pinned_master_key: MasterPubkey,
631}
632
633#[derive(Debug, Deserialize, Serialize)]
634struct OtherUserIdentityDataSerializerV2 {
635    user_id: OwnedUserId,
636    master_key: MasterPubkey,
637    self_signing_key: SelfSigningPubkey,
638    pinned_master_key: MasterPubkey,
639    previously_verified: bool,
640}
641
642impl TryFrom<OtherUserIdentityDataSerializer> for OtherUserIdentityData {
643    type Error = serde_json::Error;
644    fn try_from(
645        value: OtherUserIdentityDataSerializer,
646    ) -> Result<OtherUserIdentityData, Self::Error> {
647        match value.version {
648            None => {
649                // Old format, migrate the pinned identity
650                let v0: OtherUserIdentityDataSerializerV0 = serde_json::from_value(value.other)?;
651                Ok(OtherUserIdentityData {
652                    user_id: v0.user_id,
653                    master_key: Arc::new(v0.master_key.clone()),
654                    self_signing_key: Arc::new(v0.self_signing_key),
655                    // We migrate by pinning the current master key
656                    pinned_master_key: Arc::new(RwLock::new(v0.master_key)),
657                    previously_verified: Arc::new(false.into()),
658                })
659            }
660            Some(v) if v == "1" => {
661                let v1: OtherUserIdentityDataSerializerV1 = serde_json::from_value(value.other)?;
662                Ok(OtherUserIdentityData {
663                    user_id: v1.user_id,
664                    master_key: Arc::new(v1.master_key.clone()),
665                    self_signing_key: Arc::new(v1.self_signing_key),
666                    pinned_master_key: Arc::new(RwLock::new(v1.pinned_master_key)),
667                    // Put it to false. There will be a migration to mark all users as dirty, so we
668                    // will receive an update for the identity that will correctly set up the value.
669                    previously_verified: Arc::new(false.into()),
670                })
671            }
672            Some(v) if v == "2" => {
673                let v2: OtherUserIdentityDataSerializerV2 = serde_json::from_value(value.other)?;
674                Ok(OtherUserIdentityData {
675                    user_id: v2.user_id,
676                    master_key: Arc::new(v2.master_key.clone()),
677                    self_signing_key: Arc::new(v2.self_signing_key),
678                    pinned_master_key: Arc::new(RwLock::new(v2.pinned_master_key)),
679                    previously_verified: Arc::new(v2.previously_verified.into()),
680                })
681            }
682            _ => Err(serde::de::Error::custom(format!("Unsupported Version {:?}", value.version))),
683        }
684    }
685}
686
687impl From<OtherUserIdentityData> for OtherUserIdentityDataSerializer {
688    fn from(value: OtherUserIdentityData) -> Self {
689        let v2 = OtherUserIdentityDataSerializerV2 {
690            user_id: value.user_id.clone(),
691            master_key: value.master_key().to_owned(),
692            self_signing_key: value.self_signing_key().to_owned(),
693            pinned_master_key: value.pinned_master_key.read().clone(),
694            previously_verified: value.previously_verified.load(Ordering::SeqCst),
695        };
696        OtherUserIdentityDataSerializer {
697            version: Some("2".to_owned()),
698            other: serde_json::to_value(v2).unwrap(),
699        }
700    }
701}
702
703impl PartialEq for OtherUserIdentityData {
704    /// The `PartialEq` implementation compares several attributes, including
705    /// the user ID, key material, usage, and, notably, the signatures of
706    /// the master key.
707    ///
708    /// This approach contrasts with the `PartialEq` implementation of the
709    /// [`MasterPubkey`], and [`SelfSigningPubkey`] types,
710    /// where the signatures are disregarded. This distinction arises from our
711    /// treatment of identity as the combined representation of cross-signing
712    /// keys and the associated verification state.
713    ///
714    /// The verification state of an identity depends on the signatures of the
715    /// master key, requiring their inclusion in our `PartialEq` implementation.
716    fn eq(&self, other: &Self) -> bool {
717        self.user_id == other.user_id
718            && self.master_key == other.master_key
719            && self.self_signing_key == other.self_signing_key
720            && self.master_key.signatures() == other.master_key.signatures()
721    }
722}
723
724impl OtherUserIdentityData {
725    /// Create a new user identity with the given master and self signing key.
726    ///
727    /// # Arguments
728    ///
729    /// * `master_key` - The master key of the user identity.
730    ///
731    /// * `self signing key` - The self signing key of user identity.
732    ///
733    /// Returns a `SignatureError` if the self signing key fails to be correctly
734    /// verified by the given master key.
735    pub(crate) fn new(
736        master_key: MasterPubkey,
737        self_signing_key: SelfSigningPubkey,
738    ) -> Result<Self, SignatureError> {
739        master_key.verify_subkey(&self_signing_key)?;
740
741        Ok(Self {
742            user_id: master_key.user_id().into(),
743            master_key: master_key.clone().into(),
744            self_signing_key: self_signing_key.into(),
745            pinned_master_key: RwLock::new(master_key).into(),
746            previously_verified: Arc::new(false.into()),
747        })
748    }
749
750    #[cfg(test)]
751    pub(crate) async fn from_private(identity: &crate::olm::PrivateCrossSigningIdentity) -> Self {
752        let master_key = identity.master_key.lock().await.as_ref().unwrap().public_key().clone();
753        let self_signing_key =
754            identity.self_signing_key.lock().await.as_ref().unwrap().public_key().clone().into();
755
756        Self {
757            user_id: identity.user_id().into(),
758            master_key: Arc::new(master_key.clone()),
759            self_signing_key,
760            pinned_master_key: Arc::new(RwLock::new(master_key.clone())),
761            previously_verified: Arc::new(false.into()),
762        }
763    }
764
765    /// Get the user id of this identity.
766    pub fn user_id(&self) -> &UserId {
767        &self.user_id
768    }
769
770    /// Get the public master key of the identity.
771    pub fn master_key(&self) -> &MasterPubkey {
772        &self.master_key
773    }
774
775    /// Get the public self-signing key of the identity.
776    pub fn self_signing_key(&self) -> &SelfSigningPubkey {
777        &self.self_signing_key
778    }
779
780    /// Remember this identity, ensuring it does not result in a pin violation.
781    ///
782    /// When we first see a user, we assume their cryptographic identity has not
783    /// been tampered with by the homeserver or another entity with
784    /// man-in-the-middle capabilities. We remember this identity and call this
785    /// action "pinning".
786    ///
787    /// If the identity presented for the user changes later on, the newly
788    /// presented identity is considered to be in "pin violation". This
789    /// method explicitly accepts the new identity, allowing it to replace
790    /// the previously pinned one and bringing it out of pin violation.
791    ///
792    /// UIs should display a warning to the user when encountering an identity
793    /// which is not verified and is in pin violation. See
794    /// [`OtherUserIdentity::identity_needs_user_approval`].
795    pub(crate) fn pin(&self) {
796        let mut m = self.pinned_master_key.write();
797        *m = self.master_key.as_ref().clone()
798    }
799
800    /// Remember that this identity used to be verified at some point.
801    pub(crate) fn mark_as_previously_verified(&self) {
802        self.previously_verified.store(true, Ordering::SeqCst)
803    }
804
805    /// True if we verified this identity (with any own identity, at any
806    /// point).
807    ///
808    /// To set this latch back to false, call
809    /// [`OtherUserIdentityData::withdraw_verification()`].
810    pub fn was_previously_verified(&self) -> bool {
811        self.previously_verified.load(Ordering::SeqCst)
812    }
813
814    /// Remove the requirement for this identity to be verified.
815    ///
816    /// If an identity was previously verified and is not anymore it will be
817    /// reported to the user. In order to remove this notice users have to
818    /// verify again or to withdraw the verification requirement.
819    pub fn withdraw_verification(&self) {
820        // We also pin when we withdraw, since withdrawing implicitly acknowledges
821        // the identity change
822        self.pin();
823        self.previously_verified.store(false, Ordering::SeqCst)
824    }
825
826    /// Returns true if the identity has changed since we last pinned it.
827    ///
828    /// Key pinning acts as a trust on first use mechanism: the first time an
829    /// identity is known for a user it will be pinned.
830    ///
831    /// For future interaction with a user, the identity is expected to be the
832    /// one that was pinned. In case of identity change the UI client should
833    /// receive reports of pinning violation and decide to act accordingly:
834    /// accept and pin the new identity, perform a verification, or
835    /// stop communications.
836    pub(crate) fn has_pin_violation(&self) -> bool {
837        let pinned_master_key = self.pinned_master_key.read();
838        pinned_master_key.get_first_key() != self.master_key().get_first_key()
839    }
840
841    /// Update the identity with a new master key and self signing key.
842    ///
843    /// # Arguments
844    ///
845    /// * `master_key` - The new master key of the user identity.
846    ///
847    /// * `self_signing_key` - The new self signing key of user identity.
848    ///
849    /// * `maybe_verified_own_user_signing_key` - Our own user_signing_key if it
850    ///   is verified to check the identity trust status after update.
851    ///
852    /// Returns a `SignatureError` if we failed to update the identity.
853    /// Otherwise, returns `true` if there was a change to the identity and
854    /// `false` if the identity is unchanged.
855    pub(crate) fn update(
856        &mut self,
857        master_key: MasterPubkey,
858        self_signing_key: SelfSigningPubkey,
859        maybe_verified_own_user_signing_key: Option<&UserSigningPubkey>,
860    ) -> Result<bool, SignatureError> {
861        master_key.verify_subkey(&self_signing_key)?;
862
863        // We update the identity with the new master and self signing key, but we keep
864        // the previous pinned master key.
865        // This identity will have a pin violation until the new master key is pinned
866        // (see `has_pin_violation()`).
867        let pinned_master_key = self.pinned_master_key.read().clone();
868
869        // Check if the new master_key is signed by our own **verified**
870        // user_signing_key. If the identity was verified we remember it.
871        let updated_is_verified =
872            maybe_verified_own_user_signing_key.is_some_and(|own_user_signing_key| {
873                own_user_signing_key.verify_master_key(&master_key).is_ok()
874            });
875
876        let new = Self {
877            user_id: master_key.user_id().into(),
878            master_key: master_key.clone().into(),
879            self_signing_key: self_signing_key.into(),
880            pinned_master_key: RwLock::new(pinned_master_key).into(),
881            previously_verified: Arc::new(
882                (self.was_previously_verified() || updated_is_verified).into(),
883            ),
884        };
885        let changed = new != *self;
886
887        *self = new;
888        Ok(changed)
889    }
890
891    /// Check if the given device has been signed by this identity.
892    ///
893    /// The user_id of the user identity and the user_id of the device need to
894    /// match for the signature check to succeed as we don't trust users to sign
895    /// devices of other users.
896    ///
897    /// # Arguments
898    ///
899    /// * `device` - The device that should be checked for a valid signature.
900    ///
901    /// Returns `true` if the signature check succeeded, otherwise `false`.
902    pub(crate) fn is_device_signed(&self, device: &DeviceData) -> bool {
903        self.user_id() == device.user_id() && self.self_signing_key.verify_device(device).is_ok()
904    }
905}
906
907/// Struct representing a cross signing identity of our own user.
908///
909/// This is the user identity of our own user. This user identity will contain a
910/// master key, self signing key as well as a user signing key.
911///
912/// This identity can verify other identities as well as devices belonging to
913/// the identity.
914#[derive(Debug, Clone, Serialize, Deserialize)]
915pub struct OwnUserIdentityData {
916    user_id: OwnedUserId,
917    master_key: Arc<MasterPubkey>,
918    self_signing_key: Arc<SelfSigningPubkey>,
919    user_signing_key: Arc<UserSigningPubkey>,
920    #[serde(deserialize_with = "deserialize_own_user_identity_data_verified")]
921    verified: Arc<RwLock<OwnUserIdentityVerifiedState>>,
922}
923
924#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
925enum OwnUserIdentityVerifiedState {
926    /// We have never verified our own identity
927    #[default]
928    NeverVerified,
929
930    /// We previously verified this identity, but it has changed.
931    #[serde(alias = "PreviouslyVerifiedButNoLonger")]
932    VerificationViolation,
933
934    /// We have verified the current identity.
935    Verified,
936}
937
938impl PartialEq for OwnUserIdentityData {
939    /// The `PartialEq` implementation compares several attributes, including
940    /// the user ID, key material, usage, and, notably, the signatures of
941    /// the master key.
942    ///
943    /// This approach contrasts with the `PartialEq` implementation of the
944    /// [`MasterPubkey`], [`SelfSigningPubkey`] and [`UserSigningPubkey`] types,
945    /// where the signatures are disregarded. This distinction arises from our
946    /// treatment of identity as the combined representation of cross-signing
947    /// keys and the associated verification state.
948    ///
949    /// The verification state of an identity depends on the signatures of the
950    /// master key, requiring their inclusion in our `PartialEq` implementation.
951    fn eq(&self, other: &Self) -> bool {
952        self.user_id == other.user_id
953            && self.master_key == other.master_key
954            && self.self_signing_key == other.self_signing_key
955            && self.user_signing_key == other.user_signing_key
956            && *self.verified.read() == *other.verified.read()
957            && self.master_key.signatures() == other.master_key.signatures()
958    }
959}
960
961impl OwnUserIdentityData {
962    /// Create a new own user identity with the given master, self signing, and
963    /// user signing key.
964    ///
965    /// # Arguments
966    ///
967    /// * `master_key` - The master key of the user identity.
968    ///
969    /// * `self_signing_key` - The self signing key of user identity.
970    ///
971    /// * `user_signing_key` - The user signing key of user identity.
972    ///
973    /// Returns a `SignatureError` if the self signing key fails to be correctly
974    /// verified by the given master key.
975    pub(crate) fn new(
976        master_key: MasterPubkey,
977        self_signing_key: SelfSigningPubkey,
978        user_signing_key: UserSigningPubkey,
979    ) -> Result<Self, SignatureError> {
980        master_key.verify_subkey(&self_signing_key)?;
981        master_key.verify_subkey(&user_signing_key)?;
982
983        Ok(Self {
984            user_id: master_key.user_id().into(),
985            master_key: master_key.into(),
986            self_signing_key: self_signing_key.into(),
987            user_signing_key: user_signing_key.into(),
988            verified: Default::default(),
989        })
990    }
991
992    #[cfg(test)]
993    pub(crate) async fn from_private(identity: &crate::olm::PrivateCrossSigningIdentity) -> Self {
994        let master_key = identity.master_key.lock().await.as_ref().unwrap().public_key().clone();
995        let self_signing_key =
996            identity.self_signing_key.lock().await.as_ref().unwrap().public_key().clone();
997        let user_signing_key =
998            identity.user_signing_key.lock().await.as_ref().unwrap().public_key().clone();
999
1000        Self {
1001            user_id: identity.user_id().into(),
1002            master_key: master_key.into(),
1003            self_signing_key: self_signing_key.into(),
1004            user_signing_key: user_signing_key.into(),
1005            verified: Default::default(),
1006        }
1007    }
1008
1009    /// Get the user id of this identity.
1010    pub fn user_id(&self) -> &UserId {
1011        &self.user_id
1012    }
1013
1014    /// Get the public master key of the identity.
1015    pub fn master_key(&self) -> &MasterPubkey {
1016        &self.master_key
1017    }
1018
1019    /// Get the public self-signing key of the identity.
1020    pub fn self_signing_key(&self) -> &SelfSigningPubkey {
1021        &self.self_signing_key
1022    }
1023
1024    /// Get the public user-signing key of the identity.
1025    pub fn user_signing_key(&self) -> &UserSigningPubkey {
1026        &self.user_signing_key
1027    }
1028
1029    /// Check if the given user identity has been verified.
1030    ///
1031    /// The identity of another user is verified iff our own identity is
1032    /// verified and if our own identity has signed the other user's
1033    /// identity.
1034    ///
1035    /// # Arguments
1036    ///
1037    /// * `identity` - The identity of another user which we want to check has
1038    ///   been verified.
1039    pub fn is_identity_verified(&self, identity: &OtherUserIdentityData) -> bool {
1040        self.is_verified() && self.is_identity_signed(identity)
1041    }
1042
1043    /// Check if the given identity has been signed by this identity.
1044    ///
1045    /// Note that, normally, you'll also want to check that the
1046    /// `OwnUserIdentityData` has been verified; for that,
1047    /// [`Self::is_identity_verified`] is more appropriate.
1048    ///
1049    /// # Arguments
1050    ///
1051    /// * `identity` - The identity of another user that we want to check if it
1052    ///   has been signed.
1053    ///
1054    /// Returns `true` if the signature check succeeded, otherwise `false`.
1055    pub(crate) fn is_identity_signed(&self, identity: &OtherUserIdentityData) -> bool {
1056        self.user_signing_key.verify_master_key(&identity.master_key).is_ok()
1057    }
1058
1059    /// Check if the given device has been signed by this identity.
1060    ///
1061    /// Only devices of our own user should be checked with this method. If a
1062    /// device of a different user is given, the signature check will always
1063    /// fail even if a valid signature exists.
1064    ///
1065    /// # Arguments
1066    ///
1067    /// * `device` - The device that should be checked for a valid signature.
1068    ///
1069    /// Returns `true` if the signature check succeeded, otherwise `false`.
1070    pub(crate) fn is_device_signed(&self, device: &DeviceData) -> bool {
1071        self.user_id() == device.user_id() && self.self_signing_key.verify_device(device).is_ok()
1072    }
1073
1074    /// Mark our identity as verified.
1075    pub fn mark_as_verified(&self) {
1076        *self.verified.write() = OwnUserIdentityVerifiedState::Verified;
1077    }
1078
1079    /// Mark our identity as unverified.
1080    pub(crate) fn mark_as_unverified(&self) {
1081        let mut guard = self.verified.write();
1082        if *guard == OwnUserIdentityVerifiedState::Verified {
1083            *guard = OwnUserIdentityVerifiedState::VerificationViolation;
1084        }
1085    }
1086
1087    /// Check if our identity is verified.
1088    pub fn is_verified(&self) -> bool {
1089        *self.verified.read() == OwnUserIdentityVerifiedState::Verified
1090    }
1091
1092    /// True if we verified our own identity at some point in the past.
1093    ///
1094    /// To reset this latch back to `false`, one must call
1095    /// [`OwnUserIdentityData::withdraw_verification()`].
1096    pub fn was_previously_verified(&self) -> bool {
1097        matches!(
1098            *self.verified.read(),
1099            OwnUserIdentityVerifiedState::Verified
1100                | OwnUserIdentityVerifiedState::VerificationViolation
1101        )
1102    }
1103
1104    /// Remove the requirement for this identity to be verified.
1105    ///
1106    /// If an identity was previously verified and is not any more it will be
1107    /// reported to the user. In order to remove this notice users have to
1108    /// verify again or to withdraw the verification requirement.
1109    pub fn withdraw_verification(&self) {
1110        let mut guard = self.verified.write();
1111        if *guard == OwnUserIdentityVerifiedState::VerificationViolation {
1112            *guard = OwnUserIdentityVerifiedState::NeverVerified;
1113        }
1114    }
1115
1116    /// Was this identity previously verified, and is no longer?
1117    ///
1118    /// Such a violation should be reported to the local user by the
1119    /// application, and resolved by
1120    ///
1121    /// - Verifying the new identity with
1122    ///   [`OwnUserIdentity::request_verification`]
1123    /// - Or by withdrawing the verification requirement
1124    ///   [`OwnUserIdentity::withdraw_verification`].
1125    pub fn has_verification_violation(&self) -> bool {
1126        *self.verified.read() == OwnUserIdentityVerifiedState::VerificationViolation
1127    }
1128
1129    /// Update the identity with a new master key and self signing key.
1130    ///
1131    /// Note: This will reset the verification state if the master keys differ.
1132    ///
1133    /// # Arguments
1134    ///
1135    /// * `master_key` - The new master key of the user identity.
1136    ///
1137    /// * `self_signing_key` - The new self signing key of user identity.
1138    ///
1139    /// * `user_signing_key` - The new user signing key of user identity.
1140    ///
1141    /// Returns a `SignatureError` if we failed to update the identity.
1142    /// Otherwise, returns `true` if there was a change to the identity and
1143    /// `false` if the identity is unchanged.
1144    pub(crate) fn update(
1145        &mut self,
1146        master_key: MasterPubkey,
1147        self_signing_key: SelfSigningPubkey,
1148        user_signing_key: UserSigningPubkey,
1149    ) -> Result<bool, SignatureError> {
1150        master_key.verify_subkey(&self_signing_key)?;
1151        master_key.verify_subkey(&user_signing_key)?;
1152
1153        let old = self.clone();
1154
1155        self.self_signing_key = self_signing_key.into();
1156        self.user_signing_key = user_signing_key.into();
1157
1158        if self.master_key.as_ref() != &master_key {
1159            self.mark_as_unverified()
1160        }
1161
1162        self.master_key = master_key.into();
1163
1164        Ok(old != *self)
1165    }
1166
1167    fn filter_devices_to_request(
1168        &self,
1169        devices: HashMap<OwnedDeviceId, DeviceData>,
1170        own_device_id: &DeviceId,
1171    ) -> Vec<OwnedDeviceId> {
1172        devices
1173            .into_iter()
1174            .filter_map(|(device_id, device)| {
1175                (device_id != own_device_id && self.is_device_signed(&device)).then_some(device_id)
1176            })
1177            .collect()
1178    }
1179}
1180
1181/// Custom deserializer for [`OwnUserIdentityData::verified`].
1182///
1183/// This used to be a bool, so we need to handle that.
1184fn deserialize_own_user_identity_data_verified<'de, D>(
1185    de: D,
1186) -> Result<Arc<RwLock<OwnUserIdentityVerifiedState>>, D::Error>
1187where
1188    D: Deserializer<'de>,
1189{
1190    #[derive(Deserialize)]
1191    #[serde(untagged)]
1192    enum VerifiedStateOrBool {
1193        VerifiedState(OwnUserIdentityVerifiedState),
1194        Bool(bool),
1195    }
1196
1197    let verified_state = match VerifiedStateOrBool::deserialize(de)? {
1198        VerifiedStateOrBool::Bool(true) => OwnUserIdentityVerifiedState::Verified,
1199        VerifiedStateOrBool::Bool(false) => OwnUserIdentityVerifiedState::NeverVerified,
1200        VerifiedStateOrBool::VerifiedState(x) => x,
1201    };
1202
1203    Ok(Arc::new(RwLock::new(verified_state)))
1204}
1205
1206/// Testing Facilities
1207#[cfg(any(test, feature = "testing"))]
1208#[allow(dead_code)]
1209pub(crate) mod testing {
1210    use matrix_sdk_test::ruma_response_from_json;
1211    use ruma::{
1212        UserId,
1213        api::client::keys::{
1214            get_keys::v3::Response as KeyQueryResponse,
1215            upload_signatures::v3::Request as SignatureUploadRequest,
1216        },
1217        user_id,
1218    };
1219    use serde_json::json;
1220
1221    use super::{OtherUserIdentityData, OwnUserIdentity, OwnUserIdentityData};
1222    #[cfg(test)]
1223    use crate::{identities::manager::testing::other_user_id, olm::PrivateCrossSigningIdentity};
1224    use crate::{
1225        identities::{
1226            DeviceData,
1227            manager::testing::{other_key_query, own_key_query},
1228        },
1229        store::Store,
1230        types::CrossSigningKey,
1231        verification::VerificationMachine,
1232    };
1233
1234    /// Generate test devices from KeyQueryResponse
1235    pub fn device(response: &KeyQueryResponse) -> (DeviceData, DeviceData) {
1236        let mut devices = response.device_keys.values().next().unwrap().values();
1237        let first =
1238            DeviceData::try_from(&devices.next().unwrap().deserialize_as().unwrap()).unwrap();
1239        let second =
1240            DeviceData::try_from(&devices.next().unwrap().deserialize_as().unwrap()).unwrap();
1241        (first, second)
1242    }
1243
1244    /// Generate [`OwnUserIdentityData`] from a [`KeyQueryResponse`] for testing
1245    pub fn own_identity(response: &KeyQueryResponse) -> OwnUserIdentityData {
1246        let user_id = user_id!("@example:localhost");
1247
1248        let master_key: CrossSigningKey =
1249            response.master_keys.get(user_id).unwrap().deserialize_as().unwrap();
1250        let user_signing: CrossSigningKey =
1251            response.user_signing_keys.get(user_id).unwrap().deserialize_as().unwrap();
1252        let self_signing: CrossSigningKey =
1253            response.self_signing_keys.get(user_id).unwrap().deserialize_as().unwrap();
1254
1255        OwnUserIdentityData::new(
1256            master_key.try_into().unwrap(),
1257            self_signing.try_into().unwrap(),
1258            user_signing.try_into().unwrap(),
1259        )
1260        .unwrap()
1261    }
1262
1263    /// Generate default own identity for tests
1264    pub fn get_own_identity() -> OwnUserIdentityData {
1265        own_identity(&own_key_query())
1266    }
1267
1268    pub fn own_identity_wrapped(
1269        inner: OwnUserIdentityData,
1270        verification_machine: VerificationMachine,
1271        store: Store,
1272    ) -> OwnUserIdentity {
1273        OwnUserIdentity { inner, verification_machine, store }
1274    }
1275
1276    /// Generate default other "own" identity for tests
1277    #[cfg(test)]
1278    pub async fn get_other_own_identity() -> OwnUserIdentityData {
1279        let private_identity = PrivateCrossSigningIdentity::new(other_user_id().into());
1280        OwnUserIdentityData::from_private(&private_identity).await
1281    }
1282
1283    /// Generate default other identify for tests
1284    pub fn get_other_identity() -> OtherUserIdentityData {
1285        let user_id = user_id!("@example2:localhost");
1286        let response = other_key_query();
1287
1288        let master_key: CrossSigningKey =
1289            response.master_keys.get(user_id).unwrap().deserialize_as().unwrap();
1290        let self_signing: CrossSigningKey =
1291            response.self_signing_keys.get(user_id).unwrap().deserialize_as().unwrap();
1292
1293        OtherUserIdentityData::new(master_key.try_into().unwrap(), self_signing.try_into().unwrap())
1294            .unwrap()
1295    }
1296
1297    /// When we want to test identities that are verified, we need to simulate
1298    /// the verification process. This function supports that by simulating
1299    /// what happens when a successful verification dance happens and
1300    /// providing the /keys/query response we would get when that happened.
1301    ///
1302    /// signature_upload_request will be the result of calling
1303    /// [`super::OtherUserIdentity::verify`].
1304    ///
1305    /// # Example
1306    ///
1307    /// ```ignore
1308    /// let signature_upload_request = their_identity.verify().await.unwrap();
1309    ///
1310    /// let msk_json = json!({
1311    ///     "their_user_id": {
1312    ///         "keys": { "ed25519:blah": "blah" }
1313    ///         "signatures": {
1314    ///             "their_user_id": { "ed25519:blah": "blah", ... }
1315    ///         }
1316    ///         "usage": [ "master" ],
1317    ///         "user_id": "their_user_id"
1318    ///     }
1319    /// });
1320    ///
1321    /// let ssk_json = json!({
1322    ///     "their_user_id": {
1323    ///         "keys": { "ed25519:blah": "blah" },
1324    ///         "signatures": {
1325    ///             "their_user_id": { "ed25519:blah": "blah" }
1326    ///         },
1327    ///         "usage": [ "self_signing" ],
1328    ///         "user_id": "their_user_id"
1329    ///     }
1330    /// })
1331    ///
1332    /// let response = simulate_key_query_response_for_verification(
1333    ///     signature_upload_request,
1334    ///     my_identity,
1335    ///     my_user_id,
1336    ///     their_user_id,
1337    ///     msk_json,
1338    ///     ssk_json
1339    /// ).await;
1340    ///
1341    /// olm_machine
1342    ///     .mark_request_as_sent(
1343    ///         &TransactionId::new(),
1344    ///         crate::IncomingResponse::KeysQuery(&kq_response),
1345    ///     )
1346    ///     .await
1347    ///     .unwrap();
1348    /// ```
1349    pub fn simulate_key_query_response_for_verification(
1350        signature_upload_request: SignatureUploadRequest,
1351        my_identity: OwnUserIdentity,
1352        my_user_id: &UserId,
1353        their_user_id: &UserId,
1354        msk_json: serde_json::Value,
1355        ssk_json: serde_json::Value,
1356    ) -> KeyQueryResponse {
1357        // Find the signed key inside the SignatureUploadRequest
1358        let cross_signing_key: CrossSigningKey = serde_json::from_str(
1359            signature_upload_request
1360                .signed_keys
1361                .get(their_user_id)
1362                .expect("Signature upload request should contain a key for their user ID")
1363                .iter()
1364                .next()
1365                .expect("There should be a key in the signature upload request")
1366                .1
1367                .get(),
1368        )
1369        .expect("Should not fail to deserialize the key");
1370
1371        // Find their master key that we want to update inside their msk JSON
1372        let mut their_msk: CrossSigningKey = serde_json::from_value(
1373            msk_json.get(their_user_id.as_str()).expect("msk should contain their user ID").clone(),
1374        )
1375        .expect("Should not fail to deserialize msk");
1376
1377        // Find our own user signing key
1378        let my_user_signing_key_id = my_identity
1379            .user_signing_key()
1380            .keys()
1381            .iter()
1382            .next()
1383            .expect("There should be a user signing key")
1384            .0;
1385
1386        // Add the signature from the SignatureUploadRequest to their master key, under
1387        // our user ID
1388        their_msk.signatures.add_signature(
1389            my_user_id.to_owned(),
1390            my_user_signing_key_id.to_owned(),
1391            cross_signing_key
1392                .signatures
1393                .get_signature(my_user_id, my_user_signing_key_id)
1394                .expect("There should be a signature for our user"),
1395        );
1396
1397        // Create a JSON response as if the verification has happened
1398        ruma_response_from_json(&json!({
1399            "device_keys": {}, // Don't need devices here, even though they would exist
1400            "failures": {},
1401            "master_keys": {
1402                their_user_id: their_msk,
1403            },
1404            "self_signing_keys": ssk_json,
1405        }))
1406    }
1407}
1408
1409#[cfg(test)]
1410pub(crate) mod tests {
1411    use std::{collections::HashMap, sync::Arc};
1412
1413    use assert_matches::assert_matches;
1414    use matrix_sdk_test::{async_test, test_json};
1415    use ruma::{TransactionId, device_id, user_id};
1416    use serde_json::{Value, json};
1417    use tokio::sync::Mutex;
1418
1419    use super::{
1420        OtherUserIdentityDataSerializerV2, OwnUserIdentityData, OwnUserIdentityVerifiedState,
1421        UserIdentityData,
1422        testing::{device, get_other_identity, get_own_identity},
1423    };
1424    use crate::{
1425        CrossSigningKeyExport, OlmMachine, OtherUserIdentity, OtherUserIdentityData,
1426        identities::{
1427            Device,
1428            manager::testing::own_key_query,
1429            user::{
1430                OtherUserIdentityDataSerializer,
1431                testing::simulate_key_query_response_for_verification,
1432            },
1433        },
1434        olm::{Account, PrivateCrossSigningIdentity},
1435        store::{CryptoStoreWrapper, MemoryStore},
1436        types::{CrossSigningKey, MasterPubkey, SelfSigningPubkey, Signatures, UserSigningPubkey},
1437        verification::VerificationMachine,
1438    };
1439
1440    #[test]
1441    fn own_identity_create() {
1442        let user_id = user_id!("@example:localhost");
1443        let response = own_key_query();
1444
1445        let master_key: CrossSigningKey =
1446            response.master_keys.get(user_id).unwrap().deserialize_as().unwrap();
1447        let user_signing: CrossSigningKey =
1448            response.user_signing_keys.get(user_id).unwrap().deserialize_as().unwrap();
1449        let self_signing: CrossSigningKey =
1450            response.self_signing_keys.get(user_id).unwrap().deserialize_as().unwrap();
1451
1452        OwnUserIdentityData::new(
1453            master_key.try_into().unwrap(),
1454            self_signing.try_into().unwrap(),
1455            user_signing.try_into().unwrap(),
1456        )
1457        .unwrap();
1458    }
1459
1460    #[test]
1461    fn own_identity_partial_equality() {
1462        let user_id = user_id!("@example:localhost");
1463        let response = own_key_query();
1464
1465        let master_key: CrossSigningKey =
1466            response.master_keys.get(user_id).unwrap().deserialize_as().unwrap();
1467        let user_signing: CrossSigningKey =
1468            response.user_signing_keys.get(user_id).unwrap().deserialize_as().unwrap();
1469        let self_signing: CrossSigningKey =
1470            response.self_signing_keys.get(user_id).unwrap().deserialize_as().unwrap();
1471
1472        let identity = OwnUserIdentityData::new(
1473            master_key.clone().try_into().unwrap(),
1474            self_signing.clone().try_into().unwrap(),
1475            user_signing.clone().try_into().unwrap(),
1476        )
1477        .unwrap();
1478
1479        let mut master_key_updated_signature = master_key;
1480        master_key_updated_signature.signatures = Signatures::new();
1481
1482        let updated_identity = OwnUserIdentityData::new(
1483            master_key_updated_signature.try_into().unwrap(),
1484            self_signing.try_into().unwrap(),
1485            user_signing.try_into().unwrap(),
1486        )
1487        .unwrap();
1488
1489        assert_ne!(identity, updated_identity);
1490        assert_eq!(identity.master_key(), updated_identity.master_key());
1491    }
1492
1493    #[test]
1494    fn other_identity_create() {
1495        get_other_identity();
1496    }
1497
1498    #[test]
1499    fn deserialization_migration_test() {
1500        let serialized_value = json!({
1501                "user_id":"@example2:localhost",
1502                "master_key":{
1503                   "user_id":"@example2:localhost",
1504                   "usage":[
1505                      "master"
1506                   ],
1507                   "keys":{
1508                      "ed25519:kC/HmRYw4HNqUp/i4BkwYENrf+hd9tvdB7A1YOf5+Do":"kC/HmRYw4HNqUp/i4BkwYENrf+hd9tvdB7A1YOf5+Do"
1509                   },
1510                   "signatures":{
1511                      "@example2:localhost":{
1512                         "ed25519:SKISMLNIMH":"KdUZqzt8VScGNtufuQ8lOf25byYLWIhmUYpPENdmM8nsldexD7vj+Sxoo7PknnTX/BL9h2N7uBq0JuykjunCAw"
1513                      }
1514                   }
1515                },
1516                "self_signing_key":{
1517                   "user_id":"@example2:localhost",
1518                   "usage":[
1519                      "self_signing"
1520                   ],
1521                   "keys":{
1522                      "ed25519:ZtFrSkJ1qB8Jph/ql9Eo/lKpIYCzwvKAKXfkaS4XZNc":"ZtFrSkJ1qB8Jph/ql9Eo/lKpIYCzwvKAKXfkaS4XZNc"
1523                   },
1524                   "signatures":{
1525                      "@example2:localhost":{
1526                         "ed25519:kC/HmRYw4HNqUp/i4BkwYENrf+hd9tvdB7A1YOf5+Do":"W/O8BnmiUETPpH02mwYaBgvvgF/atXnusmpSTJZeUSH/vHg66xiZOhveQDG4cwaW8iMa+t9N4h1DWnRoHB4mCQ"
1527                      }
1528                   }
1529                }
1530        });
1531        let migrated: OtherUserIdentityData = serde_json::from_value(serialized_value).unwrap();
1532
1533        let pinned_master_key = migrated.pinned_master_key.read();
1534        assert_eq!(*pinned_master_key, migrated.master_key().clone());
1535
1536        // Serialize back
1537        let value = serde_json::to_value(migrated.clone()).unwrap();
1538
1539        // Should be serialized with latest version
1540        let _: OtherUserIdentityDataSerializerV2 =
1541            serde_json::from_value(value.clone()).expect("Should deserialize as version 2");
1542
1543        let with_serializer: OtherUserIdentityDataSerializer =
1544            serde_json::from_value(value).unwrap();
1545        assert_eq!("2", with_serializer.version.unwrap());
1546    }
1547
1548    /// [`OwnUserIdentityData::verified`] was previously an AtomicBool. Check
1549    /// that we can deserialize boolean values.
1550    #[test]
1551    fn test_deserialize_own_user_identity_bool_verified() {
1552        let mut json = own_user_identity_data();
1553
1554        // Set `"verified": false`
1555        *json.get_mut("verified").unwrap() = false.into();
1556        let id: OwnUserIdentityData = serde_json::from_value(json.clone()).unwrap();
1557        assert_eq!(*id.verified.read(), OwnUserIdentityVerifiedState::NeverVerified);
1558
1559        // Tweak the json to have `"verified": true`, and repeat
1560        *json.get_mut("verified").unwrap() = true.into();
1561        let id: OwnUserIdentityData = serde_json::from_value(json.clone()).unwrap();
1562        assert_eq!(*id.verified.read(), OwnUserIdentityVerifiedState::Verified);
1563    }
1564
1565    #[test]
1566    fn test_own_user_identity_verified_state_verification_violation_deserializes() {
1567        // Given data containing verified: VerificationViolation
1568        let mut json = own_user_identity_data();
1569        *json.get_mut("verified").unwrap() = "VerificationViolation".into();
1570
1571        // When we deserialize
1572        let id: OwnUserIdentityData = serde_json::from_value(json.clone()).unwrap();
1573
1574        // Then the value is correctly populated
1575        assert_eq!(*id.verified.read(), OwnUserIdentityVerifiedState::VerificationViolation);
1576    }
1577
1578    #[test]
1579    fn test_own_user_identity_verified_state_previously_verified_deserializes() {
1580        // Given data containing verified: PreviouslyVerifiedButNoLonger
1581        let mut json = own_user_identity_data();
1582        *json.get_mut("verified").unwrap() = "PreviouslyVerifiedButNoLonger".into();
1583
1584        // When we deserialize
1585        let id: OwnUserIdentityData = serde_json::from_value(json.clone()).unwrap();
1586
1587        // Then the old value is re-interpreted as VerificationViolation
1588        assert_eq!(*id.verified.read(), OwnUserIdentityVerifiedState::VerificationViolation);
1589    }
1590
1591    #[test]
1592    fn own_identity_check_signatures() {
1593        let response = own_key_query();
1594        let identity = get_own_identity();
1595        let (first, second) = device(&response);
1596
1597        assert!(!identity.is_device_signed(&first));
1598        assert!(identity.is_device_signed(&second));
1599
1600        let account = Account::with_device_id(second.user_id(), second.device_id());
1601        let verification_machine = get_verification_machine(&account);
1602
1603        let first = Device {
1604            inner: first,
1605            verification_machine: verification_machine.clone(),
1606            own_identity: Some(identity.clone()),
1607            device_owner_identity: Some(UserIdentityData::Own(identity.clone())),
1608        };
1609
1610        let second = Device {
1611            inner: second,
1612            verification_machine,
1613            own_identity: Some(identity.clone()),
1614            device_owner_identity: Some(UserIdentityData::Own(identity.clone())),
1615        };
1616
1617        assert!(!second.is_locally_trusted());
1618        assert!(!second.is_cross_signing_trusted());
1619
1620        assert!(!first.is_locally_trusted());
1621        assert!(!first.is_cross_signing_trusted());
1622
1623        identity.mark_as_verified();
1624        assert!(second.is_verified());
1625        assert!(!first.is_verified());
1626    }
1627
1628    #[async_test]
1629    async fn test_own_device_with_private_identity() {
1630        let response = own_key_query();
1631        let (_, device) = device(&response);
1632
1633        let account = Account::with_device_id(device.user_id(), device.device_id());
1634        let verification_machine = get_verification_machine(&account);
1635        let public_identity = verification_machine.get_own_user_identity_data().await.unwrap();
1636
1637        let mut device = Device {
1638            inner: device,
1639            verification_machine: verification_machine.clone(),
1640            own_identity: Some(public_identity.clone()),
1641            device_owner_identity: Some(public_identity.clone().into()),
1642        };
1643
1644        assert!(!device.is_verified());
1645
1646        let mut device_keys = device.as_device_keys().to_owned();
1647
1648        let identity = verification_machine.store.private_identity.lock().await;
1649        identity.sign_device_keys(&mut device_keys).await.unwrap();
1650        device.inner.update_device(&device_keys).expect("Couldn't update newly signed device keys");
1651        assert!(device.is_verified());
1652    }
1653
1654    /// Test that `CrossSigningKey` instances without a correct `usage` cannot
1655    /// be deserialized into high-level structs representing the MSK, SSK
1656    /// and USK.
1657    #[test]
1658    fn cannot_instantiate_keys_with_incorrect_usage() {
1659        let user_id = user_id!("@example:localhost");
1660        let response = own_key_query();
1661
1662        let master_key = response.master_keys.get(user_id).unwrap();
1663        let mut master_key_json: Value = master_key.deserialize_as().unwrap();
1664        let self_signing_key = response.self_signing_keys.get(user_id).unwrap();
1665        let mut self_signing_key_json: Value = self_signing_key.deserialize_as().unwrap();
1666        let user_signing_key = response.user_signing_keys.get(user_id).unwrap();
1667        let mut user_signing_key_json: Value = user_signing_key.deserialize_as().unwrap();
1668
1669        // Delete the usages.
1670        let usage = master_key_json.get_mut("usage").unwrap();
1671        *usage = json!([]);
1672        let usage = self_signing_key_json.get_mut("usage").unwrap();
1673        *usage = json!([]);
1674        let usage = user_signing_key_json.get_mut("usage").unwrap();
1675        *usage = json!([]);
1676
1677        // It should now be impossible to deserialize the keys into their corresponding
1678        // high-level cross-signing key structs.
1679        assert_matches!(serde_json::from_value::<MasterPubkey>(master_key_json.clone()), Err(_));
1680        assert_matches!(
1681            serde_json::from_value::<SelfSigningPubkey>(self_signing_key_json.clone()),
1682            Err(_)
1683        );
1684        assert_matches!(
1685            serde_json::from_value::<UserSigningPubkey>(user_signing_key_json.clone()),
1686            Err(_)
1687        );
1688
1689        // Add additional usages.
1690        let usage = master_key_json.get_mut("usage").unwrap();
1691        *usage = json!(["master", "user_signing"]);
1692        let usage = self_signing_key_json.get_mut("usage").unwrap();
1693        *usage = json!(["self_signing", "user_signing"]);
1694        let usage = user_signing_key_json.get_mut("usage").unwrap();
1695        *usage = json!(["user_signing", "self_signing"]);
1696
1697        // It should still be impossible to deserialize the keys into their
1698        // corresponding high-level cross-signing key structs.
1699        assert_matches!(serde_json::from_value::<MasterPubkey>(master_key_json.clone()), Err(_));
1700        assert_matches!(
1701            serde_json::from_value::<SelfSigningPubkey>(self_signing_key_json.clone()),
1702            Err(_)
1703        );
1704        assert_matches!(
1705            serde_json::from_value::<UserSigningPubkey>(user_signing_key_json.clone()),
1706            Err(_)
1707        );
1708    }
1709
1710    #[test]
1711    fn filter_devices_to_request() {
1712        let response = own_key_query();
1713        let identity = get_own_identity();
1714        let (first, second) = device(&response);
1715
1716        let second_device_id = second.device_id().to_owned();
1717        let unknown_device_id = device_id!("UNKNOWN");
1718
1719        let devices = HashMap::from([
1720            (first.device_id().to_owned(), first),
1721            (second.device_id().to_owned(), second),
1722        ]);
1723
1724        // Own device and devices not verified are filtered out.
1725        assert_eq!(identity.filter_devices_to_request(devices.clone(), &second_device_id).len(), 0);
1726        // Signed devices that are not our own are kept.
1727        assert_eq!(
1728            identity.filter_devices_to_request(devices, unknown_device_id),
1729            [second_device_id]
1730        );
1731    }
1732
1733    #[async_test]
1734    async fn test_resolve_identity_pin_violation_with_verification() {
1735        use test_json::keys_query_sets::IdentityChangeDataSet as DataSet;
1736
1737        let my_user_id = user_id!("@me:localhost");
1738        let machine = OlmMachine::new(my_user_id, device_id!("ABCDEFGH")).await;
1739        machine.bootstrap_cross_signing(false).await.unwrap();
1740
1741        let my_id = machine.get_identity(my_user_id, None).await.unwrap().unwrap().own().unwrap();
1742
1743        let keys_query = DataSet::key_query_with_identity_a();
1744        let txn_id = TransactionId::new();
1745        machine.mark_request_as_sent(&txn_id, &keys_query).await.unwrap();
1746
1747        // Simulate an identity change
1748        let keys_query = DataSet::key_query_with_identity_b();
1749        let txn_id = TransactionId::new();
1750        machine.mark_request_as_sent(&txn_id, &keys_query).await.unwrap();
1751
1752        let other_user_id = DataSet::user_id();
1753
1754        let other_identity =
1755            machine.get_identity(other_user_id, None).await.unwrap().unwrap().other().unwrap();
1756
1757        // The identity should need user approval now
1758        assert!(other_identity.identity_needs_user_approval());
1759
1760        // Manually verify for the purpose of this test
1761        let sig_upload = other_identity.verify().await.unwrap();
1762
1763        let kq_response = simulate_key_query_response_for_verification(
1764            sig_upload,
1765            my_id,
1766            my_user_id,
1767            other_user_id,
1768            DataSet::master_signing_keys_b(),
1769            DataSet::self_signing_keys_b(),
1770        );
1771        machine.mark_request_as_sent(&TransactionId::new(), &kq_response).await.unwrap();
1772
1773        // The identity should not need any user approval now
1774        let other_identity =
1775            machine.get_identity(other_user_id, None).await.unwrap().unwrap().other().unwrap();
1776        assert!(!other_identity.identity_needs_user_approval());
1777        // But there is still a pin violation
1778        assert!(other_identity.inner.has_pin_violation());
1779    }
1780
1781    #[async_test]
1782    async fn test_resolve_identity_pin_violation_with_withdraw_verification() {
1783        use test_json::keys_query_sets::IdentityChangeDataSet as DataSet;
1784
1785        let my_user_id = user_id!("@me:localhost");
1786        let machine = OlmMachine::new(my_user_id, device_id!("ABCDEFGH")).await;
1787        machine.bootstrap_cross_signing(false).await.unwrap();
1788
1789        let keys_query = DataSet::key_query_with_identity_a();
1790        let txn_id = TransactionId::new();
1791        machine.mark_request_as_sent(&txn_id, &keys_query).await.unwrap();
1792
1793        // Simulate an identity change
1794        let keys_query = DataSet::key_query_with_identity_b();
1795        let txn_id = TransactionId::new();
1796        machine.mark_request_as_sent(&txn_id, &keys_query).await.unwrap();
1797
1798        let other_user_id = DataSet::user_id();
1799
1800        let other_identity =
1801            machine.get_identity(other_user_id, None).await.unwrap().unwrap().other().unwrap();
1802
1803        // For testing purpose mark it as previously verified
1804        other_identity.mark_as_previously_verified().await.unwrap();
1805
1806        // The identity should need user approval now
1807        assert!(other_identity.identity_needs_user_approval());
1808
1809        // We withdraw verification
1810        other_identity.withdraw_verification().await.unwrap();
1811
1812        // The identity should not need any user approval now
1813        let other_identity =
1814            machine.get_identity(other_user_id, None).await.unwrap().unwrap().other().unwrap();
1815        assert!(!other_identity.identity_needs_user_approval());
1816        // And should not have a pin violation
1817        assert!(!other_identity.inner.has_pin_violation());
1818    }
1819
1820    #[async_test]
1821    async fn test_resolve_identity_verification_violation_with_withdraw() {
1822        use test_json::keys_query_sets::VerificationViolationTestData as DataSet;
1823
1824        let machine = OlmMachine::new(DataSet::own_id(), device_id!("LOCAL")).await;
1825
1826        let keys_query = DataSet::own_keys_query_response_1();
1827        let txn_id = TransactionId::new();
1828        machine.mark_request_as_sent(&txn_id, &keys_query).await.unwrap();
1829
1830        machine
1831            .import_cross_signing_keys(CrossSigningKeyExport {
1832                master_key: DataSet::MASTER_KEY_PRIVATE_EXPORT.to_owned().into(),
1833                self_signing_key: DataSet::SELF_SIGNING_KEY_PRIVATE_EXPORT.to_owned().into(),
1834                user_signing_key: DataSet::USER_SIGNING_KEY_PRIVATE_EXPORT.to_owned().into(),
1835            })
1836            .await
1837            .unwrap();
1838
1839        let keys_query = DataSet::bob_keys_query_response_rotated();
1840        let txn_id = TransactionId::new();
1841        machine.mark_request_as_sent(&txn_id, &keys_query).await.unwrap();
1842
1843        let bob_identity =
1844            machine.get_identity(DataSet::bob_id(), None).await.unwrap().unwrap().other().unwrap();
1845
1846        // For testing purpose mark it as previously verified
1847        bob_identity.mark_as_previously_verified().await.unwrap();
1848
1849        assert!(bob_identity.has_verification_violation());
1850
1851        // withdraw
1852        bob_identity.withdraw_verification().await.unwrap();
1853
1854        let bob_identity =
1855            machine.get_identity(DataSet::bob_id(), None).await.unwrap().unwrap().other().unwrap();
1856
1857        assert!(!bob_identity.has_verification_violation());
1858    }
1859
1860    #[async_test]
1861    async fn test_reset_own_keys_creates_verification_violation() {
1862        use test_json::keys_query_sets::VerificationViolationTestData as DataSet;
1863
1864        let machine = OlmMachine::new(DataSet::own_id(), device_id!("LOCAL")).await;
1865
1866        let keys_query = DataSet::own_keys_query_response_1();
1867        let txn_id = TransactionId::new();
1868        machine.mark_request_as_sent(&txn_id, &keys_query).await.unwrap();
1869
1870        machine
1871            .import_cross_signing_keys(CrossSigningKeyExport {
1872                master_key: DataSet::MASTER_KEY_PRIVATE_EXPORT.to_owned().into(),
1873                self_signing_key: DataSet::SELF_SIGNING_KEY_PRIVATE_EXPORT.to_owned().into(),
1874                user_signing_key: DataSet::USER_SIGNING_KEY_PRIVATE_EXPORT.to_owned().into(),
1875            })
1876            .await
1877            .unwrap();
1878
1879        let keys_query = DataSet::bob_keys_query_response_signed();
1880        let txn_id = TransactionId::new();
1881        machine.mark_request_as_sent(&txn_id, &keys_query).await.unwrap();
1882
1883        let bob_identity =
1884            machine.get_identity(DataSet::bob_id(), None).await.unwrap().unwrap().other().unwrap();
1885
1886        // For testing purpose mark it as previously verified
1887        bob_identity.mark_as_previously_verified().await.unwrap();
1888
1889        assert!(!bob_identity.has_verification_violation());
1890
1891        let _ = machine.bootstrap_cross_signing(true).await.unwrap();
1892
1893        let bob_identity =
1894            machine.get_identity(DataSet::bob_id(), None).await.unwrap().unwrap().other().unwrap();
1895
1896        assert!(bob_identity.has_verification_violation());
1897    }
1898
1899    /// Test that receiving new public keys for our own identity causes a
1900    /// verification violation on our own identity.
1901    #[async_test]
1902    async fn test_own_keys_update_creates_own_identity_verification_violation() {
1903        use test_json::keys_query_sets::VerificationViolationTestData as DataSet;
1904
1905        let machine = OlmMachine::new(DataSet::own_id(), device_id!("LOCAL")).await;
1906
1907        // Start with our own identity verified
1908        let own_keys = DataSet::own_keys_query_response_1();
1909        machine.mark_request_as_sent(&TransactionId::new(), &own_keys).await.unwrap();
1910
1911        machine
1912            .import_cross_signing_keys(CrossSigningKeyExport {
1913                master_key: DataSet::MASTER_KEY_PRIVATE_EXPORT.to_owned().into(),
1914                self_signing_key: DataSet::SELF_SIGNING_KEY_PRIVATE_EXPORT.to_owned().into(),
1915                user_signing_key: DataSet::USER_SIGNING_KEY_PRIVATE_EXPORT.to_owned().into(),
1916            })
1917            .await
1918            .unwrap();
1919
1920        // Double-check that we have a verified identity
1921        let own_identity = machine.get_identity(DataSet::own_id(), None).await.unwrap().unwrap();
1922        assert!(own_identity.is_verified());
1923        assert!(own_identity.was_previously_verified());
1924        assert!(!own_identity.has_verification_violation());
1925
1926        // Now, we receive a *different* set of public keys
1927        let own_keys = DataSet::own_keys_query_response_2();
1928        machine.mark_request_as_sent(&TransactionId::new(), &own_keys).await.unwrap();
1929
1930        // That should give an identity that is no longer verified, with a verification
1931        // violation.
1932        let own_identity = machine.get_identity(DataSet::own_id(), None).await.unwrap().unwrap();
1933        assert!(!own_identity.is_verified());
1934        assert!(own_identity.was_previously_verified());
1935        assert!(own_identity.has_verification_violation());
1936
1937        // Now check that we can withdraw verification for our own identity, and that it
1938        // becomes valid again.
1939        own_identity.withdraw_verification().await.unwrap();
1940
1941        assert!(!own_identity.is_verified());
1942        assert!(!own_identity.was_previously_verified());
1943        assert!(!own_identity.has_verification_violation());
1944    }
1945
1946    fn own_user_identity_data() -> Value {
1947        json!({
1948            "user_id": "@example:localhost",
1949            "master_key": {
1950                "user_id":"@example:localhost",
1951                "usage":["master"],
1952                "keys":{"ed25519:rJ2TAGkEOP6dX41Ksll6cl8K3J48l8s/59zaXyvl2p0":"rJ2TAGkEOP6dX41Ksll6cl8K3J48l8s/59zaXyvl2p0"},
1953            },
1954            "self_signing_key": {
1955                "user_id":"@example:localhost",
1956                "usage":["self_signing"],
1957                "keys":{"ed25519:0C8lCBxrvrv/O7BQfsKnkYogHZX3zAgw3RfJuyiq210":"0C8lCBxrvrv/O7BQfsKnkYogHZX3zAgw3RfJuyiq210"}
1958            },
1959            "user_signing_key": {
1960                "user_id":"@example:localhost",
1961                "usage":["user_signing"],
1962                "keys":{"ed25519:DU9z4gBFKFKCk7a13sW9wjT0Iyg7Hqv5f0BPM7DEhPo":"DU9z4gBFKFKCk7a13sW9wjT0Iyg7Hqv5f0BPM7DEhPo"}
1963            },
1964            "verified": false
1965        })
1966    }
1967
1968    #[async_test]
1969    async fn test_other_user_identity_verification_request_content() {
1970        let other_user_identity = other_user_identity().await;
1971        let verification_request_content = other_user_identity.verification_request_content(None);
1972        let mut verification_request_content_json =
1973            serde_json::to_value(verification_request_content)
1974                .expect("Could not serialize verification request content");
1975
1976        // Remove the body which is a pain to match
1977        let verification_request_content_object = verification_request_content_json
1978            .as_object_mut()
1979            .expect("serialized verification request was not an object");
1980        verification_request_content_object.remove("body").expect("No `body` in message content");
1981
1982        // The methods are variable too
1983        let methods = verification_request_content_object
1984            .remove("methods")
1985            .expect("No `methods` in message content");
1986        let methods = methods.as_array().expect("`methods` was not an array");
1987        assert!(methods.contains(&json!("m.sas.v1")));
1988        assert!(methods.contains(&json!("m.reciprocate.v1")));
1989
1990        assert_eq!(
1991            verification_request_content_json,
1992            json!({
1993                "msgtype": "m.key.verification.request",
1994                "from_device": "DEV123",
1995                "to": other_user_identity.user_id().to_string(),
1996            })
1997        );
1998    }
1999
2000    /// Create an [`OtherUserIdentity`] for use in tests
2001    async fn other_user_identity() -> OtherUserIdentity {
2002        use ruma::owned_device_id;
2003
2004        let other_user_identity_data = get_other_identity();
2005
2006        let account =
2007            Account::with_device_id(user_id!("@own_user:localhost"), &owned_device_id!("DEV123"));
2008
2009        let verification_machine = get_verification_machine(&account);
2010        let own_identity_data = verification_machine.get_own_user_identity_data().await.unwrap();
2011
2012        OtherUserIdentity {
2013            inner: other_user_identity_data,
2014            own_identity: Some(own_identity_data),
2015            verification_machine,
2016        }
2017    }
2018
2019    /**
2020     * Create a minimal [`VerificationMachine`] for the given account,
2021     * backed by a [`MemoryStore`].
2022     *
2023     * Creates a new private user identity for the account.
2024     */
2025    fn get_verification_machine(account: &Account) -> VerificationMachine {
2026        let private_identity = PrivateCrossSigningIdentity::for_account(account);
2027        VerificationMachine::new(
2028            account.static_data().clone(),
2029            Arc::new(Mutex::new(private_identity)),
2030            Arc::new(CryptoStoreWrapper::new(
2031                account.user_id(),
2032                account.device_id(),
2033                MemoryStore::new(),
2034            )),
2035        )
2036    }
2037}