1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
// Copyright 2024 The Matrix.org Foundation C.I.C.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use std::collections::HashMap;

use async_trait::async_trait;
use ruma::{
    events::{
        room::member::{MembershipState, SyncRoomMemberEvent},
        SyncStateEvent,
    },
    OwnedUserId, UserId,
};

use super::UserIdentity;
use crate::store::IdentityUpdates;

/// Something that can answer questions about the membership of a room and the
/// identities of users.
///
/// This is implemented by `matrix_sdk::Room` and is a trait here so we can
/// supply a mock when needed.
#[async_trait]
pub trait RoomIdentityProvider: core::fmt::Debug {
    /// Is the user with the supplied ID a member of this room?
    async fn is_member(&self, user_id: &UserId) -> bool;

    /// Return a list of the [`UserIdentity`] of all members of this room
    async fn member_identities(&self) -> Vec<UserIdentity>;

    /// Return the [`UserIdentity`] of the user with the supplied ID (even if
    /// they are not a member of this room) or None if this user does not
    /// exist.
    async fn user_identity(&self, user_id: &UserId) -> Option<UserIdentity>;

    /// Return the [`IdentityState`] of the supplied user identity.
    /// Normally only overridden in tests.
    fn state_of(&self, user_identity: &UserIdentity) -> IdentityState {
        if user_identity.is_verified() {
            IdentityState::Verified
        } else if user_identity.has_verification_violation() {
            IdentityState::VerificationViolation
        } else if let UserIdentity::Other(u) = user_identity {
            if u.identity_needs_user_approval() {
                IdentityState::PinViolation
            } else {
                IdentityState::Pinned
            }
        } else {
            IdentityState::Pinned
        }
    }
}

/// The state of the identities in a given room - whether they are:
///
/// * in pin violation (the identity changed after we accepted their identity),
/// * verified (we manually did the emoji dance),
/// * previously verified (we did the emoji dance and then their identity
///   changed),
/// * otherwise, they are pinned.
#[derive(Debug)]
pub struct RoomIdentityState<R: RoomIdentityProvider> {
    room: R,
    known_states: KnownStates,
}

impl<R: RoomIdentityProvider> RoomIdentityState<R> {
    /// Create a new RoomIdentityState using the provided room to check whether
    /// users are members.
    pub async fn new(room: R) -> Self {
        let known_states = KnownStates::from_identities(room.member_identities().await, &room);
        Self { room, known_states }
    }

    /// Provide the current state of the room: a list of all the non-pinned
    /// identities and their status.
    pub fn current_state(&self) -> Vec<IdentityStatusChange> {
        self.known_states
            .known_states
            .iter()
            .map(|(user_id, state)| IdentityStatusChange {
                user_id: user_id.clone(),
                changed_to: state.clone(),
            })
            .collect()
    }

    /// Deal with an incoming event - either someone's identity changed, or some
    /// changes happened to a room's membership.
    ///
    /// Returns the changes (if any) to the list of valid/invalid identities in
    /// the room.
    pub async fn process_change(&mut self, item: RoomIdentityChange) -> Vec<IdentityStatusChange> {
        match item {
            RoomIdentityChange::IdentityUpdates(identity_updates) => {
                self.process_identity_changes(identity_updates).await
            }
            RoomIdentityChange::SyncRoomMemberEvent(sync_room_member_event) => {
                self.process_membership_change(sync_room_member_event).await
            }
        }
    }

    async fn process_identity_changes(
        &mut self,
        identity_updates: IdentityUpdates,
    ) -> Vec<IdentityStatusChange> {
        let mut ret = vec![];

        for user_identity in identity_updates.new.values().chain(identity_updates.changed.values())
        {
            let user_id = user_identity.user_id();
            if self.room.is_member(user_id).await {
                let update = self.update_user_state(user_id, user_identity);
                if let Some(identity_status_change) = update {
                    ret.push(identity_status_change);
                }
            }
        }

        ret
    }

    async fn process_membership_change(
        &mut self,
        sync_room_member_event: SyncRoomMemberEvent,
    ) -> Vec<IdentityStatusChange> {
        // Ignore redacted events - memberships should come through as new events, not
        // redactions.
        if let SyncStateEvent::Original(event) = sync_room_member_event {
            // Ignore invalid user IDs
            let user_id: Result<&UserId, _> = event.state_key.as_str().try_into();
            if let Ok(user_id) = user_id {
                // Ignore non-existent users, and changes to our own identity
                if let Some(user_identity @ UserIdentity::Other(_)) =
                    self.room.user_identity(user_id).await
                {
                    match event.content.membership {
                        MembershipState::Join | MembershipState::Invite => {
                            // They are joining the room - check whether we need to display a
                            // warning to the user
                            if let Some(update) = self.update_user_state(user_id, &user_identity) {
                                return vec![update];
                            }
                        }
                        MembershipState::Leave | MembershipState::Ban => {
                            // They are leaving the room - treat that as if they are becoming
                            // Pinned, which means the UI will remove any banner it was displaying
                            // for them.

                            if let Some(update) =
                                self.update_user_state_to(user_id, IdentityState::Pinned)
                            {
                                return vec![update];
                            }
                        }
                        MembershipState::Knock => {
                            // No need to do anything when someone is knocking
                        }
                        _ => {}
                    }
                }
            }
        }

        // We didn't find a relevant update, so return an empty list
        vec![]
    }

    fn update_user_state(
        &mut self,
        user_id: &UserId,
        user_identity: &UserIdentity,
    ) -> Option<IdentityStatusChange> {
        if let UserIdentity::Other(_) = &user_identity {
            self.update_user_state_to(user_id, self.room.state_of(user_identity))
        } else {
            // Ignore updates to our own identity
            None
        }
    }

    /// Updates our internal state for this user to the supplied `new_state`. If
    /// the change of state is significant (it requires something to change
    /// in the UI, like a warning being added or removed), returns the
    /// change information we will surface to the UI.
    fn update_user_state_to(
        &mut self,
        user_id: &UserId,
        new_state: IdentityState,
    ) -> Option<IdentityStatusChange> {
        use IdentityState::*;

        let old_state = self.known_states.get(user_id);

        match (old_state, &new_state) {
            // good -> bad - report so we can add a message
            (Pinned, PinViolation) |
            (Pinned, VerificationViolation) |
            (Verified, PinViolation) |
            (Verified, VerificationViolation) |

            // bad -> good - report so we can remove a message
            (PinViolation, Pinned) |
            (PinViolation, Verified) |
            (VerificationViolation, Pinned) |
            (VerificationViolation, Verified) |

            // Changed the type of bad - report so can change the message
            (PinViolation, VerificationViolation) |
            (VerificationViolation, PinViolation) => Some(self.set_state(user_id, new_state)),

            // good -> good - don't report - no message needed in either case
            (Pinned, Verified) |
            (Verified, Pinned) => {
                // The state has changed, so we update it
                self.set_state(user_id, new_state);
                // but there is no need to report a change to the UI
                None
            }

            // State didn't change - don't report - nothing changed
            (Pinned, Pinned) |
            (Verified, Verified) |
            (PinViolation, PinViolation) |
            (VerificationViolation, VerificationViolation) => None,
        }
    }

    fn set_state(&mut self, user_id: &UserId, new_state: IdentityState) -> IdentityStatusChange {
        // Remember the new state of the user
        self.known_states.set(user_id, &new_state);

        // And return the update
        IdentityStatusChange { user_id: user_id.to_owned(), changed_to: new_state }
    }
}

/// A change in the status of the identity of a member of the room. Returned by
/// [`RoomIdentityState::process_change`] to indicate that something significant
/// changed in this room and we should either show or hide a warning.
///
/// Examples of "significant" changes:
/// - pinned->unpinned
/// - verification violation->verified
///
/// Examples of "insignificant" changes:
/// - pinned->verified
/// - verified->pinned
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub struct IdentityStatusChange {
    /// The user ID of the user whose identity status changed
    pub user_id: OwnedUserId,

    /// The new state of the identity of the user
    pub changed_to: IdentityState,
}

/// The state of an identity - verified, pinned etc.
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))]
pub enum IdentityState {
    /// The user is verified with us
    Verified,

    /// Either this is the first identity we have seen for this user, or the
    /// user has acknowledged a change of identity explicitly e.g. by
    /// clicking OK on a notification.
    Pinned,

    /// The user's identity has changed since it was pinned. The user should be
    /// notified about this and given the opportunity to acknowledge the
    /// change, which will make the new identity pinned.
    /// When the user acknowledges the change, the app should call
    /// [`crate::OtherUserIdentity::pin_current_master_key`].
    PinViolation,

    /// The user's identity has changed, and before that it was verified. This
    /// is a serious problem. The user can either verify again to make this
    /// identity verified, or withdraw verification
    /// [`UserIdentity::withdraw_verification`] to make it pinned.
    VerificationViolation,
}

/// The type of update that can be received by
/// [`RoomIdentityState::process_change`] - either a change of someone's
/// identity, or a change of room membership.
#[derive(Debug)]
pub enum RoomIdentityChange {
    /// Someone's identity changed
    IdentityUpdates(IdentityUpdates),

    /// Someone joined or left a room
    SyncRoomMemberEvent(SyncRoomMemberEvent),
}

/// What we know about the states of users in this room.
/// Only stores users who _not_ in the Pinned stated.
#[derive(Debug)]
struct KnownStates {
    known_states: HashMap<OwnedUserId, IdentityState>,
}

impl KnownStates {
    fn from_identities(
        member_identities: impl IntoIterator<Item = UserIdentity>,
        room: &dyn RoomIdentityProvider,
    ) -> Self {
        let mut known_states = HashMap::new();
        for user_identity in member_identities {
            let state = room.state_of(&user_identity);
            if state != IdentityState::Pinned {
                known_states.insert(user_identity.user_id().to_owned(), state);
            }
        }
        Self { known_states }
    }

    /// Return the known state of the supplied user, or IdentityState::Pinned if
    /// we don't know.
    fn get(&self, user_id: &UserId) -> IdentityState {
        self.known_states.get(user_id).cloned().unwrap_or(IdentityState::Pinned)
    }

    /// Set the supplied user's state to the state given. If identity_state is
    /// IdentityState::Pinned, forget this user.
    fn set(&mut self, user_id: &UserId, identity_state: &IdentityState) {
        if let IdentityState::Pinned = identity_state {
            self.known_states.remove(user_id);
        } else {
            self.known_states.insert(user_id.to_owned(), identity_state.clone());
        }
    }
}

#[cfg(test)]
mod tests {
    use std::{
        collections::HashMap,
        sync::{Arc, Mutex},
    };

    use async_trait::async_trait;
    use matrix_sdk_test::async_test;
    use ruma::{
        device_id,
        events::{
            room::member::{
                MembershipState, RoomMemberEventContent, RoomMemberUnsigned, SyncRoomMemberEvent,
            },
            OriginalSyncStateEvent,
        },
        owned_event_id, owned_user_id, user_id, MilliSecondsSinceUnixEpoch, OwnedUserId, UInt,
        UserId,
    };

    use super::{IdentityState, RoomIdentityChange, RoomIdentityProvider, RoomIdentityState};
    use crate::{
        identities::user::testing::own_identity_wrapped,
        store::{IdentityUpdates, Store},
        IdentityStatusChange, OtherUserIdentity, OtherUserIdentityData, OwnUserIdentityData,
        UserIdentity,
    };

    #[async_test]
    async fn test_unpinning_a_pinned_identity_in_the_room_notifies() {
        // Given someone in the room is pinned
        let user_id = user_id!("@u:s.co");
        let mut room = FakeRoom::new();
        room.member(other_user_identity(user_id).await, IdentityState::Pinned);
        let mut state = RoomIdentityState::new(room.clone()).await;

        // When their identity changes to unpinned
        let updates =
            identity_change(&mut room, user_id, IdentityState::PinViolation, false, false).await;
        let update = state.process_change(updates).await;

        // Then we emit an update saying they became unpinned
        assert_eq!(
            update,
            vec![IdentityStatusChange {
                user_id: user_id.to_owned(),
                changed_to: IdentityState::PinViolation
            }]
        );
    }

    #[async_test]
    async fn test_verifying_a_pinned_identity_in_the_room_does_nothing() {
        // Given someone in the room is pinned
        let user_id = user_id!("@u:s.co");
        let mut room = FakeRoom::new();
        room.member(other_user_identity(user_id).await, IdentityState::Pinned);
        let mut state = RoomIdentityState::new(room.clone()).await;

        // When their identity changes to verified
        let updates =
            identity_change(&mut room, user_id, IdentityState::Verified, false, false).await;
        let update = state.process_change(updates).await;

        // Then we emit no update
        assert_eq!(update, vec![]);
    }

    #[async_test]
    async fn test_pinning_an_unpinned_identity_in_the_room_notifies() {
        // Given someone in the room is unpinned
        let user_id = user_id!("@u:s.co");
        let mut room = FakeRoom::new();
        room.member(other_user_identity(user_id).await, IdentityState::PinViolation);
        let mut state = RoomIdentityState::new(room.clone()).await;

        // When their identity changes to pinned
        let updates =
            identity_change(&mut room, user_id, IdentityState::Pinned, false, false).await;
        let update = state.process_change(updates).await;

        // Then we emit an update saying they became pinned
        assert_eq!(
            update,
            vec![IdentityStatusChange {
                user_id: user_id.to_owned(),
                changed_to: IdentityState::Pinned
            }]
        );
    }

    #[async_test]
    async fn test_unpinned_identity_becoming_verification_violating_in_the_room_notifies() {
        // Given someone in the room is unpinned
        let user_id = user_id!("@u:s.co");
        let mut room = FakeRoom::new();
        room.member(other_user_identity(user_id).await, IdentityState::PinViolation);
        let mut state = RoomIdentityState::new(room.clone()).await;

        // When their identity changes to verification violation
        let updates =
            identity_change(&mut room, user_id, IdentityState::VerificationViolation, false, false)
                .await;
        let update = state.process_change(updates).await;

        // Then we emit an update saying they became verification violating
        assert_eq!(
            update,
            vec![IdentityStatusChange {
                user_id: user_id.to_owned(),
                changed_to: IdentityState::VerificationViolation
            }]
        );
    }

    #[async_test]
    async fn test_unpinning_an_identity_not_in_the_room_does_nothing() {
        // Given an empty room
        let user_id = user_id!("@u:s.co");
        let mut room = FakeRoom::new();
        let mut state = RoomIdentityState::new(room.clone()).await;

        // When a new unpinned user identity appears but they are not in the room
        let updates =
            identity_change(&mut room, user_id, IdentityState::PinViolation, true, false).await;
        let update = state.process_change(updates).await;

        // Then we emit no update
        assert_eq!(update, vec![]);
    }

    #[async_test]
    async fn test_pinning_an_identity_not_in_the_room_does_nothing() {
        // Given an empty room
        let user_id = user_id!("@u:s.co");
        let mut room = FakeRoom::new();
        let mut state = RoomIdentityState::new(room.clone()).await;

        // When a new pinned user appears but is not in the room
        let updates = identity_change(&mut room, user_id, IdentityState::Pinned, true, false).await;
        let update = state.process_change(updates).await;

        // Then we emit no update
        assert_eq!(update, []);
    }

    #[async_test]
    async fn test_pinning_an_already_pinned_identity_in_the_room_does_nothing() {
        // Given someone in the room is pinned
        let user_id = user_id!("@u:s.co");
        let mut room = FakeRoom::new();
        room.member(other_user_identity(user_id).await, IdentityState::Pinned);
        let mut state = RoomIdentityState::new(room.clone()).await;

        // When we are told they are pinned
        let updates =
            identity_change(&mut room, user_id, IdentityState::Pinned, false, false).await;
        let update = state.process_change(updates).await;

        // Then we emit no update
        assert_eq!(update, []);
    }

    #[async_test]
    async fn test_unpinning_an_already_unpinned_identity_in_the_room_does_nothing() {
        // Given someone in the room is unpinned
        let user_id = user_id!("@u:s.co");
        let mut room = FakeRoom::new();
        room.member(other_user_identity(user_id).await, IdentityState::PinViolation);
        let mut state = RoomIdentityState::new(room.clone()).await;

        // When we are told they are unpinned
        let updates =
            identity_change(&mut room, user_id, IdentityState::PinViolation, false, false).await;
        let update = state.process_change(updates).await;

        // Then we emit no update
        assert_eq!(update, []);
    }

    #[async_test]
    async fn test_a_pinned_identity_joining_the_room_does_nothing() {
        // Given an empty room and we know of a user who is pinned
        let user_id = user_id!("@u:s.co");
        let mut room = FakeRoom::new();
        room.non_member(other_user_identity(user_id).await, IdentityState::Pinned);
        let mut state = RoomIdentityState::new(room.clone()).await;

        // When the pinned user joins the room
        let updates = room_change(user_id, MembershipState::Join);
        let update = state.process_change(updates).await;

        // Then we emit no update because they are pinned
        assert_eq!(update, []);
    }

    #[async_test]
    async fn test_a_verified_identity_joining_the_room_does_nothing() {
        // Given an empty room and we know of a user who is verified
        let user_id = user_id!("@u:s.co");
        let mut room = FakeRoom::new();
        room.non_member(other_user_identity(user_id).await, IdentityState::Verified);
        let mut state = RoomIdentityState::new(room).await;

        // When the verified user joins the room
        let updates = room_change(user_id, MembershipState::Join);
        let update = state.process_change(updates).await;

        // Then we emit no update because they are verified
        assert_eq!(update, []);
    }

    #[async_test]
    async fn test_an_unpinned_identity_joining_the_room_notifies() {
        // Given an empty room and we know of a user who is unpinned
        let user_id = user_id!("@u:s.co");
        let mut room = FakeRoom::new();
        room.non_member(other_user_identity(user_id).await, IdentityState::PinViolation);
        let mut state = RoomIdentityState::new(room.clone()).await;

        // When the unpinned user joins the room
        let updates = room_change(user_id, MembershipState::Join);
        let update = state.process_change(updates).await;

        // Then we emit an update saying they became unpinned
        assert_eq!(
            update,
            vec![IdentityStatusChange {
                user_id: user_id.to_owned(),
                changed_to: IdentityState::PinViolation
            }]
        );
    }

    #[async_test]
    async fn test_a_pinned_identity_invited_to_the_room_does_nothing() {
        // Given an empty room and we know of a user who is pinned
        let user_id = user_id!("@u:s.co");
        let mut room = FakeRoom::new();
        room.non_member(other_user_identity(user_id).await, IdentityState::Pinned);
        let mut state = RoomIdentityState::new(room.clone()).await;

        // When the pinned user is invited to the room
        let updates = room_change(user_id, MembershipState::Invite);
        let update = state.process_change(updates).await;

        // Then we emit no update because they are pinned
        assert_eq!(update, []);
    }

    #[async_test]
    async fn test_an_unpinned_identity_invited_to_the_room_notifies() {
        // Given an empty room and we know of a user who is unpinned
        let user_id = user_id!("@u:s.co");
        let mut room = FakeRoom::new();
        room.non_member(other_user_identity(user_id).await, IdentityState::PinViolation);
        let mut state = RoomIdentityState::new(room.clone()).await;

        // When the unpinned user is invited to the room
        let updates = room_change(user_id, MembershipState::Invite);
        let update = state.process_change(updates).await;

        // Then we emit an update saying they became unpinned
        assert_eq!(
            update,
            vec![IdentityStatusChange {
                user_id: user_id.to_owned(),
                changed_to: IdentityState::PinViolation
            }]
        );
    }

    #[async_test]
    async fn test_a_verification_violating_identity_invited_to_the_room_notifies() {
        // Given an empty room and we know of a user who is unpinned
        let user_id = user_id!("@u:s.co");
        let mut room = FakeRoom::new();
        room.non_member(other_user_identity(user_id).await, IdentityState::VerificationViolation);
        let mut state = RoomIdentityState::new(room).await;

        // When the user is invited to the room
        let updates = room_change(user_id, MembershipState::Invite);
        let update = state.process_change(updates).await;

        // Then we emit an update saying they became verification violation
        assert_eq!(
            update,
            vec![IdentityStatusChange {
                user_id: user_id.to_owned(),
                changed_to: IdentityState::VerificationViolation
            }]
        );
    }

    #[async_test]
    async fn test_own_identity_becoming_unpinned_is_ignored() {
        // Given I am pinned
        let user_id = user_id!("@u:s.co");
        let mut room = FakeRoom::new();
        room.member(own_user_identity(user_id).await, IdentityState::Pinned);
        let mut state = RoomIdentityState::new(room.clone()).await;

        // When I become unpinned
        let updates =
            identity_change(&mut room, user_id, IdentityState::PinViolation, false, true).await;
        let update = state.process_change(updates).await;

        // Then we do nothing because own identities are ignored
        assert_eq!(update, vec![]);
    }

    #[async_test]
    async fn test_own_identity_becoming_pinned_is_ignored() {
        // Given I am unpinned
        let user_id = user_id!("@u:s.co");
        let mut room = FakeRoom::new();
        room.member(own_user_identity(user_id).await, IdentityState::PinViolation);
        let mut state = RoomIdentityState::new(room.clone()).await;

        // When I become unpinned
        let updates = identity_change(&mut room, user_id, IdentityState::Pinned, false, true).await;
        let update = state.process_change(updates).await;

        // Then we do nothing because own identities are ignored
        assert_eq!(update, vec![]);
    }

    #[async_test]
    async fn test_own_pinned_identity_joining_room_is_ignored() {
        // Given an empty room and we know of a user who is pinned
        let user_id = user_id!("@u:s.co");
        let mut room = FakeRoom::new();
        room.non_member(own_user_identity(user_id).await, IdentityState::Pinned);
        let mut state = RoomIdentityState::new(room.clone()).await;

        // When the pinned user joins the room
        let updates = room_change(user_id, MembershipState::Join);
        let update = state.process_change(updates).await;

        // Then we emit no update because this is our own identity
        assert_eq!(update, []);
    }

    #[async_test]
    async fn test_own_unpinned_identity_joining_room_is_ignored() {
        // Given an empty room and we know of a user who is unpinned
        let user_id = user_id!("@u:s.co");
        let mut room = FakeRoom::new();
        room.non_member(own_user_identity(user_id).await, IdentityState::PinViolation);
        let mut state = RoomIdentityState::new(room.clone()).await;

        // When the unpinned user joins the room
        let updates = room_change(user_id, MembershipState::Join);
        let update = state.process_change(updates).await;

        // Then we emit no update because this is our own identity
        assert_eq!(update, vec![]);
    }

    #[async_test]
    async fn test_a_pinned_identity_leaving_the_room_does_nothing() {
        // Given a pinned user is in the room
        let user_id = user_id!("@u:s.co");
        let mut room = FakeRoom::new();
        room.member(other_user_identity(user_id).await, IdentityState::Pinned);
        let mut state = RoomIdentityState::new(room.clone()).await;

        // When the pinned user leaves the room
        let updates = room_change(user_id, MembershipState::Leave);
        let update = state.process_change(updates).await;

        // Then we emit no update because they are pinned
        assert_eq!(update, []);
    }

    #[async_test]
    async fn test_a_verified_identity_leaving_the_room_does_nothing() {
        // Given a pinned user is in the room
        let user_id = user_id!("@u:s.co");
        let mut room = FakeRoom::new();
        room.member(other_user_identity(user_id).await, IdentityState::Verified);
        let mut state = RoomIdentityState::new(room).await;

        // When the user leaves the room
        let updates = room_change(user_id, MembershipState::Leave);
        let update = state.process_change(updates).await;

        // Then we emit no update because they are verified
        assert_eq!(update, []);
    }

    #[async_test]
    async fn test_an_unpinned_identity_leaving_the_room_notifies() {
        // Given an unpinned user is in the room
        let user_id = user_id!("@u:s.co");
        let mut room = FakeRoom::new();
        room.member(other_user_identity(user_id).await, IdentityState::PinViolation);
        let mut state = RoomIdentityState::new(room.clone()).await;

        // When the unpinned user leaves the room
        let updates = room_change(user_id, MembershipState::Leave);
        let update = state.process_change(updates).await;

        // Then we emit an update saying they became pinned
        assert_eq!(
            update,
            vec![IdentityStatusChange {
                user_id: user_id.to_owned(),
                changed_to: IdentityState::Pinned
            }]
        );
    }

    #[async_test]
    async fn test_a_verification_violating_identity_leaving_the_room_notifies() {
        // Given an unpinned user is in the room
        let user_id = user_id!("@u:s.co");
        let mut room = FakeRoom::new();
        room.member(other_user_identity(user_id).await, IdentityState::VerificationViolation);
        let mut state = RoomIdentityState::new(room).await;

        // When the user leaves the room
        let updates = room_change(user_id, MembershipState::Leave);
        let update = state.process_change(updates).await;

        // Then we emit an update saying they became pinned
        assert_eq!(
            update,
            vec![IdentityStatusChange {
                user_id: user_id.to_owned(),
                changed_to: IdentityState::Pinned
            }]
        );
    }

    #[async_test]
    async fn test_a_pinned_identity_being_banned_does_nothing() {
        // Given a pinned user is in the room
        let user_id = user_id!("@u:s.co");
        let mut room = FakeRoom::new();
        room.member(other_user_identity(user_id).await, IdentityState::Pinned);
        let mut state = RoomIdentityState::new(room.clone()).await;

        // When the pinned user is banned
        let updates = room_change(user_id, MembershipState::Ban);
        let update = state.process_change(updates).await;

        // Then we emit no update because they are pinned
        assert_eq!(update, []);
    }

    #[async_test]
    async fn test_an_unpinned_identity_being_banned_notifies() {
        // Given an unpinned user is in the room
        let user_id = user_id!("@u:s.co");
        let mut room = FakeRoom::new();
        room.member(other_user_identity(user_id).await, IdentityState::PinViolation);
        let mut state = RoomIdentityState::new(room.clone()).await;

        // When the unpinned user is banned
        let updates = room_change(user_id, MembershipState::Ban);
        let update = state.process_change(updates).await;

        // Then we emit an update saying they became unpinned
        assert_eq!(
            update,
            vec![IdentityStatusChange {
                user_id: user_id.to_owned(),
                changed_to: IdentityState::Pinned
            }]
        );
    }

    #[async_test]
    async fn test_multiple_simultaneous_identity_updates_are_all_notified() {
        // Given several people in the room with different states
        let user1 = user_id!("@u1:s.co");
        let user2 = user_id!("@u2:s.co");
        let user3 = user_id!("@u3:s.co");
        let mut room = FakeRoom::new();
        room.member(other_user_identity(user1).await, IdentityState::Pinned);
        room.member(other_user_identity(user2).await, IdentityState::PinViolation);
        room.member(other_user_identity(user3).await, IdentityState::Pinned);
        let mut state = RoomIdentityState::new(room.clone()).await;

        // When they all change state simultaneously
        let updates = identity_changes(
            &mut room,
            &[
                IdentityChangeSpec {
                    user_id: user1.to_owned(),
                    changed_to: IdentityState::PinViolation,
                    new: false,
                    own: false,
                },
                IdentityChangeSpec {
                    user_id: user2.to_owned(),
                    changed_to: IdentityState::Pinned,
                    new: false,
                    own: false,
                },
                IdentityChangeSpec {
                    user_id: user3.to_owned(),
                    changed_to: IdentityState::PinViolation,
                    new: false,
                    own: false,
                },
            ],
        )
        .await;
        let update = state.process_change(updates).await;

        // Then we emit updates for each of them
        assert_eq!(
            update,
            vec![
                IdentityStatusChange {
                    user_id: user1.to_owned(),
                    changed_to: IdentityState::PinViolation
                },
                IdentityStatusChange {
                    user_id: user2.to_owned(),
                    changed_to: IdentityState::Pinned
                },
                IdentityStatusChange {
                    user_id: user3.to_owned(),
                    changed_to: IdentityState::PinViolation
                }
            ]
        );
    }

    #[async_test]
    async fn test_multiple_changes_are_notified() {
        // Given someone in the room is pinned
        let user_id = user_id!("@u:s.co");
        let mut room = FakeRoom::new();
        room.member(other_user_identity(user_id).await, IdentityState::Pinned);
        let mut state = RoomIdentityState::new(room.clone()).await;

        // When they change state multiple times
        let update1 = state
            .process_change(
                identity_change(&mut room, user_id, IdentityState::PinViolation, false, false)
                    .await,
            )
            .await;
        let update2 = state
            .process_change(
                identity_change(&mut room, user_id, IdentityState::PinViolation, false, false)
                    .await,
            )
            .await;
        let update3 = state
            .process_change(
                identity_change(&mut room, user_id, IdentityState::Pinned, false, false).await,
            )
            .await;
        let update4 = state
            .process_change(
                identity_change(&mut room, user_id, IdentityState::PinViolation, false, false)
                    .await,
            )
            .await;

        // Then we emit updates each time
        assert_eq!(
            update1,
            vec![IdentityStatusChange {
                user_id: user_id.to_owned(),
                changed_to: IdentityState::PinViolation
            }]
        );
        // (Except update2 where nothing changed)
        assert_eq!(update2, vec![]);
        assert_eq!(
            update3,
            vec![IdentityStatusChange {
                user_id: user_id.to_owned(),
                changed_to: IdentityState::Pinned
            }]
        );
        assert_eq!(
            update4,
            vec![IdentityStatusChange {
                user_id: user_id.to_owned(),
                changed_to: IdentityState::PinViolation
            }]
        );
    }

    #[async_test]
    async fn test_current_state_of_all_pinned_room_is_empty() {
        // Given everyone in the room is pinned
        let user1 = user_id!("@u1:s.co");
        let user2 = user_id!("@u2:s.co");
        let mut room = FakeRoom::new();
        room.member(other_user_identity(user1).await, IdentityState::Pinned);
        room.member(other_user_identity(user2).await, IdentityState::Pinned);
        let state = RoomIdentityState::new(room).await;
        assert!(state.current_state().is_empty());
    }

    #[async_test]
    async fn test_current_state_contains_all_nonpinned_users() {
        // Given some people are unpinned
        let user1 = user_id!("@u1:s.co");
        let user2 = user_id!("@u2:s.co");
        let user3 = user_id!("@u3:s.co");
        let user4 = user_id!("@u4:s.co");
        let user5 = user_id!("@u5:s.co");
        let user6 = user_id!("@u6:s.co");
        let mut room = FakeRoom::new();
        room.member(other_user_identity(user1).await, IdentityState::Pinned);
        room.member(other_user_identity(user2).await, IdentityState::PinViolation);
        room.member(other_user_identity(user3).await, IdentityState::Pinned);
        room.member(other_user_identity(user4).await, IdentityState::PinViolation);
        room.member(other_user_identity(user5).await, IdentityState::Verified);
        room.member(other_user_identity(user6).await, IdentityState::VerificationViolation);
        let mut state = RoomIdentityState::new(room).await.current_state();
        state.sort_by_key(|change| change.user_id.to_owned());
        assert_eq!(
            state,
            vec![
                IdentityStatusChange {
                    user_id: owned_user_id!("@u2:s.co"),
                    changed_to: IdentityState::PinViolation
                },
                IdentityStatusChange {
                    user_id: owned_user_id!("@u4:s.co"),
                    changed_to: IdentityState::PinViolation
                },
                IdentityStatusChange {
                    user_id: owned_user_id!("@u5:s.co"),
                    changed_to: IdentityState::Verified
                },
                IdentityStatusChange {
                    user_id: owned_user_id!("@u6:s.co"),
                    changed_to: IdentityState::VerificationViolation
                }
            ]
        );
    }

    #[derive(Debug)]
    struct Membership {
        is_member: bool,
        user_identity: UserIdentity,
        identity_state: IdentityState,
    }

    #[derive(Clone, Debug)]
    struct FakeRoom {
        users: Arc<Mutex<HashMap<OwnedUserId, Membership>>>,
    }

    impl FakeRoom {
        fn new() -> Self {
            Self { users: Default::default() }
        }

        fn member(&mut self, user_identity: UserIdentity, identity_state: IdentityState) {
            self.users.lock().unwrap().insert(
                user_identity.user_id().to_owned(),
                Membership { is_member: true, user_identity, identity_state },
            );
        }

        fn non_member(&mut self, user_identity: UserIdentity, identity_state: IdentityState) {
            self.users.lock().unwrap().insert(
                user_identity.user_id().to_owned(),
                Membership { is_member: false, user_identity, identity_state },
            );
        }

        fn update_state(&self, user_id: &UserId, changed_to: &IdentityState) {
            self.users
                .lock()
                .unwrap()
                .entry(user_id.to_owned())
                .and_modify(|m| m.identity_state = changed_to.clone());
        }
    }

    #[async_trait]
    impl RoomIdentityProvider for FakeRoom {
        async fn is_member(&self, user_id: &UserId) -> bool {
            self.users.lock().unwrap().get(user_id).map(|m| m.is_member).unwrap_or(false)
        }

        async fn member_identities(&self) -> Vec<UserIdentity> {
            self.users
                .lock()
                .unwrap()
                .values()
                .filter_map(|m| if m.is_member { Some(m.user_identity.clone()) } else { None })
                .collect()
        }

        async fn user_identity(&self, user_id: &UserId) -> Option<UserIdentity> {
            self.users.lock().unwrap().get(user_id).map(|m| m.user_identity.clone())
        }

        fn state_of(&self, user_identity: &UserIdentity) -> IdentityState {
            self.users
                .lock()
                .unwrap()
                .get(user_identity.user_id())
                .map(|m| m.identity_state.clone())
                .unwrap_or(IdentityState::Pinned)
        }
    }

    fn room_change(user_id: &UserId, new_state: MembershipState) -> RoomIdentityChange {
        let event = SyncRoomMemberEvent::Original(OriginalSyncStateEvent {
            content: RoomMemberEventContent::new(new_state),
            event_id: owned_event_id!("$1"),
            sender: owned_user_id!("@admin:b.c"),
            origin_server_ts: MilliSecondsSinceUnixEpoch(UInt::new(2123).unwrap()),
            unsigned: RoomMemberUnsigned::new(),
            state_key: user_id.to_owned(),
        });
        RoomIdentityChange::SyncRoomMemberEvent(event)
    }

    async fn identity_change(
        room: &mut FakeRoom,
        user_id: &UserId,
        changed_to: IdentityState,
        new: bool,
        own: bool,
    ) -> RoomIdentityChange {
        identity_changes(
            room,
            &[IdentityChangeSpec { user_id: user_id.to_owned(), changed_to, new, own }],
        )
        .await
    }

    struct IdentityChangeSpec {
        user_id: OwnedUserId,
        changed_to: IdentityState,
        new: bool,
        own: bool,
    }

    async fn identity_changes(
        room: &mut FakeRoom,
        changes: &[IdentityChangeSpec],
    ) -> RoomIdentityChange {
        let mut updates = IdentityUpdates::default();

        for change in changes {
            let user_identity = if change.own {
                own_user_identity(&change.user_id).await
            } else {
                other_user_identity(&change.user_id).await
            };

            room.update_state(user_identity.user_id(), &change.changed_to);
            if change.new {
                updates.new.insert(user_identity.user_id().to_owned(), user_identity);
            } else {
                updates.changed.insert(user_identity.user_id().to_owned(), user_identity);
            }
        }
        RoomIdentityChange::IdentityUpdates(updates)
    }

    /// Create an other `UserIdentity` for use in tests
    async fn other_user_identity(user_id: &UserId) -> UserIdentity {
        use std::sync::Arc;

        use ruma::owned_device_id;
        use tokio::sync::Mutex;

        use crate::{
            olm::PrivateCrossSigningIdentity,
            store::{CryptoStoreWrapper, MemoryStore},
            verification::VerificationMachine,
            Account,
        };

        let device_id = owned_device_id!("DEV123");
        let account = Account::with_device_id(user_id, &device_id);

        let private_identity =
            Arc::new(Mutex::new(PrivateCrossSigningIdentity::with_account(&account).await.0));

        let other_user_identity_data =
            OtherUserIdentityData::from_private(&*private_identity.lock().await).await;

        UserIdentity::Other(OtherUserIdentity {
            inner: other_user_identity_data,
            own_identity: None,
            verification_machine: VerificationMachine::new(
                account.clone(),
                Arc::new(Mutex::new(PrivateCrossSigningIdentity::new(
                    account.user_id().to_owned(),
                ))),
                Arc::new(CryptoStoreWrapper::new(
                    account.user_id(),
                    account.device_id(),
                    MemoryStore::new(),
                )),
            ),
        })
    }

    /// Create an own `UserIdentity` for use in tests
    async fn own_user_identity(user_id: &UserId) -> UserIdentity {
        use std::sync::Arc;

        use ruma::owned_device_id;
        use tokio::sync::Mutex;

        use crate::{
            olm::PrivateCrossSigningIdentity,
            store::{CryptoStoreWrapper, MemoryStore},
            verification::VerificationMachine,
            Account,
        };

        let device_id = owned_device_id!("DEV123");
        let account = Account::with_device_id(user_id, &device_id);

        let private_identity =
            Arc::new(Mutex::new(PrivateCrossSigningIdentity::with_account(&account).await.0));

        let own_user_identity_data =
            OwnUserIdentityData::from_private(&*private_identity.lock().await).await;

        let cross_signing_identity = PrivateCrossSigningIdentity::new(account.user_id().to_owned());
        let verification_machine = VerificationMachine::new(
            account.clone(),
            Arc::new(Mutex::new(cross_signing_identity.clone())),
            Arc::new(CryptoStoreWrapper::new(
                account.user_id(),
                account.device_id(),
                MemoryStore::new(),
            )),
        );

        UserIdentity::Own(own_identity_wrapped(
            own_user_identity_data,
            verification_machine.clone(),
            Store::new(
                account.static_data().clone(),
                Arc::new(Mutex::new(cross_signing_identity)),
                Arc::new(CryptoStoreWrapper::new(
                    user_id!("@u:s.co"),
                    device_id!("DEV7"),
                    MemoryStore::new(),
                )),
                verification_machine,
            ),
        ))
    }
}