File: pref_hash_browsertest.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 (1927 lines) | stat: -rw-r--r-- 78,688 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
// Copyright 2014 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include <memory>
#include <optional>
#include <string>
#include <utility>

#include "base/base_switches.h"
#include "base/check_deref.h"
#include "base/command_line.h"
#include "base/files/file_path.h"
#include "base/files/file_util.h"
#include "base/json/json_file_value_serializer.h"
#include "base/json/json_reader.h"
#include "base/metrics/histogram_base.h"
#include "base/metrics/histogram_samples.h"
#include "base/metrics/statistics_recorder.h"
#include "base/path_service.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_util.h"
#include "base/strings/stringprintf.h"
#include "base/strings/utf_string_conversions.h"
#include "base/test/metrics/histogram_tester.h"
#include "base/test/scoped_feature_list.h"
#include "base/values.h"
#include "build/build_config.h"
#include "chrome/browser/extensions/extension_browsertest.h"
#include "chrome/browser/prefs/chrome_pref_service_factory.h"
#include "chrome/browser/prefs/profile_pref_store_manager.h"
#include "chrome/browser/prefs/session_startup_pref.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/search_engine_choice/search_engine_choice_service_factory.h"
#include "chrome/browser/search_engines/template_url_prepopulate_data_resolver_factory.h"
#include "chrome/browser/sync/test/integration/sync_test.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/common/chrome_constants.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/pref_names.h"
#include "chrome/test/base/testing_profile.h"
#include "components/prefs/json_pref_store.h"
#include "components/prefs/pref_service.h"
#include "components/prefs/scoped_user_pref_update.h"
#include "components/prefs/segregated_pref_store.h"
#include "components/search_engines/default_search_manager.h"
#include "components/search_engines/template_url_data.h"
#include "components/signin/public/base/signin_switches.h"
#include "components/sync/base/features.h"
#include "content/public/test/browser_task_environment.h"
#include "content/public/test/browser_test.h"
#include "content/public/test/test_launcher.h"
#include "extensions/browser/pref_names.h"
#include "extensions/common/extension.h"
#include "services/preferences/public/cpp/tracked/tracked_preference_histogram_names.h"
#include "services/preferences/tracked/features.h"

#if BUILDFLAG(IS_CHROMEOS)
#include "ash/constants/ash_switches.h"
#endif

#if BUILDFLAG(IS_WIN)
#include "base/win/registry.h"
#include "chrome/install_static/install_util.h"
#endif

namespace {

// Extension ID of chrome/test/data/extensions/good.crx
const char kGoodCrxId[] = "ldnnhddmnhbkjipkidpdiheffobcpfmf";

// Explicit expectations from the caller of GetTrackedPrefHistogramCount(). This
// enables detailed reporting of the culprit on failure.
enum AllowedBuckets {
  // Allow no samples in any buckets.
  ALLOW_NONE = -1,
  // Any integer between BEGIN_ALLOW_SINGLE_BUCKET and END_ALLOW_SINGLE_BUCKET
  // indicates that only this specific bucket is allowed to have a sample.
  BEGIN_ALLOW_SINGLE_BUCKET = 0,
  END_ALLOW_SINGLE_BUCKET = 100,
  // Allow any buckets (no extra verifications performed).
  ALLOW_ANY
};

#if BUILDFLAG(IS_WIN)
std::wstring GetRegistryPathForTestProfile() {
  // Cleanup follow-up to http://crbug.com/721245 for the previous location of
  // this test key which had similar problems (to a lesser extent). It's
  // redundant but harmless to have multiple callers hit this on the same
  // machine. TODO(gab): remove this mid-june 2017.
  base::win::RegKey key;
  if (key.Open(HKEY_CURRENT_USER, L"SOFTWARE\\Chromium\\PrefHashBrowserTest",
               KEY_SET_VALUE | KEY_WOW64_32KEY) == ERROR_SUCCESS) {
    LONG result = key.DeleteKey(L"");
    EXPECT_TRUE(result == ERROR_SUCCESS || result == ERROR_FILE_NOT_FOUND);
  }

  base::FilePath profile_dir;
  EXPECT_TRUE(base::PathService::Get(chrome::DIR_USER_DATA, &profile_dir));

  // |DIR_USER_DATA| usually has format %TMP%\12345_6789012345\user_data
  // (unless running with --single-process-tests, where the format is
  // %TMP%\scoped_dir12345_6789012345). Use the parent directory name instead of
  // the leaf directory name "user_data" to avoid conflicts in parallel tests,
  // which would try to modify the same registry key otherwise.
  if (profile_dir.BaseName().value() == L"user_data") {
    profile_dir = profile_dir.DirName();
  }
  // Try to detect regressions when |DIR_USER_DATA| test location changes, which
  // could cause this test to become flaky. See http://crbug/1091409 for more
  // details.
  DCHECK(profile_dir.BaseName().value().find_first_of(L"0123456789") !=
         std::string::npos);

  // Use a location under the real PreferenceMACs path so that the backup
  // cleanup logic in ChromeTestLauncherDelegate::PreSharding() for interrupted
  // tests covers this test key as well.
  return install_static::GetRegistryPath() +
         L"\\PreferenceMACs\\PrefHashBrowserTest\\" +
         profile_dir.BaseName().value();
}
#endif

// Returns the number of times |histogram_name| was reported so far; adding the
// results of the first 100 buckets (there are only ~19 reporting IDs as of this
// writing; varies depending on the platform). |allowed_buckets| hints at extra
// requirements verified in this method (see AllowedBuckets for details).
int GetTrackedPrefHistogramCount(const char* histogram_name,
                                 const char* histogram_suffix,
                                 int allowed_buckets) {
  std::string full_histogram_name(histogram_name);
  if (*histogram_suffix)
    full_histogram_name.append(".").append(histogram_suffix);
  const base::HistogramBase* histogram =
      base::StatisticsRecorder::FindHistogram(full_histogram_name);
  if (!histogram)
    return 0;

  std::unique_ptr<base::HistogramSamples> samples(histogram->SnapshotSamples());
  int sum = 0;
  for (int i = 0; i < 100; ++i) {
    int count_for_id = samples->GetCount(i);
    EXPECT_GE(count_for_id, 0);
    sum += count_for_id;

    if (allowed_buckets == ALLOW_NONE ||
        (allowed_buckets != ALLOW_ANY && i != allowed_buckets)) {
      EXPECT_EQ(0, count_for_id) << "Unexpected reporting_id: " << i;
    }
  }
  return sum;
}

// Helper function to call GetTrackedPrefHistogramCount with no external
// validation suffix.
int GetTrackedPrefHistogramCount(const char* histogram_name,
                                 int allowed_buckets) {
  return GetTrackedPrefHistogramCount(histogram_name, "", allowed_buckets);
}

#if !BUILDFLAG(IS_CHROMEOS)
// Helper function to get the test profile directory path.
base::FilePath GetProfileDir() {
  base::FilePath profile_dir;
  CHECK(base::PathService::Get(chrome::DIR_USER_DATA, &profile_dir));
  return profile_dir.AppendASCII(TestingProfile::kTestUserProfileDir);
}

std::optional<base::Value::Dict> ReadPrefsDictionary(
    const base::FilePath& pref_file) {
  JSONFileValueDeserializer deserializer(pref_file);
  int error_code = JSONFileValueDeserializer::JSON_NO_ERROR;
  std::string error_str;
  std::unique_ptr<base::Value> prefs =
      deserializer.Deserialize(&error_code, &error_str);
  if (!prefs || error_code != JSONFileValueDeserializer::JSON_NO_ERROR) {
    ADD_FAILURE() << "Error #" << error_code << ": " << error_str;
    return std::nullopt;
  }
  if (!prefs->is_dict()) {
    ADD_FAILURE();
    return std::nullopt;
  }
  return std::move(*prefs).TakeDict();
}
#endif

// Returns whether external validation is supported on the platform through
// storing MACs in the registry.
bool SupportsRegistryValidation() {
#if BUILDFLAG(IS_WIN)
  return true;
#else
  return false;
#endif
}

#define PREF_HASH_BROWSER_TEST(fixture, test_name)                             \
  IN_PROC_BROWSER_TEST_F(fixture, PRE_##test_name) { SetupPreferences(); }     \
  IN_PROC_BROWSER_TEST_F(fixture, test_name) { VerifyReactionToPrefAttack(); } \
  static_assert(true, "")

// A base fixture designed such that implementations do two things:
//  1) Override all three pure-virtual methods below to setup, attack, and
//     verify preferences throughout the tests provided by this fixture.
//  2) Instantiate their test via the PREF_HASH_BROWSER_TEST macro above.
// Based on top of ExtensionBrowserTest to allow easy interaction with the
// ExtensionRegistry.
class PrefHashBrowserTestBase : public extensions::ExtensionBrowserTest {
 public:
  // List of potential protection levels for this test in strict increasing
  // order of protection levels.
  enum SettingsProtectionLevel {
    PROTECTION_DISABLED_ON_PLATFORM,
    PROTECTION_DISABLED_FOR_GROUP,
    PROTECTION_ENABLED_BASIC,
    PROTECTION_ENABLED_DSE,
    PROTECTION_ENABLED_EXTENSIONS,
    // Represents the strongest level (i.e. always equivalent to the last one in
    // terms of protection), leave this one last when adding new levels.
    PROTECTION_ENABLED_ALL
  };

  PrefHashBrowserTestBase() : protection_level_(GetProtectionLevel()) {}

  void SetUpCommandLine(base::CommandLine* command_line) override {
    extensions::ExtensionBrowserTest::SetUpCommandLine(command_line);
#if BUILDFLAG(IS_CHROMEOS)
    command_line->AppendSwitch(
        ash::switches::kIgnoreUserProfileMappingForTests);
#endif
  }

  bool SetUpUserDataDirectory() override {
    // Do the normal setup in the PRE test and attack preferences in the main
    // test.
    if (content::IsPreTest())
      return extensions::ExtensionBrowserTest::SetUpUserDataDirectory();

#if BUILDFLAG(IS_CHROMEOS)
    // For some reason, the Preferences file does not exist in the location
    // below on Chrome OS. Since protection is disabled on Chrome OS, it's okay
    // to simply not attack preferences at all (and still assert that no
    // hardening related histogram kicked in in VerifyReactionToPrefAttack()).
    // TODO(gab): Figure out why there is no Preferences file in this location
    // on Chrome OS (and re-enable the section disabled for OS_CHROMEOS further
    // below).
    EXPECT_EQ(PROTECTION_DISABLED_ON_PLATFORM, protection_level_);
    return true;
#else
    base::FilePath profile_dir;
    EXPECT_TRUE(base::PathService::Get(chrome::DIR_USER_DATA, &profile_dir));
    profile_dir = profile_dir.AppendASCII(TestingProfile::kTestUserProfileDir);

    // Sanity check that old protected pref file is never present in modern
    // Chromes.
    EXPECT_FALSE(base::PathExists(
        profile_dir.Append(FILE_PATH_LITERAL("Protected Preferences"))));

    // Read the preferences from disk.

    const base::FilePath unprotected_pref_file =
        profile_dir.Append(chrome::kPreferencesFilename);
    EXPECT_TRUE(base::PathExists(unprotected_pref_file));

    const base::FilePath protected_pref_file =
        profile_dir.Append(chrome::kSecurePreferencesFilename);
    EXPECT_EQ(protection_level_ > PROTECTION_DISABLED_ON_PLATFORM,
              base::PathExists(protected_pref_file));

    std::optional<base::Value::Dict> unprotected_preferences(
        ReadPrefsDictionary(unprotected_pref_file));
    if (!unprotected_preferences)
      return false;

    std::optional<base::Value::Dict> protected_preferences;
    if (protection_level_ > PROTECTION_DISABLED_ON_PLATFORM) {
      protected_preferences = ReadPrefsDictionary(protected_pref_file);
      if (!protected_preferences)
        return false;
    }

    // Let the underlying test modify the preferences.
    AttackPreferencesOnDisk(
        &unprotected_preferences.value(),
        protected_preferences ? &protected_preferences.value() : nullptr);

    // Write the modified preferences back to disk.
    JSONFileValueSerializer unprotected_prefs_serializer(unprotected_pref_file);
    EXPECT_TRUE(
        unprotected_prefs_serializer.Serialize(*unprotected_preferences));

    if (protected_preferences) {
      JSONFileValueSerializer protected_prefs_serializer(protected_pref_file);
      EXPECT_TRUE(protected_prefs_serializer.Serialize(*protected_preferences));
    }

    return true;
#endif
  }

  void SetUpInProcessBrowserTestFixture() override {
    extensions::ExtensionBrowserTest::SetUpInProcessBrowserTestFixture();

    // Bots are on a domain, turn off the domain check for settings hardening in
    // order to be able to test all SettingsEnforcement groups.
    chrome_prefs::DisableDomainCheckForTesting();

#if BUILDFLAG(IS_WIN)
    // Avoid polluting prefs for the user and the bots by writing to a specific
    // testing registry path.
    registry_key_for_external_validation_ = GetRegistryPathForTestProfile();
    ProfilePrefStoreManager::SetPreferenceValidationRegistryPathForTesting(
        &registry_key_for_external_validation_);

    // Keys should be unique, but to avoid flakes in the long run make sure an
    // identical test key wasn't left behind by a previous test.
    if (content::IsPreTest()) {
      base::win::RegKey key;
      if (key.Open(HKEY_CURRENT_USER,
                   registry_key_for_external_validation_.c_str(),
                   KEY_SET_VALUE | KEY_WOW64_32KEY) == ERROR_SUCCESS) {
        LONG result = key.DeleteKey(L"");
        ASSERT_TRUE(result == ERROR_SUCCESS || result == ERROR_FILE_NOT_FOUND);
      }
    }
#endif
  }

  void TearDown() override {
#if BUILDFLAG(IS_WIN)
    // When done, delete the Registry key to avoid polluting the registry.
    if (!content::IsPreTest()) {
      std::wstring registry_key = GetRegistryPathForTestProfile();
      base::win::RegKey key;
      if (key.Open(HKEY_CURRENT_USER, registry_key.c_str(),
                   KEY_SET_VALUE | KEY_WOW64_32KEY) == ERROR_SUCCESS) {
        LONG result = key.DeleteKey(L"");
        ASSERT_TRUE(result == ERROR_SUCCESS || result == ERROR_FILE_NOT_FOUND);
      }
    }
#endif
    extensions::ExtensionBrowserTest::TearDown();
  }

  void TearDownOnMainThread() override {
    // In the PRE_ test, we must ensure all asynchronous
    // work is flushed before the test exits, guaranteeing the pref files on
    // disk are in a stable state for the main test to read.
    if (content::IsPreTest()) {
      // First, allow any pending asynchronous tasks (like our deferred
      // validation) to complete.
      base::RunLoop().RunUntilIdle();
      // Then, commit any writes that were scheduled by those tasks.
      base::RunLoop run_loop;
      profile()->GetPrefs()->CommitPendingWrite(run_loop.QuitClosure());
      run_loop.Run();
    }
    extensions::ExtensionBrowserTest::TearDownOnMainThread();
  }

  // In the PRE_ test, find the number of tracked preferences that were
  // initialized and save it to a file to be read back in the main test and used
  // as the total number of tracked preferences.
  void SetUpOnMainThread() override {
    extensions::ExtensionBrowserTest::SetUpOnMainThread();

    // File in which the PRE_ test will save the number of tracked preferences
    // on this platform.
    const char kNumTrackedPrefFilename[] = "NumTrackedPrefs";

    base::FilePath num_tracked_prefs_file;
    ASSERT_TRUE(
        base::PathService::Get(chrome::DIR_USER_DATA, &num_tracked_prefs_file));
    num_tracked_prefs_file =
        num_tracked_prefs_file.AppendASCII(kNumTrackedPrefFilename);

    if (content::IsPreTest()) {
      num_tracked_prefs_ = GetTrackedPrefHistogramCount(
          user_prefs::tracked::kTrackedPrefHistogramNullInitialized, ALLOW_ANY);
      EXPECT_EQ(protection_level_ > PROTECTION_DISABLED_ON_PLATFORM,
                num_tracked_prefs_ > 0);
      // Split tracked prefs are reported as Unchanged not as NullInitialized
      // when an empty dictionary is encountered on first run (this should only
      // hit for pref #5 in the current design).
      int num_split_tracked_prefs = GetTrackedPrefHistogramCount(
          user_prefs::tracked::kTrackedPrefHistogramUnchanged,
          BEGIN_ALLOW_SINGLE_BUCKET + 5);
      EXPECT_EQ(protection_level_ > PROTECTION_DISABLED_ON_PLATFORM ? 1 : 0,
                num_split_tracked_prefs);
      if (SupportsRegistryValidation()) {
        // Same checks as above, but for the registry.
        num_tracked_prefs_ = GetTrackedPrefHistogramCount(
            user_prefs::tracked::kTrackedPrefHistogramNullInitialized,
            user_prefs::tracked::kTrackedPrefRegistryValidationSuffix,
            ALLOW_ANY);
        EXPECT_EQ(protection_level_ > PROTECTION_DISABLED_ON_PLATFORM,
                  num_tracked_prefs_ > 0);

        int split_tracked_prefs = GetTrackedPrefHistogramCount(
            user_prefs::tracked::kTrackedPrefHistogramUnchanged,
            user_prefs::tracked::kTrackedPrefRegistryValidationSuffix,
            BEGIN_ALLOW_SINGLE_BUCKET + 5);
        EXPECT_EQ(protection_level_ > PROTECTION_DISABLED_ON_PLATFORM ? 1 : 0,
                  split_tracked_prefs);
      }

      num_tracked_prefs_ += num_split_tracked_prefs;

      std::string num_tracked_prefs_str =
          base::NumberToString(num_tracked_prefs_);
      EXPECT_TRUE(
          base::WriteFile(num_tracked_prefs_file, num_tracked_prefs_str));
    } else {
      std::string num_tracked_prefs_str;
      EXPECT_TRUE(base::ReadFileToString(num_tracked_prefs_file,
                                         &num_tracked_prefs_str));
      EXPECT_TRUE(
          base::StringToInt(num_tracked_prefs_str, &num_tracked_prefs_));
    }
  }

 protected:
  // Called from the PRE_ test's body. Overrides should use it to setup
  // preferences through Chrome.
  virtual void SetupPreferences() = 0;

  // Called prior to the main test launching its browser. Overrides should use
  // it to attack preferences. |(un)protected_preferences| represent the state
  // on disk prior to launching the main test, they can be modified by this
  // method and modifications will be flushed back to disk before launching the
  // main test. |unprotected_preferences| is never NULL, |protected_preferences|
  // may be NULL if in PROTECTION_DISABLED_ON_PLATFORM mode.
  virtual void AttackPreferencesOnDisk(
      base::Value::Dict* unprotected_preferences,
      base::Value::Dict* protected_preferences) = 0;

  // Called from the body of the main test. Overrides should use it to verify
  // that the browser had the desired reaction when faced when the attack
  // orchestrated in AttackPreferencesOnDisk().
  virtual void VerifyReactionToPrefAttack() = 0;

  int num_tracked_prefs() const { return num_tracked_prefs_; }

  const SettingsProtectionLevel protection_level_;

  base::HistogramTester histograms_;

 private:
  SettingsProtectionLevel GetProtectionLevel() {
    if (!ProfilePrefStoreManager::kPlatformSupportsPreferenceTracking)
      return PROTECTION_DISABLED_ON_PLATFORM;

#if BUILDFLAG(IS_WIN) || BUILDFLAG(IS_MAC)
    // The strongest mode is enforced on Windows and MacOS in the absence of a
    // field trial.
    return PROTECTION_ENABLED_ALL;
#else
    return PROTECTION_DISABLED_FOR_GROUP;
#endif  // BUILDFLAG(IS_WIN) || BUILDFLAG(IS_MAC)
  }

  int num_tracked_prefs_;

#if BUILDFLAG(IS_WIN)
  std::wstring registry_key_for_external_validation_;
#endif
};

}  // namespace

// Verifies that nothing is reset when nothing is tampered with.
// Also sanity checks that the expected preferences files are in place.
class PrefHashBrowserTestUnchangedDefault : public PrefHashBrowserTestBase {
 public:
  void SetupPreferences() override {
    // Default Chrome setup.
  }

  void AttackPreferencesOnDisk(
      base::Value::Dict* unprotected_preferences,
      base::Value::Dict* protected_preferences) override {
    // No attack.
  }

  void VerifyReactionToPrefAttack() override {
    // Expect all prefs to be reported as Unchanged with no resets.
    EXPECT_EQ(
        protection_level_ > PROTECTION_DISABLED_ON_PLATFORM
            ? num_tracked_prefs()
            : 0,
        GetTrackedPrefHistogramCount(
            user_prefs::tracked::kTrackedPrefHistogramUnchanged, ALLOW_ANY));
    EXPECT_EQ(0, GetTrackedPrefHistogramCount(
                     user_prefs::tracked::kTrackedPrefHistogramWantedReset,
                     ALLOW_NONE));
    EXPECT_EQ(0,
              GetTrackedPrefHistogramCount(
                  user_prefs::tracked::kTrackedPrefHistogramReset, ALLOW_NONE));

    // Nothing else should have triggered.
    EXPECT_EQ(
        0, GetTrackedPrefHistogramCount(
               user_prefs::tracked::kTrackedPrefHistogramChanged, ALLOW_NONE));
    EXPECT_EQ(
        0, GetTrackedPrefHistogramCount(
               user_prefs::tracked::kTrackedPrefHistogramCleared, ALLOW_NONE));
    EXPECT_EQ(0, GetTrackedPrefHistogramCount(
                     user_prefs::tracked::kTrackedPrefHistogramInitialized,
                     ALLOW_NONE));
    EXPECT_EQ(0,
              GetTrackedPrefHistogramCount(
                  user_prefs::tracked::kTrackedPrefHistogramTrustedInitialized,
                  ALLOW_NONE));
    EXPECT_EQ(0, GetTrackedPrefHistogramCount(
                     user_prefs::tracked::kTrackedPrefHistogramNullInitialized,
                     ALLOW_NONE));

    histograms_.ExpectUniqueSample(
        DefaultSearchManager::kDefaultSearchEngineMirroredMetric, true,
#if BUILDFLAG(IS_CHROMEOS)
        2);  // CHROMEOS doesn't support Preference tracking.
#else
        1);
#endif  // BUILDFLAG(IS_CHROMEOS)

    if (SupportsRegistryValidation()) {
      // Expect all prefs to be reported as Unchanged.
      EXPECT_EQ(protection_level_ > PROTECTION_DISABLED_ON_PLATFORM
                    ? num_tracked_prefs()
                    : 0,
                GetTrackedPrefHistogramCount(
                    user_prefs::tracked::kTrackedPrefHistogramUnchanged,
                    user_prefs::tracked::kTrackedPrefRegistryValidationSuffix,
                    ALLOW_ANY));
    }
  }
};

PREF_HASH_BROWSER_TEST(PrefHashBrowserTestUnchangedDefault, UnchangedDefault);

// Augments PrefHashBrowserTestUnchangedDefault to confirm that nothing is reset
// when nothing is tampered with, even if Chrome itself wrote custom prefs in
// its last run.
class PrefHashBrowserTestUnchangedCustom
    : public PrefHashBrowserTestUnchangedDefault {
 public:
  void SetupPreferences() override {
    profile()->GetPrefs()->SetString(prefs::kHomePage, "http://example.com");

    InstallExtensionWithUIAutoConfirm(test_data_dir_.AppendASCII("good.crx"),
                                      1);
  }

  void VerifyReactionToPrefAttack() override {
    // Make sure the settings written in the last run stuck.
    EXPECT_EQ("http://example.com",
              profile()->GetPrefs()->GetString(prefs::kHomePage));

    EXPECT_TRUE(extension_registry()->enabled_extensions().GetByID(kGoodCrxId));

    // Reaction should be identical to unattacked default prefs.
    PrefHashBrowserTestUnchangedDefault::VerifyReactionToPrefAttack();
  }
};

PREF_HASH_BROWSER_TEST(PrefHashBrowserTestUnchangedCustom, UnchangedCustom);

// Verifies that cleared prefs are reported.
class PrefHashBrowserTestClearedAtomic : public PrefHashBrowserTestBase {
 public:
  void SetupPreferences() override {
    profile()->GetPrefs()->SetString(prefs::kHomePage, "http://example.com");
  }

  void AttackPreferencesOnDisk(
      base::Value::Dict* unprotected_preferences,
      base::Value::Dict* protected_preferences) override {
    base::Value::Dict* selected_prefs =
        protection_level_ >= PROTECTION_ENABLED_BASIC ? protected_preferences
                                                      : unprotected_preferences;
    // |selected_prefs| should never be NULL under the protection level picking
    // it.
    EXPECT_TRUE(selected_prefs);
    EXPECT_TRUE(selected_prefs->Remove(prefs::kHomePage));
  }

  void VerifyReactionToPrefAttack() override {
    // The clearance of homepage should have been noticed (as pref #2 being
    // cleared), but shouldn't have triggered a reset (as there is nothing we
    // can do when the pref is already gone).
    EXPECT_EQ(protection_level_ > PROTECTION_DISABLED_ON_PLATFORM ? 1 : 0,
              GetTrackedPrefHistogramCount(
                  user_prefs::tracked::kTrackedPrefHistogramCleared,
                  BEGIN_ALLOW_SINGLE_BUCKET + 2));
    EXPECT_EQ(
        protection_level_ > PROTECTION_DISABLED_ON_PLATFORM
            ? num_tracked_prefs() - 1
            : 0,
        GetTrackedPrefHistogramCount(
            user_prefs::tracked::kTrackedPrefHistogramUnchanged, ALLOW_ANY));
    EXPECT_EQ(0, GetTrackedPrefHistogramCount(
                     user_prefs::tracked::kTrackedPrefHistogramWantedReset,
                     ALLOW_NONE));
    EXPECT_EQ(0,
              GetTrackedPrefHistogramCount(
                  user_prefs::tracked::kTrackedPrefHistogramReset, ALLOW_NONE));

    // Nothing else should have triggered.
    EXPECT_EQ(
        0, GetTrackedPrefHistogramCount(
               user_prefs::tracked::kTrackedPrefHistogramChanged, ALLOW_NONE));
    EXPECT_EQ(0, GetTrackedPrefHistogramCount(
                     user_prefs::tracked::kTrackedPrefHistogramInitialized,
                     ALLOW_NONE));
    EXPECT_EQ(0,
              GetTrackedPrefHistogramCount(
                  user_prefs::tracked::kTrackedPrefHistogramTrustedInitialized,
                  ALLOW_NONE));
    EXPECT_EQ(0, GetTrackedPrefHistogramCount(
                     user_prefs::tracked::kTrackedPrefHistogramNullInitialized,
                     ALLOW_NONE));

    if (SupportsRegistryValidation()) {
      // Expect homepage clearance to have been noticed by registry validation.
      EXPECT_EQ(protection_level_ > PROTECTION_DISABLED_ON_PLATFORM ? 1 : 0,
                GetTrackedPrefHistogramCount(
                    user_prefs::tracked::kTrackedPrefHistogramCleared,
                    user_prefs::tracked::kTrackedPrefRegistryValidationSuffix,
                    BEGIN_ALLOW_SINGLE_BUCKET + 2));
    }
  }
};

PREF_HASH_BROWSER_TEST(PrefHashBrowserTestClearedAtomic, ClearedAtomic);

// Verifies that clearing the MACs results in untrusted Initialized pings for
// non-null protected prefs.
class PrefHashBrowserTestUntrustedInitialized : public PrefHashBrowserTestBase {
 public:
  void SetupPreferences() override {
    // Explicitly set the DSE (it's otherwise NULL by default, preventing
    // thorough testing of the PROTECTION_ENABLED_DSE level).
    DefaultSearchManager default_search_manager(
        profile()->GetPrefs(),
        search_engines::SearchEngineChoiceServiceFactory::GetForProfile(
            profile()),
        CHECK_DEREF(TemplateURLPrepopulateData::ResolverFactory::GetForProfile(
            profile())),
        DefaultSearchManager::ObserverCallback());
    DefaultSearchManager::Source dse_source =
        static_cast<DefaultSearchManager::Source>(-1);

    const TemplateURLData* default_template_url_data =
        default_search_manager.GetDefaultSearchEngine(&dse_source);
    EXPECT_EQ(DefaultSearchManager::FROM_FALLBACK, dse_source);

    default_search_manager.SetUserSelectedDefaultSearchEngine(
        *default_template_url_data);

    default_search_manager.GetDefaultSearchEngine(&dse_source);
    EXPECT_EQ(DefaultSearchManager::FROM_USER, dse_source);

    // Also explicitly set an atomic pref that falls under
    // PROTECTION_ENABLED_BASIC.
    profile()->GetPrefs()->SetInteger(prefs::kRestoreOnStartup,
                                      SessionStartupPref::URLS);
  }

  void AttackPreferencesOnDisk(
      base::Value::Dict* unprotected_preferences,
      base::Value::Dict* protected_preferences) override {
    unprotected_preferences->RemoveByDottedPath("protection.macs");
    if (protected_preferences)
      protected_preferences->RemoveByDottedPath("protection.macs");
  }

  void VerifyReactionToPrefAttack() override {
    // Preferences that are NULL by default will be NullInitialized.
    int num_null_values = GetTrackedPrefHistogramCount(
        user_prefs::tracked::kTrackedPrefHistogramNullInitialized, ALLOW_ANY);
    EXPECT_EQ(protection_level_ > PROTECTION_DISABLED_ON_PLATFORM,
              num_null_values > 0);
    if (num_null_values > 0) {
      // This test requires that at least 3 prefs be non-null (extensions, DSE,
      // and 1 atomic pref explictly set for this test above).
      EXPECT_GE(num_tracked_prefs() - num_null_values, 3);
    }

    // Expect all non-null prefs to be reported as Initialized (with
    // accompanying resets or wanted resets based on the current protection
    // level).
    EXPECT_EQ(
        num_tracked_prefs() - num_null_values,
        GetTrackedPrefHistogramCount(
            user_prefs::tracked::kTrackedPrefHistogramInitialized, ALLOW_ANY));

    int num_protected_prefs = 0;
    // A switch statement falling through each protection level in decreasing
    // levels of protection to add expectations for each level which augments
    // the previous one.
    switch (protection_level_) {
      case PROTECTION_ENABLED_ALL:
      case PROTECTION_ENABLED_EXTENSIONS:
        ++num_protected_prefs;
        [[fallthrough]];
      case PROTECTION_ENABLED_DSE:
        ++num_protected_prefs;
        [[fallthrough]];
      case PROTECTION_ENABLED_BASIC:
        num_protected_prefs += num_tracked_prefs() - num_null_values - 2;
        [[fallthrough]];
      case PROTECTION_DISABLED_FOR_GROUP:
      case PROTECTION_DISABLED_ON_PLATFORM:
        // No protection.
        break;
    }

    EXPECT_EQ(
        num_tracked_prefs() - num_null_values - num_protected_prefs,
        GetTrackedPrefHistogramCount(
            user_prefs::tracked::kTrackedPrefHistogramWantedReset, ALLOW_ANY));
    EXPECT_EQ(num_protected_prefs,
              GetTrackedPrefHistogramCount(
                  user_prefs::tracked::kTrackedPrefHistogramReset, ALLOW_ANY));

    // Explicitly verify the result of reported resets.

    DefaultSearchManager default_search_manager(
        profile()->GetPrefs(),
        search_engines::SearchEngineChoiceServiceFactory::GetForProfile(
            profile()),
        CHECK_DEREF(TemplateURLPrepopulateData::ResolverFactory::GetForProfile(
            profile())),
        DefaultSearchManager::ObserverCallback());
    DefaultSearchManager::Source dse_source =
        static_cast<DefaultSearchManager::Source>(-1);
    default_search_manager.GetDefaultSearchEngine(&dse_source);
    EXPECT_EQ(protection_level_ < PROTECTION_ENABLED_DSE
                  ? DefaultSearchManager::FROM_USER
                  : DefaultSearchManager::FROM_FALLBACK,
              dse_source);

    EXPECT_EQ(protection_level_ < PROTECTION_ENABLED_BASIC,
              profile()->GetPrefs()->GetInteger(prefs::kRestoreOnStartup) ==
                  SessionStartupPref::URLS);

    // Nothing else should have triggered.
    EXPECT_EQ(0, GetTrackedPrefHistogramCount(
                     user_prefs::tracked::kTrackedPrefHistogramUnchanged,
                     ALLOW_NONE));
    EXPECT_EQ(
        0, GetTrackedPrefHistogramCount(
               user_prefs::tracked::kTrackedPrefHistogramChanged, ALLOW_NONE));
    EXPECT_EQ(
        0, GetTrackedPrefHistogramCount(
               user_prefs::tracked::kTrackedPrefHistogramCleared, ALLOW_NONE));

    if (SupportsRegistryValidation()) {
      // The MACs have been cleared but the preferences have not been tampered.
      // The registry should report all prefs as unchanged.
      EXPECT_EQ(protection_level_ > PROTECTION_DISABLED_ON_PLATFORM
                    ? num_tracked_prefs()
                    : 0,
                GetTrackedPrefHistogramCount(
                    user_prefs::tracked::kTrackedPrefHistogramUnchanged,
                    user_prefs::tracked::kTrackedPrefRegistryValidationSuffix,
                    ALLOW_ANY));
    }
  }
};

PREF_HASH_BROWSER_TEST(PrefHashBrowserTestUntrustedInitialized,
                       UntrustedInitialized);

// Verifies that changing an atomic pref results in it being reported (and reset
// if the protection level allows it).
class PrefHashBrowserTestChangedAtomic : public PrefHashBrowserTestBase {
 public:
  void SetupPreferences() override {
    profile()->GetPrefs()->SetInteger(prefs::kRestoreOnStartup,
                                      SessionStartupPref::URLS);

    ScopedListPrefUpdate update(profile()->GetPrefs(),
                                prefs::kURLsToRestoreOnStartup);
    update->Append("http://example.com");
  }

  void AttackPreferencesOnDisk(
      base::Value::Dict* unprotected_preferences,
      base::Value::Dict* protected_preferences) override {
    base::Value::Dict* selected_prefs =
        protection_level_ >= PROTECTION_ENABLED_BASIC ? protected_preferences
                                                      : unprotected_preferences;
    // `selected_prefs` should never be NULL under the protection level picking
    // it.
    ASSERT_TRUE(selected_prefs);
    base::Value::List* startup_urls =
        selected_prefs->FindListByDottedPath(prefs::kURLsToRestoreOnStartup);
    ASSERT_TRUE(startup_urls);
    EXPECT_EQ(1U, startup_urls->size());
    startup_urls->Append("http://example.org");
  }

  void VerifyReactionToPrefAttack() override {
    // Expect a single Changed event for tracked pref #4 (startup URLs).
    EXPECT_EQ(protection_level_ > PROTECTION_DISABLED_ON_PLATFORM ? 1 : 0,
              GetTrackedPrefHistogramCount(
                  user_prefs::tracked::kTrackedPrefHistogramChanged,
                  BEGIN_ALLOW_SINGLE_BUCKET + 4));
    EXPECT_EQ(
        protection_level_ > PROTECTION_DISABLED_ON_PLATFORM
            ? num_tracked_prefs() - 1
            : 0,
        GetTrackedPrefHistogramCount(
            user_prefs::tracked::kTrackedPrefHistogramUnchanged, ALLOW_ANY));

    EXPECT_EQ((protection_level_ > PROTECTION_DISABLED_ON_PLATFORM &&
               protection_level_ < PROTECTION_ENABLED_BASIC)
                  ? 1
                  : 0,
              GetTrackedPrefHistogramCount(
                  user_prefs::tracked::kTrackedPrefHistogramWantedReset,
                  BEGIN_ALLOW_SINGLE_BUCKET + 4));
    EXPECT_EQ(protection_level_ >= PROTECTION_ENABLED_BASIC ? 1 : 0,
              GetTrackedPrefHistogramCount(
                  user_prefs::tracked::kTrackedPrefHistogramReset,
                  BEGIN_ALLOW_SINGLE_BUCKET + 4));

// TODO(gab): This doesn't work on OS_CHROMEOS because we fail to attack
// Preferences.
#if !BUILDFLAG(IS_CHROMEOS)
    // Explicitly verify the result of reported resets.
    EXPECT_EQ(
        protection_level_ >= PROTECTION_ENABLED_BASIC ? 0U : 2U,
        profile()->GetPrefs()->GetList(prefs::kURLsToRestoreOnStartup).size());
#endif

    // Nothing else should have triggered.
    EXPECT_EQ(
        0, GetTrackedPrefHistogramCount(
               user_prefs::tracked::kTrackedPrefHistogramCleared, ALLOW_NONE));
    EXPECT_EQ(0, GetTrackedPrefHistogramCount(
                     user_prefs::tracked::kTrackedPrefHistogramInitialized,
                     ALLOW_NONE));
    EXPECT_EQ(0,
              GetTrackedPrefHistogramCount(
                  user_prefs::tracked::kTrackedPrefHistogramTrustedInitialized,
                  ALLOW_NONE));
    EXPECT_EQ(0, GetTrackedPrefHistogramCount(
                     user_prefs::tracked::kTrackedPrefHistogramNullInitialized,
                     ALLOW_NONE));

    if (SupportsRegistryValidation()) {
      // Expect a single Changed event for tracked pref #4 (startup URLs).
      EXPECT_EQ(protection_level_ > PROTECTION_DISABLED_ON_PLATFORM ? 1 : 0,
                GetTrackedPrefHistogramCount(
                    user_prefs::tracked::kTrackedPrefHistogramChanged,
                    user_prefs::tracked::kTrackedPrefRegistryValidationSuffix,
                    BEGIN_ALLOW_SINGLE_BUCKET + 4));
    }
  }
};

PREF_HASH_BROWSER_TEST(PrefHashBrowserTestChangedAtomic, ChangedAtomic);

// Verifies that changing or adding an entry in a split pref results in both
// items being reported (and remove if the protection level allows it).
class PrefHashBrowserTestChangedSplitPref : public PrefHashBrowserTestBase {
 public:
  void SetupPreferences() override {
    InstallExtensionWithUIAutoConfirm(test_data_dir_.AppendASCII("good.crx"),
                                      1);
  }

  void AttackPreferencesOnDisk(
      base::Value::Dict* unprotected_preferences,
      base::Value::Dict* protected_preferences) override {
    base::Value::Dict* selected_prefs =
        protection_level_ >= PROTECTION_ENABLED_EXTENSIONS
            ? protected_preferences
            : unprotected_preferences;
    // |selected_prefs| should never be NULL under the protection level picking
    // it.
    EXPECT_TRUE(selected_prefs);
    base::Value::Dict* extensions_dict = selected_prefs->FindDictByDottedPath(
        extensions::pref_names::kExtensions);
    EXPECT_TRUE(extensions_dict);

    // Tamper with any installed setting for good.crx
    base::Value::Dict* good_crx_dict = extensions_dict->FindDict(kGoodCrxId);
    ASSERT_TRUE(good_crx_dict);

    std::optional<int> good_crx_incognito_access =
        good_crx_dict->FindBool("incognito");
    ASSERT_FALSE(good_crx_incognito_access.has_value());
    good_crx_dict->Set("incognito", true);

    // Drop a fake extension (for the purpose of this test, dropped settings
    // don't need to be valid extension settings).
    base::Value::Dict fake_extension;
    fake_extension.Set("name", "foo");
    extensions_dict->Set(std::string(32, 'a'), std::move(fake_extension));
  }

  void VerifyReactionToPrefAttack() override {
    EXPECT_EQ(protection_level_ > PROTECTION_DISABLED_ON_PLATFORM ? 1 : 0,
              GetTrackedPrefHistogramCount(
                  user_prefs::tracked::kTrackedPrefHistogramChanged,
                  BEGIN_ALLOW_SINGLE_BUCKET + 5));

    // Everything else should have remained unchanged.
    EXPECT_EQ(
        protection_level_ > PROTECTION_DISABLED_ON_PLATFORM
            ? num_tracked_prefs() - 1
            : 0,
        GetTrackedPrefHistogramCount(
            user_prefs::tracked::kTrackedPrefHistogramUnchanged, ALLOW_ANY));

    EXPECT_EQ((protection_level_ > PROTECTION_DISABLED_ON_PLATFORM &&
               protection_level_ < PROTECTION_ENABLED_EXTENSIONS)
                  ? 1
                  : 0,
              GetTrackedPrefHistogramCount(
                  user_prefs::tracked::kTrackedPrefHistogramWantedReset,
                  BEGIN_ALLOW_SINGLE_BUCKET + 5));
    EXPECT_EQ(protection_level_ >= PROTECTION_ENABLED_EXTENSIONS ? 1 : 0,
              GetTrackedPrefHistogramCount(
                  user_prefs::tracked::kTrackedPrefHistogramReset,
                  BEGIN_ALLOW_SINGLE_BUCKET + 5));

    EXPECT_EQ(
        protection_level_ < PROTECTION_ENABLED_EXTENSIONS,
        extension_registry()->GetExtensionById(
            kGoodCrxId, extensions::ExtensionRegistry::EVERYTHING) != nullptr);

    // Nothing else should have triggered.
    EXPECT_EQ(
        0, GetTrackedPrefHistogramCount(
               user_prefs::tracked::kTrackedPrefHistogramCleared, ALLOW_NONE));
    EXPECT_EQ(0, GetTrackedPrefHistogramCount(
                     user_prefs::tracked::kTrackedPrefHistogramInitialized,
                     ALLOW_NONE));
    EXPECT_EQ(0,
              GetTrackedPrefHistogramCount(
                  user_prefs::tracked::kTrackedPrefHistogramTrustedInitialized,
                  ALLOW_NONE));
    EXPECT_EQ(0, GetTrackedPrefHistogramCount(
                     user_prefs::tracked::kTrackedPrefHistogramNullInitialized,
                     ALLOW_NONE));

    if (SupportsRegistryValidation()) {
      // Expect that the registry validation caught the invalid MAC in split
      // pref #5 (extensions).
      EXPECT_EQ(protection_level_ > PROTECTION_DISABLED_ON_PLATFORM ? 1 : 0,
                GetTrackedPrefHistogramCount(
                    user_prefs::tracked::kTrackedPrefHistogramChanged,
                    user_prefs::tracked::kTrackedPrefRegistryValidationSuffix,
                    BEGIN_ALLOW_SINGLE_BUCKET + 5));
    }
  }
};

PREF_HASH_BROWSER_TEST(PrefHashBrowserTestChangedSplitPref, ChangedSplitPref);

// Verifies that adding a value to unprotected preferences for a key which is
// still using the default (i.e. has no value stored in protected preferences)
// doesn't allow that value to slip in with no valid MAC (regression test for
// http://crbug.com/414554)
class PrefHashBrowserTestUntrustedAdditionToPrefs
    : public PrefHashBrowserTestBase {
 public:
  void SetupPreferences() override {
    // Ensure there is no user-selected value for kRestoreOnStartup.
    EXPECT_FALSE(
        profile()->GetPrefs()->GetUserPrefValue(prefs::kRestoreOnStartup));
  }

  void AttackPreferencesOnDisk(
      base::Value::Dict* unprotected_preferences,
      base::Value::Dict* protected_preferences) override {
    unprotected_preferences->SetByDottedPath(
        prefs::kRestoreOnStartup, static_cast<int>(SessionStartupPref::LAST));
  }

  void VerifyReactionToPrefAttack() override {
    // Expect a single Changed event for tracked pref #3 (kRestoreOnStartup) if
    // not protecting; if protection is enabled the change should be a no-op.
    int changed_expected =
        protection_level_ == PROTECTION_DISABLED_FOR_GROUP ? 1 : 0;
    EXPECT_EQ((protection_level_ > PROTECTION_DISABLED_ON_PLATFORM &&
               protection_level_ < PROTECTION_ENABLED_BASIC)
                  ? changed_expected
                  : 0,
              GetTrackedPrefHistogramCount(
                  user_prefs::tracked::kTrackedPrefHistogramChanged,
                  BEGIN_ALLOW_SINGLE_BUCKET + 3));
    EXPECT_EQ(
        protection_level_ > PROTECTION_DISABLED_ON_PLATFORM
            ? num_tracked_prefs() - changed_expected
            : 0,
        GetTrackedPrefHistogramCount(
            user_prefs::tracked::kTrackedPrefHistogramUnchanged, ALLOW_ANY));

    EXPECT_EQ((protection_level_ > PROTECTION_DISABLED_ON_PLATFORM &&
               protection_level_ < PROTECTION_ENABLED_BASIC)
                  ? 1
                  : 0,
              GetTrackedPrefHistogramCount(
                  user_prefs::tracked::kTrackedPrefHistogramWantedReset,
                  BEGIN_ALLOW_SINGLE_BUCKET + 3));
    EXPECT_EQ(0,
              GetTrackedPrefHistogramCount(
                  user_prefs::tracked::kTrackedPrefHistogramReset, ALLOW_NONE));

    // Nothing else should have triggered.
    EXPECT_EQ(
        0, GetTrackedPrefHistogramCount(
               user_prefs::tracked::kTrackedPrefHistogramCleared, ALLOW_NONE));
    EXPECT_EQ(0, GetTrackedPrefHistogramCount(
                     user_prefs::tracked::kTrackedPrefHistogramInitialized,
                     ALLOW_NONE));
    EXPECT_EQ(0,
              GetTrackedPrefHistogramCount(
                  user_prefs::tracked::kTrackedPrefHistogramTrustedInitialized,
                  ALLOW_NONE));
    EXPECT_EQ(0, GetTrackedPrefHistogramCount(
                     user_prefs::tracked::kTrackedPrefHistogramNullInitialized,
                     ALLOW_NONE));

    if (SupportsRegistryValidation()) {
      EXPECT_EQ((protection_level_ > PROTECTION_DISABLED_ON_PLATFORM &&
                 protection_level_ < PROTECTION_ENABLED_BASIC)
                    ? changed_expected
                    : 0,
                GetTrackedPrefHistogramCount(
                    user_prefs::tracked::kTrackedPrefHistogramChanged,
                    user_prefs::tracked::kTrackedPrefRegistryValidationSuffix,
                    BEGIN_ALLOW_SINGLE_BUCKET + 3));
    }
  }
};

PREF_HASH_BROWSER_TEST(PrefHashBrowserTestUntrustedAdditionToPrefs,
                       UntrustedAdditionToPrefs);

// Verifies that adding a value to unprotected preferences while wiping a
// user-selected value from protected preferences doesn't allow that value to
// slip in with no valid MAC (regression test for http://crbug.com/414554).
class PrefHashBrowserTestUntrustedAdditionToPrefsAfterWipe
    : public PrefHashBrowserTestBase {
 public:
  void SetupPreferences() override {
    profile()->GetPrefs()->SetString(prefs::kHomePage, "http://example.com");
  }

  void AttackPreferencesOnDisk(
      base::Value::Dict* unprotected_preferences,
      base::Value::Dict* protected_preferences) override {
    // Set or change the value in Preferences to the attacker's choice.
    unprotected_preferences->Set(prefs::kHomePage, "http://example.net");
    // Clear the value in Secure Preferences, if any.
    if (protected_preferences)
      protected_preferences->Remove(prefs::kHomePage);
  }

  void VerifyReactionToPrefAttack() override {
    // Expect a single Changed event for tracked pref #2 (kHomePage) if
    // not protecting; if protection is enabled the change should be a Cleared.
    int changed_expected =
        protection_level_ > PROTECTION_DISABLED_ON_PLATFORM &&
                protection_level_ < PROTECTION_ENABLED_BASIC
            ? 1
            : 0;
    int cleared_expected =
        protection_level_ >= PROTECTION_ENABLED_BASIC
        ? 1 : 0;
    EXPECT_EQ(changed_expected,
              GetTrackedPrefHistogramCount(
                  user_prefs::tracked::kTrackedPrefHistogramChanged,
                  BEGIN_ALLOW_SINGLE_BUCKET + 2));
    EXPECT_EQ(cleared_expected,
              GetTrackedPrefHistogramCount(
                  user_prefs::tracked::kTrackedPrefHistogramCleared,
                  BEGIN_ALLOW_SINGLE_BUCKET + 2));
    EXPECT_EQ(
        protection_level_ > PROTECTION_DISABLED_ON_PLATFORM
            ? num_tracked_prefs() - changed_expected - cleared_expected
            : 0,
        GetTrackedPrefHistogramCount(
            user_prefs::tracked::kTrackedPrefHistogramUnchanged, ALLOW_ANY));

    EXPECT_EQ(changed_expected,
              GetTrackedPrefHistogramCount(
                  user_prefs::tracked::kTrackedPrefHistogramWantedReset,
                  BEGIN_ALLOW_SINGLE_BUCKET + 2));
    EXPECT_EQ(0,
              GetTrackedPrefHistogramCount(
                  user_prefs::tracked::kTrackedPrefHistogramReset, ALLOW_NONE));

    // Nothing else should have triggered.
    EXPECT_EQ(0, GetTrackedPrefHistogramCount(
                     user_prefs::tracked::kTrackedPrefHistogramInitialized,
                     ALLOW_NONE));
    EXPECT_EQ(0,
              GetTrackedPrefHistogramCount(
                  user_prefs::tracked::kTrackedPrefHistogramTrustedInitialized,
                  ALLOW_NONE));
    EXPECT_EQ(0, GetTrackedPrefHistogramCount(
                     user_prefs::tracked::kTrackedPrefHistogramNullInitialized,
                     ALLOW_NONE));

    if (SupportsRegistryValidation()) {
      EXPECT_EQ(changed_expected,
                GetTrackedPrefHistogramCount(
                    user_prefs::tracked::kTrackedPrefHistogramChanged,
                    user_prefs::tracked::kTrackedPrefRegistryValidationSuffix,
                    BEGIN_ALLOW_SINGLE_BUCKET + 2));
      EXPECT_EQ(cleared_expected,
                GetTrackedPrefHistogramCount(
                    user_prefs::tracked::kTrackedPrefHistogramCleared,
                    user_prefs::tracked::kTrackedPrefRegistryValidationSuffix,
                    BEGIN_ALLOW_SINGLE_BUCKET + 2));
    }
  }
};

PREF_HASH_BROWSER_TEST(PrefHashBrowserTestUntrustedAdditionToPrefsAfterWipe,
                       UntrustedAdditionToPrefsAfterWipe);

#if BUILDFLAG(IS_WIN)
class PrefHashBrowserTestRegistryValidationFailure
    : public PrefHashBrowserTestBase {
 public:
  void SetupPreferences() override {
    profile()->GetPrefs()->SetString(prefs::kHomePage, "http://example.com");
  }

  void AttackPreferencesOnDisk(
      base::Value::Dict* unprotected_preferences,
      base::Value::Dict* protected_preferences) override {
    std::wstring registry_key =
        GetRegistryPathForTestProfile() + L"\\PreferenceMACs\\Default";
    base::win::RegKey key;
    ASSERT_EQ(ERROR_SUCCESS, key.Open(HKEY_CURRENT_USER, registry_key.c_str(),
                                      KEY_SET_VALUE | KEY_WOW64_32KEY));
    // An incorrect hash should still have the correct size.
    ASSERT_EQ(ERROR_SUCCESS,
              key.WriteValue(L"homepage", std::wstring(64, 'A').c_str()));
  }

  void VerifyReactionToPrefAttack() override {
    EXPECT_EQ(
        protection_level_ > PROTECTION_DISABLED_ON_PLATFORM
            ? num_tracked_prefs()
            : 0,
        GetTrackedPrefHistogramCount(
            user_prefs::tracked::kTrackedPrefHistogramUnchanged, ALLOW_ANY));

    if (SupportsRegistryValidation()) {
      // Expect that the registry validation caught the invalid MAC for pref #2
      // (homepage).
      EXPECT_EQ(protection_level_ > PROTECTION_DISABLED_ON_PLATFORM ? 1 : 0,
                GetTrackedPrefHistogramCount(
                    user_prefs::tracked::kTrackedPrefHistogramChanged,
                    user_prefs::tracked::kTrackedPrefRegistryValidationSuffix,
                    BEGIN_ALLOW_SINGLE_BUCKET + 2));
    }
  }
};

PREF_HASH_BROWSER_TEST(PrefHashBrowserTestRegistryValidationFailure,
                       RegistryValidationFailure);
#endif

// Verifies that all preferences related to choice of default search engine are
// protected.
class PrefHashBrowserTestDefaultSearch : public PrefHashBrowserTestBase {
 public:
  void SetupPreferences() override {
    // Set user selected default search engine.
    DefaultSearchManager default_search_manager(
        profile()->GetPrefs(),
        search_engines::SearchEngineChoiceServiceFactory::GetForProfile(
            profile()),
        CHECK_DEREF(TemplateURLPrepopulateData::ResolverFactory::GetForProfile(
            profile())),
        DefaultSearchManager::ObserverCallback());
    DefaultSearchManager::Source dse_source =
        static_cast<DefaultSearchManager::Source>(-1);

    TemplateURLData user_dse;
    user_dse.SetKeyword(u"userkeyword");
    user_dse.SetShortName(u"username");
    user_dse.SetURL("http://user_default_engine/search?q=good_user_query");
    default_search_manager.SetUserSelectedDefaultSearchEngine(user_dse);

    const TemplateURLData* current_dse =
        default_search_manager.GetDefaultSearchEngine(&dse_source);
    EXPECT_EQ(DefaultSearchManager::FROM_USER, dse_source);
    EXPECT_EQ(current_dse->keyword(), u"userkeyword");
    EXPECT_EQ(current_dse->short_name(), u"username");
    EXPECT_EQ(current_dse->url(),
              "http://user_default_engine/search?q=good_user_query");
  }

  void AttackPreferencesOnDisk(
      base::Value::Dict* unprotected_preferences,
      base::Value::Dict* protected_preferences) override {
    static constexpr char default_search_provider_data[] = R"(
    {
      "default_search_provider_data" : {
        "template_url_data" : {
          "keyword" : "badkeyword",
          "short_name" : "badname",
          "url" : "http://bad_default_engine/search?q=dirty_user_query"
        }
      }
    })";
    static constexpr char search_provider_overrides[] = R"(
    {
      "search_provider_overrides" : [
        {
          "keyword" : "badkeyword",
          "name" : "badname",
          "search_url" :
          "http://bad_default_engine/search?q=dirty_user_query", "encoding" :
          "utf-8", "id" : 1
        }, {
          "keyword" : "badkeyword2",
          "name" : "badname2",
          "search_url" :
          "http://bad_default_engine2/search?q=dirty_user_query", "encoding"
          : "utf-8", "id" : 2
        }
      ]
    })";

    // Try to override default search in all three of available preferences.
    base::Value attack1 = *base::JSONReader::Read(default_search_provider_data);
    base::Value attack2 = *base::JSONReader::Read(search_provider_overrides);
    unprotected_preferences->Merge(attack1.GetDict().Clone());
    unprotected_preferences->Merge(attack2.GetDict().Clone());
    if (protected_preferences) {
      // Override here, too.
      protected_preferences->Merge(attack1.GetDict().Clone());
      protected_preferences->Merge(attack2.GetDict().Clone());
    }
  }

  void VerifyReactionToPrefAttack() override {
    DefaultSearchManager default_search_manager(
        profile()->GetPrefs(),
        search_engines::SearchEngineChoiceServiceFactory::GetForProfile(
            profile()),
        CHECK_DEREF(TemplateURLPrepopulateData::ResolverFactory::GetForProfile(
            profile())),
        DefaultSearchManager::ObserverCallback());
    DefaultSearchManager::Source dse_source =
        static_cast<DefaultSearchManager::Source>(-1);

    const TemplateURLData* current_dse =
        default_search_manager.GetDefaultSearchEngine(&dse_source);

    if (protection_level_ < PROTECTION_ENABLED_DSE) {
// This doesn't work on OS_CHROMEOS because we fail to attack Preferences.
#if !BUILDFLAG(IS_CHROMEOS)
      // Attack is successful.
      EXPECT_EQ(DefaultSearchManager::FROM_USER, dse_source);
      EXPECT_EQ(current_dse->keyword(), u"badkeyword");
      EXPECT_EQ(current_dse->short_name(), u"badname");
      EXPECT_EQ(current_dse->url(),
                "http://bad_default_engine/search?q=dirty_user_query");
#endif
    } else {
      // Attack fails.
      EXPECT_EQ(DefaultSearchManager::FROM_FALLBACK, dse_source);
      EXPECT_NE(current_dse->keyword(), u"badkeyword");
      EXPECT_NE(current_dse->short_name(), u"badname");
      EXPECT_NE(current_dse->url(),
                "http://bad_default_engine/search?q=dirty_user_query");
    }
// This doesn't work on OS_CHROMEOS because we fail to attack Preferences.
#if !BUILDFLAG(IS_CHROMEOS)
    // This test creates 2 DefaultSearchManagers, because the browser creates
    // one, and this function creates a second one, so 2 samples are emitted,
    // both attacked by the PRE_ test.
    histograms_.ExpectUniqueSample(
        DefaultSearchManager::kDefaultSearchEngineMirroredMetric, false, 2);
#endif  // !BUILDFLAG(IS_CHROMEOS)
  }
};

PREF_HASH_BROWSER_TEST(PrefHashBrowserTestDefaultSearch, SearchProtected);

// Verifies that we handle a protected Dict preference being changed to an
// unexpected type (int). See https://crbug.com/1512724.
class PrefHashBrowserTestExtensionDictTypeChanged
    : public PrefHashBrowserTestBase {
 public:
  void SetupPreferences() override {
    InstallExtensionWithUIAutoConfirm(test_data_dir_.AppendASCII("good.crx"),
                                      1);
  }

  void AttackPreferencesOnDisk(
      base::Value::Dict* unprotected_preferences,
      base::Value::Dict* protected_preferences) override {
    base::Value::Dict* const selected_prefs =
        protection_level_ >= PROTECTION_ENABLED_EXTENSIONS
            ? protected_preferences
            : unprotected_preferences;
    // |selected_prefs| should never be NULL under the protection level picking
    // it.
    ASSERT_TRUE(selected_prefs);
    EXPECT_TRUE(selected_prefs->FindDictByDottedPath(
        extensions::pref_names::kExtensions));
    // Overwrite with an int (wrong type).
    selected_prefs->SetByDottedPath(extensions::pref_names::kExtensions, 13);
    EXPECT_EQ(13, selected_prefs
                      ->FindIntByDottedPath(extensions::pref_names::kExtensions)
                      .value());
  }

  void VerifyReactionToPrefAttack() override {
    // Setting the extensions dict to an invalid type gets noticed regardless
    // of protection level. This implementation just happened to be easier and
    // it doesn't seem important to not protect the kExtensions from being the
    // wrong type at any protection level. PrefService will correct the
    // type either way.
    EXPECT_EQ(protection_level_ > PROTECTION_DISABLED_ON_PLATFORM ? 1 : 0,
              GetTrackedPrefHistogramCount(
                  user_prefs::tracked::kTrackedPrefHistogramCleared,
                  BEGIN_ALLOW_SINGLE_BUCKET + 5));

    // Expect a dictionary for extensions. This shouldn't somehow explode.
    profile()->GetPrefs()->GetDict(extensions::pref_names::kExtensions);
  }
};

PREF_HASH_BROWSER_TEST(PrefHashBrowserTestExtensionDictTypeChanged,
                       ExtensionDictTypeChanged);

// Verifies that changing the account value of a tracked pref results in it
// being reported under the same id as the local value (and reset if the
// protection level allows it).
class PrefHashBrowserTestAccountValueUntrustedAddition
    : public PrefHashBrowserTestBase {
 public:
  PrefHashBrowserTestAccountValueUntrustedAddition()
      : feature_list_(switches::kEnablePreferencesAccountStorage) {}

  void SetupPreferences() override {
    EXPECT_FALSE(profile()->GetPrefs()->GetBoolean(prefs::kShowHomeButton));
  }

  void AttackPreferencesOnDisk(
      base::Value::Dict* unprotected_preferences,
      base::Value::Dict* protected_preferences) override {
    base::Value::Dict* selected_prefs =
        protection_level_ >= PROTECTION_ENABLED_BASIC ? protected_preferences
                                                      : unprotected_preferences;
    // `selected_prefs` should never be NULL under the protection level picking
    // it.
    ASSERT_TRUE(selected_prefs);
    selected_prefs->SetByDottedPath(
        base::StringPrintf("%s.%s", chrome_prefs::kAccountPreferencesPrefix,
                           prefs::kShowHomeButton),
        true);
  }

  void VerifyReactionToPrefAttack() override {
    // Expect a single Changed event for tracked pref #0 (show home button).
    EXPECT_EQ(protection_level_ > PROTECTION_DISABLED_ON_PLATFORM ? 1 : 0,
              GetTrackedPrefHistogramCount(
                  user_prefs::tracked::kTrackedPrefHistogramChanged,
                  BEGIN_ALLOW_SINGLE_BUCKET + 0));
    EXPECT_EQ(
        protection_level_ > PROTECTION_DISABLED_ON_PLATFORM
            ? num_tracked_prefs() - 1
            : 0,
        GetTrackedPrefHistogramCount(
            user_prefs::tracked::kTrackedPrefHistogramUnchanged, ALLOW_ANY));

    EXPECT_EQ((protection_level_ > PROTECTION_DISABLED_ON_PLATFORM &&
               protection_level_ < PROTECTION_ENABLED_BASIC)
                  ? 1
                  : 0,
              GetTrackedPrefHistogramCount(
                  user_prefs::tracked::kTrackedPrefHistogramWantedReset,
                  BEGIN_ALLOW_SINGLE_BUCKET + 0));
    EXPECT_EQ(protection_level_ >= PROTECTION_ENABLED_BASIC ? 1 : 0,
              GetTrackedPrefHistogramCount(
                  user_prefs::tracked::kTrackedPrefHistogramReset,
                  BEGIN_ALLOW_SINGLE_BUCKET + 0));

// TODO(gab): This doesn't work on OS_CHROMEOS because we fail to attack
// Preferences.
#if !BUILDFLAG(IS_CHROMEOS)
    // Explicitly verify the result of reported resets.
    EXPECT_EQ(protection_level_ < PROTECTION_ENABLED_BASIC,
              profile()->GetPrefs()->GetBoolean(prefs::kShowHomeButton));
#endif  // !BUILDFLAG(IS_CHROMEOS)

    // Nothing else should have triggered.
    EXPECT_EQ(
        0, GetTrackedPrefHistogramCount(
               user_prefs::tracked::kTrackedPrefHistogramCleared, ALLOW_NONE));
    EXPECT_EQ(0, GetTrackedPrefHistogramCount(
                     user_prefs::tracked::kTrackedPrefHistogramInitialized,
                     ALLOW_NONE));
    EXPECT_EQ(0,
              GetTrackedPrefHistogramCount(
                  user_prefs::tracked::kTrackedPrefHistogramTrustedInitialized,
                  ALLOW_NONE));
    EXPECT_EQ(0, GetTrackedPrefHistogramCount(
                     user_prefs::tracked::kTrackedPrefHistogramNullInitialized,
                     ALLOW_NONE));

    if (SupportsRegistryValidation()) {
      // Expect a single Changed event for tracked pref #0 (show home button).
      EXPECT_EQ(protection_level_ > PROTECTION_DISABLED_ON_PLATFORM ? 1 : 0,
                GetTrackedPrefHistogramCount(
                    user_prefs::tracked::kTrackedPrefHistogramChanged,
                    user_prefs::tracked::kTrackedPrefRegistryValidationSuffix,
                    BEGIN_ALLOW_SINGLE_BUCKET + 0));
    }
  }

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

PREF_HASH_BROWSER_TEST(PrefHashBrowserTestAccountValueUntrustedAddition,
                       AccountValueUntrustedAddition);

// Suffix used to distinguish encrypted hash keys from MAC keys in storage.
const char kEncryptedHashSuffix[] = "_encrypted_hash";
// Base class for tests that need to control the EncryptedPrefHashing
// feature flag.
class PrefHashBrowserTestEncryptedBase : public PrefHashBrowserTestBase {};

// Tests that a tampered encrypted hash is caught and triggers a reset.
class PrefHashBrowserTestEncryptedTampered
    : public PrefHashBrowserTestEncryptedBase {
 public:
  PrefHashBrowserTestEncryptedTampered() {
    // Feature must be ON for both the PRE_ and main test phases.
    feature_list_.InitAndEnableFeature(tracked::kEncryptedPrefHashing);
  }

  void SetupPreferences() override {
    // PRE_ test (feature ON): Set a value to ensure both MAC and encrypted
    // hashes are written.
    profile()->GetPrefs()->SetString(prefs::kHomePage, "http://example.com");
  }

  void AttackPreferencesOnDisk(
      base::Value::Dict* unprotected_preferences,
      base::Value::Dict* protected_preferences) override {
    // Attack the encrypted hash, leaving the legacy MAC intact.
    base::Value::Dict* selected_prefs =
        protection_level_ >= PROTECTION_ENABLED_BASIC ? protected_preferences
                                                      : unprotected_preferences;
    ASSERT_TRUE(selected_prefs);

    // Hashes are stored in the "protection.macs" dictionary.
    base::Value::Dict* macs_dict =
        selected_prefs->FindDictByDottedPath("protection.macs");
    ASSERT_TRUE(macs_dict);

    const std::string encrypted_hash_key =
        std::string(prefs::kHomePage) + kEncryptedHashSuffix;

    // Verify the key exists, then tamper with it.
    ASSERT_TRUE(macs_dict->contains(encrypted_hash_key));
    macs_dict->Set(encrypted_hash_key, "invalid_tampered_hash");
  }

  void VerifyReactionToPrefAttack() override {
    // Main test (feature ON):
    if (protection_level_ <= PROTECTION_DISABLED_ON_PLATFORM) {
      return;
    }

    // The validation prioritizes the encrypted hash. Since it's invalid, a
    // change should be detected.
    if (protection_level_ >= PROTECTION_ENABLED_BASIC) {
      // The tampered encrypted hash should be detected and trigger a reset.
      histograms_.ExpectUniqueSample(
          user_prefs::tracked::kTrackedPrefHistogramChangedEncrypted,
          2 /* homepage reporting_id */, 1);
      histograms_.ExpectUniqueSample(
          user_prefs::tracked::kTrackedPrefHistogramResetEncrypted,
          2 /* homepage reporting_id */, 1);
      // The pref should now be reset to its default value.
      EXPECT_TRUE(profile()->GetPrefs()->GetString(prefs::kHomePage).empty());
    } else {
      // If enforcement is off, we should want a reset but not perform it.
      histograms_.ExpectUniqueSample(
          user_prefs::tracked::kTrackedPrefHistogramChangedEncrypted,
          2 /* homepage reporting_id */, 1);
      histograms_.ExpectUniqueSample(
          user_prefs::tracked::kTrackedPrefHistogramWantedResetEncrypted,
          2 /* homepage reporting_id */, 1);
      // The pref value should remain as it was on disk.
      EXPECT_EQ("http://example.com",
                profile()->GetPrefs()->GetString(prefs::kHomePage));
    }
  }

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

PREF_HASH_BROWSER_TEST(PrefHashBrowserTestEncryptedTampered, EncryptedTampered);

// Tests the fallback path: loads prefs with only legacy MACs and verifies
// that new encrypted hashes are created without resetting any values.
class PrefHashBrowserTestEncryptedFallbackAndGeneratingEH
    : public PrefHashBrowserTestEncryptedBase {
 public:
  PrefHashBrowserTestEncryptedFallbackAndGeneratingEH() {
    if (content::IsPreTest()) {
      // PRE_ phase: Feature is explicitly OFF to write only legacy MACs.
      feature_list_.InitWithFeatures({}, {tracked::kEncryptedPrefHashing});
    } else {
      // Main phase: Feature is ON to trigger the fallback and the generation of
      // encrypted hash process.
      feature_list_.InitWithFeatures({tracked::kEncryptedPrefHashing}, {});
    }
  }

  // Runs in the PRE_ test, with the encryption feature OFF.
  void SetupPreferences() override {
    profile()->GetPrefs()->SetString(prefs::kHomePage, "http://example.com");
  }

  // Runs before the main test. Verifies the on-disk state.
  void AttackPreferencesOnDisk(
      base::Value::Dict* unprotected_preferences,
      base::Value::Dict* protected_preferences) override {
    if (protection_level_ <= PROTECTION_DISABLED_ON_PLATFORM) {
      return;
    }

    // The 'macs' dict may be in either pref file depending on platform.
    base::Value::Dict* macs_dict = nullptr;
    if (protected_preferences) {
      macs_dict =
          protected_preferences->FindDictByDottedPath("protection.macs");
    }
    if (!macs_dict) {
      macs_dict =
          unprotected_preferences->FindDictByDottedPath("protection.macs");
    }
    ASSERT_TRUE(macs_dict);

    // VERIFY: The legacy MAC for 'homepage' must exist.
    ASSERT_TRUE(macs_dict->contains(prefs::kHomePage));

    // VERIFY: The encrypted hash for 'homepage' must NOT exist yet.
    const std::string encrypted_hash_key =
        std::string(prefs::kHomePage) + kEncryptedHashSuffix;
    ASSERT_FALSE(macs_dict->contains(encrypted_hash_key));
  }

  // Runs in the main test, with the encryption feature ON.
  void VerifyReactionToPrefAttack() override {
    if (protection_level_ <= PROTECTION_DISABLED_ON_PLATFORM) {
      return;
    }

    // Verify initial load behavior.
    EXPECT_EQ("http://example.com",
              profile()->GetPrefs()->GetString(prefs::kHomePage));

    histograms_.ExpectBucketCount(
        user_prefs::tracked::kTrackedPrefHistogramUnchangedViaHmacFallback,
        2 /* homepage reporting_id */, 1);
    EXPECT_GE(
        GetTrackedPrefHistogramCount(
            user_prefs::tracked::kTrackedPrefHistogramUnchangedViaHmacFallback,
            ALLOW_ANY),
        1);
    histograms_.ExpectTotalCount(
        user_prefs::tracked::kTrackedPrefHistogramReset, 0);

    base::RunLoop run_loop;
    // A write operation is scheduled after the encryptor received.
    profile()->GetPrefs()->CommitPendingWrite(run_loop.QuitClosure());
    run_loop.Run();
#if !BUILDFLAG(IS_CHROMEOS)
    std::optional<base::Value::Dict> final_protected_prefs;
    std::optional<base::Value::Dict> final_unprotected_prefs;
    base::Value::Dict* final_macs_dict = nullptr;

    {
      base::ScopedAllowBlockingForTesting allow_blocking;
      base::FilePath profile_dir = GetProfileDir();
      const base::FilePath protected_pref_file =
          profile_dir.Append(chrome::kSecurePreferencesFilename);
      if (base::PathExists(protected_pref_file)) {
        final_protected_prefs = ReadPrefsDictionary(protected_pref_file);
      }
    }

    if (final_protected_prefs.has_value()) {
      final_macs_dict =
          final_protected_prefs->FindDictByDottedPath("protection.macs");
    }

    if (!final_macs_dict) {
      base::ScopedAllowBlockingForTesting allow_blocking;
      base::FilePath profile_dir = GetProfileDir();
      const base::FilePath unprotected_pref_file =
          profile_dir.Append(chrome::kPreferencesFilename);
      final_unprotected_prefs = ReadPrefsDictionary(unprotected_pref_file);
      ASSERT_TRUE(final_unprotected_prefs.has_value());
      final_macs_dict =
          final_unprotected_prefs->FindDictByDottedPath("protection.macs");
    }
    ASSERT_TRUE(final_macs_dict);

    // VERIFY: The new encrypted hash should now exist on disk.
    const std::string encrypted_hash_key =
        std::string(prefs::kHomePage) + kEncryptedHashSuffix;
    EXPECT_TRUE(final_macs_dict->contains(encrypted_hash_key));
#endif  // #if !BUILDFLAG(IS_CHROMEOS)
  }

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

PREF_HASH_BROWSER_TEST(PrefHashBrowserTestEncryptedFallbackAndGeneratingEH,
                       EncryptedHashGeneration);

class PrefHashBrowserTestEncryptedSplitPrefFallbackAndGeneratingEH
    : public PrefHashBrowserTestEncryptedBase {
 public:
  PrefHashBrowserTestEncryptedSplitPrefFallbackAndGeneratingEH() {
    if (content::IsPreTest()) {
      // PRE_ phase: Feature is OFF to write only legacy MACs.
      feature_list_.InitWithFeatures({}, {tracked::kEncryptedPrefHashing});
    } else {
      // Main phase: Feature is ON to trigger FallbackAndGeneratingEH.
      feature_list_.InitWithFeatures({tracked::kEncryptedPrefHashing}, {});
    }
  }

  void SetupPreferences() override {
    // This creates a split preference entry for extensions.settings.
    InstallExtensionWithUIAutoConfirm(test_data_dir_.AppendASCII("good.crx"),
                                      1);
  }

  void AttackPreferencesOnDisk(
      base::Value::Dict* unprotected_preferences,
      base::Value::Dict* protected_preferences) override {
    if (protection_level_ <= PROTECTION_DISABLED_ON_PLATFORM) {
      pre_test_state_ok_ = true;
      return;
    }

    base::Value::Dict* macs_dict = nullptr;
    if (protected_preferences) {
      macs_dict =
          protected_preferences->FindDictByDottedPath("protection.macs");
    }
    if (!macs_dict) {
      macs_dict =
          unprotected_preferences->FindDictByDottedPath("protection.macs");
    }

    // Instead of asserting, check if the required legacy hashes were actually
    // written by the PRE_ test.
    if (macs_dict && macs_dict->FindDict(extensions::pref_names::kExtensions)) {
      // State is good, we can proceed.
      pre_test_state_ok_ = true;

      // Now we can safely assert that the encrypted hashes are not yet present.
      const std::string encrypted_hash_key =
          std::string(extensions::pref_names::kExtensions) +
          kEncryptedHashSuffix;
      ASSERT_FALSE(macs_dict->FindDict(encrypted_hash_key));
    } else {
      // The PRE_ test failed to write the legacy hashes. Log a warning and
      // set the flag so the main test verification is skipped.
      pre_test_state_ok_ = false;
    }
  }

  void VerifyReactionToPrefAttack() override {
    if (!pre_test_state_ok_) {
      return;
    }

    if (protection_level_ <= PROTECTION_DISABLED_ON_PLATFORM) {
      return;
    }

    EXPECT_TRUE(extension_registry()->enabled_extensions().GetByID(kGoodCrxId));
    histograms_.ExpectBucketCount(
        user_prefs::tracked::kTrackedPrefHistogramUnchangedViaHmacFallback,
        5 /* extensions.settings reporting_id */, 1);
    histograms_.ExpectTotalCount(
        user_prefs::tracked::kTrackedPrefHistogramReset, 0);

    profile()->GetPrefs()->SetBoolean(prefs::kShowHomeButton, true);
    base::RunLoop run_loop;
    profile()->GetPrefs()->CommitPendingWrite(run_loop.QuitClosure());
    run_loop.Run();
#if !BUILDFLAG(IS_CHROMEOS)
    std::optional<base::Value::Dict> final_protected_prefs;
    std::optional<base::Value::Dict> final_unprotected_prefs;
    base::Value::Dict* final_macs_dict = nullptr;
    {
      base::ScopedAllowBlockingForTesting allow_blocking;
      final_protected_prefs = ReadPrefsDictionary(
          GetProfileDir().Append(chrome::kSecurePreferencesFilename));
      if (final_protected_prefs.has_value()) {
        final_macs_dict =
            final_protected_prefs->FindDictByDottedPath("protection.macs");
      }
    }
    if (!final_macs_dict) {
      base::ScopedAllowBlockingForTesting allow_blocking;
      final_unprotected_prefs = ReadPrefsDictionary(
          GetProfileDir().Append(chrome::kPreferencesFilename));
      if (final_unprotected_prefs.has_value()) {
        final_macs_dict =
            final_unprotected_prefs->FindDictByDottedPath("protection.macs");
      }
    }
    ASSERT_TRUE(final_macs_dict);

    const std::string encrypted_hash_key =
        std::string(extensions::pref_names::kExtensions) + kEncryptedHashSuffix;
    EXPECT_TRUE(final_macs_dict->FindDict(encrypted_hash_key));
#endif  // #if !BUILDFLAG(IS_CHROMEOS)
  }

 private:
  base::test::ScopedFeatureList feature_list_;
  bool pre_test_state_ok_ = false;
};

PREF_HASH_BROWSER_TEST(
    PrefHashBrowserTestEncryptedSplitPrefFallbackAndGeneratingEH,
    EncryptedSplitPrefFallbackAndGeneratingEH);

class PrefHashBrowserTestEncryptedSplitPrefTampered
    : public PrefHashBrowserTestEncryptedBase {
 public:
  PrefHashBrowserTestEncryptedSplitPrefTampered() {
    feature_list_.InitAndEnableFeature(tracked::kEncryptedPrefHashing);
  }

  void SetupPreferences() override {
    InstallExtensionWithUIAutoConfirm(test_data_dir_.AppendASCII("good.crx"),
                                      1);
  }

  void AttackPreferencesOnDisk(
      base::Value::Dict* unprotected_preferences,
      base::Value::Dict* protected_preferences) override {
    if (protection_level_ <= PROTECTION_DISABLED_ON_PLATFORM) {
      return;
    }

    base::Value::Dict* macs_dict = nullptr;
    if (protected_preferences) {
      macs_dict =
          protected_preferences->FindDictByDottedPath("protection.macs");
    }
    if (!macs_dict) {
      macs_dict =
          unprotected_preferences->FindDictByDottedPath("protection.macs");
    }
    ASSERT_TRUE(macs_dict);

    const std::string encrypted_hash_key =
        std::string(extensions::pref_names::kExtensions) + kEncryptedHashSuffix;
    base::Value::Dict* encrypted_split_hashes =
        macs_dict->FindDict(encrypted_hash_key);

    if (encrypted_split_hashes) {
      // Hashes exist, so we can perform the attack.
      encrypted_split_hashes->Set(kGoodCrxId, "invalid_split_hash");
      was_attacked_ = true;
    } else {
      // This indicates the race condition occurred. The test will still run but
      // won't be able to verify the tampering-detection logic.
      was_attacked_ = false;
    }
  }

  void VerifyReactionToPrefAttack() override {
    if (!was_attacked_) {
      // If we couldn't perform the attack, we can't verify the reaction.
      // The WARNING log from the attack phase will serve as the failure signal.
      return;
    }

    if (protection_level_ < PROTECTION_ENABLED_EXTENSIONS) {
      EXPECT_TRUE(
          extension_registry()->enabled_extensions().GetByID(kGoodCrxId));
      histograms_.ExpectBucketCount(
          user_prefs::tracked::kTrackedPrefHistogramChangedEncrypted, 5, 1);
      histograms_.ExpectBucketCount(
          user_prefs::tracked::kTrackedPrefHistogramWantedResetEncrypted, 5, 1);
    } else {
      EXPECT_FALSE(
          extension_registry()->enabled_extensions().GetByID(kGoodCrxId));
      histograms_.ExpectBucketCount(
          user_prefs::tracked::kTrackedPrefHistogramChangedEncrypted,
          5 /* extensions.settings reporting_id */, 1);
      histograms_.ExpectBucketCount(
          user_prefs::tracked::kTrackedPrefHistogramResetEncrypted, 5, 1);
    }
  }

 private:
  base::test::ScopedFeatureList feature_list_;
  // Member variable to track if the attack was successfully performed.
  bool was_attacked_ = false;
};

PREF_HASH_BROWSER_TEST(PrefHashBrowserTestEncryptedSplitPrefTampered,
                       EncryptedSplitPrefTampered);

class PrefHashBrowserTestEncryptedHashIsAuthoritative
    : public PrefHashBrowserTestEncryptedBase {
 public:
  PrefHashBrowserTestEncryptedHashIsAuthoritative() {
    feature_list_.InitAndEnableFeature(tracked::kEncryptedPrefHashing);
  }

  void SetupPreferences() override {
    // In the PRE_ test, set a value. This will cause both a valid legacy MAC
    // and a valid encrypted hash to be written to disk on shutdown.
    profile()->GetPrefs()->SetString(prefs::kHomePage, "http://good.com");
  }

  void AttackPreferencesOnDisk(
      base::Value::Dict* unprotected_preferences,
      base::Value::Dict* protected_preferences) override {
    if (protection_level_ <= PROTECTION_DISABLED_ON_PLATFORM) {
      return;
    }

    base::Value::Dict* macs_dict = nullptr;
    if (protected_preferences) {
      macs_dict =
          protected_preferences->FindDictByDottedPath("protection.macs");
    }
    if (!macs_dict) {
      macs_dict =
          unprotected_preferences->FindDictByDottedPath("protection.macs");
    }
    ASSERT_TRUE(macs_dict);

    const std::string encrypted_hash_key =
        std::string(prefs::kHomePage) + kEncryptedHashSuffix;
    ASSERT_TRUE(macs_dict->contains(prefs::kHomePage));
    ASSERT_TRUE(macs_dict->contains(encrypted_hash_key));

    // Tamper with the legacy MAC, but leave the encrypted hash
    // (the authoritative source) and the preference value untouched.
    macs_dict->Set(prefs::kHomePage, "invalid_legacy_mac");
  }

  void VerifyReactionToPrefAttack() override {
    if (protection_level_ <= PROTECTION_DISABLED_ON_PLATFORM) {
      return;
    }

    if (protection_level_ >= PROTECTION_ENABLED_BASIC) {
      // Assert that the preference was reset to its default (empty) value.
      EXPECT_TRUE(profile()->GetPrefs()->GetString(prefs::kHomePage).empty());

      // Verify that the reset was triggered by the non-encrypted, legacy MAC
      // validation path.
      histograms_.ExpectUniqueSample(
          user_prefs::tracked::kTrackedPrefHistogramChanged,
          2 /* homepage reporting_id */, 1);
      histograms_.ExpectUniqueSample(
          user_prefs::tracked::kTrackedPrefHistogramReset,
          2 /* homepage reporting_id */, 1);

      // No other validation paths should have triggered a reset.
      histograms_.ExpectTotalCount(
          user_prefs::tracked::kTrackedPrefHistogramUnchangedEncrypted, 0);
      histograms_.ExpectTotalCount(
          user_prefs::tracked::kTrackedPrefHistogramResetEncrypted, 0);

    } else {
      // On platforms with low enforcement (Linux), the initial validation pass
      // logs the invalid legacy MAC but does NOT reset the preference. The
      // deferred validation pass then checks the authoritative encrypted hash,
      // finds it valid, and the preference value is kept.
      EXPECT_EQ("http://good.com",
                profile()->GetPrefs()->GetString(prefs::kHomePage));

      // Verify the preference was considered unchanged because the
      // authoritative encrypted hash was valid.
      histograms_.ExpectBucketCount(
          user_prefs::tracked::kTrackedPrefHistogramUnchangedEncrypted,
          2 /* homepage reporting_id */, 1);

      // Verify no resets of any kind were performed.
      histograms_.ExpectTotalCount(
          user_prefs::tracked::kTrackedPrefHistogramReset, 0);
      histograms_.ExpectTotalCount(
          user_prefs::tracked::kTrackedPrefHistogramResetEncrypted, 0);
      histograms_.ExpectTotalCount(
          user_prefs::tracked::kTrackedPrefHistogramResetViaHmacFallback, 0);
    }
  }

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

PREF_HASH_BROWSER_TEST(PrefHashBrowserTestEncryptedHashIsAuthoritative,
                       EncryptedHashIsAuthoritative);