summaryrefslogtreecommitdiffstats
path: root/security/manager/ssl/tests/unit/test_crlite_filters.js
blob: 55fe4d75e33ada86f67798c57396bd9bdfe37d5e (plain)
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
// -*- indent-tabs-mode: nil; js-indent-level: 2 -*-
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.

// Tests that CRLite filter downloading works correctly.

// The file `test_crlite_filters/20201017-0-filter` can be regenerated using
// the rust-create-cascade program from https://github.com/mozilla/crlite.
//
// The input to this program is a list of known serial numbers and a list of
// revoked serial numbers. The lists are presented as directories of files in
// which each file holds serials for one issuer. The file names are
// urlsafe-base64 encoded SHA256 hashes of issuer SPKIs. The file contents are
// ascii hex encoded serial numbers. The program crlite_key.py in this directory
// can generate these values for you.
//
// The test filter was generated as follows:
//
// $ ./crlite_key.py test_crlite_filters/issuer.pem test_crlite_filters/valid.pem
// 8Rw90Ej3Ttt8RRkrg-WYDS9n7IS03bk5bjP_UXPtaY8=
// 00da4f392bfd8bcea8
//
// $ ./crlite_key.py test_crlite_filters/issuer.pem test_crlite_filters/revoked.pem
// 8Rw90Ej3Ttt8RRkrg-WYDS9n7IS03bk5bjP_UXPtaY8=
// 2d35ca6503fb1ba3
//
// $ mkdir known revoked
// $ echo "00da4f392bfd8bcea8" > known/8Rw90Ej3Ttt8RRkrg-WYDS9n7IS03bk5bjP_UXPtaY8\=
// $ echo "2d35ca6503fb1ba3" >> known/8Rw90Ej3Ttt8RRkrg-WYDS9n7IS03bk5bjP_UXPtaY8\=
// $ echo "2d35ca6503fb1ba3" > revoked/8Rw90Ej3Ttt8RRkrg-WYDS9n7IS03bk5bjP_UXPtaY8\=
//
// $ rust-create-cascade --known ./known/ --revoked ./revoked/
//

"use strict";
do_get_profile(); // must be called before getting nsIX509CertDB

const { RemoteSecuritySettings } = ChromeUtils.importESModule(
  "resource://gre/modules/psm/RemoteSecuritySettings.sys.mjs"
);
const { TestUtils } = ChromeUtils.importESModule(
  "resource://testing-common/TestUtils.sys.mjs"
);

const { CRLiteFiltersClient } = RemoteSecuritySettings.init();

const CRLITE_FILTERS_ENABLED_PREF =
  "security.remote_settings.crlite_filters.enabled";
const INTERMEDIATES_ENABLED_PREF =
  "security.remote_settings.intermediates.enabled";
const INTERMEDIATES_DL_PER_POLL_PREF =
  "security.remote_settings.intermediates.downloads_per_poll";

// crlite_enrollment_id.py test_crlite_filters/issuer.pem
const ISSUER_PEM_UID = "UbH9/ZAnjuqf79Xhah1mFOWo6ZvgQCgsdheWfjvVUM8=";
// crlite_enrollment_id.py test_crlite_filters/no-sct-issuer.pem
const NO_SCT_ISSUER_PEM_UID = "Myn7EasO1QikOtNmo/UZdh6snCAw0BOY6wgU8OsUeeY=";

function getHashCommon(aStr, useBase64) {
  let hasher = Cc["@mozilla.org/security/hash;1"].createInstance(
    Ci.nsICryptoHash
  );
  hasher.init(Ci.nsICryptoHash.SHA256);
  let stringStream = Cc["@mozilla.org/io/string-input-stream;1"].createInstance(
    Ci.nsIStringInputStream
  );
  stringStream.data = aStr;
  hasher.updateFromStream(stringStream, -1);

  return hasher.finish(useBase64);
}

// Get a hexified SHA-256 hash of the given string.
function getHash(aStr) {
  return hexify(getHashCommon(aStr, false));
}

// Get the name of the file in the test directory to serve as the attachment
// for the given filter.
function getFilenameForFilter(filter) {
  if (filter.type == "full") {
    return "20201017-0-filter";
  }
  if (filter.id == "0001") {
    return "20201017-1-filter.stash";
  }
  // The addition of another stash file was written more than a month after
  // other parts of this test. As such, the second stash file for October 17th,
  // 2020 was not readily available. Since the structure of stash files don't
  // depend on each other, though, any two stash files are compatible, and so
  // this stash from December 1st is used instead.
  return "20201201-3-filter.stash";
}

/**
 * Simulate a Remote Settings synchronization by filling up the local data with
 * fake records.
 *
 * @param {*} filters List of filters for which we will create records.
 * @param {boolean} clear Whether or not to clear the local DB first. Defaults
 *                        to true.
 */
async function syncAndDownload(filters, clear = true) {
  const localDB = await CRLiteFiltersClient.client.db;
  if (clear) {
    await localDB.clear();
  }

  for (let filter of filters) {
    const filename = getFilenameForFilter(filter);
    const file = do_get_file(`test_crlite_filters/${filename}`);
    const fileBytes = readFile(file);

    const record = {
      details: {
        name: `${filter.timestamp}-${filter.type}`,
      },
      attachment: {
        hash: getHash(fileBytes),
        size: fileBytes.length,
        filename,
        location: `security-state-workspace/cert-revocations/test_crlite_filters/${filename}`,
        mimetype: "application/octet-stream",
      },
      incremental: filter.type == "diff",
      effectiveTimestamp: new Date(filter.timestamp).getTime(),
      parent: filter.type == "diff" ? filter.parent : undefined,
      id: filter.id,
      coverage: filter.type == "full" ? filter.coverage : undefined,
      enrolledIssuers:
        filter.type == "full" ? filter.enrolledIssuers : undefined,
    };

    await localDB.create(record);
  }
  // This promise will wait for the end of downloading.
  let promise = TestUtils.topicObserved(
    "remote-security-settings:crlite-filters-downloaded"
  );
  // Simulate polling for changes, trigger the download of attachments.
  Services.obs.notifyObservers(null, "remote-settings:changes-poll-end");
  let results = await promise;
  return results[1]; // topicObserved gives back a 2-array
}

add_task(async function test_crlite_filters_disabled() {
  Services.prefs.setBoolPref(CRLITE_FILTERS_ENABLED_PREF, false);

  let result = await syncAndDownload([
    {
      timestamp: "2019-01-01T00:00:00Z",
      type: "full",
      id: "0000",
      coverage: [
        {
          logID: "9lyUL9F3MCIUVBgIMJRWjuNNExkzv98MLyALzE7xZOM=",
          minTimestamp: 0,
          maxTimestamp: 9999999999999,
        },
      ],
    },
  ]);
  equal(result, "disabled", "CRLite filter download should not have run");
});

add_task(async function test_crlite_no_filters() {
  Services.prefs.setBoolPref(CRLITE_FILTERS_ENABLED_PREF, true);

  let result = await syncAndDownload([]);
  equal(
    result,
    "unavailable",
    "CRLite filter download should have run, but nothing was available"
  );
});

add_task(async function test_crlite_only_incremental_filters() {
  Services.prefs.setBoolPref(CRLITE_FILTERS_ENABLED_PREF, true);

  let result = await syncAndDownload([
    {
      timestamp: "2019-01-01T06:00:00Z",
      type: "diff",
      id: "0001",
      parent: "0000",
    },
    {
      timestamp: "2019-01-01T18:00:00Z",
      type: "diff",
      id: "0002",
      parent: "0001",
    },
    {
      timestamp: "2019-01-01T12:00:00Z",
      type: "diff",
      id: "0003",
      parent: "0002",
    },
  ]);
  equal(
    result,
    "unavailable",
    "CRLite filter download should have run, but no full filters were available"
  );
});

add_task(async function test_crlite_incremental_filters_with_wrong_parent() {
  Services.prefs.setBoolPref(CRLITE_FILTERS_ENABLED_PREF, true);

  let result = await syncAndDownload([
    { timestamp: "2019-01-01T00:00:00Z", type: "full", id: "0000" },
    {
      timestamp: "2019-01-01T06:00:00Z",
      type: "diff",
      id: "0001",
      parent: "0000",
    },
    {
      timestamp: "2019-01-01T12:00:00Z",
      type: "diff",
      id: "0003",
      parent: "0002",
    },
    {
      timestamp: "2019-01-01T18:00:00Z",
      type: "diff",
      id: "0004",
      parent: "0003",
    },
  ]);
  let [status, filters] = result.split(";");
  equal(status, "finished", "CRLite filter download should have run");
  let filtersSplit = filters.split(",");
  deepEqual(
    filtersSplit,
    ["2019-01-01T00:00:00Z-full", "2019-01-01T06:00:00Z-diff"],
    "Should have downloaded the expected CRLite filters"
  );
});

add_task(async function test_crlite_incremental_filter_too_early() {
  Services.prefs.setBoolPref(CRLITE_FILTERS_ENABLED_PREF, true);

  let result = await syncAndDownload([
    { timestamp: "2019-01-02T00:00:00Z", type: "full", id: "0000" },
    {
      timestamp: "2019-01-01T00:00:00Z",
      type: "diff",
      id: "0001",
      parent: "0000",
    },
  ]);
  equal(
    result,
    "finished;2019-01-02T00:00:00Z-full",
    "CRLite filter download should have run"
  );
});

add_task(async function test_crlite_filters_basic() {
  Services.prefs.setBoolPref(CRLITE_FILTERS_ENABLED_PREF, true);

  let result = await syncAndDownload([
    { timestamp: "2019-01-01T00:00:00Z", type: "full", id: "0000" },
  ]);
  equal(
    result,
    "finished;2019-01-01T00:00:00Z-full",
    "CRLite filter download should have run"
  );
});

add_task(async function test_crlite_filters_not_cached() {
  Services.prefs.setBoolPref(CRLITE_FILTERS_ENABLED_PREF, true);
  let filters = [
    { timestamp: "2019-01-01T00:00:00Z", type: "full", id: "0000" },
  ];
  let result = await syncAndDownload(filters);
  equal(
    result,
    "finished;2019-01-01T00:00:00Z-full",
    "CRLite filter download should have run"
  );

  let records = await CRLiteFiltersClient.client.db.list();

  // `syncAndDownload` should not cache the attachment, so this download should
  // get the attachment from the source.
  let attachment = await CRLiteFiltersClient.client.attachments.download(
    records[0]
  );
  equal(attachment._source, "remote_match");
  await CRLiteFiltersClient.client.attachments.deleteDownloaded(records[0]);
});

add_task(async function test_crlite_filters_full_and_incremental() {
  Services.prefs.setBoolPref(CRLITE_FILTERS_ENABLED_PREF, true);

  let result = await syncAndDownload([
    // These are deliberately listed out of order.
    {
      timestamp: "2019-01-01T06:00:00Z",
      type: "diff",
      id: "0001",
      parent: "0000",
    },
    { timestamp: "2019-01-01T00:00:00Z", type: "full", id: "0000" },
    {
      timestamp: "2019-01-01T18:00:00Z",
      type: "diff",
      id: "0003",
      parent: "0002",
    },
    {
      timestamp: "2019-01-01T12:00:00Z",
      type: "diff",
      id: "0002",
      parent: "0001",
    },
  ]);
  let [status, filters] = result.split(";");
  equal(status, "finished", "CRLite filter download should have run");
  let filtersSplit = filters.split(",");
  deepEqual(
    filtersSplit,
    [
      "2019-01-01T00:00:00Z-full",
      "2019-01-01T06:00:00Z-diff",
      "2019-01-01T12:00:00Z-diff",
      "2019-01-01T18:00:00Z-diff",
    ],
    "Should have downloaded the expected CRLite filters"
  );
});

add_task(async function test_crlite_filters_multiple_days() {
  Services.prefs.setBoolPref(CRLITE_FILTERS_ENABLED_PREF, true);

  let result = await syncAndDownload([
    // These are deliberately listed out of order.
    {
      timestamp: "2019-01-02T06:00:00Z",
      type: "diff",
      id: "0011",
      parent: "0010",
    },
    {
      timestamp: "2019-01-03T12:00:00Z",
      type: "diff",
      id: "0022",
      parent: "0021",
    },
    {
      timestamp: "2019-01-02T12:00:00Z",
      type: "diff",
      id: "0012",
      parent: "0011",
    },
    {
      timestamp: "2019-01-03T18:00:00Z",
      type: "diff",
      id: "0023",
      parent: "0022",
    },
    {
      timestamp: "2019-01-02T18:00:00Z",
      type: "diff",
      id: "0013",
      parent: "0012",
    },
    { timestamp: "2019-01-02T00:00:00Z", type: "full", id: "0010" },
    { timestamp: "2019-01-03T00:00:00Z", type: "full", id: "0020" },
    {
      timestamp: "2019-01-01T06:00:00Z",
      type: "diff",
      id: "0001",
      parent: "0000",
    },
    {
      timestamp: "2019-01-01T18:00:00Z",
      type: "diff",
      id: "0003",
      parent: "0002",
    },
    {
      timestamp: "2019-01-01T12:00:00Z",
      type: "diff",
      id: "0002",
      parent: "0001",
    },
    { timestamp: "2019-01-01T00:00:00Z", type: "full", id: "0000" },
    {
      timestamp: "2019-01-03T06:00:00Z",
      type: "diff",
      id: "0021",
      parent: "0020",
    },
  ]);
  let [status, filters] = result.split(";");
  equal(status, "finished", "CRLite filter download should have run");
  let filtersSplit = filters.split(",");
  deepEqual(
    filtersSplit,
    [
      "2019-01-03T00:00:00Z-full",
      "2019-01-03T06:00:00Z-diff",
      "2019-01-03T12:00:00Z-diff",
      "2019-01-03T18:00:00Z-diff",
    ],
    "Should have downloaded the expected CRLite filters"
  );
});

add_task(async function test_crlite_confirm_revocations_mode() {
  Services.prefs.setBoolPref(CRLITE_FILTERS_ENABLED_PREF, true);
  Services.prefs.setIntPref(
    "security.pki.crlite_mode",
    CRLiteModeConfirmRevocationsValue
  );
  Services.prefs.setBoolPref(INTERMEDIATES_ENABLED_PREF, true);

  let certdb = Cc["@mozilla.org/security/x509certdb;1"].getService(
    Ci.nsIX509CertDB
  );
  addCertFromFile(certdb, "test_crlite_filters/issuer.pem", ",,");
  addCertFromFile(certdb, "test_crlite_filters/no-sct-issuer.pem", ",,");

  let result = await syncAndDownload([
    {
      timestamp: "2020-10-17T00:00:00Z",
      type: "full",
      id: "0000",
      coverage: [
        {
          logID: "9lyUL9F3MCIUVBgIMJRWjuNNExkzv98MLyALzE7xZOM=",
          minTimestamp: 0,
          maxTimestamp: 9999999999999,
        },
        {
          logID: "pLkJkLQYWBSHuxOizGdwCjw1mAT5G9+443fNDsgN3BA=",
          minTimestamp: 0,
          maxTimestamp: 9999999999999,
        },
      ],
      enrolledIssuers: [ISSUER_PEM_UID, NO_SCT_ISSUER_PEM_UID],
    },
  ]);
  equal(
    result,
    "finished;2020-10-17T00:00:00Z-full",
    "CRLite filter download should have run"
  );

  // The CRLite result should be enforced for this certificate and
  // OCSP should not be consulted.
  let validCert = constructCertFromFile("test_crlite_filters/valid.pem");
  await checkCertErrorGenericAtTime(
    certdb,
    validCert,
    PRErrorCodeSuccess,
    certificateUsageSSLServer,
    new Date("2020-10-20T00:00:00Z").getTime() / 1000,
    undefined,
    "vpn.worldofspeed.org",
    0
  );

  // OCSP should be consulted for this certificate, but OCSP is disabled by
  // Ci.nsIX509CertDB.FLAG_LOCAL_ONLY so this will be treated as a soft-failure
  // and the CRLite result will be used.
  let revokedCert = constructCertFromFile("test_crlite_filters/revoked.pem");
  await checkCertErrorGenericAtTime(
    certdb,
    revokedCert,
    SEC_ERROR_REVOKED_CERTIFICATE,
    certificateUsageSSLServer,
    new Date("2020-10-20T00:00:00Z").getTime() / 1000,
    undefined,
    "us-datarecovery.com",
    Ci.nsIX509CertDB.FLAG_LOCAL_ONLY
  );

  // Reload the filter w/o coverage and enrollment metadata.
  result = await syncAndDownload([
    {
      timestamp: "2020-10-17T00:00:00Z",
      type: "full",
      id: "0000",
      coverage: [],
      enrolledIssuers: [],
    },
  ]);
  equal(
    result,
    "finished;2020-10-17T00:00:00Z-full",
    "CRLite filter download should have run"
  );

  // OCSP will be consulted for the revoked certificate, but a soft-failure
  // should now result in a Success return.
  await checkCertErrorGenericAtTime(
    certdb,
    revokedCert,
    PRErrorCodeSuccess,
    certificateUsageSSLServer,
    new Date("2020-10-20T00:00:00Z").getTime() / 1000,
    undefined,
    "us-datarecovery.com",
    Ci.nsIX509CertDB.FLAG_LOCAL_ONLY
  );
});

add_task(async function test_crlite_filters_and_check_revocation() {
  Services.prefs.setBoolPref(CRLITE_FILTERS_ENABLED_PREF, true);
  Services.prefs.setIntPref(
    "security.pki.crlite_mode",
    CRLiteModeEnforcePrefValue
  );
  Services.prefs.setBoolPref(INTERMEDIATES_ENABLED_PREF, true);

  let certdb = Cc["@mozilla.org/security/x509certdb;1"].getService(
    Ci.nsIX509CertDB
  );
  addCertFromFile(certdb, "test_crlite_filters/issuer.pem", ",,");
  addCertFromFile(certdb, "test_crlite_filters/no-sct-issuer.pem", ",,");

  let result = await syncAndDownload([
    {
      timestamp: "2020-10-17T00:00:00Z",
      type: "full",
      id: "0000",
      coverage: [
        {
          logID: "9lyUL9F3MCIUVBgIMJRWjuNNExkzv98MLyALzE7xZOM=",
          minTimestamp: 0,
          maxTimestamp: 9999999999999,
        },
        {
          logID: "pLkJkLQYWBSHuxOizGdwCjw1mAT5G9+443fNDsgN3BA=",
          minTimestamp: 0,
          maxTimestamp: 9999999999999,
        },
      ],
      enrolledIssuers: [ISSUER_PEM_UID, NO_SCT_ISSUER_PEM_UID],
    },
  ]);
  equal(
    result,
    "finished;2020-10-17T00:00:00Z-full",
    "CRLite filter download should have run"
  );

  let validCert = constructCertFromFile("test_crlite_filters/valid.pem");
  // NB: by not specifying Ci.nsIX509CertDB.FLAG_LOCAL_ONLY, this tests that
  // the implementation does not fall back to OCSP fetching, because if it
  // did, the implementation would attempt to connect to a server outside the
  // test infrastructure, which would result in a crash in the test
  // environment, which would be treated as a test failure.
  await checkCertErrorGenericAtTime(
    certdb,
    validCert,
    PRErrorCodeSuccess,
    certificateUsageSSLServer,
    new Date("2020-10-20T00:00:00Z").getTime() / 1000,
    false,
    "vpn.worldofspeed.org",
    0
  );

  let revokedCert = constructCertFromFile("test_crlite_filters/revoked.pem");
  await checkCertErrorGenericAtTime(
    certdb,
    revokedCert,
    SEC_ERROR_REVOKED_CERTIFICATE,
    certificateUsageSSLServer,
    new Date("2020-10-20T00:00:00Z").getTime() / 1000,
    false,
    "us-datarecovery.com",
    0
  );

  // Before any stashes are downloaded, this should verify successfully.
  let revokedInStashCert = constructCertFromFile(
    "test_crlite_filters/revoked-in-stash.pem"
  );
  await checkCertErrorGenericAtTime(
    certdb,
    revokedInStashCert,
    PRErrorCodeSuccess,
    certificateUsageSSLServer,
    new Date("2020-10-20T00:00:00Z").getTime() / 1000,
    false,
    "stokedmoto.com",
    0
  );

  result = await syncAndDownload(
    [
      {
        timestamp: "2020-10-17T03:00:00Z",
        type: "diff",
        id: "0001",
        parent: "0000",
      },
    ],
    false
  );
  equal(
    result,
    "finished;2020-10-17T03:00:00Z-diff",
    "Should have downloaded the expected CRLite filters"
  );

  // After downloading the first stash, this should be revoked.
  await checkCertErrorGenericAtTime(
    certdb,
    revokedInStashCert,
    SEC_ERROR_REVOKED_CERTIFICATE,
    certificateUsageSSLServer,
    new Date("2020-10-20T00:00:00Z").getTime() / 1000,
    false,
    "stokedmoto.com",
    0
  );

  // Before downloading the second stash, this should not be revoked.
  let revokedInStash2Cert = constructCertFromFile(
    "test_crlite_filters/revoked-in-stash-2.pem"
  );
  await checkCertErrorGenericAtTime(
    certdb,
    revokedInStash2Cert,
    PRErrorCodeSuccess,
    certificateUsageSSLServer,
    new Date("2020-10-20T00:00:00Z").getTime() / 1000,
    false,
    "icsreps.com",
    0
  );

  result = await syncAndDownload(
    [
      {
        timestamp: "2020-10-17T06:00:00Z",
        type: "diff",
        id: "0002",
        parent: "0001",
      },
    ],
    false
  );
  equal(
    result,
    "finished;2020-10-17T06:00:00Z-diff",
    "Should have downloaded the expected CRLite filters"
  );

  // After downloading the second stash, this should be revoked.
  await checkCertErrorGenericAtTime(
    certdb,
    revokedInStash2Cert,
    SEC_ERROR_REVOKED_CERTIFICATE,
    certificateUsageSSLServer,
    new Date("2020-10-20T00:00:00Z").getTime() / 1000,
    false,
    "icsreps.com",
    0
  );

  // The other certificates should still get the same results as they did before.
  await checkCertErrorGenericAtTime(
    certdb,
    validCert,
    PRErrorCodeSuccess,
    certificateUsageSSLServer,
    new Date("2020-10-20T00:00:00Z").getTime() / 1000,
    false,
    "vpn.worldofspeed.org",
    0
  );

  await checkCertErrorGenericAtTime(
    certdb,
    revokedCert,
    SEC_ERROR_REVOKED_CERTIFICATE,
    certificateUsageSSLServer,
    new Date("2020-10-20T00:00:00Z").getTime() / 1000,
    false,
    "us-datarecovery.com",
    0
  );

  await checkCertErrorGenericAtTime(
    certdb,
    revokedInStashCert,
    SEC_ERROR_REVOKED_CERTIFICATE,
    certificateUsageSSLServer,
    new Date("2020-10-20T00:00:00Z").getTime() / 1000,
    false,
    "stokedmoto.com",
    0
  );

  // This certificate has no embedded SCTs, so it is not guaranteed to be in
  // CT, so CRLite can't be guaranteed to give the correct answer, so it is
  // not consulted, and the implementation falls back to OCSP. Since the real
  // OCSP responder can't be reached, this results in a
  // SEC_ERROR_OCSP_SERVER_ERROR.
  let noSCTCert = constructCertFromFile("test_crlite_filters/no-sct.pem");
  // NB: this will cause an OCSP request to be sent to localhost:80, but
  // since an OCSP responder shouldn't be running on that port, this should
  // fail safely.
  Services.prefs.setCharPref("network.dns.localDomains", "ocsp.digicert.com");
  Services.prefs.setBoolPref("security.OCSP.require", true);
  Services.prefs.setIntPref("security.OCSP.enabled", 1);
  await checkCertErrorGenericAtTime(
    certdb,
    noSCTCert,
    SEC_ERROR_OCSP_SERVER_ERROR,
    certificateUsageSSLServer,
    new Date("2020-10-20T00:00:00Z").getTime() / 1000,
    false,
    "mail233.messagelabs.com",
    0
  );
  Services.prefs.clearUserPref("network.dns.localDomains");
  Services.prefs.clearUserPref("security.OCSP.require");
  Services.prefs.clearUserPref("security.OCSP.enabled");

  // The revoked certificate example has one SCT from the log with ID "9ly...="
  // at time 1598140096613 and another from the log with ID "XNx...=" at time
  // 1598140096917. The filter we construct here fails to cover it by one
  // millisecond in each case. The implementation will fall back to OCSP
  // fetching. Since this would result in a crash and test failure, the
  // Ci.nsIX509CertDB.FLAG_LOCAL_ONLY is used.
  result = await syncAndDownload([
    {
      timestamp: "2020-10-17T00:00:00Z",
      type: "full",
      id: "0000",
      coverage: [
        {
          logID: "9lyUL9F3MCIUVBgIMJRWjuNNExkzv98MLyALzE7xZOM=",
          minTimestamp: 0,
          maxTimestamp: 1598140096612,
        },
        {
          logID: "XNxDkv7mq0VEsV6a1FbmEDf71fpH3KFzlLJe5vbHDso=",
          minTimestamp: 1598140096917,
          maxTimestamp: 9999999999999,
        },
      ],
      enrolledIssuers: [ISSUER_PEM_UID, NO_SCT_ISSUER_PEM_UID],
    },
  ]);
  equal(
    result,
    "finished;2020-10-17T00:00:00Z-full",
    "CRLite filter download should have run"
  );
  await checkCertErrorGenericAtTime(
    certdb,
    revokedCert,
    PRErrorCodeSuccess,
    certificateUsageSSLServer,
    new Date("2020-10-20T00:00:00Z").getTime() / 1000,
    false,
    "us-datarecovery.com",
    Ci.nsIX509CertDB.FLAG_LOCAL_ONLY
  );
});

add_task(async function test_crlite_filters_avoid_reprocessing_filters() {
  Services.prefs.setBoolPref(CRLITE_FILTERS_ENABLED_PREF, true);

  let result = await syncAndDownload([
    {
      timestamp: "2019-01-01T00:00:00Z",
      type: "full",
      id: "0000",
      coverage: [
        {
          logID: "9lyUL9F3MCIUVBgIMJRWjuNNExkzv98MLyALzE7xZOM=",
          minTimestamp: 0,
          maxTimestamp: 9999999999999,
        },
      ],
      enrolledIssuers: [ISSUER_PEM_UID, NO_SCT_ISSUER_PEM_UID],
    },
    {
      timestamp: "2019-01-01T06:00:00Z",
      type: "diff",
      id: "0001",
      parent: "0000",
    },
    {
      timestamp: "2019-01-01T12:00:00Z",
      type: "diff",
      id: "0002",
      parent: "0001",
    },
    {
      timestamp: "2019-01-01T18:00:00Z",
      type: "diff",
      id: "0003",
      parent: "0002",
    },
  ]);
  let [status, filters] = result.split(";");
  equal(status, "finished", "CRLite filter download should have run");
  let filtersSplit = filters.split(",");
  deepEqual(
    filtersSplit,
    [
      "2019-01-01T00:00:00Z-full",
      "2019-01-01T06:00:00Z-diff",
      "2019-01-01T12:00:00Z-diff",
      "2019-01-01T18:00:00Z-diff",
    ],
    "Should have downloaded the expected CRLite filters"
  );
  // This simulates another poll without clearing the database first. The
  // filter and stashes should not be re-downloaded.
  result = await syncAndDownload([], false);
  equal(result, "finished;");

  // If a new stash is added, only it should be downloaded.
  result = await syncAndDownload(
    [
      {
        timestamp: "2019-01-02T00:00:00Z",
        type: "diff",
        id: "0004",
        parent: "0003",
      },
    ],
    false
  );
  equal(result, "finished;2019-01-02T00:00:00Z-diff");
});

let server;

function run_test() {
  server = new HttpServer();
  server.start(-1);
  registerCleanupFunction(() => server.stop(() => {}));

  server.registerDirectory(
    "/cdn/security-state-workspace/cert-revocations/",
    do_get_file(".")
  );

  server.registerPathHandler("/v1/", (request, response) => {
    response.write(
      JSON.stringify({
        capabilities: {
          attachments: {
            base_url: `http://localhost:${server.identity.primaryPort}/cdn/`,
          },
        },
      })
    );
    response.setHeader("Content-Type", "application/json; charset=UTF-8");
    response.setStatusLine(null, 200, "OK");
  });

  Services.prefs.setCharPref(
    "services.settings.server",
    `http://localhost:${server.identity.primaryPort}/v1`
  );

  // Set intermediate preloading to download 0 intermediates at a time.
  Services.prefs.setIntPref(INTERMEDIATES_DL_PER_POLL_PREF, 0);

  Services.prefs.setCharPref("browser.policies.loglevel", "debug");

  run_next_test();
}