Skip to main content

matrix_sdk_crypto/identities/
user.rs

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