summaryrefslogtreecommitdiffstats
path: root/toolkit/components/url-classifier/tests/gtest/TestUrlClassifierTableUpdateV4.cpp
blob: d4dec867bd65cbd6613f6dc6f9315f141e350b37 (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
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 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/. */

#include "Classifier.h"
#include "HashStore.h"
#include "mozilla/Components.h"
#include "mozilla/Unused.h"
#include "nsAppDirectoryServiceDefs.h"
#include "nsIFile.h"
#include "nsThreadUtils.h"
#include "string.h"
#include "LookupCacheV4.h"
#include "nsUrlClassifierUtils.h"

#include "Common.h"

#define GTEST_SAFEBROWSING_DIR "safebrowsing"_ns
#define GTEST_TABLE "gtest-malware-proto"_ns
#define GTEST_PREFIXFILE "gtest-malware-proto.vlpset"_ns

// This function removes common elements of inArray and outArray from
// outArray. This is used by partial update testcase to ensure partial update
// data won't contain prefixes we already have.
static void RemoveIntersection(const _PrefixArray& inArray,
                               _PrefixArray& outArray) {
  for (uint32_t i = 0; i < inArray.Length(); i++) {
    int32_t idx = outArray.BinaryIndexOf(inArray[i]);
    if (idx >= 0) {
      outArray.RemoveElementAt(idx);
    }
  }
}

// This fucntion removes elements from outArray by index specified in
// removal array.
static void RemoveElements(const nsTArray<uint32_t>& removal,
                           _PrefixArray& outArray) {
  for (int32_t i = removal.Length() - 1; i >= 0; i--) {
    outArray.RemoveElementAt(removal[i]);
  }
}

static void MergeAndSortArray(const _PrefixArray& array1,
                              const _PrefixArray& array2,
                              _PrefixArray& output) {
  output.Clear();
  output.AppendElements(array1);
  output.AppendElements(array2);
  output.Sort();
}

static void CalculateSHA256(_PrefixArray& prefixArray, nsCString& sha256) {
  prefixArray.Sort();

  nsresult rv;
  nsCOMPtr<nsICryptoHash> cryptoHash =
      do_CreateInstance(NS_CRYPTO_HASH_CONTRACTID, &rv);

  cryptoHash->Init(nsICryptoHash::SHA256);
  for (uint32_t i = 0; i < prefixArray.Length(); i++) {
    const _Prefix& prefix = prefixArray[i];
    cryptoHash->Update(
        reinterpret_cast<uint8_t*>(const_cast<char*>(prefix.get())),
        prefix.Length());
  }
  cryptoHash->Finish(false, sha256);
}

// N: Number of prefixes, MIN/MAX: minimum/maximum prefix size
// This function will append generated prefixes to outArray.
static void CreateRandomSortedPrefixArray(uint32_t N, uint32_t MIN,
                                          uint32_t MAX,
                                          _PrefixArray& outArray) {
  outArray.SetCapacity(outArray.Length() + N);

  const uint32_t range = (MAX - MIN + 1);

  for (uint32_t i = 0; i < N; i++) {
    uint32_t prefixSize = (rand() % range) + MIN;
    _Prefix prefix;
    prefix.SetLength(prefixSize);

    while (true) {
      char* dst = prefix.BeginWriting();
      for (uint32_t j = 0; j < prefixSize; j++) {
        dst[j] = rand() % 256;
      }

      if (!outArray.Contains(prefix)) {
        outArray.AppendElement(prefix);
        break;
      }
    }
  }

  outArray.Sort();
}

// N: Number of removal indices, MAX: maximum index
static void CreateRandomRemovalIndices(uint32_t N, uint32_t MAX,
                                       nsTArray<uint32_t>& outArray) {
  for (uint32_t i = 0; i < N; i++) {
    uint32_t idx = rand() % MAX;
    if (!outArray.Contains(idx)) {
      outArray.InsertElementSorted(idx);
    }
  }
}

// Function to generate TableUpdateV4.
static void GenerateUpdateData(bool fullUpdate, PrefixStringMap& add,
                               nsTArray<uint32_t>* removal, nsCString* sha256,
                               TableUpdateArray& tableUpdates) {
  RefPtr<TableUpdateV4> tableUpdate = new TableUpdateV4(GTEST_TABLE);
  tableUpdate->SetFullUpdate(fullUpdate);

  for (const auto& entry : add) {
    nsCString* pstring = entry.GetWeak();
    tableUpdate->NewPrefixes(entry.GetKey(), *pstring);
  }

  if (removal) {
    tableUpdate->NewRemovalIndices(removal->Elements(), removal->Length());
  }

  if (sha256) {
    std::string stdSHA256;
    stdSHA256.assign(const_cast<char*>(sha256->BeginReading()),
                     sha256->Length());

    tableUpdate->SetSHA256(stdSHA256);
  }

  tableUpdates.AppendElement(tableUpdate);
}

static void VerifyPrefixSet(PrefixStringMap& expected) {
  // Verify the prefix set is written to disk.
  nsCOMPtr<nsIFile> file;
  NS_GetSpecialDirectory(NS_APP_USER_PROFILE_50_DIR, getter_AddRefs(file));
  file->AppendNative(GTEST_SAFEBROWSING_DIR);

  RefPtr<LookupCacheV4> lookup =
      new LookupCacheV4(GTEST_TABLE, "test"_ns, file);
  lookup->Init();

  file->AppendNative(GTEST_PREFIXFILE);
  lookup->LoadFromFile(file);

  PrefixStringMap prefixesInFile;
  lookup->GetPrefixes(prefixesInFile);

  for (const auto& entry : expected) {
    nsCString* expectedPrefix = entry.GetWeak();
    nsCString* resultPrefix = prefixesInFile.Get(entry.GetKey());

    ASSERT_TRUE(*resultPrefix == *expectedPrefix);
  }
}

static void Clear() {
  nsCOMPtr<nsIFile> file;
  NS_GetSpecialDirectory(NS_APP_USER_PROFILE_50_DIR, getter_AddRefs(file));

  RefPtr<Classifier> classifier = new Classifier();
  classifier->Open(*file);
  classifier->Reset();
}

static void testUpdateFail(TableUpdateArray& tableUpdates) {
  nsresult rv = SyncApplyUpdates(tableUpdates);
  ASSERT_NS_FAILED(rv);
}

static void testUpdate(TableUpdateArray& tableUpdates,
                       PrefixStringMap& expected) {
  // Force nsUrlClassifierUtils loading on main thread
  // because nsIUrlClassifierDBService will not run in advance
  // in gtest.
  nsUrlClassifierUtils::GetInstance();

  nsresult rv = SyncApplyUpdates(tableUpdates);
  ASSERT_TRUE(rv == NS_OK);
  VerifyPrefixSet(expected);
}

static void testFullUpdate(PrefixStringMap& add, nsCString* sha256) {
  TableUpdateArray tableUpdates;

  GenerateUpdateData(true, add, nullptr, sha256, tableUpdates);

  testUpdate(tableUpdates, add);
}

static void testPartialUpdate(PrefixStringMap& add, nsTArray<uint32_t>* removal,
                              nsCString* sha256, PrefixStringMap& expected) {
  TableUpdateArray tableUpdates;
  GenerateUpdateData(false, add, removal, sha256, tableUpdates);

  testUpdate(tableUpdates, expected);
}

static void testOpenLookupCache() {
  nsCOMPtr<nsIFile> file;
  NS_GetSpecialDirectory(NS_APP_USER_PROFILE_50_DIR, getter_AddRefs(file));
  file->AppendNative(GTEST_SAFEBROWSING_DIR);

  RunTestInNewThread([&]() -> void {
    RefPtr<LookupCacheV4> cache =
        new LookupCacheV4(nsCString(GTEST_TABLE), ""_ns, file);
    nsresult rv = cache->Init();
    ASSERT_EQ(rv, NS_OK);

    rv = cache->Open();
    ASSERT_EQ(rv, NS_OK);
  });
}

// Tests start from here.
TEST(UrlClassifierTableUpdateV4, FixLengthPSetFullUpdate)
{
  srand(time(NULL));

  _PrefixArray array;
  PrefixStringMap map;
  nsCString sha256;

  CreateRandomSortedPrefixArray(5000, 4, 4, array);
  PrefixArrayToPrefixStringMap(array, map);
  CalculateSHA256(array, sha256);

  testFullUpdate(map, &sha256);

  Clear();
}

TEST(UrlClassifierTableUpdateV4, VariableLengthPSetFullUpdate)
{
  _PrefixArray array;
  PrefixStringMap map;
  nsCString sha256;

  CreateRandomSortedPrefixArray(5000, 5, 32, array);
  PrefixArrayToPrefixStringMap(array, map);
  CalculateSHA256(array, sha256);

  testFullUpdate(map, &sha256);

  Clear();
}

// This test contain both variable length prefix set and fixed-length prefix set
TEST(UrlClassifierTableUpdateV4, MixedPSetFullUpdate)
{
  _PrefixArray array;
  PrefixStringMap map;
  nsCString sha256;

  CreateRandomSortedPrefixArray(5000, 4, 4, array);
  CreateRandomSortedPrefixArray(1000, 5, 32, array);
  PrefixArrayToPrefixStringMap(array, map);
  CalculateSHA256(array, sha256);

  testFullUpdate(map, &sha256);

  Clear();
}

TEST(UrlClassifierTableUpdateV4, PartialUpdateWithRemoval)
{
  _PrefixArray fArray;

  // Apply a full update first.
  {
    PrefixStringMap fMap;
    nsCString sha256;

    CreateRandomSortedPrefixArray(10000, 4, 4, fArray);
    CreateRandomSortedPrefixArray(2000, 5, 32, fArray);
    PrefixArrayToPrefixStringMap(fArray, fMap);
    CalculateSHA256(fArray, sha256);

    testFullUpdate(fMap, &sha256);
  }

  // Apply a partial update with removal.
  {
    _PrefixArray pArray, mergedArray;
    PrefixStringMap pMap, mergedMap;
    nsCString sha256;

    CreateRandomSortedPrefixArray(5000, 4, 4, pArray);
    CreateRandomSortedPrefixArray(1000, 5, 32, pArray);
    RemoveIntersection(fArray, pArray);
    PrefixArrayToPrefixStringMap(pArray, pMap);

    // Remove 1/5 of elements of original prefix set.
    nsTArray<uint32_t> removal;
    CreateRandomRemovalIndices(fArray.Length() / 5, fArray.Length(), removal);
    RemoveElements(removal, fArray);

    // Calculate the expected prefix map.
    MergeAndSortArray(fArray, pArray, mergedArray);
    PrefixArrayToPrefixStringMap(mergedArray, mergedMap);
    CalculateSHA256(mergedArray, sha256);

    testPartialUpdate(pMap, &removal, &sha256, mergedMap);
  }

  Clear();
}

TEST(UrlClassifierTableUpdateV4, PartialUpdateWithoutRemoval)
{
  _PrefixArray fArray;

  // Apply a full update first.
  {
    PrefixStringMap fMap;
    nsCString sha256;

    CreateRandomSortedPrefixArray(10000, 4, 4, fArray);
    CreateRandomSortedPrefixArray(2000, 5, 32, fArray);
    PrefixArrayToPrefixStringMap(fArray, fMap);
    CalculateSHA256(fArray, sha256);

    testFullUpdate(fMap, &sha256);
  }

  // Apply a partial update without removal
  {
    _PrefixArray pArray, mergedArray;
    PrefixStringMap pMap, mergedMap;
    nsCString sha256;

    CreateRandomSortedPrefixArray(5000, 4, 4, pArray);
    CreateRandomSortedPrefixArray(1000, 5, 32, pArray);
    RemoveIntersection(fArray, pArray);
    PrefixArrayToPrefixStringMap(pArray, pMap);

    // Calculate the expected prefix map.
    MergeAndSortArray(fArray, pArray, mergedArray);
    PrefixArrayToPrefixStringMap(mergedArray, mergedMap);
    CalculateSHA256(mergedArray, sha256);

    testPartialUpdate(pMap, nullptr, &sha256, mergedMap);
  }

  Clear();
}

// Expect failure because partial update contains prefix already
// in old prefix set.
TEST(UrlClassifierTableUpdateV4, PartialUpdatePrefixAlreadyExist)
{
  _PrefixArray fArray;

  // Apply a full update fist.
  {
    PrefixStringMap fMap;
    nsCString sha256;

    CreateRandomSortedPrefixArray(1000, 4, 32, fArray);
    PrefixArrayToPrefixStringMap(fArray, fMap);
    CalculateSHA256(fArray, sha256);

    testFullUpdate(fMap, &sha256);
  }

  // Apply a partial update which contains a prefix in previous full update.
  // This should cause an update error.
  {
    _PrefixArray pArray;
    PrefixStringMap pMap;
    TableUpdateArray tableUpdates;

    // Pick one prefix from full update prefix and add it to partial update.
    // This should result a failure when call ApplyUpdates.
    pArray.AppendElement(fArray[rand() % fArray.Length()]);
    CreateRandomSortedPrefixArray(200, 4, 32, pArray);
    PrefixArrayToPrefixStringMap(pArray, pMap);

    GenerateUpdateData(false, pMap, nullptr, nullptr, tableUpdates);
    testUpdateFail(tableUpdates);
  }

  Clear();
}

// Test apply partial update directly without applying an full update first.
TEST(UrlClassifierTableUpdateV4, OnlyPartialUpdate)
{
  _PrefixArray pArray;
  PrefixStringMap pMap;
  nsCString sha256;

  CreateRandomSortedPrefixArray(5000, 4, 4, pArray);
  CreateRandomSortedPrefixArray(1000, 5, 32, pArray);
  PrefixArrayToPrefixStringMap(pArray, pMap);
  CalculateSHA256(pArray, sha256);

  testPartialUpdate(pMap, nullptr, &sha256, pMap);

  Clear();
}

// Test partial update without any ADD prefixes, only removalIndices.
TEST(UrlClassifierTableUpdateV4, PartialUpdateOnlyRemoval)
{
  _PrefixArray fArray;

  // Apply a full update first.
  {
    PrefixStringMap fMap;
    nsCString sha256;

    CreateRandomSortedPrefixArray(5000, 4, 4, fArray);
    CreateRandomSortedPrefixArray(1000, 5, 32, fArray);
    PrefixArrayToPrefixStringMap(fArray, fMap);
    CalculateSHA256(fArray, sha256);

    testFullUpdate(fMap, &sha256);
  }

  // Apply a partial update without add prefix, only contain removal indices.
  {
    _PrefixArray pArray;
    PrefixStringMap pMap, mergedMap;
    nsCString sha256;

    // Remove 1/5 of elements of original prefix set.
    nsTArray<uint32_t> removal;
    CreateRandomRemovalIndices(fArray.Length() / 5, fArray.Length(), removal);
    RemoveElements(removal, fArray);

    PrefixArrayToPrefixStringMap(fArray, mergedMap);
    CalculateSHA256(fArray, sha256);

    testPartialUpdate(pMap, &removal, &sha256, mergedMap);
  }

  Clear();
}

// Test one tableupdate array contains full update and multiple partial updates.
TEST(UrlClassifierTableUpdateV4, MultipleTableUpdates)
{
  _PrefixArray fArray, pArray, mergedArray;
  PrefixStringMap fMap, pMap, mergedMap;
  nsCString sha256;

  TableUpdateArray tableUpdates;

  // Generate first full udpate
  CreateRandomSortedPrefixArray(10000, 4, 4, fArray);
  CreateRandomSortedPrefixArray(2000, 5, 32, fArray);
  PrefixArrayToPrefixStringMap(fArray, fMap);
  CalculateSHA256(fArray, sha256);

  GenerateUpdateData(true, fMap, nullptr, &sha256, tableUpdates);

  // Generate second partial update
  CreateRandomSortedPrefixArray(3000, 4, 4, pArray);
  CreateRandomSortedPrefixArray(1000, 5, 32, pArray);
  RemoveIntersection(fArray, pArray);
  PrefixArrayToPrefixStringMap(pArray, pMap);

  MergeAndSortArray(fArray, pArray, mergedArray);
  CalculateSHA256(mergedArray, sha256);

  GenerateUpdateData(false, pMap, nullptr, &sha256, tableUpdates);

  // Generate thrid partial update
  fArray.AppendElements(pArray);
  fArray.Sort();
  pArray.Clear();
  CreateRandomSortedPrefixArray(3000, 4, 4, pArray);
  CreateRandomSortedPrefixArray(1000, 5, 32, pArray);
  RemoveIntersection(fArray, pArray);
  PrefixArrayToPrefixStringMap(pArray, pMap);

  // Remove 1/5 of elements of original prefix set.
  nsTArray<uint32_t> removal;
  CreateRandomRemovalIndices(fArray.Length() / 5, fArray.Length(), removal);
  RemoveElements(removal, fArray);

  MergeAndSortArray(fArray, pArray, mergedArray);
  PrefixArrayToPrefixStringMap(mergedArray, mergedMap);
  CalculateSHA256(mergedArray, sha256);

  GenerateUpdateData(false, pMap, &removal, &sha256, tableUpdates);

  testUpdate(tableUpdates, mergedMap);

  Clear();
}

// Test apply full update first, and then apply multiple partial updates
// in one tableupdate array.
TEST(UrlClassifierTableUpdateV4, MultiplePartialUpdateTableUpdates)
{
  _PrefixArray fArray;

  // Apply a full update first
  {
    PrefixStringMap fMap;
    nsCString sha256;

    // Generate first full udpate
    CreateRandomSortedPrefixArray(10000, 4, 4, fArray);
    CreateRandomSortedPrefixArray(3000, 5, 32, fArray);
    PrefixArrayToPrefixStringMap(fArray, fMap);
    CalculateSHA256(fArray, sha256);

    testFullUpdate(fMap, &sha256);
  }

  // Apply multiple partial updates in one table update
  {
    _PrefixArray pArray, mergedArray;
    PrefixStringMap pMap, mergedMap;
    nsCString sha256;
    nsTArray<uint32_t> removal;
    TableUpdateArray tableUpdates;

    // Generate first partial update
    CreateRandomSortedPrefixArray(3000, 4, 4, pArray);
    CreateRandomSortedPrefixArray(1000, 5, 32, pArray);
    RemoveIntersection(fArray, pArray);
    PrefixArrayToPrefixStringMap(pArray, pMap);

    // Remove 1/5 of elements of original prefix set.
    CreateRandomRemovalIndices(fArray.Length() / 5, fArray.Length(), removal);
    RemoveElements(removal, fArray);

    MergeAndSortArray(fArray, pArray, mergedArray);
    CalculateSHA256(mergedArray, sha256);

    GenerateUpdateData(false, pMap, &removal, &sha256, tableUpdates);

    fArray.AppendElements(pArray);
    fArray.Sort();
    pArray.Clear();
    removal.Clear();

    // Generate second partial update.
    CreateRandomSortedPrefixArray(2000, 4, 4, pArray);
    CreateRandomSortedPrefixArray(1000, 5, 32, pArray);
    RemoveIntersection(fArray, pArray);
    PrefixArrayToPrefixStringMap(pArray, pMap);

    // Remove 1/5 of elements of original prefix set.
    CreateRandomRemovalIndices(fArray.Length() / 5, fArray.Length(), removal);
    RemoveElements(removal, fArray);

    MergeAndSortArray(fArray, pArray, mergedArray);
    PrefixArrayToPrefixStringMap(mergedArray, mergedMap);
    CalculateSHA256(mergedArray, sha256);

    GenerateUpdateData(false, pMap, &removal, &sha256, tableUpdates);

    testUpdate(tableUpdates, mergedMap);
  }

  Clear();
}

// Test removal indices are larger than the original prefix set.
TEST(UrlClassifierTableUpdateV4, RemovalIndexTooLarge)
{
  _PrefixArray fArray;

  // Apply a full update first
  {
    PrefixStringMap fMap;
    nsCString sha256;

    CreateRandomSortedPrefixArray(1000, 4, 32, fArray);
    PrefixArrayToPrefixStringMap(fArray, fMap);
    CalculateSHA256(fArray, sha256);

    testFullUpdate(fMap, &sha256);
  }

  // Apply a partial update with removal indice array larger than
  // old prefix set(fArray). This should cause an error.
  {
    _PrefixArray pArray;
    PrefixStringMap pMap;
    nsTArray<uint32_t> removal;
    TableUpdateArray tableUpdates;

    CreateRandomSortedPrefixArray(200, 4, 32, pArray);
    RemoveIntersection(fArray, pArray);
    PrefixArrayToPrefixStringMap(pArray, pMap);

    for (uint32_t i = 0; i < fArray.Length() + 1; i++) {
      removal.AppendElement(i);
    }

    GenerateUpdateData(false, pMap, &removal, nullptr, tableUpdates);
    testUpdateFail(tableUpdates);
  }

  Clear();
}

TEST(UrlClassifierTableUpdateV4, ChecksumMismatch)
{
  // Apply a full update first
  {
    _PrefixArray fArray;
    PrefixStringMap fMap;
    nsCString sha256;

    CreateRandomSortedPrefixArray(1000, 4, 32, fArray);
    PrefixArrayToPrefixStringMap(fArray, fMap);
    CalculateSHA256(fArray, sha256);

    testFullUpdate(fMap, &sha256);
  }

  // Apply a partial update with incorrect sha256
  {
    _PrefixArray pArray;
    PrefixStringMap pMap;
    nsCString sha256;
    TableUpdateArray tableUpdates;

    CreateRandomSortedPrefixArray(200, 4, 32, pArray);
    PrefixArrayToPrefixStringMap(pArray, pMap);

    // sha256 should be calculated with both old prefix set and add prefix
    // set, here we only calculate sha256 with add prefix set to check if
    // applyUpdate will return failure.
    CalculateSHA256(pArray, sha256);

    GenerateUpdateData(false, pMap, nullptr, &sha256, tableUpdates);
    testUpdateFail(tableUpdates);
  }

  Clear();
}

TEST(UrlClassifierTableUpdateV4, ApplyUpdateThenLoad)
{
  // Apply update with sha256
  {
    _PrefixArray fArray;
    PrefixStringMap fMap;
    nsCString sha256;

    CreateRandomSortedPrefixArray(1000, 4, 32, fArray);
    PrefixArrayToPrefixStringMap(fArray, fMap);
    CalculateSHA256(fArray, sha256);

    testFullUpdate(fMap, &sha256);

    // Open lookup cache will load prefix set and verify the sha256
    testOpenLookupCache();
  }

  Clear();

  // Apply update without sha256
  {
    _PrefixArray fArray;
    PrefixStringMap fMap;

    CreateRandomSortedPrefixArray(1000, 4, 32, fArray);
    PrefixArrayToPrefixStringMap(fArray, fMap);

    testFullUpdate(fMap, nullptr);

    testOpenLookupCache();
  }

  Clear();
}

// This test is used to avoid an eror from nsICryptoHash
TEST(UrlClassifierTableUpdateV4, ApplyUpdateWithFixedChecksum)
{
  _PrefixArray fArray = {_Prefix("enus"),
                         _Prefix("apollo"),
                         _Prefix("mars"),
                         _Prefix("Hecatonchires cyclopes"),
                         _Prefix("vesta"),
                         _Prefix("neptunus"),
                         _Prefix("jupiter"),
                         _Prefix("diana"),
                         _Prefix("minerva"),
                         _Prefix("ceres"),
                         _Prefix("Aidos,Adephagia,Adikia,Aletheia"),
                         _Prefix("hecatonchires"),
                         _Prefix("alcyoneus"),
                         _Prefix("hades"),
                         _Prefix("vulcanus"),
                         _Prefix("juno"),
                         _Prefix("mercury"),
                         _Prefix("Stheno, Euryale and Medusa")};
  fArray.Sort();

  PrefixStringMap fMap;
  PrefixArrayToPrefixStringMap(fArray, fMap);

  nsCString sha256(
      "\xae\x18\x94\xd7\xd0\x83\x5f\xc1"
      "\x58\x59\x5c\x2c\x72\xb9\x6e\x5e"
      "\xf4\xe8\x0a\x6b\xff\x5e\x6b\x81"
      "\x65\x34\x06\x16\x06\x59\xa0\x67");

  testFullUpdate(fMap, &sha256);

  // Open lookup cache will load prefix set and verify the sha256
  testOpenLookupCache();

  Clear();
}

// This test ensure that an empty update works correctly. Empty update
// should be skipped by CheckValidUpdate in Classifier::UpdateTableV4.
TEST(UrlClassifierTableUpdateV4, EmptyUpdate)
{
  PrefixStringMap emptyAddition;
  nsTArray<uint32_t> emptyRemoval;

  _PrefixArray array;
  PrefixStringMap map;
  nsCString sha256;

  CalculateSHA256(array, sha256);

  // Test apply empty full/partial update before we already
  // have data in DB.
  testFullUpdate(emptyAddition, &sha256);
  testPartialUpdate(emptyAddition, &emptyRemoval, &sha256, map);

  // Apply an full update.
  CreateRandomSortedPrefixArray(100, 4, 4, array);
  CreateRandomSortedPrefixArray(10, 5, 32, array);
  PrefixArrayToPrefixStringMap(array, map);
  CalculateSHA256(array, sha256);

  testFullUpdate(map, &sha256);

  // Test apply empty full/partial update when we already
  // have data in DB
  testPartialUpdate(emptyAddition, &emptyRemoval, &sha256, map);
  testFullUpdate(emptyAddition, &sha256);

  Clear();
}

// This test ensure applying an empty update directly through update algorithm
// should be correct.
TEST(UrlClassifierTableUpdateV4, EmptyUpdate2)
{
  // Setup LookupCache with initial data
  _PrefixArray array;
  CreateRandomSortedPrefixArray(100, 4, 4, array);
  CreateRandomSortedPrefixArray(10, 5, 32, array);
  RefPtr<LookupCacheV4> cache = SetupLookupCache<LookupCacheV4>(array);

  // Setup TableUpdate object with only sha256 from previous update(initial
  // data).
  nsCString sha256;
  CalculateSHA256(array, sha256);
  std::string stdSHA256;
  stdSHA256.assign(const_cast<char*>(sha256.BeginReading()), sha256.Length());

  RefPtr<TableUpdateV4> tableUpdate = new TableUpdateV4(GTEST_TABLE);
  tableUpdate->SetSHA256(stdSHA256);

  // Apply update directly through LookupCache interface
  PrefixStringMap input, output;
  PrefixArrayToPrefixStringMap(array, input);
  nsresult rv = cache->ApplyUpdate(tableUpdate.get(), input, output);

  ASSERT_TRUE(rv == NS_OK);

  Clear();
}