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