This repository was archived by the owner on Oct 22, 2024. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathMatrixChat-test.tsx
1505 lines (1238 loc) · 62.4 KB
/
MatrixChat-test.tsx
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
/*
Copyright 2024 New Vector Ltd.
Copyright 2023 The Matrix.org Foundation C.I.C.
SPDX-License-Identifier: AGPL-3.0-only OR GPL-3.0-only
Please see LICENSE files in the repository root for full details.
*/
import React, { ComponentProps } from "react";
import { fireEvent, render, RenderResult, screen, waitFor, within } from "@testing-library/react";
import fetchMock from "fetch-mock-jest";
import { Mocked, mocked } from "jest-mock";
import { ClientEvent, MatrixClient, MatrixEvent, Room, SyncState } from "matrix-js-sdk/src/matrix";
import { MediaHandler } from "matrix-js-sdk/src/webrtc/mediaHandler";
import * as MatrixJs from "matrix-js-sdk/src/matrix";
import { completeAuthorizationCodeGrant } from "matrix-js-sdk/src/oidc/authorize";
import { logger } from "matrix-js-sdk/src/logger";
import { OidcError } from "matrix-js-sdk/src/oidc/error";
import { BearerTokenResponse } from "matrix-js-sdk/src/oidc/validate";
import { defer, sleep } from "matrix-js-sdk/src/utils";
import { UserVerificationStatus } from "matrix-js-sdk/src/crypto-api";
import MatrixChat from "../../../src/components/structures/MatrixChat";
import * as StorageAccess from "../../../src/utils/StorageAccess";
import defaultDispatcher from "../../../src/dispatcher/dispatcher";
import { Action } from "../../../src/dispatcher/actions";
import { UserTab } from "../../../src/components/views/dialogs/UserTab";
import {
clearAllModals,
createStubMatrixRTC,
filterConsole,
flushPromises,
getMockClientWithEventEmitter,
mockClientMethodsServer,
mockClientMethodsUser,
MockClientWithEventEmitter,
mockPlatformPeg,
resetJsDomAfterEach,
unmockClientPeg,
} from "../../test-utils";
import * as leaveRoomUtils from "../../../src/utils/leave-behaviour";
import { OidcClientError } from "../../../src/utils/oidc/error";
import * as voiceBroadcastUtils from "../../../src/voice-broadcast/utils/cleanUpBroadcasts";
import LegacyCallHandler from "../../../src/LegacyCallHandler";
import { CallStore } from "../../../src/stores/CallStore";
import { Call } from "../../../src/models/Call";
import { PosthogAnalytics } from "../../../src/PosthogAnalytics";
import PlatformPeg from "../../../src/PlatformPeg";
import EventIndexPeg from "../../../src/indexing/EventIndexPeg";
import * as Lifecycle from "../../../src/Lifecycle";
import { SSO_HOMESERVER_URL_KEY, SSO_ID_SERVER_URL_KEY } from "../../../src/BasePlatform";
import SettingsStore from "../../../src/settings/SettingsStore";
import { SettingLevel } from "../../../src/settings/SettingLevel";
import { MatrixClientPeg as peg } from "../../../src/MatrixClientPeg";
import DMRoomMap from "../../../src/utils/DMRoomMap";
import { ReleaseAnnouncementStore } from "../../../src/stores/ReleaseAnnouncementStore";
import { DRAFT_LAST_CLEANUP_KEY } from "../../../src/DraftCleaner";
import { UIFeature } from "../../../src/settings/UIFeature";
jest.mock("matrix-js-sdk/src/oidc/authorize", () => ({
completeAuthorizationCodeGrant: jest.fn(),
}));
/** The matrix versions our mock server claims to support */
const SERVER_SUPPORTED_MATRIX_VERSIONS = ["v1.1", "v1.5", "v1.6", "v1.8", "v1.9"];
describe("<MatrixChat />", () => {
const userId = "@alice:server.org";
const deviceId = "qwertyui";
const accessToken = "abc123";
// reused in createClient mock below
const getMockClientMethods = () => ({
...mockClientMethodsUser(userId),
...mockClientMethodsServer(),
getVersions: jest.fn().mockResolvedValue({ versions: SERVER_SUPPORTED_MATRIX_VERSIONS }),
startClient: jest.fn(),
stopClient: jest.fn(),
setCanResetTimelineCallback: jest.fn(),
isInitialSyncComplete: jest.fn(),
getSyncState: jest.fn(),
getSsoLoginUrl: jest.fn(),
getSyncStateData: jest.fn().mockReturnValue(null),
getThirdpartyProtocols: jest.fn().mockResolvedValue({}),
getClientWellKnown: jest.fn().mockReturnValue({}),
isVersionSupported: jest.fn().mockResolvedValue(false),
isCryptoEnabled: jest.fn().mockReturnValue(false),
initRustCrypto: jest.fn(),
getRoom: jest.fn(),
getMediaHandler: jest.fn().mockReturnValue({
setVideoInput: jest.fn(),
setAudioInput: jest.fn(),
setAudioSettings: jest.fn(),
stopAllStreams: jest.fn(),
} as unknown as MediaHandler),
setAccountData: jest.fn(),
store: {
destroy: jest.fn(),
startup: jest.fn(),
},
login: jest.fn(),
loginFlows: jest.fn(),
isGuest: jest.fn().mockReturnValue(false),
clearStores: jest.fn(),
setGuest: jest.fn(),
setNotifTimelineSet: jest.fn(),
getAccountData: jest.fn(),
doesServerSupportUnstableFeature: jest.fn(),
getDevices: jest.fn().mockResolvedValue({ devices: [] }),
getProfileInfo: jest.fn(),
getVisibleRooms: jest.fn().mockReturnValue([]),
getRooms: jest.fn().mockReturnValue([]),
userHasCrossSigningKeys: jest.fn(),
setGlobalBlacklistUnverifiedDevices: jest.fn(),
setGlobalErrorOnUnknownDevices: jest.fn(),
getCrypto: jest.fn(),
secretStorage: {
isStored: jest.fn().mockReturnValue(null),
},
matrixRTC: createStubMatrixRTC(),
getDehydratedDevice: jest.fn(),
whoami: jest.fn(),
isRoomEncrypted: jest.fn(),
logout: jest.fn(),
getDeviceId: jest.fn(),
});
let mockClient: Mocked<MatrixClient>;
const serverConfig = {
hsUrl: "https://test.com",
hsName: "Test Server",
hsNameIsDifferent: false,
isUrl: "https://is.com",
isDefault: true,
isNameResolvable: true,
warning: "",
};
const defaultProps: ComponentProps<typeof MatrixChat> = {
config: {
brand: "Test",
help_url: "help_url",
help_encryption_url: "help_encryption_url",
element_call: {},
feedback: {
existing_issues_url: "https://feedback.org/existing",
new_issue_url: "https://feedback.org/new",
},
validated_server_config: serverConfig,
},
onNewScreen: jest.fn(),
onTokenLoginCompleted: jest.fn(),
realQueryParams: {},
};
const getComponent = (props: Partial<ComponentProps<typeof MatrixChat>> = {}) =>
render(<MatrixChat {...defaultProps} {...props} />);
// make test results readable
filterConsole(
"Failed to parse localStorage object",
"Sync store cannot be used on this browser",
"Crypto store cannot be used on this browser",
"Storage consistency checks failed",
"LegacyCallHandler: missing <audio",
);
/** populate storage with details of a persisted session */
async function populateStorageForSession() {
localStorage.setItem("mx_hs_url", serverConfig.hsUrl);
localStorage.setItem("mx_is_url", serverConfig.isUrl);
// TODO: nowadays the access token lives (encrypted) in indexedDB, and localstorage is only used as a fallback.
localStorage.setItem("mx_access_token", accessToken);
localStorage.setItem("mx_user_id", userId);
localStorage.setItem("mx_device_id", deviceId);
}
/**
* Wait for a bunch of stuff to happen
* between deciding we are logged in and removing the spinner
* including waiting for initial sync
*/
const waitForSyncAndLoad = async (client: MatrixClient, withoutSecuritySetup?: boolean): Promise<void> => {
// need to wait for different elements depending on which flow
// without security setup we go to a loading page
if (withoutSecuritySetup) {
// we think we are logged in, but are still waiting for the /sync to complete
await screen.findByText("Logout");
// initial sync
client.emit(ClientEvent.Sync, SyncState.Prepared, null);
// wait for logged in view to load
await screen.findByLabelText("User menu");
// otherwise we stay on login and load from there for longer
} else {
// we are logged in, but are still waiting for the /sync to complete
await screen.findByText("Syncing…");
// initial sync
client.emit(ClientEvent.Sync, SyncState.Prepared, null);
}
// let things settle
await flushPromises();
// and some more for good measure
// this proved to be a little flaky
await flushPromises();
};
beforeEach(async () => {
mockClient = getMockClientWithEventEmitter(getMockClientMethods());
fetchMock.get("https://test.com/_matrix/client/versions", {
unstable_features: {},
versions: SERVER_SUPPORTED_MATRIX_VERSIONS,
});
fetchMock.catch({
status: 404,
body: '{"errcode": "M_UNRECOGNIZED", "error": "Unrecognized request"}',
headers: { "content-type": "application/json" },
});
jest.spyOn(StorageAccess, "idbLoad").mockReset();
jest.spyOn(StorageAccess, "idbSave").mockResolvedValue(undefined);
jest.spyOn(defaultDispatcher, "dispatch").mockClear();
jest.spyOn(defaultDispatcher, "fire").mockClear();
DMRoomMap.makeShared(mockClient);
await clearAllModals();
});
resetJsDomAfterEach();
afterEach(() => {
// @ts-ignore
DMRoomMap.setShared(null);
jest.restoreAllMocks();
// emit a loggedOut event so that all of the Store singletons forget about their references to the mock client
defaultDispatcher.dispatch({ action: Action.OnLoggedOut });
});
it("should render spinner while app is loading", () => {
const { container } = getComponent();
expect(container).toMatchSnapshot();
});
it("should fire to focus the message composer", async () => {
getComponent();
defaultDispatcher.dispatch({ action: Action.ViewRoom, room_id: "!room:server.org", focusNext: "composer" });
await waitFor(() => {
expect(defaultDispatcher.fire).toHaveBeenCalledWith(Action.FocusSendMessageComposer);
});
});
it("should fire to focus the threads panel", async () => {
getComponent();
defaultDispatcher.dispatch({ action: Action.ViewRoom, room_id: "!room:server.org", focusNext: "threadsPanel" });
await waitFor(() => {
expect(defaultDispatcher.fire).toHaveBeenCalledWith(Action.FocusThreadsPanel);
});
});
describe("when query params have a OIDC params", () => {
const issuer = "https://auth.com/";
const homeserverUrl = "https://matrix.org";
const identityServerUrl = "https://is.org";
const clientId = "xyz789";
const code = "test-oidc-auth-code";
const state = "test-oidc-state";
const realQueryParams = {
code,
state: state,
};
const userId = "@alice:server.org";
const deviceId = "test-device-id";
const accessToken = "test-access-token-from-oidc";
const tokenResponse: BearerTokenResponse = {
access_token: accessToken,
refresh_token: "def456",
id_token: "ghi789",
scope: "test",
token_type: "Bearer",
expires_at: 12345,
};
let loginClient!: ReturnType<typeof getMockClientWithEventEmitter>;
const expectOIDCError = async (
errorMessage = "Something went wrong during authentication. Go to the sign in page and try again.",
): Promise<void> => {
await flushPromises();
const dialog = await screen.findByRole("dialog");
expect(within(dialog).getByText(errorMessage)).toBeInTheDocument();
// just check we're back on welcome page
expect(document.querySelector(".mx_Welcome")!).toBeInTheDocument();
};
beforeEach(() => {
mocked(completeAuthorizationCodeGrant)
.mockClear()
.mockResolvedValue({
oidcClientSettings: {
clientId,
issuer,
},
tokenResponse,
homeserverUrl,
identityServerUrl,
idTokenClaims: {
aud: "123",
iss: issuer,
sub: "123",
exp: 123,
iat: 456,
},
});
jest.spyOn(logger, "error").mockClear();
});
beforeEach(() => {
loginClient = getMockClientWithEventEmitter(getMockClientMethods());
// this is used to create a temporary client during login
jest.spyOn(MatrixJs, "createClient").mockReturnValue(loginClient);
jest.spyOn(logger, "error").mockClear();
jest.spyOn(logger, "log").mockClear();
loginClient.whoami.mockResolvedValue({
user_id: userId,
device_id: deviceId,
is_guest: false,
});
});
it("should fail when query params do not include valid code and state", async () => {
const queryParams = {
code: 123,
state: "abc",
};
getComponent({ realQueryParams: queryParams });
await flushPromises();
expect(logger.error).toHaveBeenCalledWith(
"Failed to login via OIDC",
new Error(OidcClientError.InvalidQueryParameters),
);
await expectOIDCError();
});
it("should make correct request to complete authorization", async () => {
getComponent({ realQueryParams });
await flushPromises();
expect(completeAuthorizationCodeGrant).toHaveBeenCalledWith(code, state);
});
it("should look up userId using access token", async () => {
getComponent({ realQueryParams });
await flushPromises();
// check we used a client with the correct accesstoken
expect(MatrixJs.createClient).toHaveBeenCalledWith({
baseUrl: homeserverUrl,
accessToken,
idBaseUrl: identityServerUrl,
});
expect(loginClient.whoami).toHaveBeenCalled();
});
it("should log error and return to welcome page when userId lookup fails", async () => {
loginClient.whoami.mockRejectedValue(new Error("oups"));
getComponent({ realQueryParams });
await flushPromises();
expect(logger.error).toHaveBeenCalledWith(
"Failed to login via OIDC",
new Error("Failed to retrieve userId using accessToken"),
);
await expectOIDCError();
});
it("should call onTokenLoginCompleted", async () => {
const onTokenLoginCompleted = jest.fn();
getComponent({ realQueryParams, onTokenLoginCompleted });
await flushPromises();
expect(onTokenLoginCompleted).toHaveBeenCalled();
});
describe("when login fails", () => {
beforeEach(() => {
mocked(completeAuthorizationCodeGrant).mockRejectedValue(new Error(OidcError.CodeExchangeFailed));
});
it("should log and return to welcome page with correct error when login state is not found", async () => {
mocked(completeAuthorizationCodeGrant).mockRejectedValue(
new Error(OidcError.MissingOrInvalidStoredState),
);
getComponent({ realQueryParams });
await flushPromises();
expect(logger.error).toHaveBeenCalledWith(
"Failed to login via OIDC",
new Error(OidcError.MissingOrInvalidStoredState),
);
await expectOIDCError(
"We asked the browser to remember which homeserver you use to let you sign in, but unfortunately your browser has forgotten it. Go to the sign in page and try again.",
);
});
it("should log and return to welcome page", async () => {
getComponent({ realQueryParams });
await flushPromises();
expect(logger.error).toHaveBeenCalledWith(
"Failed to login via OIDC",
new Error(OidcError.CodeExchangeFailed),
);
// warning dialog
await expectOIDCError();
});
it("should not clear storage", async () => {
getComponent({ realQueryParams });
await flushPromises();
expect(loginClient.clearStores).not.toHaveBeenCalled();
});
it("should not store clientId or issuer", async () => {
const sessionStorageSetSpy = jest.spyOn(sessionStorage.__proto__, "setItem");
getComponent({ realQueryParams });
await flushPromises();
expect(sessionStorageSetSpy).not.toHaveBeenCalledWith("mx_oidc_client_id", clientId);
expect(sessionStorageSetSpy).not.toHaveBeenCalledWith("mx_oidc_token_issuer", issuer);
});
});
describe("when login succeeds", () => {
beforeEach(() => {
jest.spyOn(StorageAccess, "idbLoad").mockImplementation(
async (_table: string, key: string | string[]) => (key === "mx_access_token" ? accessToken : null),
);
loginClient.getProfileInfo.mockResolvedValue({
displayname: "Ernie",
});
});
it("should persist login credentials", async () => {
getComponent({ realQueryParams });
await flushPromises();
expect(localStorage.getItem("mx_hs_url")).toEqual(homeserverUrl);
expect(localStorage.getItem("mx_user_id")).toEqual(userId);
expect(localStorage.getItem("mx_has_access_token")).toEqual("true");
expect(localStorage.getItem("mx_device_id")).toEqual(deviceId);
});
it("should store clientId and issuer in session storage", async () => {
getComponent({ realQueryParams });
await flushPromises();
expect(localStorage.getItem("mx_oidc_client_id")).toEqual(clientId);
expect(localStorage.getItem("mx_oidc_token_issuer")).toEqual(issuer);
});
it("should set logged in and start MatrixClient", async () => {
getComponent({ realQueryParams });
await flushPromises();
await flushPromises();
expect(logger.log).toHaveBeenCalledWith(
"setLoggedIn: mxid: " +
userId +
" deviceId: " +
deviceId +
" guest: " +
false +
" hs: " +
homeserverUrl +
" softLogout: " +
false,
" freshLogin: " + true,
);
// client successfully started
expect(defaultDispatcher.dispatch).toHaveBeenCalledWith({ action: "client_started" });
// check we get to logged in view
await waitForSyncAndLoad(loginClient, true);
});
it("should persist device language when available", async () => {
await SettingsStore.setValue("language", null, SettingLevel.DEVICE, "en");
const languageBefore = SettingsStore.getValueAt(SettingLevel.DEVICE, "language", null, true, true);
jest.spyOn(Lifecycle, "attemptDelegatedAuthLogin");
getComponent({ realQueryParams });
await flushPromises();
expect(Lifecycle.attemptDelegatedAuthLogin).toHaveBeenCalled();
const languageAfter = SettingsStore.getValueAt(SettingLevel.DEVICE, "language", null, true, true);
expect(languageBefore).toEqual(languageAfter);
});
it("should not persist device language when not available", async () => {
await SettingsStore.setValue("language", null, SettingLevel.DEVICE, undefined);
const languageBefore = SettingsStore.getValueAt(SettingLevel.DEVICE, "language", null, true, true);
jest.spyOn(Lifecycle, "attemptDelegatedAuthLogin");
getComponent({ realQueryParams });
await flushPromises();
expect(Lifecycle.attemptDelegatedAuthLogin).toHaveBeenCalled();
const languageAfter = SettingsStore.getValueAt(SettingLevel.DEVICE, "language", null, true, true);
expect(languageBefore).toEqual(languageAfter);
});
});
});
describe("with an existing session", () => {
const mockidb: Record<string, Record<string, string>> = {
acccount: {
mx_access_token: accessToken,
},
};
beforeEach(async () => {
await populateStorageForSession();
jest.spyOn(StorageAccess, "idbLoad").mockImplementation(async (table, key) => {
const safeKey = Array.isArray(key) ? key[0] : key;
return mockidb[table]?.[safeKey];
});
});
const getComponentAndWaitForReady = async (): Promise<RenderResult> => {
const renderResult = getComponent();
// we think we are logged in, but are still waiting for the /sync to complete
await screen.findByText("Logout");
// initial sync
mockClient.emit(ClientEvent.Sync, SyncState.Prepared, null);
// wait for logged in view to load
await screen.findByLabelText("User menu");
// let things settle
await flushPromises();
// and some more for good measure
// this proved to be a little flaky
await flushPromises();
return renderResult;
};
it("should render welcome page after login", async () => {
getComponent();
// we think we are logged in, but are still waiting for the /sync to complete
const logoutButton = await screen.findByText("Logout");
expect(logoutButton).toBeInTheDocument();
expect(screen.getByRole("progressbar")).toBeInTheDocument();
// initial sync
mockClient.emit(ClientEvent.Sync, SyncState.Prepared, null);
// wait for logged in view to load
await screen.findByLabelText("User menu");
// let things settle
await flushPromises();
expect(screen.queryByRole("progressbar")).not.toBeInTheDocument();
expect(screen.getByText(`Welcome ${userId}`)).toBeInTheDocument();
});
describe("clean up drafts", () => {
const roomId = "!room:server.org";
const unknownRoomId = "!room2:server.org";
const room = new Room(roomId, mockClient, userId);
const timestamp = 2345678901234;
beforeEach(() => {
localStorage.setItem(`mx_cider_state_${unknownRoomId}`, "fake_content");
localStorage.setItem(`mx_cider_state_${roomId}`, "fake_content");
mockClient.getRoom.mockImplementation((id) => [room].find((room) => room.roomId === id) || null);
});
afterEach(() => {
jest.restoreAllMocks();
});
it("should clean up drafts", async () => {
Date.now = jest.fn(() => timestamp);
localStorage.setItem(`mx_cider_state_${roomId}`, "fake_content");
localStorage.setItem(`mx_cider_state_${unknownRoomId}`, "fake_content");
await getComponentAndWaitForReady();
mockClient.emit(ClientEvent.Sync, SyncState.Syncing, SyncState.Syncing);
// let things settle
await flushPromises();
expect(localStorage.getItem(`mx_cider_state_${roomId}`)).not.toBeNull();
expect(localStorage.getItem(`mx_cider_state_${unknownRoomId}`)).toBeNull();
});
it("should clean up wysiwyg drafts", async () => {
Date.now = jest.fn(() => timestamp);
localStorage.setItem(`mx_wysiwyg_state_${roomId}`, "fake_content");
localStorage.setItem(`mx_wysiwyg_state_${unknownRoomId}`, "fake_content");
await getComponentAndWaitForReady();
mockClient.emit(ClientEvent.Sync, SyncState.Syncing, SyncState.Syncing);
// let things settle
await flushPromises();
expect(localStorage.getItem(`mx_wysiwyg_state_${roomId}`)).not.toBeNull();
expect(localStorage.getItem(`mx_wysiwyg_state_${unknownRoomId}`)).toBeNull();
});
it("should not clean up drafts before expiry", async () => {
// Set the last cleanup to the recent past
localStorage.setItem(`mx_cider_state_${unknownRoomId}`, "fake_content");
localStorage.setItem(DRAFT_LAST_CLEANUP_KEY, String(timestamp - 100));
await getComponentAndWaitForReady();
mockClient.emit(ClientEvent.Sync, SyncState.Syncing, SyncState.Syncing);
expect(localStorage.getItem(`mx_cider_state_${unknownRoomId}`)).not.toBeNull();
});
});
describe("onAction()", () => {
beforeEach(() => {
jest.spyOn(defaultDispatcher, "dispatch").mockClear();
jest.spyOn(defaultDispatcher, "fire").mockClear();
});
it("should open user device settings", async () => {
await getComponentAndWaitForReady();
defaultDispatcher.dispatch({
action: Action.ViewUserDeviceSettings,
});
await flushPromises();
expect(defaultDispatcher.dispatch).toHaveBeenCalledWith({
action: Action.ViewUserSettings,
initialTabId: UserTab.SessionManager,
});
});
describe("room actions", () => {
const roomId = "!room:server.org";
const spaceId = "!spaceRoom:server.org";
const room = new Room(roomId, mockClient, userId);
const spaceRoom = new Room(spaceId, mockClient, userId);
beforeEach(() => {
mockClient.getRoom.mockImplementation(
(id) => [room, spaceRoom].find((room) => room.roomId === id) || null,
);
jest.spyOn(spaceRoom, "isSpaceRoom").mockReturnValue(true);
jest.spyOn(ReleaseAnnouncementStore.instance, "getReleaseAnnouncement").mockReturnValue(null);
});
afterEach(() => {
jest.restoreAllMocks();
});
describe("leave_room", () => {
beforeEach(async () => {
await clearAllModals();
await getComponentAndWaitForReady();
// this is thoroughly unit tested elsewhere
jest.spyOn(leaveRoomUtils, "leaveRoomBehaviour").mockClear().mockResolvedValue(undefined);
});
const dispatchAction = () =>
defaultDispatcher.dispatch({
action: "leave_room",
room_id: roomId,
});
const publicJoinRule = new MatrixEvent({
type: "m.room.join_rules",
content: {
join_rule: "public",
},
});
const inviteJoinRule = new MatrixEvent({
type: "m.room.join_rules",
content: {
join_rule: "invite",
},
});
describe("for a room", () => {
beforeEach(() => {
jest.spyOn(room.currentState, "getJoinedMemberCount").mockReturnValue(2);
jest.spyOn(room.currentState, "getStateEvents").mockReturnValue(publicJoinRule);
});
it("should launch a confirmation modal", async () => {
dispatchAction();
const dialog = await screen.findByRole("dialog");
expect(dialog).toMatchSnapshot();
});
it("should warn when room has only one joined member", async () => {
jest.spyOn(room.currentState, "getJoinedMemberCount").mockReturnValue(1);
dispatchAction();
await screen.findByRole("dialog");
expect(
screen.getByText(
"You are the only person here. If you leave, no one will be able to join in the future, including you.",
),
).toBeInTheDocument();
});
it("should warn when room is not public", async () => {
jest.spyOn(room.currentState, "getStateEvents").mockReturnValue(inviteJoinRule);
dispatchAction();
await screen.findByRole("dialog");
expect(
screen.getByText(
"This room is not public. You will not be able to rejoin without an invite.",
),
).toBeInTheDocument();
});
it("should do nothing on cancel", async () => {
dispatchAction();
const dialog = await screen.findByRole("dialog");
fireEvent.click(within(dialog).getByText("Cancel"));
await flushPromises();
expect(leaveRoomUtils.leaveRoomBehaviour).not.toHaveBeenCalled();
expect(defaultDispatcher.dispatch).not.toHaveBeenCalledWith({
action: Action.AfterLeaveRoom,
room_id: roomId,
});
});
it("should leave room and dispatch after leave action", async () => {
dispatchAction();
const dialog = await screen.findByRole("dialog");
fireEvent.click(within(dialog).getByText("Leave"));
await flushPromises();
expect(leaveRoomUtils.leaveRoomBehaviour).toHaveBeenCalled();
expect(defaultDispatcher.dispatch).toHaveBeenCalledWith({
action: Action.AfterLeaveRoom,
room_id: roomId,
});
});
});
describe("for a space", () => {
const dispatchAction = () =>
defaultDispatcher.dispatch({
action: "leave_room",
room_id: spaceId,
});
beforeEach(() => {
jest.spyOn(spaceRoom.currentState, "getStateEvents").mockReturnValue(publicJoinRule);
});
it("should launch a confirmation modal", async () => {
dispatchAction();
const dialog = await screen.findByRole("dialog");
expect(dialog).toMatchSnapshot();
});
it("should warn when space is not public", async () => {
jest.spyOn(spaceRoom.currentState, "getStateEvents").mockReturnValue(inviteJoinRule);
dispatchAction();
await screen.findByRole("dialog");
expect(
screen.getByText(
"This space is not public. You will not be able to rejoin without an invite.",
),
).toBeInTheDocument();
});
});
});
});
describe("logout", () => {
let logoutClient!: ReturnType<typeof getMockClientWithEventEmitter>;
const call1 = { disconnect: jest.fn() } as unknown as Call;
const call2 = { disconnect: jest.fn() } as unknown as Call;
const dispatchLogoutAndWait = async (): Promise<void> => {
defaultDispatcher.dispatch({
action: "logout",
});
await flushPromises();
};
beforeEach(() => {
// stub out various cleanup functions
jest.spyOn(LegacyCallHandler.instance, "hangupAllCalls")
.mockClear()
.mockImplementation(() => {});
jest.spyOn(voiceBroadcastUtils, "cleanUpBroadcasts").mockImplementation(async () => {});
jest.spyOn(PosthogAnalytics.instance, "logout").mockImplementation(() => {});
jest.spyOn(EventIndexPeg, "deleteEventIndex").mockImplementation(async () => {});
jest.spyOn(CallStore.instance, "connectedCalls", "get").mockReturnValue(new Set([call1, call2]));
mockPlatformPeg({
destroyPickleKey: jest.fn(),
});
logoutClient = getMockClientWithEventEmitter(getMockClientMethods());
mockClient = getMockClientWithEventEmitter(getMockClientMethods());
mockClient.logout.mockResolvedValue({});
mockClient.getDeviceId.mockReturnValue(deviceId);
// this is used to create a temporary client to cleanup after logout
jest.spyOn(MatrixJs, "createClient").mockClear().mockReturnValue(logoutClient);
jest.spyOn(logger, "warn").mockClear();
});
afterAll(() => {
jest.spyOn(voiceBroadcastUtils, "cleanUpBroadcasts").mockRestore();
});
it("should hangup all legacy calls", async () => {
await getComponentAndWaitForReady();
await dispatchLogoutAndWait();
expect(LegacyCallHandler.instance.hangupAllCalls).toHaveBeenCalled();
});
it("should cleanup broadcasts", async () => {
await getComponentAndWaitForReady();
await dispatchLogoutAndWait();
expect(voiceBroadcastUtils.cleanUpBroadcasts).toHaveBeenCalled();
});
it("should disconnect all calls", async () => {
await getComponentAndWaitForReady();
await dispatchLogoutAndWait();
expect(call1.disconnect).toHaveBeenCalled();
expect(call2.disconnect).toHaveBeenCalled();
});
it("should logout of posthog", async () => {
await getComponentAndWaitForReady();
await dispatchLogoutAndWait();
expect(PosthogAnalytics.instance.logout).toHaveBeenCalled();
});
it("should destroy pickle key", async () => {
await getComponentAndWaitForReady();
await dispatchLogoutAndWait();
expect(PlatformPeg.get()!.destroyPickleKey).toHaveBeenCalledWith(userId, deviceId);
});
describe("without delegated auth", () => {
it("should call /logout", async () => {
await getComponentAndWaitForReady();
await dispatchLogoutAndWait();
expect(mockClient.logout).toHaveBeenCalledWith(true);
});
it("should warn and do post-logout cleanup anyway when logout fails", async () => {
const error = new Error("test logout failed");
mockClient.logout.mockRejectedValue(error);
await getComponentAndWaitForReady();
await dispatchLogoutAndWait();
expect(logger.warn).toHaveBeenCalledWith(
"Failed to call logout API: token will not be invalidated",
error,
);
// stuff that happens in onloggedout
expect(defaultDispatcher.fire).toHaveBeenCalledWith(Action.OnLoggedOut, true);
expect(logoutClient.clearStores).toHaveBeenCalled();
});
it("should do post-logout cleanup", async () => {
await getComponentAndWaitForReady();
await dispatchLogoutAndWait();
// stuff that happens in onloggedout
expect(defaultDispatcher.fire).toHaveBeenCalledWith(Action.OnLoggedOut, true);
expect(EventIndexPeg.deleteEventIndex).toHaveBeenCalled();
expect(logoutClient.clearStores).toHaveBeenCalled();
});
});
});
});
});
describe("with a soft-logged-out session", () => {
const mockidb: Record<string, Record<string, string>> = {};
beforeEach(async () => {
await populateStorageForSession();
localStorage.setItem("mx_soft_logout", "true");
mockClient.loginFlows.mockResolvedValue({ flows: [{ type: "m.login.password" }] });
jest.spyOn(StorageAccess, "idbLoad").mockImplementation(async (table, key) => {
const safeKey = Array.isArray(key) ? key[0] : key;
return mockidb[table]?.[safeKey];
});
});
it("should show the soft-logout page", async () => {
// XXX This test is strange, it was working with legacy crypto
// without mocking the following but the initCrypto call was failing
// but as the exception was swallowed, the test was passing (see in `initClientCrypto`).
// There are several uses of the peg in the app, so during all these tests you might end-up
// with a real client instead of the mocked one. Not sure how reliable all these tests are.
const originalReplace = peg.replaceUsingCreds;
peg.replaceUsingCreds = jest.fn().mockResolvedValue(mockClient);
// @ts-ignore - need to mock this for the test
peg.matrixClient = mockClient;
const result = getComponent();
await result.findByText("You're signed out");
expect(result.container).toMatchSnapshot();
peg.replaceUsingCreds = originalReplace;
});
});
describe("login via key/pass", () => {
let loginClient!: ReturnType<typeof getMockClientWithEventEmitter>;
const userName = "ernie";
const password = "ilovebert";
const getComponentAndWaitForReady = async (): Promise<RenderResult> => {
const renderResult = getComponent();
// wait for welcome page chrome render
await screen.findByText("powered by Matrix");
// go to login page
defaultDispatcher.dispatch({
action: "start_login",
});
await flushPromises();
return renderResult;
};
const getComponentAndLogin = async (withoutSecuritySetup?: boolean): Promise<void> => {
await getComponentAndWaitForReady();
fireEvent.change(screen.getByLabelText("Username"), { target: { value: userName } });
fireEvent.change(screen.getByLabelText("Password"), { target: { value: password } });
// sign in button is an input
fireEvent.click(screen.getByDisplayValue("Sign in"));
await waitForSyncAndLoad(loginClient, withoutSecuritySetup);
};
beforeEach(() => {
loginClient = getMockClientWithEventEmitter(getMockClientMethods());
// this is used to create a temporary client during login
// FIXME: except it is *also* used as the permanent client for the rest of the test.
jest.spyOn(MatrixJs, "createClient").mockClear().mockReturnValue(loginClient);
loginClient.login.mockClear().mockResolvedValue({
access_token: "TOKEN",
device_id: "IMADEVICE",
user_id: userId,
});
loginClient.loginFlows.mockClear().mockResolvedValue({ flows: [{ type: "m.login.password" }] });
loginClient.getProfileInfo.mockResolvedValue({
displayname: "Ernie",
});
});
it("should render login page", async () => {
await getComponentAndWaitForReady();
expect(screen.getAllByText("Sign in")[0]).toBeInTheDocument();
});
describe("post login setup", () => {
beforeEach(() => {
const mockCrypto = {
getVersion: jest.fn().mockReturnValue("Version 0"),
getVerificationRequestsToDeviceInProgress: jest.fn().mockReturnValue([]),