File: network_context_configuration_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 (2276 lines) | stat: -rw-r--r-- 98,005 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
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
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
// Copyright 2017 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include <atomic>
#include <optional>
#include <string>
#include <unordered_set>
#include <vector>

#include "base/command_line.h"
#include "base/files/file_path.h"
#include "base/files/file_util.h"
#include "base/files/scoped_temp_dir.h"
#include "base/functional/bind.h"
#include "base/location.h"
#include "base/memory/raw_ptr.h"
#include "base/path_service.h"
#include "base/strings/strcat.h"
#include "base/strings/string_util.h"
#include "base/strings/stringprintf.h"
#include "base/task/single_thread_task_runner.h"
#include "base/test/bind.h"
#include "base/threading/thread_restrictions.h"
#include "base/uuid.h"
#include "build/build_config.h"
#include "build/chromeos_buildflags.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/content_settings/cookie_settings_factory.h"
#include "chrome/browser/net/profile_network_context_service.h"
#include "chrome/browser/net/profile_network_context_service_factory.h"
#include "chrome/browser/net/system_network_context_manager.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/safe_browsing/safe_browsing_service.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/pref_names.h"
#include "chrome/common/webui_url_constants.h"
#include "chrome/test/base/in_process_browser_test.h"
#include "components/content_settings/core/browser/cookie_settings.h"
#include "components/content_settings/core/common/content_settings.h"
#include "components/content_settings/core/common/pref_names.h"
#include "components/embedder_support/switches.h"
#include "components/embedder_support/user_agent_utils.h"
#include "components/language/core/browser/pref_names.h"
#include "components/network_session_configurator/common/network_switches.h"
#include "components/policy/core/browser/browser_policy_connector.h"
#include "components/policy/core/common/mock_configuration_policy_provider.h"
#include "components/policy/core/common/policy_map.h"
#include "components/policy/policy_constants.h"
#include "components/prefs/pref_service.h"
#include "components/proxy_config/proxy_config_dictionary.h"
#include "components/proxy_config/proxy_config_pref_names.h"
#include "content/public/browser/browser_context.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/network_service_instance.h"
#include "content/public/browser/network_service_util.h"
#include "content/public/browser/storage_partition.h"
#include "content/public/browser/storage_partition_config.h"
#include "content/public/common/content_switches.h"
#include "content/public/common/url_constants.h"
#include "content/public/test/browser_test.h"
#include "content/public/test/browser_test_utils.h"
#include "content/public/test/simple_url_loader_test_helper.h"
#include "mojo/public/cpp/bindings/remote.h"
#include "mojo/public/cpp/system/data_pipe_utils.h"
#include "net/base/address_list.h"
#include "net/base/filename_util.h"
#include "net/base/host_port_pair.h"
#include "net/base/load_flags.h"
#include "net/base/net_errors.h"
#include "net/cookies/canonical_cookie.h"
#include "net/cookies/cookie_options.h"
#include "net/dns/mock_host_resolver.h"
#include "net/dns/public/resolve_error_info.h"
#include "net/http/http_response_headers.h"
#include "net/reporting/reporting_policy.h"
#include "net/ssl/ssl_config.h"
#include "net/ssl/ssl_server_config.h"
#include "net/test/embedded_test_server/controllable_http_response.h"
#include "net/test/embedded_test_server/default_handlers.h"
#include "net/test/embedded_test_server/embedded_test_server.h"
#include "net/test/embedded_test_server/embedded_test_server_connection_listener.h"
#include "net/test/embedded_test_server/http_request.h"
#include "net/test/embedded_test_server/http_response.h"
#include "net/test/gtest_util.h"
#include "net/test/spawned_test_server/spawned_test_server.h"
#include "net/traffic_annotation/network_traffic_annotation_test_helper.h"
#include "net/url_request/referrer_policy.h"
#include "services/network/public/cpp/features.h"
#include "services/network/public/cpp/network_connection_tracker.h"
#include "services/network/public/cpp/resource_request.h"
#include "services/network/public/cpp/simple_url_loader.h"
#include "services/network/public/mojom/cookie_manager.mojom.h"
#include "services/network/public/mojom/host_resolver.mojom.h"
#include "services/network/public/mojom/network_service.mojom.h"
#include "services/network/public/mojom/url_loader.mojom.h"
#include "services/network/public/mojom/url_loader_factory.mojom.h"
#include "services/network/test/test_dns_util.h"
#include "services/network/test/test_url_loader_client.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "url/gurl.h"

#if BUILDFLAG(IS_MAC)
#include "base/mac/mac_util.h"
#endif

#if BUILDFLAG(ENABLE_EXTENSIONS)
#include "chrome/browser/extensions/chrome_test_extension_loader.h"
#include "chrome/browser/extensions/scoped_test_mv2_enabler.h"
#include "extensions/browser/browsertest_util.h"
#include "extensions/test/test_extension_dir.h"
#endif

namespace {

constexpr char kHostname[] = "foo.test";
constexpr char kHstsHostname[] = "hsts.test";
constexpr char kAddress[] = "5.8.13.21";

const char kCacheRandomPath[] = "/cacherandom";

// Path using a ControllableHttpResponse that's part of the test fixture.
const char kControllablePath[] = "/controllable";

enum class NetworkServiceState {
  kEnabled,
  // Similar to |kEnabled|, but will simulate a crash and run tests again the
  // restarted Network Service process.
  kRestarted,
};

enum class NetworkContextType {
  kSystem,
  kSafeBrowsing,
  kProfile,
  kIncognitoProfile,
  kOnDiskApp,
  kInMemoryApp,
  kOnDiskAppWithIncognitoProfile,
};

// This list should be kept in sync with the NetworkContextType enum.
const NetworkContextType kNetworkContextTypes[] = {
    NetworkContextType::kSystem,
    NetworkContextType::kSafeBrowsing,
    NetworkContextType::kProfile,
    NetworkContextType::kIncognitoProfile,
    NetworkContextType::kOnDiskApp,
    NetworkContextType::kInMemoryApp,
    NetworkContextType::kOnDiskAppWithIncognitoProfile,
};

struct TestCase {
  NetworkServiceState network_service_state;
  NetworkContextType network_context_type;
};

// Waits for the network connection type to be the specified value.
class ConnectionTypeWaiter
    : public network::NetworkConnectionTracker::NetworkConnectionObserver {
 public:
  ConnectionTypeWaiter() : tracker_(content::GetNetworkConnectionTracker()) {
    tracker_->AddNetworkConnectionObserver(this);
  }

  ~ConnectionTypeWaiter() override {
    tracker_->RemoveNetworkConnectionObserver(this);
  }

  void Wait(network::mojom::ConnectionType expected_type) {
    auto current_type = network::mojom::ConnectionType::CONNECTION_UNKNOWN;
    for (;;) {
      network::NetworkConnectionTracker::ConnectionTypeCallback callback =
          base::BindOnce(&ConnectionTypeWaiter::OnConnectionChanged,
                         base::Unretained(this));
      if (tracker_->GetConnectionType(&current_type, std::move(callback)) &&
          current_type == expected_type)
        break;
      run_loop_ = std::make_unique<base::RunLoop>(
          base::RunLoop::Type::kNestableTasksAllowed);
      run_loop_->Run();
    }
  }

 private:
  // network::NetworkConnectionTracker::NetworkConnectionObserver:
  void OnConnectionChanged(network::mojom::ConnectionType type) override {
    if (run_loop_)
      run_loop_->Quit();
  }

  raw_ptr<network::NetworkConnectionTracker> tracker_;
  std::unique_ptr<base::RunLoop> run_loop_;
};

// Tests the system, profile, and incognito profile NetworkContexts.
class NetworkContextConfigurationBrowserTest
    : public InProcessBrowserTest,
      public testing::WithParamInterface<TestCase> {
 public:
  // Backing storage types that can used for various things (HTTP cache,
  // cookies, etc).
  enum class StorageType {
    kNone,
    kMemory,
    kDisk,
  };

  enum class CookieType {
    kFirstParty,
    kThirdParty,
  };

  enum class CookiePersistenceType {
    kSession,
    kPersistent,
  };

  NetworkContextConfigurationBrowserTest()
      : https_server_(net::EmbeddedTestServer::TYPE_HTTPS) {
    // TODO(crbug.com/334954143) Fix the tests when turning on the reduce
    // accept-language feature.
    scoped_feature_list_.InitWithFeatures(
        {}, {network::features::kReduceAcceptLanguage});

    // Have to get a port before setting up the command line, but can only set
    // up the connection listener after there's a main thread, so can't start
    // the test server here.
    EXPECT_TRUE(embedded_test_server()->InitializeAndListen());
    EXPECT_TRUE(https_server()->InitializeAndListen());
  }

  // Returns a cacheable response (10 hours) that is some random text.
  static std::unique_ptr<net::test_server::HttpResponse> HandleCacheRandom(
      const net::test_server::HttpRequest& request) {
    if (request.relative_url != kCacheRandomPath)
      return nullptr;

    std::unique_ptr<net::test_server::BasicHttpResponse> response =
        std::make_unique<net::test_server::BasicHttpResponse>();
    response->set_content(base::Uuid::GenerateRandomV4().AsLowercaseString());
    response->set_content_type("text/plain");
    response->AddCustomHeader("Cache-Control", "max-age=60000");
    return std::move(response);
  }

  NetworkContextConfigurationBrowserTest(
      const NetworkContextConfigurationBrowserTest&) = delete;
  NetworkContextConfigurationBrowserTest& operator=(
      const NetworkContextConfigurationBrowserTest&) = delete;

  ~NetworkContextConfigurationBrowserTest() override = default;

  void SetUpInProcessBrowserTestFixture() override {
    provider_.SetDefaultReturns(
        /*is_initialization_complete_return=*/true,
        /*is_first_policy_load_complete_return=*/true);
    policy::BrowserPolicyConnector::SetPolicyProviderForTesting(&provider_);
  }

  void SetUpOnMainThread() override {
    // Used in a bunch of proxy tests. Should not resolve.
    host_resolver()->AddSimulatedFailure("does.not.resolve.test");

    host_resolver()->AddRule(kHostname, kAddress);
    host_resolver()->AddRule(kHstsHostname, "127.0.0.1");

    controllable_http_response_ =
        std::make_unique<net::test_server::ControllableHttpResponse>(
            embedded_test_server(), kControllablePath);
    embedded_test_server()->RegisterRequestHandler(base::BindRepeating(
        &NetworkContextConfigurationBrowserTest::HandleCacheRandom));
    embedded_test_server()->StartAcceptingConnections();
    net::test_server::RegisterDefaultHandlers(https_server());
    https_server()->StartAcceptingConnections();

    if (is_incognito())
      incognito_ = CreateIncognitoBrowser();
    SimulateNetworkServiceCrashIfNecessary();

#if BUILDFLAG(IS_CHROMEOS)
    // On ChromeOS the connection type comes from a fake Shill service, which
    // is configured with a fake ethernet connection asynchronously. Wait for
    // the connection type to be available to avoid getting notified of the
    // connection change halfway through the test.
    ConnectionTypeWaiter().Wait(
        network::mojom::ConnectionType::CONNECTION_ETHERNET);
#endif
  }

  // Returns true if the NetworkContext being tested is associated with an
  // incognito profile.
  bool is_incognito() const {
    return GetParam().network_context_type ==
               NetworkContextType::kIncognitoProfile ||
           GetParam().network_context_type ==
               NetworkContextType::kOnDiskAppWithIncognitoProfile;
  }

  void TearDownOnMainThread() override {
    // Have to destroy this before the main message loop is torn down. Need to
    // leave the embedded test server up for tests that use
    // |live_during_shutdown_simple_loader_|. It's safe to destroy the
    // ControllableHttpResponse before the test server.
    controllable_http_response_.reset();
  }

  // Returns, as a string, a PAC script that will use the EmbeddedTestServer as
  // a proxy.
  std::string GetPacScript() const {
    return base::StringPrintf(
        "function FindProxyForURL(url, host){ return 'PROXY %s;' }",
        net::HostPortPair::FromURL(embedded_test_server()->base_url())
            .ToString()
            .c_str());
  }

  net::EmbeddedTestServer* https_server() { return &https_server_; }

  content::StoragePartition* GetStoragePartition() {
    return GetStoragePartitionForContextType(GetParam().network_context_type);
  }

  content::StoragePartition* GetStoragePartitionForContextType(
      NetworkContextType network_context_type) {
    const auto kOnDiskConfig = content::StoragePartitionConfig::Create(
        browser()->profile(), "foo", /*partition_name=*/"",
        /*in_memory=*/false);
    const auto kInMemoryConfig = content::StoragePartitionConfig::Create(
        browser()->profile(), "foo", /*partition_name=*/"", /*in_memory=*/true);

    switch (network_context_type) {
      case NetworkContextType::kSystem:
      case NetworkContextType::kSafeBrowsing:
        NOTREACHED() << "Network context has no storage partition";
      case NetworkContextType::kProfile:
        return browser()->profile()->GetDefaultStoragePartition();
      case NetworkContextType::kIncognitoProfile:
        DCHECK(incognito_);
        return incognito_->profile()->GetDefaultStoragePartition();
      case NetworkContextType::kOnDiskApp:
        return browser()->profile()->GetStoragePartition(kOnDiskConfig);
      case NetworkContextType::kInMemoryApp:
        return browser()->profile()->GetStoragePartition(kInMemoryConfig);
      case NetworkContextType::kOnDiskAppWithIncognitoProfile: {
        DCHECK(incognito_);
        // Note: Even though we are requesting an on-disk config, the function
        // will return an in-memory config because incognito profiles are not
        // supposed to to use on-disk storage.
        const auto kIncognitoConfig = content::StoragePartitionConfig::Create(
            incognito_->profile(), "foo", /*partition_name=*/"",
            /*in_memory=*/false);
        DCHECK(kIncognitoConfig.in_memory());

        return incognito_->profile()->GetStoragePartition(kIncognitoConfig);
      }
    }
    NOTREACHED();
  }

  network::mojom::URLLoaderFactory* loader_factory() {
    return GetLoaderFactoryForContextType(GetParam().network_context_type);
  }

  network::mojom::URLLoaderFactory* GetLoaderFactoryForContextType(
      NetworkContextType network_context_type) {
    switch (network_context_type) {
      case NetworkContextType::kSystem:
        return g_browser_process->system_network_context_manager()
            ->GetURLLoaderFactory();
      case NetworkContextType::kSafeBrowsing:
        return g_browser_process->safe_browsing_service()
            ->GetURLLoaderFactory(browser()->profile())
            .get();
      case NetworkContextType::kProfile:
      case NetworkContextType::kIncognitoProfile:
      case NetworkContextType::kOnDiskApp:
      case NetworkContextType::kInMemoryApp:
      case NetworkContextType::kOnDiskAppWithIncognitoProfile:
        return GetStoragePartitionForContextType(network_context_type)
            ->GetURLLoaderFactoryForBrowserProcess()
            .get();
    }
    NOTREACHED();
  }

  network::mojom::NetworkContext* network_context() {
    return GetNetworkContextForContextType(GetParam().network_context_type);
  }

  network::mojom::NetworkContext* GetNetworkContextForContextType(
      NetworkContextType network_context_type) {
    switch (network_context_type) {
      case NetworkContextType::kSystem:
        return g_browser_process->system_network_context_manager()
            ->GetContext();
      case NetworkContextType::kSafeBrowsing:
        return g_browser_process->safe_browsing_service()->GetNetworkContext(
            browser()->profile());
      case NetworkContextType::kProfile:
      case NetworkContextType::kIncognitoProfile:
      case NetworkContextType::kOnDiskApp:
      case NetworkContextType::kInMemoryApp:
      case NetworkContextType::kOnDiskAppWithIncognitoProfile:
        return GetStoragePartitionForContextType(network_context_type)
            ->GetNetworkContext();
    }
    NOTREACHED();
  }

  StorageType GetHttpCacheType() const {
    switch (GetParam().network_context_type) {
      case NetworkContextType::kSystem:
      case NetworkContextType::kSafeBrowsing:
        return StorageType::kNone;
      case NetworkContextType::kProfile:
      case NetworkContextType::kOnDiskApp:
        return StorageType::kDisk;
      case NetworkContextType::kIncognitoProfile:
      case NetworkContextType::kInMemoryApp:
      case NetworkContextType::kOnDiskAppWithIncognitoProfile:
        return StorageType::kMemory;
    }
    NOTREACHED();
  }

  StorageType GetCookieStorageType() const {
    switch (GetParam().network_context_type) {
      case NetworkContextType::kSystem:
      case NetworkContextType::kIncognitoProfile:
      case NetworkContextType::kInMemoryApp:
      case NetworkContextType::kOnDiskAppWithIncognitoProfile:
        return StorageType::kMemory;
      case NetworkContextType::kSafeBrowsing:
      case NetworkContextType::kProfile:
      case NetworkContextType::kOnDiskApp:
        return StorageType::kDisk;
    }
    NOTREACHED();
  }

  // Returns the pref service with most prefs related to the NetworkContext
  // being tested.
  PrefService* GetPrefService() {
    switch (GetParam().network_context_type) {
      case NetworkContextType::kSystem:
        return g_browser_process->local_state();
      case NetworkContextType::kSafeBrowsing:
      case NetworkContextType::kProfile:
      case NetworkContextType::kInMemoryApp:
      case NetworkContextType::kOnDiskApp:
        return browser()->profile()->GetPrefs();
      case NetworkContextType::kIncognitoProfile:
      case NetworkContextType::kOnDiskAppWithIncognitoProfile:
        // Incognito actually uses the non-incognito prefs, so this should end
        // up being the same pref store as in the KProfile case.
        return browser()
            ->profile()
            ->GetPrimaryOTRProfile(/*create_if_needed=*/true)
            ->GetPrefs();
    }
  }

  // Sets the proxy preference on a PrefService based on the NetworkContextType,
  // and waits for it to be applied.
  void SetProxyPref(const net::HostPortPair& host_port_pair) {
    GetPrefService()->SetDict(proxy_config::prefs::kProxy,
                              ProxyConfigDictionary::CreateFixedServers(
                                  host_port_pair.ToString(), std::string()));

    // Wait for the new ProxyConfig to be passed over the pipe. Needed because
    // Mojo doesn't guarantee ordering of events on different Mojo pipes, and
    // requests are sent on a separate pipe from ProxyConfigs.
    switch (GetParam().network_context_type) {
      case NetworkContextType::kSystem:
      case NetworkContextType::kSafeBrowsing:
        g_browser_process->system_network_context_manager()
            ->FlushProxyConfigMonitorForTesting();
        break;
      case NetworkContextType::kProfile:
      case NetworkContextType::kInMemoryApp:
      case NetworkContextType::kOnDiskApp:
        ProfileNetworkContextServiceFactory::GetForContext(browser()->profile())
            ->FlushProxyConfigMonitorForTesting();
        break;
      case NetworkContextType::kIncognitoProfile:
      case NetworkContextType::kOnDiskAppWithIncognitoProfile:
        ProfileNetworkContextServiceFactory::GetForContext(
            browser()->profile()->GetPrimaryOTRProfile(
                /*create_if_needed=*/true))
            ->FlushProxyConfigMonitorForTesting();
        break;
    }
  }

  // Sends a request and expects it to be handled by embedded_test_server()
  // acting as a proxy;
  void TestProxyConfigured(bool expect_success) {
    std::unique_ptr<network::ResourceRequest> request =
        std::make_unique<network::ResourceRequest>();
    // This URL should be directed to the test server because of the proxy.
    request->url = GURL("http://does.not.resolve.test:1872/echo");
    request->credentials_mode = network::mojom::CredentialsMode::kOmit;

    content::SimpleURLLoaderTestHelper simple_loader_helper;
    std::unique_ptr<network::SimpleURLLoader> simple_loader =
        network::SimpleURLLoader::Create(std::move(request),
                                         TRAFFIC_ANNOTATION_FOR_TESTS);

    simple_loader->DownloadToStringOfUnboundedSizeUntilCrashAndDie(
        loader_factory(), simple_loader_helper.GetCallbackDeprecated());
    simple_loader_helper.WaitForCallback();

    if (expect_success) {
      EXPECT_EQ(net::OK, simple_loader->NetError());
      ASSERT_TRUE(simple_loader_helper.response_body());
      EXPECT_EQ(*simple_loader_helper.response_body(), "Echo");
    } else {
      EXPECT_EQ(net::ERR_NAME_NOT_RESOLVED, simple_loader->NetError());
      ASSERT_FALSE(simple_loader_helper.response_body());
    }
  }

  // Makes a request that hangs, and will live until browser shutdown.
  void MakeLongLivedRequestThatHangsUntilShutdown() {
    std::unique_ptr<network::ResourceRequest> request =
        std::make_unique<network::ResourceRequest>();
    request->url = embedded_test_server()->GetURL(kControllablePath);
    request->credentials_mode = network::mojom::CredentialsMode::kOmit;
    live_during_shutdown_simple_loader_ = network::SimpleURLLoader::Create(
        std::move(request), TRAFFIC_ANNOTATION_FOR_TESTS);
    live_during_shutdown_simple_loader_helper_ =
        std::make_unique<content::SimpleURLLoaderTestHelper>();

    live_during_shutdown_simple_loader_
        ->DownloadToStringOfUnboundedSizeUntilCrashAndDie(
            loader_factory(), live_during_shutdown_simple_loader_helper_
                                  ->GetCallbackDeprecated());

    // Don't actually care about controlling the response, just need to wait
    // until it sees the request, to make sure that a URLRequest has been
    // created to potentially leak. Since the |controllable_http_response_| is
    // not used to send a response to the request, the request just hangs until
    // the NetworkContext is destroyed (Or the test server is shut down, but the
    // NetworkContext should be destroyed before that happens, in this test).
    controllable_http_response_->WaitForRequest();
  }

  // Sends a request to the test server's echoheader URL and sets
  // |header_value_out| to the value of the specified response header. Returns
  // false if the request fails. If non-null, uses |request| to make the
  // request, after setting its |url| value.
  [[nodiscard]] bool FetchHeaderEcho(
      const std::string& header_name,
      std::string* header_value_out,
      std::unique_ptr<network::ResourceRequest> request = nullptr) {
    if (!request)
      request = std::make_unique<network::ResourceRequest>();
    request->url = embedded_test_server()->GetURL(
        base::StrCat({"/echoheader?", header_name}));
    content::SimpleURLLoaderTestHelper simple_loader_helper;
    std::unique_ptr<network::SimpleURLLoader> simple_loader =
        network::SimpleURLLoader::Create(std::move(request),
                                         TRAFFIC_ANNOTATION_FOR_TESTS);
    simple_loader->DownloadToStringOfUnboundedSizeUntilCrashAndDie(
        loader_factory(), simple_loader_helper.GetCallbackDeprecated());
    simple_loader_helper.WaitForCallback();
    if (simple_loader_helper.response_body()) {
      *header_value_out = *simple_loader_helper.response_body();
      return true;
    }
    return false;
  }

  // |server| should be |TYPE_HTTPS| if the cookie is third-party, because
  // SameSite=None cookies must be Secure.
  void SetCookie(CookieType cookie_type,
                 CookiePersistenceType cookie_expiration_type,
                 net::EmbeddedTestServer* server) {
    std::unique_ptr<network::ResourceRequest> request =
        std::make_unique<network::ResourceRequest>();
    std::string cookie_line = "cookie";
    if (cookie_expiration_type == CookiePersistenceType::kPersistent)
      cookie_line += ";max-age=3600";
    // Third party (i.e. SameSite=None) cookies must be secure.
    if (cookie_type == CookieType::kThirdParty)
      cookie_line += ";SameSite=None;Secure";
    request->url = server->GetURL("/set-cookie?" + cookie_line);
    url::Origin origin;
    if (cookie_type == CookieType::kThirdParty)
      origin = url::Origin::Create(GURL("http://example.com"));
    else
      origin = url::Origin::Create(server->base_url());
    request->site_for_cookies = net::SiteForCookies::FromOrigin(origin);

    request->trusted_params = network::ResourceRequest::TrustedParams();
    request->trusted_params->isolation_info =
        net::IsolationInfo::CreateForInternalRequest(origin);

    content::SimpleURLLoaderTestHelper simple_loader_helper;
    std::unique_ptr<network::SimpleURLLoader> simple_loader =
        network::SimpleURLLoader::Create(std::move(request),
                                         TRAFFIC_ANNOTATION_FOR_TESTS);

    simple_loader->DownloadToStringOfUnboundedSizeUntilCrashAndDie(
        loader_factory(), simple_loader_helper.GetCallbackDeprecated());
    simple_loader_helper.WaitForCallback();
    EXPECT_EQ(net::OK, simple_loader->NetError());
  }

  void FlushNetworkInterface() {
    switch (GetParam().network_context_type) {
      case NetworkContextType::kSystem:
        g_browser_process->system_network_context_manager()
            ->FlushNetworkInterfaceForTesting();
        break;
      case NetworkContextType::kSafeBrowsing:
        g_browser_process->safe_browsing_service()
            ->FlushNetworkInterfaceForTesting(GetProfile());
        break;
      case NetworkContextType::kProfile:
      case NetworkContextType::kIncognitoProfile:
      case NetworkContextType::kInMemoryApp:
      case NetworkContextType::kOnDiskApp:
      case NetworkContextType::kOnDiskAppWithIncognitoProfile:
        GetStoragePartition()->FlushNetworkInterfaceForTesting();
        break;
    }
  }

  Profile* GetProfile() {
    switch (GetParam().network_context_type) {
      case NetworkContextType::kSystem:
      case NetworkContextType::kSafeBrowsing:
      case NetworkContextType::kProfile:
      case NetworkContextType::kInMemoryApp:
      case NetworkContextType::kOnDiskApp:
        return browser()->profile();
      case NetworkContextType::kIncognitoProfile:
      case NetworkContextType::kOnDiskAppWithIncognitoProfile:
        DCHECK(incognito_);
        return incognito_->profile();
    }
  }

  // Gets all cookies for given URL, as a single string.
  std::string GetCookies(const GURL& url) {
    return GetCookiesForContextType(GetParam().network_context_type, url);
  }

  std::string GetCookiesForContextType(NetworkContextType network_context_type,
                                       const GURL& url) {
    std::string cookies;
    base::RunLoop run_loop;
    mojo::Remote<network::mojom::CookieManager> cookie_manager;
    GetNetworkContextForContextType(network_context_type)
        ->GetCookieManager(cookie_manager.BindNewPipeAndPassReceiver());
    cookie_manager->GetCookieList(
        url, net::CookieOptions::MakeAllInclusive(),
        net::CookiePartitionKeyCollection(),
        base::BindOnce(
            [](std::string* cookies_out, base::RunLoop* run_loop,
               const net::CookieAccessResultList& cookies,
               const net::CookieAccessResultList& excluded_cookies) {
              *cookies_out = net::CanonicalCookie::BuildCookieLine(cookies);
              run_loop->Quit();
            },
            &cookies, &run_loop));
    run_loop.Run();
    return cookies;
  }

  void ForEachOtherContext(
      base::RepeatingCallback<void(NetworkContextType network_context_type)>
          callback) {
    // Create Incognito Profile if needed.
    if (!incognito_)
      incognito_ = CreateIncognitoBrowser();

    // True if the |network_context_type| corresponding to GetParam() has been
    // found. Used to verify that kNetworkContextTypes is kept up to date, and
    // contains no duplicates.
    bool found_matching_type = false;
    for (const auto network_context_type : kNetworkContextTypes) {
      if (network_context_type == GetParam().network_context_type) {
        EXPECT_FALSE(found_matching_type);
        found_matching_type = true;
        continue;
      }
      callback.Run(network_context_type);
    }
    EXPECT_TRUE(found_matching_type);
  }

  bool IsRestartStateWithInProcessNetworkService() {
    return GetParam().network_service_state ==
               NetworkServiceState::kRestarted &&
           content::IsInProcessNetworkService();
  }

  void UpdateChromePolicy(const policy::PolicyMap& policy_map) {
    provider_.UpdateChromePolicy(policy_map);
  }

 private:
  void SimulateNetworkServiceCrashIfNecessary() {
    if (GetParam().network_service_state != NetworkServiceState::kRestarted ||
        content::IsInProcessNetworkService()) {
      return;
    }

    // Make sure |network_context()| is working as expected. Use '/echoheader'
    // instead of '/echo' to avoid a disk_cache bug.
    // See https://crbug.com/792255.
    int net_error = content::LoadBasicRequest(
        network_context(), embedded_test_server()->GetURL("/echoheader"),
        net::LOAD_BYPASS_PROXY);
    EXPECT_THAT(net_error, net::test::IsOk());

    // Crash the NetworkService process. Existing interfaces should receive
    // error notifications at some point.
    SimulateNetworkServiceCrash();
    // Flush the interface to make sure the error notification was received.
    FlushNetworkInterface();
  }

  raw_ptr<Browser, AcrossTasksDanglingUntriaged> incognito_ = nullptr;

  net::EmbeddedTestServer https_server_;
  std::unique_ptr<net::test_server::ControllableHttpResponse>
      controllable_http_response_;

  testing::NiceMock<policy::MockConfigurationPolicyProvider> provider_;
  // Used in tests that need a live request during browser shutdown.
  std::unique_ptr<network::SimpleURLLoader> live_during_shutdown_simple_loader_;
  std::unique_ptr<content::SimpleURLLoaderTestHelper>
      live_during_shutdown_simple_loader_helper_;
  base::test::ScopedFeatureList scoped_feature_list_;
};

IN_PROC_BROWSER_TEST_P(NetworkContextConfigurationBrowserTest,
                       SecureCookiesAllowedForChromeScheme) {
  if (IsRestartStateWithInProcessNetworkService())
    return;
  // The system and SafeBrowsing network contexts don't support cookie options,
  // including the special scheme-based rules.
  bool system =
      GetParam().network_context_type == NetworkContextType::kSystem ||
      GetParam().network_context_type == NetworkContextType::kSafeBrowsing;
  if (system)
    return;

  // Cookies are only allowed for chrome:// schemes requesting a secure origin,
  // so create an HTTPS server.
  net::EmbeddedTestServer https_server(net::EmbeddedTestServer::TYPE_HTTPS);
  net::test_server::RegisterDefaultHandlers(&https_server);
  ASSERT_TRUE(https_server.Start());
  if (GetPrefService()->FindPreference(prefs::kCookieControlsMode)) {
    GetPrefService()->SetInteger(
        prefs::kCookieControlsMode,
        static_cast<int>(
            content_settings::CookieControlsMode::kBlockThirdParty));
  }
  SetCookie(CookieType::kFirstParty, CookiePersistenceType::kPersistent,
            embedded_test_server());

  std::unique_ptr<network::ResourceRequest> request =
      std::make_unique<network::ResourceRequest>();
  request->url = https_server.GetURL("/echoheader?Cookie");
  url::Origin origin = url::Origin::Create(GURL(chrome::kChromeUIPrintURL));
  request->site_for_cookies = net::SiteForCookies::FromOrigin(origin);
  request->trusted_params = network::ResourceRequest::TrustedParams();
  request->trusted_params->isolation_info =
      net::IsolationInfo::CreateForInternalRequest(origin);
  content::SimpleURLLoaderTestHelper simple_loader_helper;
  std::unique_ptr<network::SimpleURLLoader> simple_loader =
      network::SimpleURLLoader::Create(std::move(request),
                                       TRAFFIC_ANNOTATION_FOR_TESTS);

  simple_loader->DownloadToStringOfUnboundedSizeUntilCrashAndDie(
      loader_factory(), simple_loader_helper.GetCallbackDeprecated());
  simple_loader_helper.WaitForCallback();

  EXPECT_EQ(200, simple_loader->ResponseInfo()->headers->response_code());
  ASSERT_TRUE(simple_loader_helper.response_body());
  EXPECT_EQ("cookie", *simple_loader_helper.response_body());
}

#if BUILDFLAG(ENABLE_EXTENSIONS)
std::unique_ptr<net::test_server::HttpResponse> EchoCookieHeader(
    const net::test_server::HttpRequest& request) {
  auto response = std::make_unique<net::test_server::BasicHttpResponse>();
  auto it = request.headers.find("Cookie");
  if (it != request.headers.end())
    response->set_content(it->second);
  response->AddCustomHeader("Access-Control-Allow-Origin", "*");
  return response;
}

IN_PROC_BROWSER_TEST_P(NetworkContextConfigurationBrowserTest,
                       ThirdPartyCookiesAllowedForExtensions) {
  // TODO(https://crbug.com/40804030): Remove this when updated to use MV3.
  extensions::ScopedTestMV2Enabler mv2_enabler;

  if (IsRestartStateWithInProcessNetworkService())
    return;

  // Loading an extension only makes sense for profile contexts.
  if (GetParam().network_context_type != NetworkContextType::kProfile &&
      GetParam().network_context_type !=
          NetworkContextType::kIncognitoProfile) {
    return;
  }
  net::EmbeddedTestServer test_server;
  net::test_server::RegisterDefaultHandlers(&test_server);
  test_server.RegisterRequestHandler(base::BindRepeating(&EchoCookieHeader));
  ASSERT_TRUE(test_server.Start());

  GetPrefService()->SetInteger(
      prefs::kCookieControlsMode,
      static_cast<int>(content_settings::CookieControlsMode::kBlockThirdParty));
  SetCookie(CookieType::kFirstParty, CookiePersistenceType::kPersistent,
            embedded_test_server());

  extensions::TestExtensionDir extension_dir;
  extension_dir.WriteManifest(R"({
    "name": "Cookie Test",
    "manifest_version": 2,
    "version": "1.0",
    "background": {
      "scripts": ["background.js"]
    },
    "incognito": "split",
    "permissions": ["<all_urls>"]
   })");
  extension_dir.WriteFile(FILE_PATH_LITERAL("background.js"), "");
  extensions::ChromeTestExtensionLoader loader(GetProfile());
  loader.set_allow_incognito_access(true);
  scoped_refptr<const extensions::Extension> extension =
      loader.LoadExtension(extension_dir.UnpackedPath());
  ASSERT_TRUE(extension);

  // This request will show up as cross-site because the chrome-extension URL
  // won't match the test_server domain (127.0.0.1), but because we set
  // |force_ignore_site_for_cookies| to true for extension-initiated requests,
  // this will actually be able to get the cookie.
  GURL url = test_server.GetURL("/echocookieheader");
  std::string script = R"((url => {
    var xhr = new XMLHttpRequest();
    xhr.open('GET', url, true);
    xhr.onload = () => chrome.test.sendScriptResult(xhr.responseText);
    xhr.send();
  }))";
  base::Value result =
      extensions::browsertest_util::ExecuteScriptInBackgroundPage(
          GetProfile(), extension->id(), script + "('" + url.spec() + "')");
  EXPECT_EQ("cookie", result);
}
#endif

IN_PROC_BROWSER_TEST_P(NetworkContextConfigurationBrowserTest, BasicRequest) {
  if (IsRestartStateWithInProcessNetworkService())
    return;
  std::unique_ptr<network::ResourceRequest> request =
      std::make_unique<network::ResourceRequest>();
  request->url = embedded_test_server()->GetURL("/echo");
  request->credentials_mode = network::mojom::CredentialsMode::kOmit;
  content::SimpleURLLoaderTestHelper simple_loader_helper;
  std::unique_ptr<network::SimpleURLLoader> simple_loader =
      network::SimpleURLLoader::Create(std::move(request),
                                       TRAFFIC_ANNOTATION_FOR_TESTS);

  simple_loader->DownloadToStringOfUnboundedSizeUntilCrashAndDie(
      loader_factory(), simple_loader_helper.GetCallbackDeprecated());
  simple_loader_helper.WaitForCallback();

  ASSERT_TRUE(simple_loader->ResponseInfo());
  ASSERT_TRUE(simple_loader->ResponseInfo()->headers);
  EXPECT_EQ(200, simple_loader->ResponseInfo()->headers->response_code());
  ASSERT_TRUE(simple_loader_helper.response_body());
  EXPECT_EQ("Echo", *simple_loader_helper.response_body());
}

// Make sure a cache is used when expected.
IN_PROC_BROWSER_TEST_P(NetworkContextConfigurationBrowserTest, Cache) {
  if (IsRestartStateWithInProcessNetworkService())
    return;
  // Crashing the network service may corrupt the disk cache, so skip this test
  // in tests that crash the network service and use an on-disk cache.
  if (GetParam().network_service_state == NetworkServiceState::kRestarted &&
      GetHttpCacheType() == StorageType::kDisk) {
    return;
  }

  // Make a request whose response should be cached.
  GURL request_url = embedded_test_server()->GetURL(kCacheRandomPath);
  url::Origin request_origin =
      url::Origin::Create(embedded_test_server()->base_url());
  std::unique_ptr<network::ResourceRequest> request =
      std::make_unique<network::ResourceRequest>();
  request->url = request_url;
  request->trusted_params = network::ResourceRequest::TrustedParams();
  request->trusted_params->isolation_info =
      net::IsolationInfo::CreateForInternalRequest(request_origin);
  request->site_for_cookies =
      request->trusted_params->isolation_info.site_for_cookies();

  content::SimpleURLLoaderTestHelper simple_loader_helper;
  std::unique_ptr<network::SimpleURLLoader> simple_loader =
      network::SimpleURLLoader::Create(std::move(request),
                                       TRAFFIC_ANNOTATION_FOR_TESTS);

  simple_loader->DownloadToStringOfUnboundedSizeUntilCrashAndDie(
      loader_factory(), simple_loader_helper.GetCallbackDeprecated());
  simple_loader_helper.WaitForCallback();

  ASSERT_TRUE(simple_loader_helper.response_body());
  EXPECT_GT(simple_loader_helper.response_body()->size(), 0u);

  // Make the request again, and make sure it's cached or not, according to
  // expectations. Reuse the content::ResourceRequest, but nothing else.
  std::unique_ptr<network::ResourceRequest> request2 =
      std::make_unique<network::ResourceRequest>();
  request2->url = request_url;
  request2->trusted_params = network::ResourceRequest::TrustedParams();
  request2->trusted_params->isolation_info =
      net::IsolationInfo::CreateForInternalRequest(request_origin);
  request2->site_for_cookies =
      request2->trusted_params->isolation_info.site_for_cookies();

  content::SimpleURLLoaderTestHelper simple_loader_helper2;
  std::unique_ptr<network::SimpleURLLoader> simple_loader2 =
      network::SimpleURLLoader::Create(std::move(request2),
                                       TRAFFIC_ANNOTATION_FOR_TESTS);
  simple_loader2->DownloadToStringOfUnboundedSizeUntilCrashAndDie(
      loader_factory(), simple_loader_helper2.GetCallbackDeprecated());
  simple_loader_helper2.WaitForCallback();
  ASSERT_TRUE(simple_loader_helper2.response_body());
  if (GetHttpCacheType() == StorageType::kNone) {
    // If there's no cache, the request should have returned a different
    // response than before.
    EXPECT_NE(*simple_loader_helper.response_body(),
              *simple_loader_helper2.response_body());
  } else {
    // Otherwise, the request should have returned the same result as before.
    EXPECT_EQ(*simple_loader_helper.response_body(),
              *simple_loader_helper2.response_body());
  }
}

// Make sure that NetworkContexts can't access each other's disk caches.
IN_PROC_BROWSER_TEST_P(NetworkContextConfigurationBrowserTest, CacheIsolation) {
  if (IsRestartStateWithInProcessNetworkService())
    return;
  // Make a request whose response should be cached.
  GURL request_url = embedded_test_server()->GetURL("/cachetime");
  std::unique_ptr<network::ResourceRequest> request =
      std::make_unique<network::ResourceRequest>();
  request->url = request_url;
  request->credentials_mode = network::mojom::CredentialsMode::kOmit;
  content::SimpleURLLoaderTestHelper simple_loader_helper;
  std::unique_ptr<network::SimpleURLLoader> simple_loader =
      network::SimpleURLLoader::Create(std::move(request),
                                       TRAFFIC_ANNOTATION_FOR_TESTS);

  simple_loader->DownloadToStringOfUnboundedSizeUntilCrashAndDie(
      loader_factory(), simple_loader_helper.GetCallbackDeprecated());
  simple_loader_helper.WaitForCallback();

  ASSERT_TRUE(simple_loader_helper.response_body());
  EXPECT_GT(simple_loader_helper.response_body()->size(), 0u);

  // Stop the server.
  ASSERT_TRUE(embedded_test_server()->ShutdownAndWaitUntilComplete());

  // Make the request again, for each other network context, and make sure the
  // response is not cached.
  ForEachOtherContext(
      base::BindLambdaForTesting([&](NetworkContextType network_context_type) {
        std::unique_ptr<network::ResourceRequest> request2 =
            std::make_unique<network::ResourceRequest>();
        request2->url = request_url;
        request2->credentials_mode = network::mojom::CredentialsMode::kOmit;
        content::SimpleURLLoaderTestHelper simple_loader_helper2;
        std::unique_ptr<network::SimpleURLLoader> simple_loader2 =
            network::SimpleURLLoader::Create(std::move(request2),
                                             TRAFFIC_ANNOTATION_FOR_TESTS);
        simple_loader2->DownloadToStringOfUnboundedSizeUntilCrashAndDie(
            GetLoaderFactoryForContextType(network_context_type),
            simple_loader_helper2.GetCallbackDeprecated());
        simple_loader_helper2.WaitForCallback();
        EXPECT_FALSE(simple_loader_helper2.response_body());
        EXPECT_EQ(net::ERR_CONNECTION_REFUSED, simple_loader2->NetError());
      }));
}

// Make sure an on-disk cache is used when expected. PRE_DiskCache populates the
// cache. DiskCache then makes sure the cache entry is still there (Or not) as
// expected.
IN_PROC_BROWSER_TEST_P(NetworkContextConfigurationBrowserTest, PRE_DiskCache) {
  if (IsRestartStateWithInProcessNetworkService())
    return;
  // Save test URL to disk, so it can be used in the next test (Test server uses
  // a random port, so need to know the port to try and retrieve it from the
  // cache in the next test). The profile directory is preserved between the
  // PRE_DiskCache and DiskCache run, so can just keep a file there.
  GURL test_url = embedded_test_server()->GetURL(kCacheRandomPath);
  url::Origin test_origin = url::Origin::Create(test_url);
  base::ScopedAllowBlockingForTesting allow_blocking;
  base::FilePath save_url_file_path = browser()->profile()->GetPath().Append(
      FILE_PATH_LITERAL("url_for_test.txt"));

  // Make a request whose response should be cached.
  std::unique_ptr<network::ResourceRequest> request =
      std::make_unique<network::ResourceRequest>();
  request->url = test_url;
  request->trusted_params = network::ResourceRequest::TrustedParams();
  request->trusted_params->isolation_info =
      net::IsolationInfo::CreateForInternalRequest(test_origin);
  request->site_for_cookies =
      request->trusted_params->isolation_info.site_for_cookies();

  content::SimpleURLLoaderTestHelper simple_loader_helper;
  std::unique_ptr<network::SimpleURLLoader> simple_loader =
      network::SimpleURLLoader::Create(std::move(request),
                                       TRAFFIC_ANNOTATION_FOR_TESTS);
  simple_loader->DownloadToStringOfUnboundedSizeUntilCrashAndDie(
      loader_factory(), simple_loader_helper.GetCallbackDeprecated());
  simple_loader_helper.WaitForCallback();

  EXPECT_EQ(net::OK, simple_loader->NetError());
  ASSERT_TRUE(simple_loader_helper.response_body());
  EXPECT_FALSE(simple_loader_helper.response_body()->empty());

  // Write the URL and expected response to a file.
  std::string file_data =
      test_url.spec() + "\n" + *simple_loader_helper.response_body();
  ASSERT_TRUE(base::WriteFile(save_url_file_path, file_data));

  EXPECT_TRUE(embedded_test_server()->ShutdownAndWaitUntilComplete());
}

// Check if the URL loaded in PRE_DiskCache is still in the cache, across a
// browser restart.
// TODO(crbug.com/40922934): Fix test flake and re-enable
#if BUILDFLAG(IS_MAC)
#define MAYBE_DiskCache DISABLED_DiskCache
#else
#define MAYBE_DiskCache DiskCache
#endif
IN_PROC_BROWSER_TEST_P(NetworkContextConfigurationBrowserTest,
                       MAYBE_DiskCache) {
  if (IsRestartStateWithInProcessNetworkService())
    return;
  // Crashing the network service may corrupt the disk cache, so skip this phase
  // in tests that crash the network service and use an on-disk cache.
  if (GetParam().network_service_state == NetworkServiceState::kRestarted &&
      GetHttpCacheType() == StorageType::kDisk) {
    return;
  }

  // Load URL from the above test body to disk.
  base::ScopedAllowBlockingForTesting allow_blocking;
  base::FilePath save_url_file_path = browser()->profile()->GetPath().Append(
      FILE_PATH_LITERAL("url_for_test.txt"));
  std::string file_data;
  ASSERT_TRUE(ReadFileToString(save_url_file_path, &file_data));

  size_t newline_pos = file_data.find('\n');
  ASSERT_NE(newline_pos, std::string::npos);

  GURL test_url = GURL(file_data.substr(0, newline_pos));
  ASSERT_TRUE(test_url.is_valid()) << test_url.possibly_invalid_spec();
  url::Origin test_origin = url::Origin::Create(test_url);

  std::string original_response = file_data.substr(newline_pos + 1);

  // Request the same test URL as may have been cached by PRE_DiskCache.
  std::unique_ptr<network::ResourceRequest> request =
      std::make_unique<network::ResourceRequest>();
  request->url = test_url;
  request->trusted_params = network::ResourceRequest::TrustedParams();
  request->trusted_params->isolation_info =
      net::IsolationInfo::CreateForInternalRequest(test_origin);
  request->site_for_cookies =
      request->trusted_params->isolation_info.site_for_cookies();

  content::SimpleURLLoaderTestHelper simple_loader_helper;
  request->load_flags = net::LOAD_ONLY_FROM_CACHE;
  std::unique_ptr<network::SimpleURLLoader> simple_loader =
      network::SimpleURLLoader::Create(std::move(request),
                                       TRAFFIC_ANNOTATION_FOR_TESTS);
  simple_loader->DownloadToStringOfUnboundedSizeUntilCrashAndDie(
      loader_factory(), simple_loader_helper.GetCallbackDeprecated());
  simple_loader_helper.WaitForCallback();

  // The request should only succeed if there is an on-disk cache.
  if (GetHttpCacheType() != StorageType::kDisk) {
    EXPECT_FALSE(simple_loader_helper.response_body());
  } else {
    DCHECK_NE(GetParam().network_service_state,
              NetworkServiceState::kRestarted);
    ASSERT_TRUE(simple_loader_helper.response_body());
    EXPECT_EQ(original_response, *simple_loader_helper.response_body());
  }
}

// Make sure that NetworkContexts have separate DNS caches.
IN_PROC_BROWSER_TEST_P(NetworkContextConfigurationBrowserTest,
                       DnsCacheIsolation) {
  net::NetworkAnonymizationKey network_anonymization_key =
      net::NetworkAnonymizationKey::CreateTransient();
  net::HostPortPair host_port_pair(kHostname, 0);
  network::mojom::ResolveHostParametersPtr params =
      network::mojom::ResolveHostParameters::New();
  // Use A queries, to avoid running into issues with the IPv6 probe, the
  // results of which can change during runtime, and can affect the DNS cache
  // key.
  params->dns_query_type = net::DnsQueryType ::A;
  // Resolve |host_port_pair|, which should succeed and put it in the
  // NetworkContext's cache.
  network::DnsLookupResult result =
      network::BlockingDnsLookup(network_context(), host_port_pair,
                                 std::move(params), network_anonymization_key);
  EXPECT_EQ(net::OK, result.error);
  ASSERT_TRUE(result.resolved_addresses.has_value());
  ASSERT_EQ(1u, result.resolved_addresses->size());
  EXPECT_EQ(kAddress,
            result.resolved_addresses.value()[0].ToStringWithoutPort());
  // Make a cache-only request for the same hostname, for each other network
  // context, and make sure no result is returned.
  ForEachOtherContext(
      base::BindLambdaForTesting([&](NetworkContextType network_context_type) {
        params = network::mojom::ResolveHostParameters::New();
        params->dns_query_type = net::DnsQueryType ::A;
        // Cache only lookup.
        params->cache_usage =
            network::mojom::ResolveHostParameters::CacheUsage::STALE_ALLOWED;
        params->source = net::HostResolverSource::LOCAL_ONLY;
        network::DnsLookupResult result = network::BlockingDnsLookup(
            GetNetworkContextForContextType(network_context_type),
            host_port_pair, std::move(params), network_anonymization_key);
        EXPECT_EQ(net::ERR_NAME_NOT_RESOLVED, result.error);
      }));
  // Do a cache-only lookup using the original network context, which should
  // return the same result it initially did.
  params = network::mojom::ResolveHostParameters::New();
  // Cache only lookup.
  params->dns_query_type = net::DnsQueryType ::A;
  params->source = net::HostResolverSource::LOCAL_ONLY;
  params->cache_usage =
      network::mojom::ResolveHostParameters::CacheUsage::STALE_ALLOWED;
  result =
      network::BlockingDnsLookup(network_context(), host_port_pair,
                                 std::move(params), network_anonymization_key);
  EXPECT_EQ(net::OK, result.error);
  ASSERT_TRUE(result.resolved_addresses.has_value());
  ASSERT_EQ(1u, result.resolved_addresses->size());
  EXPECT_EQ(kAddress,
            result.resolved_addresses.value()[0].ToStringWithoutPort());
}

// Visits a URL with an HSTS header, and makes sure it is respected.
IN_PROC_BROWSER_TEST_P(NetworkContextConfigurationBrowserTest, PRE_Hsts) {
  if (IsRestartStateWithInProcessNetworkService())
    return;
  net::test_server::EmbeddedTestServer ssl_server(
      net::test_server::EmbeddedTestServer::TYPE_HTTPS);
  ssl_server.SetCertHostnames({kHstsHostname});
  ssl_server.AddDefaultHandlers(GetChromeTestDataDir());
  ASSERT_TRUE(ssl_server.Start());

  // Make a request whose response has an STS header.
  std::unique_ptr<network::ResourceRequest> request =
      std::make_unique<network::ResourceRequest>();
  request->url = ssl_server.GetURL(
      kHstsHostname, "/set-header?Strict-Transport-Security: max-age%3D600000");
  request->credentials_mode = network::mojom::CredentialsMode::kOmit;

  content::SimpleURLLoaderTestHelper simple_loader_helper;
  std::unique_ptr<network::SimpleURLLoader> simple_loader =
      network::SimpleURLLoader::Create(std::move(request),
                                       TRAFFIC_ANNOTATION_FOR_TESTS);
  simple_loader->DownloadToStringOfUnboundedSizeUntilCrashAndDie(
      loader_factory(), simple_loader_helper.GetCallbackDeprecated());
  simple_loader_helper.WaitForCallback();

  EXPECT_EQ(net::OK, simple_loader->NetError());
  ASSERT_TRUE(simple_loader->ResponseInfo()->headers);
  EXPECT_TRUE(simple_loader->ResponseInfo()->headers->HasHeaderValue(
      "Strict-Transport-Security", "max-age=600000"));

  // Make a cache-only request to make sure the HSTS entry is respected. Using a
  // cache-only request both prevents the result from being cached, and makes
  // the check identical to the one in the next test, which is run after the
  // test server has been shut down.
  GURL exected_ssl_url = ssl_server.GetURL(kHstsHostname, "/");
  GURL::Replacements replacements;
  replacements.SetSchemeStr("http");
  GURL start_url = exected_ssl_url.ReplaceComponents(replacements);
  url::Origin origin = url::Origin::Create(start_url);

  request = std::make_unique<network::ResourceRequest>();
  request->url = start_url;
  request->load_flags = net::LOAD_ONLY_FROM_CACHE;
  // Have this request simulate a main frame request. This is necessary when
  // kHstsTopLevelNavigationsOnly is enabled.
  request->site_for_cookies = net::SiteForCookies::FromOrigin(origin);
  request->update_first_party_url_on_redirect = true;
  request->trusted_params.emplace();
  request->trusted_params->isolation_info = net::IsolationInfo::Create(
      net::IsolationInfo::RequestType::kMainFrame, origin, origin,
      net::SiteForCookies::FromOrigin(origin));

  content::SimpleURLLoaderTestHelper simple_loader_helper2;
  simple_loader = network::SimpleURLLoader::Create(
      std::move(request), TRAFFIC_ANNOTATION_FOR_TESTS);
  simple_loader->DownloadToStringOfUnboundedSizeUntilCrashAndDie(
      loader_factory(), simple_loader_helper2.GetCallbackDeprecated());
  simple_loader_helper2.WaitForCallback();
  EXPECT_FALSE(simple_loader_helper2.response_body());
  EXPECT_EQ(exected_ssl_url, simple_loader->GetFinalURL());

  // Write the URL with HSTS information to a file, so it can be loaded in the
  // next test. Have to use a file for this, since the server's port is random.
  base::ScopedAllowBlockingForTesting allow_blocking;
  base::FilePath save_url_file_path = browser()->profile()->GetPath().Append(
      FILE_PATH_LITERAL("url_for_test.txt"));
  std::string file_data = start_url.spec();
  ASSERT_TRUE(base::WriteFile(save_url_file_path, file_data));
}

// Checks if the HSTS information from the last test is still available after a
// restart.
IN_PROC_BROWSER_TEST_P(NetworkContextConfigurationBrowserTest, Hsts) {
  if (IsRestartStateWithInProcessNetworkService())
    return;
  // The network service must be cleanly shut down to guarantee HSTS information
  // is flushed to disk, but that currently generally doesn't happen. See
  // https://crbug.com/820996.
  if (GetHttpCacheType() == StorageType::kDisk) {
    return;
  }
  base::ScopedAllowBlockingForTesting allow_blocking;
  base::FilePath save_url_file_path = browser()->profile()->GetPath().Append(
      FILE_PATH_LITERAL("url_for_test.txt"));
  std::string file_data;
  ASSERT_TRUE(ReadFileToString(save_url_file_path, &file_data));
  GURL start_url = GURL(file_data);
  url::Origin origin = url::Origin::Create(start_url);

  // Unfortunately, loading HSTS information is loaded asynchronously from
  // disk, so there's no way to guarantee it has loaded by the time a
  // request is made. As a result, may have to try multiple times to verify that
  // cached HSTS information has been loaded, when it's stored on disk.
  while (true) {
    std::unique_ptr<network::ResourceRequest> request =
        std::make_unique<network::ResourceRequest>();
    request->url = start_url;
    request->load_flags = net::LOAD_ONLY_FROM_CACHE;
    // Have this request simulate a main frame request. This is necessary when
    // kHstsTopLevelNavigationsOnly is enabled.
    request->site_for_cookies = net::SiteForCookies::FromOrigin(origin);
    request->update_first_party_url_on_redirect = true;
    request->trusted_params.emplace();
    request->trusted_params->isolation_info = net::IsolationInfo::Create(
        net::IsolationInfo::RequestType::kMainFrame, origin, origin,
        net::SiteForCookies::FromOrigin(origin));

    content::SimpleURLLoaderTestHelper simple_loader_helper;
    std::unique_ptr<network::SimpleURLLoader> simple_loader =
        network::SimpleURLLoader::Create(std::move(request),
                                         TRAFFIC_ANNOTATION_FOR_TESTS);
    simple_loader->DownloadToStringOfUnboundedSizeUntilCrashAndDie(
        loader_factory(), simple_loader_helper.GetCallbackDeprecated());
    simple_loader_helper.WaitForCallback();
    EXPECT_FALSE(simple_loader_helper.response_body());

    // HSTS information is currently stored on disk if-and-only-if there's an
    // on-disk HTTP cache.
    if (GetHttpCacheType() == StorageType::kDisk) {
      GURL::Replacements replacements;
      replacements.SetSchemeStr("https");
      GURL expected_https_url = start_url.ReplaceComponents(replacements);
      // The file may not have been loaded yet, so if the cached HSTS
      // information was not respected, try again.
      if (expected_https_url != simple_loader->GetFinalURL())
        continue;
      EXPECT_EQ(expected_https_url, simple_loader->GetFinalURL());
      break;
    } else {
      EXPECT_EQ(start_url, simple_loader->GetFinalURL());
      break;
    }
  }
}

IN_PROC_BROWSER_TEST_P(NetworkContextConfigurationBrowserTest, ProxyConfig) {
  if (IsRestartStateWithInProcessNetworkService())
    return;
  SetProxyPref(embedded_test_server()->host_port_pair());
  TestProxyConfigured(/*expect_success=*/true);
}

// This test should not end in an AssertNoURLLRequests CHECK.
IN_PROC_BROWSER_TEST_P(NetworkContextConfigurationBrowserTest,
                       ShutdownWithLiveRequest) {
  if (IsRestartStateWithInProcessNetworkService())
    return;
  MakeLongLivedRequestThatHangsUntilShutdown();
}

// Disabled due to flakiness. See crbug.com/1189031.
#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) || BUILDFLAG(IS_MAC)
#define MAYBE_UserAgentAndLanguagePrefs DISABLED_UserAgentAndLanguagePrefs
#else
#define MAYBE_UserAgentAndLanguagePrefs UserAgentAndLanguagePrefs
#endif
IN_PROC_BROWSER_TEST_P(NetworkContextConfigurationBrowserTest,
                       MAYBE_UserAgentAndLanguagePrefs) {
  if (IsRestartStateWithInProcessNetworkService())
    return;
  // The system and SafeBrowsing network contexts aren't associated with any
  // profile, so changing the language settings for the profile's main network
  // context won't affect what they send.
  bool system =
      (GetParam().network_context_type == NetworkContextType::kSystem ||
       GetParam().network_context_type == NetworkContextType::kSafeBrowsing);
  // echoheader returns "None" when the header isn't there in the first place.
  const char kNoAcceptLanguage[] = "None";

  std::string accept_language, user_agent;
  // Check default.
  ASSERT_TRUE(FetchHeaderEcho("accept-language", &accept_language));
  EXPECT_EQ(system ? kNoAcceptLanguage : "en-US,en;q=0.9", accept_language);
  ASSERT_TRUE(FetchHeaderEcho("user-agent", &user_agent));
  EXPECT_EQ(embedder_support::GetUserAgent(), user_agent);

  // Change AcceptLanguages preferences, and check that headers are updated.
  // First, A single language.
  browser()->profile()->GetPrefs()->SetString(language::prefs::kAcceptLanguages,
                                              "zu");
  FlushNetworkInterface();
  std::string accept_language2, user_agent2;
  ASSERT_TRUE(FetchHeaderEcho("accept-language", &accept_language2));
  EXPECT_EQ(system ? kNoAcceptLanguage : "zu", accept_language2);
  ASSERT_TRUE(FetchHeaderEcho("user-agent", &user_agent2));
  EXPECT_EQ(embedder_support::GetUserAgent(), user_agent2);

  // Second, a single language with locale.
  browser()->profile()->GetPrefs()->SetString(language::prefs::kAcceptLanguages,
                                              "zu-ZA");
  FlushNetworkInterface();
  std::string accept_language3, user_agent3;
  ASSERT_TRUE(FetchHeaderEcho("accept-language", &accept_language3));
  EXPECT_EQ(system ? kNoAcceptLanguage : "zu-ZA,zu;q=0.9", accept_language3);
  ASSERT_TRUE(FetchHeaderEcho("user-agent", &user_agent3));
  EXPECT_EQ(embedder_support::GetUserAgent(), user_agent3);

  // Third, a list with multiple languages. Incognito mode should return only
  // the first.
  browser()->profile()->GetPrefs()->SetString(language::prefs::kAcceptLanguages,
                                              "ar,am,en-GB,ru,zu");
  FlushNetworkInterface();
  std::string accept_language4;
  std::string user_agent4;
  ASSERT_TRUE(FetchHeaderEcho("accept-language", &accept_language4));
  if (GetProfile()->IsOffTheRecord()) {
    EXPECT_EQ(system ? kNoAcceptLanguage : "ar", accept_language4);
  } else {
    EXPECT_EQ(system ? kNoAcceptLanguage
                     : "ar,am;q=0.9,en-GB;q=0.8,en;q=0.7,ru;q=0.6,zu;q=0.5",
              accept_language4);
  }
  ASSERT_TRUE(FetchHeaderEcho("user-agent", &user_agent4));
  EXPECT_EQ(embedder_support::GetUserAgent(), user_agent4);
}

// First part of testing enable referrers. Check that referrers are enabled by
// default at browser start, and referrers are indeed sent. Then disable
// referrers, and make sure that they aren't set.
IN_PROC_BROWSER_TEST_P(NetworkContextConfigurationBrowserTest,
                       PRE_EnableReferrers) {
  if (IsRestartStateWithInProcessNetworkService())
    return;
  const GURL kReferrer("http://referrer/");

  // Referrers should be enabled by default.
  EXPECT_TRUE(GetPrefService()->GetBoolean(prefs::kEnableReferrers));

  // Send a request, make sure the referrer is sent.
  std::string referrer;
  std::unique_ptr<network::ResourceRequest> request =
      std::make_unique<network::ResourceRequest>();
  request->referrer = kReferrer;
  request->credentials_mode = network::mojom::CredentialsMode::kOmit;
  ASSERT_TRUE(FetchHeaderEcho("referer", &referrer, std::move(request)));

  // SafeBrowsing never sends the referrer since it doesn't need to.
  if (GetParam().network_context_type == NetworkContextType::kSafeBrowsing) {
    EXPECT_EQ("None", referrer);
  } else {
    EXPECT_EQ(kReferrer.spec(), referrer);
  }

  // Disable referrers, and flush the NetworkContext mojo interface it's set on,
  // to avoid any races with the URLLoaderFactory pipe.
  GetPrefService()->SetBoolean(prefs::kEnableReferrers, false);
  FlushNetworkInterface();

  // Send a request and make sure its referer is not sent.
  std::string referrer2;
  std::unique_ptr<network::ResourceRequest> request2 =
      std::make_unique<network::ResourceRequest>();
  request2->referrer = kReferrer;
  request2->credentials_mode = network::mojom::CredentialsMode::kOmit;
  ASSERT_TRUE(FetchHeaderEcho("referer", &referrer2, std::move(request2)));
  EXPECT_EQ("None", referrer2);
}

// Second part of enable referrer test. Referrer should still be disabled. Make
// sure that disable referrers option is respected after startup, as to just
// after changing it.
IN_PROC_BROWSER_TEST_P(NetworkContextConfigurationBrowserTest,
                       EnableReferrers) {
  if (IsRestartStateWithInProcessNetworkService())
    return;
  const GURL kReferrer("http://referrer/");

  // The preference is expected to be reset in incognito mode.
  if (is_incognito()) {
    EXPECT_TRUE(GetPrefService()->GetBoolean(prefs::kEnableReferrers));
    return;
  }

  // Referrers should still be disabled.
  EXPECT_FALSE(GetPrefService()->GetBoolean(prefs::kEnableReferrers));

  // Send a request and make sure its referer is not sent.
  std::string referrer;
  std::unique_ptr<network::ResourceRequest> request =
      std::make_unique<network::ResourceRequest>();
  request->referrer = kReferrer;
  request->credentials_mode = network::mojom::CredentialsMode::kOmit;
  ASSERT_TRUE(FetchHeaderEcho("referer", &referrer, std::move(request)));
  EXPECT_EQ("None", referrer);
}

// Make sure that sending referrers that violate the referrer policy results in
// errors.
IN_PROC_BROWSER_TEST_P(NetworkContextConfigurationBrowserTest,
                       PolicyViolatingReferrers) {
  if (IsRestartStateWithInProcessNetworkService())
    return;
  std::unique_ptr<network::ResourceRequest> request =
      std::make_unique<network::ResourceRequest>();
  request->url = embedded_test_server()->GetURL("/echoheader?Referer");
  request->credentials_mode = network::mojom::CredentialsMode::kOmit;
  request->referrer = GURL("http://referrer/");
  request->referrer_policy = net::ReferrerPolicy::NO_REFERRER;
  content::SimpleURLLoaderTestHelper simple_loader_helper;
  std::unique_ptr<network::SimpleURLLoader> simple_loader =
      network::SimpleURLLoader::Create(std::move(request),
                                       TRAFFIC_ANNOTATION_FOR_TESTS);

  simple_loader->DownloadToStringOfUnboundedSizeUntilCrashAndDie(
      loader_factory(), simple_loader_helper.GetCallbackDeprecated());
  simple_loader_helper.WaitForCallback();
  if (GetParam().network_context_type == NetworkContextType::kSafeBrowsing) {
    // Safebrowsing ignores referrers so the requests succeed.
    EXPECT_EQ(net::OK, simple_loader->NetError());
    ASSERT_TRUE(simple_loader_helper.response_body());
    EXPECT_EQ("None", *simple_loader_helper.response_body());
  } else {
    // In all other cases, the invalid referrer causes the request to fail.
    EXPECT_EQ(net::ERR_BLOCKED_BY_CLIENT, simple_loader->NetError());
  }
}

// Makes sure cookies are enabled by default, and saved to disk / not saved to
// disk as expected.
IN_PROC_BROWSER_TEST_P(NetworkContextConfigurationBrowserTest,
                       PRE_CookiesEnabled) {
  if (IsRestartStateWithInProcessNetworkService())
    return;
  EXPECT_TRUE(GetCookies(embedded_test_server()->base_url()).empty());

  SetCookie(CookieType::kFirstParty, CookiePersistenceType::kPersistent,
            embedded_test_server());
  EXPECT_FALSE(GetCookies(embedded_test_server()->base_url()).empty());
}

// Disabled due to flakiness. See https://crbug.com/1273903.
IN_PROC_BROWSER_TEST_P(NetworkContextConfigurationBrowserTest,
                       DISABLED_CookiesEnabled) {
  if (IsRestartStateWithInProcessNetworkService())
    return;
  // Check that the cookie from the first stage of the test was / was not
  // preserved between browser restarts, as expected.
  bool has_cookies = !GetCookies(embedded_test_server()->base_url()).empty();
  EXPECT_EQ(GetCookieStorageType() == StorageType::kDisk, has_cookies);
}

IN_PROC_BROWSER_TEST_P(NetworkContextConfigurationBrowserTest,
                       CookieIsolation) {
  if (IsRestartStateWithInProcessNetworkService())
    return;
  SetCookie(CookieType::kFirstParty, CookiePersistenceType::kPersistent,
            embedded_test_server());
  EXPECT_FALSE(GetCookies(embedded_test_server()->base_url()).empty());

  ForEachOtherContext(
      base::BindLambdaForTesting([&](NetworkContextType network_context_type) {
        EXPECT_TRUE(GetCookiesForContextType(network_context_type,
                                             embedded_test_server()->base_url())
                        .empty());
      }));
}

// Disabled due to flakiness. See https://crbug.com/1126755.
#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS)
#define MAYBE_PRE_ThirdPartyCookiesBlocked DISABLED_PRE_ThirdPartyCookiesBlocked
#define MAYBE_ThirdPartyCookiesBlocked DISABLED_ThirdPartyCookiesBlocked
#else
#define MAYBE_PRE_ThirdPartyCookiesBlocked PRE_ThirdPartyCookiesBlocked
#define MAYBE_ThirdPartyCookiesBlocked ThirdPartyCookiesBlocked
#endif
IN_PROC_BROWSER_TEST_P(NetworkContextConfigurationBrowserTest,
                       MAYBE_PRE_ThirdPartyCookiesBlocked) {
  if (IsRestartStateWithInProcessNetworkService())
    return;
  // The system and SafeBrowsing network contexts don't support the third party
  // cookie blocking options, since they have no notion of third parties.
  bool system =
      GetParam().network_context_type == NetworkContextType::kSystem ||
      GetParam().network_context_type == NetworkContextType::kSafeBrowsing;
  if (system)
    return;

  GetPrefService()->SetInteger(
      prefs::kCookieControlsMode,
      static_cast<int>(content_settings::CookieControlsMode::kBlockThirdParty));
  SetCookie(CookieType::kThirdParty, CookiePersistenceType::kSession,
            https_server());

  EXPECT_TRUE(GetCookies(https_server()->base_url()).empty());
}

// Disabled due to flakiness. See https://crbug.com/1126755.
IN_PROC_BROWSER_TEST_P(NetworkContextConfigurationBrowserTest,
                       MAYBE_ThirdPartyCookiesBlocked) {
  if (IsRestartStateWithInProcessNetworkService())
    return;
  // The system and SafeBrowsing network contexts don't support the third party
  // cookie blocking options, since they have no notion of third parties.
  bool system =
      GetParam().network_context_type == NetworkContextType::kSystem ||
      GetParam().network_context_type == NetworkContextType::kSafeBrowsing;
  if (system)
    return;

  // The third-party cookies pref should carry over to the next session.
  EXPECT_EQ(
      static_cast<int>(content_settings::CookieControlsMode::kBlockThirdParty),
      GetPrefService()->GetInteger(prefs::kCookieControlsMode));
  SetCookie(CookieType::kThirdParty, CookiePersistenceType::kSession,
            https_server());

  EXPECT_TRUE(GetCookies(https_server()->base_url()).empty());

  // Add exception, third party cookies should be allowed now.
  CookieSettingsFactory::GetForProfile(browser()->profile())
      ->SetCookieSetting(https_server()->base_url(), CONTENT_SETTING_ALLOW);
  // Set a third-party cookie. It should actually get set this time.
  SetCookie(CookieType::kThirdParty, CookiePersistenceType::kSession,
            https_server());

  EXPECT_FALSE(GetCookies(https_server()->base_url()).empty());
}

IN_PROC_BROWSER_TEST_P(NetworkContextConfigurationBrowserTest,
                       PRE_CookieSettings) {
  if (IsRestartStateWithInProcessNetworkService())
    return;
  // The system and SafeBrowsing network contexts don't respect cookie blocking
  // options, which are per-profile.
  bool system =
      GetParam().network_context_type == NetworkContextType::kSystem ||
      GetParam().network_context_type == NetworkContextType::kSafeBrowsing;
  if (system)
    return;

  CookieSettingsFactory::GetForProfile(browser()->profile())
      ->SetDefaultCookieSetting(CONTENT_SETTING_BLOCK);
  FlushNetworkInterface();
  SetCookie(CookieType::kFirstParty, CookiePersistenceType::kSession,
            embedded_test_server());

  EXPECT_TRUE(GetCookies(embedded_test_server()->base_url()).empty());
}

IN_PROC_BROWSER_TEST_P(NetworkContextConfigurationBrowserTest, CookieSettings) {
  if (IsRestartStateWithInProcessNetworkService())
    return;
  // The system and SafeBrowsing network contexts don't respect cookie blocking
  // options, which are per-profile.
  bool system =
      GetParam().network_context_type == NetworkContextType::kSystem ||
      GetParam().network_context_type == NetworkContextType::kSafeBrowsing;
  if (system)
    return;

  // The content settings should carry over to the next session.
  SetCookie(CookieType::kFirstParty, CookiePersistenceType::kSession,
            embedded_test_server());

  EXPECT_TRUE(GetCookies(embedded_test_server()->base_url()).empty());

  // Set default setting to allow, cookies should be set now.
  CookieSettingsFactory::GetForProfile(browser()->profile())
      ->SetDefaultCookieSetting(CONTENT_SETTING_ALLOW);
  FlushNetworkInterface();
  SetCookie(CookieType::kFirstParty, CookiePersistenceType::kSession,
            embedded_test_server());

  EXPECT_FALSE(GetCookies(embedded_test_server()->base_url()).empty());
}

// Make sure file uploads work.
IN_PROC_BROWSER_TEST_P(NetworkContextConfigurationBrowserTest, UploadFile) {
  if (IsRestartStateWithInProcessNetworkService())
    return;
  std::unique_ptr<network::ResourceRequest> request =
      std::make_unique<network::ResourceRequest>();
  request->method = "POST";
  request->url = embedded_test_server()->GetURL("/echo");
  request->credentials_mode = network::mojom::CredentialsMode::kOmit;
  content::SimpleURLLoaderTestHelper simple_loader_helper;
  std::unique_ptr<network::SimpleURLLoader> simple_loader =
      network::SimpleURLLoader::Create(std::move(request),
                                       TRAFFIC_ANNOTATION_FOR_TESTS);
  base::FilePath dir_test_data;
  base::PathService::Get(chrome::DIR_TEST_DATA, &dir_test_data);
  base::FilePath path =
      dir_test_data.Append(base::FilePath(FILE_PATH_LITERAL("simple.html")));
  simple_loader->AttachFileForUpload(path, "text/html");

  simple_loader->DownloadToStringOfUnboundedSizeUntilCrashAndDie(
      loader_factory(), simple_loader_helper.GetCallbackDeprecated());
  simple_loader_helper.WaitForCallback();

  ASSERT_TRUE(simple_loader->ResponseInfo());
  ASSERT_TRUE(simple_loader->ResponseInfo()->headers);
  EXPECT_EQ(200, simple_loader->ResponseInfo()->headers->response_code());
  ASSERT_TRUE(simple_loader_helper.response_body());
  base::ScopedAllowBlockingForTesting allow_blocking;
  std::string expected_response;
  base::ReadFileToString(path, &expected_response);
  EXPECT_EQ(expected_response.c_str(), *simple_loader_helper.response_body());
}

class NetworkContextConfigurationFixedPortBrowserTest
    : public NetworkContextConfigurationBrowserTest {
 public:
  NetworkContextConfigurationFixedPortBrowserTest() = default;
  ~NetworkContextConfigurationFixedPortBrowserTest() override = default;

  void SetUpCommandLine(base::CommandLine* command_line) override {
    command_line->AppendSwitchASCII(
        switches::kTestingFixedHttpPort,
        base::StringPrintf("%u", embedded_test_server()->port()));
    LOG(WARNING) << base::StringPrintf("%u", embedded_test_server()->port());
  }
};

// Test that the command line switch makes it to the network service and is
// respected.
IN_PROC_BROWSER_TEST_P(NetworkContextConfigurationFixedPortBrowserTest,
                       TestingFixedPort) {
  if (IsRestartStateWithInProcessNetworkService())
    return;
  std::unique_ptr<network::ResourceRequest> request =
      std::make_unique<network::ResourceRequest>();
  // This URL does not use the port the embedded test server is using. The
  // command line switch should make it result in the request being directed to
  // the test server anyways.
  request->url = GURL("http://127.0.0.1/echo");
  request->credentials_mode = network::mojom::CredentialsMode::kOmit;
  content::SimpleURLLoaderTestHelper simple_loader_helper;
  std::unique_ptr<network::SimpleURLLoader> simple_loader =
      network::SimpleURLLoader::Create(std::move(request),
                                       TRAFFIC_ANNOTATION_FOR_TESTS);

  simple_loader->DownloadToStringOfUnboundedSizeUntilCrashAndDie(
      loader_factory(), simple_loader_helper.GetCallbackDeprecated());
  simple_loader_helper.WaitForCallback();

  EXPECT_EQ(net::OK, simple_loader->NetError());
  ASSERT_TRUE(simple_loader_helper.response_body());
  EXPECT_EQ(*simple_loader_helper.response_body(), "Echo");
}

class NetworkContextConfigurationProxyOnStartBrowserTest
    : public NetworkContextConfigurationBrowserTest {
 public:
  NetworkContextConfigurationProxyOnStartBrowserTest() = default;

  NetworkContextConfigurationProxyOnStartBrowserTest(
      const NetworkContextConfigurationProxyOnStartBrowserTest&) = delete;
  NetworkContextConfigurationProxyOnStartBrowserTest& operator=(
      const NetworkContextConfigurationProxyOnStartBrowserTest&) = delete;

  ~NetworkContextConfigurationProxyOnStartBrowserTest() override = default;

  void SetUpCommandLine(base::CommandLine* command_line) override {
    command_line->AppendSwitchASCII(
        switches::kProxyServer,
        embedded_test_server()->host_port_pair().ToString());
  }
};

// Test that when there's a proxy configuration at startup, the initial requests
// use that configuration.
IN_PROC_BROWSER_TEST_P(NetworkContextConfigurationProxyOnStartBrowserTest,
                       TestInitialProxyConfig) {
  if (IsRestartStateWithInProcessNetworkService())
    return;
  TestProxyConfigured(/*expect_success=*/true);
}

// Make sure the system URLRequestContext can handle fetching PAC scripts from
// http URLs.
class NetworkContextConfigurationHttpPacBrowserTest
    : public NetworkContextConfigurationBrowserTest {
 public:
  NetworkContextConfigurationHttpPacBrowserTest()
      : pac_test_server_(net::test_server::EmbeddedTestServer::TYPE_HTTP) {}

  NetworkContextConfigurationHttpPacBrowserTest(
      const NetworkContextConfigurationHttpPacBrowserTest&) = delete;
  NetworkContextConfigurationHttpPacBrowserTest& operator=(
      const NetworkContextConfigurationHttpPacBrowserTest&) = delete;

  ~NetworkContextConfigurationHttpPacBrowserTest() override = default;

  void SetUpCommandLine(base::CommandLine* command_line) override {
    pac_test_server_.RegisterRequestHandler(base::BindRepeating(
        &NetworkContextConfigurationHttpPacBrowserTest::HandlePacRequest,
        GetPacScript()));
    EXPECT_TRUE(pac_test_server_.Start());

    command_line->AppendSwitchASCII(switches::kProxyPacUrl,
                                    pac_test_server_.base_url().spec().c_str());
  }

  static std::unique_ptr<net::test_server::HttpResponse> HandlePacRequest(
      const std::string& pac_script,
      const net::test_server::HttpRequest& request) {
    std::unique_ptr<net::test_server::BasicHttpResponse> response =
        std::make_unique<net::test_server::BasicHttpResponse>();
    response->set_content(pac_script);
    return response;
  }

 private:
  net::test_server::EmbeddedTestServer pac_test_server_;
};

IN_PROC_BROWSER_TEST_P(NetworkContextConfigurationHttpPacBrowserTest, HttpPac) {
  if (IsRestartStateWithInProcessNetworkService())
    return;
  TestProxyConfigured(/*expect_success=*/true);
}

// Make sure the system URLRequestContext can handle fetching PAC scripts from
// file URLs.
class NetworkContextConfigurationFilePacBrowserTest
    : public NetworkContextConfigurationBrowserTest {
 public:
  NetworkContextConfigurationFilePacBrowserTest() = default;

  NetworkContextConfigurationFilePacBrowserTest(
      const NetworkContextConfigurationFilePacBrowserTest&) = delete;
  NetworkContextConfigurationFilePacBrowserTest& operator=(
      const NetworkContextConfigurationFilePacBrowserTest&) = delete;

  ~NetworkContextConfigurationFilePacBrowserTest() override = default;

  void SetUpCommandLine(base::CommandLine* command_line) override {
    const char kPacFileName[] = "foo.pac";

    ASSERT_TRUE(temp_dir_.CreateUniqueTempDir());
    base::FilePath pac_file_path =
        temp_dir_.GetPath().AppendASCII(kPacFileName);

    std::string pac_script = GetPacScript();
    ASSERT_TRUE(base::WriteFile(pac_file_path, pac_script));

    command_line->AppendSwitchASCII(
        switches::kProxyPacUrl, net::FilePathToFileURL(pac_file_path).spec());
  }

 private:
  base::ScopedTempDir temp_dir_;
};

IN_PROC_BROWSER_TEST_P(NetworkContextConfigurationFilePacBrowserTest, FilePac) {
  if (IsRestartStateWithInProcessNetworkService())
    return;
  TestProxyConfigured(false);
}

// Make sure the system URLRequestContext can handle fetching PAC scripts from
// data URLs.
class NetworkContextConfigurationDataPacBrowserTest
    : public NetworkContextConfigurationBrowserTest {
 public:
  NetworkContextConfigurationDataPacBrowserTest() = default;

  NetworkContextConfigurationDataPacBrowserTest(
      const NetworkContextConfigurationDataPacBrowserTest&) = delete;
  NetworkContextConfigurationDataPacBrowserTest& operator=(
      const NetworkContextConfigurationDataPacBrowserTest&) = delete;

  ~NetworkContextConfigurationDataPacBrowserTest() override = default;

  void SetUpCommandLine(base::CommandLine* command_line) override {
    std::string contents;
    // Read in kPACScript contents.
    command_line->AppendSwitchASCII(switches::kProxyPacUrl,
                                    "data:," + GetPacScript());
  }
};

IN_PROC_BROWSER_TEST_P(NetworkContextConfigurationDataPacBrowserTest, DataPac) {
  if (IsRestartStateWithInProcessNetworkService())
    return;
  TestProxyConfigured(/*expect_success=*/true);
}

class NetworkContextConfigurationProxySettingsBrowserTest
    : public NetworkContextConfigurationHttpPacBrowserTest {
 public:
  const size_t kDefaultMaxConnectionsPerProxy = 32;

  NetworkContextConfigurationProxySettingsBrowserTest() = default;

  NetworkContextConfigurationProxySettingsBrowserTest(
      const NetworkContextConfigurationProxySettingsBrowserTest&) = delete;
  NetworkContextConfigurationProxySettingsBrowserTest& operator=(
      const NetworkContextConfigurationProxySettingsBrowserTest&) = delete;

  ~NetworkContextConfigurationProxySettingsBrowserTest() override = default;

  void SetUpOnMainThread() override {
    embedded_test_server()->RegisterRequestHandler(base::BindRepeating(
        &NetworkContextConfigurationProxySettingsBrowserTest::TrackConnections,
        base::Unretained(this)));

    expected_connections_loop_ptr_.store(nullptr);

    NetworkContextConfigurationHttpPacBrowserTest::SetUpOnMainThread();
  }

  virtual size_t GetExpectedMaxConnectionsPerProxy() const {
    return kDefaultMaxConnectionsPerProxy;
  }

  std::unique_ptr<net::test_server::HttpResponse> TrackConnections(
      const net::test_server::HttpRequest& request) {
    if (!base::StartsWith(request.relative_url, "/hung",
                          base::CompareCase::INSENSITIVE_ASCII))
      return nullptr;

    // Record the number of connections we're seeing.
    CHECK(observed_request_urls_.find(request.GetURL().spec()) ==
          observed_request_urls_.end());
    observed_request_urls_.emplace(request.GetURL().spec());
    CHECK_GE(GetExpectedMaxConnectionsPerProxy(),
             observed_request_urls_.size());

    // Once we've seen at least as many connections as we expect, we can quit
    // the loop on the main test thread. The test may choose to wait for
    // longer to see if there are any additional unexpected connections.
    if (GetExpectedMaxConnectionsPerProxy() == observed_request_urls_.size() &&
        expected_connections_loop_ptr_.load() != nullptr) {
      expected_connections_loop_ptr_.load()->Quit();
    }

    // To test the number of connections per proxy, we'll hang all responses.
    return std::make_unique<net::test_server::HungResponse>();
  }

  void RunMaxConnectionsPerProxyTest() {
    // At this point in the test, we've set up a proxy that points to our
    // embedded test server. We've also set things up to hang all incoming
    // requests and record how many concurrent connections we have running. To
    // detect the maximum number of requests per proxy, we now just have to
    // attempt to make as many requests as possible to ensure we don't see an
    // incorrect number of concurrent requests.

    // First of all, we're going to want to wait for at least as many
    // connections as we expect.
    base::RunLoop expected_connections_run_loop;
    expected_connections_loop_ptr_.store(&expected_connections_run_loop);

    std::vector<std::unique_ptr<network::SimpleURLLoader>> loaders(
        GetExpectedMaxConnectionsPerProxy());
    for (unsigned int i = 0; i < GetExpectedMaxConnectionsPerProxy() + 1; ++i) {
      std::unique_ptr<network::ResourceRequest> request =
          std::make_unique<network::ResourceRequest>();
      request->url =
          embedded_test_server()->GetURL(base::StringPrintf("foo%u.test", i),
                                         base::StringPrintf("/hung_%u", i));
      request->credentials_mode = network::mojom::CredentialsMode::kOmit;

      content::SimpleURLLoaderTestHelper simple_loader_helper;
      std::unique_ptr<network::SimpleURLLoader> simple_loader =
          network::SimpleURLLoader::Create(std::move(request),
                                           TRAFFIC_ANNOTATION_FOR_TESTS);

      simple_loader->DownloadToStringOfUnboundedSizeUntilCrashAndDie(
          loader_factory(), simple_loader_helper.GetCallbackDeprecated());
      loaders.emplace_back(std::move(simple_loader));
    }
    expected_connections_run_loop.Run();

    // Then wait for any remaining connections that we should NOT get.
    base::RunLoop ugly_100ms_wait;
    base::SingleThreadTaskRunner::GetCurrentDefault()->PostDelayedTask(
        FROM_HERE, ugly_100ms_wait.QuitClosure(), base::Milliseconds(100));
    ugly_100ms_wait.Run();

    // Stop the server.
    ASSERT_TRUE(embedded_test_server()->ShutdownAndWaitUntilComplete());
  }

 private:
  std::atomic<base::RunLoop*> expected_connections_loop_ptr_{nullptr};

  // In RunMaxConnectionsPerProxyTest(), we'll make several network requests
  // that hang. These hung requests are assumed to last for the duration of the
  // test. This member, which is only accessed from the server's IO thread,
  // records each observed request to ensure we see only as many connections as
  // we expect.
  std::unordered_set<std::string> observed_request_urls_;
};

// Test failure on macOS: crbug.com/1287934
#if BUILDFLAG(IS_MAC)
#define MAYBE_MaxConnectionsPerProxy DISABLED_MaxConnectionsPerProxy
#else
#define MAYBE_MaxConnectionsPerProxy MaxConnectionsPerProxy
#endif
IN_PROC_BROWSER_TEST_P(NetworkContextConfigurationProxySettingsBrowserTest,
                       MAYBE_MaxConnectionsPerProxy) {
  RunMaxConnectionsPerProxyTest();
}

class NetworkContextConfigurationManagedProxySettingsBrowserTest
    : public NetworkContextConfigurationProxySettingsBrowserTest {
 public:
  const size_t kTestMaxConnectionsPerProxy = 37;

  NetworkContextConfigurationManagedProxySettingsBrowserTest() = default;

  NetworkContextConfigurationManagedProxySettingsBrowserTest(
      const NetworkContextConfigurationManagedProxySettingsBrowserTest&) =
      delete;
  NetworkContextConfigurationManagedProxySettingsBrowserTest& operator=(
      const NetworkContextConfigurationManagedProxySettingsBrowserTest&) =
      delete;

  ~NetworkContextConfigurationManagedProxySettingsBrowserTest() override =
      default;

  void SetUpInProcessBrowserTestFixture() override {
    NetworkContextConfigurationProxySettingsBrowserTest::
        SetUpInProcessBrowserTestFixture();
    policy::PolicyMap policies;
    policies.Set(policy::key::kMaxConnectionsPerProxy,
                 policy::POLICY_LEVEL_MANDATORY, policy::POLICY_SCOPE_MACHINE,
                 policy::POLICY_SOURCE_CLOUD,
                 base::Value(static_cast<int>(kTestMaxConnectionsPerProxy)),
                 /*external_data_fetcher=*/nullptr);
    UpdateChromePolicy(policies);
  }

  size_t GetExpectedMaxConnectionsPerProxy() const override {
    return kTestMaxConnectionsPerProxy;
  }
};

// crbug.com/1288780: flaky on Mac.
#if BUILDFLAG(IS_MAC)
#define MAYBE_MaxConnectionsPerProxy DISABLED_MaxConnectionsPerProxy
#else
#define MAYBE_MaxConnectionsPerProxy MaxConnectionsPerProxy
#endif
IN_PROC_BROWSER_TEST_P(
    NetworkContextConfigurationManagedProxySettingsBrowserTest,
    MAYBE_MaxConnectionsPerProxy) {
  RunMaxConnectionsPerProxyTest();
}

#if BUILDFLAG(ENABLE_REPORTING)
// Used to test that we persist Reporting clients and NEL policies to disk, but
// only when appropriate.
class NetworkContextConfigurationReportingAndNelBrowserTest
    : public NetworkContextConfigurationBrowserTest {
 public:
  struct RequestState {
    content::SimpleURLLoaderTestHelper helper;
    std::unique_ptr<network::SimpleURLLoader> loader;
  };

  NetworkContextConfigurationReportingAndNelBrowserTest()
      : https_server_(net::test_server::EmbeddedTestServer::TYPE_HTTPS) {
    // Set up an SSL certificate so we can make requests to "https://localhost"
    https_server_.SetSSLConfig(
        net::test_server::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
    // Only start the server if we actually need it in the test (i.e., we'll
    // call StartAcceptingConnections somewhere in the test).
    if (!IsRestartStateWithInProcessNetworkService() &&
        AreReportingAndNelEnabled()) {
      EXPECT_TRUE(https_server_.InitializeAndListen());
    }

    // Make report delivery happen instantly.
    net::ReportingPolicy policy;
    policy.delivery_interval = base::Seconds(0);
    net::ReportingPolicy::UsePolicyForTesting(policy);
  }

  std::unique_ptr<RequestState> NewSimpleRequest(const GURL& url) {
    auto request_state = std::make_unique<RequestState>();
    std::unique_ptr<network::ResourceRequest> request =
        std::make_unique<network::ResourceRequest>();
    request->url = url;
    request->credentials_mode = network::mojom::CredentialsMode::kOmit;
    request_state->loader = network::SimpleURLLoader::Create(
        std::move(request), TRAFFIC_ANNOTATION_FOR_TESTS);
    request_state->loader->DownloadToStringOfUnboundedSizeUntilCrashAndDie(
        loader_factory(), request_state->helper.GetCallbackDeprecated());
    return request_state;
  }

  void SetUpCommandLine(base::CommandLine* command_line) override {
    command_line->AppendSwitch(embedder_support::kShortReportingDelay);
    // This switch will cause traffic to *any* port to go to https_server_,
    // regardless of which arbitrary port https_server_ decides to run on.
    // NEL and Reporting policies are only valid for a single origin.
    if (!IsRestartStateWithInProcessNetworkService() &&
        AreReportingAndNelEnabled()) {
      command_line->AppendSwitchASCII(switches::kTestingFixedHttpsPort,
                                      base::StringPrintf("%u", port()));
    }
  }

  net::EmbeddedTestServer* http_server() { return &https_server_; }
  int port() const { return https_server_.port(); }

  static GURL GetCollectorURL() { return GURL("https://localhost/upload"); }

  static std::string GetReportToHeader() {
    return "Report-To: {\"endpoints\":[{\"url\":\"" + GetCollectorURL().spec() +
           "\"}],\"max_age\":86400}\r\n";
  }

  static std::string GetNELHeader() {
    return "NEL: "
           "{\"report_to\":\"default\",\"max_age\":86400,\"success_fraction\":"
           "1.0}\r\n";
  }

  void RespondWithHeaders(net::test_server::ControllableHttpResponse* resp) {
    resp->WaitForRequest();
    resp->Send("HTTP/1.1 200 OK\r\n");
    resp->Send(GetReportToHeader());
    resp->Send(GetNELHeader());
    resp->Send("\r\n");
    resp->Done();
  }

  void RespondWithoutHeaders(net::test_server::ControllableHttpResponse* resp) {
    resp->WaitForRequest();
    resp->Send("HTTP/1.1 200 OK\r\n");
    resp->Send("\r\n");
    resp->Done();
  }

  bool AreReportingAndNelEnabled() const {
    switch (GetParam().network_context_type) {
      case NetworkContextType::kSystem:
      case NetworkContextType::kSafeBrowsing:
        return false;
      case NetworkContextType::kProfile:
      case NetworkContextType::kIncognitoProfile:
      case NetworkContextType::kOnDiskApp:
      case NetworkContextType::kInMemoryApp:
      case NetworkContextType::kOnDiskAppWithIncognitoProfile:
        return true;
    }
  }

  bool ExpectPersistenceEnabled() const {
    switch (GetParam().network_context_type) {
      case NetworkContextType::kSystem:
      case NetworkContextType::kSafeBrowsing:
      case NetworkContextType::kIncognitoProfile:
      case NetworkContextType::kInMemoryApp:
      case NetworkContextType::kOnDiskAppWithIncognitoProfile:
        return false;
      case NetworkContextType::kProfile:
      case NetworkContextType::kOnDiskApp:
        return true;
    }
  }

 private:
  net::EmbeddedTestServer https_server_;
};

namespace {

constexpr char kReportingEnabledURL[] = "https://localhost/page";
constexpr char kCrossOriginReportingEnabledURL[] = "https://localhost:444/page";

}  // namespace

IN_PROC_BROWSER_TEST_P(NetworkContextConfigurationReportingAndNelBrowserTest,
                       PRE_PersistReportingAndNel) {
  if (IsRestartStateWithInProcessNetworkService() ||
      !AreReportingAndNelEnabled()) {
    return;
  }

  net::test_server::ControllableHttpResponse original_response(http_server(),
                                                               "/page");
  net::test_server::ControllableHttpResponse upload_response(http_server(),
                                                             "/upload");
  http_server()->StartAcceptingConnections();

  // Make a request to /page and respond with Report-To and NEL headers, which
  // will turn on NEL for the localhost:443 origin.
  std::unique_ptr<RequestState> request =
      NewSimpleRequest(GURL(kReportingEnabledURL));
  RespondWithHeaders(&original_response);
  request->helper.WaitForCallback();

  // Wait for a request to /upload, which should happen because the previous
  // request precipitated a NEL report.
  upload_response.WaitForRequest();
  EXPECT_EQ(net::test_server::METHOD_POST,
            upload_response.http_request()->method);
}

IN_PROC_BROWSER_TEST_P(NetworkContextConfigurationReportingAndNelBrowserTest,
                       PersistReportingAndNel) {
  if (IsRestartStateWithInProcessNetworkService() ||
      !AreReportingAndNelEnabled()) {
    return;
  }

  net::test_server::ControllableHttpResponse original_response(http_server(),
                                                               "/page");
  net::test_server::ControllableHttpResponse cross_origin_response(
      http_server(), "/page");
  net::test_server::ControllableHttpResponse upload_response(http_server(),
                                                             "/upload");
  http_server()->StartAcceptingConnections();

  // Make a request that will only precipitate a NEL report if we loaded a NEL
  // policy from the store.
  std::unique_ptr<RequestState> request =
      NewSimpleRequest(GURL(kReportingEnabledURL));
  RespondWithoutHeaders(&original_response);
  request->helper.WaitForCallback();

  // Make another request that will generate another upload to the same
  // collector. If the previous request didn't generate a NEL report (e.g.,
  // because persistence is disabled) then this'll be first upload to the NEL
  // collector. Note that because this upload is to a different origin than the
  // request, Reporting will make a CORS preflight request, which is what we
  // look for.
  std::unique_ptr<RequestState> cross_origin_request =
      NewSimpleRequest(GURL(kCrossOriginReportingEnabledURL));
  RespondWithHeaders(&cross_origin_response);
  cross_origin_request->helper.WaitForCallback();

  // Wait for a request to /upload, which should happen because the previous
  // requests precipitated NEL reports.
  //
  // We assume that Reporting/NEL will send reports in the order we made the
  // requests above, which seems to be the case today but may not necessarily
  // true in general.
  upload_response.WaitForRequest();
  if (ExpectPersistenceEnabled()) {
    // A NEL upload about https://localhost
    EXPECT_EQ(net::test_server::METHOD_POST,
              upload_response.http_request()->method);
  } else {
    // A CORS preflight request before a cross-origin NEL upload about
    // https://localhost:444
    EXPECT_EQ(net::test_server::METHOD_OPTIONS,
              upload_response.http_request()->method);
  }
}
#endif  // BUILDFLAG(ENABLE_REPORTING)

// Instantiates tests with a prefix indicating which NetworkContext is being
// tested, and a suffix of "/0" if the network service is enabled, "/1" if it's
// enabled and restarted.
#define TEST_CASES(network_context_type)                           \
  TestCase({NetworkServiceState::kEnabled, network_context_type}), \
      TestCase({NetworkServiceState::kRestarted, network_context_type})

#if BUILDFLAG(ENABLE_EXTENSIONS)
#define INSTANTIATE_EXTENSION_TESTS(TestFixture)                        \
  INSTANTIATE_TEST_SUITE_P(                                             \
      OnDiskApp, TestFixture,                                           \
      ::testing::Values(TEST_CASES(NetworkContextType::kOnDiskApp)));   \
                                                                        \
  INSTANTIATE_TEST_SUITE_P(                                             \
      InMemoryApp, TestFixture,                                         \
      ::testing::Values(TEST_CASES(NetworkContextType::kInMemoryApp))); \
                                                                        \
  INSTANTIATE_TEST_SUITE_P(                                             \
      OnDiskAppWithIncognitoProfile, TestFixture,                       \
      ::testing::Values(                                                \
          TEST_CASES(NetworkContextType::kOnDiskAppWithIncognitoProfile)));
#else  // !BUILDFLAG(ENABLE_EXTENSIONS)
#define INSTANTIATE_EXTENSION_TESTS(TestFixture)
#endif  // !BUILDFLAG(ENABLE_EXTENSIONS)

#define INSTANTIATE_TEST_CASES_FOR_TEST_FIXTURE(TestFixture)             \
  INSTANTIATE_EXTENSION_TESTS(TestFixture)                               \
  INSTANTIATE_TEST_SUITE_P(                                              \
      SystemNetworkContext, TestFixture,                                 \
      ::testing::Values(TEST_CASES(NetworkContextType::kSystem)));       \
                                                                         \
  INSTANTIATE_TEST_SUITE_P(                                              \
      SafeBrowsingNetworkContext, TestFixture,                           \
      ::testing::Values(TEST_CASES(NetworkContextType::kSafeBrowsing))); \
                                                                         \
  INSTANTIATE_TEST_SUITE_P(                                              \
      ProfileMainNetworkContext, TestFixture,                            \
      ::testing::Values(TEST_CASES(NetworkContextType::kProfile)));      \
                                                                         \
  INSTANTIATE_TEST_SUITE_P(                                              \
      IncognitoProfileMainNetworkContext, TestFixture,                   \
      ::testing::Values(TEST_CASES(NetworkContextType::kIncognitoProfile)))

INSTANTIATE_TEST_CASES_FOR_TEST_FIXTURE(NetworkContextConfigurationBrowserTest);
INSTANTIATE_TEST_CASES_FOR_TEST_FIXTURE(
    NetworkContextConfigurationFixedPortBrowserTest);
INSTANTIATE_TEST_CASES_FOR_TEST_FIXTURE(
    NetworkContextConfigurationProxyOnStartBrowserTest);
INSTANTIATE_TEST_CASES_FOR_TEST_FIXTURE(
    NetworkContextConfigurationHttpPacBrowserTest);
INSTANTIATE_TEST_CASES_FOR_TEST_FIXTURE(
    NetworkContextConfigurationFilePacBrowserTest);
INSTANTIATE_TEST_CASES_FOR_TEST_FIXTURE(
    NetworkContextConfigurationDataPacBrowserTest);
INSTANTIATE_TEST_CASES_FOR_TEST_FIXTURE(
    NetworkContextConfigurationProxySettingsBrowserTest);
INSTANTIATE_TEST_CASES_FOR_TEST_FIXTURE(
    NetworkContextConfigurationManagedProxySettingsBrowserTest);
#if BUILDFLAG(ENABLE_REPORTING)
INSTANTIATE_TEST_CASES_FOR_TEST_FIXTURE(
    NetworkContextConfigurationReportingAndNelBrowserTest);
#endif

}  // namespace