File: extension_allowlist_unittest.cc

package info (click to toggle)
chromium 139.0.7258.127-1
  • links: PTS, VCS
  • area: main
  • in suites:
  • size: 6,122,068 kB
  • sloc: cpp: 35,100,771; ansic: 7,163,530; javascript: 4,103,002; python: 1,436,920; asm: 946,517; xml: 746,709; pascal: 187,653; perl: 88,691; sh: 88,436; objc: 79,953; sql: 51,488; cs: 44,583; fortran: 24,137; makefile: 22,147; tcl: 15,277; php: 13,980; yacc: 8,984; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (828 lines) | stat: -rw-r--r-- 35,820 bytes parent folder | download | duplicates (5)
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
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/extensions/extension_allowlist.h"

#include "base/memory/raw_ptr.h"
#include "chrome/browser/extensions/crx_installer.h"
#include "chrome/browser/extensions/extension_management_test_util.h"
#include "chrome/browser/extensions/extension_service.h"
#include "chrome/browser/extensions/extension_service_test_base.h"
#include "chrome/browser/extensions/test_blocklist.h"
#include "chrome/browser/policy/policy_test_utils.h"
#include "chrome/test/base/testing_profile.h"
#include "components/safe_browsing/core/common/safe_browsing_prefs.h"
#include "components/sync_preferences/testing_pref_service_syncable.h"
#include "extensions/browser/allowlist_state.h"
#include "extensions/browser/blocklist_extension_prefs.h"
#include "extensions/browser/disable_reason.h"
#include "extensions/browser/extension_registrar.h"
#include "extensions/browser/extension_registry.h"
#include "extensions/common/extension_builder.h"
#include "extensions/common/extension_features.h"
#include "extensions/common/extension_id.h"
#include "testing/gtest/include/gtest/gtest.h"

namespace extensions {

namespace {

// Extension ids used during testing.
constexpr char kExtensionId1[] = "behllobkkfkfnphdnhnkndlbkcpglgmj";
constexpr char kExtensionId2[] = "hpiknbiabeeppbpihjehijgoemciehgk";
constexpr char kExtensionId3[] = "bjafgdebaacbbbecmhlhpofkepfkgcpa";
constexpr char kInstalledCrx[] = "ldnnhddmnhbkjipkidpdiheffobcpfmf";

using ManagementPrefUpdater = ExtensionManagementPrefUpdater<
    sync_preferences::TestingPrefServiceSyncable>;

}  // namespace

// Test suite to test safe browsing allowlist enforcement.
//
// Features EnforceSafeBrowsingExtensionAllowlist and
// DisableMalwareExtensionsRemotely are enabled.
class ExtensionAllowlistUnitTestBase : public ExtensionServiceTestBase {
 protected:
  // Creates a test extension service with 3 installed extensions.
  void CreateExtensionService(bool enhanced_protection_enabled) {
    ExtensionServiceInitParams params;
    ASSERT_TRUE(
        params.ConfigureByTestDataDirectory(data_dir().AppendASCII("good")));
    InitializeExtensionService(std::move(params));
    extension_prefs_ = ExtensionPrefs::Get(profile());

    if (enhanced_protection_enabled) {
      safe_browsing::SetSafeBrowsingState(
          profile()->GetPrefs(),
          safe_browsing::SafeBrowsingState::ENHANCED_PROTECTION);
    }
  }

  void CreateEmptyExtensionService() {
    InitializeExtensionService(ExtensionServiceInitParams());
    extension_prefs_ = ExtensionPrefs::Get(profile());
    safe_browsing::SetSafeBrowsingState(
        profile()->GetPrefs(),
        safe_browsing::SafeBrowsingState::ENHANCED_PROTECTION);
  }

  void PerformActionBasedOnOmahaAttributes(const ExtensionId& extension_id,
                                           bool is_malware,
                                           bool is_allowlisted) {
    auto attributes = base::Value::Dict().Set("_esbAllowlist", is_allowlisted);
    if (is_malware) {
      attributes.Set("_malware", true);
    }

    service()->PerformActionBasedOnOmahaAttributes(extension_id, attributes);
  }

  bool IsEnabled(const ExtensionId& extension_id) {
    return registry()->enabled_extensions().Contains(extension_id);
  }

  bool IsDisabled(const ExtensionId& extension_id) {
    return registry()->disabled_extensions().Contains(extension_id);
  }

  bool IsBlocklisted(const ExtensionId& extension_id) {
    return registry()->blocklisted_extensions().Contains(extension_id);
  }

  ExtensionAllowlist* allowlist() { return service()->allowlist(); }

  ExtensionPrefs* extension_prefs() { return extension_prefs_; }

 private:
  raw_ptr<ExtensionPrefs> extension_prefs_;
};

class ExtensionAllowlistUnitTest : public ExtensionAllowlistUnitTestBase {
 public:
  ExtensionAllowlistUnitTest() {
    feature_list_.InitWithFeatures(
        {extensions_features::kSafeBrowsingCrxAllowlistShowWarnings,
         extensions_features::kSafeBrowsingCrxAllowlistAutoDisable},
        {});
  }

 private:
  base::test::ScopedFeatureList feature_list_;
};

TEST_F(ExtensionAllowlistUnitTest, AllowlistEnforcement) {
  // Created with 3 installed extensions.
  CreateExtensionService(/*enhanced_protection_enabled=*/true);
  service()->Init();

  // On the first startup, the allowlist state for existing extensions will be
  // undefined.
  EXPECT_EQ(ALLOWLIST_UNDEFINED,
            allowlist()->GetExtensionAllowlistState(kExtensionId1));
  EXPECT_TRUE(extension_prefs()->GetDisableReasons(kExtensionId1).empty());
  EXPECT_TRUE(IsEnabled(kExtensionId1));

  // A first update check will set the allowlist state. In this case, an
  // extension not in the allowlist will be disabled.
  PerformActionBasedOnOmahaAttributes(kExtensionId1,
                                      /*is_malware=*/false,
                                      /*is_allowlisted=*/false);
  EXPECT_EQ(ALLOWLIST_NOT_ALLOWLISTED,
            allowlist()->GetExtensionAllowlistState(kExtensionId1));
  EXPECT_THAT(
      extension_prefs()->GetDisableReasons(kExtensionId1),
      testing::UnorderedElementsAre(disable_reason::DISABLE_NOT_ALLOWLISTED));
  EXPECT_TRUE(IsDisabled(kExtensionId1));

  // A future update check can change the allowlist state. Here the extension is
  // now allowlisted and should be re-enabled.
  PerformActionBasedOnOmahaAttributes(kExtensionId1,
                                      /*is_malware=*/false,
                                      /*is_allowlisted=*/true);
  EXPECT_EQ(ALLOWLIST_ALLOWLISTED,
            allowlist()->GetExtensionAllowlistState(kExtensionId1));
  EXPECT_TRUE(extension_prefs()->GetDisableReasons(kExtensionId1).empty());
  EXPECT_TRUE(IsEnabled(kExtensionId1));

  // When an extension is disabled remotely for malware and is not allowlisted,
  // it should have both disable reasons.
  PerformActionBasedOnOmahaAttributes(kExtensionId1,
                                      /*is_malware=*/true,
                                      /*is_allowlisted=*/false);
  EXPECT_EQ(ALLOWLIST_NOT_ALLOWLISTED,
            allowlist()->GetExtensionAllowlistState(kExtensionId1));
  EXPECT_EQ(BitMapBlocklistState::BLOCKLISTED_MALWARE,
            blocklist_prefs::GetExtensionBlocklistState(kExtensionId1,
                                                        extension_prefs()));
  EXPECT_TRUE(blocklist_prefs::HasOmahaBlocklistState(
      kExtensionId1, BitMapBlocklistState::BLOCKLISTED_MALWARE,
      extension_prefs()));
  EXPECT_THAT(
      extension_prefs()->GetDisableReasons(kExtensionId1),
      testing::UnorderedElementsAre(disable_reason::DISABLE_NOT_ALLOWLISTED));
  EXPECT_TRUE(IsBlocklisted(kExtensionId1));

  // A blocklisted item should not be allowlisted, but if the improbable
  // happens, the item should still be blocklisted.
  PerformActionBasedOnOmahaAttributes(kExtensionId1,
                                      /*is_malware=*/true,
                                      /*is_allowlisted=*/true);
  EXPECT_EQ(ALLOWLIST_ALLOWLISTED,
            allowlist()->GetExtensionAllowlistState(kExtensionId1));
  EXPECT_EQ(BitMapBlocklistState::BLOCKLISTED_MALWARE,
            blocklist_prefs::GetExtensionBlocklistState(kExtensionId1,
                                                        extension_prefs()));
  EXPECT_TRUE(blocklist_prefs::HasOmahaBlocklistState(
      kExtensionId1, BitMapBlocklistState::BLOCKLISTED_MALWARE,
      extension_prefs()));
  EXPECT_TRUE(extension_prefs()->GetDisableReasons(kExtensionId1).empty());
  EXPECT_TRUE(IsBlocklisted(kExtensionId1));

  // If the item is removed from the malware blocklist, it should stay disabled
  // if it's not allowlisted.
  PerformActionBasedOnOmahaAttributes(kExtensionId1,
                                      /*is_malware=*/false,
                                      /*is_allowlisted=*/false);
  EXPECT_EQ(ALLOWLIST_NOT_ALLOWLISTED,
            allowlist()->GetExtensionAllowlistState(kExtensionId1));
  EXPECT_EQ(BitMapBlocklistState::NOT_BLOCKLISTED,
            blocklist_prefs::GetSafeBrowsingExtensionBlocklistState(
                kExtensionId1, extension_prefs()));
  EXPECT_THAT(
      extension_prefs()->GetDisableReasons(kExtensionId1),
      testing::UnorderedElementsAre(disable_reason::DISABLE_NOT_ALLOWLISTED));
  EXPECT_TRUE(IsDisabled(kExtensionId1));
}

TEST_F(ExtensionAllowlistUnitTest, DisabledReasonResetWhenBlocklisted) {
  // Created with 3 installed extensions.
  CreateExtensionService(/*enhanced_protection_enabled=*/true);
  service()->Init();

  // The disabled reason should be set if an extension is not in the allowlist.
  PerformActionBasedOnOmahaAttributes(kExtensionId1,
                                      /*is_malware=*/false,
                                      /*is_allowlisted=*/false);
  EXPECT_THAT(
      extension_prefs()->GetDisableReasons(kExtensionId1),
      testing::UnorderedElementsAre(disable_reason::DISABLE_NOT_ALLOWLISTED));

  // The extension is added to the blocklist.
  service()->BlocklistExtensionForTest(kExtensionId1);

  // A blocklisted item should not be allowlisted, but if the improbable
  // happens, the item should still be blocklisted.
  PerformActionBasedOnOmahaAttributes(kExtensionId1,
                                      /*is_malware=*/false,
                                      /*is_allowlisted=*/true);
  EXPECT_TRUE(IsBlocklisted(kExtensionId1));
  // The disabled reason should be reset because the extension is in the
  // allowlist.
  EXPECT_TRUE(extension_prefs()->GetDisableReasons(kExtensionId1).empty());
}

TEST_F(ExtensionAllowlistUnitTest, DisabledItemStaysDisabledWhenAllowlisted) {
  // Created with 3 installed extensions.
  CreateExtensionService(/*enhanced_protection_enabled=*/true);
  service()->Init();

  // Start with an extension disabled by user.
  registrar()->DisableExtension(kExtensionId1,
                                {disable_reason::DISABLE_USER_ACTION});
  EXPECT_TRUE(IsDisabled(kExtensionId1));

  // Disable the extension with allowlist enforcement.
  PerformActionBasedOnOmahaAttributes(kExtensionId1,
                                      /*is_malware=*/false,
                                      /*is_allowlisted=*/false);
  EXPECT_EQ(ALLOWLIST_NOT_ALLOWLISTED,
            allowlist()->GetExtensionAllowlistState(kExtensionId1));
  EXPECT_THAT(
      extension_prefs()->GetDisableReasons(kExtensionId1),
      testing::UnorderedElementsAre(disable_reason::DISABLE_USER_ACTION,
                                    disable_reason::DISABLE_NOT_ALLOWLISTED));
  EXPECT_TRUE(IsDisabled(kExtensionId1));

  // The extension is allowlisted, but stays disabled by user action.
  PerformActionBasedOnOmahaAttributes(kExtensionId1,
                                      /*is_malware=*/false,
                                      /*is_allowlisted=*/true);
  EXPECT_EQ(ALLOWLIST_ALLOWLISTED,
            allowlist()->GetExtensionAllowlistState(kExtensionId1));
  EXPECT_EQ(BitMapBlocklistState::NOT_BLOCKLISTED,
            blocklist_prefs::GetSafeBrowsingExtensionBlocklistState(
                kExtensionId1, extension_prefs()));
  EXPECT_THAT(
      extension_prefs()->GetDisableReasons(kExtensionId1),
      testing::UnorderedElementsAre(disable_reason::DISABLE_USER_ACTION));
  EXPECT_TRUE(IsDisabled(kExtensionId1));
}

TEST_F(ExtensionAllowlistUnitTest, EnforcementOnInit) {
  // Created with 3 installed extensions.
  CreateExtensionService(/*enhanced_protection_enabled=*/true);

  // Start an extension not allowlisted and in an unenforced state, this can
  // happen if the 'EnforceSafeBrowsingExtensionAllowlist' feature was
  // previously disabled for this profile.
  allowlist()->SetExtensionAllowlistState(kExtensionId1,
                                          ALLOWLIST_NOT_ALLOWLISTED);

  // During initialization, the allowlist will be enforced for extensions not
  // allowlisted.
  service()->Init();
  EXPECT_EQ(ALLOWLIST_NOT_ALLOWLISTED,
            allowlist()->GetExtensionAllowlistState(kExtensionId1));
  EXPECT_THAT(
      extension_prefs()->GetDisableReasons(kExtensionId1),
      testing::UnorderedElementsAre(disable_reason::DISABLE_NOT_ALLOWLISTED));
  EXPECT_TRUE(IsDisabled(kExtensionId1));

  // The enforcement isn't done for extensions having an undefined allowlist
  // state.
  EXPECT_EQ(ALLOWLIST_UNDEFINED,
            allowlist()->GetExtensionAllowlistState(kExtensionId2));
  EXPECT_TRUE(IsEnabled(kExtensionId2));
}

TEST_F(ExtensionAllowlistUnitTest, EnhancedProtectionSettingChange) {
  // Created with 3 installed extensions.
  CreateExtensionService(/*enhanced_protection_enabled=*/false);
  // Start with ESB off and one extension not allowlisted.
  allowlist()->SetExtensionAllowlistState(kExtensionId1,
                                          ALLOWLIST_NOT_ALLOWLISTED);

  // Since ESB is off, no enforcement will be done for extensions not
  // allowlisted.
  service()->Init();
  EXPECT_EQ(ALLOWLIST_NOT_ALLOWLISTED,
            allowlist()->GetExtensionAllowlistState(kExtensionId1));
  EXPECT_TRUE(IsEnabled(kExtensionId1));

  EXPECT_EQ(ALLOWLIST_UNDEFINED,
            allowlist()->GetExtensionAllowlistState(kExtensionId2));

  // Even if the enforcement is off, the allowlist state is still tracked when
  // receiving update check results.
  PerformActionBasedOnOmahaAttributes(kExtensionId2,
                                      /*is_malware=*/false,
                                      /*is_allowlisted=*/false);
  EXPECT_EQ(ALLOWLIST_NOT_ALLOWLISTED,
            allowlist()->GetExtensionAllowlistState(kExtensionId2));
  EXPECT_TRUE(IsEnabled(kExtensionId2));

  // When ESB is enabled, the extension service will enforce all extensions with
  // `ALLOWLIST_NOT_ALLOWLISTED` state.
  safe_browsing::SetSafeBrowsingState(
      profile()->GetPrefs(),
      safe_browsing::SafeBrowsingState::ENHANCED_PROTECTION);
  EXPECT_EQ(ALLOWLIST_NOT_ALLOWLISTED,
            allowlist()->GetExtensionAllowlistState(kExtensionId1));
  EXPECT_THAT(
      extension_prefs()->GetDisableReasons(kExtensionId1),
      testing::UnorderedElementsAre(disable_reason::DISABLE_NOT_ALLOWLISTED));
  EXPECT_TRUE(IsDisabled(kExtensionId1));

  EXPECT_EQ(ALLOWLIST_NOT_ALLOWLISTED,
            allowlist()->GetExtensionAllowlistState(kExtensionId2));
  EXPECT_THAT(
      extension_prefs()->GetDisableReasons(kExtensionId2),
      testing::UnorderedElementsAre(disable_reason::DISABLE_NOT_ALLOWLISTED));
  EXPECT_TRUE(IsDisabled(kExtensionId2));

  // If the ESB setting is turned off, the extensions are re-enabled.
  safe_browsing::SetSafeBrowsingState(
      profile()->GetPrefs(),
      safe_browsing::SafeBrowsingState::STANDARD_PROTECTION);
  EXPECT_EQ(ALLOWLIST_NOT_ALLOWLISTED,
            allowlist()->GetExtensionAllowlistState(kExtensionId1));
  EXPECT_TRUE(IsEnabled(kExtensionId1));

  EXPECT_EQ(ALLOWLIST_NOT_ALLOWLISTED,
            allowlist()->GetExtensionAllowlistState(kExtensionId2));
  EXPECT_TRUE(IsEnabled(kExtensionId2));
}

TEST_F(ExtensionAllowlistUnitTest, ExtensionsNotAllowlistedThenBlocklisted) {
  // Created with 3 installed extensions.
  CreateExtensionService(/*enhanced_protection_enabled=*/true);
  TestBlocklist test_blocklist;
  test_blocklist.Attach(service()->blocklist_);

  // Start with two not allowlisted extensions, the enforcement will be done
  // during `Init`.
  allowlist()->SetExtensionAllowlistState(kExtensionId1,
                                          ALLOWLIST_NOT_ALLOWLISTED);
  allowlist()->SetExtensionAllowlistState(kExtensionId2,
                                          ALLOWLIST_NOT_ALLOWLISTED);
  service()->Init();
  EXPECT_EQ(ALLOWLIST_NOT_ALLOWLISTED,
            allowlist()->GetExtensionAllowlistState(kExtensionId1));
  EXPECT_TRUE(IsDisabled(kExtensionId1));

  EXPECT_EQ(ALLOWLIST_NOT_ALLOWLISTED,
            allowlist()->GetExtensionAllowlistState(kExtensionId2));
  EXPECT_TRUE(IsDisabled(kExtensionId2));

  // Then blocklist and greylist the two extensions respectively.
  test_blocklist.SetBlocklistState(kExtensionId1, BLOCKLISTED_MALWARE, true);
  test_blocklist.SetBlocklistState(kExtensionId2,
                                   BLOCKLISTED_POTENTIALLY_UNWANTED, true);
  base::RunLoop().RunUntilIdle();
  EXPECT_EQ(ALLOWLIST_NOT_ALLOWLISTED,
            allowlist()->GetExtensionAllowlistState(kExtensionId1));
  EXPECT_EQ(BitMapBlocklistState::BLOCKLISTED_MALWARE,
            blocklist_prefs::GetSafeBrowsingExtensionBlocklistState(
                kExtensionId1, extension_prefs()));
  EXPECT_THAT(
      extension_prefs()->GetDisableReasons(kExtensionId1),
      testing::UnorderedElementsAre(disable_reason::DISABLE_NOT_ALLOWLISTED));
  EXPECT_TRUE(IsBlocklisted(kExtensionId1));

  EXPECT_EQ(ALLOWLIST_NOT_ALLOWLISTED,
            allowlist()->GetExtensionAllowlistState(kExtensionId2));
  EXPECT_EQ(BitMapBlocklistState::BLOCKLISTED_POTENTIALLY_UNWANTED,
            blocklist_prefs::GetSafeBrowsingExtensionBlocklistState(
                kExtensionId2, extension_prefs()));
  EXPECT_THAT(
      extension_prefs()->GetDisableReasons(kExtensionId2),
      testing::UnorderedElementsAre(disable_reason::DISABLE_GREYLIST,
                                    disable_reason::DISABLE_NOT_ALLOWLISTED));
  EXPECT_TRUE(IsDisabled(kExtensionId2));

  // When the extensions are unblocklisted, the allowlist enforcement will still
  // be effective if the extensions are not allowlisted.
  test_blocklist.SetBlocklistState(kExtensionId1, NOT_BLOCKLISTED, true);
  test_blocklist.SetBlocklistState(kExtensionId2, NOT_BLOCKLISTED, true);
  base::RunLoop().RunUntilIdle();

  EXPECT_EQ(ALLOWLIST_NOT_ALLOWLISTED,
            allowlist()->GetExtensionAllowlistState(kExtensionId1));
  EXPECT_EQ(BitMapBlocklistState::NOT_BLOCKLISTED,
            blocklist_prefs::GetSafeBrowsingExtensionBlocklistState(
                kExtensionId1, extension_prefs()));
  EXPECT_THAT(
      extension_prefs()->GetDisableReasons(kExtensionId1),
      testing::UnorderedElementsAre(disable_reason::DISABLE_NOT_ALLOWLISTED));
  EXPECT_TRUE(IsDisabled(kExtensionId1));

  EXPECT_EQ(ALLOWLIST_NOT_ALLOWLISTED,
            allowlist()->GetExtensionAllowlistState(kExtensionId2));
  EXPECT_EQ(BitMapBlocklistState::NOT_BLOCKLISTED,
            blocklist_prefs::GetSafeBrowsingExtensionBlocklistState(
                kExtensionId2, extension_prefs()));
  EXPECT_THAT(
      extension_prefs()->GetDisableReasons(kExtensionId2),
      testing::UnorderedElementsAre(disable_reason::DISABLE_NOT_ALLOWLISTED));
  EXPECT_TRUE(IsDisabled(kExtensionId2));
}

TEST_F(ExtensionAllowlistUnitTest, ExtensionsBlocklistedThenNotAllowlisted) {
  // Created with 3 installed extensions.
  CreateExtensionService(/*enhanced_protection_enabled=*/true);
  TestBlocklist test_blocklist;
  test_blocklist.Attach(service()->blocklist_);

  service()->Init();

  // Blocklist and greylist the two extensions respectively.
  test_blocklist.SetBlocklistState(kExtensionId1, BLOCKLISTED_MALWARE, true);
  base::RunLoop().RunUntilIdle();
  EXPECT_EQ(BitMapBlocklistState::BLOCKLISTED_MALWARE,
            blocklist_prefs::GetSafeBrowsingExtensionBlocklistState(
                kExtensionId1, extension_prefs()));
  EXPECT_TRUE(IsBlocklisted(kExtensionId1));

  // The extension is then also disabled from allowlist enforcement.
  PerformActionBasedOnOmahaAttributes(kExtensionId1,
                                      /*is_malware=*/false,
                                      /*is_allowlisted=*/false);
  EXPECT_EQ(ALLOWLIST_NOT_ALLOWLISTED,
            allowlist()->GetExtensionAllowlistState(kExtensionId1));
  EXPECT_EQ(BitMapBlocklistState::BLOCKLISTED_MALWARE,
            blocklist_prefs::GetSafeBrowsingExtensionBlocklistState(
                kExtensionId1, extension_prefs()));
  // The disable reason is added even if the extension is already blocklisted.
  EXPECT_THAT(
      extension_prefs()->GetDisableReasons(kExtensionId1),
      testing::UnorderedElementsAre(disable_reason::DISABLE_NOT_ALLOWLISTED));
  EXPECT_TRUE(IsBlocklisted(kExtensionId1));

  // When the extensions is unblocklisted, the allowlist enforcement will still
  // be effective if the extension is not allowlisted.
  test_blocklist.SetBlocklistState(kExtensionId1, NOT_BLOCKLISTED, true);
  base::RunLoop().RunUntilIdle();

  EXPECT_EQ(ALLOWLIST_NOT_ALLOWLISTED,
            allowlist()->GetExtensionAllowlistState(kExtensionId1));
  EXPECT_EQ(BitMapBlocklistState::NOT_BLOCKLISTED,
            blocklist_prefs::GetSafeBrowsingExtensionBlocklistState(
                kExtensionId1, extension_prefs()));
  EXPECT_THAT(
      extension_prefs()->GetDisableReasons(kExtensionId1),
      testing::UnorderedElementsAre(disable_reason::DISABLE_NOT_ALLOWLISTED));
  EXPECT_TRUE(IsDisabled(kExtensionId1));
}

TEST_F(ExtensionAllowlistUnitTest, MissingAttributeAreIgnored) {
  // Created with 3 installed extensions.
  CreateExtensionService(/*enhanced_protection_enabled=*/true);

  // Start with one extension allowlisted and another not allowlisted.
  allowlist()->SetExtensionAllowlistState(kExtensionId1, ALLOWLIST_ALLOWLISTED);
  allowlist()->SetExtensionAllowlistState(kExtensionId2,
                                          ALLOWLIST_NOT_ALLOWLISTED);

  // During initialization, the allowlist will be enforced for extensions not
  // allowlisted.
  service()->Init();
  EXPECT_TRUE(IsEnabled(kExtensionId1));
  EXPECT_THAT(
      extension_prefs()->GetDisableReasons(kExtensionId2),
      testing::UnorderedElementsAre(disable_reason::DISABLE_NOT_ALLOWLISTED));

  // Simulate an update check with no custom attribute defined.
  base::Value::Dict attributes;
  service()->PerformActionBasedOnOmahaAttributes(kExtensionId1, attributes);
  service()->PerformActionBasedOnOmahaAttributes(kExtensionId2, attributes);

  // The undefined allowlist attributes should be ignored and the state should
  // remain unchanged.
  EXPECT_EQ(ALLOWLIST_ALLOWLISTED,
            allowlist()->GetExtensionAllowlistState(kExtensionId1));
  EXPECT_TRUE(IsEnabled(kExtensionId1));

  EXPECT_EQ(ALLOWLIST_NOT_ALLOWLISTED,
            allowlist()->GetExtensionAllowlistState(kExtensionId2));
  EXPECT_THAT(
      extension_prefs()->GetDisableReasons(kExtensionId2),
      testing::UnorderedElementsAre(disable_reason::DISABLE_NOT_ALLOWLISTED));
}

TEST_F(ExtensionAllowlistUnitTest, AcknowledgeNeededOnEnforcement) {
  CreateExtensionService(/*enhanced_protection_enabled=*/true);

  service()->Init();
  EXPECT_TRUE(IsEnabled(kExtensionId1));
  EXPECT_EQ(ALLOWLIST_ACKNOWLEDGE_NONE,
            allowlist()->GetExtensionAllowlistAcknowledgeState(kExtensionId1));

  // Make the extension not allowlisted.
  PerformActionBasedOnOmahaAttributes(kExtensionId1,
                                      /*is_malware=*/false,
                                      /*is_allowlisted=*/false);

  // Expect the acknowledge state to change appropriately.
  EXPECT_TRUE(IsDisabled(kExtensionId1));
  EXPECT_EQ(ALLOWLIST_ACKNOWLEDGE_NEEDED,
            allowlist()->GetExtensionAllowlistAcknowledgeState(kExtensionId1));
}

TEST_F(ExtensionAllowlistUnitTest, AcknowledgeNotNeededIfAlreadyDisabled) {
  CreateExtensionService(/*enhanced_protection_enabled=*/true);

  service()->Init();
  registrar()->DisableExtension(kExtensionId1,
                                {disable_reason::DISABLE_USER_ACTION});
  EXPECT_TRUE(IsDisabled(kExtensionId1));
  EXPECT_EQ(ALLOWLIST_ACKNOWLEDGE_NONE,
            allowlist()->GetExtensionAllowlistAcknowledgeState(kExtensionId1));

  // Make the extension not allowlisted.
  PerformActionBasedOnOmahaAttributes(kExtensionId1,
                                      /*is_malware=*/false,
                                      /*is_allowlisted=*/false);

  // There is no need for acknowledge if the extension was already disabled.
  EXPECT_TRUE(IsDisabled(kExtensionId1));
  EXPECT_THAT(
      extension_prefs()->GetDisableReasons(kExtensionId1),
      testing::UnorderedElementsAre(disable_reason::DISABLE_NOT_ALLOWLISTED,
                                    disable_reason::DISABLE_USER_ACTION));
  EXPECT_EQ(ALLOWLIST_ACKNOWLEDGE_NONE,
            allowlist()->GetExtensionAllowlistAcknowledgeState(kExtensionId1));
}

TEST_F(ExtensionAllowlistUnitTest,
       AcknowledgeStateIsSetWhenExtensionIsReenabled) {
  CreateExtensionService(/*enhanced_protection_enabled=*/true);

  EXPECT_EQ(ALLOWLIST_ACKNOWLEDGE_NONE,
            allowlist()->GetExtensionAllowlistAcknowledgeState(kExtensionId1));

  // Start with a not allowlisted extension.
  allowlist()->SetExtensionAllowlistState(kExtensionId1,
                                          ALLOWLIST_NOT_ALLOWLISTED);

  // The enforcement on init should disable the extension.
  service()->Init();
  EXPECT_TRUE(IsDisabled(kExtensionId1));
  EXPECT_EQ(ALLOWLIST_ACKNOWLEDGE_NEEDED,
            allowlist()->GetExtensionAllowlistAcknowledgeState(kExtensionId1));

  // Re-enable the extension.
  registrar()->EnableExtension(kExtensionId1);

  // The extensions should now be marked with
  // `ALLOWLIST_ACKNOWLEDGE_ENABLED_BY_USER'.
  EXPECT_EQ(ALLOWLIST_ACKNOWLEDGE_ENABLED_BY_USER,
            allowlist()->GetExtensionAllowlistAcknowledgeState(kExtensionId1));
  EXPECT_TRUE(IsEnabled(kExtensionId1));
  EXPECT_EQ(ALLOWLIST_NOT_ALLOWLISTED,
            allowlist()->GetExtensionAllowlistState(kExtensionId1));
}

TEST_F(ExtensionAllowlistUnitTest, ReenabledExtensionsAreNotReenforced) {
  CreateExtensionService(/*enhanced_protection_enabled=*/true);

  // Start with a not allowlisted extension that was re-enabled by user.
  allowlist()->SetExtensionAllowlistState(kExtensionId1,
                                          ALLOWLIST_NOT_ALLOWLISTED);
  allowlist()->SetExtensionAllowlistAcknowledgeState(
      kExtensionId1, ALLOWLIST_ACKNOWLEDGE_ENABLED_BY_USER);

  // And an extension that became allowlisted after it was re-enabled by user.
  allowlist()->SetExtensionAllowlistState(kExtensionId2, ALLOWLIST_ALLOWLISTED);
  allowlist()->SetExtensionAllowlistAcknowledgeState(
      kExtensionId2, ALLOWLIST_ACKNOWLEDGE_ENABLED_BY_USER);

  service()->Init();
  // Even though ExtensionId1 is not allowlisted, it should stay enabled because
  // it was re-enabled by user.
  EXPECT_TRUE(IsEnabled(kExtensionId1));
  // Assert that ExtensionId2 is enabled before testing the allowlist state
  // change.
  EXPECT_TRUE(IsEnabled(kExtensionId2));

  // If `kExtensionId2` becomes not allowlisted again, it should stay enabled
  // because the user already chose to re-enable it in the past.
  PerformActionBasedOnOmahaAttributes(kExtensionId2,
                                      /*is_malware=*/false,
                                      /*is_allowlisted=*/false);
  EXPECT_TRUE(IsEnabled(kExtensionId2));
  EXPECT_EQ(ALLOWLIST_ACKNOWLEDGE_ENABLED_BY_USER,
            allowlist()->GetExtensionAllowlistAcknowledgeState(kExtensionId2));
  EXPECT_EQ(ALLOWLIST_NOT_ALLOWLISTED,
            allowlist()->GetExtensionAllowlistState(kExtensionId2));
}

TEST_F(ExtensionAllowlistUnitTest, TurnOffEnhancedProtection) {
  CreateExtensionService(/*enhanced_protection_enabled=*/true);

  // Start with 3 not allowlisted extensions.
  allowlist()->SetExtensionAllowlistState(kExtensionId1,
                                          ALLOWLIST_NOT_ALLOWLISTED);
  allowlist()->SetExtensionAllowlistState(kExtensionId2,
                                          ALLOWLIST_NOT_ALLOWLISTED);
  allowlist()->SetExtensionAllowlistState(kExtensionId3,
                                          ALLOWLIST_NOT_ALLOWLISTED);
  allowlist()->SetExtensionAllowlistAcknowledgeState(
      kExtensionId3, ALLOWLIST_ACKNOWLEDGE_ENABLED_BY_USER);

  // They should get disabled by allowlist enforcement and have their
  // acknowledge state set (except the extension re-enabled by user).
  service()->Init();
  EXPECT_TRUE(IsDisabled(kExtensionId1));
  EXPECT_EQ(ALLOWLIST_ACKNOWLEDGE_NEEDED,
            allowlist()->GetExtensionAllowlistAcknowledgeState(kExtensionId1));

  EXPECT_TRUE(IsDisabled(kExtensionId2));
  EXPECT_EQ(ALLOWLIST_ACKNOWLEDGE_NEEDED,
            allowlist()->GetExtensionAllowlistAcknowledgeState(kExtensionId2));

  EXPECT_TRUE(IsEnabled(kExtensionId3));
  EXPECT_EQ(ALLOWLIST_ACKNOWLEDGE_ENABLED_BY_USER,
            allowlist()->GetExtensionAllowlistAcknowledgeState(kExtensionId3));

  // Leave `kExtensionId1` with acknowledge needed and acknowledge
  // `kExtensionId2`.
  allowlist()->SetExtensionAllowlistAcknowledgeState(
      kExtensionId2, ALLOWLIST_ACKNOWLEDGE_DONE);

  // When turning off enhanced protection.
  safe_browsing::SetSafeBrowsingState(
      profile()->GetPrefs(),
      safe_browsing::SafeBrowsingState::STANDARD_PROTECTION);

  // 'kExtensionId1' and 'kExtensionId2' should be re-enabled and have their
  // acknowledge state reset.
  EXPECT_TRUE(IsEnabled(kExtensionId1));
  EXPECT_EQ(ALLOWLIST_ACKNOWLEDGE_NONE,
            allowlist()->GetExtensionAllowlistAcknowledgeState(kExtensionId1));

  EXPECT_TRUE(IsEnabled(kExtensionId2));
  EXPECT_EQ(ALLOWLIST_ACKNOWLEDGE_NONE,
            allowlist()->GetExtensionAllowlistAcknowledgeState(kExtensionId2));

  // 'kExtensionId3' should remain enabled because it was already re-enabled by
  // user.
  EXPECT_TRUE(IsEnabled(kExtensionId3));
  EXPECT_EQ(ALLOWLIST_ACKNOWLEDGE_ENABLED_BY_USER,
            allowlist()->GetExtensionAllowlistAcknowledgeState(kExtensionId3));
}

TEST_F(ExtensionAllowlistUnitTest, BypassFrictionSetAckowledgeEnabledByUser) {
  CreateExtensionService(/*enhanced_protection_enabled=*/true);

  scoped_refptr<CrxInstaller> installer(CrxInstaller::CreateSilent(profile()));
  installer->set_allow_silent_install(true);
  installer->set_bypassed_safebrowsing_friction_for_testing(true);

  base::RunLoop run_loop;
  installer->AddInstallerCallback(base::BindOnce(
      [](base::OnceClosure quit_closure,
         const std::optional<CrxInstallError>& error) {
        ASSERT_FALSE(error) << error->message();
        std::move(quit_closure).Run();
      },
      run_loop.QuitWhenIdleClosure()));

  installer->InstallCrx(data_dir().AppendASCII("good.crx"));
  run_loop.Run();

  EXPECT_TRUE(registry()->enabled_extensions().GetByID(kInstalledCrx));
  EXPECT_EQ(ALLOWLIST_NOT_ALLOWLISTED,
            allowlist()->GetExtensionAllowlistState(kInstalledCrx));
  EXPECT_EQ(ALLOWLIST_ACKNOWLEDGE_ENABLED_BY_USER,
            allowlist()->GetExtensionAllowlistAcknowledgeState(kInstalledCrx));
}

TEST_F(ExtensionAllowlistUnitTest, NoEnforcementOnPolicyForceInstall) {
  // Mark as enterprise managed.
  policy::ScopedDomainEnterpriseManagement scoped_domain;
  CreateEmptyExtensionService();
  service()->Init();

  // Add a policy installed extension.
  scoped_refptr<const Extension> extension =
      ExtensionBuilder("policy_installed")
          .SetPath(data_dir().AppendASCII("good.crx"))
          .SetLocation(mojom::ManifestLocation::kExternalPolicyDownload)
          .Build();
  registrar()->AddExtension(extension.get());

  {
    ManagementPrefUpdater pref(profile_->GetTestingPrefService());
    pref.SetIndividualExtensionAutoInstalled(
        extension->id(), "http://example.com/update_url", true);
  }

  EXPECT_TRUE(IsEnabled(extension->id()));

  // On next update check, the extension is now marked as not allowlisted.
  PerformActionBasedOnOmahaAttributes(extension->id(),
                                      /*is_malware=*/false,
                                      /*is_allowlisted=*/false);

  EXPECT_EQ(ALLOWLIST_NOT_ALLOWLISTED,
            allowlist()->GetExtensionAllowlistState(extension->id()));
  // A policy installed extension is not disabled by allowlist enforcement.
  EXPECT_TRUE(IsEnabled(extension->id()));
  // No warnings are shown for policy installed extensions.
  EXPECT_FALSE(allowlist()->ShouldDisplayWarning(extension->id()));
}

class ExtensionAllowlistWithFeatureDisabledUnitTest
    : public ExtensionAllowlistUnitTestBase {
 public:
  ExtensionAllowlistWithFeatureDisabledUnitTest() {
    // Test with warnings enabled but auto disable disabled.
    feature_list_.InitWithFeatures(
        {extensions_features::kSafeBrowsingCrxAllowlistShowWarnings},
        {extensions_features::kSafeBrowsingCrxAllowlistAutoDisable});
  }

 private:
  base::test::ScopedFeatureList feature_list_;
};

TEST_F(ExtensionAllowlistWithFeatureDisabledUnitTest,
       NoEnforcementWhenFeatureDisabled) {
  // Created with 3 installed extensions.
  CreateExtensionService(/*enhanced_protection_enabled=*/true);

  allowlist()->SetExtensionAllowlistState(kExtensionId1,
                                          ALLOWLIST_NOT_ALLOWLISTED);
  service()->Init();
  EXPECT_TRUE(IsEnabled(kExtensionId1));

  PerformActionBasedOnOmahaAttributes(kExtensionId2,
                                      /*is_malware=*/false,
                                      /*is_allowlisted=*/false);
  EXPECT_TRUE(IsEnabled(kExtensionId1));
}

// TODO(jeffcyr): Test with auto-disablement enabled when the enforcement is
// skipped for policy recommended and policy allowed extensions.
TEST_F(ExtensionAllowlistWithFeatureDisabledUnitTest,
       NoEnforcementOnPolicyRecommendedInstall) {
  CreateEmptyExtensionService();
  service()->Init();

  // Add a policy installed extension.
  scoped_refptr<const Extension> extension =
      ExtensionBuilder("policy_installed")
          .SetPath(data_dir().AppendASCII("good.crx"))
          .SetLocation(mojom::ManifestLocation::kExternalPrefDownload)
          .Build();
  registrar()->AddExtension(extension.get());

  {
    ManagementPrefUpdater pref(profile_->GetTestingPrefService());
    pref.SetIndividualExtensionAutoInstalled(
        extension->id(), "http://example.com/update_url", false);
  }

  EXPECT_TRUE(IsEnabled(extension->id()));

  // On next update check, the extension is now marked as not allowlisted.
  PerformActionBasedOnOmahaAttributes(extension->id(),
                                      /*is_malware=*/false,
                                      /*is_allowlisted=*/false);

  EXPECT_EQ(ALLOWLIST_NOT_ALLOWLISTED,
            allowlist()->GetExtensionAllowlistState(extension->id()));
  // A policy installed extension is not disabled by allowlist enforcement.
  EXPECT_TRUE(IsEnabled(extension->id()));
  // No warnings are shown for policy installed extensions.
  EXPECT_FALSE(allowlist()->ShouldDisplayWarning(extension->id()));
}

TEST_F(ExtensionAllowlistWithFeatureDisabledUnitTest,
       NoEnforcementOnPolicyAllowedInstall) {
  CreateEmptyExtensionService();
  service()->Init();

  // Add a policy allowed extension.
  scoped_refptr<const Extension> extension =
      ExtensionBuilder("policy_allowed")
          .SetPath(data_dir().AppendASCII("good.crx"))
          .SetLocation(mojom::ManifestLocation::kInternal)
          .Build();
  registrar()->AddExtension(extension.get());

  {
    ManagementPrefUpdater pref(profile_->GetTestingPrefService());
    pref.SetIndividualExtensionInstallationAllowed(extension->id(), true);
  }

  EXPECT_TRUE(IsEnabled(extension->id()));

  // On next update check, the extension is now marked as not allowlisted.
  PerformActionBasedOnOmahaAttributes(extension->id(),
                                      /*is_malware=*/false,
                                      /*is_allowlisted=*/false);

  EXPECT_EQ(ALLOWLIST_NOT_ALLOWLISTED,
            allowlist()->GetExtensionAllowlistState(extension->id()));
  // An extension allowed by policy is not disabled by allowlist enforcement.
  EXPECT_TRUE(IsEnabled(extension->id()));
  // No warnings are shown for policy allowed extensions.
  EXPECT_FALSE(allowlist()->ShouldDisplayWarning(extension->id()));
}

// TODO(crbug.com/40175473): Add more ExtensionAllowlist::Observer coverage

}  // namespace extensions