This repository was archived by the owner on Sep 11, 2024. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 825
/
Copy pathDecryptionFailureTracker-test.ts
743 lines (596 loc) · 28.4 KB
/
DecryptionFailureTracker-test.ts
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
/*
Copyright 2018 New Vector Ltd
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.
*/
import { mocked, Mocked, MockedObject } from "jest-mock";
import { CryptoEvent, HttpApiEvent, MatrixClient, MatrixEvent, MatrixEventEvent } from "matrix-js-sdk/src/matrix";
import { decryptExistingEvent, mkDecryptionFailureMatrixEvent } from "matrix-js-sdk/src/testing";
import { CryptoApi, DecryptionFailureCode, UserVerificationStatus } from "matrix-js-sdk/src/crypto-api";
import { sleep } from "matrix-js-sdk/src/utils";
import { DecryptionFailureTracker, ErrorProperties } from "../src/DecryptionFailureTracker";
import { stubClient } from "./test-utils";
import * as Lifecycle from "../src/Lifecycle";
async function createFailedDecryptionEvent(opts: { sender?: string; code?: DecryptionFailureCode } = {}) {
return await mkDecryptionFailureMatrixEvent({
roomId: "!room:id",
sender: opts.sender ?? "@alice:example.com",
code: opts.code ?? DecryptionFailureCode.UNKNOWN_ERROR,
msg: ":(",
});
}
// wrap tracker.eventDecrypted so that we don't need to have so many `ts-ignore`s
function eventDecrypted(tracker: DecryptionFailureTracker, e: MatrixEvent, nowTs: number): void {
// @ts-ignore access to private member
return tracker.eventDecrypted(e, nowTs);
}
describe("DecryptionFailureTracker", function () {
afterEach(() => {
localStorage.clear();
});
it("tracks a failed decryption for a visible event", async function () {
const failedDecryptionEvent = await createFailedDecryptionEvent();
let count = 0;
// @ts-ignore access to private constructor
const tracker = new DecryptionFailureTracker(
() => count++,
() => "UnknownError",
false,
);
tracker.addVisibleEvent(failedDecryptionEvent);
eventDecrypted(tracker, failedDecryptionEvent, Date.now());
// Pretend "now" is Infinity
tracker.checkFailures(Infinity);
// should track a failure for an event that failed decryption
expect(count).not.toBe(0);
});
it("tracks a failed decryption with expected raw error for a visible event", async function () {
const failedDecryptionEvent = await createFailedDecryptionEvent({
code: DecryptionFailureCode.OLM_UNKNOWN_MESSAGE_INDEX,
});
let count = 0;
let reportedRawCode = "";
// @ts-ignore access to private constructor
const tracker = new DecryptionFailureTracker(
(_errCode: string, rawCode: string) => {
count++;
reportedRawCode = rawCode;
},
() => "UnknownError",
false,
);
tracker.addVisibleEvent(failedDecryptionEvent);
eventDecrypted(tracker, failedDecryptionEvent, Date.now());
// Pretend "now" is Infinity
tracker.checkFailures(Infinity);
// should track a failure for an event that failed decryption
expect(count).not.toBe(0);
// Should add the rawCode to the event context
expect(reportedRawCode).toBe("OLM_UNKNOWN_MESSAGE_INDEX");
});
it("tracks a failed decryption for an event that becomes visible later", async function () {
const failedDecryptionEvent = await createFailedDecryptionEvent();
let count = 0;
// @ts-ignore access to private constructor
const tracker = new DecryptionFailureTracker(
() => count++,
() => "UnknownError",
false,
);
eventDecrypted(tracker, failedDecryptionEvent, Date.now());
tracker.addVisibleEvent(failedDecryptionEvent);
// Pretend "now" is Infinity
tracker.checkFailures(Infinity);
// should track a failure for an event that failed decryption
expect(count).not.toBe(0);
});
it("tracks visible vs. not visible events", async () => {
const propertiesByErrorCode: Record<string, ErrorProperties> = {};
// @ts-ignore access to private constructor
const tracker = new DecryptionFailureTracker(
(errorCode: string, rawError: string, properties: ErrorProperties) => {
propertiesByErrorCode[errorCode] = properties;
},
(error: string) => error,
false,
);
// use three different errors so that we can distinguish the reports
const error1 = DecryptionFailureCode.MEGOLM_UNKNOWN_INBOUND_SESSION_ID;
const error2 = DecryptionFailureCode.MEGOLM_BAD_ROOM;
const error3 = DecryptionFailureCode.MEGOLM_MISSING_FIELDS;
// event that will be marked as visible before it's marked as undecryptable
const markedVisibleFirst = await createFailedDecryptionEvent({ code: error1 });
// event that will be marked as undecryptable before it's marked as visible
const markedUndecryptableFirst = await createFailedDecryptionEvent({ code: error2 });
// event that is never marked as visible
const neverVisible = await createFailedDecryptionEvent({ code: error3 });
tracker.addVisibleEvent(markedVisibleFirst);
const now = Date.now();
eventDecrypted(tracker, markedVisibleFirst, now);
eventDecrypted(tracker, markedUndecryptableFirst, now);
eventDecrypted(tracker, neverVisible, now);
tracker.addVisibleEvent(markedUndecryptableFirst);
// Pretend "now" is Infinity
tracker.checkFailures(Infinity);
expect(propertiesByErrorCode[error1].wasVisibleToUser).toBe(true);
expect(propertiesByErrorCode[error2].wasVisibleToUser).toBe(true);
expect(propertiesByErrorCode[error3].wasVisibleToUser).toBe(false);
});
it("does not track a failed decryption where the event is subsequently successfully decrypted", async () => {
const decryptedEvent = await createFailedDecryptionEvent();
// @ts-ignore access to private constructor
const tracker = new DecryptionFailureTracker(
() => {
// should not track an event that has since been decrypted correctly
expect(true).toBe(false);
},
() => "UnknownError",
false,
);
tracker.addVisibleEvent(decryptedEvent);
eventDecrypted(tracker, decryptedEvent, Date.now());
// Indicate successful decryption.
await decryptExistingEvent(decryptedEvent, {
plainType: "m.room.message",
plainContent: { body: "success" },
});
eventDecrypted(tracker, decryptedEvent, Date.now());
// Pretend "now" is Infinity
tracker.checkFailures(Infinity);
});
it(
"does not track a failed decryption where the event is subsequently successfully decrypted " +
"and later becomes visible",
async () => {
const decryptedEvent = await createFailedDecryptionEvent();
// @ts-ignore access to private constructor
const tracker = new DecryptionFailureTracker(
() => {
// should not track an event that has since been decrypted correctly
expect(true).toBe(false);
},
() => "UnknownError",
false,
);
eventDecrypted(tracker, decryptedEvent, Date.now());
// Indicate successful decryption.
await decryptExistingEvent(decryptedEvent, {
plainType: "m.room.message",
plainContent: { body: "success" },
});
eventDecrypted(tracker, decryptedEvent, Date.now());
tracker.addVisibleEvent(decryptedEvent);
// Pretend "now" is Infinity
tracker.checkFailures(Infinity);
},
);
it("only tracks a single failure per event, despite multiple failed decryptions for multiple events", async () => {
const decryptedEvent = await createFailedDecryptionEvent();
const decryptedEvent2 = await createFailedDecryptionEvent();
let count = 0;
// @ts-ignore access to private constructor
const tracker = new DecryptionFailureTracker(
() => count++,
() => "UnknownError",
false,
);
tracker.addVisibleEvent(decryptedEvent);
// Arbitrary number of failed decryptions for both events
const now = Date.now();
eventDecrypted(tracker, decryptedEvent, now);
eventDecrypted(tracker, decryptedEvent, now);
eventDecrypted(tracker, decryptedEvent, now);
eventDecrypted(tracker, decryptedEvent, now);
eventDecrypted(tracker, decryptedEvent, now);
eventDecrypted(tracker, decryptedEvent2, now);
eventDecrypted(tracker, decryptedEvent2, now);
tracker.addVisibleEvent(decryptedEvent2);
eventDecrypted(tracker, decryptedEvent2, now);
// Pretend "now" is Infinity
tracker.checkFailures(Infinity);
// Simulated polling of `checkFailures`, an arbitrary number ( > 2 ) times
tracker.checkFailures(Infinity);
tracker.checkFailures(Infinity);
// should only track a single failure per event
expect(count).toBe(2);
});
it("should not track a failure for an event that was tracked previously", async () => {
const decryptedEvent = await createFailedDecryptionEvent();
let count = 0;
// @ts-ignore access to private constructor
const tracker = new DecryptionFailureTracker(
() => count++,
() => "UnknownError",
);
await tracker.start(mockClient());
tracker.addVisibleEvent(decryptedEvent);
// Indicate decryption
eventDecrypted(tracker, decryptedEvent, Date.now());
// Pretend "now" is Infinity
tracker.checkFailures(Infinity);
// Indicate a second decryption, after having tracked the failure
eventDecrypted(tracker, decryptedEvent, Date.now());
tracker.checkFailures(Infinity);
// should only track a single failure per event
expect(count).toBe(1);
});
it("should not report a failure for an event that was reported in a previous session", async () => {
const decryptedEvent = await createFailedDecryptionEvent();
let count = 0;
// @ts-ignore access to private constructor
const tracker = new DecryptionFailureTracker(
() => count++,
() => "UnknownError",
);
await tracker.start(mockClient());
tracker.addVisibleEvent(decryptedEvent);
// Indicate decryption
eventDecrypted(tracker, decryptedEvent, Date.now());
// Pretend "now" is Infinity
// NB: This saves to localStorage specific to DFT
tracker.checkFailures(Infinity);
// Simulate the browser refreshing by destroying tracker and creating a new tracker
// @ts-ignore access to private constructor
const secondTracker = new DecryptionFailureTracker(
() => count++,
() => "UnknownError",
);
await secondTracker.start(mockClient());
secondTracker.addVisibleEvent(decryptedEvent);
eventDecrypted(secondTracker, decryptedEvent, Date.now());
secondTracker.checkFailures(Infinity);
// should only track a single failure per event
expect(count).toBe(1);
});
it("should report a failure for an event that was tracked but not reported in a previous session", async () => {
const decryptedEvent = await createFailedDecryptionEvent();
let count = 0;
// @ts-ignore access to private constructor
const tracker = new DecryptionFailureTracker(
() => count++,
() => "UnknownError",
);
await tracker.start(mockClient());
tracker.addVisibleEvent(decryptedEvent);
// Indicate decryption
eventDecrypted(tracker, decryptedEvent, Date.now());
// we do *not* call `checkFailures` here
expect(count).toBe(0);
// Simulate the browser refreshing by destroying tracker and creating a new tracker
// @ts-ignore access to private constructor
const secondTracker = new DecryptionFailureTracker(
() => count++,
() => "UnknownError",
);
await secondTracker.start(mockClient());
secondTracker.addVisibleEvent(decryptedEvent);
eventDecrypted(secondTracker, decryptedEvent, Date.now());
secondTracker.checkFailures(Infinity);
expect(count).toBe(1);
});
it("should report a failure for an event that was reported before a logout/login cycle", async () => {
const decryptedEvent = await createFailedDecryptionEvent();
let count = 0;
// @ts-ignore access to private constructor
const tracker = new DecryptionFailureTracker(
() => count++,
() => "UnknownError",
);
await tracker.start(mockClient());
tracker.addVisibleEvent(decryptedEvent);
// Indicate decryption
eventDecrypted(tracker, decryptedEvent, Date.now());
tracker.checkFailures(Infinity);
expect(count).toBe(1);
// Simulate a logout/login cycle
await Lifecycle.onLoggedOut();
await tracker.start(mockClient());
tracker.addVisibleEvent(decryptedEvent);
eventDecrypted(tracker, decryptedEvent, Date.now());
tracker.checkFailures(Infinity);
expect(count).toBe(2);
});
it("should count different error codes separately for multiple failures with different error codes", async () => {
const counts: Record<string, number> = {};
// @ts-ignore access to private constructor
const tracker = new DecryptionFailureTracker(
(errorCode: string) => (counts[errorCode] = (counts[errorCode] || 0) + 1),
(error: DecryptionFailureCode) =>
error === DecryptionFailureCode.UNKNOWN_ERROR ? "UnknownError" : "OlmKeysNotSentError",
false,
);
const decryptedEvent1 = await createFailedDecryptionEvent({
code: DecryptionFailureCode.UNKNOWN_ERROR,
});
const decryptedEvent2 = await createFailedDecryptionEvent({
code: DecryptionFailureCode.MEGOLM_UNKNOWN_INBOUND_SESSION_ID,
});
const decryptedEvent3 = await createFailedDecryptionEvent({
code: DecryptionFailureCode.MEGOLM_UNKNOWN_INBOUND_SESSION_ID,
});
tracker.addVisibleEvent(decryptedEvent1);
tracker.addVisibleEvent(decryptedEvent2);
tracker.addVisibleEvent(decryptedEvent3);
// One failure of UNKNOWN_ERROR, and effectively two for MEGOLM_UNKNOWN_INBOUND_SESSION_ID
const now = Date.now();
eventDecrypted(tracker, decryptedEvent1, now);
eventDecrypted(tracker, decryptedEvent2, now);
eventDecrypted(tracker, decryptedEvent2, now);
eventDecrypted(tracker, decryptedEvent3, now);
// Pretend "now" is Infinity
tracker.checkFailures(Infinity);
//expect(counts['UnknownError']).toBe(1, 'should track one UnknownError');
expect(counts["OlmKeysNotSentError"]).toBe(2);
});
it("should aggregate error codes correctly", async () => {
const counts: Record<string, number> = {};
// @ts-ignore access to private constructor
const tracker = new DecryptionFailureTracker(
(errorCode: string) => (counts[errorCode] = (counts[errorCode] || 0) + 1),
(_errorCode: string) => "OlmUnspecifiedError",
false,
);
const decryptedEvent1 = await createFailedDecryptionEvent({
code: DecryptionFailureCode.MEGOLM_UNKNOWN_INBOUND_SESSION_ID,
});
const decryptedEvent2 = await createFailedDecryptionEvent({
code: DecryptionFailureCode.OLM_UNKNOWN_MESSAGE_INDEX,
});
const decryptedEvent3 = await createFailedDecryptionEvent({
code: DecryptionFailureCode.UNKNOWN_ERROR,
});
tracker.addVisibleEvent(decryptedEvent1);
tracker.addVisibleEvent(decryptedEvent2);
tracker.addVisibleEvent(decryptedEvent3);
const now = Date.now();
eventDecrypted(tracker, decryptedEvent1, now);
eventDecrypted(tracker, decryptedEvent2, now);
eventDecrypted(tracker, decryptedEvent3, now);
// Pretend "now" is Infinity
tracker.checkFailures(Infinity);
expect(counts["OlmUnspecifiedError"]).toBe(3);
});
it("should remap error codes correctly", async () => {
const counts: Record<string, number> = {};
// @ts-ignore access to private constructor
const tracker = new DecryptionFailureTracker(
(errorCode: string) => (counts[errorCode] = (counts[errorCode] || 0) + 1),
(errorCode: string) => Array.from(errorCode).reverse().join(""),
false,
);
const decryptedEvent = await createFailedDecryptionEvent({
code: DecryptionFailureCode.OLM_UNKNOWN_MESSAGE_INDEX,
});
tracker.addVisibleEvent(decryptedEvent);
eventDecrypted(tracker, decryptedEvent, Date.now());
// Pretend "now" is Infinity
tracker.checkFailures(Infinity);
// should track remapped error code
expect(counts["XEDNI_EGASSEM_NWONKNU_MLO"]).toBe(1);
});
it("default error code mapper maps error codes correctly", async () => {
const errorCodes: string[] = [];
// @ts-ignore access to private constructor
const tracker = new DecryptionFailureTracker(
(errorCode: string) => {
errorCodes.push(errorCode);
},
// @ts-ignore access to private member
DecryptionFailureTracker.instance.errorCodeMapFn,
false,
);
const now = Date.now();
async function createAndTrackEventWithError(code: DecryptionFailureCode) {
const event = await createFailedDecryptionEvent({ code });
tracker.addVisibleEvent(event);
eventDecrypted(tracker, event, now);
return event;
}
await createAndTrackEventWithError(DecryptionFailureCode.MEGOLM_UNKNOWN_INBOUND_SESSION_ID);
await createAndTrackEventWithError(DecryptionFailureCode.OLM_UNKNOWN_MESSAGE_INDEX);
await createAndTrackEventWithError(DecryptionFailureCode.HISTORICAL_MESSAGE_NO_KEY_BACKUP);
await createAndTrackEventWithError(DecryptionFailureCode.HISTORICAL_MESSAGE_BACKUP_UNCONFIGURED);
await createAndTrackEventWithError(DecryptionFailureCode.HISTORICAL_MESSAGE_WORKING_BACKUP);
await createAndTrackEventWithError(DecryptionFailureCode.HISTORICAL_MESSAGE_USER_NOT_JOINED);
await createAndTrackEventWithError(DecryptionFailureCode.MEGOLM_KEY_WITHHELD);
await createAndTrackEventWithError(DecryptionFailureCode.MEGOLM_KEY_WITHHELD_FOR_UNVERIFIED_DEVICE);
await createAndTrackEventWithError(DecryptionFailureCode.UNKNOWN_ERROR);
// Pretend "now" is Infinity
tracker.checkFailures(Infinity);
expect(errorCodes).toEqual([
"OlmKeysNotSentError",
"OlmIndexError",
"HistoricalMessage",
"HistoricalMessage",
"HistoricalMessage",
"ExpectedDueToMembership",
"OlmKeysNotSentError",
"RoomKeysWithheldForUnverifiedDevice",
"UnknownError",
]);
});
it("tracks late decryptions vs. undecryptable", async () => {
const propertiesByErrorCode: Record<string, ErrorProperties> = {};
// @ts-ignore access to private constructor
const tracker = new DecryptionFailureTracker(
(errorCode: string, rawError: string, properties: ErrorProperties) => {
propertiesByErrorCode[errorCode] = properties;
},
(error: string) => error,
false,
);
// use three different errors so that we can distinguish the reports
const error1 = DecryptionFailureCode.MEGOLM_UNKNOWN_INBOUND_SESSION_ID;
const error2 = DecryptionFailureCode.MEGOLM_BAD_ROOM;
const error3 = DecryptionFailureCode.MEGOLM_MISSING_FIELDS;
// event that will be slow to decrypt
const lateDecryption = await createFailedDecryptionEvent({ code: error1 });
// event that will be so slow to decrypt, it gets counted as undecryptable
const veryLateDecryption = await createFailedDecryptionEvent({ code: error2 });
// event that never gets decrypted
const neverDecrypted = await createFailedDecryptionEvent({ code: error3 });
tracker.addVisibleEvent(lateDecryption);
tracker.addVisibleEvent(veryLateDecryption);
tracker.addVisibleEvent(neverDecrypted);
const now = Date.now();
eventDecrypted(tracker, lateDecryption, now);
eventDecrypted(tracker, veryLateDecryption, now);
eventDecrypted(tracker, neverDecrypted, now);
await decryptExistingEvent(lateDecryption, {
plainType: "m.room.message",
plainContent: { body: "success" },
});
await decryptExistingEvent(veryLateDecryption, {
plainType: "m.room.message",
plainContent: { body: "success" },
});
eventDecrypted(tracker, lateDecryption, now + 40000);
eventDecrypted(tracker, veryLateDecryption, now + 100000);
// Pretend "now" is Infinity
tracker.checkFailures(Infinity);
expect(propertiesByErrorCode[error1].timeToDecryptMillis).toEqual(40000);
expect(propertiesByErrorCode[error2].timeToDecryptMillis).toEqual(-1);
expect(propertiesByErrorCode[error3].timeToDecryptMillis).toEqual(-1);
});
it("listens for client events", async () => {
// Test that the decryption failure tracker registers the right event
// handlers on start, and unregisters them when the client logs out.
const client = mockClient();
let errorCount: number = 0;
// @ts-ignore access to private constructor
const tracker = new DecryptionFailureTracker(
(errorCode: string, rawError: string, properties: ErrorProperties) => {
errorCount++;
},
(error: string) => error,
false,
);
// Calling .start will start some intervals. This test shouldn't run
// long enough for the timers to fire, but we'll use fake timers just
// to be safe.
jest.useFakeTimers();
await tracker.start(client);
// If the client fails to decrypt, it should get tracked
const failedDecryption = await createFailedDecryptionEvent();
client.emit(MatrixEventEvent.Decrypted, failedDecryption);
tracker.checkFailures(Infinity);
expect(errorCount).toEqual(1);
client.emit(HttpApiEvent.SessionLoggedOut, {} as any);
// After the client has logged out, we shouldn't be listening to events
// any more, so even if the client emits an event regarding a failed
// decryption, we won't track it.
const anotherFailedDecryption = await createFailedDecryptionEvent();
client.emit(MatrixEventEvent.Decrypted, anotherFailedDecryption);
// Pretend "now" is Infinity
tracker.checkFailures(Infinity);
expect(errorCount).toEqual(1);
jest.useRealTimers();
});
it("tracks client information", async () => {
const client = mockClient();
const propertiesByErrorCode: Record<string, ErrorProperties> = {};
// @ts-ignore access to private constructor
const tracker = new DecryptionFailureTracker(
(errorCode: string, rawError: string, properties: ErrorProperties) => {
propertiesByErrorCode[errorCode] = properties;
},
(error: string) => error,
false,
);
// @ts-ignore access to private method
await tracker.calculateClientProperties(client);
// @ts-ignore access to private method
await tracker.registerHandlers(client);
// use three different errors so that we can distinguish the reports
const error1 = DecryptionFailureCode.MEGOLM_UNKNOWN_INBOUND_SESSION_ID;
const error2 = DecryptionFailureCode.MEGOLM_BAD_ROOM;
const error3 = DecryptionFailureCode.MEGOLM_MISSING_FIELDS;
// event from a federated user (@alice:example.com)
const federatedDecryption = await createFailedDecryptionEvent({
code: error1,
});
// event from a local user
const localDecryption = await createFailedDecryptionEvent({
sender: "@bob:matrix.org",
code: error2,
});
tracker.addVisibleEvent(federatedDecryption);
tracker.addVisibleEvent(localDecryption);
const now = Date.now();
eventDecrypted(tracker, federatedDecryption, now);
mocked(client.getCrypto()!.getUserVerificationStatus).mockResolvedValue(
new UserVerificationStatus(true, true, false),
);
client.emit(CryptoEvent.KeysChanged, {});
await sleep(100);
eventDecrypted(tracker, localDecryption, now);
// Pretend "now" is Infinity
tracker.checkFailures(Infinity);
expect(propertiesByErrorCode[error1].isMatrixDotOrg).toBe(true);
expect(propertiesByErrorCode[error1].cryptoSDK).toEqual("Rust");
expect(propertiesByErrorCode[error1].isFederated).toBe(true);
expect(propertiesByErrorCode[error1].userTrustsOwnIdentity).toEqual(false);
expect(propertiesByErrorCode[error2].isFederated).toBe(false);
expect(propertiesByErrorCode[error2].userTrustsOwnIdentity).toEqual(true);
// change client params, and make sure the reports the right values
client.getDomain.mockReturnValue("example.com");
mocked(client.getCrypto()!.getVersion).mockReturnValue("Olm 0.0.0");
// @ts-ignore access to private method
await tracker.calculateClientProperties(client);
const anotherFailure = await createFailedDecryptionEvent({
code: error3,
});
tracker.addVisibleEvent(anotherFailure);
eventDecrypted(tracker, anotherFailure, now);
tracker.checkFailures(Infinity);
expect(propertiesByErrorCode[error3].isMatrixDotOrg).toBe(false);
expect(propertiesByErrorCode[error3].cryptoSDK).toEqual("Legacy");
});
it("keeps the original timestamp after repeated decryption failures", async () => {
const failedDecryptionEvent = await createFailedDecryptionEvent();
let failure: ErrorProperties | undefined;
// @ts-ignore access to private constructor
const tracker = new DecryptionFailureTracker(
(errorCode: string, rawError: string, properties: ErrorProperties) => {
failure = properties;
},
() => "UnknownError",
false,
);
tracker.addVisibleEvent(failedDecryptionEvent);
const now = Date.now();
eventDecrypted(tracker, failedDecryptionEvent, now);
eventDecrypted(tracker, failedDecryptionEvent, now + 20000);
await decryptExistingEvent(failedDecryptionEvent, {
plainType: "m.room.message",
plainContent: { body: "success" },
});
eventDecrypted(tracker, failedDecryptionEvent, now + 50000);
// Pretend "now" is Infinity
tracker.checkFailures(Infinity);
// the time to decrypt should be relative to the first time we failed
// to decrypt, not the second
expect(failure?.timeToDecryptMillis).toEqual(50000);
});
});
function mockClient(): MockedObject<MatrixClient> {
const client = mocked(stubClient());
const mockCrypto = {
getVersion: jest.fn().mockReturnValue("Rust SDK 0.7.0 (61b175b), Vodozemac 0.5.1"),
getUserVerificationStatus: jest.fn().mockResolvedValue(new UserVerificationStatus(false, false, false)),
} as unknown as Mocked<CryptoApi>;
client.getCrypto.mockReturnValue(mockCrypto);
// @ts-ignore
client.stopClient = jest.fn(() => {});
// @ts-ignore
client.removeAllListeners = jest.fn(() => {});
client.store = { destroy: jest.fn(() => {}) } as any;
return client;
}