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