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