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