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