File: transport_security_state_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 (1884 lines) | stat: -rw-r--r-- 80,811 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
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
// Copyright 2012 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "net/http/transport_security_state.h"

#include <stdint.h>

#include <algorithm>
#include <array>
#include <iterator>
#include <memory>
#include <ranges>
#include <string>
#include <vector>

#include "base/base64.h"
#include "base/containers/to_vector.h"
#include "base/files/file_path.h"
#include "base/functional/callback_helpers.h"
#include "base/json/json_reader.h"
#include "base/memory/raw_ptr.h"
#include "base/metrics/field_trial.h"
#include "base/metrics/field_trial_param_associator.h"
#include "base/rand_util.h"
#include "base/stl_util.h"
#include "base/strings/stringprintf.h"
#include "base/test/metrics/histogram_tester.h"
#include "base/test/mock_entropy_provider.h"
#include "base/test/scoped_feature_list.h"
#include "base/time/time.h"
#include "base/values.h"
#include "build/build_config.h"
#include "crypto/sha2.h"
#include "net/base/features.h"
#include "net/base/hash_value.h"
#include "net/base/host_port_pair.h"
#include "net/base/net_errors.h"
#include "net/base/schemeful_site.h"
#include "net/base/test_completion_callback.h"
#include "net/cert/asn1_util.h"
#include "net/cert/cert_verifier.h"
#include "net/cert/cert_verify_result.h"
#include "net/cert/ct_policy_status.h"
#include "net/cert/test_root_certs.h"
#include "net/cert/x509_certificate.h"
#include "net/extras/preload_data/decoder.h"
#include "net/http/http_status_code.h"
#include "net/http/http_util.h"
#include "net/http/transport_security_state_source.h"
#include "net/net_buildflags.h"
#include "net/ssl/ssl_info.h"
#include "net/test/cert_test_util.h"
#include "net/test/test_data_directory.h"
#include "net/test/test_with_task_environment.h"
#include "net/tools/huffman_trie/bit_writer.h"
#include "net/tools/huffman_trie/trie/trie_bit_buffer.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "url/origin.h"

namespace net {

namespace {

namespace test_default {
#include "net/http/transport_security_state_static_unittest_default.h"
}
namespace test1 {
#include "net/http/transport_security_state_static_unittest1.h"
}
namespace test2 {
#include "net/http/transport_security_state_static_unittest2.h"
}
namespace test3 {
#include "net/http/transport_security_state_static_unittest3.h"
}

const char kHost[] = "example.test";

// kGoodPath and kBadPath are each a list of the steps in a single path.
constexpr auto kGoodPath = std::to_array<const char*>({
    "sha256/AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=",
    "sha256/fzP+pVAbH0hRoUphJKenIP8+2tD/d2QH9J+kQNieM6Q=",
    "sha256/9vRUVdjloCa4wXUKfDWotV5eUXYD7vu0v0z9SRzQdzg=",
    "sha256/Nn8jk5By4Vkq6BeOVZ7R7AC6XUUBZsWmUbJR1f1Y5FY=",
});

constexpr auto kBadPath = std::to_array<const char*>({
    "sha256/1111111111111111111111111111111111111111111=",
    "sha256/2222222222222222222222222222222222222222222=",
    "sha256/3333333333333333333333333333333333333333333=",
});

class MockRequireCTDelegate : public RequireCTDelegate {
 public:
  MOCK_CONST_METHOD3(IsCTRequiredForHost,
                     CTRequirementLevel(std::string_view hostname,
                                        const X509Certificate* chain,
                                        const HashValueVector& hashes));

 protected:
  ~MockRequireCTDelegate() override = default;
};

bool operator==(const TransportSecurityState::STSState& lhs,
                const TransportSecurityState::STSState& rhs) {
  return lhs.last_observed == rhs.last_observed && lhs.expiry == rhs.expiry &&
         lhs.upgrade_mode == rhs.upgrade_mode &&
         lhs.include_subdomains == rhs.include_subdomains &&
         lhs.domain == rhs.domain;
}

bool operator==(const TransportSecurityState::PKPState& lhs,
                const TransportSecurityState::PKPState& rhs) {
  return lhs.last_observed == rhs.last_observed && lhs.expiry == rhs.expiry &&
         lhs.spki_hashes == rhs.spki_hashes &&
         lhs.bad_spki_hashes == rhs.bad_spki_hashes &&
         lhs.include_subdomains == rhs.include_subdomains &&
         lhs.domain == rhs.domain;
}

net::HashValueVector DeserializeHashes(
    base::span<const char* const> serialized_hashes) {
  net::HashValueVector result;
  for (const auto* serialized_hash : serialized_hashes) {
    net::HashValue h(HASH_VALUE_SHA256);
    CHECK(h.FromString(std::string_view(serialized_hash)));
    result.push_back(h);
  }
  return result;
}

std::vector<std::vector<uint8_t>> UnpackRawHashes(
    const net::HashValueVector& hashes) {
  std::vector<std::vector<uint8_t>> raws;
  for (const auto& hash : hashes) {
    raws.emplace_back(base::ToVector(hash.span()));
  }
  return raws;
}

}  // namespace

class TransportSecurityStateTest : public ::testing::Test,
                                   public WithTaskEnvironment {
 public:
  TransportSecurityStateTest()
      : WithTaskEnvironment(
            base::test::TaskEnvironment::TimeSource::MOCK_TIME) {
    SetTransportSecurityStateSourceForTesting(&test_default::kHSTSSource);
    // Need mocked out time for pruning tests. Don't start with a
    // time of 0, as code doesn't generally expect it.
    FastForwardBy(base::Days(1));
  }

  ~TransportSecurityStateTest() override {
    SetTransportSecurityStateSourceForTesting(nullptr);
  }

  static void DisableStaticPins(TransportSecurityState* state) {
    state->enable_static_pins_ = false;
  }

  static void EnableStaticPins(TransportSecurityState* state) {
    state->enable_static_pins_ = true;
    state->SetPinningListAlwaysTimelyForTesting(true);
  }

  static HashValueVector GetSampleSPKIHashes() {
    HashValueVector spki_hashes;
    HashValue hash({});
    spki_hashes.push_back(hash);
    return spki_hashes;
  }

  static HashValue GetSampleSPKIHash(uint8_t value) {
    HashValue hash(HASH_VALUE_SHA256);
    std::ranges::fill(hash.span(), value);
    return hash;
  }

 protected:
  bool GetStaticDomainState(TransportSecurityState* state,
                            const std::string& host,
                            TransportSecurityState::STSState* sts_result,
                            TransportSecurityState::PKPState* pkp_result) {
    bool ret = state->GetStaticSTSState(host, sts_result);
    if (state->GetStaticPKPState(host, pkp_result))
      ret = true;
    return ret;
  }

 private:
  base::test::ScopedFeatureList scoped_feature_list_;
};

// Setting `is_top_level_nav` true prevents the upgrade from being blocked by
// kHstsTopLevelNavigationsOnly.
TEST_F(TransportSecurityStateTest, DomainNameOddities) {
  TransportSecurityState state;
  const base::Time current_time(base::Time::Now());
  const base::Time expiry = current_time + base::Seconds(1000);

  // DNS suffix search tests. Some DNS resolvers allow a terminal "." to
  // indicate not perform DNS suffix searching. Ensure that regardless
  // of how this is treated at the resolver layer, or at the URL/origin
  // layer (that is, whether they are treated as equivalent or distinct),
  // ensure that for policy matching, something lacking a terminal "."
  // is equivalent to something with a terminal "."
  EXPECT_FALSE(
      state.ShouldUpgradeToSSL("example.com", /*is_top_level_nav=*/true));

  state.AddHSTS("example.com", expiry, true /* include_subdomains */);
  EXPECT_TRUE(
      state.ShouldUpgradeToSSL("example.com", /*is_top_level_nav=*/true));
  // Trailing '.' should be equivalent; it's just a resolver hint
  EXPECT_TRUE(
      state.ShouldUpgradeToSSL("example.com.", /*is_top_level_nav=*/true));
  // Leading '.' should be invalid
  EXPECT_FALSE(
      state.ShouldUpgradeToSSL(".example.com", /*is_top_level_nav=*/true));
  // Subdomains should work regardless
  EXPECT_TRUE(
      state.ShouldUpgradeToSSL("sub.example.com", /*is_top_level_nav=*/true));
  EXPECT_TRUE(
      state.ShouldUpgradeToSSL("sub.example.com.", /*is_top_level_nav=*/true));
  // But invalid subdomains should be rejected
  EXPECT_FALSE(
      state.ShouldUpgradeToSSL("sub..example.com", /*is_top_level_nav=*/true));
  EXPECT_FALSE(
      state.ShouldUpgradeToSSL("sub..example.com.", /*is_top_level_nav=*/true));

  // Now try the inverse form
  TransportSecurityState state2;
  state2.AddHSTS("example.net.", expiry, true /* include_subdomains */);
  EXPECT_TRUE(
      state2.ShouldUpgradeToSSL("example.net.", /*is_top_level_nav=*/true));
  EXPECT_TRUE(
      state2.ShouldUpgradeToSSL("example.net", /*is_top_level_nav=*/true));
  EXPECT_TRUE(
      state2.ShouldUpgradeToSSL("sub.example.net.", /*is_top_level_nav=*/true));
  EXPECT_TRUE(
      state2.ShouldUpgradeToSSL("sub.example.net", /*is_top_level_nav=*/true));

  // Finally, test weird things
  TransportSecurityState state3;
  state3.AddHSTS("", expiry, true /* include_subdomains */);
  EXPECT_FALSE(state3.ShouldUpgradeToSSL("", /*is_top_level_nav=*/true));
  EXPECT_FALSE(state3.ShouldUpgradeToSSL(".", /*is_top_level_nav=*/true));
  EXPECT_FALSE(state3.ShouldUpgradeToSSL("...", /*is_top_level_nav=*/true));
  // Make sure it didn't somehow apply HSTS to the world
  EXPECT_FALSE(
      state3.ShouldUpgradeToSSL("example.org", /*is_top_level_nav=*/true));

  TransportSecurityState state4;
  state4.AddHSTS(".", expiry, true /* include_subdomains */);
  EXPECT_FALSE(state4.ShouldUpgradeToSSL("", /*is_top_level_nav=*/true));
  EXPECT_FALSE(state4.ShouldUpgradeToSSL(".", /*is_top_level_nav=*/true));
  EXPECT_FALSE(state4.ShouldUpgradeToSSL("...", /*is_top_level_nav=*/true));
  EXPECT_FALSE(
      state4.ShouldUpgradeToSSL("example.org", /*is_top_level_nav=*/true));

  // Now do the same for preloaded entries
  TransportSecurityState state5;
  EXPECT_TRUE(state5.ShouldUpgradeToSSL("hsts-preloaded.test",
                                        /*is_top_level_nav=*/true));
  EXPECT_TRUE(state5.ShouldUpgradeToSSL("hsts-preloaded.test.",
                                        /*is_top_level_nav=*/true));
  EXPECT_FALSE(state5.ShouldUpgradeToSSL("hsts-preloaded..test",
                                         /*is_top_level_nav=*/true));
  EXPECT_FALSE(state5.ShouldUpgradeToSSL("hsts-preloaded..test.",
                                         /*is_top_level_nav=*/true));
}

// Setting `is_top_level_nav` true prevents the upgrade from being blocked by
// kHstsTopLevelNavigationsOnly.
TEST_F(TransportSecurityStateTest, SimpleMatches) {
  TransportSecurityState state;
  const base::Time current_time(base::Time::Now());
  const base::Time expiry = current_time + base::Seconds(1000);

  EXPECT_FALSE(
      state.ShouldUpgradeToSSL("example.com", /*is_top_level_nav=*/true));
  bool include_subdomains = false;
  state.AddHSTS("example.com", expiry, include_subdomains);
  EXPECT_TRUE(
      state.ShouldUpgradeToSSL("example.com", /*is_top_level_nav=*/true));
  EXPECT_TRUE(state.ShouldSSLErrorsBeFatal("example.com"));
  EXPECT_FALSE(
      state.ShouldUpgradeToSSL("foo.example.com", /*is_top_level_nav=*/true));
  EXPECT_FALSE(state.ShouldSSLErrorsBeFatal("foo.example.com"));
}

// Setting `is_top_level_nav` true prevents the upgrade from being blocked by
// kHstsTopLevelNavigationsOnly.
TEST_F(TransportSecurityStateTest, MatchesCase1) {
  TransportSecurityState state;
  const base::Time current_time(base::Time::Now());
  const base::Time expiry = current_time + base::Seconds(1000);

  EXPECT_FALSE(
      state.ShouldUpgradeToSSL("example.com", /*is_top_level_nav=*/true));
  bool include_subdomains = false;
  state.AddHSTS("EXample.coM", expiry, include_subdomains);
  EXPECT_TRUE(
      state.ShouldUpgradeToSSL("example.com", /*is_top_level_nav=*/true));
}

// Setting `is_top_level_nav` true prevents the upgrade from being blocked by
// kHstsTopLevelNavigationsOnly.
TEST_F(TransportSecurityStateTest, MatchesCase2) {
  TransportSecurityState state;
  const base::Time current_time(base::Time::Now());
  const base::Time expiry = current_time + base::Seconds(1000);

  // Check dynamic entries
  EXPECT_FALSE(
      state.ShouldUpgradeToSSL("EXample.coM", /*is_top_level_nav=*/true));
  bool include_subdomains = false;
  state.AddHSTS("example.com", expiry, include_subdomains);
  EXPECT_TRUE(
      state.ShouldUpgradeToSSL("EXample.coM", /*is_top_level_nav=*/true));

  // Check static entries
  EXPECT_TRUE(state.ShouldUpgradeToSSL("hStS-prelOAded.tEsT",
                                       /*is_top_level_nav=*/true));
  EXPECT_TRUE(state.ShouldUpgradeToSSL("inClude-subDOmaIns-hsts-prEloaDed.TesT",
                                       /*is_top_level_nav=*/true));
}

// Setting `is_top_level_nav` true prevents the upgrade from being blocked by
// kHstsTopLevelNavigationsOnly.
TEST_F(TransportSecurityStateTest, SubdomainMatches) {
  TransportSecurityState state;
  const base::Time current_time(base::Time::Now());
  const base::Time expiry = current_time + base::Seconds(1000);

  EXPECT_FALSE(
      state.ShouldUpgradeToSSL("example.test", /*is_top_level_nav=*/true));
  bool include_subdomains = true;
  state.AddHSTS("example.test", expiry, include_subdomains);
  EXPECT_TRUE(
      state.ShouldUpgradeToSSL("example.test", /*is_top_level_nav=*/true));
  EXPECT_TRUE(
      state.ShouldUpgradeToSSL("foo.example.test", /*is_top_level_nav=*/true));
  EXPECT_TRUE(state.ShouldUpgradeToSSL("foo.bar.example.test",
                                       /*is_top_level_nav=*/true));
  EXPECT_TRUE(state.ShouldUpgradeToSSL("foo.bar.baz.example.test",
                                       /*is_top_level_nav=*/true));
  EXPECT_FALSE(state.ShouldUpgradeToSSL("test", /*is_top_level_nav=*/true));
  EXPECT_FALSE(
      state.ShouldUpgradeToSSL("notexample.test", /*is_top_level_nav=*/true));
}

// Tests that a more-specific HSTS rule without the includeSubDomains bit does
// not override a less-specific rule with includeSubDomains. Applicability is
// checked before specificity. See https://crbug.com/821811.
//
// Setting `is_top_level_nav` true prevents the upgrade from being blocked by
// kHstsTopLevelNavigationsOnly.
TEST_F(TransportSecurityStateTest, STSSubdomainNoOverride) {
  TransportSecurityState state;
  const base::Time current_time(base::Time::Now());
  const base::Time expiry = current_time + base::Seconds(1000);
  const base::Time older = current_time - base::Seconds(1000);

  state.AddHSTS("example.test", expiry, true);
  state.AddHSTS("foo.example.test", expiry, false);

  // The example.test rule applies to the entire domain, including subdomains of
  // foo.example.test.
  EXPECT_TRUE(
      state.ShouldUpgradeToSSL("example.test", /*is_top_level_nav=*/true));
  EXPECT_TRUE(
      state.ShouldUpgradeToSSL("foo.example.test", /*is_top_level_nav=*/true));
  EXPECT_TRUE(state.ShouldUpgradeToSSL("bar.foo.example.test",
                                       /*is_top_level_nav=*/true));
  EXPECT_TRUE(state.ShouldSSLErrorsBeFatal("bar.foo.example.test"));

  // Expire the foo.example.test rule.
  state.AddHSTS("foo.example.test", older, false);

  // The example.test rule still applies.
  EXPECT_TRUE(
      state.ShouldUpgradeToSSL("example.test", /*is_top_level_nav=*/true));
  EXPECT_TRUE(
      state.ShouldUpgradeToSSL("foo.example.test", /*is_top_level_nav=*/true));
  EXPECT_TRUE(state.ShouldUpgradeToSSL("bar.foo.example.test",
                                       /*is_top_level_nav=*/true));
  EXPECT_TRUE(state.ShouldSSLErrorsBeFatal("bar.foo.example.test"));
}

// Tests that a more-specific HPKP rule overrides a less-specific rule
// with it, regardless of the includeSubDomains bit. Note this behavior does not
// match HSTS. See https://crbug.com/821811.
TEST_F(TransportSecurityStateTest, PKPSubdomainCarveout) {
  TransportSecurityState state;
  const base::Time current_time(base::Time::Now());
  const base::Time expiry = current_time + base::Seconds(1000);
  const base::Time older = current_time - base::Seconds(1000);

  state.AddHPKP("example.test", expiry, true, GetSampleSPKIHashes());
  state.AddHPKP("foo.example.test", expiry, false, GetSampleSPKIHashes());
  EXPECT_TRUE(state.HasPublicKeyPins("example.test"));
  EXPECT_TRUE(state.HasPublicKeyPins("foo.example.test"));

  // The foo.example.test rule overrides the example1.test rule, so
  // bar.foo.example.test has no HPKP state.
  EXPECT_FALSE(state.HasPublicKeyPins("bar.foo.example.test"));
  EXPECT_FALSE(state.ShouldSSLErrorsBeFatal("bar.foo.example.test"));

  // Expire the foo.example.test rule.
  state.AddHPKP("foo.example.test", older, false, GetSampleSPKIHashes());

  // Now the base example.test rule applies to bar.foo.example.test.
  EXPECT_TRUE(state.HasPublicKeyPins("bar.foo.example.test"));
  EXPECT_TRUE(state.ShouldSSLErrorsBeFatal("bar.foo.example.test"));
}

TEST_F(TransportSecurityStateTest, FatalSSLErrors) {
  TransportSecurityState state;
  const base::Time current_time(base::Time::Now());
  const base::Time expiry = current_time + base::Seconds(1000);

  state.AddHSTS("example1.test", expiry, false);
  state.AddHPKP("example2.test", expiry, false, GetSampleSPKIHashes());

  // The presense of either HSTS or HPKP is enough to make SSL errors fatal.
  EXPECT_TRUE(state.ShouldSSLErrorsBeFatal("example1.test"));
  EXPECT_TRUE(state.ShouldSSLErrorsBeFatal("example2.test"));
}

// Tests that HPKP and HSTS state both expire. Also tests that expired entries
// are pruned.
//
// Setting `is_top_level_nav` true prevents the upgrade from being blocked by
// kHstsTopLevelNavigationsOnly.
TEST_F(TransportSecurityStateTest, Expiration) {
  TransportSecurityState state;
  const base::Time current_time(base::Time::Now());
  const base::Time expiry = current_time + base::Seconds(1000);
  const base::Time older = current_time - base::Seconds(1000);

  // Note: this test assumes that inserting an entry with an expiration time in
  // the past works and is pruned on query.
  state.AddHSTS("example1.test", older, false);
  EXPECT_TRUE(TransportSecurityState::STSStateIterator(state).HasNext());
  EXPECT_FALSE(
      state.ShouldUpgradeToSSL("example1.test", /*is_top_level_nav=*/true));
  // Querying |state| for a domain should flush out expired entries.
  EXPECT_FALSE(TransportSecurityState::STSStateIterator(state).HasNext());

  state.AddHPKP("example1.test", older, false, GetSampleSPKIHashes());
  EXPECT_TRUE(state.has_dynamic_pkp_state());
  EXPECT_FALSE(state.HasPublicKeyPins("example1.test"));
  // Querying |state| for a domain should flush out expired entries.
  EXPECT_FALSE(state.has_dynamic_pkp_state());

  state.AddHSTS("example1.test", older, false);
  state.AddHPKP("example1.test", older, false, GetSampleSPKIHashes());
  EXPECT_TRUE(TransportSecurityState::STSStateIterator(state).HasNext());
  EXPECT_TRUE(state.has_dynamic_pkp_state());
  EXPECT_FALSE(state.ShouldSSLErrorsBeFatal("example1.test"));
  // Querying |state| for a domain should flush out expired entries.
  EXPECT_FALSE(TransportSecurityState::STSStateIterator(state).HasNext());
  EXPECT_FALSE(state.has_dynamic_pkp_state());

  // Test that HSTS can outlive HPKP.
  state.AddHSTS("example1.test", expiry, false);
  state.AddHPKP("example1.test", older, false, GetSampleSPKIHashes());
  EXPECT_TRUE(
      state.ShouldUpgradeToSSL("example1.test", /*is_top_level_nav=*/true));
  EXPECT_FALSE(state.HasPublicKeyPins("example1.test"));

  // Test that HPKP can outlive HSTS.
  state.AddHSTS("example2.test", older, false);
  state.AddHPKP("example2.test", expiry, false, GetSampleSPKIHashes());
  EXPECT_FALSE(
      state.ShouldUpgradeToSSL("example2.test", /*is_top_level_nav=*/true));
  EXPECT_TRUE(state.HasPublicKeyPins("example2.test"));
}

// Tests that HPKP and HSTS state are queried independently for subdomain
// matches.
//
// Setting `is_top_level_nav` true prevents the upgrade from being blocked by
// kHstsTopLevelNavigationsOnly.
TEST_F(TransportSecurityStateTest, IndependentSubdomain) {
  TransportSecurityState state;
  const base::Time current_time(base::Time::Now());
  const base::Time expiry = current_time + base::Seconds(1000);

  state.AddHSTS("example1.test", expiry, true);
  state.AddHPKP("example1.test", expiry, false, GetSampleSPKIHashes());

  state.AddHSTS("example2.test", expiry, false);
  state.AddHPKP("example2.test", expiry, true, GetSampleSPKIHashes());

  EXPECT_TRUE(
      state.ShouldUpgradeToSSL("foo.example1.test", /*is_top_level_nav=*/true));
  EXPECT_FALSE(state.HasPublicKeyPins("foo.example1.test"));
  EXPECT_FALSE(
      state.ShouldUpgradeToSSL("foo.example2.test", /*is_top_level_nav=*/true));
  EXPECT_TRUE(state.HasPublicKeyPins("foo.example2.test"));
}

// Tests that HPKP and HSTS state are inserted and overridden independently.
//
// Setting `is_top_level_nav` true prevents the upgrade from being blocked by
// kHstsTopLevelNavigationsOnly.
TEST_F(TransportSecurityStateTest, IndependentInsertion) {
  TransportSecurityState state;
  const base::Time current_time(base::Time::Now());
  const base::Time expiry = current_time + base::Seconds(1000);

  // Place an includeSubdomains HSTS entry below a normal HPKP entry.
  state.AddHSTS("example1.test", expiry, true);
  state.AddHPKP("foo.example1.test", expiry, false, GetSampleSPKIHashes());

  EXPECT_TRUE(
      state.ShouldUpgradeToSSL("foo.example1.test", /*is_top_level_nav=*/true));
  EXPECT_TRUE(state.HasPublicKeyPins("foo.example1.test"));
  EXPECT_TRUE(
      state.ShouldUpgradeToSSL("example1.test", /*is_top_level_nav=*/true));
  EXPECT_FALSE(state.HasPublicKeyPins("example1.test"));

  // Drop the includeSubdomains from the HSTS entry.
  state.AddHSTS("example1.test", expiry, false);

  EXPECT_FALSE(
      state.ShouldUpgradeToSSL("foo.example1.test", /*is_top_level_nav=*/true));
  EXPECT_TRUE(state.HasPublicKeyPins("foo.example1.test"));

  // Place an includeSubdomains HPKP entry below a normal HSTS entry.
  state.AddHSTS("foo.example2.test", expiry, false);
  state.AddHPKP("example2.test", expiry, true, GetSampleSPKIHashes());

  EXPECT_TRUE(
      state.ShouldUpgradeToSSL("foo.example2.test", /*is_top_level_nav=*/true));
  EXPECT_TRUE(state.HasPublicKeyPins("foo.example2.test"));

  // Drop the includeSubdomains from the HSTS entry.
  state.AddHPKP("example2.test", expiry, false, GetSampleSPKIHashes());

  EXPECT_TRUE(
      state.ShouldUpgradeToSSL("foo.example2.test", /*is_top_level_nav=*/true));
  EXPECT_FALSE(state.HasPublicKeyPins("foo.example2.test"));
}

// Tests that GetDynamic[PKP|STS]State returns the correct data and that the
// states are not mixed together.
//
// Setting `is_top_level_nav` true prevents the upgrade from being blocked by
// kHstsTopLevelNavigationsOnly.
TEST_F(TransportSecurityStateTest, DynamicDomainState) {
  TransportSecurityState state;
  const base::Time current_time(base::Time::Now());
  const base::Time expiry1 = current_time + base::Seconds(1000);
  const base::Time expiry2 = current_time + base::Seconds(2000);

  state.AddHSTS("example.com", expiry1, true);
  state.AddHPKP("foo.example.com", expiry2, false, GetSampleSPKIHashes());

  TransportSecurityState::STSState sts_state;
  TransportSecurityState::PKPState pkp_state;
  ASSERT_TRUE(state.GetDynamicSTSState("foo.example.com", &sts_state));
  ASSERT_TRUE(state.GetDynamicPKPState("foo.example.com", &pkp_state));
  EXPECT_TRUE(sts_state.ShouldUpgradeToSSL());
  EXPECT_TRUE(pkp_state.HasPublicKeyPins());
  EXPECT_TRUE(sts_state.include_subdomains);
  EXPECT_FALSE(pkp_state.include_subdomains);
  EXPECT_EQ(expiry1, sts_state.expiry);
  EXPECT_EQ(expiry2, pkp_state.expiry);
  EXPECT_EQ("example.com", sts_state.domain);
  EXPECT_EQ("foo.example.com", pkp_state.domain);
}

// Tests that GetSSLUpgradeDecision() matches the result of ShouldUpgradeToSSL()
// and correctly identifies the source of the decision.
//
// Setting `is_top_level_nav` true prevents the upgrade from being blocked by
// kHstsTopLevelNavigationsOnly.
TEST_F(TransportSecurityStateTest, StaticOrDynamicSource) {
  TransportSecurityState state;
  SetTransportSecurityStateSourceForTesting(&test1::kHSTSSource);

  // Check preconditions of preloaded states.
  TransportSecurityState::STSState sts_state;
  ASSERT_TRUE(state.GetStaticSTSState("hsts.example.com", &sts_state));
  ASSERT_EQ(sts_state.upgrade_mode,
            TransportSecurityState::STSState::MODE_FORCE_HTTPS);
  ASSERT_TRUE(sts_state.include_subdomains);
  ASSERT_FALSE(state.GetStaticSTSState("dynamic.example.com", &sts_state));

  const base::Time current_time(base::Time::Now());
  const base::Time expiry = current_time + base::Seconds(1000);

  EXPECT_EQ(state.GetSSLUpgradeDecision("dynamic.example.com",
                                        /*is_top_level_nav=*/true),
            SSLUpgradeDecision::kNoUpgrade);
  EXPECT_FALSE(state.ShouldUpgradeToSSL("dynamic.example.com",
                                        /*is_top_level_nav=*/true));

  EXPECT_EQ(state.GetSSLUpgradeDecision("hsts.example.com",
                                        /*is_top_level_nav=*/true),
            SSLUpgradeDecision::kStaticUpgrade);
  EXPECT_TRUE(
      state.ShouldUpgradeToSSL("hsts.example.com", /*is_top_level_nav=*/true));

  state.AddHSTS("dynamic.example.com", expiry, false);
  EXPECT_EQ(state.GetSSLUpgradeDecision("dynamic.example.com",
                                        /*is_top_level_nav=*/true),
            SSLUpgradeDecision::kDynamicUpgrade);
  EXPECT_TRUE(state.ShouldUpgradeToSSL("dynamic.example.com",
                                       /*is_top_level_nav=*/true));

  // Dynamic state for a host that already has static state doesn't change the
  // decision.
  state.AddHSTS("subdomain.hsts.example.com", expiry, false);
  EXPECT_EQ(state.GetSSLUpgradeDecision("subdomain.hsts.example.com",
                                        /*is_top_level_nav=*/true),
            SSLUpgradeDecision::kStaticUpgrade);
  EXPECT_TRUE(state.ShouldUpgradeToSSL("subdomain.hsts.example.com",
                                       /*is_top_level_nav=*/true));
}

// Tests that new pins always override previous pins. This should be true for
// both pins at the same domain or includeSubdomains pins at a parent domain.
TEST_F(TransportSecurityStateTest, NewPinsOverride) {
  TransportSecurityState state;
  TransportSecurityState::PKPState pkp_state;
  const base::Time current_time(base::Time::Now());
  const base::Time expiry = current_time + base::Seconds(1000);
  HashValue hash1(HASH_VALUE_SHA256);
  std::ranges::fill(hash1.span(), 0x01);
  HashValue hash2(HASH_VALUE_SHA256);
  std::ranges::fill(hash2.span(), 0x02);
  HashValue hash3(HASH_VALUE_SHA256);
  std::ranges::fill(hash3.span(), 0x03);

  state.AddHPKP("example.com", expiry, true, HashValueVector(1, hash1));

  ASSERT_TRUE(state.GetDynamicPKPState("foo.example.com", &pkp_state));
  ASSERT_EQ(1u, pkp_state.spki_hashes.size());
  EXPECT_EQ(pkp_state.spki_hashes[0], hash1);

  state.AddHPKP("foo.example.com", expiry, false, HashValueVector(1, hash2));

  ASSERT_TRUE(state.GetDynamicPKPState("foo.example.com", &pkp_state));
  ASSERT_EQ(1u, pkp_state.spki_hashes.size());
  EXPECT_EQ(pkp_state.spki_hashes[0], hash2);

  state.AddHPKP("foo.example.com", expiry, false, HashValueVector(1, hash3));

  ASSERT_TRUE(state.GetDynamicPKPState("foo.example.com", &pkp_state));
  ASSERT_EQ(1u, pkp_state.spki_hashes.size());
  EXPECT_EQ(pkp_state.spki_hashes[0], hash3);
}

// Setting `is_top_level_nav` true prevents the upgrade from being blocked by
// kHstsTopLevelNavigationsOnly.
TEST_F(TransportSecurityStateTest, DeleteAllDynamicDataBetween) {
  TransportSecurityState state;
  const base::Time current_time(base::Time::Now());
  const base::Time expiry = current_time + base::Seconds(1000);
  const base::Time older = current_time - base::Seconds(1000);

  EXPECT_FALSE(
      state.ShouldUpgradeToSSL("example.com", /*is_top_level_nav=*/true));
  EXPECT_FALSE(state.HasPublicKeyPins("example.com"));
  bool include_subdomains = false;
  state.AddHSTS("example.com", expiry, include_subdomains);
  state.AddHPKP("example.com", expiry, include_subdomains,
                GetSampleSPKIHashes());

  state.DeleteAllDynamicDataBetween(expiry, base::Time::Max(),
                                    base::DoNothing());
  EXPECT_TRUE(
      state.ShouldUpgradeToSSL("example.com", /*is_top_level_nav=*/true));
  EXPECT_TRUE(state.HasPublicKeyPins("example.com"));

  state.DeleteAllDynamicDataBetween(older, current_time, base::DoNothing());
  EXPECT_TRUE(
      state.ShouldUpgradeToSSL("example.com", /*is_top_level_nav=*/true));
  EXPECT_TRUE(state.HasPublicKeyPins("example.com"));

  state.DeleteAllDynamicDataBetween(base::Time(), current_time,
                                    base::DoNothing());
  EXPECT_TRUE(
      state.ShouldUpgradeToSSL("example.com", /*is_top_level_nav=*/true));
  EXPECT_TRUE(state.HasPublicKeyPins("example.com"));

  state.DeleteAllDynamicDataBetween(older, base::Time::Max(),
                                    base::DoNothing());
  EXPECT_FALSE(
      state.ShouldUpgradeToSSL("example.com", /*is_top_level_nav=*/true));
  EXPECT_FALSE(state.HasPublicKeyPins("example.com"));

  // Dynamic data in |state| should be empty now.
  EXPECT_FALSE(TransportSecurityState::STSStateIterator(state).HasNext());
  EXPECT_FALSE(state.has_dynamic_pkp_state());
}

// Setting `is_top_level_nav` true prevents the upgrade from being blocked by
// kHstsTopLevelNavigationsOnly.
TEST_F(TransportSecurityStateTest, DeleteDynamicDataForHost) {
  TransportSecurityState state;
  const base::Time current_time(base::Time::Now());
  const base::Time expiry = current_time + base::Seconds(1000);
  bool include_subdomains = false;

  state.AddHSTS("example1.test", expiry, include_subdomains);
  state.AddHPKP("example1.test", expiry, include_subdomains,
                GetSampleSPKIHashes());

  EXPECT_TRUE(
      state.ShouldUpgradeToSSL("example1.test", /*is_top_level_nav=*/true));
  EXPECT_FALSE(
      state.ShouldUpgradeToSSL("example2.test", /*is_top_level_nav=*/true));
  EXPECT_TRUE(state.HasPublicKeyPins("example1.test"));
  EXPECT_FALSE(state.HasPublicKeyPins("example2.test"));

  EXPECT_TRUE(state.DeleteDynamicDataForHost("example1.test"));
  EXPECT_FALSE(
      state.ShouldUpgradeToSSL("example1.test", /*is_top_level_nav=*/true));
  EXPECT_FALSE(state.HasPublicKeyPins("example1.test"));
}

TEST_F(TransportSecurityStateTest, LongNames) {
  TransportSecurityState state;
  state.SetPinningListAlwaysTimelyForTesting(true);
  const char kLongName[] =
      "lookupByWaveIdHashAndWaveIdIdAndWaveIdDomainAndWaveletIdIdAnd"
      "WaveletIdDomainAndBlipBlipid";
  TransportSecurityState::STSState sts_state;
  TransportSecurityState::PKPState pkp_state;
  // Just checks that we don't hit a NOTREACHED
  EXPECT_FALSE(state.GetStaticSTSState(kLongName, &sts_state));
  EXPECT_FALSE(state.GetStaticPKPState(kLongName, &pkp_state));
  EXPECT_FALSE(state.GetDynamicSTSState(kLongName, &sts_state));
  EXPECT_FALSE(state.GetDynamicPKPState(kLongName, &pkp_state));
}

TEST_F(TransportSecurityStateTest, PinValidationWithoutRejectedCerts) {
  base::test::ScopedFeatureList scoped_feature_list_;
  scoped_feature_list_.InitAndEnableFeature(
      features::kStaticKeyPinningEnforcement);

  HashValueVector good_hashes = DeserializeHashes(kGoodPath);
  HashValueVector bad_hashes = DeserializeHashes(kBadPath);

  TransportSecurityState state;
  state.SetPinningListAlwaysTimelyForTesting(true);
  EnableStaticPins(&state);

  TransportSecurityState::PKPState pkp_state;
  EXPECT_TRUE(state.GetStaticPKPState("no-rejected-pins-pkp.preloaded.test",
                                      &pkp_state));
  EXPECT_TRUE(pkp_state.HasPublicKeyPins());

  EXPECT_TRUE(pkp_state.CheckPublicKeyPins(good_hashes));
  EXPECT_FALSE(pkp_state.CheckPublicKeyPins(bad_hashes));
}

// Simple test for the HSTS preload process. The trie (generated from
// transport_security_state_static_unittest1.json) contains 1 entry. Test that
// the lookup methods can find the entry and correctly decode the different
// preloaded states (HSTS and HPKP).
TEST_F(TransportSecurityStateTest, DecodePreloadedSingle) {
  base::test::ScopedFeatureList scoped_feature_list_;
  scoped_feature_list_.InitAndEnableFeature(
      features::kStaticKeyPinningEnforcement);
  SetTransportSecurityStateSourceForTesting(&test1::kHSTSSource);

  TransportSecurityState state;
  TransportSecurityStateTest::EnableStaticPins(&state);

  TransportSecurityState::STSState sts_state;
  TransportSecurityState::PKPState pkp_state;
  EXPECT_TRUE(
      GetStaticDomainState(&state, "hsts.example.com", &sts_state, &pkp_state));
  EXPECT_TRUE(sts_state.include_subdomains);
  EXPECT_EQ(TransportSecurityState::STSState::MODE_FORCE_HTTPS,
            sts_state.upgrade_mode);
  EXPECT_TRUE(pkp_state.include_subdomains);
  ASSERT_EQ(1u, pkp_state.spki_hashes.size());
  EXPECT_EQ(pkp_state.spki_hashes[0], GetSampleSPKIHash(0x1));
  ASSERT_EQ(1u, pkp_state.bad_spki_hashes.size());
  EXPECT_EQ(pkp_state.bad_spki_hashes[0], GetSampleSPKIHash(0x2));
}

// More advanced test for the HSTS preload process where the trie (generated
// from transport_security_state_static_unittest2.json) contains multiple
// entries with a common prefix. Test that the lookup methods can find all
// entries and correctly decode the different preloaded states (HSTS and HPKP)
// for each entry.
TEST_F(TransportSecurityStateTest, DecodePreloadedMultiplePrefix) {
  base::test::ScopedFeatureList scoped_feature_list_;
  scoped_feature_list_.InitAndEnableFeature(
      features::kStaticKeyPinningEnforcement);
  SetTransportSecurityStateSourceForTesting(&test2::kHSTSSource);

  TransportSecurityState state;
  TransportSecurityStateTest::EnableStaticPins(&state);

  TransportSecurityState::STSState sts_state;
  TransportSecurityState::PKPState pkp_state;

  EXPECT_TRUE(
      GetStaticDomainState(&state, "hsts.example.com", &sts_state, &pkp_state));
  EXPECT_FALSE(sts_state.include_subdomains);
  EXPECT_EQ(TransportSecurityState::STSState::MODE_FORCE_HTTPS,
            sts_state.upgrade_mode);
  EXPECT_TRUE(pkp_state == TransportSecurityState::PKPState());

  sts_state = TransportSecurityState::STSState();
  pkp_state = TransportSecurityState::PKPState();
  EXPECT_TRUE(
      GetStaticDomainState(&state, "hpkp.example.com", &sts_state, &pkp_state));
  EXPECT_TRUE(sts_state == TransportSecurityState::STSState());
  EXPECT_TRUE(pkp_state.include_subdomains);
  EXPECT_EQ(1U, pkp_state.spki_hashes.size());
  EXPECT_EQ(pkp_state.spki_hashes[0], GetSampleSPKIHash(0x1));
  EXPECT_EQ(0U, pkp_state.bad_spki_hashes.size());

  sts_state = TransportSecurityState::STSState();
  pkp_state = TransportSecurityState::PKPState();
  EXPECT_TRUE(
      GetStaticDomainState(&state, "mix.example.com", &sts_state, &pkp_state));
  EXPECT_FALSE(sts_state.include_subdomains);
  EXPECT_EQ(TransportSecurityState::STSState::MODE_FORCE_HTTPS,
            sts_state.upgrade_mode);
  EXPECT_TRUE(pkp_state.include_subdomains);
  EXPECT_EQ(1U, pkp_state.spki_hashes.size());
  EXPECT_EQ(pkp_state.spki_hashes[0], GetSampleSPKIHash(0x2));
  EXPECT_EQ(1U, pkp_state.bad_spki_hashes.size());
  EXPECT_EQ(pkp_state.bad_spki_hashes[0], GetSampleSPKIHash(0x1));
}

// More advanced test for the HSTS preload process where the trie (generated
// from transport_security_state_static_unittest3.json) contains a mix of
// entries. Some entries share a prefix with the prefix also having its own
// preloaded state while others share no prefix. This results in a trie with
// several different internal structures. Test that the lookup methods can find
// all entries and correctly decode the different preloaded states (HSTS and
// HPKP) for each entry.
TEST_F(TransportSecurityStateTest, DecodePreloadedMultipleMix) {
  base::test::ScopedFeatureList scoped_feature_list_;
  scoped_feature_list_.InitAndEnableFeature(
      features::kStaticKeyPinningEnforcement);
  SetTransportSecurityStateSourceForTesting(&test3::kHSTSSource);

  TransportSecurityState state;
  TransportSecurityStateTest::EnableStaticPins(&state);

  TransportSecurityState::STSState sts_state;
  TransportSecurityState::PKPState pkp_state;

  EXPECT_TRUE(
      GetStaticDomainState(&state, "example.com", &sts_state, &pkp_state));
  EXPECT_TRUE(sts_state.include_subdomains);
  EXPECT_EQ(TransportSecurityState::STSState::MODE_FORCE_HTTPS,
            sts_state.upgrade_mode);
  EXPECT_TRUE(pkp_state == TransportSecurityState::PKPState());

  sts_state = TransportSecurityState::STSState();
  pkp_state = TransportSecurityState::PKPState();
  EXPECT_TRUE(
      GetStaticDomainState(&state, "hpkp.example.com", &sts_state, &pkp_state));
  EXPECT_TRUE(sts_state == TransportSecurityState::STSState());
  EXPECT_TRUE(pkp_state.include_subdomains);
  EXPECT_EQ(1U, pkp_state.spki_hashes.size());
  EXPECT_EQ(pkp_state.spki_hashes[0], GetSampleSPKIHash(0x1));
  EXPECT_EQ(0U, pkp_state.bad_spki_hashes.size());

  sts_state = TransportSecurityState::STSState();
  pkp_state = TransportSecurityState::PKPState();
  EXPECT_TRUE(
      GetStaticDomainState(&state, "example.org", &sts_state, &pkp_state));
  EXPECT_FALSE(sts_state.include_subdomains);
  EXPECT_EQ(TransportSecurityState::STSState::MODE_FORCE_HTTPS,
            sts_state.upgrade_mode);
  EXPECT_TRUE(pkp_state == TransportSecurityState::PKPState());

  sts_state = TransportSecurityState::STSState();
  pkp_state = TransportSecurityState::PKPState();
  EXPECT_TRUE(
      GetStaticDomainState(&state, "badssl.com", &sts_state, &pkp_state));
  EXPECT_TRUE(sts_state == TransportSecurityState::STSState());
  EXPECT_TRUE(pkp_state.include_subdomains);
  EXPECT_EQ(1U, pkp_state.spki_hashes.size());
  EXPECT_EQ(pkp_state.spki_hashes[0], GetSampleSPKIHash(0x1));
  EXPECT_EQ(0U, pkp_state.bad_spki_hashes.size());

  sts_state = TransportSecurityState::STSState();
  pkp_state = TransportSecurityState::PKPState();
  EXPECT_TRUE(
      GetStaticDomainState(&state, "mix.badssl.com", &sts_state, &pkp_state));
  EXPECT_FALSE(sts_state.include_subdomains);
  EXPECT_EQ(TransportSecurityState::STSState::MODE_FORCE_HTTPS,
            sts_state.upgrade_mode);
  EXPECT_TRUE(pkp_state.include_subdomains);
  EXPECT_EQ(1U, pkp_state.spki_hashes.size());
  EXPECT_EQ(pkp_state.spki_hashes[0], GetSampleSPKIHash(0x2));
  EXPECT_EQ(1U, pkp_state.bad_spki_hashes.size());
  EXPECT_EQ(pkp_state.bad_spki_hashes[0], GetSampleSPKIHash(0x1));

  sts_state = TransportSecurityState::STSState();
  pkp_state = TransportSecurityState::PKPState();

  // This should be a simple entry in the context of
  // TrieWriter::IsSimpleEntry().
  EXPECT_TRUE(GetStaticDomainState(&state, "simple-entry.example.com",
                                   &sts_state, &pkp_state));
  EXPECT_TRUE(sts_state.include_subdomains);
  EXPECT_EQ(TransportSecurityState::STSState::MODE_FORCE_HTTPS,
            sts_state.upgrade_mode);
  EXPECT_TRUE(pkp_state == TransportSecurityState::PKPState());
}

// Setting `is_top_level_nav` true prevents the upgrade from being blocked by
// kHstsTopLevelNavigationsOnly.
TEST_F(TransportSecurityStateTest, HstsHostBypassList) {
  SetTransportSecurityStateSourceForTesting(&test_default::kHSTSSource);

  TransportSecurityState::STSState sts_state;
  TransportSecurityState::PKPState pkp_state;

  std::string preloaded_tld = "example";
  std::string subdomain = "sub.example";

  {
    TransportSecurityState state;
    // Check that "example" is preloaded with subdomains.
    EXPECT_TRUE(
        state.ShouldUpgradeToSSL(preloaded_tld, /*is_top_level_nav=*/true));
    EXPECT_TRUE(state.ShouldUpgradeToSSL(subdomain, /*is_top_level_nav=*/true));
  }

  {
    // Add "example" to the bypass list.
    TransportSecurityState state({preloaded_tld});
    EXPECT_FALSE(
        state.ShouldUpgradeToSSL(preloaded_tld, /*is_top_level_nav=*/true));
    // The preloaded entry should still apply to the subdomain.
    EXPECT_TRUE(state.ShouldUpgradeToSSL(subdomain, /*is_top_level_nav=*/true));
  }
}

// Tests that TransportSecurityState always consults the RequireCTDelegate,
// if supplied.
TEST_F(TransportSecurityStateTest, RequireCTConsultsDelegate) {
  using ::testing::_;
  using ::testing::Return;
  using CTRequirementLevel = RequireCTDelegate::CTRequirementLevel;

  // Dummy cert to use as the validation chain. The contents do not matter.
  scoped_refptr<X509Certificate> cert =
      ImportCertFromFile(GetTestCertsDirectory(), "expired_cert.pem");
  ASSERT_TRUE(cert);

  HashValueVector hashes;
  hashes.push_back(
      HashValue(X509Certificate::CalculateFingerprint256(cert->cert_buffer())));

  // If CT is required, then the requirements are not met if the CT policy
  // wasn't met, but are met if the policy was met or the build was out of
  // date.
  {
    TransportSecurityState state;
    const ct::CTRequirementsStatus original_status = state.CheckCTRequirements(
        "www.example.com", true, hashes, cert.get(),
        ct::CTPolicyCompliance::CT_POLICY_NOT_ENOUGH_SCTS);

    scoped_refptr<MockRequireCTDelegate> always_require_delegate =
        base::MakeRefCounted<MockRequireCTDelegate>();
    EXPECT_CALL(*always_require_delegate, IsCTRequiredForHost(_, _, _))
        .WillRepeatedly(Return(CTRequirementLevel::REQUIRED));
    state.SetRequireCTDelegate(always_require_delegate);
    EXPECT_EQ(ct::CTRequirementsStatus::CT_REQUIREMENTS_NOT_MET,
              state.CheckCTRequirements(
                  "www.example.com", true, hashes, cert.get(),
                  ct::CTPolicyCompliance::CT_POLICY_NOT_ENOUGH_SCTS));
    EXPECT_EQ(ct::CTRequirementsStatus::CT_REQUIREMENTS_NOT_MET,
              state.CheckCTRequirements(
                  "www.example.com", true, hashes, cert.get(),
                  ct::CTPolicyCompliance::CT_POLICY_NOT_DIVERSE_SCTS));
    EXPECT_EQ(ct::CTRequirementsStatus::CT_REQUIREMENTS_MET,
              state.CheckCTRequirements(
                  "www.example.com", true, hashes, cert.get(),
                  ct::CTPolicyCompliance::CT_POLICY_COMPLIES_VIA_SCTS));
    EXPECT_EQ(ct::CTRequirementsStatus::CT_REQUIREMENTS_MET,
              state.CheckCTRequirements(
                  "www.example.com", true, hashes, cert.get(),
                  ct::CTPolicyCompliance::CT_POLICY_BUILD_NOT_TIMELY));

    state.SetRequireCTDelegate(nullptr);
    EXPECT_EQ(original_status,
              state.CheckCTRequirements(
                  "www.example.com", true, hashes, cert.get(),
                  ct::CTPolicyCompliance::CT_POLICY_NOT_ENOUGH_SCTS));
  }

  // If CT is not required, then regardless of the CT state for the host,
  // it should indicate CT is not required.
  {
    TransportSecurityState state;
    const ct::CTRequirementsStatus original_status = state.CheckCTRequirements(
        "www.example.com", true, hashes, cert.get(),
        ct::CTPolicyCompliance::CT_POLICY_NOT_ENOUGH_SCTS);

    scoped_refptr<MockRequireCTDelegate> never_require_delegate =
        base::MakeRefCounted<MockRequireCTDelegate>();
    EXPECT_CALL(*never_require_delegate, IsCTRequiredForHost(_, _, _))
        .WillRepeatedly(Return(CTRequirementLevel::NOT_REQUIRED));
    state.SetRequireCTDelegate(never_require_delegate);
    EXPECT_EQ(ct::CTRequirementsStatus::CT_NOT_REQUIRED,
              state.CheckCTRequirements(
                  "www.example.com", true, hashes, cert.get(),
                  ct::CTPolicyCompliance::CT_POLICY_NOT_ENOUGH_SCTS));
    EXPECT_EQ(ct::CTRequirementsStatus::CT_NOT_REQUIRED,
              state.CheckCTRequirements(
                  "www.example.com", true, hashes, cert.get(),
                  ct::CTPolicyCompliance::CT_POLICY_NOT_DIVERSE_SCTS));

    state.SetRequireCTDelegate(nullptr);
    EXPECT_EQ(original_status,
              state.CheckCTRequirements(
                  "www.example.com", true, hashes, cert.get(),
                  ct::CTPolicyCompliance::CT_POLICY_NOT_ENOUGH_SCTS));
  }
}

// Tests that the emergency disable flags cause CT to stop being required
// regardless of host or delegate status.
TEST(CTEmergencyDisableTest, CTEmergencyDisable) {
  using ::testing::_;
  using ::testing::Return;
  using CTRequirementLevel = RequireCTDelegate::CTRequirementLevel;

  // Dummy cert to use as the validation chain. The contents do not matter.
  scoped_refptr<X509Certificate> cert =
      ImportCertFromFile(GetTestCertsDirectory(), "expired_cert.pem");
  ASSERT_TRUE(cert);

  HashValueVector hashes;
  hashes.push_back(
      HashValue(X509Certificate::CalculateFingerprint256(cert->cert_buffer())));

  TransportSecurityState state;
  state.SetCTEmergencyDisabled(true);

  scoped_refptr<MockRequireCTDelegate> always_require_delegate =
      base::MakeRefCounted<MockRequireCTDelegate>();
  EXPECT_CALL(*always_require_delegate, IsCTRequiredForHost(_, _, _))
      .WillRepeatedly(Return(CTRequirementLevel::REQUIRED));
  state.SetRequireCTDelegate(always_require_delegate);
  EXPECT_EQ(ct::CTRequirementsStatus::CT_NOT_REQUIRED,
            state.CheckCTRequirements(
                "www.example.com", true, hashes, cert.get(),
                ct::CTPolicyCompliance::CT_POLICY_NOT_ENOUGH_SCTS));
  EXPECT_EQ(ct::CTRequirementsStatus::CT_NOT_REQUIRED,
            state.CheckCTRequirements(
                "www.example.com", true, hashes, cert.get(),
                ct::CTPolicyCompliance::CT_POLICY_NOT_DIVERSE_SCTS));
  EXPECT_EQ(ct::CTRequirementsStatus::CT_NOT_REQUIRED,
            state.CheckCTRequirements(
                "www.example.com", true, hashes, cert.get(),
                ct::CTPolicyCompliance::CT_POLICY_COMPLIES_VIA_SCTS));
  EXPECT_EQ(ct::CTRequirementsStatus::CT_NOT_REQUIRED,
            state.CheckCTRequirements(
                "www.example.com", true, hashes, cert.get(),
                ct::CTPolicyCompliance::CT_POLICY_BUILD_NOT_TIMELY));

  state.SetRequireCTDelegate(nullptr);
  EXPECT_EQ(ct::CTRequirementsStatus::CT_NOT_REQUIRED,
            state.CheckCTRequirements(
                "www.example.com", true, hashes, cert.get(),
                ct::CTPolicyCompliance::CT_POLICY_NOT_ENOUGH_SCTS));
}

#if BUILDFLAG(INCLUDE_TRANSPORT_SECURITY_STATE_PRELOAD_LIST)

class TransportSecurityStateStaticTest : public TransportSecurityStateTest {
 public:
  TransportSecurityStateStaticTest() {
    SetTransportSecurityStateSourceForTesting(nullptr);
  }
};

static bool StaticShouldRedirect(const char* hostname) {
  TransportSecurityState state;
  TransportSecurityState::STSState sts_state;
  return state.GetStaticSTSState(hostname, &sts_state) &&
         sts_state.ShouldUpgradeToSSL();
}

static bool HasStaticState(const char* hostname) {
  TransportSecurityState state;
  state.SetPinningListAlwaysTimelyForTesting(true);
  TransportSecurityState::STSState sts_state;
  TransportSecurityState::PKPState pkp_state;
  return state.GetStaticSTSState(hostname, &sts_state) ||
         state.GetStaticPKPState(hostname, &pkp_state);
}

static bool HasStaticPublicKeyPins(const char* hostname) {
  TransportSecurityState state;
  state.SetPinningListAlwaysTimelyForTesting(true);
  TransportSecurityStateTest::EnableStaticPins(&state);
  TransportSecurityState::PKPState pkp_state;
  if (!state.GetStaticPKPState(hostname, &pkp_state))
    return false;

  return pkp_state.HasPublicKeyPins();
}

static bool OnlyPinningInStaticState(const char* hostname) {
  TransportSecurityState state;
  TransportSecurityStateTest::EnableStaticPins(&state);
  TransportSecurityState::STSState sts_state;
  TransportSecurityState::PKPState pkp_state;
  return HasStaticPublicKeyPins(hostname) && !StaticShouldRedirect(hostname);
}

TEST_F(TransportSecurityStateStaticTest, EnableStaticPins) {
  base::test::ScopedFeatureList scoped_feature_list_;
  scoped_feature_list_.InitAndEnableFeature(
      features::kStaticKeyPinningEnforcement);
  TransportSecurityState state;
  state.SetPinningListAlwaysTimelyForTesting(true);
  TransportSecurityState::PKPState pkp_state;

  EnableStaticPins(&state);

  EXPECT_TRUE(state.GetStaticPKPState("chrome.google.com", &pkp_state));
  EXPECT_FALSE(pkp_state.spki_hashes.empty());
}

TEST_F(TransportSecurityStateStaticTest, DisableStaticPins) {
  TransportSecurityState state;
  state.SetPinningListAlwaysTimelyForTesting(true);
  TransportSecurityState::PKPState pkp_state;

  DisableStaticPins(&state);
  EXPECT_FALSE(state.GetStaticPKPState("chrome.google.com", &pkp_state));
  EXPECT_TRUE(pkp_state.spki_hashes.empty());
}

TEST_F(TransportSecurityStateStaticTest, IsPreloaded) {
  const std::string paypal = "paypal.com";
  const std::string www_paypal = "www.paypal.com";
  const std::string foo_paypal = "foo.paypal.com";
  const std::string a_www_paypal = "a.www.paypal.com";
  const std::string abc_paypal = "a.b.c.paypal.com";
  const std::string example = "example.com";
  const std::string aypal = "aypal.com";
  const std::string google = "google";
  const std::string www_google = "www.google";
  const std::string foo = "foo";
  const std::string bank = "example.bank";
  const std::string insurance = "sub.example.insurance";

  TransportSecurityState state;
  TransportSecurityState::STSState sts_state;
  TransportSecurityState::PKPState pkp_state;

  EXPECT_TRUE(GetStaticDomainState(&state, paypal, &sts_state, &pkp_state));
  EXPECT_TRUE(GetStaticDomainState(&state, www_paypal, &sts_state, &pkp_state));
  EXPECT_FALSE(sts_state.include_subdomains);
  EXPECT_TRUE(GetStaticDomainState(&state, google, &sts_state, &pkp_state));
  EXPECT_TRUE(GetStaticDomainState(&state, www_google, &sts_state, &pkp_state));
  EXPECT_TRUE(GetStaticDomainState(&state, foo, &sts_state, &pkp_state));
  EXPECT_TRUE(GetStaticDomainState(&state, bank, &sts_state, &pkp_state));
  EXPECT_TRUE(sts_state.include_subdomains);
  EXPECT_TRUE(GetStaticDomainState(&state, insurance, &sts_state, &pkp_state));
  EXPECT_TRUE(sts_state.include_subdomains);
  EXPECT_FALSE(
      GetStaticDomainState(&state, a_www_paypal, &sts_state, &pkp_state));
  EXPECT_FALSE(
      GetStaticDomainState(&state, abc_paypal, &sts_state, &pkp_state));
  EXPECT_FALSE(GetStaticDomainState(&state, example, &sts_state, &pkp_state));
  EXPECT_FALSE(GetStaticDomainState(&state, aypal, &sts_state, &pkp_state));
}

TEST_F(TransportSecurityStateStaticTest, PreloadedDomainSet) {
  base::test::ScopedFeatureList scoped_feature_list_;
  scoped_feature_list_.InitAndEnableFeature(
      features::kStaticKeyPinningEnforcement);
  TransportSecurityState state;
  EnableStaticPins(&state);
  TransportSecurityState::STSState sts_state;
  TransportSecurityState::PKPState pkp_state;

  // The domain wasn't being set, leading to a blank string in the
  // chrome://net-internals/#hsts UI. So test that.
  EXPECT_TRUE(state.GetStaticPKPState("market.android.com", &pkp_state));
  EXPECT_TRUE(state.GetStaticSTSState("market.android.com", &sts_state));
  EXPECT_EQ(sts_state.domain, "market.android.com");
  EXPECT_EQ(pkp_state.domain, "market.android.com");
  EXPECT_TRUE(state.GetStaticPKPState("sub.market.android.com", &pkp_state));
  EXPECT_TRUE(state.GetStaticSTSState("sub.market.android.com", &sts_state));
  EXPECT_EQ(sts_state.domain, "market.android.com");
  EXPECT_EQ(pkp_state.domain, "market.android.com");
}

TEST_F(TransportSecurityStateStaticTest, Preloaded) {
  base::test::ScopedFeatureList scoped_feature_list_;
  scoped_feature_list_.InitAndEnableFeature(
      features::kStaticKeyPinningEnforcement);
  TransportSecurityState state;
  EnableStaticPins(&state);
  TransportSecurityState::STSState sts_state;
  TransportSecurityState::PKPState pkp_state;

  // We do more extensive checks for the first domain.
  EXPECT_TRUE(state.GetStaticSTSState("www.paypal.com", &sts_state));
  EXPECT_FALSE(state.GetStaticPKPState("www.paypal.com", &pkp_state));
  EXPECT_EQ(sts_state.upgrade_mode,
            TransportSecurityState::STSState::MODE_FORCE_HTTPS);
  EXPECT_FALSE(sts_state.include_subdomains);
  EXPECT_FALSE(pkp_state.include_subdomains);

  EXPECT_TRUE(HasStaticState("paypal.com"));
  EXPECT_FALSE(HasStaticState("www2.paypal.com"));

  // Google hosts:

  EXPECT_TRUE(StaticShouldRedirect("chrome.google.com"));
  EXPECT_TRUE(StaticShouldRedirect("checkout.google.com"));
  EXPECT_TRUE(StaticShouldRedirect("wallet.google.com"));
  EXPECT_TRUE(StaticShouldRedirect("docs.google.com"));
  EXPECT_TRUE(StaticShouldRedirect("sites.google.com"));
  EXPECT_TRUE(StaticShouldRedirect("drive.google.com"));
  EXPECT_TRUE(StaticShouldRedirect("spreadsheets.google.com"));
  EXPECT_TRUE(StaticShouldRedirect("appengine.google.com"));
  EXPECT_TRUE(StaticShouldRedirect("market.android.com"));
  EXPECT_TRUE(StaticShouldRedirect("encrypted.google.com"));
  EXPECT_TRUE(StaticShouldRedirect("accounts.google.com"));
  EXPECT_TRUE(StaticShouldRedirect("profiles.google.com"));
  EXPECT_TRUE(StaticShouldRedirect("mail.google.com"));
  EXPECT_TRUE(StaticShouldRedirect("chatenabled.mail.google.com"));
  EXPECT_TRUE(StaticShouldRedirect("talkgadget.google.com"));
  EXPECT_TRUE(StaticShouldRedirect("hostedtalkgadget.google.com"));
  EXPECT_TRUE(StaticShouldRedirect("talk.google.com"));
  EXPECT_TRUE(StaticShouldRedirect("plus.google.com"));
  EXPECT_TRUE(StaticShouldRedirect("groups.google.com"));
  EXPECT_TRUE(StaticShouldRedirect("apis.google.com"));
  EXPECT_TRUE(StaticShouldRedirect("oauthaccountmanager.googleapis.com"));
  EXPECT_TRUE(StaticShouldRedirect("passwordsleakcheck-pa.googleapis.com"));
  EXPECT_TRUE(StaticShouldRedirect("ssl.google-analytics.com"));
  EXPECT_TRUE(StaticShouldRedirect("google"));
  EXPECT_TRUE(StaticShouldRedirect("foo.google"));
  EXPECT_TRUE(StaticShouldRedirect("foo"));
  EXPECT_TRUE(StaticShouldRedirect("domaintest.foo"));
  EXPECT_TRUE(StaticShouldRedirect("gmail.com"));
  EXPECT_TRUE(StaticShouldRedirect("www.gmail.com"));
  EXPECT_TRUE(StaticShouldRedirect("googlemail.com"));
  EXPECT_TRUE(StaticShouldRedirect("www.googlemail.com"));
  EXPECT_TRUE(StaticShouldRedirect("googleplex.com"));
  EXPECT_TRUE(StaticShouldRedirect("www.googleplex.com"));
  EXPECT_TRUE(StaticShouldRedirect("www.google-analytics.com"));
  EXPECT_TRUE(StaticShouldRedirect("www.youtube.com"));
  EXPECT_TRUE(StaticShouldRedirect("youtube.com"));

  // These domains used to be only HSTS when SNI was available.
  EXPECT_TRUE(state.GetStaticSTSState("gmail.com", &sts_state));
  EXPECT_TRUE(state.GetStaticPKPState("gmail.com", &pkp_state));
  EXPECT_TRUE(state.GetStaticSTSState("www.gmail.com", &sts_state));
  EXPECT_TRUE(state.GetStaticPKPState("www.gmail.com", &pkp_state));
  EXPECT_TRUE(state.GetStaticSTSState("googlemail.com", &sts_state));
  EXPECT_TRUE(state.GetStaticPKPState("googlemail.com", &pkp_state));
  EXPECT_TRUE(state.GetStaticSTSState("www.googlemail.com", &sts_state));
  EXPECT_TRUE(state.GetStaticPKPState("www.googlemail.com", &pkp_state));

  // fi.g.co should not force HTTPS because there are still HTTP-only services
  // on it.
  EXPECT_FALSE(StaticShouldRedirect("fi.g.co"));

  // Other hosts:

  EXPECT_TRUE(StaticShouldRedirect("aladdinschools.appspot.com"));

  EXPECT_TRUE(StaticShouldRedirect("ottospora.nl"));
  EXPECT_TRUE(StaticShouldRedirect("www.ottospora.nl"));

  EXPECT_TRUE(StaticShouldRedirect("www.paycheckrecords.com"));

  EXPECT_TRUE(StaticShouldRedirect("lastpass.com"));
  EXPECT_TRUE(StaticShouldRedirect("www.lastpass.com"));
  EXPECT_FALSE(HasStaticState("blog.lastpass.com"));

  EXPECT_TRUE(StaticShouldRedirect("keyerror.com"));
  EXPECT_TRUE(StaticShouldRedirect("www.keyerror.com"));

  EXPECT_TRUE(StaticShouldRedirect("entropia.de"));
  EXPECT_TRUE(StaticShouldRedirect("www.entropia.de"));
  EXPECT_FALSE(HasStaticState("foo.entropia.de"));

  EXPECT_TRUE(StaticShouldRedirect("www.elanex.biz"));
  EXPECT_FALSE(HasStaticState("elanex.biz"));
  EXPECT_FALSE(HasStaticState("foo.elanex.biz"));

  EXPECT_TRUE(StaticShouldRedirect("sunshinepress.org"));
  EXPECT_TRUE(StaticShouldRedirect("www.sunshinepress.org"));
  EXPECT_TRUE(StaticShouldRedirect("a.b.sunshinepress.org"));

  EXPECT_TRUE(StaticShouldRedirect("www.noisebridge.net"));
  EXPECT_FALSE(HasStaticState("noisebridge.net"));
  EXPECT_FALSE(HasStaticState("foo.noisebridge.net"));

  EXPECT_TRUE(StaticShouldRedirect("neg9.org"));
  EXPECT_FALSE(HasStaticState("www.neg9.org"));

  EXPECT_TRUE(StaticShouldRedirect("riseup.net"));
  EXPECT_TRUE(StaticShouldRedirect("foo.riseup.net"));

  EXPECT_TRUE(StaticShouldRedirect("factor.cc"));
  EXPECT_FALSE(HasStaticState("www.factor.cc"));

  EXPECT_TRUE(StaticShouldRedirect("members.mayfirst.org"));
  EXPECT_TRUE(StaticShouldRedirect("support.mayfirst.org"));
  EXPECT_TRUE(StaticShouldRedirect("id.mayfirst.org"));
  EXPECT_TRUE(StaticShouldRedirect("lists.mayfirst.org"));
  EXPECT_FALSE(HasStaticState("www.mayfirst.org"));

  EXPECT_TRUE(StaticShouldRedirect("romab.com"));
  EXPECT_TRUE(StaticShouldRedirect("www.romab.com"));
  EXPECT_TRUE(StaticShouldRedirect("foo.romab.com"));

  EXPECT_TRUE(StaticShouldRedirect("logentries.com"));
  EXPECT_TRUE(StaticShouldRedirect("www.logentries.com"));
  EXPECT_FALSE(HasStaticState("foo.logentries.com"));

  EXPECT_TRUE(StaticShouldRedirect("stripe.com"));
  EXPECT_TRUE(StaticShouldRedirect("foo.stripe.com"));

  EXPECT_TRUE(StaticShouldRedirect("cloudsecurityalliance.org"));
  EXPECT_TRUE(StaticShouldRedirect("foo.cloudsecurityalliance.org"));

  EXPECT_TRUE(StaticShouldRedirect("login.sapo.pt"));
  EXPECT_TRUE(StaticShouldRedirect("foo.login.sapo.pt"));

  EXPECT_TRUE(StaticShouldRedirect("mattmccutchen.net"));
  EXPECT_TRUE(StaticShouldRedirect("foo.mattmccutchen.net"));

  EXPECT_TRUE(StaticShouldRedirect("betnet.fr"));
  EXPECT_TRUE(StaticShouldRedirect("foo.betnet.fr"));

  EXPECT_TRUE(StaticShouldRedirect("uprotect.it"));
  EXPECT_TRUE(StaticShouldRedirect("foo.uprotect.it"));

  EXPECT_TRUE(StaticShouldRedirect("cert.se"));
  EXPECT_TRUE(StaticShouldRedirect("foo.cert.se"));

  EXPECT_TRUE(StaticShouldRedirect("crypto.is"));
  EXPECT_TRUE(StaticShouldRedirect("foo.crypto.is"));

  EXPECT_TRUE(StaticShouldRedirect("simon.butcher.name"));
  EXPECT_TRUE(StaticShouldRedirect("foo.simon.butcher.name"));

  EXPECT_TRUE(StaticShouldRedirect("linx.net"));
  EXPECT_TRUE(StaticShouldRedirect("foo.linx.net"));

  EXPECT_TRUE(StaticShouldRedirect("dropcam.com"));
  EXPECT_TRUE(StaticShouldRedirect("www.dropcam.com"));
  EXPECT_FALSE(HasStaticState("foo.dropcam.com"));

  EXPECT_TRUE(StaticShouldRedirect("ebanking.indovinabank.com.vn"));
  EXPECT_TRUE(StaticShouldRedirect("foo.ebanking.indovinabank.com.vn"));

  EXPECT_TRUE(StaticShouldRedirect("epoxate.com"));
  EXPECT_FALSE(HasStaticState("foo.epoxate.com"));

  EXPECT_TRUE(StaticShouldRedirect("www.moneybookers.com"));
  EXPECT_FALSE(HasStaticState("moneybookers.com"));

  EXPECT_TRUE(StaticShouldRedirect("ledgerscope.net"));
  EXPECT_TRUE(StaticShouldRedirect("www.ledgerscope.net"));
  EXPECT_FALSE(HasStaticState("status.ledgerscope.net"));

  EXPECT_TRUE(StaticShouldRedirect("foo.app.recurly.com"));
  EXPECT_TRUE(StaticShouldRedirect("foo.api.recurly.com"));

  EXPECT_TRUE(StaticShouldRedirect("greplin.com"));
  EXPECT_TRUE(StaticShouldRedirect("www.greplin.com"));
  EXPECT_FALSE(HasStaticState("foo.greplin.com"));

  EXPECT_TRUE(StaticShouldRedirect("luneta.nearbuysystems.com"));
  EXPECT_TRUE(StaticShouldRedirect("foo.luneta.nearbuysystems.com"));

  EXPECT_TRUE(StaticShouldRedirect("ubertt.org"));
  EXPECT_TRUE(StaticShouldRedirect("foo.ubertt.org"));

  EXPECT_TRUE(StaticShouldRedirect("pixi.me"));
  EXPECT_TRUE(StaticShouldRedirect("www.pixi.me"));

  EXPECT_TRUE(StaticShouldRedirect("grepular.com"));
  EXPECT_TRUE(StaticShouldRedirect("www.grepular.com"));

  EXPECT_TRUE(StaticShouldRedirect("mydigipass.com"));
  EXPECT_FALSE(StaticShouldRedirect("foo.mydigipass.com"));
  EXPECT_TRUE(StaticShouldRedirect("www.mydigipass.com"));
  EXPECT_FALSE(StaticShouldRedirect("foo.www.mydigipass.com"));
  EXPECT_TRUE(StaticShouldRedirect("developer.mydigipass.com"));
  EXPECT_FALSE(StaticShouldRedirect("foo.developer.mydigipass.com"));
  EXPECT_TRUE(StaticShouldRedirect("www.developer.mydigipass.com"));
  EXPECT_FALSE(StaticShouldRedirect("foo.www.developer.mydigipass.com"));
  EXPECT_TRUE(StaticShouldRedirect("sandbox.mydigipass.com"));
  EXPECT_FALSE(StaticShouldRedirect("foo.sandbox.mydigipass.com"));
  EXPECT_TRUE(StaticShouldRedirect("www.sandbox.mydigipass.com"));
  EXPECT_FALSE(StaticShouldRedirect("foo.www.sandbox.mydigipass.com"));

  EXPECT_TRUE(StaticShouldRedirect("bigshinylock.minazo.net"));
  EXPECT_TRUE(StaticShouldRedirect("foo.bigshinylock.minazo.net"));

  EXPECT_TRUE(StaticShouldRedirect("crate.io"));
  EXPECT_TRUE(StaticShouldRedirect("foo.crate.io"));

  EXPECT_TRUE(StaticShouldRedirect("sub.bank"));
  EXPECT_TRUE(StaticShouldRedirect("sub.insurance"));
}

TEST_F(TransportSecurityStateStaticTest, PreloadedPins) {
  base::test::ScopedFeatureList scoped_feature_list_;
  scoped_feature_list_.InitAndEnableFeature(
      features::kStaticKeyPinningEnforcement);
  TransportSecurityState state;
  EnableStaticPins(&state);
  TransportSecurityState::STSState sts_state;
  TransportSecurityState::PKPState pkp_state;

  // We do more extensive checks for the first domain.
  EXPECT_TRUE(state.GetStaticSTSState("www.paypal.com", &sts_state));
  EXPECT_FALSE(state.GetStaticPKPState("www.paypal.com", &pkp_state));
  EXPECT_EQ(sts_state.upgrade_mode,
            TransportSecurityState::STSState::MODE_FORCE_HTTPS);
  EXPECT_FALSE(sts_state.include_subdomains);
  EXPECT_FALSE(pkp_state.include_subdomains);

  EXPECT_TRUE(OnlyPinningInStaticState("www.google.com"));
  EXPECT_TRUE(OnlyPinningInStaticState("foo.google.com"));
  EXPECT_TRUE(OnlyPinningInStaticState("google.com"));
  EXPECT_TRUE(OnlyPinningInStaticState("i.ytimg.com"));
  EXPECT_TRUE(OnlyPinningInStaticState("ytimg.com"));
  EXPECT_TRUE(OnlyPinningInStaticState("googleusercontent.com"));
  EXPECT_TRUE(OnlyPinningInStaticState("www.googleusercontent.com"));
  EXPECT_TRUE(OnlyPinningInStaticState("googleapis.com"));
  EXPECT_TRUE(OnlyPinningInStaticState("googleadservices.com"));
  EXPECT_TRUE(OnlyPinningInStaticState("googlecode.com"));
  EXPECT_TRUE(OnlyPinningInStaticState("appspot.com"));
  EXPECT_TRUE(OnlyPinningInStaticState("googlesyndication.com"));
  EXPECT_TRUE(OnlyPinningInStaticState("doubleclick.net"));
  EXPECT_TRUE(OnlyPinningInStaticState("googlegroups.com"));

  // Facebook has pinning and hsts on facebook.com, but only pinning on
  // subdomains.
  EXPECT_TRUE(state.GetStaticPKPState("facebook.com", &pkp_state));
  EXPECT_FALSE(pkp_state.spki_hashes.empty());
  EXPECT_TRUE(StaticShouldRedirect("facebook.com"));

  EXPECT_TRUE(state.GetStaticPKPState("foo.facebook.com", &pkp_state));
  EXPECT_FALSE(pkp_state.spki_hashes.empty());
  EXPECT_FALSE(StaticShouldRedirect("foo.facebook.com"));

  // www.facebook.com and subdomains have both pinning and hsts.
  EXPECT_TRUE(state.GetStaticPKPState("www.facebook.com", &pkp_state));
  EXPECT_FALSE(pkp_state.spki_hashes.empty());
  EXPECT_TRUE(StaticShouldRedirect("www.facebook.com"));

  EXPECT_TRUE(state.GetStaticPKPState("foo.www.facebook.com", &pkp_state));
  EXPECT_FALSE(pkp_state.spki_hashes.empty());
  EXPECT_TRUE(StaticShouldRedirect("foo.www.facebook.com"));
}

TEST_F(TransportSecurityStateStaticTest, BuiltinCertPins) {
  base::test::ScopedFeatureList scoped_feature_list_;
  scoped_feature_list_.InitAndEnableFeature(
      features::kStaticKeyPinningEnforcement);
  TransportSecurityState state;
  EnableStaticPins(&state);
  TransportSecurityState::PKPState pkp_state;

  EXPECT_TRUE(state.GetStaticPKPState("chrome.google.com", &pkp_state));
  EXPECT_TRUE(HasStaticPublicKeyPins("chrome.google.com"));

  HashValueVector hashes;
  // Checks that a built-in list does exist.
  EXPECT_FALSE(pkp_state.CheckPublicKeyPins(hashes));
  EXPECT_FALSE(HasStaticPublicKeyPins("www.paypal.com"));

  EXPECT_TRUE(HasStaticPublicKeyPins("docs.google.com"));
  EXPECT_TRUE(HasStaticPublicKeyPins("1.docs.google.com"));
  EXPECT_TRUE(HasStaticPublicKeyPins("sites.google.com"));
  EXPECT_TRUE(HasStaticPublicKeyPins("drive.google.com"));
  EXPECT_TRUE(HasStaticPublicKeyPins("spreadsheets.google.com"));
  EXPECT_TRUE(HasStaticPublicKeyPins("wallet.google.com"));
  EXPECT_TRUE(HasStaticPublicKeyPins("checkout.google.com"));
  EXPECT_TRUE(HasStaticPublicKeyPins("appengine.google.com"));
  EXPECT_TRUE(HasStaticPublicKeyPins("market.android.com"));
  EXPECT_TRUE(HasStaticPublicKeyPins("encrypted.google.com"));
  EXPECT_TRUE(HasStaticPublicKeyPins("accounts.google.com"));
  EXPECT_TRUE(HasStaticPublicKeyPins("profiles.google.com"));
  EXPECT_TRUE(HasStaticPublicKeyPins("mail.google.com"));
  EXPECT_TRUE(HasStaticPublicKeyPins("chatenabled.mail.google.com"));
  EXPECT_TRUE(HasStaticPublicKeyPins("talkgadget.google.com"));
  EXPECT_TRUE(HasStaticPublicKeyPins("hostedtalkgadget.google.com"));
  EXPECT_TRUE(HasStaticPublicKeyPins("talk.google.com"));
  EXPECT_TRUE(HasStaticPublicKeyPins("plus.google.com"));
  EXPECT_TRUE(HasStaticPublicKeyPins("groups.google.com"));
  EXPECT_TRUE(HasStaticPublicKeyPins("apis.google.com"));
  EXPECT_TRUE(HasStaticPublicKeyPins("www.google-analytics.com"));
  EXPECT_TRUE(HasStaticPublicKeyPins("www.youtube.com"));
  EXPECT_TRUE(HasStaticPublicKeyPins("youtube.com"));

  EXPECT_TRUE(HasStaticPublicKeyPins("ssl.gstatic.com"));
  EXPECT_TRUE(HasStaticPublicKeyPins("gstatic.com"));
  EXPECT_TRUE(HasStaticPublicKeyPins("www.gstatic.com"));
  EXPECT_TRUE(HasStaticPublicKeyPins("ssl.google-analytics.com"));
  EXPECT_TRUE(HasStaticPublicKeyPins("www.googleplex.com"));
}

TEST_F(TransportSecurityStateStaticTest, OptionalHSTSCertPins) {
  base::test::ScopedFeatureList scoped_feature_list_;
  scoped_feature_list_.InitAndEnableFeature(
      features::kStaticKeyPinningEnforcement);
  TransportSecurityState state;
  EnableStaticPins(&state);

  EXPECT_TRUE(HasStaticPublicKeyPins("google.com"));
  EXPECT_TRUE(HasStaticPublicKeyPins("www.google.com"));
  EXPECT_TRUE(HasStaticPublicKeyPins("mail-attachment.googleusercontent.com"));
  EXPECT_TRUE(HasStaticPublicKeyPins("www.youtube.com"));
  EXPECT_TRUE(HasStaticPublicKeyPins("i.ytimg.com"));
  EXPECT_TRUE(HasStaticPublicKeyPins("googleapis.com"));
  EXPECT_TRUE(HasStaticPublicKeyPins("ajax.googleapis.com"));
  EXPECT_TRUE(HasStaticPublicKeyPins("googleadservices.com"));
  EXPECT_TRUE(HasStaticPublicKeyPins("pagead2.googleadservices.com"));
  EXPECT_TRUE(HasStaticPublicKeyPins("googlecode.com"));
  EXPECT_TRUE(HasStaticPublicKeyPins("kibbles.googlecode.com"));
  EXPECT_TRUE(HasStaticPublicKeyPins("appspot.com"));
  EXPECT_TRUE(HasStaticPublicKeyPins("googlesyndication.com"));
  EXPECT_TRUE(HasStaticPublicKeyPins("doubleclick.net"));
  EXPECT_TRUE(HasStaticPublicKeyPins("ad.doubleclick.net"));
  EXPECT_TRUE(HasStaticPublicKeyPins("redirector.gvt1.com"));
  EXPECT_TRUE(HasStaticPublicKeyPins("a.googlegroups.com"));
}

// Setting `is_top_level_nav` true prevents the upgrade from being blocked by
// kHstsTopLevelNavigationsOnly.
TEST_F(TransportSecurityStateStaticTest, OverrideBuiltins) {
  base::test::ScopedFeatureList scoped_feature_list_;
  scoped_feature_list_.InitAndEnableFeature(
      features::kStaticKeyPinningEnforcement);
  EXPECT_TRUE(HasStaticPublicKeyPins("google.com"));
  EXPECT_FALSE(StaticShouldRedirect("google.com"));
  EXPECT_FALSE(StaticShouldRedirect("www.google.com"));

  TransportSecurityState state;
  state.SetPinningListAlwaysTimelyForTesting(true);

  const base::Time current_time(base::Time::Now());
  const base::Time expiry = current_time + base::Seconds(1000);
  state.AddHSTS("www.google.com", expiry, true);

  EXPECT_TRUE(
      state.ShouldUpgradeToSSL("www.google.com", /*is_top_level_nav=*/true));
}

TEST_F(TransportSecurityStateTest, WriteSizeDecodeSize) {
  for (size_t i = 0; i < 300; ++i) {
    SCOPED_TRACE(i);
    huffman_trie::TrieBitBuffer buffer;
    buffer.WriteSize(i);
    huffman_trie::BitWriter writer;
    buffer.WriteToBitWriter(&writer);
    size_t position = writer.position();
    writer.Flush();
    ASSERT_NE(writer.bytes().data(), nullptr);
    extras::PreloadDecoder::BitReader reader(writer.bytes().data(), position);
    size_t decoded_size;
    EXPECT_TRUE(reader.DecodeSize(&decoded_size));
    EXPECT_EQ(i, decoded_size);
  }
}

TEST_F(TransportSecurityStateTest, DecodeSizeFour) {
  // Test that BitReader::DecodeSize properly handles the number 4, including
  // not over-reading input bytes. BitReader::Next only fails if there's not
  // another byte to read from; if it reads past the number of bits in the
  // buffer but is still in the last byte it will still succeed. For this
  // reason, this test puts the encoding of 4 at the end of the byte to check
  // that DecodeSize doesn't over-read.
  //
  // 4 is encoded as 0b010. Shifted right to fill one byte, it is 0x02, with 5
  // bits of padding.
  uint8_t encoded = 0x02;
  extras::PreloadDecoder::BitReader reader(&encoded, 8);
  for (size_t i = 0; i < 5; ++i) {
    bool unused;
    ASSERT_TRUE(reader.Next(&unused));
  }
  size_t decoded_size;
  EXPECT_TRUE(reader.DecodeSize(&decoded_size));
  EXPECT_EQ(4u, decoded_size);
}

#endif  // BUILDFLAG(INCLUDE_TRANSPORT_SECURITY_STATE_PRELOAD_LIST)

TEST_F(TransportSecurityStateTest, UpdateKeyPinsListValidPin) {
  base::test::ScopedFeatureList scoped_feature_list_;
  scoped_feature_list_.InitAndEnableFeature(
      features::kStaticKeyPinningEnforcement);
  HashValueVector bad_hashes = DeserializeHashes(kBadPath);

  TransportSecurityState state;
  EnableStaticPins(&state);

  // Prior to updating the list, bad_hashes should be rejected.
  EXPECT_EQ(TransportSecurityState::PKPStatus::VIOLATED,
            state.CheckPublicKeyPins(kHost, true, bad_hashes));

  // Update the pins list, adding bad_hashes to the accepted hashes for this
  // host.
  TransportSecurityState::PinSet test_pinset(
      /*name=*/"test",
      /*static_spki_hashes=*/UnpackRawHashes(bad_hashes),
      /*bad_static_spki_hashes=*/{});
  TransportSecurityState::PinSetInfo test_pinsetinfo(
      /*hostname=*/kHost, /*pinset_name=*/"test",
      /*include_subdomains=*/false);
  state.UpdatePinList({test_pinset}, {test_pinsetinfo}, base::Time::Now());

  // Hashes should now be accepted.
  EXPECT_EQ(TransportSecurityState::PKPStatus::OK,
            state.CheckPublicKeyPins(kHost, true, bad_hashes));
}

TEST_F(TransportSecurityStateTest, UpdateKeyPinsListNotValidPin) {
  base::test::ScopedFeatureList scoped_feature_list_;
  scoped_feature_list_.InitAndEnableFeature(
      features::kStaticKeyPinningEnforcement);
  HashValueVector good_hashes = DeserializeHashes(kGoodPath);

  TransportSecurityState state;
  EnableStaticPins(&state);

  // Prior to updating the list, good_hashes should be accepted
  EXPECT_EQ(TransportSecurityState::PKPStatus::OK,
            state.CheckPublicKeyPins(kHost, true, good_hashes));

  // Update the pins list, adding good_hashes to the rejected hashes for this
  // host.
  TransportSecurityState::PinSet test_pinset(
      /*name=*/"test",
      /*static_spki_hashes=*/{},
      /*bad_static_spki_hashes=*/UnpackRawHashes(good_hashes));
  TransportSecurityState::PinSetInfo test_pinsetinfo(
      /*hostname=*/kHost, /* pinset_name=*/"test",
      /*include_subdomains=*/false);
  state.UpdatePinList({test_pinset}, {test_pinsetinfo}, base::Time::Now());

  // Hashes should now be rejected.
  EXPECT_EQ(TransportSecurityState::PKPStatus::VIOLATED,
            state.CheckPublicKeyPins(kHost, true, good_hashes));

  // Hashes should also be rejected if the hostname has a trailing dot.
  EXPECT_EQ(TransportSecurityState::PKPStatus::VIOLATED,
            state.CheckPublicKeyPins("example.test", true, good_hashes));

  // Hashes should also be rejected if the hostname has different
  // capitalization.
  EXPECT_EQ(TransportSecurityState::PKPStatus::VIOLATED,
            state.CheckPublicKeyPins("ExAmpLe.tEsT", true, good_hashes));
}

TEST_F(TransportSecurityStateTest, UpdateKeyPinsEmptyList) {
  base::test::ScopedFeatureList scoped_feature_list_;
  scoped_feature_list_.InitAndEnableFeature(
      features::kStaticKeyPinningEnforcement);
  HashValueVector bad_hashes = DeserializeHashes(kBadPath);

  TransportSecurityState state;
  EnableStaticPins(&state);

  // Prior to updating the list, bad_hashes should be rejected.
  EXPECT_EQ(TransportSecurityState::PKPStatus::VIOLATED,
            state.CheckPublicKeyPins(kHost, true, bad_hashes));

  // Update the pins list with an empty list.
  state.UpdatePinList({}, {}, base::Time::Now());

  // Hashes should now be accepted.
  EXPECT_EQ(TransportSecurityState::PKPStatus::OK,
            state.CheckPublicKeyPins(kHost, true, bad_hashes));
}

TEST_F(TransportSecurityStateTest, UpdateKeyPinsIncludeSubdomains) {
  base::test::ScopedFeatureList scoped_feature_list_;
  scoped_feature_list_.InitAndEnableFeature(
      features::kStaticKeyPinningEnforcement);
  // unpinned_hashes is a set of hashes that (after the update) won't match the
  // expected hashes for the tld of this domain. kGoodPath is used here because
  // it's a path that is accepted prior to any updates, and this test will
  // validate it is rejected afterwards.
  HashValueVector unpinned_hashes = DeserializeHashes(kGoodPath);

  TransportSecurityState state;
  EnableStaticPins(&state);

  // Prior to updating the list, unpinned_hashes should be accepted
  EXPECT_EQ(
      TransportSecurityState::PKPStatus::OK,
      state.CheckPublicKeyPins("example.sub.test", true, unpinned_hashes));

  // Update the pins list, adding kBadPath to the accepted hashes for this
  // host, relying on include_subdomains for enforcement. The contents of the
  // hashes don't matter as long as they are different from unpinned_hashes,
  // kBadPath is used for convenience.
  TransportSecurityState::PinSet test_pinset(
      /*name=*/"test",
      /*static_spki_hashes=*/UnpackRawHashes(DeserializeHashes(kBadPath)),
      /*bad_static_spki_hashes=*/{});
  // The host used in the test is "example.sub.test", so this pinset will only
  // match due to include subdomains.
  TransportSecurityState::PinSetInfo test_pinsetinfo(
      /*hostname=*/"sub.test", /* pinset_name=*/"test",
      /*include_subdomains=*/true);
  state.UpdatePinList({test_pinset}, {test_pinsetinfo}, base::Time::Now());

  // The path that was accepted before updating the pins should now be rejected.
  EXPECT_EQ(
      TransportSecurityState::PKPStatus::VIOLATED,
      state.CheckPublicKeyPins("example.sub.test", true, unpinned_hashes));
}

TEST_F(TransportSecurityStateTest, UpdateKeyPinsIncludeSubdomainsTLD) {
  base::test::ScopedFeatureList scoped_feature_list_;
  scoped_feature_list_.InitAndEnableFeature(
      features::kStaticKeyPinningEnforcement);
  // unpinned_hashes is a set of hashes that (after the update) won't match the
  // expected hashes for the tld of this domain. kGoodPath is used here because
  // it's a path that is accepted prior to any updates, and this test will
  // validate it is rejected afterwards.
  HashValueVector unpinned_hashes = DeserializeHashes(kGoodPath);

  TransportSecurityState state;
  EnableStaticPins(&state);

  // Prior to updating the list, unpinned_hashes should be accepted
  EXPECT_EQ(TransportSecurityState::PKPStatus::OK,
            state.CheckPublicKeyPins(kHost, true, unpinned_hashes));

  // Update the pins list, adding kBadPath to the accepted hashes for this
  // host, relying on include_subdomains for enforcement. The contents of the
  // hashes don't matter as long as they are different from unpinned_hashes,
  // kBadPath is used for convenience.
  TransportSecurityState::PinSet test_pinset(
      /*name=*/"test",
      /*static_spki_hashes=*/UnpackRawHashes(DeserializeHashes(kBadPath)),
      /*bad_static_spki_hashes=*/{});
  // The host used in the test is "example.test", so this pinset will only match
  // due to include subdomains.
  TransportSecurityState::PinSetInfo test_pinsetinfo(
      /*hostname=*/"test", /* pinset_name=*/"test",
      /*include_subdomains=*/true);
  state.UpdatePinList({test_pinset}, {test_pinsetinfo}, base::Time::Now());

  // The path that was accepted before updating the pins should now be rejected.
  EXPECT_EQ(TransportSecurityState::PKPStatus::VIOLATED,
            state.CheckPublicKeyPins(kHost, true, unpinned_hashes));
}

TEST_F(TransportSecurityStateTest, UpdateKeyPinsDontIncludeSubdomains) {
  base::test::ScopedFeatureList scoped_feature_list_;
  scoped_feature_list_.InitAndEnableFeature(
      features::kStaticKeyPinningEnforcement);
  // unpinned_hashes is a set of hashes that (after the update) won't match the
  // expected hashes for the tld of this domain. kGoodPath is used here because
  // it's a path that is accepted prior to any updates, and this test will
  // validate it is accepted or rejected afterwards depending on whether the
  // domain is an exact match.
  HashValueVector unpinned_hashes = DeserializeHashes(kGoodPath);

  TransportSecurityState state;
  EnableStaticPins(&state);

  // Prior to updating the list, unpinned_hashes should be accepted
  EXPECT_EQ(TransportSecurityState::PKPStatus::OK,
            state.CheckPublicKeyPins(kHost, true, unpinned_hashes));

  // Update the pins list, adding kBadPath to the accepted hashes for the
  // tld of this host, but without include_subdomains set. The contents of the
  // hashes don't matter as long as they are different from unpinned_hashes,
  // kBadPath is used for convenience.
  TransportSecurityState::PinSet test_pinset(
      /*name=*/"test",
      /*static_spki_hashes=*/UnpackRawHashes(DeserializeHashes(kBadPath)),
      /*bad_static_spki_hashes=*/{});
  // The host used in the test is "example.test", so this pinset will not match
  // due to include subdomains not being set.
  TransportSecurityState::PinSetInfo test_pinsetinfo(
      /*hostname=*/"test", /* pinset_name=*/"test",
      /*include_subdomains=*/false);
  state.UpdatePinList({test_pinset}, {test_pinsetinfo}, base::Time::Now());

  // Hashes that were accepted before the update should still be accepted since
  // include subdomains is not set for the pinset, and this is not an exact
  // match.
  EXPECT_EQ(TransportSecurityState::PKPStatus::OK,
            state.CheckPublicKeyPins(kHost, true, unpinned_hashes));

  // Hashes should be rejected for an exact match of the hostname.
  EXPECT_EQ(TransportSecurityState::PKPStatus::VIOLATED,
            state.CheckPublicKeyPins("test", true, unpinned_hashes));
}

TEST_F(TransportSecurityStateTest, UpdateKeyPinsListTimestamp) {
  base::test::ScopedFeatureList scoped_feature_list_;
  scoped_feature_list_.InitAndEnableFeature(
      features::kStaticKeyPinningEnforcement);
  HashValueVector bad_hashes = DeserializeHashes(kBadPath);

  TransportSecurityState state;
  EnableStaticPins(&state);

  // Prior to updating the list, bad_hashes should be rejected.
  EXPECT_EQ(TransportSecurityState::PKPStatus::VIOLATED,
            state.CheckPublicKeyPins(kHost, true, bad_hashes));

  // TransportSecurityStateTest sets a flag when EnableStaticPins is called that
  // results in TransportSecurityState considering the pins list as always
  // timely. We need to disable it so we can test that the timestamp has the
  // required effect.
  state.SetPinningListAlwaysTimelyForTesting(false);

  TransportSecurityState::PinSet test_pinset(
      /*name=*/"test",
      /*static_spki_hashes=*/{},
      /*bad_static_spki_hashes=*/UnpackRawHashes(bad_hashes));
  TransportSecurityState::PinSetInfo test_pinsetinfo(
      /*hostname=*/kHost, /* pinset_name=*/"test",
      /*include_subdomains=*/false);
  state.UpdatePinList({test_pinset}, {test_pinsetinfo},
                      base::Time::Now() - base::Days(70));

  // Hashes should now be accepted.
  EXPECT_EQ(TransportSecurityState::PKPStatus::OK,
            state.CheckPublicKeyPins(kHost, true, bad_hashes));

  // Update the pins list again, with a timestamp <70 days old.
  state.UpdatePinList({test_pinset}, {test_pinsetinfo},
                      base::Time::Now() - base::Days(69));

  // Hashes should now be rejected.
  EXPECT_EQ(TransportSecurityState::PKPStatus::VIOLATED,
            state.CheckPublicKeyPins(kHost, true, bad_hashes));
}

class TransportSecurityStatePinningKillswitchTest
    : public TransportSecurityStateTest {
 public:
  TransportSecurityStatePinningKillswitchTest() {
    scoped_feature_list_.InitAndDisableFeature(
        features::kStaticKeyPinningEnforcement);
  }

 protected:
  base::test::ScopedFeatureList scoped_feature_list_;
};

TEST_F(TransportSecurityStatePinningKillswitchTest, PinningKillswitchSet) {
  HashValueVector bad_hashes = DeserializeHashes(kBadPath);

  TransportSecurityState state;
  EnableStaticPins(&state);

  // Hashes should be accepted since pinning enforcement is disabled.
  EXPECT_EQ(TransportSecurityState::PKPStatus::OK,
            state.CheckPublicKeyPins(kHost, true, bad_hashes));
}

}  // namespace net