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