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