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 7561 7562 7563 7564 7565 7566 7567 7568 7569 7570 7571 7572 7573 7574 7575 7576 7577 7578 7579 7580 7581 7582 7583 7584 7585 7586 7587 7588 7589 7590 7591 7592 7593 7594 7595 7596 7597 7598 7599 7600 7601 7602 7603 7604 7605 7606 7607 7608 7609 7610 7611 7612 7613 7614 7615 7616 7617 7618 7619 7620 7621 7622 7623 7624 7625 7626 7627 7628 7629 7630 7631 7632 7633 7634 7635 7636 7637 7638 7639 7640 7641 7642 7643 7644 7645 7646 7647 7648 7649 7650 7651 7652 7653 7654 7655 7656 7657 7658 7659 7660 7661 7662 7663 7664 7665 7666 7667 7668 7669 7670 7671 7672 7673 7674 7675 7676 7677 7678 7679 7680 7681 7682 7683 7684 7685 7686 7687 7688 7689 7690 7691 7692 7693 7694 7695 7696 7697 7698 7699 7700 7701 7702 7703 7704 7705 7706 7707 7708 7709 7710 7711 7712 7713 7714 7715 7716 7717 7718 7719 7720 7721 7722 7723 7724 7725 7726 7727 7728 7729 7730 7731 7732 7733 7734 7735 7736 7737 7738 7739 7740 7741 7742 7743 7744 7745 7746 7747 7748 7749 7750 7751 7752 7753 7754 7755 7756 7757 7758 7759 7760 7761 7762 7763 7764 7765 7766 7767 7768 7769 7770 7771 7772 7773 7774 7775 7776 7777 7778 7779 7780 7781 7782 7783 7784 7785 7786 7787 7788 7789 7790 7791 7792 7793 7794 7795 7796 7797 7798 7799 7800 7801 7802 7803 7804 7805 7806 7807 7808 7809 7810 7811 7812 7813 7814 7815 7816 7817 7818 7819 7820 7821 7822 7823 7824 7825 7826 7827 7828 7829 7830 7831 7832 7833 7834 7835 7836 7837 7838 7839 7840 7841 7842 7843 7844 7845 7846 7847 7848 7849 7850 7851 7852 7853 7854 7855 7856 7857 7858 7859 7860 7861 7862 7863 7864 7865 7866 7867 7868 7869 7870 7871 7872 7873 7874 7875 7876 7877 7878 7879 7880 7881 7882 7883 7884 7885 7886 7887 7888 7889 7890 7891 7892 7893 7894 7895 7896 7897 7898 7899 7900 7901 7902 7903 7904 7905 7906 7907 7908 7909 7910 7911 7912 7913 7914 7915 7916 7917 7918 7919 7920 7921 7922 7923 7924 7925 7926 7927 7928 7929 7930 7931 7932 7933 7934 7935 7936 7937 7938 7939 7940 7941 7942 7943 7944 7945 7946 7947 7948 7949 7950 7951 7952 7953 7954 7955 7956 7957 7958 7959 7960 7961 7962 7963 7964 7965 7966 7967 7968 7969 7970 7971 7972 7973 7974 7975 7976 7977 7978 7979 7980 7981 7982 7983 7984 7985 7986 7987 7988 7989 7990 7991 7992 7993 7994 7995 7996 7997 7998 7999 8000 8001 8002 8003 8004 8005 8006 8007 8008 8009 8010 8011 8012 8013 8014 8015 8016 8017 8018 8019 8020 8021 8022 8023 8024 8025 8026 8027 8028 8029 8030 8031 8032 8033 8034 8035 8036 8037 8038 8039 8040 8041 8042 8043 8044 8045 8046 8047 8048 8049 8050 8051 8052 8053 8054 8055 8056 8057 8058 8059 8060 8061 8062 8063 8064 8065 8066 8067 8068 8069 8070 8071 8072 8073 8074 8075 8076 8077 8078 8079 8080 8081 8082 8083 8084 8085 8086 8087 8088 8089 8090 8091 8092 8093 8094 8095 8096 8097 8098 8099 8100 8101 8102 8103 8104 8105 8106 8107 8108 8109 8110 8111 8112 8113 8114 8115 8116 8117 8118 8119 8120 8121 8122 8123 8124 8125 8126 8127 8128 8129 8130 8131 8132 8133 8134 8135 8136 8137 8138 8139 8140 8141 8142 8143 8144 8145 8146 8147 8148 8149 8150 8151 8152 8153 8154 8155 8156 8157 8158 8159 8160 8161 8162 8163 8164 8165 8166 8167 8168 8169 8170 8171 8172 8173 8174 8175 8176 8177 8178 8179 8180 8181 8182 8183 8184 8185 8186 8187 8188 8189 8190 8191 8192 8193 8194 8195 8196 8197 8198 8199 8200 8201 8202 8203 8204 8205 8206 8207 8208 8209 8210 8211 8212 8213 8214 8215 8216 8217 8218 8219 8220 8221 8222 8223 8224 8225 8226 8227 8228 8229 8230 8231 8232 8233 8234 8235 8236 8237 8238 8239 8240 8241 8242 8243 8244 8245 8246 8247 8248 8249 8250 8251 8252 8253 8254 8255 8256 8257 8258 8259 8260 8261 8262 8263 8264 8265 8266 8267 8268 8269 8270 8271 8272 8273 8274 8275 8276 8277 8278 8279 8280 8281 8282 8283 8284 8285 8286 8287 8288 8289 8290 8291 8292 8293 8294 8295 8296 8297 8298 8299 8300 8301 8302 8303 8304 8305 8306 8307 8308 8309 8310 8311 8312 8313 8314 8315 8316 8317 8318 8319 8320 8321 8322 8323 8324 8325 8326 8327 8328 8329 8330 8331 8332 8333 8334 8335 8336 8337 8338 8339 8340 8341 8342 8343 8344 8345 8346 8347 8348 8349 8350 8351 8352 8353 8354 8355 8356 8357 8358 8359 8360 8361 8362 8363 8364 8365 8366 8367 8368 8369 8370 8371 8372 8373 8374 8375 8376 8377 8378 8379 8380 8381 8382 8383 8384 8385 8386 8387 8388 8389 8390 8391 8392 8393 8394 8395 8396 8397 8398 8399 8400 8401 8402 8403 8404 8405 8406 8407 8408 8409 8410 8411 8412 8413 8414 8415 8416 8417 8418 8419 8420 8421 8422 8423 8424 8425 8426 8427 8428 8429 8430 8431 8432 8433 8434 8435 8436 8437 8438 8439 8440 8441 8442 8443 8444 8445 8446 8447 8448 8449 8450 8451 8452 8453 8454 8455 8456 8457 8458 8459 8460 8461 8462 8463 8464 8465 8466 8467 8468 8469 8470 8471 8472 8473 8474 8475 8476 8477 8478 8479 8480 8481 8482 8483 8484 8485 8486 8487 8488 8489 8490 8491 8492 8493 8494 8495 8496 8497 8498 8499 8500 8501 8502 8503 8504 8505 8506 8507 8508 8509 8510 8511 8512 8513 8514 8515 8516 8517 8518 8519 8520 8521 8522 8523 8524 8525 8526 8527 8528 8529 8530 8531 8532 8533 8534 8535 8536 8537 8538 8539 8540 8541 8542 8543 8544 8545 8546 8547 8548 8549 8550 8551 8552 8553 8554 8555 8556 8557 8558 8559 8560 8561 8562 8563 8564 8565 8566 8567 8568 8569 8570 8571 8572 8573 8574 8575 8576 8577 8578 8579 8580 8581 8582 8583 8584 8585 8586 8587 8588 8589 8590 8591 8592 8593 8594 8595 8596 8597 8598 8599 8600 8601 8602 8603 8604 8605 8606 8607 8608 8609 8610 8611 8612 8613 8614 8615 8616 8617 8618 8619 8620 8621 8622 8623 8624 8625 8626 8627 8628 8629 8630 8631 8632 8633 8634 8635 8636 8637 8638 8639 8640 8641 8642 8643 8644 8645 8646 8647 8648 8649 8650 8651 8652 8653 8654 8655 8656 8657 8658 8659 8660 8661 8662 8663 8664 8665 8666 8667 8668 8669 8670 8671 8672 8673 8674 8675 8676 8677 8678 8679 8680 8681 8682 8683 8684 8685 8686 8687 8688 8689 8690 8691 8692 8693 8694 8695 8696 8697 8698 8699 8700 8701 8702 8703 8704 8705 8706 8707 8708 8709 8710 8711 8712 8713 8714 8715 8716 8717 8718 8719 8720 8721 8722 8723 8724 8725 8726 8727 8728 8729 8730 8731 8732 8733 8734 8735 8736 8737 8738 8739 8740 8741 8742 8743 8744 8745 8746 8747 8748 8749 8750 8751 8752 8753 8754 8755 8756 8757 8758 8759 8760 8761 8762 8763 8764 8765 8766 8767 8768 8769 8770 8771 8772 8773 8774 8775 8776 8777 8778 8779 8780 8781 8782 8783 8784 8785 8786 8787 8788 8789 8790 8791 8792 8793 8794 8795 8796 8797 8798 8799 8800 8801 8802 8803 8804 8805 8806 8807 8808 8809 8810 8811 8812 8813 8814 8815 8816 8817 8818 8819 8820 8821 8822 8823 8824 8825 8826 8827 8828 8829 8830 8831 8832 8833 8834 8835 8836 8837 8838 8839 8840 8841 8842 8843 8844 8845 8846 8847 8848 8849 8850 8851 8852 8853 8854 8855 8856 8857 8858 8859 8860 8861 8862 8863 8864 8865 8866 8867 8868 8869 8870 8871 8872 8873 8874 8875 8876 8877 8878 8879 8880 8881 8882 8883 8884 8885 8886 8887 8888 8889 8890 8891 8892 8893 8894 8895 8896 8897 8898 8899 8900 8901 8902 8903 8904 8905 8906 8907 8908 8909 8910 8911 8912 8913 8914 8915 8916 8917 8918 8919 8920 8921 8922 8923 8924 8925 8926 8927 8928 8929 8930 8931 8932 8933 8934 8935 8936 8937 8938 8939 8940 8941 8942 8943 8944 8945 8946 8947 8948 8949 8950 8951 8952 8953 8954 8955 8956 8957 8958 8959 8960 8961 8962 8963 8964 8965 8966 8967 8968 8969 8970 8971 8972 8973 8974 8975 8976 8977 8978 8979 8980 8981 8982 8983 8984 8985 8986 8987 8988 8989 8990 8991 8992 8993 8994 8995 8996 8997 8998 8999 9000 9001 9002 9003 9004 9005 9006 9007 9008 9009 9010 9011 9012 9013 9014 9015 9016 9017 9018 9019 9020 9021 9022 9023 9024 9025 9026 9027 9028 9029 9030 9031 9032 9033 9034 9035 9036 9037 9038 9039 9040 9041 9042 9043 9044 9045 9046 9047 9048 9049 9050 9051 9052 9053 9054 9055 9056 9057 9058 9059 9060 9061 9062 9063 9064 9065 9066 9067 9068 9069 9070 9071 9072 9073 9074 9075 9076 9077 9078 9079 9080 9081 9082 9083 9084 9085 9086 9087 9088 9089 9090 9091 9092 9093 9094 9095 9096 9097 9098 9099 9100 9101 9102 9103 9104 9105 9106 9107 9108 9109 9110 9111 9112 9113 9114 9115 9116 9117 9118 9119 9120 9121 9122 9123 9124 9125 9126 9127 9128 9129 9130 9131 9132 9133 9134 9135 9136 9137 9138 9139 9140 9141 9142 9143 9144 9145 9146 9147 9148 9149 9150 9151 9152 9153 9154 9155 9156 9157 9158 9159 9160 9161 9162 9163 9164 9165 9166 9167 9168 9169 9170 9171 9172 9173 9174 9175 9176 9177 9178 9179 9180 9181 9182 9183 9184 9185 9186 9187 9188 9189 9190 9191 9192 9193 9194 9195 9196 9197 9198 9199 9200 9201 9202 9203 9204 9205 9206 9207 9208 9209 9210 9211 9212 9213 9214 9215 9216 9217 9218 9219 9220 9221 9222 9223 9224 9225 9226 9227 9228 9229 9230 9231 9232 9233 9234 9235 9236 9237 9238 9239 9240 9241 9242 9243 9244 9245 9246 9247 9248 9249 9250 9251 9252 9253 9254 9255 9256 9257 9258 9259 9260 9261 9262 9263 9264 9265 9266 9267 9268 9269 9270 9271 9272 9273 9274 9275 9276 9277 9278 9279 9280 9281 9282 9283 9284 9285 9286 9287 9288 9289 9290 9291 9292 9293 9294 9295 9296 9297 9298 9299 9300 9301 9302 9303 9304 9305 9306 9307 9308 9309 9310 9311 9312 9313 9314 9315 9316 9317 9318 9319 9320 9321 9322 9323 9324 9325 9326 9327 9328 9329 9330 9331 9332 9333 9334 9335 9336 9337 9338 9339 9340 9341 9342 9343 9344 9345 9346 9347 9348 9349 9350 9351 9352 9353 9354 9355 9356 9357 9358 9359 9360 9361 9362 9363 9364 9365 9366 9367 9368 9369 9370 9371 9372 9373 9374 9375 9376 9377 9378 9379 9380 9381 9382 9383 9384 9385 9386 9387 9388 9389 9390 9391 9392 9393 9394 9395 9396 9397 9398 9399 9400 9401 9402 9403 9404 9405 9406 9407 9408 9409 9410 9411 9412 9413 9414 9415 9416 9417 9418 9419 9420 9421 9422 9423 9424 9425 9426 9427 9428 9429 9430 9431 9432 9433 9434 9435 9436 9437 9438 9439 9440 9441 9442 9443 9444 9445 9446 9447 9448 9449 9450 9451 9452 9453 9454 9455 9456 9457 9458 9459 9460 9461 9462 9463 9464 9465 9466 9467 9468 9469 9470 9471 9472 9473 9474 9475 9476 9477 9478 9479 9480 9481 9482 9483 9484 9485 9486 9487 9488 9489 9490 9491 9492 9493 9494 9495 9496 9497 9498 9499 9500 9501 9502 9503 9504 9505 9506 9507 9508 9509 9510 9511 9512 9513 9514 9515 9516 9517 9518 9519 9520 9521 9522 9523 9524 9525 9526 9527 9528 9529 9530 9531 9532 9533 9534 9535 9536 9537 9538 9539 9540 9541 9542 9543 9544 9545 9546 9547 9548 9549 9550 9551 9552 9553 9554 9555 9556 9557 9558 9559 9560 9561 9562 9563 9564 9565 9566 9567 9568 9569 9570 9571 9572 9573 9574 9575 9576 9577 9578 9579 9580 9581 9582 9583 9584 9585 9586 9587 9588 9589 9590 9591 9592 9593 9594 9595 9596 9597 9598 9599 9600 9601 9602
|
// Copyright 2015 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/browser/renderer_host/render_frame_host_impl.h"
#include <initializer_list>
#include <memory>
#include <optional>
#include <string>
#include <string_view>
#include <utility>
#include "base/command_line.h"
#include "base/containers/contains.h"
#include "base/files/file_path.h"
#include "base/functional/bind.h"
#include "base/functional/callback_helpers.h"
#include "base/memory/ptr_util.h"
#include "base/memory/raw_ptr.h"
#include "base/memory/raw_ref.h"
#include "base/path_service.h"
#include "base/run_loop.h"
#include "base/strings/strcat.h"
#include "base/strings/string_util.h"
#include "base/strings/stringprintf.h"
#include "base/strings/utf_string_conversions.h"
#include "base/task/single_thread_task_runner.h"
#include "base/test/bind.h"
#include "base/test/gtest_util.h"
#include "base/test/metrics/histogram_tester.h"
#include "base/test/mock_callback.h"
#include "base/test/run_until.h"
#include "base/test/scoped_feature_list.h"
#include "build/build_config.h"
#include "components/input/timeout_monitor.h"
#include "components/viz/common/features.h"
#include "content/browser/browser_main_loop.h"
#include "content/browser/renderer_host/navigation_request.h"
#include "content/browser/renderer_host/origin_trial_state_host_impl.h"
#include "content/browser/renderer_host/render_process_host_impl.h"
#include "content/browser/sms/test/mock_sms_provider.h"
#include "content/browser/web_contents/web_contents_impl.h"
#include "content/common/content_navigation_policy.h"
#include "content/common/features.h"
#include "content/common/frame.mojom-forward.h"
#include "content/common/frame.mojom-shared.h"
#include "content/common/frame.mojom-test-utils.h"
#include "content/common/frame_messages.mojom.h"
#include "content/public/browser/browser_context.h"
#include "content/public/browser/cors_origin_pattern_setter.h"
#include "content/public/browser/document_service.h"
#include "content/public/browser/document_user_data.h"
#include "content/public/browser/javascript_dialog_manager.h"
#include "content/public/browser/origin_trials_controller_delegate.h"
#include "content/public/browser/page_user_data.h"
#include "content/public/browser/render_frame_host.h"
#include "content/public/browser/web_contents.h"
#include "content/public/browser/web_contents_observer.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/common/page_visibility_state.h"
#include "content/public/common/url_constants.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/commit_message_delayer.h"
#include "content/public/test/content_browser_test.h"
#include "content/public/test/content_browser_test_content_browser_client.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/render_frame_host_test_support.h"
#include "content/public/test/simple_url_loader_test_helper.h"
#include "content/public/test/test_frame_navigation_observer.h"
#include "content/public/test/test_navigation_observer.h"
#include "content/public/test/test_navigation_throttle.h"
#include "content/public/test/test_navigation_throttle_inserter.h"
#include "content/public/test/test_utils.h"
#include "content/public/test/url_loader_interceptor.h"
#include "content/shell/browser/shell.h"
#include "content/shell/browser/shell_browser_context.h"
#include "content/shell/browser/shell_content_browser_client.h"
#include "content/test/content_browser_test_utils_internal.h"
#include "content/test/data/mojo_web_test_helper.test-mojom.h"
#include "content/test/did_commit_navigation_interceptor.h"
#include "content/test/frame_host_test_interface.mojom.h"
#include "content/test/test_render_frame_host_factory.h"
#include "mojo/public/cpp/bindings/self_owned_receiver.h"
#include "net/base/features.h"
#include "net/base/net_errors.h"
#include "net/base/schemeful_site.h"
#include "net/dns/mock_host_resolver.h"
#include "net/test/embedded_test_server/connection_tracker.h"
#include "net/test/embedded_test_server/controllable_http_response.h"
#include "net/test/embedded_test_server/default_handlers.h"
#include "net/test/embedded_test_server/embedded_test_server.h"
#include "net/test/embedded_test_server/http_request.h"
#include "net/test/embedded_test_server/request_handler_util.h"
#include "net/traffic_annotation/network_traffic_annotation_test_helper.h"
#include "services/metrics/public/cpp/ukm_source_id.h"
#include "services/network/public/cpp/features.h"
#include "services/network/public/cpp/network_switches.h"
#include "services/network/public/cpp/resource_request.h"
#include "services/network/public/cpp/simple_url_loader.h"
#include "services/network/public/mojom/connection_change_observer_client.mojom.h"
#include "services/network/public/mojom/network_context.mojom.h"
#include "services/network/public/mojom/url_loader_factory.mojom.h"
#include "services/network/test/test_url_loader_factory.h"
#include "services/service_manager/public/cpp/interface_provider.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/switches.h"
#include "third_party/blink/public/mojom/browser_interface_broker.mojom-test-utils.h"
#include "third_party/blink/public/mojom/frame/frame.mojom-test-utils.h"
#include "url/gurl.h"
#include "url/origin.h"
#if BUILDFLAG(IS_ANDROID)
#include "base/android/build_info.h"
#include "content/browser/renderer_host/render_widget_host_view_android.h"
#include "third_party/blink/public/mojom/remote_objects/remote_objects.mojom.h"
#include "ui/android/delegated_frame_host_android.h"
#endif // BUILDFLAG(IS_ANDROID)
#if defined(USE_AURA)
#include "content/browser/renderer_host/delegated_frame_host.h"
#include "content/browser/renderer_host/render_widget_host_view_aura.h"
#endif // defined(USE_AURA)
#if BUILDFLAG(IS_MAC)
#include "content/browser/renderer_host/browser_compositor_view_mac.h"
#include "content/browser/renderer_host/test_render_widget_host_view_mac_factory.h"
#endif
#if BUILDFLAG(IS_IOS)
#include "content/browser/renderer_host/browser_compositor_ios.h"
#include "content/browser/renderer_host/test_render_widget_host_view_ios_factory.h"
#endif
namespace content {
namespace {
const char kTrustMeUrl[] = "trustme://host/path/";
const char kTrustMeIfEmbeddingSecureUrl[] =
"trustmeifembeddingsecure://host/path/";
// Configure trustme: as a scheme that should cause cookies to be treated as
// first-party when top-level, and also installs a URLLoaderFactory that
// makes all requests to it via kTrustMeUrl return a particular iframe.
// Same for trustmeifembeddingsecure, which does the same if the embedded origin
// is secure.
class FirstPartySchemeContentBrowserClient
: public ContentBrowserTestContentBrowserClient {
public:
explicit FirstPartySchemeContentBrowserClient(const GURL& iframe_url)
: iframe_url_(iframe_url) {
trustme_factory_ = std::make_unique<network::TestURLLoaderFactory>();
trustmeifembeddingsecure_factory_ =
std::make_unique<network::TestURLLoaderFactory>();
std::string response_body =
base::StrCat({"<iframe src=\"", iframe_url_.spec(), "\"></iframe>"});
trustme_factory_->AddResponse(kTrustMeUrl, response_body);
trustmeifembeddingsecure_factory_->AddResponse(kTrustMeIfEmbeddingSecureUrl,
response_body);
}
FirstPartySchemeContentBrowserClient(
const FirstPartySchemeContentBrowserClient&) = delete;
FirstPartySchemeContentBrowserClient& operator=(
const FirstPartySchemeContentBrowserClient&) = delete;
~FirstPartySchemeContentBrowserClient() override = default;
bool ShouldTreatURLSchemeAsFirstPartyWhenTopLevel(
std::string_view scheme,
bool is_embedded_origin_secure) override {
if (is_embedded_origin_secure && scheme == "trustmeifembeddingsecure")
return true;
return scheme == "trustme";
}
mojo::PendingRemote<network::mojom::URLLoaderFactory>
CreateNonNetworkNavigationURLLoaderFactory(
const std::string& scheme,
FrameTreeNodeId frame_tree_node_id) override {
if (scheme == "trustme") {
mojo::PendingRemote<network::mojom::URLLoaderFactory> trustme_remote;
trustme_factory_->Clone(trustme_remote.InitWithNewPipeAndPassReceiver());
return trustme_remote;
}
if (scheme == "trustmeifembeddingsecure") {
mojo::PendingRemote<network::mojom::URLLoaderFactory>
trustmeifembeddingsecure_remote;
trustmeifembeddingsecure_factory_->Clone(
trustmeifembeddingsecure_remote.InitWithNewPipeAndPassReceiver());
return trustmeifembeddingsecure_remote;
}
return {};
}
private:
GURL iframe_url_;
std::unique_ptr<network::TestURLLoaderFactory> trustme_factory_;
std::unique_ptr<network::TestURLLoaderFactory>
trustmeifembeddingsecure_factory_;
};
} // namespace
// TODO(mlamouri): part of these tests were removed because they were dependent
// on an environment were focus is guaranteed. This is only for
// interactive_ui_tests so these bits need to move there.
// See https://crbug.com/491535
class RenderFrameHostImplBrowserTest : public ContentBrowserTest {
public:
using LifecycleStateImpl = RenderFrameHostImpl::LifecycleStateImpl;
using NavigationStartAdjustmentType =
NavigationRequest::NavigationStartAdjustmentType;
RenderFrameHostImplBrowserTest()
: https_server_(net::EmbeddedTestServer::TYPE_HTTPS) {}
~RenderFrameHostImplBrowserTest() override = default;
// Return an URL for loading a local test file.
GURL GetFileURL(const base::FilePath::CharType* file_path) {
base::FilePath path;
CHECK(base::PathService::Get(base::DIR_SRC_TEST_DATA_ROOT, &path));
path = path.Append(GetTestDataFilePath());
path = path.Append(file_path);
return GURL("file:" + path.AsUTF8Unsafe());
}
protected:
void SetUpOnMainThread() override {
host_resolver()->AddRule("*", "127.0.0.1");
SetupCrossSiteRedirector(embedded_test_server());
ASSERT_TRUE(embedded_test_server()->Start());
}
void SetUpCommandLine(base::CommandLine* command_line) override {
// TODO(crbug.com/40554401): Remove this when the new Java Bridge code
// is integrated into WebView.
command_line->AppendSwitchASCII(blink::switches::kJavaScriptFlags,
"--expose_gc");
command_line->AppendSwitchASCII(switches::kEnableBlinkFeatures, "WebOTP");
// URLLoaderFactoryNotTrusted test could trigger ReportBadMessage and crash
// network service process. Use kIgnoreBadMessageForTesting switch to
// ignore the bad message.
command_line->AppendSwitch(network::switches::kIgnoreBadMessageForTesting);
}
net::EmbeddedTestServer* https_server() { return &https_server_; }
WebContentsImpl* web_contents() const {
return static_cast<WebContentsImpl*>(shell()->web_contents());
}
RenderFrameHostImpl* root_frame_host() const {
return web_contents()->GetPrimaryMainFrame();
}
private:
net::EmbeddedTestServer https_server_;
};
std::string ExecuteJavaScriptMethodAndGetResult(
RenderFrameHostImpl* render_frame,
const std::string& object,
const std::string& method,
base::Value::List arguments) {
bool executing = true;
std::string result;
base::OnceCallback<void(base::Value)> call_back = base::BindOnce(
[](bool* flag, std::string* reason, base::Value value) {
*flag = false;
DCHECK(value.is_string());
*reason = value.GetString();
},
base::Unretained(&executing), base::Unretained(&result));
render_frame->ExecuteJavaScriptMethod(
base::UTF8ToUTF16(object), base::UTF8ToUTF16(method),
std::move(arguments), std::move(call_back));
while (executing) {
base::RunLoop loop;
loop.RunUntilIdle();
}
return result;
}
// Navigates to a URL and waits till the navigation is finished. It doesn't wait
// for the load to complete. Use this instead of NavigateToURL in tests that are
// testing navigation related cases and doesn't need the load to finish. Load
// could get blocked on blink::mojom::CodeCacheHostInterface if the browser
// interface is not available.
bool NavigateToURLAndDoNotWaitForLoadStop(Shell* window, const GURL& url) {
TestNavigationManager observer(window->web_contents(), url);
window->LoadURL(url);
EXPECT_TRUE(observer.WaitForNavigationFinished());
return url ==
window->web_contents()->GetPrimaryMainFrame()->GetLastCommittedURL();
}
// Navigates an iframe nested within another iframe to the specified URL via
// Javascript executed from the outer document. Also, this waits for the
// navigation to finish.
void NavigateToURLFromGrandparentDocument(Shell* window, const GURL& url) {
RenderFrameHostImpl* rfh_grandparent =
static_cast<WebContentsImpl*>(window->web_contents())
->GetPrimaryMainFrame();
RenderFrameHostImpl* rfh_parent =
rfh_grandparent->child_at(0)->current_frame_host();
RenderFrameHostImpl* rfh_child =
rfh_parent->child_at(0)->current_frame_host();
// If we are navigating from a.com/ to a.com/#x or vice versa, we expect this
// to be a same-document navigation.
bool expected_is_same_document =
rfh_child->GetLastCommittedURL().GetWithoutRef() == url.GetWithoutRef();
TestNavigationManager navigation_manager(window->web_contents(), url);
NavigationHandleObserver navigation_observer(window->web_contents(), url);
ASSERT_TRUE(
ExecJs(rfh_grandparent,
JsReplace("frames[0].frames[0].location.href = $1;", url)));
ASSERT_TRUE(navigation_manager.WaitForNavigationFinished());
ASSERT_FALSE(navigation_observer.is_error());
ASSERT_EQ(navigation_observer.last_committed_url(), url);
rfh_child = rfh_parent->child_at(0)->current_frame_host();
ASSERT_EQ(navigation_observer.frame_tree_node_id(),
rfh_child->GetFrameTreeNodeId());
EXPECT_EQ(navigation_observer.is_same_document(), expected_is_same_document);
}
// Returns the `initiator_origin` member of the last committed frame navigation
// entry corresponding to `rfh`. For more information on the returned value, see
// `FrameNavigationEntry::initiator_origin()`.
std::optional<url::Origin> GetInitiatorOrigin(RenderFrameHostImpl* rfh) {
FrameTreeNode* frame_tree_node = rfh->frame_tree_node();
FrameNavigationEntry* frame_navigation_entry =
frame_tree_node->frame_tree()
.controller()
.GetLastCommittedEntry()
->GetFrameEntry(frame_tree_node);
EXPECT_TRUE(frame_navigation_entry);
return frame_navigation_entry->initiator_origin();
}
using blink::mojom::BlockingDetails;
using BackForwardCacheBlockingDetails =
RenderFrameHostImpl::BackForwardCacheBlockingDetails;
using BlocklistedFeature = blink::scheduler::WebSchedulerTrackedFeature;
using BlocklistedFeatures = blink::scheduler::WebSchedulerTrackedFeatures;
// Helper function to create a vector which contains the mojom feature
// information.
BackForwardCacheBlockingDetails CreateBlockingDetails(
std::initializer_list<BlocklistedFeature> features) {
BackForwardCacheBlockingDetails feature_vector;
for (auto feature : features) {
auto feature_info = BlockingDetails::New();
feature_info->feature = static_cast<uint32_t>(feature);
feature_vector.push_back(std::move(feature_info));
}
return feature_vector;
}
// This is for the test cases where the beforeunload handlers are handled in a
// legacy way. See the comment about `for_legacy` on
// `RenderFrameHostImpl::SendBeforeUnload()`.
class RenderFrameHostImplWithLegacyBeforeUnloadBrowserTest
: public RenderFrameHostImplBrowserTest {
public:
RenderFrameHostImplWithLegacyBeforeUnloadBrowserTest() {
scoped_feature_list_.InitAndDisableFeature(
features::kAvoidUnnecessaryBeforeUnloadCheckSync);
}
private:
base::test::ScopedFeatureList scoped_feature_list_;
};
// This is a parameterized test that covers the beforeunload handlers are
// handled in both legacy and non-legacy ways. See the comment about
// `for_legacy` on `RenderFrameHostImpl::SendBeforeUnload()`.
class RenderFrameHostImplWithOrWithoutLegacyBeforeUnloadBrowserTest
: public RenderFrameHostImplBrowserTest,
public testing::WithParamInterface<bool> {
public:
RenderFrameHostImplWithOrWithoutLegacyBeforeUnloadBrowserTest() {
if (UseLegacyPostTaskForBeforeUnload()) {
scoped_feature_list_.InitAndDisableFeature(
features::kAvoidUnnecessaryBeforeUnloadCheckSync);
} else {
scoped_feature_list_.InitWithFeaturesAndParameters(
/*enabled_features=*/
{{features::kAvoidUnnecessaryBeforeUnloadCheckSync,
{{features::kAvoidUnnecessaryBeforeUnloadCheckSyncMode.name,
"WithoutSendBeforeUnload"}}}},
/*disabled_features=*/{});
}
}
bool UseLegacyPostTaskForBeforeUnload() const { return GetParam(); }
// Provides meaningful param names instead of /0, /1, ...
static std::string DescribeParams(
const testing::TestParamInfo<ParamType>& info) {
return info.param ? "WithLegacyBeforeUnload" : "WithoutLegacyBeforeUnload";
}
private:
base::test::ScopedFeatureList scoped_feature_list_;
};
INSTANTIATE_TEST_SUITE_P(
All,
RenderFrameHostImplWithOrWithoutLegacyBeforeUnloadBrowserTest,
testing::Bool(),
RenderFrameHostImplWithOrWithoutLegacyBeforeUnloadBrowserTest::
DescribeParams);
IN_PROC_BROWSER_TEST_F(RenderFrameHostImplBrowserTest,
ExecuteJavaScriptMethodWorksWithArguments) {
EXPECT_TRUE(NavigateToURL(
shell(), GetTestUrl("render_frame_host", "jsMethodTest.html")));
RenderFrameHostImpl* render_frame = web_contents()->GetPrimaryMainFrame();
render_frame->AllowInjectingJavaScript();
base::Value::List empty_arguments;
std::string result = ExecuteJavaScriptMethodAndGetResult(
render_frame, "window", "someMethod", std::move(empty_arguments));
EXPECT_EQ(result, "called someMethod()");
base::Value::List single_arguments;
single_arguments.Append("arg1");
result = ExecuteJavaScriptMethodAndGetResult(
render_frame, "window", "someMethod", std::move(single_arguments));
EXPECT_EQ(result, "called someMethod(arg1)");
base::Value::List four_arguments;
four_arguments.Append("arg1");
four_arguments.Append("arg2");
four_arguments.Append("arg3");
four_arguments.Append("arg4");
result = ExecuteJavaScriptMethodAndGetResult(
render_frame, "window", "someMethod", std::move(four_arguments));
EXPECT_EQ(result, "called someMethod(arg1,arg2,arg3,arg4)");
}
// Tests that IPC messages that are dropped (because they are sent before
// RenderFrameCreated) do not prevent later IPC messages from being sent after
// the RenderFrame is created. See https://crbug.com/1154852.
IN_PROC_BROWSER_TEST_F(RenderFrameHostImplBrowserTest,
MessagesBeforeAndAfterRenderFrameCreated) {
// Start with a WebContents that hasn't created its main RenderFrame.
WebContents* web_contents = shell()->web_contents();
ASSERT_FALSE(web_contents->GetPrimaryMainFrame()->IsRenderFrameLive());
// An attempt to run script via GetAssociatedLocalFrame will do nothing before
// the RenderFrame is created, since the message sent to the renderer will get
// dropped. In https://crbug.com/1154852, this causes future messages sent via
// GetAssociatedLocalFrame to also be dropped.
web_contents->GetPrimaryMainFrame()->ExecuteJavaScriptForTests(
u"'foo'", base::NullCallback(), ISOLATED_WORLD_ID_GLOBAL);
// Navigating will create the RenderFrame.
GURL url(embedded_test_server()->GetURL("/title1.html"));
EXPECT_TRUE(NavigateToURL(shell(), url));
ASSERT_TRUE(web_contents->GetPrimaryMainFrame()->IsRenderFrameLive());
// Future attempts to run script via GetAssociatedLocalFrame should succeed.
// This timed out before the fix, since the message was dropped and no value
// was retrieved.
EXPECT_EQ("foo", EvalJs(web_contents->GetPrimaryMainFrame(), "'foo'"));
}
// Test that when creating a new window, the main frame is correctly focused.
IN_PROC_BROWSER_TEST_F(RenderFrameHostImplBrowserTest, IsFocused_AtLoad) {
EXPECT_TRUE(
NavigateToURL(shell(), GetTestUrl("render_frame_host", "focus.html")));
// The main frame should be focused.
EXPECT_EQ(web_contents()->GetPrimaryMainFrame(),
web_contents()->GetFocusedFrame());
}
// Test that if the content changes the focused frame, it is correctly exposed.
IN_PROC_BROWSER_TEST_F(RenderFrameHostImplBrowserTest, IsFocused_Change) {
EXPECT_TRUE(
NavigateToURL(shell(), GetTestUrl("render_frame_host", "focus.html")));
std::string frames[2] = {"frame1", "frame2"};
for (const std::string& frame : frames) {
EXPECT_TRUE(
ExecJs(web_contents()->GetPrimaryMainFrame(), "focus" + frame + "()"));
// The main frame is not the focused frame in the frame tree but the main
// frame is focused per RFHI rules because one of its descendant is focused.
// TODO(mlamouri): we should check the frame focus state per RFHI, see the
// general comment at the beginning of this test file.
EXPECT_NE(web_contents()->GetPrimaryMainFrame(),
web_contents()->GetFocusedFrame());
EXPECT_EQ(frame, web_contents()->GetFocusedFrame()->GetFrameName());
}
}
// Tests focus behavior when the focused frame is removed from the frame tree.
IN_PROC_BROWSER_TEST_F(RenderFrameHostImplBrowserTest, RemoveFocusedFrame) {
EXPECT_TRUE(
NavigateToURL(shell(), GetTestUrl("render_frame_host", "focus.html")));
EXPECT_TRUE(ExecJs(web_contents()->GetPrimaryMainFrame(), "focusframe4()"));
EXPECT_NE(web_contents()->GetPrimaryMainFrame(),
web_contents()->GetFocusedFrame());
EXPECT_EQ("frame4", web_contents()->GetFocusedFrame()->GetFrameName());
EXPECT_EQ("frame3",
web_contents()->GetFocusedFrame()->GetParent()->GetFrameName());
EXPECT_TRUE(
web_contents()->GetPrimaryFrameTree().focused_frame_tree_node_id_);
EXPECT_TRUE(ExecJs(web_contents()->GetPrimaryMainFrame(), "detachframe(3)"));
EXPECT_EQ(nullptr, web_contents()->GetFocusedFrame());
EXPECT_TRUE(web_contents()
->GetPrimaryFrameTree()
.focused_frame_tree_node_id_.is_null());
EXPECT_TRUE(ExecJs(web_contents()->GetPrimaryMainFrame(), "focusframe2()"));
EXPECT_NE(nullptr, web_contents()->GetFocusedFrame());
EXPECT_NE(web_contents()->GetPrimaryMainFrame(),
web_contents()->GetFocusedFrame());
EXPECT_TRUE(
web_contents()->GetPrimaryFrameTree().focused_frame_tree_node_id_);
EXPECT_TRUE(ExecJs(web_contents()->GetPrimaryMainFrame(), "detachframe(2)"));
EXPECT_EQ(nullptr, web_contents()->GetFocusedFrame());
EXPECT_TRUE(web_contents()
->GetPrimaryFrameTree()
.focused_frame_tree_node_id_.is_null());
}
// Test that a frame is visible/hidden depending on its WebContents visibility
// state.
IN_PROC_BROWSER_TEST_F(RenderFrameHostImplBrowserTest,
GetVisibilityState_Basic) {
EXPECT_TRUE(NavigateToURL(shell(), GURL("data:text/html,foo")));
web_contents()->WasShown();
EXPECT_EQ(PageVisibilityState::kVisible,
web_contents()->GetPrimaryMainFrame()->GetVisibilityState());
web_contents()->WasHidden();
EXPECT_EQ(PageVisibilityState::kHidden,
web_contents()->GetPrimaryMainFrame()->GetVisibilityState());
}
// Check that the URLLoaderFactories created by RenderFrameHosts for renderers
// are not trusted.
IN_PROC_BROWSER_TEST_F(RenderFrameHostImplBrowserTest,
URLLoaderFactoryNotTrusted) {
EXPECT_TRUE(NavigateToURL(shell(), embedded_test_server()->GetURL("/echo")));
mojo::Remote<network::mojom::URLLoaderFactory> url_loader_factory;
web_contents()->GetPrimaryMainFrame()->CreateNetworkServiceDefaultFactory(
url_loader_factory.BindNewPipeAndPassReceiver());
std::unique_ptr<network::ResourceRequest> request =
std::make_unique<network::ResourceRequest>();
request->url = embedded_test_server()->GetURL("/echo");
request->request_initiator =
url::Origin::Create(embedded_test_server()->base_url());
request->trusted_params = network::ResourceRequest::TrustedParams();
content::SimpleURLLoaderTestHelper simple_loader_helper;
std::unique_ptr<network::SimpleURLLoader> simple_loader =
network::SimpleURLLoader::Create(std::move(request),
TRAFFIC_ANNOTATION_FOR_TESTS);
simple_loader->DownloadToStringOfUnboundedSizeUntilCrashAndDie(
url_loader_factory.get(), simple_loader_helper.GetCallbackDeprecated());
simple_loader_helper.WaitForCallback();
EXPECT_FALSE(simple_loader_helper.response_body());
EXPECT_EQ(net::ERR_INVALID_ARGUMENT, simple_loader->NetError());
}
namespace {
class TestJavaScriptDialogManager : public JavaScriptDialogManager,
public WebContentsDelegate {
public:
TestJavaScriptDialogManager()
: message_loop_runner_(new MessageLoopRunner), url_invalidate_count_(0) {}
TestJavaScriptDialogManager(const TestJavaScriptDialogManager&) = delete;
TestJavaScriptDialogManager& operator=(const TestJavaScriptDialogManager&) =
delete;
~TestJavaScriptDialogManager() override {}
// This waits until either WCD::BeforeUnloadFired is called (the unload has
// been handled) or JSDM::RunJavaScriptDialog/RunBeforeUnloadDialog is called
// (a request to display a dialog has been received).
void Wait() {
message_loop_runner_->Run();
message_loop_runner_ = new MessageLoopRunner;
}
// Runs the dialog callback.
void Run(bool success, const std::u16string& user_input) {
std::move(callback_).Run(success, user_input);
}
int num_beforeunload_dialogs_seen() { return num_beforeunload_dialogs_seen_; }
int num_beforeunload_fired_seen() { return num_beforeunload_fired_seen_; }
bool proceed() { return proceed_; }
// WebContentsDelegate
JavaScriptDialogManager* GetJavaScriptDialogManager(
WebContents* source) override {
return this;
}
void BeforeUnloadFired(WebContents* tab,
bool proceed,
bool* proceed_to_fire_unload) override {
++num_beforeunload_fired_seen_;
proceed_ = proceed;
message_loop_runner_->Quit();
}
// JavaScriptDialogManager
void RunJavaScriptDialog(WebContents* web_contents,
RenderFrameHost* render_frame_host,
JavaScriptDialogType dialog_type,
const std::u16string& message_text,
const std::u16string& default_prompt_text,
DialogClosedCallback callback,
bool* did_suppress_message) override {
callback_ = std::move(callback);
message_loop_runner_->Quit();
}
void RunBeforeUnloadDialog(WebContents* web_contents,
RenderFrameHost* render_frame_host,
bool is_reload,
DialogClosedCallback callback) override {
++num_beforeunload_dialogs_seen_;
callback_ = std::move(callback);
message_loop_runner_->Quit();
}
bool HandleJavaScriptDialog(WebContents* web_contents,
bool accept,
const std::u16string* prompt_override) override {
return true;
}
void CancelDialogs(WebContents* web_contents, bool reset_state) override {}
// Keep track of whether the tab has notified us of a navigation state change
// which invalidates the displayed URL.
void NavigationStateChanged(WebContents* source,
InvalidateTypes changed_flags) override {
if (changed_flags & INVALIDATE_TYPE_URL)
url_invalidate_count_++;
}
int url_invalidate_count() { return url_invalidate_count_; }
void reset_url_invalidate_count() { url_invalidate_count_ = 0; }
private:
DialogClosedCallback callback_;
// The MessageLoopRunner used to spin the message loop.
scoped_refptr<MessageLoopRunner> message_loop_runner_;
// The number of times NavigationStateChanged has been called.
int url_invalidate_count_;
// The total number of beforeunload dialogs seen by this dialog manager.
int num_beforeunload_dialogs_seen_ = 0;
// The total number of BeforeUnloadFired events witnessed by the
// WebContentsDelegate.
int num_beforeunload_fired_seen_ = 0;
// The |proceed| value returned by the last unload event.
bool proceed_ = false;
};
// A RenderFrameHostImpl that discards callback for BeforeUnload.
class RenderFrameHostImplForBeforeUnloadInterceptor
: public RenderFrameHostImpl {
public:
using RenderFrameHostImpl::RenderFrameHostImpl;
void SendBeforeUnload(bool is_reload,
base::WeakPtr<RenderFrameHostImpl> rfh,
bool for_legacy,
const bool is_renderer_initiated_navigation) override {
rfh->GetAssociatedLocalFrame()->BeforeUnload(is_reload, base::DoNothing());
}
private:
friend class RenderFrameHostFactoryForBeforeUnloadInterceptor;
};
class RenderFrameHostFactoryForBeforeUnloadInterceptor
: public TestRenderFrameHostFactory {
protected:
std::unique_ptr<RenderFrameHostImpl> CreateRenderFrameHost(
SiteInstance* site_instance,
scoped_refptr<RenderViewHostImpl> render_view_host,
RenderFrameHostDelegate* delegate,
FrameTree* frame_tree,
FrameTreeNode* frame_tree_node,
int32_t routing_id,
mojo::PendingAssociatedRemote<mojom::Frame> frame_remote,
const blink::LocalFrameToken& frame_token,
const blink::DocumentToken& document_token,
base::UnguessableToken devtools_frame_token,
bool renderer_initiated_creation,
RenderFrameHostImpl::LifecycleStateImpl lifecycle_state,
scoped_refptr<BrowsingContextState> browsing_context_state) override {
return base::WrapUnique(new RenderFrameHostImplForBeforeUnloadInterceptor(
site_instance, std::move(render_view_host), delegate, frame_tree,
frame_tree_node, routing_id, std::move(frame_remote), frame_token,
document_token, devtools_frame_token, renderer_initiated_creation,
lifecycle_state, std::move(browsing_context_state),
frame_tree_node->frame_owner_element_type(), frame_tree_node->parent(),
frame_tree_node->fenced_frame_status()));
}
};
} // namespace
// Tests that a beforeunload dialog in an iframe doesn't stop the beforeunload
// timer of a parent frame.
// TODO(avi): flaky on Linux TSAN: http://crbug.com/795326
#if (BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS)) && defined(THREAD_SANITIZER)
#define MAYBE_IframeBeforeUnloadParentHang DISABLED_IframeBeforeUnloadParentHang
#else
#define MAYBE_IframeBeforeUnloadParentHang IframeBeforeUnloadParentHang
#endif
IN_PROC_BROWSER_TEST_F(RenderFrameHostImplBrowserTest,
MAYBE_IframeBeforeUnloadParentHang) {
RenderFrameHostFactoryForBeforeUnloadInterceptor interceptor;
TestJavaScriptDialogManager dialog_manager;
web_contents()->SetDelegate(&dialog_manager);
EXPECT_TRUE(NavigateToURL(shell(), GURL("about:blank")));
// Make an iframe with a beforeunload handler.
std::string script =
"var iframe = document.createElement('iframe');"
"document.body.appendChild(iframe);"
"iframe.contentWindow.onbeforeunload=function(e){return 'x'};";
EXPECT_TRUE(ExecJs(web_contents(), script));
EXPECT_TRUE(WaitForLoadStop(web_contents()));
// JavaScript onbeforeunload dialogs require a user gesture.
web_contents()->GetPrimaryMainFrame()->ForEachRenderFrameHostImpl(
[](content::RenderFrameHostImpl* render_frame_host) {
render_frame_host->ExecuteJavaScriptWithUserGestureForTests(
std::u16string(), base::NullCallback(), ISOLATED_WORLD_ID_GLOBAL);
});
// Force a process switch by going to a privileged page. The beforeunload
// timer will be started on the top-level frame but will be paused while the
// beforeunload dialog is shown by the subframe.
GURL web_ui_page(std::string(kChromeUIScheme) + "://" +
std::string(kChromeUIGpuHost));
shell()->LoadURL(web_ui_page);
dialog_manager.Wait();
RenderFrameHostImpl* main_frame = web_contents()->GetPrimaryMainFrame();
EXPECT_TRUE(main_frame->is_waiting_for_beforeunload_completion());
// Answer the dialog.
dialog_manager.Run(true, std::u16string());
// There will be no beforeunload completion callback invocation, so if the
// beforeunload completion callback timer isn't functioning then the
// navigation will hang forever and this test will time out. If this waiting
// for the load stop works, this test won't time out.
EXPECT_TRUE(WaitForLoadStop(web_contents()));
EXPECT_EQ(web_ui_page, web_contents()->GetLastCommittedURL());
web_contents()->SetDelegate(nullptr);
}
// Tests that a gesture is required in a frame before it can request a
// beforeunload dialog.
IN_PROC_BROWSER_TEST_F(RenderFrameHostImplBrowserTest,
BeforeUnloadDialogRequiresGesture) {
TestJavaScriptDialogManager dialog_manager;
web_contents()->SetDelegate(&dialog_manager);
{
base::HistogramTester histogram_tester;
EXPECT_TRUE(NavigateToURL(
shell(), GetTestUrl("render_frame_host", "beforeunload.html")));
histogram_tester.ExpectUniqueSample("Navigation.StartAdjustment.AllFrames",
NavigationStartAdjustmentType::kNone,
1);
histogram_tester.ExpectUniqueSample(
"Navigation.StartAdjustment.MainFrameOnly",
NavigationStartAdjustmentType::kNone, 1);
// Check for timeline metrics, which should include main frame only
// versions.
histogram_tester.ExpectTotalCount(
"Navigation.Timeline.TotalExcludingBeforeUnload.Duration", 1);
histogram_tester.ExpectTotalCount(
"Navigation.Timeline.TotalExcludingBeforeUnload.MainFrameOnly.Duration",
1);
// This navigation has no start adjustment, but the
//`actual_navigation_start` is now recorded at an earlier time (closer to
// the start of the navigation) than the web-facing `navigation_start_time`
// in NavigateWithoutEntry, so this triggers IgnoredIncorrectly metrics.
histogram_tester.ExpectTotalCount(
"Navigation.Timeline.IgnoredIncorrectly.Duration", 1);
histogram_tester.ExpectTotalCount(
"Navigation.Timeline.IgnoredIncorrectly.MainFrameOnly.Duration", 1);
histogram_tester.ExpectTotalCount(
"Navigation.Timeline.IgnoredIncorrectly.Percentage", 1);
histogram_tester.ExpectTotalCount(
"Navigation.Timeline.IgnoredIncorrectly.MainFrameOnly.Percentage", 1);
}
// Disable the hang monitor, otherwise there will be a race between the
// beforeunload dialog and the beforeunload hang timer.
web_contents()
->GetPrimaryMainFrame()
->DisableBeforeUnloadHangMonitorForTesting();
// Reload. There should be no beforeunload dialog because there was no gesture
// on the page. If there was, this WaitForLoadStop call will hang.
{
base::HistogramTester histogram_tester;
web_contents()->GetController().Reload(ReloadType::NORMAL, false);
EXPECT_TRUE(WaitForLoadStop(web_contents()));
histogram_tester.ExpectUniqueSample(
"Navigation.StartAdjustment.AllFrames",
NavigationStartAdjustmentType::kBeforeUnloadHandlers, 1);
histogram_tester.ExpectUniqueSample(
"Navigation.StartAdjustment.MainFrameOnly",
NavigationStartAdjustmentType::kBeforeUnloadHandlers, 1);
histogram_tester.ExpectTotalCount(
"Navigation.StartAdjustment.BeforeUnloadHandlers", 1);
histogram_tester.ExpectTotalCount(
"Navigation.StartAdjustment.BeforeUnloadHandlers.Percentage", 1);
}
// Give the page a user gesture and try reloading again. This time there
// should be a dialog. If there is no dialog, the call to Wait will hang.
web_contents()
->GetPrimaryMainFrame()
->ExecuteJavaScriptWithUserGestureForTests(
std::u16string(), base::NullCallback(), ISOLATED_WORLD_ID_GLOBAL);
{
base::HistogramTester histogram_tester;
web_contents()->GetController().Reload(ReloadType::NORMAL, false);
dialog_manager.Wait();
// Answer the dialog.
dialog_manager.Run(true, std::u16string());
EXPECT_TRUE(WaitForLoadStop(web_contents()));
histogram_tester.ExpectUniqueSample(
"Navigation.StartAdjustment.AllFrames",
NavigationStartAdjustmentType::kBeforeUnloadDialog, 1);
histogram_tester.ExpectUniqueSample(
"Navigation.StartAdjustment.MainFrameOnly",
NavigationStartAdjustmentType::kBeforeUnloadDialog, 1);
histogram_tester.ExpectTotalCount(
"Navigation.StartAdjustment.BeforeUnloadDialog", 1);
histogram_tester.ExpectTotalCount(
"Navigation.StartAdjustment.BeforeUnloadDialog.Percentage", 1);
// Check for timeline metrics, which should include main frame only
// versions.
histogram_tester.ExpectTotalCount(
"Navigation.Timeline.TotalExcludingBeforeUnload.Duration", 1);
histogram_tester.ExpectTotalCount(
"Navigation.Timeline.TotalExcludingBeforeUnload.MainFrameOnly.Duration",
1);
// The beforeunload dialog will cause an adjustment that includes both
// IgnoredCorrectly and IgnoredIncorrectly durations. (Only the latter
// metric has a main frame only version).
histogram_tester.ExpectTotalCount(
"Navigation.Timeline.IgnoredCorrectly.Duration", 1);
histogram_tester.ExpectTotalCount(
"Navigation.Timeline.IgnoredIncorrectly.Duration", 1);
histogram_tester.ExpectTotalCount(
"Navigation.Timeline.IgnoredIncorrectly.MainFrameOnly.Duration", 1);
histogram_tester.ExpectTotalCount(
"Navigation.Timeline.IgnoredIncorrectly.Percentage", 1);
histogram_tester.ExpectTotalCount(
"Navigation.Timeline.IgnoredIncorrectly.MainFrameOnly.Percentage", 1);
}
// The reload should have cleared the user gesture bit, so upon leaving again
// there should be no beforeunload dialog.
shell()->LoadURL(GURL("about:blank"));
EXPECT_TRUE(WaitForLoadStop(web_contents()));
web_contents()->SetDelegate(nullptr);
}
// Test that beforeunload handlers registered in out-of-process iframes can
// display dialogs, even during renderer-initiated navigations in a process that
// does not have a beforeunload handler. Also verifies that the correct metrics
// are recorded.
IN_PROC_BROWSER_TEST_P(
RenderFrameHostImplWithOrWithoutLegacyBeforeUnloadBrowserTest,
BeforeUnloadDialogInOOPIF) {
IsolateAllSitesForTesting(base::CommandLine::ForCurrentProcess());
TestJavaScriptDialogManager dialog_manager;
web_contents()->SetDelegate(&dialog_manager);
GURL main_url(embedded_test_server()->GetURL("a.com", "/title1.html"));
EXPECT_TRUE(NavigateToURL(shell(), main_url));
FrameTreeNode* root = web_contents()->GetPrimaryFrameTree().root();
// A same-document navigation does not result in an adjustment, nor does it
// record an adjustment metric.
{
base::HistogramTester histogram_tester;
TestNavigationObserver nav_observer(web_contents());
ASSERT_TRUE(ExecJs(shell(), "location.hash = 'foo';"));
nav_observer.WaitForNavigationFinished();
histogram_tester.ExpectTotalCount("Navigation.StartAdjustment.AllFrames",
0);
histogram_tester.ExpectTotalCount(
"Navigation.StartAdjustment.MainFrameOnly", 0);
// Check for timeline metrics, which should not include main frame only
// versions, since those are limited to cross-document navigations.
histogram_tester.ExpectTotalCount(
"Navigation.Timeline.TotalExcludingBeforeUnload.Duration", 1);
histogram_tester.ExpectTotalCount(
"Navigation.Timeline.TotalExcludingBeforeUnload.MainFrameOnly.Duration",
0);
// This navigation has no start adjustment but it does ignore initial work
// in the renderer process, so there are (non-main frame) IgnoredIncorrectly
// metrics.
histogram_tester.ExpectTotalCount(
"Navigation.Timeline.IgnoredIncorrectly.Duration", 1);
histogram_tester.ExpectTotalCount(
"Navigation.Timeline.IgnoredIncorrectly.MainFrameOnly.Duration", 0);
histogram_tester.ExpectTotalCount(
"Navigation.Timeline.IgnoredIncorrectly.Percentage", 1);
histogram_tester.ExpectTotalCount(
"Navigation.Timeline.IgnoredIncorrectly.MainFrameOnly.Percentage", 0);
}
// Create an out-of-process iframe.
GURL subframe_url(embedded_test_server()->GetURL("b.com", "/title1.html"));
{
base::HistogramTester histogram_tester;
std::string subframe_script = JsReplace(
"var f = document.createElement('iframe');"
"f.id = 'subframe';"
"f.src = $1;"
"document.body.append(f);",
subframe_url);
ASSERT_TRUE(ExecJs(shell(), subframe_script));
EXPECT_TRUE(WaitForLoadStop(web_contents()));
// No adjustment is made on a renderer-initiated navigation that targets a
// local frame.
histogram_tester.ExpectUniqueSample("Navigation.StartAdjustment.AllFrames",
NavigationStartAdjustmentType::kNone,
1);
// This does not contribute to MainFrameOnly counts.
histogram_tester.ExpectTotalCount(
"Navigation.StartAdjustment.MainFrameOnly", 0);
// Check for timeline metrics, which should not include main frame only
// versions.
histogram_tester.ExpectTotalCount(
"Navigation.Timeline.TotalExcludingBeforeUnload.Duration", 1);
histogram_tester.ExpectTotalCount(
"Navigation.Timeline.TotalExcludingBeforeUnload.MainFrameOnly.Duration",
0);
// This navigation has no start adjustment but it does ignore initial work
// in the renderer process, so there are (non-main frame) IgnoredIncorrectly
// metrics.
histogram_tester.ExpectTotalCount(
"Navigation.Timeline.IgnoredIncorrectly.Duration", 1);
histogram_tester.ExpectTotalCount(
"Navigation.Timeline.IgnoredIncorrectly.MainFrameOnly.Duration", 0);
histogram_tester.ExpectTotalCount(
"Navigation.Timeline.IgnoredIncorrectly.Percentage", 1);
histogram_tester.ExpectTotalCount(
"Navigation.Timeline.IgnoredIncorrectly.MainFrameOnly.Percentage", 0);
}
ASSERT_EQ(1u, root->child_count());
FrameTreeNode* child = root->child_at(0u);
EXPECT_NE(root->current_frame_host()->GetProcess(),
child->current_frame_host()->GetProcess());
// Navigate the remote iframe to a page with a beforeunload handler.
GURL beforeunload_url(embedded_test_server()->GetURL(
"b.com", "/render_frame_host/beforeunload.html"));
{
base::HistogramTester histogram_tester;
TestFrameNavigationObserver nav_observer(child->current_frame_host());
std::string subframe_script = JsReplace(
"iframe = document.querySelector('#subframe');"
"iframe.contentWindow.location.href = $1;",
beforeunload_url);
ASSERT_TRUE(ExecJs(shell(), subframe_script));
// It is important to use `Wait` and not `WaitForCommit` here, to allow the
// load to finish and the beforeunload handler to be registered with the
// browser process. If the next navigation starts in the main frame's
// process and reaches the browser process before the beforeunload handler
// is registered, the dialog will not be displayed.
nav_observer.Wait();
EXPECT_TRUE(child->current_frame_host()->GetSuddenTerminationDisablerState(
blink::mojom::SuddenTerminationDisablerType::kBeforeUnloadHandler));
if (UseLegacyPostTaskForBeforeUnload()) {
// A legacy PostTask is used when a renderer-initiated navigation targets
// a remote frame that has no beforeunload handler.
histogram_tester.ExpectUniqueSample(
"Navigation.StartAdjustment.AllFrames",
NavigationStartAdjustmentType::kLegacyPostTask, 1);
// This does not contribute to MainFrameOnly counts.
histogram_tester.ExpectTotalCount(
"Navigation.StartAdjustment.MainFrameOnly", 0);
histogram_tester.ExpectTotalCount(
"Navigation.StartAdjustment.LegacyPostTask", 1);
histogram_tester.ExpectTotalCount(
"Navigation.StartAdjustment.LegacyPostTask.Percentage", 1);
} else {
// No adjustment to the navigation start time was made when a
// renderer-initiated navigation targets a remote frame that has no
// beforeunload handler.
histogram_tester.ExpectUniqueSample(
"Navigation.StartAdjustment.AllFrames",
NavigationStartAdjustmentType::kNone, 1);
// This does not contribute to MainFrameOnly counts.
histogram_tester.ExpectTotalCount(
"Navigation.StartAdjustment.MainFrameOnly", 0);
histogram_tester.ExpectTotalCount(
"Navigation.StartAdjustment.LegacyPostTask", 0);
histogram_tester.ExpectTotalCount(
"Navigation.StartAdjustment.LegacyPostTask.Percentage", 0);
}
// Check for timeline metrics, which should not include main frame only
// versions.
histogram_tester.ExpectTotalCount(
"Navigation.Timeline.TotalExcludingBeforeUnload.Duration", 1);
histogram_tester.ExpectTotalCount(
"Navigation.Timeline.TotalExcludingBeforeUnload.MainFrameOnly.Duration",
0);
// The beforeunload dialog will cause an adjustment that includes some
// (non-main-frame) IgnoredIncorrectly durations.
histogram_tester.ExpectTotalCount(
"Navigation.Timeline.IgnoredIncorrectly.Duration", 1);
histogram_tester.ExpectTotalCount(
"Navigation.Timeline.IgnoredIncorrectly.MainFrameOnly.Duration", 0);
histogram_tester.ExpectTotalCount(
"Navigation.Timeline.IgnoredIncorrectly.Percentage", 1);
histogram_tester.ExpectTotalCount(
"Navigation.Timeline.IgnoredIncorrecttly.MainFrameOnly.Percentage", 0);
}
EXPECT_NE(root->current_frame_host()->GetProcess(),
child->current_frame_host()->GetProcess());
// Disable hang monitor and grant a user gesture to all frames, so that the
// dialog will reliably appear.
PrepContentsForBeforeUnloadTest(web_contents(),
/*trigger_user_activation=*/true);
ASSERT_TRUE(child->HasTransientUserActivation());
// Navigate the iframe from the main frame's process, which doesn't know about
// the beforeunload handler. The browser process should check with the
// subframe's process and show a beforeunload dialog. If there is no dialog,
// the call to Wait will hang.
{
base::HistogramTester histogram_tester;
TestFrameNavigationObserver nav_observer(child->current_frame_host());
std::string subframe_script = JsReplace(
"iframe = document.querySelector('#subframe');"
"iframe.contentWindow.location.href = $1;",
subframe_url);
ASSERT_TRUE(ExecJs(shell(), subframe_script));
dialog_manager.Wait();
// Answer the dialog.
dialog_manager.Run(true, std::u16string());
nav_observer.Wait();
histogram_tester.ExpectUniqueSample(
"Navigation.StartAdjustment.AllFrames",
NavigationStartAdjustmentType::kBeforeUnloadDialog, 1);
// This does not contribute to MainFrameOnly counts.
histogram_tester.ExpectTotalCount(
"Navigation.StartAdjustment.MainFrameOnly", 0);
histogram_tester.ExpectTotalCount(
"Navigation.StartAdjustment.BeforeUnloadDialog", 1);
histogram_tester.ExpectTotalCount(
"Navigation.StartAdjustment.BeforeUnloadDialog.Percentage", 1);
}
web_contents()->SetDelegate(nullptr);
}
// Tests that requesting a before unload confirm dialog on a non-active
// does not show a dialog.
IN_PROC_BROWSER_TEST_F(RenderFrameHostImplBrowserTest,
BeforeUnloadConfirmOnNonActive) {
TestJavaScriptDialogManager dialog_manager;
web_contents()->SetDelegate(&dialog_manager);
GURL url_a(embedded_test_server()->GetURL("a.com", "/title1.html"));
GURL url_b(embedded_test_server()->GetURL("b.com", "/title1.html"));
EXPECT_TRUE(NavigateToURL(shell(), url_a));
RenderFrameHostImpl* rfh_a = root_frame_host();
LeaveInPendingDeletionState(rfh_a);
EXPECT_TRUE(NavigateToURL(shell(), url_b));
rfh_a->RunBeforeUnloadConfirm(true, base::DoNothing());
// We should not have seen a dialog because the page isn't active anymore.
EXPECT_EQ(0, dialog_manager.num_beforeunload_dialogs_seen());
web_contents()->SetDelegate(nullptr);
}
// Test for crbug.com/80401. Canceling a beforeunload dialog should reset
// the URL to the previous page's URL.
IN_PROC_BROWSER_TEST_F(RenderFrameHostImplBrowserTest,
CancelBeforeUnloadResetsURL) {
TestJavaScriptDialogManager dialog_manager;
web_contents()->SetDelegate(&dialog_manager);
GURL url(GetTestUrl("render_frame_host", "beforeunload.html"));
EXPECT_TRUE(NavigateToURL(shell(), url));
PrepContentsForBeforeUnloadTest(web_contents());
// Navigate to a page that triggers a cross-site transition.
GURL url2(embedded_test_server()->GetURL("foo.com", "/title1.html"));
shell()->LoadURL(url2);
dialog_manager.Wait();
// Cancel the dialog.
dialog_manager.reset_url_invalidate_count();
dialog_manager.Run(false, std::u16string());
EXPECT_FALSE(web_contents()->IsLoading());
// Verify there are no pending history items after the dialog is cancelled.
// (see crbug.com/93858)
NavigationEntry* entry = web_contents()->GetController().GetPendingEntry();
EXPECT_EQ(nullptr, entry);
EXPECT_EQ(url, web_contents()->GetVisibleURL());
// There should have been at least one NavigationStateChange event for
// invalidating the URL in the address bar, to avoid leaving the stale URL
// visible.
EXPECT_GE(dialog_manager.url_invalidate_count(), 1);
web_contents()->SetDelegate(nullptr);
}
// A separate class needed to test with Origin Trial tokens.
class RenderFrameHostImplWithTokensBrowserTest : public ContentBrowserTest {
public:
RenderFrameHostImplWithTokensBrowserTest() = default;
~RenderFrameHostImplWithTokensBrowserTest() override = default;
// The URL that will be used for Origin Trials.
static constexpr char kOriginTrialUrl[] = "https://127.0.0.1:44444";
// The URL that will be used to load third-party scripts.
static constexpr char kThirdPartyScriptUrl[] = "https://127.0.0.1:44445";
// The URL that is same-site but cross-origin to the third-party scripts URL.
static constexpr char kThirdPartyCrossOriginUrl[] = "https://127.0.0.1:44446";
// URL for empty page responses.
static constexpr char kEmptyPageUrl[] = "https://127.0.0.1:44440";
// A cross-site URL used for Origin Trials.
static constexpr char kCrossSiteOriginTrialUrl[] = "https://a.com";
protected:
void SetUpOnMainThread() override {
// Set up the framework that allows us to intercept and inspect any Origin
// Trial header requests.
url_loader_interceptor_ =
std::make_unique<URLLoaderInterceptor>(base::BindRepeating(
&RenderFrameHostImplWithTokensBrowserTest::InterceptURLRequest,
base::Unretained(this)));
host_resolver()->AddRule("*", "127.0.0.1");
SetupCrossSiteRedirector(embedded_test_server());
ASSERT_TRUE(embedded_test_server()->Start());
}
void TearDownOnMainThread() override {
url_loader_interceptor_.reset();
GetOriginTrialsDelegate()->ClearPersistedTokens();
ContentBrowserTest::TearDownOnMainThread();
}
void SetOriginTrialToken(const std::string& token) {
origin_trial_token_ = token;
}
OriginTrialsControllerDelegate* GetOriginTrialsDelegate() {
return shell()
->web_contents()
->GetPrimaryMainFrame()
->GetBrowserContext()
->GetOriginTrialsControllerDelegate();
}
GURL empty_page_url() const {
return GURL(base::StrCat({kEmptyPageUrl, "/empty.html"}));
}
GURL simple_origin_trial_url() const {
return GURL(base::StrCat({kOriginTrialUrl, "/title1.html"}));
}
GURL meta_tag_origin_trial_url() const {
return GURL(base::StrCat({kOriginTrialUrl, "/meta.html"}));
}
GURL script_meta_tag_origin_trial_url() const {
return GURL(base::StrCat({kOriginTrialUrl, "/meta_script.html"}));
}
GURL meta_tag_injecting_javascript_url() const {
return GURL(base::StrCat({kThirdPartyScriptUrl, "/meta.js"}));
}
GURL cross_site_script_meta_tag_origin_trial_url() const {
return GURL(base::StrCat({kCrossSiteOriginTrialUrl, "/meta_script.html"}));
}
GURL empty_frame_meta_origin_trial_url() const {
return GURL(base::StrCat({kThirdPartyScriptUrl, "/empty.html"}));
}
GURL same_site_cross_origin_url() const {
return GURL(base::StrCat({kThirdPartyCrossOriginUrl, "/empty.html"}));
}
WebContentsImpl* web_contents() const {
return static_cast<WebContentsImpl*>(shell()->web_contents());
}
private:
bool RespondForEmptyUrl(URLLoaderInterceptor::RequestParams* params) {
std::string headers = "HTTP/1.1 200 OK\nContent-Type: text/html\n";
std::string body = "<html>This page has no title.</html>";
URLLoaderInterceptor::WriteResponse(headers, body, params->client.get());
return true;
}
bool RespondForSimpleOriginTrialUrl(
URLLoaderInterceptor::RequestParams* params) {
if (origin_trial_token_.empty()) {
return false;
}
// Construct the origin trial header response.
std::string headers = "HTTP/1.1 200 OK\nContent-Type: text/html\n";
base::StrAppend(&headers, {"Origin-Trial: ", origin_trial_token_, "\n"});
std::string body = "<html>This page has no title.</html>";
URLLoaderInterceptor::WriteResponse(headers, body, params->client.get());
return true;
}
bool RespondForMetaTagOriginTrialUrl(
URLLoaderInterceptor::RequestParams* params) {
if (origin_trial_token_.empty()) {
return false;
}
// Construct the origin trial header response.
std::string headers = "HTTP/1.1 200 OK\nContent-Type: text/html\n";
std::string body = base::StrCat(
{"<html><head><meta http-equiv=\"origin-trial\" content=\"",
origin_trial_token_,
"\"></head><body>"
"This page has no title.</body></html>"});
URLLoaderInterceptor::WriteResponse(headers, body, params->client.get());
return true;
}
bool RespondForScriptMetaTagOriginTrialUrl(
URLLoaderInterceptor::RequestParams* params) {
if (origin_trial_token_.empty()) {
return false;
}
// Construct the origin trial header response.
std::string headers = "HTTP/1.1 200 OK\nContent-Type: text/html\n";
std::string body = base::StrCat(
{"<html><head><script src=\"",
meta_tag_injecting_javascript_url().spec(),
"\"></script></head><body>This page has no title.</body></html>"});
URLLoaderInterceptor::WriteResponse(headers, body, params->client.get());
return true;
}
bool RespondForMetaTagInjectingScriptUrl(
URLLoaderInterceptor::RequestParams* params) {
if (origin_trial_token_.empty()) {
return false;
}
// Construct the origin trial header response.
std::string headers =
"HTTP/1.1 200 OK\nContent-Type: application/javascript\n";
std::string body =
base::StrCat({"const otMeta = document.createElement('meta'); "
"otMeta.httpEquiv = 'origin-trial'; "
"otMeta.content = '",
origin_trial_token_,
"'; "
"document.head.append(otMeta); ",
"const iframe = document.createElement('iframe'); ",
"document.head.appendChild(iframe); "});
URLLoaderInterceptor::WriteResponse(headers, body, params->client.get());
return true;
}
// Create the framework to intercept origin trial header requests.
bool InterceptURLRequest(URLLoaderInterceptor::RequestParams* params) {
if (params->url_request.url == empty_page_url()) {
return RespondForEmptyUrl(params);
}
if (params->url_request.url == simple_origin_trial_url()) {
return RespondForSimpleOriginTrialUrl(params);
}
if (params->url_request.url == meta_tag_origin_trial_url()) {
return RespondForMetaTagOriginTrialUrl(params);
}
if (params->url_request.url == script_meta_tag_origin_trial_url()) {
return RespondForScriptMetaTagOriginTrialUrl(params);
}
if (params->url_request.url == meta_tag_injecting_javascript_url()) {
return RespondForMetaTagInjectingScriptUrl(params);
}
if (params->url_request.url ==
cross_site_script_meta_tag_origin_trial_url()) {
return RespondForScriptMetaTagOriginTrialUrl(params);
}
if (params->url_request.url == empty_frame_meta_origin_trial_url()) {
return RespondForEmptyUrl(params);
}
if (params->url_request.url == same_site_cross_origin_url()) {
return RespondForEmptyUrl(params);
}
return false;
}
base::test::ScopedFeatureList test_features_;
std::string origin_trial_token_;
std::unique_ptr<URLLoaderInterceptor> url_loader_interceptor_;
};
// Check that the RuntimeFeatureStateDocumentData is altered when we receive a
// OriginTrialStateHost IPC.
IN_PROC_BROWSER_TEST_F(RenderFrameHostImplWithTokensBrowserTest,
DocumentDataAltered) {
// Generated with:
// tools/origin_trials/generate_token.py https://127.0.0.1:44444
// DisableThirdPartyStoragePartitioning3
// --expire-timestamp=2000000000
const char kValidFirstPartyToken[] =
"A5jVLTrvQDj8COebCcRQ5xrBVsOZxNYbmx/"
"2YWW6muRlmYGegGu2BGjIQfSe3wuJR4WosC+8XNf/"
"nFUO7MegiwQAAABveyJvcmlnaW4iOiAiaHR0cHM6Ly8xMjcuMC4wLjE6NDQ0NDQiLCAiZmVh"
"dHVyZSI6ICJEaXNhYmxlVGhpcmRQYXJ0eVN0b3JhZ2VQYXJ0aXRpb25pbmczIiwgImV4cGly"
"eSI6IDIwMDAwMDAwMDB9";
SetOriginTrialToken(kValidFirstPartyToken);
EXPECT_TRUE(NavigateToURL(shell(), simple_origin_trial_url()));
// Create a test remote to initiate the IPC.
mojo::Remote<blink::mojom::OriginTrialStateHost>
origin_trial_state_host_remote;
OriginTrialStateHostImpl::Create(
web_contents()->GetPrimaryMainFrame(),
origin_trial_state_host_remote.BindNewPipeAndPassReceiver());
ASSERT_TRUE(origin_trial_state_host_remote.is_connected());
// Before ApplyFeatureDiffForOriginTrial() is called, we expect that the
// feature overrides will be empty.
auto expected_overrides =
base::flat_map<blink::mojom::RuntimeFeature, bool>();
RuntimeFeatureStateDocumentData* actual_document_data =
RuntimeFeatureStateDocumentData::GetForCurrentDocument(
web_contents()->GetPrimaryMainFrame());
EXPECT_EQ(expected_overrides,
actual_document_data->runtime_feature_state_read_context()
.GetFeatureOverrides());
// Simulate receiving a feature diff from the renderer process.
auto overrides_with_tokens =
base::flat_map<blink::mojom::RuntimeFeature,
blink::mojom::OriginTrialFeatureStatePtr>();
std::string raw_token(kValidFirstPartyToken);
std::vector<std::string> raw_tokens_vector{raw_token};
overrides_with_tokens
[blink::mojom::RuntimeFeature::kDisableThirdPartyStoragePartitioning3] =
blink::mojom::OriginTrialFeatureState::New(true, raw_tokens_vector);
origin_trial_state_host_remote.get()->ApplyFeatureDiffForOriginTrial(
std::move(overrides_with_tokens));
// Create the set of expected overrides without the corresponding tokens.
expected_overrides
[blink::mojom::RuntimeFeature::kDisableThirdPartyStoragePartitioning3] =
true;
// Verify that the document data was altered with the correct overrides.
origin_trial_state_host_remote.FlushForTesting();
EXPECT_EQ(expected_overrides,
actual_document_data->runtime_feature_state_read_context()
.GetFeatureOverrides());
}
// Tests that the frame's RuntimeFeatureStateDocumentData is in a valid
// state when
// * The frame has crashed
// * It is reloaded
// * The renderer attempts to apply a header OT token before the frame has been
// finished committing. (While header OT tokens aren't supported by
// RuntimeFeatureState, we still shouldn't crash if someone tries to use one.)
//
// Also tests that even if a dummy RuntimeFeatureStateDocumentData is created,
// the NavigationRequest's RuntimeFeatureStateContext will overwrite it.
IN_PROC_BROWSER_TEST_F(
RenderFrameHostImplWithTokensBrowserTest,
ReloadedCrashedFrameWithHeaderOriginTrialShouldHaveValidRuntimeFeatureStateDocumentData) {
// Generated with:
// tools/origin_trials/generate_token.py https://127.0.0.1:44440
// DisableThirdPartyStoragePartitioning3
// --expire-timestamp=2000000000
const char kValidFirstPartyTokenForEmptyUrl[] =
"AzAtYm5Ul5OyOlBPY0CLWksTcVSXX0t3KSWmzZWT0AwcDRRzadYiezTLXGMjmHgrlkjjCbns"
"u0cTOwDyQKHiRAkAAABveyJvcmlnaW4iOiAiaHR0cHM6Ly8xMjcuMC4wLjE6NDQ0NDAiLCAi"
"ZmVhdHVyZSI6ICJEaXNhYmxlVGhpcmRQYXJ0eVN0b3JhZ2VQYXJ0aXRpb25pbmczIiwgImV4"
"cGlyeSI6IDIwMDAwMDAwMDB9";
SetOriginTrialToken(kValidFirstPartyTokenForEmptyUrl);
EXPECT_TRUE(NavigateToURL(shell(), empty_page_url()));
// Crash the frame.
WebContentsImpl* web_contents =
static_cast<WebContentsImpl*>(shell()->web_contents());
RenderFrameHostImpl* rfh = web_contents->GetPrimaryMainFrame();
RenderProcessHost* process = rfh->GetProcess();
{
RenderProcessHostWatcher crash_observer(
process, RenderProcessHostWatcher::WATCH_FOR_PROCESS_EXIT);
process->Shutdown(0);
crash_observer.Wait();
}
ASSERT_FALSE(rfh->IsRenderFrameLive());
// Create an observer that will set the state of
// DisableThirdPartyStoragePartitioning3 to true once the navigation begins to
// commit.
class ReadyToCommitObserver : public WebContentsObserver {
public:
explicit ReadyToCommitObserver(WebContentsImpl* web_contents)
: WebContentsObserver(web_contents) {}
// WebContentsObserver:
void ReadyToCommitNavigation(NavigationHandle* navigation_handle) override {
navigation_handle->GetMutableRuntimeFeatureStateContext()
.SetDisableThirdPartyStoragePartitioning3Enabled(true);
}
};
ReadyToCommitObserver commit_observer(web_contents);
// Create a message delayer that will mock a header OT token being applied
// before the navigation finishes committing.
auto did_commit_callback =
base::BindLambdaForTesting([&](RenderFrameHost* rfh) {
// Create a test remote to initiate the IPC.
mojo::Remote<blink::mojom::OriginTrialStateHost>
origin_trial_state_host_remote;
OriginTrialStateHostImpl::Create(
web_contents->GetPrimaryMainFrame(),
origin_trial_state_host_remote.BindNewPipeAndPassReceiver());
ASSERT_TRUE(origin_trial_state_host_remote.is_connected());
auto overrides_with_tokens =
base::flat_map<blink::mojom::RuntimeFeature,
blink::mojom::OriginTrialFeatureStatePtr>();
std::string raw_token(kValidFirstPartyTokenForEmptyUrl);
std::vector<std::string> raw_tokens_vector{raw_token};
overrides_with_tokens[blink::mojom::RuntimeFeature::
kDisableThirdPartyStoragePartitioning3] =
blink::mojom::OriginTrialFeatureState::New(true, raw_tokens_vector);
origin_trial_state_host_remote.get()->ApplyFeatureDiffForOriginTrial(
std::move(overrides_with_tokens));
origin_trial_state_host_remote.FlushForTesting();
RuntimeFeatureStateDocumentData* document_data =
RuntimeFeatureStateDocumentData::GetForCurrentDocument(
web_contents->GetPrimaryMainFrame());
ASSERT_TRUE(document_data);
// Confirm that attempting to check if the feature is enabled doesn't
// result in a crash.
//
// The feature should still be disabled. This is because even though we
// sent an, otherwise, valid token we're unable to verify it against
// the expected url since the frame has a last committed origin of null
// at this point in time.
// Additionally, the RuntimeFeatureStateContext in the navigation
// request hasn't yet been saved into the DocumentData.
EXPECT_FALSE(document_data->runtime_feature_state_read_context()
.IsDisableThirdPartyStoragePartitioning3Enabled());
});
CommitMessageDelayer commit_delayer(web_contents,
empty_page_url() /* deferred_url */,
std::move(did_commit_callback));
shell()->Reload();
commit_delayer.Wait();
RuntimeFeatureStateDocumentData* document_data =
RuntimeFeatureStateDocumentData::GetForCurrentDocument(
web_contents->GetPrimaryMainFrame());
ASSERT_TRUE(document_data);
// Now that the navigation has finished committing, the DocumentData should
// contain the "true" set by the observer.
EXPECT_TRUE(document_data->runtime_feature_state_read_context()
.IsDisableThirdPartyStoragePartitioning3Enabled());
}
// Check that the RuntimeFeatureStateDocumentData is not altered when we receive
// a OriginTrialStateHost IPC that contains an invalid token.
IN_PROC_BROWSER_TEST_F(RenderFrameHostImplWithTokensBrowserTest,
DocumentDataInvalidToken) {
const char kInvalidToken[] = "invalid";
SetOriginTrialToken(kInvalidToken);
EXPECT_TRUE(NavigateToURL(shell(), simple_origin_trial_url()));
// Create a test remote to initiate the IPC.
mojo::Remote<blink::mojom::OriginTrialStateHost>
origin_trial_state_host_remote;
OriginTrialStateHostImpl::Create(
web_contents()->GetPrimaryMainFrame(),
origin_trial_state_host_remote.BindNewPipeAndPassReceiver());
ASSERT_TRUE(origin_trial_state_host_remote.is_connected());
// Before ApplyFeatureDiffForOriginTrial() is called, we expect that the
// feature overrides will be empty.
auto expected_overrides =
base::flat_map<blink::mojom::RuntimeFeature, bool>();
RuntimeFeatureStateDocumentData* actual_document_data =
RuntimeFeatureStateDocumentData::GetForCurrentDocument(
web_contents()->GetPrimaryMainFrame());
EXPECT_EQ(expected_overrides,
actual_document_data->runtime_feature_state_read_context()
.GetFeatureOverrides());
// Simulate receiving a feature diff from the renderer process.
auto overrides_with_tokens =
base::flat_map<blink::mojom::RuntimeFeature,
blink::mojom::OriginTrialFeatureStatePtr>();
std::string raw_token(kInvalidToken);
std::vector<std::string> raw_tokens_vector{raw_token};
overrides_with_tokens
[blink::mojom::RuntimeFeature::kDisableThirdPartyStoragePartitioning3] =
blink::mojom::OriginTrialFeatureState::New(true, raw_tokens_vector);
origin_trial_state_host_remote.get()->ApplyFeatureDiffForOriginTrial(
std::move(overrides_with_tokens));
// Verify that no feature overrides were added.
origin_trial_state_host_remote.FlushForTesting();
EXPECT_EQ(expected_overrides,
actual_document_data->runtime_feature_state_read_context()
.GetFeatureOverrides());
}
IN_PROC_BROWSER_TEST_F(RenderFrameHostImplWithTokensBrowserTest,
BrowserValidatesTokensFromMetaTags) {
// Generated with
// tools/origin_trials/generate_token.py https://127.0.0.1:44444 \
// FrobulatePersistent --expire-timestamp=2000000000
const char kValidToken[] =
"A156ll3LJpuECt+dqMQpOAg3H6ayl6AfL6v3Lf/"
"pu2RWy4VHhJ6dnNYoaLbdXnhQUmOxjxcoIarc6lrgGvmKBwgAAABdeyJvcmlnaW4iOiAiaHR"
"0cHM6Ly8xMjcuMC4wLjE6NDQ0NDQiLCAiZmVhdHVyZSI6ICJGcm9idWxhdGVQZXJzaXN0ZW5"
"0IiwgImV4cGlyeSI6IDIwMDAwMDAwMDB9";
base::Time validTime = base::Time::FromSecondsSinceUnixEpoch(1000000000);
SetOriginTrialToken(kValidToken);
EXPECT_TRUE(NavigateToURL(shell(), meta_tag_origin_trial_url()));
// Navigate to a different page as a means of waiting, due to flakiness
// caused by a race between the meta tag being pushed and us checking the
// origin trial.
EXPECT_TRUE(NavigateToURL(shell(), empty_page_url()));
OriginTrialsControllerDelegate* delegate = GetOriginTrialsDelegate();
url::Origin trial_origin = url::Origin::Create(GURL(kOriginTrialUrl));
EXPECT_TRUE(delegate->IsFeaturePersistedForOrigin(
/*origin=*/trial_origin, /*partition_origin=*/trial_origin,
blink::mojom::OriginTrialFeature::kOriginTrialsSampleAPIPersistentFeature,
validTime));
}
IN_PROC_BROWSER_TEST_F(RenderFrameHostImplWithTokensBrowserTest,
BrowserRejectsInvalidTokensFromMetaTags) {
const char kInvalidToken[] = "invalid";
base::Time validTime = base::Time::FromSecondsSinceUnixEpoch(1000000000);
SetOriginTrialToken(kInvalidToken);
EXPECT_TRUE(NavigateToURL(shell(), meta_tag_origin_trial_url()));
// Navigate to a different page as a means of waiting, due to flakiness
// caused by a race between the meta tag being pushed and us checking the
// origin trial.
EXPECT_TRUE(NavigateToURL(shell(), empty_page_url()));
OriginTrialsControllerDelegate* delegate = GetOriginTrialsDelegate();
url::Origin trial_origin = url::Origin::Create(GURL(kOriginTrialUrl));
EXPECT_TRUE(delegate
->GetPersistedTrialsForOrigin(
/*origin=*/trial_origin,
/*partition_origin=*/trial_origin, validTime)
.empty());
}
IN_PROC_BROWSER_TEST_F(
RenderFrameHostImplWithTokensBrowserTest,
BrowserValidatesThirdPartyDeprecationTokensFromMetaTags) {
// Generated with
// tools/origin_trials/generate_token.py https://127.0.0.1:44445
// FrobulatePersistentThirdPartyDeprecation --expire-timestamp=2000000000
// --is-third-party
const char kValidToken[] =
"A8B9KtAVHmLw5hAydE4P2L/"
"AU3V2CWYHQyFtbm2EJIED3tLM4MTg85xMiXrwj8fzQZbIEvnJjJV+"
"azzrkWAxUw8AAACIeyJvcmlnaW4iOiAiaHR0cHM6Ly8xMjcuMC4wLjE6NDQ0NDUiLCAiZmVh"
"dHVyZSI6ICJGcm9idWxhdGVQZXJzaXN0ZW50VGhpcmRQYXJ0eURlcHJlY2F0aW9uIiwgImV4"
"cGlyeSI6IDIwMDAwMDAwMDAsICJpc1RoaXJkUGFydHkiOiB0cnVlfQ==";
base::Time validTime = base::Time::FromSecondsSinceUnixEpoch(1000000000);
SetOriginTrialToken(kValidToken);
EXPECT_TRUE(NavigateToURL(shell(), script_meta_tag_origin_trial_url()));
// Navigate to a different page as a means of waiting, due to flakiness
// caused by a race between the meta tag being pushed and us checking the
// origin trial.
EXPECT_TRUE(NavigateToURL(shell(), empty_page_url()));
OriginTrialsControllerDelegate* delegate = GetOriginTrialsDelegate();
// The Trial should be enabled in the context where it was set.
url::Origin main_origin = url::Origin::Create(GURL(kOriginTrialUrl));
url::Origin trial_origin = url::Origin::Create(GURL(kThirdPartyScriptUrl));
EXPECT_TRUE(delegate->IsFeaturePersistedForOrigin(
/*origin=*/trial_origin, /*partition_origin=*/main_origin,
blink::mojom::OriginTrialFeature::
kOriginTrialsSampleAPIPersistentThirdPartyDeprecationFeature,
validTime));
}
IN_PROC_BROWSER_TEST_F(
RenderFrameHostImplWithTokensBrowserTest,
ReusedChildFrameNavigatedFromDeprecationTrialIsPartitioned) {
// Generated with
// tools/origin_trials/generate_token.py https://127.0.0.1:44445
// DisableThirdPartyStoragePartitioning3 --expire-timestamp=2000000000
// --is-third-party
const char kValidToken[] =
"A7BpVOcOsvw3FiZnc4wIJ9pfGSrhUqMyV8GmGkZrm6emdOW5hBe9YN8XKoFa+"
"YQkVUxdNR22quD3oCJvuIX2cAoAAACFeyJvcmlnaW4iOiAiaHR0cHM6Ly8xMjcuMC4wLjE6N"
"DQ0NDUiLCAiZmVhdHVyZSI6ICJEaXNhYmxlVGhpcmRQYXJ0eVN0b3JhZ2VQYXJ0aXRpb25pb"
"mczIiwgImV4cGlyeSI6IDIwMDAwMDAwMDAsICJpc1RoaXJkUGFydHkiOiB0cnVlfQ==";
SetOriginTrialToken(kValidToken);
// Navigate to "a.com" and load a script from a third-party. In that script,
// the deprecation trial token above is added via <meta> tag. Then, the script
// adds an iframe.
EXPECT_TRUE(
NavigateToURL(shell(), cross_site_script_meta_tag_origin_trial_url()));
RenderFrameHostImpl* child_frame =
static_cast<RenderFrameHostImpl*>(ChildFrameAt(shell(), 0));
ASSERT_TRUE(child_frame);
// Navigate the currently empty iframe to a URL that is same-site with the
// third-party script.
EXPECT_TRUE(NavigateToURLFromRenderer(child_frame,
empty_frame_meta_origin_trial_url()));
// Execute a dummy roundtrip to ensure the <meta> tag trial token has time to
// parse and be applied to the iframe.
EXPECT_TRUE(ExecJs(shell(), ";"));
// Re-obtain the iframe after confirming the navigation is complete. If
// deprecation trial is registered correctly, its StorageKey will be
// first-party.
child_frame = static_cast<RenderFrameHostImpl*>(ChildFrameAt(shell(), 0));
EXPECT_TRUE(child_frame->GetStorageKey().IsFirstPartyContext());
// Calculate the StorageKey when providing a same-site, cross-origin
// `new_rfh_origin`, which simulates a navigation where the RenderFrameHost
// would be reused.
url::Origin new_rfh_origin =
url::Origin::Create(same_site_cross_origin_url());
blink::StorageKey new_storage_key =
child_frame->CalculateStorageKey(new_rfh_origin, /*nonce=*/nullptr);
// Ensure that the StorageKey is third-party, even though the
// RenderFrameHost we "reused" had ThirdPartyStoragePartitioning
// disabled via deprecation trial.
EXPECT_TRUE(new_storage_key.IsThirdPartyContext());
}
IN_PROC_BROWSER_TEST_F(RenderFrameHostImplWithTokensBrowserTest,
BrowserRejectsThirdPartyMetaTagsNonDeprecation) {
// Generated with
// tools/origin_trials/generate_token.py https://127.0.0.1:44445 \
// FrobulatePersistent --expire-timestamp=2000000000 --is-third-party
const char kValidToken[] =
"A5It5cGJLhpgVjvJ/GFD/hJci1G7qeWdhAdZEJ4/"
"RQz0ZtVOfRufZVsYjATJe5DNuDjLtH4IjC5tYUQiDq6hsQgAAABzeyJvcmlnaW4iOiAiaHR0"
"cHM6Ly8xMjcuMC4wLjE6NDQ0NDUiLCAiZmVhdHVyZSI6ICJGcm9idWxhdGVQZXJzaXN0ZW50"
"IiwgImV4cGlyeSI6IDIwMDAwMDAwMDAsICJpc1RoaXJkUGFydHkiOiB0cnVlfQ==";
base::Time validTime = base::Time::FromSecondsSinceUnixEpoch(1000000000);
SetOriginTrialToken(kValidToken);
EXPECT_TRUE(NavigateToURL(shell(), script_meta_tag_origin_trial_url()));
// Navigate to a different page as a means of waiting, due to flakiness
// caused by a race between the meta tag being pushed and us checking the
// origin trial.
EXPECT_TRUE(NavigateToURL(shell(), empty_page_url()));
OriginTrialsControllerDelegate* delegate = GetOriginTrialsDelegate();
url::Origin main_origin = url::Origin::Create(GURL(kOriginTrialUrl));
url::Origin trial_origin = url::Origin::Create(GURL(kThirdPartyScriptUrl));
EXPECT_TRUE(delegate
->GetPersistedTrialsForOrigin(
/*origin=*/trial_origin,
/*partition_origin=*/main_origin, validTime)
.empty());
}
// Helper class for beforunload tests. Sets up a custom dialog manager for the
// main WebContents and provides helpers to register and test beforeunload
// handlers.
//
// TODO(alexmos): Refactor other beforeunload tests in this file to use this
// class.
class RenderFrameHostImplBeforeUnloadBrowserTest
: public RenderFrameHostImplBrowserTest {
public:
RenderFrameHostImplBeforeUnloadBrowserTest() {}
RenderFrameHostImplBeforeUnloadBrowserTest(
const RenderFrameHostImplBeforeUnloadBrowserTest&) = delete;
RenderFrameHostImplBeforeUnloadBrowserTest& operator=(
const RenderFrameHostImplBeforeUnloadBrowserTest&) = delete;
TestJavaScriptDialogManager* dialog_manager() {
return dialog_manager_.get();
}
void CloseDialogAndProceed() {
dialog_manager_->Run(true /* navigation should proceed */,
std::u16string());
}
void CloseDialogAndCancel() {
dialog_manager_->Run(false /* navigation should proceed */,
std::u16string());
}
// Installs a beforeunload handler in the given frame.
// |before_unload_options| specify whether the handler should send a "ping"
// message through domAutomationController, and/or whether it should trigger
// the modal beforeunload confirmation dialog.
enum BeforeUnloadOptions {
SHOW_DIALOG = 1,
SEND_PING = 2,
};
void InstallBeforeUnloadHandler(FrameTreeNode* ftn,
int before_unload_options) {
std::string script = "window.onbeforeunload = () => { ";
if (before_unload_options & SEND_PING)
script += "domAutomationController.send('ping'); ";
if (before_unload_options & SHOW_DIALOG)
script += "return 'x'; ";
script += " }";
EXPECT_TRUE(ExecJs(ftn, script));
}
int RetrievePingsFromMessageQueue(DOMMessageQueue* msg_queue) {
int num_pings = 0;
std::string message;
while (msg_queue->PopMessage(&message)) {
base::TrimString(message, "\"", &message);
// Only count messages from beforeunload. For example, an ExecJs
// sends its own message to DOMMessageQueue, which we need to ignore.
if (message == "ping")
++num_pings;
}
return num_pings;
}
protected:
void SetUpOnMainThread() override {
RenderFrameHostImplBrowserTest::SetUpOnMainThread();
dialog_manager_ = std::make_unique<TestJavaScriptDialogManager>();
web_contents()->SetDelegate(dialog_manager_.get());
}
void TearDownOnMainThread() override {
web_contents()->SetDelegate(nullptr);
RenderFrameHostImplBrowserTest::TearDownOnMainThread();
}
private:
std::unique_ptr<TestJavaScriptDialogManager> dialog_manager_;
};
// Check that when a frame performs a browser-initiated navigation, its
// cross-site subframe is able to execute a beforeunload handler and put up a
// dialog to cancel or allow the navigation. This matters especially in
// --site-per-process mode; see https://crbug.com/853021.
IN_PROC_BROWSER_TEST_F(RenderFrameHostImplBeforeUnloadBrowserTest,
SubframeShowsDialogWhenMainFrameNavigates) {
GURL main_url(embedded_test_server()->GetURL(
"a.com", "/cross_site_iframe_factory.html?a(b)"));
EXPECT_TRUE(NavigateToURL(shell(), main_url));
// Install a beforeunload handler in the b.com subframe.
FrameTreeNode* root = web_contents()->GetPrimaryFrameTree().root();
InstallBeforeUnloadHandler(root->child_at(0), SHOW_DIALOG);
// This test assumes a beforeunload handler is present on the main frame.
static_cast<RenderFrameHostImpl*>(web_contents()->GetPrimaryMainFrame())
->SuddenTerminationDisablerChanged(
true,
blink::mojom::SuddenTerminationDisablerType::kBeforeUnloadHandler);
// Disable beforeunload timer to prevent flakiness.
PrepContentsForBeforeUnloadTest(web_contents());
// Navigate cross-site.
GURL cross_site_url(embedded_test_server()->GetURL("c.com", "/title1.html"));
shell()->LoadURL(cross_site_url);
// Only the main frame should be marked as waiting for beforeunload completion
// callback as the frame being navigated.
RenderFrameHostImpl* main_frame = web_contents()->GetPrimaryMainFrame();
RenderFrameHostImpl* child = root->child_at(0)->current_frame_host();
EXPECT_TRUE(main_frame->is_waiting_for_beforeunload_completion());
EXPECT_FALSE(child->is_waiting_for_beforeunload_completion());
// Sanity check that the main frame is waiting for subframe's beforeunload
// ACK.
EXPECT_EQ(main_frame, child->GetBeforeUnloadInitiator());
EXPECT_EQ(main_frame, main_frame->GetBeforeUnloadInitiator());
// With full site isolation, LoadURL() should trigger two beforeunload IPCs
// for subframe and the main frame: the subframe has a beforeunload handler,
// and while the main frame does not, we always send the IPC to navigating
// frames, regardless of whether or not they have a handler.
//
// Without full site isolation, only one beforeunload IPC should be sent to
// the main frame, which will handle both (same-process) frames.
EXPECT_EQ(AreAllSitesIsolatedForTesting() ? 2u : 1u,
main_frame->beforeunload_pending_replies_.size());
// Wait for the beforeunload dialog to be shown from the subframe.
dialog_manager()->Wait();
// The main frame should still be waiting for subframe's beforeunload
// completion callback.
EXPECT_EQ(main_frame, child->GetBeforeUnloadInitiator());
EXPECT_EQ(main_frame, main_frame->GetBeforeUnloadInitiator());
EXPECT_TRUE(main_frame->is_waiting_for_beforeunload_completion());
EXPECT_FALSE(child->is_waiting_for_beforeunload_completion());
// With full site isolation, the beforeunload completion callback should
// happen on the child RFH. Without full site isolation, it will come from the
// main frame RFH, which processes beforeunload for both main frame and child
// frame, since they are in the same process and SiteInstance.
RenderFrameHostImpl* frame_that_sent_beforeunload_ipc =
AreAllSitesIsolatedForTesting() ? child : main_frame;
EXPECT_TRUE(main_frame->beforeunload_pending_replies_.count(
frame_that_sent_beforeunload_ipc));
// Answer the dialog with "cancel" to stay on current page.
CloseDialogAndCancel();
EXPECT_TRUE(WaitForLoadStop(web_contents()));
EXPECT_EQ(main_url, web_contents()->GetLastCommittedURL());
// Verify beforeunload state has been cleared.
EXPECT_FALSE(main_frame->is_waiting_for_beforeunload_completion());
EXPECT_FALSE(child->is_waiting_for_beforeunload_completion());
EXPECT_EQ(nullptr, main_frame->GetBeforeUnloadInitiator());
EXPECT_EQ(nullptr, child->GetBeforeUnloadInitiator());
EXPECT_EQ(0u, main_frame->beforeunload_pending_replies_.size());
// Try navigating again. The dialog should come up again.
shell()->LoadURL(cross_site_url);
dialog_manager()->Wait();
EXPECT_TRUE(main_frame->is_waiting_for_beforeunload_completion());
// Now answer the dialog and allow the navigation to proceed. Disable
// unload ACK on the old frame so that it sticks around in pending delete
// state, since the test later verifies that it has received the beforeunload
// ACK.
TestFrameNavigationObserver commit_observer(root);
main_frame->DisableUnloadTimerForTesting();
CloseDialogAndProceed();
commit_observer.WaitForCommit();
EXPECT_EQ(cross_site_url, web_contents()->GetLastCommittedURL());
EXPECT_FALSE(web_contents()
->GetPrimaryMainFrame()
->is_waiting_for_beforeunload_completion());
// The navigation that succeeded was a browser-initiated, main frame
// navigation, so it swapped RenderFrameHosts. |main_frame| should either be
// in pending deletion and waiting for unload ACK or enter back-forward cache,
// but it should not be waiting for the beforeunload completion callback.
EXPECT_THAT(
main_frame->lifecycle_state(),
testing::AnyOf(testing::Eq(LifecycleStateImpl::kRunningUnloadHandlers),
testing::Eq(LifecycleStateImpl::kInBackForwardCache)));
EXPECT_FALSE(main_frame->is_waiting_for_beforeunload_completion());
EXPECT_EQ(0u, main_frame->beforeunload_pending_replies_.size());
EXPECT_EQ(nullptr, main_frame->GetBeforeUnloadInitiator());
}
// Check that when a frame with multiple cross-site subframes navigates, all
// the subframes execute their beforeunload handlers, but at most one
// beforeunload dialog is allowed per navigation.
IN_PROC_BROWSER_TEST_F(RenderFrameHostImplBeforeUnloadBrowserTest,
MultipleSubframes) {
GURL main_url(embedded_test_server()->GetURL(
"a.com", "/cross_site_iframe_factory.html?a(b(c),b,c(d),c,d)"));
EXPECT_TRUE(NavigateToURL(shell(), main_url));
// Install a beforeunload handler in five of eight frames to send a ping via
// domAutomationController and request a beforeunload dialog.
FrameTreeNode* root = web_contents()->GetPrimaryFrameTree().root();
InstallBeforeUnloadHandler(root, SEND_PING | SHOW_DIALOG);
InstallBeforeUnloadHandler(root->child_at(0)->child_at(0),
SEND_PING | SHOW_DIALOG);
InstallBeforeUnloadHandler(root->child_at(1), SEND_PING | SHOW_DIALOG);
InstallBeforeUnloadHandler(root->child_at(2), SEND_PING | SHOW_DIALOG);
InstallBeforeUnloadHandler(root->child_at(2)->child_at(0),
SEND_PING | SHOW_DIALOG);
// Disable beforeunload timer to prevent flakiness.
PrepContentsForBeforeUnloadTest(web_contents());
// Navigate main frame cross-site and wait for the beforeunload dialog to be
// shown from one of the frames.
DOMMessageQueue msg_queue(web_contents());
GURL cross_site_url(embedded_test_server()->GetURL("e.com", "/title1.html"));
shell()->LoadURL(cross_site_url);
dialog_manager()->Wait();
// Answer the dialog and allow the navigation to proceed.
CloseDialogAndProceed();
EXPECT_TRUE(WaitForLoadStop(web_contents()));
EXPECT_EQ(cross_site_url, web_contents()->GetLastCommittedURL());
// We should've received five beforeunload pings.
EXPECT_EQ(5, RetrievePingsFromMessageQueue(&msg_queue));
// No more beforeunload dialogs shouldn't been shown, due to a policy of at
// most one dialog per navigation.
EXPECT_EQ(1, dialog_manager()->num_beforeunload_dialogs_seen());
}
// Similar to the test above, but test scenarios where the subframes with
// beforeunload handlers aren't local roots.
IN_PROC_BROWSER_TEST_F(RenderFrameHostImplBeforeUnloadBrowserTest,
NonLocalRootSubframes) {
GURL main_url(embedded_test_server()->GetURL(
"a.com", "/cross_site_iframe_factory.html?a(a(b),c(c))"));
EXPECT_TRUE(NavigateToURL(shell(), main_url));
// Install a beforeunload handler in two of five frames to send a ping via
// domAutomationController and request a beforeunload dialog.
FrameTreeNode* root = web_contents()->GetPrimaryFrameTree().root();
InstallBeforeUnloadHandler(root->child_at(0), SEND_PING | SHOW_DIALOG);
InstallBeforeUnloadHandler(root->child_at(0)->child_at(0),
SEND_PING | SHOW_DIALOG);
// Disable beforeunload timer to prevent flakiness.
PrepContentsForBeforeUnloadTest(web_contents());
// Navigate and wait for the beforeunload dialog to be shown from one of the
// frames.
DOMMessageQueue msg_queue(web_contents());
GURL cross_site_url(embedded_test_server()->GetURL("a.com", "/title1.html"));
shell()->LoadURL(cross_site_url);
dialog_manager()->Wait();
// Answer the dialog and allow the navigation to proceed.
CloseDialogAndProceed();
EXPECT_TRUE(WaitForLoadStop(web_contents()));
EXPECT_EQ(cross_site_url, web_contents()->GetLastCommittedURL());
// We should've received two beforeunload pings.
EXPECT_EQ(2, RetrievePingsFromMessageQueue(&msg_queue));
// No more beforeunload dialogs shouldn't been shown, due to a policy of at
// most one dialog per navigation.
EXPECT_EQ(1, dialog_manager()->num_beforeunload_dialogs_seen());
}
// Test that cross-site subframes run the beforeunload handler when the main
// frame performs a renderer-initiated navigation.
IN_PROC_BROWSER_TEST_F(RenderFrameHostImplBeforeUnloadBrowserTest,
RendererInitiatedNavigation) {
GURL main_url(embedded_test_server()->GetURL(
"a.com", "/cross_site_iframe_factory.html?a(a,b,c)"));
EXPECT_TRUE(NavigateToURL(shell(), main_url));
// Install a beforeunload handler in both a.com frames to send a ping via
// domAutomationController.
FrameTreeNode* root = web_contents()->GetPrimaryFrameTree().root();
InstallBeforeUnloadHandler(root, SEND_PING);
InstallBeforeUnloadHandler(root->child_at(0), SEND_PING);
// Install a beforeunload handler in the b.com frame to put up a dialog.
InstallBeforeUnloadHandler(root->child_at(1), SHOW_DIALOG);
// Disable beforeunload timer to prevent flakiness.
PrepContentsForBeforeUnloadTest(web_contents());
// Start a same-site renderer-initiated navigation. The beforeunload dialog
// from the b.com frame should be shown. The other two a.com frames should
// send pings from their beforeunload handlers.
DOMMessageQueue msg_queue(web_contents());
GURL new_url(embedded_test_server()->GetURL("a.com", "/title1.html"));
TestNavigationManager navigation_manager(web_contents(), new_url);
// Use ExecuteScriptAsync because a ping may arrive before the script
// execution completion notification and confuse our expectations.
ExecuteScriptAsync(root, "location.href = '" + new_url.spec() + "';");
dialog_manager()->Wait();
// Answer the dialog and allow the navigation to proceed. Note that at this
// point, without site isolation, the navigation hasn't started yet, as the
// navigating frame is still processing beforeunload for all its descendant
// local frames. With site isolation, the a.com frames have finished
// beforeunload, and the browser process has received OnBeginNavigation, but
// the navigation is paused until the b.com subframe process finishes running
// beforeunload.
CloseDialogAndProceed();
// Wait for navigation to end.
ASSERT_TRUE(navigation_manager.WaitForNavigationFinished());
EXPECT_EQ(new_url, web_contents()->GetLastCommittedURL());
// We should have received two pings from two a.com frames. If we receive
// more, that probably means we ran beforeunload an extra time in the a.com
// frames.
EXPECT_EQ(2, RetrievePingsFromMessageQueue(&msg_queue));
EXPECT_EQ(1, dialog_manager()->num_beforeunload_dialogs_seen());
}
// Similar to the test above, but check a navigation in a subframe rather than
// the main frame.
IN_PROC_BROWSER_TEST_F(RenderFrameHostImplBeforeUnloadBrowserTest,
RendererInitiatedNavigationInSubframe) {
GURL main_url(embedded_test_server()->GetURL(
"a.com", "/cross_site_iframe_factory.html?a(b(c),c)"));
EXPECT_TRUE(NavigateToURL(shell(), main_url));
// Install a beforeunload handler to send a ping in all frames.
FrameTreeNode* root = web_contents()->GetPrimaryFrameTree().root();
InstallBeforeUnloadHandler(root, SEND_PING);
InstallBeforeUnloadHandler(root->child_at(0), SEND_PING);
InstallBeforeUnloadHandler(root->child_at(0)->child_at(0), SEND_PING);
InstallBeforeUnloadHandler(root->child_at(1), SEND_PING);
// Disable beforeunload timer to prevent flakiness.
PrepContentsForBeforeUnloadTest(web_contents());
// Start a renderer-initiated navigation in the middle frame.
DOMMessageQueue msg_queue(web_contents());
GURL new_url(embedded_test_server()->GetURL("a.com", "/title1.html"));
TestNavigationManager navigation_manager(web_contents(), new_url);
// Use ExecuteScriptAsync because a ping may arrive before the script
// execution completion notification and confuse our expectations.
ExecuteScriptAsync(root->child_at(0),
"location.href = '" + new_url.spec() + "';");
ASSERT_TRUE(navigation_manager.WaitForNavigationFinished());
EXPECT_EQ(new_url,
root->child_at(0)->current_frame_host()->GetLastCommittedURL());
// We should have received two pings from the b.com frame and its child.
// Other frames' beforeunload handlers shouldn't have run.
EXPECT_EQ(2, RetrievePingsFromMessageQueue(&msg_queue));
// We shouldn't have seen any beforeunload dialogs.
EXPECT_EQ(0, dialog_manager()->num_beforeunload_dialogs_seen());
}
// Ensure that when a beforeunload handler deletes a subframe which is also
// running beforeunload, the navigation can still proceed.
IN_PROC_BROWSER_TEST_F(RenderFrameHostImplBeforeUnloadBrowserTest,
DetachSubframe) {
GURL main_url(embedded_test_server()->GetURL(
"a.com", "/cross_site_iframe_factory.html?a(b)"));
EXPECT_TRUE(NavigateToURL(shell(), main_url));
// Install a beforeunload handler in root frame to delete the subframe.
FrameTreeNode* root = web_contents()->GetPrimaryFrameTree().root();
std::string script =
"window.onbeforeunload = () => { "
" document.body.removeChild(document.querySelector('iframe'));"
"}";
EXPECT_TRUE(ExecJs(root, script));
// Install a beforeunload handler which never finishes in subframe.
EXPECT_TRUE(ExecJs(root->child_at(0),
"window.onbeforeunload = () => { while (1) ; }"));
// Disable beforeunload timer to prevent flakiness.
PrepContentsForBeforeUnloadTest(web_contents());
// Navigate main frame and ensure that it doesn't time out. When the main
// frame detaches the subframe, the RFHI destruction should unblock the
// navigation from waiting on the subframe's beforeunload completion callback.
GURL new_url(embedded_test_server()->GetURL("c.com", "/title1.html"));
EXPECT_TRUE(NavigateToURL(shell(), new_url));
}
// Ensure that A(B(A)) cases work sanely with beforeunload handlers.
IN_PROC_BROWSER_TEST_F(RenderFrameHostImplBeforeUnloadBrowserTest,
RendererInitiatedNavigationInABAB) {
GURL main_url(embedded_test_server()->GetURL(
"a.com", "/cross_site_iframe_factory.html?a(b(a(b)))"));
EXPECT_TRUE(NavigateToURL(shell(), main_url));
// Install a beforeunload handler to send a ping in all frames.
FrameTreeNode* root = web_contents()->GetPrimaryFrameTree().root();
InstallBeforeUnloadHandler(root, SEND_PING);
InstallBeforeUnloadHandler(root->child_at(0), SEND_PING);
InstallBeforeUnloadHandler(root->child_at(0)->child_at(0), SEND_PING);
InstallBeforeUnloadHandler(root->child_at(0)->child_at(0)->child_at(0),
SEND_PING);
// Disable beforeunload timer to prevent flakiness.
PrepContentsForBeforeUnloadTest(web_contents());
// Navigate the main frame.
DOMMessageQueue msg_queue(web_contents());
GURL new_url(embedded_test_server()->GetURL("c.com", "/title1.html"));
EXPECT_TRUE(NavigateToURL(shell(), new_url));
// We should have received four pings.
EXPECT_EQ(4, RetrievePingsFromMessageQueue(&msg_queue));
// We shouldn't have seen any beforeunload dialogs.
EXPECT_EQ(0, dialog_manager()->num_beforeunload_dialogs_seen());
}
// Ensure that the beforeunload timeout works properly when
// beforeunload handlers from subframes time out.
IN_PROC_BROWSER_TEST_F(RenderFrameHostImplBeforeUnloadBrowserTest,
TimeoutInSubframe) {
GURL main_url(embedded_test_server()->GetURL(
"a.com", "/cross_site_iframe_factory.html?a(b)"));
EXPECT_TRUE(NavigateToURL(shell(), main_url));
// Install a beforeunload handler to send a ping in main frame.
FrameTreeNode* root = web_contents()->GetPrimaryFrameTree().root();
InstallBeforeUnloadHandler(root, SEND_PING);
// Install a beforeunload handler which never finishes in subframe.
EXPECT_TRUE(ExecJs(root->child_at(0),
"window.onbeforeunload = () => { while (1) ; }"));
// Navigate the main frame. We should eventually time out on the subframe
// beforeunload handler and complete the navigation.
GURL new_url(embedded_test_server()->GetURL("c.com", "/title1.html"));
EXPECT_TRUE(NavigateToURL(shell(), new_url));
}
// Ensure that the beforeunload timeout isn't restarted when a frame attempts
// to show a beforeunload dialog and fails because the dialog is already being
// shown by another frame. See https://crbug.com/865223.
IN_PROC_BROWSER_TEST_F(RenderFrameHostImplBeforeUnloadBrowserTest,
TimerNotRestartedBySecondDialog) {
// This test exercises a scenario that's only possible with
// --site-per-process.
if (!AreAllSitesIsolatedForTesting())
return;
GURL main_url(embedded_test_server()->GetURL(
"a.com", "/cross_site_iframe_factory.html?a(b)"));
EXPECT_TRUE(NavigateToURL(shell(), main_url));
RenderFrameHostImpl* main_frame = web_contents()->GetPrimaryMainFrame();
// Install a beforeunload handler to show a dialog in both frames.
FrameTreeNode* root = web_contents()->GetPrimaryFrameTree().root();
InstallBeforeUnloadHandler(root, SHOW_DIALOG);
InstallBeforeUnloadHandler(root->child_at(0), SHOW_DIALOG);
// Extend the beforeunload timeout to prevent flakiness. This test can't use
// PrepContentsForBeforeUnloadTest(), as that clears the timer altogether,
// and this test needs the timer to be valid, to see whether it gets paused
// and not restarted correctly.
main_frame->SetBeforeUnloadTimeoutDelayForTesting(base::Seconds(30));
// Start a navigation in the main frame.
GURL new_url(embedded_test_server()->GetURL("c.com", "/title1.html"));
shell()->LoadURL(new_url);
// We should have two pending beforeunload completion callbacks at this point,
// and the beforeunload timer should be running.
EXPECT_EQ(2u, main_frame->beforeunload_pending_replies_.size());
EXPECT_TRUE(main_frame->beforeunload_timeout_->IsRunning());
// Wait for the dialog from one of the frames. Note that either frame could
// be the first to trigger the dialog.
dialog_manager()->Wait();
// The dialog should've canceled the timer.
EXPECT_FALSE(main_frame->beforeunload_timeout_->IsRunning());
// Don't close the dialog and allow the second beforeunload to come in and
// attempt to show a dialog. This should fail due to the intervention of at
// most one dialog per navigation and respond to the renderer with the
// confirmation to proceed, which should trigger a beforeunload completion
// callback from the second frame. Wait for that beforeunload completion
// callback. After it's received, there will be one ACK remaining for the
// frame that's currently showing the dialog.
EXPECT_TRUE(base::test::RunUntil(
[&]() { return main_frame->beforeunload_pending_replies_.size() <= 1; }));
// Ensure that the beforeunload timer hasn't been restarted, since the first
// beforeunload dialog is still up at this point.
EXPECT_FALSE(main_frame->beforeunload_timeout_->IsRunning());
// Cancel the dialog and make sure we stay on the old page.
CloseDialogAndCancel();
EXPECT_TRUE(WaitForLoadStop(web_contents()));
EXPECT_EQ(main_url, web_contents()->GetLastCommittedURL());
}
// During a complex WebContents destruction, test resuming a navigation, due to
// of a beforeunloader. This is a regersion test for: https://crbug.com/1147567.
// - Start from A(B(C))
// - C adds a beforeunload handler.
// - B starts a navigation, waiting for C.
// - The WebContents is closed, which deletes C, then B, then A.
// When deleting C, the navigations in B can begin, but this happen while B was
// destructing itself.
//
// Note: This needs 3 nested documents instead of 2, because deletion of the
// main RenderFrameHost is different from normal RenderFrameHost. This is
// required to reproduce https://crbug.com/1147567.
IN_PROC_BROWSER_TEST_F(RenderFrameHostImplBeforeUnloadBrowserTest,
CloseWebContent) {
// This test exercises a scenario that's only possible with
// --site-per-process.
if (!AreAllSitesIsolatedForTesting())
return;
// For unknown reasons, it seems required to start from a "live"
// RenderFrameHost. Otherwise creating a new Shell below will crash.
EXPECT_TRUE(NavigateToURL(shell(), GURL(url::kAboutBlankURL)));
GURL url = embedded_test_server()->GetURL(
"a.com", "/cross_site_iframe_factory.html?a(b(c))");
Shell* new_shell = Shell::CreateNewWindow(
web_contents()->GetController().GetBrowserContext(), url, nullptr,
gfx::Size());
auto* web_contents = static_cast<WebContentsImpl*>(new_shell->web_contents());
EXPECT_TRUE(WaitForLoadStop(web_contents));
RenderFrameHostImpl* rfh_a = web_contents->GetPrimaryMainFrame();
RenderFrameHostImpl* rfh_b = rfh_a->child_at(0)->current_frame_host();
RenderFrameHostImpl* rfh_c = rfh_b->child_at(0)->current_frame_host();
// C has a beforeunload handler, slow to reply.
EXPECT_TRUE(ExecJs(rfh_c, "onbeforeunload = () => {while(1);}"));
// B navigate elsewhere. This triggers C's beforeunload handler.
EXPECT_TRUE(ExecJs(rfh_b, "location.href = 'about:blank';"));
// Closing the Shell, this deletes C and causes the navigation above to start.
new_shell->Close();
// Test pass if this doesn't reach a CHECK.
}
namespace {
class OnDidStartNavigation : public WebContentsObserver {
public:
OnDidStartNavigation(WebContents* web_contents,
base::RepeatingClosure callback)
: WebContentsObserver(web_contents), callback_(callback) {}
void DidStartNavigation(NavigationHandle* navigation) override {
callback_.Run();
}
private:
base::RepeatingClosure callback_;
};
} // namespace
// This test closes beforeunload dialog due to a new navigation starting from
// within WebContentsObserver::DidStartNavigation. This test succeeds if it
// doesn't crash with a UAF while loading the second page.
IN_PROC_BROWSER_TEST_F(RenderFrameHostImplBeforeUnloadBrowserTest,
DidStartNavigationClosesDialog) {
GURL url1 = embedded_test_server()->GetURL(
"a.com", "/render_frame_host/beforeunload.html");
GURL url2 = embedded_test_server()->GetURL("b.com", "/title1.html");
EXPECT_TRUE(NavigateToURL(shell(), url1));
auto weak_web_contents = web_contents()->GetWeakPtr();
// This matches the behaviour of TabModalDialogManager in
// components/javascript_dialogs.
OnDidStartNavigation close_dialog(web_contents(),
base::BindLambdaForTesting([&]() {
CloseDialogAndCancel();
// Check that web_contents() were not
// deleted.
ASSERT_TRUE(weak_web_contents);
}));
web_contents()->GetPrimaryMainFrame()->RunBeforeUnloadConfirm(
true, base::DoNothing());
EXPECT_TRUE(NavigateToURL(shell(), url2));
}
namespace {
// A helper to execute some script in a frame just before it is deleted, such
// that no message loops are pumped and no sync IPC messages are processed
// between script execution and the destruction of the RenderFrameHost .
class ExecuteScriptBeforeRenderFrameDeletedHelper
: public RenderFrameDeletedObserver {
public:
ExecuteScriptBeforeRenderFrameDeletedHelper(RenderFrameHost* observed_frame,
const std::string& script)
: RenderFrameDeletedObserver(observed_frame), script_(script) {}
ExecuteScriptBeforeRenderFrameDeletedHelper(
const ExecuteScriptBeforeRenderFrameDeletedHelper&) = delete;
ExecuteScriptBeforeRenderFrameDeletedHelper& operator=(
const ExecuteScriptBeforeRenderFrameDeletedHelper&) = delete;
protected:
// WebContentsObserver:
void RenderFrameDeleted(RenderFrameHost* render_frame_host) override {
const bool was_deleted = deleted();
RenderFrameDeletedObserver::RenderFrameDeleted(render_frame_host);
if (deleted() && !was_deleted)
ExecuteScriptAsync(render_frame_host, script_);
}
private:
std::string script_;
};
} // namespace
// Regression test for https://crbug.com/728171 where the sync IPC channel has a
// connection error but we don't properly check for it. This occurs because we
// send a sync window.open IPC after the RenderFrameHost is destroyed.
//
// The test creates two WebContents rendered in the same process. The first is
// is the window-opener of the second, so the first window can be used to relay
// information collected during the destruction of the RenderFrame in the second
// WebContents back to the browser process.
//
// The issue is then reproduced by asynchronously triggering a call to
// window.open() in the main frame of the second WebContents in response to
// WebContentsObserver::RenderFrameDeleted -- that is, just before the RFHI is
// destroyed on the browser side. The test assumes that between these two
// events, the UI message loop is not pumped, and no sync IPC messages are
// processed on the UI thread.
//
// Note that if the second WebContents scheduled a call to window.close() to
// close itself after it calls window.open(), the CreateNewWindow sync IPC could
// be dispatched *before* WidgetHostMsg_Close in the browser process, provided
// that the browser happened to be in IPC::SyncChannel::WaitForReply on the UI
// thread (most likely after sending GpuCommandBufferMsg_* messages), in which
// case incoming sync IPCs to this thread are dispatched, but the message loop
// is not pumped, so proxied non-sync IPCs are not delivered.
//
// Furthermore, on Android, exercising window.open() must be delayed until after
// content::RemoveShellView returns, as that method calls into JNI to close the
// view corresponding to the WebContents, which will then call back into native
// code and may run nested message loops and send sync IPC messages.
IN_PROC_BROWSER_TEST_F(RenderFrameHostImplBrowserTest,
FrameDetached_WindowOpenIPCFails) {
EXPECT_TRUE(
NavigateToURL(shell(), embedded_test_server()->GetURL("/title1.html")));
EXPECT_EQ(1u, Shell::windows().size());
GURL test_url =
embedded_test_server()->GetURL("/render_frame_host/window_open.html");
std::string open_script =
base::StringPrintf("popup = window.open('%s');", test_url.spec().c_str());
TestNavigationObserver second_contents_navigation_observer(nullptr, 1);
second_contents_navigation_observer.StartWatchingNewWebContents();
EXPECT_TRUE(ExecJs(shell(), open_script));
second_contents_navigation_observer.Wait();
ASSERT_EQ(2u, Shell::windows().size());
Shell* new_shell = Shell::windows()[1];
ExecuteScriptBeforeRenderFrameDeletedHelper deleted_observer(
new_shell->web_contents()->GetPrimaryMainFrame(), "callWindowOpen();");
new_shell->Close();
deleted_observer.WaitUntilDeleted();
EXPECT_EQ(true, EvalJs(shell(), "!!popup.didCallWindowOpen"));
EXPECT_EQ("null", EvalJs(shell(), "String(popup.resultOfWindowOpen)"));
}
namespace {
void PostRequestMonitor(int* post_counter,
const net::test_server::HttpRequest& request) {
if (request.method != net::test_server::METHOD_POST)
return;
(*post_counter)++;
auto it = request.headers.find("Content-Type");
CHECK(it != request.headers.end());
CHECK(!it->second.empty());
}
} // namespace
// Verifies form submits and resubmits work.
IN_PROC_BROWSER_TEST_P(
RenderFrameHostImplWithOrWithoutLegacyBeforeUnloadBrowserTest,
POSTNavigation) {
net::EmbeddedTestServer http_server;
http_server.AddDefaultHandlers(GetTestDataFilePath());
int post_counter = 0;
http_server.RegisterRequestMonitor(
base::BindRepeating(&PostRequestMonitor, &post_counter));
ASSERT_TRUE(http_server.Start());
GURL url(http_server.GetURL("/session_history/form.html"));
GURL post_url = http_server.GetURL("/echotitle");
// Navigate to a page with a form.
TestNavigationObserver observer(web_contents());
EXPECT_TRUE(NavigateToURL(shell(), url));
EXPECT_EQ(url, observer.last_navigation_url());
EXPECT_TRUE(observer.last_navigation_succeeded());
// Submit the form.
GURL submit_url("javascript:submitForm('isubmit')");
EXPECT_TRUE(
NavigateToURL(shell(), submit_url, post_url /* expected_commit_url */));
// Check that a proper POST navigation was done.
EXPECT_EQ("text=&select=a", base::UTF16ToASCII(web_contents()->GetTitle()));
EXPECT_EQ(post_url, web_contents()->GetLastCommittedURL());
EXPECT_TRUE(shell()
->web_contents()
->GetController()
.GetLastCommittedEntry()
->GetHasPostData());
// Reload and verify the form was submitted.
{
base::HistogramTester histogram_tester;
web_contents()->GetController().Reload(ReloadType::NORMAL, false);
EXPECT_TRUE(WaitForLoadStop(web_contents()));
if (UseLegacyPostTaskForBeforeUnload()) {
// This browser-initiated reload adjusts navigation start time for a
// legacy PostTask, without any beforeunload handlers present.
histogram_tester.ExpectUniqueSample(
"Navigation.StartAdjustment.AllFrames",
NavigationStartAdjustmentType::kLegacyPostTask, 1);
histogram_tester.ExpectUniqueSample(
"Navigation.StartAdjustment.MainFrameOnly",
NavigationStartAdjustmentType::kLegacyPostTask, 1);
histogram_tester.ExpectTotalCount(
"Navigation.StartAdjustment.LegacyPostTask", 1);
histogram_tester.ExpectTotalCount(
"Navigation.StartAdjustment.LegacyPostTask.Percentage", 1);
} else {
// This browser-initiated reload does not adjust navigation start.
histogram_tester.ExpectUniqueSample(
"Navigation.StartAdjustment.AllFrames",
NavigationStartAdjustmentType::kNone, 1);
histogram_tester.ExpectUniqueSample(
"Navigation.StartAdjustment.MainFrameOnly",
NavigationStartAdjustmentType::kNone, 1);
histogram_tester.ExpectTotalCount(
"Navigation.StartAdjustment.LegacyPostTask", 0);
histogram_tester.ExpectTotalCount(
"Navigation.StartAdjustment.LegacyPostTask.Percentage", 0);
}
}
EXPECT_EQ("text=&select=a", base::UTF16ToASCII(web_contents()->GetTitle()));
CHECK_EQ(2, post_counter);
}
// Tests navigation metrics for back to back reloads, without waiting for the
// first reload to complete. This currently incorrectly creates a negative
// adjustment to the start time, because a posted task from the first navigation
// updates the start time of the second navigation (after the first is
// canceled). See https://crbug.com/385170155.
IN_PROC_BROWSER_TEST_F(RenderFrameHostImplWithLegacyBeforeUnloadBrowserTest,
BackToBackReloads) {
EXPECT_TRUE(
NavigateToURL(shell(), embedded_test_server()->GetURL("/title1.html")));
base::HistogramTester histogram_tester;
web_contents()->GetController().Reload(ReloadType::NORMAL, false);
web_contents()->GetController().Reload(ReloadType::NORMAL, false);
EXPECT_TRUE(WaitForLoadStop(web_contents()));
// The negative adjustment counts as a legacy post task case, but its time
// should show up in a separate negative time bucket, without a corresponding
// percentage value.
histogram_tester.ExpectUniqueSample(
"Navigation.StartAdjustment.AllFrames",
NavigationStartAdjustmentType::kLegacyPostTask, 1);
histogram_tester.ExpectUniqueSample(
"Navigation.StartAdjustment.MainFrameOnly",
NavigationStartAdjustmentType::kLegacyPostTask, 1);
histogram_tester.ExpectTotalCount(
"Navigation.StartAdjustment.LegacyPostTask.Negative", 1);
histogram_tester.ExpectTotalCount("Navigation.StartAdjustment.LegacyPostTask",
0);
histogram_tester.ExpectTotalCount(
"Navigation.StartAdjustment.LegacyPostTask.Percentage", 0);
}
class AvoidUnnecessaryBeforeUnloadCheckSyncBrowserTest
: public RenderFrameHostImplBrowserTest,
public testing::WithParamInterface<std::string> {
public:
AvoidUnnecessaryBeforeUnloadCheckSyncBrowserTest() {
scoped_feature_list_.InitWithFeaturesAndParameters(
/*enabled_features=*/
{{features::kAvoidUnnecessaryBeforeUnloadCheckSync,
{{features::kAvoidUnnecessaryBeforeUnloadCheckSyncMode.name,
GetMode()}}}},
/*disabled_features=*/{});
}
const std::string& GetMode() { return GetParam(); }
private:
base::test::ScopedFeatureList scoped_feature_list_;
};
INSTANTIATE_TEST_SUITE_P(
All,
AvoidUnnecessaryBeforeUnloadCheckSyncBrowserTest,
::testing::Values("DumpWithoutCrashing",
"WithSendBeforeUnload",
"WithoutSendBeforeUnload"),
[](const testing::TestParamInfo<
AvoidUnnecessaryBeforeUnloadCheckSyncBrowserTest::ParamType>& info) {
return info.param;
});
// Regression test for https://crbug.com/411855273.
// Confirms that the back navigation in the following scenario must not report
// DumpWithoutCrashing and must not crash with the navigation re-entrancy issue.
IN_PROC_BROWSER_TEST_P(AvoidUnnecessaryBeforeUnloadCheckSyncBrowserTest,
PotentialReentrancyOnFailedSubframeBackNavigation) {
const base::HistogramTester histogram_tester;
// Load a page with a CSP policy that causes all subframe loads to fail.
EXPECT_TRUE(NavigateToURL(shell(),
GURL("data:text/html,"
"<html><head>"
"<meta http-equiv=\"Content-Security-Policy\" "
"content=\"frame-src 'none'\">"
"</head><body></body></html>")));
// Create an iframe, and navigate to title1.html in iframe. This subframe load
// fails the CSP policy above and ends up in OnRequestFailedInternal.
TestNavigationObserver test_navigation_observer1(web_contents());
EXPECT_TRUE(
ExecJs(root_frame_host(),
JsReplace("const frame = document.createElement('iframe');"
"frame.src = $1;"
"document.body.appendChild(frame);",
embedded_test_server()->GetURL("/title1.html"))));
test_navigation_observer1.Wait();
// Navigate to title2.html in iframe. This subframe load fails the CSP policy
// above and ends up in OnRequestFailedInternal.
TestNavigationObserver test_navigation_observer2(web_contents());
EXPECT_TRUE(
ExecJs(root_frame_host(),
JsReplace("document.getElementsByTagName('iframe')[0].src = $1;",
embedded_test_server()->GetURL("/title2.html"))));
test_navigation_observer2.Wait();
// The following back navigation used to trigger https://crbug.com/411855273,
// but it is fixed now.
TestNavigationObserver test_navigation_observer3(web_contents());
web_contents()->GetController().GoBack();
test_navigation_observer3.Wait();
histogram_tester.ExpectTotalCount("Stability.DumpWithoutCrashingStatus", 0);
}
namespace {
class NavigationHandleGrabber : public WebContentsObserver {
public:
explicit NavigationHandleGrabber(WebContents* web_contents)
: WebContentsObserver(web_contents) {}
void ReadyToCommitNavigation(NavigationHandle* navigation_handle) override {
if (navigation_handle->GetURL().path() != "/title2.html")
return;
ExecuteScriptAsync(web_contents(), "document.open();");
}
void DidFinishNavigation(NavigationHandle* navigation_handle) override {
if (navigation_handle->GetURL().path() != "/title2.html")
return;
if (navigation_handle->HasCommitted())
committed_title2_ = true;
run_loop_.Quit();
}
void WaitForTitle2() { run_loop_.Run(); }
bool committed_title2() { return committed_title2_; }
private:
bool committed_title2_ = false;
base::RunLoop run_loop_;
};
class DocumentUkmSourceIdObserver : public WebContentsObserver {
public:
explicit DocumentUkmSourceIdObserver(WebContents* web_contents)
: WebContentsObserver(web_contents) {}
DocumentUkmSourceIdObserver(const DocumentUkmSourceIdObserver&) = delete;
DocumentUkmSourceIdObserver& operator=(const DocumentUkmSourceIdObserver&) =
delete;
ukm::SourceId GetPrimaryMainFrameDocumentUkmSourceId() {
return main_frame_document_ukm_source_id_;
}
ukm::SourceId GetSubFrameDocumentUkmSourceId() {
return sub_frame_document_ukm_source_id_;
}
protected:
// WebContentsObserver:
void DidFinishNavigation(NavigationHandle* navigation_handle) override {
bool is_main_frame_navigation = navigation_handle->IsInMainFrame();
// Track the source ids from NavigationRequests for access by browser tests.
NavigationRequest* request = NavigationRequest::From(navigation_handle);
ukm::SourceId document_ukm_source_id =
request->commit_params().document_ukm_source_id;
if (is_main_frame_navigation)
main_frame_document_ukm_source_id_ = document_ukm_source_id;
else
sub_frame_document_ukm_source_id_ = document_ukm_source_id;
}
private:
ukm::SourceId main_frame_document_ukm_source_id_ = ukm::kInvalidSourceId;
ukm::SourceId sub_frame_document_ukm_source_id_ = ukm::kInvalidSourceId;
};
} // namespace
// Verifies that if a frame aborts a navigation right after it starts, it is
// cancelled.
IN_PROC_BROWSER_TEST_F(RenderFrameHostImplBrowserTest, FastNavigationAbort) {
GURL url(embedded_test_server()->GetURL("/title1.html"));
EXPECT_TRUE(NavigateToURL(shell(), url));
// This test only makes sense for navigations that stay in the same
// RenderFrame, otherwise the document.open() will run on the previous
// page's RenderFrame, and the navigation won't get aborted. We need to
// ensure that we won't trigger a same-site cross-RFH navigation.
// TODO(crbug.com/40137364): This should also work on cross-RFH same-site
// navigations.
if (ShouldCreateNewHostForAllFrames()) {
return;
}
DisableProactiveBrowsingInstanceSwapFor(
web_contents()->GetPrimaryMainFrame());
// Now make a navigation. |observer| will make a document.open() call at
// ReadyToCommit time - see
// NavigationHandleGrabber::SendingNavigationCommitted(). The navigation
// should get aborted because of the document.open() in the navigating RFH.
NavigationHandleGrabber observer(web_contents());
const std::u16string title = u"done";
EXPECT_TRUE(ExecJs(web_contents(), "window.location.href='/title2.html'"));
observer.WaitForTitle2();
// Flush IPCs to make sure the renderer didn't tell us to navigate. Need to
// make two round trips.
EXPECT_TRUE(ExecJs(web_contents(), ""));
EXPECT_TRUE(ExecJs(web_contents(), ""));
EXPECT_FALSE(observer.committed_title2());
}
IN_PROC_BROWSER_TEST_F(RenderFrameHostImplBrowserTest,
TerminationDisablersClearedOnRendererCrash) {
EXPECT_TRUE(NavigateToURL(
shell(), GetTestUrl("render_frame_host", "beforeunload.html")));
EXPECT_TRUE(WaitForLoadStop(web_contents()));
RenderFrameHostImpl* main_rfh1 = web_contents()->GetPrimaryMainFrame();
EXPECT_TRUE(main_rfh1->GetSuddenTerminationDisablerState(
blink::mojom::SuddenTerminationDisablerType::kBeforeUnloadHandler));
// Make the renderer crash.
RenderProcessHost* renderer_process = main_rfh1->GetProcess();
RenderProcessHostWatcher crash_observer(
renderer_process, RenderProcessHostWatcher::WATCH_FOR_PROCESS_EXIT);
renderer_process->Shutdown(0);
crash_observer.Wait();
EXPECT_FALSE(main_rfh1->GetSuddenTerminationDisablerState(
blink::mojom::SuddenTerminationDisablerType::kBeforeUnloadHandler));
// This should not trigger a DCHECK once the renderer sends up the termination
// disabler flags.
web_contents()->GetController().Reload(ReloadType::NORMAL, false);
EXPECT_TRUE(WaitForLoadStop(web_contents()));
RenderFrameHostImpl* main_rfh2 = web_contents()->GetPrimaryMainFrame();
EXPECT_TRUE(main_rfh2->GetSuddenTerminationDisablerState(
blink::mojom::SuddenTerminationDisablerType::kBeforeUnloadHandler));
}
// Aborted renderer-initiated navigations that don't destroy the current
// document (e.g. no error page is displayed) must not cancel pending
// XMLHttpRequests.
// See https://crbug.com/762945.
IN_PROC_BROWSER_TEST_F(
ContentBrowserTest,
AbortedRendererInitiatedNavigationDoNotCancelPendingXHR) {
net::test_server::ControllableHttpResponse xhr_response(
embedded_test_server(), "/xhr_request");
EXPECT_TRUE(embedded_test_server()->Start());
GURL main_url(embedded_test_server()->GetURL("/title1.html"));
EXPECT_TRUE(NavigateToURL(shell(), main_url));
EXPECT_TRUE(WaitForLoadStop(shell()->web_contents()));
// 1) Send an xhr request, but do not send its response for the moment.
static constexpr char kSendSlowXhr[] =
"var request = new XMLHttpRequest();"
"request.addEventListener('abort', () => document.title = 'xhr aborted');"
"request.addEventListener('load', () => document.title = 'xhr loaded');"
"request.open('GET', '%s');"
"request.send();";
const GURL slow_url = embedded_test_server()->GetURL("/xhr_request");
EXPECT_TRUE(ExecJs(
shell(), base::StringPrintf(kSendSlowXhr, slow_url.spec().c_str())));
xhr_response.WaitForRequest();
// 2) In the meantime, create a renderer-initiated navigation. It will be
// aborted.
TestNavigationManager observer(shell()->web_contents(),
GURL("customprotocol:aborted"));
EXPECT_TRUE(ExecJs(shell(), "window.location = 'customprotocol:aborted'"));
EXPECT_FALSE(observer.WaitForResponse());
ASSERT_TRUE(observer.WaitForNavigationFinished());
// 3) Send the response for the XHR requests.
xhr_response.Send(
"HTTP/1.1 200 OK\r\n"
"Connection: close\r\n"
"Content-Length: 2\r\n"
"Content-Type: text/plain; charset=utf-8\r\n"
"\r\n"
"OK");
xhr_response.Done();
// 4) Wait for the XHR request to complete.
const std::u16string xhr_aborted_title = u"xhr aborted";
const std::u16string xhr_loaded_title = u"xhr loaded";
TitleWatcher watcher(shell()->web_contents(), xhr_loaded_title);
watcher.AlsoWaitForTitle(xhr_aborted_title);
EXPECT_EQ(xhr_loaded_title, watcher.WaitAndGetTitle());
}
// A browser-initiated javascript-url navigation must not prevent the current
// document from loading.
// See https://crbug.com/766149.
IN_PROC_BROWSER_TEST_F(ContentBrowserTest,
BrowserInitiatedJavascriptUrlDoNotPreventLoading) {
net::test_server::ControllableHttpResponse main_document_response(
embedded_test_server(), "/main_document");
EXPECT_TRUE(embedded_test_server()->Start());
GURL main_document_url(embedded_test_server()->GetURL("/main_document"));
TestNavigationManager main_document_observer(shell()->web_contents(),
main_document_url);
// 1) Navigate. Send the header but not the body. The navigation commits in
// the browser. The renderer is still loading the document.
{
shell()->LoadURL(main_document_url);
EXPECT_TRUE(main_document_observer.WaitForRequestStart());
main_document_observer.ResumeNavigation(); // Send the request.
main_document_response.WaitForRequest();
main_document_response.Send(
"HTTP/1.1 200 OK\r\n"
"Connection: close\r\n"
"Content-Type: text/html; charset=utf-8\r\n"
"\r\n");
EXPECT_TRUE(main_document_observer.WaitForResponse());
main_document_observer.ResumeNavigation(); // Commit the navigation.
}
// 2) A browser-initiated javascript-url navigation happens.
{
GURL javascript_url(
"javascript:window.domAutomationController.send('done')");
shell()->LoadURL(javascript_url);
DOMMessageQueue dom_message_queue(WebContents::FromRenderFrameHost(
shell()->web_contents()->GetPrimaryMainFrame()));
std::string done;
EXPECT_TRUE(dom_message_queue.WaitForMessage(&done));
EXPECT_EQ("\"done\"", done);
}
// 3) The end of the response is issued. The renderer must be able to receive
// it.
{
const std::u16string document_loaded_title = u"document loaded";
TitleWatcher watcher(shell()->web_contents(), document_loaded_title);
main_document_response.Send(
"<script>"
" window.onload = function(){"
" document.title = 'document loaded'"
" }"
"</script>");
main_document_response.Done();
EXPECT_EQ(document_loaded_title, watcher.WaitAndGetTitle());
}
}
// Test that a same-document browser-initiated navigation doesn't prevent a
// document from loading. See https://crbug.com/769645.
IN_PROC_BROWSER_TEST_F(
ContentBrowserTest,
SameDocumentBrowserInitiatedNavigationWhileDocumentIsLoading) {
net::test_server::ControllableHttpResponse response(embedded_test_server(),
"/main_document");
EXPECT_TRUE(embedded_test_server()->Start());
// 1) Load a new document. It reaches the ReadyToCommit stage and then is slow
// to load.
GURL url(embedded_test_server()->GetURL("/main_document"));
TestNavigationManager observer_new_document(shell()->web_contents(), url);
shell()->LoadURL(url);
// The navigation starts
EXPECT_TRUE(observer_new_document.WaitForRequestStart());
observer_new_document.ResumeNavigation();
// The server sends the first part of the response and waits.
response.WaitForRequest();
response.Send(
"HTTP/1.1 200 OK\r\n"
"Content-Type: text/html; charset=utf-8\r\n"
"\r\n"
"<html>"
" <body>"
" <div id=\"anchor\"></div>"
" <script>"
" domAutomationController.send('First part received')"
" </script>");
// The browser reaches the ReadyToCommit stage.
EXPECT_TRUE(observer_new_document.WaitForResponse());
RenderFrameHostImpl* main_rfh = static_cast<RenderFrameHostImpl*>(
shell()->web_contents()->GetPrimaryMainFrame());
DOMMessageQueue dom_message_queue(WebContents::FromRenderFrameHost(main_rfh));
observer_new_document.ResumeNavigation();
// Wait for the renderer to load the first part of the response.
std::string first_part_received;
EXPECT_TRUE(dom_message_queue.WaitForMessage(&first_part_received));
EXPECT_EQ("\"First part received\"", first_part_received);
// 2) In the meantime, a browser-initiated same-document navigation commits.
GURL anchor_url(url.spec() + "#anchor");
TestNavigationManager observer_same_document(shell()->web_contents(),
anchor_url);
shell()->LoadURL(anchor_url);
ASSERT_TRUE(observer_same_document.WaitForNavigationFinished());
// 3) The last part of the response is received.
response.Send(
" <script>"
" domAutomationController.send('Second part received')"
" </script>"
" </body>"
"</html>");
response.Done();
EXPECT_TRUE(WaitForLoadStop(shell()->web_contents()));
// The renderer should be able to load the end of the response.
std::string second_part_received;
EXPECT_TRUE(dom_message_queue.WaitForMessage(&second_part_received));
EXPECT_EQ("\"Second part received\"", second_part_received);
}
namespace {
// Allows injecting a fake, test-provided |interface_broker_receiver| into
// DidCommitProvisionalLoad messages in a given |web_contents| instead of the
// real one coming from the renderer process.
class ScopedFakeInterfaceBrokerRequestInjector
: public DidCommitNavigationInterceptor {
public:
explicit ScopedFakeInterfaceBrokerRequestInjector(WebContents* web_contents)
: DidCommitNavigationInterceptor(web_contents) {}
~ScopedFakeInterfaceBrokerRequestInjector() override = default;
ScopedFakeInterfaceBrokerRequestInjector(
const ScopedFakeInterfaceBrokerRequestInjector&) = delete;
ScopedFakeInterfaceBrokerRequestInjector& operator=(
const ScopedFakeInterfaceBrokerRequestInjector&) = delete;
// Sets the fake BrowserInterfaceBroker |receiver| to inject into the next
// incoming DidCommitProvisionalLoad message.
void set_fake_receiver_for_next_commit(
mojo::PendingReceiver<blink::mojom::BrowserInterfaceBroker> receiver) {
next_fake_receiver_ = std::move(receiver);
}
const GURL& url_of_last_commit() const { return url_of_last_commit_; }
const mojo::PendingReceiver<blink::mojom::BrowserInterfaceBroker>&
original_receiver_of_last_commit() const {
return original_receiver_of_last_commit_;
}
protected:
bool WillProcessDidCommitNavigation(
RenderFrameHost* render_frame_host,
NavigationRequest* navigation_request,
mojom::DidCommitProvisionalLoadParamsPtr* params,
mojom::DidCommitProvisionalLoadInterfaceParamsPtr* interface_params)
override {
url_of_last_commit_ = (**params).url;
if (*interface_params) {
original_receiver_of_last_commit_ =
std::move((*interface_params)->browser_interface_broker_receiver);
(*interface_params)->browser_interface_broker_receiver =
std::move(next_fake_receiver_);
}
return true;
}
private:
mojo::PendingReceiver<blink::mojom::BrowserInterfaceBroker>
next_fake_receiver_;
mojo::PendingReceiver<blink::mojom::BrowserInterfaceBroker>
original_receiver_of_last_commit_;
GURL url_of_last_commit_;
};
// Monitors the |broker_receiver_| of the given |render_frame_host| for incoming
// interface requests for |interface_name|, and invokes |callback| synchronously
// just before such a request would be dispatched.
class ScopedInterfaceRequestMonitor
: public blink::mojom::BrowserInterfaceBrokerInterceptorForTesting {
public:
ScopedInterfaceRequestMonitor(RenderFrameHostImpl* render_frame_host,
std::string_view interface_name,
base::RepeatingClosure callback)
: rfhi_(render_frame_host),
impl_(receiver().SwapImplForTesting(this)),
interface_name_(interface_name),
request_callback_(callback) {}
ScopedInterfaceRequestMonitor(const ScopedInterfaceRequestMonitor&) = delete;
ScopedInterfaceRequestMonitor& operator=(
const ScopedInterfaceRequestMonitor&) = delete;
~ScopedInterfaceRequestMonitor() override {
auto* old_impl = receiver().SwapImplForTesting(impl_);
DCHECK_EQ(old_impl, this);
}
protected:
// blink::mojom::BrowserInterfaceBrokerInterceptorForTesting:
blink::mojom::BrowserInterfaceBroker* GetForwardingInterface() override {
return impl_;
}
void GetInterface(mojo::GenericPendingReceiver receiver) override {
if (receiver.interface_name() == interface_name_)
request_callback_.Run();
GetForwardingInterface()->GetInterface(std::move(receiver));
}
private:
mojo::Receiver<blink::mojom::BrowserInterfaceBroker>& receiver() {
return rfhi_->browser_interface_broker_receiver_for_testing();
}
raw_ptr<RenderFrameHostImpl> rfhi_;
raw_ptr<blink::mojom::BrowserInterfaceBroker> impl_;
std::string interface_name_;
base::RepeatingClosure request_callback_;
};
} // namespace
// For cross-document navigations, the DidCommitProvisionalLoad message from
// the renderer process will have its |interface_broker_receiver| argument set
// to the receiver end of a new BrowserInterfaceBroker interface connection that
// will be used by the newly committed document to access services exposed by
// the RenderFrameHost.
//
// This test verifies that even if that |interface_broker_receiver| already
// has pending interface receivers, the RenderFrameHost binds the
// BrowserInterfaceBroker receiver in such a way that these pending interface
// receivers are dispatched strictly after
// WebContentsObserver::DidFinishNavigation has fired, so that the receivers
// will be served correctly in the security context of the newly committed
// document (i.e. GetLastCommittedURL/Origin will have been updated).
IN_PROC_BROWSER_TEST_F(
RenderFrameHostImplBrowserTest,
EarlyInterfaceRequestsFromNewDocumentDispatchedAfterNavigationFinished) {
const GURL first_url(embedded_test_server()->GetURL("/title1.html"));
const GURL second_url(embedded_test_server()->GetURL("/title2.html"));
// Load a URL that maps to the same SiteInstance as the second URL, to make
// sure the second navigation will not be cross-process.
ASSERT_TRUE(NavigateToURL(shell(), first_url));
// Prepare an PendingReceiver<BrowserInterfaceBroker> with pending interface
// requests.
mojo::Remote<blink::mojom::BrowserInterfaceBroker>
interface_broker_with_pending_requests;
mojo::PendingReceiver<blink::mojom::BrowserInterfaceBroker>
interface_broker_receiver_with_pending_receiver =
interface_broker_with_pending_requests.BindNewPipeAndPassReceiver();
mojo::Remote<mojom::FrameHostTestInterface> test_interface;
interface_broker_with_pending_requests->GetInterface(
test_interface.BindNewPipeAndPassReceiver());
// Replace the |interface_broker_receiver| argument in the next
// DidCommitProvisionalLoad message coming from the renderer with the
// rigged |interface_broker_with_pending_requests| from above.
ScopedFakeInterfaceBrokerRequestInjector injector(web_contents());
injector.set_fake_receiver_for_next_commit(
std::move(interface_broker_receiver_with_pending_receiver));
// Expect that by the time the interface request for FrameHostTestInterface is
// dispatched to the RenderFrameHost, WebContentsObserver::DidFinishNavigation
// will have already been invoked.
bool did_finish_navigation = false;
// Start the same-process navigation.
TestNavigationManager navigation_manager(web_contents(), second_url);
shell()->LoadURL(second_url);
EXPECT_TRUE(navigation_manager.WaitForResponse());
auto* committing_rfh =
NavigationRequest::From(navigation_manager.GetNavigationHandle())
->GetRenderFrameHost();
DidFinishNavigationObserver navigation_finish_observer(
committing_rfh,
base::BindLambdaForTesting([&did_finish_navigation](NavigationHandle*) {
did_finish_navigation = true;
}));
base::RunLoop wait_until_interface_request_is_dispatched;
ScopedInterfaceRequestMonitor monitor(
committing_rfh, mojom::FrameHostTestInterface::Name_,
base::BindLambdaForTesting([&]() {
EXPECT_TRUE(did_finish_navigation);
wait_until_interface_request_is_dispatched.Quit();
}));
// Finish the navigation.
ASSERT_TRUE(navigation_manager.WaitForNavigationFinished());
EXPECT_EQ(second_url, injector.url_of_last_commit());
EXPECT_TRUE(injector.original_receiver_of_last_commit().is_valid());
// Wait until the interface request for FrameHostTestInterface is dispatched.
wait_until_interface_request_is_dispatched.Run();
}
// The BrowserInterfaceBroker interface, which is used by the RenderFrame to
// access Mojo services exposed by the RenderFrameHost, is not
// Channel-associated, thus not synchronized with navigation IPC messages. As a
// result, when the renderer commits a load, the DidCommitProvisional message
// might be at race with GetInterface messages, for example, an interface
// request issued by the previous document in its unload handler might arrive to
// the browser process just a moment after DidCommitProvisionalLoad.
//
// This test verifies that even if there is such a last-second GetInterface
// message originating from the previous document, it is no longer serviced.
IN_PROC_BROWSER_TEST_F(RenderFrameHostImplBrowserTest,
LateInterfaceRequestsFromOldDocumentNotDispatched) {
const GURL first_url(embedded_test_server()->GetURL("/title1.html"));
const GURL second_url(embedded_test_server()->GetURL("/title2.html"));
// Prepare an PendingReceiver<BrowserInterfaceBroker> with no pending
// requests.
mojo::Remote<blink::mojom::BrowserInterfaceBroker> interface_broker;
mojo::PendingReceiver<blink::mojom::BrowserInterfaceBroker>
interface_broker_receiver = interface_broker.BindNewPipeAndPassReceiver();
// Set up a cunning mechanism to replace the |interface_broker_receiver|
// argument in next DidCommitProvisionalLoad message with the rigged
// |interface_broker_receiver| from above, whose client end is controlled by
// this test; then trigger a navigation.
{
ScopedFakeInterfaceBrokerRequestInjector injector(web_contents());
injector.set_fake_receiver_for_next_commit(
std::move(interface_broker_receiver));
ASSERT_TRUE(NavigateToURLAndDoNotWaitForLoadStop(shell(), first_url));
ASSERT_EQ(first_url, injector.url_of_last_commit());
ASSERT_TRUE(injector.original_receiver_of_last_commit().is_valid());
}
// The test below only works for same-RFH navigations, so we need to ensure
// that we won't trigger a same-site cross-RFH navigation.
DisableProactiveBrowsingInstanceSwapFor(
web_contents()->GetPrimaryMainFrame());
if (ShouldCreateNewHostForAllFrames()) {
return;
}
// Prepare an interface receiver for FrameHostTestInterface.
mojo::Remote<mojom::FrameHostTestInterface> test_interface;
auto test_interface_receiver = test_interface.BindNewPipeAndPassReceiver();
// Set up |dispatched_interface_request_callback| that would be invoked if the
// interface receiver for FrameHostTestInterface was ever dispatched to the
// RenderFrameHostImpl.
base::MockCallback<base::RepeatingClosure>
dispatched_interface_request_callback;
auto* main_rfh = web_contents()->GetPrimaryMainFrame();
ScopedInterfaceRequestMonitor monitor(
main_rfh, mojom::FrameHostTestInterface::Name_,
dispatched_interface_request_callback.Get());
// Set up the |test_interface request| to arrive on the BrowserInterfaceBroker
// connection corresponding to the old document in the middle of the firing of
// WebContentsObserver::DidFinishNavigation.
// TODO(engedy): Should we PostTask() this instead just before synchronously
// invoking DidCommitProvisionalLoad?
//
// Also set up |navigation_finished_callback| to be invoked afterwards, as a
// sanity check to ensure that the request injection is actually executed.
base::MockCallback<base::RepeatingClosure> navigation_finished_callback;
DidFinishNavigationObserver navigation_finish_observer(
main_rfh, base::BindLambdaForTesting([&](NavigationHandle*) {
interface_broker->GetInterface(std::move(test_interface_receiver));
std::move(navigation_finished_callback).Run();
}));
// The BrowserInterfaceBroker connection that semantically belongs to the old
// document, but whose client end is actually controlled by this test, should
// still be alive and well.
ASSERT_TRUE(test_interface.is_bound());
ASSERT_TRUE(test_interface.is_connected());
base::RunLoop run_loop;
test_interface.set_disconnect_handler(run_loop.QuitWhenIdleClosure());
// Expect that the GetInterface message will never be dispatched, but the
// DidFinishNavigation callback will be invoked.
EXPECT_CALL(dispatched_interface_request_callback, Run()).Times(0);
EXPECT_CALL(navigation_finished_callback, Run());
// Start the same-process navigation.
ASSERT_TRUE(NavigateToURLAndDoNotWaitForLoadStop(shell(), second_url));
// Wait for a connection error on the |test_interface| as a signal, after
// which it can be safely assumed that no GetInterface message will ever be
// dispatched from that old InterfaceConnection.
run_loop.Run();
EXPECT_FALSE(test_interface.is_connected());
}
// Test the edge case where the `window` global object asssociated with the
// initial empty document is re-used for document corresponding to the first
// real committed load. This happens when the security origins of the two
// documents are the same. We do not want to recalculate this in the browser
// process, however, so for the first commit we leave it up to the renderer
// whether it wants to replace the BrowserInterfaceBroker connection or not.
IN_PROC_BROWSER_TEST_F(RenderFrameHostImplBrowserTest,
InterfaceBrokerRequestIsOptionalForFirstCommit) {
const GURL main_frame_url(embedded_test_server()->GetURL("/title1.html"));
const GURL subframe_url(embedded_test_server()->GetURL("/title2.html"));
mojo::PendingRemote<blink::mojom::BrowserInterfaceBroker> interface_broker;
auto stub_interface_broker_receiver =
interface_broker.InitWithNewPipeAndPassReceiver();
mojo::PendingReceiver<blink::mojom::BrowserInterfaceBroker>
null_interface_broker_receiver((mojo::NullReceiver()));
for (auto* interface_broker_receiver :
{&stub_interface_broker_receiver, &null_interface_broker_receiver}) {
SCOPED_TRACE(interface_broker_receiver->is_valid());
ASSERT_TRUE(NavigateToURL(shell(), main_frame_url));
ScopedFakeInterfaceBrokerRequestInjector injector(web_contents());
injector.set_fake_receiver_for_next_commit(
std::move(*interface_broker_receiver));
// Must set 'src` before adding the iframe element to the DOM, otherwise it
// will load `about:blank` as the first real load instead of |subframe_url|.
// See: https://crbug.com/778318.
//
// Note that the child frame will first cycle through loading the initial
// empty document regardless of when/how/if the `src` attribute is set.
const auto script = base::StringPrintf(
"let f = document.createElement(\"iframe\");"
"f.src=\"%s\"; "
"document.body.append(f);",
subframe_url.spec().c_str());
ASSERT_TRUE(ExecJs(shell(), script));
EXPECT_TRUE(WaitForLoadStop(web_contents()));
FrameTreeNode* root = web_contents()->GetPrimaryFrameTree().root();
ASSERT_EQ(1u, root->child_count());
FrameTreeNode* child = root->child_at(0u);
EXPECT_FALSE(injector.original_receiver_of_last_commit().is_valid());
EXPECT_FALSE(child->is_on_initial_empty_document());
EXPECT_EQ(subframe_url, child->current_url());
}
}
// Regression test for https://crbug.com/821022.
//
// Test the edge case of the above, namely, where the following commits take
// place in a subframe embedded into a document at `http://foo.com/`:
//
// 1) the initial empty document (`about:blank`)
// 2) `about:blank#ref`
// 3) `http://foo.com`
//
// Here, (2) should classify as a same-document navigation, and (3) should be
// considered the first real load. Because the first real load is same-origin
// with the initial empty document, the latter's `window` global object
// asssociated with the initial empty document is re-used for document
// corresponding to the first real committed load.
IN_PROC_BROWSER_TEST_F(
RenderFrameHostImplBrowserTest,
InterfaceBrokerRequestNotPresentForFirstRealLoadAfterAboutBlankWithRef) {
const GURL kMainFrameURL(embedded_test_server()->GetURL("/title1.html"));
const GURL kSubframeURLTwo("about:blank#ref");
const GURL kSubframeURLThree(embedded_test_server()->GetURL("/title2.html"));
const auto kNavigateToOneThenTwoScript = base::StringPrintf(
"var f = document.createElement(\"iframe\");"
"f.src=\"%s\"; "
"document.body.append(f);",
kSubframeURLTwo.spec().c_str());
const auto kNavigateToThreeScript =
base::StringPrintf("f.src=\"%s\";", kSubframeURLThree.spec().c_str());
ASSERT_TRUE(NavigateToURL(shell(), kMainFrameURL));
// Trigger navigation (1) by creating a new subframe, and then trigger
// navigation (2) by setting it's `src` attribute before adding it to the DOM.
//
// We must set 'src` before adding the iframe element to the DOM, otherwise it
// will load `about:blank` as the first real load instead of
// |kSubframeURLTwo|. See: https://crbug.com/778318.
//
// Note that the child frame will first cycle through loading the initial
// empty document regardless of when/how/if the `src` attribute is set.
ASSERT_TRUE(ExecJs(shell(), kNavigateToOneThenTwoScript));
EXPECT_TRUE(WaitForLoadStop(web_contents()));
FrameTreeNode* root = web_contents()->GetPrimaryFrameTree().root();
ASSERT_EQ(1u, root->child_count());
FrameTreeNode* child = root->child_at(0u);
EXPECT_TRUE(child->is_on_initial_empty_document());
EXPECT_EQ(kSubframeURLTwo, child->current_url());
EXPECT_EQ(url::Origin::Create(kMainFrameURL), child->current_origin());
// Set the `src` attribute again to trigger navigation (3).
TestFrameNavigationObserver commit_observer(child->current_frame_host());
ScopedFakeInterfaceBrokerRequestInjector injector(web_contents());
injector.set_fake_receiver_for_next_commit(mojo::NullReceiver());
ASSERT_TRUE(ExecJs(shell(), kNavigateToThreeScript));
commit_observer.WaitForCommit();
EXPECT_FALSE(injector.original_receiver_of_last_commit().is_valid());
EXPECT_FALSE(child->is_on_initial_empty_document());
EXPECT_EQ(kSubframeURLThree, child->current_url());
EXPECT_EQ(url::Origin::Create(kMainFrameURL), child->current_origin());
}
namespace {
void CheckURLOriginAndNetworkIsolationKey(
FrameTreeNode* node,
GURL url,
url::Origin origin,
net::NetworkIsolationKey network_isolation_key) {
EXPECT_EQ(url, node->current_url());
EXPECT_EQ(origin, node->current_origin());
EXPECT_EQ(network_isolation_key,
node->current_frame_host()->GetNetworkIsolationKey());
}
} // namespace
IN_PROC_BROWSER_TEST_F(RenderFrameHostImplBrowserTest,
NetworkIsolationKeyInitialEmptyDocumentIframe) {
GURL main_frame_url(embedded_test_server()->GetURL("/title1.html"));
url::Origin main_frame_origin = url::Origin::Create(main_frame_url);
net::SchemefulSite main_frame_site = net::SchemefulSite(main_frame_url);
net::NetworkIsolationKey expected_main_frame_key =
net::NetworkIsolationKey(main_frame_site, main_frame_site);
GURL subframe_url_one("about:blank");
GURL subframe_url_two("about:blank#foo");
GURL subframe_url_three(
embedded_test_server()->GetURL("foo.com", "/title2.html"));
url::Origin subframe_origin_three = url::Origin::Create(subframe_url_three);
net::NetworkIsolationKey expected_subframe_key_three =
net::NetworkIsolationKey(main_frame_site,
net::SchemefulSite(subframe_origin_three));
// Main frame navigation.
ASSERT_TRUE(NavigateToURL(shell(), main_frame_url));
FrameTreeNode* root = web_contents()->GetPrimaryFrameTree().root();
CheckURLOriginAndNetworkIsolationKey(root, main_frame_url, main_frame_origin,
expected_main_frame_key);
// Create iframe.
ASSERT_TRUE(ExecJs(shell(), R"(
var f = document.createElement('iframe');
f.id = 'myiframe';
document.body.append(f);
)"));
EXPECT_TRUE(WaitForLoadStop(web_contents()));
ASSERT_EQ(1u, root->child_count());
FrameTreeNode* child = root->child_at(0u);
CheckURLOriginAndNetworkIsolationKey(
child, subframe_url_one, main_frame_origin, expected_main_frame_key);
EXPECT_EQ(root->current_frame_host()->GetProcess(),
child->current_frame_host()->GetProcess());
// Same-document navigation of iframe.
ASSERT_TRUE(ExecJs(shell(), R"(
let iframe = document.querySelector('#myiframe');
iframe.contentWindow.location.hash = 'foo';
)"));
EXPECT_TRUE(WaitForLoadStop(web_contents()));
CheckURLOriginAndNetworkIsolationKey(
child, subframe_url_two, main_frame_origin, expected_main_frame_key);
EXPECT_EQ(root->current_frame_host()->GetProcess(),
child->current_frame_host()->GetProcess());
// Cross-document navigation of iframe.
TestFrameNavigationObserver commit_observer(child->current_frame_host());
std::string subframe_script_three = JsReplace(
"iframe = document.querySelector('#myiframe');"
"iframe.contentWindow.location.href = $1;",
subframe_url_three);
ASSERT_TRUE(ExecJs(shell(), subframe_script_three));
commit_observer.WaitForCommit();
CheckURLOriginAndNetworkIsolationKey(child, subframe_url_three,
subframe_origin_three,
expected_subframe_key_three);
if (AreAllSitesIsolatedForTesting()) {
EXPECT_NE(root->current_frame_host()->GetProcess(),
child->current_frame_host()->GetProcess());
}
}
IN_PROC_BROWSER_TEST_F(RenderFrameHostImplBrowserTest,
NetworkIsolationKeyInitialEmptyDocumentPopup) {
GURL main_frame_url(embedded_test_server()->GetURL("/title1.html"));
url::Origin main_frame_origin = url::Origin::Create(main_frame_url);
net::SchemefulSite main_frame_site = net::SchemefulSite(main_frame_url);
net::NetworkIsolationKey expected_main_frame_key =
net::NetworkIsolationKey(main_frame_site, main_frame_site);
GURL popup_url_one("about:blank");
GURL popup_url_two("about:blank#foo");
GURL popup_url_three(
embedded_test_server()->GetURL("foo.com", "/title2.html"));
url::Origin popup_origin_three = url::Origin::Create(popup_url_three);
net::SchemefulSite pop_site_three = net::SchemefulSite(popup_url_three);
net::NetworkIsolationKey expected_popup_key_three =
net::NetworkIsolationKey(pop_site_three, pop_site_three);
// Main frame navigation.
ASSERT_TRUE(NavigateToURL(shell(), main_frame_url));
FrameTreeNode* root = web_contents()->GetPrimaryFrameTree().root();
CheckURLOriginAndNetworkIsolationKey(root, main_frame_url, main_frame_origin,
expected_main_frame_key);
// Create popup.
WebContentsAddedObserver popup_observer;
ASSERT_TRUE(ExecJs(shell(), "var w = window.open('');"));
WebContentsImpl* popup =
static_cast<WebContentsImpl*>(popup_observer.GetWebContents());
FrameTreeNode* popup_frame = popup->GetPrimaryMainFrame()->frame_tree_node();
CheckURLOriginAndNetworkIsolationKey(
popup_frame, popup_url_one, main_frame_origin, expected_main_frame_key);
EXPECT_EQ(root->current_frame_host()->GetProcess(),
popup_frame->current_frame_host()->GetProcess());
// Same-document navigation of popup.
ASSERT_TRUE(ExecJs(shell(), "w.location.hash = 'foo';"));
EXPECT_TRUE(WaitForLoadStop(popup));
CheckURLOriginAndNetworkIsolationKey(
popup_frame, popup_url_two, main_frame_origin, expected_main_frame_key);
EXPECT_EQ(root->current_frame_host()->GetProcess(),
popup_frame->current_frame_host()->GetProcess());
// Cross-document navigation of popup.
TestFrameNavigationObserver commit_observer(
popup_frame->current_frame_host());
ASSERT_TRUE(
ExecJs(shell(), JsReplace("w.location.href = $1;", popup_url_three)));
commit_observer.WaitForCommit();
CheckURLOriginAndNetworkIsolationKey(popup_frame, popup_url_three,
popup_origin_three,
expected_popup_key_three);
if (AreAllSitesIsolatedForTesting()) {
EXPECT_NE(root->current_frame_host()->GetProcess(),
popup_frame->current_frame_host()->GetProcess());
}
}
// Navigating an iframe to about:blank sets the NetworkIsolationKey differently
// than creating a new frame at about:blank, so needs to be tested.
IN_PROC_BROWSER_TEST_F(RenderFrameHostImplBrowserTest,
NetworkIsolationKeyNavigateIframeToAboutBlank) {
GURL main_frame_url(embedded_test_server()->GetURL("/page_with_iframe.html"));
url::Origin origin = url::Origin::Create(main_frame_url);
net::SchemefulSite main_frame_site = net::SchemefulSite(main_frame_url);
net::NetworkIsolationKey expected_network_isolation_key =
net::NetworkIsolationKey(main_frame_site, main_frame_site);
ASSERT_TRUE(NavigateToURL(shell(), main_frame_url));
FrameTreeNode* root = web_contents()->GetPrimaryFrameTree().root();
CheckURLOriginAndNetworkIsolationKey(root, main_frame_url, origin,
expected_network_isolation_key);
ASSERT_EQ(1u, root->child_count());
CheckURLOriginAndNetworkIsolationKey(
root->child_at(0), embedded_test_server()->GetURL("/title1.html"), origin,
expected_network_isolation_key);
RenderFrameHost* iframe = root->child_at(0)->current_frame_host();
TestFrameNavigationObserver commit_observer(iframe);
ASSERT_TRUE(ExecJs(iframe, "window.location = 'about:blank'"));
commit_observer.WaitForCommit();
ASSERT_EQ(1u, root->child_count());
CheckURLOriginAndNetworkIsolationKey(root->child_at(0), GURL("about:blank"),
origin, expected_network_isolation_key);
// The iframe's SiteForCookies should first party with respect to
// |main_frame_url|.
EXPECT_TRUE(root->child_at(0)
->current_frame_host()
->ComputeSiteForCookies()
.IsFirstParty(main_frame_url));
}
// An iframe that starts at about:blank and is itself nested in a cross-site
// iframe should have the same NetworkIsolationKey as its parent.
IN_PROC_BROWSER_TEST_F(RenderFrameHostImplBrowserTest,
NetworkIsolationKeyNestedCrossSiteAboutBlankIframe) {
const char kSiteA[] = "a.test";
const char kSiteB[] = "b.test";
// Navigation and creation paths for determining about:blank's
// NetworkIsolationKey are different. This test is for the NIK-on-creation
// path, so need a URL that will start with a nested about:blank iframe.
GURL nested_iframe_url = GURL("about:blank");
GURL cross_site_iframe_url(embedded_test_server()->GetURL(
kSiteB, net::test_server::GetFilePathWithReplacements(
"/page_with_iframe.html",
base::StringPairs{
{"title1.html", nested_iframe_url.spec().c_str()}})));
GURL main_frame_url(embedded_test_server()->GetURL(
kSiteA, net::test_server::GetFilePathWithReplacements(
"/page_with_iframe.html",
base::StringPairs{
{"title1.html", cross_site_iframe_url.spec().c_str()}})));
// This should be the origin for both the iframes.
url::Origin iframe_origin = url::Origin::Create(cross_site_iframe_url);
url::Origin main_frame_origin = url::Origin::Create(main_frame_url);
net::SchemefulSite main_frame_site = net::SchemefulSite(main_frame_url);
net::NetworkIsolationKey expected_iframe_network_isolation_key(
main_frame_site, net::SchemefulSite{iframe_origin});
net::NetworkIsolationKey expected_main_frame_network_isolation_key(
main_frame_site, main_frame_site);
ASSERT_TRUE(NavigateToURL(shell(), main_frame_url));
FrameTreeNode* root = web_contents()->GetPrimaryFrameTree().root();
CheckURLOriginAndNetworkIsolationKey(
root, main_frame_url, main_frame_origin,
expected_main_frame_network_isolation_key);
ASSERT_EQ(1u, root->child_count());
FrameTreeNode* cross_site_iframe = root->child_at(0);
CheckURLOriginAndNetworkIsolationKey(cross_site_iframe, cross_site_iframe_url,
iframe_origin,
expected_iframe_network_isolation_key);
// Cross site iframes should have an empty site-for-cookies.
EXPECT_TRUE(cross_site_iframe->current_frame_host()
->ComputeSiteForCookies()
.IsNull());
ASSERT_EQ(1u, cross_site_iframe->child_count());
FrameTreeNode* nested_iframe = cross_site_iframe->child_at(0);
CheckURLOriginAndNetworkIsolationKey(nested_iframe, nested_iframe_url,
iframe_origin,
expected_iframe_network_isolation_key);
// Cross site iframes should have an empty site-for-cookies.
EXPECT_TRUE(
nested_iframe->current_frame_host()->ComputeSiteForCookies().IsNull());
}
// An iframe that's navigated to about:blank and is itself nested in a
// cross-site iframe should have the same NetworkIsolationKey as its parent. The
// navigation path is a bit different from the creation path in the above path,
// so needs to be tested as well.
IN_PROC_BROWSER_TEST_F(
RenderFrameHostImplBrowserTest,
NetworkIsolationKeyNavigateNestedCrossSiteAboutBlankIframe) {
const char kSiteA[] = "a.test";
const char kSiteB[] = "b.test";
const char kSiteC[] = "c.test";
// Start with a.test iframing b.test iframing c.test. Innermost iframe should
// not be on the same site as the middle iframe, so that navigations to/from
// about:blank initiated by b.test change its origin.
GURL innermost_iframe_url(
embedded_test_server()->GetURL(kSiteC, "/title1.html"));
GURL middle_iframe_url(embedded_test_server()->GetURL(
kSiteB, net::test_server::GetFilePathWithReplacements(
"/page_with_iframe.html",
base::StringPairs{
{"title1.html", innermost_iframe_url.spec().c_str()}})));
GURL main_frame_url(embedded_test_server()->GetURL(
kSiteA, net::test_server::GetFilePathWithReplacements(
"/page_with_iframe.html",
base::StringPairs{
{"title1.html", middle_iframe_url.spec().c_str()}})));
url::Origin innermost_iframe_origin =
url::Origin::Create(innermost_iframe_url);
url::Origin middle_iframe_origin = url::Origin::Create(middle_iframe_url);
url::Origin main_frame_origin = url::Origin::Create(main_frame_url);
net::SchemefulSite main_frame_site = net::SchemefulSite(main_frame_url);
net::NetworkIsolationKey expected_innermost_iframe_network_isolation_key(
main_frame_site, net::SchemefulSite{innermost_iframe_origin});
net::NetworkIsolationKey expected_middle_iframe_network_isolation_key(
main_frame_site, net::SchemefulSite{middle_iframe_origin});
net::NetworkIsolationKey expected_main_frame_network_isolation_key(
main_frame_site, main_frame_site);
ASSERT_TRUE(NavigateToURL(shell(), main_frame_url));
FrameTreeNode* root = web_contents()->GetPrimaryFrameTree().root();
CheckURLOriginAndNetworkIsolationKey(
root, main_frame_url, main_frame_origin,
expected_main_frame_network_isolation_key);
ASSERT_EQ(1u, root->child_count());
FrameTreeNode* middle_iframe = root->child_at(0);
CheckURLOriginAndNetworkIsolationKey(
middle_iframe, middle_iframe_url, middle_iframe_origin,
expected_middle_iframe_network_isolation_key);
// Cross site iframes should have an empty site-for-cookies.
EXPECT_TRUE(
middle_iframe->current_frame_host()->ComputeSiteForCookies().IsNull());
ASSERT_EQ(1u, middle_iframe->child_count());
FrameTreeNode* innermost_iframe = middle_iframe->child_at(0);
CheckURLOriginAndNetworkIsolationKey(
innermost_iframe, innermost_iframe_url, innermost_iframe_origin,
expected_innermost_iframe_network_isolation_key);
// Cross site iframes should have an empty site-for-cookies.
EXPECT_TRUE(
innermost_iframe->current_frame_host()->ComputeSiteForCookies().IsNull());
// The middle iframe navigates the innermost iframe to about:blank. It should
// then have the same NetworkIsolationKey as the middle iframe.
TestNavigationObserver nav_observer1(web_contents());
ASSERT_TRUE(ExecJs(
middle_iframe->current_frame_host(),
"var iframe = "
"document.getElementById('test_iframe');iframe.src='about:blank';"));
nav_observer1.WaitForNavigationFinished();
CheckURLOriginAndNetworkIsolationKey(
innermost_iframe, GURL("about:blank"), middle_iframe_origin,
expected_middle_iframe_network_isolation_key);
// Cross site iframes should have an empty site-for-cookies.
EXPECT_TRUE(
middle_iframe->current_frame_host()->ComputeSiteForCookies().IsNull());
// The innermost iframe, now at about:blank, navigates itself back its
// original location, which should make it use c.test's NIK again.
TestNavigationObserver nav_observer2(web_contents());
ASSERT_TRUE(
ExecJs(innermost_iframe->current_frame_host(), "window.history.back();"));
nav_observer2.WaitForNavigationFinished();
CheckURLOriginAndNetworkIsolationKey(
innermost_iframe, innermost_iframe_url, innermost_iframe_origin,
expected_innermost_iframe_network_isolation_key);
// Cross site iframes should have an empty site-for-cookies.
EXPECT_TRUE(
innermost_iframe->current_frame_host()->ComputeSiteForCookies().IsNull());
// The innermost iframe, now at c.test, navigates itself back to about:blank.
// Despite c.test initiating the navigation, the iframe should be using
// b.test's NIK, since the navigation entry was created by a navigation
// initiated by b.test.
TestNavigationObserver nav_observer3(web_contents());
ASSERT_TRUE(ExecJs(innermost_iframe->current_frame_host(),
"window.history.forward();"));
nav_observer3.WaitForNavigationFinished();
CheckURLOriginAndNetworkIsolationKey(
innermost_iframe, GURL("about:blank"), middle_iframe_origin,
expected_middle_iframe_network_isolation_key);
// Cross site iframes should have an empty site-for-cookies.
EXPECT_TRUE(
innermost_iframe->current_frame_host()->ComputeSiteForCookies().IsNull());
}
// Helper function to fetch the canonical link URL from the provided frame.
std::optional<GURL> GetCanonicalUrlFromFrame(RenderFrameHostImpl* frame) {
base::RunLoop loop;
std::optional<GURL> canon_url;
frame->GetCanonicalUrl(
base::BindLambdaForTesting([&](const std::optional<GURL>& url) {
canon_url = url;
loop.Quit();
}));
loop.Run();
return canon_url;
}
IN_PROC_BROWSER_TEST_F(RenderFrameHostImplBrowserTest, GetCanonicalUrl_None) {
EXPECT_TRUE(NavigateToURL(shell(), GURL(url::kAboutBlankURL)));
base::HistogramTester histogram_tester;
std::optional<GURL> canon_url =
GetCanonicalUrlFromFrame(web_contents()->GetPrimaryMainFrame());
// No canonical link should be returned if the page has none.
ASSERT_FALSE(canon_url.has_value());
content::FetchHistogramsFromChildProcesses();
#if BUILDFLAG(IS_ANDROID)
ASSERT_TRUE(base::TimeTicks::IsHighResolution())
<< "The Blink.Frame.GetCanonicalUrlRendererTime histogram has "
"microseconds precision and requires a high-resolution clock";
histogram_tester.ExpectTotalCount("Blink.Frame.GetCanonicalUrlRendererTime",
1);
#endif
}
IN_PROC_BROWSER_TEST_F(RenderFrameHostImplBrowserTest, GetCanonicalUrl_InBody) {
EXPECT_TRUE(NavigateToURL(
shell(), GetTestUrl("render_frame_host", "canonical_link_in_body.html")));
base::HistogramTester histogram_tester;
std::optional<GURL> canon_url =
GetCanonicalUrlFromFrame(web_contents()->GetPrimaryMainFrame());
// A canonical link in the body should be ignored.
ASSERT_FALSE(canon_url.has_value());
content::FetchHistogramsFromChildProcesses();
#if BUILDFLAG(IS_ANDROID)
ASSERT_TRUE(base::TimeTicks::IsHighResolution())
<< "The Blink.Frame.GetCanonicalUrlRendererTime histogram has "
"microseconds precision and requires a high-resolution clock";
histogram_tester.ExpectTotalCount("Blink.Frame.GetCanonicalUrlRendererTime",
1);
#endif
}
IN_PROC_BROWSER_TEST_F(RenderFrameHostImplBrowserTest,
GetCanonicalUrl_SingleLink_WithDocumentFragment) {
GURL::Replacements replace_fragment;
replace_fragment.SetRefStr("fragment");
GURL url_with_fragment =
GetTestUrl("render_frame_host", "canonical_link.html")
.ReplaceComponents(replace_fragment);
EXPECT_TRUE(NavigateToURL(shell(), url_with_fragment));
base::HistogramTester histogram_tester;
std::optional<GURL> canon_url =
GetCanonicalUrlFromFrame(web_contents()->GetPrimaryMainFrame());
ASSERT_TRUE(canon_url.has_value());
// The canonical link should be returned appended with the fragment from the
// loaded document/URL.
EXPECT_EQ(GURL("https://example.com/canonical.html#fragment"),
canon_url.value());
content::FetchHistogramsFromChildProcesses();
#if BUILDFLAG(IS_ANDROID)
ASSERT_TRUE(base::TimeTicks::IsHighResolution())
<< "The Blink.Frame.GetCanonicalUrlRendererTime histogram has "
"microseconds precision and requires a high-resolution clock";
histogram_tester.ExpectTotalCount("Blink.Frame.GetCanonicalUrlRendererTime",
1);
#endif
}
IN_PROC_BROWSER_TEST_F(RenderFrameHostImplBrowserTest,
GetCanonicalUrl_MultipleLinks_WithCanonicalFragment) {
GURL::Replacements replace_fragment;
replace_fragment.SetRefStr("fragment");
GURL url_with_fragment =
GetTestUrl("render_frame_host", "canonical_links_with_fragments.html")
.ReplaceComponents(replace_fragment);
EXPECT_TRUE(NavigateToURL(shell(), url_with_fragment));
base::HistogramTester histogram_tester;
std::optional<GURL> canon_url =
GetCanonicalUrlFromFrame(web_contents()->GetPrimaryMainFrame());
ASSERT_TRUE(canon_url.has_value());
// The first canonical link should be returned, and its fragment should
// take precedence over the one from the loaded document/URL.
EXPECT_EQ(GURL("https://example.com/canonical1.html#a1"), canon_url.value());
content::FetchHistogramsFromChildProcesses();
#if BUILDFLAG(IS_ANDROID)
ASSERT_TRUE(base::TimeTicks::IsHighResolution())
<< "The Blink.Frame.GetCanonicalUrlRendererTime histogram has "
"microseconds precision and requires a high-resolution clock";
histogram_tester.ExpectTotalCount("Blink.Frame.GetCanonicalUrlRendererTime",
1);
#endif
}
// Regression test for https://crbug.com/852350
IN_PROC_BROWSER_TEST_F(RenderFrameHostImplBrowserTest,
GetCanonicalUrlAfterRendererCrash) {
EXPECT_TRUE(NavigateToURL(
shell(), GetTestUrl("render_frame_host", "beforeunload.html")));
EXPECT_TRUE(WaitForLoadStop(web_contents()));
RenderFrameHostImpl* main_frame = web_contents()->GetPrimaryMainFrame();
// Make the renderer crash.
RenderProcessHost* renderer_process = main_frame->GetProcess();
RenderProcessHostWatcher crash_observer(
renderer_process, RenderProcessHostWatcher::WATCH_FOR_PROCESS_EXIT);
renderer_process->Shutdown(0);
crash_observer.Wait();
main_frame->GetCanonicalUrl(base::DoNothing());
}
// This test makes sure that when a blocked frame commits with a different URL,
// it doesn't lead to a leaked NavigationHandle. This is a regression test for
// https://crbug.com/872803.
IN_PROC_BROWSER_TEST_F(RenderFrameHostImplBrowserTest,
ErrorPagesShouldntLeakNavigationHandles) {
GURL main_url(embedded_test_server()->GetURL(
"foo.com", "/frame_tree/page_with_one_frame.html"));
EXPECT_TRUE(NavigateToURL(shell(), main_url));
GURL blocked_url(embedded_test_server()->GetURL(
"blocked.com", "/frame-ancestors-none.html"));
NavigationHandleObserver navigation_observer(web_contents(), blocked_url);
EXPECT_TRUE(NavigateIframeToURL(web_contents(), "child0", blocked_url));
// Verify that the NavigationHandle / NavigationRequest didn't leak.
RenderFrameHostImpl* frame =
static_cast<RenderFrameHostImpl*>(ChildFrameAt(root_frame_host(), 0));
EXPECT_FALSE(frame->HasPendingCommitNavigation());
// TODO(lukasza, clamy): https://crbug.com/784904: Verify that
// WebContentsObserver::DidFinishNavigation was called with the same
// NavigationHandle as WebContentsObserver::DidStartNavigation. This requires
// properly matching the commit IPC to the NavigationHandle (ignoring that
// their URLs do not match - matching instead using navigation id or mojo
// interface identity).
// TODO(crbug.com/40537082): Verify CSP frame-ancestors in the browser
// process. Currently, this is done by the renderer process, which commits an
// empty document with success instead.
EXPECT_TRUE(navigation_observer.has_committed());
EXPECT_TRUE(navigation_observer.is_error());
EXPECT_EQ(blocked_url, frame->GetLastCommittedURL());
EXPECT_EQ(net::ERR_BLOCKED_BY_RESPONSE, navigation_observer.net_error_code());
}
// Tests that when a same-document commit is aborted in the renderer (in this
// case, by the navigate event being cancelled), it does not leak its
// NavigationHandle.
IN_PROC_BROWSER_TEST_F(
RenderFrameHostImplBrowserTest,
AbortedSameDocumentNavigationsShouldNotLeakNavigationHandles) {
GURL main_url(embedded_test_server()->GetURL("foo.com", "/title1.html"));
ASSERT_TRUE(NavigateToURL(shell(), main_url));
// Abort the next navigation via the navigate event.
EXPECT_TRUE(ExecJs(root_frame_host(),
"navigation.onnavigate = e => e.preventDefault()"));
GURL blocked_url(
embedded_test_server()->GetURL("foo.com", "/title1.html#blocked"));
NavigationHandleObserver navigation_observer(web_contents(), blocked_url);
EXPECT_FALSE(NavigateToURL(shell(), blocked_url));
EXPECT_EQ(main_url,
web_contents()->GetPrimaryMainFrame()->GetLastCommittedURL());
EXPECT_TRUE(navigation_observer.is_same_document());
// Verify that the NavigationHandle / NavigationRequest didn't leak.
EXPECT_FALSE(root_frame_host()->HasPendingCommitNavigation());
}
// TODO(japhet): Remove this helper class and use RenderFrameHostImplBrowserTest
// when blink::features::kNavigateEventCommitBehavior is removed.
class RenderFrameHostImplCommitBehaviorBrowserTest
: public RenderFrameHostImplBrowserTest {
public:
RenderFrameHostImplCommitBehaviorBrowserTest() {
scoped_feature_list_.InitAndEnableFeature(
blink::features::kNavigateEventCommitBehavior);
}
protected:
base::test::ScopedFeatureList scoped_feature_list_;
};
// Tests that when the navigation API intercepts and defers a commit, then
// a second navigation preempts the deferred commit, no NavigationHandles are
// leaked.
IN_PROC_BROWSER_TEST_F(
RenderFrameHostImplCommitBehaviorBrowserTest,
DeferredAndPreemptedSameDocumentNavigationsShouldNotLeakNavigationHandles) {
GURL main_url(embedded_test_server()->GetURL("foo.com", "/title1.html"));
ASSERT_TRUE(NavigateToURL(shell(), main_url));
// Add a navigate event listener that will intercept the next navigation and
// defer it for 100ms, then start a new navigation to preempt it.
EXPECT_TRUE(ExecJs(root_frame_host(),
"navigation.addEventListener('navigate',"
" e => { e.intercept({"
" precommitHandler: async() => {"
" await new Promise(r => setTimeout(r, 100));"
" }"
" }); "
" setTimeout(() => navigation.navigate('#allowed'), 0);"
"}, { once: true });"));
GURL blocked_url(
embedded_test_server()->GetURL("foo.com", "/title1.html#blocked"));
NavigationHandleObserver navigation_observer(web_contents(), blocked_url);
EXPECT_FALSE(NavigateToURL(shell(), blocked_url));
EXPECT_TRUE(navigation_observer.is_same_document());
GURL allowed_url(
embedded_test_server()->GetURL("foo.com", "/title1.html#allowed"));
EXPECT_EQ(allowed_url,
web_contents()->GetPrimaryMainFrame()->GetLastCommittedURL());
// Verify that the NavigationHandle / NavigationRequest didn't leak.
EXPECT_FALSE(root_frame_host()->HasPendingCommitNavigation());
}
// Tests that when the navigation API intercepts and defers a commit, then
// the commit is aborted by script, no NavigationHandles are leaked.
IN_PROC_BROWSER_TEST_F(
RenderFrameHostImplCommitBehaviorBrowserTest,
DeferredAndRejectedSameDocumentNavigationsShouldntLeakNavigationHandles) {
GURL main_url(embedded_test_server()->GetURL("foo.com", "/title1.html"));
ASSERT_TRUE(NavigateToURL(shell(), main_url));
// Add a navigate event listener that will intercept the next navigation and
// reject it without committing it, causing the navigation to abort.
EXPECT_TRUE(ExecJs(root_frame_host(),
"navigation.addEventListener('navigate',"
" e => { e.intercept({"
" precommitHandler: () => Promise.reject()"
" }); "
"});"));
GURL blocked_url(
embedded_test_server()->GetURL("foo.com", "/title1.html#blocked"));
NavigationHandleObserver navigation_observer(web_contents(), blocked_url);
EXPECT_FALSE(NavigateToURL(shell(), blocked_url));
EXPECT_TRUE(navigation_observer.is_same_document());
// Verify that the NavigationHandle / NavigationRequest didn't leak.
EXPECT_FALSE(root_frame_host()->HasPendingCommitNavigation());
}
IN_PROC_BROWSER_TEST_F(RenderFrameHostImplBrowserTest,
BeforeUnloadDialogSuppressedForDiscard) {
TestJavaScriptDialogManager dialog_manager;
web_contents()->SetDelegate(&dialog_manager);
EXPECT_TRUE(NavigateToURL(
shell(), GetTestUrl("render_frame_host", "beforeunload.html")));
// Disable the hang monitor, otherwise there will be a race between the
// beforeunload dialog and the beforeunload hang timer.
web_contents()
->GetPrimaryMainFrame()
->DisableBeforeUnloadHangMonitorForTesting();
// Give the page a user gesture so javascript beforeunload works, and then
// dispatch a before unload with discard as a reason. This should return
// without any dialog being seen.
web_contents()
->GetPrimaryMainFrame()
->ExecuteJavaScriptWithUserGestureForTests(
std::u16string(), base::NullCallback(), ISOLATED_WORLD_ID_GLOBAL);
web_contents()->GetPrimaryMainFrame()->DispatchBeforeUnload(
RenderFrameHostImpl::BeforeUnloadType::DISCARD, false);
dialog_manager.Wait();
EXPECT_EQ(0, dialog_manager.num_beforeunload_dialogs_seen());
EXPECT_EQ(1, dialog_manager.num_beforeunload_fired_seen());
EXPECT_FALSE(dialog_manager.proceed());
web_contents()->SetDelegate(nullptr);
}
IN_PROC_BROWSER_TEST_F(RenderFrameHostImplBrowserTest,
PendingDialogMakesDiscardUnloadReturnFalse) {
TestJavaScriptDialogManager dialog_manager;
web_contents()->SetDelegate(&dialog_manager);
EXPECT_TRUE(NavigateToURL(
shell(), GetTestUrl("render_frame_host", "beforeunload.html")));
// Disable the hang monitor, otherwise there will be a race between the
// beforeunload dialog and the beforeunload hang timer.
web_contents()
->GetPrimaryMainFrame()
->DisableBeforeUnloadHangMonitorForTesting();
// Give the page a user gesture so javascript beforeunload works, and then
// dispatch a before unload with discard as a reason. This should return
// without any dialog being seen.
web_contents()
->GetPrimaryMainFrame()
->ExecuteJavaScriptWithUserGestureForTests(
std::u16string(), base::NullCallback(), ISOLATED_WORLD_ID_GLOBAL);
// Launch an alert javascript dialog. This pending dialog should block a
// subsequent discarding before unload request.
web_contents()->GetPrimaryMainFrame()->ExecuteJavaScriptForTests(
u"setTimeout(function(){alert('hello');}, 10);", base::NullCallback(),
ISOLATED_WORLD_ID_GLOBAL);
dialog_manager.Wait();
EXPECT_EQ(0, dialog_manager.num_beforeunload_dialogs_seen());
EXPECT_EQ(0, dialog_manager.num_beforeunload_fired_seen());
// Dispatch a before unload request while the first is still blocked
// on the dialog, and expect it to return false immediately (synchronously).
web_contents()->GetPrimaryMainFrame()->DispatchBeforeUnload(
RenderFrameHostImpl::BeforeUnloadType::DISCARD, false);
dialog_manager.Wait();
EXPECT_EQ(0, dialog_manager.num_beforeunload_dialogs_seen());
EXPECT_EQ(1, dialog_manager.num_beforeunload_fired_seen());
EXPECT_FALSE(dialog_manager.proceed());
// Clear the existing javascript dialog so that the associated IPC message
// doesn't leak.
dialog_manager.Run(true, std::u16string());
web_contents()->SetDelegate(nullptr);
}
IN_PROC_BROWSER_TEST_F(RenderFrameHostImplBrowserTest,
NotifiesProcessHostOfAudibleAudio) {
const auto RunPostedTasks = []() {
base::RunLoop run_loop;
base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
FROM_HERE, run_loop.QuitClosure());
run_loop.Run();
};
// Note: Just using the beforeunload.html test document to spin-up a
// renderer. Any document will do.
EXPECT_TRUE(NavigateToURL(
shell(), GetTestUrl("render_frame_host", "beforeunload.html")));
EXPECT_TRUE(WaitForLoadStop(web_contents()));
auto* frame = web_contents()->GetPrimaryMainFrame();
auto* process = static_cast<RenderProcessHostImpl*>(frame->GetProcess());
ASSERT_EQ(0, process->get_media_stream_count_for_testing());
// Audible audio output should cause the media stream count to increment.
frame->OnMediaStreamAdded(RenderFrameHostImpl::GetAudibleMediaStreamType());
RunPostedTasks();
EXPECT_EQ(1, process->get_media_stream_count_for_testing());
// Silence should cause the media stream count to decrement.
frame->OnMediaStreamRemoved(RenderFrameHostImpl::GetAudibleMediaStreamType());
RunPostedTasks();
EXPECT_EQ(0, process->get_media_stream_count_for_testing());
// Start audible audio output again, and then crash the renderer. Expect the
// media stream count to be zero after the crash.
frame->OnMediaStreamAdded(RenderFrameHostImpl::GetAudibleMediaStreamType());
RunPostedTasks();
EXPECT_EQ(1, process->get_media_stream_count_for_testing());
RenderProcessHostWatcher crash_observer(
process, RenderProcessHostWatcher::WATCH_FOR_PROCESS_EXIT);
process->Shutdown(0);
crash_observer.Wait();
RunPostedTasks();
EXPECT_EQ(0, process->get_media_stream_count_for_testing());
}
// Test that a frame is visible/hidden depending on its WebContents visibility
// state.
IN_PROC_BROWSER_TEST_F(RenderFrameHostImplBrowserTest,
DISABLED_VisibilityScrolledOutOfView) {
GURL main_frame(embedded_test_server()->GetURL("/iframe_out_of_view.html"));
GURL child_url(embedded_test_server()->GetURL("/hello.html"));
// This will set up the page frame tree as A(A1()).
ASSERT_TRUE(NavigateToURL(shell(), main_frame));
// TODO(crbug.com/41453701): Re-enable this test
FrameTreeNode* root = web_contents()->GetPrimaryFrameTree().root();
FrameTreeNode* nested_iframe_node = root->child_at(0);
EXPECT_TRUE(NavigateToURLFromRenderer(nested_iframe_node, child_url));
ASSERT_EQ(blink::mojom::FrameVisibility::kRenderedOutOfViewport,
nested_iframe_node->current_frame_host()->visibility());
}
// Test that a frame is visible/hidden depending on its WebContents visibility
// state.
IN_PROC_BROWSER_TEST_F(RenderFrameHostImplBrowserTest, VisibilityChildInView) {
GURL main_frame(embedded_test_server()->GetURL("/iframe_clipped.html"));
GURL child_url(embedded_test_server()->GetURL("/hello.html"));
// This will set up the page frame tree as A(A1()).
ASSERT_TRUE(NavigateToURL(shell(), main_frame));
FrameTreeNode* root = web_contents()->GetPrimaryFrameTree().root();
FrameTreeNode* nested_iframe_node = root->child_at(0);
EXPECT_TRUE(NavigateToURLFromRenderer(nested_iframe_node, child_url));
ASSERT_EQ(blink::mojom::FrameVisibility::kRenderedInViewport,
nested_iframe_node->current_frame_host()->visibility());
}
IN_PROC_BROWSER_TEST_F(RenderFrameHostImplBrowserTest,
OriginOfFreshFrame_Subframe_NavCancelledByDocWrite) {
NavigationController& controller = web_contents()->GetController();
GURL main_url(embedded_test_server()->GetURL("foo.com", "/title1.html"));
ASSERT_TRUE(NavigateToURL(shell(), main_url));
EXPECT_EQ(1, controller.GetEntryCount());
url::Origin main_origin = url::Origin::Create(main_url);
// document.open should cancel the cross-origin navigation to '/hung' and the
// subframe should remain on the parent/initiator origin.
const char kScriptTemplate[] = R"(
const frame = document.createElement('iframe');
frame.src = $1;
document.body.appendChild(frame);
const html = '<!DOCTYPE html><html><body>Hello world!</body></html>';
const doc = frame.contentDocument;
doc.open();
doc.write(html);
doc.close();
frame.contentWindow.origin;
)";
GURL cross_site_url(embedded_test_server()->GetURL("bar.com", "/hung"));
std::string script = JsReplace(kScriptTemplate, cross_site_url);
EXPECT_EQ(main_origin.Serialize(), EvalJs(web_contents(), script));
// The subframe navigation should be cancelled and therefore shouldn't
// contribute an extra history entry.
EXPECT_EQ(1, controller.GetEntryCount());
// Browser-side origin should match the renderer-side origin.
// See also https://crbug.com/932067.
RenderFrameHostImpl* subframe =
static_cast<RenderFrameHostImpl*>(ChildFrameAt(root_frame_host(), 0));
ASSERT_TRUE(subframe);
EXPECT_EQ(main_origin, subframe->GetLastCommittedOrigin());
EXPECT_EQ(blink::StorageKey::CreateFirstParty(main_origin),
subframe->GetStorageKey());
}
IN_PROC_BROWSER_TEST_F(RenderFrameHostImplBrowserTest,
OriginOfFreshFrame_SandboxedSubframe) {
NavigationController& controller = web_contents()->GetController();
GURL main_url(embedded_test_server()->GetURL("foo.com", "/title1.html"));
ASSERT_TRUE(NavigateToURL(shell(), main_url));
EXPECT_EQ(1, controller.GetEntryCount());
url::Origin main_origin = url::Origin::Create(main_url);
// Navigate a sandboxed frame to a cross-origin '/hung'.
RenderFrameHostCreatedObserver subframe_observer(web_contents());
const char kScriptTemplate[] = R"(
const frame = document.createElement('iframe');
frame.sandbox = 'allow-scripts';
frame.src = $1;
document.body.appendChild(frame);
)";
GURL cross_site_url(embedded_test_server()->GetURL("bar.com", "/hung"));
std::string script = JsReplace(kScriptTemplate, cross_site_url);
EXPECT_TRUE(ExecJs(web_contents(), script));
// Wait for a new subframe, but ignore the frame returned by
// |subframe_observer| (it might be the speculative one, not the current one).
subframe_observer.Wait();
RenderFrameHost* subframe = ChildFrameAt(root_frame_host(), 0);
ASSERT_TRUE(subframe);
// The browser-side origin of the *sandboxed* subframe should be set to an
// *opaque* origin (with the parent's origin as the precursor origin).
EXPECT_TRUE(subframe->GetLastCommittedOrigin().opaque());
EXPECT_EQ(
main_origin.GetTupleOrPrecursorTupleIfOpaque(),
subframe->GetLastCommittedOrigin().GetTupleOrPrecursorTupleIfOpaque());
// Note that the test cannot check the renderer-side origin of the frame:
// - Scripts cannot be executed before the frame commits,
// - The parent cannot document.write into the *sandboxed* frame.
}
IN_PROC_BROWSER_TEST_F(RenderFrameHostImplBrowserTest,
OriginOfFreshFrame_Subframe_AboutBlankAndThenDocWrite) {
NavigationController& controller = web_contents()->GetController();
GURL main_url(embedded_test_server()->GetURL("foo.com", "/title1.html"));
ASSERT_TRUE(NavigateToURL(shell(), main_url));
EXPECT_EQ(1, controller.GetEntryCount());
url::Origin main_origin = url::Origin::Create(main_url);
// Create a new about:blank subframe and document.write into it.
TestNavigationObserver load_observer(web_contents());
RenderFrameHostCreatedObserver subframe_observer(web_contents());
const char kScript[] = R"(
const frame = document.createElement('iframe');
// Don't set |frame.src| - have the frame commit an initial about:blank.
document.body.appendChild(frame);
const html = '<!DOCTYPE html><html><body>Hello world!</body></html>';
const doc = frame.contentDocument;
doc.open();
doc.write(html);
doc.close();
)";
ExecuteScriptAsync(web_contents(), kScript);
// Wait for the new subframe to be created - this will be still before the
// commit of about:blank.
RenderFrameHostImpl* subframe =
static_cast<RenderFrameHostImpl*>(subframe_observer.Wait());
EXPECT_EQ(main_origin, subframe->GetLastCommittedOrigin());
EXPECT_EQ(blink::StorageKey::CreateFirstParty(main_origin),
subframe->GetStorageKey());
// Wait for the about:blank navigation to finish.
load_observer.Wait();
// The subframe commit to about:blank should not contribute an extra history
// entry.
EXPECT_EQ(1, controller.GetEntryCount());
// Browser-side origin should match the renderer-side origin.
// See also https://crbug.com/932067.
RenderFrameHostImpl* subframe2 =
static_cast<RenderFrameHostImpl*>(ChildFrameAt(root_frame_host(), 0));
ASSERT_TRUE(subframe2);
EXPECT_EQ(subframe, subframe2); // No swaps are expected.
EXPECT_EQ(main_origin, subframe2->GetLastCommittedOrigin());
EXPECT_EQ(blink::StorageKey::CreateFirstParty(main_origin),
subframe2->GetStorageKey());
EXPECT_EQ(main_origin.Serialize(), EvalJs(subframe2, "window.origin"));
}
IN_PROC_BROWSER_TEST_F(RenderFrameHostImplBrowserTest,
OriginOfFreshFrame_Popup_NavCancelledByDocWrite) {
GURL main_url(embedded_test_server()->GetURL("foo.com", "/title1.html"));
ASSERT_TRUE(NavigateToURL(shell(), main_url));
url::Origin main_origin = url::Origin::Create(main_url);
// document.open should cancel the cross-origin navigation to '/hung' and the
// popup should remain on the initiator origin.
WebContentsAddedObserver popup_observer;
const char kScriptTemplate[] = R"(
var popup = window.open($1, 'popup');
const html = '<!DOCTYPE html><html><body>Hello world!</body></html>';
const doc = popup.document;
doc.open();
doc.write(html);
doc.close();
popup.origin;
)";
GURL cross_site_url(embedded_test_server()->GetURL("bar.com", "/hung"));
std::string script = JsReplace(kScriptTemplate, cross_site_url);
EXPECT_EQ(main_origin.Serialize(), EvalJs(web_contents(), script));
// Browser-side origin should match the renderer-side origin.
// See also https://crbug.com/932067.
WebContents* popup = popup_observer.GetWebContents();
EXPECT_EQ(main_origin,
popup->GetPrimaryMainFrame()->GetLastCommittedOrigin());
EXPECT_EQ(blink::StorageKey::CreateFirstParty(main_origin),
static_cast<RenderFrameHostImpl*>(popup->GetPrimaryMainFrame())
->GetStorageKey());
// The popup navigation should be cancelled and therefore shouldn't
// contribute an extra history entry.
EXPECT_EQ(1, popup->GetController().GetEntryCount());
EXPECT_TRUE(popup->GetController().GetLastCommittedEntry()->IsInitialEntry());
}
IN_PROC_BROWSER_TEST_F(RenderFrameHostImplBrowserTest,
OriginOfFreshFrame_Popup_AboutBlankAndThenDocWrite) {
GURL main_url(embedded_test_server()->GetURL("foo.com", "/title1.html"));
ASSERT_TRUE(NavigateToURL(shell(), main_url));
url::Origin main_origin = url::Origin::Create(main_url);
// Create a new about:blank popup and document.write into it.
WebContentsAddedObserver popup_observer;
const char kScript[] = R"(
// Empty |url| argument means that the popup will commit an initial
// about:blank.
var popup = window.open('', 'popup');
const html = '<!DOCTYPE html><html><body>Hello world!</body></html>';
const doc = popup.document;
doc.open();
doc.write(html);
doc.close();
)";
ExecuteScriptAsync(web_contents(), kScript);
// Wait for the new popup to be created (this will be before the popup finish
// the synchronous about:blank commit in the browser).
WebContents* popup = popup_observer.GetWebContents();
content::TestNavigationObserver load_observer(popup);
EXPECT_EQ(main_origin,
popup->GetPrimaryMainFrame()->GetLastCommittedOrigin());
EXPECT_EQ(blink::StorageKey::CreateFirstParty(main_origin),
static_cast<RenderFrameHostImpl*>(popup->GetPrimaryMainFrame())
->GetStorageKey());
load_observer.WaitForNavigationFinished();
EXPECT_EQ(main_origin,
popup->GetPrimaryMainFrame()->GetLastCommittedOrigin());
EXPECT_EQ(blink::StorageKey::CreateFirstParty(main_origin),
static_cast<RenderFrameHostImpl*>(popup->GetPrimaryMainFrame())
->GetStorageKey());
// The popup navigation should be cancelled and therefore shouldn't
// contribute an extra history entry.
EXPECT_EQ(1, popup->GetController().GetEntryCount());
EXPECT_TRUE(popup->GetController().GetLastCommittedEntry()->IsInitialEntry());
}
IN_PROC_BROWSER_TEST_F(RenderFrameHostImplBrowserTest,
AccessibilityIsRootIframe) {
GURL main_url(
embedded_test_server()->GetURL("foo.com", "/page_with_iframe.html"));
ASSERT_TRUE(NavigateToURL(shell(), main_url));
RenderFrameHostImpl* main_frame = web_contents()->GetPrimaryMainFrame();
EXPECT_TRUE(main_frame->AccessibilityIsRootFrame());
ASSERT_EQ(1u, main_frame->child_count());
RenderFrameHostImpl* iframe = main_frame->child_at(0)->current_frame_host();
EXPECT_FALSE(iframe->AccessibilityIsRootFrame());
}
IN_PROC_BROWSER_TEST_F(RenderFrameHostImplBrowserTest,
RequestSnapshotAXTreeAfterRenderProcessHostDeath) {
EXPECT_TRUE(NavigateToURL(shell(), GURL(url::kAboutBlankURL)));
auto* rfh = web_contents()->GetPrimaryMainFrame();
// Kill the renderer process.
RenderProcessHostWatcher crash_observer(
rfh->GetProcess(), RenderProcessHostWatcher::WATCH_FOR_PROCESS_EXIT);
rfh->GetProcess()->Shutdown(0);
crash_observer.Wait();
// Call RequestAXSnapshotTree method. The browser process should not crash.
auto params = mojom::SnapshotAccessibilityTreeParams::New();
rfh->RequestAXTreeSnapshot(
base::BindOnce([](ui::AXTreeUpdate& snapshot) { NOTREACHED(); }),
std::move(params));
base::RunLoop().RunUntilIdle();
// Pass if this didn't crash.
}
// Verify that adding an <object> tag which resource is blocked by the network
// stack does not result in terminating the renderer process.
// See https://crbug.com/955777.
IN_PROC_BROWSER_TEST_F(RenderFrameHostImplBrowserTest,
ObjectTagBlockedResource) {
EXPECT_TRUE(NavigateToURL(shell(), embedded_test_server()->GetURL(
"/page_with_object_fallback.html")));
GURL object_url(embedded_test_server()->GetURL("a.com", "/title1.html"));
std::unique_ptr<URLLoaderInterceptor> url_interceptor =
URLLoaderInterceptor::SetupRequestFailForURL(object_url,
net::ERR_BLOCKED_BY_CLIENT);
auto* rfh = web_contents()->GetPrimaryMainFrame();
TestNavigationObserver observer(web_contents());
EXPECT_TRUE(ExecJs(rfh, JsReplace("setUrl($1);", object_url),
EXECUTE_SCRIPT_NO_RESOLVE_PROMISES));
observer.Wait();
EXPECT_EQ(rfh->GetLastCommittedOrigin().Serialize(),
EvalJs(web_contents(), "window.origin"));
}
// Regression test for crbug.com/953934. It shouldn't crash if we quickly remove
// an object element in the middle of its failing navigation.
IN_PROC_BROWSER_TEST_F(RenderFrameHostImplBrowserTest,
NoCrashOnRemoveObjectElementWithInvalidData) {
GURL url = GetFileURL(
FILE_PATH_LITERAL("remove_object_element_with_invalid_data.html"));
RenderProcessHostWatcher crash_observer(
web_contents(), RenderProcessHostWatcher::WATCH_FOR_PROCESS_EXIT);
// This navigates to a page with an object element that will fail to load.
// When document load event hits, it'll attempt to remove that object element.
// This might happen while the object element's failed commit is underway.
// To make sure we hit these conditions and that we don't exit the test too
// soon, let's wait until the document.readyState finalizes. We don't really
// care if that succeeds since, in the failing case, the renderer is crashing.
EXPECT_TRUE(NavigateToURL(shell(), url));
std::ignore = WaitForRenderFrameReady(web_contents()->GetPrimaryMainFrame());
EXPECT_TRUE(crash_observer.did_exit_normally());
}
IN_PROC_BROWSER_TEST_F(RenderFrameHostImplBrowserTest,
SchedulerTrackedFeatures) {
EXPECT_TRUE(
NavigateToURL(shell(), embedded_test_server()->GetURL("/title1.html")));
RenderFrameHostImpl* main_frame = web_contents()->GetPrimaryMainFrame();
// Simulate getting WebSocket in a feature vector from the renderer.
main_frame->DidChangeBackForwardCacheDisablingFeatures(
CreateBlockingDetails({BlocklistedFeature::kWebSocket}));
ASSERT_EQ(main_frame->GetBackForwardCacheDisablingFeatures(),
BlocklistedFeatures({BlocklistedFeature::kWebSocket}));
// Simulate the browser side reporting WebRTC usage.
main_frame->OnBackForwardCacheDisablingStickyFeatureUsed(
static_cast<BlocklistedFeature>(BlocklistedFeature::kWebRTC));
ASSERT_EQ(main_frame->GetBackForwardCacheDisablingFeatures(),
BlocklistedFeatures(
{BlocklistedFeature::kWebSocket, BlocklistedFeature::kWebRTC}));
// Simulate a feature vector being updated from the renderer with some
// features being activated and some being deactivated.
// [kWebSocket(0), kWebRTC(1)] -> [kWebRTC(1),
// kMainResourceHasCacheControlNoCache(2)]
main_frame->DidChangeBackForwardCacheDisablingFeatures(CreateBlockingDetails(
{BlocklistedFeature::kWebRTC,
BlocklistedFeature::kMainResourceHasCacheControlNoCache}));
ASSERT_EQ(main_frame->GetBackForwardCacheDisablingFeatures(),
BlocklistedFeatures(
{BlocklistedFeature::kWebRTC,
BlocklistedFeature::kMainResourceHasCacheControlNoCache}));
// Navigate away and expect that no values persist the navigation.
// Note that we are still simulating the renderer call, otherwise features
// like "document loaded" will show up here.
EXPECT_TRUE(
NavigateToURL(shell(), embedded_test_server()->GetURL("/title2.html")));
main_frame = web_contents()->GetPrimaryMainFrame();
BackForwardCacheBlockingDetails empty_vector;
main_frame->DidChangeBackForwardCacheDisablingFeatures(
CreateBlockingDetails({}));
}
class RenderFrameHostImplNoStrictSiteIsolationOnAndroidBrowserTest
: public RenderFrameHostImplBrowserTest {
public:
RenderFrameHostImplNoStrictSiteIsolationOnAndroidBrowserTest() = default;
~RenderFrameHostImplNoStrictSiteIsolationOnAndroidBrowserTest() override =
default;
void SetUpCommandLine(base::CommandLine* command_line) override {
RenderFrameHostImplBrowserTest::SetUpCommandLine(command_line);
#if BUILDFLAG(IS_ANDROID)
// On Android, --site-per-process may be passed on some bots to force strict
// site isolation. That causes this test too create a lot of processes and
// time out due to running too slowly, so force this test to run without
// strict site isolation on Android. This is ok since this test doesn't
// actually care about process isolation.
command_line->RemoveSwitch(switches::kSitePerProcess);
#endif
}
};
IN_PROC_BROWSER_TEST_F(RenderFrameHostImplBrowserTest,
ComputeIsolationInfoForNavigationSiteForCookies) {
// Start second server for HTTPS.
https_server()->ServeFilesFromSourceDirectory(GetTestDataFilePath());
ASSERT_TRUE(https_server()->Start());
GURL url = embedded_test_server()->GetURL(
"a.com", "/cross_site_iframe_factory.html?a(a(b(d)),c())");
FirstPartySchemeContentBrowserClient new_client(url);
GURL b_url = embedded_test_server()->GetURL("b.com", "/");
GURL c_url = embedded_test_server()->GetURL("c.com", "/");
GURL secure_url = https_server()->GetURL("/");
EXPECT_TRUE(NavigateToURL(shell(), url));
{
RenderFrameHostImpl* main_frame = web_contents()->GetPrimaryMainFrame();
EXPECT_EQ("a.com", main_frame->GetLastCommittedURL().host());
ASSERT_EQ(2u, main_frame->child_count());
FrameTreeNode* child_a = main_frame->child_at(0);
FrameTreeNode* child_c = main_frame->child_at(1);
EXPECT_EQ("a.com", child_a->current_url().host());
EXPECT_EQ("c.com", child_c->current_url().host());
ASSERT_EQ(1u, child_a->child_count());
FrameTreeNode* child_b = child_a->child_at(0);
EXPECT_EQ("b.com", child_b->current_url().host());
ASSERT_EQ(1u, child_b->child_count());
FrameTreeNode* child_d = child_b->child_at(0);
EXPECT_EQ("d.com", child_d->current_url().host());
EXPECT_EQ("a.com", main_frame->ComputeIsolationInfoForNavigation(url)
.site_for_cookies()
.registrable_domain());
EXPECT_EQ("b.com", main_frame->ComputeIsolationInfoForNavigation(b_url)
.site_for_cookies()
.registrable_domain());
EXPECT_EQ("c.com", main_frame->ComputeIsolationInfoForNavigation(c_url)
.site_for_cookies()
.registrable_domain());
// a.com -> a.com frame being navigated.
EXPECT_EQ("a.com", child_a->current_frame_host()
->ComputeIsolationInfoForNavigation(url)
.site_for_cookies()
.registrable_domain());
EXPECT_EQ("a.com", child_a->current_frame_host()
->ComputeIsolationInfoForNavigation(b_url)
.site_for_cookies()
.registrable_domain());
EXPECT_EQ("a.com", child_a->current_frame_host()
->ComputeIsolationInfoForNavigation(c_url)
.site_for_cookies()
.registrable_domain());
// a.com -> a.com -> b.com frame being navigated.
// The first case here is especially interesting, since we go to
// a/a/a from a/a/b. We currently treat this as all first-party, but there
// is a case to be made for doing it differently, due to involvement of b.
EXPECT_EQ("a.com", child_b->current_frame_host()
->ComputeIsolationInfoForNavigation(url)
.site_for_cookies()
.registrable_domain());
EXPECT_EQ("a.com", child_b->current_frame_host()
->ComputeIsolationInfoForNavigation(b_url)
.site_for_cookies()
.registrable_domain());
EXPECT_EQ("a.com", child_b->current_frame_host()
->ComputeIsolationInfoForNavigation(c_url)
.site_for_cookies()
.registrable_domain());
// a.com -> c.com frame being navigated.
EXPECT_EQ("a.com", child_c->current_frame_host()
->ComputeIsolationInfoForNavigation(url)
.site_for_cookies()
.registrable_domain());
EXPECT_EQ("a.com", child_c->current_frame_host()
->ComputeIsolationInfoForNavigation(b_url)
.site_for_cookies()
.registrable_domain());
EXPECT_EQ("a.com", child_c->current_frame_host()
->ComputeIsolationInfoForNavigation(c_url)
.site_for_cookies()
.registrable_domain());
// a.com -> a.com -> b.com -> d.com frame being navigated.
EXPECT_EQ("", child_d->current_frame_host()
->ComputeIsolationInfoForNavigation(url)
.site_for_cookies()
.registrable_domain());
EXPECT_EQ("", child_d->current_frame_host()
->ComputeIsolationInfoForNavigation(b_url)
.site_for_cookies()
.registrable_domain());
EXPECT_EQ("", child_d->current_frame_host()
->ComputeIsolationInfoForNavigation(c_url)
.site_for_cookies()
.registrable_domain());
}
// Now try with a trusted scheme that gives first-partiness.
GURL trusty_url(kTrustMeUrl);
EXPECT_TRUE(NavigateToURL(shell(), trusty_url));
{
RenderFrameHostImpl* main_frame = web_contents()->GetPrimaryMainFrame();
EXPECT_EQ(trusty_url.DeprecatedGetOriginAsURL(),
main_frame->GetLastCommittedURL().DeprecatedGetOriginAsURL());
ASSERT_EQ(1u, main_frame->child_count());
FrameTreeNode* child_a = main_frame->child_at(0);
EXPECT_EQ("a.com", child_a->current_url().host());
ASSERT_EQ(2u, child_a->child_count());
FrameTreeNode* child_aa = child_a->child_at(0);
EXPECT_EQ("a.com", child_aa->current_url().host());
ASSERT_EQ(1u, child_aa->child_count());
FrameTreeNode* child_aab = child_aa->child_at(0);
EXPECT_EQ("b.com", child_aab->current_url().host());
ASSERT_EQ(1u, child_aab->child_count());
FrameTreeNode* child_aabd = child_aab->child_at(0);
EXPECT_EQ("d.com", child_aabd->current_url().host());
// Main frame navigations are not affected by the special schema.
EXPECT_TRUE(net::SiteForCookies::FromUrl(url).IsEquivalent(
main_frame->ComputeIsolationInfoForNavigation(url).site_for_cookies()));
EXPECT_TRUE(net::SiteForCookies::FromUrl(b_url).IsEquivalent(
main_frame->ComputeIsolationInfoForNavigation(b_url)
.site_for_cookies()));
EXPECT_TRUE(net::SiteForCookies::FromUrl(c_url).IsEquivalent(
main_frame->ComputeIsolationInfoForNavigation(c_url)
.site_for_cookies()));
// Child navigation gets the magic scheme.
EXPECT_TRUE(net::SiteForCookies::FromUrl(trusty_url)
.IsEquivalent(child_aa->current_frame_host()
->ComputeIsolationInfoForNavigation(url)
.site_for_cookies()));
EXPECT_TRUE(net::SiteForCookies::FromUrl(trusty_url)
.IsEquivalent(child_aa->current_frame_host()
->ComputeIsolationInfoForNavigation(b_url)
.site_for_cookies()));
EXPECT_TRUE(net::SiteForCookies::FromUrl(trusty_url)
.IsEquivalent(child_aa->current_frame_host()
->ComputeIsolationInfoForNavigation(c_url)
.site_for_cookies()));
EXPECT_TRUE(net::SiteForCookies::FromUrl(trusty_url)
.IsEquivalent(child_aabd->current_frame_host()
->ComputeIsolationInfoForNavigation(url)
.site_for_cookies()));
EXPECT_TRUE(net::SiteForCookies::FromUrl(trusty_url)
.IsEquivalent(child_aabd->current_frame_host()
->ComputeIsolationInfoForNavigation(b_url)
.site_for_cookies()));
EXPECT_TRUE(net::SiteForCookies::FromUrl(trusty_url)
.IsEquivalent(child_aabd->current_frame_host()
->ComputeIsolationInfoForNavigation(c_url)
.site_for_cookies()));
}
// Test trusted scheme that gives first-partiness if the url is secure.
GURL trusty_if_secure_url(kTrustMeIfEmbeddingSecureUrl);
EXPECT_TRUE(NavigateToURL(shell(), trusty_if_secure_url));
{
RenderFrameHostImpl* main_frame = web_contents()->GetPrimaryMainFrame();
EXPECT_EQ(trusty_if_secure_url.DeprecatedGetOriginAsURL(),
main_frame->GetLastCommittedURL().DeprecatedGetOriginAsURL());
ASSERT_EQ(1u, main_frame->child_count());
FrameTreeNode* child_a = main_frame->child_at(0);
EXPECT_EQ("a.com", child_a->current_url().host());
ASSERT_EQ(2u, child_a->child_count());
FrameTreeNode* child_aa = child_a->child_at(0);
EXPECT_EQ("a.com", child_aa->current_url().host());
ASSERT_EQ(1u, child_aa->child_count());
FrameTreeNode* child_aab = child_aa->child_at(0);
EXPECT_EQ("b.com", child_aab->current_url().host());
ASSERT_EQ(1u, child_aab->child_count());
FrameTreeNode* child_aabd = child_aab->child_at(0);
EXPECT_EQ("d.com", child_aabd->current_url().host());
// Main frame navigations are not affected by the special schema.
EXPECT_TRUE(net::SiteForCookies::FromUrl(url).IsEquivalent(
main_frame->ComputeIsolationInfoForNavigation(url).site_for_cookies()));
EXPECT_TRUE(net::SiteForCookies::FromUrl(b_url).IsEquivalent(
main_frame->ComputeIsolationInfoForNavigation(b_url)
.site_for_cookies()));
EXPECT_TRUE(
net::SiteForCookies::FromUrl(secure_url)
.IsEquivalent(
main_frame->ComputeIsolationInfoForNavigation(secure_url)
.site_for_cookies()));
// Child navigation gets the magic scheme iff secure.
EXPECT_TRUE(child_aa->current_frame_host()
->ComputeIsolationInfoForNavigation(url)
.site_for_cookies()
.IsNull());
EXPECT_TRUE(child_aa->current_frame_host()
->ComputeIsolationInfoForNavigation(b_url)
.site_for_cookies()
.IsNull());
EXPECT_TRUE(
net::SiteForCookies::FromUrl(trusty_url)
.IsEquivalent(child_aa->current_frame_host()
->ComputeIsolationInfoForNavigation(secure_url)
.site_for_cookies()));
EXPECT_TRUE(child_aabd->current_frame_host()
->ComputeIsolationInfoForNavigation(url)
.site_for_cookies()
.IsNull());
EXPECT_TRUE(child_aabd->current_frame_host()
->ComputeIsolationInfoForNavigation(b_url)
.site_for_cookies()
.IsNull());
EXPECT_TRUE(
net::SiteForCookies::FromUrl(trusty_url)
.IsEquivalent(child_aabd->current_frame_host()
->ComputeIsolationInfoForNavigation(secure_url)
.site_for_cookies()));
}
}
// Verifies that when a document navigates a cross-origin grandchild frame to
// a new origin, the corresponding FrameNavigationEntry initiator origin equals
// the document origin.
IN_PROC_BROWSER_TEST_F(
RenderFrameHostImplBrowserTest,
InitiatorOriginForCrossDocumentNavigationInCrossOriginGrandchild) {
GURL a_url = embedded_test_server()->GetURL(
"a.com", "/cross_site_iframe_factory.html?a(b(c))");
EXPECT_TRUE(NavigateToURL(shell(), a_url));
RenderFrameHostImpl* rfh_a = web_contents()->GetPrimaryMainFrame();
RenderFrameHostImpl* rfh_b = rfh_a->child_at(0)->current_frame_host();
RenderFrameHostImpl* rfh_c = rfh_b->child_at(0)->current_frame_host();
// The initiator origin should begin as b.com since it created the iframe.
EXPECT_EQ(embedded_test_server()->GetOrigin("b.com"),
GetInitiatorOrigin(rfh_c));
// Navigate to d.com/title1.html from the outer document.
GURL d_url = embedded_test_server()->GetURL("d.com", "/title1.html");
NavigateToURLFromGrandparentDocument(shell(), d_url);
RenderFrameHostImpl* rfh_d = rfh_b->child_at(0)->current_frame_host();
// A navigation initiated by the outer document should update the initiator to
// the origin of that document.
EXPECT_EQ(url::Origin::Create(a_url), GetInitiatorOrigin(rfh_d));
}
class RenderFrameHostImplSiteIsolationBrowserTest
: public RenderFrameHostImplBrowserTest,
public testing::WithParamInterface<bool> {
void SetUpCommandLine(base::CommandLine* command_line) override {
if (disable_site_isolation_) {
command_line->AppendSwitch(switches::kDisableSiteIsolation);
} else {
command_line->AppendSwitch(switches::kSitePerProcess);
}
RenderFrameHostImplBrowserTest::SetUpCommandLine(command_line);
}
private:
bool disable_site_isolation_ = GetParam();
};
INSTANTIATE_TEST_SUITE_P(All,
RenderFrameHostImplSiteIsolationBrowserTest,
testing::Bool(),
[](const testing::TestParamInfo<bool>& info) {
return info.param ? "SiteIsolationDisabled"
: "SiteIsolationEnabled";
});
// Verifies that when a document navigates a cross-origin grandchild frame to
// a fragment URL (i.e. a same-document navigation), the corresponding
// FrameNavigationEntry initiator origin equals the document origin.
IN_PROC_BROWSER_TEST_P(
RenderFrameHostImplSiteIsolationBrowserTest,
InitiatorOriginForSameDocumentNavigationInCrossOriginGrandchild) {
GURL a_url = embedded_test_server()->GetURL(
"a.com", "/cross_site_iframe_factory.html?a(b(c))");
EXPECT_TRUE(NavigateToURL(shell(), a_url));
RenderFrameHostImpl* rfh_a = web_contents()->GetPrimaryMainFrame();
RenderFrameHostImpl* rfh_b = rfh_a->child_at(0)->current_frame_host();
RenderFrameHostImpl* rfh_c = rfh_b->child_at(0)->current_frame_host();
// The initiator origin should begin as b.com since it created the iframe.
EXPECT_EQ(embedded_test_server()->GetOrigin("b.com"),
GetInitiatorOrigin(rfh_c));
// Do a same-document navigation from the outer document.
GURL c_url_with_fragment =
GURL(base::StrCat({rfh_c->GetLastCommittedURL().spec(), "#x"}));
NavigateToURLFromGrandparentDocument(shell(), c_url_with_fragment);
// A navigation initiated by the outer document should update the initiator to
// the origin of that document.
if (AreAllSitesIsolatedForTesting()) {
EXPECT_EQ(url::Origin::Create(a_url), GetInitiatorOrigin(rfh_c));
} else {
// TODO(crbug.com/367440964): The origin of the same-document navigation is
// currently used in place of the actual initiator_origin:
// https://source.chromium.org/chromium/chromium/src/+/main:content/browser/renderer_host/navigation_request.cc;l=1495-1497;drc=e66b343b5554785a32ad988bfe5c3c524f5e1857
EXPECT_EQ(url::Origin::Create(c_url_with_fragment),
GetInitiatorOrigin(rfh_c));
}
}
// Verifies that when a document navigates a same-origin grandchild frame to
// a new origin, the corresponding FrameNavigationEntry initiator origin equals
// the document origin.
IN_PROC_BROWSER_TEST_F(
RenderFrameHostImplBrowserTest,
InitiatorOriginForCrossDocumentNavigationInSameOriginGrandchild) {
GURL a_url = embedded_test_server()->GetURL(
"a.com", "/cross_site_iframe_factory.html?a(b(a))");
EXPECT_TRUE(NavigateToURL(shell(), a_url));
RenderFrameHostImpl* rfh_a = web_contents()->GetPrimaryMainFrame();
RenderFrameHostImpl* rfh_b = rfh_a->child_at(0)->current_frame_host();
RenderFrameHostImpl* rfh_a2 = rfh_b->child_at(0)->current_frame_host();
// The initiator origin should begin as b.com since it created the iframe.
EXPECT_EQ(embedded_test_server()->GetOrigin("b.com"),
GetInitiatorOrigin(rfh_a2));
// Navigate to d.com/title1.html from the outer document.
GURL d_url = embedded_test_server()->GetURL("d.com", "/title1.html");
NavigateToURLFromGrandparentDocument(shell(), d_url);
RenderFrameHostImpl* rfh_d = rfh_b->child_at(0)->current_frame_host();
// A navigation initiated by the outer document should update the initiator to
// the origin of that document.
EXPECT_EQ(embedded_test_server()->GetOrigin("a.com"),
GetInitiatorOrigin(rfh_d));
}
// Verifies that when a document navigates a same-origin grandchild frame to a
// fragment URL (i.e. a same-document navigation), the corresponding
// FrameNavigationEntry initiator origin equals the document origin.
IN_PROC_BROWSER_TEST_F(
RenderFrameHostImplBrowserTest,
InitiatorOriginForSameDocumentNavigationInSameOriginGrandchild) {
GURL a_url = embedded_test_server()->GetURL(
"a.com", "/cross_site_iframe_factory.html?a(b(a))");
EXPECT_TRUE(NavigateToURL(shell(), a_url));
RenderFrameHostImpl* rfh_a = web_contents()->GetPrimaryMainFrame();
RenderFrameHostImpl* rfh_b = rfh_a->child_at(0)->current_frame_host();
RenderFrameHostImpl* rfh_a2 = rfh_b->child_at(0)->current_frame_host();
// The initiator origin should begin as b.com since it created the iframe.
EXPECT_EQ(embedded_test_server()->GetOrigin("b.com"),
GetInitiatorOrigin(rfh_a2));
// Do a same-document navigation from the outer document.
GURL a_url_with_fragment =
GURL(base::StrCat({rfh_a2->GetLastCommittedURL().spec(), "#x"}));
NavigateToURLFromGrandparentDocument(shell(), a_url_with_fragment);
// A navigation initiated by the outer document should update the initiator to
// the origin of that document.
EXPECT_EQ(embedded_test_server()->GetOrigin("a.com"),
GetInitiatorOrigin(rfh_a2));
}
// Test that when ancestor iframes differ in scheme that the SiteForCookies
// state is updated accordingly.
IN_PROC_BROWSER_TEST_F(RenderFrameHostImplBrowserTest,
ComputeSiteForCookiesSchemefulIsSameForAncestorFrames) {
https_server()->ServeFilesFromSourceDirectory(GetTestDataFilePath());
https_server()->SetSSLConfig(net::EmbeddedTestServer::CERT_TEST_NAMES);
ASSERT_TRUE(https_server()->Start());
GURL url = https_server()->GetURL(
"a.test", "/cross_site_iframe_factory.html?a.test(a.test)");
GURL insecure_url = embedded_test_server()->GetURL(
"a.test", "/cross_site_iframe_factory.html?a.test(a.test(a.test))");
GURL other_url = https_server()->GetURL("c.test", "/");
EXPECT_TRUE(NavigateToURL(shell(), insecure_url));
{
RenderFrameHostImpl* main_frame = web_contents()->GetPrimaryMainFrame();
EXPECT_EQ("a.test", main_frame->GetLastCommittedURL().host());
EXPECT_EQ("http", main_frame->frame_tree_node()->current_origin().scheme());
ASSERT_EQ(1u, main_frame->child_count());
FrameTreeNode* child = main_frame->child_at(0);
EXPECT_EQ("a.test", child->current_url().host());
EXPECT_EQ("http", child->current_origin().scheme());
ASSERT_EQ(1u, child->child_count());
FrameTreeNode* grandchild = child->child_at(0);
EXPECT_EQ("a.test", grandchild->current_url().host());
// Both the frames above grandchild are the same scheme, so
// SiteForCookies::schemefully_same() should indicate that.
EXPECT_TRUE(child->current_frame_host()
->ComputeIsolationInfoForNavigation(other_url)
.site_for_cookies()
.schemefully_same());
EXPECT_EQ("a.test", child->current_frame_host()
->ComputeIsolationInfoForNavigation(other_url)
.site_for_cookies()
.registrable_domain());
net::SiteForCookies grandchild_same_scheme =
grandchild->current_frame_host()->ComputeSiteForCookies();
EXPECT_TRUE(grandchild_same_scheme.schemefully_same());
EXPECT_EQ("a.test", grandchild_same_scheme.registrable_domain());
net::SiteForCookies grandchild_same_scheme_navigation =
grandchild->current_frame_host()
->ComputeIsolationInfoForNavigation(other_url)
.site_for_cookies();
EXPECT_TRUE(grandchild_same_scheme_navigation.schemefully_same());
EXPECT_EQ("a.test", grandchild_same_scheme_navigation.registrable_domain());
// Navigate the middle child frame to https.
EXPECT_TRUE(NavigateToURLFromRenderer(child, url));
EXPECT_EQ("a.test", child->current_url().host());
EXPECT_EQ("https", child->current_origin().scheme());
EXPECT_EQ(1u, child->child_count());
grandchild = child->child_at(0);
// Now the frames above grandchild differ only in scheme. This results in
// null SiteForCookies because of the schemefully_same flag, but site should
// still not be opaque.
net::SiteForCookies grandchild_cross_scheme =
grandchild->current_frame_host()->ComputeSiteForCookies();
EXPECT_TRUE(grandchild_cross_scheme.IsNull());
EXPECT_FALSE(grandchild_cross_scheme.site().opaque());
net::SiteForCookies grandchild_cross_scheme_navigation =
grandchild->current_frame_host()
->ComputeIsolationInfoForNavigation(other_url)
.site_for_cookies();
EXPECT_TRUE(grandchild_cross_scheme_navigation.IsNull());
EXPECT_FALSE(grandchild_cross_scheme_navigation.site().opaque());
}
}
IN_PROC_BROWSER_TEST_F(RenderFrameHostImplBrowserTest,
ComputeIsolationInfoForNavigationSiteForCookiesSandbox) {
// Test sandboxed subframe.
{
GURL url = embedded_test_server()->GetURL(
"a.com",
"/cross_site_iframe_factory.html?a(a{sandbox-allow-scripts}(a),"
"a{sandbox-allow-scripts,sandbox-allow-same-origin}(a))");
EXPECT_TRUE(NavigateToURL(shell(), url));
RenderFrameHostImpl* main_frame = web_contents()->GetPrimaryMainFrame();
EXPECT_EQ("a.com", main_frame->GetLastCommittedURL().host());
ASSERT_EQ(2u, main_frame->child_count());
FrameTreeNode* child_a = main_frame->child_at(0);
EXPECT_EQ("a.com", child_a->current_url().host());
EXPECT_TRUE(
child_a->current_frame_host()->GetLastCommittedOrigin().opaque());
ASSERT_EQ(1u, child_a->child_count());
FrameTreeNode* child_aa = child_a->child_at(0);
EXPECT_EQ("a.com", child_aa->current_url().host());
EXPECT_TRUE(
child_aa->current_frame_host()->GetLastCommittedOrigin().opaque());
FrameTreeNode* child_a2 = main_frame->child_at(1);
EXPECT_EQ("a.com", child_a2->current_url().host());
EXPECT_FALSE(
child_a2->current_frame_host()->GetLastCommittedOrigin().opaque());
ASSERT_EQ(1u, child_a2->child_count());
FrameTreeNode* child_a2a = child_a2->child_at(0);
EXPECT_EQ("a.com", child_a2a->current_url().host());
EXPECT_FALSE(
child_a2a->current_frame_host()->GetLastCommittedOrigin().opaque());
// |child_aa| frame navigation should be cross-site since its parent is
// sandboxed without allow-same-origin
EXPECT_TRUE(child_aa->current_frame_host()
->ComputeIsolationInfoForNavigation(url)
.site_for_cookies()
.IsNull());
// |child_a2a| frame navigation should be same-site since its sandboxed
// parent is sandbox-same-origin.
EXPECT_EQ("a.com", child_a2a->current_frame_host()
->ComputeIsolationInfoForNavigation(url)
.site_for_cookies()
.registrable_domain());
}
// Test sandboxed main frame.
{
GURL url =
embedded_test_server()->GetURL("a.com", "/csp_sandboxed_frame.html");
EXPECT_TRUE(NavigateToURL(shell(), url));
RenderFrameHostImpl* main_frame = web_contents()->GetPrimaryMainFrame();
EXPECT_EQ(url, main_frame->GetLastCommittedURL());
EXPECT_TRUE(main_frame->GetLastCommittedOrigin().opaque());
ASSERT_EQ(2u, main_frame->child_count());
FrameTreeNode* child_a = main_frame->child_at(0);
EXPECT_EQ("a.com", child_a->current_url().host());
EXPECT_TRUE(
child_a->current_frame_host()->GetLastCommittedOrigin().opaque());
EXPECT_TRUE(child_a->current_frame_host()
->ComputeIsolationInfoForNavigation(url)
.site_for_cookies()
.IsNull());
}
}
IN_PROC_BROWSER_TEST_F(
RenderFrameHostImplBrowserTest,
ComputeIsolationInfoForNavigationSiteForCookiesAboutBlank) {
GURL url = embedded_test_server()->GetURL(
"a.com", "/page_with_blank_iframe_tree.html");
EXPECT_TRUE(NavigateToURL(shell(), url));
RenderFrameHostImpl* main_frame = web_contents()->GetPrimaryMainFrame();
EXPECT_EQ("a.com", main_frame->GetLastCommittedURL().host());
ASSERT_EQ(1u, main_frame->child_count());
FrameTreeNode* child_a = main_frame->child_at(0);
EXPECT_TRUE(child_a->current_url().IsAboutBlank());
EXPECT_EQ("a.com",
child_a->current_frame_host()->GetLastCommittedOrigin().host());
ASSERT_EQ(1u, child_a->child_count());
FrameTreeNode* child_aa = child_a->child_at(0);
EXPECT_TRUE(child_aa->current_url().IsAboutBlank());
EXPECT_EQ("a.com",
child_aa->current_frame_host()->GetLastCommittedOrigin().host());
// navigating the nested about:blank iframe to a.com is fine, since the origin
// is inherited.
EXPECT_EQ("a.com", child_aa->current_frame_host()
->ComputeIsolationInfoForNavigation(url)
.site_for_cookies()
.registrable_domain());
}
IN_PROC_BROWSER_TEST_F(RenderFrameHostImplBrowserTest,
ComputeIsolationInfoForNavigationSiteForCookiesSrcDoc) {
// srcdoc frames basically don't figure into site_for_cookies computation.
GURL url = embedded_test_server()->GetURL(
"a.com", "/frame_tree/page_with_srcdoc_iframe_tree.html");
EXPECT_TRUE(NavigateToURL(shell(), url));
RenderFrameHostImpl* main_frame = web_contents()->GetPrimaryMainFrame();
EXPECT_EQ("a.com", main_frame->GetLastCommittedURL().host());
ASSERT_EQ(1u, main_frame->child_count());
FrameTreeNode* child_sd = main_frame->child_at(0);
EXPECT_TRUE(child_sd->current_url().IsAboutSrcdoc());
ASSERT_EQ(1u, child_sd->child_count());
FrameTreeNode* child_sd_a = child_sd->child_at(0);
EXPECT_EQ("a.com", child_sd_a->current_url().host());
ASSERT_EQ(1u, child_sd_a->child_count());
FrameTreeNode* child_sd_a_sd = child_sd_a->child_at(0);
EXPECT_TRUE(child_sd_a_sd->current_url().IsAboutSrcdoc());
ASSERT_EQ(0u, child_sd_a_sd->child_count());
EXPECT_EQ("a.com", child_sd->current_frame_host()
->ComputeIsolationInfoForNavigation(url)
.site_for_cookies()
.registrable_domain());
EXPECT_EQ("a.com", child_sd_a->current_frame_host()
->ComputeIsolationInfoForNavigation(url)
.site_for_cookies()
.registrable_domain());
EXPECT_EQ("a.com", child_sd_a_sd->current_frame_host()
->ComputeIsolationInfoForNavigation(url)
.site_for_cookies()
.registrable_domain());
GURL b_url = embedded_test_server()->GetURL("b.com", "/");
EXPECT_EQ("b.com", main_frame->ComputeIsolationInfoForNavigation(b_url)
.site_for_cookies()
.registrable_domain());
EXPECT_EQ("a.com", child_sd->current_frame_host()
->ComputeIsolationInfoForNavigation(b_url)
.site_for_cookies()
.registrable_domain());
EXPECT_EQ("a.com", child_sd_a->current_frame_host()
->ComputeIsolationInfoForNavigation(b_url)
.site_for_cookies()
.registrable_domain());
EXPECT_EQ("a.com", child_sd_a_sd->current_frame_host()
->ComputeIsolationInfoForNavigation(b_url)
.site_for_cookies()
.registrable_domain());
}
IN_PROC_BROWSER_TEST_F(RenderFrameHostImplBrowserTest,
ComputeSiteForCookiesFileURL) {
GURL main_frame_url = GetFileURL(FILE_PATH_LITERAL("page_with_iframe.html"));
GURL subframe_url = GetFileURL(FILE_PATH_LITERAL("title1.html"));
EXPECT_TRUE(NavigateToURL(shell(), main_frame_url));
RenderFrameHostImpl* main_frame = web_contents()->GetPrimaryMainFrame();
EXPECT_EQ(main_frame_url, main_frame->GetLastCommittedURL());
EXPECT_TRUE(net::SiteForCookies::FromUrl(GURL("file:///"))
.IsEquivalent(main_frame->ComputeSiteForCookies()));
ASSERT_EQ(1u, main_frame->child_count());
RenderFrameHostImpl* child = main_frame->child_at(0)->current_frame_host();
EXPECT_EQ(subframe_url, child->GetLastCommittedURL());
EXPECT_TRUE(net::SiteForCookies::FromUrl(GURL("file:///"))
.IsEquivalent(child->ComputeSiteForCookies()));
}
IN_PROC_BROWSER_TEST_F(RenderFrameHostImplBrowserTest,
ComputeSiteForCookiesParentNavigatedAway) {
// Navigate to site with same-domain frame, save a RenderFrameHostImpl to
// the child.
GURL url = embedded_test_server()->GetURL(
"a.com", "/cross_site_iframe_factory.html?a(a)");
EXPECT_TRUE(NavigateToURL(shell(), url));
RenderFrameHostImpl* main_frame = web_contents()->GetPrimaryMainFrame();
EXPECT_EQ("a.com", main_frame->GetLastCommittedURL().host());
ASSERT_EQ(1u, main_frame->child_count());
FrameTreeNode* child_a = main_frame->child_at(0);
RenderFrameHostImpl* child_rfh = child_a->current_frame_host();
EXPECT_EQ("a.com", child_rfh->GetLastCommittedOrigin().host());
GURL kid_url = child_rfh->GetLastCommittedURL();
// Disable the unload ACK and the unload timer. Also pretend the child frame
// has an unload handler, so it doesn't get cleaned up synchronously, and
// block its detach handler.
auto unload_ack_filter = base::BindRepeating([] { return true; });
main_frame->SetUnloadACKCallbackForTesting(unload_ack_filter);
main_frame->DisableUnloadTimerForTesting();
child_rfh->SuddenTerminationDisablerChanged(
true, blink::mojom::SuddenTerminationDisablerType::kUnloadHandler);
child_rfh->SetSubframeUnloadTimeoutForTesting(base::Days(7));
child_rfh->DoNotDeleteForTesting();
// Open a popup on a.com to keep the process alive.
OpenPopup(shell(), embedded_test_server()->GetURL("a.com", "/title2.html"),
"foo");
// Navigate root to b.com.
EXPECT_TRUE(NavigateToURL(
shell(), embedded_test_server()->GetURL("b.com", "/title3.html")));
// The old RFH should be pending deletion, but its site_for_cookies should
// be unchanged.
EXPECT_TRUE(child_rfh->IsPendingDeletion());
EXPECT_EQ(kid_url, child_rfh->GetLastCommittedURL());
EXPECT_EQ(url, main_frame->GetLastCommittedURL());
EXPECT_TRUE(main_frame->IsPendingDeletion());
EXPECT_FALSE(main_frame->IsActive());
net::SiteForCookies computed_for_child = child_rfh->ComputeSiteForCookies();
EXPECT_TRUE(
net::SiteForCookies::FromUrl(url).IsEquivalent(computed_for_child))
<< computed_for_child.ToDebugString();
}
// Make sure a local file and its subresources can be reloaded after a crash. In
// particular, after https://crbug.com/981339, a different RenderFrameHost will
// be used for reloading the file. File access must be correctly granted.
IN_PROC_BROWSER_TEST_F(RenderFrameHostImplBrowserTest, FileReloadAfterCrash) {
// 1. Navigate a local file with an iframe.
GURL main_frame_url = GetFileURL(FILE_PATH_LITERAL("page_with_iframe.html"));
GURL subframe_url = GetFileURL(FILE_PATH_LITERAL("title1.html"));
EXPECT_TRUE(NavigateToURL(shell(), main_frame_url));
// 2. Crash.
RenderProcessHost* process =
web_contents()->GetPrimaryMainFrame()->GetProcess();
RenderProcessHostWatcher crash_observer(
process, RenderProcessHostWatcher::WATCH_FOR_PROCESS_EXIT);
process->Shutdown(0);
crash_observer.Wait();
// 3. Reload.
web_contents()->GetController().Reload(ReloadType::NORMAL, false);
EXPECT_TRUE(WaitForLoadStop(web_contents()));
// Check the document is correctly reloaded.
RenderFrameHostImpl* main_document = web_contents()->GetPrimaryMainFrame();
ASSERT_EQ(1u, main_document->child_count());
RenderFrameHostImpl* sub_document =
main_document->child_at(0)->current_frame_host();
EXPECT_EQ(main_frame_url, main_document->GetLastCommittedURL());
EXPECT_EQ(subframe_url, sub_document->GetLastCommittedURL());
EXPECT_THAT(
EvalJs(main_document, "document.body.textContent").ExtractString(),
::testing::HasSubstr("This page has an iframe. Yay for iframes!"));
EXPECT_EQ("This page has no title.\n\n",
EvalJs(sub_document, "document.body.textContent"));
}
// Make sure a webui can be reloaded after a crash.
IN_PROC_BROWSER_TEST_F(RenderFrameHostImplBrowserTest, WebUiReloadAfterCrash) {
// 1. Navigate a local file with an iframe.
GURL main_frame_url(std::string(kChromeUIScheme) + "://" +
std::string(kChromeUIGpuHost));
EXPECT_TRUE(NavigateToURL(shell(), main_frame_url));
// 2. Crash.
RenderProcessHost* process =
web_contents()->GetPrimaryMainFrame()->GetProcess();
RenderProcessHostWatcher crash_observer(
process, RenderProcessHostWatcher::WATCH_FOR_PROCESS_EXIT);
process->Shutdown(0);
crash_observer.Wait();
// 3. Reload.
web_contents()->GetController().Reload(ReloadType::NORMAL, false);
EXPECT_TRUE(WaitForLoadStop(web_contents()));
// Check the document is correctly reloaded.
RenderFrameHostImpl* main_document = web_contents()->GetPrimaryMainFrame();
EXPECT_EQ(main_frame_url, main_document->GetLastCommittedURL());
// Execute script in an isolated world to avoid causing a Trusted Types
// violation due to eval.
EXPECT_THAT(EvalJs(main_document,
"document.querySelector('info-view').shadowRoot"
".querySelector('#used-only-by-test').text",
EXECUTE_SCRIPT_DEFAULT_OPTIONS, /*world_id=*/1)
.ExtractString(),
testing::StartsWith("GPU Info"));
}
// Start with A(B), navigate A to C. By emulating a slow unload handler B, check
// the status of IsActive for subframes of A i.e., B before and after
// navigating to C.
// Test is flaky: https://crbug.com/1114149.
IN_PROC_BROWSER_TEST_F(RenderFrameHostImplBrowserTest,
DISABLED_CheckIsActiveBeforeAndAfterUnload) {
IsolateAllSitesForTesting(base::CommandLine::ForCurrentProcess());
GURL url_ab(embedded_test_server()->GetURL(
"a.com", "/cross_site_iframe_factory.html?a(b)"));
GURL url_c(embedded_test_server()->GetURL("c.com", "/title1.html"));
// 1) Navigate to a page with an iframe.
EXPECT_TRUE(NavigateToURL(shell(), url_ab));
RenderFrameHostImpl* rfh_a = web_contents()->GetPrimaryMainFrame();
RenderFrameHostImpl* rfh_b = rfh_a->child_at(0)->current_frame_host();
RenderFrameDeletedObserver delete_rfh_b(rfh_b);
EXPECT_EQ(LifecycleStateImpl::kActive, rfh_b->lifecycle_state());
// 2) Leave rfh_b in pending deletion state.
LeaveInPendingDeletionState(rfh_b);
// 3) Check the IsActive state of rfh_a, rfh_b before navigating to C.
EXPECT_TRUE(rfh_a->IsActive());
EXPECT_TRUE(rfh_b->IsActive());
// 4) Navigate rfh_a to C.
EXPECT_TRUE(NavigateToURL(shell(), url_c));
RenderFrameHostImpl* rfh_c = web_contents()->GetPrimaryMainFrame();
EXPECT_THAT(
rfh_a->lifecycle_state(),
testing::AnyOf(testing::Eq(LifecycleStateImpl::kReadyToBeDeleted),
testing::Eq(LifecycleStateImpl::kInBackForwardCache)));
EXPECT_THAT(
rfh_b->lifecycle_state(),
testing::AnyOf(testing::Eq(LifecycleStateImpl::kRunningUnloadHandlers),
testing::Eq(LifecycleStateImpl::kInBackForwardCache)));
// 5) Check the IsActive state of rfh_a, rfh_b and rfh_c after navigating to
// C.
EXPECT_FALSE(rfh_a->IsActive());
EXPECT_FALSE(rfh_b->IsActive());
EXPECT_TRUE(rfh_c->IsActive());
}
// Test the LifecycleStateImpl is updated correctly for the main frame during
// navigation.
IN_PROC_BROWSER_TEST_F(RenderFrameHostImplBrowserTest,
CheckLifecycleStateTransitionOnMainFrame) {
GURL url_a(embedded_test_server()->GetURL("a.com", "/title1.html"));
GURL url_b(embedded_test_server()->GetURL("b.com", "/title2.html"));
IsolateAllSitesForTesting(base::CommandLine::ForCurrentProcess());
// 1) Navigate to A.
EXPECT_TRUE(NavigateToURL(shell(), url_a));
RenderFrameHostImpl* rfh_a = root_frame_host();
EXPECT_EQ(LifecycleStateImpl::kActive, rfh_a->lifecycle_state());
// 2) Leave rfh_a in pending deletion state to check for rfh_a
// LifecycleStateImpl after navigating to B.
LeaveInPendingDeletionState(rfh_a);
// 3) Start navigation to B, but don't commit yet.
TestNavigationManager manager(web_contents(), url_b);
shell()->LoadURL(url_b);
manager.WaitForSpeculativeRenderFrameHostCreation();
FrameTreeNode* root = web_contents()->GetPrimaryFrameTree().root();
RenderFrameHostImpl* pending_rfh =
root->render_manager()->speculative_frame_host();
NavigationRequest* navigation_request = root->navigation_request();
EXPECT_EQ(navigation_request->GetAssociatedRFHType(),
NavigationRequest::AssociatedRenderFrameHostType::SPECULATIVE);
EXPECT_TRUE(pending_rfh);
// 4) Check the LifecycleStateImpl of both rfh_a and pending_rfh before
// commit.
EXPECT_EQ(LifecycleStateImpl::kSpeculative, pending_rfh->lifecycle_state());
EXPECT_EQ(LifecycleStateImpl::kActive, rfh_a->lifecycle_state());
EXPECT_EQ(root_frame_host(), rfh_a);
EXPECT_TRUE(rfh_a->IsInPrimaryMainFrame());
EXPECT_FALSE(pending_rfh->IsInPrimaryMainFrame());
// 5) Let the navigation finish and make sure it is succeeded.
ASSERT_TRUE(manager.WaitForNavigationFinished());
EXPECT_EQ(url_b,
web_contents()->GetPrimaryMainFrame()->GetLastCommittedURL());
RenderFrameHostImpl* rfh_b = root_frame_host();
// 6) Check the LifecycleStateImpl of both rfh_a and rfh_b after navigating to
// B.
EXPECT_THAT(
rfh_a->lifecycle_state(),
testing::AnyOf(testing::Eq(LifecycleStateImpl::kRunningUnloadHandlers),
testing::Eq(LifecycleStateImpl::kInBackForwardCache)));
EXPECT_FALSE(rfh_a->GetPage().IsPrimary());
EXPECT_FALSE(rfh_a->IsInPrimaryMainFrame());
EXPECT_EQ(LifecycleStateImpl::kActive, rfh_b->lifecycle_state());
EXPECT_TRUE(rfh_b->GetPage().IsPrimary());
EXPECT_TRUE(rfh_b->IsInPrimaryMainFrame());
}
// Test the LifecycleStateImpl is updated correctly for a subframe.
IN_PROC_BROWSER_TEST_F(RenderFrameHostImplBrowserTest,
CheckRFHLifecycleStateTransitionOnSubFrame) {
IsolateAllSitesForTesting(base::CommandLine::ForCurrentProcess());
GURL url_ab(embedded_test_server()->GetURL(
"a.com", "/cross_site_iframe_factory.html?a(b)"));
GURL url_c(embedded_test_server()->GetURL("c.com", "/title1.html"));
// Lifecycle state of initial (Blank page) RenderFrameHost should be active as
// we don't update the LifecycleStateImpl prior to navigation commits (to new
// URL i.e., url_ab in this case).
EXPECT_EQ(LifecycleStateImpl::kActive, root_frame_host()->lifecycle_state());
// 1) Navigate to a page with an iframe.
EXPECT_TRUE(NavigateToURL(shell(), url_ab));
RenderFrameHostImpl* rfh_a = web_contents()->GetPrimaryMainFrame();
RenderFrameHostImpl* rfh_b = rfh_a->child_at(0)->current_frame_host();
EXPECT_EQ(LifecycleStateImpl::kActive, rfh_b->lifecycle_state());
// `rfh_b` is in the primary page, but since it's a subframe, it's not the
// primary main frame.
EXPECT_TRUE(rfh_b->GetPage().IsPrimary());
EXPECT_FALSE(rfh_b->IsInPrimaryMainFrame());
// 2) Navigate B's subframe to a cross-site C.
EXPECT_TRUE(NavigateToURLFromRenderer(rfh_b->frame_tree_node(), url_c));
// 3) Check LifecycleStateImpl of sub-frame rfh_c after navigating from
// subframe rfh_b.
RenderFrameHostImpl* rfh_c = rfh_a->child_at(0)->current_frame_host();
EXPECT_EQ(LifecycleStateImpl::kActive, rfh_c->lifecycle_state());
// 4) Add a new child frame.
RenderFrameHostCreatedObserver subframe_observer(web_contents());
EXPECT_TRUE(ExecJs(rfh_c,
"let iframe = document.createElement('iframe');"
"document.body.appendChild(iframe);"));
subframe_observer.Wait();
// 5) LifecycleStateImpl of newly inserted child frame should be kActive
// before navigation.
RenderFrameHostImpl* rfh_d = rfh_c->child_at(0)->current_frame_host();
EXPECT_EQ(LifecycleStateImpl::kActive, rfh_d->lifecycle_state());
}
// Test that LifecycleStateImpl is updated correctly during
// cross-RenderFrameHost navigation.
IN_PROC_BROWSER_TEST_F(RenderFrameHostImplBrowserTest,
CheckLifecycleStateTransitionWithPendingCommit) {
class CheckLifecycleStateImpl : public WebContentsObserver {
public:
explicit CheckLifecycleStateImpl(WebContents* web_contents)
: WebContentsObserver(web_contents) {}
// WebContentsObserver overrides:
void ReadyToCommitNavigation(NavigationHandle* navigation_handle) override {
RenderFrameHostImpl* rfh = static_cast<RenderFrameHostImpl*>(
navigation_handle->GetRenderFrameHost());
EXPECT_EQ(rfh->lifecycle_state(), LifecycleStateImpl::kPendingCommit);
EXPECT_EQ(rfh->GetLifecycleState(),
RenderFrameHost::LifecycleState::kPendingCommit);
EXPECT_FALSE(rfh->GetPage().IsPrimary());
EXPECT_FALSE(rfh->IsInPrimaryMainFrame());
}
};
GURL url_a(embedded_test_server()->GetURL("a.com", "/title1.html"));
GURL url_b(embedded_test_server()->GetURL("b.com", "/title2.html"));
IsolateAllSitesForTesting(base::CommandLine::ForCurrentProcess());
// 1) Navigate to A.
EXPECT_TRUE(NavigateToURL(shell(), url_a));
RenderFrameHostImpl* rfh_a = root_frame_host();
EXPECT_EQ(LifecycleStateImpl::kActive, rfh_a->lifecycle_state());
// 2) Start navigation to B, but don't commit yet.
TestNavigationManager manager(web_contents(), url_b);
shell()->LoadURL(url_b);
manager.WaitForSpeculativeRenderFrameHostCreation();
FrameTreeNode* root = web_contents()->GetPrimaryFrameTree().root();
RenderFrameHostImpl* speculative_rfh =
root->render_manager()->speculative_frame_host();
NavigationRequest* navigation_request = root->navigation_request();
EXPECT_EQ(navigation_request->GetAssociatedRFHType(),
NavigationRequest::AssociatedRenderFrameHostType::SPECULATIVE);
EXPECT_TRUE(speculative_rfh);
// 3) Check the LifecycleStateImpl of both rfh_a and speculative_rfh before
// commit.
EXPECT_EQ(LifecycleStateImpl::kSpeculative,
speculative_rfh->lifecycle_state());
EXPECT_EQ(LifecycleStateImpl::kActive, rfh_a->lifecycle_state());
EXPECT_EQ(root_frame_host(), rfh_a);
EXPECT_TRUE(rfh_a->IsInPrimaryMainFrame());
EXPECT_FALSE(speculative_rfh->IsInPrimaryMainFrame());
// 4) Check that LifecycleStateImpl of speculative_rfh transitions to
// kPendingCommit in ReadyToCommitNavigation.
CheckLifecycleStateImpl check_pending_commit(web_contents());
// 5) Let the navigation finish and make sure it is succeeded.
ASSERT_TRUE(manager.WaitForNavigationFinished());
EXPECT_EQ(url_b,
web_contents()->GetPrimaryMainFrame()->GetLastCommittedURL());
RenderFrameHostImpl* rfh_b = root_frame_host();
EXPECT_EQ(rfh_b, speculative_rfh);
EXPECT_EQ(LifecycleStateImpl::kActive, rfh_b->lifecycle_state());
}
// Verify that a new RFH gets marked as having committed a navigation after
// both normal navigations and error page navigations.
IN_PROC_BROWSER_TEST_F(RenderFrameHostImplBrowserTest,
HasCommittedAnyNavigation) {
GURL url_a(embedded_test_server()->GetURL("a.com", "/title1.html"));
EXPECT_TRUE(NavigateToURL(shell(), url_a));
EXPECT_TRUE(root_frame_host()->has_committed_any_navigation_);
GURL error_url(embedded_test_server()->GetURL("b.com", "/empty.html"));
std::unique_ptr<URLLoaderInterceptor> url_interceptor =
URLLoaderInterceptor::SetupRequestFailForURL(error_url,
net::ERR_DNS_TIMED_OUT);
EXPECT_FALSE(NavigateToURL(shell(), error_url));
EXPECT_TRUE(root_frame_host()->has_committed_any_navigation_);
}
// Ensure that calling document.open in an error page does not cause a renderer
// kill when it inherits the unreachable error URL.
IN_PROC_BROWSER_TEST_F(RenderFrameHostImplBrowserTest,
DocumentOpenInErrorPage) {
GURL error_url(embedded_test_server()->GetURL("error.com", "/empty.html"));
std::unique_ptr<URLLoaderInterceptor> url_interceptor =
URLLoaderInterceptor::SetupRequestFailForURL(error_url,
net::ERR_DNS_TIMED_OUT);
EXPECT_FALSE(NavigateToURL(shell(), error_url));
// Calling document.open should not cause CanCommitURL to fail, even though
// the error page URL is inherited.
// See https://crbug.com/326250356#comment36.
EXPECT_TRUE(ExecJs(shell(), "document.open();"));
EXPECT_EQ(GURL(kUnreachableWebDataURL),
root_frame_host()->last_document_url_in_renderer());
// Ensure the renderer process has not crashed.
ASSERT_TRUE(ExecJs(shell(), "true"));
ASSERT_TRUE(root_frame_host()->IsRenderFrameLive());
}
// Similar to DocumentOpenInErrorPage, but without error page isolation in the
// main frame, which changes ProcessLock expectations and can thus fail in
// additional ways.
IN_PROC_BROWSER_TEST_F(RenderFrameHostImplBrowserTest,
DocumentOpenInErrorPageWithoutErrorPageIsolation) {
// Disable error page isolation in main frames, similar to Android WebView.
class NoErrorPageIsolationContentBrowserClient
: public ContentBrowserTestContentBrowserClient {
public:
bool ShouldIsolateErrorPage(bool in_main_frame) override { return false; }
} no_error_isolation_client;
GURL error_url(embedded_test_server()->GetURL("error.com", "/empty.html"));
std::unique_ptr<URLLoaderInterceptor> url_interceptor =
URLLoaderInterceptor::SetupRequestFailForURL(error_url,
net::ERR_DNS_TIMED_OUT);
EXPECT_FALSE(NavigateToURL(shell(), error_url));
// Calling document.open should not cause CanCommitURL to fail, even though
// the error page URL is inherited.
// See https://crbug.com/326250356#comment36.
EXPECT_TRUE(ExecJs(shell(), "document.open();"));
EXPECT_EQ(GURL(kUnreachableWebDataURL),
root_frame_host()->last_document_url_in_renderer());
// Ensure the renderer process has not crashed.
ASSERT_TRUE(ExecJs(shell(), "true"));
ASSERT_TRUE(root_frame_host()->IsRenderFrameLive());
}
// Similar to DocumentOpenInErrorPage, but when loading the error page in a
// subframe, which lacks error page isolation.
IN_PROC_BROWSER_TEST_F(RenderFrameHostImplBrowserTest,
DocumentOpenInErrorPageSubframe) {
GURL main_frame_url(
embedded_test_server()->GetURL("/frame_tree/page_with_one_frame.html"));
ASSERT_TRUE(NavigateToURL(shell(), main_frame_url));
GURL error_url(embedded_test_server()->GetURL("error.com", "/empty.html"));
std::unique_ptr<URLLoaderInterceptor> url_interceptor =
URLLoaderInterceptor::SetupRequestFailForURL(error_url,
net::ERR_DNS_TIMED_OUT);
EXPECT_TRUE(NavigateIframeToURL(web_contents(), "child0", error_url));
RenderFrameHostImpl* subframe =
static_cast<RenderFrameHostImpl*>(ChildFrameAt(root_frame_host(), 0));
// Calling document.open should not cause CanCommitURL to fail, even though
// the error page URL is inherited.
// See https://crbug.com/326250356#comment36.
EXPECT_TRUE(ExecJs(subframe, "document.open();"));
EXPECT_EQ(GURL(kUnreachableWebDataURL),
subframe->last_document_url_in_renderer());
// Ensure the renderer process has not crashed.
ASSERT_TRUE(ExecJs(subframe, "true"));
ASSERT_TRUE(subframe->IsRenderFrameLive());
}
// Test the LifecycleStateImpl when a renderer crashes during navigation.
// When navigating after a crash, the new RenderFrameHost should
// become active immediately, prior to the navigation committing. This is
// an optimization to prevent the user from sitting around on the sad tab
// unnecessarily.
// TODO(crbug.com/40052076): This behavior might be revisited in the
// future.
IN_PROC_BROWSER_TEST_F(RenderFrameHostImplBrowserTest,
CheckRFHLifecycleStateWhenRendererCrashes) {
GURL url_a(embedded_test_server()->GetURL("a.com", "/title1.html"));
GURL url_b(embedded_test_server()->GetURL("b.com", "/title2.html"));
IsolateAllSitesForTesting(base::CommandLine::ForCurrentProcess());
// 1) Navigate to A.
EXPECT_TRUE(NavigateToURL(shell(), url_a));
RenderFrameHostImpl* rfh_a = root_frame_host();
EXPECT_EQ(LifecycleStateImpl::kActive, rfh_a->lifecycle_state());
// 2) Renderer crash.
RenderProcessHost* renderer_process = rfh_a->GetProcess();
RenderProcessHostWatcher crash_observer(
renderer_process, RenderProcessHostWatcher::WATCH_FOR_PROCESS_EXIT);
renderer_process->Shutdown(0);
crash_observer.Wait();
// 3) Start navigation to B, but don't commit yet.
TestNavigationManager manager(web_contents(), url_b);
shell()->LoadURL(url_b);
EXPECT_TRUE(manager.WaitForRequestStart());
FrameTreeNode* root = web_contents()->GetPrimaryFrameTree().root();
RenderFrameHostImpl* current_rfh =
root->render_manager()->current_frame_host();
NavigationRequest* navigation_request = root->navigation_request();
if (ShouldSkipEarlyCommitPendingForCrashedFrame()) {
EXPECT_EQ(navigation_request->GetAssociatedRFHType(),
NavigationRequest::AssociatedRenderFrameHostType::SPECULATIVE);
} else {
EXPECT_EQ(navigation_request->GetAssociatedRFHType(),
NavigationRequest::AssociatedRenderFrameHostType::CURRENT);
}
// 4) Check the LifecycleStateImpl of B's RFH.
EXPECT_EQ(LifecycleStateImpl::kActive, current_rfh->lifecycle_state());
// 5) Let the navigation finish and make sure it is succeeded.
ASSERT_TRUE(manager.WaitForNavigationFinished());
EXPECT_EQ(url_b,
web_contents()->GetPrimaryMainFrame()->GetLastCommittedURL());
// The RenderFrameHost has been replaced after the crash, so get it again.
current_rfh = root->render_manager()->current_frame_host();
EXPECT_EQ(LifecycleStateImpl::kActive, current_rfh->lifecycle_state());
}
// Check that same site navigation correctly resets document_used_web_otp_.
IN_PROC_BROWSER_TEST_F(RenderFrameHostImplBrowserTest,
SameSiteNavigationResetsDocumentUsedWebOTP) {
const GURL first_url(embedded_test_server()->GetURL("/title1.html"));
ASSERT_TRUE(NavigateToURL(shell(), first_url));
auto provider = std::make_unique<MockSmsProvider>();
MockSmsProvider* mock_provider_ptr = provider.get();
BrowserMainLoop::GetInstance()->SetSmsProviderForTesting(std::move(provider));
std::string script = R"(
(async () => {
let cred = await navigator.credentials.get({otp: {transport: ["sms"]}});
return cred.code;
}) ();
)";
EXPECT_CALL(*mock_provider_ptr, Retrieve(testing::_, testing::_))
.WillOnce(testing::Invoke([&]() {
mock_provider_ptr->NotifyReceive(
std::vector<url::Origin>{url::Origin::Create(first_url)}, "hello",
SmsFetcher::UserConsent::kObtained);
}));
// EvalJs waits for the promise being resolved. This ensures that the browser
// has time to see the otp usage, and records it, before we test for it below.
EXPECT_EQ("hello", EvalJs(shell(), script));
EXPECT_TRUE(web_contents()->GetPrimaryMainFrame()->DocumentUsedWebOTP());
// Loads a URL that maps to the same SiteInstance as the first URL, to make
// sure the navigation will not be cross-process.
const GURL second_url(embedded_test_server()->GetURL("/title2.html"));
ASSERT_TRUE(NavigateToURL(shell(), second_url));
EXPECT_FALSE(web_contents()->GetPrimaryMainFrame()->DocumentUsedWebOTP());
}
namespace {
// Calls |callback| whenever a DOMContentLoaded is reached in
// |render_frame_host|.
class DOMContentLoadedObserver : public WebContentsObserver {
public:
DOMContentLoadedObserver(WebContents* web_contents,
base::RepeatingClosure callback)
: WebContentsObserver(web_contents), callback_(callback) {}
DOMContentLoadedObserver(const DOMContentLoadedObserver&) = delete;
DOMContentLoadedObserver& operator=(const DOMContentLoadedObserver&) = delete;
protected:
// WebContentsObserver:
void DOMContentLoaded(RenderFrameHost* render_Frame_host) override {
callback_.Run();
}
private:
base::RepeatingClosure callback_;
};
// Calls |callback| whenever a DocumentOnLoad is reached in
// |render_frame_host|.
class DocumentOnLoadObserver : public WebContentsObserver {
public:
DocumentOnLoadObserver(WebContents* web_contents,
base::RepeatingClosure callback)
: WebContentsObserver(web_contents), callback_(callback) {}
DocumentOnLoadObserver(const DocumentOnLoadObserver&) = delete;
DocumentOnLoadObserver& operator=(const DocumentOnLoadObserver&) = delete;
protected:
// WebContentsObserver:
void DocumentOnLoadCompletedInPrimaryMainFrame() override { callback_.Run(); }
private:
base::RepeatingClosure callback_;
};
} // namespace
IN_PROC_BROWSER_TEST_F(ContentBrowserTest, LoadCallbacks) {
net::test_server::ControllableHttpResponse main_document_response(
embedded_test_server(), "/main_document");
net::test_server::ControllableHttpResponse image_response(
embedded_test_server(), "/img");
EXPECT_TRUE(embedded_test_server()->Start());
GURL main_document_url(embedded_test_server()->GetURL("/main_document"));
WebContents* web_contents = shell()->web_contents();
RenderFrameHostImpl* rfhi =
static_cast<RenderFrameHostImpl*>(web_contents->GetPrimaryMainFrame());
TestNavigationObserver load_observer(web_contents);
base::RunLoop loop_until_dcl;
DOMContentLoadedObserver dcl_observer(web_contents,
loop_until_dcl.QuitClosure());
shell()->LoadURL(main_document_url);
EXPECT_FALSE(rfhi->IsDOMContentLoaded());
EXPECT_FALSE(web_contents->IsDocumentOnLoadCompletedInPrimaryMainFrame());
main_document_response.WaitForRequest();
main_document_response.Send(
"HTTP/1.1 200 OK\r\n"
"Connection: close\r\n"
"Content-Type: text/html; charset=utf-8\r\n"
"\r\n"
"<img src='/img'>");
load_observer.WaitForNavigationFinished();
EXPECT_FALSE(rfhi->IsDOMContentLoaded());
EXPECT_FALSE(web_contents->IsDocumentOnLoadCompletedInPrimaryMainFrame());
main_document_response.Done();
// We should reach DOMContentLoaded, but not onload, since the image resource
// is still loading.
loop_until_dcl.Run();
EXPECT_TRUE(rfhi->is_loading());
EXPECT_TRUE(rfhi->IsDOMContentLoaded());
EXPECT_FALSE(web_contents->IsDocumentOnLoadCompletedInPrimaryMainFrame());
base::RunLoop loop_until_onload;
DocumentOnLoadObserver onload_observer(web_contents,
loop_until_onload.QuitClosure());
image_response.WaitForRequest();
image_response.Done();
// And now onload() should be reached.
loop_until_onload.Run();
EXPECT_TRUE(rfhi->IsDOMContentLoaded());
EXPECT_TRUE(web_contents->IsDocumentOnLoadCompletedInPrimaryMainFrame());
}
IN_PROC_BROWSER_TEST_F(ContentBrowserTest, LoadingStateResetOnNavigation) {
net::test_server::ControllableHttpResponse document2_response(
embedded_test_server(), "/document2");
EXPECT_TRUE(embedded_test_server()->Start());
GURL url1(embedded_test_server()->GetURL("/title1.html"));
GURL url2(embedded_test_server()->GetURL("/document2"));
WebContents* web_contents = shell()->web_contents();
base::RunLoop loop_until_onload;
DocumentOnLoadObserver onload_observer(web_contents,
loop_until_onload.QuitClosure());
shell()->LoadURL(url1);
loop_until_onload.Run();
EXPECT_TRUE(
static_cast<RenderFrameHostImpl*>(web_contents->GetPrimaryMainFrame())
->IsDOMContentLoaded());
EXPECT_TRUE(web_contents->IsDocumentOnLoadCompletedInPrimaryMainFrame());
// Expect that the loading state will be reset after a navigation.
TestNavigationObserver navigation_observer(web_contents);
shell()->LoadURL(url2);
document2_response.WaitForRequest();
document2_response.Send(
"HTTP/1.1 200 OK\r\n"
"Content-Type: text/html; charset=utf-8\r\n"
"\r\n");
navigation_observer.WaitForNavigationFinished();
EXPECT_FALSE(web_contents->GetPrimaryMainFrame()->IsDOMContentLoaded());
EXPECT_FALSE(web_contents->IsDocumentOnLoadCompletedInPrimaryMainFrame());
}
IN_PROC_BROWSER_TEST_F(ContentBrowserTest,
LoadingStateIsNotResetOnFailedNavigation) {
net::test_server::ControllableHttpResponse document2_response(
embedded_test_server(), "/document2");
EXPECT_TRUE(embedded_test_server()->Start());
GURL url1(embedded_test_server()->GetURL("/title1.html"));
GURL url2(embedded_test_server()->GetURL("/document2"));
WebContents* web_contents = shell()->web_contents();
RenderFrameHostImpl* rfhi =
static_cast<RenderFrameHostImpl*>(web_contents->GetPrimaryMainFrame());
base::RunLoop loop_until_onload;
DocumentOnLoadObserver onload_observer(web_contents,
loop_until_onload.QuitClosure());
shell()->LoadURL(url1);
loop_until_onload.Run();
EXPECT_TRUE(rfhi->IsDOMContentLoaded());
EXPECT_TRUE(web_contents->IsDocumentOnLoadCompletedInPrimaryMainFrame());
// Expect that the loading state will NOT be reset after a cancelled
// navigation.
TestNavigationManager navigation_manager(web_contents, url2);
shell()->LoadURL(url2);
EXPECT_TRUE(navigation_manager.WaitForRequestStart());
navigation_manager.ResumeNavigation();
document2_response.WaitForRequest();
document2_response.Send(
"HTTP/1.1 204 No Content\r\n"
"Content-Type: text/html; charset=utf-8\r\n"
"\r\n");
ASSERT_TRUE(navigation_manager.WaitForNavigationFinished());
EXPECT_TRUE(rfhi->IsDOMContentLoaded());
EXPECT_TRUE(web_contents->IsDocumentOnLoadCompletedInPrimaryMainFrame());
}
// Flaky on all platforms. crbug/1336851
IN_PROC_BROWSER_TEST_F(RenderFrameHostImplBrowserTest,
DISABLED_GetUkmSourceIds) {
ukm::TestAutoSetUkmRecorder recorder;
// This test site has one cross-site iframe.
GURL main_frame_url(
embedded_test_server()->GetURL("/frame_tree/page_with_one_frame.html"));
WebContents* web_contents = shell()->web_contents();
DocumentUkmSourceIdObserver observer(web_contents);
ASSERT_TRUE(NavigateToURL(shell(), main_frame_url));
RenderFrameHostImpl* main_frame_host =
static_cast<RenderFrameHostImpl*>(web_contents->GetPrimaryMainFrame());
ukm::SourceId page_ukm_source_id = main_frame_host->GetPageUkmSourceId();
ukm::SourceId main_frame_doc_ukm_source_id =
observer.GetPrimaryMainFrameDocumentUkmSourceId();
ASSERT_EQ(1u, main_frame_host->child_count());
RenderFrameHostImpl* sub_frame_host = static_cast<RenderFrameHostImpl*>(
main_frame_host->child_at(0)->current_frame_host());
ukm::SourceId subframe_doc_ukm_source_id =
observer.GetSubFrameDocumentUkmSourceId();
// Navigation-level source id should be the same for all frames on the page.
ASSERT_EQ(page_ukm_source_id, sub_frame_host->GetPageUkmSourceId());
// The two document source ids and the navigation source id should be all
// distinct.
EXPECT_NE(page_ukm_source_id, main_frame_doc_ukm_source_id);
EXPECT_NE(page_ukm_source_id, subframe_doc_ukm_source_id);
EXPECT_NE(main_frame_doc_ukm_source_id, subframe_doc_ukm_source_id);
const auto& document_created_entries =
recorder.GetEntriesByName("DocumentCreated");
// There should be one DocumentCreated entry for each of the two frames.
ASSERT_EQ(2u, document_created_entries.size());
auto* main_frame_document_created_entry =
recorder.GetDocumentCreatedEntryForSourceId(main_frame_doc_ukm_source_id);
auto* sub_frame_document_created_entry =
recorder.GetDocumentCreatedEntryForSourceId(subframe_doc_ukm_source_id);
// Verify the recorded values on the DocumentCreated entries.
EXPECT_EQ(page_ukm_source_id,
*recorder.GetEntryMetric(main_frame_document_created_entry,
"NavigationSourceId"));
EXPECT_TRUE(*recorder.GetEntryMetric(main_frame_document_created_entry,
"IsMainFrame"));
EXPECT_FALSE(*recorder.GetEntryMetric(main_frame_document_created_entry,
"IsCrossOriginFrame"));
EXPECT_FALSE(*recorder.GetEntryMetric(main_frame_document_created_entry,
"IsCrossSiteFrame"));
EXPECT_EQ(page_ukm_source_id,
*recorder.GetEntryMetric(sub_frame_document_created_entry,
"NavigationSourceId"));
EXPECT_FALSE(*recorder.GetEntryMetric(sub_frame_document_created_entry,
"IsMainFrame"));
EXPECT_TRUE(*recorder.GetEntryMetric(sub_frame_document_created_entry,
"IsCrossOriginFrame"));
EXPECT_TRUE(*recorder.GetEntryMetric(sub_frame_document_created_entry,
"IsCrossSiteFrame"));
// Verify source creations. Main frame document source should have the URL;
// no source should have been created for the sub-frame document.
recorder.ExpectEntrySourceHasUrl(main_frame_document_created_entry,
main_frame_url);
EXPECT_EQ(nullptr, recorder.GetSourceForSourceId(subframe_doc_ukm_source_id));
// Spot-check that an example entry recorded from the renderer uses the
// correct document source id set by the RFH.
const auto& blink_entries = recorder.GetEntriesByName("Blink.PageLoad");
for (const ukm::mojom::UkmEntry* entry : blink_entries) {
EXPECT_EQ(main_frame_doc_ukm_source_id, entry->source_id);
}
}
IN_PROC_BROWSER_TEST_F(RenderFrameHostImplBrowserTest, CrossSiteFrame) {
ukm::TestAutoSetUkmRecorder recorder;
// This test site has one cross-origin but same-site iframe (b.x.com).
GURL main_frame_url(embedded_test_server()->GetURL(
"a.x.com", "/frame_tree/page_with_cross_origin_same_site_iframe.html"));
WebContents* web_contents = shell()->web_contents();
DocumentUkmSourceIdObserver observer(web_contents);
ASSERT_TRUE(NavigateToURL(shell(), main_frame_url));
auto* sub_frame_document_created_entry =
recorder.GetDocumentCreatedEntryForSourceId(
observer.GetSubFrameDocumentUkmSourceId());
// Verify the recorded values on the sub frame's DocumentCreated entry.
EXPECT_FALSE(*recorder.GetEntryMetric(sub_frame_document_created_entry,
"IsMainFrame"));
EXPECT_TRUE(*recorder.GetEntryMetric(sub_frame_document_created_entry,
"IsCrossOriginFrame"));
EXPECT_FALSE(*recorder.GetEntryMetric(sub_frame_document_created_entry,
"IsCrossSiteFrame"));
}
// TODO(crbug.com/40554401): the code below is temporary and will be
// removed when Java Bridge is mojofied.
#if BUILDFLAG(IS_ANDROID)
struct ObjectData {
const int32_t id;
const std::vector<std::string> methods;
};
ObjectData kMainObject{5, {"getId", "getInnerObject", "readArray"}};
ObjectData kInnerObject{10, {"getInnerId"}};
class MockInnerObject : public blink::mojom::RemoteObject {
public:
void HasMethod(const std::string& name, HasMethodCallback callback) override {
std::move(callback).Run(base::Contains(kInnerObject.methods, name));
}
void GetMethods(GetMethodsCallback callback) override {
std::move(callback).Run(kInnerObject.methods);
}
void InvokeMethod(
const std::string& name,
std::vector<blink::mojom::RemoteInvocationArgumentPtr> arguments,
InvokeMethodCallback callback) override {
EXPECT_EQ("getInnerId", name);
blink::mojom::RemoteInvocationResultPtr result =
blink::mojom::RemoteInvocationResult::New();
result->error = blink::mojom::RemoteInvocationError::OK;
result->value = blink::mojom::RemoteInvocationResultValue::NewNumberValue(
kInnerObject.id);
std::move(callback).Run(std::move(result));
}
void NotifyReleasedObject() override {}
};
class MockObject : public blink::mojom::RemoteObject {
public:
explicit MockObject(
mojo::PendingReceiver<blink::mojom::RemoteObject> receiver)
: receiver_(this, std::move(receiver)) {}
void HasMethod(const std::string& name, HasMethodCallback callback) override {
std::move(callback).Run(base::Contains(kMainObject.methods, name));
}
void GetMethods(GetMethodsCallback callback) override {
std::move(callback).Run(kMainObject.methods);
}
void InvokeMethod(
const std::string& name,
std::vector<blink::mojom::RemoteInvocationArgumentPtr> arguments,
InvokeMethodCallback callback) override {
blink::mojom::RemoteInvocationResultPtr result =
blink::mojom::RemoteInvocationResult::New();
result->error = blink::mojom::RemoteInvocationError::OK;
if (name == "getId") {
result->value = blink::mojom::RemoteInvocationResultValue::NewNumberValue(
kMainObject.id);
} else if (name == "readArray") {
EXPECT_EQ(1U, arguments.size());
EXPECT_TRUE(arguments[0]->is_array_value());
num_elements_received_ = arguments[0]->get_array_value().size();
result->value =
blink::mojom::RemoteInvocationResultValue::NewBooleanValue(true);
} else if (name == "getInnerObject") {
result->value = blink::mojom::RemoteInvocationResultValue::NewObjectId(
kInnerObject.id);
}
std::move(callback).Run(std::move(result));
}
void NotifyReleasedObject() override {}
int get_num_elements_received() const { return num_elements_received_; }
private:
int num_elements_received_ = 0;
mojo::Receiver<blink::mojom::RemoteObject> receiver_;
};
class MockObjectHost : public blink::mojom::RemoteObjectHost {
public:
void GetObject(
int32_t object_id,
mojo::PendingReceiver<blink::mojom::RemoteObject> receiver) override {
if (object_id == kMainObject.id) {
mock_object_ = std::make_unique<MockObject>(std::move(receiver));
} else if (object_id == kInnerObject.id) {
mojo::MakeSelfOwnedReceiver(std::make_unique<MockInnerObject>(),
std::move(receiver));
}
reference_count_map_[object_id]++;
}
void AcquireObject(int32_t object_id) override {
reference_count_map_[object_id]++;
}
void ReleaseObject(int32_t object_id) override {
reference_count_map_[object_id]--;
}
mojo::PendingRemote<blink::mojom::RemoteObjectHost> GetRemote() {
if (receiver_.is_bound()) {
// When a new RenderFrame is created for a navigation we call this
// function again from `RemoteObjectInjector::RenderFrameCreated()`,
// so unbind the previous connection with the previous RenderFrame if
// needed. Note that we might lose some in-flight messages with the
// previous RenderFrame in this case, so this is not perfect.
// TODO(https://crbug.com/40615943): Add better support for RemoteObjects
// on RenderFrame swaps, if needed.
receiver_.reset();
}
return receiver_.BindNewPipeAndPassRemote();
}
MockObject* GetMockObject() const { return mock_object_.get(); }
int ReferenceCount(int32_t object_id) const {
return !reference_count_map_.at(object_id);
}
private:
mojo::Receiver<blink::mojom::RemoteObjectHost> receiver_{this};
std::unique_ptr<MockObject> mock_object_;
std::map<int32_t, int> reference_count_map_{{kMainObject.id, 0},
{kInnerObject.id, 0}};
};
class RemoteObjectInjector : public WebContentsObserver {
public:
explicit RemoteObjectInjector(WebContents* web_contents)
: WebContentsObserver(web_contents) {}
RemoteObjectInjector(const RemoteObjectInjector&) = delete;
RemoteObjectInjector& operator=(const RemoteObjectInjector&) = delete;
const MockObjectHost& GetObjectHost() const { return host_; }
private:
void RenderFrameCreated(RenderFrameHost* render_frame_host) override {
mojo::Remote<blink::mojom::RemoteObjectGateway> gateway;
mojo::Remote<blink::mojom::RemoteObjectGatewayFactory> factory;
static_cast<RenderFrameHostImpl*>(render_frame_host)
->GetRemoteInterfaces()
->GetInterface(factory.BindNewPipeAndPassReceiver());
factory->CreateRemoteObjectGateway(host_.GetRemote(),
gateway.BindNewPipeAndPassReceiver());
gateway->AddNamedObject("testObject", kMainObject.id);
}
MockObjectHost host_;
};
namespace {
void SetupRemoteObjectInvocation(Shell* shell, const GURL& url) {
WebContents* web_contents = shell->web_contents();
// The first load triggers RenderFrameCreated on a WebContentsObserver
// instance, where the object injection happens.
shell->LoadURL(url);
EXPECT_TRUE(WaitForLoadStop(web_contents));
// Injected objects become visible only after reload.
web_contents->GetController().Reload(ReloadType::NORMAL, false);
EXPECT_TRUE(WaitForLoadStop(web_contents));
}
} // namespace
// TODO(crbug.com/40554401): Remove this when the new Java Bridge code is
// integrated into WebView.
// This test is a temporary way of verifying that the renderer part
// works as expected.
// TODO(crbug.com/347691518): This test is flaky.
IN_PROC_BROWSER_TEST_F(RenderFrameHostImplBrowserTest,
DISABLED_RemoteObjectEnumerateProperties) {
GURL url(embedded_test_server()->GetURL("/empty.html"));
RemoteObjectInjector injector(web_contents());
SetupRemoteObjectInvocation(shell(), url);
std::string kScript = "Object.keys(testObject).join(' ');";
auto result = EvalJs(web_contents(), kScript);
EXPECT_EQ(base::JoinString(kMainObject.methods, " "),
result.value.GetString());
}
IN_PROC_BROWSER_TEST_F(RenderFrameHostImplBrowserTest,
RemoteObjectInvokeNonexistentMethod) {
GURL url(embedded_test_server()->GetURL("/empty.html"));
RemoteObjectInjector injector(web_contents());
SetupRemoteObjectInvocation(shell(), url);
std::string kScript = "testObject.getInnerId();";
EXPECT_THAT(EvalJs(web_contents(), kScript), EvalJsResult::IsError());
}
// TODO(crbug.com/40236762): This test is flaky.
IN_PROC_BROWSER_TEST_F(RenderFrameHostImplBrowserTest,
DISABLED_RemoteObjectInvokeMethodReturningNumber) {
GURL url(embedded_test_server()->GetURL("/empty.html"));
RemoteObjectInjector injector(web_contents());
SetupRemoteObjectInvocation(shell(), url);
std::string kScript = "testObject.getId();";
EXPECT_EQ(kMainObject.id, EvalJs(web_contents(), kScript));
}
// TODO(crbug.com/40236899): This test is flaky.
IN_PROC_BROWSER_TEST_F(RenderFrameHostImplBrowserTest,
DISABLED_RemoteObjectInvokeMethodTakingArray) {
GURL url(embedded_test_server()->GetURL("/empty.html"));
RemoteObjectInjector injector(web_contents());
SetupRemoteObjectInvocation(shell(), url);
std::string kScript = "testObject.readArray([6, 8, 2]);";
EXPECT_THAT(EvalJs(web_contents(), kScript), EvalJsResult::IsOk());
EXPECT_EQ(
3, injector.GetObjectHost().GetMockObject()->get_num_elements_received());
}
// TODO(crbug.com/40274210): This test is flaky.
IN_PROC_BROWSER_TEST_F(RenderFrameHostImplBrowserTest,
DISABLED_RemoteObjectInvokeMethodReturningObject) {
GURL url(embedded_test_server()->GetURL("/empty.html"));
RemoteObjectInjector injector(web_contents());
SetupRemoteObjectInvocation(shell(), url);
std::string kScript = "testObject.getInnerObject().getInnerId();";
EXPECT_EQ(kInnerObject.id, EvalJs(web_contents(), kScript));
}
// TODO(crbug.com/340869172): This test is flaky.
IN_PROC_BROWSER_TEST_F(RenderFrameHostImplBrowserTest,
DISABLED_RemoteObjectInvokeMethodException) {
GURL url(embedded_test_server()->GetURL("/empty.html"));
RemoteObjectInjector injector(web_contents());
SetupRemoteObjectInvocation(shell(), url);
std::string error_message = "hahaha";
std::string kScript = JsReplace(R"(
const array = [1, 2, 3];
Object.defineProperty(array, 0, {
get() { throw new Error($1); }
});
testObject.readArray(array);
)",
error_message);
auto error = EvalJs(web_contents(), kScript).error;
EXPECT_NE(error.find(error_message), std::string::npos);
}
// Based on testReturnedObjectIsGarbageCollected.
// TODO(crbug.com/340928363): This test is flaky.
IN_PROC_BROWSER_TEST_F(RenderFrameHostImplBrowserTest,
DISABLED_RemoteObjectRelease) {
GURL url(embedded_test_server()->GetURL("/empty.html"));
RemoteObjectInjector injector(web_contents());
SetupRemoteObjectInvocation(shell(), url);
EXPECT_EQ(
"object",
EvalJs(
web_contents(),
"globalInner = testObject.getInnerObject(); typeof globalInner; "));
EXPECT_GT(injector.GetObjectHost().ReferenceCount(kInnerObject.id), 0);
EXPECT_EQ("object", EvalJs(web_contents(), "gc(); typeof globalInner;"));
EXPECT_GT(injector.GetObjectHost().ReferenceCount(kInnerObject.id), 0);
EXPECT_EQ(
"undefined",
EvalJs(web_contents(), "delete globalInner; gc(); typeof globalInner;"));
EXPECT_EQ(injector.GetObjectHost().ReferenceCount(kInnerObject.id), 0);
}
#endif // BUILDFLAG(IS_ANDROID)
// The RenderFrameHost's last HTTP status code shouldn't change after
// same-document navigations.
IN_PROC_BROWSER_TEST_F(RenderFrameHostImplBrowserTest,
HttpStatusCodeAfterSameDocumentNavigation) {
GURL url_201(embedded_test_server()->GetURL("/echo?status=201"));
EXPECT_TRUE(NavigateToURL(shell(), url_201));
EXPECT_EQ(201, root_frame_host()->last_http_status_code());
EXPECT_TRUE(ExecJs(root_frame_host(), "location.href = '#'"));
EXPECT_EQ(201, root_frame_host()->last_http_status_code());
}
// The RenderFrameHost's last HTTP method shouldn't change after
// same-document navigations.
IN_PROC_BROWSER_TEST_F(RenderFrameHostImplBrowserTest,
HttpMethodAfterSameDocumentNavigation) {
GURL url(embedded_test_server()->GetURL("/empty.html"));
EXPECT_TRUE(NavigateToURL(shell(), url));
EXPECT_EQ("GET", root_frame_host()->last_http_method());
TestNavigationObserver observer_post(web_contents());
ExecuteScriptAsync(root_frame_host(), R"(
let input = document.createElement("input");
input.setAttribute("type", "hidden");
input.setAttribute("name", "value");
let form = document.createElement('form');
form.appendChild(input);
form.setAttribute("method", "POST");
form.setAttribute("action", "?1");
document.body.appendChild(form);
form.submit();
)");
observer_post.Wait();
EXPECT_EQ("POST", root_frame_host()->last_http_method());
EXPECT_TRUE(ExecJs(root_frame_host(), "location.href = '#'"));
EXPECT_EQ("POST", root_frame_host()->last_http_method());
}
// Check Chrome won't attempt automatically loading the /favicon.ico if it would
// be blocked by CSP.
IN_PROC_BROWSER_TEST_F(RenderFrameHostImplBrowserTest,
DefaultFaviconVersusCSP) {
auto navigate = [&](std::string csp) {
EXPECT_TRUE(NavigateToURL(
shell(), embedded_test_server()->GetURL(
"/set-header?Content-Security-Policy: " + csp)));
// DidStopLoading() and UpdateFaviconURL() are sent together from the same
// task. However we have waited only for DidStopLoading(). Make a round trip
// with the renderer to ensure UpdateFaviconURL() to be received.
EXPECT_TRUE(ExecJs(root_frame_host(), ""));
};
// Blocked by CSP.
navigate("img-src 'none'");
EXPECT_EQ(0u, web_contents()->GetFaviconURLs().size());
// Allowed by CSP.
navigate("img-src *");
EXPECT_EQ(1u, web_contents()->GetFaviconURLs().size());
EXPECT_EQ("/favicon.ico",
web_contents()->GetFaviconURLs()[0]->icon_url.path());
}
IN_PROC_BROWSER_TEST_F(RenderFrameHostImplBrowserTest,
GetWebExposedIsolationLevel) {
// Not isolated:
EXPECT_TRUE(
NavigateToURL(shell(), embedded_test_server()->GetURL("/empty.html")));
EXPECT_EQ(WebExposedIsolationLevel::kNotIsolated,
root_frame_host()->GetWebExposedIsolationLevel());
// Cross-Origin Isolated:
EXPECT_TRUE(NavigateToURL(shell(),
embedded_test_server()->GetURL(
"/set-header?"
"Cross-Origin-Opener-Policy: same-origin&"
"Cross-Origin-Embedder-Policy: require-corp")));
// Status is kIsolated.
EXPECT_EQ(WebExposedIsolationLevel::kIsolated,
root_frame_host()->GetWebExposedIsolationLevel());
}
// Regression test for https://crbug.com/40864543
// The main document is using COEP, but the 204 No Content child document isn't.
// This shouldn't crash.
IN_PROC_BROWSER_TEST_F(RenderFrameHostImplBrowserTest,
NoCrashOn204NoContentChildDocumentCOEP) {
// Main document sets COEP.
GURL main_url(embedded_test_server()->GetURL(
"/set-header?"
"Cross-Origin-Embedder-Policy: require-corp"));
EXPECT_TRUE(NavigateToURL(shell(), main_url));
// Iframe is a 204 No Content.
TestNavigationManager navigation_manager(
web_contents(), embedded_test_server()->GetURL("/nocontent"));
EXPECT_TRUE(ExecJs(root_frame_host(), R"(
let iframe = document.createElement('iframe');
iframe.src = '/nocontent'
document.body.appendChild(iframe);
)"));
ASSERT_TRUE(navigation_manager.WaitForNavigationFinished());
}
class IsolatedApplicationContentBrowserClient
: public ContentBrowserTestContentBrowserClient {
public:
explicit IsolatedApplicationContentBrowserClient(
const std::string& isolated_application_host)
: isolated_application_host_(isolated_application_host) {}
bool ShouldUrlUseApplicationIsolationLevel(BrowserContext* browser_context,
const GURL& url) override {
return url.host() == isolated_application_host_;
}
private:
std::string isolated_application_host_;
};
class RenderFrameHostImplBrowserTestWithRestrictedApis
: public RenderFrameHostImplBrowserTest {
public:
void SetUpCommandLine(base::CommandLine* command_line) override {
RenderFrameHostImplBrowserTest::SetUpCommandLine(command_line);
mock_cert_verifier_.SetUpCommandLine(command_line);
}
void SetUpInProcessBrowserTestFixture() override {
RenderFrameHostImplBrowserTest::SetUpInProcessBrowserTestFixture();
mock_cert_verifier_.SetUpInProcessBrowserTestFixture();
}
void TearDownInProcessBrowserTestFixture() override {
RenderFrameHostImplBrowserTest::TearDownInProcessBrowserTestFixture();
mock_cert_verifier_.TearDownInProcessBrowserTestFixture();
}
protected:
void SetUpOnMainThread() override {
RenderFrameHostImplBrowserTest::SetUpOnMainThread();
mock_cert_verifier_.mock_cert_verifier()->set_default_result(net::OK);
https_server()->ServeFilesFromSourceDirectory(GetTestDataFilePath());
net::test_server::RegisterDefaultHandlers(https_server());
ASSERT_TRUE(https_server()->Start());
}
private:
ContentMockCertVerifier mock_cert_verifier_;
};
IN_PROC_BROWSER_TEST_F(RenderFrameHostImplBrowserTestWithRestrictedApis,
GetWebExposedIsolationLevel) {
std::string app_host = "app.com";
IsolatedApplicationContentBrowserClient client(app_host);
// Not isolated:
std::string non_app_host = "nonapp.com";
TestNavigationObserver navigation_observer(web_contents());
shell()->LoadURL(https_server()->GetURL(non_app_host, "/empty.html"));
navigation_observer.Wait();
EXPECT_TRUE(navigation_observer.last_navigation_succeeded());
EXPECT_EQ(WebExposedIsolationLevel::kNotIsolated,
root_frame_host()->GetProcess()->GetWebExposedIsolationLevel());
EXPECT_EQ(WebExposedIsolationLevel::kNotIsolated,
root_frame_host()->GetWebExposedIsolationLevel());
EXPECT_EQ(false, EvalJs(root_frame_host(), "self.crossOriginIsolated"));
// Cross-Origin Isolated:
GURL non_app_url =
https_server()->GetURL(non_app_host,
"/set-header?"
"Cross-Origin-Opener-Policy: same-origin&"
"Cross-Origin-Embedder-Policy: require-corp&"
"Cross-Origin-Resource-Policy: cross-origin");
EXPECT_TRUE(NavigateToURL(shell(), non_app_url));
EXPECT_EQ(WebExposedIsolationLevel::kIsolated,
root_frame_host()->GetProcess()->GetWebExposedIsolationLevel());
EXPECT_EQ(WebExposedIsolationLevel::kIsolated,
root_frame_host()->GetWebExposedIsolationLevel());
EXPECT_EQ(true, EvalJs(root_frame_host(), "self.crossOriginIsolated"));
// Permission delegated Cross-Origin Isolated child frame:
std::string create_iframe = R"(
new Promise(resolve => {
const iframe = document.createElement('iframe');
iframe.src = $1;
iframe.allow = $2;
iframe.addEventListener('load', () => resolve(true));
document.body.appendChild(iframe);
});
)";
EXPECT_TRUE(ExecJs(shell(), JsReplace(create_iframe, non_app_url, "")));
RenderFrameHost* non_app_child_frame = ChildFrameAt(root_frame_host(), 0);
EXPECT_EQ(WebExposedIsolationLevel::kIsolated,
non_app_child_frame->GetProcess()->GetWebExposedIsolationLevel());
EXPECT_EQ(WebExposedIsolationLevel::kIsolated,
non_app_child_frame->GetWebExposedIsolationLevel());
EXPECT_EQ(true, EvalJs(non_app_child_frame, "self.crossOriginIsolated"));
// Non permission delegated Cross-Origin Isolated child frame:
EXPECT_TRUE(ExecJs(shell(), JsReplace(create_iframe, non_app_url,
"cross-origin-isolated 'none'")));
non_app_child_frame = ChildFrameAt(root_frame_host(), 1);
EXPECT_EQ(WebExposedIsolationLevel::kIsolated,
non_app_child_frame->GetProcess()->GetWebExposedIsolationLevel());
EXPECT_EQ(WebExposedIsolationLevel::kNotIsolated,
non_app_child_frame->GetWebExposedIsolationLevel());
EXPECT_EQ(false, EvalJs(non_app_child_frame, "self.crossOriginIsolated"));
// Isolated Application:
GURL app_url =
https_server()->GetURL(app_host,
"/set-header?"
"Cross-Origin-Opener-Policy: same-origin&"
"Cross-Origin-Embedder-Policy: require-corp&"
"Cross-Origin-Resource-Policy: same-origin");
Shell* app_shell = shell()->CreateNewWindow(
web_contents()->GetController().GetBrowserContext(), GURL(),
/*site_instance=*/nullptr, gfx::Size());
EXPECT_TRUE(NavigateToURL(app_shell, app_url));
RenderFrameHost* app_frame = app_shell->web_contents()->GetPrimaryMainFrame();
EXPECT_EQ(WebExposedIsolationLevel::kIsolatedApplication,
app_frame->GetProcess()->GetWebExposedIsolationLevel());
EXPECT_EQ(WebExposedIsolationLevel::kIsolatedApplication,
app_frame->GetWebExposedIsolationLevel());
EXPECT_EQ(true, EvalJs(app_frame, "self.crossOriginIsolated"));
// Permission delegated same-origin Isolated Application child frame:
EXPECT_TRUE(ExecJs(
app_shell, JsReplace(create_iframe, app_url, "cross-origin-isolated")));
RenderFrameHost* app_child_frame = ChildFrameAt(app_frame, 0);
EXPECT_EQ(WebExposedIsolationLevel::kIsolatedApplication,
app_child_frame->GetProcess()->GetWebExposedIsolationLevel());
EXPECT_EQ(WebExposedIsolationLevel::kIsolatedApplication,
app_child_frame->GetWebExposedIsolationLevel());
EXPECT_EQ(true, EvalJs(app_child_frame, "self.crossOriginIsolated"));
// Non permission delegated same-origin Isolated Application child frame:
EXPECT_TRUE(ExecJs(app_shell, JsReplace(create_iframe, app_url,
"cross-origin-isolated 'none'")));
app_child_frame = ChildFrameAt(app_frame, 1);
EXPECT_EQ(WebExposedIsolationLevel::kIsolatedApplication,
app_child_frame->GetProcess()->GetWebExposedIsolationLevel());
EXPECT_EQ(WebExposedIsolationLevel::kNotIsolated,
app_child_frame->GetWebExposedIsolationLevel());
EXPECT_EQ(false, EvalJs(app_child_frame, "self.crossOriginIsolated"));
// Permission delegated cross-origin Isolated Application child frame:
// The frame's WebExposedIsolationLevel isn't "isolated application" despite
// being delegated the "cross-origin-isolated" permission because that
// isolation level can only be delegated to same-origin child frames.
EXPECT_TRUE(ExecJs(app_shell, JsReplace(create_iframe, non_app_url,
"cross-origin-isolated")));
non_app_child_frame = ChildFrameAt(app_frame, 2);
EXPECT_EQ(WebExposedIsolationLevel::kIsolated,
non_app_child_frame->GetProcess()->GetWebExposedIsolationLevel());
EXPECT_EQ(WebExposedIsolationLevel::kIsolated,
non_app_child_frame->GetWebExposedIsolationLevel());
EXPECT_EQ(true, EvalJs(non_app_child_frame, "self.crossOriginIsolated"));
// Non permission delegated cross-origin Isolated Application child frame:
EXPECT_TRUE(ExecJs(app_shell, JsReplace(create_iframe, non_app_url,
"cross-origin-isolated 'none'")));
non_app_child_frame = ChildFrameAt(app_frame, 3);
EXPECT_EQ(WebExposedIsolationLevel::kIsolated,
non_app_child_frame->GetProcess()->GetWebExposedIsolationLevel());
EXPECT_EQ(WebExposedIsolationLevel::kNotIsolated,
non_app_child_frame->GetWebExposedIsolationLevel());
EXPECT_EQ(false, EvalJs(non_app_child_frame, "self.crossOriginIsolated"));
}
IN_PROC_BROWSER_TEST_F(RenderFrameHostImplBrowserTest,
CommitNavigationCounter) {
GURL initial_url = embedded_test_server()->GetURL("a.com", "/title1.html");
GURL same_document_url =
embedded_test_server()->GetURL("a.com", "/title1.html#index");
GURL other_url = embedded_test_server()->GetURL("a.com", "/title2.html");
GURL blocked_url(embedded_test_server()->GetURL("a.com", "/blocked.html"));
std::unique_ptr<URLLoaderInterceptor> url_interceptor =
URLLoaderInterceptor::SetupRequestFailForURL(blocked_url,
net::ERR_BLOCKED_BY_CLIENT);
// Regular, initial navigation.
{
RenderFrameHostImpl* initial_rfh = static_cast<RenderFrameHostImpl*>(
web_contents()->GetPrimaryMainFrame());
int initial_counter = initial_rfh->commit_navigation_sent_counter();
EXPECT_TRUE(NavigateToURL(shell(), initial_url));
EXPECT_EQ(initial_rfh, web_contents()->GetPrimaryMainFrame())
<< "No RFH swap expected.";
EXPECT_GT(
web_contents()->GetPrimaryMainFrame()->commit_navigation_sent_counter(),
initial_counter)
<< "The commit_navigation_sent_counter has been increased.";
}
// Same document navigation.
{
RenderFrameHostImpl* initial_rfh = static_cast<RenderFrameHostImpl*>(
web_contents()->GetPrimaryMainFrame());
int initial_counter = initial_rfh->commit_navigation_sent_counter();
EXPECT_TRUE(NavigateToURL(shell(), same_document_url));
EXPECT_EQ(initial_rfh, web_contents()->GetPrimaryMainFrame())
<< "No RFH swap expected.";
EXPECT_EQ(
initial_counter,
web_contents()->GetPrimaryMainFrame()->commit_navigation_sent_counter())
<< "The commit_navigation_sent_counter has not been increased.";
}
// New document navigation.
{
RenderFrameHostImpl* initial_rfh = static_cast<RenderFrameHostImpl*>(
web_contents()->GetPrimaryMainFrame());
int initial_counter = initial_rfh->commit_navigation_sent_counter();
EXPECT_TRUE(NavigateToURL(shell(), other_url));
EXPECT_TRUE(initial_rfh != web_contents()->GetPrimaryMainFrame() ||
web_contents()
->GetPrimaryMainFrame()
->commit_navigation_sent_counter() > initial_counter)
<< "Either the RFH has been swapped or the counter has been increased.";
}
// Failed navigation.
{
RenderFrameHostImpl* initial_rfh = static_cast<RenderFrameHostImpl*>(
web_contents()->GetPrimaryMainFrame());
int initial_counter = initial_rfh->commit_navigation_sent_counter();
EXPECT_FALSE(NavigateToURL(shell(), blocked_url));
EXPECT_TRUE(initial_rfh != web_contents()->GetPrimaryMainFrame() ||
web_contents()
->GetPrimaryMainFrame()
->commit_navigation_sent_counter() > initial_counter)
<< "Either the RFH has been swapped or the counter has been increased.";
}
}
using RenderFrameHostImplSubframeReuseBrowserTest =
RenderFrameHostImplBrowserTest;
IN_PROC_BROWSER_TEST_F(RenderFrameHostImplSubframeReuseBrowserTest,
SubframeShutdownDelay) {
// This test exercises a scenario that's only possible with
// --site-per-process.
if (!AreAllSitesIsolatedForTesting())
return;
// Navigate to a site with a subframe.
GURL url_1(embedded_test_server()->GetURL(
"a.com", "/cross_site_iframe_factory.html?a(b)"));
EXPECT_TRUE(NavigateToURL(shell(), url_1));
RenderFrameHostImpl* rfh_b =
root_frame_host()->child_at(0)->current_frame_host();
int subframe_process_id = rfh_b->GetProcess()->GetDeprecatedID();
RenderFrameDeletedObserver delete_rfh_b(rfh_b);
TestFrameNavigationObserver commit_observer(
web_contents()->GetPrimaryFrameTree().root());
// Navigate to another page on the same site with the same subframe.
GURL url_2(embedded_test_server()->GetURL(
"a.com", "/cross_site_iframe_factory.html?a(b)"));
shell()->LoadURL(url_2);
// Wait for site |url_2| to commit, but not fully load so that its subframe is
// not yet loaded.
commit_observer.WaitForCommit();
// Wait for the subframe RenderFrameHost in |url_1| to shut down.
delete_rfh_b.WaitUntilDeleted();
// The process hosting the subframe should have its shutdown delayed and be
// tracked in the pending-delete tracker.
auto* subframe_process_host = static_cast<RenderProcessHostImpl*>(
content::RenderProcessHost::FromID(subframe_process_id));
if (RenderProcessHostImpl::ShouldDelayProcessShutdown()) {
ASSERT_TRUE(subframe_process_host->IsProcessShutdownDelayedForTesting());
} else {
ASSERT_EQ(nullptr, subframe_process_host);
}
// Wait for |url_2| to fully load so that its subframe loads.
EXPECT_TRUE(WaitForLoadStop(web_contents()));
// The process for the just-deleted subframe should be reused for the new
// subframe, because they share the same site.
RenderFrameHostImpl* new_rfh_b =
root_frame_host()->child_at(0)->current_frame_host();
ASSERT_EQ(RenderProcessHostImpl::ShouldDelayProcessShutdown(),
subframe_process_id == new_rfh_b->GetProcess()->GetDeprecatedID());
// The process should no longer be in the pending-delete tracker, as it has
// been reused.
if (RenderProcessHostImpl::ShouldDelayProcessShutdown()) {
ASSERT_FALSE(static_cast<RenderProcessHostImpl*>(
content::RenderProcessHost::FromID(subframe_process_id))
->IsProcessShutdownDelayedForTesting());
}
}
// Renderer process reuse with empty available renderers tests. Feature flag
// kTrackEmptyRendererProcessesForReuse controls enablement.
class RenderFrameHostImplReuseEmptyAvailableRenderBrowserTest
: public RenderFrameHostImplBrowserTest {
public:
RenderFrameHostImplReuseEmptyAvailableRenderBrowserTest() {
scoped_feature_list_.InitAndEnableFeature(
features::kTrackEmptyRendererProcessesForReuse);
}
void SetUpCommandLine(base::CommandLine* command_line) override {
RenderFrameHostImplBrowserTest::SetUpCommandLine(command_line);
IsolateAllSitesForTesting(base::CommandLine::ForCurrentProcess());
}
protected:
base::test::ScopedFeatureList scoped_feature_list_;
};
#if !BUILDFLAG(IS_ANDROID)
IN_PROC_BROWSER_TEST_F(RenderFrameHostImplReuseEmptyAvailableRenderBrowserTest,
ReuseEmptyAvailableRenderForMainFrame) {
// The test assumes that the main frame RFH will be reused when navigating.
DisableBackForwardCacheForTesting(shell()->web_contents(),
BackForwardCache::TEST_REQUIRES_NO_CACHING);
const GURL url_a(embedded_test_server()->GetURL("a.com", "/title1.html"));
const GURL url_b(embedded_test_server()->GetURL("b.com", "/title1.html"));
EXPECT_TRUE(NavigateToURL(shell(), url_a));
auto* first_navigation_rph =
shell()->web_contents()->GetPrimaryMainFrame()->GetProcess();
// Normally, a policy above //content (e.g., KeepAliveDSEPolicy, like via
// SetDSEKeepAlive()) might keep an empty process alive using
// IncrementPendingReuseRefCount(). This emulates such a policy directly and
// force the renderer process to remain alive for reuse.
first_navigation_rph->IncrementPendingReuseRefCount();
EXPECT_EQ(1, first_navigation_rph->GetPendingReuseRefCountForTesting());
EXPECT_TRUE(first_navigation_rph->IsInitializedAndNotDead());
// Navigate to a different page.
EXPECT_TRUE(NavigateToURL(shell(), url_b));
auto* second_navigation_rph =
shell()->web_contents()->GetPrimaryMainFrame()->GetProcess();
EXPECT_NE(first_navigation_rph->GetID(), second_navigation_rph->GetID());
// Make sure the initial renderer is still available.
EXPECT_EQ(1, first_navigation_rph->GetPendingReuseRefCountForTesting());
// Navigate back to the initial page should take the empty renderer process
// being kept alive from the first navigation.
EXPECT_TRUE(NavigateToURL(shell(), url_a));
auto* third_navigation_rph =
shell()->web_contents()->GetPrimaryMainFrame()->GetProcess();
EXPECT_EQ(first_navigation_rph->GetID(), third_navigation_rph->GetID());
}
#endif
#if BUILDFLAG(IS_ANDROID)
// On Android, the OS can kill the renderer process at any point without the
// browser's control. Therefore, the Android version of the test below cannot
// guarantee that the original process will still be alive and available for
// reuse. It checks if it's still alive; if so, it should be reused. If not,
// a new process will be created, which is also acceptable. This is different
// from the Desktop scenario where the browser has more control over the process
// lifecycle.
// TODO(crbug.com/405884216): Very flaky on multiple bots.
IN_PROC_BROWSER_TEST_F(
RenderFrameHostImplReuseEmptyAvailableRenderBrowserTest,
DISABLED_ReuseEmptyAvailableRenderIfAvailableForMainFrame) {
// The test assumes that the main frame RFH will be reused when navigating.
DisableBackForwardCacheForTesting(shell()->web_contents(),
BackForwardCache::TEST_REQUIRES_NO_CACHING);
const GURL url_a(embedded_test_server()->GetURL("a.com", "/title1.html"));
const GURL url_b(embedded_test_server()->GetURL("b.com", "/title1.html"));
EXPECT_TRUE(NavigateToURL(shell(), url_a));
auto* first_navigation_rph =
shell()->web_contents()->GetPrimaryMainFrame()->GetProcess();
// Normally, a policy above //content (e.g., KeepAliveDSEPolicy, like via
// SetDSEKeepAlive()) might keep an empty process alive using
// IncrementPendingReuseRefCount(). This emulates such a policy directly and
// force the renderer process to remain alive for reuse.
first_navigation_rph->IncrementPendingReuseRefCount();
EXPECT_EQ(1, first_navigation_rph->GetPendingReuseRefCountForTesting());
EXPECT_TRUE(first_navigation_rph->IsInitializedAndNotDead());
// Navigate to a different page.
EXPECT_TRUE(NavigateToURL(shell(), url_b));
auto* second_navigation_rph =
shell()->web_contents()->GetPrimaryMainFrame()->GetProcess();
EXPECT_NE(first_navigation_rph->GetID(), second_navigation_rph->GetID());
// Make sure the initial renderer is still available.
EXPECT_EQ(1, first_navigation_rph->GetPendingReuseRefCountForTesting());
// Navigate back to the initial page should take the empty renderer process
// being kept alive from the first navigation.
EXPECT_TRUE(NavigateToURL(shell(), url_a));
auto* third_navigation_rph =
shell()->web_contents()->GetPrimaryMainFrame()->GetProcess();
if (first_navigation_rph->IsInitializedAndNotDead()) {
EXPECT_EQ(first_navigation_rph->GetID(), third_navigation_rph->GetID());
} else {
EXPECT_NE(first_navigation_rph->GetID(), third_navigation_rph->GetID());
}
}
#endif
// Test that multiple subframe-shutdown delays from the same source can be in
// effect, and that cancelling one delay does not cancel the others.
IN_PROC_BROWSER_TEST_F(RenderFrameHostImplSubframeReuseBrowserTest,
MultipleDelays) {
// This test exercises a scenario that's only possible with
// --site-per-process.
if (!AreAllSitesIsolatedForTesting())
return;
// Create a test RenderProcessHostImpl.
ASSERT_TRUE(NavigateToURL(shell(),
embedded_test_server()->GetURL(
"a.com", "/cross_site_iframe_factory.html?a")));
RenderFrameHostImpl* rfh = root_frame_host();
RenderProcessHostImpl* process =
static_cast<RenderProcessHostImpl*>(rfh->GetProcess());
EXPECT_FALSE(process->IsProcessShutdownDelayedForTesting());
// Delay process shutdown twice from the same site info.
const SiteInfo site_info = rfh->GetSiteInstance()->GetSiteInfo();
const base::TimeDelta delay = base::Seconds(5);
process->DelayProcessShutdown(delay, base::TimeDelta(), site_info);
EXPECT_EQ(RenderProcessHostImpl::ShouldDelayProcessShutdown(),
process->IsProcessShutdownDelayedForTesting());
process->DelayProcessShutdown(delay, base::TimeDelta(), site_info);
EXPECT_EQ(RenderProcessHostImpl::ShouldDelayProcessShutdown(),
process->IsProcessShutdownDelayedForTesting());
// When one delay is cancelled, the other should remain in effect.
process->CancelProcessShutdownDelay(site_info);
EXPECT_EQ(RenderProcessHostImpl::ShouldDelayProcessShutdown(),
process->IsProcessShutdownDelayedForTesting());
process->CancelProcessShutdownDelay(site_info);
EXPECT_FALSE(process->IsProcessShutdownDelayedForTesting());
}
// Tests that RenderFrameHostImpl::ForEachRenderFrameHostImpl visits the correct
// frames in the correct order.
IN_PROC_BROWSER_TEST_F(RenderFrameHostImplBrowserTest,
ForEachRenderFrameHostImpl) {
GURL url_a(embedded_test_server()->GetURL(
"a.com", "/cross_site_iframe_factory.html?a(b(c),d)"));
EXPECT_TRUE(NavigateToURL(shell(), url_a));
RenderFrameHostImpl* rfh_a = root_frame_host();
RenderFrameHostImpl* rfh_b = rfh_a->child_at(0)->current_frame_host();
RenderFrameHostImpl* rfh_c = rfh_b->child_at(0)->current_frame_host();
RenderFrameHostImpl* rfh_d = rfh_a->child_at(1)->current_frame_host();
// When starting iteration from the primary frame, we should see the frame
// itself and its descendants in breadth first order.
EXPECT_THAT(CollectAllRenderFrameHosts(rfh_a),
testing::ElementsAre(rfh_a, rfh_b, rfh_d, rfh_c));
// When starting iteration from a subframe, only it and its descendants should
// be seen.
EXPECT_THAT(CollectAllRenderFrameHosts(rfh_b),
testing::ElementsAre(rfh_b, rfh_c));
// Test that iteration stops when requested.
{
std::vector<RenderFrameHostImpl*> visited_frames;
rfh_a->ForEachRenderFrameHostImplWithAction([&](RenderFrameHostImpl* rfh) {
visited_frames.push_back(rfh);
return RenderFrameHost::FrameIterationAction::kStop;
});
EXPECT_THAT(visited_frames, testing::ElementsAre(rfh_a));
}
{
std::vector<RenderFrameHostImpl*> visited_frames;
rfh_a->ForEachRenderFrameHostImplWithAction([&](RenderFrameHostImpl* rfh) {
visited_frames.push_back(rfh);
return RenderFrameHost::FrameIterationAction::kSkipChildren;
});
EXPECT_THAT(visited_frames, testing::ElementsAre(rfh_a));
}
// Now consider stopping or skipping children at |rfh_b|. If we skip children,
// we skip |rfh_c|, but not |rfh_d|. If we stop iteration, we skip both
// |rfh_c| and |rfh_d|.
{
std::vector<RenderFrameHostImpl*> visited_frames;
rfh_a->ForEachRenderFrameHostImplWithAction([&](RenderFrameHostImpl* rfh) {
visited_frames.push_back(rfh);
return rfh == rfh_b ? RenderFrameHost::FrameIterationAction::kStop
: RenderFrameHost::FrameIterationAction::kContinue;
});
EXPECT_THAT(visited_frames, testing::ElementsAre(rfh_a, rfh_b));
}
{
std::vector<RenderFrameHostImpl*> visited_frames;
rfh_a->ForEachRenderFrameHostImplWithAction([&](RenderFrameHostImpl* rfh) {
visited_frames.push_back(rfh);
return rfh == rfh_b ? RenderFrameHost::FrameIterationAction::kSkipChildren
: RenderFrameHost::FrameIterationAction::kContinue;
});
EXPECT_THAT(visited_frames, testing::ElementsAre(rfh_a, rfh_b, rfh_d));
}
EXPECT_EQ(nullptr, rfh_a->GetParentOrOuterDocument());
EXPECT_EQ(rfh_a, rfh_b->GetParentOrOuterDocument());
EXPECT_EQ(rfh_b, rfh_c->GetParentOrOuterDocument());
EXPECT_EQ(rfh_a, rfh_d->GetParentOrOuterDocument());
EXPECT_EQ(rfh_a, rfh_a->GetOutermostMainFrame());
EXPECT_EQ(rfh_a, rfh_b->GetOutermostMainFrame());
EXPECT_EQ(rfh_a, rfh_c->GetOutermostMainFrame());
EXPECT_EQ(rfh_a, rfh_d->GetOutermostMainFrame());
EXPECT_EQ(rfh_a, rfh_a->GetOutermostMainFrameOrEmbedder());
EXPECT_EQ(rfh_a, rfh_b->GetOutermostMainFrameOrEmbedder());
EXPECT_EQ(rfh_a, rfh_c->GetOutermostMainFrameOrEmbedder());
EXPECT_EQ(rfh_a, rfh_d->GetOutermostMainFrameOrEmbedder());
}
// Tests that RenderFrameHostImpl::ForEachRenderFrameHostImpl does not expose
// speculative RFHs, unless content internal code requests them.
IN_PROC_BROWSER_TEST_F(RenderFrameHostImplBrowserTest,
ForEachRenderFrameHostImplSpeculative) {
IsolateAllSitesForTesting(base::CommandLine::ForCurrentProcess());
GURL url_a(embedded_test_server()->GetURL("a.com", "/title1.html"));
GURL url_b(embedded_test_server()->GetURL("b.com", "/title1.html"));
EXPECT_TRUE(NavigateToURL(shell(), url_a));
RenderFrameHostImpl* rfh_a = root_frame_host();
EXPECT_EQ(LifecycleStateImpl::kActive, rfh_a->lifecycle_state());
TestNavigationManager nav_manager(web_contents(), url_b);
shell()->LoadURL(url_b);
nav_manager.WaitForSpeculativeRenderFrameHostCreation();
RenderFrameHostImpl* rfh_b =
rfh_a->frame_tree_node()->render_manager()->speculative_frame_host();
ASSERT_TRUE(rfh_b);
EXPECT_EQ(LifecycleStateImpl::kSpeculative, rfh_b->lifecycle_state());
// We test that the following properties hold during both the speculative and
// pending commit lifecycle state of |rfh_b|.
base::RepeatingClosure test_expectations = base::BindRepeating(
[](RenderFrameHostImpl* rfh_a, RenderFrameHostImpl* rfh_b) {
// ForEachRenderFrameHostImpl does not expose the speculative RFH.
EXPECT_THAT(CollectAllRenderFrameHosts(rfh_a),
testing::ElementsAre(rfh_a));
// When we request the speculative RFH, we visit it.
EXPECT_THAT(CollectAllRenderFrameHostsIncludingSpeculative(rfh_a),
testing::UnorderedElementsAre(rfh_a, rfh_b));
// If ForEachRenderFrameHostImpl is called on a speculative RFH
// directly, do nothing.
rfh_b->ForEachRenderFrameHostImplWithAction(
[](RenderFrameHostImpl* rfh) {
ADD_FAILURE() << "Visited speculative RFH";
return RenderFrameHost::FrameIterationAction::kStop;
});
// If we request speculative RFHs and directly call this on a
// speculative RFH, just visit the given speculative RFH.
EXPECT_THAT(CollectAllRenderFrameHostsIncludingSpeculative(rfh_b),
testing::ElementsAre(rfh_b));
},
rfh_a, rfh_b);
{
SCOPED_TRACE("Speculative LifecycleState");
test_expectations.Run();
}
class ReadyToCommitObserver : public WebContentsObserver {
public:
explicit ReadyToCommitObserver(WebContentsImpl* web_contents,
base::RepeatingClosure test_expectations)
: WebContentsObserver(web_contents),
test_expectations_(test_expectations) {}
// WebContentsObserver:
void ReadyToCommitNavigation(NavigationHandle* navigation_handle) override {
EXPECT_EQ(static_cast<RenderFrameHostImpl*>(
navigation_handle->GetRenderFrameHost())
->lifecycle_state(),
LifecycleStateImpl::kPendingCommit);
SCOPED_TRACE("PendingCommit LifecycleState");
test_expectations_.Run();
}
private:
base::RepeatingClosure test_expectations_;
};
ReadyToCommitObserver ready_to_commit_observer(web_contents(),
test_expectations);
ASSERT_TRUE(nav_manager.WaitForNavigationFinished());
}
// Like ForEachRenderFrameHostImplSpeculative, but for a speculative RFH for a
// subframe navigation.
IN_PROC_BROWSER_TEST_F(RenderFrameHostImplBrowserTest,
ForEachRenderFrameHostImplSpeculativeWithSubframes) {
IsolateAllSitesForTesting(base::CommandLine::ForCurrentProcess());
GURL url_a(embedded_test_server()->GetURL(
"a.com", "/cross_site_iframe_factory.html?a(b(c))"));
GURL url_d(embedded_test_server()->GetURL("d.com", "/title1.html"));
EXPECT_TRUE(NavigateToURL(shell(), url_a));
RenderFrameHostImpl* rfh_a = root_frame_host();
RenderFrameHostImpl* rfh_b = rfh_a->child_at(0)->current_frame_host();
RenderFrameHostImpl* rfh_c = rfh_b->child_at(0)->current_frame_host();
EXPECT_EQ(LifecycleStateImpl::kActive, rfh_a->lifecycle_state());
EXPECT_EQ(LifecycleStateImpl::kActive, rfh_b->lifecycle_state());
EXPECT_EQ(LifecycleStateImpl::kActive, rfh_c->lifecycle_state());
TestNavigationManager nav_manager(web_contents(), url_d);
ASSERT_TRUE(BeginNavigateToURLFromRenderer(rfh_b, url_d));
nav_manager.WaitForSpeculativeRenderFrameHostCreation();
RenderFrameHostImpl* rfh_d =
rfh_b->frame_tree_node()->render_manager()->speculative_frame_host();
ASSERT_TRUE(rfh_d);
EXPECT_EQ(LifecycleStateImpl::kSpeculative, rfh_d->lifecycle_state());
// ForEachRenderFrameHostImpl does not expose the speculative RFH.
EXPECT_THAT(CollectAllRenderFrameHosts(rfh_a),
testing::ElementsAre(rfh_a, rfh_b, rfh_c));
// When we request the speculative RFH, we visit it.
EXPECT_THAT(CollectAllRenderFrameHostsIncludingSpeculative(rfh_a),
testing::UnorderedElementsAre(rfh_a, rfh_b, rfh_d, rfh_c));
// When beginning iteration from the current RFH of the navigating frame, we
// also visit the speculative RFH.
EXPECT_THAT(CollectAllRenderFrameHostsIncludingSpeculative(rfh_b),
testing::UnorderedElementsAre(rfh_b, rfh_d, rfh_c));
// If ForEachRenderFrameHostImpl is called on a speculative RFH directly, do
// nothing.
rfh_d->ForEachRenderFrameHostImplWithAction([](RenderFrameHostImpl* rfh) {
ADD_FAILURE() << "Visited speculative RFH";
return RenderFrameHost::FrameIterationAction::kStop;
});
// If we request speculative RFHs and directly call this on a speculative RFH,
// just visit the given speculative RFH.
EXPECT_THAT(CollectAllRenderFrameHostsIncludingSpeculative(rfh_d),
testing::ElementsAre(rfh_d));
// Test that iteration stops when requested.
{
// We don't check the RFHs visited in the interest of not overtesting the
// ordering of speculative RFHs.
bool stopped = false;
rfh_a->ForEachRenderFrameHostImplIncludingSpeculativeWithAction(
[&](RenderFrameHostImpl* rfh) {
EXPECT_FALSE(stopped);
if (rfh->lifecycle_state() == LifecycleStateImpl::kSpeculative) {
stopped = true;
return RenderFrameHost::FrameIterationAction::kStop;
}
return RenderFrameHost::FrameIterationAction::kContinue;
});
}
{
bool stopped = false;
rfh_b->ForEachRenderFrameHostImplIncludingSpeculativeWithAction(
[&](RenderFrameHostImpl* rfh) {
EXPECT_FALSE(stopped);
if (rfh->lifecycle_state() == LifecycleStateImpl::kSpeculative) {
stopped = true;
return RenderFrameHost::FrameIterationAction::kStop;
}
return RenderFrameHost::FrameIterationAction::kContinue;
});
}
// Skipping the children of a current RFH whose FrameTreeNode has a
// speculative RFH skips the children but still includes the speculative RFH.
{
std::vector<RenderFrameHostImpl*> visited_frames;
rfh_a->ForEachRenderFrameHostImplIncludingSpeculativeWithAction(
[&](RenderFrameHostImpl* rfh) {
visited_frames.push_back(rfh);
return (rfh == rfh_b)
? RenderFrameHost::FrameIterationAction::kSkipChildren
: RenderFrameHost::FrameIterationAction::kContinue;
});
EXPECT_THAT(visited_frames,
testing::UnorderedElementsAre(rfh_a, rfh_b, rfh_d));
}
{
std::vector<RenderFrameHostImpl*> visited_frames;
rfh_b->ForEachRenderFrameHostImplIncludingSpeculativeWithAction(
[&](RenderFrameHostImpl* rfh) {
visited_frames.push_back(rfh);
return (rfh == rfh_b)
? RenderFrameHost::FrameIterationAction::kSkipChildren
: RenderFrameHost::FrameIterationAction::kContinue;
});
EXPECT_THAT(visited_frames, testing::UnorderedElementsAre(rfh_b, rfh_d));
}
// Skipping the children of a speculative RFH is not useful, but is included
// here for completeness of testing.
{
std::vector<RenderFrameHostImpl*> visited_frames;
rfh_a->ForEachRenderFrameHostImplIncludingSpeculativeWithAction(
[&](RenderFrameHostImpl* rfh) {
visited_frames.push_back(rfh);
return (rfh->lifecycle_state() == LifecycleStateImpl::kSpeculative)
? RenderFrameHost::FrameIterationAction::kSkipChildren
: RenderFrameHost::FrameIterationAction::kContinue;
});
EXPECT_THAT(visited_frames,
testing::UnorderedElementsAre(rfh_a, rfh_b, rfh_d, rfh_c));
}
{
std::vector<RenderFrameHostImpl*> visited_frames;
rfh_b->ForEachRenderFrameHostImplIncludingSpeculativeWithAction(
[&](RenderFrameHostImpl* rfh) {
visited_frames.push_back(rfh);
return (rfh->lifecycle_state() == LifecycleStateImpl::kSpeculative)
? RenderFrameHost::FrameIterationAction::kSkipChildren
: RenderFrameHost::FrameIterationAction::kContinue;
});
EXPECT_THAT(visited_frames,
testing::UnorderedElementsAre(rfh_b, rfh_d, rfh_c));
}
}
IN_PROC_BROWSER_TEST_F(RenderFrameHostImplBrowserTest,
ForEachRenderFrameHostImplPendingDeletion) {
GURL url_a(embedded_test_server()->GetURL(
"a.com", "/cross_site_iframe_factory.html?a(b(c))"));
GURL url_d(embedded_test_server()->GetURL("d.com", "/title1.html"));
EXPECT_TRUE(NavigateToURL(shell(), url_a));
RenderFrameHostImpl* rfh_a = root_frame_host();
RenderFrameHostImpl* rfh_b = rfh_a->child_at(0)->current_frame_host();
RenderFrameHostImpl* rfh_c = rfh_b->child_at(0)->current_frame_host();
EXPECT_EQ(LifecycleStateImpl::kActive, rfh_a->lifecycle_state());
EXPECT_EQ(LifecycleStateImpl::kActive, rfh_b->lifecycle_state());
EXPECT_EQ(LifecycleStateImpl::kActive, rfh_c->lifecycle_state());
LeaveInPendingDeletionState(rfh_a);
LeaveInPendingDeletionState(rfh_b);
LeaveInPendingDeletionState(rfh_c);
EXPECT_TRUE(NavigateToURL(shell(), url_d));
RenderFrameHostImpl* rfh_d = root_frame_host();
// ForEachRenderFrameHostImpl on the primary RFH does not visit the pending
// delete RFHs.
EXPECT_THAT(CollectAllRenderFrameHosts(rfh_d), testing::ElementsAre(rfh_d));
// ForEachRenderFrameHostImpl on the pending delete RFHs only visits the
// pendingdelete RFHs.
EXPECT_THAT(CollectAllRenderFrameHosts(rfh_a),
testing::ElementsAre(rfh_a, rfh_b, rfh_c));
EXPECT_THAT(CollectAllRenderFrameHosts(rfh_b),
testing::ElementsAre(rfh_b, rfh_c));
}
// Tests that RenderFrameHostImpl::ForEachRenderFrameHostImpl visits the frames
// of an inner WebContents.
IN_PROC_BROWSER_TEST_F(RenderFrameHostImplBrowserTest,
ForEachRenderFrameHostImplInnerContents) {
GURL url_a(embedded_test_server()->GetURL("a.com", "/page_with_iframe.html"));
GURL url_b(embedded_test_server()->GetURL("b.com", "/title1.html"));
EXPECT_TRUE(NavigateToURL(shell(), url_a));
RenderFrameHostImpl* rfh_a = root_frame_host();
WebContentsImpl* inner_contents = static_cast<WebContentsImpl*>(
CreateAndAttachInnerContents(rfh_a->child_at(0)->current_frame_host()));
ASSERT_TRUE(NavigateToURLFromRenderer(inner_contents, url_b));
RenderFrameHostImpl* rfh_b = inner_contents->GetPrimaryMainFrame();
EXPECT_THAT(CollectAllRenderFrameHosts(rfh_a),
testing::ElementsAre(rfh_a, rfh_b));
EXPECT_EQ(nullptr, rfh_b->GetParent());
// Note that since this is a generic test inner WebContents, whether it's
// considered an outer document or embedder is just an implementation detail.
EXPECT_EQ(nullptr, rfh_b->GetParentOrOuterDocument());
EXPECT_EQ(rfh_b, rfh_b->GetOutermostMainFrame());
EXPECT_EQ(rfh_a, rfh_b->GetParentOrOuterDocumentOrEmbedder());
EXPECT_EQ(rfh_a, rfh_b->GetOutermostMainFrameOrEmbedder());
}
IN_PROC_BROWSER_TEST_F(RenderFrameHostImplBrowserTest,
ForEachRenderFrameHostImplInnerContentsWithSubframes) {
GURL url_a(embedded_test_server()->GetURL(
"a.com", "/cross_site_iframe_factory.html?a(a(a),a)"));
GURL url_b(embedded_test_server()->GetURL(
"b.com", "/cross_site_iframe_factory.html?b(c(d),e)"));
EXPECT_TRUE(NavigateToURL(shell(), url_a));
RenderFrameHostImpl* rfh_a_main = root_frame_host();
RenderFrameHostImpl* rfh_a_sub1 =
rfh_a_main->child_at(0)->current_frame_host();
RenderFrameHostImpl* rfh_a_sub2 =
rfh_a_main->child_at(1)->current_frame_host();
WebContentsImpl* inner_contents =
static_cast<WebContentsImpl*>(CreateAndAttachInnerContents(
rfh_a_sub1->child_at(0)->current_frame_host()));
ASSERT_TRUE(NavigateToURLFromRenderer(inner_contents, url_b));
RenderFrameHostImpl* rfh_b = inner_contents->GetPrimaryMainFrame();
RenderFrameHostImpl* rfh_c = rfh_b->child_at(0)->current_frame_host();
RenderFrameHostImpl* rfh_d = rfh_c->child_at(0)->current_frame_host();
RenderFrameHostImpl* rfh_e = rfh_b->child_at(1)->current_frame_host();
EXPECT_THAT(CollectAllRenderFrameHosts(rfh_a_main),
testing::ElementsAre(rfh_a_main, rfh_a_sub1, rfh_a_sub2, rfh_b,
rfh_c, rfh_e, rfh_d));
}
IN_PROC_BROWSER_TEST_F(RenderFrameHostImplBrowserTest,
ForEachRenderFrameHostImplMultipleInnerContents) {
// After attaching inner contents, this will be A(B(C),D)
GURL url_a(embedded_test_server()->GetURL(
"a.com", "/cross_site_iframe_factory.html?a(a,a)"));
GURL url_b(embedded_test_server()->GetURL(
"b.com", "/cross_site_iframe_factory.html?b(b)"));
GURL url_c(embedded_test_server()->GetURL("c.com", "/title1.html"));
GURL url_d(embedded_test_server()->GetURL("d.com", "/title1.html"));
EXPECT_TRUE(NavigateToURL(shell(), url_a));
RenderFrameHostImpl* rfh_a = root_frame_host();
WebContentsImpl* contents_b = static_cast<WebContentsImpl*>(
CreateAndAttachInnerContents(rfh_a->child_at(0)->current_frame_host()));
ASSERT_TRUE(NavigateToURLFromRenderer(contents_b, url_b));
RenderFrameHostImpl* rfh_b = contents_b->GetPrimaryMainFrame();
WebContentsImpl* contents_c = static_cast<WebContentsImpl*>(
CreateAndAttachInnerContents(rfh_b->child_at(0)->current_frame_host()));
ASSERT_TRUE(NavigateToURLFromRenderer(contents_c, url_c));
RenderFrameHostImpl* rfh_c = contents_c->GetPrimaryMainFrame();
WebContentsImpl* contents_d = static_cast<WebContentsImpl*>(
CreateAndAttachInnerContents(rfh_a->child_at(1)->current_frame_host()));
ASSERT_TRUE(NavigateToURLFromRenderer(contents_d, url_d));
RenderFrameHostImpl* rfh_d = contents_d->GetPrimaryMainFrame();
EXPECT_THAT(CollectAllRenderFrameHosts(rfh_a),
testing::ElementsAre(rfh_a, rfh_b, rfh_d, rfh_c));
}
// This test verifies that RFHImpl::ForEachImmediateLocalRoot works as expected.
// The frame tree used in the test is:
// A0
// / | \
// A1 B1 A2
// / \ | / \
// B2 A3 B3 A4 C2
// / / / \ \
// D1 D2 C3 C4 C5
//
// As an example, the expected set of immediate local roots for the root node A0
// should be {B1, B2, C2, D2, C5}. Note that the order is compatible with that
// of a BFS traversal from root node A0.
IN_PROC_BROWSER_TEST_F(RenderFrameHostImplBrowserTest,
FindImmediateLocalRoots) {
IsolateAllSitesForTesting(base::CommandLine::ForCurrentProcess());
GURL main_url(embedded_test_server()->GetURL(
"a.com",
"/cross_site_iframe_factory.html?a(a(b(d),a(d)),b(b(c,c)),a(a(c),c))"));
EXPECT_TRUE(NavigateToURL(shell(), main_url));
// Each entry is of the frame "LABEL:ILR1ILR2..." where ILR stands for
// immediate local root.
const auto immediate_local_roots = std::to_array<std::string>(
{"A0:B1B2C2D2C5", "A1:B2D2", "B1:C3C4", "A2:C2C5", "B2:D1", "A3:D2",
"B3:C3C4", "A4:C5", "C2:", "D1:", "D2:", "C3:", "C4:", "C5:"});
std::map<RenderFrameHostImpl*, std::string>
frame_to_immediate_local_roots_map;
std::map<RenderFrameHostImpl*, std::string> frame_to_label_map;
size_t index = 0;
// Map each RenderFrameHostImpl to its label and set of immediate local roots.
for (auto* ftn : web_contents()->GetPrimaryFrameTree().Nodes()) {
std::string roots = immediate_local_roots[index++];
frame_to_immediate_local_roots_map[ftn->current_frame_host()] = roots;
frame_to_label_map[ftn->current_frame_host()] = roots.substr(0, 2);
}
// For each frame in the tree, verify that ForEachImmediateLocalRoot properly
// visits each and only each immediate local root in a BFS traversal order.
for (auto* ftn : web_contents()->GetPrimaryFrameTree().Nodes()) {
RenderFrameHostImpl* current_frame_host = ftn->current_frame_host();
std::vector<RenderFrameHostImpl*> frame_list;
current_frame_host->ForEachImmediateLocalRoot(
[&frame_list](RenderFrameHostImpl* rfh) { frame_list.push_back(rfh); });
std::string result = frame_to_label_map[current_frame_host];
result.append(":");
for (auto* ilr_ptr : frame_list)
result.append(frame_to_label_map[ilr_ptr]);
EXPECT_EQ(frame_to_immediate_local_roots_map[current_frame_host], result);
}
}
IN_PROC_BROWSER_TEST_F(RenderFrameHostImplBrowserTest, GetSiblings) {
IsolateAllSitesForTesting(base::CommandLine::ForCurrentProcess());
// Use actual FrameTreeNode id values in URL.
GURL main_url(embedded_test_server()->GetURL(
"1.com", "/cross_site_iframe_factory.html?1(2,3(5),4)"));
EXPECT_TRUE(NavigateToURL(shell(), main_url));
FrameTreeNode* ftn1 = web_contents()->GetPrimaryFrameTree().root();
FrameTreeNode* ftn2 = ftn1->child_at(0);
FrameTreeNode* ftn3 = ftn1->child_at(1);
FrameTreeNode* ftn4 = ftn1->child_at(2);
FrameTreeNode* ftn5 = ftn3->child_at(0);
// Check root node.
EXPECT_EQ(ftn1->current_frame_host()->NextSibling(), nullptr);
EXPECT_EQ(ftn1->current_frame_host()->PreviousSibling(), nullptr);
// Check first child of root (leaf node).
EXPECT_EQ(ftn2->current_frame_host()->NextSibling(), ftn3);
EXPECT_EQ(ftn2->current_frame_host()->PreviousSibling(), nullptr);
// Check second child of root (has child).
EXPECT_EQ(ftn3->current_frame_host()->NextSibling(), ftn4);
EXPECT_EQ(ftn3->current_frame_host()->PreviousSibling(), ftn2);
// Check third child of root (leaf).
EXPECT_EQ(ftn4->current_frame_host()->NextSibling(), nullptr);
EXPECT_EQ(ftn4->current_frame_host()->PreviousSibling(), ftn3);
// Check deepest node in tree (leaf with no siblings).
EXPECT_EQ(ftn5->current_frame_host()->NextSibling(), nullptr);
EXPECT_EQ(ftn5->current_frame_host()->PreviousSibling(), nullptr);
}
// Helpers for the DestructorLifetime test case.
class DestructorLifetimeDocumentService
// The interface in question doesn't really matter here, so just pick a
// generic one with an easy interface to stub.
: public DocumentService<blink::mojom::BrowserInterfaceBroker> {
public:
DestructorLifetimeDocumentService(
RenderFrameHostImpl& render_frame_host,
mojo::PendingReceiver<blink::mojom::BrowserInterfaceBroker> receiver,
bool& was_destroyed)
: DocumentService(render_frame_host, std::move(receiver)),
render_frame_host_(render_frame_host.GetWeakPtr()),
page_(render_frame_host.GetPage().GetWeakPtr()),
was_destroyed_(was_destroyed) {}
~DestructorLifetimeDocumentService() override {
*was_destroyed_ = true;
// The destructor should run before SafeRef<RenderFrameHost> is invalidated.
EXPECT_TRUE(render_frame_host_);
EXPECT_TRUE(page_);
}
void GetInterface(mojo::GenericPendingReceiver pending_receiver) override {}
private:
// This should be a SafeRef but that is not yet exposed publicly.
const base::WeakPtr<RenderFrameHostImpl> render_frame_host_;
const base::WeakPtr<Page> page_;
const raw_ref<bool> was_destroyed_;
};
class DestructorLifetimeDocumentUserData
: public DocumentUserData<DestructorLifetimeDocumentUserData> {
public:
explicit DestructorLifetimeDocumentUserData(
RenderFrameHost* render_frame_host,
bool& was_destroyed)
: DocumentUserData<DestructorLifetimeDocumentUserData>(render_frame_host),
render_frame_host_(
static_cast<RenderFrameHostImpl*>(render_frame_host)->GetWeakPtr()),
page_(render_frame_host->GetPage().GetWeakPtr()),
was_destroyed_(was_destroyed) {}
~DestructorLifetimeDocumentUserData() override {
*was_destroyed_ = true;
// The destructor should run before SafeRef<RenderFrameHost> is invalidated.
EXPECT_TRUE(render_frame_host_);
EXPECT_TRUE(page_);
}
private:
friend DocumentUserData;
DOCUMENT_USER_DATA_KEY_DECL();
// This should be a SafeRef or use render_frame_host().
const base::WeakPtr<RenderFrameHostImpl> render_frame_host_;
const base::WeakPtr<Page> page_;
const raw_ref<bool> was_destroyed_;
};
DOCUMENT_USER_DATA_KEY_IMPL(DestructorLifetimeDocumentUserData);
// Tests that when RenderFrameHostImpl is destroyed, destructors of
// commonly-used extension points (currently DocumentService and
// DocumentUserData) run while RenderFrameHostImpl is still in a
// reasonable state.
IN_PROC_BROWSER_TEST_F(RenderFrameHostImplBrowserTest,
MainFrameSameSiteNavigationDestructorLifetime) {
// The test assumes that the main frame RFH will be reused when navigating.
DisableBackForwardCacheForTesting(shell()->web_contents(),
BackForwardCache::TEST_REQUIRES_NO_CACHING);
EXPECT_TRUE(NavigateToURL(
shell(), embedded_test_server()->GetURL("a.com", "/title1.html")));
RenderFrameHostImpl* main_frame = web_contents()->GetPrimaryMainFrame();
ASSERT_TRUE(main_frame);
bool document_service_was_destroyed = false;
mojo::Remote<blink::mojom::BrowserInterfaceBroker> remote;
// This is self-owned so the bare new is OK.
new DestructorLifetimeDocumentService(*main_frame,
remote.BindNewPipeAndPassReceiver(),
document_service_was_destroyed);
bool document_user_data_was_destroyed = false;
DestructorLifetimeDocumentUserData::CreateForCurrentDocument(
main_frame, document_user_data_was_destroyed);
RenderFrameHostWrapper main_frame_wrapper(main_frame);
ASSERT_FALSE(main_frame_wrapper.IsDestroyed());
// Perform a same-site navigation in the main frame.
EXPECT_TRUE(NavigateToURLFromRenderer(
main_frame, embedded_test_server()->GetURL("a.com", "/title2.html")));
// The navigation should reuse the same RenderFrameHost, except when
// RenderDocument is enabled.
if (ShouldCreateNewHostForAllFrames()) {
EXPECT_TRUE(main_frame_wrapper.WaitUntilRenderFrameDeleted());
} else {
EXPECT_EQ(web_contents()->GetPrimaryMainFrame(), main_frame_wrapper.get());
}
// The destructors of DestructorLifetimeDocumentService and
// DestructorLifetimeDocumentUserData also perform googletest
// assertions to validate invariants.
EXPECT_TRUE(document_service_was_destroyed);
EXPECT_TRUE(document_user_data_was_destroyed);
}
IN_PROC_BROWSER_TEST_F(RenderFrameHostImplBrowserTest,
MainFrameCrossSiteNavigationDestructorLifetime) {
// The test assumes that the main frame RFH will be replaced during
// navigation.
DisableBackForwardCacheForTesting(shell()->web_contents(),
BackForwardCache::TEST_REQUIRES_NO_CACHING);
// All sites must be isolated in order for the navigatino code to replace the
// navigated RFH.
IsolateAllSitesForTesting(base::CommandLine::ForCurrentProcess());
EXPECT_TRUE(NavigateToURL(
shell(), embedded_test_server()->GetURL("a.com", "/title1.html")));
RenderFrameHostImpl* main_frame = web_contents()->GetPrimaryMainFrame();
ASSERT_TRUE(main_frame);
bool document_service_was_destroyed = false;
mojo::Remote<blink::mojom::BrowserInterfaceBroker> remote;
// This is self-owned so the bare new is OK.
new DestructorLifetimeDocumentService(*main_frame,
remote.BindNewPipeAndPassReceiver(),
document_service_was_destroyed);
bool document_user_data_was_destroyed = false;
DestructorLifetimeDocumentUserData::CreateForCurrentDocument(
main_frame, document_user_data_was_destroyed);
RenderFrameHostWrapper main_frame_wrapper(main_frame);
ASSERT_FALSE(main_frame_wrapper.IsDestroyed());
// Perform a cross-site navigation in the main frame.
EXPECT_TRUE(NavigateToURLFromRenderer(
main_frame, embedded_test_server()->GetURL("b.com", "/title2.html")));
ASSERT_TRUE(main_frame_wrapper.WaitUntilRenderFrameDeleted());
// The destructors of DestructorLifetimeDocumentService and
// DestructorLifetimeDocumentUserData also perform googletest
// assertions to validate invariants.
EXPECT_TRUE(main_frame_wrapper.IsDestroyed());
EXPECT_TRUE(document_service_was_destroyed);
EXPECT_TRUE(document_user_data_was_destroyed);
}
IN_PROC_BROWSER_TEST_F(RenderFrameHostImplBrowserTest,
ChildFrameSameSiteNavigationDestructorLifetime) {
EXPECT_TRUE(NavigateToURL(
shell(), embedded_test_server()->GetURL(
"a.com", "/cross_site_iframe_factory.html?a(a)")));
RenderFrameHostImpl* child_frame =
static_cast<RenderFrameHostImpl*>(ChildFrameAt(shell(), 0));
ASSERT_TRUE(child_frame);
bool should_change_rfh =
child_frame->ShouldChangeRenderFrameHostOnSameSiteNavigation();
bool document_service_was_destroyed = false;
mojo::Remote<blink::mojom::BrowserInterfaceBroker> remote;
// This is self-owned so the bare new is OK.
new DestructorLifetimeDocumentService(*child_frame,
remote.BindNewPipeAndPassReceiver(),
document_service_was_destroyed);
bool document_user_data_was_destroyed = false;
DestructorLifetimeDocumentUserData::CreateForCurrentDocument(
child_frame, document_user_data_was_destroyed);
RenderFrameHostWrapper child_frame_wrapper(child_frame);
ASSERT_FALSE(child_frame_wrapper.IsDestroyed());
// Perform a same-site navigation in the child frame.
EXPECT_TRUE(NavigateToURLFromRenderer(
child_frame, embedded_test_server()->GetURL("a.com", "/title2.html")));
// The navigation should reuse the same RenderFrameHost, except when
// RenderDocument is enabled.
if (should_change_rfh) {
EXPECT_TRUE(child_frame_wrapper.WaitUntilRenderFrameDeleted());
} else {
EXPECT_EQ(ChildFrameAt(shell(), 0), child_frame_wrapper.get());
}
// The destructors of DestructorLifetimeDocumentService and
// DestructorLifetimeDocumentUserData also perform googletest
// assertions to validate invariants.
EXPECT_TRUE(document_service_was_destroyed);
EXPECT_TRUE(document_user_data_was_destroyed);
}
IN_PROC_BROWSER_TEST_F(RenderFrameHostImplBrowserTest,
ChildFrameCrossSiteNavigationDestructorLifetime) {
// All sites must be isolated in order for the navigatino code to replace the
// navigated RFH.
IsolateAllSitesForTesting(base::CommandLine::ForCurrentProcess());
EXPECT_TRUE(NavigateToURL(
shell(), embedded_test_server()->GetURL(
"a.com", "/cross_site_iframe_factory.html?a(a)")));
RenderFrameHostImpl* child_frame =
static_cast<RenderFrameHostImpl*>(ChildFrameAt(shell(), 0));
ASSERT_TRUE(child_frame);
bool document_service_was_destroyed = false;
mojo::Remote<blink::mojom::BrowserInterfaceBroker> remote;
// This is self-owned so the bare new is OK.
new DestructorLifetimeDocumentService(*child_frame,
remote.BindNewPipeAndPassReceiver(),
document_service_was_destroyed);
bool document_user_data_was_destroyed = false;
DestructorLifetimeDocumentUserData::CreateForCurrentDocument(
child_frame, document_user_data_was_destroyed);
RenderFrameHostWrapper child_frame_wrapper(child_frame);
ASSERT_FALSE(child_frame_wrapper.IsDestroyed());
// Perform a cross-site navigation in the child frame.
EXPECT_TRUE(NavigateToURLFromRenderer(
child_frame, embedded_test_server()->GetURL("b.com", "/title2.html")));
ASSERT_TRUE(child_frame_wrapper.WaitUntilRenderFrameDeleted());
// The destructors of DestructorLifetimeDocumentService and
// DestructorLifetimeDocumentUserData also perform googletest
// assertions to validate invariants.
EXPECT_TRUE(child_frame_wrapper.IsDestroyed());
EXPECT_TRUE(document_service_was_destroyed);
EXPECT_TRUE(document_user_data_was_destroyed);
}
IN_PROC_BROWSER_TEST_F(RenderFrameHostImplBrowserTest,
ChildFrameDetachDestructorLifetime) {
EXPECT_TRUE(NavigateToURL(
shell(), embedded_test_server()->GetURL(
"a.com", "/cross_site_iframe_factory.html?a(a)")));
RenderFrameHostImpl* child_frame =
static_cast<RenderFrameHostImpl*>(ChildFrameAt(shell(), 0));
ASSERT_TRUE(child_frame);
bool document_service_was_destroyed = false;
mojo::Remote<blink::mojom::BrowserInterfaceBroker> remote;
// This is self-owned so the bare new is OK.
new DestructorLifetimeDocumentService(*child_frame,
remote.BindNewPipeAndPassReceiver(),
document_service_was_destroyed);
bool document_user_data_was_destroyed = false;
DestructorLifetimeDocumentUserData::CreateForCurrentDocument(
child_frame, document_user_data_was_destroyed);
RenderFrameHostWrapper child_frame_wrapper(child_frame);
ASSERT_FALSE(child_frame_wrapper.IsDestroyed());
// Remove the child frame from the DOM, which destroys the RenderFrameHost.
EXPECT_TRUE(ExecJs(shell(), "document.querySelector('iframe').remove()"));
// The destructors of DestructorLifetimeDocumentService and
// DestructorLifetimeDocumentUserData also perform googletest
// assertions to validate invariants.
EXPECT_TRUE(child_frame_wrapper.IsDestroyed());
EXPECT_TRUE(document_service_was_destroyed);
EXPECT_TRUE(document_user_data_was_destroyed);
}
class DestructorLifetimePageUserData
: public PageUserData<DestructorLifetimePageUserData> {
public:
explicit DestructorLifetimePageUserData(Page& page, bool& was_destroyed)
: PageUserData<DestructorLifetimePageUserData>(page),
page_(page.GetWeakPtr()),
was_destroyed_(was_destroyed) {}
~DestructorLifetimePageUserData() override {
*was_destroyed_ = true;
// The destructor should run before WeakPtr<Page> is invalidated.
EXPECT_TRUE(page_);
if (!page_) {
return;
}
// Check Page is still accessible through RenderFrameHost::GetPage. Such
// access can happen in PageUserData implementations with a complicated
// destructor.
auto& render_frame_host = page_->GetMainDocument();
auto& page = render_frame_host.GetPage();
// Check returned Page reference is valid.
EXPECT_EQ(page_.get(), &page);
// The page is considered as primary if its RenderFrameHost is active. This
// will be true unless we changed RenderFrameHosts.
EXPECT_EQ(page.IsPrimary(), !ShouldCreateNewHostForAllFrames());
if (ShouldCreateNewHostForAllFrames()) {
EXPECT_EQ(render_frame_host.GetLifecycleState(),
RenderFrameHost::LifecycleState::kPendingDeletion);
}
}
private:
friend PageUserData;
PAGE_USER_DATA_KEY_DECL();
const base::WeakPtr<Page> page_;
const raw_ref<bool> was_destroyed_;
};
PAGE_USER_DATA_KEY_IMPL(DestructorLifetimePageUserData);
// Tests that when DocumentAssociatedData is destroyed, destructors of
// PageUserData run while Page and DocumentAssociatedData are still in a
// reasonable state.
IN_PROC_BROWSER_TEST_F(RenderFrameHostImplBrowserTest,
PageUserDataDestructorLifetime) {
// The test assumes that the Page will get destructed after navigation.
DisableBackForwardCacheForTesting(shell()->web_contents(),
BackForwardCache::TEST_REQUIRES_NO_CACHING);
EXPECT_TRUE(NavigateToURL(
shell(), embedded_test_server()->GetURL("a.com", "/title1.html")));
RenderFrameHostImpl* main_frame = web_contents()->GetPrimaryMainFrame();
ASSERT_TRUE(main_frame);
bool page_user_data_was_destroyed = false;
DestructorLifetimePageUserData::CreateForPage(main_frame->GetPage(),
page_user_data_was_destroyed);
RenderFrameHostWrapper main_frame_wrapper(main_frame);
ASSERT_FALSE(main_frame_wrapper.IsDestroyed());
// Perform a same-site navigation in the main frame.
EXPECT_TRUE(NavigateToURLFromRenderer(
main_frame, embedded_test_server()->GetURL("a.com", "/title2.html")));
// The navigation should reuse the same RenderFrameHost, except when
// RenderDocument is enabled.
if (ShouldCreateNewHostForAllFrames()) {
EXPECT_TRUE(main_frame_wrapper.WaitUntilRenderFrameDeleted());
} else {
EXPECT_EQ(web_contents()->GetPrimaryMainFrame(), main_frame_wrapper.get());
}
// The destructor of DestructorLifetimePageUserData also perform googletest
// assertions to validate invariants.
EXPECT_TRUE(page_user_data_was_destroyed);
}
class RenderFrameHostImplCredentiallessIframeBrowserTest
: public RenderFrameHostImplBrowserTest {
public:
void SetUpCommandLine(base::CommandLine* command_line) override {
RenderFrameHostImplBrowserTest::SetUpCommandLine(command_line);
// Enable parsing the iframe 'credentialless' attribute.
command_line->AppendSwitch(switches::kEnableBlinkTestFeatures);
}
};
// This test checks that the initial empty document in a credentialless iframe
// whose parent document is not credentialless is credentialless.
IN_PROC_BROWSER_TEST_F(RenderFrameHostImplCredentiallessIframeBrowserTest,
InitialEmptyDocumentInCredentiallessIframe) {
GURL main_url = embedded_test_server()->GetURL("/title1.html");
EXPECT_TRUE(NavigateToURL(shell(), main_url));
RenderFrameHostImpl* main_rfh = web_contents()->GetPrimaryMainFrame();
// Create an empty iframe
EXPECT_TRUE(ExecJs(main_rfh,
"let child = document.createElement('iframe');"
"child.credentialless = true;"
"document.body.appendChild(child);"));
WaitForLoadStop(web_contents());
EXPECT_FALSE(main_rfh->IsCredentialless());
EXPECT_EQ(false, EvalJs(main_rfh, "window.credentialless"));
EXPECT_FALSE(main_rfh->GetStorageKey().nonce().has_value());
EXPECT_EQ(1U, main_rfh->child_count());
EXPECT_TRUE(main_rfh->child_at(0)->Credentialless());
EXPECT_FALSE(main_rfh->child_at(0)->current_frame_host()->IsCredentialless());
EXPECT_EQ(true, EvalJs(main_rfh->child_at(0)->current_frame_host(),
"window.credentialless"));
EXPECT_FALSE(main_rfh->child_at(0)
->current_frame_host()
->GetStorageKey()
.nonce()
.has_value());
}
// Check that a page's credentialless_iframes_nonce is re-initialized after
// navigations.
IN_PROC_BROWSER_TEST_F(RenderFrameHostImplCredentiallessIframeBrowserTest,
NewCredentiallessNonceOnNavigation) {
GURL main_url = embedded_test_server()->GetURL("/title1.html");
EXPECT_TRUE(NavigateToURL(shell(), main_url));
base::UnguessableToken first_nonce =
web_contents()->GetPrimaryPage().credentialless_iframes_nonce();
EXPECT_TRUE(first_nonce);
// Same-document navigation does not change the nonce.
EXPECT_TRUE(NavigateToURL(shell(), main_url.Resolve("#here")));
EXPECT_EQ(first_nonce,
web_contents()->GetPrimaryPage().credentialless_iframes_nonce());
// Cross-document same-site navigation creates a new nonce.
EXPECT_TRUE(
NavigateToURL(shell(), embedded_test_server()->GetURL("/title2.html")));
base::UnguessableToken second_nonce =
web_contents()->GetPrimaryPage().credentialless_iframes_nonce();
EXPECT_TRUE(second_nonce);
EXPECT_NE(first_nonce, second_nonce);
// Cross-document cross-site navigation creates a new nonce.
EXPECT_TRUE(NavigateToURL(
shell(), embedded_test_server()->GetURL("b.com", "/title1.html")));
EXPECT_NE(first_nonce,
web_contents()->GetPrimaryPage().credentialless_iframes_nonce());
EXPECT_NE(second_nonce,
web_contents()->GetPrimaryPage().credentialless_iframes_nonce());
}
class RenderFrameHostImplCredentiallessIframeNikBrowserTest
: public RenderFrameHostImplCredentiallessIframeBrowserTest {
public:
RenderFrameHostImplCredentiallessIframeNikBrowserTest() {
scoped_feature_list_.InitAndEnableFeature(
net::features::kPartitionConnectionsByNetworkIsolationKey);
}
void SetUpOnMainThread() override {
alternate_test_server_ =
std::make_unique<net::test_server::EmbeddedTestServer>();
connection_tracker_ = std::make_unique<net::test_server::ConnectionTracker>(
alternate_test_server_.get());
alternate_test_server_->AddDefaultHandlers(GetTestDataFilePath());
ASSERT_TRUE(alternate_test_server_->Start());
RenderFrameHostImplCredentiallessIframeBrowserTest::SetUpOnMainThread();
}
void ResetNetworkState() {
auto* network_context = shell()
->web_contents()
->GetBrowserContext()
->GetDefaultStoragePartition()
->GetNetworkContext();
base::RunLoop close_all_connections_loop;
network_context->CloseAllConnections(
close_all_connections_loop.QuitClosure());
close_all_connections_loop.Run();
connection_tracker_->ResetCounts();
}
protected:
std::unique_ptr<net::test_server::ConnectionTracker> connection_tracker_;
std::unique_ptr<net::EmbeddedTestServer> alternate_test_server_;
private:
base::test::ScopedFeatureList scoped_feature_list_;
};
IN_PROC_BROWSER_TEST_F(RenderFrameHostImplCredentiallessIframeNikBrowserTest,
CredentiallessIframeHasPartitionedNetworkState) {
GURL main_url = embedded_test_server()->GetURL("/title1.html");
for (bool credentialless : {false, true}) {
SCOPED_TRACE(credentialless ? "credentialless iframe" : "normal iframe");
EXPECT_TRUE(NavigateToURL(shell(), main_url));
RenderFrameHostImpl* main_rfh = web_contents()->GetPrimaryMainFrame();
// Create an iframe.
EXPECT_TRUE(ExecJs(main_rfh,
JsReplace("let child = document.createElement('iframe');"
"child.src = $1;"
"child.credentialless = $2;"
"document.body.appendChild(child);",
main_url, credentialless)));
WaitForLoadStop(web_contents());
EXPECT_EQ(1U, main_rfh->child_count());
RenderFrameHostImpl* iframe = main_rfh->child_at(0)->current_frame_host();
EXPECT_EQ(credentialless, iframe->IsCredentialless());
EXPECT_EQ(credentialless, EvalJs(iframe, "window.credentialless"));
ResetNetworkState();
std::string main_url_origin = main_url.DeprecatedGetOriginAsURL().spec();
// Remove trailing '/'.
main_url_origin.pop_back();
GURL fetch_url = alternate_test_server_->GetURL(
"/set-header?"
"Access-Control-Allow-Credentials: true&"
"Access-Control-Allow-Origin: " +
main_url_origin);
// Preconnect a socket with the NetworkIsolationKey of the main frame.
shell()
->web_contents()
->GetBrowserContext()
->GetDefaultStoragePartition()
->GetNetworkContext()
->PreconnectSockets(1, fetch_url.DeprecatedGetOriginAsURL(),
network::mojom::CredentialsMode::kInclude,
main_rfh->GetIsolationInfoForSubresources()
.network_anonymization_key(),
net::MutableNetworkTrafficAnnotationTag(
TRAFFIC_ANNOTATION_FOR_TESTS),
std::nullopt, mojo::NullRemote());
connection_tracker_->WaitForAcceptedConnections(1);
EXPECT_EQ(1u, connection_tracker_->GetAcceptedSocketCount());
EXPECT_EQ(0u, connection_tracker_->GetReadSocketCount());
std::string fetch_resource = JsReplace(
"(async () => {"
" let resp = (await fetch($1, { credentials : 'include'}));"
" return resp.status; })();",
fetch_url);
EXPECT_EQ(200, EvalJs(iframe, fetch_resource));
// The normal iframe should reuse the preconnected socket, the
// credentialless iframe should open a new one.
if (!credentialless) {
EXPECT_EQ(1u, connection_tracker_->GetAcceptedSocketCount());
} else {
EXPECT_EQ(2u, connection_tracker_->GetAcceptedSocketCount());
}
EXPECT_EQ(1u, connection_tracker_->GetReadSocketCount());
}
}
IN_PROC_BROWSER_TEST_F(RenderFrameHostImplBrowserTest, ErrorDocuments) {
GURL main_url(embedded_test_server()->GetURL("a.com", "/empty.html"));
{
// Block the navigation.
std::unique_ptr<URLLoaderInterceptor> url_interceptor =
URLLoaderInterceptor::SetupRequestFailForURL(
main_url, net::ERR_BLOCKED_BY_CLIENT);
TestNavigationManager manager(web_contents(), main_url);
shell()->LoadURL(main_url);
ASSERT_TRUE(manager.WaitForNavigationFinished());
}
EXPECT_TRUE(web_contents()->GetPrimaryMainFrame()->IsErrorDocument());
// Reload with no blocking.
shell()->Reload();
EXPECT_TRUE(WaitForLoadStop(web_contents()));
EXPECT_FALSE(web_contents()->GetPrimaryMainFrame()->IsErrorDocument());
std::string script =
"let child = document.createElement('iframe');"
"child.src = $1;"
"document.body.appendChild(child);";
// Create an iframe.
EXPECT_TRUE(ExecJs(web_contents()->GetPrimaryMainFrame(),
JsReplace(script, "title1.html")));
EXPECT_TRUE(WaitForLoadStop(web_contents()));
{
// Block the navigation.
GURL child_url(embedded_test_server()->GetURL("a.com", "/title1.html"));
std::unique_ptr<URLLoaderInterceptor> url_interceptor =
URLLoaderInterceptor::SetupRequestFailForURL(
child_url, net::ERR_BLOCKED_BY_CLIENT);
// Create an iframe but block the navigation.
EXPECT_TRUE(ExecJs(web_contents()->GetPrimaryMainFrame(),
JsReplace(script, "title1.html")));
EXPECT_TRUE(WaitForLoadStop(web_contents()));
}
RenderFrameHostImpl* main_rfh = web_contents()->GetPrimaryMainFrame();
EXPECT_EQ(2U, main_rfh->child_count());
RenderFrameHost* child_a = main_rfh->child_at(0)->current_frame_host();
RenderFrameHost* child_b = main_rfh->child_at(1)->current_frame_host();
EXPECT_FALSE(web_contents()->GetPrimaryMainFrame()->IsErrorDocument());
EXPECT_FALSE(child_a->IsErrorDocument());
EXPECT_TRUE(child_b->IsErrorDocument());
}
// Tests that a popup that is opened by a subframe inherits the subframe's
// origin, instead of the main frame's origin.
// Regression test for https://crbug.com/1311820 and https://crbug.com/1291764.
IN_PROC_BROWSER_TEST_F(RenderFrameHostImplBrowserTest,
PopupOpenedBySubframeHasCorrectOrigin) {
GURL main_url(embedded_test_server()->GetURL(
"a.com", "/cross_site_iframe_factory.html?a(b)"));
// Navigate to a page with a cross-site iframe.
EXPECT_TRUE(NavigateToURL(shell(), main_url));
FrameTreeNode* root = web_contents()->GetPrimaryFrameTree().root();
FrameTreeNode* child = root->child_at(0);
// Verify that the main frame & subframe origin differs.
url::Origin a_origin = url::Origin::Create(main_url);
url::Origin b_origin = url::Origin::Create(child->current_url());
EXPECT_EQ(a_origin, root->current_frame_host()->GetLastCommittedOrigin());
EXPECT_EQ(b_origin, child->current_frame_host()->GetLastCommittedOrigin());
EXPECT_NE(a_origin, b_origin);
{
// From the subframe, open a popup that stays on the initial empty
// document.
WebContentsAddedObserver popup_observer;
ASSERT_TRUE(ExecJs(child, "var w = window.open('/nocontent');"));
WebContentsImpl* popup =
static_cast<WebContentsImpl*>(popup_observer.GetWebContents());
FrameTreeNode* popup_frame =
popup->GetPrimaryMainFrame()->frame_tree_node();
// The popup should inherit the subframe's origin. Before the fix for
// https://crbug.com/1311820, the popup used to inherit the main frame's
// origin instead.
EXPECT_EQ(b_origin,
popup_frame->current_frame_host()->GetLastCommittedOrigin());
EXPECT_EQ(b_origin.Serialize(), EvalJs(popup_frame, "self.origin"));
// Try calling document.open() on the popup from itself.
// This used to cause a renderer kill as the browser used to notice the
// current origin & process lock mismatched when the document.open()
// notification IPC arrives.
EXPECT_EQ(GURL("about:blank"), EvalJs(popup_frame, "location.href"));
EXPECT_TRUE(ExecJs(popup_frame, "document.open()"));
EXPECT_EQ(GURL("about:blank"), EvalJs(popup_frame, "location.href"));
// Try updating the URL of the popup to the opener subframe's URL by
// calling document.open() on the popup from the opener subframe.
// This used to cause a renderer kill as the browser used to expect that
// the popup frame can only update to URLs under `a_origin`, while the
// new URL is under `b_origin`. See also https://crbug.com/1291764.
EXPECT_TRUE(ExecJs(child, "w.document.open()"));
EXPECT_EQ(child->current_url().spec(),
EvalJs(popup_frame, "location.href"));
}
{
// From the subframe, open a popup that stays on the initial empty
// document, and specify 'noopener' to sever the opener relationship.
WebContentsAddedObserver popup_observer;
ASSERT_TRUE(
ExecJs(child, "var w = window.open('/nocontent', '', 'noopener');"));
WebContentsImpl* popup =
static_cast<WebContentsImpl*>(popup_observer.GetWebContents());
FrameTreeNode* popup_frame =
popup->GetPrimaryMainFrame()->frame_tree_node();
EXPECT_EQ(nullptr, EvalJs(popup_frame, "window.opener"));
// The popup should use a new opaque origin, instead of the subframe's
// origin.
EXPECT_NE(b_origin,
popup_frame->current_frame_host()->GetLastCommittedOrigin());
EXPECT_TRUE(
popup_frame->current_frame_host()->GetLastCommittedOrigin().opaque());
EXPECT_EQ("null", EvalJs(popup_frame, "self.origin"));
}
}
class ShouldShowLoadingUIDelegate : public WebContentsDelegate {
public:
void LoadingStateChanged(WebContents* source,
bool should_show_loading_ui) final {
is_loading_values_.push_back(source->IsLoading());
did_show_loading_ui_values_.push_back(should_show_loading_ui);
}
const std::vector<bool>& is_loading_values() { return is_loading_values_; }
const std::vector<bool>& did_show_loading_ui_values() {
return did_show_loading_ui_values_;
}
private:
std::vector<bool> is_loading_values_;
std::vector<bool> did_show_loading_ui_values_;
};
IN_PROC_BROWSER_TEST_F(RenderFrameHostImplBrowserTest,
NavigationApiInterceptsBrowserInitiatedSameDocument) {
GURL main_url = embedded_test_server()->GetURL("a.com", "/title1.html");
GURL same_doc_url = embedded_test_server()->GetURL("a.com", "/title1.html#a");
ASSERT_TRUE(NavigateToURL(shell(), main_url));
std::unique_ptr<ShouldShowLoadingUIDelegate> delegate =
std::make_unique<ShouldShowLoadingUIDelegate>();
web_contents()->SetDelegate(delegate.get());
EXPECT_TRUE(
ExecJs(web_contents(),
"navigation.onnavigate = e => e.intercept("
"{ handler: () => new Promise(r => setTimeout(r, 100)) })"));
ASSERT_TRUE(NavigateToURL(shell(), same_doc_url));
ASSERT_EQ(delegate->is_loading_values().size(), 3ul);
ASSERT_EQ(delegate->did_show_loading_ui_values().size(), 3ul);
// First LoadingStateChanged called: start for a browser-initiated
// same-document navigation. NavigationApi hasn't intercepted yet, so the
// default same-document behavior of not showing loading UI applies.
EXPECT_TRUE(delegate->is_loading_values()[0]);
EXPECT_FALSE(delegate->did_show_loading_ui_values()[0]);
// Navigation commits, and it's a NavigationApi intercept. The commit message
// will not trigger DidStartLoading() (because is_loading() is already
// true), but when StartLoadingForAsyncNavigationApiCommit() is called, a
// LoadingStateChanged to enable loading UI is fired.
EXPECT_TRUE(delegate->is_loading_values()[1]);
EXPECT_TRUE(delegate->did_show_loading_ui_values()[1]);
// Navigation completes.
EXPECT_FALSE(delegate->is_loading_values()[2]);
EXPECT_FALSE(delegate->did_show_loading_ui_values()[2]);
}
// Like NavigationApiInterceptsBrowserInitiatedSameDocument, but the navigation
// is fast enough that the browser never receives a
// StartLoadingForAsyncNavigationApiCommit message from the renderer.
IN_PROC_BROWSER_TEST_F(
RenderFrameHostImplBrowserTest,
NavigationApiInterceptsBrowserInitiatedSameDocumentFastHandler) {
GURL main_url = embedded_test_server()->GetURL("a.com", "/title1.html");
GURL same_doc_url = embedded_test_server()->GetURL("a.com", "/title1.html#a");
ASSERT_TRUE(NavigateToURL(shell(), main_url));
std::unique_ptr<ShouldShowLoadingUIDelegate> delegate =
std::make_unique<ShouldShowLoadingUIDelegate>();
web_contents()->SetDelegate(delegate.get());
// Intercept, but take only a short time to execute the handler.
// The renderer waits 50ms before sending a
// StartLoadingForAsyncNavigationApiCommit, and will not send it at all if,
// as in this case, the navigation completes before the timer fires.
EXPECT_TRUE(
ExecJs(web_contents(),
"navigation.onnavigate = e => e.intercept("
"{ handler: () => new Promise(r => setTimeout(r, 10)) })"));
ASSERT_TRUE(NavigateToURL(shell(), same_doc_url));
ASSERT_EQ(delegate->is_loading_values().size(), 2ul);
ASSERT_EQ(delegate->did_show_loading_ui_values().size(), 2ul);
// First LoadingStateChanged called: start for a browser-initiated
// same-document navigation. NavigationApi hasn't intercepted yet, so the
// default same-document behavior of not showing loading UI applies.
EXPECT_TRUE(delegate->is_loading_values()[0]);
EXPECT_FALSE(delegate->did_show_loading_ui_values()[0]);
// Next, the navigation will commit due to the intercept. The commit will not
// trigger DidStartLoading() (because is_loading() is already
// true), and the renderer will complete its navigation before it would have
// called StartLoadingForAsyncNavigationApiCommit(), so we never enable the
// loading UI.
// Navigation completes.
EXPECT_FALSE(delegate->is_loading_values()[1]);
EXPECT_FALSE(delegate->did_show_loading_ui_values()[1]);
}
// Ensure that navigating with a frame tree of A(B(A)) results in the right
// number of beforeunload messages sent.
IN_PROC_BROWSER_TEST_F(RenderFrameHostImplBeforeUnloadBrowserTest,
RendererInitiatedNavigationInABA) {
GURL main_url(embedded_test_server()->GetURL(
"a.com", "/cross_site_iframe_factory.html?a(b(a))"));
EXPECT_TRUE(NavigateToURL(shell(), main_url));
// Install a beforeunload handler to send a ping from both a's.
FrameTreeNode* root = web_contents()->GetPrimaryFrameTree().root();
InstallBeforeUnloadHandler(root->child_at(0)->child_at(0), SEND_PING);
// Disable beforeunload timer to prevent flakiness.
PrepContentsForBeforeUnloadTest(web_contents());
// Navigate the main frame.
DOMMessageQueue msg_queue(web_contents());
GURL new_url(embedded_test_server()->GetURL("c.com", "/title1.html"));
EXPECT_TRUE(NavigateToURL(shell(), new_url));
// We should have received one pings (for the grandchild 'a').
EXPECT_EQ(1, RetrievePingsFromMessageQueue(&msg_queue));
// We shouldn't have seen any beforeunload dialogs.
EXPECT_EQ(0, dialog_manager()->num_beforeunload_dialogs_seen());
}
class RenderFrameHostImplBrowserTestWithStoragePartitioning
: public RenderFrameHostImplBrowserTest,
public testing::WithParamInterface<bool> {
public:
RenderFrameHostImplBrowserTestWithStoragePartitioning() {
if (ThirdPartyStoragePartitioningEnabled()) {
scoped_feature_list_.InitAndEnableFeature(
net::features::kThirdPartyStoragePartitioning);
} else {
scoped_feature_list_.InitAndDisableFeature(
net::features::kThirdPartyStoragePartitioning);
}
}
bool ThirdPartyStoragePartitioningEnabled() { return GetParam(); }
private:
base::test::ScopedFeatureList scoped_feature_list_;
};
INSTANTIATE_TEST_SUITE_P(
All,
RenderFrameHostImplBrowserTestWithStoragePartitioning,
/*third_party_storage_partitioning_enabled*/ testing::Bool());
IN_PROC_BROWSER_TEST_P(RenderFrameHostImplBrowserTestWithStoragePartitioning,
RenderIframeWithHostPermissionsToChildFrame) {
GURL main_url(embedded_test_server()->GetURL(
"a.com", "/cross_site_iframe_factory.html?a(b(a))"));
GURL child_rfh_url(embedded_test_server()->GetURL(
"b.com", "/cross_site_iframe_factory.html?b(a())"));
GURL grandchild_rfh_url(embedded_test_server()->GetURL(
"a.com", "/cross_site_iframe_factory.html?a()"));
EXPECT_TRUE(NavigateToURL(shell(), main_url));
RenderFrameHostImpl* root_rfh = web_contents()->GetPrimaryMainFrame();
RenderFrameHostImpl* child_rfh_1 =
root_rfh->child_at(0)->current_frame_host();
RenderFrameHostImpl* grandchild_rfh_1 =
child_rfh_1->child_at(0)->current_frame_host();
// Check root document setup. The StorageKey at the root should be the same
// regardless of if `kThirdPartyStoragePartitioning` is enabled.
EXPECT_EQ(blink::StorageKey::CreateFirstParty(url::Origin::Create(main_url)),
root_rfh->GetStorageKey());
// child_rfh_1 should have a StorageKey of a.com + b.com when
// `kThirdPartyStoragePartitioning` is enabled and there are no host
// permissions set.
if (ThirdPartyStoragePartitioningEnabled()) {
EXPECT_EQ(blink::StorageKey::Create(
url::Origin::Create(child_rfh_url),
net::SchemefulSite(root_rfh->GetLastCommittedOrigin()),
blink::mojom::AncestorChainBit::kCrossSite),
child_rfh_1->GetStorageKey());
EXPECT_EQ(blink::StorageKey::Create(
url::Origin::Create(grandchild_rfh_url),
net::SchemefulSite(root_rfh->GetLastCommittedOrigin()),
blink::mojom::AncestorChainBit::kCrossSite),
grandchild_rfh_1->GetStorageKey());
} else {
// When `kThirdPartyStoragePartitioning` is disabled, the child and
// grandchild document's storage key should depend only on their own origin
// regardless of host permissions.
EXPECT_EQ(
blink::StorageKey::CreateFirstParty(url::Origin::Create(child_rfh_url)),
child_rfh_1->GetStorageKey());
EXPECT_EQ(blink::StorageKey::CreateFirstParty(
url::Origin::Create(grandchild_rfh_url)),
grandchild_rfh_1->GetStorageKey());
}
// Give host permissions for b.com (child_rfh) to a.com (root_rfh).
{
std::vector<network::mojom::CorsOriginPatternPtr> patterns;
base::RunLoop run_loop;
patterns.push_back(network::mojom::CorsOriginPattern::New(
"http", "b.com", 0,
network::mojom::CorsDomainMatchMode::kAllowSubdomains,
network::mojom::CorsPortMatchMode::kAllowAnyPort,
network::mojom::CorsOriginAccessMatchPriority::kDefaultPriority));
CorsOriginPatternSetter::Set(
root_rfh->GetBrowserContext(), root_rfh->GetLastCommittedOrigin(),
std::move(patterns), {}, run_loop.QuitClosure());
run_loop.Run();
}
// Navigate main host to re-calculate StorageKey calculation.
EXPECT_TRUE(NavigateToURL(shell(), main_url));
root_rfh = web_contents()->GetPrimaryMainFrame();
RenderFrameHostImpl* child_rfh_2 =
root_rfh->child_at(0)->current_frame_host();
RenderFrameHostImpl* grandchild_rfh_2 =
child_rfh_2->child_at(0)->current_frame_host();
// root_rfh's storage key should not have changed.
EXPECT_EQ(blink::StorageKey::CreateFirstParty(url::Origin::Create(main_url)),
root_rfh->GetStorageKey());
if (ThirdPartyStoragePartitioningEnabled()) {
// When `kThirdPartyStoragePartitioning` is enabled, the child rfh should
// now have a top level StorageKey because it is the direct child of the
// root document and the root has host permissions to it.
EXPECT_EQ(blink::StorageKey(blink::StorageKey::Create(
url::Origin::Create(child_rfh_url),
net::SchemefulSite(url::Origin::Create(child_rfh_url)),
blink::mojom::AncestorChainBit::kSameSite)),
child_rfh_2->GetStorageKey());
// The grandchild document should create a StorageKey using the child
// document's origin as the top level site.
EXPECT_EQ(blink::StorageKey::Create(
url::Origin::Create(grandchild_rfh_url),
net::SchemefulSite(url::Origin::Create(child_rfh_url)),
blink::mojom::AncestorChainBit::kCrossSite),
grandchild_rfh_2->GetStorageKey());
} else {
// When `kThirdPartyStoragePartitioning` is disabled, the child and
// grandchild document's storage key should depend only on their own origin
// regardless of host permissions.
EXPECT_EQ(
blink::StorageKey::CreateFirstParty(url::Origin::Create(child_rfh_url)),
child_rfh_2->GetStorageKey());
EXPECT_EQ(blink::StorageKey::CreateFirstParty(
url::Origin::Create(grandchild_rfh_url)),
grandchild_rfh_2->GetStorageKey());
}
}
// Tests for clearing window.name on cross-site cross-BrowsingInstance
// navigations, with swapping BrowsingContextState and clearing window.name both
// enabled and disabled.
class RenderFrameHostImplBrowsingContextStateNameTest
: public RenderFrameHostImplBrowserTest,
public testing::WithParamInterface<bool> {
public:
// Provides meaningful param names instead of /0, /1, ...
static std::string DescribeParams(
const testing::TestParamInfo<ParamType>& info) {
return info.param ? "NewBrowsingContextStateOnBrowsingContextGroupSwap"
: "LegacyOneToOneWithFrameTreeNode";
}
protected:
void SetUp() override {
// TODO(crbug.com/40840863): Flaky on Mac, Android, Linux, and ChromeOS.
#if BUILDFLAG(IS_MAC) || BUILDFLAG(IS_ANDROID) || BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS)
GTEST_SKIP();
#else
// TODO(crbug.com/40259517):
// A RenderViewHostImpl from outside the BackForward take a
// `main_browsing_context_state` associated with a RenderFrameHost from
// within the BackForwardCache.
//
// During WebContents deletion, this causes the
// RenderViewHostImpl::main_browsing_context_state SafeRef to become
// dangling, because the BackForwardCache is cleared first.
if (NewBrowsingContextStateOnBrowsingContextGroupSwap()) {
GTEST_SKIP();
}
browsing_context_state_feature_list_.InitWithFeatureState(
features::kNewBrowsingContextStateOnBrowsingContextGroupSwap,
NewBrowsingContextStateOnBrowsingContextGroupSwap());
RenderFrameHostImplBrowserTest::SetUp();
#endif
}
bool NewBrowsingContextStateOnBrowsingContextGroupSwap() {
return GetParam();
}
private:
base::test::ScopedFeatureList browsing_context_state_feature_list_;
};
// Test that, when the RenderFrameHostImpl is in the BackForwardCache, the
// name update is blocked.
IN_PROC_BROWSER_TEST_P(RenderFrameHostImplBrowsingContextStateNameTest,
BlockNameUpdateForBackForwardCache) {
// This test specifically wants to test with BackForwardCache enabled, so skip
// it if BackForwardCache is disabled.
if (!IsBackForwardCacheEnabled())
return;
// Create the RenderFrameHost and store it in the BackForwardCache.
GURL url_a(embedded_test_server()->GetURL("a.com", "/title1.html"));
GURL url_b(embedded_test_server()->GetURL("b.com", "/title2.html"));
EXPECT_TRUE(NavigateToURL(shell(), url_a));
RenderFrameHostImpl* render_frame_host =
web_contents()->GetPrimaryMainFrame();
EXPECT_TRUE(ExecJs(render_frame_host, "window.name = 'page_name';"));
EXPECT_TRUE(ExecJs(render_frame_host, "window.name == 'page_name';"));
EXPECT_EQ(render_frame_host->browsing_context_state()->frame_name(),
"page_name");
EXPECT_EQ(render_frame_host->browsing_context_state()
->current_replication_state()
.unique_name,
"");
// Update the name using a pagehide handler to ensure that it occurs while the
// RenderFrameHost is in the BackForwardCache. This typically shouldn't occur
// and the name update should therefore be blocked.
EXPECT_TRUE(ExecJs(
render_frame_host,
"window.onpagehide = function() { window.name = 'unused_name'; }"));
// Navigate so that the current RenderFrameHost is cached.
EXPECT_TRUE(NavigateToURL(shell(), url_b));
EXPECT_TRUE(render_frame_host->IsInBackForwardCache());
std::string frame_name =
render_frame_host->browsing_context_state()->frame_name();
std::string unique_name = render_frame_host->browsing_context_state()
->current_replication_state()
.unique_name;
// Verify that the frame name and unique name haven't been changed, even
// though a name change was triggered by the Javascript.
EXPECT_EQ(frame_name, "page_name");
EXPECT_EQ(unique_name, "");
}
// Test that, when the RenderFrameHostImpl is in a pending delete state, the
// name update is blocked.
IN_PROC_BROWSER_TEST_P(RenderFrameHostImplBrowsingContextStateNameTest,
BlockNameUpdateForPendingDelete) {
// Disable BackForwardCache so that a pending delete state can be forced.
web_contents()->GetController().GetBackForwardCache().DisableForTesting(
content::BackForwardCache::TEST_USES_UNLOAD_EVENT);
// Create the RenderFrameHost and mark it as a pending delete.
GURL url_a(embedded_test_server()->GetURL("a.com", "/title1.html"));
GURL url_b(embedded_test_server()->GetURL("b.com", "/title2.html"));
EXPECT_TRUE(NavigateToURL(shell(), url_a));
RenderFrameHostImpl* render_frame_host =
web_contents()->GetPrimaryMainFrame();
LeaveInPendingDeletionState(render_frame_host);
EXPECT_TRUE(ExecJs(render_frame_host, "window.name = 'page_name';"));
EXPECT_TRUE(ExecJs(render_frame_host, "window.name == 'page_name';"));
EXPECT_EQ(render_frame_host->browsing_context_state()->frame_name(),
"page_name");
EXPECT_EQ(render_frame_host->browsing_context_state()
->current_replication_state()
.unique_name,
"");
// Update the name using an unload handler to ensure that it occurs while the
// RenderFrameHost is in a pending delete state. This typically shouldn't
// occur and the name update should therefore be blocked.
EXPECT_TRUE(
ExecJs(render_frame_host,
"window.onunload = function() { window.name = 'unused_name'; }"));
// Navigate so that the current RenderFrameHost is marked as pending delete.
EXPECT_TRUE(NavigateToURL(shell(), url_b));
EXPECT_TRUE(render_frame_host->IsPendingDeletion());
std::string frame_name =
render_frame_host->browsing_context_state()->frame_name();
std::string unique_name = render_frame_host->browsing_context_state()
->current_replication_state()
.unique_name;
// Verify that the frame name and unique name haven't been changed, even
// though a name change was triggered by the Javascript.
EXPECT_EQ(frame_name, "page_name");
EXPECT_EQ(unique_name, "");
}
INSTANTIATE_TEST_SUITE_P(
All,
RenderFrameHostImplBrowsingContextStateNameTest,
testing::Bool(),
RenderFrameHostImplBrowsingContextStateNameTest::DescribeParams);
IN_PROC_BROWSER_TEST_F(RenderFrameHostImplBrowserTest,
ResetOwnerInPendingDeletion) {
GURL url_a(embedded_test_server()->GetURL("a.com", "/title1.html"));
GURL url_b(embedded_test_server()->GetURL("b.com", "/title2.html"));
// Navigate to A.
EXPECT_TRUE(NavigateToURL(shell(), url_a));
RenderFrameHostImpl* rfh_a = web_contents()->GetPrimaryMainFrame();
// With BackForwardCache, swapped out RenderFrameHost won't have a
// replacement proxy as the document is stored in cache.
DisableBackForwardCacheForTesting(shell()->web_contents(),
BackForwardCache::TEST_REQUIRES_NO_CACHING);
// Set up a slow unload handler to force the RFH to linger in the unloaded
// but not-yet-deleted state.
EXPECT_TRUE(ExecJs(rfh_a, "window.onunload = function(){}"));
// Leave rfh_a in pending deletion state.
LeaveInPendingDeletionState(rfh_a);
// Navigate to B.
EXPECT_TRUE(NavigateToURL(shell(), url_b));
RenderFrameHostImpl* rfh_b = web_contents()->GetPrimaryMainFrame();
EXPECT_NE(rfh_a, rfh_b);
EXPECT_TRUE(rfh_a->IsPendingDeletion());
EXPECT_EQ(nullptr, rfh_a->owner_);
EXPECT_NE(nullptr, rfh_b->owner_);
EXPECT_EQ(rfh_b->owner_, web_contents()->GetPrimaryFrameTree().root());
}
IN_PROC_BROWSER_TEST_F(RenderFrameHostImplBrowserTest,
SetOwnerInSpeculativeRFHOwner) {
GURL url_a(embedded_test_server()->GetURL("a.com", "/title1.html"));
GURL url_b(embedded_test_server()->GetURL("b.com", "/title2.html"));
IsolateAllSitesForTesting(base::CommandLine::ForCurrentProcess());
// 1) Navigate to A.
EXPECT_TRUE(NavigateToURL(shell(), url_a));
RenderFrameHostImpl* rfh_a = web_contents()->GetPrimaryMainFrame();
// 2) Leave rfh_a in pending deletion state to check for rfh_a
// LifecycleStateImpl after navigating to B.
LeaveInPendingDeletionState(rfh_a);
// 3) Start navigation to B, but don't commit yet.
TestNavigationManager manager(web_contents(), url_b);
shell()->LoadURL(url_b);
manager.WaitForSpeculativeRenderFrameHostCreation();
FrameTreeNode* root = web_contents()->GetPrimaryFrameTree().root();
RenderFrameHostImpl* pending_rfh =
root->render_manager()->speculative_frame_host();
EXPECT_TRUE(pending_rfh);
EXPECT_NE(nullptr, pending_rfh->owner_);
}
// Tests that the devtools_navigation_token is set correctly after:
// 1) Initialization of the RFH (initial empty document)
// 2) First navigation
IN_PROC_BROWSER_TEST_F(RenderFrameHostImplBrowserTest,
DevToolsNavigationToken_InitialNavigation) {
RenderFrameHostImplWrapper rfh(web_contents()->GetPrimaryMainFrame());
EXPECT_EQ(rfh->GetDevToolsNavigationToken(), std::nullopt);
GURL url(embedded_test_server()->GetURL("a.com", "/title1.html"));
TestNavigationManager nav_manager(web_contents(), url);
shell()->LoadURL(url);
ASSERT_TRUE(nav_manager.WaitForFirstYieldAfterDidStartNavigation());
base::UnguessableToken devtools_navigation_token =
NavigationRequest::From(nav_manager.GetNavigationHandle())
->devtools_navigation_token();
ASSERT_TRUE(nav_manager.WaitForNavigationFinished());
ASSERT_EQ(rfh.get(), web_contents()->GetPrimaryMainFrame());
EXPECT_EQ(rfh->GetDevToolsNavigationToken(), devtools_navigation_token);
}
// Tests that the devtools_navigation_token changes after a cross-document
// navigation where the RFH is swapped.
IN_PROC_BROWSER_TEST_F(RenderFrameHostImplBrowserTest,
DevToolsNavigationToken_CrossDocumentNavigation) {
// This test requires that a same-site main frame navigation changes
// RenderFrameHosts, so we return early if that isn't possible.
if (!CanSameSiteMainFrameNavigationsChangeRenderFrameHosts()) {
LOG(ERROR) << "Skipping test due to precondition not being met.";
return;
}
GURL url_a(embedded_test_server()->GetURL("a.com", "/title1.html"));
GURL url_b(embedded_test_server()->GetURL("b.com", "/title2.html"));
IsolateAllSitesForTesting(base::CommandLine::ForCurrentProcess());
ASSERT_TRUE(NavigateToURL(shell(), url_a));
RenderFrameHostImplWrapper rfh_a(web_contents()->GetPrimaryMainFrame());
auto dnt_a = rfh_a->GetDevToolsNavigationToken();
EXPECT_TRUE(dnt_a.has_value());
ASSERT_TRUE(NavigateToURL(shell(), url_b));
RenderFrameHostImplWrapper rfh_b(web_contents()->GetPrimaryMainFrame());
ASSERT_NE(rfh_a.get(), rfh_b.get());
auto dnt_b = rfh_b->GetDevToolsNavigationToken();
EXPECT_TRUE(dnt_b.has_value());
// The devtools_navigation_token for |rfh_b| should be different from
// |rfh_a|'s token.
EXPECT_NE(dnt_a, dnt_b);
}
// Tests that the devtools_navigation_token changes after a cross-document
// navigation where the RFH stays the same.
IN_PROC_BROWSER_TEST_F(RenderFrameHostImplBrowserTest,
DevToolsNavigationToken_SameRFHCrossDocumentNavigation) {
GURL url_a(embedded_test_server()->GetURL("a.com", "/title1.html"));
GURL url_b(embedded_test_server()->GetURL("a.com", "/title2.html"));
ASSERT_TRUE(NavigateToURL(shell(), url_a));
RenderFrameHostImplWrapper rfh_a(web_contents()->GetPrimaryMainFrame());
// This test requires that a same site main frame navigation reuses the
// current RFH, which will not happen if RenderDocument is enabled.
if (rfh_a->ShouldChangeRenderFrameHostOnSameSiteNavigation()) {
LOG(ERROR) << "This test case is supposed to test behaviour when a "
"same-site navigation reuses the current RFH, which will not "
"happen if RenderDocument is enabled.";
return;
}
auto dnt_a = rfh_a->GetDevToolsNavigationToken();
EXPECT_TRUE(dnt_a.has_value());
DisableProactiveBrowsingInstanceSwapFor(rfh_a.get());
ASSERT_TRUE(NavigateToURL(shell(), url_b));
RenderFrameHostImplWrapper rfh_b(web_contents()->GetPrimaryMainFrame());
ASSERT_EQ(rfh_a->GetSiteInstance(), rfh_b->GetSiteInstance());
ASSERT_EQ(rfh_a.get(), rfh_b.get());
auto dnt_b = rfh_b->GetDevToolsNavigationToken();
EXPECT_TRUE(dnt_b.has_value());
// The devtools_navigation_token should change after the navigation commits.
EXPECT_NE(dnt_a, dnt_b);
}
// Tests that the devtools_navigation_token is unchanged after a same document
// navigation.
IN_PROC_BROWSER_TEST_F(RenderFrameHostImplBrowserTest,
DevToolsNavigationToken_SameDocumentNavigation) {
GURL url(embedded_test_server()->GetURL("a.com", "/title1.html"));
EXPECT_TRUE(NavigateToURL(shell(), url));
RenderFrameHostImplWrapper rfh(web_contents()->GetPrimaryMainFrame());
auto dnt = rfh->GetDevToolsNavigationToken();
GURL anchor_url = GURL(url.spec() + "#anchor");
TestNavigationManager nav_manager(web_contents(), anchor_url);
shell()->LoadURL(anchor_url);
ASSERT_TRUE(nav_manager.WaitForNavigationFinished());
ASSERT_EQ(rfh.get(), web_contents()->GetPrimaryMainFrame());
auto new_dnt = rfh->GetDevToolsNavigationToken();
// The devtools_navigation_token should not change after a same-document
// navigation.
EXPECT_EQ(dnt, new_dnt);
}
// Tests that a BFCached RFH preserves its devtools_navigation_token
// after being restored.
IN_PROC_BROWSER_TEST_F(RenderFrameHostImplBrowserTest,
DevToolsNavigationToken_BFCacheNavigation) {
// This test specifically wants to test with BackForwardCache enabled, so skip
// it if BackForwardCache is disabled.
if (!IsBackForwardCacheEnabled()) {
LOG(ERROR) << "Skipping test because BackForwardCache is not enabled.";
return;
}
GURL url_a(embedded_test_server()->GetURL("a.com", "/title1.html"));
GURL url_b(embedded_test_server()->GetURL("b.com", "/title2.html"));
IsolateAllSitesForTesting(base::CommandLine::ForCurrentProcess());
EXPECT_TRUE(NavigateToURL(shell(), url_a));
RenderFrameHostImplWrapper rfh_a(web_contents()->GetPrimaryMainFrame());
auto dnt = rfh_a->GetDevToolsNavigationToken();
EXPECT_TRUE(NavigateToURL(shell(), url_b));
RenderFrameHostImplWrapper rfh_b(web_contents()->GetPrimaryMainFrame());
ASSERT_TRUE(rfh_a->IsInBackForwardCache());
ASSERT_NE(rfh_a.get(), rfh_b.get());
ASSERT_TRUE(HistoryGoBack(web_contents()));
ASSERT_EQ(rfh_a.get(), web_contents()->GetPrimaryMainFrame());
// |rfh_a|'s devtools_navigation_token should not have changed after being
// restored from the BFCache.
EXPECT_EQ(rfh_a->GetDevToolsNavigationToken(), dnt);
}
// Tests that the devtools_navigation_token remains null after a synchronous
// about:blank navigation in an iframe.
IN_PROC_BROWSER_TEST_F(
RenderFrameHostImplBrowserTest,
DevToolsNavigationToken_SynchronousAboutBlankNavigation) {
GURL url(embedded_test_server()->GetURL("a.com", "/title1.html"));
ASSERT_TRUE(NavigateToURL(shell(), url));
RenderFrameHostImplWrapper subframe(
CreateSubframe(web_contents(), "", GURL(), true));
ASSERT_TRUE(subframe->is_initial_empty_document());
// Synchronous about:blank navigations are not strictly considered to be
// "same-document" navigations; but the synchronously committed about:blank
// document is still considered to be the initial empty document, and the
// devtools_navigation_token remains null.
EXPECT_EQ(subframe->GetDevToolsNavigationToken(), std::nullopt);
}
// Tests that the devtools_navigation_token of an RFH is updated after a
// navigation from a crashed RFH. In particular, this code tries to test the
// early-commit-of-speculative-rfh code path.
IN_PROC_BROWSER_TEST_F(RenderFrameHostImplBrowserTest,
DevToolsNavigationToken_EarlyCommitAfterCrash) {
GURL url_a(embedded_test_server()->GetURL("a.com", "/title1.html"));
GURL url_b(embedded_test_server()->GetURL("b.com", "/title2.html"));
ASSERT_TRUE(NavigateToURL(shell(), url_a));
RenderFrameHostImplWrapper rfh_a(web_contents()->GetPrimaryMainFrame());
auto dnt_a = rfh_a->GetDevToolsNavigationToken();
RenderProcessHost* process = rfh_a->GetProcess();
RenderProcessHostWatcher process_exit_observer(
process, content::RenderProcessHostWatcher::WATCH_FOR_PROCESS_EXIT);
process->Shutdown(RESULT_CODE_KILLED);
process_exit_observer.Wait();
ASSERT_TRUE(NavigateToURL(shell(), url_b));
RenderFrameHostImplWrapper rfh_b(web_contents()->GetPrimaryMainFrame());
auto dnt_b = rfh_b->GetDevToolsNavigationToken();
EXPECT_NE(dnt_a, dnt_b);
}
class RenderFrameHostImplNewProcessUsedBrowserTest
: public RenderFrameHostImplBrowserTest {
public:
RenderFrameHostImplNewProcessUsedBrowserTest() {
scoped_feature_list_.InitAndDisableFeature(
features::kProcessPerSiteUpToMainFrameThreshold);
}
private:
base::test::ScopedFeatureList scoped_feature_list_;
};
IN_PROC_BROWSER_TEST_F(
RenderFrameHostImplNewProcessUsedBrowserTest,
RecordNewProcessUsedForNavigationWhenSameSiteProcessExists_SameSite) {
base::HistogramTester histogram;
GURL url = embedded_test_server()->GetURL("a.com", "/title1.html");
GURL second_shell_start_url =
embedded_test_server()->GetURL("start.test", "/title1.html");
ASSERT_TRUE(NavigateToURL(shell(), url));
// Navigation from the initial empty RFH does not count.
histogram.ExpectTotalCount(
"SiteIsolation.NewProcessUsedForNavigationWhenSameSiteProcessExists", 0);
Shell* second_shell =
Shell::CreateNewWindow(shell()->web_contents()->GetBrowserContext(),
second_shell_start_url, nullptr, gfx::Size());
ASSERT_TRUE(NavigateToURL(second_shell, url));
ASSERT_NE(shell()->web_contents()->GetPrimaryMainFrame()->GetProcess(),
second_shell->web_contents()->GetPrimaryMainFrame()->GetProcess());
// `shell()` and `second_shell` opened the same site.
EXPECT_THAT(
histogram.GetAllSamples(
"SiteIsolation.NewProcessUsedForNavigationWhenSameSiteProcessExists"),
testing::ElementsAre(base::Bucket(true, 1)));
}
IN_PROC_BROWSER_TEST_F(
RenderFrameHostImplNewProcessUsedBrowserTest,
RecordNewProcessUsedForNavigationWhenSameSiteProcessExists_OtherSiteToSameSite) {
base::HistogramTester histogram;
GURL url = embedded_test_server()->GetURL("a.com", "/title1.html");
GURL second_shell_start_url =
embedded_test_server()->GetURL("start.test", "/title1.html");
GURL other_url = embedded_test_server()->GetURL("b.com", "/title1.html");
ASSERT_TRUE(NavigateToURL(shell(), url));
// Navigation from the initial empty RFH does not count.
histogram.ExpectTotalCount(
"SiteIsolation.NewProcessUsedForNavigationWhenSameSiteProcessExists", 0);
Shell* second_shell =
Shell::CreateNewWindow(shell()->web_contents()->GetBrowserContext(),
second_shell_start_url, nullptr, gfx::Size());
ASSERT_TRUE(NavigateToURL(second_shell, other_url));
ASSERT_NE(shell()->web_contents()->GetPrimaryMainFrame()->GetProcess(),
second_shell->web_contents()->GetPrimaryMainFrame()->GetProcess());
bool requires_dedicated_process = second_shell->web_contents()
->GetPrimaryMainFrame()
->GetSiteInstance()
->RequiresDedicatedProcess();
// `shell()` and `second_shell` opened different sites.
// TODO(crbug.com/419469455): Make sure metrics are updated correctly with the
// introduction of default SiteInstanceGroup.
if (requires_dedicated_process || ShouldUseDefaultSiteInstanceGroup()) {
EXPECT_THAT(histogram.GetAllSamples(
"SiteIsolation."
"NewProcessUsedForNavigationWhenSameSiteProcessExists"),
testing::ElementsAre(base::Bucket(false, 1)));
} else {
EXPECT_THAT(histogram.GetAllSamples(
"SiteIsolation."
"NewProcessUsedForNavigationWhenSameSiteProcessExists"),
testing::ElementsAre(base::Bucket(true, 1)));
}
ASSERT_TRUE(NavigateToURL(second_shell, url));
// Now `shell()` and `second_shell` opened the same site.
if (requires_dedicated_process || ShouldUseDefaultSiteInstanceGroup()) {
EXPECT_THAT(
histogram.GetAllSamples(
"SiteIsolation."
"NewProcessUsedForNavigationWhenSameSiteProcessExists"),
testing::ElementsAre(base::Bucket(false, 1), base::Bucket(true, 1)));
} else {
EXPECT_THAT(histogram.GetAllSamples(
"SiteIsolation."
"NewProcessUsedForNavigationWhenSameSiteProcessExists"),
testing::ElementsAre(base::Bucket(true, 2)));
}
}
// TODO(crbug.com/40264958): Consider enabling this test on Android.
// There is no plan to analyze the histogram on Android for now.
#if !BUILDFLAG(IS_ANDROID)
IN_PROC_BROWSER_TEST_F(
RenderFrameHostImplNewProcessUsedBrowserTest,
RecordNewProcessUsedForNavigationWhenSameSiteProcessExists_DifferentProfile) {
base::HistogramTester histogram;
GURL url = embedded_test_server()->GetURL("a.com", "/title1.html");
GURL second_shell_start_url =
embedded_test_server()->GetURL("start.test", "/title1.html");
ASSERT_TRUE(NavigateToURL(shell(), url));
// Navigation from the initial empty RFH does not count.
histogram.ExpectTotalCount(
"SiteIsolation.NewProcessUsedForNavigationWhenSameSiteProcessExists", 0);
Shell* second_shell = Shell::CreateNewWindow(
ShellContentBrowserClient::Get()->off_the_record_browser_context(),
second_shell_start_url, nullptr, gfx::Size());
ASSERT_TRUE(NavigateToURL(second_shell, url));
ASSERT_NE(shell()->web_contents()->GetPrimaryMainFrame()->GetProcess(),
second_shell->web_contents()->GetPrimaryMainFrame()->GetProcess());
// `shell()` and `second_shell` opened the same site but use different
// profiles.
EXPECT_THAT(
histogram.GetAllSamples(
"SiteIsolation.NewProcessUsedForNavigationWhenSameSiteProcessExists"),
testing::ElementsAre(base::Bucket(false, 1)));
}
#endif
IN_PROC_BROWSER_TEST_F(
RenderFrameHostImplNewProcessUsedBrowserTest,
RecordNewProcessUsedForNavigationWhenSameSiteProcessExists_SameSiteNavigateTwice) {
base::HistogramTester histogram;
GURL url = embedded_test_server()->GetURL("a.com", "/title1.html");
GURL url2 = embedded_test_server()->GetURL("a.com", "/title2.html");
GURL second_shell_start_url =
embedded_test_server()->GetURL("start.test", "/title1.html");
ASSERT_TRUE(NavigateToURL(shell(), url));
// Navigation from the initial empty RFH does not count.
histogram.ExpectTotalCount(
"SiteIsolation.NewProcessUsedForNavigationWhenSameSiteProcessExists", 0);
Shell* second_shell =
Shell::CreateNewWindow(shell()->web_contents()->GetBrowserContext(),
second_shell_start_url, nullptr, gfx::Size());
ASSERT_TRUE(NavigateToURL(second_shell, url));
ASSERT_NE(shell()->web_contents()->GetPrimaryMainFrame()->GetProcess(),
second_shell->web_contents()->GetPrimaryMainFrame()->GetProcess());
// `shell()` and `second_shell` opened the same site.
EXPECT_THAT(
histogram.GetAllSamples(
"SiteIsolation.NewProcessUsedForNavigationWhenSameSiteProcessExists"),
testing::ElementsAre(base::Bucket(true, 1)));
ASSERT_TRUE(NavigateToURL(second_shell, url2));
// Navigating the different page in the same site shouldn't count up
// histograms.
EXPECT_THAT(
histogram.GetAllSamples(
"SiteIsolation.NewProcessUsedForNavigationWhenSameSiteProcessExists"),
testing::ElementsAre(base::Bucket(true, 1)));
}
// Tests that if a shutdown BeforeUnload ACK is received when a navigation has
// picked its final RenderFrameHost, both the RenderFrameHost and navigation
// gets destructed.
// Regression test for crbug.com/349065727.
IN_PROC_BROWSER_TEST_F(RenderFrameHostImplBrowserTest,
BeforeUnloadACKWithOngoingNavigation) {
GURL url = embedded_test_server()->GetURL("a.com", "/title1.html");
GURL url2 = embedded_test_server()->GetURL("b.com", "/title2.html");
FrameTreeNode* root = web_contents()->GetPrimaryFrameTree().root();
// Navigate to an initial page.
EXPECT_TRUE(NavigateToURL(shell(), url));
// Set up a throttle for the next navigation to simulate a shutdown
// BeforeUnload ACK from OnWillProcessResponse, after a final RenderFrameHost
// has been picked.
TestNavigationThrottleInserter throttle_inserter(
shell()->web_contents(),
base::BindLambdaForTesting(
[&](NavigationThrottleRegistry& registry) -> void {
auto throttle = std::make_unique<TestNavigationThrottle>(registry);
throttle->SetCallback(
TestNavigationThrottle::WILL_PROCESS_RESPONSE,
base::BindLambdaForTesting([&]() {
// Simulate a shutdown BeforeUnload ACK that can happen if
// e.g. the tab is being closed. Note that this beforeunload
// is not triggered by the navigation itself (a navigation
// beforeunload will call `Navigator::BeforeUnloadCompleted()`
// instead). The shutdown beforeunload ACK will trigger the
// deletion of the speculative RenderFrameHost &
// NavigationRequest, so do it asynchronously to not crash the
// TestNavigationThrottle.
GetUIThreadTaskRunner({})->PostTask(
FROM_HERE, base::BindLambdaForTesting([&]() {
// Check that the NavigationRequest has picked its final
// RenderFrameHost.
EXPECT_TRUE(root->navigation_request());
EXPECT_TRUE(
root->navigation_request()->HasRenderFrameHost());
// Simulate the BeforeUnload ACK.
root->render_manager()->BeforeUnloadCompleted(
/*proceed=*/true);
// Ensure that the NavigationRequest and speculative
// RenderFrameHost has been cleared.
EXPECT_FALSE(
root->render_manager()->speculative_frame_host());
EXPECT_FALSE(root->navigation_request());
}));
}));
registry.AddThrottle(std::move(throttle));
}));
// Navigate to another page, which will be cancelled by the shutdown
// BeforeUnload ACK above.
TestNavigationManager navigation_manager(web_contents(), url2);
shell()->LoadURL(url2);
// A speculative RFH will be created if needed.
if (AreAllSitesIsolatedForTesting() || IsBackForwardCacheEnabled() ||
root->current_frame_host()
->ShouldChangeRenderFrameHostOnSameSiteNavigation()) {
navigation_manager.WaitForSpeculativeRenderFrameHostCreation();
EXPECT_TRUE(root->render_manager()->speculative_frame_host());
} else {
EXPECT_TRUE(navigation_manager.WaitForRequestStart());
EXPECT_FALSE(root->render_manager()->speculative_frame_host());
navigation_manager.ResumeNavigation();
}
// The NavigationRequest got deleted before commit because of the
// BeforeUnload ACK, along with the speculative RenderFrameHost (if it was
// created).
EXPECT_TRUE(navigation_manager.WaitForNavigationFinished());
EXPECT_FALSE(navigation_manager.was_committed());
EXPECT_FALSE(root->render_manager()->speculative_frame_host());
}
// Intercept calls to RenderFramHostImpl's CreateNewWindow mojo method to
// overwrite the target url.
class FrameHostInterceptorForPopins
: public mojom::FrameHostInterceptorForTesting {
public:
explicit FrameHostInterceptorForPopins(RenderFrameHostImpl* render_frame_host,
const GURL& target_url)
: swapped_impl_(render_frame_host->frame_host_receiver_for_testing(),
this),
target_url_(target_url) {}
~FrameHostInterceptorForPopins() override = default;
FrameHostInterceptorForPopins(const FrameHostInterceptorForPopins&) = delete;
FrameHostInterceptorForPopins& operator=(
const FrameHostInterceptorForPopins&) = delete;
mojom::FrameHost* GetForwardingInterface() override {
return swapped_impl_.old_impl();
}
void CreateNewWindow(mojom::CreateNewWindowParamsPtr params,
CreateNewWindowCallback callback) override {
params->target_url = target_url_;
static_cast<RenderFrameHostImpl*>(GetForwardingInterface())
->CreateNewWindow(std::move(params), std::move(callback));
}
private:
mojo::test::ScopedSwapImplForTesting<mojom::FrameHost> swapped_impl_;
GURL target_url_;
};
class RenderFrameHostImplPartitionedPopinBrowserTest
: public RenderFrameHostImplBrowserTest {
public:
RenderFrameHostImplPartitionedPopinBrowserTest() {
feature_list_.InitAndEnableFeature(blink::features::kPartitionedPopins);
}
~RenderFrameHostImplPartitionedPopinBrowserTest() override = default;
private:
void SetUpOnMainThread() override {
host_resolver()->AddRule("*", "127.0.0.1");
embedded_https_test_server().SetSSLConfig(
net::EmbeddedTestServer::CERT_TEST_NAMES);
net::test_server::RegisterDefaultHandlers(&embedded_https_test_server());
ASSERT_TRUE(embedded_https_test_server().Start());
}
base::test::ScopedFeatureList feature_list_;
};
IN_PROC_BROWSER_TEST_F(RenderFrameHostImplPartitionedPopinBrowserTest,
CreateNewWindow_FailsWithEmptyTargetUrl) {
FrameHostInterceptorForPopins interceptor(
static_cast<content::RenderFrameHostImpl*>(
web_contents()->GetPrimaryMainFrame()),
GURL());
GURL url(embedded_https_test_server().GetURL("a.test", "/empty.html"));
ASSERT_TRUE(NavigateToURL(web_contents(), url));
ASSERT_EQ(ListValueOf("partitioned"),
EvalJs(web_contents(), "window.popinContextTypesSupported()"));
content::RenderProcessHostBadMojoMessageWaiter crash_observer(
web_contents()->GetPrimaryMainFrame()->GetProcess());
// ExecJs will sometimes finish before the renderer gets killed, so we must
// ignore the result.
std::ignore = ExecJs(web_contents(),
"window.open('" + url.spec() + "', '_blank', 'popin');");
EXPECT_EQ(
"Received bad user message: "
"Partitioned popins can only open https URLs.",
crash_observer.Wait());
// The test passes if the renderer crashes but not the browser.
}
IN_PROC_BROWSER_TEST_F(RenderFrameHostImplPartitionedPopinBrowserTest,
CreateNewWindow_FailsWithAboutBlankTargetUrl) {
FrameHostInterceptorForPopins interceptor(
static_cast<content::RenderFrameHostImpl*>(
web_contents()->GetPrimaryMainFrame()),
GURL("about:blank"));
GURL url(embedded_https_test_server().GetURL("a.test", "/empty.html"));
ASSERT_TRUE(NavigateToURL(web_contents(), url));
ASSERT_EQ(ListValueOf("partitioned"),
EvalJs(web_contents(), "window.popinContextTypesSupported()"));
content::RenderProcessHostBadMojoMessageWaiter crash_observer(
web_contents()->GetPrimaryMainFrame()->GetProcess());
// ExecJs will sometimes finish before the renderer gets killed, so we must
// ignore the result.
std::ignore = ExecJs(web_contents(),
"window.open('" + url.spec() + "', '_blank', 'popin');");
EXPECT_EQ(
"Received bad user message: "
"Partitioned popins can only open https URLs.",
crash_observer.Wait());
// The test passes if the renderer crashes but not the browser.
}
IN_PROC_BROWSER_TEST_F(RenderFrameHostImplPartitionedPopinBrowserTest,
CreateNewWindow_FailsWithHttpTargetUrl) {
FrameHostInterceptorForPopins interceptor(
static_cast<content::RenderFrameHostImpl*>(
web_contents()->GetPrimaryMainFrame()),
GURL("http://a.test"));
GURL url(embedded_https_test_server().GetURL("a.test", "/empty.html"));
ASSERT_TRUE(NavigateToURL(web_contents(), url));
ASSERT_EQ(ListValueOf("partitioned"),
EvalJs(web_contents(), "window.popinContextTypesSupported()"));
content::RenderProcessHostBadMojoMessageWaiter crash_observer(
web_contents()->GetPrimaryMainFrame()->GetProcess());
// ExecJs will sometimes finish before the renderer gets killed, so we must
// ignore the result.
std::ignore = ExecJs(web_contents(),
"window.open('" + url.spec() + "', '_blank', 'popin');");
EXPECT_EQ(
"Received bad user message: "
"Partitioned popins can only open https URLs.",
crash_observer.Wait());
// The test passes if the renderer crashes but not the browser.
}
// Test that a popin doesn't crash the browser if the opener goes away during
// navigation. This simulates a case where the opening frame gets deleted before
// the popin is closed by `PartitionedPopinController`.
IN_PROC_BROWSER_TEST_F(RenderFrameHostImplPartitionedPopinBrowserTest,
PopinNavigationAfterOpenerCleared) {
// Navigate to a.test.
ASSERT_TRUE(NavigateToURL(web_contents(), embedded_https_test_server().GetURL(
"a.test", "/empty.html")));
// Open a popin.
WebContentsAddedObserver new_tab_observer;
const GURL old_url = embedded_https_test_server().GetURL(
"a.test", "/partitioned_popins/wildcard_policy.html");
EXPECT_TRUE(content::ExecJs(web_contents(), "window.open('" + old_url.spec() +
"', '_blank', 'popin')"));
WebContentsImpl* popin_web_contents =
static_cast<WebContentsImpl*>(new_tab_observer.GetWebContents());
EXPECT_TRUE(popin_web_contents->IsPartitionedPopin());
EXPECT_EQ(popin_web_contents->GetPrimaryMainFrame()->GetStorageKey(),
blink::StorageKey::CreateFromStringForTesting(old_url.spec()));
// Clear opener so the popin cannot use it as a source of data.
popin_web_contents->ClearPartitionedPopinOpenerForTesting();
// Navigate the popin and see it work.
const GURL new_url = embedded_https_test_server().GetURL(
"b.test", "/partitioned_popins/wildcard_policy.html");
EXPECT_TRUE(NavigateToURL(popin_web_contents, new_url));
EXPECT_TRUE(popin_web_contents->IsPartitionedPopin());
EXPECT_EQ(popin_web_contents->GetPrimaryMainFrame()->GetStorageKey(),
blink::StorageKey::Create(
url::Origin::Create(new_url), net::SchemefulSite(GURL(old_url)),
blink::mojom::AncestorChainBit::kCrossSite));
}
class RenderFrameHostImplBrowserTestWithBFCache
: public RenderFrameHostImplBrowserTest {
public:
RenderFrameHostImplBrowserTestWithBFCache() {
std::vector<base::test::FeatureRefAndParams> enabled_features =
GetDefaultEnabledBackForwardCacheFeaturesForTesting(
/*ignore_outstanding_network_request=*/false);
scoped_feature_list_.InitWithFeaturesAndParameters(
enabled_features,
GetDefaultDisabledBackForwardCacheFeaturesForTesting());
}
~RenderFrameHostImplBrowserTestWithBFCache() override = default;
viz::SurfaceId GetSurfaceId(const FrameTreeNode* frame_tree_node) const;
bool ContainsSurfaceIdOrNewer(const std::vector<viz::SurfaceId>& ids,
viz::SurfaceId expected_id) const;
protected:
void SetUpCommandLine(base::CommandLine* command_line) override;
private:
base::test::ScopedFeatureList scoped_feature_list_;
};
viz::SurfaceId RenderFrameHostImplBrowserTestWithBFCache::GetSurfaceId(
const FrameTreeNode* frame_tree_node) const {
viz::SurfaceId id;
auto* view = static_cast<RenderWidgetHostViewBase*>(
frame_tree_node->current_frame_host()->GetView());
if (view) {
id = view->GetCurrentSurfaceId();
}
return id;
}
bool RenderFrameHostImplBrowserTestWithBFCache::ContainsSurfaceIdOrNewer(
const std::vector<viz::SurfaceId>& ids,
viz::SurfaceId expected_id) const {
for (auto id : ids) {
if (id.IsSameOrNewerThan(expected_id)) {
return true;
}
}
return false;
}
void RenderFrameHostImplBrowserTestWithBFCache::SetUpCommandLine(
base::CommandLine* command_line) {
// The full BackForwardCacheBrowserTest suite ads far more to the CommandLine.
// While we enable many features in the ctor, we need `--site-per-process` to
// ensure full testing of OOPIFs in BFCache.
IsolateAllSitesForTesting(command_line);
RenderFrameHostImplBrowserTest::SetUpCommandLine(command_line);
}
IN_PROC_BROWSER_TEST_F(RenderFrameHostImplBrowserTestWithBFCache,
ResetOwnerInBFCache) {
GURL url_a(embedded_test_server()->GetURL(
"a.com", "/cross_site_iframe_factory.html?a(b)"));
GURL url_c(embedded_test_server()->GetURL("c.com", "/title2.html"));
// 1) Navigate to A(B).
EXPECT_TRUE(NavigateToURL(shell(), url_a));
RenderFrameHostImpl* rfh_a = web_contents()->GetPrimaryMainFrame();
RenderFrameHostImpl* rfh_b = rfh_a->child_at(0)->current_frame_host();
FrameTreeNode* expected_parent_ftn = rfh_a->frame_tree_node();
FrameTreeNode* expected_child_ftn = rfh_b->frame_tree_node();
// 2) Navigate to C.
EXPECT_TRUE(NavigateToURL(shell(), url_c));
RenderFrameHostImpl* rfh_c = web_contents()->GetPrimaryMainFrame();
// 3) Ensure A(B) are cached.
EXPECT_TRUE(rfh_a->IsInBackForwardCache());
EXPECT_TRUE(rfh_b->IsInBackForwardCache());
EXPECT_FALSE(rfh_c->IsInBackForwardCache());
EXPECT_NE(rfh_a, rfh_c);
EXPECT_EQ(nullptr, rfh_a->owner_);
EXPECT_EQ(expected_child_ftn, rfh_b->owner_);
EXPECT_EQ(expected_parent_ftn, rfh_c->owner_);
// 4) Navigate back to A(B).
ASSERT_TRUE(HistoryGoBack(web_contents()));
// 5) Ensure C is cached and A's owner is updated.
EXPECT_TRUE(rfh_c->IsInBackForwardCache());
EXPECT_EQ(rfh_a, web_contents()->GetPrimaryMainFrame());
EXPECT_EQ(expected_parent_ftn, rfh_a->owner_);
EXPECT_EQ(expected_child_ftn, rfh_b->owner_);
EXPECT_EQ(nullptr, rfh_c->owner_);
}
IN_PROC_BROWSER_TEST_F(RenderFrameHostImplBrowserTestWithBFCache,
NewContentTimeoutIsNotSetWhenLeavingBFCacheWithSurface) {
GURL url_a(embedded_test_server()->GetURL("a.com", "/title1.html"));
GURL url_b(embedded_test_server()->GetURL("b.com", "/title2.html"));
// Navigate to A.
EXPECT_TRUE(NavigateToURL(shell(), url_a));
RenderFrameHostImpl* rfh_a = web_contents()->GetPrimaryMainFrame();
// Navigate to B.
EXPECT_TRUE(NavigateToURL(shell(), url_b));
EXPECT_TRUE(rfh_a->IsInBackForwardCache());
RenderWidgetHostViewBase* rwhvb_a =
static_cast<RenderWidgetHostViewBase*>(rfh_a->GetView());
bool timer_should_set =
!rwhvb_a->GetLocalSurfaceId().is_valid() || rwhvb_a->is_evicted();
// Ensure there is an activation to allow cross-origin paint holding.
web_contents()->GetPrimaryMainFrame()->ActivateUserActivation(
blink::mojom::UserActivationNotificationType::kInteraction,
/*sticky_only=*/true);
// Navigate back to A.
ASSERT_TRUE(HistoryGoBack(web_contents()));
EXPECT_EQ(rfh_a, web_contents()->GetPrimaryMainFrame());
RenderWidgetHostImpl* rwhi_a =
RenderWidgetHostImpl::From(rfh_a->GetView()->GetRenderWidgetHost());
EXPECT_EQ(rwhi_a->IsContentRenderingTimeoutRunning(), timer_should_set);
}
IN_PROC_BROWSER_TEST_F(RenderFrameHostImplBrowserTestWithBFCache,
NewContentTimeoutIsSetWhenLeavingBFCacheWithoutSurface) {
GURL url_a(embedded_test_server()->GetURL("a.com", "/title1.html"));
GURL url_b(embedded_test_server()->GetURL("b.com", "/title2.html"));
// Navigate to A.
EXPECT_TRUE(NavigateToURL(shell(), url_a));
RenderFrameHostImpl* rfh_a = web_contents()->GetPrimaryMainFrame();
// Navigate to B.
EXPECT_TRUE(NavigateToURL(shell(), url_b));
EXPECT_TRUE(rfh_a->IsInBackForwardCache());
RenderViewHostImpl* rvh_a =
static_cast<RenderViewHostImpl*>(rfh_a->GetRenderViewHost());
std::vector<viz::SurfaceId> ids = rvh_a->CollectSurfaceIdsForEviction();
web_contents()->GetPrimaryMainFrame()->ActivateUserActivation(
blink::mojom::UserActivationNotificationType::kInteraction,
/*sticky_only=*/true);
// Navigate back to A.
ASSERT_TRUE(HistoryGoBack(web_contents()));
EXPECT_EQ(rfh_a, web_contents()->GetPrimaryMainFrame());
RenderWidgetHostImpl* rwhi_a =
RenderWidgetHostImpl::From(rfh_a->GetView()->GetRenderWidgetHost());
EXPECT_TRUE(rwhi_a->IsContentRenderingTimeoutRunning());
}
// Test that the new content timeout only applies when there is a user
// activation, since cross-origin paint holding does not apply otherwise. See
// also NewContentTimeoutIsSetWhenLeavingBFCacheWithoutSurface and
// crbug.com/40942531.
IN_PROC_BROWSER_TEST_F(
RenderFrameHostImplBrowserTestWithBFCache,
IsNotSetWhenLeavingBFCacheWithoutSurfaceOrUserActivation) {
GURL url_a(embedded_test_server()->GetURL("a.com", "/title1.html"));
GURL url_b(embedded_test_server()->GetURL("b.com", "/title2.html"));
// Navigate to A.
EXPECT_TRUE(NavigateToURL(shell(), url_a));
RenderFrameHostImpl* rfh_a = web_contents()->GetPrimaryMainFrame();
// Navigate to B.
EXPECT_TRUE(NavigateToURL(shell(), url_b));
EXPECT_TRUE(rfh_a->IsInBackForwardCache());
RenderViewHostImpl* rvh_a =
static_cast<RenderViewHostImpl*>(rfh_a->GetRenderViewHost());
std::vector<viz::SurfaceId> ids = rvh_a->CollectSurfaceIdsForEviction();
// Navigate back to A.
ASSERT_TRUE(HistoryGoBack(web_contents()));
EXPECT_EQ(rfh_a, web_contents()->GetPrimaryMainFrame());
RenderWidgetHostImpl* rwhi_a =
RenderWidgetHostImpl::From(rfh_a->GetView()->GetRenderWidgetHost());
// Here we verify that the timeout is not running as a proxy to say that there
// is no paint holding. It would be nice to directly check this instead.
EXPECT_FALSE(rwhi_a->IsContentRenderingTimeoutRunning());
}
namespace {
class RenderFrameHostImplBrowserTestWithBFCacheAndViewTransition
: public RenderFrameHostImplBrowserTestWithBFCache {
public:
RenderFrameHostImplBrowserTestWithBFCacheAndViewTransition() {
std::vector<base::test::FeatureRefAndParams> enabled_features =
GetDefaultEnabledBackForwardCacheFeaturesForTesting(
/*ignore_outstanding_network_request=*/false);
enabled_features.push_back({blink::features::kPageSwapEvent, {{}}});
scoped_feature_list_.InitWithFeaturesAndParameters(
enabled_features,
GetDefaultDisabledBackForwardCacheFeaturesForTesting());
EnablePixelOutput();
}
~RenderFrameHostImplBrowserTestWithBFCacheAndViewTransition() override =
default;
private:
base::test::ScopedFeatureList scoped_feature_list_;
};
bool IsChildFrame(RenderWidgetHostView* view) {
CHECK(view);
return static_cast<RenderWidgetHostViewBase*>(view)
->IsRenderWidgetHostViewChildFrame();
}
#if BUILDFLAG(IS_ANDROID)
ui::DelegatedFrameHostAndroid* GetDelegatedFrameHost(
RenderWidgetHostView* view) {
CHECK(!IsChildFrame(view));
return static_cast<RenderWidgetHostViewAndroid*>(view)
->delegated_frame_host_for_testing();
}
#else
DelegatedFrameHost* GetDelegatedFrameHost(RenderWidgetHostView* view) {
CHECK(!IsChildFrame(view));
DelegatedFrameHost* dfh = nullptr;
#if BUILDFLAG(IS_MAC)
auto* compositor = GetBrowserCompositorMacForTesting(view);
dfh = compositor->GetDelegatedFrameHost();
#elif BUILDFLAG(IS_IOS)
auto* compositor = GetBrowserCompositorIOSForTesting(view);
dfh = compositor->GetDelegatedFrameHost();
#elif defined(USE_AURA)
dfh = static_cast<RenderWidgetHostViewAura*>(view)
->GetDelegatedFrameHostForTesting();
#endif // BUILDFLAG(IS_MAC)
return dfh;
}
#endif // BUILDFLAG(IS_ANDROID)
viz::SurfaceId GetCurrentSurfaceIdOnDelegatedFrameHost(
RenderWidgetHostView* view) {
auto* dfh = GetDelegatedFrameHost(view);
CHECK(dfh);
#if BUILDFLAG(IS_ANDROID)
return dfh->GetCurrentSurfaceIdForTesting();
#else
return dfh->GetCurrentSurfaceId();
#endif // BUILDFLAG(IS_ANDROID)
}
viz::SurfaceId GetFirstSurfaceIdAfterNavigation(RenderWidgetHostView* view) {
auto* dfh = GetDelegatedFrameHost(view);
CHECK(dfh);
return dfh->GetFirstSurfaceIdAfterNavigationForTesting();
}
} // namespace
// https://crbug.com/1415340: For a page with ViewTransition being restored from
// BFCache, we explicitly set its fallback surface to the current View to avoid
// visual glitches.
IN_PROC_BROWSER_TEST_F(
RenderFrameHostImplBrowserTestWithBFCacheAndViewTransition,
NewContentTimeoutIsSetWhenLeavingBFCacheWithViewTransition) {
// "red_jank_second_pageshow.html" janks the renderer on the second pageshow
// event.
const GURL url_red(embedded_test_server()->GetURL(
"a.com", "/view_transitions/red_jank_second_pageshow.html"));
const GURL url_green(
embedded_test_server()->GetURL("a.com", "/view_transitions/green.html"));
// Navigate to Red.
ASSERT_TRUE(NavigateToURL(shell(), url_red));
RenderFrameHostWrapper rfh_red(web_contents()->GetPrimaryMainFrame());
const auto first_surface_id_after_nav_before_bfcache_restore =
GetFirstSurfaceIdAfterNavigation(rfh_red->GetView());
// Navigate to Green.
ASSERT_TRUE(NavigateToURL(shell(), url_green));
ASSERT_FALSE(rfh_red.IsDestroyed());
ASSERT_TRUE(
static_cast<RenderFrameHostImpl*>(rfh_red.get())->IsInBackForwardCache());
auto* rwhi_red =
RenderWidgetHostImpl::From(rfh_red->GetView()->GetRenderWidgetHost());
// The BFCached `RenderWidgetHostImpl` must have a stopped timer.
ASSERT_FALSE(rwhi_red->IsContentRenderingTimeoutRunning());
// Set the timeout to a max value, such that we can guarantee to manually
// force the timer to fire via
// `RenderWidgetHostImpl::ForceFirstFrameAfterNavigationTimeout()`. Deflake
// the tests.
rwhi_red->SetNewContentRenderingTimeoutForTesting(base::TimeDelta::Max());
// Ensure the first frame in the green page is rendered, so that the
// transition is not skipped.
WaitForCopyableViewInWebContents(web_contents());
// Navigate back to Red.
ASSERT_TRUE(HistoryGoBack(web_contents()));
ASSERT_EQ(rfh_red.get(), web_contents()->GetPrimaryMainFrame());
ASSERT_TRUE(rwhi_red->IsContentRenderingTimeoutRunning());
const auto first_surface_id_after_nav_after_bfcache_restore =
GetFirstSurfaceIdAfterNavigation(rfh_red->GetView());
// The `first_surface_id_after_nav_` of the DelegatedFrameHost{Android}, after
// the BFCache restore, should have a different value than before.
ASSERT_NE(first_surface_id_after_nav_after_bfcache_restore,
first_surface_id_after_nav_before_bfcache_restore);
// The first call to `DelegatedFrameHost{Android}::EmbedSurface` will set
// `first_surface_id_after_nav_` to the new current `viz::SurfaceId`; if there
// are subsequent `EmbedSurface` calls (i.e., Android), the current surface id
// will be newer than `first_surface_id_after_nav_`.
ASSERT_TRUE(
GetCurrentSurfaceIdOnDelegatedFrameHost(rfh_red->GetView())
.IsSameOrNewerThan(first_surface_id_after_nav_after_bfcache_restore));
// Manually force the timer to fire, since the timeout is infinity.
ASSERT_TRUE(rwhi_red->IsContentRenderingTimeoutRunning());
rwhi_red->ForceFirstFrameAfterNavigationTimeout();
ASSERT_FALSE(rwhi_red->IsContentRenderingTimeoutRunning());
ASSERT_EQ(first_surface_id_after_nav_after_bfcache_restore,
GetDelegatedFrameHost(rfh_red->GetView())
->GetFallbackSurfaceIdForTesting());
// TODO(crbug.com/40278487): If the red page's renderer still hasn't
// submitted a new frame after the ContentRenderingTimeout is up, we should
// abort the transition. Expand this test to cover that behavior when we have
// a way to abort the transition.
}
// Tests that when a RenderFrameHost is stored in BFCache, that the visibility
// of its child frames are also updating. Any OOPIF should stop submitting new
// viz::CompositorFrames while in the cache. Conversely upon being removed from
// the BFCache, and re-navigated to, the OOPIF should once again start
// submitting new frames.
IN_PROC_BROWSER_TEST_F(RenderFrameHostImplBrowserTestWithBFCache,
ChildFramesHiddenWhileInBFCache) {
GURL url_a(embedded_test_server()->GetURL(
"a.com", "/cross_site_iframe_factory.html?a(b)"));
GURL url_c(embedded_test_server()->GetURL("c.com", "/title2.html"));
// 1) Navigate to A(B).
EXPECT_TRUE(NavigateToURL(shell(), url_a));
RenderFrameHostImplWrapper rfh_a(web_contents()->GetPrimaryMainFrame());
FrameTreeNode* expected_parent_ftn = rfh_a->frame_tree_node();
// 2) Navigate OOPIF B to a page with a continuous Compositor-thread
// animation.
GURL url_d(embedded_test_server()->GetURL(
"b.com", "/rwhv_compositing_animation.html"));
EXPECT_TRUE(NavigateToURLFromRenderer(
ChildFrameAt(shell()->web_contents()->GetPrimaryMainFrame(), 0), url_d));
RenderFrameHostImplWrapper rfh_b(rfh_a->child_at(0)->current_frame_host());
RenderFrameSubmissionObserver rfso_d(rfh_b.get());
FrameTreeNode* expected_child_ftn = rfh_b->frame_tree_node();
// 3) Navigate to C.
EXPECT_TRUE(NavigateToURL(shell(), url_c));
// Even though navigation has completed, there may still be a frame from D
// that is being processed by Viz, or whose RenderFrameMetadata has yet to
// arrive and be processed on the Browser UI thread.
//
// So we wait until the first frame submitted by C has been produced and the
// metadata processed on the Browser UI thread. From this point on we expect
// that there are no new frames submitted by D.
RenderFrameHostImplWrapper rfh_c(web_contents()->GetPrimaryMainFrame());
RenderFrameSubmissionObserver rfso_c =
RenderFrameSubmissionObserver(rfh_c.get());
rfso_c.WaitForAnyFrameSubmission();
int post_nav_num_frames = rfso_d.render_frame_count();
// 4) Ensure A(B) are cached.
EXPECT_TRUE(rfh_a->IsInBackForwardCache());
EXPECT_TRUE(rfh_b->IsInBackForwardCache());
EXPECT_FALSE(rfh_c->IsInBackForwardCache());
EXPECT_NE(rfh_a.get(), rfh_c.get());
EXPECT_EQ(nullptr, rfh_a->owner_);
EXPECT_EQ(expected_child_ftn, rfh_b->owner_);
EXPECT_EQ(expected_parent_ftn, rfh_c->owner_);
// Since previous content had continuous animation, wait a while and confirm
// no further frames were submitted. Let's wait for 10 frames at 60 Hz, to
// give some time for slower builds.
{
base::RunLoop run_loop;
base::SingleThreadTaskRunner::GetCurrentDefault()->PostDelayedTask(
FROM_HERE, run_loop.QuitClosure(), base::Milliseconds(160));
run_loop.Run();
}
int post_wait_num_frames = rfso_d.render_frame_count();
EXPECT_EQ(post_wait_num_frames, post_nav_num_frames);
// 5) Navigate back to A(B).
ASSERT_TRUE(HistoryGoBack(web_contents()));
// 6) Ensure C is cached and A's owner is updated.
EXPECT_TRUE(rfh_c->IsInBackForwardCache());
EXPECT_EQ(rfh_a.get(), web_contents()->GetPrimaryMainFrame());
EXPECT_EQ(expected_parent_ftn, rfh_a->owner_);
EXPECT_EQ(expected_child_ftn, rfh_b->owner_);
EXPECT_EQ(nullptr, rfh_c->owner_);
// Ensure that the OOPIF became visible and submitted a frame. If this times
// out then D failed to become visible again.
rfso_d.WaitForAnyFrameSubmission();
}
// Tests that when a RenderFrameHost is stored in BFCache, that when it is
// evicted, that both it and its child frames have their viz::SurfaceIds
// collected for eviction.
IN_PROC_BROWSER_TEST_F(RenderFrameHostImplBrowserTestWithBFCache,
EvictionInBFCache) {
GURL url_a(embedded_test_server()->GetURL(
"a.com", "/cross_site_iframe_factory.html?a(b)"));
GURL url_c(embedded_test_server()->GetURL("c.com", "/title2.html"));
// 1) Navigate to A(B).
EXPECT_TRUE(NavigateToURL(shell(), url_a));
RenderFrameHostImpl* rfh_a = web_contents()->GetPrimaryMainFrame();
RenderFrameHostImpl* rfh_b = rfh_a->child_at(0)->current_frame_host();
FrameTreeNode* expected_parent_ftn = rfh_a->frame_tree_node();
FrameTreeNode* expected_child_ftn = rfh_b->frame_tree_node();
viz::SurfaceId id_a = GetSurfaceId(expected_parent_ftn);
// On slower machines the Main-thread for the child frame may not have
// completed blink::RemoteFrameView::UpdateViewportIntersectionsForSubtree
// which can advance the viz::SurfaceId. The final may be newer than this, but
// from the same viz::FrameSink and viz::LocalSurfaceId::embed_token, so we
// cache now anyways.
viz::SurfaceId id_b = GetSurfaceId(expected_child_ftn);
EXPECT_TRUE(id_a.is_valid());
EXPECT_TRUE(id_b.is_valid());
// Ensure that they are separate surfaces and that site-isolation of test
// setup has not regressed.
EXPECT_NE(id_a, id_b);
// 2) Navigate to C.
EXPECT_TRUE(NavigateToURL(shell(), url_c));
RenderFrameHostImpl* rfh_c = web_contents()->GetPrimaryMainFrame();
// 3) Ensure A(B) are cached.
EXPECT_TRUE(rfh_a->IsInBackForwardCache());
EXPECT_TRUE(rfh_b->IsInBackForwardCache());
EXPECT_FALSE(rfh_c->IsInBackForwardCache());
EXPECT_NE(rfh_a, rfh_c);
EXPECT_EQ(nullptr, rfh_a->owner_);
EXPECT_EQ(expected_child_ftn, rfh_b->owner_);
EXPECT_EQ(expected_parent_ftn, rfh_c->owner_);
// Collect the viz::SurfaceIds to evict. We should find both `id_a` and
// `id_b`.
RenderViewHostImpl* rvh_a =
static_cast<RenderViewHostImpl*>(rfh_a->GetRenderViewHost());
std::vector<viz::SurfaceId> ids = rvh_a->CollectSurfaceIdsForEviction();
EXPECT_EQ(ids.size(), 2u);
EXPECT_TRUE(ContainsSurfaceIdOrNewer(ids, id_a));
EXPECT_TRUE(ContainsSurfaceIdOrNewer(ids, id_b));
}
class RenderFrameHostImplPrerenderBrowserTest
: public RenderFrameHostImplBrowserTest {
public:
RenderFrameHostImplPrerenderBrowserTest()
: prerender_helper_(base::BindRepeating(
&RenderFrameHostImplPrerenderBrowserTest::GetWebContents,
base::Unretained(this))) {}
test::PrerenderTestHelper& prerender_helper() { return prerender_helper_; }
WebContents* GetWebContents() { return shell()->web_contents(); }
private:
test::PrerenderTestHelper prerender_helper_;
};
IN_PROC_BROWSER_TEST_F(RenderFrameHostImplPrerenderBrowserTest,
KeepPrerenderRFHOwnerAfterActivation) {
GURL url_a = embedded_test_server()->GetURL("/title1.html");
GURL prerender_url = embedded_test_server()->GetURL("/title2.html");
EXPECT_TRUE(NavigateToURL(shell(), url_a));
RenderFrameHostImpl* rfh_a = web_contents()->GetPrimaryMainFrame();
FrameTreeNode* expected_ftn = rfh_a->frame_tree_node();
// Load a page in the prerender.
FrameTreeNodeId host_id = prerender_helper().AddPrerender(prerender_url);
RenderFrameHostImpl* prerender_frame_host = static_cast<RenderFrameHostImpl*>(
prerender_helper().GetPrerenderedMainFrameHost(host_id));
EXPECT_NE(rfh_a->owner_, prerender_frame_host->owner_);
// Activate the prerendered page.
prerender_helper().NavigatePrimaryPage(prerender_url);
RenderFrameHostImpl* activated_rfh = web_contents()->GetPrimaryMainFrame();
EXPECT_EQ(prerender_frame_host, activated_rfh);
EXPECT_EQ(expected_ftn, activated_rfh->owner_);
}
IN_PROC_BROWSER_TEST_F(RenderFrameHostImplPrerenderBrowserTest,
NewContentTimeoutIsNotSetInPrerender) {
GURL url_a = embedded_test_server()->GetURL("/title1.html");
GURL prerender_url = embedded_test_server()->GetURL("/title2.html");
EXPECT_TRUE(NavigateToURL(shell(), url_a));
// Load a page in the prerender.
FrameTreeNodeId host_id = prerender_helper().AddPrerender(prerender_url);
RenderFrameHostImpl* prerender_frame_host = static_cast<RenderFrameHostImpl*>(
prerender_helper().GetPrerenderedMainFrameHost(host_id));
EXPECT_TRUE(prerender_frame_host);
RenderWidgetHostImpl* prerender_rwhi = RenderWidgetHostImpl::From(
prerender_frame_host->GetView()->GetRenderWidgetHost());
EXPECT_FALSE(prerender_rwhi->IsContentRenderingTimeoutRunning());
// Activate the prerendered page.
prerender_helper().NavigatePrimaryPage(prerender_url);
RenderFrameHostImpl* activated_rfh = web_contents()->GetPrimaryMainFrame();
RenderWidgetHostImpl* activated_rwhi = RenderWidgetHostImpl::From(
activated_rfh->GetView()->GetRenderWidgetHost());
EXPECT_EQ(activated_rwhi, prerender_rwhi);
EXPECT_TRUE(activated_rwhi->IsContentRenderingTimeoutRunning());
}
IN_PROC_BROWSER_TEST_F(RenderFrameHostImplPrerenderBrowserTest,
ActivationSurfaceRangeIncludesFallback) {
GURL url_a = embedded_test_server()->GetURL("/title1.html");
GURL prerender_url = embedded_test_server()->GetURL("/title2.html");
EXPECT_TRUE(NavigateToURL(shell(), url_a));
// Load a page in the prerender.
prerender_helper().AddPrerender(prerender_url);
RenderWidgetHostViewBase* initial_view =
RenderWidgetHostImpl::From(web_contents()
->GetPrimaryMainFrame()
->GetView()
->GetRenderWidgetHost())
->GetView();
viz::SurfaceId initial_surface_id = initial_view->GetCurrentSurfaceId();
EXPECT_TRUE(initial_surface_id.is_valid());
// Activate the prerendered page.
prerender_helper().NavigatePrimaryPage(prerender_url);
RenderWidgetHostViewBase* activated_view =
RenderWidgetHostImpl::From(web_contents()
->GetPrimaryMainFrame()
->GetView()
->GetRenderWidgetHost())
->GetView();
EXPECT_NE(activated_view, initial_view);
#if defined(USE_AURA)
DelegatedFrameHost* activated_dfh =
static_cast<RenderWidgetHostViewAura*>(activated_view)
->GetDelegatedFrameHostForTesting();
viz::SurfaceId fallback_surface_id =
activated_dfh->GetFallbackSurfaceIdForTesting();
EXPECT_TRUE(initial_surface_id.IsSameOrNewerThan(fallback_surface_id));
#elif BUILDFLAG(IS_ANDROID)
ui::DelegatedFrameHostAndroid* activated_dfh =
static_cast<RenderWidgetHostViewAndroid*>(activated_view)
->delegated_frame_host_for_testing();
viz::SurfaceId fallback_surface_id =
activated_dfh->GetFallbackSurfaceIdForTesting();
EXPECT_TRUE(initial_surface_id.IsSameOrNewerThan(fallback_surface_id))
<< initial_surface_id.ToString() << " " << fallback_surface_id.ToString();
#endif
}
using RenderFrameHostImplDeathTest = RenderFrameHostImplBrowserTest;
IN_PROC_BROWSER_TEST_F(RenderFrameHostImplDeathTest,
ReloadInPendingDeletionOrBFCache) {
GURL url_a(embedded_test_server()->GetURL("a.com", "/title1.html"));
GURL url_b(embedded_test_server()->GetURL("b.com", "/title2.html"));
// Navigate to A.
EXPECT_TRUE(NavigateToURL(shell(), url_a));
RenderFrameHostImpl* rfh_a = web_contents()->GetPrimaryMainFrame();
// Leave rfh_a in pending deletion state.
LeaveInPendingDeletionState(rfh_a);
// Navigate to B.
EXPECT_TRUE(NavigateToURL(shell(), url_b));
EXPECT_TRUE(rfh_a->IsPendingDeletion() || rfh_a->IsInBackForwardCache());
EXPECT_CHECK_DEATH(rfh_a->Reload());
}
class RenderFrameHostImplUrgentNavigationIPCBrowserTest
: public RenderFrameHostImplBrowserTest,
public testing::WithParamInterface<bool> {
public:
RenderFrameHostImplUrgentNavigationIPCBrowserTest() {
if (RenderDocumentEnabled()) {
scoped_feature_list_.InitWithFeaturesAndParameters(
/*enabled_features=*/
{{features::kRenderDocument, {{"level", "all-frames"}}}},
/*disabled_features=*/{});
} else {
scoped_feature_list_.InitWithFeatures(
/*enabled_features=*/{},
/*disabled_features=*/{features::kRenderDocument});
}
}
~RenderFrameHostImplUrgentNavigationIPCBrowserTest() override = default;
private:
void SetUpCommandLine(base::CommandLine* command_line) override {
// Override RenderFrameHostImplBrowserTest command line switches, which
// aren't needed for this test.
base::CommandLine::ForCurrentProcess()->AppendSwitchASCII(
switches::kEnableBlinkFeatures, "SchedulerYield");
}
bool RenderDocumentEnabled() { return GetParam(); }
base::test::ScopedFeatureList scoped_feature_list_;
};
IN_PROC_BROWSER_TEST_P(RenderFrameHostImplUrgentNavigationIPCBrowserTest,
UrgentMessageNavigationIPCs) {
GURL url(embedded_test_server()->GetURL("a.com", "/title1.html"));
EXPECT_TRUE(NavigateToURL(shell(), url));
std::string script =
"function spin(howLong) {"
" const start = performance.now();"
" while (performance.now() - start < howLong);"
"}"
"window.onbeforeunload = () => spin(5);"
"async function runTest() {"
" while (true) {"
" spin(5);"
" await scheduler.yield()"
" }"
"}"
"runTest()";
EXPECT_TRUE(
ExecJs(web_contents(), script, EXECUTE_SCRIPT_NO_RESOLVE_PROMISES));
// Disable the hang monitor to ensure the beforeunload task is prioritized.
web_contents()
->GetPrimaryMainFrame()
->DisableBeforeUnloadHangMonitorForTesting();
// Reload. The loop shouldn't cause WaitForLoadStop to hang.
web_contents()->GetController().Reload(ReloadType::NORMAL, false);
EXPECT_TRUE(WaitForLoadStop(web_contents()));
}
INSTANTIATE_TEST_SUITE_P(All,
RenderFrameHostImplUrgentNavigationIPCBrowserTest,
/*RenderDocumentEnabled()*/ testing::Bool());
} // namespace content
|