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
 2277
 2278
 2279
 2280
 2281
 2282
 2283
 2284
 2285
 2286
 2287
 2288
 2289
 2290
 2291
 2292
 2293
 2294
 2295
 2296
 2297
 2298
 2299
 2300
 2301
 2302
 2303
 2304
 2305
 2306
 2307
 2308
 2309
 2310
 2311
 2312
 2313
 2314
 2315
 2316
 2317
 2318
 2319
 2320
 2321
 2322
 2323
 2324
 2325
 2326
 2327
 2328
 2329
 2330
 2331
 2332
 2333
 2334
 2335
 2336
 2337
 2338
 2339
 2340
 2341
 2342
 2343
 2344
 2345
 2346
 2347
 2348
 2349
 2350
 2351
 2352
 2353
 2354
 2355
 2356
 2357
 2358
 2359
 2360
 2361
 2362
 2363
 2364
 2365
 2366
 2367
 2368
 2369
 2370
 2371
 2372
 2373
 2374
 2375
 2376
 2377
 2378
 2379
 2380
 2381
 2382
 2383
 2384
 2385
 2386
 2387
 2388
 2389
 2390
 2391
 2392
 2393
 2394
 2395
 2396
 2397
 2398
 2399
 2400
 2401
 2402
 2403
 2404
 2405
 2406
 2407
 2408
 2409
 2410
 2411
 2412
 2413
 2414
 2415
 2416
 2417
 2418
 2419
 2420
 2421
 2422
 2423
 2424
 2425
 2426
 2427
 2428
 2429
 2430
 2431
 2432
 2433
 2434
 2435
 2436
 2437
 2438
 2439
 2440
 2441
 2442
 2443
 2444
 2445
 2446
 2447
 2448
 2449
 2450
 2451
 2452
 2453
 2454
 2455
 2456
 2457
 2458
 2459
 2460
 2461
 2462
 2463
 2464
 2465
 2466
 2467
 2468
 2469
 2470
 2471
 2472
 2473
 2474
 2475
 2476
 2477
 2478
 2479
 2480
 2481
 2482
 2483
 2484
 2485
 2486
 2487
 2488
 2489
 2490
 2491
 2492
 2493
 2494
 2495
 2496
 2497
 2498
 2499
 2500
 2501
 2502
 2503
 2504
 2505
 2506
 2507
 2508
 2509
 2510
 2511
 2512
 2513
 2514
 2515
 2516
 2517
 2518
 2519
 2520
 2521
 2522
 2523
 2524
 2525
 2526
 2527
 2528
 2529
 2530
 2531
 2532
 2533
 2534
 2535
 2536
 2537
 2538
 2539
 2540
 2541
 2542
 2543
 2544
 2545
 2546
 2547
 2548
 2549
 2550
 2551
 2552
 2553
 2554
 2555
 2556
 2557
 2558
 2559
 2560
 2561
 2562
 2563
 2564
 2565
 2566
 2567
 2568
 2569
 2570
 2571
 2572
 2573
 2574
 2575
 2576
 2577
 2578
 2579
 2580
 2581
 2582
 2583
 2584
 2585
 2586
 2587
 2588
 2589
 2590
 2591
 2592
 2593
 2594
 2595
 2596
 2597
 2598
 2599
 2600
 2601
 2602
 2603
 2604
 2605
 2606
 2607
 2608
 2609
 2610
 2611
 2612
 2613
 2614
 2615
 2616
 2617
 2618
 2619
 2620
 2621
 2622
 2623
 2624
 2625
 2626
 2627
 2628
 2629
 2630
 2631
 2632
 2633
 2634
 2635
 2636
 2637
 2638
 2639
 2640
 2641
 2642
 2643
 2644
 2645
 2646
 2647
 2648
 2649
 2650
 2651
 2652
 2653
 2654
 2655
 2656
 2657
 2658
 2659
 2660
 2661
 2662
 2663
 2664
 2665
 2666
 2667
 2668
 2669
 2670
 2671
 2672
 2673
 2674
 2675
 2676
 2677
 2678
 2679
 2680
 2681
 2682
 2683
 2684
 2685
 2686
 2687
 2688
 2689
 2690
 2691
 2692
 2693
 2694
 2695
 2696
 2697
 2698
 2699
 2700
 2701
 2702
 2703
 2704
 2705
 2706
 2707
 2708
 2709
 2710
 2711
 2712
 2713
 2714
 2715
 2716
 2717
 2718
 2719
 2720
 2721
 2722
 2723
 2724
 2725
 2726
 2727
 2728
 2729
 2730
 2731
 2732
 2733
 2734
 2735
 2736
 2737
 2738
 2739
 2740
 2741
 2742
 2743
 2744
 2745
 2746
 2747
 2748
 2749
 2750
 2751
 2752
 2753
 2754
 2755
 2756
 2757
 2758
 2759
 2760
 2761
 2762
 2763
 2764
 2765
 2766
 2767
 2768
 2769
 2770
 2771
 2772
 2773
 2774
 2775
 2776
 2777
 2778
 2779
 2780
 2781
 2782
 2783
 2784
 2785
 2786
 2787
 2788
 2789
 2790
 2791
 2792
 2793
 2794
 2795
 2796
 2797
 2798
 2799
 2800
 2801
 2802
 2803
 2804
 2805
 2806
 2807
 2808
 2809
 2810
 2811
 2812
 2813
 2814
 2815
 2816
 2817
 2818
 2819
 2820
 2821
 2822
 2823
 2824
 2825
 2826
 2827
 2828
 2829
 2830
 2831
 2832
 2833
 2834
 2835
 2836
 2837
 2838
 2839
 2840
 2841
 2842
 2843
 2844
 2845
 2846
 2847
 2848
 2849
 2850
 2851
 2852
 2853
 2854
 2855
 2856
 2857
 2858
 2859
 2860
 2861
 2862
 2863
 2864
 2865
 2866
 2867
 2868
 2869
 2870
 2871
 2872
 2873
 2874
 2875
 2876
 2877
 2878
 2879
 2880
 2881
 2882
 2883
 2884
 2885
 2886
 2887
 2888
 2889
 2890
 2891
 2892
 2893
 2894
 2895
 2896
 2897
 2898
 2899
 2900
 2901
 2902
 2903
 2904
 2905
 2906
 2907
 2908
 2909
 2910
 2911
 2912
 2913
 2914
 2915
 2916
 2917
 2918
 2919
 2920
 2921
 2922
 2923
 2924
 2925
 2926
 2927
 2928
 2929
 2930
 2931
 2932
 2933
 2934
 2935
 2936
 2937
 2938
 2939
 2940
 2941
 2942
 2943
 2944
 2945
 2946
 2947
 2948
 2949
 2950
 2951
 2952
 2953
 2954
 2955
 2956
 2957
 2958
 2959
 2960
 2961
 2962
 2963
 2964
 2965
 2966
 2967
 2968
 2969
 2970
 2971
 2972
 2973
 2974
 2975
 2976
 2977
 2978
 2979
 2980
 2981
 2982
 2983
 2984
 2985
 2986
 2987
 2988
 2989
 2990
 2991
 2992
 2993
 2994
 2995
 2996
 2997
 2998
 2999
 3000
 3001
 3002
 3003
 3004
 3005
 3006
 3007
 3008
 3009
 3010
 3011
 3012
 3013
 3014
 3015
 3016
 3017
 3018
 3019
 3020
 3021
 3022
 3023
 3024
 3025
 3026
 3027
 3028
 3029
 3030
 3031
 3032
 3033
 3034
 3035
 3036
 3037
 3038
 3039
 3040
 3041
 3042
 3043
 3044
 3045
 3046
 3047
 3048
 3049
 3050
 3051
 3052
 3053
 3054
 3055
 3056
 3057
 3058
 3059
 3060
 3061
 3062
 3063
 3064
 3065
 3066
 3067
 3068
 3069
 3070
 3071
 3072
 3073
 3074
 3075
 3076
 3077
 3078
 3079
 3080
 3081
 3082
 3083
 3084
 3085
 3086
 3087
 3088
 3089
 3090
 3091
 3092
 3093
 3094
 3095
 3096
 3097
 3098
 3099
 3100
 3101
 3102
 3103
 3104
 3105
 3106
 3107
 3108
 3109
 3110
 3111
 3112
 3113
 3114
 3115
 3116
 3117
 3118
 3119
 3120
 3121
 3122
 3123
 3124
 3125
 3126
 3127
 3128
 3129
 3130
 3131
 3132
 3133
 3134
 3135
 3136
 3137
 3138
 3139
 3140
 3141
 3142
 3143
 3144
 3145
 3146
 3147
 3148
 3149
 3150
 3151
 3152
 3153
 3154
 3155
 3156
 3157
 3158
 3159
 3160
 3161
 3162
 3163
 3164
 3165
 3166
 3167
 3168
 3169
 3170
 3171
 3172
 3173
 3174
 3175
 3176
 3177
 3178
 3179
 3180
 3181
 3182
 3183
 3184
 3185
 3186
 3187
 3188
 3189
 3190
 3191
 3192
 3193
 3194
 3195
 3196
 3197
 3198
 3199
 3200
 3201
 3202
 3203
 3204
 3205
 3206
 3207
 3208
 3209
 3210
 3211
 3212
 3213
 3214
 3215
 3216
 3217
 3218
 3219
 3220
 3221
 3222
 3223
 3224
 3225
 3226
 3227
 3228
 3229
 3230
 3231
 3232
 3233
 3234
 3235
 3236
 3237
 3238
 3239
 3240
 3241
 3242
 3243
 3244
 3245
 3246
 3247
 3248
 3249
 3250
 3251
 3252
 3253
 3254
 3255
 3256
 3257
 3258
 3259
 3260
 3261
 3262
 3263
 3264
 3265
 3266
 3267
 3268
 3269
 3270
 3271
 3272
 3273
 3274
 3275
 3276
 3277
 3278
 3279
 3280
 3281
 3282
 3283
 3284
 3285
 3286
 3287
 3288
 3289
 3290
 3291
 3292
 3293
 3294
 3295
 3296
 3297
 3298
 3299
 3300
 3301
 3302
 3303
 3304
 3305
 3306
 3307
 3308
 3309
 3310
 3311
 3312
 3313
 3314
 3315
 3316
 3317
 3318
 3319
 3320
 3321
 3322
 3323
 3324
 3325
 3326
 3327
 3328
 3329
 3330
 3331
 3332
 3333
 3334
 3335
 3336
 3337
 3338
 3339
 3340
 3341
 3342
 3343
 3344
 3345
 3346
 3347
 3348
 3349
 3350
 3351
 3352
 3353
 3354
 3355
 3356
 3357
 3358
 3359
 3360
 3361
 3362
 3363
 3364
 3365
 3366
 3367
 3368
 3369
 3370
 3371
 3372
 3373
 3374
 3375
 3376
 3377
 3378
 3379
 3380
 3381
 3382
 3383
 3384
 3385
 3386
 3387
 3388
 3389
 3390
 3391
 3392
 3393
 3394
 3395
 3396
 3397
 3398
 3399
 3400
 3401
 3402
 3403
 3404
 3405
 3406
 3407
 3408
 3409
 3410
 3411
 3412
 3413
 3414
 3415
 3416
 3417
 3418
 3419
 3420
 3421
 3422
 3423
 3424
 3425
 3426
 3427
 3428
 3429
 3430
 3431
 3432
 3433
 3434
 3435
 3436
 3437
 3438
 3439
 3440
 3441
 3442
 3443
 3444
 3445
 3446
 3447
 3448
 3449
 3450
 3451
 3452
 3453
 3454
 3455
 3456
 3457
 3458
 3459
 3460
 3461
 3462
 3463
 3464
 3465
 3466
 3467
 3468
 3469
 3470
 3471
 3472
 3473
 3474
 3475
 3476
 3477
 3478
 3479
 3480
 3481
 3482
 3483
 3484
 3485
 3486
 3487
 3488
 3489
 3490
 3491
 3492
 3493
 3494
 3495
 3496
 3497
 3498
 3499
 3500
 3501
 3502
 3503
 3504
 3505
 3506
 3507
 3508
 3509
 3510
 3511
 3512
 3513
 3514
 3515
 3516
 3517
 3518
 3519
 3520
 3521
 3522
 3523
 3524
 3525
 3526
 3527
 3528
 3529
 3530
 3531
 3532
 3533
 3534
 3535
 3536
 3537
 3538
 3539
 3540
 3541
 3542
 3543
 3544
 3545
 3546
 3547
 3548
 3549
 3550
 3551
 3552
 3553
 3554
 3555
 3556
 3557
 3558
 3559
 3560
 3561
 3562
 3563
 3564
 3565
 3566
 3567
 3568
 3569
 3570
 3571
 3572
 3573
 3574
 3575
 3576
 3577
 3578
 3579
 3580
 3581
 3582
 3583
 3584
 3585
 3586
 3587
 3588
 3589
 3590
 3591
 3592
 3593
 3594
 3595
 3596
 3597
 3598
 3599
 3600
 3601
 3602
 3603
 3604
 3605
 3606
 3607
 3608
 3609
 3610
 3611
 3612
 3613
 3614
 3615
 3616
 3617
 3618
 3619
 3620
 3621
 3622
 3623
 3624
 3625
 3626
 3627
 3628
 3629
 3630
 3631
 3632
 3633
 3634
 3635
 3636
 3637
 3638
 3639
 3640
 3641
 3642
 3643
 3644
 3645
 3646
 3647
 3648
 3649
 3650
 3651
 3652
 3653
 3654
 3655
 3656
 3657
 3658
 3659
 3660
 3661
 3662
 3663
 3664
 3665
 3666
 3667
 3668
 3669
 3670
 3671
 3672
 3673
 3674
 3675
 3676
 3677
 3678
 3679
 3680
 3681
 3682
 3683
 3684
 3685
 3686
 3687
 3688
 3689
 3690
 3691
 3692
 3693
 3694
 3695
 3696
 3697
 3698
 3699
 3700
 3701
 3702
 3703
 3704
 3705
 3706
 3707
 3708
 3709
 3710
 3711
 3712
 3713
 3714
 3715
 3716
 3717
 3718
 3719
 3720
 3721
 3722
 3723
 3724
 3725
 3726
 3727
 3728
 3729
 3730
 3731
 3732
 3733
 3734
 3735
 3736
 3737
 3738
 3739
 3740
 3741
 3742
 3743
 3744
 3745
 3746
 3747
 3748
 3749
 3750
 3751
 3752
 3753
 3754
 3755
 3756
 3757
 3758
 3759
 3760
 3761
 3762
 3763
 3764
 3765
 3766
 3767
 3768
 3769
 3770
 3771
 3772
 3773
 3774
 3775
 3776
 3777
 3778
 3779
 3780
 3781
 3782
 3783
 3784
 3785
 3786
 3787
 3788
 3789
 3790
 3791
 3792
 3793
 3794
 3795
 3796
 3797
 3798
 3799
 3800
 3801
 3802
 3803
 3804
 3805
 3806
 3807
 3808
 3809
 3810
 3811
 3812
 3813
 3814
 3815
 3816
 3817
 3818
 3819
 3820
 3821
 3822
 3823
 3824
 3825
 3826
 3827
 3828
 3829
 3830
 3831
 3832
 3833
 3834
 3835
 3836
 3837
 3838
 3839
 3840
 3841
 3842
 3843
 3844
 3845
 3846
 3847
 3848
 3849
 3850
 3851
 3852
 3853
 3854
 3855
 3856
 3857
 3858
 3859
 3860
 3861
 3862
 3863
 3864
 3865
 3866
 3867
 3868
 3869
 3870
 3871
 3872
 3873
 3874
 3875
 3876
 3877
 3878
 3879
 3880
 3881
 3882
 3883
 3884
 3885
 3886
 3887
 3888
 3889
 3890
 3891
 3892
 3893
 3894
 3895
 3896
 3897
 3898
 3899
 3900
 3901
 3902
 3903
 3904
 3905
 3906
 3907
 3908
 3909
 3910
 3911
 3912
 3913
 3914
 3915
 3916
 3917
 3918
 3919
 3920
 3921
 3922
 3923
 3924
 3925
 3926
 3927
 3928
 3929
 3930
 3931
 3932
 3933
 3934
 3935
 3936
 3937
 3938
 3939
 3940
 3941
 3942
 3943
 3944
 3945
 3946
 3947
 3948
 3949
 3950
 3951
 3952
 3953
 3954
 3955
 3956
 3957
 3958
 3959
 3960
 3961
 3962
 3963
 3964
 3965
 3966
 3967
 3968
 3969
 3970
 3971
 3972
 3973
 3974
 3975
 3976
 3977
 3978
 3979
 3980
 3981
 3982
 3983
 3984
 3985
 3986
 3987
 3988
 3989
 3990
 3991
 3992
 3993
 3994
 3995
 3996
 3997
 3998
 3999
 4000
 4001
 4002
 4003
 4004
 4005
 4006
 4007
 4008
 4009
 4010
 4011
 4012
 4013
 4014
 4015
 4016
 4017
 4018
 4019
 4020
 4021
 4022
 4023
 4024
 4025
 4026
 4027
 4028
 4029
 4030
 4031
 4032
 4033
 4034
 4035
 4036
 4037
 4038
 4039
 4040
 4041
 4042
 4043
 4044
 4045
 4046
 4047
 4048
 4049
 4050
 4051
 4052
 4053
 4054
 4055
 4056
 4057
 4058
 4059
 4060
 4061
 4062
 4063
 4064
 4065
 4066
 4067
 4068
 4069
 4070
 4071
 4072
 4073
 4074
 4075
 4076
 4077
 4078
 4079
 4080
 4081
 4082
 4083
 4084
 4085
 4086
 4087
 4088
 4089
 4090
 4091
 4092
 4093
 4094
 4095
 4096
 4097
 4098
 4099
 4100
 4101
 4102
 4103
 4104
 4105
 4106
 4107
 4108
 4109
 4110
 4111
 4112
 4113
 4114
 4115
 4116
 4117
 4118
 4119
 4120
 4121
 4122
 4123
 4124
 4125
 4126
 4127
 4128
 4129
 4130
 4131
 4132
 4133
 4134
 4135
 4136
 4137
 4138
 4139
 4140
 4141
 4142
 4143
 4144
 4145
 4146
 4147
 4148
 4149
 4150
 4151
 4152
 4153
 4154
 4155
 4156
 4157
 4158
 4159
 4160
 4161
 4162
 4163
 4164
 4165
 4166
 4167
 4168
 4169
 4170
 4171
 4172
 4173
 4174
 4175
 4176
 4177
 4178
 4179
 4180
 4181
 4182
 4183
 4184
 4185
 4186
 4187
 4188
 4189
 4190
 4191
 4192
 4193
 4194
 4195
 4196
 4197
 4198
 4199
 4200
 4201
 4202
 4203
 4204
 4205
 4206
 4207
 4208
 4209
 4210
 4211
 4212
 4213
 4214
 4215
 4216
 4217
 4218
 4219
 4220
 4221
 4222
 4223
 4224
 4225
 4226
 4227
 4228
 4229
 4230
 4231
 4232
 4233
 4234
 4235
 4236
 4237
 4238
 4239
 4240
 4241
 4242
 4243
 4244
 4245
 4246
 4247
 4248
 4249
 4250
 4251
 4252
 4253
 4254
 4255
 4256
 4257
 4258
 4259
 4260
 4261
 4262
 4263
 4264
 4265
 4266
 4267
 4268
 4269
 4270
 4271
 4272
 4273
 4274
 4275
 4276
 4277
 4278
 4279
 4280
 4281
 4282
 4283
 4284
 4285
 4286
 4287
 4288
 4289
 4290
 4291
 4292
 4293
 4294
 4295
 4296
 4297
 4298
 4299
 4300
 4301
 4302
 4303
 4304
 4305
 4306
 4307
 4308
 4309
 4310
 4311
 4312
 4313
 4314
 4315
 4316
 4317
 4318
 4319
 4320
 4321
 4322
 4323
 4324
 4325
 4326
 4327
 4328
 4329
 4330
 4331
 4332
 4333
 4334
 4335
 4336
 4337
 4338
 4339
 4340
 4341
 4342
 4343
 4344
 4345
 4346
 4347
 4348
 4349
 4350
 4351
 4352
 4353
 4354
 4355
 4356
 4357
 4358
 4359
 4360
 4361
 4362
 4363
 4364
 4365
 4366
 4367
 4368
 4369
 4370
 4371
 4372
 4373
 4374
 4375
 4376
 4377
 4378
 4379
 4380
 4381
 4382
 4383
 4384
 4385
 4386
 4387
 4388
 4389
 4390
 4391
 4392
 4393
 4394
 4395
 4396
 4397
 4398
 4399
 4400
 4401
 4402
 4403
 4404
 4405
 4406
 4407
 4408
 4409
 4410
 4411
 4412
 4413
 4414
 4415
 4416
 4417
 4418
 4419
 4420
 4421
 4422
 4423
 4424
 4425
 4426
 4427
 4428
 4429
 4430
 4431
 4432
 4433
 4434
 4435
 4436
 4437
 4438
 4439
 4440
 4441
 4442
 4443
 4444
 4445
 4446
 4447
 4448
 4449
 4450
 4451
 4452
 4453
 4454
 4455
 4456
 4457
 4458
 4459
 4460
 4461
 4462
 4463
 4464
 4465
 4466
 4467
 4468
 4469
 4470
 4471
 4472
 4473
 4474
 4475
 4476
 4477
 4478
 4479
 4480
 4481
 4482
 4483
 4484
 4485
 4486
 4487
 4488
 4489
 4490
 4491
 4492
 4493
 4494
 4495
 4496
 4497
 4498
 4499
 4500
 4501
 4502
 4503
 4504
 4505
 4506
 4507
 4508
 4509
 4510
 4511
 4512
 4513
 4514
 4515
 4516
 4517
 4518
 4519
 4520
 4521
 4522
 4523
 4524
 4525
 4526
 4527
 4528
 4529
 4530
 4531
 4532
 4533
 4534
 4535
 4536
 4537
 4538
 4539
 4540
 4541
 4542
 4543
 4544
 4545
 4546
 4547
 4548
 4549
 4550
 4551
 4552
 4553
 4554
 4555
 4556
 4557
 4558
 4559
 4560
 4561
 4562
 4563
 4564
 4565
 4566
 4567
 4568
 4569
 4570
 4571
 4572
 4573
 4574
 4575
 4576
 4577
 4578
 4579
 4580
 4581
 4582
 4583
 4584
 4585
 4586
 4587
 4588
 4589
 4590
 4591
 4592
 4593
 4594
 4595
 4596
 4597
 4598
 4599
 4600
 4601
 4602
 4603
 4604
 4605
 4606
 4607
 4608
 4609
 4610
 4611
 4612
 4613
 4614
 4615
 4616
 4617
 4618
 4619
 4620
 4621
 4622
 4623
 4624
 4625
 4626
 4627
 4628
 4629
 4630
 4631
 4632
 4633
 4634
 4635
 4636
 4637
 4638
 4639
 4640
 4641
 4642
 4643
 4644
 4645
 4646
 4647
 4648
 4649
 4650
 4651
 4652
 4653
 4654
 4655
 4656
 4657
 4658
 4659
 4660
 4661
 4662
 4663
 4664
 4665
 4666
 4667
 4668
 4669
 4670
 4671
 4672
 4673
 4674
 4675
 4676
 4677
 4678
 4679
 4680
 4681
 4682
 4683
 4684
 4685
 4686
 4687
 4688
 4689
 4690
 4691
 4692
 4693
 4694
 4695
 4696
 4697
 4698
 4699
 4700
 4701
 4702
 4703
 4704
 4705
 4706
 4707
 4708
 4709
 4710
 4711
 4712
 4713
 4714
 4715
 4716
 4717
 4718
 4719
 4720
 4721
 4722
 4723
 4724
 4725
 4726
 4727
 4728
 4729
 4730
 4731
 4732
 4733
 4734
 4735
 4736
 4737
 4738
 4739
 4740
 4741
 4742
 4743
 4744
 4745
 4746
 4747
 4748
 4749
 4750
 4751
 4752
 4753
 4754
 4755
 4756
 4757
 4758
 4759
 4760
 4761
 4762
 4763
 4764
 4765
 4766
 4767
 4768
 4769
 4770
 4771
 4772
 4773
 4774
 4775
 4776
 4777
 4778
 4779
 4780
 4781
 4782
 4783
 4784
 4785
 4786
 4787
 4788
 4789
 4790
 4791
 4792
 4793
 4794
 4795
 4796
 4797
 4798
 4799
 4800
 4801
 4802
 4803
 4804
 4805
 4806
 4807
 4808
 4809
 4810
 4811
 4812
 4813
 4814
 4815
 4816
 4817
 4818
 4819
 4820
 4821
 4822
 4823
 4824
 4825
 4826
 4827
 4828
 4829
 4830
 4831
 4832
 4833
 4834
 4835
 4836
 4837
 4838
 4839
 4840
 4841
 4842
 4843
 4844
 4845
 4846
 4847
 4848
 4849
 4850
 4851
 4852
 4853
 4854
 4855
 4856
 4857
 4858
 4859
 4860
 4861
 4862
 4863
 4864
 4865
 4866
 4867
 4868
 4869
 4870
 4871
 4872
 4873
 4874
 4875
 4876
 4877
 4878
 4879
 4880
 4881
 4882
 4883
 4884
 4885
 4886
 4887
 4888
 4889
 4890
 4891
 4892
 4893
 4894
 4895
 4896
 4897
 4898
 4899
 4900
 4901
 4902
 4903
 4904
 4905
 4906
 4907
 4908
 4909
 4910
 4911
 4912
 4913
 4914
 4915
 4916
 4917
 4918
 4919
 4920
 4921
 4922
 4923
 4924
 4925
 4926
 4927
 4928
 4929
 4930
 4931
 4932
 4933
 4934
 4935
 4936
 4937
 4938
 4939
 4940
 4941
 4942
 4943
 4944
 4945
 4946
 4947
 4948
 4949
 4950
 4951
 4952
 4953
 4954
 4955
 4956
 4957
 4958
 4959
 4960
 4961
 4962
 4963
 4964
 4965
 4966
 4967
 4968
 4969
 4970
 4971
 4972
 4973
 4974
 4975
 4976
 4977
 4978
 4979
 4980
 4981
 4982
 4983
 4984
 4985
 4986
 4987
 4988
 4989
 4990
 4991
 4992
 4993
 4994
 4995
 4996
 4997
 4998
 4999
 5000
 5001
 5002
 5003
 5004
 5005
 5006
 5007
 5008
 5009
 5010
 5011
 5012
 5013
 5014
 5015
 5016
 5017
 5018
 5019
 5020
 5021
 5022
 5023
 5024
 5025
 5026
 5027
 5028
 5029
 5030
 5031
 5032
 5033
 5034
 5035
 5036
 5037
 5038
 5039
 5040
 5041
 5042
 5043
 5044
 5045
 5046
 5047
 5048
 5049
 5050
 5051
 5052
 5053
 5054
 5055
 5056
 5057
 5058
 5059
 5060
 5061
 5062
 5063
 5064
 5065
 5066
 5067
 5068
 5069
 5070
 5071
 5072
 5073
 5074
 5075
 5076
 5077
 5078
 5079
 5080
 5081
 5082
 5083
 5084
 5085
 5086
 5087
 5088
 5089
 5090
 5091
 5092
 5093
 5094
 5095
 5096
 5097
 5098
 5099
 5100
 5101
 5102
 5103
 5104
 5105
 5106
 5107
 5108
 5109
 5110
 5111
 5112
 5113
 5114
 5115
 5116
 5117
 5118
 5119
 5120
 5121
 5122
 5123
 5124
 5125
 5126
 5127
 5128
 5129
 5130
 5131
 5132
 5133
 5134
 5135
 5136
 5137
 5138
 5139
 5140
 5141
 5142
 5143
 5144
 5145
 5146
 5147
 5148
 5149
 5150
 5151
 5152
 5153
 5154
 5155
 5156
 5157
 5158
 5159
 5160
 5161
 5162
 5163
 5164
 5165
 5166
 5167
 5168
 5169
 5170
 5171
 5172
 5173
 5174
 5175
 5176
 5177
 5178
 5179
 5180
 5181
 5182
 5183
 5184
 5185
 5186
 5187
 5188
 5189
 5190
 5191
 5192
 5193
 5194
 5195
 5196
 5197
 5198
 5199
 5200
 5201
 5202
 5203
 5204
 5205
 5206
 5207
 5208
 5209
 5210
 5211
 5212
 5213
 5214
 5215
 5216
 5217
 5218
 5219
 5220
 5221
 5222
 5223
 5224
 5225
 5226
 5227
 5228
 5229
 5230
 5231
 5232
 5233
 5234
 5235
 5236
 5237
 5238
 5239
 5240
 5241
 5242
 5243
 5244
 5245
 5246
 5247
 5248
 5249
 5250
 5251
 5252
 5253
 5254
 5255
 5256
 5257
 5258
 5259
 5260
 5261
 5262
 5263
 5264
 5265
 5266
 5267
 5268
 5269
 5270
 5271
 5272
 5273
 5274
 5275
 5276
 5277
 5278
 5279
 5280
 5281
 5282
 5283
 5284
 5285
 5286
 5287
 5288
 5289
 5290
 5291
 5292
 5293
 5294
 5295
 5296
 5297
 5298
 5299
 5300
 5301
 5302
 5303
 5304
 5305
 5306
 5307
 5308
 5309
 5310
 5311
 5312
 5313
 5314
 5315
 5316
 5317
 5318
 5319
 5320
 5321
 5322
 5323
 5324
 5325
 5326
 5327
 5328
 5329
 5330
 5331
 5332
 5333
 5334
 5335
 5336
 5337
 5338
 5339
 5340
 5341
 5342
 5343
 5344
 5345
 5346
 5347
 5348
 5349
 5350
 5351
 5352
 5353
 5354
 5355
 5356
 5357
 5358
 5359
 5360
 5361
 5362
 5363
 5364
 5365
 5366
 5367
 5368
 5369
 5370
 5371
 5372
 5373
 5374
 5375
 5376
 5377
 5378
 5379
 5380
 5381
 5382
 5383
 5384
 5385
 5386
 5387
 5388
 5389
 5390
 5391
 5392
 5393
 5394
 5395
 5396
 5397
 5398
 5399
 5400
 5401
 5402
 5403
 5404
 5405
 5406
 5407
 5408
 5409
 5410
 5411
 5412
 5413
 5414
 5415
 5416
 5417
 5418
 5419
 5420
 5421
 5422
 5423
 5424
 5425
 5426
 5427
 5428
 5429
 5430
 5431
 5432
 5433
 5434
 5435
 5436
 5437
 5438
 5439
 5440
 5441
 5442
 5443
 5444
 5445
 5446
 5447
 5448
 5449
 5450
 5451
 5452
 5453
 5454
 5455
 5456
 5457
 5458
 5459
 5460
 5461
 5462
 5463
 5464
 5465
 5466
 5467
 5468
 5469
 5470
 5471
 5472
 5473
 5474
 5475
 5476
 5477
 5478
 5479
 5480
 5481
 5482
 5483
 5484
 5485
 5486
 5487
 5488
 5489
 5490
 5491
 5492
 5493
 5494
 5495
 5496
 5497
 5498
 5499
 5500
 5501
 5502
 5503
 5504
 5505
 5506
 5507
 5508
 5509
 5510
 5511
 5512
 5513
 5514
 5515
 5516
 5517
 5518
 5519
 5520
 5521
 5522
 5523
 5524
 5525
 5526
 5527
 5528
 5529
 5530
 5531
 5532
 5533
 5534
 5535
 5536
 5537
 5538
 5539
 5540
 5541
 5542
 5543
 5544
 5545
 5546
 5547
 5548
 5549
 5550
 5551
 5552
 5553
 5554
 5555
 5556
 5557
 5558
 5559
 5560
 5561
 5562
 5563
 5564
 5565
 5566
 5567
 5568
 5569
 5570
 5571
 5572
 5573
 5574
 5575
 5576
 5577
 5578
 5579
 5580
 5581
 5582
 5583
 5584
 5585
 5586
 5587
 5588
 5589
 5590
 5591
 5592
 5593
 5594
 5595
 5596
 5597
 5598
 5599
 5600
 5601
 5602
 5603
 5604
 5605
 5606
 5607
 5608
 5609
 5610
 5611
 5612
 5613
 5614
 5615
 5616
 5617
 5618
 5619
 5620
 5621
 5622
 5623
 5624
 5625
 5626
 5627
 5628
 5629
 5630
 5631
 5632
 5633
 5634
 5635
 5636
 5637
 5638
 5639
 5640
 5641
 5642
 5643
 5644
 5645
 5646
 5647
 5648
 5649
 5650
 5651
 5652
 5653
 5654
 5655
 5656
 5657
 5658
 5659
 5660
 5661
 5662
 5663
 5664
 5665
 5666
 5667
 5668
 5669
 5670
 5671
 5672
 5673
 5674
 5675
 5676
 5677
 5678
 5679
 5680
 5681
 5682
 5683
 5684
 5685
 5686
 5687
 5688
 5689
 5690
 5691
 5692
 5693
 5694
 5695
 5696
 5697
 5698
 5699
 5700
 5701
 5702
 5703
 5704
 5705
 5706
 5707
 5708
 5709
 5710
 5711
 5712
 5713
 5714
 5715
 5716
 5717
 5718
 5719
 5720
 5721
 5722
 5723
 5724
 5725
 5726
 5727
 5728
 5729
 5730
 5731
 5732
 5733
 5734
 5735
 5736
 5737
 5738
 5739
 5740
 5741
 5742
 5743
 5744
 5745
 5746
 5747
 5748
 5749
 5750
 5751
 5752
 5753
 5754
 5755
 5756
 5757
 5758
 5759
 5760
 5761
 5762
 5763
 5764
 5765
 5766
 5767
 5768
 5769
 5770
 5771
 5772
 5773
 5774
 5775
 5776
 5777
 5778
 5779
 5780
 5781
 5782
 5783
 5784
 5785
 5786
 5787
 5788
 5789
 5790
 5791
 5792
 5793
 5794
 5795
 5796
 5797
 5798
 5799
 5800
 5801
 5802
 5803
 5804
 5805
 5806
 5807
 5808
 5809
 5810
 5811
 5812
 5813
 5814
 5815
 5816
 5817
 5818
 5819
 5820
 5821
 5822
 5823
 5824
 5825
 5826
 5827
 5828
 5829
 5830
 5831
 5832
 5833
 5834
 5835
 5836
 5837
 5838
 5839
 5840
 5841
 5842
 5843
 5844
 5845
 5846
 5847
 5848
 5849
 5850
 5851
 5852
 5853
 5854
 5855
 5856
 5857
 5858
 5859
 5860
 5861
 5862
 5863
 5864
 5865
 5866
 5867
 5868
 5869
 5870
 5871
 5872
 5873
 5874
 5875
 5876
 5877
 5878
 5879
 5880
 5881
 5882
 5883
 5884
 5885
 5886
 5887
 5888
 5889
 5890
 5891
 5892
 5893
 5894
 5895
 5896
 5897
 5898
 5899
 5900
 5901
 5902
 5903
 5904
 5905
 5906
 5907
 5908
 5909
 5910
 5911
 5912
 5913
 5914
 5915
 5916
 5917
 5918
 5919
 5920
 5921
 5922
 5923
 5924
 5925
 5926
 5927
 5928
 5929
 5930
 5931
 5932
 5933
 5934
 5935
 5936
 5937
 5938
 5939
 5940
 5941
 5942
 5943
 5944
 5945
 5946
 5947
 5948
 5949
 5950
 5951
 5952
 5953
 5954
 5955
 5956
 5957
 5958
 5959
 5960
 5961
 5962
 5963
 5964
 5965
 5966
 5967
 5968
 5969
 5970
 5971
 5972
 5973
 5974
 5975
 5976
 5977
 5978
 5979
 5980
 5981
 5982
 5983
 5984
 5985
 5986
 5987
 5988
 5989
 5990
 5991
 5992
 5993
 5994
 5995
 5996
 5997
 5998
 5999
 6000
 6001
 6002
 6003
 6004
 6005
 6006
 6007
 6008
 6009
 6010
 6011
 6012
 6013
 6014
 6015
 6016
 6017
 6018
 6019
 6020
 6021
 6022
 6023
 6024
 6025
 6026
 6027
 6028
 6029
 6030
 6031
 6032
 6033
 6034
 6035
 6036
 6037
 6038
 6039
 6040
 6041
 6042
 6043
 6044
 6045
 6046
 6047
 6048
 6049
 6050
 6051
 6052
 6053
 6054
 6055
 6056
 6057
 6058
 6059
 6060
 6061
 6062
 6063
 6064
 6065
 6066
 6067
 6068
 6069
 6070
 6071
 6072
 6073
 6074
 6075
 6076
 6077
 6078
 6079
 6080
 6081
 6082
 6083
 6084
 6085
 6086
 6087
 6088
 6089
 6090
 6091
 6092
 6093
 6094
 6095
 6096
 6097
 6098
 6099
 6100
 6101
 6102
 6103
 6104
 6105
 6106
 6107
 6108
 6109
 6110
 6111
 6112
 6113
 6114
 6115
 6116
 6117
 6118
 6119
 6120
 6121
 6122
 6123
 6124
 6125
 6126
 6127
 6128
 6129
 6130
 6131
 6132
 6133
 6134
 6135
 6136
 6137
 6138
 6139
 6140
 6141
 6142
 6143
 6144
 6145
 6146
 6147
 6148
 6149
 6150
 6151
 6152
 6153
 6154
 6155
 6156
 6157
 6158
 6159
 6160
 6161
 6162
 6163
 6164
 6165
 6166
 6167
 6168
 6169
 6170
 6171
 6172
 6173
 6174
 6175
 6176
 6177
 6178
 6179
 6180
 6181
 6182
 6183
 6184
 6185
 6186
 6187
 6188
 6189
 6190
 6191
 6192
 6193
 6194
 6195
 6196
 6197
 6198
 6199
 6200
 6201
 6202
 6203
 6204
 6205
 6206
 6207
 6208
 6209
 6210
 6211
 6212
 6213
 6214
 6215
 6216
 6217
 6218
 6219
 6220
 6221
 6222
 6223
 6224
 6225
 6226
 6227
 6228
 6229
 6230
 6231
 6232
 6233
 6234
 6235
 6236
 6237
 6238
 6239
 6240
 6241
 6242
 6243
 6244
 6245
 6246
 6247
 6248
 6249
 6250
 6251
 6252
 6253
 6254
 6255
 6256
 6257
 6258
 6259
 6260
 6261
 6262
 6263
 6264
 6265
 6266
 6267
 6268
 6269
 6270
 6271
 6272
 6273
 6274
 6275
 6276
 6277
 6278
 6279
 6280
 6281
 6282
 6283
 6284
 6285
 6286
 6287
 6288
 6289
 6290
 6291
 6292
 6293
 6294
 6295
 6296
 6297
 6298
 6299
 6300
 6301
 6302
 6303
 6304
 6305
 6306
 6307
 6308
 6309
 6310
 6311
 6312
 6313
 6314
 6315
 6316
 6317
 6318
 6319
 6320
 6321
 6322
 6323
 6324
 6325
 6326
 6327
 6328
 6329
 6330
 6331
 6332
 6333
 6334
 6335
 6336
 6337
 6338
 6339
 6340
 6341
 6342
 6343
 6344
 6345
 6346
 6347
 6348
 6349
 6350
 6351
 6352
 6353
 6354
 6355
 6356
 6357
 6358
 6359
 6360
 6361
 6362
 6363
 6364
 6365
 6366
 6367
 6368
 6369
 6370
 6371
 6372
 6373
 6374
 6375
 6376
 6377
 6378
 6379
 6380
 6381
 6382
 6383
 6384
 6385
 6386
 6387
 6388
 6389
 6390
 6391
 6392
 6393
 6394
 6395
 6396
 6397
 6398
 6399
 6400
 6401
 6402
 6403
 6404
 6405
 6406
 6407
 6408
 6409
 6410
 6411
 6412
 6413
 6414
 6415
 6416
 6417
 6418
 6419
 6420
 6421
 6422
 6423
 6424
 6425
 6426
 6427
 6428
 6429
 6430
 6431
 6432
 6433
 6434
 6435
 6436
 6437
 6438
 6439
 6440
 6441
 6442
 6443
 6444
 6445
 6446
 6447
 6448
 6449
 6450
 6451
 6452
 6453
 6454
 6455
 6456
 6457
 6458
 6459
 6460
 6461
 6462
 6463
 6464
 6465
 6466
 6467
 6468
 6469
 6470
 6471
 6472
 6473
 6474
 6475
 6476
 6477
 6478
 6479
 6480
 6481
 6482
 6483
 6484
 6485
 6486
 6487
 6488
 6489
 6490
 6491
 6492
 6493
 6494
 6495
 6496
 6497
 6498
 6499
 6500
 6501
 6502
 6503
 6504
 6505
 6506
 6507
 6508
 6509
 6510
 6511
 6512
 6513
 6514
 6515
 6516
 6517
 6518
 6519
 6520
 6521
 6522
 6523
 6524
 6525
 6526
 6527
 6528
 6529
 6530
 6531
 6532
 6533
 6534
 6535
 6536
 6537
 6538
 6539
 6540
 6541
 6542
 6543
 6544
 6545
 6546
 6547
 6548
 6549
 6550
 6551
 6552
 6553
 6554
 6555
 6556
 6557
 6558
 6559
 6560
 6561
 6562
 6563
 6564
 6565
 6566
 6567
 6568
 6569
 6570
 6571
 6572
 6573
 6574
 6575
 6576
 6577
 6578
 6579
 6580
 6581
 6582
 6583
 6584
 6585
 6586
 6587
 6588
 6589
 6590
 6591
 6592
 6593
 6594
 6595
 6596
 6597
 6598
 6599
 6600
 6601
 6602
 6603
 6604
 6605
 6606
 6607
 6608
 6609
 6610
 6611
 6612
 6613
 6614
 6615
 6616
 6617
 6618
 6619
 6620
 6621
 6622
 6623
 6624
 6625
 6626
 6627
 6628
 6629
 6630
 6631
 6632
 6633
 6634
 6635
 6636
 6637
 6638
 6639
 6640
 6641
 6642
 6643
 6644
 6645
 6646
 6647
 6648
 6649
 6650
 6651
 6652
 6653
 6654
 6655
 6656
 6657
 6658
 6659
 6660
 6661
 6662
 6663
 6664
 6665
 6666
 6667
 6668
 6669
 6670
 6671
 6672
 6673
 6674
 6675
 6676
 6677
 6678
 6679
 6680
 6681
 6682
 6683
 6684
 6685
 6686
 6687
 6688
 6689
 6690
 6691
 6692
 6693
 6694
 6695
 6696
 6697
 6698
 6699
 6700
 6701
 6702
 6703
 6704
 6705
 6706
 6707
 6708
 6709
 6710
 6711
 6712
 6713
 6714
 6715
 6716
 6717
 6718
 6719
 6720
 6721
 6722
 6723
 6724
 6725
 6726
 6727
 6728
 6729
 6730
 6731
 6732
 6733
 6734
 6735
 6736
 6737
 6738
 6739
 6740
 6741
 6742
 6743
 6744
 6745
 6746
 6747
 6748
 6749
 6750
 6751
 6752
 6753
 6754
 6755
 6756
 6757
 6758
 6759
 6760
 6761
 6762
 6763
 6764
 6765
 6766
 6767
 6768
 6769
 6770
 6771
 6772
 6773
 6774
 6775
 6776
 6777
 6778
 6779
 6780
 6781
 6782
 6783
 6784
 6785
 6786
 6787
 6788
 6789
 6790
 6791
 6792
 6793
 6794
 6795
 6796
 6797
 6798
 6799
 6800
 6801
 6802
 6803
 6804
 6805
 6806
 6807
 6808
 6809
 6810
 6811
 6812
 6813
 6814
 6815
 6816
 6817
 6818
 6819
 6820
 6821
 6822
 6823
 6824
 6825
 6826
 6827
 6828
 6829
 6830
 6831
 6832
 6833
 6834
 6835
 6836
 6837
 6838
 6839
 6840
 6841
 6842
 6843
 6844
 6845
 6846
 6847
 6848
 6849
 6850
 6851
 6852
 6853
 6854
 6855
 6856
 6857
 6858
 6859
 6860
 6861
 6862
 6863
 6864
 6865
 6866
 6867
 6868
 6869
 6870
 6871
 6872
 6873
 6874
 6875
 6876
 6877
 6878
 6879
 6880
 6881
 6882
 6883
 6884
 6885
 6886
 6887
 6888
 6889
 6890
 6891
 6892
 6893
 6894
 6895
 6896
 6897
 6898
 6899
 6900
 6901
 6902
 6903
 6904
 6905
 6906
 6907
 6908
 6909
 6910
 6911
 6912
 6913
 6914
 6915
 6916
 6917
 6918
 6919
 6920
 6921
 6922
 6923
 6924
 6925
 6926
 6927
 6928
 6929
 6930
 6931
 6932
 6933
 6934
 6935
 6936
 6937
 6938
 6939
 6940
 6941
 6942
 6943
 6944
 6945
 6946
 6947
 6948
 6949
 6950
 6951
 6952
 6953
 6954
 6955
 6956
 6957
 6958
 6959
 6960
 6961
 6962
 6963
 6964
 6965
 6966
 6967
 6968
 6969
 6970
 6971
 6972
 6973
 6974
 6975
 6976
 6977
 6978
 6979
 6980
 6981
 6982
 6983
 6984
 6985
 6986
 6987
 6988
 6989
 6990
 6991
 6992
 6993
 6994
 6995
 6996
 6997
 6998
 6999
 7000
 7001
 7002
 7003
 7004
 7005
 7006
 7007
 7008
 7009
 7010
 7011
 7012
 7013
 7014
 7015
 7016
 7017
 7018
 7019
 7020
 7021
 7022
 7023
 7024
 7025
 7026
 7027
 7028
 7029
 7030
 7031
 7032
 7033
 7034
 7035
 7036
 7037
 7038
 7039
 7040
 7041
 7042
 7043
 7044
 7045
 7046
 7047
 7048
 7049
 7050
 7051
 7052
 7053
 7054
 7055
 7056
 7057
 7058
 7059
 7060
 7061
 7062
 7063
 7064
 7065
 7066
 7067
 7068
 7069
 7070
 7071
 7072
 7073
 7074
 7075
 7076
 7077
 7078
 7079
 7080
 7081
 7082
 7083
 7084
 7085
 7086
 7087
 7088
 7089
 7090
 7091
 7092
 7093
 7094
 7095
 7096
 7097
 7098
 7099
 7100
 7101
 7102
 7103
 7104
 7105
 7106
 7107
 7108
 7109
 7110
 7111
 7112
 7113
 7114
 7115
 7116
 7117
 7118
 7119
 7120
 7121
 7122
 7123
 7124
 7125
 7126
 7127
 7128
 7129
 7130
 7131
 7132
 7133
 7134
 7135
 7136
 7137
 7138
 7139
 7140
 7141
 7142
 7143
 7144
 7145
 7146
 7147
 7148
 7149
 7150
 7151
 7152
 7153
 7154
 7155
 7156
 7157
 7158
 7159
 7160
 7161
 7162
 7163
 7164
 7165
 7166
 7167
 7168
 7169
 7170
 7171
 7172
 7173
 7174
 7175
 7176
 7177
 7178
 7179
 7180
 7181
 7182
 7183
 7184
 7185
 7186
 7187
 7188
 7189
 7190
 7191
 7192
 7193
 7194
 7195
 7196
 7197
 7198
 7199
 7200
 7201
 7202
 7203
 7204
 7205
 7206
 7207
 7208
 7209
 7210
 7211
 7212
 7213
 7214
 7215
 7216
 7217
 7218
 7219
 7220
 7221
 7222
 7223
 7224
 7225
 7226
 7227
 7228
 7229
 7230
 7231
 7232
 7233
 7234
 7235
 7236
 7237
 7238
 7239
 7240
 7241
 7242
 7243
 7244
 7245
 7246
 7247
 7248
 7249
 7250
 7251
 7252
 7253
 7254
 7255
 7256
 7257
 7258
 7259
 7260
 7261
 7262
 7263
 7264
 7265
 7266
 7267
 7268
 7269
 7270
 7271
 7272
 7273
 7274
 7275
 7276
 7277
 7278
 7279
 7280
 7281
 7282
 7283
 7284
 7285
 7286
 7287
 7288
 7289
 7290
 7291
 7292
 7293
 7294
 7295
 7296
 7297
 7298
 7299
 7300
 7301
 7302
 7303
 7304
 7305
 7306
 7307
 7308
 7309
 7310
 7311
 7312
 7313
 7314
 7315
 7316
 7317
 7318
 7319
 7320
 7321
 7322
 7323
 7324
 7325
 7326
 7327
 7328
 7329
 7330
 7331
 7332
 7333
 7334
 7335
 7336
 7337
 7338
 7339
 7340
 7341
 7342
 7343
 7344
 7345
 7346
 7347
 7348
 7349
 7350
 7351
 7352
 7353
 7354
 7355
 7356
 7357
 7358
 7359
 7360
 7361
 7362
 7363
 7364
 7365
 7366
 7367
 7368
 7369
 7370
 7371
 7372
 7373
 7374
 7375
 7376
 7377
 7378
 7379
 7380
 7381
 7382
 7383
 7384
 7385
 7386
 7387
 7388
 7389
 7390
 7391
 7392
 7393
 7394
 7395
 7396
 7397
 7398
 7399
 7400
 7401
 7402
 7403
 7404
 7405
 7406
 7407
 7408
 7409
 7410
 7411
 7412
 7413
 7414
 7415
 7416
 7417
 7418
 7419
 7420
 7421
 7422
 7423
 7424
 7425
 7426
 7427
 7428
 7429
 7430
 7431
 7432
 7433
 7434
 7435
 7436
 7437
 7438
 7439
 7440
 7441
 7442
 7443
 7444
 7445
 7446
 7447
 7448
 7449
 7450
 7451
 7452
 7453
 7454
 7455
 7456
 7457
 7458
 7459
 7460
 7461
 7462
 7463
 7464
 7465
 7466
 7467
 7468
 7469
 7470
 7471
 7472
 7473
 7474
 7475
 7476
 7477
 7478
 7479
 7480
 7481
 7482
 7483
 7484
 7485
 7486
 7487
 7488
 7489
 7490
 7491
 7492
 7493
 7494
 7495
 7496
 7497
 7498
 7499
 7500
 7501
 7502
 7503
 7504
 7505
 7506
 7507
 7508
 7509
 7510
 7511
 7512
 7513
 7514
 7515
 7516
 7517
 7518
 7519
 7520
 7521
 7522
 7523
 7524
 7525
 7526
 7527
 7528
 7529
 7530
 7531
 7532
 7533
 7534
 7535
 7536
 7537
 7538
 7539
 7540
 7541
 7542
 7543
 7544
 7545
 7546
 7547
 7548
 7549
 7550
 7551
 7552
 7553
 7554
 7555
 7556
 7557
 7558
 7559
 7560

content / browser / isolated_origin_browsertest.cc [blame]

// 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 <sstream>
#include <tuple>
#include <vector>

#include "base/command_line.h"
#include "base/functional/bind.h"
#include "base/memory/raw_ptr.h"
#include "base/memory/raw_ref.h"
#include "base/strings/string_util.h"
#include "base/strings/stringprintf.h"
#include "base/test/bind.h"
#include "base/test/metrics/histogram_tester.h"
#include "base/test/scoped_feature_list.h"
#include "build/build_config.h"
#include "content/browser/bad_message.h"
#include "content/browser/child_process_security_policy_impl.h"
#include "content/browser/origin_agent_cluster_isolation_state.h"
#include "content/browser/process_lock.h"
#include "content/browser/process_reuse_policy.h"
#include "content/browser/renderer_host/navigation_request.h"
#include "content/browser/renderer_host/navigator.h"
#include "content/browser/renderer_host/render_process_host_impl.h"
#include "content/browser/site_info.h"
#include "content/browser/storage_partition_impl.h"
#include "content/browser/web_contents/web_contents_impl.h"
#include "content/common/content_navigation_policy.h"
#include "content/common/features.h"
#include "content/public/browser/browser_or_resource_context.h"
#include "content/public/browser/render_frame_host.h"
#include "content/public/browser/render_process_host.h"
#include "content/public/browser/site_isolation_policy.h"
#include "content/public/browser/storage_partition_config.h"
#include "content/public/browser/web_exposed_isolation_level.h"
#include "content/public/common/content_client.h"
#include "content/public/common/content_features.h"
#include "content/public/common/content_switches.h"
#include "content/public/test/back_forward_cache_util.h"
#include "content/public/test/browser_test.h"
#include "content/public/test/browser_test_utils.h"
#include "content/public/test/content_browser_test.h"
#include "content/public/test/content_browser_test_utils.h"
#include "content/public/test/content_mock_cert_verifier.h"
#include "content/public/test/navigation_handle_observer.h"
#include "content/public/test/prerender_test_util.h"
#include "content/public/test/test_frame_navigation_observer.h"
#include "content/public/test/test_navigation_observer.h"
#include "content/public/test/test_utils.h"
#include "content/public/test/url_loader_interceptor.h"
#include "content/shell/browser/shell.h"
#include "content/test/content_browser_test_utils_internal.h"
#include "content/test/did_commit_navigation_interceptor.h"
#include "mojo/public/cpp/bindings/pending_receiver.h"
#include "mojo/public/cpp/bindings/receiver_set.h"
#include "net/dns/mock_host_resolver.h"
#include "net/test/embedded_test_server/embedded_test_server.h"
#include "net/test/embedded_test_server/http_request.h"
#include "net/test/embedded_test_server/http_response.h"
#include "services/network/public/cpp/features.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/blink/public/common/features.h"
#include "third_party/blink/public/common/storage_key/storage_key.h"
#include "third_party/blink/public/common/tokens/tokens.h"
#include "third_party/blink/public/mojom/dom_storage/dom_storage.mojom-test-utils.h"
#include "url/gurl.h"

namespace content {

using IsolatedOriginSource = ChildProcessSecurityPolicy::IsolatedOriginSource;

// This is a base class for all tests in this class.  It does not isolate any
// origins and only provides common helper functions to the other test classes.
class IsolatedOriginTestBase : public ContentBrowserTest {
 public:
  IsolatedOriginTestBase() = default;
  ~IsolatedOriginTestBase() override = default;

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

  // Check if `origin` is an isolated origin.  This helper is used in tests
  // that care only about globally applicable isolated origins (not restricted
  // to a particular BrowsingInstance or profile).
  bool IsIsolatedOrigin(const url::Origin& origin) {
    auto* policy = ChildProcessSecurityPolicyImpl::GetInstance();
    IsolationContext isolation_context(
        shell()->web_contents()->GetBrowserContext());
    return policy->IsIsolatedOrigin(isolation_context, origin,
                                    false /* origin_requests_isolation */);
  }

  bool IsIsolatedOrigin(const GURL& url) {
    return IsIsolatedOrigin(url::Origin::Create(url));
  }

  OriginAgentClusterIsolationState MakeOACIsolationState(
      bool requires_origin_keyed_process) {
    // Assume |requires_origin_keyed_process| is the same as
    // |is_origin_agent_cluster| here.
    if (!requires_origin_keyed_process) {
      return OriginAgentClusterIsolationState::CreateNonIsolated();
    }
    return OriginAgentClusterIsolationState::CreateForOriginAgentCluster(
        requires_origin_keyed_process);
  }

  bool ShouldOriginGetOptInProcessIsolation(const url::Origin& origin) {
    auto* site_instance = static_cast<SiteInstanceImpl*>(
        shell()->web_contents()->GetPrimaryMainFrame()->GetSiteInstance());

    OriginAgentClusterIsolationState isolation_request =
        OriginAgentClusterIsolationState::CreateNonIsolated();

    return ChildProcessSecurityPolicyImpl::GetInstance()
        ->DetermineOriginAgentClusterIsolation(
            site_instance->GetIsolationContext(), origin, isolation_request)
        .requires_origin_keyed_process();
  }

  // Assuming no additional explicit opt-in or opt-out was requested, check what
  // isolation state would currently be used for a navigation to |url| in
  // |site_instance| in the test, based on the current state in the
  // BrowsingInstance.
  static OriginAgentClusterIsolationState DetermineOriginAgentClusterIsolation(
      SiteInstanceImpl* site_instance,
      const GURL& url) {
    OriginAgentClusterIsolationState isolation_request =
        site_instance->GetIsolationContext().default_isolation_state();

    return ChildProcessSecurityPolicyImpl::GetInstance()
        ->DetermineOriginAgentClusterIsolation(
            site_instance->GetIsolationContext(), url::Origin::Create(url),
            isolation_request);
  }

  ProcessLock ProcessLockFromUrl(const std::string& url) {
    BrowserContext* browser_context = web_contents()->GetBrowserContext();
    return ProcessLock::FromSiteInfo(SiteInfo(
        /*site_url=*/GURL(url),
        /*process_lock_url=*/GURL(url),
        /*requires_origin_keyed_process=*/false,
        /*requires_origin_keyed_process_by_default=*/false,
        /*is_sandboxed=*/false, UrlInfo::kInvalidUniqueSandboxId,
        StoragePartitionConfig::CreateDefault(browser_context),
        WebExposedIsolationInfo::CreateNonIsolated(),
        WebExposedIsolationLevel::kNotIsolated, /*is_guest=*/false,
        /*does_site_request_dedicated_process_for_coop=*/false,
        /*is_jit_disabled=*/false, /*are_v8_optimizations_disabled=*/false,
        /*is_pdf=*/false, /*is_fenced=*/false,
        /*cross_origin_isolation_key=*/std::nullopt));
  }

  WebContentsImpl* web_contents() const {
    return static_cast<WebContentsImpl*>(shell()->web_contents());
  }

  // Helper function that computes an appropriate process lock that corresponds
  // to `url`'s origin (without converting to sites, handling effective URLs,
  // etc). This must be equivalent to what
  // SiteInstanceImpl::DetermineProcessLockURL() would return
  // for strict origin isolation.
  // Note: do not use this for opt-in origin isolation, as it won't set
  // requires_origin_keyed_process to true.
  ProcessLock GetStrictProcessLock(const GURL& url) {
    BrowserContext* browser_context = web_contents()->GetBrowserContext();
    GURL origin_url = url::Origin::Create(url).GetURL();
    return ProcessLock::FromSiteInfo(SiteInfo(
        /*site_url=*/origin_url,
        /*process_lock_url=*/origin_url,
        /*requires_origin_keyed_process=*/false,
        /*requires_origin_keyed_process_by_default=*/false,
        /*is_sandboxed=*/false, UrlInfo::kInvalidUniqueSandboxId,
        StoragePartitionConfig::CreateDefault(browser_context),
        WebExposedIsolationInfo::CreateNonIsolated(),
        WebExposedIsolationLevel::kNotIsolated, /*is_guest=*/false,
        /*does_site_request_dedicated_process_for_coop=*/false,
        /*is_jit_disabled=*/false, /*are_v8_optimizations_disabled=*/false,
        /*is_pdf=*/false, /*is_fenced=*/false,
        /*cross_origin_isolation_key=*/std::nullopt));
  }

 protected:
  void SetUpOnMainThread() override {
    ContentBrowserTest::SetUpOnMainThread();
    mock_cert_verifier_.mock_cert_verifier()->set_default_result(net::OK);
  }

  void SetUpCommandLine(base::CommandLine* command_line) override {
    mock_cert_verifier_.SetUpCommandLine(command_line);
  }

  void SetUpInProcessBrowserTestFixture() override {
    ContentBrowserTest::SetUpInProcessBrowserTestFixture();
    mock_cert_verifier_.SetUpInProcessBrowserTestFixture();
  }

  void TearDownInProcessBrowserTestFixture() override {
    ContentBrowserTest::TearDownInProcessBrowserTestFixture();
    mock_cert_verifier_.TearDownInProcessBrowserTestFixture();
  }

 private:
  content::ContentMockCertVerifier mock_cert_verifier_;
};

class IsolatedOriginTest : public IsolatedOriginTestBase {
 public:
  IsolatedOriginTest() = default;
  ~IsolatedOriginTest() override = default;

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

  void SetUpCommandLine(base::CommandLine* command_line) override {
    IsolatedOriginTestBase::SetUpCommandLine(command_line);
    ASSERT_TRUE(embedded_test_server()->InitializeAndListen());

    std::string origin_list =
        embedded_test_server()->GetURL("isolated.foo.com", "/").spec() + "," +
        embedded_test_server()->GetURL("isolated.bar.com", "/").spec();
    command_line->AppendSwitchASCII(switches::kIsolateOrigins, origin_list);
  }

  void SetUpOnMainThread() override {
    IsolatedOriginTestBase::SetUpOnMainThread();
    host_resolver()->AddRule("*", "127.0.0.1");
    embedded_test_server()->StartAcceptingConnections();
  }

  void InjectAndClickLinkTo(GURL url) {
    EXPECT_TRUE(ExecJs(web_contents(),
                       "var link = document.createElement('a');"
                       "link.href = '" +
                           url.spec() +
                           "';"
                           "document.body.appendChild(link);"
                           "link.click();"));
  }
};

// Tests that verify the header can be used to opt-in to origin isolation.
class OriginIsolationOptInHeaderTest : public IsolatedOriginTestBase {
 public:
  OriginIsolationOptInHeaderTest()
      : https_server_(net::EmbeddedTestServer::TYPE_HTTPS) {
    feature_list_.InitWithFeatures(
        /*enabled_features=*/{features::kOriginIsolationHeader},
        /*disabled_features=*/{
            // TODO(https://crbug.com/40259221): update this test to be
            // parameterized on kOriginKeyedProcessesByDefault, and then
            // make sure all the tests have correct expectations both with and
            // without. This will assist in removing the
            // kOriginAgentClusterDefaultEnabled flag.
            blink::features::kOriginAgentClusterDefaultEnabled,
            features::kOriginKeyedProcessesByDefault});
  }
  ~OriginIsolationOptInHeaderTest() override = default;

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

  void SetUpCommandLine(base::CommandLine* command_line) override {
    IsolatedOriginTestBase::SetUpCommandLine(command_line);
    ASSERT_TRUE(embedded_test_server()->InitializeAndListen());

    // This is needed for this test to run properly on platforms where
    //  --site-per-process isn't the default, such as Android.
    IsolateAllSitesForTesting(command_line);

    // Start the HTTPS server here so derived tests can use it if they override
    // SetUpCommandLine().
    https_server()->AddDefaultHandlers(GetTestDataFilePath());
    https_server()->RegisterRequestHandler(
        base::BindRepeating(&OriginIsolationOptInHeaderTest::HandleResponse,
                            base::Unretained(this)));
    ASSERT_TRUE(https_server()->Start());
  }

  void SetHeaderValue(const std::string& header_value) {
    header_ = header_value;
  }

  void SetRedirectTarget(const std::string& redirect_target) {
    redirect_target_ = redirect_target;
  }

  // Allows specifying what content to return when an opt-in isolation header is
  // intercepted. Uses a queue so that multiple requests can be handled without
  // returning to the test body. If the queue is empty, the document content is
  // simply "isolate me!".
  void AddContentToQueue(const std::string& content_str) {
    content_.push(content_str);
  }

  void SetUpOnMainThread() override {
    IsolatedOriginTestBase::SetUpOnMainThread();

    host_resolver()->AddRule("*", "127.0.0.1");
    embedded_test_server()->StartAcceptingConnections();
  }

  void TearDownOnMainThread() override {
    ASSERT_TRUE(https_server()->ShutdownAndWaitUntilComplete());
    IsolatedOriginTestBase::TearDownOnMainThread();
  }

  // Need an https server because the header requires HTTPS.
  net::EmbeddedTestServer* https_server() { return &https_server_; }

 private:
  std::unique_ptr<net::test_server::HttpResponse> HandleResponse(
      const net::test_server::HttpRequest& request) {
    if (request.relative_url == "/isolate_origin") {
      auto response = std::make_unique<net::test_server::BasicHttpResponse>();
      response->set_code(net::HTTP_OK);
      response->set_content_type("text/html");

      if (header_) {
        response->AddCustomHeader("Origin-Agent-Cluster", *header_);
      }

      if (!content_.empty()) {
        response->set_content(content_.front());
        content_.pop();
      } else {
        response->set_content("isolate me!");
      }
      return std::move(response);
    } else if (request.relative_url == "/redirect_me") {
      auto response = std::make_unique<net::test_server::BasicHttpResponse>();
      response->set_code(net::HTTP_MOVED_PERMANENTLY);
      response->AddCustomHeader("Location", *redirect_target_);
      response->AddCustomHeader("Origin-Agent-Cluster", *header_);
      response->set_content("redirected");
      return std::move(response);
    }

    // If we return nullptr, then the server will go ahead and actually serve
    // the file.
    return nullptr;
  }

  net::EmbeddedTestServer https_server_;
  base::test::ScopedFeatureList feature_list_;

  std::optional<std::string> header_;
  std::optional<std::string> redirect_target_;
  std::queue<std::string> content_;
};

// A set of tests that enable OriginAgentCluster by default.
class OriginIsolationDefaultOACTest : public OriginIsolationOptInHeaderTest {
 public:
  OriginIsolationDefaultOACTest() {
    feature_list_.InitAndEnableFeature(
        blink::features::kOriginAgentClusterDefaultEnabled);
  }

  ~OriginIsolationDefaultOACTest() override = default;

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

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

// A set of tests that enable process-isolated OriginAgentCluster-by-default.
class OriginKeyedProcessByDefaultTest : public OriginIsolationOptInHeaderTest {
 public:
  OriginKeyedProcessByDefaultTest() {
    feature_list_.InitWithFeatures(
        {blink::features::kOriginAgentClusterDefaultEnabled,
         features::kOriginKeyedProcessesByDefault},
        {});
  }

  ~OriginKeyedProcessByDefaultTest() override = default;

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

  void SetUpOnMainThread() override {
    OriginIsolationOptInHeaderTest::SetUpOnMainThread();
    // Constructing a new BrowserClient also installs it; the old BrowserClient
    // is restored when the new one destructs.
    browser_client_ =
        std::make_unique<OriginAgentClusterByDefaultContentBrowserClient>();
  }

 protected:
  // A custom ContentBrowserClient to allow tests to simulate turning off
  // OriginAgentClusterByDefault.
  class OriginAgentClusterByDefaultContentBrowserClient
      : public ContentBrowserTestContentBrowserClient {
   public:
    bool ShouldDisableOriginAgentClusterDefault(
        BrowserContext* browser_context) override {
      return should_disable_origin_agent_cluster_default_;
    }

    void SetShouldDisableOriginAgentClusterDefault(bool should_disable) {
      should_disable_origin_agent_cluster_default_ = should_disable;
    }

   private:
    bool should_disable_origin_agent_cluster_default_ = false;
  };

  std::unique_ptr<OriginAgentClusterByDefaultContentBrowserClient>
      browser_client_;

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

class OriginIsolationPrerenderOptInHeaderTest
    : public OriginIsolationOptInHeaderTest {
 public:
  OriginIsolationPrerenderOptInHeaderTest()
      : prerender_helper_(base::BindRepeating(
            &OriginIsolationPrerenderOptInHeaderTest::prerender_web_contents,
            base::Unretained(this))) {}
  ~OriginIsolationPrerenderOptInHeaderTest() override = default;

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

  void SetUpCommandLine(base::CommandLine* command_line) override {
    // This must be called prior to starting the test server.
    prerender_helper_.RegisterServerRequestMonitor(https_server());
    OriginIsolationOptInHeaderTest::SetUpCommandLine(command_line);
  }

  void set_prerender_web_contents(WebContents* web_contents) {
    prerender_web_contents_ = web_contents->GetWeakPtr();
  }
  WebContents* prerender_web_contents() {
    CHECK(prerender_web_contents_);
    return prerender_web_contents_.get();
  }

 protected:
  test::PrerenderTestHelper prerender_helper_;

 private:
  base::WeakPtr<WebContents> prerender_web_contents_;
};  // class OriginIsolationPrerenderOptInHeaderTest

// As in OriginIsolationOptInHeaderTest, but with same-process origin
// isolation.
class SameProcessOriginIsolationOptInHeaderTest
    : public OriginIsolationOptInHeaderTest {
 public:
  SameProcessOriginIsolationOptInHeaderTest() = default;
  ~SameProcessOriginIsolationOptInHeaderTest() override = default;

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

  void SetUpCommandLine(base::CommandLine* command_line) override {
    OriginIsolationOptInHeaderTest::SetUpCommandLine(command_line);
    command_line->AppendSwitch(switches::kDisableSiteIsolation);
    command_line->RemoveSwitch(switches::kSitePerProcess);
  }
};

// As in SameProcessOriginIsolationOptInHeaderTest, but command-line isolate
// foo.com.
class SameProcessOriginIsolationOptInHeaderWithIsolatedOriginTest
    : public SameProcessOriginIsolationOptInHeaderTest {
 public:
  SameProcessOriginIsolationOptInHeaderWithIsolatedOriginTest() = default;
  ~SameProcessOriginIsolationOptInHeaderWithIsolatedOriginTest() override =
      default;

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

  void SetUpCommandLine(base::CommandLine* command_line) override {
    SameProcessOriginIsolationOptInHeaderTest::SetUpCommandLine(command_line);
    command_line->AppendSwitchASCII(switches::kIsolateOrigins,
                                    "https://foo.com/");
  }
};

// Force WebSecurity off for tests.
class SameProcessNoWebSecurityOriginIsolationOptInHeaderTest
    : public SameProcessOriginIsolationOptInHeaderTest {
 public:
  SameProcessNoWebSecurityOriginIsolationOptInHeaderTest() = default;
  ~SameProcessNoWebSecurityOriginIsolationOptInHeaderTest() override = default;

  // Disallow copy & assign.
  SameProcessNoWebSecurityOriginIsolationOptInHeaderTest(
      const SameProcessNoWebSecurityOriginIsolationOptInHeaderTest&) = delete;
  SameProcessNoWebSecurityOriginIsolationOptInHeaderTest& operator=(
      const SameProcessNoWebSecurityOriginIsolationOptInHeaderTest&) = delete;

  void SetUpCommandLine(base::CommandLine* command_line) override {
    SameProcessOriginIsolationOptInHeaderTest::SetUpCommandLine(command_line);
    command_line->AppendSwitch(switches::kDisableWebSecurity);
  }
};

// Used for a few tests that check non-HTTPS secure context behavior.
class OriginIsolationOptInHttpServerHeaderTest : public IsolatedOriginTestBase {
 public:
  OriginIsolationOptInHttpServerHeaderTest() = default;

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

  void SetUpCommandLine(base::CommandLine* command_line) override {
    IsolatedOriginTestBase::SetUpCommandLine(command_line);
    ASSERT_TRUE(embedded_test_server()->InitializeAndListen());

    // This is needed for this test to run properly on platforms where
    //  --site-per-process isn't the default, such as Android.
    IsolateAllSitesForTesting(command_line);

    feature_list_.InitAndEnableFeature(features::kOriginIsolationHeader);

    embedded_test_server()->RegisterRequestHandler(base::BindRepeating(
        &OriginIsolationOptInHttpServerHeaderTest::HandleResponse,
        base::Unretained(this)));
  }

  void SetUpOnMainThread() override {
    host_resolver()->AddRule("*", "127.0.0.1");
    embedded_test_server()->StartAcceptingConnections();
  }

 private:
  std::unique_ptr<net::test_server::HttpResponse> HandleResponse(
      const net::test_server::HttpRequest& request) {
    auto response = std::make_unique<net::test_server::BasicHttpResponse>();
    response->set_code(net::HTTP_OK);
    response->set_content_type("text/html");
    response->AddCustomHeader("Origin-Agent-Cluster", "?1");

    response->set_content("isolate me!");
    return std::move(response);
  }

  base::test::ScopedFeatureList feature_list_;
};

// This class allows testing the interaction of OptIn isolation and command-line
// isolation for origins. Tests using this class will isolate foo.com and
// bar.com by default using command-line isolation, but any opt-in isolation
// will override this.
class OriginIsolationOptInHeaderCommandLineTest
    : public OriginIsolationOptInHeaderTest {
 public:
  OriginIsolationOptInHeaderCommandLineTest() = default;

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

  void SetUpCommandLine(base::CommandLine* command_line) override {
    OriginIsolationOptInHeaderTest::SetUpCommandLine(command_line);
    // The base class should already have started the HTTPS server so we can use
    // it here to generate origins to specify on the command line.
    ASSERT_TRUE(https_server()->Started());

    std::string origin_list = https_server()->GetURL("foo.com", "/").spec() +
                              "," +
                              https_server()->GetURL("bar.com", "/").spec();
    command_line->AppendSwitchASCII(switches::kIsolateOrigins, origin_list);
  }
};

// This test verifies that opt-in isolation takes precedence over command-line
// isolation. It loads an opt-in isolated base origin (which would have
// otherwise been isolated via command-line isolation), and then loads a child
// frame sub-origin which should-not be isolated (but would have been if the
// base origin was command-line isolated).
IN_PROC_BROWSER_TEST_F(OriginIsolationOptInHeaderCommandLineTest,
                       OptInOverridesCommandLine) {
  SetHeaderValue("?1");
  // Start off with an isolated base-origin in an a(a) configuration, then
  // navigate the subframe to a sub-origin not requesting isolation.
  // Note: this works because we serve mock headers with the base origin's html
  // file, which set the header.
  GURL isolated_base_origin_url(https_server()->GetURL(
      "foo.com", "/isolated_base_origin_with_subframe.html"));
  GURL non_isolated_sub_origin(
      https_server()->GetURL("non_isolated.foo.com", "/title1.html"));
  EXPECT_TRUE(NavigateToURL(shell(), isolated_base_origin_url));
  // The .html main frame has two iframes, this test only uses the first one.
  EXPECT_EQ(3u, CollectAllRenderFrameHosts(shell()->web_contents()).size());

  FrameTreeNode* root = web_contents()->GetPrimaryFrameTree().root();
  FrameTreeNode* child_frame_node = root->child_at(0);

  EXPECT_TRUE(
      NavigateToURLFromRenderer(child_frame_node, non_isolated_sub_origin));

  auto* policy = ChildProcessSecurityPolicyImpl::GetInstance();
  EXPECT_TRUE(policy
                  ->DetermineOriginAgentClusterIsolation(
                      root->current_frame_host()
                          ->GetSiteInstance()
                          ->GetIsolationContext(),
                      url::Origin::Create(isolated_base_origin_url),
                      MakeOACIsolationState(false))
                  .requires_origin_keyed_process());
  EXPECT_FALSE(policy
                   ->DetermineOriginAgentClusterIsolation(
                       root->current_frame_host()
                           ->GetSiteInstance()
                           ->GetIsolationContext(),
                       url::Origin::Create(non_isolated_sub_origin),
                       MakeOACIsolationState(false))
                   .requires_origin_keyed_process());
  // Make sure the child (i.e. sub-origin) is not isolated.
  EXPECT_NE(root->current_frame_host()->GetSiteInstance(),
            child_frame_node->current_frame_host()->GetSiteInstance());
  EXPECT_EQ(
      GURL("https://foo.com"),
      child_frame_node->current_frame_host()->GetSiteInstance()->GetSiteURL());
  // The following test passes because IsIsolatedOrigin doesn't distinguish
  // between command-line isolation and opt-in isolation.
  EXPECT_TRUE(policy->IsIsolatedOrigin(
      root->current_frame_host()->GetSiteInstance()->GetIsolationContext(),
      url::Origin::Create(non_isolated_sub_origin),
      false /* origin_requests_isolation */));

  // Make sure the opt-in isolated origin is origin-keyed, and the non-opt-in
  // origin is site-keyed.
  EXPECT_TRUE(root->current_frame_host()
                  ->GetSiteInstance()
                  ->GetSiteInfo()
                  .requires_origin_keyed_process());
  EXPECT_FALSE(child_frame_node->current_frame_host()
                   ->GetSiteInstance()
                   ->GetSiteInfo()
                   .requires_origin_keyed_process());

  // Make sure the master opt-in list has the base origin isolated and the sub
  // origin not isolated.
  BrowserContext* browser_context = web_contents()->GetBrowserContext();
  EXPECT_TRUE(policy->HasOriginEverRequestedOriginAgentClusterValue(
      browser_context, url::Origin::Create(isolated_base_origin_url)));
  EXPECT_FALSE(policy->HasOriginEverRequestedOriginAgentClusterValue(
      browser_context, url::Origin::Create(non_isolated_sub_origin)));
}

// A test to verify that an origin with a trailing dot in the domain name
// doesn't crash when it opts-out of origin isolation when
// kOriginAgentClusterDefaultEnabled is enabled.
IN_PROC_BROWSER_TEST_F(OriginIsolationOptInHeaderTest,
                       TrailingDotDomainOptOutDoesNotCrash) {
  GURL dotted_nonisolated_url(
      https_server()->GetURL("a.com.", "/isolate_origin"));

  // Set header to opt this domain out of default OriginAgentCluster.
  SetHeaderValue("?0");
  EXPECT_TRUE(NavigateToURL(shell(), dotted_nonisolated_url));
  url::Origin origin(url::Origin::Create(dotted_nonisolated_url));
  EXPECT_FALSE(ShouldOriginGetOptInProcessIsolation(origin));
}

// A test to confirm that "a.com." is treated as a separate host (and hence
// a separate origin) from "a.com". See example at
// https://url.spec.whatwg.org/#concept-domain.
IN_PROC_BROWSER_TEST_F(OriginIsolationOptInHeaderTest,
                       TrailingDotDomainIsolatesSeparately1) {
  GURL main_frame_url(https_server()->GetURL(
      "foo.com", "/cross_site_iframe_factory.html?foo.com(foo.com,foo.com)"));
  GURL isolated_url(https_server()->GetURL("a.com", "/isolate_origin"));
  GURL dotted_isolated_url(https_server()->GetURL("a.com.", "/isolate_origin"));
  SetHeaderValue("?1");

  // Create page with sibling iframes.
  EXPECT_TRUE(NavigateToURL(shell(), main_frame_url));
  FrameTreeNode* root = web_contents()->GetPrimaryFrameTree().root();
  EXPECT_EQ(2u, root->child_count());
  FrameTreeNode* child0_frame_node = root->child_at(0);
  FrameTreeNode* child1_frame_node = root->child_at(1);
  EXPECT_TRUE(NavigateToURLFromRenderer(child0_frame_node, isolated_url));
  EXPECT_TRUE(
      NavigateToURLFromRenderer(child1_frame_node, dotted_isolated_url));

  url::Origin child0_origin(url::Origin::Create(isolated_url));
  url::Origin child1_origin(url::Origin::Create(dotted_isolated_url));
  EXPECT_NE(isolated_url, dotted_isolated_url);
  EXPECT_NE(child0_origin, child1_origin);

  EXPECT_TRUE(ShouldOriginGetOptInProcessIsolation(child0_origin));
  EXPECT_TRUE(ShouldOriginGetOptInProcessIsolation(child1_origin));

  scoped_refptr<SiteInstanceImpl> child0_site_instance =
      child0_frame_node->current_frame_host()->GetSiteInstance();
  scoped_refptr<SiteInstanceImpl> child1_site_instance =
      child1_frame_node->current_frame_host()->GetSiteInstance();
  EXPECT_NE(child0_site_instance, child1_site_instance);
  EXPECT_NE(child0_site_instance->GetProcess(),
            child1_site_instance->GetProcess());
}

// A test similar to TrailingDotDomainIsolatesSeparately1, but this time the
// "a.com" domain does not opt-in via a header, and does not get an origin-
// keyed process. Thus, it ends up in a separate process from "a.com.".
IN_PROC_BROWSER_TEST_F(OriginIsolationOptInHeaderTest,
                       TrailingDotDomainIsolatesSeparately2) {
  GURL main_frame_url(https_server()->GetURL(
      "foo.com", "/cross_site_iframe_factory.html?foo.com(foo.com,foo.com)"));
  GURL non_isolated_url(https_server()->GetURL("a.com", "/title1.html"));
  GURL dotted_isolated_url(https_server()->GetURL("a.com.", "/isolate_origin"));

  // Create page with sibling iframes.
  EXPECT_TRUE(NavigateToURL(shell(), main_frame_url));
  FrameTreeNode* root = web_contents()->GetPrimaryFrameTree().root();
  EXPECT_EQ(2u, root->child_count());
  FrameTreeNode* child0_frame_node = root->child_at(0);
  FrameTreeNode* child1_frame_node = root->child_at(1);
  SetHeaderValue("?1");
  EXPECT_TRUE(
      NavigateToURLFromRenderer(child0_frame_node, dotted_isolated_url));
  SetHeaderValue("");
  EXPECT_TRUE(NavigateToURLFromRenderer(child1_frame_node, non_isolated_url));

  url::Origin child0_origin(url::Origin::Create(dotted_isolated_url));
  url::Origin child1_origin(url::Origin::Create(non_isolated_url));

  EXPECT_TRUE(ShouldOriginGetOptInProcessIsolation(child0_origin));
  EXPECT_FALSE(ShouldOriginGetOptInProcessIsolation(child1_origin));

  scoped_refptr<SiteInstanceImpl> child0_site_instance =
      child0_frame_node->current_frame_host()->GetSiteInstance();
  scoped_refptr<SiteInstanceImpl> child1_site_instance =
      child1_frame_node->current_frame_host()->GetSiteInstance();
  EXPECT_NE(child0_site_instance, child1_site_instance);
  EXPECT_NE(child0_site_instance->GetProcess(),
            child1_site_instance->GetProcess());
}

// A test to confirm that if an Origin-Agent-Cluster header is encountered (but
// not committed) as part of a redirect, that it does not opt-in to
// OriginAgentCluster isolation. The setup in this test is subtle, since in
// order for the call to NavigationRequest::OnRequestRedirected() to attempt to
// create a new SiteInstance, we must load the same origin the redirect wants to
// use, and load it without OriginAgentCluster isolation. Prior to the fix for
// https://crbug.com/1329061 the redirect would result in opting the origin into
// OriginAgentCluster isolation since no global walk is present to detect that
// it has already been loaded without.
IN_PROC_BROWSER_TEST_F(OriginIsolationOptInHeaderTest,
                       RedirectSameSiteWithOACDoesntOptIn) {
  GURL main_frame_url(https_server()->GetURL(
      "foo.com", "/cross_site_iframe_factory.html?foo.com(foo.com)"));
  GURL redirect_url(https_server()->GetURL("foo.com", "/redirect_me"));
  GURL expected_commit_url(https_server()->GetURL("foo.com", "/title1.html"));
  url::Origin origin(url::Origin::Create(main_frame_url));

  EXPECT_TRUE(NavigateToURL(shell(), main_frame_url));
  EXPECT_FALSE(ShouldOriginGetOptInProcessIsolation(origin));
  EXPECT_EQ(2u, CollectAllRenderFrameHosts(shell()->web_contents()).size());
  FrameTreeNode* root = web_contents()->GetPrimaryFrameTree().root();
  FrameTreeNode* child_frame_node = root->child_at(0);

  SetRedirectTarget("/title1.html");
  SetHeaderValue("?1");
  EXPECT_TRUE(NavigateToURLFromRenderer(child_frame_node, redirect_url,
                                        expected_commit_url));
  // This next line verifies that the OriginAgentCluster header sent with the
  // 301 redirect failed to opt foo.com into OriginAgentCluster isolation, as
  // it should. The check will fail if the origin was opted-in to
  // OriginAgentCluster isolation.
  EXPECT_FALSE(ShouldOriginGetOptInProcessIsolation(origin));
}

// Same as the preceding test, but the redirect is cross-site.
IN_PROC_BROWSER_TEST_F(OriginIsolationOptInHeaderTest,
                       RedirectCrossSiteWithOACDoesntOptIn) {
  GURL main_frame_url(https_server()->GetURL(
      "foo.com", "/cross_site_iframe_factory.html?foo.com(foo.com)"));
  GURL redirect_url(https_server()->GetURL("bar.com", "/redirect_me"));
  GURL expected_commit_url(https_server()->GetURL("foo.com", "/title1.html"));
  url::Origin origin(url::Origin::Create(main_frame_url));

  EXPECT_TRUE(NavigateToURL(shell(), main_frame_url));
  EXPECT_FALSE(ShouldOriginGetOptInProcessIsolation(origin));

  EXPECT_EQ(2u, CollectAllRenderFrameHosts(shell()->web_contents()).size());
  FrameTreeNode* root = web_contents()->GetPrimaryFrameTree().root();
  FrameTreeNode* child_frame_node = root->child_at(0);

  SetRedirectTarget(expected_commit_url.spec());
  SetHeaderValue("?1");
  EXPECT_TRUE(NavigateToURLFromRenderer(child_frame_node, redirect_url,
                                        expected_commit_url));

  // This next line verifies that the OriginAgentCluster header sent with the
  // 301 redirect failed to opt foo.com into OriginAgentCluster isolation, as
  // it should. The check will fail if the origin was opted-in to
  // OriginAgentCluster isolation.
  EXPECT_FALSE(ShouldOriginGetOptInProcessIsolation(origin));
}

// This tests that header-based opt-in causes the origin to end up in the
// isolated origins list.
IN_PROC_BROWSER_TEST_F(OriginIsolationOptInHeaderTest, Basic) {
  base::HistogramTester histograms;
  SetHeaderValue("?1");

  GURL url(https_server()->GetURL("isolated.foo.com", "/isolate_origin"));
  url::Origin origin(url::Origin::Create(url));

  EXPECT_FALSE(ShouldOriginGetOptInProcessIsolation(origin));
  EXPECT_TRUE(NavigateToURL(shell(), url));
  EXPECT_TRUE(ShouldOriginGetOptInProcessIsolation(origin));

  EXPECT_THAT(
      histograms.GetAllSamples("Navigation.OriginAgentCluster.Result"),
      testing::ElementsAre(base::Bucket(
          static_cast<int>(NavigationRequest::OriginAgentClusterEndResult::
                               kRequestedAndOriginKeyed),
          1)));
}

// A test to ensure that origins whose host has a trailing dot pass the
// validation checks for explicit opt-ins and opt-outs. This is an
// `OriginKeyedProcessByDefaultTest` test in order that the explicit opt-out
// will be tracked. Note: failure for either part of this test will involve
// crashing on a CHECK in
// ChildProcessSecurityPolicyImpl::AddOriginIsolationStateForBrowsingInstance():
IN_PROC_BROWSER_TEST_F(OriginKeyedProcessByDefaultTest,
                       HostWithTrailingDotAllowed) {
  // Explicit opt-in with a trailing dot.
  SetHeaderValue("?1");
  GURL opt_in_url(https_server()->GetURL("opt-in.foo.com.", "/isolate_origin"));
  url::Origin opt_in_origin(url::Origin::Create(opt_in_url));

  EXPECT_FALSE(ShouldOriginGetOptInProcessIsolation(opt_in_origin));
  EXPECT_TRUE(NavigateToURL(shell(), opt_in_url));
  EXPECT_TRUE(ShouldOriginGetOptInProcessIsolation(opt_in_origin));

  // Explicit opt-out with a trailing dot.
  SetHeaderValue("?0");
  GURL opt_out_url(
      https_server()->GetURL("opt-out.foo.com.", "/isolate_origin"));
  url::Origin opt_out_origin(url::Origin::Create(opt_out_url));

  EXPECT_FALSE(ShouldOriginGetOptInProcessIsolation(opt_out_origin));
  EXPECT_TRUE(NavigateToURL(shell(), opt_out_url));
  EXPECT_FALSE(ShouldOriginGetOptInProcessIsolation(opt_out_origin));
}

// A simple test that, when OAC-by-default is enabled with process-isolation, an
// origin that receives default OAC is put in an origin-keyed process.
IN_PROC_BROWSER_TEST_F(OriginKeyedProcessByDefaultTest,
                       DefaultIsOriginKeyedProcess) {
  GURL test_url(https_server()->GetURL("foo.com", "/title1.html"));
  EXPECT_TRUE(NavigateToURL(shell(), test_url));
  FrameTreeNode* root = web_contents()->GetPrimaryFrameTree().root();
  scoped_refptr<SiteInstanceImpl> site_instance =
      root->current_frame_host()->GetSiteInstance();
  OriginAgentClusterIsolationState isolation_state =
      DetermineOriginAgentClusterIsolation(site_instance.get(), test_url);
  // Even though this request has no OriginAgentCluster header, it should get
  // an origin-keyed process by default.
  EXPECT_TRUE(isolation_state.is_origin_agent_cluster());
  EXPECT_TRUE(isolation_state.requires_origin_keyed_process());
  EXPECT_TRUE(site_instance->GetSiteInfo().requires_origin_keyed_process());
  EXPECT_TRUE(
      site_instance->GetSiteInfo().requires_origin_keyed_process_by_default());
}

// A test to make sure that a renderer-initiated navigation from a default-
// isolated frame to about:blank doesn't crash on a ProcessLock mismatch.
IN_PROC_BROWSER_TEST_F(OriginKeyedProcessByDefaultTest,
                       RendererInitiatedNavigationToAboutBlankSucceeds) {
  GURL test_url(https_server()->GetURL("foo.com", "/title1.html"));
  EXPECT_TRUE(NavigateToURL(shell(), test_url));

  // Verify the main frame got an origin-keyed process by default.
  FrameTreeNode* root = web_contents()->GetPrimaryFrameTree().root();
  scoped_refptr<SiteInstanceImpl> site_instance =
      root->current_frame_host()->GetSiteInstance();
  EXPECT_TRUE(site_instance->GetSiteInfo().requires_origin_keyed_process());
  EXPECT_TRUE(
      site_instance->GetSiteInfo().requires_origin_keyed_process_by_default());

  // Record the origin of the isolated frame.
  std::string initial_origin = EvalJs(shell(), "origin").ExtractString();
  EXPECT_EQ(url::Origin::Create(test_url).GetURL(), GURL(initial_origin));

  // Renderer-initiated navigation to about:blank.
  TestNavigationObserver navigation_observer(shell()->web_contents(), 1);
  EXPECT_TRUE(ExecJs(shell(), "location.href = 'about:blank';"));
  navigation_observer.Wait();

  // Expect that the about:blank frame inherits the origin of the initiator.
  // Also, this gives us additional verification that the navigation succeeded
  // without hitting the ProcessLock check.
  EXPECT_EQ(initial_origin, EvalJs(shell(), "origin").ExtractString());
  scoped_refptr<SiteInstanceImpl> new_site_instance =
      root->current_frame_host()->GetSiteInstance();
  // Note: the site_instance has changed, due to the proactive BrowsingInstance
  // swap done to make the previous page eligible for back-forward cache.
  // Note: some bots may run this test with BFCache disabled, so we need to
  // handle both cases here.
  if (base::FeatureList::IsEnabled(features::kBackForwardCache)) {
    EXPECT_NE(site_instance, new_site_instance);
  } else {
    EXPECT_EQ(site_instance, new_site_instance);
  }
  EXPECT_EQ(site_instance->GetSiteInfo(), site_instance->GetSiteInfo());
  EXPECT_TRUE(new_site_instance->GetSiteInfo().requires_origin_keyed_process());
}

// A test to make sure that a renderer-initiated navigation from a default-
// isolated frame to about:blank doesn't crash on a ProcessLock mismatch.
// This test is similar to RendererInitiatedNavigationToAboutBlankSucceeds
// but with BFCache disabled.
IN_PROC_BROWSER_TEST_F(
    OriginKeyedProcessByDefaultTest,
    RendererInitiatedNavigationToAboutBlankSucceeds_BFCacheDisabled) {
  DisableBackForwardCacheForTesting(
      web_contents(), BackForwardCacheImpl::TEST_REQUIRES_NO_CACHING);
  GURL test_url(https_server()->GetURL("foo.com", "/title1.html"));
  EXPECT_TRUE(NavigateToURL(shell(), test_url));

  // Verify the main frame got an origin-keyed process by default.
  FrameTreeNode* root = web_contents()->GetPrimaryFrameTree().root();
  scoped_refptr<SiteInstanceImpl> site_instance =
      root->current_frame_host()->GetSiteInstance();
  EXPECT_TRUE(site_instance->GetSiteInfo().requires_origin_keyed_process());
  EXPECT_TRUE(
      site_instance->GetSiteInfo().requires_origin_keyed_process_by_default());

  // Record the origin of the isolated frame.
  std::string initial_origin = EvalJs(shell(), "origin").ExtractString();
  EXPECT_EQ(url::Origin::Create(test_url).GetURL(), GURL(initial_origin));

  // Renderer-initiated navigation to about:blank.
  TestNavigationObserver navigation_observer(shell()->web_contents(), 1);
  EXPECT_TRUE(ExecJs(shell(), "location.href = 'about:blank';"));
  navigation_observer.Wait();

  // Expect that the about:blank frame inherits the origin of the initiator.
  // Also, this gives us additional verification that the navigation succeeded
  // without hitting the ProcessLock check.
  EXPECT_EQ(initial_origin, EvalJs(shell(), "origin").ExtractString());
  scoped_refptr<SiteInstanceImpl> new_site_instance =
      root->current_frame_host()->GetSiteInstance();
  // Note: with BFCache disabled, the site_instance does not change.
  EXPECT_EQ(site_instance, new_site_instance);
  EXPECT_EQ(site_instance->GetSiteInfo(), site_instance->GetSiteInfo());
  EXPECT_TRUE(new_site_instance->GetSiteInfo().requires_origin_keyed_process());
}

// The same as for DefaultOptInIsIsolated, but testing on a subframe.
IN_PROC_BROWSER_TEST_F(OriginKeyedProcessByDefaultTest,
                       SubframeDefaultIsOriginKeyedProcess) {
  GURL test_url(https_server()->GetURL("foo.com",
                                       "/cross_site_iframe_factory.html?"
                                       "foo.com(foo.com)"));
  EXPECT_TRUE(NavigateToURL(shell(), test_url));
  EXPECT_EQ(2u, CollectAllRenderFrameHosts(shell()->web_contents()).size());
  FrameTreeNode* root = web_contents()->GetPrimaryFrameTree().root();
  FrameTreeNode* child_frame_node = root->child_at(0);

  // Even though this request has no OriginAgentCluster header, it should get
  // an origin-keyed process by default.
  SetHeaderValue("");
  GURL default_isolated_url(
      https_server()->GetURL("isolated.foo.com", "/title1.html"));
  EXPECT_TRUE(
      NavigateToURLFromRenderer(child_frame_node, default_isolated_url));

  scoped_refptr<SiteInstanceImpl> root_site_instance =
      root->current_frame_host()->GetSiteInstance();
  scoped_refptr<SiteInstanceImpl> child_site_instance =
      child_frame_node->current_frame_host()->GetSiteInstance();
  OriginAgentClusterIsolationState child_isolation_state =
      DetermineOriginAgentClusterIsolation(child_site_instance.get(),
                                           default_isolated_url);
  EXPECT_NE(child_site_instance, root_site_instance);
  EXPECT_NE(child_site_instance->GetProcess(),
            root_site_instance->GetProcess());
  EXPECT_TRUE(child_isolation_state.is_origin_agent_cluster());
  EXPECT_TRUE(child_isolation_state.requires_origin_keyed_process());
  EXPECT_EQ(
      root_site_instance->GetIsolationContext().default_isolation_state(),
      child_site_instance->GetIsolationContext().default_isolation_state());
  EXPECT_TRUE(
      child_site_instance->GetSiteInfo().requires_origin_keyed_process());
  EXPECT_TRUE(child_site_instance->GetSiteInfo()
                  .requires_origin_keyed_process_by_default());

  auto* policy = ChildProcessSecurityPolicyImpl::GetInstance();
  IsolationContext isolation_context =
      root_site_instance->GetIsolationContext();
  // Verify that we're not explicitly tracking the origin for
  // `default_isolated_url`.
  EXPECT_EQ(static_cast<OriginAgentClusterIsolationState*>(nullptr),
            policy->LookupOriginIsolationStateForTesting(
                isolation_context.browsing_instance_id(),
                url::Origin::Create(default_isolated_url)));

  // Now trigger a global walk by attempting to create a non-isolated version of
  // the same origin.
  GURL attempted_non_isolated_url(
      https_server()->GetURL("isolated.foo.com", "/isolate_origin"));
  SetHeaderValue("?0");
  EXPECT_TRUE(
      NavigateToURLFromRenderer(child_frame_node, attempted_non_isolated_url));
  // Now the origin should be explicitly tracked, even though it continues to
  // have the default isolation state as defined for the current
  // BrowsingInstance.
  OriginAgentClusterIsolationState* isolation_state2 =
      policy->LookupOriginIsolationStateForTesting(
          isolation_context.browsing_instance_id(),
          url::Origin::Create(default_isolated_url));
  ASSERT_NE(static_cast<OriginAgentClusterIsolationState*>(nullptr),
            isolation_state2);
  EXPECT_TRUE(isolation_state2->is_origin_agent_cluster());
  EXPECT_TRUE(isolation_state2->requires_origin_keyed_process());
}

// The test ExplicitOptInRespected tests the speculative RFH created before
// receiving the OAC headers. The delay must be set to zero so that the
// speculative RFH is always created before receiving the header.
class OriginKeyedProcessByDefaultTestWithoutSpeculativeRFHDelay
    : public OriginKeyedProcessByDefaultTest {
 public:
  OriginKeyedProcessByDefaultTestWithoutSpeculativeRFHDelay() {
    feature_list_for_defer_speculative_rfh_.InitAndEnableFeatureWithParameters(
        features::kDeferSpeculativeRFHCreation,
        {{"create_speculative_rfh_delay_ms", "0"}});
  }

 private:
  base::test::ScopedFeatureList feature_list_for_defer_speculative_rfh_;
};

// Using origin-keyed processes by default faces a challenge for speculative
// RenderFrameHosts, which are created before any OAC headers arrive.
// Note: the origin is tracked even though the SiteInfo still says it is an
// origin-keyed process by default.
IN_PROC_BROWSER_TEST_F(
    OriginKeyedProcessByDefaultTestWithoutSpeculativeRFHDelay,
    ExplicitOptInRespected) {
  GURL test_url(https_server()->GetURL("foo.com",
                                       "/cross_site_iframe_factory.html?"
                                       "foo.com(foo.com)"));
  EXPECT_TRUE(NavigateToURL(shell(), test_url));
  EXPECT_EQ(2u, CollectAllRenderFrameHosts(shell()->web_contents()).size());
  FrameTreeNode* root = web_contents()->GetPrimaryFrameTree().root();
  FrameTreeNode* child_frame_node = root->child_at(0);

  // This request explicitly opts-in to OAC, and should get process isolation.
  // Note the use of the "isolate_origin" relative path below to force
  // processing of the (non-empty) OAC header.
  SetHeaderValue("?1");
  GURL explicit_isolated_url(
      https_server()->GetURL("isolated.foo.com", "/isolate_origin"));
  EXPECT_TRUE(
      NavigateToURLFromRenderer(child_frame_node, explicit_isolated_url));

  auto* site_instance =
      child_frame_node->current_frame_host()->GetSiteInstance();
  OriginAgentClusterIsolationState isolation_state =
      DetermineOriginAgentClusterIsolation(site_instance,
                                           explicit_isolated_url);
  EXPECT_TRUE(isolation_state.is_origin_agent_cluster());
  EXPECT_TRUE(isolation_state.requires_origin_keyed_process());
  EXPECT_TRUE(site_instance->GetSiteInfo().requires_origin_keyed_process());
  // In this scenario, the explicit opt-in ends up using a SiteInstance that was
  // created for the speculative RFH, and with requires_origin_keyed_process on
  // by default. Since we don't want to alter the underlying SiteInfo after
  // it's been used to create a ProcessLock, we leave this case as "by_default"
  // in the SiteInfo since the isolation behavior is the same.
  //
  // Note that if the speculative RFH had been created after a previous instance
  // of the origin had been explicitly opted-in, then
  // `requires_origin_keyed_process_by_default()` would return false in that
  // case. This can happen in a cross-origin redirect from A to B, where B has
  // an opt-in header. We would create a speculative RFH for A, throw it away
  // when the redirect happens, and wait to create the RFH for B until headers
  // have arrived.
  EXPECT_TRUE(
      site_instance->GetSiteInfo().requires_origin_keyed_process_by_default());

  // Verify the explicit opt-in is being tracked.
  auto* policy = ChildProcessSecurityPolicyImpl::GetInstance();
  IsolationContext isolation_context =
      root->current_frame_host()->GetSiteInstance()->GetIsolationContext();
  OriginAgentClusterIsolationState* isolation_state2 =
      policy->LookupOriginIsolationStateForTesting(
          isolation_context.browsing_instance_id(),
          url::Origin::Create(explicit_isolated_url));
  ASSERT_NE(static_cast<OriginAgentClusterIsolationState*>(nullptr),
            isolation_state2);
  EXPECT_TRUE(isolation_state2->is_origin_agent_cluster());
  EXPECT_TRUE(isolation_state2->requires_origin_keyed_process());
}

// Process-isolated OAC-by-default should not process isolate a navigation that
// explicitly opts-out. This test is important, in part, for making sure all the
// CanAccessDataForOrigin checks encountered during the navigation pass.
IN_PROC_BROWSER_TEST_F(OriginKeyedProcessByDefaultTest,
                       ExplicitOptOutRespected) {
  GURL test_url(https_server()->GetURL("foo.com",
                                       "/cross_site_iframe_factory.html?"
                                       "foo.com(foo.com)"));
  EXPECT_TRUE(NavigateToURL(shell(), test_url));
  EXPECT_EQ(2u, CollectAllRenderFrameHosts(shell()->web_contents()).size());
  FrameTreeNode* root = web_contents()->GetPrimaryFrameTree().root();
  FrameTreeNode* child_frame_node = root->child_at(0);

  // This request explicitly opts-out of OAC, and should not get process
  // isolation. Note the use of the "isolate_origin" relative path below to
  // force processing of the (non-empty) OAC header.
  SetHeaderValue("?0");
  GURL default_not_isolated_url(
      https_server()->GetURL("not-isolated.foo.com", "/isolate_origin"));
  EXPECT_TRUE(
      NavigateToURLFromRenderer(child_frame_node, default_not_isolated_url));

  auto* child_site_instance =
      child_frame_node->current_frame_host()->GetSiteInstance();
  // The child should be in a separate process from the main frame despite
  // opting-out, because the child is now in a site-keyed process while the
  // main frame is in an origin-keyed process (as verified below).
  EXPECT_NE(child_site_instance->GetProcess(),
            root->current_frame_host()->GetSiteInstance()->GetProcess());

  OriginAgentClusterIsolationState isolation_state =
      DetermineOriginAgentClusterIsolation(child_site_instance,
                                           default_not_isolated_url);
  EXPECT_FALSE(isolation_state.is_origin_agent_cluster());
  EXPECT_FALSE(isolation_state.requires_origin_keyed_process());
  EXPECT_FALSE(
      child_site_instance->GetSiteInfo().requires_origin_keyed_process());
  EXPECT_FALSE(child_site_instance->GetSiteInfo()
                   .requires_origin_keyed_process_by_default());

  // Verify the explicit opt-out is being tracked.
  auto* policy = ChildProcessSecurityPolicyImpl::GetInstance();
  IsolationContext isolation_context =
      root->current_frame_host()->GetSiteInstance()->GetIsolationContext();
  OriginAgentClusterIsolationState* isolation_state2 =
      policy->LookupOriginIsolationStateForTesting(
          isolation_context.browsing_instance_id(),
          url::Origin::Create(default_not_isolated_url));
  ASSERT_NE(static_cast<OriginAgentClusterIsolationState*>(nullptr),
            isolation_state2);
  EXPECT_FALSE(isolation_state2->is_origin_agent_cluster());
  EXPECT_FALSE(isolation_state2->requires_origin_keyed_process());
}

namespace {

void TestDefaultIsolationForFrame(
    FrameTreeNode* ftn,
    const GURL& default_isolated_url,
    bool expect_origin_agent_cluster,
    bool expect_requires_origin_keyed_process,
    bool expect_default_requires_origin_keyed_process) {
  auto* policy = ChildProcessSecurityPolicyImpl::GetInstance();
  auto* site_instance = ftn->current_frame_host()->GetSiteInstance();
  OriginAgentClusterIsolationState isolation_state =
      IsolatedOriginTestBase::DetermineOriginAgentClusterIsolation(
          site_instance, default_isolated_url);
  const SiteInfo& site_info = site_instance->GetSiteInfo();
  EXPECT_EQ(expect_origin_agent_cluster,
            isolation_state.is_origin_agent_cluster());
  EXPECT_EQ(expect_requires_origin_keyed_process,
            isolation_state.requires_origin_keyed_process());
  EXPECT_EQ(expect_requires_origin_keyed_process,
            site_info.requires_origin_keyed_process());
  EXPECT_EQ(expect_default_requires_origin_keyed_process,
            site_info.requires_origin_keyed_process_by_default());

  // Verify that we're not explicitly tracking the origin we isolated by
  // default.
  IsolationContext isolation_context = site_instance->GetIsolationContext();
  EXPECT_EQ(static_cast<OriginAgentClusterIsolationState*>(nullptr),
            policy->LookupOriginIsolationStateForTesting(
                isolation_context.browsing_instance_id(),
                url::Origin::Create(default_isolated_url)));
}

}  // namespace

// This test verifies that locking the definition of default isolation to
// individual BrowsingInstances works correctly when the underlying feature
// is changed dynamically.
IN_PROC_BROWSER_TEST_F(OriginKeyedProcessByDefaultTest,
                       DynamicEnterprisePolicyChange) {
  GURL test_url(https_server()->GetURL("foo.com",
                                       "/cross_site_iframe_factory.html?"
                                       "foo.com(foo.com)"));
  SetHeaderValue("");
  GURL default_isolated_url(
      https_server()->GetURL("isolated.foo.com", "/title1.html"));

  // Setup first BrowsingInstance. This one will have default isolation with
  // origin_agent_cluster and requests_origin_keyed_process (by default) true.
  Shell* shell1 = shell();
  auto* web_contents1 = static_cast<WebContentsImpl*>(shell1->web_contents());

  EXPECT_TRUE(NavigateToURL(shell1, test_url));
  EXPECT_EQ(2u, CollectAllRenderFrameHosts(web_contents1).size());
  FrameTreeNode* root1 = web_contents1->GetPrimaryFrameTree().root();
  FrameTreeNode* child_frame_node1 = root1->child_at(0);

  // Load a frame into the first BrowsingInstance.
  // Even though this request has no OriginAgentCluster header, it should get
  // process-isolated OAC by default.
  EXPECT_TRUE(
      NavigateToURLFromRenderer(child_frame_node1, default_isolated_url));
  EXPECT_NE(
      child_frame_node1->current_frame_host()->GetSiteInstance()->GetProcess(),
      root1->current_frame_host()->GetSiteInstance()->GetProcess());

  {
    SCOPED_TRACE("child_frame_node1");
    TestDefaultIsolationForFrame(
        child_frame_node1, default_isolated_url,
        /*expect_origin_agent_cluster=*/true,
        /*expect_requires_origin_keyed_process=*/true,
        /*expect_default_requires_origin_keyed_process=*/true);
  }

  // Dynamically disable the feature to simulate the enterprise policy being
  // dynamically changed.
  browser_client_->SetShouldDisableOriginAgentClusterDefault(true);

  // Create a second BrowsingInstance. This one will have default isolation with
  // origin_agent_cluster = false and requests_origin_keyed_process (by default)
  // false.
  Shell* shell2 = CreateBrowser();
  auto* web_contents2 = static_cast<WebContentsImpl*>(shell2->web_contents());

  // Load a frame into the second BrowsingInstance.
  // This request also has no OriginAgentCluster header, but it should not get
  // OAC by default, nor request process-isolation.
  EXPECT_TRUE(NavigateToURL(shell2, test_url));
  FrameTreeNode* root2 = web_contents2->GetPrimaryFrameTree().root();
  FrameTreeNode* child_frame_node2 = root2->child_at(0);
  // We navigate to `default_isolated_url` again so that we're using the same
  // urls in both parts of the test, but we don't expect it to be isolated in
  // this BrowsingInstance.
  EXPECT_TRUE(
      NavigateToURLFromRenderer(child_frame_node2, default_isolated_url));
  EXPECT_EQ(
      child_frame_node2->current_frame_host()->GetSiteInstance()->GetProcess(),
      root2->current_frame_host()->GetSiteInstance()->GetProcess());

  {
    SCOPED_TRACE("child_frame_node2");
    TestDefaultIsolationForFrame(
        child_frame_node2, default_isolated_url,
        /*expect_origin_agent_cluster=*/false,
        /*expect_requires_origin_keyed_process=*/false,
        /*expect_default_requires_origin_keyed_process=*/false);
  }

  // We expect the default isolation to be different in the two
  // BrowsingInstances.
  EXPECT_NE(root1->current_frame_host()
                ->GetSiteInstance()
                ->GetIsolationContext()
                .default_isolation_state(),
            root2->current_frame_host()
                ->GetSiteInstance()
                ->GetIsolationContext()
                .default_isolation_state());

  // Another navigation in root1 should respect the origin-keyed default used by
  // that BrowsingInstance and not the current site-keyed default.
  GURL default_isolated_url2(
      https_server()->GetURL("isolated.bar.com", "/title1.html"));
  EXPECT_TRUE(NavigateToURL(shell1, test_url));
  {
    SCOPED_TRACE("root1");
    TestDefaultIsolationForFrame(
        root1, default_isolated_url2,
        /*expect_origin_agent_cluster=*/true,
        /*expect_requires_origin_keyed_process=*/true,
        /*expect_default_requires_origin_keyed_process=*/true);
  }
}

IN_PROC_BROWSER_TEST_F(OriginIsolationDefaultOACTest, Basic) {
  GURL test_url(https_server()->GetURL("foo.com",
                                       "/cross_site_iframe_factory.html?"
                                       "foo.com(foo.com)"));
  // We must load the origins to be isolated (or not) into a child frame so that
  // they all stay in the same BrowsingInstance, since the test relies on
  // knowing isolation history for the OriginAgentClusterEndResult::*But* cases.
  // In this test, the convention is:
  //   foo.com is (implicitly) isolated,
  //   isolated.foo.com is (explicitly) isolated,
  //   isolated.bar.com is (implicitly) isolated, and
  //   bar.com is (explicitly) not isolated.
  EXPECT_TRUE(NavigateToURL(shell(), test_url));
  EXPECT_EQ(2u, CollectAllRenderFrameHosts(shell()->web_contents()).size());
  FrameTreeNode* root = web_contents()->GetPrimaryFrameTree().root();
  FrameTreeNode* child_frame_node = root->child_at(0);

  // The first three scenarios should all get the isolation status they request
  // (the "And" cases).
  {
    // Explicitly request OriginAgentCluster via the header.
    SetHeaderValue("?1");
    base::HistogramTester histograms;
    GURL isolated_suborigin_url(
        https_server()->GetURL("isolated.foo.com", "/isolate_origin"));
    EXPECT_TRUE(
        NavigateToURLFromRenderer(child_frame_node, isolated_suborigin_url));
    auto* site_instance =
        child_frame_node->current_frame_host()->GetSiteInstance();
    EXPECT_TRUE(DetermineOriginAgentClusterIsolation(site_instance,
                                                     isolated_suborigin_url)
                    .requires_origin_keyed_process());

    EXPECT_THAT(
        histograms.GetAllSamples("Navigation.OriginAgentCluster.Result"),
        testing::ElementsAre(base::Bucket(
            static_cast<int>(NavigationRequest::OriginAgentClusterEndResult::
                                 kExplicitlyRequestedAndOriginKeyed),
            1)));
  }
  {
    // Even though this request has no OriginAgentCluster header, it should get
    // OAC by default.
    SetHeaderValue("");
    base::HistogramTester histograms;
    GURL default_isolated_url(
        https_server()->GetURL("isolated.bar.com", "/title1.html"));
    EXPECT_TRUE(
        NavigateToURLFromRenderer(child_frame_node, default_isolated_url));

    auto* site_instance =
        child_frame_node->current_frame_host()->GetSiteInstance();
    OriginAgentClusterIsolationState isolation_state =
        DetermineOriginAgentClusterIsolation(site_instance,
                                             default_isolated_url);
    // TODO(wjmaclean): If OriginAgentCluster-by-default transitions to using
    // process-isolation at some future date, the second expectation below will
    // need to change to EXPECT_TRUE.
    EXPECT_TRUE(isolation_state.is_origin_agent_cluster());
    EXPECT_FALSE(isolation_state.requires_origin_keyed_process());

    EXPECT_THAT(
        histograms.GetAllSamples("Navigation.OriginAgentCluster.Result"),
        testing::ElementsAre(base::Bucket(
            static_cast<int>(NavigationRequest::OriginAgentClusterEndResult::
                                 kNotExplicitlyRequestedAndOriginKeyed),
            1)));
    // Ensure that the implicit case did not do a global walk (which would be
    // inefficient), by noticing that a hypothetical request for non-isolation
    // of that origin in the same SiteInstance would succeed. That can only
    // happen if the implicit case was not recorded in the BrowsingInstance.
    OriginAgentClusterIsolationState hypothetical_isolation_request =
        OriginAgentClusterIsolationState::CreateNonIsolated();
    OriginAgentClusterIsolationState hypothetical_isolation_state =
        ChildProcessSecurityPolicyImpl::GetInstance()
            ->DetermineOriginAgentClusterIsolation(
                site_instance->GetIsolationContext(),
                url::Origin::Create(default_isolated_url),
                hypothetical_isolation_request);
    EXPECT_FALSE(hypothetical_isolation_state.is_origin_agent_cluster());
  }
  {
    // The "isolate_origin" path in the url will force the test framework to
    // include the OriginAgentCluster header. Here we explicitly request not to
    // have OAC.
    SetHeaderValue("?0");
    base::HistogramTester histograms;
    GURL explicit_non_isolated_url(
        https_server()->GetURL("bar.com", "/isolate_origin"));
    EXPECT_TRUE(
        NavigateToURLFromRenderer(child_frame_node, explicit_non_isolated_url));
    auto* site_instance =
        child_frame_node->current_frame_host()->GetSiteInstance();

    EXPECT_FALSE(DetermineOriginAgentClusterIsolation(site_instance,
                                                      explicit_non_isolated_url)
                     .is_origin_agent_cluster());

    EXPECT_THAT(
        histograms.GetAllSamples("Navigation.OriginAgentCluster.Result"),
        testing::ElementsAre(base::Bucket(
            static_cast<int>(NavigationRequest::OriginAgentClusterEndResult::
                                 kExplicitlyNotRequestedAndNotOriginKeyed),
            1)));
  }

  // The next three cases should all fail to get the isolation status they
  // request (the "But" cases). In these cases, URLs from origins we have
  // already visited in the BrowsingInstance return different OAC header values,
  // but are forced to stick with their earlier value rather than the newly
  // requested value.
  {
    // Even though the lack of a header would normally lead to default OAC
    // isolation, the previous explicitly non-isolated visit to this origin
    // means that this origin will remain not origin keyed.
    SetHeaderValue("");
    base::HistogramTester histograms;
    GURL url(https_server()->GetURL("bar.com", "/title1.html"));
    EXPECT_TRUE(NavigateToURLFromRenderer(child_frame_node, url));
    auto* site_instance =
        child_frame_node->current_frame_host()->GetSiteInstance();

    EXPECT_FALSE(DetermineOriginAgentClusterIsolation(site_instance, url)
                     .is_origin_agent_cluster());

    EXPECT_THAT(
        histograms.GetAllSamples("Navigation.OriginAgentCluster.Result"),
        testing::ElementsAre(base::Bucket(
            static_cast<int>(NavigationRequest::OriginAgentClusterEndResult::
                                 kNotExplicitlyRequestedButNotOriginKeyed),
            1)));
  }

  {
    // An explicit opt-out for isolated.bar.com should not be granted given the
    // previous default-opt-in above.
    SetHeaderValue("?0");
    base::HistogramTester histograms;
    GURL explicit_non_isolated_url(
        https_server()->GetURL("isolated.bar.com", "/isolate_origin"));
    EXPECT_TRUE(
        NavigateToURLFromRenderer(child_frame_node, explicit_non_isolated_url));
    auto* site_instance =
        child_frame_node->current_frame_host()->GetSiteInstance();

    OriginAgentClusterIsolationState isolation_state =
        DetermineOriginAgentClusterIsolation(site_instance,
                                             explicit_non_isolated_url);
    EXPECT_TRUE(isolation_state.is_origin_agent_cluster());
    EXPECT_FALSE(isolation_state.requires_origin_keyed_process());

    EXPECT_THAT(
        histograms.GetAllSamples("Navigation.OriginAgentCluster.Result"),
        testing::ElementsAre(base::Bucket(
            static_cast<int>(NavigationRequest::OriginAgentClusterEndResult::
                                 kExplicitlyNotRequestedButOriginKeyed),
            1)));
  }
  {
    // Verify that we don't explicitly opt-in an origin that was explicitly
    // opted-out.
    SetHeaderValue("?1");
    base::HistogramTester histograms;
    GURL explicit_isolated_url(
        https_server()->GetURL("bar.com", "/isolate_origin"));
    EXPECT_TRUE(
        NavigateToURLFromRenderer(child_frame_node, explicit_isolated_url));
    auto* site_instance =
        child_frame_node->current_frame_host()->GetSiteInstance();

    EXPECT_FALSE(DetermineOriginAgentClusterIsolation(site_instance,
                                                      explicit_isolated_url)
                     .is_origin_agent_cluster());

    EXPECT_THAT(
        histograms.GetAllSamples("Navigation.OriginAgentCluster.Result"),
        testing::ElementsAre(base::Bucket(
            static_cast<int>(NavigationRequest::OriginAgentClusterEndResult::
                                 kExplicitlyRequestedButNotOriginKeyed),
            1)));
  }
}

// These tests ensure that non-HTTPS secure contexts (see
// https://w3c.github.io/webappsec-secure-contexts/#is-origin-trustworthy) are
// able to use origin isolation.
IN_PROC_BROWSER_TEST_F(OriginIsolationOptInHttpServerHeaderTest, Localhost) {
  GURL url(embedded_test_server()->GetURL("localhost", "/"));
  url::Origin origin(url::Origin::Create(url));

  EXPECT_FALSE(ShouldOriginGetOptInProcessIsolation(origin));
  EXPECT_TRUE(NavigateToURL(shell(), url));
  EXPECT_TRUE(ShouldOriginGetOptInProcessIsolation(origin));
}

IN_PROC_BROWSER_TEST_F(OriginIsolationOptInHttpServerHeaderTest, DotLocalhost) {
  GURL url(embedded_test_server()->GetURL("test.localhost", "/"));
  url::Origin origin(url::Origin::Create(url));

  EXPECT_FALSE(ShouldOriginGetOptInProcessIsolation(origin));
  EXPECT_TRUE(NavigateToURL(shell(), url));
  EXPECT_TRUE(ShouldOriginGetOptInProcessIsolation(origin));
}

IN_PROC_BROWSER_TEST_F(OriginIsolationOptInHttpServerHeaderTest,
                       OneTwentySeven) {
  GURL url(embedded_test_server()->GetURL("127.0.0.1", "/"));
  url::Origin origin(url::Origin::Create(url));

  EXPECT_FALSE(ShouldOriginGetOptInProcessIsolation(origin));
  EXPECT_TRUE(NavigateToURL(shell(), url));
  EXPECT_TRUE(ShouldOriginGetOptInProcessIsolation(origin));
}

// Two tests for basic OAC operation w.r.t. prerendering FrameTrees.

// Basic test to make sure an origin opting-in in a primary FrameTree
// triggers registration of a non-opting-origin in an existing prerendering
// Frametree.
IN_PROC_BROWSER_TEST_F(OriginIsolationPrerenderOptInHeaderTest,
                       SimplePrerenderSubOriginIsolationTest) {
  GURL test_url(https_server()->GetURL("foo.com",
                                       "/cross_site_iframe_factory.html?"
                                       "foo.com(foo.com)"));
  // Navigate primary tab to a non-isolated origin.
  EXPECT_TRUE(NavigateToURL(shell(), test_url));
  EXPECT_EQ(2u, CollectAllRenderFrameHosts(shell()->web_contents()).size());
  FrameTreeNode* root = web_contents()->GetPrimaryFrameTree().root();
  FrameTreeNode* child_frame_node = root->child_at(0);

  // Create prerender tab, load non-isolated "a.foo.com".
  Shell* prerender_tab = CreateBrowser();
  EXPECT_TRUE(NavigateToURL(prerender_tab, GURL(https_server()->GetURL(
                                               "a.foo.com", "/title1.html"))));
  auto* prerender_web_contents =
      static_cast<WebContentsImpl*>(prerender_tab->web_contents());
  set_prerender_web_contents(prerender_web_contents);
  GURL non_isolated_origin_url(
      https_server()->GetURL("a.foo.com", "/title2.html"));

  FrameTreeNodeId host_id =
      prerender_helper_.AddPrerender(non_isolated_origin_url);

  // In primary tab, navigate to an isolated origin.
  SetHeaderValue("?1");
  GURL isolated_suborigin_url(
      https_server()->GetURL("a.foo.com", "/isolate_origin"));
  EXPECT_TRUE(
      NavigateToURLFromRenderer(child_frame_node, isolated_suborigin_url));
  EXPECT_NE(root->current_frame_host()->GetSiteInstance(),
            child_frame_node->current_frame_host()->GetSiteInstance());
  EXPECT_TRUE(child_frame_node->current_frame_host()
                  ->GetSiteInstance()
                  ->RequiresDedicatedProcess());
  EXPECT_TRUE(child_frame_node->current_frame_host()
                  ->GetSiteInstance()
                  ->GetSiteInfo()
                  .requires_origin_keyed_process());

  // Verify in prerender tab that "a.foo.com" is registered as a non-isolated
  // origin. We must get the SiteInstance() to test from the
  // PrerenderedMainFrameHost() to make sure the opt-out registration has
  // propagated to the right place.
  auto* policy = ChildProcessSecurityPolicyImpl::GetInstance();
  auto* prerender_site_instance_impl = static_cast<SiteInstanceImpl*>(
      prerender_helper_.GetPrerenderedMainFrameHost(host_id)
          ->GetSiteInstance());
  EXPECT_FALSE(policy
                   ->DetermineOriginAgentClusterIsolation(
                       prerender_site_instance_impl->GetIsolationContext(),
                       url::Origin::Create(non_isolated_origin_url),
                       MakeOACIsolationState(true))
                   .requires_origin_keyed_process());

  // Activate the prerendered page and confirm the non-isolated origin remains
  // non-isolated.
  prerender_helper_.NavigatePrimaryPage(non_isolated_origin_url);
  auto* new_prerender_site_instance_impl = static_cast<SiteInstanceImpl*>(
      prerender_tab->web_contents()->GetSiteInstance());
  EXPECT_EQ(prerender_site_instance_impl, new_prerender_site_instance_impl);
  EXPECT_FALSE(policy
                   ->DetermineOriginAgentClusterIsolation(
                       new_prerender_site_instance_impl->GetIsolationContext(),
                       url::Origin::Create(non_isolated_origin_url),
                       MakeOACIsolationState(true))
                   .requires_origin_keyed_process());
  EXPECT_FALSE(new_prerender_site_instance_impl->GetSiteInfo()
                   .requires_origin_keyed_process());
  EXPECT_TRUE(new_prerender_site_instance_impl->GetSiteURL() ==
                  GURL("https://foo.com") ||
              new_prerender_site_instance_impl->IsDefaultSiteInstance());
}

// Basic test to make sure an origin opting-in in a prerendering FrameTree
// triggers registration of a non-opting-origin in an existing primary
// Frametree.
IN_PROC_BROWSER_TEST_F(OriginIsolationPrerenderOptInHeaderTest,
                       SimplePrerenderSubOriginIsolationTest2) {
  GURL test_url(https_server()->GetURL("foo.com",
                                       "/cross_site_iframe_factory.html?"
                                       "foo.com(foo.com)"));
  EXPECT_TRUE(NavigateToURL(shell(), test_url));
  EXPECT_EQ(2u, CollectAllRenderFrameHosts(shell()->web_contents()).size());
  FrameTreeNode* root = web_contents()->GetPrimaryFrameTree().root();
  FrameTreeNode* child_frame_node = root->child_at(0);
  // Navigate child frame to a non-isolated origin "a.foo.com".
  GURL non_isolated_suborigin_url(
      https_server()->GetURL("a.foo.com", "/title1.html"));
  EXPECT_TRUE(
      NavigateToURLFromRenderer(child_frame_node, non_isolated_suborigin_url));
  EXPECT_EQ(root->current_frame_host()->GetSiteInstance(),
            child_frame_node->current_frame_host()->GetSiteInstance());

  // Create prerender tab, load isolated "a.foo.com".
  Shell* prerender_tab = CreateBrowser();
  EXPECT_TRUE(NavigateToURL(prerender_tab, GURL(https_server()->GetURL(
                                               "a.foo.com", "/title1.html"))));
  auto* prerender_web_contents =
      static_cast<WebContentsImpl*>(prerender_tab->web_contents());
  set_prerender_web_contents(prerender_web_contents);
  SetHeaderValue("?1");
  GURL isolated_origin_url(
      https_server()->GetURL("a.foo.com", "/isolate_origin"));

  FrameTreeNodeId host_id = prerender_helper_.AddPrerender(isolated_origin_url);

  // Verify origin is isolated in the prerender IsolationContext.
  auto* policy = ChildProcessSecurityPolicyImpl::GetInstance();
  auto* prerender_site_instance_impl = static_cast<SiteInstanceImpl*>(
      prerender_helper_.GetPrerenderedMainFrameHost(host_id)
          ->GetSiteInstance());
  EXPECT_TRUE(policy
                  ->DetermineOriginAgentClusterIsolation(
                      prerender_site_instance_impl->GetIsolationContext(),
                      url::Origin::Create(isolated_origin_url),
                      MakeOACIsolationState(false))
                  .requires_origin_keyed_process());
  EXPECT_TRUE(prerender_site_instance_impl->RequiresDedicatedProcess());
  EXPECT_TRUE(prerender_site_instance_impl->GetSiteInfo()
                  .requires_origin_keyed_process());

  // Verify in original tab that "a.foo.com" is now registered as a non-isolated
  // origin.
  auto* primary_site_instance_impl = static_cast<SiteInstanceImpl*>(
      shell()->web_contents()->GetSiteInstance());
  EXPECT_FALSE(policy
                   ->DetermineOriginAgentClusterIsolation(
                       primary_site_instance_impl->GetIsolationContext(),
                       url::Origin::Create(isolated_origin_url),
                       MakeOACIsolationState(true))
                   .requires_origin_keyed_process());

  // Activate the prerendered page and confirm the isolated origin remains
  // isolated.
  prerender_helper_.NavigatePrimaryPage(isolated_origin_url);
  auto* new_prerender_site_instance_impl = static_cast<SiteInstanceImpl*>(
      prerender_tab->web_contents()->GetSiteInstance());
  EXPECT_EQ(prerender_site_instance_impl, new_prerender_site_instance_impl);
  EXPECT_TRUE(policy
                  ->DetermineOriginAgentClusterIsolation(
                      new_prerender_site_instance_impl->GetIsolationContext(),
                      url::Origin::Create(isolated_origin_url),
                      MakeOACIsolationState(false))
                  .requires_origin_keyed_process());
  EXPECT_TRUE(prerender_site_instance_impl->RequiresDedicatedProcess());
  EXPECT_TRUE(new_prerender_site_instance_impl->GetSiteInfo()
                  .requires_origin_keyed_process());
}

// Further tests deep-dive into various scenarios for the isolation opt-ins.

// In this test the sub-origin is isolated because the header requests it. It
// will have a different site instance than the main frame.
IN_PROC_BROWSER_TEST_F(OriginIsolationOptInHeaderTest,
                       SimpleSubOriginIsolationTest) {
  base::HistogramTester histograms;
  SetHeaderValue("?1");
  // Start off with an a(a) page, then navigate the subframe to an isolated sub
  // origin.
  GURL test_url(https_server()->GetURL("foo.com",
                                       "/cross_site_iframe_factory.html?"
                                       "foo.com(foo.com)"));
  GURL isolated_suborigin_url(
      https_server()->GetURL("isolated.foo.com", "/isolate_origin"));
  GURL origin_url = url::Origin::Create(isolated_suborigin_url).GetURL();
  BrowserContext* browser_context = web_contents()->GetBrowserContext();
  auto expected_isolated_suborigin_lock = ProcessLock::FromSiteInfo(SiteInfo(
      /*site_url=*/origin_url,
      /*process_lock_url=*/origin_url,
      /*requires_origin_keyed_process=*/true,
      /*requires_origin_keyed_process_by_default=*/false,
      /*is_sandboxed=*/false, UrlInfo::kInvalidUniqueSandboxId,
      StoragePartitionConfig::CreateDefault(browser_context),
      WebExposedIsolationInfo::CreateNonIsolated(),
      WebExposedIsolationLevel::kNotIsolated, /*is_guest=*/false,
      /*does_site_request_dedicated_process_for_coop=*/false,
      /*is_jit_disabled=*/false, /*are_v8_optimizations_disabled=*/false,
      /*is_pdf=*/false, /*is_fenced=*/false,
      /*cross_origin_isolation_key=*/std::nullopt));
  EXPECT_TRUE(NavigateToURL(shell(), test_url));
  EXPECT_EQ(2u, CollectAllRenderFrameHosts(shell()->web_contents()).size());

  FrameTreeNode* root = web_contents()->GetPrimaryFrameTree().root();
  FrameTreeNode* child_frame_node = root->child_at(0);
  EXPECT_TRUE(
      NavigateToURLFromRenderer(child_frame_node, isolated_suborigin_url));
  EXPECT_NE(root->current_frame_host()->GetSiteInstance(),
            child_frame_node->current_frame_host()->GetSiteInstance());
  EXPECT_TRUE(child_frame_node->current_frame_host()
                  ->GetSiteInstance()
                  ->RequiresDedicatedProcess());
  GURL expected_isolated_sub_origin =
      url::Origin::Create(isolated_suborigin_url).GetURL();
  EXPECT_EQ(
      expected_isolated_sub_origin,
      child_frame_node->current_frame_host()->GetSiteInstance()->GetSiteURL());
  EXPECT_EQ(expected_isolated_suborigin_lock,
            ProcessLock::FromSiteInfo(child_frame_node->current_frame_host()
                                          ->GetSiteInstance()
                                          ->GetSiteInfo()));
  EXPECT_EQ(
      ProcessLock::FromSiteInfo(child_frame_node->current_frame_host()
                                    ->GetSiteInstance()
                                    ->GetSiteInfo()),
      child_frame_node->current_frame_host()->GetProcess()->GetProcessLock());

  EXPECT_THAT(
      histograms.GetAllSamples("Navigation.OriginAgentCluster.Result"),
      testing::ElementsAre(
          base::Bucket(
              static_cast<int>(NavigationRequest::OriginAgentClusterEndResult::
                                   kNotRequestedAndNotOriginKeyed),
              2),
          base::Bucket(
              static_cast<int>(NavigationRequest::OriginAgentClusterEndResult::
                                   kRequestedAndOriginKeyed),
              1)));
}

// Check that two same-site Origin-Agent-Cluster subframes in unrelated windows
// obey the subframe process reuse policy.
IN_PROC_BROWSER_TEST_F(OriginIsolationOptInHeaderTest,
                       OriginAgentClusterProcessReuse) {
  SetHeaderValue("?1");
  // Start off with an a(a) page, then navigate the subframe to an isolated
  // suborigin.
  GURL test_url(https_server()->GetURL("foo.com",
                                       "/cross_site_iframe_factory.html?"
                                       "foo.com(foo.com)"));
  GURL isolated_suborigin_url(
      https_server()->GetURL("isolated.foo.com", "/isolate_origin"));
  EXPECT_TRUE(NavigateToURL(shell(), test_url));

  FrameTreeNode* root = web_contents()->GetPrimaryFrameTree().root();
  FrameTreeNode* child = root->child_at(0);
  EXPECT_TRUE(NavigateToURLFromRenderer(child, isolated_suborigin_url));
  EXPECT_NE(root->current_frame_host()->GetSiteInstance(),
            child->current_frame_host()->GetSiteInstance());
  EXPECT_TRUE(child->current_frame_host()
                  ->GetSiteInstance()
                  ->GetSiteInfo()
                  .requires_origin_keyed_process());

  // Open an unrelated window and set up the same frame hierarchy there.
  Shell* new_shell = CreateBrowser();
  EXPECT_TRUE(NavigateToURL(new_shell, test_url));
  FrameTreeNode* new_root =
      static_cast<WebContentsImpl*>(new_shell->web_contents())
          ->GetPrimaryFrameTree()
          .root();
  FrameTreeNode* new_child = new_root->child_at(0);
  EXPECT_TRUE(NavigateToURLFromRenderer(new_child, isolated_suborigin_url));
  EXPECT_NE(new_root->current_frame_host()->GetSiteInstance(),
            new_child->current_frame_host()->GetSiteInstance());

  // Even though the two subframes should be in different BrowsingInstances,
  // they should share the same process due to the subframe process reuse
  // policy.
  EXPECT_FALSE(
      child->current_frame_host()->GetSiteInstance()->IsRelatedSiteInstance(
          new_child->current_frame_host()->GetSiteInstance()));
  EXPECT_EQ(child->current_frame_host()->GetProcess(),
            new_child->current_frame_host()->GetProcess());
}

// In this test the sub-origin is isolated because the header requests it. It
// will have the same site instance as the main frame, and it will be in the
// same process.
IN_PROC_BROWSER_TEST_F(SameProcessOriginIsolationOptInHeaderTest,
                       SimpleSubOriginIsolationTest) {
  base::HistogramTester histograms;
  SetHeaderValue("?1");
  // Start off with an a(a) page, then navigate the subframe to an isolated sub
  // origin.
  GURL test_url(https_server()->GetURL("foo.com",
                                       "/cross_site_iframe_factory.html?"
                                       "foo.com(foo.com)"));
  GURL isolated_suborigin_url(
      https_server()->GetURL("isolated.foo.com", "/isolate_origin"));
  GURL origin_url = url::Origin::Create(isolated_suborigin_url).GetURL();
  EXPECT_FALSE(
      SiteIsolationPolicy::IsProcessIsolationForOriginAgentClusterEnabled());
  EXPECT_TRUE(NavigateToURL(shell(), test_url));
  EXPECT_EQ(2u, CollectAllRenderFrameHosts(shell()->web_contents()).size());

  FrameTreeNode* root = web_contents()->GetPrimaryFrameTree().root();
  FrameTreeNode* child_frame_node = root->child_at(0);
  EXPECT_TRUE(
      NavigateToURLFromRenderer(child_frame_node, isolated_suborigin_url));
  EXPECT_EQ(root->current_frame_host()->GetSiteInstance(),
            child_frame_node->current_frame_host()->GetSiteInstance());
  EXPECT_FALSE(child_frame_node->current_frame_host()
                   ->GetSiteInstance()
                   ->RequiresDedicatedProcess());
  auto* policy = ChildProcessSecurityPolicyImpl::GetInstance();
  EXPECT_TRUE(policy
                  ->DetermineOriginAgentClusterIsolation(
                      root->current_frame_host()
                          ->GetSiteInstance()
                          ->GetIsolationContext(),
                      url::Origin::Create(isolated_suborigin_url),
                      MakeOACIsolationState(false))
                  .is_origin_agent_cluster());
  EXPECT_FALSE(policy
                   ->DetermineOriginAgentClusterIsolation(
                       root->current_frame_host()
                           ->GetSiteInstance()
                           ->GetIsolationContext(),
                       url::Origin::Create(isolated_suborigin_url),
                       MakeOACIsolationState(false))
                   .requires_origin_keyed_process());
  EXPECT_TRUE(policy->HasOriginEverRequestedOriginAgentClusterValue(
      web_contents()->GetBrowserContext(),
      url::Origin::Create(isolated_suborigin_url)));

  EXPECT_THAT(
      histograms.GetAllSamples("Navigation.OriginAgentCluster.Result"),
      testing::ElementsAre(
          base::Bucket(
              static_cast<int>(NavigationRequest::OriginAgentClusterEndResult::
                                   kNotRequestedAndNotOriginKeyed),
              2),
          base::Bucket(
              static_cast<int>(NavigationRequest::OriginAgentClusterEndResult::
                                   kRequestedAndOriginKeyed),
              1)));
}

// This test is *nearly* the same as SameProcessOriginIsolationOptInHeaderTest.
// SimpleSubOriginIsolationTest, but here we have command-line isolated foo.com
// so it will be in a site instance with a non-empty ProcessLock. But the
// same-process OAC isolated.foo.com will still be in the same SiteInstance,
// and checks on the expected ProcessLock for isolated.foo.com should pass,
// i.e. it should be the same as for the foo.com process.
IN_PROC_BROWSER_TEST_F(
    SameProcessOriginIsolationOptInHeaderWithIsolatedOriginTest,
    SimpleSubOriginIsolationTest) {
  base::HistogramTester histograms;
  SetHeaderValue("?1");
  // Start off with a foo(foo) page, then navigate the subframe to an isolated
  // sub origin. foo.com is isolated from the command line.
  GURL test_url(https_server()->GetURL("foo.com",
                                       "/cross_site_iframe_factory.html?"
                                       "foo.com(foo.com)"));
  GURL isolated_suborigin_url(
      https_server()->GetURL("isolated.foo.com", "/isolate_origin"));
  GURL origin_url = url::Origin::Create(isolated_suborigin_url).GetURL();
  EXPECT_FALSE(
      SiteIsolationPolicy::IsProcessIsolationForOriginAgentClusterEnabled());
  EXPECT_TRUE(NavigateToURL(shell(), test_url));
  EXPECT_EQ(2u, CollectAllRenderFrameHosts(shell()->web_contents()).size());

  FrameTreeNode* root = web_contents()->GetPrimaryFrameTree().root();
  FrameTreeNode* child_frame_node = root->child_at(0);
  EXPECT_TRUE(
      NavigateToURLFromRenderer(child_frame_node, isolated_suborigin_url));
  EXPECT_EQ(root->current_frame_host()->GetSiteInstance(),
            child_frame_node->current_frame_host()->GetSiteInstance());
  EXPECT_TRUE(root->current_frame_host()
                  ->GetSiteInstance()
                  ->RequiresDedicatedProcess());
  EXPECT_TRUE(child_frame_node->current_frame_host()
                  ->GetSiteInstance()
                  ->RequiresDedicatedProcess());
  ProcessLock root_process_lock = ProcessLock::FromSiteInfo(
      root->current_frame_host()->GetSiteInstance()->GetSiteInfo());
  EXPECT_TRUE(root_process_lock.is_locked_to_site());
  EXPECT_EQ(root_process_lock.lock_url(), GURL("https://foo.com/"));
  auto* policy = ChildProcessSecurityPolicyImpl::GetInstance();
  EXPECT_TRUE(policy
                  ->DetermineOriginAgentClusterIsolation(
                      root->current_frame_host()
                          ->GetSiteInstance()
                          ->GetIsolationContext(),
                      url::Origin::Create(isolated_suborigin_url),
                      MakeOACIsolationState(false))
                  .is_origin_agent_cluster());
  EXPECT_FALSE(policy
                   ->DetermineOriginAgentClusterIsolation(
                       root->current_frame_host()
                           ->GetSiteInstance()
                           ->GetIsolationContext(),
                       url::Origin::Create(isolated_suborigin_url),
                       MakeOACIsolationState(false))
                   .requires_origin_keyed_process());
  EXPECT_TRUE(policy->HasOriginEverRequestedOriginAgentClusterValue(
      web_contents()->GetBrowserContext(),
      url::Origin::Create(isolated_suborigin_url)));

  EXPECT_THAT(
      histograms.GetAllSamples("Navigation.OriginAgentCluster.Result"),
      testing::ElementsAre(
          base::Bucket(
              static_cast<int>(NavigationRequest::OriginAgentClusterEndResult::
                                   kNotRequestedAndNotOriginKeyed),
              2),
          base::Bucket(
              static_cast<int>(NavigationRequest::OriginAgentClusterEndResult::
                                   kRequestedAndOriginKeyed),
              1)));
}

// Verify OAC is calculated using the base URL when using LoadDataWithBaseURL()
// (analogous to Android WebView's loadDataWithBaseURL()) when the actual site
// does not specify an Origin-Agent-Cluster value.
IN_PROC_BROWSER_TEST_F(SameProcessOriginIsolationOptInHeaderTest,
                       LoadDataWithBaseURLNoOAC) {
  const GURL test_url = https_server()->GetURL("foo.com", "/title1.html");

  TestNavigationObserver navigation_observer(shell()->web_contents(), 1);
  shell()->LoadDataWithBaseURL(
      test_url, "<!DOCTYPE html><html><body></body></html>", test_url);
  navigation_observer.Wait();

  // Even though this internally navigates to a data: URL (which would imply
  // `window.originAgentCluster === true`, the base URL should be used for the
  // OAC calculation.
  EXPECT_EQ(false, EvalJs(shell(), "window.originAgentCluster"));
  EXPECT_TRUE(ExecJs(
      shell(), "document.body.appendChild(document.createElement('iframe'))"));

  EXPECT_TRUE(NavigateToURLFromRenderer(
      ChildFrameAt(web_contents()->GetPrimaryMainFrame(), 0), test_url));
  EXPECT_EQ(false,
            EvalJs(ChildFrameAt(web_contents()->GetPrimaryMainFrame(), 0),
                   "window.originAgentCluster"));

  // If OAC is incorrectly calculated for `LoadDataWithBaseURL()`, this will
  // fail the access checks in Blink because the two browsing contexts will be
  // treated as cross-origin.
  EXPECT_EQ("This page has no title.\n\n",
            EvalJs(shell(), "window[0].document.body.textContent"));
}

// Verify OAC is calculated using the base URL when using LoadDataWithBaseURL()
// (analogous to Android WebView's loadDataWithBaseURL()). Unlike the previous
// test, the actual site specifies an Origin-Agent-Cluster value, which should
// be ignored.
IN_PROC_BROWSER_TEST_F(SameProcessOriginIsolationOptInHeaderTest,
                       LoadDataWithBaseURLWithOAC) {
  const GURL test_url = https_server()->GetURL("foo.com", "/isolate_origin");
  SetHeaderValue("?1");

  // `tab2` and `shell()` will be in separate browsing instances. As an
  // optimization, browsing instances only track OAC consistency if an origin
  // has ever sent OAC headers. Once an origin has sent OAC headers, this is
  // tracked globally.
  //
  // This navigation marks "foo.com" as having sent OAC headers. This is
  // important to validate that `LoadDataWithBaseURL()` uses the origin
  // calculated from the base URL to update the non-isolated origin list in
  // `shell()`'s browsing instance. If this is not done correctly, then loading
  // "foo.com/isolate_origin" in the subframe will incorrectly use OAC in the
  // subframe, which will be inconsistent with the main frame loaded via
  // `LoadDataWithBaseURL()`.
  Shell* tab2 = CreateBrowser();
  EXPECT_TRUE(NavigateToURL(tab2, test_url));

  TestNavigationObserver navigation_observer(shell()->web_contents(), 1);
  shell()->LoadDataWithBaseURL(
      test_url, "<!DOCTYPE html><html><body></body></html>", test_url);
  navigation_observer.Wait();

  // Even though this internally navigates to a data: URL (which would imply
  // `window.originAgentCluster === true`, the base URL should be used for the
  // OAC calculation.
  EXPECT_EQ(false, EvalJs(shell(), "window.originAgentCluster"));
  EXPECT_TRUE(ExecJs(
      shell(), "document.body.appendChild(document.createElement('iframe'))"));

  // Even though this navigation sets the OAC header value, it should be
  // ignored, since the SiteInstance for foo.com is already site-keyed.
  EXPECT_TRUE(NavigateToURLFromRenderer(
      ChildFrameAt(web_contents()->GetPrimaryMainFrame(), 0), test_url));
  EXPECT_EQ(false,
            EvalJs(ChildFrameAt(web_contents()->GetPrimaryMainFrame(), 0),
                   "window.originAgentCluster"));

  // The two frames should be same-origin to each other, since the OAC header
  // value should be ignored.
  EXPECT_EQ("isolate me!",
            EvalJs(shell(), "window[0].document.body.textContent"));
}

// This test checks that same-process OriginAgentCluster won't crash and will
// apply properly when used on a localhost URL.  See https://crbug.com/1276155.
IN_PROC_BROWSER_TEST_F(SameProcessOriginIsolationOptInHeaderTest, Localhost) {
  SetHeaderValue("?1");
  GURL url(https_server()->GetURL("localhost", "/isolate_origin"));
  url::Origin origin(url::Origin::Create(url));

  EXPECT_TRUE(SiteIsolationPolicy::IsOriginAgentClusterEnabled());
  EXPECT_FALSE(
      SiteIsolationPolicy::IsProcessIsolationForOriginAgentClusterEnabled());
  EXPECT_FALSE(ShouldOriginGetOptInProcessIsolation(origin));

  EXPECT_TRUE(NavigateToURL(shell(), url));
  FrameTreeNode* root = web_contents()->GetPrimaryFrameTree().root();
  EXPECT_FALSE(root->current_frame_host()
                   ->GetSiteInstance()
                   ->RequiresDedicatedProcess());
  EXPECT_FALSE(ShouldOriginGetOptInProcessIsolation(origin));
  auto* policy = ChildProcessSecurityPolicyImpl::GetInstance();
  auto isolation_result = policy->DetermineOriginAgentClusterIsolation(
      root->current_frame_host()->GetSiteInstance()->GetIsolationContext(),
      origin, MakeOACIsolationState(false));
  EXPECT_TRUE(isolation_result.is_origin_agent_cluster());
  EXPECT_FALSE(isolation_result.requires_origin_keyed_process());
  EXPECT_TRUE(policy->HasOriginEverRequestedOriginAgentClusterValue(
      web_contents()->GetBrowserContext(), origin));
}

// This test verifies that --disable-web-security overrides same-process
// OriginAgentCluster (i.e. disables it).
IN_PROC_BROWSER_TEST_F(SameProcessNoWebSecurityOriginIsolationOptInHeaderTest,
                       DisableWebSecurityDisablesOriginAgentCluster) {
  // Make sure we request the header for OriginAgentCluster for the child; the
  // fact that this test uses --disable-web-security will override the header.
  SetHeaderValue("?1");
  GURL main_url(https_server()->GetURL("foo.com",
                                       "/cross_site_iframe_factory.html?"
                                       "foo.com(foo.com)"));
  GURL isolated_suborigin_url(
      https_server()->GetURL("isolated.foo.com", "/isolate_origin"));
  EXPECT_TRUE(NavigateToURL(shell(), main_url));
  EXPECT_EQ(2u, CollectAllRenderFrameHosts(shell()->web_contents()).size());

  FrameTreeNode* root = web_contents()->GetPrimaryFrameTree().root();
  FrameTreeNode* child_frame_node = root->child_at(0);
  EXPECT_TRUE(
      NavigateToURLFromRenderer(child_frame_node, isolated_suborigin_url));

  // Web security is disabled so everything should be same-origin and
  // accessible across browsing contexts.
  EXPECT_EQ(false, EvalJs(child_frame_node, "window.originAgentCluster"));

  std::string parent_body_content =
      EvalJs(root, "document.body.textContent").ExtractString();
  // Make sure that the child frame doesn't think it's isolated.
  EXPECT_EQ(parent_body_content,
            EvalJs(child_frame_node, "window.parent.document.body.textContent")
                .ExtractString());
}

// In this test the sub-origin isn't isolated because no header is set. It will
// have the same site instance as the main frame.
IN_PROC_BROWSER_TEST_F(OriginIsolationOptInHeaderTest,
                       SimpleSubOriginNonIsolationTest) {
  base::HistogramTester histograms;
  // Start off with an a(a) page, then navigate the subframe to an isolated sub
  // origin.
  GURL test_url(https_server()->GetURL("foo.com",
                                       "/cross_site_iframe_factory.html?"
                                       "foo.com(foo.com)"));
  GURL isolated_suborigin_url(
      https_server()->GetURL("isolated.foo.com", "/isolate_origin"));
  EXPECT_TRUE(NavigateToURL(shell(), test_url));
  EXPECT_EQ(2u, CollectAllRenderFrameHosts(shell()->web_contents()).size());

  FrameTreeNode* root = web_contents()->GetPrimaryFrameTree().root();
  FrameTreeNode* child_frame_node = root->child_at(0);
  EXPECT_TRUE(
      NavigateToURLFromRenderer(child_frame_node, isolated_suborigin_url));
  EXPECT_EQ(root->current_frame_host()->GetSiteInstance(),
            child_frame_node->current_frame_host()->GetSiteInstance());
  EXPECT_THAT(
      histograms.GetAllSamples("Navigation.OriginAgentCluster.Result"),
      testing::ElementsAre(base::Bucket(
          static_cast<int>(NavigationRequest::OriginAgentClusterEndResult::
                               kNotRequestedAndNotOriginKeyed),
          3)));
}

// This test verifies that renderer-initiated navigations to/from isolated
// sub-origins works as expected.
IN_PROC_BROWSER_TEST_F(OriginIsolationOptInHeaderTest,
                       RendererInitiatedNavigations) {
  SetHeaderValue("?1");
  GURL test_url(https_server()->GetURL("foo.com",
                                       "/cross_site_iframe_factory.html?"
                                       "foo.com(foo.com)"));
  EXPECT_TRUE(NavigateToURL(shell(), test_url));
  EXPECT_EQ(2u, CollectAllRenderFrameHosts(shell()->web_contents()).size());

  FrameTreeNode* root = web_contents()->GetPrimaryFrameTree().root();
  FrameTreeNode* child = root->child_at(0);

  GURL isolated_sub_origin_url(
      https_server()->GetURL("isolated.foo.com", "/isolate_origin"));
  {
    // Navigate the child to an isolated origin.
    TestFrameNavigationObserver observer(child);
    EXPECT_TRUE(ExecJs(
        child, "location.href = '" + isolated_sub_origin_url.spec() + "';"));
    observer.Wait();
  }
  EXPECT_NE(root->current_frame_host()->GetSiteInstance(),
            child->current_frame_host()->GetSiteInstance());

  GURL non_isolated_sub_origin_url(
      https_server()->GetURL("bar.foo.com", "/title1.html"));
  {
    // Navigate the child to a non-isolated origin.
    TestFrameNavigationObserver observer(child);
    EXPECT_TRUE(ExecJs(child, "location.href = '" +
                                  non_isolated_sub_origin_url.spec() + "';"));
    observer.Wait();
  }
  EXPECT_EQ(root->current_frame_host()->GetSiteInstance(),
            child->current_frame_host()->GetSiteInstance());
}

// Check that navigating a main frame from an non-isolated origin to an
// isolated origin and vice versa swaps processes and uses a new SiteInstance,
// both for renderer-initiated and browser-initiated navigations.
// Note: this test is essentially identical to
// IsolatedOriginTest.MainFrameNavigation.
IN_PROC_BROWSER_TEST_F(OriginIsolationOptInHeaderTest, MainFrameNavigation) {
  SetHeaderValue("?1");
  GURL unisolated_url(https_server()->GetURL("www.foo.com", "/title1.html"));
  GURL isolated_url(
      https_server()->GetURL("isolated.foo.com", "/isolate_origin"));

  EXPECT_TRUE(NavigateToURL(shell(), unisolated_url));

  // Open a same-site popup to keep the www.foo.com process alive.
  Shell* popup = OpenPopup(shell(), GURL(url::kAboutBlankURL), "foo");
  SiteInstance* unisolated_instance =
      popup->web_contents()->GetPrimaryMainFrame()->GetSiteInstance();
  RenderProcessHost* unisolated_process =
      popup->web_contents()->GetPrimaryMainFrame()->GetProcess();

  // Go to isolated.foo.com with a renderer-initiated navigation.
  EXPECT_TRUE(NavigateToURLFromRenderer(web_contents(), isolated_url));
  scoped_refptr<SiteInstance> isolated_instance =
      web_contents()->GetSiteInstance();
  RenderProcessHost* isolated_process =
      web_contents()->GetPrimaryMainFrame()->GetProcess();

  EXPECT_NE(unisolated_instance, isolated_instance);
  EXPECT_NE(unisolated_process, isolated_process);

  // The site URL for isolated.foo.com should be the full origin rather than
  // scheme and eTLD+1.
  EXPECT_EQ(https_server()->GetURL("isolated.foo.com", "/"),
            isolated_instance->GetSiteURL());

  // Now use a renderer-initiated navigation to go to an unisolated origin,
  // www.foo.com. This should end up back in the `popup`'s process.
  EXPECT_TRUE(NavigateToURLFromRenderer(web_contents(), unisolated_url));
  EXPECT_EQ(unisolated_instance, web_contents()->GetSiteInstance());
  EXPECT_EQ(unisolated_process,
            web_contents()->GetPrimaryMainFrame()->GetProcess());

  // Now, perform a browser-initiated navigation to an isolated origin and
  // ensure that this ends up in a new process and SiteInstance for
  // isolated.foo.com.
  EXPECT_TRUE(NavigateToURL(shell(), isolated_url));
  scoped_refptr<SiteInstance> isolated_instance2 =
      web_contents()->GetSiteInstance();
  RenderProcessHost* isolated_process2 =
      web_contents()->GetPrimaryMainFrame()->GetProcess();
  EXPECT_NE(unisolated_instance, isolated_instance2);
  EXPECT_NE(isolated_instance, isolated_instance2);
  EXPECT_NE(unisolated_process, isolated_process2);

  // Go back to www.foo.com: this should end up in the unisolated process.
  {
    TestNavigationObserver back_observer(web_contents());
    web_contents()->GetController().GoBack();
    back_observer.Wait();
  }

  EXPECT_EQ(unisolated_instance, web_contents()->GetSiteInstance());
  EXPECT_EQ(unisolated_process,
            web_contents()->GetPrimaryMainFrame()->GetProcess());

  // Go back again.  This should go to isolated.foo.com in an isolated process.
  {
    TestNavigationObserver back_observer(web_contents());
    web_contents()->GetController().GoBack();
    back_observer.Wait();
  }

  EXPECT_EQ(isolated_instance, web_contents()->GetSiteInstance());
  EXPECT_NE(unisolated_process,
            web_contents()->GetPrimaryMainFrame()->GetProcess());

  // Do a renderer-initiated navigation from isolated.foo.com to another
  // isolated origin and ensure there is a different isolated process.
  GURL second_isolated_url(
      https_server()->GetURL("isolated.bar.com", "/isolate_origin"));
  EXPECT_TRUE(NavigateToURLFromRenderer(web_contents(), second_isolated_url));
  EXPECT_EQ(https_server()->GetURL("isolated.bar.com", "/"),
            web_contents()->GetSiteInstance()->GetSiteURL());
  EXPECT_NE(isolated_instance, web_contents()->GetSiteInstance());
  EXPECT_NE(unisolated_instance, web_contents()->GetSiteInstance());
}

// This test ensures that if an origin starts off being isolated in a
// BrowsingInstance, it continues that way within the BrowsingInstance, even
// if a new policy is received that removes the opt-in request.
IN_PROC_BROWSER_TEST_F(OriginIsolationOptInHeaderTest,
                       OriginIsolationStateRetainedForBrowsingInstance) {
  base::HistogramTester histograms;
  SetHeaderValue("?1");
  // Start off with an a(a,a) page, then navigate the subframe to an isolated
  // sub origin.
  GURL test_url(https_server()->GetURL("foo.com",
                                       "/cross_site_iframe_factory.html?"
                                       "foo.com(foo.com, foo.com)"));
  GURL isolated_suborigin_url(
      https_server()->GetURL("isolated.foo.com", "/isolate_origin"));
  EXPECT_TRUE(NavigateToURL(shell(), test_url));
  EXPECT_EQ(3u, CollectAllRenderFrameHosts(shell()->web_contents()).size());

  FrameTreeNode* root = web_contents()->GetPrimaryFrameTree().root();
  FrameTreeNode* child_frame_node0 = root->child_at(0);
  FrameTreeNode* child_frame_node1 = root->child_at(1);

  EXPECT_TRUE(
      NavigateToURLFromRenderer(child_frame_node0, isolated_suborigin_url));
  EXPECT_NE(root->current_frame_host()->GetSiteInstance(),
            child_frame_node0->current_frame_host()->GetSiteInstance());

  // Change the server's responses to stop isolating the sub-origin. It should
  // still be isolated, to remain consistent with the other frame.
  SetHeaderValue("?0");

  WebContentsConsoleObserver console_observer(shell()->web_contents());
  console_observer.SetPattern(
      "The page did not request an origin-keyed agent cluster, but was put in "
      "one anyway*");

  EXPECT_TRUE(
      NavigateToURLFromRenderer(child_frame_node1, isolated_suborigin_url));

  ASSERT_TRUE(console_observer.Wait());

  EXPECT_NE(root->current_frame_host()->GetSiteInstance(),
            child_frame_node1->current_frame_host()->GetSiteInstance());

  // The two sub-frames should be in the same site instance.
  EXPECT_EQ(child_frame_node0->current_frame_host()->GetSiteInstance(),
            child_frame_node1->current_frame_host()->GetSiteInstance());

  // Make sure the master opt-in list still has the origin tracked.
  auto* policy = ChildProcessSecurityPolicyImpl::GetInstance();
  EXPECT_TRUE(policy->HasOriginEverRequestedOriginAgentClusterValue(
      web_contents()->GetBrowserContext(),
      url::Origin::Create(isolated_suborigin_url)));

  EXPECT_THAT(
      histograms.GetAllSamples("Navigation.OriginAgentCluster.Result"),
      testing::ElementsAre(
          // Original loads of a(a,a) go here.
          base::Bucket(
              static_cast<int>(NavigationRequest::OriginAgentClusterEndResult::
                                   kNotRequestedAndNotOriginKeyed),
              3),
          // Second isolated subframe load goes here.
          base::Bucket(
              static_cast<int>(NavigationRequest::OriginAgentClusterEndResult::
                                   kNotRequestedButOriginKeyed),
              1),
          // First isolated subframe load goes here.
          base::Bucket(
              static_cast<int>(NavigationRequest::OriginAgentClusterEndResult::
                                   kRequestedAndOriginKeyed),
              1)));
}

// This test ensures that if an origin starts off not being isolated in a
// BrowsingInstance, it continues that way within the BrowsingInstance, even
// if the header starts being sent.
// Case #1 where the non-opted-in origin is currently in the frame tree.
IN_PROC_BROWSER_TEST_F(OriginIsolationOptInHeaderTest,
                       OriginNonIsolationStateRetainedForBrowsingInstance1) {
  base::HistogramTester histograms;
  SetHeaderValue("?0");
  // Start off with an a(a,a) page, then navigate the subframe to an isolated
  // sub origin.
  GURL test_url(https_server()->GetURL("foo.com",
                                       "/cross_site_iframe_factory.html?"
                                       "foo.com(foo.com, foo.com)"));
  GURL isolated_suborigin_url(
      https_server()->GetURL("isolated.foo.com", "/isolate_origin"));
  EXPECT_TRUE(NavigateToURL(shell(), test_url));
  EXPECT_EQ(3u, CollectAllRenderFrameHosts(shell()->web_contents()).size());

  FrameTreeNode* root = web_contents()->GetPrimaryFrameTree().root();
  FrameTreeNode* child_frame_node0 = root->child_at(0);
  FrameTreeNode* child_frame_node1 = root->child_at(1);

  EXPECT_TRUE(
      NavigateToURLFromRenderer(child_frame_node0, isolated_suborigin_url));
  EXPECT_EQ(root->current_frame_host()->GetSiteInstance(),
            child_frame_node0->current_frame_host()->GetSiteInstance());

  // Change the server responses to start isolating the sub-origin. It should
  // still be not-isolated, to remain consistent with the other frame.
  SetHeaderValue("?1");

  WebContentsConsoleObserver console_observer(shell()->web_contents());
  console_observer.SetPattern(
      "The page requested an origin-keyed agent cluster using the "
      "Origin-Agent-Cluster header, but could not be origin-keyed*");

  EXPECT_TRUE(
      NavigateToURLFromRenderer(child_frame_node1, isolated_suborigin_url));

  ASSERT_TRUE(console_observer.Wait());

  EXPECT_EQ(root->current_frame_host()->GetSiteInstance(),
            child_frame_node1->current_frame_host()->GetSiteInstance());

  // Make sure the master opt-in list has the origin listed.
  auto* policy = ChildProcessSecurityPolicyImpl::GetInstance();
  EXPECT_TRUE(policy->HasOriginEverRequestedOriginAgentClusterValue(
      web_contents()->GetBrowserContext(),
      url::Origin::Create(isolated_suborigin_url)));

  EXPECT_THAT(
      histograms.GetAllSamples("Navigation.OriginAgentCluster.Result"),
      testing::ElementsAre(
          // Original loads of a(a,a) go here.
          base::Bucket(
              static_cast<int>(NavigationRequest::OriginAgentClusterEndResult::
                                   kNotRequestedAndNotOriginKeyed),
              4),
          base::Bucket(
              static_cast<int>(NavigationRequest::OriginAgentClusterEndResult::
                                   kRequestedButNotOriginKeyed),
              1)));
}

// This test ensures that if an origin starts off not being isolated in a
// BrowsingInstance, it continues that way within the BrowsingInstance, even
// if the header starts being sent.
// Case #2 where the non-opted-in origin is currently not in the frame tree.
IN_PROC_BROWSER_TEST_F(OriginIsolationOptInHeaderTest,
                       OriginNonIsolationStateRetainedForBrowsingInstance2) {
  SetHeaderValue("?0");
  // Start off with an a(a) page, then navigate the subframe to an isolated sub
  // origin.
  GURL test_url(https_server()->GetURL("foo.com",
                                       "/cross_site_iframe_factory.html?"
                                       "foo.com(foo.com)"));
  GURL isolated_suborigin_url(
      https_server()->GetURL("isolated.foo.com", "/isolate_origin"));
  EXPECT_TRUE(NavigateToURL(shell(), test_url));
  EXPECT_EQ(2u, CollectAllRenderFrameHosts(shell()->web_contents()).size());

  FrameTreeNode* root = web_contents()->GetPrimaryFrameTree().root();
  FrameTreeNode* child_frame_node0 = root->child_at(0);

  // Even though we're navigating to isolated.foo.com, there's no manifest
  // requesting opt-in, so it should end up in the same SiteInstance as the
  // main frame.
  EXPECT_TRUE(
      NavigateToURLFromRenderer(child_frame_node0, isolated_suborigin_url));
  EXPECT_EQ(root->current_frame_host()->GetSiteInstance(),
            child_frame_node0->current_frame_host()->GetSiteInstance());

  // This navigation removes isolated_suborigin_url from the frame tree, but it
  // should still be in the session history.
  EXPECT_TRUE(NavigateToURLFromRenderer(
      child_frame_node0, https_server()->GetURL("foo.com", "/title1.html")));
  EXPECT_EQ(root->current_frame_host()->GetSiteInstance(),
            child_frame_node0->current_frame_host()->GetSiteInstance());

  // Change the server to start isolating the sub-origin. It should
  // still be not isolated, to remain consistent with the other frame.
  SetHeaderValue("?1");
  EXPECT_TRUE(
      NavigateToURLFromRenderer(child_frame_node0, isolated_suborigin_url));
  EXPECT_EQ(root->current_frame_host()->GetSiteInstance(),
            child_frame_node0->current_frame_host()->GetSiteInstance());

  // Make sure the master opt-in list has the origin listed.
  auto* policy = ChildProcessSecurityPolicyImpl::GetInstance();
  EXPECT_TRUE(policy->HasOriginEverRequestedOriginAgentClusterValue(
      web_contents()->GetBrowserContext(),
      url::Origin::Create(isolated_suborigin_url)));

  // Make sure the current browsing instance does *not* isolate the origin.
  EXPECT_FALSE(policy
                   ->DetermineOriginAgentClusterIsolation(
                       root->current_frame_host()
                           ->GetSiteInstance()
                           ->GetIsolationContext(),
                       url::Origin::Create(isolated_suborigin_url),
                       MakeOACIsolationState(false))
                   .requires_origin_keyed_process());
}

// This test makes sure that a different tab in the same BrowsingInstance where
// an origin originally did not opt-in respects that state even if the
// server sends a different header.
IN_PROC_BROWSER_TEST_F(OriginIsolationOptInHeaderTest,
                       OriginNonIsolationStateRetainedForPopup) {
  SetHeaderValue("?0");
  // Start off with an a(a,a) page, then navigate the subframe to an isolated
  // sub origin.
  GURL test_url(https_server()->GetURL("foo.com",
                                       "/cross_site_iframe_factory.html?"
                                       "foo.com(foo.com)"));
  GURL isolated_suborigin_url(
      https_server()->GetURL("isolated.foo.com", "/isolate_origin"));
  EXPECT_TRUE(NavigateToURL(shell(), test_url));
  EXPECT_EQ(2u, CollectAllRenderFrameHosts(shell()->web_contents()).size());

  FrameTreeNode* root = web_contents()->GetPrimaryFrameTree().root();
  FrameTreeNode* child_frame_node0 = root->child_at(0);

  EXPECT_TRUE(
      NavigateToURLFromRenderer(child_frame_node0, isolated_suborigin_url));
  EXPECT_EQ(root->current_frame_host()->GetSiteInstance(),
            child_frame_node0->current_frame_host()->GetSiteInstance());

  // Change the server to start isolating the sub-origin. It should
  // not be isolated, to remain consistent with the other frame.
  SetHeaderValue("?1");

  // Open a popup in the same browsing instance, and navigate it to the
  // not-opted-in origin. Even though the manifest now requests isolation, it
  // should not opt-in since it's in the same BrowsingInstance where it
  // originally wasn't opted in.
  Shell* popup = OpenPopup(shell(), isolated_suborigin_url, "foo");
  auto* popup_web_contents = popup->web_contents();
  EXPECT_TRUE(
      NavigateToURLFromRenderer(popup_web_contents, isolated_suborigin_url));

  EXPECT_EQ(shell()->web_contents()->GetSiteInstance()->GetBrowsingInstanceId(),
            popup_web_contents->GetSiteInstance()->GetBrowsingInstanceId());

  // Make sure the current browsing instance does *not* isolate the origin.
  auto* policy = ChildProcessSecurityPolicyImpl::GetInstance();
  EXPECT_FALSE(policy
                   ->DetermineOriginAgentClusterIsolation(
                       root->current_frame_host()
                           ->GetSiteInstance()
                           ->GetIsolationContext(),
                       url::Origin::Create(isolated_suborigin_url),
                       MakeOACIsolationState(false))
                   .requires_origin_keyed_process());
}

// This test creates a no-opener popup that is origin-isolated, and has two
// same-sub-origin iframes, one of which requests isolation and one that
// doesn't. The non-isolated child commits first, so the second child shouldn't
// get isolation, but more importantly we shouldn't crash on a NOTREACHED() in
// RenderFrameHostManager that is verifying that the second child frame was
// put in a compatible renderer process.
// https://crbug.com/1099718
IN_PROC_BROWSER_TEST_F(OriginIsolationOptInHeaderTest,
                       NoKillForBrowsingInstanceDifferencesInProcess) {
  SetHeaderValue("?1");
  GURL opener_url(https_server()->GetURL("foo.com", "/title1.html"));
  EXPECT_TRUE(NavigateToURL(shell(), opener_url));

  // Create content for popup. The first subframe is in a sub-domain of the
  // popup mainframe, which is an isolated base-origin. The second subframe is
  // in the same sub-origin as the first, but requests isolation. The isolation
  // request will fail, and both subframes will end up in the same site-locked
  // process as the opener document (due to subframe process reuse).
  GURL popup_subframe1_url(
      https_server()->GetURL("sub.foo.com", "/title1.html"));
  GURL popup_subframe2_url(
      https_server()->GetURL("sub.foo.com", "/isolate_origin"));
  // This is the HTML content for the popup mainframe.
  std::string popup_content = base::StringPrintf(
      R"(<!DOCTYPE html>
         <html><head>
         <meta charset="utf-8">
         <title>This page should not crash when window.open()ed</title>
         </head><body>
         <iframe src="%s"></iframe>
         <iframe></iframe>
         </body></html>)",
      popup_subframe1_url.spec().c_str());
  // The next navigation with relative URL = "/isolate_origin" should serve this
  // content.
  AddContentToQueue(popup_content);

  // Open popup.
  GURL isolated_popup_url(https_server()->GetURL("foo.com", "/isolate_origin"));
  // Opening the popup with "noopener" guarantees that the isolated popup is in
  // a different BrowsingInstance from the opener.
  Shell* popup =
      OpenPopup(shell(), isolated_popup_url, "windowName1", "noopener",
                false /* expect_return_from_window_open */);

  // If we got here without crashing, all that remains is to verify everything
  // is isolated/not-isolated as expected.
  ASSERT_NE(nullptr, popup);
  RenderFrameHostImpl* popup_root =
      static_cast<WebContentsImpl*>(popup->web_contents())
          ->GetPrimaryMainFrame();
  EXPECT_EQ(2U, popup_root->child_count());
  FrameTreeNode* popup_child1 = popup_root->child_at(0);
  FrameTreeNode* popup_child2 = popup_root->child_at(1);

  // Navigate the second child iframe after the first one has loaded.
  EXPECT_TRUE(NavigateFrameToURL(popup_child2, popup_subframe2_url));

  // Set cookie on `popup_child1` to make sure we don't get a renderer kill in
  // the process with the opener.
  EXPECT_TRUE(ExecJs(popup_child1, "document.cookie = 'foo=bar';"));
  EXPECT_EQ("foo=bar", EvalJs(popup_child1, "document.cookie"));

  // Verify state of various SiteIstances, BrowsingInstances and processes.
  SiteInstanceImpl* root_instance = popup_root->GetSiteInstance();
  EXPECT_TRUE(root_instance->GetSiteInfo().requires_origin_keyed_process());
  SiteInstanceImpl* child1_instance =
      popup_child1->current_frame_host()->GetSiteInstance();
  SiteInstanceImpl* child2_instance =
      popup_child2->current_frame_host()->GetSiteInstance();
  EXPECT_EQ(child1_instance, child2_instance);
  EXPECT_NE(child1_instance, root_instance);

  // Make sure child1 and the opener share the same process, but different
  // BrowsingInstances.
  SiteInstanceImpl* opener_instance =
      static_cast<WebContentsImpl*>(shell()->web_contents())->GetSiteInstance();
  EXPECT_NE(child1_instance->GetBrowsingInstanceId(),
            opener_instance->GetBrowsingInstanceId());
  EXPECT_EQ(child1_instance->GetProcess(), opener_instance->GetProcess());
  EXPECT_FALSE(child2_instance->GetSiteInfo().requires_origin_keyed_process());
}

// Same as NoKillForBrowsingInstanceDifferencesInProcess, except the starting
// page has an isolated iframe that matches the origin that won't get isolation
// in the popup's BrowsingInstance. Since this means that the first
// BrowsingInstance will show sub.foo.com as isolated, then if
// CanAccessDataForOrigin only checks the first BrowsingInstance it will get the
// wrong result.
IN_PROC_BROWSER_TEST_F(OriginIsolationOptInHeaderTest,
                       NoKillForBrowsingInstanceDifferencesInProcess2) {
  SetHeaderValue("?1");
  // Start on a page with same-site iframe.
  GURL opener_url(https_server()->GetURL("foo.com", "/page_with_iframe.html"));
  EXPECT_TRUE(NavigateToURL(shell(), opener_url));
  FrameTreeNode* root = web_contents()->GetPrimaryFrameTree().root();
  FrameTreeNode* child = root->child_at(0);
  GURL isolated_opener_iframe_url(
      https_server()->GetURL("sub.foo.com", "/isolate_origin"));
  EXPECT_TRUE(NavigateFrameToURL(child, isolated_opener_iframe_url));
  EXPECT_NE(root->current_frame_host()->GetSiteInstance(),
            child->current_frame_host()->GetSiteInstance());
  EXPECT_TRUE(child->current_frame_host()
                  ->GetSiteInstance()
                  ->GetSiteInfo()
                  .requires_origin_keyed_process());

  // Create content for popup. The first subframe is in a sub-domain of the
  // popup mainframe, which is an isolated base-origin. The second subframe is
  // in the same sub-origin as the first, but requests isolation. The isolation
  // request will fail, and both subframes will end up in the same site-locked
  // process as the opener document (due to subframe process reuse).
  GURL popup_subframe1_url(
      https_server()->GetURL("sub.foo.com", "/title1.html"));
  GURL popup_subframe2_url(
      https_server()->GetURL("sub.foo.com", "/isolate_origin"));
  // This is the HTML content for the popup mainframe.
  std::string popup_content = base::StringPrintf(
      R"(<!DOCTYPE html>
         <html><head>
         <meta charset="utf-8">
         <title>This page should not crash when window.open()ed</title>
         </head><body>
         <iframe src="%s"></iframe>
         <iframe></iframe>
         </body></html>)",
      popup_subframe1_url.spec().c_str());
  // The next navigation with relative URL = "/isolate_origin" should serve this
  // content.
  AddContentToQueue(popup_content);

  // Open popup.
  GURL isolated_popup_url(https_server()->GetURL("foo.com", "/isolate_origin"));
  // Opening the popup with "noopener" guarantees that the isolated popup is in
  // a different BrowsingInstance from the opener.
  Shell* popup =
      OpenPopup(shell(), isolated_popup_url, "windowName1", "noopener",
                false /* expect_return_from_window_open */);

  // If we got here without crashing, all that remains is to verify everything
  // is isolated/not-isolated as expected.
  ASSERT_NE(nullptr, popup);
  RenderFrameHostImpl* popup_root =
      static_cast<WebContentsImpl*>(popup->web_contents())
          ->GetPrimaryMainFrame();
  EXPECT_EQ(2U, popup_root->child_count());
  FrameTreeNode* popup_child1 = popup_root->child_at(0);
  FrameTreeNode* popup_child2 = popup_root->child_at(1);

  // Navigate the second child iframe after the first one has loaded.
  EXPECT_TRUE(NavigateFrameToURL(popup_child2, popup_subframe2_url));

  // Set cookie on `popup_child1` to make sure we don't get a renderer kill in
  // the process with the opener.
  EXPECT_TRUE(ExecJs(popup_child1, "document.cookie = 'foo=bar';"));
  EXPECT_EQ("foo=bar", EvalJs(popup_child1, "document.cookie"));

  // Verify state of various SiteIstances, BrowsingInstances and processes.
  SiteInstanceImpl* root_instance = popup_root->GetSiteInstance();
  EXPECT_TRUE(root_instance->GetSiteInfo().requires_origin_keyed_process());
  SiteInstanceImpl* child1_instance =
      popup_child1->current_frame_host()->GetSiteInstance();
  SiteInstanceImpl* child2_instance =
      popup_child2->current_frame_host()->GetSiteInstance();
  EXPECT_EQ(child1_instance, child2_instance);
  EXPECT_NE(child1_instance, root_instance);

  // Make sure child1 and the opener share the same process, but different
  // BrowsingInstances.
  SiteInstanceImpl* opener_instance =
      static_cast<WebContentsImpl*>(shell()->web_contents())->GetSiteInstance();
  EXPECT_NE(child1_instance->GetBrowsingInstanceId(),
            opener_instance->GetBrowsingInstanceId());
  EXPECT_EQ(child1_instance->GetProcess(), opener_instance->GetProcess());
  EXPECT_FALSE(child2_instance->GetSiteInfo().requires_origin_keyed_process());
}

// This test handles the case where the base origin is isolated, but a
// sub-origin isn't. In this case we need to place the sub-origin in a site-
// keyed SiteInstance with the same site URL as the origin-keyed SiteInstance
// used for the isolated base origin. Note: only the isolated base origin will
// have a port in this test, as the non-isolated sub-origin will have its port
// value stripped. The test IsolatedBaseOriginNoPorts tests the case where
// neither the isolated base origin nor the non-isolated sub-origin has a port
// value.
IN_PROC_BROWSER_TEST_F(OriginIsolationOptInHeaderTest, IsolatedBaseOrigin) {
  base::HistogramTester histograms;
  SetHeaderValue("?1");
  // Start off with an isolated base-origin in an a(a) configuration, then
  // navigate the subframe to a sub-origin no requesting isolation.
  GURL test_url(https_server()->GetURL(
      "foo.com", "/isolated_base_origin_with_subframe.html"));
  GURL non_isolated_sub_origin1(
      https_server()->GetURL("non_isolated1.foo.com", "/title1.html"));
  GURL non_isolated_sub_origin2(
      https_server()->GetURL("non_isolated2.foo.com", "/title1.html"));
  EXPECT_TRUE(NavigateToURL(shell(), test_url));
  EXPECT_EQ(3u, CollectAllRenderFrameHosts(shell()->web_contents()).size());

  FrameTreeNode* root = web_contents()->GetPrimaryFrameTree().root();
  FrameTreeNode* child_frame_node1 = root->child_at(0);
  FrameTreeNode* child_frame_node2 = root->child_at(1);
  EXPECT_TRUE(
      NavigateToURLFromRenderer(child_frame_node1, non_isolated_sub_origin1));
  EXPECT_TRUE(
      NavigateToURLFromRenderer(child_frame_node2, non_isolated_sub_origin2));

  auto* policy = ChildProcessSecurityPolicyImpl::GetInstance();
  EXPECT_TRUE(
      policy
          ->DetermineOriginAgentClusterIsolation(root->current_frame_host()
                                                     ->GetSiteInstance()
                                                     ->GetIsolationContext(),
                                                 url::Origin::Create(test_url),
                                                 MakeOACIsolationState(false))
          .requires_origin_keyed_process());
  EXPECT_FALSE(policy
                   ->DetermineOriginAgentClusterIsolation(
                       child_frame_node1->current_frame_host()
                           ->GetSiteInstance()
                           ->GetIsolationContext(),
                       url::Origin::Create(non_isolated_sub_origin1),
                       MakeOACIsolationState(false))
                   .requires_origin_keyed_process());
  EXPECT_FALSE(policy
                   ->DetermineOriginAgentClusterIsolation(
                       child_frame_node2->current_frame_host()
                           ->GetSiteInstance()
                           ->GetIsolationContext(),
                       url::Origin::Create(non_isolated_sub_origin2),
                       MakeOACIsolationState(false))
                   .requires_origin_keyed_process());

  // Base origin and subdomains should have different SiteInstances.
  EXPECT_NE(root->current_frame_host()->GetSiteInstance(),
            child_frame_node1->current_frame_host()->GetSiteInstance());
  EXPECT_TRUE(root->current_frame_host()
                  ->GetSiteInstance()
                  ->GetSiteInfo()
                  .requires_origin_keyed_process());
  EXPECT_FALSE(child_frame_node1->current_frame_host()
                   ->GetSiteInstance()
                   ->GetSiteInfo()
                   .requires_origin_keyed_process());

  // Both non-isolated subdomains are in the same SiteInstance.
  EXPECT_EQ(child_frame_node1->current_frame_host()->GetSiteInstance(),
            child_frame_node2->current_frame_host()->GetSiteInstance());
  EXPECT_EQ(
      GURL("https://foo.com"),
      child_frame_node1->current_frame_host()->GetSiteInstance()->GetSiteURL());

  // The base-origin and the children are in different processes.
  EXPECT_NE(
      root->current_frame_host()->GetSiteInstance()->GetProcess(),
      child_frame_node1->current_frame_host()->GetSiteInstance()->GetProcess());

  // Make sure the master opt-in list has the base origin as isolated, but not
  // the sub-origins.
  BrowserContext* browser_context = web_contents()->GetBrowserContext();
  EXPECT_TRUE(policy->HasOriginEverRequestedOriginAgentClusterValue(
      browser_context, url::Origin::Create(test_url)));
  EXPECT_FALSE(policy->HasOriginEverRequestedOriginAgentClusterValue(
      browser_context, url::Origin::Create(non_isolated_sub_origin1)));
  EXPECT_FALSE(policy->HasOriginEverRequestedOriginAgentClusterValue(
      browser_context, url::Origin::Create(non_isolated_sub_origin2)));

  EXPECT_THAT(
      histograms.GetAllSamples("Navigation.OriginAgentCluster.Result"),
      testing::ElementsAre(
          base::Bucket(
              static_cast<int>(NavigationRequest::OriginAgentClusterEndResult::
                                   kNotRequestedAndNotOriginKeyed),
              2),
          base::Bucket(
              static_cast<int>(NavigationRequest::OriginAgentClusterEndResult::
                                   kRequestedAndOriginKeyed),
              1)));
}

// This test is the same as OriginIsolationOptInHeaderTest
// .IsolatedBaseOrigin except it uses port-free URLs. This is critical since we
// can have two SiteInstances with the same SiteURL as long as one is
// origin-keyed and the other isn't. Site URLs used to be used as map-keys but
// with opt-in origin isolation we need to also consider the keying flag.
// When the URLs all have non-default ports, we will never have duplicate
// site URLs since the site-keyed one will have the port stripped.
IN_PROC_BROWSER_TEST_F(OriginIsolationOptInHeaderTest,
                       IsolatedBaseOriginNoPorts) {
  GURL isolated_base_origin_url("https://foo.com");
  GURL non_isolated_sub_origin_url_a("https://a.foo.com");
  GURL non_isolated_sub_origin_url_b("https://b.foo.com");

  // Since the embedded test server only works for URLs with non-default ports,
  // use a URLLoaderInterceptor to mimic port-free operation. This allows the
  // rest of the test to operate as if all URLs are using the default ports.
  URLLoaderInterceptor interceptor(base::BindLambdaForTesting(
      [&](URLLoaderInterceptor::RequestParams* params) {
        if (params->url_request.url.host() == "foo.com") {
          if (params->url_request.url.path() != "/") {
            return false;
          }

          const std::string headers =
              "HTTP/1.1 200 OK\n"
              "Content-Type: text/html\n"
              "Origin-Agent-Cluster: ?1\n";
          // Note: this call would normally get the headers from
          // isolated_base_origin_with_subframe.html.mock-http-headers,
          // but those are meant for use with a
          // OriginIsolationOptInHeaderTest. and won't work here, so we
          // override them.
          URLLoaderInterceptor::WriteResponse(
              "content/test/data/isolated_base_origin_with_subframe.html",
              params->client.get(), &headers, std::optional<net::SSLInfo>());
          return true;
        }
        if (params->url_request.url.host() == "a.foo.com" ||
            params->url_request.url.host() == "b.foo.com") {
          URLLoaderInterceptor::WriteResponse("content/test/data/title1.html",
                                              params->client.get());
          return true;
        }
        // Not handled by us.
        return false;
      }));

  // Load the isolated base url.
  EXPECT_TRUE(NavigateToURL(shell(), isolated_base_origin_url));
  EXPECT_EQ(3u, CollectAllRenderFrameHosts(shell()->web_contents()).size());

  FrameTreeNode* root = web_contents()->GetPrimaryFrameTree().root();
  FrameTreeNode* child_frame_node1 = root->child_at(0);
  FrameTreeNode* child_frame_node2 = root->child_at(1);
  EXPECT_TRUE(NavigateToURLFromRenderer(child_frame_node1,
                                        non_isolated_sub_origin_url_a));
  EXPECT_TRUE(NavigateToURLFromRenderer(child_frame_node2,
                                        non_isolated_sub_origin_url_b));

  auto* policy = ChildProcessSecurityPolicyImpl::GetInstance();
  EXPECT_TRUE(policy
                  ->DetermineOriginAgentClusterIsolation(
                      root->current_frame_host()
                          ->GetSiteInstance()
                          ->GetIsolationContext(),
                      url::Origin::Create(isolated_base_origin_url),
                      MakeOACIsolationState(false))
                  .requires_origin_keyed_process());
  EXPECT_FALSE(policy
                   ->DetermineOriginAgentClusterIsolation(
                       child_frame_node1->current_frame_host()
                           ->GetSiteInstance()
                           ->GetIsolationContext(),
                       url::Origin::Create(non_isolated_sub_origin_url_a),
                       MakeOACIsolationState(false))
                   .requires_origin_keyed_process());
  EXPECT_FALSE(policy
                   ->DetermineOriginAgentClusterIsolation(
                       child_frame_node2->current_frame_host()
                           ->GetSiteInstance()
                           ->GetIsolationContext(),
                       url::Origin::Create(non_isolated_sub_origin_url_b),
                       MakeOACIsolationState(false))
                   .requires_origin_keyed_process());
  // Base origin and subdomains should have different SiteInstances.
  EXPECT_NE(root->current_frame_host()->GetSiteInstance(),
            child_frame_node1->current_frame_host()->GetSiteInstance());
  EXPECT_TRUE(root->current_frame_host()
                  ->GetSiteInstance()
                  ->GetSiteInfo()
                  .requires_origin_keyed_process());
  EXPECT_FALSE(child_frame_node1->current_frame_host()
                   ->GetSiteInstance()
                   ->GetSiteInfo()
                   .requires_origin_keyed_process());

  // Both SiteInstances should have the same site URL, because they have no
  // port.
  EXPECT_EQ(
      root->current_frame_host()->GetSiteInstance()->GetSiteURL(),
      child_frame_node1->current_frame_host()->GetSiteInstance()->GetSiteURL());
  EXPECT_NE(root->current_frame_host()->GetSiteInstance()->GetSiteInfo(),
            child_frame_node1->current_frame_host()
                ->GetSiteInstance()
                ->GetSiteInfo());

  // Both non-isolated subdomains are in the same SiteInstance.
  EXPECT_EQ(child_frame_node1->current_frame_host()->GetSiteInstance(),
            child_frame_node2->current_frame_host()->GetSiteInstance());

  // The base-origin and the children are in different processes.
  EXPECT_NE(
      root->current_frame_host()->GetSiteInstance()->GetProcess(),
      child_frame_node1->current_frame_host()->GetSiteInstance()->GetProcess());

  // Make sure the master opt-in list has the base origin isolated and the sub
  // origins both not isolated.
  BrowserContext* browser_context = web_contents()->GetBrowserContext();
  EXPECT_TRUE(policy->HasOriginEverRequestedOriginAgentClusterValue(
      browser_context, url::Origin::Create(isolated_base_origin_url)));
  EXPECT_FALSE(policy->HasOriginEverRequestedOriginAgentClusterValue(
      browser_context, url::Origin::Create(non_isolated_sub_origin_url_a)));
  EXPECT_FALSE(policy->HasOriginEverRequestedOriginAgentClusterValue(
      browser_context, url::Origin::Create(non_isolated_sub_origin_url_b)));
}

IN_PROC_BROWSER_TEST_F(OriginIsolationOptInHeaderTest,
                       SeparateBrowserContextTest) {
  GURL isolated_origin_url(
      https_server()->GetURL("isolated.foo.com", "/isolate_origin"));
  Shell* shell_otr = CreateOffTheRecordBrowser();

  EXPECT_NE(shell()->web_contents()->GetBrowserContext(),
            shell_otr->web_contents()->GetBrowserContext());

  // The isolation header is not present, so this navigation will result in a
  // site-keyed instance.
  EXPECT_TRUE(NavigateToURL(shell_otr, isolated_origin_url));
  WebContentsImpl* web_contents_shell_otr =
      static_cast<WebContentsImpl*>(shell_otr->web_contents());
  SiteInstanceImpl* site_instance_shell_otr =
      web_contents_shell_otr->GetPrimaryFrameTree()
          .root()
          ->current_frame_host()
          ->GetSiteInstance();
  EXPECT_FALSE(
      site_instance_shell_otr->GetSiteInfo().requires_origin_keyed_process());

  url::Origin isolated_origin = url::Origin::Create(isolated_origin_url);
  auto* policy = ChildProcessSecurityPolicyImpl::GetInstance();

  // Now navigate a different BrowserContext to the same origin, but this time
  // requesting isolation. The presence of the site-keyed instance in a
  // different BrowsingInstance shouldn't prevent this navigation from being
  // isolated. The presence of the site-keyed instance in a different
  // BrowsingInstance (whether in the same BrowserContext or a different one)
  // shouldn't prevent this navigation from being isolated. We'll test
  // cross-BrowserContext interactions below.
  SetHeaderValue("?1");
  EXPECT_TRUE(NavigateToURL(shell(), isolated_origin_url));
  EXPECT_TRUE(policy
                  ->DetermineOriginAgentClusterIsolation(
                      static_cast<WebContentsImpl*>(shell()->web_contents())
                          ->GetPrimaryFrameTree()
                          .root()
                          ->current_frame_host()
                          ->GetSiteInstance()
                          ->GetIsolationContext(),
                      isolated_origin, MakeOACIsolationState(false))
                  .requires_origin_keyed_process());

  // Make sure isolating the origin in the main context didn't affect it in the
  // off-the-record context. Specifically, if the opting-in in shell() did leak
  // to shell_otr, then `isolated_origin` will be recorded as non-opted in in
  // that BrowsingInstance. The following check makes sure that
  // `isolated_origin` is not in the non-opt-in list, verifying that the
  // internal bookkeeping is specific to each BrowserContext. Isolating the
  // bookkeeping by BrowserContext prevents timing attacks from detecting
  // whether an origin has been visited in another BrowserContext by detecting
  // the global walk.
  // At this stage, `isolated_origin` is not in the non-opt-in list for this
  // BrowsingInstance, since we haven't yet done a global walk in the OTR
  // BrowserContext, so DetermineOriginAgentClusterIsolation will return true.
  // However, during the navigation by the OpenPopup call below that global walk
  // will be triggered before the url's isolation status is set. This walk is
  // triggered by the call to CheckForIsolationOptIn() in
  // NavigationRequest::OnResponseStarted().
  EXPECT_TRUE(policy
                  ->DetermineOriginAgentClusterIsolation(
                      static_cast<WebContentsImpl*>(shell_otr->web_contents())
                          ->GetPrimaryFrameTree()
                          .root()
                          ->current_frame_host()
                          ->GetSiteInstance()
                          ->GetIsolationContext(),
                      isolated_origin, MakeOACIsolationState(true))
                  .requires_origin_keyed_process());

  // Make sure the OTR context does a global (i.e. profile) walk if we attempt
  // to now opt-in when we didn't before.
  Shell* popup = OpenPopup(shell_otr, isolated_origin_url, "popup_otr");
  WebContentsImpl* web_contents_popup =
      static_cast<WebContentsImpl*>(popup->web_contents());
  SiteInstanceImpl* site_instance_popup =
      web_contents_popup->GetPrimaryFrameTree()
          .root()
          ->current_frame_host()
          ->GetSiteInstance();
  // This shouldn't be isolated because we already have a non-isolated version
  // of this origin in shell_otr's main frame, in the same BrowsingInstance.
  EXPECT_FALSE(
      site_instance_popup->GetSiteInfo().requires_origin_keyed_process());
  // Since the OpenPopup navigation triggered a global walk, `isolated_origin`
  // was added to the non-opt-in list, so now calling
  // DetermineOriginAgentClusterIsolation will return false.
  EXPECT_FALSE(policy
                   ->DetermineOriginAgentClusterIsolation(
                       site_instance_popup->GetIsolationContext(),
                       isolated_origin, MakeOACIsolationState(true))
                   .requires_origin_keyed_process());

  // Opening a new tab in the OTR profile, which will create a new
  // BrowsingInstance, should be allowed to isolate.
  Shell* shell_otr_tab2 = CreateOffTheRecordBrowser();
  EXPECT_TRUE(NavigateToURL(shell_otr_tab2, isolated_origin_url));
  WebContentsImpl* web_contenst_shell_otr_tab2 =
      static_cast<WebContentsImpl*>(shell_otr_tab2->web_contents());
  SiteInstanceImpl* site_instance_shell_otr_tab2 =
      web_contenst_shell_otr_tab2->GetPrimaryFrameTree()
          .root()
          ->current_frame_host()
          ->GetSiteInstance();
  EXPECT_TRUE(site_instance_shell_otr_tab2->GetSiteInfo()
                  .requires_origin_keyed_process());
  EXPECT_TRUE(policy
                  ->DetermineOriginAgentClusterIsolation(
                      site_instance_shell_otr_tab2->GetIsolationContext(),
                      isolated_origin, MakeOACIsolationState(true))
                  .requires_origin_keyed_process());
}

// This test creates a scenario where we have a frame that is on the initial
// NavigationEntry, and then we created another frame with the same origin
// that opts-in to isolation. The opt-in triggers a walk of the session history
// and the frame tree ... the session history won't pick up the first frame, but
// the frame-tree walk should.
// TODO(crbug.com/40467594): Once every created frame is guaranteed to
// have a FrameNavigationEntry and thus represented in the sesion history, we
// probably can remove the frame-tree walk.
IN_PROC_BROWSER_TEST_F(OriginIsolationOptInHeaderTest, FrameTreeTest) {
  EXPECT_TRUE(NavigateToURL(shell(),
                            https_server()->GetURL("bar.com", "/title1.html")));
  // Have tab1 call window.open() to create blank tab2.
  FrameTreeNode* tab1_root = web_contents()->GetPrimaryFrameTree().root();
  ShellAddedObserver new_shell_observer;
  ASSERT_TRUE(ExecJs(tab1_root->current_frame_host(),
                     "window.w = window.open('/nocontent')"));
  Shell* tab2_shell = new_shell_observer.GetShell();

  // Create iframe in tab2.
  FrameTreeNode* tab2_root =
      static_cast<WebContentsImpl*>(tab2_shell->web_contents())
          ->GetPrimaryFrameTree()
          .root();
  ASSERT_TRUE(ExecJs(tab2_root->current_frame_host(),
                     "var iframe = document.createElement('iframe');"
                     "document.body.appendChild(iframe);"));
  EXPECT_EQ(1U, tab2_root->child_count());
  FrameTreeNode* tab2_child = tab2_root->child_at(0);
  GURL isolated_origin_url(
      https_server()->GetURL("isolated.foo.com", "/isolate_origin"));
  // Navigate the iframe in tab2 to `isolated_origin_url` without requesting
  // isolation, so it won't be isolated.
  EXPECT_TRUE(NavigateFrameToURL(tab2_child, isolated_origin_url));

  // Do a browser-initiated navigation of tab1 to the same origin, but isolate
  // it this time. This should place the two frames with `isolated_origin_url`
  // into different BrowsingInstances.
  SetHeaderValue("?1");
  EXPECT_TRUE(NavigateToURL(shell(), isolated_origin_url));

  // Since the same origin exists in two tabs, but one is isolated and the other
  // isn't, we expect them to be in different BrowsingInstances.
  EXPECT_NE(tab1_root->current_frame_host()->GetSiteInstance(),
            tab2_child->current_frame_host()->GetSiteInstance());
  EXPECT_NE(tab1_root->current_frame_host()
                ->GetSiteInstance()
                ->GetIsolationContext()
                .browsing_instance_id(),
            tab2_child->current_frame_host()
                ->GetSiteInstance()
                ->GetIsolationContext()
                .browsing_instance_id());

  url::Origin isolated_origin = url::Origin::Create(isolated_origin_url);
  auto* policy = ChildProcessSecurityPolicyImpl::GetInstance();
  // Verify that `isolated origin` is in the non-opt-in list for tab2's
  // child's BrowsingInstance. We do this by requesting opt-in for the origin,
  // then verifying that it is denied by DoesOriginRequestOptInIsolation.
  EXPECT_FALSE(policy
                   ->DetermineOriginAgentClusterIsolation(
                       tab2_child->current_frame_host()
                           ->GetSiteInstance()
                           ->GetIsolationContext(),
                       isolated_origin, MakeOACIsolationState(true))
                   .requires_origin_keyed_process());
  // Verify that `isolated_origin` in tab1 is indeed isolated.
  EXPECT_TRUE(policy
                  ->DetermineOriginAgentClusterIsolation(
                      tab1_root->current_frame_host()
                          ->GetSiteInstance()
                          ->GetIsolationContext(),
                      isolated_origin, MakeOACIsolationState(false))
                  .requires_origin_keyed_process());
  // Verify that the tab2 child frame is on the initial NavigationEntry.
  EXPECT_TRUE(tab2_shell->web_contents()
                  ->GetController()
                  .GetLastCommittedEntry()
                  ->IsInitialEntry());

  // Now, create a second frame in tab2 and navigate it to
  // `isolated_origin_url`. Even though isolation is requested, it should not
  // be isolated.
  ASSERT_TRUE(ExecJs(tab2_root->current_frame_host(),
                     "var iframe = document.createElement('iframe');"
                     "document.body.appendChild(iframe);"));
  EXPECT_EQ(2U, tab2_root->child_count());
  FrameTreeNode* tab2_child2 = tab2_root->child_at(1);
  NavigateFrameToURL(tab2_child2, isolated_origin_url);
  EXPECT_EQ(tab2_child->current_frame_host()->GetSiteInstance(),
            tab2_child2->current_frame_host()->GetSiteInstance());

  // Check that the two child frames can script each other.
  EXPECT_TRUE(ExecJs(tab2_child2, R"(
      parent.frames[0].cross_frame_property_test = 'hello from t2c2'; )"));
  EXPECT_EQ("hello from t2c2",
            EvalJs(tab2_child, "window.cross_frame_property_test;"));
}

// Similar to FrameTreeTest, but we stop the navigation that's not requesting
// isolation at the pending commit state in tab2, then verify that the FrameTree
// walk has correctly registered the origin as non-isolated in tab2, but
// isolated in tab1.
IN_PROC_BROWSER_TEST_F(OriginIsolationOptInHeaderTest,
                       FrameTreeTestPendingCommit) {
  GURL isolated_origin_url(
      https_server()->GetURL("isolated.foo.com", "/isolate_origin"));
  TestNavigationManager non_isolated_delayer(shell()->web_contents(),
                                             isolated_origin_url);
  shell()->web_contents()->GetController().LoadURL(
      isolated_origin_url, Referrer(), ui::PAGE_TRANSITION_LINK, std::string());
  EXPECT_TRUE(non_isolated_delayer.WaitForResponse());

  Shell* tab2 = CreateBrowser();
  // Do a browser-initiated navigation of tab2 to the same origin, but isolate
  // it this time. This should place the two frames with `isolated_origin_url`
  // into different BrowsingInstances.
  SetHeaderValue("?1");
  EXPECT_TRUE(NavigateToURL(tab2, isolated_origin_url));

  // Now commit the non-isolated navigation.
  ASSERT_TRUE(non_isolated_delayer.WaitForNavigationFinished());

  FrameTreeNode* tab1_root = web_contents()->GetPrimaryFrameTree().root();
  SiteInstanceImpl* tab1_site_instance =
      tab1_root->current_frame_host()->GetSiteInstance();
  FrameTreeNode* tab2_root = static_cast<WebContentsImpl*>(tab2->web_contents())
                                 ->GetPrimaryFrameTree()
                                 .root();
  SiteInstanceImpl* tab2_site_instance =
      tab2_root->current_frame_host()->GetSiteInstance();
  EXPECT_NE(tab1_site_instance, tab2_site_instance);
  EXPECT_NE(tab1_site_instance->GetIsolationContext().browsing_instance_id(),
            tab2_site_instance->GetIsolationContext().browsing_instance_id());

  // Despite the non-isolated navigation only being at pending-commit when we
  // got the response for the isolated navigation, it should be properly
  // registered as non-isolated in its browsing instance.

  url::Origin isolated_origin = url::Origin::Create(isolated_origin_url);
  auto* policy = ChildProcessSecurityPolicyImpl::GetInstance();
  // Verify that `isolated origin` is in the non-opt-in list for tab1's
  // BrowsingInstance. We do this by requesting opt-in for the origin, then
  // verifying that it is denied by DetermineOriginAgentClusterIsolation.
  EXPECT_FALSE(policy
                   ->DetermineOriginAgentClusterIsolation(
                       tab1_site_instance->GetIsolationContext(),
                       isolated_origin, MakeOACIsolationState(true))
                   .requires_origin_keyed_process());

  // Verify that `isolated_origin` in tab2 is indeed isolated.
  EXPECT_TRUE(policy
                  ->DetermineOriginAgentClusterIsolation(
                      tab2_site_instance->GetIsolationContext(),
                      isolated_origin, MakeOACIsolationState(false))
                  .requires_origin_keyed_process());
}

// Helper class to navigate a second tab to a specified URL that requests opt-in
// origin isolation just before the first tab processes the next
// DidCommitProvisionalLoad message.
class InjectIsolationRequestingNavigation
    : public DidCommitNavigationInterceptor {
 public:
  InjectIsolationRequestingNavigation(
      OriginIsolationOptInHeaderTest* test_framework,
      WebContents* tab1_web_contents,
      Shell* tab2,
      const GURL& url)
      : DidCommitNavigationInterceptor(tab1_web_contents),
        test_framework_(test_framework),
        tab2_(tab2),
        url_(url) {}

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

  bool was_called() { return was_called_; }

 private:
  // DidCommitNavigationInterceptor implementation.
  bool WillProcessDidCommitNavigation(
      RenderFrameHost* render_frame_host,
      NavigationRequest* navigation_request,
      mojom::DidCommitProvisionalLoadParamsPtr*,
      mojom::DidCommitProvisionalLoadInterfaceParamsPtr* interface_params)
      override {
    was_called_ = true;

    // Performa a navigation of `tab2_` to `url_`. `url_` should request
    // isolation.
    test_framework_->SetHeaderValue("?1");
    EXPECT_TRUE(NavigateToURL(tab2_, *url_));

    return true;
  }

  raw_ptr<OriginIsolationOptInHeaderTest> test_framework_ = nullptr;
  raw_ptr<Shell> tab2_ = nullptr;
  const raw_ref<const GURL> url_;
  bool was_called_ = false;
};

// TODO(crbug.com/40708791): flaky on Android builders since 2020-07-28.
#if BUILDFLAG(IS_ANDROID)
#define MAYBE_FrameTreeTestBeforeDidCommit DISABLED_FrameTreeTestBeforeDidCommit
#else
#define MAYBE_FrameTreeTestBeforeDidCommit FrameTreeTestBeforeDidCommit
#endif
// This test is similar to the one above, but exercises the pending navigation
// when it's at a different stage, namely between the CommitNavigation and
// DidCommitProvisionalLoad, rather than at WillProcessResponse.
IN_PROC_BROWSER_TEST_F(OriginIsolationOptInHeaderTest,
                       MAYBE_FrameTreeTestBeforeDidCommit) {
  GURL isolated_origin_url(
      https_server()->GetURL("isolated.foo.com", "/isolate_origin"));

  FrameTreeNode* tab1_root = web_contents()->GetPrimaryFrameTree().root();
  // We use the following, slightly more verbose, code instead of
  // CreateBrowser() in order to avoid issues with NavigateToURL() in
  // InjectIsolationRequestingNavigation::WillProcessDidCommitNavigation()
  // getting stuck when it calls for WaitForLoadStop internally.
  Shell* tab2 =
      Shell::CreateNewWindow(shell()->web_contents()->GetBrowserContext(),
                             GURL(), nullptr, gfx::Size());

  InjectIsolationRequestingNavigation injector(this, web_contents(), tab2,
                                               isolated_origin_url);
  {
    TestNavigationObserver tab1_navigation_observer(shell()->web_contents(), 1);
    tab1_navigation_observer.set_expected_initial_url(isolated_origin_url);
    shell()->LoadURL(isolated_origin_url);

    // Waiting for DidNavigationFinished is sufficient to ensure that
    // `injector.was_called()`.  We can't waiting for DidStopLoading, because
    // running a nested message loop in the injector confuses
    // TestNavigationObserver by changing the order of notifications.
    tab1_navigation_observer.WaitForNavigationFinished();
  }
  EXPECT_TRUE(injector.was_called());

  SiteInstanceImpl* tab1_site_instance =
      tab1_root->current_frame_host()->GetSiteInstance();
  FrameTreeNode* tab2_root = static_cast<WebContentsImpl*>(tab2->web_contents())
                                 ->GetPrimaryFrameTree()
                                 .root();
  SiteInstanceImpl* tab2_site_instance =
      tab2_root->current_frame_host()->GetSiteInstance();
  EXPECT_NE(tab1_site_instance, tab2_site_instance);
  EXPECT_NE(tab1_site_instance->GetIsolationContext().browsing_instance_id(),
            tab2_site_instance->GetIsolationContext().browsing_instance_id());

  // Despite the non-isolated navigation only being at pending-commit when we
  // got the response for the isolated navigation, it should be properly
  // registered as non-isolated in its browsing instance.
  auto* policy = ChildProcessSecurityPolicyImpl::GetInstance();
  url::Origin isolated_origin = url::Origin::Create(isolated_origin_url);
  // Verify that `isolated origin` is in the non-opt-in list for tab1's
  // BrowsingInstance. We do this by requesting opt-in for the origin, then
  // verifying that it is denied by DoesOriginRequestOptInIsolation.
  EXPECT_FALSE(policy
                   ->DetermineOriginAgentClusterIsolation(
                       tab1_site_instance->GetIsolationContext(),
                       isolated_origin, MakeOACIsolationState(true))
                   .requires_origin_keyed_process());

  // Verify that `isolated_origin` in tab2 is indeed isolated.
  EXPECT_TRUE(policy
                  ->DetermineOriginAgentClusterIsolation(
                      tab2_site_instance->GetIsolationContext(),
                      isolated_origin, MakeOACIsolationState(false))
                  .requires_origin_keyed_process());
}

class StrictOriginIsolationTest : public IsolatedOriginTestBase {
 public:
  StrictOriginIsolationTest() = default;
  ~StrictOriginIsolationTest() override = default;

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

  void SetUpCommandLine(base::CommandLine* command_line) override {
    IsolatedOriginTestBase::SetUpCommandLine(command_line);
    ASSERT_TRUE(embedded_test_server()->InitializeAndListen());

    // This is needed for this test to run properly on platforms where
    //  --site-per-process isn't the default, such as Android.
    IsolateAllSitesForTesting(command_line);
    feature_list_.InitAndEnableFeature(features::kStrictOriginIsolation);
  }

  void SetUpOnMainThread() override {
    host_resolver()->AddRule("*", "127.0.0.1");
    embedded_test_server()->StartAcceptingConnections();
  }

  // Helper function that creates an http URL for `host` that includes the test
  // server's port and returns the strict ProcessLock for that URL.
  ProcessLock GetStrictProcessLockForHost(const std::string& host) {
    return GetStrictProcessLock(embedded_test_server()->GetURL(host, "/"));
  }

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

IN_PROC_BROWSER_TEST_F(StrictOriginIsolationTest, SubframesAreIsolated) {
  GURL test_url(embedded_test_server()->GetURL(
      "foo.com",
      "/cross_site_iframe_factory.html?"
      "foo.com(mail.foo.com,bar.foo.com(foo.com),foo.com)"));
  EXPECT_TRUE(NavigateToURL(shell(), test_url));
  EXPECT_EQ(5u, CollectAllRenderFrameHosts(shell()->web_contents()).size());

  // Make sure we have three separate processes.
  FrameTreeNode* root = web_contents()->GetPrimaryFrameTree().root();
  RenderFrameHost* main_frame = root->current_frame_host();
  int main_frame_id = main_frame->GetProcess()->GetID();
  RenderFrameHost* child_frame0 = root->child_at(0)->current_frame_host();
  RenderFrameHost* child_frame1 = root->child_at(1)->current_frame_host();
  RenderFrameHost* child_frame2 = root->child_at(2)->current_frame_host();
  RenderFrameHost* grandchild_frame0 =
      root->child_at(1)->child_at(0)->current_frame_host();
  EXPECT_NE(main_frame_id, child_frame0->GetProcess()->GetID());
  EXPECT_NE(main_frame_id, child_frame1->GetProcess()->GetID());
  EXPECT_EQ(main_frame_id, child_frame2->GetProcess()->GetID());
  EXPECT_EQ(main_frame_id, grandchild_frame0->GetProcess()->GetID());

  EXPECT_EQ(GetStrictProcessLockForHost("foo.com"),
            main_frame->GetProcess()->GetProcessLock());
  EXPECT_EQ(GetStrictProcessLockForHost("mail.foo.com"),
            child_frame0->GetProcess()->GetProcessLock());
  EXPECT_EQ(GetStrictProcessLockForHost("bar.foo.com"),
            child_frame1->GetProcess()->GetProcessLock());
  EXPECT_EQ(GetStrictProcessLockForHost("foo.com"),
            child_frame2->GetProcess()->GetProcessLock());
  EXPECT_EQ(GetStrictProcessLockForHost("foo.com"),
            grandchild_frame0->GetProcess()->GetProcessLock());

  // Navigate child_frame1 to a new origin ... it should get its own process.
  FrameTreeNode* child_frame2_node = root->child_at(2);
  GURL foo_url(embedded_test_server()->GetURL("www.foo.com", "/title1.html"));
  const auto expected_foo_lock = GetStrictProcessLock(foo_url);
  EXPECT_TRUE(NavigateToURLFromRenderer(child_frame2_node, foo_url));
  EXPECT_NE(root->current_frame_host()->GetSiteInstance(),
            child_frame2_node->current_frame_host()->GetSiteInstance());
  // The old RenderFrameHost for subframe3 will no longer be valid, so get the
  // new one.
  child_frame2 = root->child_at(2)->current_frame_host();
  EXPECT_NE(main_frame->GetProcess()->GetID(),
            child_frame2->GetProcess()->GetID());
  EXPECT_EQ(expected_foo_lock, child_frame2->GetProcess()->GetProcessLock());
}

IN_PROC_BROWSER_TEST_F(StrictOriginIsolationTest, MainframesAreIsolated) {
  GURL foo_url(embedded_test_server()->GetURL("foo.com", "/title1.html"));
  const auto expected_foo_lock = GetStrictProcessLock(foo_url);
  EXPECT_TRUE(NavigateToURL(shell(), foo_url));
  EXPECT_EQ(1u, CollectAllRenderFrameHosts(shell()->web_contents()).size());
  auto* policy = ChildProcessSecurityPolicyImpl::GetInstance();

  auto foo_process_id =
      web_contents()->GetPrimaryMainFrame()->GetProcess()->GetID();
  SiteInstanceImpl* foo_site_instance = web_contents()->GetSiteInstance();
  EXPECT_EQ(expected_foo_lock,
            ProcessLock::FromSiteInfo(foo_site_instance->GetSiteInfo()));
  EXPECT_EQ(ProcessLock::FromSiteInfo(foo_site_instance->GetSiteInfo()),
            policy->GetProcessLock(foo_process_id));

  GURL sub_foo_url =
      embedded_test_server()->GetURL("sub.foo.com", "/title1.html");
  const auto expected_sub_foo_lock = GetStrictProcessLock(sub_foo_url);
  EXPECT_TRUE(NavigateToURL(shell(), sub_foo_url));
  auto sub_foo_process_id =
      shell()->web_contents()->GetPrimaryMainFrame()->GetProcess()->GetID();
  SiteInstanceImpl* sub_foo_site_instance = web_contents()->GetSiteInstance();
  EXPECT_EQ(expected_sub_foo_lock,
            ProcessLock::FromSiteInfo(sub_foo_site_instance->GetSiteInfo()));
  EXPECT_EQ(ProcessLock::FromSiteInfo(sub_foo_site_instance->GetSiteInfo()),
            policy->GetProcessLock(sub_foo_process_id));

  EXPECT_NE(foo_process_id, sub_foo_process_id);
  EXPECT_NE(foo_site_instance->GetSiteURL(),
            sub_foo_site_instance->GetSiteURL());

  // Now verify with a renderer-initiated navigation.
  GURL another_foo_url(
      embedded_test_server()->GetURL("another.foo.com", "/title2.html"));
  const auto expected_another_foo_lock = GetStrictProcessLock(another_foo_url);
  EXPECT_TRUE(NavigateToURLFromRenderer(shell(), another_foo_url));
  auto another_foo_process_id =
      shell()->web_contents()->GetPrimaryMainFrame()->GetProcess()->GetID();
  SiteInstanceImpl* another_foo_site_instance =
      web_contents()->GetSiteInstance();
  EXPECT_NE(another_foo_process_id, sub_foo_process_id);
  EXPECT_NE(another_foo_process_id, foo_process_id);
  EXPECT_EQ(
      expected_another_foo_lock,
      ProcessLock::FromSiteInfo(another_foo_site_instance->GetSiteInfo()));
  EXPECT_EQ(ProcessLock::FromSiteInfo(another_foo_site_instance->GetSiteInfo()),
            policy->GetProcessLock(another_foo_process_id));
  EXPECT_NE(another_foo_site_instance, foo_site_instance);

  EXPECT_NE(expected_foo_lock, expected_sub_foo_lock);
  EXPECT_NE(expected_sub_foo_lock, expected_another_foo_lock);
  EXPECT_NE(expected_another_foo_lock, expected_foo_lock);
}

// Ensure that navigations across two URLs that resolve to the same effective
// URL won't result in a renderer kill with strict origin isolation. See
// https://crbug.com/961386.
IN_PROC_BROWSER_TEST_F(StrictOriginIsolationTest,
                       NavigateToURLsWithSameEffectiveURL) {
  GURL foo_url(embedded_test_server()->GetURL("foo.com", "/title1.html"));
  GURL bar_url(embedded_test_server()->GetURL("bar.com", "/title1.html"));
  GURL app_url(GetWebUIURL("translated"));

  // Set up effective URL translation that maps both `foo_url` and `bar_url` to
  // `app_url`.
  EffectiveURLContentBrowserTestContentBrowserClient modified_client(
      false /* requires_dedicated_process */);
  modified_client.AddTranslation(foo_url, app_url);
  modified_client.AddTranslation(bar_url, app_url);

  // Calculate the expected SiteInfo for each URL.  Both `foo_url` and
  // `bar_url` should have a site URL of `app_url`, but the process locks
  // should be foo.com and bar.com.
  SiteInfo foo_site_info = SiteInfo::CreateForTesting(
      web_contents()->GetSiteInstance()->GetIsolationContext(), foo_url);
  EXPECT_EQ(app_url, foo_site_info.site_url());
  EXPECT_EQ(foo_url.DeprecatedGetOriginAsURL(),
            foo_site_info.process_lock_url());
  SiteInfo bar_site_info = SiteInfo::CreateForTesting(
      web_contents()->GetSiteInstance()->GetIsolationContext(), bar_url);
  EXPECT_EQ(app_url, bar_site_info.site_url());
  EXPECT_EQ(bar_url.DeprecatedGetOriginAsURL(),
            bar_site_info.process_lock_url());
  EXPECT_EQ(foo_site_info.site_url(), bar_site_info.site_url());

  // Navigate to foo_url and then to bar_url.  Verify that we end up with
  // correct SiteInfo in each case.
  EXPECT_TRUE(NavigateToURL(shell(), foo_url));
  scoped_refptr<SiteInstanceImpl> foo_site_instance =
      web_contents()->GetSiteInstance();
  EXPECT_EQ(foo_site_info, foo_site_instance->GetSiteInfo());

  EXPECT_TRUE(NavigateToURL(shell(), bar_url));
  scoped_refptr<SiteInstanceImpl> bar_site_instance =
      web_contents()->GetSiteInstance();
  EXPECT_EQ(bar_site_info, bar_site_instance->GetSiteInfo());

  // Verify that the SiteInstances and processes are different.  In
  // https://crbug.com/961386, we didn't swap processes for the second
  // navigation, leading to renderer kills.
  EXPECT_NE(foo_site_instance.get(), bar_site_instance.get());
  EXPECT_NE(foo_site_instance->GetProcess(), bar_site_instance->GetProcess());

  // Navigate to another site, then repeat this test with a redirect from
  // foo.com to bar.com.  The navigation should throw away the speculative RFH
  // created for foo.com and should commit in a process locked to bar.com.
  EXPECT_TRUE(NavigateToURL(
      shell(), embedded_test_server()->GetURL("a.com", "/title1.html")));
  GURL redirect_url(embedded_test_server()->GetURL(
      "foo.com", "/server-redirect?" + bar_url.spec()));
  modified_client.AddTranslation(redirect_url, app_url);
  EXPECT_TRUE(NavigateToURL(shell(), redirect_url, bar_url));
  EXPECT_EQ(bar_site_info, web_contents()->GetSiteInstance()->GetSiteInfo());
}

// Check that navigating a main frame from an non-isolated origin to an
// isolated origin and vice versa swaps processes and uses a new SiteInstance,
// both for renderer-initiated and browser-initiated navigations.
IN_PROC_BROWSER_TEST_F(IsolatedOriginTest, MainFrameNavigation) {
  GURL unisolated_url(
      embedded_test_server()->GetURL("www.foo.com", "/title1.html"));
  GURL isolated_url(
      embedded_test_server()->GetURL("isolated.foo.com", "/title2.html"));

  EXPECT_TRUE(NavigateToURL(shell(), unisolated_url));

  // Open a same-site popup to keep the www.foo.com process alive.
  Shell* popup = OpenPopup(shell(), GURL(url::kAboutBlankURL), "foo");
  SiteInstance* unisolated_instance =
      popup->web_contents()->GetPrimaryMainFrame()->GetSiteInstance();
  RenderProcessHost* unisolated_process =
      popup->web_contents()->GetPrimaryMainFrame()->GetProcess();

  // Go to isolated.foo.com with a renderer-initiated navigation.
  EXPECT_TRUE(NavigateToURLFromRenderer(web_contents(), isolated_url));
  scoped_refptr<SiteInstance> isolated_instance =
      web_contents()->GetSiteInstance();
  EXPECT_EQ(isolated_instance, web_contents()->GetSiteInstance());
  EXPECT_NE(unisolated_process,
            web_contents()->GetPrimaryMainFrame()->GetProcess());

  // The site URL for isolated.foo.com should be the full origin rather than
  // scheme and eTLD+1.
  EXPECT_EQ(GURL("http://isolated.foo.com/"), isolated_instance->GetSiteURL());

  // Now use a renderer-initiated navigation to go to an unisolated origin,
  // www.foo.com. This should end up back in the `popup`'s process.
  EXPECT_TRUE(NavigateToURLFromRenderer(web_contents(), unisolated_url));
  EXPECT_EQ(unisolated_instance, web_contents()->GetSiteInstance());
  EXPECT_EQ(unisolated_process,
            web_contents()->GetPrimaryMainFrame()->GetProcess());

  // Now, perform a browser-initiated navigation to an isolated origin and
  // ensure that this ends up in a new process and SiteInstance for
  // isolated.foo.com.
  EXPECT_TRUE(NavigateToURL(shell(), isolated_url));
  EXPECT_NE(web_contents()->GetSiteInstance(), unisolated_instance);
  EXPECT_NE(web_contents()->GetPrimaryMainFrame()->GetProcess(),
            unisolated_process);

  // Go back to www.foo.com: this should end up in the unisolated process.
  {
    TestNavigationObserver back_observer(web_contents());
    web_contents()->GetController().GoBack();
    back_observer.Wait();
  }

  EXPECT_EQ(unisolated_instance, web_contents()->GetSiteInstance());
  EXPECT_EQ(unisolated_process,
            web_contents()->GetPrimaryMainFrame()->GetProcess());

  // Go back again.  This should go to isolated.foo.com in an isolated process.
  {
    TestNavigationObserver back_observer(web_contents());
    web_contents()->GetController().GoBack();
    back_observer.Wait();
  }

  EXPECT_EQ(isolated_instance, web_contents()->GetSiteInstance());
  EXPECT_NE(unisolated_process,
            web_contents()->GetPrimaryMainFrame()->GetProcess());

  // Do a renderer-initiated navigation from isolated.foo.com to another
  // isolated origin and ensure there is a different isolated process.
  GURL second_isolated_url(
      embedded_test_server()->GetURL("isolated.bar.com", "/title3.html"));
  EXPECT_TRUE(NavigateToURLFromRenderer(web_contents(), second_isolated_url));
  EXPECT_EQ(GURL("http://isolated.bar.com/"),
            web_contents()->GetSiteInstance()->GetSiteURL());
  EXPECT_NE(isolated_instance, web_contents()->GetSiteInstance());
  EXPECT_NE(unisolated_instance, web_contents()->GetSiteInstance());
}

// Check that opening a popup for an isolated origin puts it into a new process
// and its own SiteInstance.
IN_PROC_BROWSER_TEST_F(IsolatedOriginTest, Popup) {
  GURL unisolated_url(
      embedded_test_server()->GetURL("foo.com", "/title1.html"));
  GURL isolated_url(
      embedded_test_server()->GetURL("isolated.foo.com", "/title2.html"));

  EXPECT_TRUE(NavigateToURL(shell(), unisolated_url));

  // Open a popup to a URL with an isolated origin and ensure that there was a
  // process swap.
  Shell* popup = OpenPopup(shell(), isolated_url, "foo");

  EXPECT_NE(shell()->web_contents()->GetSiteInstance(),
            popup->web_contents()->GetSiteInstance());

  // The popup's site URL should match the full isolated origin.
  EXPECT_EQ(GURL("http://isolated.foo.com/"),
            popup->web_contents()->GetSiteInstance()->GetSiteURL());

  // Now open a second popup from an isolated origin to a URL with an
  // unisolated origin and ensure that there was another process swap.
  Shell* popup2 = OpenPopup(popup, unisolated_url, "bar");
  EXPECT_EQ(shell()->web_contents()->GetSiteInstance(),
            popup2->web_contents()->GetSiteInstance());
  EXPECT_NE(popup->web_contents()->GetSiteInstance(),
            popup2->web_contents()->GetSiteInstance());
}

// Check that navigating a subframe to an isolated origin puts the subframe
// into an OOPIF and its own SiteInstance.  Also check that the isolated
// frame's subframes also end up in correct SiteInstance.
IN_PROC_BROWSER_TEST_F(IsolatedOriginTest, Subframe) {
  GURL top_url(
      embedded_test_server()->GetURL("www.foo.com", "/page_with_iframe.html"));
  EXPECT_TRUE(NavigateToURL(shell(), top_url));

  GURL isolated_url(embedded_test_server()->GetURL("isolated.foo.com",
                                                   "/page_with_iframe.html"));

  FrameTreeNode* root = web_contents()->GetPrimaryFrameTree().root();
  FrameTreeNode* child = root->child_at(0);

  NavigateIframeToURL(web_contents(), "test_iframe", isolated_url);
  EXPECT_EQ(child->current_url(), isolated_url);

  // Verify that the child frame is an OOPIF with a different SiteInstance.
  EXPECT_NE(web_contents()->GetSiteInstance(),
            child->current_frame_host()->GetSiteInstance());
  EXPECT_TRUE(child->current_frame_host()->IsCrossProcessSubframe());
  EXPECT_EQ(GURL("http://isolated.foo.com/"),
            child->current_frame_host()->GetSiteInstance()->GetSiteURL());

  // Verify that the isolated frame's subframe (which starts out at a relative
  // path) is kept in the isolated parent's SiteInstance.
  FrameTreeNode* grandchild = child->child_at(0);
  EXPECT_EQ(child->current_frame_host()->GetSiteInstance(),
            grandchild->current_frame_host()->GetSiteInstance());

  // Navigating the grandchild to www.foo.com should put it into the top
  // frame's SiteInstance.
  GURL non_isolated_url(
      embedded_test_server()->GetURL("www.foo.com", "/title3.html"));
  TestFrameNavigationObserver observer(grandchild);
  EXPECT_TRUE(
      ExecJs(grandchild, "location.href = '" + non_isolated_url.spec() + "';"));
  observer.Wait();
  EXPECT_EQ(non_isolated_url, grandchild->current_url());

  EXPECT_EQ(root->current_frame_host()->GetSiteInstance(),
            grandchild->current_frame_host()->GetSiteInstance());
  EXPECT_NE(child->current_frame_host()->GetSiteInstance(),
            grandchild->current_frame_host()->GetSiteInstance());
}

// Check that when an non-isolated origin foo.com embeds a subframe from an
// isolated origin, which then navigates to a non-isolated origin bar.com,
// bar.com goes back to the main frame's SiteInstance.  See
// https://crbug.com/711006.
IN_PROC_BROWSER_TEST_F(IsolatedOriginTest,
                       NoOOPIFWhenIsolatedOriginNavigatesToNonIsolatedOrigin) {
  if (AreAllSitesIsolatedForTesting()) {
    return;
  }

  GURL top_url(
      embedded_test_server()->GetURL("www.foo.com", "/page_with_iframe.html"));
  EXPECT_TRUE(NavigateToURL(shell(), top_url));

  FrameTreeNode* root = web_contents()->GetPrimaryFrameTree().root();
  FrameTreeNode* child = root->child_at(0);

  GURL isolated_url(embedded_test_server()->GetURL("isolated.foo.com",
                                                   "/page_with_iframe.html"));

  NavigateIframeToURL(web_contents(), "test_iframe", isolated_url);
  EXPECT_EQ(isolated_url, child->current_url());

  // Verify that the child frame is an OOPIF with a different SiteInstance.
  EXPECT_NE(web_contents()->GetSiteInstance(),
            child->current_frame_host()->GetSiteInstance());
  EXPECT_TRUE(child->current_frame_host()->IsCrossProcessSubframe());
  EXPECT_EQ(GURL("http://isolated.foo.com/"),
            child->current_frame_host()->GetSiteInstance()->GetSiteURL());

  // Navigate the child frame cross-site, but to a non-isolated origin. When
  // strict SiteInstaces are not enabled, this should bring the subframe back
  // into the main frame's SiteInstance. If strict SiteInstances are enabled,
  // we expect the SiteInstances to be different because a SiteInstance is not
  // allowed to contain multiple sites in that mode. In all cases though we
  // expect the navigation to end up in the same process.
  GURL bar_url(embedded_test_server()->GetURL("bar.com", "/title1.html"));
  EXPECT_FALSE(IsIsolatedOrigin(bar_url));
  NavigateIframeToURL(web_contents(), "test_iframe", bar_url);

  if (AreStrictSiteInstancesEnabled()) {
    EXPECT_NE(web_contents()->GetSiteInstance(),
              child->current_frame_host()->GetSiteInstance());
  } else {
    EXPECT_EQ(web_contents()->GetSiteInstance(),
              child->current_frame_host()->GetSiteInstance());
  }
  EXPECT_EQ(web_contents()->GetSiteInstance()->GetProcess(),
            child->current_frame_host()->GetSiteInstance()->GetProcess());
}

// Check that a new isolated origin subframe will attempt to reuse an existing
// process for that isolated origin, even across BrowsingInstances.  Also check
// that main frame navigations to an isolated origin keep using the default
// process model and do not reuse existing processes.
IN_PROC_BROWSER_TEST_F(IsolatedOriginTest, SubframeReusesExistingProcess) {
  GURL top_url(
      embedded_test_server()->GetURL("www.foo.com", "/page_with_iframe.html"));
  EXPECT_TRUE(NavigateToURL(shell(), top_url));
  FrameTreeNode* root = web_contents()->GetPrimaryFrameTree().root();
  FrameTreeNode* child = root->child_at(0);

  // Open an unrelated tab in a separate BrowsingInstance, and navigate it to
  // to an isolated origin.  This SiteInstance should have a default process
  // reuse policy - only subframes attempt process reuse.
  GURL isolated_url(embedded_test_server()->GetURL("isolated.foo.com",
                                                   "/page_with_iframe.html"));
  Shell* second_shell = CreateBrowser();
  EXPECT_TRUE(NavigateToURL(second_shell, isolated_url));
  scoped_refptr<SiteInstanceImpl> second_shell_instance =
      static_cast<SiteInstanceImpl*>(second_shell->web_contents()
                                         ->GetPrimaryMainFrame()
                                         ->GetSiteInstance());
  EXPECT_FALSE(second_shell_instance->IsRelatedSiteInstance(
      root->current_frame_host()->GetSiteInstance()));
  RenderProcessHost* isolated_process = second_shell_instance->GetProcess();
  EXPECT_EQ(ProcessReusePolicy::DEFAULT,
            second_shell_instance->process_reuse_policy());

  // Now navigate the first tab's subframe to an isolated origin.  See that it
  // reuses the existing `isolated_process`.
  NavigateIframeToURL(web_contents(), "test_iframe", isolated_url);
  EXPECT_EQ(isolated_url, child->current_url());
  EXPECT_EQ(isolated_process, child->current_frame_host()->GetProcess());
  EXPECT_EQ(
      ProcessReusePolicy::REUSE_PENDING_OR_COMMITTED_SITE_SUBFRAME,
      child->current_frame_host()->GetSiteInstance()->process_reuse_policy());

  EXPECT_TRUE(child->current_frame_host()->IsCrossProcessSubframe());
  EXPECT_EQ(GURL("http://isolated.foo.com/"),
            child->current_frame_host()->GetSiteInstance()->GetSiteURL());

  // The subframe's SiteInstance should still be different from second_shell's
  // SiteInstance, and they should be in separate BrowsingInstances.
  EXPECT_NE(second_shell_instance,
            child->current_frame_host()->GetSiteInstance());
  EXPECT_FALSE(second_shell_instance->IsRelatedSiteInstance(
      child->current_frame_host()->GetSiteInstance()));

  // Navigate the second tab to a normal URL with a same-site subframe.  This
  // leaves only the first tab's subframe in the isolated origin process.
  EXPECT_TRUE(NavigateToURL(second_shell, top_url));
  EXPECT_NE(isolated_process,
            second_shell->web_contents()->GetPrimaryMainFrame()->GetProcess());

  // Navigate the second tab's subframe to an isolated origin, and check that
  // this new subframe reuses the isolated process of the subframe in the first
  // tab, even though the two are in separate BrowsingInstances.
  NavigateIframeToURL(second_shell->web_contents(), "test_iframe",
                      isolated_url);
  FrameTreeNode* second_subframe =
      static_cast<WebContentsImpl*>(second_shell->web_contents())
          ->GetPrimaryFrameTree()
          .root()
          ->child_at(0);
  EXPECT_EQ(isolated_process,
            second_subframe->current_frame_host()->GetProcess());
  EXPECT_NE(child->current_frame_host()->GetSiteInstance(),
            second_subframe->current_frame_host()->GetSiteInstance());

  // Open a third, unrelated tab, navigate it to an isolated origin, and check
  // that its main frame doesn't share a process with the existing isolated
  // subframes.
  Shell* third_shell = CreateBrowser();
  EXPECT_TRUE(NavigateToURL(third_shell, isolated_url));
  SiteInstanceImpl* third_shell_instance = static_cast<SiteInstanceImpl*>(
      third_shell->web_contents()->GetPrimaryMainFrame()->GetSiteInstance());
  EXPECT_NE(third_shell_instance,
            second_subframe->current_frame_host()->GetSiteInstance());
  EXPECT_NE(third_shell_instance,
            child->current_frame_host()->GetSiteInstance());
  EXPECT_NE(third_shell_instance->GetProcess(), isolated_process);
}

// Check that when a cross-site, non-isolated-origin iframe opens a popup,
// navigates it to an isolated origin, and then the popup navigates back to its
// opener iframe's site, the popup and the opener iframe end up in the same
// process and can script each other.  See https://crbug.com/796912.
IN_PROC_BROWSER_TEST_F(IsolatedOriginTest,
                       PopupNavigatesToIsolatedOriginAndBack) {
  // Start on a page with same-site iframe.
  GURL foo_url(
      embedded_test_server()->GetURL("www.foo.com", "/page_with_iframe.html"));
  EXPECT_TRUE(NavigateToURL(shell(), foo_url));
  FrameTreeNode* root = web_contents()->GetPrimaryFrameTree().root();
  FrameTreeNode* child = root->child_at(0);

  // Navigate iframe cross-site, but not to an isolated origin.  This should
  // stay in the main frame's SiteInstance, unless we're in a strict
  // SiteInstance mode (including --site-per-process). (Note that the bug for
  // which this test is written is exclusive to --isolate-origins and does not
  // happen with --site-per-process.)
  GURL bar_url(embedded_test_server()->GetURL("bar.com", "/title1.html"));
  NavigateIframeToURL(web_contents(), "test_iframe", bar_url);
  if (AreStrictSiteInstancesEnabled()) {
    EXPECT_NE(root->current_frame_host()->GetSiteInstance(),
              child->current_frame_host()->GetSiteInstance());
  } else {
    EXPECT_EQ(root->current_frame_host()->GetSiteInstance(),
              child->current_frame_host()->GetSiteInstance());
  }

  // Open a blank popup from the iframe.
  ShellAddedObserver new_shell_observer;
  EXPECT_TRUE(ExecJs(child, "window.w = window.open();"));
  Shell* new_shell = new_shell_observer.GetShell();

  // Have the opener iframe navigate the popup to an isolated origin.
  GURL isolated_url(
      embedded_test_server()->GetURL("isolated.foo.com", "/title1.html"));
  {
    TestNavigationManager manager(new_shell->web_contents(), isolated_url);
    EXPECT_TRUE(ExecJs(
        child, "window.w.location.href = '" + isolated_url.spec() + "';"));
    ASSERT_TRUE(manager.WaitForNavigationFinished());
  }

  // Simulate the isolated origin in the popup navigating back to bar.com.
  GURL bar_url2(embedded_test_server()->GetURL("bar.com", "/title2.html"));
  {
    TestNavigationManager manager(new_shell->web_contents(), bar_url2);
    EXPECT_TRUE(
        ExecJs(new_shell, "location.href = '" + bar_url2.spec() + "';"));
    ASSERT_TRUE(manager.WaitForNavigationFinished());
  }

  // Check that the popup ended up in the same SiteInstance as its same-site
  // opener iframe.
  EXPECT_EQ(new_shell->web_contents()->GetPrimaryMainFrame()->GetSiteInstance(),
            child->current_frame_host()->GetSiteInstance());

  // Check that the opener iframe can script the popup.
  EXPECT_EQ(bar_url2.spec(), EvalJs(child, "window.w.location.href;"));
}

// Check that when a non-isolated-origin page opens a popup, navigates it
// to an isolated origin, and then the popup navigates to a third non-isolated
// origin and finally back to its opener's origin, the popup and the opener
// iframe end up in the same process and can script each other:
//
//   foo.com
//      |
//  window.open()
//      |
//      V
//  about:blank -> isolated.foo.com -> bar.com -> foo.com
//
// This is a variant of PopupNavigatesToIsolatedOriginAndBack where the popup
// navigates to a third site before coming back to the opener's site. See
// https://crbug.com/807184.
IN_PROC_BROWSER_TEST_F(IsolatedOriginTest,
                       PopupNavigatesToIsolatedOriginThenToAnotherSiteAndBack) {
  // Start on www.foo.com.
  GURL foo_url(embedded_test_server()->GetURL("www.foo.com", "/title1.html"));
  EXPECT_TRUE(NavigateToURL(shell(), foo_url));
  FrameTreeNode* root = web_contents()->GetPrimaryFrameTree().root();

  // Open a blank popup.
  ShellAddedObserver new_shell_observer;
  EXPECT_TRUE(ExecJs(root, "window.w = window.open();"));
  Shell* new_shell = new_shell_observer.GetShell();

  // Have the opener navigate the popup to an isolated origin.
  GURL isolated_url(
      embedded_test_server()->GetURL("isolated.foo.com", "/title1.html"));
  {
    TestNavigationManager manager(new_shell->web_contents(), isolated_url);
    EXPECT_TRUE(ExecJs(
        root, "window.w.location.href = '" + isolated_url.spec() + "';"));
    ASSERT_TRUE(manager.WaitForNavigationFinished());
  }

  // Simulate the isolated origin in the popup navigating to bar.com.
  GURL bar_url(embedded_test_server()->GetURL("bar.com", "/title2.html"));
  {
    TestNavigationManager manager(new_shell->web_contents(), bar_url);
    EXPECT_TRUE(ExecJs(new_shell, "location.href = '" + bar_url.spec() + "';"));
    ASSERT_TRUE(manager.WaitForNavigationFinished());
  }

  const SiteInstanceImpl* const root_site_instance_impl =
      static_cast<SiteInstanceImpl*>(
          root->current_frame_host()->GetSiteInstance());
  const SiteInstanceImpl* const newshell_site_instance_impl =
      static_cast<SiteInstanceImpl*>(
          new_shell->web_contents()->GetPrimaryMainFrame()->GetSiteInstance());
  if (AreDefaultSiteInstancesEnabled()) {
    // When default SiteInstances are enabled, all sites that do not
    // require a dedicated process all end up in the same default SiteInstance.
    EXPECT_EQ(newshell_site_instance_impl, root_site_instance_impl);
    EXPECT_TRUE(newshell_site_instance_impl->IsDefaultSiteInstance());
  } else {
    // At this point, the popup and the opener should still be in separate
    // SiteInstances.
    EXPECT_NE(newshell_site_instance_impl, root_site_instance_impl);
    EXPECT_FALSE(newshell_site_instance_impl->IsDefaultSiteInstance());
    EXPECT_FALSE(root_site_instance_impl->IsDefaultSiteInstance());
  }

  // Simulate the isolated origin in the popup navigating to www.foo.com.
  {
    TestNavigationManager manager(new_shell->web_contents(), foo_url);
    EXPECT_TRUE(ExecJs(new_shell, "location.href = '" + foo_url.spec() + "';"));
    ASSERT_TRUE(manager.WaitForNavigationFinished());
  }

  // The popup should now be in the same SiteInstance as its same-site opener.
  EXPECT_EQ(new_shell->web_contents()->GetPrimaryMainFrame()->GetSiteInstance(),
            root->current_frame_host()->GetSiteInstance());

  // Check that the popup can script the opener.
  EXPECT_EQ(foo_url.spec(), EvalJs(new_shell, "window.opener.location.href;"));
}

// Check that with an ABA hierarchy, where B is an isolated origin, the root
// and grandchild frames end up in the same process and can script each other.
// See https://crbug.com/796912.
IN_PROC_BROWSER_TEST_F(IsolatedOriginTest,
                       IsolatedOriginSubframeCreatesGrandchildInRootSite) {
  // Start at foo.com and do a cross-site, renderer-initiated navigation to
  // bar.com, which should stay in the same SiteInstance (outside of
  // --site-per-process mode).  This sets up the main frame such that its
  // SiteInstance's site URL does not match its actual origin - a prerequisite
  // for https://crbug.com/796912 to happen.
  GURL foo_url(embedded_test_server()->GetURL("foo.com", "/title1.html"));
  EXPECT_TRUE(NavigateToURL(shell(), foo_url));
  GURL bar_url(
      embedded_test_server()->GetURL("bar.com", "/page_with_iframe.html"));
  TestNavigationObserver observer(web_contents());
  EXPECT_TRUE(ExecJs(shell(), "location.href = '" + bar_url.spec() + "';"));
  observer.Wait();

  FrameTreeNode* root = web_contents()->GetPrimaryFrameTree().root();
  FrameTreeNode* child = root->child_at(0);

  // Navigate bar.com's subframe to an isolated origin with its own subframe.
  GURL isolated_url(embedded_test_server()->GetURL("isolated.foo.com",
                                                   "/page_with_iframe.html"));
  NavigateIframeToURL(web_contents(), "test_iframe", isolated_url);
  EXPECT_EQ(isolated_url, child->current_url());
  FrameTreeNode* grandchild = child->child_at(0);

  // Navigate the isolated origin's subframe back to bar.com, completing the
  // ABA hierarchy.
  EXPECT_TRUE(NavigateToURLFromRenderer(grandchild, bar_url));

  // The root and grandchild should be in the same SiteInstance, and the
  // middle child should be in a different SiteInstance.
  EXPECT_NE(root->current_frame_host()->GetSiteInstance(),
            child->current_frame_host()->GetSiteInstance());
  EXPECT_NE(child->current_frame_host()->GetSiteInstance(),
            grandchild->current_frame_host()->GetSiteInstance());
  EXPECT_EQ(root->current_frame_host()->GetSiteInstance(),
            grandchild->current_frame_host()->GetSiteInstance());

  // Check that the root frame can script the same-site grandchild frame.
  EXPECT_EQ(bar_url.spec(), EvalJs(root, "frames[0][0].location.href;"));
}

// Check that isolated origins can access cookies.  This requires cookie checks
// on the IO thread to be aware of isolated origins.
IN_PROC_BROWSER_TEST_F(IsolatedOriginTest, Cookies) {
  GURL isolated_url(
      embedded_test_server()->GetURL("isolated.foo.com", "/title2.html"));
  EXPECT_TRUE(NavigateToURL(shell(), isolated_url));

  EXPECT_TRUE(ExecJs(web_contents(), "document.cookie = 'foo=bar';"));

  EXPECT_EQ("foo=bar", EvalJs(web_contents(), "document.cookie;"));
}

// Check that isolated origins won't be placed into processes for other sites
// when over the process limit.
IN_PROC_BROWSER_TEST_F(IsolatedOriginTest, ProcessLimit) {
  // Set the process limit to 1.
  RenderProcessHost::SetMaxRendererProcessCount(1);

  // Navigate to an unisolated foo.com URL with an iframe.
  GURL foo_url(
      embedded_test_server()->GetURL("www.foo.com", "/page_with_iframe.html"));
  EXPECT_TRUE(NavigateToURL(shell(), foo_url));
  FrameTreeNode* root = web_contents()->GetPrimaryFrameTree().root();
  RenderProcessHost* foo_process = root->current_frame_host()->GetProcess();
  FrameTreeNode* child = root->child_at(0);

  // Navigate iframe to an isolated origin.
  GURL isolated_foo_url(
      embedded_test_server()->GetURL("isolated.foo.com", "/title2.html"));
  NavigateIframeToURL(web_contents(), "test_iframe", isolated_foo_url);

  // Ensure that the subframe was rendered in a new process.
  EXPECT_NE(child->current_frame_host()->GetProcess(), foo_process);

  // Sanity-check IsSuitableHost values for the current processes.
  const IsolationContext& isolation_context =
      root->current_frame_host()->GetSiteInstance()->GetIsolationContext();
  auto is_suitable_host = [&isolation_context](RenderProcessHost* process,
                                               const GURL& url) {
    return RenderProcessHostImpl::IsSuitableHost(
        process, isolation_context,
        SiteInfo::CreateForTesting(isolation_context, url));
  };
  EXPECT_TRUE(is_suitable_host(foo_process, foo_url));
  EXPECT_FALSE(is_suitable_host(foo_process, isolated_foo_url));
  EXPECT_TRUE(is_suitable_host(child->current_frame_host()->GetProcess(),
                               isolated_foo_url));
  EXPECT_FALSE(
      is_suitable_host(child->current_frame_host()->GetProcess(), foo_url));

  // Open a new, unrelated tab and navigate it to isolated.foo.com.  This
  // should use a new, unrelated SiteInstance that reuses the existing isolated
  // origin process from first tab's subframe.
  Shell* new_shell = CreateBrowser();
  EXPECT_TRUE(NavigateToURL(new_shell, isolated_foo_url));
  scoped_refptr<SiteInstance> isolated_foo_instance(
      new_shell->web_contents()->GetPrimaryMainFrame()->GetSiteInstance());
  RenderProcessHost* isolated_foo_process = isolated_foo_instance->GetProcess();
  EXPECT_NE(child->current_frame_host()->GetSiteInstance(),
            isolated_foo_instance);
  EXPECT_FALSE(isolated_foo_instance->IsRelatedSiteInstance(
      child->current_frame_host()->GetSiteInstance()));
  // TODO(alexmos): with --site-per-process, this won't currently reuse the
  // subframe process, because the new SiteInstance will initialize its
  // process while it still has no site (during CreateBrowser()), and since
  // dedicated processes can't currently be reused for a SiteInstance with no
  // site, this creates a new process.  The subsequent navigation to
  // `isolated_foo_url` stays in that new process without consulting whether it
  // can now reuse a different process.  This should be fixed; see
  // https://crbug.com/513036.   Without --site-per-process, this works because
  // the site-less SiteInstance is allowed to reuse the first tab's foo.com
  // process (which isn't dedicated), and then it swaps to the isolated.foo.com
  // process during navigation.
  if (!AreAllSitesIsolatedForTesting()) {
    EXPECT_EQ(child->current_frame_host()->GetProcess(), isolated_foo_process);
  }

  // Navigate iframe on the first tab to a non-isolated site.  This should swap
  // processes so that it does not reuse the isolated origin's process.
  RenderFrameDeletedObserver deleted_observer(child->current_frame_host());
  NavigateIframeToURL(
      web_contents(), "test_iframe",
      embedded_test_server()->GetURL("www.foo.com", "/title1.html"));
  EXPECT_EQ(foo_process, child->current_frame_host()->GetProcess());
  EXPECT_NE(isolated_foo_process, child->current_frame_host()->GetProcess());
  deleted_observer.WaitUntilDeleted();

  // Navigate iframe back to isolated origin.  See that it reuses the
  // `new_shell` process.
  NavigateIframeToURL(web_contents(), "test_iframe", isolated_foo_url);
  EXPECT_NE(foo_process, child->current_frame_host()->GetProcess());
  EXPECT_EQ(isolated_foo_process, child->current_frame_host()->GetProcess());

  // Navigate iframe to a different isolated origin.  Ensure that this creates
  // a third process.
  GURL isolated_bar_url(
      embedded_test_server()->GetURL("isolated.bar.com", "/title3.html"));
  NavigateIframeToURL(web_contents(), "test_iframe", isolated_bar_url);
  RenderProcessHost* isolated_bar_process =
      child->current_frame_host()->GetProcess();
  EXPECT_NE(foo_process, isolated_bar_process);
  EXPECT_NE(isolated_foo_process, isolated_bar_process);

  // The new process should only be suitable to host isolated.bar.com, not
  // regular web URLs or other isolated origins.
  EXPECT_TRUE(is_suitable_host(isolated_bar_process, isolated_bar_url));
  EXPECT_FALSE(is_suitable_host(isolated_bar_process, foo_url));
  EXPECT_FALSE(is_suitable_host(isolated_bar_process, isolated_foo_url));

  // Navigate second tab (currently at isolated.foo.com) to the
  // second isolated origin, and see that it switches processes.
  EXPECT_TRUE(NavigateToURL(new_shell, isolated_bar_url));
  EXPECT_NE(foo_process,
            new_shell->web_contents()->GetPrimaryMainFrame()->GetProcess());
  EXPECT_NE(isolated_foo_process,
            new_shell->web_contents()->GetPrimaryMainFrame()->GetProcess());
  EXPECT_EQ(isolated_bar_process,
            new_shell->web_contents()->GetPrimaryMainFrame()->GetProcess());

  // Navigate second tab to a non-isolated URL and see that it goes back into
  // the www.foo.com process, and that it does not share processes with any
  // isolated origins.
  EXPECT_TRUE(NavigateToURL(new_shell, foo_url));
  EXPECT_EQ(foo_process,
            new_shell->web_contents()->GetPrimaryMainFrame()->GetProcess());
  EXPECT_NE(isolated_foo_process,
            new_shell->web_contents()->GetPrimaryMainFrame()->GetProcess());
  EXPECT_NE(isolated_bar_process,
            new_shell->web_contents()->GetPrimaryMainFrame()->GetProcess());
}

// Verify that a navigation to an non-isolated origin does not reuse a process
// from a pending navigation to an isolated origin.  See
// https://crbug.com/738634.
IN_PROC_BROWSER_TEST_F(IsolatedOriginTest,
                       ProcessReuseWithResponseStartedFromIsolatedOrigin) {
  // Set the process limit to 1.
  RenderProcessHost::SetMaxRendererProcessCount(1);

  // Start, but don't commit a navigation to an unisolated foo.com URL.
  GURL slow_url(embedded_test_server()->GetURL("www.foo.com", "/title1.html"));
  NavigationController::LoadURLParams load_params(slow_url);
  TestNavigationManager foo_delayer(shell()->web_contents(), slow_url);
  shell()->web_contents()->GetController().LoadURL(
      slow_url, Referrer(), ui::PAGE_TRANSITION_LINK, std::string());
  EXPECT_TRUE(foo_delayer.WaitForRequestStart());

  // Open a new, unrelated tab and navigate it to isolated.foo.com.
  Shell* new_shell = CreateBrowser();
  GURL isolated_url(
      embedded_test_server()->GetURL("isolated.foo.com", "/title2.html"));
  TestNavigationManager isolated_delayer(new_shell->web_contents(),
                                         isolated_url);
  new_shell->web_contents()->GetController().LoadURL(
      isolated_url, Referrer(), ui::PAGE_TRANSITION_LINK, std::string());

  // Wait for the response from the isolated origin. After this returns, we made
  // the final pick for the process to use for this navigation as part of
  // NavigationRequest::OnResponseStarted.
  EXPECT_TRUE(isolated_delayer.WaitForResponse());

  // Now, proceed with the response and commit the non-isolated URL.  This
  // should notice that the process that was picked for this navigation is not
  // suitable anymore, as it should have been locked to isolated.foo.com.
  ASSERT_TRUE(foo_delayer.WaitForNavigationFinished());

  // Commit the isolated origin.
  ASSERT_TRUE(isolated_delayer.WaitForNavigationFinished());

  // Ensure that the isolated origin did not share a process with the first
  // tab.
  EXPECT_NE(web_contents()->GetPrimaryMainFrame()->GetProcess(),
            new_shell->web_contents()->GetPrimaryMainFrame()->GetProcess());
}

// When a navigation uses a siteless SiteInstance, and a second navigation
// commits an isolated origin which reuses the siteless SiteInstance's process
// before the first navigation's response is received, ensure that the first
// navigation can still finish properly and transfer to a new process, without
// an origin lock mismatch. See https://crbug.com/773809.
IN_PROC_BROWSER_TEST_F(IsolatedOriginTest,
                       ProcessReuseWithLazilyAssignedSiteInstance) {
  // Set the process limit to 1.
  RenderProcessHost::SetMaxRendererProcessCount(1);

  // Start from an about:blank page, where the SiteInstance will not have a
  // site assigned, but will have an associated process.
  EXPECT_TRUE(NavigateToURL(shell(), GURL(url::kAboutBlankURL)));
  SiteInstanceImpl* starting_site_instance = static_cast<SiteInstanceImpl*>(
      shell()->web_contents()->GetPrimaryMainFrame()->GetSiteInstance());
  EXPECT_FALSE(starting_site_instance->HasSite());
  EXPECT_TRUE(starting_site_instance->HasProcess());

  // Inject and click a link to a non-isolated origin www.foo.com.  Note that
  // setting location.href won't work here, as that goes through OpenURL
  // instead of OnBeginNavigation when starting from an about:blank page, and
  // that doesn't trigger this bug.
  GURL foo_url(embedded_test_server()->GetURL("www.foo.com", "/title1.html"));
  TestNavigationManager manager(shell()->web_contents(), foo_url);
  InjectAndClickLinkTo(foo_url);
  EXPECT_TRUE(manager.WaitForRequestStart());

  // Before response is received, open a new, unrelated tab and navigate it to
  // isolated.foo.com. This reuses the first process, which is still considered
  // unused at this point, and locks it to isolated.foo.com.
  Shell* new_shell = CreateBrowser();
  GURL isolated_url(
      embedded_test_server()->GetURL("isolated.foo.com", "/title2.html"));
  EXPECT_TRUE(NavigateToURL(new_shell, isolated_url));
  EXPECT_EQ(web_contents()->GetPrimaryMainFrame()->GetProcess(),
            new_shell->web_contents()->GetPrimaryMainFrame()->GetProcess());

  // Wait for response from the first tab.  This should notice that the first
  // process is no longer suitable for the final destination (which is an
  // unisolated URL) and transfer to another process.  In
  // https://crbug.com/773809, this led to a CHECK due to origin lock mismatch.
  ASSERT_TRUE(manager.WaitForNavigationFinished());

  // Ensure that the isolated origin did not share a process with the first
  // tab.
  EXPECT_NE(web_contents()->GetPrimaryMainFrame()->GetProcess(),
            new_shell->web_contents()->GetPrimaryMainFrame()->GetProcess());
}

// Same as ProcessReuseWithLazilyAssignedSiteInstance above, but here the
// navigation with a siteless SiteInstance is for an isolated origin, and the
// unrelated tab loads an unisolated URL which reuses the siteless
// SiteInstance's process.  Although the unisolated URL won't lock that process
// to an origin (except when running with --site-per-process), it should still
// mark it as used and cause the isolated origin to transfer when it receives a
// response. See https://crbug.com/773809.
IN_PROC_BROWSER_TEST_F(IsolatedOriginTest,
                       ProcessReuseWithLazilyAssignedIsolatedSiteInstance) {
  // Set the process limit to 1.
  RenderProcessHost::SetMaxRendererProcessCount(1);

  // Start from an about:blank page, where the SiteInstance will not have a
  // site assigned, but will have an associated process.
  EXPECT_TRUE(NavigateToURL(shell(), GURL(url::kAboutBlankURL)));
  SiteInstanceImpl* starting_site_instance = static_cast<SiteInstanceImpl*>(
      shell()->web_contents()->GetPrimaryMainFrame()->GetSiteInstance());
  EXPECT_FALSE(starting_site_instance->HasSite());
  EXPECT_TRUE(starting_site_instance->HasProcess());
  EXPECT_TRUE(web_contents()->GetPrimaryMainFrame()->GetProcess()->IsUnused());

  // Inject and click a link to an isolated origin.  Note that
  // setting location.href won't work here, as that goes through OpenURL
  // instead of OnBeginNavigation when starting from an about:blank page, and
  // that doesn't trigger this bug.
  GURL isolated_url(
      embedded_test_server()->GetURL("isolated.foo.com", "/title2.html"));
  TestNavigationManager manager(shell()->web_contents(), isolated_url);
  InjectAndClickLinkTo(isolated_url);
  EXPECT_TRUE(manager.WaitForRequestStart());

  // Before response is received, open a new, unrelated tab and navigate it to
  // an unisolated URL. This should reuse the first process, which is still
  // considered unused at this point, and marks it as used.
  Shell* new_shell = CreateBrowser();
  GURL foo_url(embedded_test_server()->GetURL("www.foo.com", "/title1.html"));
  EXPECT_TRUE(NavigateToURL(new_shell, foo_url));
  EXPECT_EQ(web_contents()->GetPrimaryMainFrame()->GetProcess(),
            new_shell->web_contents()->GetPrimaryMainFrame()->GetProcess());
  EXPECT_FALSE(web_contents()->GetPrimaryMainFrame()->GetProcess()->IsUnused());

  // Wait for response in the first tab.  This should notice that the first
  // process is no longer suitable for the isolated origin because it should
  // already be marked as used, and transfer to another process.
  ASSERT_TRUE(manager.WaitForNavigationFinished());

  // Ensure that the isolated origin did not share a process with the second
  // tab.
  EXPECT_NE(web_contents()->GetPrimaryMainFrame()->GetProcess(),
            new_shell->web_contents()->GetPrimaryMainFrame()->GetProcess());
}

// Verify that a navigation to an unisolated origin cannot reuse a process from
// a pending navigation to an isolated origin.  Similar to
// ProcessReuseWithResponseStartedFromIsolatedOrigin, but here the non-isolated
// URL is the first to reach OnResponseStarted, which should mark the process
// as "used", so that the isolated origin can't reuse it. See
// https://crbug.com/738634.
IN_PROC_BROWSER_TEST_F(IsolatedOriginTest,
                       ProcessReuseWithResponseStartedFromUnisolatedOrigin) {
  // Set the process limit to 1.
  RenderProcessHost::SetMaxRendererProcessCount(1);

  // Start a navigation to an unisolated foo.com URL.
  GURL slow_url(embedded_test_server()->GetURL("www.foo.com", "/title1.html"));
  NavigationController::LoadURLParams load_params(slow_url);
  TestNavigationManager foo_delayer(shell()->web_contents(), slow_url);
  shell()->web_contents()->GetController().LoadURL(
      slow_url, Referrer(), ui::PAGE_TRANSITION_LINK, std::string());

  // Wait for the response for foo.com.  After this returns, we should have made
  // the final pick for the process to use for foo.com, so this should mark the
  // process as "used" and ineligible for reuse by isolated.foo.com below.
  EXPECT_TRUE(foo_delayer.WaitForResponse());

  // Open a new, unrelated tab, navigate it to isolated.foo.com, and wait for
  // the navigation to fully load.
  Shell* new_shell = CreateBrowser();
  GURL isolated_url(
      embedded_test_server()->GetURL("isolated.foo.com", "/title2.html"));
  EXPECT_TRUE(NavigateToURL(new_shell, isolated_url));

  // Finish loading the foo.com URL.
  ASSERT_TRUE(foo_delayer.WaitForNavigationFinished());

  // Ensure that the isolated origin did not share a process with the first
  // tab.
  EXPECT_NE(web_contents()->GetPrimaryMainFrame()->GetProcess(),
            new_shell->web_contents()->GetPrimaryMainFrame()->GetProcess());
}

// Verify that when a process has a pending SiteProcessCountTracker entry for
// an isolated origin, and a navigation to a non-isolated origin reuses that
// process, future isolated origin subframe navigations do not reuse that
// process. See https://crbug.com/780661.
IN_PROC_BROWSER_TEST_F(
    IsolatedOriginTest,
    IsolatedSubframeDoesNotReuseUnsuitableProcessWithPendingSiteEntry) {
  // Set the process limit to 1.
  RenderProcessHost::SetMaxRendererProcessCount(1);

  // Start from an about:blank page, where the SiteInstance will not have a
  // site assigned, but will have an associated process.
  EXPECT_TRUE(NavigateToURL(shell(), GURL(url::kAboutBlankURL)));
  EXPECT_TRUE(web_contents()->GetPrimaryMainFrame()->GetProcess()->IsUnused());

  // Inject and click a link to an isolated origin URL which never sends back a
  // response.
  GURL hung_isolated_url(
      embedded_test_server()->GetURL("isolated.foo.com", "/hung"));
  TestNavigationManager manager(web_contents(), hung_isolated_url);
  InjectAndClickLinkTo(hung_isolated_url);

  // Wait for the request and send it.  This will place
  // isolated.foo.com on the list of pending sites for this tab's process.
  EXPECT_TRUE(manager.WaitForRequestStart());
  manager.ResumeNavigation();

  // Open a new, unrelated tab and navigate it to an unisolated URL. This
  // should reuse the first process, which is still considered unused at this
  // point, and mark it as used.
  Shell* new_shell = CreateBrowser();
  GURL foo_url(
      embedded_test_server()->GetURL("www.foo.com", "/page_with_iframe.html"));
  EXPECT_TRUE(NavigateToURL(new_shell, foo_url));

  // Navigate iframe on second tab to isolated.foo.com.  This should *not*
  // reuse the first process, even though isolated.foo.com is still in its list
  // of pending sites (from the hung navigation in the first tab).  That
  // process is unsuitable because it now contains www.foo.com.
  GURL isolated_url(
      embedded_test_server()->GetURL("isolated.foo.com", "/title1.html"));
  NavigateIframeToURL(new_shell->web_contents(), "test_iframe", isolated_url);

  FrameTreeNode* root = static_cast<WebContentsImpl*>(new_shell->web_contents())
                            ->GetPrimaryFrameTree()
                            .root();
  FrameTreeNode* child = root->child_at(0);
  EXPECT_NE(child->current_frame_host()->GetProcess(),
            root->current_frame_host()->GetProcess());

  // Manipulating cookies from the main frame should not result in a renderer
  // kill.
  EXPECT_TRUE(
      ExecJs(root->current_frame_host(), "document.cookie = 'foo=bar';"));
  EXPECT_EQ("foo=bar", EvalJs(root->current_frame_host(), "document.cookie;"));
}

// Similar to the test above, but for a ServiceWorker.  When a process has a
// pending SiteProcessCountTracker entry for an isolated origin, and a
// navigation to a non-isolated origin reuses that process, a ServiceWorker
// subsequently created for that isolated origin shouldn't reuse that process.
// See https://crbug.com/780661 and https://crbug.com/780089.
IN_PROC_BROWSER_TEST_F(
    IsolatedOriginTest,
    IsolatedServiceWorkerDoesNotReuseUnsuitableProcessWithPendingSiteEntry) {
  // Set the process limit to 1.
  RenderProcessHost::SetMaxRendererProcessCount(1);

  // Start from an about:blank page, where the SiteInstance will not have a
  // site assigned, but will have an associated process.
  EXPECT_TRUE(NavigateToURL(shell(), GURL(url::kAboutBlankURL)));
  EXPECT_TRUE(web_contents()->GetPrimaryMainFrame()->GetProcess()->IsUnused());

  // Inject and click a link to an isolated origin URL which never sends back a
  // response.
  GURL hung_isolated_url(
      embedded_test_server()->GetURL("isolated.foo.com", "/hung"));
  TestNavigationManager manager(shell()->web_contents(), hung_isolated_url);
  InjectAndClickLinkTo(hung_isolated_url);

  // Wait for the request and send it.  This will place
  // isolated.foo.com on the list of pending sites for this tab's process.
  EXPECT_TRUE(manager.WaitForRequestStart());
  manager.ResumeNavigation();

  // Open a new, unrelated tab and navigate it to an unisolated URL. This
  // should reuse the first process, which is still considered unused at this
  // point, and mark it as used.
  Shell* new_shell = CreateBrowser();
  GURL foo_url(embedded_test_server()->GetURL("www.foo.com", "/title1.html"));
  EXPECT_TRUE(NavigateToURL(new_shell, foo_url));

  // A SiteInstance created for an isolated origin ServiceWorker should
  // not reuse the unsuitable first process.
  BrowserContext* browser_context = web_contents()->GetBrowserContext();
  scoped_refptr<SiteInstanceImpl> sw_site_instance =
      SiteInstanceImpl::CreateForServiceWorker(
          browser_context,
          UrlInfo::CreateForTesting(
              hung_isolated_url,
              StoragePartitionConfig::CreateDefault(browser_context)),
          /* can_reuse_process= */ true);
  RenderProcessHost* sw_host = sw_site_instance->GetProcess();
  EXPECT_NE(new_shell->web_contents()->GetPrimaryMainFrame()->GetProcess(),
            sw_host);

  // Cancel the hung request and commit a real navigation to an isolated
  // origin. This should now end up in the ServiceWorker's process.
  web_contents()->GetPrimaryFrameTree().root()->ResetNavigationRequest(
      NavigationDiscardReason::kExplicitCancellation);
  GURL isolated_url(
      embedded_test_server()->GetURL("isolated.foo.com", "/title1.html"));
  EXPECT_TRUE(NavigateToURL(shell(), isolated_url));
  EXPECT_EQ(web_contents()->GetPrimaryMainFrame()->GetProcess(), sw_host);
}

// Check that subdomains on an isolated origin (e.g., bar.isolated.foo.com)
// also end up in the isolated origin's SiteInstance.
IN_PROC_BROWSER_TEST_F(IsolatedOriginTest, IsolatedOriginWithSubdomain) {
  // Start on a page with an isolated origin with a same-site iframe.
  GURL isolated_url(embedded_test_server()->GetURL("isolated.foo.com",
                                                   "/page_with_iframe.html"));
  EXPECT_TRUE(NavigateToURL(shell(), isolated_url));

  FrameTreeNode* root = web_contents()->GetPrimaryFrameTree().root();
  FrameTreeNode* child = root->child_at(0);
  scoped_refptr<SiteInstance> isolated_instance =
      web_contents()->GetSiteInstance();

  // Navigate iframe to the isolated origin's subdomain.
  GURL isolated_subdomain_url(
      embedded_test_server()->GetURL("bar.isolated.foo.com", "/title1.html"));
  NavigateIframeToURL(web_contents(), "test_iframe", isolated_subdomain_url);
  EXPECT_EQ(child->current_url(), isolated_subdomain_url);

  EXPECT_EQ(isolated_instance, child->current_frame_host()->GetSiteInstance());
  EXPECT_FALSE(child->current_frame_host()->IsCrossProcessSubframe());
  EXPECT_EQ(GURL("http://isolated.foo.com/"),
            child->current_frame_host()->GetSiteInstance()->GetSiteURL());

  // Now try navigating the main frame (renderer-initiated) to the isolated
  // origin's subdomain.  This should not swap processes.
  TestNavigationObserver observer(web_contents());
  EXPECT_TRUE(ExecJs(web_contents(), "location.href = '" +
                                         isolated_subdomain_url.spec() + "'"));
  observer.Wait();
  if (CanSameSiteMainFrameNavigationsChangeSiteInstances()) {
    // If same-site ProactivelySwapBrowsingInstance is enabled, they should be
    // in different site instances but in the same process.
    EXPECT_NE(isolated_instance, web_contents()->GetSiteInstance());
    EXPECT_EQ(isolated_instance->GetProcess(),
              web_contents()->GetSiteInstance()->GetProcess());
  } else {
    EXPECT_EQ(isolated_instance, web_contents()->GetSiteInstance());
  }
}

// This class allows intercepting the BindStorageArea and OpenLocalStorage
// methods in order to test what happens when parameters are changed.
class StoragePartitonInterceptor
    : public blink::mojom::DomStorageInterceptorForTesting,
      public RenderProcessHostObserver {
 public:
  StoragePartitonInterceptor(
      RenderProcessHostImpl* rph,
      mojo::PendingReceiver<blink::mojom::DomStorage> receiver,
      std::optional<blink::StorageKey> storage_key_to_inject,
      std::optional<blink::LocalFrameToken> local_frame_token_to_inject,
      bool inject_first_local_frame_token)
      : storage_key_to_inject_(storage_key_to_inject),
        local_frame_token_to_inject_(local_frame_token_to_inject),
        save_first_local_frame_token_(inject_first_local_frame_token) {
    StoragePartitionImpl* storage_partition =
        static_cast<StoragePartitionImpl*>(rph->GetStoragePartition());

    // Bind the real DomStorage implementation.
    mojo::PendingRemote<blink::mojom::DomStorageClient> unused_client;
    std::ignore = unused_client.InitWithNewPipeAndPassReceiver();
    mojo::ReceiverId receiver_id = storage_partition->BindDomStorage(
        rph->GetID(), std::move(receiver), std::move(unused_client));

    // Now replace it with this object and keep a pointer to the real
    // implementation.
    dom_storage_ = storage_partition->dom_storage_receivers_for_testing()
                       .SwapImplForTesting(receiver_id, this);

    // Register the `this` as a RenderProcessHostObserver, so it can be
    // correctly cleaned up when the process exits.
    rph->AddObserver(this);
  }

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

  // Ensure this object is cleaned up when the process goes away, since it
  // is not owned by anyone else.
  void RenderProcessExited(RenderProcessHost* host,
                           const ChildProcessTerminationInfo& info) override {
    host->RemoveObserver(this);
    delete this;
  }

  // Allow all methods that aren't explicitly overridden to pass through
  // unmodified.
  blink::mojom::DomStorage* GetForwardingInterface() override {
    return dom_storage_;
  }

  // Override this method to allow changing the `storage_key` or
  // `local_frame_token`. It simulates a renderer process sending incorrect
  // data to the browser process, so security checks can be tested.
  void OpenLocalStorage(
      const blink::StorageKey& storage_key,
      const blink::LocalFrameToken& local_frame_token,
      mojo::PendingReceiver<blink::mojom::StorageArea> receiver) override {
    if (save_first_local_frame_token_ && !saved_first_local_frame_token_) {
      saved_first_local_frame_token_ = local_frame_token;
    }
    if (saved_first_local_frame_token_ && !local_frame_token_to_inject_) {
      local_frame_token_to_inject_ = saved_first_local_frame_token_;
    }
    GetForwardingInterface()->OpenLocalStorage(
        storage_key_to_inject_ ? *storage_key_to_inject_ : storage_key,
        local_frame_token_to_inject_ ? *local_frame_token_to_inject_
                                     : local_frame_token,
        std::move(receiver));
  }

  // Override this method to allow changing the `storage_key`. It simulates a
  // renderer process sending incorrect data to the browser process, so
  // security checks can be tested.
  void BindSessionStorageArea(
      const blink::StorageKey& storage_key,
      const blink::LocalFrameToken& local_frame_token,
      const std::string& namespace_id,
      mojo::PendingReceiver<blink::mojom::StorageArea> receiver) override {
    if (save_first_local_frame_token_ && !saved_first_local_frame_token_) {
      saved_first_local_frame_token_ = local_frame_token;
    }
    if (saved_first_local_frame_token_ && !local_frame_token_to_inject_) {
      local_frame_token_to_inject_ = saved_first_local_frame_token_;
    }
    GetForwardingInterface()->BindSessionStorageArea(
        storage_key_to_inject_ ? *storage_key_to_inject_ : storage_key,
        local_frame_token_to_inject_ ? *local_frame_token_to_inject_
                                     : local_frame_token,
        namespace_id, std::move(receiver));
  }

 private:
  static std::optional<blink::LocalFrameToken> saved_first_local_frame_token_;
  // Keep a pointer to the original implementation of the service, so all
  // calls can be forwarded to it.
  raw_ptr<blink::mojom::DomStorage> dom_storage_ = nullptr;
  std::optional<blink::StorageKey> storage_key_to_inject_;
  std::optional<blink::LocalFrameToken> local_frame_token_to_inject_;
  bool save_first_local_frame_token_;
};

std::optional<blink::LocalFrameToken>
    StoragePartitonInterceptor::saved_first_local_frame_token_ = std::nullopt;

// Save the first LocalFrameToken seen and inject it into future calls.
void CreateTestDomStorageBackendToSaveFirstFrame(
    RenderProcessHostImpl* rph,
    mojo::PendingReceiver<blink::mojom::DomStorage> receiver) {
  // This object will register as RenderProcessHostObserver, so it will
  // clean itself automatically on process exit.
  new StoragePartitonInterceptor(rph, std::move(receiver), std::nullopt,
                                 std::nullopt,
                                 /* save_first_local_frame_token_ */ true);
}

// Inject (or not if null) a StorageKey and LocalFrameToken.
void CreateTestDomStorageBackendToInjectValues(
    std::optional<blink::StorageKey> storage_key_to_inject,
    std::optional<blink::LocalFrameToken> local_frame_token_to_inject,
    RenderProcessHostImpl* rph,
    mojo::PendingReceiver<blink::mojom::DomStorage> receiver) {
  // This object will register as RenderProcessHostObserver, so it will
  // clean itself automatically on process exit.
  new StoragePartitonInterceptor(rph, std::move(receiver),
                                 storage_key_to_inject,
                                 local_frame_token_to_inject,
                                 /* save_first_local_frame_token_ */ false);
}

// Verify that a renderer process cannot read sessionStorage of another origin.
IN_PROC_BROWSER_TEST_F(IsolatedOriginTest, SessionStorage_WrongOrigin) {
  auto mismatched_storage_key =
      blink::StorageKey::CreateFromStringForTesting("http://bar.com");
  RenderProcessHostImpl::SetDomStorageBinderForTesting(
      base::BindRepeating(&CreateTestDomStorageBackendToInjectValues,
                          mismatched_storage_key, std::nullopt));

  GURL isolated_url(
      embedded_test_server()->GetURL("isolated.foo.com", "/title1.html"));
  EXPECT_TRUE(IsIsolatedOrigin(url::Origin::Create(isolated_url)));
  EXPECT_TRUE(NavigateToURL(shell(), isolated_url));

  content::RenderProcessHostBadIpcMessageWaiter kill_waiter(
      web_contents()->GetPrimaryMainFrame()->GetProcess());
  // Use std::ignore here, since on Android the renderer process is
  // terminated, but ExecJs still returns true. It properly returns
  // false on all other platforms.
  std::ignore =
      ExecJs(web_contents()->GetPrimaryMainFrame(), "sessionStorage.length;");
  EXPECT_EQ(bad_message::RPH_MOJO_PROCESS_ERROR, kill_waiter.Wait());
}

// Verify not fatal if the renderer reads sessionStorage from an empty
// LocalFrameToken.
IN_PROC_BROWSER_TEST_F(IsolatedOriginTest,
                       SessionStorage_EmptyLocalFrameToken) {
  // This sets up some initial sessionStorage state for the subsequent test.
  GURL page_url(embedded_test_server()->GetURL("foo.com", "/title1.html"));
  EXPECT_TRUE(NavigateToURL(shell(), page_url));
  EXPECT_TRUE(ExecJs(web_contents()->GetPrimaryMainFrame(),
                     "sessionStorage.setItem('key', 'value');"));
  EXPECT_EQ(1, EvalJs(web_contents()->GetPrimaryMainFrame(),
                      "sessionStorage.length"));

  // Set up the IPC injection and crash the renderer process so that it's used.
  // Without crashing the renderer, the default IPC will be used.
  RenderProcessHostImpl::SetDomStorageBinderForTesting(
      base::BindRepeating(&CreateTestDomStorageBackendToInjectValues,
                          std::nullopt, blink::LocalFrameToken()));
  RenderProcessHost* renderer_process =
      web_contents()->GetPrimaryMainFrame()->GetProcess();
  RenderProcessHostWatcher crash_observer(
      renderer_process, RenderProcessHostWatcher::WATCH_FOR_PROCESS_EXIT);
  renderer_process->Shutdown(0);
  crash_observer.Wait();

  // Re-do tests now that injection is in place
  EXPECT_TRUE(NavigateToURL(shell(), page_url));
  EXPECT_EQ(0, EvalJs(web_contents()->GetPrimaryMainFrame(),
                      "sessionStorage.length"));
}

// Verify fatal error if the renderer reads sessionStorage from the wrong
// LocalFrameToken.
IN_PROC_BROWSER_TEST_F(IsolatedOriginTest,
                       SessionStorage_WrongLocalFrameToken) {
  // This sets up some initial sessionStorage state for the subsequent test.
  GURL isolated_url(embedded_test_server()->GetURL(
      "isolated.foo.com",
      "/cross_site_iframe_factory.html?isolated.foo.com(bar.com)"));
  EXPECT_TRUE(NavigateToURL(shell(), isolated_url));
  EXPECT_TRUE(ExecJs(web_contents()->GetPrimaryMainFrame(),
                     "sessionStorage.setItem('key', 'value');"));
  EXPECT_EQ(1, EvalJs(web_contents()->GetPrimaryMainFrame(),
                      "sessionStorage.length"));
  EXPECT_TRUE(ExecJs(ChildFrameAt(shell(), 0),
                     "sessionStorage.setItem('key', 'value');"));
  EXPECT_EQ(1, EvalJs(ChildFrameAt(shell(), 0), "sessionStorage.length"));

  // Set up the IPC injection and crash the renderer process so that it's used.
  // Without crashing the renderer, the default IPC will be used.
  RenderProcessHostImpl::SetDomStorageBinderForTesting(
      base::BindRepeating(&CreateTestDomStorageBackendToSaveFirstFrame));
  RenderProcessHost* renderer_process_iframe =
      ChildFrameAt(shell(), 0)->GetProcess();
  RenderProcessHostWatcher crash_observer_iframe(
      renderer_process_iframe,
      RenderProcessHostWatcher::WATCH_FOR_PROCESS_EXIT);
  renderer_process_iframe->Shutdown(0);
  crash_observer_iframe.Wait();
  RenderProcessHost* renderer_process_root =
      web_contents()->GetPrimaryMainFrame()->GetProcess();
  RenderProcessHostWatcher crash_observer_root(
      renderer_process_root, RenderProcessHostWatcher::WATCH_FOR_PROCESS_EXIT);
  renderer_process_root->Shutdown(0);
  crash_observer_root.Wait();

  // Re-do tests now that injection is in place
  EXPECT_TRUE(NavigateToURL(shell(), isolated_url));
  EXPECT_EQ(1, EvalJs(web_contents()->GetPrimaryMainFrame(),
                      "sessionStorage.length"));
  content::RenderProcessHostBadIpcMessageWaiter kill_waiter(
      ChildFrameAt(shell(), 0)->GetProcess());
  std::ignore = ExecJs(ChildFrameAt(shell(), 0), "sessionStorage.length");
  EXPECT_EQ(bad_message::RPH_MOJO_PROCESS_ERROR, kill_waiter.Wait());
  // The subframe has crashed, but the main frame should still be alive and
  // working.
  EXPECT_EQ(1, EvalJs(web_contents()->GetPrimaryMainFrame(),
                      "sessionStorage.length"));
}

// Verify not fatal if the renderer reads localStorage from an empty
// LocalFrameToken.
IN_PROC_BROWSER_TEST_F(IsolatedOriginTest, LocalStorage_EmptyLocalFrameToken) {
  // This sets up some initial localStorage state for the subsequent test.
  GURL page_url(embedded_test_server()->GetURL("foo.com", "/title1.html"));
  EXPECT_TRUE(NavigateToURL(shell(), page_url));
  EXPECT_TRUE(ExecJs(web_contents()->GetPrimaryMainFrame(),
                     "localStorage.setItem('key', 'value');"));
  EXPECT_EQ(
      1, EvalJs(web_contents()->GetPrimaryMainFrame(), "localStorage.length"));

  // Set up the IPC injection and crash the renderer process so that it's used.
  // Without crashing the renderer, the default IPC will be used.
  RenderProcessHostImpl::SetDomStorageBinderForTesting(
      base::BindRepeating(&CreateTestDomStorageBackendToInjectValues,
                          std::nullopt, blink::LocalFrameToken()));
  RenderProcessHost* renderer_process =
      web_contents()->GetPrimaryMainFrame()->GetProcess();
  RenderProcessHostWatcher crash_observer(
      renderer_process, RenderProcessHostWatcher::WATCH_FOR_PROCESS_EXIT);
  renderer_process->Shutdown(0);
  crash_observer.Wait();

  // Re-do tests now that injection is in place
  EXPECT_TRUE(NavigateToURL(shell(), page_url));
  EXPECT_EQ(
      0, EvalJs(web_contents()->GetPrimaryMainFrame(), "localStorage.length"));
}

// Verify fatal error if the renderer reads localStorage from the wrong
// LocalFrameToken.
IN_PROC_BROWSER_TEST_F(IsolatedOriginTest, LocalStorage_WrongLocalFrameToken) {
  // This sets up some initial localStorage state for the subsequent test.
  GURL isolated_url(embedded_test_server()->GetURL(
      "isolated.foo.com",
      "/cross_site_iframe_factory.html?isolated.foo.com(bar.com)"));
  EXPECT_TRUE(NavigateToURL(shell(), isolated_url));
  EXPECT_TRUE(ExecJs(web_contents()->GetPrimaryMainFrame(),
                     "localStorage.setItem('key', 'value');"));
  EXPECT_EQ(
      1, EvalJs(web_contents()->GetPrimaryMainFrame(), "localStorage.length"));
  EXPECT_TRUE(ExecJs(ChildFrameAt(shell(), 0),
                     "localStorage.setItem('key', 'value');"));
  EXPECT_EQ(1, EvalJs(ChildFrameAt(shell(), 0), "localStorage.length"));

  // Set up the IPC injection and crash the renderer process so that it's used.
  // Without crashing the renderer, the default IPC will be used.
  RenderProcessHostImpl::SetDomStorageBinderForTesting(
      base::BindRepeating(&CreateTestDomStorageBackendToSaveFirstFrame));
  RenderProcessHost* renderer_process_iframe =
      ChildFrameAt(shell(), 0)->GetProcess();
  RenderProcessHostWatcher crash_observer_iframe(
      renderer_process_iframe,
      RenderProcessHostWatcher::WATCH_FOR_PROCESS_EXIT);
  renderer_process_iframe->Shutdown(0);
  crash_observer_iframe.Wait();
  RenderProcessHost* renderer_process_root =
      web_contents()->GetPrimaryMainFrame()->GetProcess();
  RenderProcessHostWatcher crash_observer_root(
      renderer_process_root, RenderProcessHostWatcher::WATCH_FOR_PROCESS_EXIT);
  renderer_process_root->Shutdown(0);
  crash_observer_root.Wait();

  // Re-do tests now that injection is in place
  EXPECT_TRUE(NavigateToURL(shell(), isolated_url));
  EXPECT_EQ(
      1, EvalJs(web_contents()->GetPrimaryMainFrame(), "localStorage.length"));
  content::RenderProcessHostBadIpcMessageWaiter kill_waiter(
      ChildFrameAt(shell(), 0)->GetProcess());
  std::ignore = ExecJs(ChildFrameAt(shell(), 0), "localStorage.length");
  EXPECT_EQ(bad_message::RPH_MOJO_PROCESS_ERROR, kill_waiter.Wait());
  // The subframe has crashed, but the main frame should still be alive and
  // working.
  EXPECT_EQ(
      1, EvalJs(web_contents()->GetPrimaryMainFrame(), "localStorage.length"));
}

// Verify that an isolated renderer process cannot read localStorage of an
// origin outside of its isolated site.
IN_PROC_BROWSER_TEST_F(
    IsolatedOriginTest,
    LocalStorageOriginEnforcement_IsolatedAccessingNonIsolated) {
  auto mismatched_storage_key =
      blink::StorageKey::CreateFromStringForTesting("http://abc.foo.com");
  EXPECT_FALSE(IsIsolatedOrigin(mismatched_storage_key.origin()));
  RenderProcessHostImpl::SetDomStorageBinderForTesting(
      base::BindRepeating(&CreateTestDomStorageBackendToInjectValues,
                          mismatched_storage_key, std::nullopt));

  GURL isolated_url(
      embedded_test_server()->GetURL("isolated.foo.com", "/title1.html"));
  EXPECT_TRUE(IsIsolatedOrigin(url::Origin::Create(isolated_url)));

  EXPECT_TRUE(NavigateToURL(shell(), isolated_url));

  content::RenderProcessHostBadIpcMessageWaiter kill_waiter(
      shell()->web_contents()->GetPrimaryMainFrame()->GetProcess());
  // Use std::ignore here, since on Android the renderer process is
  // terminated, but ExecJs still returns true. It properly returns
  // false on all other platforms.
  std::ignore = ExecJs(shell()->web_contents()->GetPrimaryMainFrame(),
                       "localStorage.length;");
  EXPECT_EQ(bad_message::RPH_MOJO_PROCESS_ERROR, kill_waiter.Wait());
}

#if BUILDFLAG(IS_ANDROID)
#define MAYBE_LocalStorageOriginEnforcement_NonIsolatedAccessingIsolated \
  LocalStorageOriginEnforcement_NonIsolatedAccessingIsolated
#else
// TODO(lukasza): https://crbug.com/566091: Once remote NTP is capable of
// embedding OOPIFs, start enforcing citadel-style checks on desktop
// platforms.
#define MAYBE_LocalStorageOriginEnforcement_NonIsolatedAccessingIsolated \
  DISABLED_LocalStorageOriginEnforcement_NonIsolatedAccessingIsolated
#endif
// Verify that a non-isolated renderer process cannot read localStorage of an
// isolated origin.
//
// TODO(alexmos, lukasza): https://crbug.com/764958: Replicate this test for
// the IO-thread case.
IN_PROC_BROWSER_TEST_F(
    IsolatedOriginTest,
    MAYBE_LocalStorageOriginEnforcement_NonIsolatedAccessingIsolated) {
  auto isolated_storage_key =
      blink::StorageKey::CreateFromStringForTesting("http://isolated.foo.com");
  EXPECT_TRUE(IsIsolatedOrigin(isolated_storage_key.origin()));

  GURL nonisolated_url(
      embedded_test_server()->GetURL("non-isolated.com", "/title1.html"));
  EXPECT_FALSE(IsIsolatedOrigin(url::Origin::Create(nonisolated_url)));

  RenderProcessHostImpl::SetDomStorageBinderForTesting(
      base::BindRepeating(&CreateTestDomStorageBackendToInjectValues,
                          isolated_storage_key, std::nullopt));
  EXPECT_TRUE(NavigateToURL(shell(), nonisolated_url));

  content::RenderProcessHostBadIpcMessageWaiter kill_waiter(
      shell()->web_contents()->GetPrimaryMainFrame()->GetProcess());
  // Use std::ignore here, since on Android the renderer process is
  // terminated, but ExecJs still returns true. It properly returns
  // false on all other platforms.
  std::ignore = ExecJs(shell()->web_contents()->GetPrimaryMainFrame(),
                       "localStorage.length;");
  EXPECT_EQ(bad_message::RPH_MOJO_PROCESS_ERROR, kill_waiter.Wait());
}

// Verify that an IPC request for reading localStorage of an *opaque* origin
// will be rejected.
IN_PROC_BROWSER_TEST_F(IsolatedOriginTest,
                       LocalStorageOriginEnforcement_OpaqueOrigin) {
  url::Origin precursor_origin =
      url::Origin::Create(GURL("https://non-isolated.com"));
  const blink::StorageKey opaque_storage_key =
      blink::StorageKey::CreateFirstParty(
          precursor_origin.DeriveNewOpaqueOrigin());
  RenderProcessHostImpl::SetDomStorageBinderForTesting(
      base::BindRepeating(&CreateTestDomStorageBackendToInjectValues,
                          opaque_storage_key, std::nullopt));

  GURL isolated_url(
      embedded_test_server()->GetURL("isolated.foo.com", "/title1.html"));
  EXPECT_TRUE(IsIsolatedOrigin(url::Origin::Create(isolated_url)));
  EXPECT_TRUE(NavigateToURL(shell(), isolated_url));

  content::RenderProcessHostBadIpcMessageWaiter kill_waiter(
      shell()->web_contents()->GetPrimaryMainFrame()->GetProcess());
  // Use std::ignore here, since on Android the renderer process is
  // terminated, but ExecJs still returns true. It properly returns
  // false on all other platforms.
  std::ignore = ExecJs(shell()->web_contents()->GetPrimaryMainFrame(),
                       "localStorage.length;");
  EXPECT_EQ(bad_message::RPH_MOJO_PROCESS_ERROR, kill_waiter.Wait());
}

class IsolatedOriginFieldTrialTest : public IsolatedOriginTestBase {
 public:
  IsolatedOriginFieldTrialTest() {
    scoped_feature_list_.InitAndEnableFeatureWithParameters(
        features::kIsolateOrigins,
        {{features::kIsolateOriginsFieldTrialParamName,
          "https://field.trial.com/,https://bar.com/"}});
  }
  ~IsolatedOriginFieldTrialTest() override = default;

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

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

IN_PROC_BROWSER_TEST_F(IsolatedOriginFieldTrialTest, Test) {
  bool expected_to_isolate = !base::CommandLine::ForCurrentProcess()->HasSwitch(
      switches::kDisableSiteIsolation);

  EXPECT_EQ(expected_to_isolate,
            IsIsolatedOrigin(GURL("https://field.trial.com/")));
  EXPECT_EQ(expected_to_isolate, IsIsolatedOrigin(GURL("https://bar.com/")));
}

class IsolatedOriginCommandLineAndFieldTrialTest
    : public IsolatedOriginFieldTrialTest {
 public:
  IsolatedOriginCommandLineAndFieldTrialTest() = default;
  IsolatedOriginCommandLineAndFieldTrialTest(
      const IsolatedOriginCommandLineAndFieldTrialTest&) = delete;
  IsolatedOriginCommandLineAndFieldTrialTest& operator=(
      const IsolatedOriginCommandLineAndFieldTrialTest&) = delete;

  void SetUpCommandLine(base::CommandLine* command_line) override {
    IsolatedOriginFieldTrialTest::SetUpCommandLine(command_line);
    command_line->AppendSwitchASCII(
        switches::kIsolateOrigins,
        "https://cmd.line.com/,https://cmdline.com/");
  }
};

// Verify that the lists of isolated origins specified via --isolate-origins
// and via field trials are merged.  See https://crbug.com/894535.
IN_PROC_BROWSER_TEST_F(IsolatedOriginCommandLineAndFieldTrialTest, Test) {
  // --isolate-origins should take effect regardless of the
  //   kDisableSiteIsolation opt-out flag.
  EXPECT_TRUE(IsIsolatedOrigin(GURL("https://cmd.line.com/")));
  EXPECT_TRUE(IsIsolatedOrigin(GURL("https://cmdline.com/")));

  // Field trial origins should also take effect, but only if the opt-out flag
  // is not present.
  bool expected_to_isolate = !base::CommandLine::ForCurrentProcess()->HasSwitch(
      switches::kDisableSiteIsolation);
  EXPECT_EQ(expected_to_isolate,
            IsIsolatedOrigin(GURL("https://field.trial.com/")));
  EXPECT_EQ(expected_to_isolate, IsIsolatedOrigin(GURL("https://bar.com/")));
}

// This is a regression test for https://crbug.com/793350 - the long list of
// origins to isolate used to be unnecessarily propagated to the renderer
// process, trigerring a crash due to exceeding kZygoteMaxMessageLength.
class IsolatedOriginLongListTest : public IsolatedOriginTestBase {
 public:
  IsolatedOriginLongListTest() = default;
  ~IsolatedOriginLongListTest() override = default;

  void SetUpCommandLine(base::CommandLine* command_line) override {
    ASSERT_TRUE(embedded_test_server()->InitializeAndListen());

    std::ostringstream origin_list;
    origin_list
        << embedded_test_server()->GetURL("isolated.foo.com", "/").spec();
    for (int i = 0; i < 1000; i++) {
      std::ostringstream hostname;
      hostname << "foo" << i << ".com";

      origin_list << ","
                  << embedded_test_server()->GetURL(hostname.str(), "/").spec();
    }
    command_line->AppendSwitchASCII(switches::kIsolateOrigins,
                                    origin_list.str());
  }

  void SetUpOnMainThread() override {
    host_resolver()->AddRule("*", "127.0.0.1");
    embedded_test_server()->StartAcceptingConnections();
  }
};

IN_PROC_BROWSER_TEST_F(IsolatedOriginLongListTest, Test) {
  GURL test_url(embedded_test_server()->GetURL(
      "bar1.com",
      "/cross_site_iframe_factory.html?"
      "bar1.com(isolated.foo.com,foo999.com,bar2.com)"));
  EXPECT_TRUE(NavigateToURL(shell(), test_url));

  EXPECT_EQ(4u, CollectAllRenderFrameHosts(shell()->web_contents()).size());
  RenderFrameHost* main_frame = shell()->web_contents()->GetPrimaryMainFrame();
  RenderFrameHost* subframe1 = ChildFrameAt(main_frame, 0);
  RenderFrameHost* subframe2 = ChildFrameAt(main_frame, 1);
  RenderFrameHost* subframe3 = ChildFrameAt(main_frame, 2);
  EXPECT_EQ("bar1.com", main_frame->GetLastCommittedOrigin().GetURL().host());
  EXPECT_EQ("isolated.foo.com",
            subframe1->GetLastCommittedOrigin().GetURL().host());
  EXPECT_EQ("foo999.com", subframe2->GetLastCommittedOrigin().GetURL().host());
  EXPECT_EQ("bar2.com", subframe3->GetLastCommittedOrigin().GetURL().host());

  // bar1.com and bar2.com are not on the list of origins to isolate - they
  // should stay in the same process, unless --site-per-process has also been
  // specified.
  if (!AreAllSitesIsolatedForTesting()) {
    EXPECT_EQ(main_frame->GetProcess()->GetID(),
              subframe3->GetProcess()->GetID());
    if (AreStrictSiteInstancesEnabled()) {
      EXPECT_NE(main_frame->GetSiteInstance(), subframe3->GetSiteInstance());
    } else {
      EXPECT_EQ(main_frame->GetSiteInstance(), subframe3->GetSiteInstance());
    }
  }

  // isolated.foo.com and foo999.com are on the list of origins to isolate -
  // they should be isolated from everything else.
  EXPECT_NE(main_frame->GetProcess()->GetID(),
            subframe1->GetProcess()->GetID());
  EXPECT_NE(main_frame->GetSiteInstance(), subframe1->GetSiteInstance());
  EXPECT_NE(main_frame->GetProcess()->GetID(),
            subframe2->GetProcess()->GetID());
  EXPECT_NE(main_frame->GetSiteInstance(), subframe2->GetSiteInstance());
  EXPECT_NE(subframe1->GetProcess()->GetID(), subframe2->GetProcess()->GetID());
  EXPECT_NE(subframe1->GetSiteInstance(), subframe2->GetSiteInstance());
}

// Check that navigating a subframe to an isolated origin error page puts the
// subframe into an OOPIF and its own SiteInstance.  Also check that the error
// page in a subframe ends up in the correct SiteInstance.
IN_PROC_BROWSER_TEST_F(IsolatedOriginTest, SubframeErrorPages) {
  GURL top_url(
      embedded_test_server()->GetURL("/frame_tree/page_with_two_frames.html"));
  GURL isolated_url(
      embedded_test_server()->GetURL("isolated.foo.com", "/close-socket"));
  GURL regular_url(embedded_test_server()->GetURL("a.com", "/close-socket"));

  EXPECT_TRUE(NavigateToURL(shell(), top_url));
  FrameTreeNode* root = web_contents()->GetPrimaryFrameTree().root();
  EXPECT_EQ(2u, root->child_count());

  FrameTreeNode* child1 = root->child_at(0);
  FrameTreeNode* child2 = root->child_at(1);

  {
    TestFrameNavigationObserver observer(child1);
    NavigationHandleObserver handle_observer(web_contents(), isolated_url);
    EXPECT_TRUE(
        ExecJs(child1, "location.href = '" + isolated_url.spec() + "';"));
    observer.Wait();
    EXPECT_EQ(child1->current_url(), isolated_url);
    EXPECT_TRUE(handle_observer.is_error());

    EXPECT_NE(root->current_frame_host()->GetSiteInstance(),
              child1->current_frame_host()->GetSiteInstance());
    if (!SiteIsolationPolicy::IsErrorPageIsolationEnabled(
            /*in_main_frame=*/false)) {
      EXPECT_EQ(GURL("http://isolated.foo.com/"),
                child1->current_frame_host()->GetSiteInstance()->GetSiteURL());
    } else {
      EXPECT_TRUE(child1->current_frame_host()
                      ->GetSiteInstance()
                      ->GetSiteInfo()
                      .is_error_page());
    }
  }

  {
    TestFrameNavigationObserver observer(child2);
    NavigationHandleObserver handle_observer(web_contents(), regular_url);
    EXPECT_TRUE(
        ExecJs(child2, "location.href = '" + regular_url.spec() + "';"));
    observer.Wait();
    EXPECT_EQ(child2->current_url(), regular_url);
    EXPECT_TRUE(handle_observer.is_error());
    if (AreStrictSiteInstancesEnabled()) {
      EXPECT_NE(root->current_frame_host()->GetSiteInstance(),
                child2->current_frame_host()->GetSiteInstance());
      if (!SiteIsolationPolicy::IsErrorPageIsolationEnabled(
              /*in_main_frame=*/false)) {
        EXPECT_EQ(
            SiteInfo::CreateForTesting(
                IsolationContext(web_contents()->GetBrowserContext()),
                regular_url),
            child2->current_frame_host()->GetSiteInstance()->GetSiteInfo());
      }
    } else {
      EXPECT_EQ(root->current_frame_host()->GetSiteInstance(),
                child2->current_frame_host()->GetSiteInstance());
    }
    EXPECT_EQ(SiteIsolationPolicy::IsErrorPageIsolationEnabled(
                  /*in_main_frame=*/false),
              child2->current_frame_host()
                  ->GetSiteInstance()
                  ->GetSiteInfo()
                  .is_error_page());
  }
}

namespace {
bool HasDefaultSiteInstance(RenderFrameHost* rfh) {
  return static_cast<SiteInstanceImpl*>(rfh->GetSiteInstance())
      ->IsDefaultSiteInstance();
}
}  // namespace

// Verify process assignment behavior for the case where a site that does not
// require isolation embeds a frame that does require isolation, which in turn
// embeds another site that does not require isolation.
// A  (Does not require isolation)
// +-> B (requires isolation)
//     +-> C (different site from A that does not require isolation.)
//         +-> A (same site as top-level which also does not require isolation.)
IN_PROC_BROWSER_TEST_F(IsolatedOriginTest, AIsolatedCA) {
  GURL main_url(
      embedded_test_server()->GetURL("www.foo.com",
                                     "/cross_site_iframe_factory.html?www.foo."
                                     "com(isolated.foo.com(c(www.foo.com)))"));
  EXPECT_TRUE(NavigateToURL(shell(), main_url));
  FrameTreeNode* root = web_contents()->GetPrimaryFrameTree().root();
  RenderFrameHost* a = root->current_frame_host();
  RenderFrameHost* b = root->child_at(0)->current_frame_host();
  RenderFrameHost* c = root->child_at(0)->child_at(0)->current_frame_host();
  RenderFrameHost* d =
      root->child_at(0)->child_at(0)->child_at(0)->current_frame_host();

  // Sanity check that the test works with the right frame tree.
  EXPECT_FALSE(IsIsolatedOrigin(a->GetLastCommittedOrigin()));
  EXPECT_TRUE(IsIsolatedOrigin(b->GetLastCommittedOrigin()));
  EXPECT_FALSE(IsIsolatedOrigin(c->GetLastCommittedOrigin()));
  EXPECT_FALSE(IsIsolatedOrigin(d->GetLastCommittedOrigin()));
  EXPECT_EQ("www.foo.com", a->GetLastCommittedURL().host());
  EXPECT_EQ("isolated.foo.com", b->GetLastCommittedURL().host());
  EXPECT_EQ("c.com", c->GetLastCommittedURL().host());
  EXPECT_EQ("www.foo.com", d->GetLastCommittedURL().host());

  // Verify that the isolated site is indeed isolated.
  EXPECT_NE(b->GetProcess()->GetID(), a->GetProcess()->GetID());
  EXPECT_NE(b->GetProcess()->GetID(), c->GetProcess()->GetID());
  EXPECT_NE(b->GetProcess()->GetID(), d->GetProcess()->GetID());

  // Verify that same-origin a and d frames share a process.  This is
  // necessary for correctness - otherwise a and d wouldn't be able to
  // synchronously script each other.
  EXPECT_EQ(a->GetProcess()->GetID(), d->GetProcess()->GetID());

  // Verify that same-origin a and d frames can script each other.
  EXPECT_TRUE(ExecJs(a, "window.name = 'a';"));
  EXPECT_TRUE(ExecJs(d, R"(
      a = window.open('', 'a');
      a.cross_frame_property_test = 'hello from d'; )"));
  EXPECT_EQ("hello from d",
            EvalJs(a, "window.cross_frame_property_test").ExtractString());

  // The test assertions below are not strictly necessary - they just document
  // the current behavior.  In particular, consolidating www.foo.com and c.com
  // sites into the same process is not necessary for correctness.
  if (AreAllSitesIsolatedForTesting()) {
    // All sites are isolated so we expect foo.com, isolated.foo.com and c.com
    // to all be in their own processes.
    EXPECT_NE(a->GetProcess()->GetID(), b->GetProcess()->GetID());
    EXPECT_NE(a->GetProcess()->GetID(), c->GetProcess()->GetID());
    EXPECT_NE(b->GetProcess()->GetID(), c->GetProcess()->GetID());

    EXPECT_NE(a->GetSiteInstance(), b->GetSiteInstance());
    EXPECT_NE(a->GetSiteInstance(), c->GetSiteInstance());
    EXPECT_EQ(a->GetSiteInstance(), d->GetSiteInstance());
    EXPECT_NE(b->GetSiteInstance(), c->GetSiteInstance());

    EXPECT_FALSE(HasDefaultSiteInstance(a));
    EXPECT_FALSE(HasDefaultSiteInstance(b));
    EXPECT_FALSE(HasDefaultSiteInstance(c));
  } else if (AreDefaultSiteInstancesEnabled()) {
    // All sites that are not isolated should be in the same default
    // SiteInstance process.
    EXPECT_NE(a->GetProcess()->GetID(), b->GetProcess()->GetID());
    EXPECT_EQ(a->GetProcess()->GetID(), c->GetProcess()->GetID());

    EXPECT_NE(a->GetSiteInstance(), b->GetSiteInstance());
    EXPECT_EQ(a->GetSiteInstance(), c->GetSiteInstance());
    EXPECT_EQ(a->GetSiteInstance(), d->GetSiteInstance());
    EXPECT_NE(b->GetSiteInstance(), c->GetSiteInstance());

    EXPECT_TRUE(HasDefaultSiteInstance(a));
    EXPECT_FALSE(HasDefaultSiteInstance(b));
  } else if (AreStrictSiteInstancesEnabled()) {
    // All sites have their own SiteInstance and sites that are not isolated
    // are all placed in the same process.
    EXPECT_NE(a->GetProcess()->GetID(), b->GetProcess()->GetID());
    EXPECT_EQ(a->GetProcess()->GetID(), c->GetProcess()->GetID());

    EXPECT_NE(a->GetSiteInstance(), b->GetSiteInstance());
    EXPECT_NE(a->GetSiteInstance(), c->GetSiteInstance());
    EXPECT_EQ(a->GetSiteInstance(), d->GetSiteInstance());
    EXPECT_NE(b->GetSiteInstance(), c->GetSiteInstance());

    EXPECT_FALSE(HasDefaultSiteInstance(a));
    EXPECT_FALSE(HasDefaultSiteInstance(b));
    EXPECT_FALSE(HasDefaultSiteInstance(c));
  } else {
    FAIL() << "Unexpected process model configuration.";
  }
}

IN_PROC_BROWSER_TEST_F(IsolatedOriginTest, NavigateToBlobURL) {
  GURL top_url(
      embedded_test_server()->GetURL("www.foo.com", "/page_with_iframe.html"));
  EXPECT_TRUE(NavigateToURL(shell(), top_url));

  GURL isolated_url(embedded_test_server()->GetURL("isolated.foo.com",
                                                   "/page_with_iframe.html"));

  FrameTreeNode* root = web_contents()->GetPrimaryFrameTree().root();
  FrameTreeNode* child = root->child_at(0);

  NavigateIframeToURL(web_contents(), "test_iframe", isolated_url);
  EXPECT_EQ(child->current_url(), isolated_url);
  EXPECT_TRUE(child->current_frame_host()->IsCrossProcessSubframe());

  // Now navigate the child frame to a Blob URL.
  TestNavigationObserver load_observer(shell()->web_contents());
  EXPECT_TRUE(ExecJs(shell()->web_contents()->GetPrimaryMainFrame(),
                     "const b = new Blob(['foo']);\n"
                     "const u = URL.createObjectURL(b);\n"
                     "frames[0].location = u;\n"
                     "URL.revokeObjectURL(u);"));
  load_observer.Wait();
  EXPECT_TRUE(base::StartsWith(child->current_url().spec(),
                               "blob:http://www.foo.com",
                               base::CompareCase::SENSITIVE));
  EXPECT_TRUE(load_observer.last_navigation_succeeded());
}

// Test that same-site cross-origin navigations keep user activation even when
// origin isolation is enabled.
IN_PROC_BROWSER_TEST_F(IsolatedOriginTest, UserActivationSameSite) {
  GURL main_url(embedded_test_server()->GetURL(
      "a.com", "/cross_site_iframe_factory.html?a(bar)"));
  EXPECT_TRUE(NavigateToURL(shell(), main_url));

  // It is safe to obtain the root frame tree node here, as it doesn't change.
  FrameTreeNode* root = web_contents()->GetPrimaryFrameTree().root();
  FrameTreeNode* child = root->child_at(0);

  // Sanity check that there is no sticky user activation at first.
  EXPECT_FALSE(child->current_frame_host()->HasStickyUserActivation());
  EXPECT_EQ(false, EvalJs(child->current_frame_host(),
                          "navigator.userActivation.hasBeenActive",
                          EXECUTE_SCRIPT_NO_USER_GESTURE));

  // Load cross-origin same-site page into iframe and verify there is still no
  // sticky user activation.
  GURL first_http_url(
      embedded_test_server()->GetURL("isolated.bar.com", "/title1.html"));
  EXPECT_TRUE(
      NavigateToURLFromRendererWithoutUserGesture(child, first_http_url));
  EXPECT_FALSE(child->current_frame_host()->HasStickyUserActivation());
  EXPECT_EQ(false, EvalJs(child->current_frame_host(),
                          "navigator.userActivation.hasBeenActive",
                          EXECUTE_SCRIPT_NO_USER_GESTURE));

  // Give the child iframe user activation.
  EXPECT_TRUE(ExecJs(child, "// No-op script"));
  EXPECT_TRUE(child->current_frame_host()->HasStickyUserActivation());
  EXPECT_EQ(true, EvalJs(child->current_frame_host(),
                         "navigator.userActivation.hasBeenActive",
                         EXECUTE_SCRIPT_NO_USER_GESTURE));

  // Perform another cross-origin same-site navigation in the iframe.
  GURL second_http_url(
      embedded_test_server()->GetURL("bar.com", "/title1.html"));
  EXPECT_TRUE(
      NavigateToURLFromRendererWithoutUserGesture(child, second_http_url));

  // The cross-origin same-site navigation should keep the sticky user
  // activation from the previous page.
  EXPECT_TRUE(child->current_frame_host()->HasStickyUserActivation());
  EXPECT_EQ(true, EvalJs(child->current_frame_host(),
                         "navigator.userActivation.hasBeenActive",
                         EXECUTE_SCRIPT_NO_USER_GESTURE));

  // Ensure that top-level navigations can still happen.
  EXPECT_TRUE(ExecJs(child->current_frame_host(),
                     JsReplace("window.open($1, $2)", first_http_url, "_top"),
                     EXECUTE_SCRIPT_NO_USER_GESTURE));
  EXPECT_TRUE(WaitForLoadStop(shell()->web_contents()));
  EXPECT_EQ(first_http_url, shell()->web_contents()->GetLastCommittedURL());
}

// Ensure that --disable-site-isolation-trials disables origin isolation.
class IsolatedOriginTrialOverrideTest : public IsolatedOriginFieldTrialTest {
 public:
  IsolatedOriginTrialOverrideTest() = default;
  ~IsolatedOriginTrialOverrideTest() override = default;

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

  void SetUpCommandLine(base::CommandLine* command_line) override {
    IsolatedOriginFieldTrialTest::SetUpCommandLine(command_line);
    command_line->AppendSwitch(switches::kDisableSiteIsolation);
  }
};

IN_PROC_BROWSER_TEST_F(IsolatedOriginTrialOverrideTest, Test) {
  if (AreAllSitesIsolatedForTesting()) {
    return;
  }
  EXPECT_FALSE(IsIsolatedOrigin(GURL("https://field.trial.com/")));
  EXPECT_FALSE(IsIsolatedOrigin(GURL("https://bar.com/")));
}

// Ensure that --disable-site-isolation-trials and/or
// --disable-site-isolation-for-policy do not override the flag.
class IsolatedOriginPolicyOverrideTest : public IsolatedOriginFieldTrialTest {
 public:
  IsolatedOriginPolicyOverrideTest() = default;
  ~IsolatedOriginPolicyOverrideTest() override = default;

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

  void SetUpCommandLine(base::CommandLine* command_line) override {
    IsolatedOriginFieldTrialTest::SetUpCommandLine(command_line);
    command_line->AppendSwitch(switches::kDisableSiteIsolation);
#if BUILDFLAG(IS_ANDROID)
    command_line->AppendSwitch(switches::kDisableSiteIsolationForPolicy);
#endif
  }
};

IN_PROC_BROWSER_TEST_F(IsolatedOriginPolicyOverrideTest, Test) {
  if (AreAllSitesIsolatedForTesting()) {
    return;
  }
  EXPECT_FALSE(IsIsolatedOrigin(GURL("https://field.trial.com/")));
  EXPECT_FALSE(IsIsolatedOrigin(GURL("https://bar.com/")));
}

// Ensure that --disable-site-isolation-trials and/or
// --disable-site-isolation-for-policy do not override the flag.
class IsolatedOriginNoFlagOverrideTest : public IsolatedOriginTest {
 public:
  IsolatedOriginNoFlagOverrideTest() = default;
  ~IsolatedOriginNoFlagOverrideTest() override = default;

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

  void SetUpCommandLine(base::CommandLine* command_line) override {
    IsolatedOriginTest::SetUpCommandLine(command_line);
    command_line->AppendSwitch(switches::kDisableSiteIsolation);
#if BUILDFLAG(IS_ANDROID)
    command_line->AppendSwitch(switches::kDisableSiteIsolationForPolicy);
#endif
  }
};

IN_PROC_BROWSER_TEST_F(IsolatedOriginNoFlagOverrideTest, Test) {
  GURL isolated_url(
      embedded_test_server()->GetURL("isolated.foo.com", "/title2.html"));
  EXPECT_TRUE(IsIsolatedOrigin(isolated_url));
}

// Verify that main frame's origin isolation still keeps all same-origin frames
// in the same process.  When allocating processes for a(b(c),d(c)), we should
// ensure that "c" frames are in the same process.
//
// This is a regression test for https://crbug.com/787576.
IN_PROC_BROWSER_TEST_F(IsolatedOriginNoFlagOverrideTest,
                       SameOriginSubframesProcessSharing) {
  GURL main_url(embedded_test_server()->GetURL(
      "isolated.foo.com",
      "/cross_site_iframe_factory.html?isolated.foo.com(b(c),d(c))"));
  EXPECT_TRUE(NavigateToURL(shell(), main_url));
  FrameTreeNode* root = web_contents()->GetPrimaryFrameTree().root();
  RenderFrameHost* a = root->current_frame_host();
  RenderFrameHost* b = root->child_at(0)->current_frame_host();
  RenderFrameHost* c1 = root->child_at(0)->child_at(0)->current_frame_host();
  RenderFrameHost* d = root->child_at(1)->current_frame_host();
  RenderFrameHost* c2 = root->child_at(1)->child_at(0)->current_frame_host();

  // Sanity check that the test works with the right frame tree.
  EXPECT_TRUE(IsIsolatedOrigin(a->GetLastCommittedOrigin()));
  EXPECT_FALSE(IsIsolatedOrigin(b->GetLastCommittedOrigin()));
  EXPECT_FALSE(IsIsolatedOrigin(d->GetLastCommittedOrigin()));
  EXPECT_FALSE(IsIsolatedOrigin(c1->GetLastCommittedOrigin()));
  EXPECT_FALSE(IsIsolatedOrigin(c2->GetLastCommittedOrigin()));
  EXPECT_EQ("b.com", b->GetLastCommittedURL().host());
  EXPECT_EQ("d.com", d->GetLastCommittedURL().host());
  EXPECT_EQ("c.com", c1->GetLastCommittedURL().host());
  EXPECT_EQ("c.com", c2->GetLastCommittedURL().host());

  // Verify that the isolated site is indeed isolated.
  EXPECT_NE(a->GetProcess()->GetID(), c1->GetProcess()->GetID());
  EXPECT_NE(a->GetProcess()->GetID(), c2->GetProcess()->GetID());
  EXPECT_NE(a->GetProcess()->GetID(), b->GetProcess()->GetID());
  EXPECT_NE(a->GetProcess()->GetID(), d->GetProcess()->GetID());

  // Verify that same-origin c1 and c2 frames share a process.  This is
  // necessary for correctness - otherwise c1 and c2 wouldn't be able to
  // synchronously script each other.
  EXPECT_EQ(c1->GetProcess()->GetID(), c2->GetProcess()->GetID());

  // Verify that same-origin c1 and c2 frames can script each other.
  EXPECT_TRUE(ExecJs(c1, "window.name = 'c1';"));
  EXPECT_TRUE(ExecJs(c2, R"(
      c1 = window.open('', 'c1');
      c1.cross_frame_property_test = 'hello from c2'; )"));
  EXPECT_EQ("hello from c2", EvalJs(c1, "window.cross_frame_property_test;"));

  // The test assertions below are not strictly necessary - they just document
  // the current behavior and might be tweaked if needed.  In particular,
  // consolidating b,c,d sites into the same process is not necessary for
  // correctness.  Consolidation might be desirable if we want to limit the
  // number of renderer processes.  OTOH, consolidation might be undesirable
  // if we desire smaller renderer processes (even if it means more processes).
  if (!AreAllSitesIsolatedForTesting()) {
    EXPECT_EQ(b->GetProcess()->GetID(), c1->GetProcess()->GetID());
    EXPECT_EQ(b->GetProcess()->GetID(), c2->GetProcess()->GetID());
    EXPECT_EQ(b->GetProcess()->GetID(), d->GetProcess()->GetID());
  } else {
    EXPECT_NE(b->GetProcess()->GetID(), c1->GetProcess()->GetID());
    EXPECT_NE(b->GetProcess()->GetID(), c2->GetProcess()->GetID());
    EXPECT_NE(b->GetProcess()->GetID(), d->GetProcess()->GetID());
    EXPECT_EQ(c1->GetProcess()->GetID(), c2->GetProcess()->GetID());
  }
}

// Helper class for testing dynamically-added isolated origins.  Tests that use
// this run without full --site-per-process, but with two isolated origins that
// are configured at startup (isolated.foo.com and isolated.bar.com).
class DynamicIsolatedOriginTest : public IsolatedOriginTest {
 public:
  DynamicIsolatedOriginTest()
      : https_server_(net::EmbeddedTestServer::TYPE_HTTPS) {}
  ~DynamicIsolatedOriginTest() override = default;

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

  void SetUpCommandLine(base::CommandLine* command_line) override {
    IsolatedOriginTest::SetUpCommandLine(command_line);
    command_line->AppendSwitch(switches::kDisableSiteIsolation);

    if (AreAllSitesIsolatedForTesting()) {
      LOG(WARNING) << "This test should be run without strict site isolation. "
                   << "It does nothing when --site-per-process is specified.";
    }
  }

  void SetUpOnMainThread() override {
    https_server()->AddDefaultHandlers(GetTestDataFilePath());
    ASSERT_TRUE(https_server()->Start());
    IsolatedOriginTest::SetUpOnMainThread();
  }

  // Need an https server because third-party cookies are used, and
  // SameSite=None cookies must be Secure.
  net::EmbeddedTestServer* https_server() { return &https_server_; }

 private:
  net::EmbeddedTestServer https_server_;
};

// Check that dynamically added isolated origins take effect for future
// BrowsingInstances only.
IN_PROC_BROWSER_TEST_F(DynamicIsolatedOriginTest,
                       IsolationAppliesToFutureBrowsingInstances) {
  // This test is designed to run without strict site isolation.
  if (AreAllSitesIsolatedForTesting()) {
    return;
  }

  // Start on a non-isolated origin with same-site iframe.
  GURL foo_url(
      embedded_test_server()->GetURL("foo.com", "/page_with_iframe.html"));
  EXPECT_TRUE(NavigateToURL(shell(), foo_url));

  FrameTreeNode* root = web_contents()->GetPrimaryFrameTree().root();
  FrameTreeNode* child = root->child_at(0);

  // Navigate iframe cross-site.
  GURL bar_url(embedded_test_server()->GetURL("bar.com", "/title1.html"));
  NavigateIframeToURL(web_contents(), "test_iframe", bar_url);
  EXPECT_EQ(child->current_url(), bar_url);

  // The two frames should be in the same process, since neither site is
  // isolated so far.
  if (AreStrictSiteInstancesEnabled()) {
    EXPECT_NE(root->current_frame_host()->GetSiteInstance(),
              child->current_frame_host()->GetSiteInstance());
  } else {
    EXPECT_EQ(root->current_frame_host()->GetSiteInstance(),
              child->current_frame_host()->GetSiteInstance());
  }
  EXPECT_EQ(root->current_frame_host()->GetProcess(),
            child->current_frame_host()->GetProcess());

  // Start isolating foo.com.
  auto* policy = ChildProcessSecurityPolicyImpl::GetInstance();
  policy->AddFutureIsolatedOrigins({url::Origin::Create(foo_url)},
                                   IsolatedOriginSource::TEST);

  // The isolation shouldn't take effect in the current frame tree, so that it
  // doesn't break same-site scripting.  Navigate iframe to a foo.com URL and
  // ensure it stays in the same process.
  NavigateIframeToURL(web_contents(), "test_iframe", foo_url);
  EXPECT_EQ(root->current_frame_host()->GetSiteInstance(),
            child->current_frame_host()->GetSiteInstance());
  EXPECT_EQ(root->current_frame_host()->GetProcess(),
            child->current_frame_host()->GetProcess());

  // Also try a foo(bar(foo)) hierarchy and check that all frames are still in
  // the same SiteInstance/process.
  GURL bar_with_foo_url(embedded_test_server()->GetURL(
      "bar.com", "/cross_site_iframe_factory.html?bar.com(foo.com)"));
  NavigateIframeToURL(web_contents(), "test_iframe", bar_with_foo_url);
  FrameTreeNode* grandchild = child->child_at(0);
  if (AreStrictSiteInstancesEnabled()) {
    EXPECT_NE(root->current_frame_host()->GetSiteInstance(),
              child->current_frame_host()->GetSiteInstance());
    EXPECT_NE(child->current_frame_host()->GetSiteInstance(),
              grandchild->current_frame_host()->GetSiteInstance());
  } else {
    EXPECT_EQ(root->current_frame_host()->GetSiteInstance(),
              child->current_frame_host()->GetSiteInstance());
    EXPECT_EQ(child->current_frame_host()->GetSiteInstance(),
              grandchild->current_frame_host()->GetSiteInstance());
  }
  EXPECT_EQ(root->current_frame_host()->GetSiteInstance(),
            grandchild->current_frame_host()->GetSiteInstance());
  EXPECT_EQ(root->current_frame_host()->GetProcess(),
            child->current_frame_host()->GetProcess());
  EXPECT_EQ(child->current_frame_host()->GetProcess(),
            grandchild->current_frame_host()->GetProcess());

  // Create an unrelated window, which will be in a new BrowsingInstance.
  // Ensure that foo.com becomes an isolated origin in that window.  A
  // cross-site bar.com subframe on foo.com should now become an OOPIF.
  Shell* second_shell = CreateBrowser();
  EXPECT_TRUE(NavigateToURL(second_shell, foo_url));

  FrameTreeNode* second_root =
      static_cast<WebContentsImpl*>(second_shell->web_contents())
          ->GetPrimaryFrameTree()
          .root();
  FrameTreeNode* second_child = second_root->child_at(0);

  NavigateIframeToURL(second_shell->web_contents(), "test_iframe", bar_url);
  scoped_refptr<SiteInstance> foo_instance =
      second_root->current_frame_host()->GetSiteInstance();
  EXPECT_NE(foo_instance,
            second_child->current_frame_host()->GetSiteInstance());
  EXPECT_NE(second_root->current_frame_host()->GetProcess(),
            second_child->current_frame_host()->GetProcess());

  // Now try the reverse: ensure that when bar.com embeds foo.com, foo.com
  // becomes an OOPIF.
  EXPECT_TRUE(NavigateToURL(second_shell, bar_with_foo_url));

  // We should've swapped processes in the main frame, since we navigated from
  // (isolated) foo.com to (non-isolated) bar.com.
  EXPECT_NE(foo_instance, second_root->current_frame_host()->GetSiteInstance());

  // Ensure the new foo.com subframe is cross-process.
  second_child = second_root->child_at(0);
  EXPECT_NE(second_root->current_frame_host()->GetSiteInstance(),
            second_child->current_frame_host()->GetSiteInstance());
  EXPECT_NE(second_root->current_frame_host()->GetProcess(),
            second_child->current_frame_host()->GetProcess());
}

// Check that dynamically added isolated origins take effect for future
// BrowsingInstances only, focusing on various main frame navigations.
IN_PROC_BROWSER_TEST_F(DynamicIsolatedOriginTest, MainFrameNavigations) {
  // This test is designed to run without strict site isolation.
  if (AreAllSitesIsolatedForTesting()) {
    return;
  }

  // Create three windows on a non-isolated origin.
  GURL foo_url(embedded_test_server()->GetURL("foo.com", "/title1.html"));
  EXPECT_TRUE(NavigateToURL(shell(), foo_url));

  Shell* shell2 = CreateBrowser();
  EXPECT_TRUE(NavigateToURL(shell2, foo_url));

  Shell* shell3 = CreateBrowser();
  EXPECT_TRUE(NavigateToURL(shell3, foo_url));

  // Create window.open popups in all three windows, which would prevent a
  // BrowsingInstance swap on renderer-initiated navigations to newly isolated
  // origins in these windows.
  OpenPopup(shell(), foo_url, "");
  OpenPopup(shell2, GURL(url::kAboutBlankURL), "");
  OpenPopup(shell3, embedded_test_server()->GetURL("baz.com", "/title1.html"),
            "");

  // Start isolating bar.com.
  GURL bar_url(embedded_test_server()->GetURL("bar.com", "/title2.html"));
  auto* policy = ChildProcessSecurityPolicyImpl::GetInstance();
  policy->AddFutureIsolatedOrigins({url::Origin::Create(bar_url)},
                                   IsolatedOriginSource::TEST);

  // Do a renderer-initiated navigation in each of the existing three windows.
  // None of them should swap to a new process, since bar.com shouldn't be
  // isolated in those older BrowsingInstances.
  int old_process_id =
      web_contents()->GetPrimaryMainFrame()->GetProcess()->GetID();
  EXPECT_TRUE(NavigateToURLFromRenderer(shell(), bar_url));
  EXPECT_EQ(old_process_id,
            web_contents()->GetPrimaryMainFrame()->GetProcess()->GetID());

  old_process_id =
      shell2->web_contents()->GetPrimaryMainFrame()->GetProcess()->GetID();
  EXPECT_TRUE(NavigateToURLFromRenderer(shell2, bar_url));
  EXPECT_EQ(
      old_process_id,
      shell2->web_contents()->GetPrimaryMainFrame()->GetProcess()->GetID());

  old_process_id =
      shell3->web_contents()->GetPrimaryMainFrame()->GetProcess()->GetID();
  EXPECT_TRUE(NavigateToURLFromRenderer(shell3, bar_url));
  EXPECT_EQ(
      old_process_id,
      shell3->web_contents()->GetPrimaryMainFrame()->GetProcess()->GetID());

  // Now try the same in a new window and BrowsingInstance, and ensure that the
  // navigation to bar.com swaps processes in that case.
  Shell* shell4 = CreateBrowser();
  EXPECT_TRUE(NavigateToURL(shell4, foo_url));

  old_process_id =
      shell4->web_contents()->GetPrimaryMainFrame()->GetProcess()->GetID();
  EXPECT_TRUE(NavigateToURLFromRenderer(shell4, bar_url));
  EXPECT_NE(
      old_process_id,
      shell4->web_contents()->GetPrimaryMainFrame()->GetProcess()->GetID());

  // Go back to foo.com in window 1, ensuring this stays in the same process.
  {
    old_process_id =
        web_contents()->GetPrimaryMainFrame()->GetProcess()->GetID();
    TestNavigationObserver back_observer(web_contents());
    web_contents()->GetController().GoBack();
    back_observer.Wait();
    EXPECT_EQ(old_process_id,
              web_contents()->GetPrimaryMainFrame()->GetProcess()->GetID());
  }

  // Go back to foo.com in window 4, ensuring this swaps processes.
  {
    old_process_id =
        shell4->web_contents()->GetPrimaryMainFrame()->GetProcess()->GetID();
    TestNavigationObserver back_observer(shell4->web_contents());
    shell4->web_contents()->GetController().GoBack();
    back_observer.Wait();
    EXPECT_NE(
        old_process_id,
        shell4->web_contents()->GetPrimaryMainFrame()->GetProcess()->GetID());
  }
}

// Check that dynamically added isolated origins do not prevent older processes
// for the same origin from accessing cookies.
IN_PROC_BROWSER_TEST_F(DynamicIsolatedOriginTest, OldProcessCanAccessCookies) {
  // This test is designed to run without strict site isolation.
  if (AreAllSitesIsolatedForTesting()) {
    return;
  }

  GURL foo_url(embedded_test_server()->GetURL("foo.com", "/title1.html"));
  EXPECT_TRUE(NavigateToURL(shell(), foo_url));
  FrameTreeNode* root = web_contents()->GetPrimaryFrameTree().root();

  // Since foo.com isn't isolated yet, its process lock should allow any site.
  auto* policy = ChildProcessSecurityPolicyImpl::GetInstance();
  EXPECT_TRUE(root->current_frame_host()
                  ->GetProcess()
                  ->GetProcessLock()
                  .allows_any_site());

  // Start isolating foo.com.
  policy->AddFutureIsolatedOrigins({url::Origin::Create(foo_url)},
                                   IsolatedOriginSource::TEST);

  // Create an unrelated window, which will be in a new BrowsingInstance.
  // foo.com will become an isolated origin in that window.
  Shell* second_shell = CreateBrowser();
  EXPECT_TRUE(NavigateToURL(second_shell, foo_url));
  FrameTreeNode* second_root =
      static_cast<WebContentsImpl*>(second_shell->web_contents())
          ->GetPrimaryFrameTree()
          .root();

  // The new window's process should be locked to "foo.com".
  int isolated_foo_com_process_id =
      second_root->current_frame_host()->GetProcess()->GetID();
  EXPECT_EQ(ProcessLockFromUrl("http://foo.com"),
            policy->GetProcessLock(isolated_foo_com_process_id));

  // Make sure both old and new foo.com processes can access cookies without
  // renderer kills.
  EXPECT_TRUE(ExecJs(root, "document.cookie = 'foo=bar';"));
  EXPECT_EQ("foo=bar", EvalJs(root, "document.cookie"));
  EXPECT_TRUE(ExecJs(second_root, "document.cookie = 'foo=bar';"));
  EXPECT_EQ("foo=bar", EvalJs(second_root, "document.cookie"));

  // Navigate to sub.foo.com in `second_shell`, staying in same
  // BrowsingInstance.  This should stay in the same process.
  GURL sub_foo_url(
      embedded_test_server()->GetURL("sub.foo.com", "/title1.html"));
  EXPECT_TRUE(NavigateToURLInSameBrowsingInstance(second_shell, sub_foo_url));
  EXPECT_EQ(isolated_foo_com_process_id,
            second_root->current_frame_host()->GetProcess()->GetID());

  // Now, start isolating sub.foo.com.
  policy->AddFutureIsolatedOrigins({url::Origin::Create(sub_foo_url)},
                                   IsolatedOriginSource::TEST);

  // Make sure the process locked to foo.com, which currently has sub.foo.com
  // committed in it, can still access sub.foo.com cookies.
  EXPECT_TRUE(ExecJs(second_root, "document.cookie = 'foo=baz';"));
  EXPECT_EQ("foo=baz", EvalJs(second_root, "document.cookie"));

  // Now, navigate to sub.foo.com in a new BrowsingInstance.  This should go
  // into a new process, locked to sub.foo.com.
  // TODO(alexmos): navigating to bar.com prior to navigating to sub.foo.com is
  // currently needed since we only swap BrowsingInstances on cross-site
  // address bar navigations.  We should look into swapping BrowsingInstances
  // even on same-site browser-initiated navigations, in cases where the sites
  // change due to a dynamically isolated origin.
  EXPECT_TRUE(NavigateToURL(
      second_shell, embedded_test_server()->GetURL("bar.com", "/title2.html")));
  EXPECT_TRUE(NavigateToURL(second_shell, sub_foo_url));
  EXPECT_NE(isolated_foo_com_process_id,
            second_root->current_frame_host()->GetProcess()->GetID());
  EXPECT_EQ(ProcessLockFromUrl("http://sub.foo.com"),
            second_root->current_frame_host()->GetProcess()->GetProcessLock());

  // Make sure that process can also access sub.foo.com cookies.
  EXPECT_TRUE(ExecJs(second_root, "document.cookie = 'foo=qux';"));
  EXPECT_EQ("foo=qux", EvalJs(second_root, "document.cookie"));
}

// Verify that when isolating sub.foo.com dynamically, foo.com and sub.foo.com
// start to be treated as cross-site for process model decisions.
IN_PROC_BROWSER_TEST_F(DynamicIsolatedOriginTest, IsolatedSubdomain) {
  // This test is designed to run without strict site isolation.
  if (AreAllSitesIsolatedForTesting()) {
    return;
  }

  GURL foo_url(
      embedded_test_server()->GetURL("foo.com", "/page_with_iframe.html"));
  EXPECT_TRUE(NavigateToURL(shell(), foo_url));

  // Start isolating sub.foo.com.
  GURL sub_foo_url(
      embedded_test_server()->GetURL("sub.foo.com", "/title1.html"));
  auto* policy = ChildProcessSecurityPolicyImpl::GetInstance();
  policy->AddFutureIsolatedOrigins({url::Origin::Create(sub_foo_url)},
                                   IsolatedOriginSource::TEST);

  // Navigate to foo.com and then to sub.foo.com in a new BrowsingInstance.
  // foo.com and sub.foo.com should now be considered cross-site for the
  // purposes of process assignment, and we should swap processes.
  Shell* new_shell = CreateBrowser();
  EXPECT_TRUE(NavigateToURL(new_shell, foo_url));
  int initial_process_id =
      new_shell->web_contents()->GetPrimaryMainFrame()->GetProcess()->GetID();
  EXPECT_TRUE(NavigateToURLFromRenderer(new_shell, sub_foo_url));
  EXPECT_NE(
      initial_process_id,
      new_shell->web_contents()->GetPrimaryMainFrame()->GetProcess()->GetID());

  // Repeat this, but now navigate a subframe on foo.com to sub.foo.com and
  // ensure that it is rendered in an OOPIF.
  new_shell = CreateBrowser();
  EXPECT_TRUE(NavigateToURL(new_shell, foo_url));
  NavigateIframeToURL(new_shell->web_contents(), "test_iframe", sub_foo_url);
  FrameTreeNode* root = static_cast<WebContentsImpl*>(new_shell->web_contents())
                            ->GetPrimaryFrameTree()
                            .root();
  FrameTreeNode* child = root->child_at(0);

  EXPECT_NE(root->current_frame_host()->GetSiteInstance(),
            child->current_frame_host()->GetSiteInstance());
  EXPECT_NE(root->current_frame_host()->GetProcess(),
            child->current_frame_host()->GetProcess());
}

// Check that when an isolated origin takes effect in BrowsingInstance 1, a new
// BrowsingInstance 2, which reuses an old process from BrowsingInstance 1 for
// its main frame, still applies the isolated origin to its subframe.  This
// demonstrates that isolated origins can't be scoped purely based on process
// IDs.
IN_PROC_BROWSER_TEST_F(DynamicIsolatedOriginTest,
                       NewBrowsingInstanceInOldProcess) {
  // This test is designed to run without strict site isolation.
  if (AreAllSitesIsolatedForTesting()) {
    return;
  }

  // Force process reuse for main frames in new BrowsingInstances.
  RenderProcessHost::SetMaxRendererProcessCount(1);

  // Start on a non-isolated origin with same-site iframe.
  GURL foo_url(https_server()->GetURL("foo.com", "/page_with_iframe.html"));
  EXPECT_TRUE(NavigateToURL(shell(), foo_url));

  FrameTreeNode* root = web_contents()->GetPrimaryFrameTree().root();
  FrameTreeNode* child = root->child_at(0);

  // Navigate iframe cross-site.
  GURL bar_url(https_server()->GetURL("bar.com", "/title1.html"));
  NavigateIframeToURL(web_contents(), "test_iframe", bar_url);
  EXPECT_EQ(child->current_url(), bar_url);

  // The iframe should not be in an OOPIF yet.
  if (AreStrictSiteInstancesEnabled()) {
    EXPECT_NE(root->current_frame_host()->GetSiteInstance(),
              child->current_frame_host()->GetSiteInstance());

  } else {
    EXPECT_EQ(root->current_frame_host()->GetSiteInstance(),
              child->current_frame_host()->GetSiteInstance());
  }
  EXPECT_EQ(root->current_frame_host()->GetProcess(),
            child->current_frame_host()->GetProcess());

  // Start isolating bar.com.
  auto* policy = ChildProcessSecurityPolicyImpl::GetInstance();
  policy->AddFutureIsolatedOrigins({url::Origin::Create(bar_url)},
                                   IsolatedOriginSource::TEST);

  // Open a new window in a new BrowsingInstance.  Navigate to foo.com and
  // check that the old foo.com process is reused.
  Shell* new_shell = CreateBrowser();
  EXPECT_TRUE(NavigateToURL(new_shell, foo_url));
  FrameTreeNode* new_root =
      static_cast<WebContentsImpl*>(new_shell->web_contents())
          ->GetPrimaryFrameTree()
          .root();
  FrameTreeNode* new_child = new_root->child_at(0);

  EXPECT_EQ(new_root->current_frame_host()->GetProcess(),
            root->current_frame_host()->GetProcess());
  EXPECT_NE(new_root->current_frame_host()->GetSiteInstance(),
            root->current_frame_host()->GetSiteInstance());
  EXPECT_FALSE(
      new_root->current_frame_host()->GetSiteInstance()->IsRelatedSiteInstance(
          root->current_frame_host()->GetSiteInstance()));

  // Navigate iframe in the second window to bar.com, and check that it becomes
  // an OOPIF in its own process.
  NavigateIframeToURL(new_shell->web_contents(), "test_iframe", bar_url);
  EXPECT_EQ(new_child->current_url(), bar_url);

  EXPECT_NE(new_child->current_frame_host()->GetProcess(),
            new_root->current_frame_host()->GetProcess());
  EXPECT_NE(new_child->current_frame_host()->GetProcess(),
            root->current_frame_host()->GetProcess());
  EXPECT_NE(new_child->current_frame_host()->GetProcess(),
            child->current_frame_host()->GetProcess());

  EXPECT_NE(new_child->current_frame_host()->GetSiteInstance(),
            new_root->current_frame_host()->GetSiteInstance());
  EXPECT_NE(new_child->current_frame_host()->GetSiteInstance(),
            child->current_frame_host()->GetSiteInstance());

  // The old foo.com process should still be able to access bar.com data,
  // since it isn't locked to a specific site.
  int old_process_id = root->current_frame_host()->GetProcess()->GetID();
  EXPECT_TRUE(policy->CanAccessDataForOrigin(old_process_id,
                                             url::Origin::Create(bar_url)));

  // In particular, make sure the bar.com iframe in the old foo.com process can
  // still access bar.com cookies.
  EXPECT_TRUE(
      ExecJs(child, "document.cookie = 'foo=bar;SameSite=None;Secure';"));
  EXPECT_EQ("foo=bar", EvalJs(child, "document.cookie"));

  // Make sure the BrowsingInstanceId is cleaned up immediately.
  policy->SetBrowsingInstanceCleanupDelayForTesting(0);

  // Now close the first window.  This destroys the first BrowsingInstance and
  // leaves only the newer BrowsingInstance (with a foo.com main frame) in the
  // old process.
  shell()->Close();

  // Now that the process only contains a BrowsingInstance where bar.com is
  // considered isolated and cannot reuse the old process, it should lose access
  // to bar.com's data due to citadel enforcement in CanAccessDataForOrigin.
  EXPECT_FALSE(policy->CanAccessDataForOrigin(old_process_id,
                                              url::Origin::Create(bar_url)));
}

// Verify that a process locked to foo.com is not reused for a navigation to
// foo.com that does not require a dedicated process.  See
// https://crbug.com/950453.
IN_PROC_BROWSER_TEST_F(DynamicIsolatedOriginTest,
                       LockedProcessNotReusedForNonisolatedSameSiteNavigation) {
  // This test is designed to run without strict site isolation.
  if (AreAllSitesIsolatedForTesting()) {
    return;
  }

  // Set the process limit to 1.
  RenderProcessHost::SetMaxRendererProcessCount(1);

  // Start on a non-isolated foo.com URL.
  GURL foo_url(embedded_test_server()->GetURL("foo.com", "/title1.html"));
  EXPECT_TRUE(NavigateToURL(shell(), foo_url));

  // Navigate to a different isolated origin and wait for the original foo.com
  // process to shut down.  Note that the foo.com SiteInstance will stick
  // around in session history.
  RenderProcessHostWatcher foo_process_observer(
      web_contents()->GetPrimaryMainFrame()->GetProcess(),
      RenderProcessHostWatcher::WATCH_FOR_HOST_DESTRUCTION);

  // Disable the BackForwardCache to ensure the old process is going to be
  // released.
  DisableBackForwardCacheForTesting(web_contents(),
                                    BackForwardCache::TEST_REQUIRES_NO_CACHING);

  GURL isolated_bar_url(
      embedded_test_server()->GetURL("isolated.bar.com", "/title1.html"));
  EXPECT_TRUE(NavigateToURL(shell(), isolated_bar_url));
  foo_process_observer.Wait();
  EXPECT_TRUE(foo_process_observer.did_exit_normally());

  // Start isolating foo.com.
  auto* policy = ChildProcessSecurityPolicyImpl::GetInstance();
  policy->AddFutureIsolatedOrigins({url::Origin::Create(foo_url)},
                                   IsolatedOriginSource::TEST);

  // Create a new window, forcing a new BrowsingInstance, and navigate it to
  // foo.com, which will spin up a process locked to foo.com.
  Shell* new_shell = CreateBrowser();
  EXPECT_TRUE(NavigateToURL(new_shell, foo_url));
  RenderProcessHost* new_process =
      new_shell->web_contents()->GetPrimaryMainFrame()->GetProcess();
  EXPECT_EQ(ProcessLockFromUrl("http://foo.com"),
            new_process->GetProcessLock());

  // Go to foo.com in the older first tab, where foo.com does not require a
  // dedicated process.  Ensure that the existing locked foo.com process is
  // *not* reused in that case (if that were the case, LockProcessIfNeeded
  // would trigger a CHECK here).  Using a history navigation here ensures that
  // the SiteInstance (from session history) will have a foo.com site URL,
  // rather than a default site URL, since this case isn't yet handled by the
  // default SiteInstance (see crbug.com/787576).
  TestNavigationObserver observer(web_contents());
  web_contents()->GetController().GoBack();
  observer.Wait();
  EXPECT_NE(web_contents()->GetPrimaryMainFrame()->GetProcess(), new_process);
}

// Checks that isolated origins can be added only for a specific profile,
// and that they don't apply to other profiles.
IN_PROC_BROWSER_TEST_F(DynamicIsolatedOriginTest, PerProfileIsolation) {
  // This test is designed to run without strict site isolation.
  if (AreAllSitesIsolatedForTesting()) {
    return;
  }

  // Create a browser in a different profile.
  BrowserContext* main_context = shell()->web_contents()->GetBrowserContext();
  Shell* other_shell = CreateOffTheRecordBrowser();
  BrowserContext* other_context =
      other_shell->web_contents()->GetBrowserContext();
  ASSERT_NE(main_context, other_context);

  // Start on bar.com in both browsers.
  GURL bar_url(embedded_test_server()->GetURL("bar.com", "/title1.html"));
  EXPECT_TRUE(NavigateToURL(shell(), bar_url));
  EXPECT_TRUE(NavigateToURL(other_shell, bar_url));

  // Start isolating foo.com in `other_context` only.
  GURL foo_url(
      embedded_test_server()->GetURL("foo.com", "/page_with_iframe.html"));
  auto* policy = ChildProcessSecurityPolicyImpl::GetInstance();
  policy->AddFutureIsolatedOrigins({url::Origin::Create(foo_url)},
                                   IsolatedOriginSource::TEST, other_context);

  // Verify that foo.com is indeed isolated in `other_shell`, by navigating to
  // it in a new BrowsingInstance and checking that a bar.com subframe becomes
  // an OOPIF.
  EXPECT_TRUE(NavigateToURL(other_shell, foo_url));
  WebContentsImpl* other_contents =
      static_cast<WebContentsImpl*>(other_shell->web_contents());
  NavigateIframeToURL(other_contents, "test_iframe", bar_url);
  FrameTreeNode* root = other_contents->GetPrimaryFrameTree().root();
  FrameTreeNode* child = root->child_at(0);
  EXPECT_EQ(child->current_url(), bar_url);
  EXPECT_NE(root->current_frame_host()->GetSiteInstance(),
            child->current_frame_host()->GetSiteInstance());
  EXPECT_NE(root->current_frame_host()->GetProcess(),
            child->current_frame_host()->GetProcess());

  // Verify that foo.com is *not* isolated in the regular shell, due to a
  // different profile.
  EXPECT_TRUE(NavigateToURL(shell(), foo_url));
  NavigateIframeToURL(web_contents(), "test_iframe", bar_url);
  root = web_contents()->GetPrimaryFrameTree().root();
  child = root->child_at(0);
  EXPECT_EQ(child->current_url(), bar_url);
  if (AreStrictSiteInstancesEnabled()) {
    EXPECT_NE(root->current_frame_host()->GetSiteInstance(),
              child->current_frame_host()->GetSiteInstance());
  } else {
    EXPECT_EQ(root->current_frame_host()->GetSiteInstance(),
              child->current_frame_host()->GetSiteInstance());
  }
  EXPECT_EQ(root->current_frame_host()->GetProcess(),
            child->current_frame_host()->GetProcess());
}

// Check that a dynamically added isolated origin can take effect on the next
// main frame navigation by forcing a BrowsingInstance swap, in the case that
// there are no script references to the frame being navigated.
IN_PROC_BROWSER_TEST_F(DynamicIsolatedOriginTest, ForceBrowsingInstanceSwap) {
  // This test is designed to run without strict site isolation.
  if (AreAllSitesIsolatedForTesting()) {
    return;
  }

  // Navigate to a non-isolated page with a cross-site iframe.  The frame
  // shouldn't be in an OOPIF.
  GURL foo_url(embedded_test_server()->GetURL(
      "foo.com", "/cross_site_iframe_factory.html?foo.com(bar.com)"));
  EXPECT_TRUE(NavigateToURL(shell(), foo_url));
  FrameTreeNode* root = web_contents()->GetPrimaryFrameTree().root();
  FrameTreeNode* child = root->child_at(0);
  scoped_refptr<SiteInstance> first_instance =
      root->current_frame_host()->GetSiteInstance();

  if (AreStrictSiteInstancesEnabled()) {
    EXPECT_NE(first_instance, child->current_frame_host()->GetSiteInstance());
  } else {
    EXPECT_EQ(first_instance, child->current_frame_host()->GetSiteInstance());
  }
  EXPECT_EQ(root->current_frame_host()->GetProcess(),
            child->current_frame_host()->GetProcess());
  auto* policy = ChildProcessSecurityPolicyImpl::GetInstance();
  EXPECT_TRUE(first_instance->GetProcess()->GetProcessLock().allows_any_site());

  // Start isolating foo.com.
  BrowserContext* context = shell()->web_contents()->GetBrowserContext();
  policy->AddFutureIsolatedOrigins({url::Origin::Create(foo_url)},
                                   IsolatedOriginSource::TEST, context);

  // Try navigating to another foo URL.
  GURL foo2_url(embedded_test_server()->GetURL(
      "foo.com", "/cross_site_iframe_factory.html?foo.com(baz.com)"));
  EXPECT_TRUE(NavigateToURL(shell(), foo2_url));

  // Verify that this navigation ended up in a dedicated process, and that we
  // swapped BrowsingInstances in the process.
  scoped_refptr<SiteInstance> second_instance =
      root->current_frame_host()->GetSiteInstance();
  EXPECT_NE(first_instance, second_instance);
  EXPECT_FALSE(first_instance->IsRelatedSiteInstance(second_instance.get()));
  EXPECT_NE(first_instance->GetProcess(), second_instance->GetProcess());
  EXPECT_EQ(ProcessLockFromUrl("http://foo.com"),
            second_instance->GetProcess()->GetProcessLock());

  // The frame on that page should now be an OOPIF.
  child = root->child_at(0);
  EXPECT_NE(second_instance, child->current_frame_host()->GetSiteInstance());
  EXPECT_NE(root->current_frame_host()->GetProcess(),
            child->current_frame_host()->GetProcess());
}

// Same as the test above, but using a renderer-initiated navigation.  Check
// that a dynamically added isolated origin can take effect on the next main
// frame navigation by forcing a BrowsingInstance swap, in the case that there
// are no script references to the frame being navigated.
IN_PROC_BROWSER_TEST_F(DynamicIsolatedOriginTest,
                       ForceBrowsingInstanceSwap_RendererInitiated) {
  // This test is designed to run without strict site isolation.
  if (AreAllSitesIsolatedForTesting()) {
    return;
  }

  // Navigate to a foo.com page.
  GURL foo_url(embedded_test_server()->GetURL("foo.com", "/title1.html"));
  EXPECT_TRUE(NavigateToURL(shell(), foo_url));
  FrameTreeNode* root = web_contents()->GetPrimaryFrameTree().root();
  scoped_refptr<SiteInstance> first_instance =
      root->current_frame_host()->GetSiteInstance();
  EXPECT_FALSE(first_instance->RequiresDedicatedProcess());
  auto* policy = ChildProcessSecurityPolicyImpl::GetInstance();
  EXPECT_TRUE(first_instance->GetProcess()->GetProcessLock().allows_any_site());

  // Set a sessionStorage value, to sanity check that foo.com's session storage
  // will still be accessible after the BrowsingInstance swap.
  EXPECT_TRUE(ExecJs(root, "window.sessionStorage['foo'] = 'bar';"));

  // Start isolating foo.com.
  BrowserContext* context = shell()->web_contents()->GetBrowserContext();
  policy->AddFutureIsolatedOrigins({url::Origin::Create(foo_url)},
                                   IsolatedOriginSource::TEST, context);

  // Do a renderer-initiated navigation to another foo URL.
  GURL foo2_url(embedded_test_server()->GetURL(
      "foo.com", "/cross_site_iframe_factory.html?foo.com(baz.com)"));
  EXPECT_TRUE(NavigateToURLFromRenderer(shell(), foo2_url));

  // Verify that this navigation ended up in a dedicated process, and that we
  // swapped BrowsingInstances in the process.
  scoped_refptr<SiteInstance> second_instance =
      root->current_frame_host()->GetSiteInstance();
  EXPECT_NE(first_instance, second_instance);
  EXPECT_FALSE(first_instance->IsRelatedSiteInstance(second_instance.get()));
  EXPECT_NE(first_instance->GetProcess(), second_instance->GetProcess());
  EXPECT_EQ(ProcessLockFromUrl("http://foo.com"),
            second_instance->GetProcess()->GetProcessLock());

  // The frame on that page should be an OOPIF.
  FrameTreeNode* child = root->child_at(0);
  EXPECT_NE(second_instance, child->current_frame_host()->GetSiteInstance());
  EXPECT_NE(root->current_frame_host()->GetProcess(),
            child->current_frame_host()->GetProcess());

  // Verify that the isolated foo.com page can still access session storage set
  // by the previous foo.com page.
  EXPECT_EQ("bar", EvalJs(root, "window.sessionStorage['foo']"));
}

IN_PROC_BROWSER_TEST_F(DynamicIsolatedOriginTest,
                       DontForceBrowsingInstanceSwapWhenScriptReferencesExist) {
  // This test is designed to run without strict site isolation.
  if (AreAllSitesIsolatedForTesting()) {
    return;
  }

  // Navigate to a page that won't be in a dedicated process.
  GURL foo_url(embedded_test_server()->GetURL("foo.com", "/title1.html"));
  EXPECT_TRUE(NavigateToURL(shell(), foo_url));
  FrameTreeNode* root = web_contents()->GetPrimaryFrameTree().root();
  scoped_refptr<SiteInstance> first_instance =
      root->current_frame_host()->GetSiteInstance();
  EXPECT_FALSE(first_instance->RequiresDedicatedProcess());

  // Start isolating foo.com.
  BrowserContext* context = shell()->web_contents()->GetBrowserContext();
  auto* policy = ChildProcessSecurityPolicyImpl::GetInstance();
  policy->AddFutureIsolatedOrigins({url::Origin::Create(foo_url)},
                                   IsolatedOriginSource::TEST, context);

  // Open a popup.
  GURL popup_url(embedded_test_server()->GetURL("a.com", "/title1.html"));
  OpenPopup(shell(), popup_url, "");

  // Try navigating the main frame to another foo URL.
  GURL foo2_url(embedded_test_server()->GetURL("foo.com", "/title2.html"));
  EXPECT_TRUE(NavigateToURLFromRenderer(shell(), foo2_url));

  // This navigation should not end up in a dedicated process.  The popup
  // should prevent the BrowsingInstance swap heuristic from applying, since it
  // should still be able to communicate with the opener after the navigation.
  EXPECT_EQ(first_instance, root->current_frame_host()->GetSiteInstance());
  EXPECT_FALSE(first_instance->RequiresDedicatedProcess());
  EXPECT_TRUE(first_instance->GetProcess()->GetProcessLock().allows_any_site());
}

// This test ensures that when a page becomes isolated in the middle of
// creating and navigating a new window, the new window prevents a
// BrowsingInstance swap.
IN_PROC_BROWSER_TEST_F(
    DynamicIsolatedOriginTest,
    DontForceBrowsingInstanceSwapWithPendingNavigationInNewWindow) {
  // This test is designed to run without strict site isolation.
  if (AreAllSitesIsolatedForTesting()) {
    return;
  }

  // Navigate to a page that won't be in a dedicated process.
  GURL foo_url(embedded_test_server()->GetURL("foo.com", "/title1.html"));
  EXPECT_TRUE(NavigateToURL(shell(), foo_url));
  FrameTreeNode* root = web_contents()->GetPrimaryFrameTree().root();
  scoped_refptr<SiteInstance> first_instance =
      root->current_frame_host()->GetSiteInstance();
  EXPECT_FALSE(first_instance->RequiresDedicatedProcess());

  // Open and start navigating a popup to a URL that never finishes loading.
  GURL popup_url(embedded_test_server()->GetURL("a.com", "/hung"));
  EXPECT_TRUE(ExecJs(root, JsReplace("window.open($1);", popup_url)));

  // Start isolating foo.com.
  BrowserContext* context = shell()->web_contents()->GetBrowserContext();
  auto* policy = ChildProcessSecurityPolicyImpl::GetInstance();
  policy->AddFutureIsolatedOrigins({url::Origin::Create(foo_url)},
                                   IsolatedOriginSource::TEST, context);

  // Navigate the main frame to another foo URL.
  GURL foo2_url(embedded_test_server()->GetURL("foo.com", "/title2.html"));
  EXPECT_TRUE(NavigateToURLFromRenderer(shell(), foo2_url));

  // This navigation should not end up in a dedicated process.  The pending
  // navigation in the popup should prevent the BrowsingInstance swap heuristic
  // from applying, since it should still be able to communicate with the
  // opener after the navigation.
  EXPECT_EQ(first_instance, root->current_frame_host()->GetSiteInstance());
  EXPECT_FALSE(first_instance->RequiresDedicatedProcess());
  EXPECT_TRUE(first_instance->GetProcess()->GetProcessLock().allows_any_site());
}

class IsolatedOriginTestWithStrictSiteInstances : public IsolatedOriginTest {
 public:
  IsolatedOriginTestWithStrictSiteInstances() {
    scoped_feature_list_.InitAndEnableFeature(
        features::kProcessSharingWithStrictSiteInstances);
  }
  ~IsolatedOriginTestWithStrictSiteInstances() override = default;

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

  void SetUpCommandLine(base::CommandLine* command_line) override {
    IsolatedOriginTest::SetUpCommandLine(command_line);
    command_line->AppendSwitch(switches::kDisableSiteIsolation);

    if (AreAllSitesIsolatedForTesting()) {
      LOG(WARNING) << "This test should be run without strict site isolation. "
                   << "It does nothing when --site-per-process is specified.";
    }
  }

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

IN_PROC_BROWSER_TEST_F(IsolatedOriginTestWithStrictSiteInstances,
                       NonIsolatedFramesCanShareDefaultProcess) {
  // This test is designed to run without strict site isolation.
  if (AreAllSitesIsolatedForTesting()) {
    return;
  }

  GURL top_url(
      embedded_test_server()->GetURL("/frame_tree/page_with_two_frames.html"));
  ASSERT_FALSE(IsIsolatedOrigin(url::Origin::Create(top_url)));
  EXPECT_TRUE(NavigateToURL(shell(), top_url));

  FrameTreeNode* root = web_contents()->GetPrimaryFrameTree().root();
  FrameTreeNode* child1 = root->child_at(0);
  FrameTreeNode* child2 = root->child_at(1);

  GURL bar_url(embedded_test_server()->GetURL("www.bar.com", "/title3.html"));
  ASSERT_FALSE(IsIsolatedOrigin(url::Origin::Create(bar_url)));
  {
    TestFrameNavigationObserver observer(child1);
    NavigationHandleObserver handle_observer(web_contents(), bar_url);
    EXPECT_TRUE(ExecJs(child1, "location.href = '" + bar_url.spec() + "';"));
    observer.Wait();
  }

  GURL baz_url(embedded_test_server()->GetURL("www.baz.com", "/title3.html"));
  ASSERT_FALSE(IsIsolatedOrigin(url::Origin::Create(baz_url)));
  {
    TestFrameNavigationObserver observer(child2);
    NavigationHandleObserver handle_observer(web_contents(), baz_url);
    EXPECT_TRUE(ExecJs(child2, "location.href = '" + baz_url.spec() + "';"));
    observer.Wait();
  }

  // All 3 frames are from different sites, so each should have its own
  // SiteInstance.
  EXPECT_NE(root->current_frame_host()->GetSiteInstance(),
            child1->current_frame_host()->GetSiteInstance());
  EXPECT_NE(root->current_frame_host()->GetSiteInstance(),
            child2->current_frame_host()->GetSiteInstance());
  EXPECT_NE(child1->current_frame_host()->GetSiteInstance(),
            child2->current_frame_host()->GetSiteInstance());
  EXPECT_EQ(
      " Site A ------------ proxies for B C\n"
      "   |--Site B ------- proxies for A C\n"
      "   +--Site C ------- proxies for A B\n"
      "Where A = http://127.0.0.1/\n"
      "      B = http://bar.com/\n"
      "      C = http://baz.com/",
      DepictFrameTree(*root));

  // But none are isolated, so all should share the default process for their
  // BrowsingInstance.
  RenderProcessHost* host = root->current_frame_host()->GetProcess();
  EXPECT_EQ(host, child1->current_frame_host()->GetProcess());
  EXPECT_EQ(host, child2->current_frame_host()->GetProcess());
  EXPECT_TRUE(host->GetProcessLock().allows_any_site());
}

// Creates a non-isolated main frame with an isolated child and non-isolated
// grandchild. With strict site isolation disabled and
// kProcessSharingWithStrictSiteInstances enabled, the main frame and the
// grandchild should be in the same process even though they have different
// SiteInstances.
IN_PROC_BROWSER_TEST_F(IsolatedOriginTestWithStrictSiteInstances,
                       IsolatedChildWithNonIsolatedGrandchild) {
  // This test is designed to run without strict site isolation.
  if (AreAllSitesIsolatedForTesting()) {
    return;
  }

  GURL top_url(
      embedded_test_server()->GetURL("www.foo.com", "/page_with_iframe.html"));
  ASSERT_FALSE(IsIsolatedOrigin(url::Origin::Create(top_url)));
  EXPECT_TRUE(NavigateToURL(shell(), top_url));

  GURL isolated_url(embedded_test_server()->GetURL("isolated.foo.com",
                                                   "/page_with_iframe.html"));
  ASSERT_TRUE(IsIsolatedOrigin(url::Origin::Create(isolated_url)));

  FrameTreeNode* root = web_contents()->GetPrimaryFrameTree().root();
  FrameTreeNode* child = root->child_at(0);

  NavigateIframeToURL(web_contents(), "test_iframe", isolated_url);
  EXPECT_EQ(child->current_url(), isolated_url);

  // Verify that the child frame is an OOPIF with a different SiteInstance.
  EXPECT_NE(web_contents()->GetSiteInstance(),
            child->current_frame_host()->GetSiteInstance());
  EXPECT_TRUE(child->current_frame_host()->IsCrossProcessSubframe());
  EXPECT_EQ(GURL("http://isolated.foo.com/"),
            child->current_frame_host()->GetSiteInstance()->GetSiteURL());

  // Verify that the isolated frame's subframe (which starts out at a relative
  // path) is kept in the isolated parent's SiteInstance.
  FrameTreeNode* grandchild = child->child_at(0);
  EXPECT_EQ(child->current_frame_host()->GetSiteInstance(),
            grandchild->current_frame_host()->GetSiteInstance());

  // Navigating the grandchild to www.bar.com should put it into the top
  // frame's process, but not its SiteInstance.
  GURL non_isolated_url(
      embedded_test_server()->GetURL("www.bar.com", "/title3.html"));
  ASSERT_FALSE(IsIsolatedOrigin(url::Origin::Create(non_isolated_url)));
  TestFrameNavigationObserver observer(grandchild);
  EXPECT_TRUE(
      ExecJs(grandchild, "location.href = '" + non_isolated_url.spec() + "';"));
  observer.Wait();
  EXPECT_EQ(non_isolated_url, grandchild->current_url());

  EXPECT_NE(root->current_frame_host()->GetSiteInstance(),
            grandchild->current_frame_host()->GetSiteInstance());
  EXPECT_NE(child->current_frame_host()->GetSiteInstance(),
            grandchild->current_frame_host()->GetSiteInstance());
  EXPECT_EQ(root->current_frame_host()->GetProcess(),
            grandchild->current_frame_host()->GetProcess());
  EXPECT_EQ(
      " Site A ------------ proxies for B C\n"
      "   +--Site B ------- proxies for A C\n"
      "        +--Site C -- proxies for A B\n"
      "Where A = http://foo.com/\n"
      "      B = http://isolated.foo.com/\n"
      "      C = http://bar.com/",
      DepictFrameTree(*root));
}

// Navigate a frame into and out of an isolated origin. This should not
// confuse BrowsingInstance into holding onto a stale default_process_.
IN_PROC_BROWSER_TEST_F(IsolatedOriginTestWithStrictSiteInstances,
                       SubframeNavigatesOutofIsolationThenToIsolation) {
  // This test is designed to run without strict site isolation.
  if (AreAllSitesIsolatedForTesting()) {
    return;
  }

  GURL isolated_url(embedded_test_server()->GetURL("isolated.foo.com",
                                                   "/page_with_iframe.html"));
  ASSERT_TRUE(IsIsolatedOrigin(url::Origin::Create(isolated_url)));
  EXPECT_TRUE(NavigateToURL(shell(), isolated_url));

  FrameTreeNode* root = web_contents()->GetPrimaryFrameTree().root();
  FrameTreeNode* child = root->child_at(0);
  EXPECT_EQ(web_contents()->GetSiteInstance(),
            child->current_frame_host()->GetSiteInstance());
  EXPECT_FALSE(child->current_frame_host()->IsCrossProcessSubframe());

  GURL non_isolated_url(
      embedded_test_server()->GetURL("www.foo.com", "/title3.html"));
  ASSERT_FALSE(IsIsolatedOrigin(url::Origin::Create(non_isolated_url)));
  NavigateIframeToURL(web_contents(), "test_iframe", non_isolated_url);
  EXPECT_EQ(child->current_url(), non_isolated_url);

  // Verify that the child frame is an OOPIF with a different SiteInstance.
  EXPECT_NE(web_contents()->GetSiteInstance(),
            child->current_frame_host()->GetSiteInstance());
  EXPECT_NE(root->current_frame_host()->GetProcess(),
            child->current_frame_host()->GetProcess());

  // Navigating the child to the isolated origin again.
  NavigateIframeToURL(web_contents(), "test_iframe", isolated_url);
  EXPECT_EQ(child->current_url(), isolated_url);
  EXPECT_EQ(web_contents()->GetSiteInstance(),
            child->current_frame_host()->GetSiteInstance());

  // And navigate out of the isolated origin one last time.
  NavigateIframeToURL(web_contents(), "test_iframe", non_isolated_url);
  EXPECT_EQ(child->current_url(), non_isolated_url);
  EXPECT_NE(web_contents()->GetSiteInstance(),
            child->current_frame_host()->GetSiteInstance());
  EXPECT_NE(root->current_frame_host()->GetProcess(),
            child->current_frame_host()->GetProcess());
  EXPECT_EQ(
      " Site A ------------ proxies for B\n"
      "   +--Site B ------- proxies for A\n"
      "Where A = http://isolated.foo.com/\n"
      "      B = http://foo.com/",
      DepictFrameTree(*root));
}

// Ensure a popup and its opener can go in the same process, even though
// they have different SiteInstances with kProcessSharingWithStrictSiteInstances
// enabled.
IN_PROC_BROWSER_TEST_F(IsolatedOriginTestWithStrictSiteInstances,
                       NonIsolatedPopup) {
  // This test is designed to run without strict site isolation.
  if (AreAllSitesIsolatedForTesting()) {
    return;
  }

  GURL foo_url(
      embedded_test_server()->GetURL("www.foo.com", "/page_with_iframe.html"));
  EXPECT_TRUE(NavigateToURL(shell(), foo_url));
  FrameTreeNode* root = web_contents()->GetPrimaryFrameTree().root();

  // Open a blank popup.
  ShellAddedObserver new_shell_observer;
  EXPECT_TRUE(ExecJs(root, "window.w = window.open();"));
  Shell* new_shell = new_shell_observer.GetShell();

  // Have the opener navigate the popup to a non-isolated origin.
  GURL isolated_url(
      embedded_test_server()->GetURL("www.bar.com", "/title1.html"));
  {
    TestNavigationManager manager(new_shell->web_contents(), isolated_url);
    EXPECT_TRUE(ExecJs(
        root, "window.w.location.href = '" + isolated_url.spec() + "';"));
    ASSERT_TRUE(manager.WaitForNavigationFinished());
  }

  // The popup and the opener should not share a SiteInstance, but should
  // end up in the same process.
  EXPECT_NE(new_shell->web_contents()->GetPrimaryMainFrame()->GetSiteInstance(),
            root->current_frame_host()->GetSiteInstance());
  EXPECT_EQ(root->current_frame_host()->GetProcess(),
            new_shell->web_contents()->GetPrimaryMainFrame()->GetProcess());
  EXPECT_EQ(
      " Site A ------------ proxies for B\n"
      "   +--Site A ------- proxies for B\n"
      "Where A = http://foo.com/\n"
      "      B = http://bar.com/",
      DepictFrameTree(*root));
  EXPECT_EQ(
      " Site A ------------ proxies for B\n"
      "Where A = http://bar.com/\n"
      "      B = http://foo.com/",
      DepictFrameTree(*static_cast<WebContentsImpl*>(new_shell->web_contents())
                           ->GetPrimaryFrameTree()
                           .root()));
}

class WildcardOriginIsolationTest : public IsolatedOriginTestBase {
 public:
  WildcardOriginIsolationTest() = default;
  ~WildcardOriginIsolationTest() override = default;

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

  void SetUpCommandLine(base::CommandLine* command_line) override {
    ASSERT_TRUE(embedded_test_server()->InitializeAndListen());

    std::string origin_list =
        MakeWildcard(embedded_test_server()->GetURL("isolated.foo.com", "/")) +
        "," + embedded_test_server()->GetURL("foo.com", "/").spec();

    command_line->AppendSwitchASCII(switches::kIsolateOrigins, origin_list);

    // This is needed for this test to run properly on platforms where
    //  --site-per-process isn't the default, such as Android.
    IsolateAllSitesForTesting(command_line);
  }

  void SetUpOnMainThread() override {
    host_resolver()->AddRule("*", "127.0.0.1");
    embedded_test_server()->StartAcceptingConnections();
  }

 private:
  const char* kAllSubdomainWildcard = "[*.]";

  // Calling GetURL() on the embedded test server will escape any '*' characters
  // into '%2A', so to create a wildcard origin they must be post-processed to
  // have the string '[*.]' inserted at the correct point.
  std::string MakeWildcard(GURL url) {
    DCHECK(url.is_valid());
    return url.scheme() + url::kStandardSchemeSeparator +
           kAllSubdomainWildcard + url.GetContent();
  }
};

IN_PROC_BROWSER_TEST_F(WildcardOriginIsolationTest, MainFrameNavigation) {
  GURL a_foo_url(embedded_test_server()->GetURL("a.foo.com", "/title1.html"));
  GURL b_foo_url(embedded_test_server()->GetURL("b.foo.com", "/title1.html"));
  GURL a_isolated_url(
      embedded_test_server()->GetURL("a.isolated.foo.com", "/title1.html"));
  GURL b_isolated_url(
      embedded_test_server()->GetURL("b.isolated.foo.com", "/title1.html"));

  EXPECT_TRUE(IsIsolatedOrigin(a_foo_url));
  EXPECT_TRUE(IsIsolatedOrigin(b_foo_url));
  EXPECT_TRUE(IsIsolatedOrigin(a_isolated_url));
  EXPECT_TRUE(IsIsolatedOrigin(b_isolated_url));

  // Navigate in the following order, all within the same shell:
  // 1. a_foo_url
  // 2. b_foo_url      -- check (1) and (2) have the same pids / instances (*)
  // 3. a_isolated_url
  // 4. b_isolated_url -- check (2), (3) and (4) have distinct pids / instances
  // 5. a_foo_url      -- check (4) and (5) have distinct pids / instances
  // 6. b_foo_url      -- check (5) and (6) have the same pids / instances (*)
  // (*) SiteInstances will be the same unless ProactivelySwapBrowsingInstances
  // is enabled for same-site navigations.
  EXPECT_TRUE(NavigateToURL(shell(), a_foo_url));
  int a_foo_pid =
      shell()->web_contents()->GetPrimaryMainFrame()->GetProcess()->GetID();
  scoped_refptr<SiteInstance> a_foo_instance =
      shell()->web_contents()->GetPrimaryMainFrame()->GetSiteInstance();

  EXPECT_TRUE(NavigateToURL(shell(), b_foo_url));
  int b_foo_pid =
      shell()->web_contents()->GetPrimaryMainFrame()->GetProcess()->GetID();
  scoped_refptr<SiteInstance> b_foo_instance =
      shell()->web_contents()->GetPrimaryMainFrame()->GetSiteInstance();

  // Check that hosts in the wildcard subdomain (but not the wildcard subdomain
  // itself) have their processes reused between navigation events.
  EXPECT_EQ(a_foo_pid, b_foo_pid);
  if (CanSameSiteMainFrameNavigationsChangeSiteInstances()) {
    EXPECT_NE(a_foo_instance, b_foo_instance);
  } else {
    EXPECT_EQ(a_foo_instance, b_foo_instance);
  }

  EXPECT_TRUE(NavigateToURL(shell(), a_isolated_url));
  int a_isolated_pid =
      shell()->web_contents()->GetPrimaryMainFrame()->GetProcess()->GetID();
  scoped_refptr<SiteInstance> a_isolated_instance =
      shell()->web_contents()->GetPrimaryMainFrame()->GetSiteInstance();

  EXPECT_TRUE(NavigateToURL(shell(), b_isolated_url));
  int b_isolated_pid =
      shell()->web_contents()->GetPrimaryMainFrame()->GetProcess()->GetID();
  scoped_refptr<SiteInstance> b_isolated_instance =
      shell()->web_contents()->GetPrimaryMainFrame()->GetSiteInstance();

  // Navigating from a non-wildcard domain to a wildcard domain should result in
  // a new process.
  EXPECT_NE(b_foo_pid, b_isolated_pid);
  EXPECT_NE(b_foo_instance, b_isolated_instance);

  // Navigating to another URL within the wildcard domain should always result
  // in a new process.
  EXPECT_NE(a_isolated_pid, b_isolated_pid);
  EXPECT_NE(a_isolated_instance, b_isolated_instance);

  EXPECT_TRUE(NavigateToURL(shell(), a_foo_url));
  a_foo_pid =
      shell()->web_contents()->GetPrimaryMainFrame()->GetProcess()->GetID();
  a_foo_instance =
      shell()->web_contents()->GetPrimaryMainFrame()->GetSiteInstance();

  EXPECT_TRUE(NavigateToURL(shell(), b_foo_url));
  b_foo_pid =
      shell()->web_contents()->GetPrimaryMainFrame()->GetProcess()->GetID();
  b_foo_instance =
      shell()->web_contents()->GetPrimaryMainFrame()->GetSiteInstance();

  // Navigating from the wildcard subdomain to the isolated subdomain should
  // produce a new pid.
  EXPECT_NE(a_foo_pid, b_isolated_pid);
  EXPECT_NE(a_foo_instance, b_isolated_instance);

  // Confirm that navigation events in the isolated domain behave the same as
  // before visiting the wildcard subdomain.
  EXPECT_EQ(a_foo_pid, b_foo_pid);
  if (CanSameSiteMainFrameNavigationsChangeSiteInstances()) {
    EXPECT_NE(a_foo_instance, b_foo_instance);
  } else {
    EXPECT_EQ(a_foo_instance, b_foo_instance);
  }
}

IN_PROC_BROWSER_TEST_F(WildcardOriginIsolationTest, SubFrameNavigation) {
  GURL url = embedded_test_server()->GetURL(
      "a.foo.com",
      "/cross_site_iframe_factory.html?a.foo.com("
      "isolated.foo.com,b.foo.com("
      "b.isolated.foo.com,a.foo.com,a.isolated.com))");

  EXPECT_TRUE(NavigateToURL(shell(), url));
  FrameTreeNode* root = web_contents()->GetPrimaryFrameTree().root();

  EXPECT_EQ(
      " Site A ------------ proxies for B C D\n"
      "   |--Site B ------- proxies for A C D\n"
      "   +--Site A ------- proxies for B C D\n"
      "        |--Site C -- proxies for A B D\n"
      "        |--Site A -- proxies for B C D\n"
      "        +--Site D -- proxies for A B C\n"
      "Where A = http://foo.com/\n"
      "      B = http://isolated.foo.com/\n"
      "      C = http://b.isolated.foo.com/\n"
      "      D = http://isolated.com/",
      DepictFrameTree(*root));
}

// Helper class for testing site isolation triggered by
// Cross-Origin-Opener-Policy headers.  These tests disable strict site
// isolation by default, so that we can check whether a site becomes isolated
// due to COOP on both desktop and Android.
class COOPIsolationTest : public IsolatedOriginTestBase {
 public:
  // Note: the COOP header is only populated for HTTPS.
  COOPIsolationTest() : https_server_(net::EmbeddedTestServer::TYPE_HTTPS) {
    // Note: OriginKeyedProcessesByDefault should only apply when strict site
    // isolation is in effect, and these tests turn that off via
    // NoSiteIsolationContentBrowserClient.
    scoped_feature_list_.InitWithFeatures(
        /*enabled_features=*/{features::
                                  kSiteIsolationForCrossOriginOpenerPolicy},
        /*disabled_features=*/{features::kOriginKeyedProcessesByDefault});
  }

  ~COOPIsolationTest() override = default;

  void SetUpCommandLine(base::CommandLine* command_line) override {
    IsolatedOriginTestBase::SetUpCommandLine(command_line);
    ASSERT_TRUE(embedded_test_server()->InitializeAndListen());
  }

  void SetUpOnMainThread() override {
    IsolatedOriginTestBase::SetUpOnMainThread();
    host_resolver()->AddRule("*", "127.0.0.1");
    embedded_test_server()->StartAcceptingConnections();

    https_server()->AddDefaultHandlers(GetTestDataFilePath());
    ASSERT_TRUE(https_server()->Start());

    browser_client_ = std::make_unique<NoSiteIsolationContentBrowserClient>();

    // The custom ContentBrowserClient above typically ensures that this test
    // runs without strict site isolation, but it's still possible to
    // inadvertently override this when running with --site-per-process on the
    // command line. This might happen on try bots, so these tests take this
    // into account to prevent failures, but this is not an intended
    // configuration for these tests, since with strict site isolation COOP
    // doesn't need to dynamically isolate any sites.
    if (AreAllSitesIsolatedForTesting()) {
      LOG(WARNING) << "This test should be run without --site-per-process, "
                   << "as it's designed to exercise code paths when strict "
                   << "site isolation is turned off.";
    }
  }

  void TearDownOnMainThread() override {
    IsolatedOriginTestBase::TearDownOnMainThread();
    browser_client_.reset();
  }

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

  // A custom ContentBrowserClient to turn off strict site isolation, since
  // COOP isolation only matters in environments like Android where it
  // is not used.  Note that kSitePerProcess is a higher-layer feature, so we
  // can't just disable it here.
  class NoSiteIsolationContentBrowserClient
      : public ContentBrowserTestContentBrowserClient {
   public:
    bool ShouldEnableStrictSiteIsolation() override { return false; }
  };

 private:
  base::test::ScopedFeatureList scoped_feature_list_;

  net::EmbeddedTestServer https_server_;

  std::unique_ptr<NoSiteIsolationContentBrowserClient> browser_client_;
};

// Check that a main frame navigation to a COOP site (with no subsequent user
// gesture) triggers isolation for that site within the current
// BrowsingInstance.
IN_PROC_BROWSER_TEST_F(COOPIsolationTest, SameOrigin) {
  if (AreAllSitesIsolatedForTesting()) {
    return;
  }

  GURL no_coop_url = https_server()->GetURL("a.com", "/title1.html");
  EXPECT_TRUE(NavigateToURL(shell(), no_coop_url));
  EXPECT_EQ(
      web_contents()->GetPrimaryMainFrame()->cross_origin_opener_policy().value,
      network::mojom::CrossOriginOpenerPolicyValue::kUnsafeNone);
  scoped_refptr<SiteInstance> first_instance =
      web_contents()->GetPrimaryMainFrame()->GetSiteInstance();
  EXPECT_FALSE(first_instance->RequiresDedicatedProcess());

  // Navigate to a b.com URL with COOP, swapping BrowsingInstances.
  GURL coop_url = https_server()->GetURL(
      "b.com", "/set-header?Cross-Origin-Opener-Policy: same-origin");
  EXPECT_TRUE(NavigateToURL(shell(), coop_url));
  EXPECT_EQ(
      web_contents()->GetPrimaryMainFrame()->cross_origin_opener_policy().value,
      network::mojom::CrossOriginOpenerPolicyValue::kSameOrigin);
  SiteInstanceImpl* coop_instance =
      web_contents()->GetPrimaryMainFrame()->GetSiteInstance();
  // The b.com COOP page should trigger the isolation heuristic and require a
  // dedicated process locked to b.com.
  EXPECT_TRUE(coop_instance->RequiresDedicatedProcess());

  auto lock = coop_instance->GetProcess()->GetProcessLock();
  EXPECT_TRUE(lock.is_locked_to_site());
  EXPECT_EQ(ProcessLockFromUrl("https://b.com"), lock);

  // Check that a cross-site subframe in a non-isolated site becomes an OOPIF
  // in a new, non-isolated SiteInstance.
  ASSERT_TRUE(ExecJs(shell(),
                     "var iframe = document.createElement('iframe');"
                     "iframe.id = 'child';"
                     "document.body.appendChild(iframe);",
                     EXECUTE_SCRIPT_NO_USER_GESTURE));
  FrameTreeNode* root = web_contents()->GetPrimaryFrameTree().root();
  FrameTreeNode* child = root->child_at(0);
  GURL c_url(https_server()->GetURL("c.com", "/title1.html"));
  EXPECT_TRUE(NavigateIframeToURL(web_contents(), "child", c_url));
  SiteInstanceImpl* child_instance =
      child->current_frame_host()->GetSiteInstance();
  EXPECT_NE(coop_instance, child_instance);
  EXPECT_NE(coop_instance->GetProcess(), child_instance->GetProcess());
  EXPECT_FALSE(child_instance->RequiresDedicatedProcess());

  // Navigating the subframe back to b.com should bring it back to the parent
  // SiteInstance.
  GURL b_url(https_server()->GetURL("b.com", "/title1.html"));
  EXPECT_TRUE(NavigateIframeToURL(web_contents(), "child", b_url));
  child_instance = child->current_frame_host()->GetSiteInstance();
  EXPECT_EQ(coop_instance, child_instance);

  // Create a new window, forcing a new BrowsingInstance, and check that b.com
  // is *not* isolated in it.  Since b.com in `coop_instance`'s
  // BrowsingInstance hasn't received a user gesture, the COOP isolation does
  // not apply to other BrowsingInstances.
  Shell* new_shell = CreateBrowser();
  GURL no_coop_b_url = https_server()->GetURL("b.com", "/title2.html");
  EXPECT_TRUE(NavigateToURL(new_shell, no_coop_b_url));
  SiteInstanceImpl* new_instance = static_cast<SiteInstanceImpl*>(
      new_shell->web_contents()->GetPrimaryMainFrame()->GetSiteInstance());
  EXPECT_FALSE(new_instance->RequiresDedicatedProcess());
}

// Verify that the same-origin-allow-popups COOP header value triggers
// isolation, and that this behaves sanely with window.open().
IN_PROC_BROWSER_TEST_F(COOPIsolationTest, SameOriginAllowPopups) {
  if (AreAllSitesIsolatedForTesting()) {
    return;
  }

  // Navigate to a coop.com URL with COOP.
  GURL coop_url = https_server()->GetURL(
      "coop.com",
      "/set-header?Cross-Origin-Opener-Policy: same-origin-allow-popups");
  EXPECT_TRUE(NavigateToURL(shell(), coop_url));
  EXPECT_EQ(
      web_contents()->GetPrimaryMainFrame()->cross_origin_opener_policy().value,
      network::mojom::CrossOriginOpenerPolicyValue::kSameOriginAllowPopups);
  SiteInstanceImpl* coop_instance =
      web_contents()->GetPrimaryMainFrame()->GetSiteInstance();
  // The coop.com COOP page should trigger the isolation heuristic and require
  // a dedicated process locked to coop.com.
  EXPECT_TRUE(coop_instance->RequiresDedicatedProcess());

  auto lock = coop_instance->GetProcess()->GetProcessLock();
  EXPECT_TRUE(lock.is_locked_to_site());
  EXPECT_EQ(ProcessLockFromUrl("https://coop.com"), lock);

  // Open a non-COOP same-site URL in a popup, which should stay in the same
  // BrowsingInstance because of same-origin-allow-popups.  Verify that the
  // popup ends up in the same SiteInstance as the opener (which requires a
  // dedicated process).
  GURL popup_url(https_server()->GetURL("coop.com", "/title1.html"));
  Shell* popup = OpenPopup(shell(), popup_url, "");
  RenderFrameHostImpl* popup_rfh = static_cast<RenderFrameHostImpl*>(
      popup->web_contents()->GetPrimaryMainFrame());
  EXPECT_EQ(popup_rfh->cross_origin_opener_policy().value,
            network::mojom::CrossOriginOpenerPolicyValue::kUnsafeNone);
  EXPECT_EQ(popup_rfh->GetSiteInstance(), coop_instance);

  // Navigate the popup to another non-isolated site, staying in the same
  // BrowsingInstance, and verify that it swaps to a new non-isolated
  // SiteInstance.  The non-isolated site has a child which is same-origin with
  // the COOP page; verify that it's placed in the same SiteInstance as the
  // COOP page, as they are allowed to synchronously script each other.
  GURL a_url(https_server()->GetURL(
      "a.com", "/cross_site_iframe_factory.html?a.com(coop.com)"));
  EXPECT_TRUE(NavigateToURLFromRenderer(popup, a_url));
  SiteInstanceImpl* new_instance = static_cast<SiteInstanceImpl*>(
      popup->web_contents()->GetPrimaryMainFrame()->GetSiteInstance());
  EXPECT_FALSE(new_instance->RequiresDedicatedProcess());
  EXPECT_NE(new_instance, coop_instance);
  FrameTreeNode* popup_child =
      static_cast<WebContentsImpl*>(popup->web_contents())
          ->GetPrimaryFrameTree()
          .root()
          ->child_at(0);
  EXPECT_EQ(popup_child->current_frame_host()->GetSiteInstance(),
            coop_instance);

  // Navigate the popup to coop.com again, staying in the same
  // BrowsingInstance, and verify that it goes back to the opener's
  // SiteInstance.
  EXPECT_TRUE(NavigateToURLFromRenderer(popup, popup_url));
  EXPECT_EQ(popup->web_contents()->GetPrimaryMainFrame()->GetSiteInstance(),
            coop_instance);
}

class COOPIsolationNoopenerTest : public COOPIsolationTest {
 public:
  COOPIsolationNoopenerTest() {
    feature_list_.InitAndEnableFeature(
        network::features::kCoopNoopenerAllowPopups);
  }

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

// Verify that the `noopener-allow-popups COOP header value triggers isolation,
// and that this behaves sanely with window.open().
IN_PROC_BROWSER_TEST_F(COOPIsolationNoopenerTest, NoopenerAllowPopups) {
  if (AreAllSitesIsolatedForTesting()) {
    return;
  }

  // Navigate to a coop.com URL with no COOP.
  GURL coop_url = https_server()->GetURL(
      "coop.com", "/set-header?Cross-Origin-Opener-Policy: unsafe-none");
  EXPECT_TRUE(NavigateToURL(shell(), coop_url));
  EXPECT_EQ(
      web_contents()->GetPrimaryMainFrame()->cross_origin_opener_policy().value,
      network::mojom::CrossOriginOpenerPolicyValue::kUnsafeNone);
  SiteInstanceImpl* coop_instance =
      web_contents()->GetPrimaryMainFrame()->GetSiteInstance();
  // The coop.com unsafe-none COOP page should not trigger the isolation
  // heuristic and not require a dedicated process locked to coop.com.
  EXPECT_FALSE(coop_instance->RequiresDedicatedProcess());

  auto lock = coop_instance->GetProcess()->GetProcessLock();
  EXPECT_FALSE(lock.is_locked_to_site());

  // Open a noopener-allow-popups COOP same-site URL in a popup, which should
  // swap a BrowsingInstance because of noopener-allow-popups.  Verify that the
  // popup ends up in a different SiteInstance from the opener.
  GURL popup_url(https_server()->GetURL(
      "coop.com",
      "/set-header?Cross-Origin-Opener-Policy: noopener-allow-popups"));
  Shell* popup = OpenPopup(shell(), popup_url, "");
  RenderFrameHostImpl* popup_rfh = static_cast<RenderFrameHostImpl*>(
      popup->web_contents()->GetPrimaryMainFrame());
  EXPECT_EQ(popup_rfh->cross_origin_opener_policy().value,
            network::mojom::CrossOriginOpenerPolicyValue::kNoopenerAllowPopups);
  EXPECT_NE(popup_rfh->GetSiteInstance(), coop_instance);
  EXPECT_NE(popup_rfh->GetSiteInstance()->GetProcess(),
            coop_instance->GetProcess());

  // Navigate the popup to another non-isolated site, staying in the same
  // BrowsingInstance, and verify that it swaps to a new non-isolated
  // SiteInstance.  The non-isolated site has a child which is same-origin with
  // the COOP page; verify that it's placed in the same SiteInstance as the
  // COOP page, as they are allowed to synchronously script each other.
  GURL a_url(https_server()->GetURL(
      "a.com", "/cross_site_iframe_factory.html?a.com(coop.com)"));
  EXPECT_TRUE(NavigateToURLFromRenderer(popup, a_url));
  SiteInstanceImpl* new_instance = static_cast<SiteInstanceImpl*>(
      popup->web_contents()->GetPrimaryMainFrame()->GetSiteInstance());
  EXPECT_FALSE(new_instance->RequiresDedicatedProcess());
  EXPECT_NE(new_instance, coop_instance);
  FrameTreeNode* popup_child =
      static_cast<WebContentsImpl*>(popup->web_contents())
          ->GetPrimaryFrameTree()
          .root()
          ->child_at(0);
  EXPECT_NE(popup_child->current_frame_host()->GetSiteInstance(),
            coop_instance);

  // Navigate the popup to coop.com again, staying in the same
  // BrowsingInstance, and verify that it goes back to the opener's
  // SiteInstance.
  EXPECT_TRUE(NavigateToURLFromRenderer(popup, popup_url));
  EXPECT_NE(popup->web_contents()->GetPrimaryMainFrame()->GetSiteInstance(),
            coop_instance);
}

// Verify that COOP isolation applies at a site (and not origin) granularity.
//
// Isolating sites rather than origins may seem counterintuitive, considering
// the COOP header value that triggers isolation is "same-origin".  However,
// process isolation granularity that we can infer from COOP is quite different
// from what that actual COOP value controls. The COOP "same-origin" value
// specifies when to sever opener relationships and create a new
// BrowsingInstance; a COOP "same-origin" main frame document may only stay in
// the same BrowsingInstance as other same-origin COOP documents.  However,
// this does not apply to iframes, and it's possible to have a
// foo.bar.coop.com(baz.coop.com) hierarchy where the main frame has COOP
// "same-origin" but both frames set document.domain to coop.com and
// synchronously script each other (*).  Hence, in this case, we must isolate
// the coop.com site and place the two frames in the same process. This test
// covers that precise scenario.
//
// (*) In the future, COOP may disallow document.domain, in which case we may
// need to revisit this.  See https://github.com/whatwg/html/issues/6177.
IN_PROC_BROWSER_TEST_F(COOPIsolationTest, SiteGranularity) {
  if (AreAllSitesIsolatedForTesting()) {
    return;
  }

  // Navigate to a URL with COOP, where the origin doesn't match the site.
  GURL coop_url = https_server()->GetURL(
      "foo.bar.coop.com",
      "/set-header?Cross-Origin-Opener-Policy: same-origin");
  EXPECT_TRUE(NavigateToURL(shell(), coop_url));
  EXPECT_EQ(
      web_contents()->GetPrimaryMainFrame()->cross_origin_opener_policy().value,
      network::mojom::CrossOriginOpenerPolicyValue::kSameOrigin);
  SiteInstanceImpl* coop_instance =
      web_contents()->GetPrimaryMainFrame()->GetSiteInstance();
  EXPECT_TRUE(coop_instance->RequiresDedicatedProcess());

  // Ensure that the process lock is for the site, not origin.
  auto lock = coop_instance->GetProcess()->GetProcessLock();
  EXPECT_TRUE(lock.is_locked_to_site());
  EXPECT_EQ(ProcessLockFromUrl("https://coop.com"), lock);

  // Check that a same-site cross-origin subframe stays in the same
  // SiteInstance and process.
  ASSERT_TRUE(ExecJs(shell(),
                     "var iframe = document.createElement('iframe');"
                     "iframe.id = 'child';"
                     "document.body.appendChild(iframe);"));
  FrameTreeNode* root = web_contents()->GetPrimaryFrameTree().root();
  FrameTreeNode* child = root->child_at(0);
  GURL c_url(https_server()->GetURL("baz.coop.com", "/title1.html"));
  EXPECT_TRUE(NavigateIframeToURL(web_contents(), "child", c_url));
  SiteInstanceImpl* child_instance =
      child->current_frame_host()->GetSiteInstance();
  EXPECT_EQ(coop_instance, child_instance);

  // Check that ChildProcessSecurityPolicy considers coop.com (and not its
  // subdomain) to be the matching isolated origin for `coop_url`.
  url::Origin matching_isolated_origin;
  ChildProcessSecurityPolicyImpl::GetInstance()
      ->GetMatchingProcessIsolatedOrigin(coop_instance->GetIsolationContext(),
                                         url::Origin::Create(GURL(coop_url)),
                                         false /* origin_requests_isolation */,
                                         &matching_isolated_origin);
  EXPECT_EQ(matching_isolated_origin,
            url::Origin::Create(GURL("https://coop.com")));
}

// Verify that COOP isolation applies when both COOP and COEP headers are set
// (i.e., for a cross-origin-isolated page).  This results in a different COOP
// header value (kSameOriginPlusCoep) which should still trigger isolation.
IN_PROC_BROWSER_TEST_F(COOPIsolationTest, COOPAndCOEP) {
  // Navigate to a URL with COOP + COEP.
  GURL coop_url = https_server()->GetURL(
      "coop.com",
      "/set-header?Cross-Origin-Opener-Policy: same-origin&"
      "Cross-Origin-Embedder-Policy: require-corp");
  EXPECT_TRUE(NavigateToURL(shell(), coop_url));
  EXPECT_EQ(
      web_contents()->GetPrimaryMainFrame()->cross_origin_opener_policy().value,
      network::mojom::CrossOriginOpenerPolicyValue::kSameOriginPlusCoep);

  // Make sure that site isolation for coop.com was triggered and that the
  // navigation ended up in a site-locked process.
  SiteInstanceImpl* coop_instance =
      web_contents()->GetPrimaryMainFrame()->GetSiteInstance();
  EXPECT_TRUE(coop_instance->RequiresDedicatedProcess());
  auto lock = coop_instance->GetProcess()->GetProcessLock();
  EXPECT_TRUE(lock.GetWebExposedIsolationInfo().is_isolated());
  EXPECT_TRUE(lock.is_locked_to_site());
  EXPECT_TRUE(
      lock.MatchesOrigin(url::Origin::Create(GURL("https://coop.com"))));
}

// Check that when a site triggers both COOP isolation and OriginAgentCluster,
// both mechanisms take effect.  This test uses a URL with default ports so
// that we can exercise the site URL being the same with both COOP and OAC.
IN_PROC_BROWSER_TEST_F(COOPIsolationTest, COOPAndOriginAgentClusterNoPorts) {
  // Since the embedded test server only works for URLs with non-default ports,
  // use a URLLoaderInterceptor to mimic port-free operation.  This allows
  // checking the site URL being identical for both COOP and OAC isolation,
  // since otherwise OAC would include ports in the site URL.  The interceptor
  // below returns COOP and OAC headers for any page on foo.com, and returns a
  // simple test page without any headers for a.foo.com and b.foo.com.
  URLLoaderInterceptor interceptor(base::BindLambdaForTesting(
      [&](URLLoaderInterceptor::RequestParams* params) {
        if (params->url_request.url.host() == "foo.com") {
          const std::string headers =
              "HTTP/1.1 200 OK\n"
              "Content-Type: text/html\n"
              "Origin-Agent-Cluster: ?1\n"
              "Cross-Origin-Opener-Policy: same-origin\n";
          URLLoaderInterceptor::WriteResponse(
              "content/test/data" + params->url_request.url.path(),
              params->client.get(), &headers, std::optional<net::SSLInfo>());
          return true;
        } else if (params->url_request.url.host() == "a.foo.com" ||
                   params->url_request.url.host() == "b.foo.com") {
          URLLoaderInterceptor::WriteResponse("content/test/data/title1.html",
                                              params->client.get());
          return true;
        }
        // Not handled by us.
        return false;
      }));

  // Navigate to a URL with with COOP and OriginAgentCluster headers, embedding
  // two iframes at a.foo.com and b.foo.com.
  GURL coop_oac_url(
      "https://foo.com/cross_site_iframe_factory.html?"
      "foo.com(a.foo.com,b.foo.com)");
  EXPECT_TRUE(NavigateToURL(shell(), coop_oac_url));
  EXPECT_EQ(
      web_contents()->GetPrimaryMainFrame()->cross_origin_opener_policy().value,
      network::mojom::CrossOriginOpenerPolicyValue::kSameOrigin);

  FrameTreeNode* root = web_contents()->GetPrimaryFrameTree().root();
  FrameTreeNode* child1 = root->child_at(0);
  FrameTreeNode* child2 = root->child_at(1);

  // The two subframes should end up in the same SiteInstance, different from
  // the main frame's SiteInstance.  Both SiteInstances should be in a process
  // dedicated to foo.com, but the main frame's process should be for
  // origin-keyed foo.com (strictly foo.com excluding subdomains) due to
  // Origin-Agent-Cluster, whereas the subframe process should be for
  // site-keyed foo.com.
  SiteInstanceImpl* main_instance =
      web_contents()->GetPrimaryMainFrame()->GetSiteInstance();
  SiteInstanceImpl* child_instance =
      child1->current_frame_host()->GetSiteInstance();
  EXPECT_EQ(child_instance, child2->current_frame_host()->GetSiteInstance());
  EXPECT_NE(child_instance, main_instance);

  EXPECT_TRUE(main_instance->RequiresDedicatedProcess());
  EXPECT_TRUE(child_instance->RequiresDedicatedProcess());

  EXPECT_TRUE(main_instance->GetSiteInfo().requires_origin_keyed_process());
  EXPECT_FALSE(child_instance->GetSiteInfo().requires_origin_keyed_process());
  EXPECT_EQ(main_instance->GetSiteInfo().site_url(),
            child_instance->GetSiteInfo().site_url());
  EXPECT_EQ(main_instance->GetSiteInfo().process_lock_url(),
            child_instance->GetSiteInfo().process_lock_url());

  auto main_lock = main_instance->GetProcess()->GetProcessLock();
  auto child_lock = child_instance->GetProcess()->GetProcessLock();
  EXPECT_TRUE(main_lock.is_locked_to_site());
  EXPECT_TRUE(child_lock.is_locked_to_site());
  EXPECT_TRUE(main_lock.is_origin_keyed_process());
  EXPECT_FALSE(child_lock.is_origin_keyed_process());
  auto foo_origin = url::Origin::Create(GURL("https://foo.com"));
  EXPECT_TRUE(main_lock.MatchesOrigin(foo_origin));
  EXPECT_TRUE(child_lock.MatchesOrigin(foo_origin));
}

// Check that when a site triggers both COOP isolation and OriginAgentCluster,
// both mechanisms take effect.  Similar to the test above, but starts on a URL
// where the origin doesn't match the site.
IN_PROC_BROWSER_TEST_F(COOPIsolationTest,
                       COOPAndOriginAgentClusterOnSubdomain) {
  // Navigate to a URL with with COOP and OriginAgentCluster headers.
  GURL coop_oac_url = https_server()->GetURL(
      "oac.coop.com",
      "/set-header?Cross-Origin-Opener-Policy: same-origin&"
      "Origin-Agent-Cluster: ?1");
  EXPECT_TRUE(NavigateToURL(shell(), coop_oac_url));
  EXPECT_EQ(
      web_contents()->GetPrimaryMainFrame()->cross_origin_opener_policy().value,
      network::mojom::CrossOriginOpenerPolicyValue::kSameOrigin);

  FrameTreeNode* root = web_contents()->GetPrimaryFrameTree().root();

  // Add a subframe and navigate to foo.coop.com.
  ASSERT_TRUE(ExecJs(shell(),
                     "var iframe = document.createElement('iframe');"
                     "iframe.id = 'child';"
                     "document.body.appendChild(iframe);"));
  FrameTreeNode* child = root->child_at(0);
  GURL child_url(https_server()->GetURL("foo.coop.com", "/title1.html"));
  EXPECT_TRUE(NavigateIframeToURL(web_contents(), "child", child_url));

  // The subframe should end up in a different SiteInstance from the main
  // frame's SiteInstance.  The main frame's SiteInstance should be in an
  // origin-keyed process locked to oac.foo.com, whereas the child's
  // SiteInstance should be in a site-keyed process locked to foo.com.
  SiteInstanceImpl* main_instance =
      web_contents()->GetPrimaryMainFrame()->GetSiteInstance();
  SiteInstanceImpl* child_instance =
      child->current_frame_host()->GetSiteInstance();
  EXPECT_NE(child_instance, main_instance);

  EXPECT_TRUE(main_instance->RequiresDedicatedProcess());
  EXPECT_TRUE(child_instance->RequiresDedicatedProcess());

  EXPECT_TRUE(main_instance->GetSiteInfo().requires_origin_keyed_process());
  EXPECT_FALSE(child_instance->GetSiteInfo().requires_origin_keyed_process());
  EXPECT_NE(main_instance->GetSiteInfo().site_url(),
            child_instance->GetSiteInfo().site_url());
  EXPECT_NE(main_instance->GetSiteInfo().process_lock_url(),
            child_instance->GetSiteInfo().process_lock_url());

  auto main_lock = main_instance->GetProcess()->GetProcessLock();
  auto child_lock = child_instance->GetProcess()->GetProcessLock();
  EXPECT_TRUE(main_lock.is_locked_to_site());
  EXPECT_TRUE(child_lock.is_locked_to_site());
  EXPECT_TRUE(main_lock.is_origin_keyed_process());
  EXPECT_FALSE(child_lock.is_origin_keyed_process());
  auto oac_coop_origin = url::Origin::Create(coop_oac_url);
  auto coop_origin = url::Origin::Create(GURL("https://coop.com"));
  EXPECT_TRUE(main_lock.MatchesOrigin(oac_coop_origin));
  EXPECT_TRUE(child_lock.MatchesOrigin(coop_origin));
}

// Verify that if strict site isolation is in place, COOP isolation does not
// add redundant isolated origins to ChildProcessSecurityPolicy.
IN_PROC_BROWSER_TEST_F(COOPIsolationTest, SiteAlreadyRequiresDedicatedProcess) {
  // Enable --site-per-process and navigate to a COOP-enabled document.
  IsolateAllSitesForTesting(base::CommandLine::ForCurrentProcess());
  GURL coop_url = https_server()->GetURL(
      "coop.com", "/set-header?Cross-Origin-Opener-Policy: same-origin");
  EXPECT_TRUE(NavigateToURL(shell(), coop_url));
  // Simulate user activation, which normally triggers COOP isolation for
  // future BrowsingInstances.
  EXPECT_TRUE(ExecJs(shell(), "// no-op"));
  EXPECT_EQ(
      web_contents()->GetPrimaryMainFrame()->cross_origin_opener_policy().value,
      network::mojom::CrossOriginOpenerPolicyValue::kSameOrigin);
  SiteInstanceImpl* coop_instance =
      web_contents()->GetPrimaryMainFrame()->GetSiteInstance();

  // The SiteInstance should require a dedicated process, but
  // ChildProcessSecurityPolicy shouldn't have added an isolated origin
  // for coop.com.
  EXPECT_TRUE(coop_instance->RequiresDedicatedProcess());
  auto* policy = ChildProcessSecurityPolicyImpl::GetInstance();
  auto origins = policy->GetIsolatedOrigins(
      ChildProcessSecurityPolicy::IsolatedOriginSource::WEB_TRIGGERED);
  EXPECT_EQ(0U, origins.size());
  EXPECT_FALSE(policy->IsIsolatedOrigin(coop_instance->GetIsolationContext(),
                                        url::Origin::Create(coop_url),
                                        false /* origin_requests_isolation */));
}

// Verify that seeing a user activation on a COOP document triggers isolation
// of that document's site in future BrowsingInstances, but doesn't affect any
// existing BrowsingInstances.
IN_PROC_BROWSER_TEST_F(COOPIsolationTest, UserActivation) {
  if (AreAllSitesIsolatedForTesting()) {
    return;
  }

  GURL coop_url = https_server()->GetURL(
      "b.com", "/set-header?Cross-Origin-Opener-Policy: same-origin");
  EXPECT_TRUE(NavigateToURL(shell(), coop_url));
  EXPECT_EQ(
      web_contents()->GetPrimaryMainFrame()->cross_origin_opener_policy().value,
      network::mojom::CrossOriginOpenerPolicyValue::kSameOrigin);
  FrameTreeNode* coop_root = web_contents()->GetPrimaryFrameTree().root();
  SiteInstance* coop_instance =
      web_contents()->GetPrimaryMainFrame()->GetSiteInstance();
  // The b.com COOP page should trigger the isolation heuristic and require a
  // dedicated process locked to b.com.
  EXPECT_TRUE(coop_instance->RequiresDedicatedProcess());

  // At this point, the COOP page shouldn't have user activation.
  EXPECT_FALSE(coop_root->HasTransientUserActivation());

  // Create a new window, forcing a new BrowsingInstance, and check that b.com
  // is *not* isolated in it.  Since b.com in `coop_instance`'s
  // BrowsingInstance hasn't been interacted with, the COOP isolation does not
  // apply to other BrowsingInstances yet.
  Shell* shell2 = CreateBrowser();
  GURL no_coop_b_url = https_server()->GetURL("b.com", "/title2.html");
  EXPECT_TRUE(NavigateToURL(shell2, no_coop_b_url));
  FrameTreeNode* shell2_root =
      static_cast<WebContentsImpl*>(shell2->web_contents())
          ->GetPrimaryFrameTree()
          .root();
  scoped_refptr<SiteInstance> instance2 =
      shell2->web_contents()->GetPrimaryMainFrame()->GetSiteInstance();
  EXPECT_FALSE(instance2->RequiresDedicatedProcess());

  // Simulate a user activation in the original COOP page by running a dummy
  // script (ExecJs sends user activation by default).
  EXPECT_TRUE(ExecJs(coop_root, "// no-op"));
  EXPECT_TRUE(coop_root->HasTransientUserActivation());

  // Create a third window in a new BrowsingInstance and navigate it to a
  // non-COOP b.com URL. The above user activation should've forced COOP
  // isolation for b.com to apply to future BrowsingInstances, so check that
  // this navigation ends up requiring a dedicated process.
  Shell* shell3 = CreateBrowser();
  EXPECT_TRUE(NavigateToURL(shell3, no_coop_b_url));
  SiteInstance* instance3 =
      shell3->web_contents()->GetPrimaryMainFrame()->GetSiteInstance();
  EXPECT_TRUE(instance3->RequiresDedicatedProcess());
  EXPECT_FALSE(instance2->IsRelatedSiteInstance(instance3));
  EXPECT_FALSE(coop_instance->IsRelatedSiteInstance(instance3));

  // Ensure that the older BrowsingInstance in the second window wasn't
  // affected by the new isolation. Adding a b.com subframe or popup should
  // stay in the same SiteInstance. Navigating the popup out from and back to
  // b.com should also end up on the same SiteInstance.
  ASSERT_TRUE(ExecJs(shell2,
                     "var iframe = document.createElement('iframe');"
                     "iframe.id = 'child';"
                     "document.body.appendChild(iframe);",
                     EXECUTE_SCRIPT_NO_USER_GESTURE));
  FrameTreeNode* child = shell2_root->child_at(0);
  GURL another_b_url(https_server()->GetURL("b.com", "/title3.html"));
  EXPECT_TRUE(
      NavigateIframeToURL(shell2->web_contents(), "child", another_b_url));
  SiteInstanceImpl* child_instance =
      child->current_frame_host()->GetSiteInstance();
  EXPECT_EQ(child_instance, instance2);

  Shell* popup = OpenPopup(shell2, another_b_url, "");
  FrameTreeNode* popup_root =
      static_cast<WebContentsImpl*>(popup->web_contents())
          ->GetPrimaryFrameTree()
          .root();
  EXPECT_EQ(popup_root->current_frame_host()->GetSiteInstance(), instance2);

  EXPECT_TRUE(NavigateToURLFromRenderer(
      popup, https_server()->GetURL("c.com", "/title1.html")));
  EXPECT_TRUE(NavigateToURLFromRenderer(popup, another_b_url));
  EXPECT_EQ(popup_root->current_frame_host()->GetSiteInstance(), instance2);

  // Close the popup.
  popup->Close();

  // Without any related windows, navigating to b.com in the second window's
  // main frame should trigger a proactive BrowsingInstance swap (see
  // ShouldSwapBrowsingInstancesForDynamicIsolation()), since we notice that
  // b.com would be isolated in a fresh BrowsingInstance, and nothing prevents
  // the BrowsingInstance swap. Hence, in that case, the navigation should be
  // in a new BrowsingInstance and in an isolated process.
  EXPECT_TRUE(NavigateToURLFromRenderer(
      shell2, https_server()->GetURL("b.com", "/title3.html")));
  scoped_refptr<SiteInstance> instance2_new =
      shell2->web_contents()->GetPrimaryMainFrame()->GetSiteInstance();
  EXPECT_TRUE(instance2_new->RequiresDedicatedProcess());
  EXPECT_NE(instance2_new, instance2);
  EXPECT_FALSE(instance2_new->IsRelatedSiteInstance(instance2.get()));
}

// Similar to the test above, but verify that a user activation on a same-site
// subframe also triggers isolation of a COOP site in the main frame for future
// BrowsingInstances.
IN_PROC_BROWSER_TEST_F(COOPIsolationTest, UserActivationInSubframe) {
  if (AreAllSitesIsolatedForTesting()) {
    return;
  }

  GURL coop_url = https_server()->GetURL(
      "b.com", "/set-header?Cross-Origin-Opener-Policy: same-origin");
  EXPECT_TRUE(NavigateToURL(shell(), coop_url));
  EXPECT_EQ(
      web_contents()->GetPrimaryMainFrame()->cross_origin_opener_policy().value,
      network::mojom::CrossOriginOpenerPolicyValue::kSameOrigin);
  SiteInstance* coop_instance =
      web_contents()->GetPrimaryMainFrame()->GetSiteInstance();
  EXPECT_TRUE(coop_instance->RequiresDedicatedProcess());

  // Add a cross-site subframe.
  ASSERT_TRUE(ExecJs(shell(),
                     "var iframe = document.createElement('iframe');"
                     "iframe.id = 'child';"
                     "document.body.appendChild(iframe);",
                     EXECUTE_SCRIPT_NO_USER_GESTURE));
  FrameTreeNode* root = web_contents()->GetPrimaryFrameTree().root();
  FrameTreeNode* child = root->child_at(0);
  GURL c_url(https_server()->GetURL("c.com", "/title1.html"));
  EXPECT_TRUE(NavigateIframeToURL(web_contents(), "child", c_url));

  EXPECT_FALSE(root->HasTransientUserActivation());
  EXPECT_FALSE(child->HasTransientUserActivation());

  // Simulate a user activation in the subframe by running a dummy script.
  EXPECT_TRUE(ExecJs(child, "// no-op"));
  EXPECT_TRUE(child->HasTransientUserActivation());

  // Since the iframe is cross-origin, it shouldn't trigger isolation of b.com
  // for future BrowsingInstances.
  GURL no_coop_b_url = https_server()->GetURL("b.com", "/title2.html");
  {
    Shell* new_shell = CreateBrowser();
    EXPECT_TRUE(NavigateToURL(new_shell, no_coop_b_url));
    scoped_refptr<SiteInstance> instance =
        new_shell->web_contents()->GetPrimaryMainFrame()->GetSiteInstance();
    EXPECT_FALSE(instance->RequiresDedicatedProcess());
  }

  // Now, make the iframe same-origin and simulate a user gesture.
  GURL b_url(https_server()->GetURL("b.com", "/title1.html"));
  EXPECT_TRUE(NavigateIframeToURL(web_contents(), "child", b_url));

  EXPECT_TRUE(ExecJs(child, "// no-op"));

  // Ensure that b.com is now isolated in a new tab and BrowsingInstance.
  {
    Shell* new_shell = CreateBrowser();
    EXPECT_TRUE(NavigateToURL(new_shell, no_coop_b_url));
    scoped_refptr<SiteInstance> instance =
        new_shell->web_contents()->GetPrimaryMainFrame()->GetSiteInstance();
    EXPECT_TRUE(instance->RequiresDedicatedProcess());
  }
}

// Similar to the test above, but verify that a user activation on a
// same-origin about:blank subframe triggers isolation of a COOP site in the
// main frame for future BrowsingInstances.
IN_PROC_BROWSER_TEST_F(COOPIsolationTest, UserActivationInAboutBlankSubframe) {
  GURL coop_url = https_server()->GetURL(
      "b.com", "/set-header?Cross-Origin-Opener-Policy: same-origin");
  EXPECT_TRUE(NavigateToURL(shell(), coop_url));
  EXPECT_EQ(
      web_contents()->GetPrimaryMainFrame()->cross_origin_opener_policy().value,
      network::mojom::CrossOriginOpenerPolicyValue::kSameOrigin);
  SiteInstance* coop_instance =
      web_contents()->GetPrimaryMainFrame()->GetSiteInstance();
  EXPECT_TRUE(coop_instance->RequiresDedicatedProcess());

  // Add a cross-site blank subframe.
  ASSERT_TRUE(ExecJs(shell(),
                     "var iframe = document.createElement('iframe');"
                     "iframe.id = 'child';"
                     "document.body.appendChild(iframe);",
                     EXECUTE_SCRIPT_NO_USER_GESTURE));
  FrameTreeNode* root = web_contents()->GetPrimaryFrameTree().root();
  FrameTreeNode* child = root->child_at(0);

  EXPECT_FALSE(root->HasTransientUserActivation());
  EXPECT_FALSE(child->HasTransientUserActivation());

  // Simulate a user activation in the subframe by running a dummy script.
  EXPECT_TRUE(ExecJs(child, "// no-op"));
  EXPECT_TRUE(child->HasTransientUserActivation());

  // Ensure that b.com is isolated in a new tab and BrowsingInstance.
  {
    Shell* new_shell = CreateBrowser();
    GURL no_coop_b_url = https_server()->GetURL("b.com", "/title2.html");
    EXPECT_TRUE(NavigateToURL(new_shell, no_coop_b_url));
    scoped_refptr<SiteInstance> instance =
        new_shell->web_contents()->GetPrimaryMainFrame()->GetSiteInstance();
    EXPECT_TRUE(instance->RequiresDedicatedProcess());
  }
}

// Ensure that navigating to http://localhost which has COOP+COEP headers, and
// hence will attempt to trigger COOP isolation, will not crash.  See
// https://crbug.com/1276155.
IN_PROC_BROWSER_TEST_F(COOPIsolationTest, Localhost) {
  // Navigate to a URL with COOP + COEP on http://localhost.
  GURL coop_url = https_server()->GetURL(
      "localhost",
      "/set-header?Cross-Origin-Opener-Policy: same-origin&"
      "Cross-Origin-Embedder-Policy: require-corp");
  EXPECT_TRUE(NavigateToURL(shell(), coop_url));
  EXPECT_EQ(
      web_contents()->GetPrimaryMainFrame()->cross_origin_opener_policy().value,
      network::mojom::CrossOriginOpenerPolicyValue::kSameOriginPlusCoep);

  // http://localhost isn't currently considered a valid isolated origin (since
  // it won't work for subdomain matching), so the navigation should not
  // trigger site isolation.  Note, however, that the process lock should still
  // reflect COOP+COEP isolation.
  SiteInstanceImpl* coop_instance =
      web_contents()->GetPrimaryMainFrame()->GetSiteInstance();
  EXPECT_FALSE(coop_instance->RequiresDedicatedProcess());
  auto lock = coop_instance->GetProcess()->GetProcessLock();
  EXPECT_TRUE(lock.GetWebExposedIsolationInfo().is_isolated());
  EXPECT_FALSE(lock.is_locked_to_site());
}

// Helper class for testing site isolation triggered by different JIT policies
// being applied.
class JITIsolationTest : public IsolatedOriginTest,
                         public ::testing::WithParamInterface<bool> {
 public:
  JITIsolationTest() = default;

  ~JITIsolationTest() override = default;

  // A custom ContentBrowserTestContentBrowserClient to selectively turn off JIT
  // for certain sites.
  class JitContentBrowserClient
      : public ContentBrowserTestContentBrowserClient {
   public:
    JitContentBrowserClient(bool jit_disabled_default,
                            bool disable_site_isolation_entirely)
        : is_jit_disabled_by_default_(jit_disabled_default),
          is_site_isolation_disabled_entirely_(
              disable_site_isolation_entirely) {}

    bool IsJitDisabledForSite(BrowserContext* browser_context,
                              const GURL& site_url) override {
      if (site_url.is_empty()) {
        return is_jit_disabled_by_default_;
      }
      if (site_url.DomainIs("jit-disabled.com")) {
        return true;
      }
      if (site_url.DomainIs("jit-enabled.com")) {
        return false;
      }
      return is_jit_disabled_by_default_;
    }

    bool ShouldEnableStrictSiteIsolation() override {
      return !is_site_isolation_disabled_entirely_;
    }

   private:
    bool is_jit_disabled_by_default_;
    bool is_site_isolation_disabled_entirely_;
  };
};

IN_PROC_BROWSER_TEST_P(JITIsolationTest, MainFrameTest) {
  bool jit_disabled_by_default = GetParam();
  JitContentBrowserClient policy(jit_disabled_by_default,
                                 /* disable_site_isolation_entirely */ false);

  // Navigate to jit-disabled.com which should always have JIT disabled.
  GURL disabled_url(
      embedded_test_server()->GetURL("www.jit-disabled.com", "/title1.html"));
  EXPECT_TRUE(NavigateToURL(shell(), disabled_url));

  EXPECT_TRUE(shell()
                  ->web_contents()
                  ->GetPrimaryMainFrame()
                  ->GetProcess()
                  ->IsJitDisabled());

  // Navigate to jit-enabled.com which should always have JIT enabled.
  GURL enabled_url(
      embedded_test_server()->GetURL("www.jit-enabled.com", "/title1.html"));
  EXPECT_TRUE(NavigateToURL(shell(), enabled_url));

  EXPECT_FALSE(shell()
                   ->web_contents()
                   ->GetPrimaryMainFrame()
                   ->GetProcess()
                   ->IsJitDisabled());

  // Navigate to a site with no policy and it should match the default.
  GURL default_url(
      embedded_test_server()->GetURL("www.foo.com", "/title1.html"));
  EXPECT_TRUE(NavigateToURL(shell(), default_url));

  EXPECT_EQ(jit_disabled_by_default, shell()
                                         ->web_contents()
                                         ->GetPrimaryMainFrame()
                                         ->GetProcess()
                                         ->IsJitDisabled());
}

IN_PROC_BROWSER_TEST_P(JITIsolationTest, DefaultSiteTest) {
  // Skip the test if --site-per-process is used on the command line, as the
  // test needs to run without strict site isolation (see
  // JitContentBrowserClient below).
  if (AreAllSitesIsolatedForTesting()) {
    return;
  }

  bool jit_disabled_by_default = GetParam();
  JitContentBrowserClient policy(jit_disabled_by_default,
                                 /* disable_site_isolation_entirely */ true);

  // All three sites should have JIT enabled or disabled together, if site
  // isolation is disabled, since they are all put into the default
  // SiteInstance.
  GURL disabled_url(
      embedded_test_server()->GetURL("www.jit-disabled.com", "/title1.html"));
  EXPECT_TRUE(NavigateToURL(shell(), disabled_url));

  EXPECT_EQ(jit_disabled_by_default, shell()
                                         ->web_contents()
                                         ->GetPrimaryMainFrame()
                                         ->GetProcess()
                                         ->IsJitDisabled());

  GURL enabled_url(
      embedded_test_server()->GetURL("www.jit-enabled.com", "/title1.html"));
  EXPECT_TRUE(NavigateToURL(shell(), enabled_url));

  EXPECT_EQ(jit_disabled_by_default, shell()
                                         ->web_contents()
                                         ->GetPrimaryMainFrame()
                                         ->GetProcess()
                                         ->IsJitDisabled());

  GURL default_url(
      embedded_test_server()->GetURL("www.foo.com", "/title1.html"));
  EXPECT_TRUE(NavigateToURL(shell(), default_url));

  EXPECT_EQ(jit_disabled_by_default, shell()
                                         ->web_contents()
                                         ->GetPrimaryMainFrame()
                                         ->GetProcess()
                                         ->IsJitDisabled());
}

INSTANTIATE_TEST_SUITE_P(JITEnabledByDefault,
                         JITIsolationTest,
                         ::testing::Values(false));
INSTANTIATE_TEST_SUITE_P(JITDisabledByDefault,
                         JITIsolationTest,
                         ::testing::Values(true));

IN_PROC_BROWSER_TEST_F(JITIsolationTest, SubFrameTest) {
  // Set JIT to be enabled by default.
  JitContentBrowserClient policy(
      /* jit_disabled_default */ false,
      /* disable_site_isolation_entirely */ false);

  GURL default_embeds_disabled(embedded_test_server()->GetURL(
      "foo.com", "/cross_site_iframe_factory.html?foo.com(jit-disabled.com)"));

  EXPECT_TRUE(NavigateToURL(shell(), default_embeds_disabled));
  EXPECT_EQ(2u, CollectAllRenderFrameHosts(shell()->web_contents()).size());

  // Top frame 'foo.com' should have JIT enabled as that's the default.
  FrameTreeNode* root = web_contents()->GetPrimaryFrameTree().root();
  EXPECT_FALSE(root->current_frame_host()->GetProcess()->IsJitDisabled());
  // The frame containing jit-disabled.com should have JIT disabled.
  FrameTreeNode* child_frame_node = root->child_at(0);
  EXPECT_TRUE(
      child_frame_node->current_frame_host()->GetProcess()->IsJitDisabled());

  // And the other way round, where jit-disabled.com embeds foo.com.
  GURL disabled_embeds_default(embedded_test_server()->GetURL(
      "jit-disabled.com",
      "/cross_site_iframe_factory.html?jit-disabled.com(foo.com)"));

  EXPECT_TRUE(NavigateToURL(shell(), disabled_embeds_default));
  EXPECT_EQ(2u, CollectAllRenderFrameHosts(
                    shell()->web_contents()->GetPrimaryMainFrame())
                    .size());

  // Top frame 'jit-disabled.com' should have JIT disabled.
  root = web_contents()->GetPrimaryFrameTree().root();
  EXPECT_TRUE(root->current_frame_host()->GetProcess()->IsJitDisabled());
  // The frame containing foo.com should have JIT enabled as that's the default.
  child_frame_node = root->child_at(0);
  EXPECT_FALSE(
      child_frame_node->current_frame_host()->GetProcess()->IsJitDisabled());
}

// Check that jitless subframes obey process reuse policies.
IN_PROC_BROWSER_TEST_F(JITIsolationTest, SubFrameProcessReuse) {
  // Set JIT to be enabled by default.
  JitContentBrowserClient policy(
      /* jit_disabled_default */ false,
      /* disable_site_isolation_entirely */ false);

  GURL default_embeds_disabled(embedded_test_server()->GetURL(
      "foo.com", "/cross_site_iframe_factory.html?foo.com(jit-disabled.com)"));

  EXPECT_TRUE(NavigateToURL(shell(), default_embeds_disabled));

  // Top frame 'foo.com' should have JIT enabled as that's the default.
  FrameTreeNode* root = web_contents()->GetPrimaryFrameTree().root();
  EXPECT_FALSE(root->current_frame_host()->GetProcess()->IsJitDisabled());
  // The frame containing jit-disabled.com should have JIT disabled.
  FrameTreeNode* child = root->child_at(0);
  EXPECT_TRUE(child->current_frame_host()->GetProcess()->IsJitDisabled());

  // Create a new window, unrelated to the current one, and set up the same
  // frame hierarchy.
  Shell* new_shell = CreateBrowser();
  EXPECT_TRUE(NavigateToURL(new_shell, default_embeds_disabled));

  FrameTreeNode* new_root =
      static_cast<WebContentsImpl*>(new_shell->web_contents())
          ->GetPrimaryFrameTree()
          .root();
  EXPECT_FALSE(new_root->current_frame_host()->GetProcess()->IsJitDisabled());

  FrameTreeNode* new_child = new_root->child_at(0);
  EXPECT_TRUE(new_child->current_frame_host()->GetProcess()->IsJitDisabled());

  // The subframes should be in separate BrowsingInstances, but because they
  // have the same site, they should share the same process.
  EXPECT_FALSE(
      new_child->current_frame_host()->GetSiteInstance()->IsRelatedSiteInstance(
          child->current_frame_host()->GetSiteInstance()));
  EXPECT_EQ(new_child->current_frame_host()->GetProcess(),
            child->current_frame_host()->GetProcess());
}

}  // namespace content