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
|
// Copyright 2016 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/navigation_request.h"
#include <memory>
#include "base/command_line.h"
#include "base/files/scoped_temp_dir.h"
#include "base/functional/bind.h"
#include "base/memory/raw_ptr.h"
#include "base/memory/weak_ptr.h"
#include "base/strings/strcat.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/stringprintf.h"
#include "base/test/bind.h"
#include "base/test/metrics/histogram_tester.h"
#include "build/build_config.h"
#include "content/browser/process_lock.h"
#include "content/browser/renderer_host/debug_urls.h"
#include "content/browser/renderer_host/navigation_controller_impl.h"
#include "content/browser/renderer_host/render_frame_host_impl.h"
#include "content/browser/site_instance_impl.h"
#include "content/browser/web_contents/web_contents_impl.h"
#include "content/common/content_navigation_policy.h"
#include "content/public/browser/browser_task_traits.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/navigation_throttle.h"
#include "content/public/browser/runtime_feature_state/runtime_feature_state_document_data.h"
#include "content/public/browser/site_isolation_policy.h"
#include "content/public/browser/web_contents.h"
#include "content/public/browser/web_contents_observer.h"
#include "content/public/common/bindings_policy.h"
#include "content/public/common/content_features.h"
#include "content/public/common/content_switches.h"
#include "content/public/common/result_codes.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/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/fenced_frame_test_util.h"
#include "content/public/test/mock_web_contents_observer.h"
#include "content/public/test/navigation_handle_observer.h"
#include "content/public/test/prerender_test_util.h"
#include "content/public/test/test_frame_navigation_observer.h"
#include "content/public/test/test_navigation_observer.h"
#include "content/public/test/test_service.mojom.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_download_manager_delegate.h"
#include "content/test/content_browser_test_utils_internal.h"
#include "content/test/mock_commit_deferring_condition.h"
#include "net/dns/mock_host_resolver.h"
#include "net/test/embedded_test_server/controllable_http_response.h"
#include "net/test/embedded_test_server/default_handlers.h"
#include "net/test/url_request/url_request_failed_job.h"
#include "services/network/public/cpp/loading_params.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "third_party/blink/public/common/chrome_debug_urls.h"
#include "third_party/blink/public/common/runtime_feature_state/runtime_feature_state_context.h"
#include "third_party/blink/public/common/runtime_feature_state/runtime_feature_state_read_context.h"
#include "third_party/blink/public/mojom/fetch/fetch_api_request.mojom.h"
#include "third_party/blink/public/mojom/runtime_feature_state/runtime_feature.mojom.h"
#include "ui/base/page_transition_types.h"
#include "url/scheme_host_port.h"
#include "url/url_constants.h"
namespace {
// Text to place in an HTML body. Should not contain any markup.
const char kBodyTextContent[] = "some plain text content";
} // namespace
namespace content {
namespace {
// A test NavigationThrottle that will return pre-determined checks and run
// callbacks when the various NavigationThrottle methods are called. It is
// not instantiated directly but through a TestNavigationThrottleInstaller.
class TestNavigationThrottle : public NavigationThrottle {
public:
TestNavigationThrottle(
NavigationHandle* handle,
NavigationThrottle::ThrottleCheckResult will_start_result,
NavigationThrottle::ThrottleCheckResult will_redirect_result,
NavigationThrottle::ThrottleCheckResult will_fail_result,
NavigationThrottle::ThrottleCheckResult will_process_result,
NavigationThrottle::ThrottleCheckResult
will_commit_without_url_loader_result,
base::OnceClosure did_call_will_start,
base::OnceClosure did_call_will_redirect,
base::OnceClosure did_call_will_fail,
base::OnceClosure did_call_will_process,
base::OnceClosure did_call_will_commit_without_url_loader)
: NavigationThrottle(handle),
will_start_result_(will_start_result),
will_redirect_result_(will_redirect_result),
will_fail_result_(will_fail_result),
will_process_result_(will_process_result),
will_commit_without_url_loader_result_(
will_commit_without_url_loader_result),
did_call_will_start_(std::move(did_call_will_start)),
did_call_will_redirect_(std::move(did_call_will_redirect)),
did_call_will_fail_(std::move(did_call_will_fail)),
did_call_will_process_(std::move(did_call_will_process)),
did_call_will_commit_without_url_loader_(
std::move(did_call_will_commit_without_url_loader)) {}
~TestNavigationThrottle() override = default;
const char* GetNameForLogging() override { return "TestNavigationThrottle"; }
blink::mojom::RequestContextType request_context_type() {
return request_context_type_;
}
// Expose Resume and Cancel to the installer.
void ResumeNavigation() { Resume(); }
void CancelNavigation(NavigationThrottle::ThrottleCheckResult result) {
CancelDeferredNavigation(result);
}
private:
// NavigationThrottle implementation.
NavigationThrottle::ThrottleCheckResult WillStartRequest() override {
NavigationRequest* navigation_request =
NavigationRequest::From(navigation_handle());
CHECK_NE(blink::mojom::RequestContextType::UNSPECIFIED,
navigation_request->request_context_type());
request_context_type_ = navigation_request->request_context_type();
GetUIThreadTaskRunner({})->PostTask(FROM_HERE,
std::move(did_call_will_start_));
return will_start_result_;
}
NavigationThrottle::ThrottleCheckResult WillRedirectRequest() override {
NavigationRequest* navigation_request =
NavigationRequest::From(navigation_handle());
CHECK_EQ(request_context_type_, navigation_request->request_context_type());
GetUIThreadTaskRunner({})->PostTask(FROM_HERE,
std::move(did_call_will_redirect_));
return will_redirect_result_;
}
NavigationThrottle::ThrottleCheckResult WillFailRequest() override {
NavigationRequest* navigation_request =
NavigationRequest::From(navigation_handle());
CHECK_EQ(request_context_type_, navigation_request->request_context_type());
GetUIThreadTaskRunner({})->PostTask(FROM_HERE,
std::move(did_call_will_fail_));
return will_fail_result_;
}
NavigationThrottle::ThrottleCheckResult WillProcessResponse() override {
NavigationRequest* navigation_request =
NavigationRequest::From(navigation_handle());
CHECK_EQ(request_context_type_, navigation_request->request_context_type());
GetUIThreadTaskRunner({})->PostTask(FROM_HERE,
std::move(did_call_will_process_));
return will_process_result_;
}
NavigationThrottle::ThrottleCheckResult WillCommitWithoutUrlLoader()
override {
NavigationRequest* navigation_request =
NavigationRequest::From(navigation_handle());
CHECK_NE(blink::mojom::RequestContextType::UNSPECIFIED,
navigation_request->request_context_type());
request_context_type_ = navigation_request->request_context_type();
GetUIThreadTaskRunner({})->PostTask(
FROM_HERE, std::move(did_call_will_commit_without_url_loader_));
return will_commit_without_url_loader_result_;
}
NavigationThrottle::ThrottleCheckResult will_start_result_;
NavigationThrottle::ThrottleCheckResult will_redirect_result_;
NavigationThrottle::ThrottleCheckResult will_fail_result_;
NavigationThrottle::ThrottleCheckResult will_process_result_;
NavigationThrottle::ThrottleCheckResult
will_commit_without_url_loader_result_;
base::OnceClosure did_call_will_start_;
base::OnceClosure did_call_will_redirect_;
base::OnceClosure did_call_will_fail_;
base::OnceClosure did_call_will_process_;
base::OnceClosure did_call_will_commit_without_url_loader_;
blink::mojom::RequestContextType request_context_type_ =
blink::mojom::RequestContextType::UNSPECIFIED;
};
// Installs a TestNavigationThrottle either on all following requests or on
// requests with an expected starting URL, and allows waiting for various
// NavigationThrottle related events. Waiting works only for the immediately
// next navigation. New instances are needed to wait for further navigations.
class TestNavigationThrottleInstaller : public WebContentsObserver {
public:
enum Method {
WILL_START_REQUEST,
WILL_REDIRECT_REQUEST,
WILL_FAIL_REQUEST,
WILL_PROCESS_RESPONSE,
WILL_COMMIT_WITHOUT_URL_LOADER,
};
TestNavigationThrottleInstaller(
WebContents* web_contents,
NavigationThrottle::ThrottleCheckResult will_start_result,
NavigationThrottle::ThrottleCheckResult will_redirect_result,
NavigationThrottle::ThrottleCheckResult will_fail_result,
NavigationThrottle::ThrottleCheckResult will_process_result,
NavigationThrottle::ThrottleCheckResult
will_commit_without_url_loader_result,
const GURL& expected_start_url = GURL())
: WebContentsObserver(web_contents),
will_start_result_(will_start_result),
will_redirect_result_(will_redirect_result),
will_fail_result_(will_fail_result),
will_process_result_(will_process_result),
will_commit_without_url_loader_result_(
will_commit_without_url_loader_result),
expected_start_url_(expected_start_url) {}
~TestNavigationThrottleInstaller() override = default;
// Installs a TestNavigationThrottle whose |method| method will return
// |result|. All other methods will return NavigationThrottle::PROCEED.
static std::unique_ptr<TestNavigationThrottleInstaller> CreateForMethod(
WebContents* web_contents,
Method method,
NavigationThrottle::ThrottleCheckResult result) {
NavigationThrottle::ThrottleCheckResult will_start_result =
NavigationThrottle::PROCEED;
auto will_redirect_result = will_start_result;
auto will_fail_result = will_start_result;
auto will_process_result = will_start_result;
auto will_commit_without_url_loader_result = will_start_result;
switch (method) {
case WILL_START_REQUEST:
will_start_result = result;
break;
case WILL_REDIRECT_REQUEST:
will_redirect_result = result;
break;
case WILL_FAIL_REQUEST:
will_fail_result = result;
break;
case WILL_PROCESS_RESPONSE:
will_process_result = result;
break;
case WILL_COMMIT_WITHOUT_URL_LOADER:
will_commit_without_url_loader_result = result;
break;
}
return std::make_unique<TestNavigationThrottleInstaller>(
web_contents, will_start_result, will_redirect_result, will_fail_result,
will_process_result, will_commit_without_url_loader_result);
}
TestNavigationThrottle* navigation_throttle() { return navigation_throttle_; }
void WaitForThrottleWillStart() {
if (will_start_called_) {
return;
}
will_start_loop_runner_ = new MessageLoopRunner();
will_start_loop_runner_->Run();
will_start_loop_runner_ = nullptr;
}
void WaitForThrottleWillRedirect() {
if (will_redirect_called_) {
return;
}
will_redirect_loop_runner_ = new MessageLoopRunner();
will_redirect_loop_runner_->Run();
will_redirect_loop_runner_ = nullptr;
}
void WaitForThrottleWillFail() {
if (will_fail_called_) {
return;
}
will_fail_loop_runner_ = new MessageLoopRunner();
will_fail_loop_runner_->Run();
will_fail_loop_runner_ = nullptr;
}
void WaitForThrottleWillProcess() {
if (will_process_called_) {
return;
}
will_process_loop_runner_ = new MessageLoopRunner();
will_process_loop_runner_->Run();
will_process_loop_runner_ = nullptr;
}
void WaitForThrottleWillCommitWithoutUrlLoader() {
if (will_commit_without_url_loader_called_) {
return;
}
will_commit_without_url_loader_loop_runner_ = new MessageLoopRunner();
will_commit_without_url_loader_loop_runner_->Run();
will_commit_without_url_loader_loop_runner_ = nullptr;
}
void Continue(NavigationThrottle::ThrottleCheckResult result) {
ASSERT_NE(NavigationThrottle::DEFER, result.action());
if (result.action() == NavigationThrottle::PROCEED) {
navigation_throttle()->ResumeNavigation();
} else {
navigation_throttle()->CancelNavigation(result);
}
}
int will_start_called() { return will_start_called_; }
int will_redirect_called() { return will_redirect_called_; }
int will_fail_called() { return will_fail_called_; }
int will_process_called() { return will_process_called_; }
int will_commit_without_url_loader_called() {
return will_commit_without_url_loader_called_;
}
int install_count() { return install_count_; }
protected:
virtual void DidCallWillStartRequest() {
will_start_called_++;
if (will_start_loop_runner_) {
will_start_loop_runner_->Quit();
}
}
virtual void DidCallWillRedirectRequest() {
will_redirect_called_++;
if (will_redirect_loop_runner_) {
will_redirect_loop_runner_->Quit();
}
}
virtual void DidCallWillFailRequest() {
will_fail_called_++;
if (will_fail_loop_runner_) {
will_fail_loop_runner_->Quit();
}
}
virtual void DidCallWillProcessResponse() {
will_process_called_++;
if (will_process_loop_runner_) {
will_process_loop_runner_->Quit();
}
}
virtual void DidCallWillCommitWithoutUrlLoader() {
will_commit_without_url_loader_called_++;
if (will_commit_without_url_loader_loop_runner_) {
will_commit_without_url_loader_loop_runner_->Quit();
}
}
private:
void DidStartNavigation(NavigationHandle* handle) override {
if (!expected_start_url_.is_empty() &&
handle->GetURL() != expected_start_url_) {
return;
}
std::unique_ptr<NavigationThrottle> throttle(new TestNavigationThrottle(
handle, will_start_result_, will_redirect_result_, will_fail_result_,
will_process_result_, will_commit_without_url_loader_result_,
base::BindOnce(
&TestNavigationThrottleInstaller::DidCallWillStartRequest,
weak_factory_.GetWeakPtr()),
base::BindOnce(
&TestNavigationThrottleInstaller::DidCallWillRedirectRequest,
weak_factory_.GetWeakPtr()),
base::BindOnce(&TestNavigationThrottleInstaller::DidCallWillFailRequest,
weak_factory_.GetWeakPtr()),
base::BindOnce(
&TestNavigationThrottleInstaller::DidCallWillProcessResponse,
weak_factory_.GetWeakPtr()),
base::BindOnce(
&TestNavigationThrottleInstaller::DidCallWillCommitWithoutUrlLoader,
weak_factory_.GetWeakPtr())));
navigation_throttle_ = static_cast<TestNavigationThrottle*>(throttle.get());
handle->RegisterThrottleForTesting(std::move(throttle));
++install_count_;
}
void DidFinishNavigation(NavigationHandle* handle) override {
if (!navigation_throttle_) {
return;
}
if (handle == navigation_throttle_->navigation_handle()) {
navigation_throttle_ = nullptr;
}
}
NavigationThrottle::ThrottleCheckResult will_start_result_;
NavigationThrottle::ThrottleCheckResult will_redirect_result_;
NavigationThrottle::ThrottleCheckResult will_fail_result_;
NavigationThrottle::ThrottleCheckResult will_process_result_;
NavigationThrottle::ThrottleCheckResult
will_commit_without_url_loader_result_;
int will_start_called_ = 0;
int will_redirect_called_ = 0;
int will_fail_called_ = 0;
int will_process_called_ = 0;
int will_commit_without_url_loader_called_ = 0;
raw_ptr<TestNavigationThrottle> navigation_throttle_ = nullptr;
int install_count_ = 0;
scoped_refptr<MessageLoopRunner> will_start_loop_runner_;
scoped_refptr<MessageLoopRunner> will_redirect_loop_runner_;
scoped_refptr<MessageLoopRunner> will_fail_loop_runner_;
scoped_refptr<MessageLoopRunner> will_process_loop_runner_;
scoped_refptr<MessageLoopRunner> will_commit_without_url_loader_loop_runner_;
GURL expected_start_url_;
// The throttle installer can be deleted before all tasks posted by its
// throttles are run, so it must be referenced via weak pointers.
base::WeakPtrFactory<TestNavigationThrottleInstaller> weak_factory_{this};
};
// Same as above, but installs NavigationThrottles that do not directly return
// the pre-programmed check results, but first DEFER the navigation at each
// stage and then resume/cancel asynchronously.
class TestDeferringNavigationThrottleInstaller
: public TestNavigationThrottleInstaller {
public:
TestDeferringNavigationThrottleInstaller(
WebContents* web_contents,
NavigationThrottle::ThrottleCheckResult will_start_result,
NavigationThrottle::ThrottleCheckResult will_redirect_result,
NavigationThrottle::ThrottleCheckResult will_fail_result,
NavigationThrottle::ThrottleCheckResult will_process_result,
NavigationThrottle::ThrottleCheckResult
will_commit_without_url_loader_result,
GURL expected_start_url = GURL())
: TestNavigationThrottleInstaller(web_contents,
NavigationThrottle::DEFER,
NavigationThrottle::DEFER,
NavigationThrottle::DEFER,
NavigationThrottle::DEFER,
NavigationThrottle::DEFER,
expected_start_url),
will_start_deferred_result_(will_start_result),
will_redirect_deferred_result_(will_redirect_result),
will_fail_deferred_result_(will_fail_result),
will_process_deferred_result_(will_process_result),
will_commit_without_url_loader_result_(
will_commit_without_url_loader_result) {}
protected:
void DidCallWillStartRequest() override {
TestNavigationThrottleInstaller::DidCallWillStartRequest();
Continue(will_start_deferred_result_);
}
void DidCallWillRedirectRequest() override {
TestNavigationThrottleInstaller::DidCallWillStartRequest();
Continue(will_redirect_deferred_result_);
}
void DidCallWillFailRequest() override {
TestNavigationThrottleInstaller::DidCallWillStartRequest();
Continue(will_fail_deferred_result_);
}
void DidCallWillProcessResponse() override {
TestNavigationThrottleInstaller::DidCallWillStartRequest();
Continue(will_process_deferred_result_);
}
void DidCallWillCommitWithoutUrlLoader() override {
TestNavigationThrottleInstaller::DidCallWillCommitWithoutUrlLoader();
Continue(will_commit_without_url_loader_result_);
}
private:
NavigationThrottle::ThrottleCheckResult will_start_deferred_result_;
NavigationThrottle::ThrottleCheckResult will_redirect_deferred_result_;
NavigationThrottle::ThrottleCheckResult will_fail_deferred_result_;
NavigationThrottle::ThrottleCheckResult will_process_deferred_result_;
NavigationThrottle::ThrottleCheckResult
will_commit_without_url_loader_result_;
};
// Records all navigation start URLs from the WebContents.
class NavigationStartUrlRecorder : public WebContentsObserver {
public:
explicit NavigationStartUrlRecorder(WebContents* web_contents)
: WebContentsObserver(web_contents) {}
void DidStartNavigation(NavigationHandle* navigation_handle) override {
urls_.push_back(navigation_handle->GetURL());
}
const std::vector<GURL>& urls() const { return urls_; }
private:
std::vector<GURL> urls_;
};
void ExpectChildFrameSetAsCollapsedInFTN(Shell* shell, bool expect_collapsed) {
// Check if the frame should be collapsed in theory as per FTN.
FrameTreeNode* root = static_cast<WebContentsImpl*>(shell->web_contents())
->GetPrimaryFrameTree()
.root();
ASSERT_EQ(1u, root->child_count());
FrameTreeNode* child = root->child_at(0u);
EXPECT_EQ(expect_collapsed, child->is_collapsed());
}
void ExpectChildFrameCollapsedInLayout(Shell* shell,
const std::string& frame_id,
bool expect_collapsed) {
// Check if the frame is collapsed in practice.
const char kScript[] = "document.getElementById(\"%s\").clientWidth;";
int client_width =
EvalJs(shell, base::StringPrintf(kScript, frame_id.c_str())).ExtractInt();
EXPECT_EQ(expect_collapsed, !client_width) << client_width;
}
void ExpectChildFrameCollapsed(Shell* shell,
const std::string& frame_id,
bool expect_collapsed) {
ExpectChildFrameSetAsCollapsedInFTN(shell, expect_collapsed);
ExpectChildFrameCollapsedInLayout(shell, frame_id, expect_collapsed);
}
} // namespace
class NavigationRequestBrowserTest : public ContentBrowserTest {
public:
WebContentsImpl* contents() const {
return static_cast<WebContentsImpl*>(shell()->web_contents());
}
protected:
void SetUpOnMainThread() override {
host_resolver()->AddRule("*", "127.0.0.1");
SetupCrossSiteRedirector(embedded_test_server());
ASSERT_TRUE(embedded_test_server()->Start());
}
// Installs a NavigationThrottle whose |method| method will return a
// ThrottleCheckResult with |action|, net::ERR_BLOCKED_BY_CLIENT and
// a custom error page. Navigates to |url|, checks that the navigation
// committed and that the custom error page is being shown.
void InstallThrottleAndTestNavigationCommittedWithErrorPage(
const GURL& url,
NavigationThrottle::ThrottleAction action,
TestNavigationThrottleInstaller::Method method) {
auto installer = TestNavigationThrottleInstaller::CreateForMethod(
shell()->web_contents(), method,
NavigationThrottle::ThrottleCheckResult(
action, net::ERR_BLOCKED_BY_CLIENT,
base::StringPrintf("<html><body>%s</body><html>",
kBodyTextContent)));
NavigationHandleObserver observer(shell()->web_contents(), url);
EXPECT_FALSE(NavigateToURL(shell(), url));
EXPECT_TRUE(observer.has_committed());
EXPECT_TRUE(observer.is_error());
content::RenderFrameHost* rfh =
shell()->web_contents()->GetPrimaryMainFrame();
EXPECT_EQ(kBodyTextContent, EvalJs(rfh, "document.body.textContent"));
}
};
// A test class that calls IsolateAllSitesForTesting() early enough in the setup
// that we get consistent results for AreOriginKeyedProcessesEnabledByDefault()
// if kOriginKeyedProcessesByDefault is enabled. Specifically, make sure the
// initial shell's main frame's BrowsingInstance gets the correct default
// isolation state, which depends on AreOriginKeyedProcessesEnabledByDefault().
class NavigationRequestBrowserTest_IsolateAllSites
: public NavigationRequestBrowserTest {
void SetUpCommandLine(base::CommandLine* command_line) override {
NavigationRequestBrowserTest::SetUpCommandLine(command_line);
IsolateAllSitesForTesting(command_line);
}
};
class NavigationRequestDownloadBrowserTest
: public NavigationRequestBrowserTest {
protected:
void SetUpOnMainThread() override {
NavigationRequestBrowserTest::SetUpOnMainThread();
// Set up a test download directory, in order to prevent prompting for
// handling downloads.
ASSERT_TRUE(downloads_directory_.CreateUniqueTempDir());
ShellDownloadManagerDelegate* delegate =
static_cast<ShellDownloadManagerDelegate*>(
shell()
->web_contents()
->GetBrowserContext()
->GetDownloadManagerDelegate());
delegate->SetDownloadBehaviorForTesting(downloads_directory_.GetPath());
}
private:
base::ScopedTempDir downloads_directory_;
};
// Ensure that PageTransition is properly set on the NavigationHandle.
IN_PROC_BROWSER_TEST_F(NavigationRequestBrowserTest, VerifyPageTransition) {
{
// Test browser initiated navigation, which should have a PageTransition as
// if it came from the omnibox.
GURL url(embedded_test_server()->GetURL("/title1.html"));
NavigationHandleObserver observer(shell()->web_contents(), url);
ui::PageTransition expected_transition = ui::PageTransitionFromInt(
ui::PAGE_TRANSITION_TYPED | ui::PAGE_TRANSITION_FROM_ADDRESS_BAR);
EXPECT_TRUE(NavigateToURL(shell(), url));
EXPECT_TRUE(observer.has_committed());
EXPECT_FALSE(observer.is_error());
EXPECT_EQ(url, observer.last_committed_url());
EXPECT_TRUE(ui::PageTransitionTypeIncludingQualifiersIs(
observer.page_transition(), expected_transition));
}
{
// Test navigating to a page with subframe. The subframe will have
// PageTransition of type AUTO_SUBFRAME.
GURL url(
embedded_test_server()->GetURL("/frame_tree/page_with_one_frame.html"));
NavigationHandleObserver observer(
shell()->web_contents(),
embedded_test_server()->GetURL("/cross-site/baz.com/title1.html"));
ui::PageTransition expected_transition =
ui::PageTransitionFromInt(ui::PAGE_TRANSITION_AUTO_SUBFRAME);
EXPECT_TRUE(NavigateToURL(shell(), url));
EXPECT_TRUE(observer.has_committed());
EXPECT_FALSE(observer.is_error());
EXPECT_EQ(embedded_test_server()->GetURL("baz.com", "/title1.html"),
observer.last_committed_url());
EXPECT_TRUE(ui::PageTransitionTypeIncludingQualifiersIs(
observer.page_transition(), expected_transition));
EXPECT_FALSE(observer.is_main_frame());
}
}
// Ensure that the following methods on NavigationHandle behave correctly:
// * IsInMainFrame
IN_PROC_BROWSER_TEST_F(NavigationRequestBrowserTest, VerifyFrameTree) {
GURL main_url(embedded_test_server()->GetURL(
"a.com", "/cross_site_iframe_factory.html?a(b(c))"));
GURL b_url(embedded_test_server()->GetURL(
"b.com", "/cross_site_iframe_factory.html?b(c())"));
GURL c_url(embedded_test_server()->GetURL(
"c.com", "/cross_site_iframe_factory.html?c()"));
NavigationHandleObserver main_observer(shell()->web_contents(), main_url);
NavigationHandleObserver b_observer(shell()->web_contents(), b_url);
NavigationHandleObserver c_observer(shell()->web_contents(), c_url);
EXPECT_TRUE(NavigateToURL(shell(), main_url));
FrameTreeNode* root = static_cast<WebContentsImpl*>(shell()->web_contents())
->GetPrimaryFrameTree()
.root();
// Verify the main frame.
EXPECT_TRUE(main_observer.has_committed());
EXPECT_FALSE(main_observer.is_error());
EXPECT_EQ(main_url, main_observer.last_committed_url());
EXPECT_TRUE(main_observer.is_main_frame());
EXPECT_EQ(root->frame_tree_node_id(), main_observer.frame_tree_node_id());
// Verify the b.com frame.
EXPECT_TRUE(b_observer.has_committed());
EXPECT_FALSE(b_observer.is_error());
EXPECT_EQ(b_url, b_observer.last_committed_url());
EXPECT_FALSE(b_observer.is_main_frame());
EXPECT_EQ(root->child_at(0)->frame_tree_node_id(),
b_observer.frame_tree_node_id());
// Verify the c.com frame.
EXPECT_TRUE(c_observer.has_committed());
EXPECT_FALSE(c_observer.is_error());
EXPECT_EQ(c_url, c_observer.last_committed_url());
EXPECT_FALSE(c_observer.is_main_frame());
EXPECT_EQ(root->child_at(0)->child_at(0)->frame_tree_node_id(),
c_observer.frame_tree_node_id());
}
// Ensure that the WasRedirected() method on NavigationHandle behaves correctly.
IN_PROC_BROWSER_TEST_F(NavigationRequestBrowserTest, VerifyRedirect) {
{
GURL url(embedded_test_server()->GetURL("/title1.html"));
NavigationHandleObserver observer(shell()->web_contents(), url);
EXPECT_TRUE(NavigateToURL(shell(), url));
EXPECT_TRUE(observer.has_committed());
EXPECT_FALSE(observer.is_error());
EXPECT_FALSE(observer.was_redirected());
}
{
GURL url(embedded_test_server()->GetURL("/cross-site/baz.com/title1.html"));
GURL final_url(embedded_test_server()->GetURL("baz.com", "/title1.html"));
NavigationHandleObserver observer(shell()->web_contents(), url);
EXPECT_TRUE(
NavigateToURL(shell(), url, final_url /* expected_commit_url */));
EXPECT_TRUE(observer.has_committed());
EXPECT_FALSE(observer.is_error());
EXPECT_TRUE(observer.was_redirected());
}
}
// Ensure that we can read and write to the browser process's copy of the blink
// runtime-enabled features via NavigationRequest's method
// GetMutableRuntimeFeatureStateContext() during commit. Then ensure that its
// values are persisted to the RenderFrameHostImpl's read-only context.
IN_PROC_BROWSER_TEST_F(NavigationRequestBrowserTest,
RuntimeFeatureStatePersisted) {
// Sets up the NavigationRequest where we can begin accessing the
// RuntimeFeatureStateContext class.
GURL url(embedded_test_server()->GetURL("/title1.html"));
TestNavigationManager manager(shell()->web_contents(), url);
// Begin loading our url and wait for the request to start.
shell()->LoadURL(url);
EXPECT_TRUE(manager.WaitForRequestStart());
// Ensure we can get and set values in RuntimeFeatureStateContext.
blink::RuntimeFeatureStateContext& context =
NavigationRequest::From(manager.GetNavigationHandle())
->GetMutableRuntimeFeatureStateContext();
bool is_test_feature_enabled(context.IsTestFeatureEnabled());
context.SetTestFeatureEnabled(!is_test_feature_enabled);
EXPECT_EQ(context.IsTestFeatureEnabled(), !is_test_feature_enabled);
// Check the override value map as well.
base::flat_map<::blink::mojom::RuntimeFeature, bool>
expected_feature_overrides = context.GetFeatureOverrides();
EXPECT_EQ(
expected_feature_overrides[blink::mojom::RuntimeFeature::kTestFeature],
!is_test_feature_enabled);
// Continue with the navigation until completion.
ASSERT_TRUE(manager.WaitForNavigationFinished());
EXPECT_TRUE(manager.was_successful());
// Check that the changes were saved to the RenderFrameHost.
RuntimeFeatureStateDocumentData* document_data =
RuntimeFeatureStateDocumentData::GetForCurrentDocument(
shell()->web_contents()->GetPrimaryMainFrame());
EXPECT_TRUE(document_data);
blink::RuntimeFeatureStateReadContext read_context =
document_data->runtime_feature_state_read_context();
EXPECT_EQ(expected_feature_overrides, read_context.GetFeatureOverrides());
}
// Similar to RuntimeFeatureStatePersisted but ensures that even for
// runtime-enabled feature values that are equivalent to the previous state.
// This is important to persist as it helps the renderer determine force-enabled
// and force-disabled values.
IN_PROC_BROWSER_TEST_F(NavigationRequestBrowserTest,
RuntimeFeatureStatePersistedForSameValue) {
// Sets up the NavigationRequest where we can begin accessing the
// RuntimeFeatureStateContext class.
GURL url(embedded_test_server()->GetURL("/title1.html"));
TestNavigationManager manager(shell()->web_contents(), url);
// Begin loading our url and wait for the request to start.
shell()->LoadURL(url);
EXPECT_TRUE(manager.WaitForRequestStart());
// Ensure we can set values in RuntimeFeatureStateContext that are
// equivalent to the feature's previous state.
blink::RuntimeFeatureStateContext& context =
NavigationRequest::From(manager.GetNavigationHandle())
->GetMutableRuntimeFeatureStateContext();
bool is_test_feature_enabled(context.IsTestFeatureEnabled());
context.SetTestFeatureEnabled(is_test_feature_enabled);
EXPECT_EQ(context.IsTestFeatureEnabled(), is_test_feature_enabled);
// Check the override value map as well.
base::flat_map<::blink::mojom::RuntimeFeature, bool>
expected_feature_overrides = context.GetFeatureOverrides();
EXPECT_EQ(
expected_feature_overrides[blink::mojom::RuntimeFeature::kTestFeature],
is_test_feature_enabled);
// Continue with the navigation until completion.
ASSERT_TRUE(manager.WaitForNavigationFinished());
EXPECT_TRUE(manager.was_successful());
// Check that the changes were saved to the RenderFrameHost's feature
// overrides.
RuntimeFeatureStateDocumentData* document_data =
RuntimeFeatureStateDocumentData::GetForCurrentDocument(
shell()->web_contents()->GetPrimaryMainFrame());
EXPECT_TRUE(document_data);
blink::RuntimeFeatureStateReadContext read_context =
document_data->runtime_feature_state_read_context();
EXPECT_EQ(expected_feature_overrides, read_context.GetFeatureOverrides());
}
// Similar to RuntimeFeatureStatePersisted but ensures that even for
// runtime-enabled feature values are cleared across redirects.
IN_PROC_BROWSER_TEST_F(NavigationRequestBrowserTest,
RuntimeFeatureStateClearOnRedirect) {
// Sets up the NavigationRequest where we can begin accessing the
// RuntimeFeatureStateContext class.
GURL redirect_url(
embedded_test_server()->GetURL("/cross-site/bar.com/title2.html"));
TestNavigationManager redirect_manager(shell()->web_contents(), redirect_url);
shell()->LoadURL(redirect_url);
EXPECT_TRUE(redirect_manager.WaitForRequestStart());
// Set a feature value we expect to be cleared upon redirect.
blink::RuntimeFeatureStateContext& context =
NavigationRequest::From(redirect_manager.GetNavigationHandle())
->GetMutableRuntimeFeatureStateContext();
bool is_test_feature_enabled(context.IsTestFeatureEnabled());
context.SetTestFeatureEnabled(!is_test_feature_enabled);
EXPECT_FALSE(context.GetFeatureOverrides().empty());
redirect_manager.ResumeNavigation();
EXPECT_TRUE(redirect_manager.WaitForResponse());
// Ensure NavigationRequest's new RuntimeFeatureStateContext is clear
const blink::RuntimeFeatureStateContext& new_context =
NavigationRequest::From(redirect_manager.GetNavigationHandle())
->GetRuntimeFeatureStateContext();
EXPECT_TRUE(new_context.GetFeatureOverrides().empty());
// Continue with the navigation until completion.
ASSERT_TRUE(redirect_manager.WaitForNavigationFinished());
EXPECT_TRUE(redirect_manager.was_successful());
// Ensure that the changes made to the features before redirect do not
// persist to the read context.
RuntimeFeatureStateDocumentData* document_data =
RuntimeFeatureStateDocumentData::GetForCurrentDocument(
shell()->web_contents()->GetPrimaryMainFrame());
EXPECT_TRUE(document_data);
blink::RuntimeFeatureStateReadContext read_context =
document_data->runtime_feature_state_read_context();
EXPECT_TRUE(read_context.GetFeatureOverrides().empty());
}
// Ensure that a certificate error results in a committed navigation with
// the appropriate error code on the handle.
IN_PROC_BROWSER_TEST_F(NavigationRequestBrowserTest, VerifyCertErrorFailure) {
net::EmbeddedTestServer https_server(net::EmbeddedTestServer::TYPE_HTTPS);
https_server.SetSSLConfig(net::EmbeddedTestServer::CERT_MISMATCHED_NAME);
ASSERT_TRUE(https_server.Start());
GURL url(https_server.GetURL("/title1.html"));
NavigationHandleObserver observer(shell()->web_contents(), url);
EXPECT_FALSE(NavigateToURL(shell(), url));
EXPECT_TRUE(observer.has_committed());
EXPECT_TRUE(observer.is_error());
EXPECT_EQ(net::ERR_CERT_COMMON_NAME_INVALID, observer.net_error_code());
}
// Ensure that the IsRendererInitiated() method on NavigationHandle behaves
// correctly.
IN_PROC_BROWSER_TEST_F(NavigationRequestBrowserTest, VerifyRendererInitiated) {
{
// Test browser initiated navigation.
GURL url(embedded_test_server()->GetURL("/title1.html"));
NavigationHandleObserver observer(shell()->web_contents(), url);
EXPECT_TRUE(NavigateToURL(shell(), url));
EXPECT_TRUE(observer.has_committed());
EXPECT_FALSE(observer.is_error());
EXPECT_FALSE(observer.is_renderer_initiated());
}
{
// Test a main frame + subframes navigation.
GURL main_url(embedded_test_server()->GetURL(
"a.com", "/cross_site_iframe_factory.html?a(b(c))"));
GURL b_url(embedded_test_server()->GetURL(
"b.com", "/cross_site_iframe_factory.html?b(c())"));
GURL c_url(embedded_test_server()->GetURL(
"c.com", "/cross_site_iframe_factory.html?c()"));
NavigationHandleObserver main_observer(shell()->web_contents(), main_url);
NavigationHandleObserver b_observer(shell()->web_contents(), b_url);
NavigationHandleObserver c_observer(shell()->web_contents(), c_url);
EXPECT_TRUE(NavigateToURL(shell(), main_url));
// Verify that the main frame navigation is not renderer initiated.
EXPECT_TRUE(main_observer.has_committed());
EXPECT_FALSE(main_observer.is_error());
EXPECT_FALSE(main_observer.is_renderer_initiated());
// Verify that the subframe navigations are renderer initiated.
EXPECT_TRUE(b_observer.has_committed());
EXPECT_FALSE(b_observer.is_error());
EXPECT_TRUE(b_observer.is_renderer_initiated());
EXPECT_TRUE(c_observer.has_committed());
EXPECT_FALSE(c_observer.is_error());
EXPECT_TRUE(c_observer.is_renderer_initiated());
}
{
// Test a pushState navigation.
GURL url(embedded_test_server()->GetURL(
"a.com", "/cross_site_iframe_factory.html?a(a())"));
EXPECT_TRUE(NavigateToURL(shell(), url));
FrameTreeNode* root = static_cast<WebContentsImpl*>(shell()->web_contents())
->GetPrimaryFrameTree()
.root();
NavigationHandleObserver observer(
shell()->web_contents(),
embedded_test_server()->GetURL("a.com", "/bar"));
EXPECT_TRUE(
ExecJs(root->child_at(0), "window.history.pushState({}, '', 'bar');"));
EXPECT_TRUE(observer.has_committed());
EXPECT_FALSE(observer.is_error());
EXPECT_TRUE(observer.is_renderer_initiated());
}
}
// Ensure that methods on NavigationHandle behave correctly with an iframe that
// navigates to its srcdoc attribute.
IN_PROC_BROWSER_TEST_F(NavigationRequestBrowserTest, VerifySrcdoc) {
GURL url(embedded_test_server()->GetURL(
"/frame_tree/page_with_srcdoc_frame.html"));
NavigationHandleObserver observer(shell()->web_contents(),
GURL("about:srcdoc"));
EXPECT_TRUE(NavigateToURL(shell(), url));
EXPECT_TRUE(observer.has_committed());
EXPECT_FALSE(observer.is_error());
EXPECT_TRUE(observer.last_committed_url().IsAboutSrcdoc());
}
// Ensure that the IsSameDocument() method on NavigationHandle behaves
// correctly.
IN_PROC_BROWSER_TEST_F(NavigationRequestBrowserTest, VerifySameDocument) {
GURL url(embedded_test_server()->GetURL(
"a.com", "/cross_site_iframe_factory.html?a(a())"));
EXPECT_TRUE(NavigateToURL(shell(), url));
FrameTreeNode* root = static_cast<WebContentsImpl*>(shell()->web_contents())
->GetPrimaryFrameTree()
.root();
{
NavigationHandleObserver observer(
shell()->web_contents(),
embedded_test_server()->GetURL("a.com", "/foo"));
EXPECT_TRUE(
ExecJs(root->child_at(0), "window.history.pushState({}, '', 'foo');"));
EXPECT_TRUE(observer.has_committed());
EXPECT_FALSE(observer.is_error());
EXPECT_TRUE(observer.is_same_document());
}
{
NavigationHandleObserver observer(
shell()->web_contents(),
embedded_test_server()->GetURL("a.com", "/bar"));
EXPECT_TRUE(ExecJs(root->child_at(0),
"window.history.replaceState({}, '', 'bar');"));
EXPECT_TRUE(observer.has_committed());
EXPECT_FALSE(observer.is_error());
EXPECT_TRUE(observer.is_same_document());
}
{
NavigationHandleObserver observer(
shell()->web_contents(),
embedded_test_server()->GetURL("a.com", "/bar#frag"));
EXPECT_TRUE(ExecJs(root->child_at(0), "window.location.replace('#frag');"));
EXPECT_TRUE(observer.has_committed());
EXPECT_FALSE(observer.is_error());
EXPECT_TRUE(observer.is_same_document());
}
GURL about_blank_url(url::kAboutBlankURL);
{
NavigationHandleObserver observer(shell()->web_contents(), about_blank_url);
EXPECT_TRUE(ExecJs(
root, "document.body.appendChild(document.createElement('iframe'));"));
EXPECT_TRUE(observer.has_committed());
EXPECT_FALSE(observer.is_error());
EXPECT_FALSE(observer.is_same_document());
EXPECT_EQ(about_blank_url, observer.last_committed_url());
}
{
NavigationHandleObserver observer(shell()->web_contents(), about_blank_url);
EXPECT_TRUE(NavigateToURLFromRenderer(root->child_at(0), about_blank_url));
EXPECT_TRUE(observer.has_committed());
EXPECT_FALSE(observer.is_error());
EXPECT_FALSE(observer.is_same_document());
EXPECT_EQ(about_blank_url, observer.last_committed_url());
}
}
// Ensure that a NavigationThrottle can cancel the navigation at navigation
// start.
IN_PROC_BROWSER_TEST_F(NavigationRequestBrowserTest, ThrottleCancelStart) {
GURL start_url(embedded_test_server()->GetURL("/title1.html"));
EXPECT_TRUE(NavigateToURL(shell(), start_url));
GURL redirect_url(
embedded_test_server()->GetURL("/cross-site/bar.com/title2.html"));
NavigationHandleObserver observer(shell()->web_contents(), redirect_url);
TestNavigationThrottleInstaller installer(
shell()->web_contents(), NavigationThrottle::CANCEL,
NavigationThrottle::PROCEED, NavigationThrottle::PROCEED,
NavigationThrottle::PROCEED, NavigationThrottle::PROCEED);
EXPECT_FALSE(NavigateToURL(shell(), redirect_url));
EXPECT_FALSE(observer.has_committed());
EXPECT_TRUE(observer.is_error());
// The navigation should have been canceled before being redirected.
EXPECT_FALSE(observer.was_redirected());
EXPECT_EQ(shell()->web_contents()->GetLastCommittedURL(), start_url);
}
// Ensure that a NavigationThrottle can cancel the navigation when a navigation
// is redirected.
IN_PROC_BROWSER_TEST_F(NavigationRequestBrowserTest, ThrottleCancelRedirect) {
GURL start_url(embedded_test_server()->GetURL("/title1.html"));
EXPECT_TRUE(NavigateToURL(shell(), start_url));
// A navigation with a redirect should be canceled.
{
GURL redirect_url(
embedded_test_server()->GetURL("/cross-site/bar.com/title2.html"));
NavigationHandleObserver observer(shell()->web_contents(), redirect_url);
TestNavigationThrottleInstaller installer(
shell()->web_contents(), NavigationThrottle::PROCEED,
NavigationThrottle::CANCEL, NavigationThrottle::PROCEED,
NavigationThrottle::PROCEED, NavigationThrottle::PROCEED);
EXPECT_FALSE(NavigateToURL(shell(), redirect_url));
EXPECT_FALSE(observer.has_committed());
EXPECT_TRUE(observer.is_error());
EXPECT_TRUE(observer.was_redirected());
EXPECT_EQ(shell()->web_contents()->GetLastCommittedURL(), start_url);
}
// A navigation without redirects should be successful.
{
GURL no_redirect_url(embedded_test_server()->GetURL("/title2.html"));
NavigationHandleObserver observer(shell()->web_contents(), no_redirect_url);
TestNavigationThrottleInstaller installer(
shell()->web_contents(), NavigationThrottle::PROCEED,
NavigationThrottle::CANCEL, NavigationThrottle::PROCEED,
NavigationThrottle::PROCEED, NavigationThrottle::PROCEED);
EXPECT_TRUE(NavigateToURL(shell(), no_redirect_url));
EXPECT_TRUE(observer.has_committed());
EXPECT_FALSE(observer.is_error());
EXPECT_FALSE(observer.was_redirected());
EXPECT_EQ(shell()->web_contents()->GetLastCommittedURL(), no_redirect_url);
}
}
// Ensure that a NavigationThrottle can respond CANCEL when a navigation fails.
IN_PROC_BROWSER_TEST_F(NavigationRequestBrowserTest, ThrottleCancelFailure) {
net::EmbeddedTestServer https_server(net::EmbeddedTestServer::TYPE_HTTPS);
https_server.SetSSLConfig(net::EmbeddedTestServer::CERT_MISMATCHED_NAME);
ASSERT_TRUE(https_server.Start());
GURL url(https_server.GetURL("/title1.html"));
// A navigation with a cert error failure should be canceled. CANCEL has a
// default net error of ERR_ABORTED, which should prevent the navigation from
// committing.
{
TestNavigationThrottleInstaller installer(
shell()->web_contents(), NavigationThrottle::PROCEED,
NavigationThrottle::PROCEED, NavigationThrottle::CANCEL,
NavigationThrottle::PROCEED, NavigationThrottle::PROCEED);
NavigationHandleObserver observer(shell()->web_contents(), url);
EXPECT_FALSE(observer.has_committed());
EXPECT_FALSE(observer.is_error());
EXPECT_FALSE(NavigateToURL(shell(), url));
EXPECT_FALSE(installer.will_fail_called());
EXPECT_FALSE(observer.has_committed());
EXPECT_TRUE(observer.is_error());
EXPECT_EQ(net::ERR_ABORTED, observer.net_error_code());
}
// A navigation with a cert error failure should be canceled.
// A custom net error should result in a committed error page.
{
TestNavigationThrottleInstaller installer(
shell()->web_contents(), NavigationThrottle::PROCEED,
NavigationThrottle::PROCEED,
NavigationThrottle::ThrottleCheckResult(NavigationThrottle::CANCEL,
net::ERR_CERT_DATE_INVALID),
NavigationThrottle::PROCEED, NavigationThrottle::PROCEED);
NavigationHandleObserver observer(shell()->web_contents(), url);
EXPECT_FALSE(observer.has_committed());
EXPECT_FALSE(observer.is_error());
EXPECT_FALSE(NavigateToURL(shell(), url));
EXPECT_TRUE(installer.will_fail_called());
EXPECT_TRUE(observer.has_committed());
EXPECT_TRUE(observer.is_error());
EXPECT_EQ(net::ERR_CERT_DATE_INVALID, observer.net_error_code());
}
// A navigation without a cert error should be successful, without calling
// WillFailRequest() on the throttle. (We set the failure method response to
// CANCEL, but that shouldn't matter if the test passes.)
{
url = embedded_test_server()->GetURL("/title2.html");
NavigationHandleObserver observer(shell()->web_contents(), url);
TestNavigationThrottleInstaller installer(
shell()->web_contents(), NavigationThrottle::PROCEED,
NavigationThrottle::PROCEED, NavigationThrottle::CANCEL,
NavigationThrottle::PROCEED, NavigationThrottle::PROCEED);
EXPECT_TRUE(NavigateToURL(shell(), url));
EXPECT_FALSE(installer.will_fail_called());
EXPECT_FALSE(observer.is_error());
}
}
// Ensure that a NavigationThrottle can cancel a redirected navigation that is
// blocked by CSP.
IN_PROC_BROWSER_TEST_F(NavigationRequestBrowserTest,
ThrottleCancelFailureRedirectBlockedByCSP) {
// Navigate to a URL with an iframe that will be later redirected to a
// URL blocked by CSP.
GURL main_url(
embedded_test_server()->GetURL("a.com", "/page_with_iframe.html"));
EXPECT_TRUE(NavigateToURL(shell(), main_url));
// Add frame-src CSP via a new <meta> element.
EXPECT_TRUE(
ExecJs(shell(),
"var meta = document.createElement('meta');"
"meta.httpEquiv = 'Content-Security-Policy';"
"meta.content = 'frame-src http://a.com:*';"
"document.getElementsByTagName('head')[0].appendChild(meta);"));
// Create a cross-origin redirect URL that doesn't honour above specified CSP.
GURL subframe_url(embedded_test_server()->GetURL("b.com", "/title2.html"));
GURL redirecting_subframe_url(embedded_test_server()->GetURL(
"a.com", "/server-redirect?" + subframe_url.spec()));
NavigationHandleObserver subframe_observer(shell()->web_contents(),
redirecting_subframe_url);
TestNavigationThrottleInstaller installer(
shell()->web_contents(), NavigationThrottle::PROCEED,
NavigationThrottle::PROCEED, NavigationThrottle::CANCEL_AND_IGNORE,
NavigationThrottle::PROCEED, NavigationThrottle::PROCEED);
FrameTreeNode* child = static_cast<WebContentsImpl*>(shell()->web_contents())
->GetPrimaryFrameTree()
.root()
->child_at(0);
// Navigate the subframe to a location that is not allowed by CSP.
EXPECT_FALSE(NavigateToURLFromRenderer(child, redirecting_subframe_url));
// Wait for WillFailRequest.
installer.WaitForThrottleWillFail();
// Make sure that throttle WillFailRequest() was called.
EXPECT_TRUE(installer.will_fail_called());
EXPECT_TRUE(subframe_observer.is_error());
// The redirected navigation is cancelled and the old net error code
// `net::BLOCKED_BY_CSP` is replaced with `net::ERR_ABORTED`.
EXPECT_EQ(net::ERR_ABORTED, subframe_observer.net_error_code());
}
// Ensure that a NavigationThrottle can cancel the navigation when the response
// is received.
IN_PROC_BROWSER_TEST_F(NavigationRequestBrowserTest, ThrottleCancelResponse) {
GURL start_url(embedded_test_server()->GetURL("/title1.html"));
EXPECT_TRUE(NavigateToURL(shell(), start_url));
GURL redirect_url(
embedded_test_server()->GetURL("/cross-site/bar.com/title2.html"));
NavigationHandleObserver observer(shell()->web_contents(), redirect_url);
TestNavigationThrottleInstaller installer(
shell()->web_contents(), NavigationThrottle::PROCEED,
NavigationThrottle::PROCEED, NavigationThrottle::PROCEED,
NavigationThrottle::CANCEL, NavigationThrottle::PROCEED);
EXPECT_FALSE(NavigateToURL(shell(), redirect_url));
EXPECT_FALSE(observer.has_committed());
EXPECT_TRUE(observer.is_error());
// The navigation should have been redirected first, and then canceled when
// the response arrived.
EXPECT_TRUE(observer.was_redirected());
EXPECT_EQ(shell()->web_contents()->GetLastCommittedURL(), start_url);
}
// Ensure that a NavigationThrottle can cancel the navigation when committing
// without a URLLoader.
IN_PROC_BROWSER_TEST_F(NavigationRequestBrowserTest,
ThrottleCancelCommitWithoutUrlLoader) {
GURL start_url(embedded_test_server()->GetURL("/title1.html"));
EXPECT_TRUE(NavigateToURL(shell(), start_url));
GURL about_blank_url(url::kAboutBlankURL);
NavigationHandleObserver observer(shell()->web_contents(), about_blank_url);
TestNavigationThrottleInstaller installer(
shell()->web_contents(), NavigationThrottle::PROCEED,
NavigationThrottle::PROCEED, NavigationThrottle::PROCEED,
NavigationThrottle::PROCEED, NavigationThrottle::CANCEL_AND_IGNORE);
EXPECT_FALSE(NavigateToURL(shell(), about_blank_url));
EXPECT_FALSE(observer.has_committed());
EXPECT_TRUE(observer.is_error());
EXPECT_FALSE(observer.was_redirected());
EXPECT_EQ(shell()->web_contents()->GetLastCommittedURL(), start_url);
}
// Ensure that a NavigationThrottle can defer and resume the navigation at
// navigation start, navigation redirect and response received.
IN_PROC_BROWSER_TEST_F(NavigationRequestBrowserTest, ThrottleDefer) {
GURL start_url(embedded_test_server()->GetURL("/title1.html"));
EXPECT_TRUE(NavigateToURL(shell(), start_url));
GURL redirect_url(
embedded_test_server()->GetURL("/cross-site/bar.com/title2.html"));
TestNavigationObserver navigation_observer(shell()->web_contents(), 1);
NavigationHandleObserver observer(shell()->web_contents(), redirect_url);
TestNavigationThrottleInstaller installer(
shell()->web_contents(), NavigationThrottle::DEFER,
NavigationThrottle::DEFER, NavigationThrottle::DEFER,
NavigationThrottle::DEFER, NavigationThrottle::DEFER);
shell()->LoadURL(redirect_url);
// Wait for WillStartRequest.
installer.WaitForThrottleWillStart();
EXPECT_EQ(1, installer.will_start_called());
EXPECT_EQ(0, installer.will_redirect_called());
EXPECT_EQ(0, installer.will_fail_called());
EXPECT_EQ(0, installer.will_process_called());
EXPECT_EQ(0, installer.will_commit_without_url_loader_called());
installer.navigation_throttle()->ResumeNavigation();
// Wait for WillRedirectRequest.
installer.WaitForThrottleWillRedirect();
EXPECT_EQ(1, installer.will_start_called());
EXPECT_EQ(1, installer.will_redirect_called());
EXPECT_EQ(0, installer.will_fail_called());
EXPECT_EQ(0, installer.will_process_called());
EXPECT_EQ(0, installer.will_commit_without_url_loader_called());
installer.navigation_throttle()->ResumeNavigation();
// Wait for WillProcessResponse.
installer.WaitForThrottleWillProcess();
EXPECT_EQ(1, installer.will_start_called());
EXPECT_EQ(1, installer.will_redirect_called());
EXPECT_EQ(0, installer.will_fail_called());
EXPECT_EQ(1, installer.will_process_called());
EXPECT_EQ(0, installer.will_commit_without_url_loader_called());
installer.navigation_throttle()->ResumeNavigation();
// Wait for the end of the navigation.
navigation_observer.Wait();
EXPECT_TRUE(observer.has_committed());
EXPECT_TRUE(observer.was_redirected());
EXPECT_FALSE(observer.is_error());
EXPECT_EQ(shell()->web_contents()->GetLastCommittedURL(),
GURL(embedded_test_server()->GetURL("bar.com", "/title2.html")));
}
// Ensure that a NavigationThrottle can defer and resume the navigation at
// navigation start and navigation failure.
IN_PROC_BROWSER_TEST_F(NavigationRequestBrowserTest, ThrottleDeferFailure) {
net::EmbeddedTestServer https_server(net::EmbeddedTestServer::TYPE_HTTPS);
https_server.SetSSLConfig(net::EmbeddedTestServer::CERT_MISMATCHED_NAME);
ASSERT_TRUE(https_server.Start());
GURL failure_url(https_server.GetURL("/title1.html"));
TestNavigationObserver navigation_observer(shell()->web_contents(), 1);
NavigationHandleObserver observer(shell()->web_contents(), failure_url);
TestNavigationThrottleInstaller installer(
shell()->web_contents(), NavigationThrottle::DEFER,
NavigationThrottle::DEFER, NavigationThrottle::DEFER,
NavigationThrottle::DEFER, NavigationThrottle::DEFER);
shell()->LoadURL(failure_url);
// Wait for WillStartRequest.
installer.WaitForThrottleWillStart();
EXPECT_EQ(1, installer.will_start_called());
EXPECT_EQ(0, installer.will_redirect_called());
EXPECT_EQ(0, installer.will_fail_called());
EXPECT_EQ(0, installer.will_process_called());
EXPECT_EQ(0, installer.will_commit_without_url_loader_called());
installer.navigation_throttle()->ResumeNavigation();
// Wait for WillFailRequest.
installer.WaitForThrottleWillFail();
EXPECT_EQ(1, installer.will_start_called());
EXPECT_EQ(0, installer.will_redirect_called());
EXPECT_EQ(1, installer.will_fail_called());
EXPECT_EQ(0, installer.will_process_called());
EXPECT_EQ(0, installer.will_commit_without_url_loader_called());
installer.navigation_throttle()->ResumeNavigation();
// Wait for the end of the navigation.
navigation_observer.Wait();
EXPECT_TRUE(observer.has_committed());
EXPECT_TRUE(observer.is_error());
EXPECT_EQ(net::ERR_CERT_COMMON_NAME_INVALID, observer.net_error_code());
}
// Ensure that a NavigationThrottle can defer and resume the navigation when
// navigating without a URLLoader. This test covers multiple types of
// navigations that do not require a URLLoader (same-document navigations and
// about:blank).
IN_PROC_BROWSER_TEST_F(NavigationRequestBrowserTest,
ThrottleDeferCommitWithoutUrlLoader) {
GURL url(embedded_test_server()->GetURL("/title1.html"));
GURL url_fragment(embedded_test_server()->GetURL("/title1.html#id_1"));
GURL about_blank_url(url::kAboutBlankURL);
// Perform a new-document navigation (setup).
{
TestNavigationThrottleInstaller installer(
shell()->web_contents(), NavigationThrottle::PROCEED,
NavigationThrottle::PROCEED, NavigationThrottle::PROCEED,
NavigationThrottle::PROCEED, NavigationThrottle::PROCEED);
NavigationHandleObserver observer(shell()->web_contents(), url);
EXPECT_TRUE(NavigateToURL(shell(), url));
EXPECT_EQ(1, installer.will_start_called());
EXPECT_EQ(1, installer.will_process_called());
EXPECT_EQ(0, installer.will_commit_without_url_loader_called());
EXPECT_FALSE(observer.is_same_document());
}
// Same-document navigation
{
TestNavigationObserver navigation_observer(shell()->web_contents(), 1);
NavigationHandleObserver observer(shell()->web_contents(), url_fragment);
TestNavigationThrottleInstaller installer(
shell()->web_contents(), NavigationThrottle::DEFER,
NavigationThrottle::DEFER, NavigationThrottle::DEFER,
NavigationThrottle::DEFER, NavigationThrottle::DEFER);
shell()->LoadURL(url_fragment);
// Wait for WillCommitWithoutUrlLoader.
installer.WaitForThrottleWillCommitWithoutUrlLoader();
EXPECT_EQ(0, installer.will_start_called());
EXPECT_EQ(0, installer.will_redirect_called());
EXPECT_EQ(0, installer.will_fail_called());
EXPECT_EQ(0, installer.will_process_called());
EXPECT_EQ(1, installer.will_commit_without_url_loader_called());
installer.navigation_throttle()->ResumeNavigation();
// Wait for the end of the navigation.
navigation_observer.Wait();
EXPECT_TRUE(observer.is_same_document());
EXPECT_TRUE(observer.has_committed());
EXPECT_FALSE(observer.was_redirected());
EXPECT_FALSE(observer.is_error());
EXPECT_EQ(shell()->web_contents()->GetLastCommittedURL(), url_fragment);
}
// about:blank
{
TestNavigationObserver navigation_observer(shell()->web_contents(), 1);
NavigationHandleObserver observer(shell()->web_contents(), about_blank_url);
TestNavigationThrottleInstaller installer(
shell()->web_contents(), NavigationThrottle::DEFER,
NavigationThrottle::DEFER, NavigationThrottle::DEFER,
NavigationThrottle::DEFER, NavigationThrottle::DEFER);
shell()->LoadURL(about_blank_url);
// Wait for WillCommitWithoutUrlLoader.
installer.WaitForThrottleWillCommitWithoutUrlLoader();
EXPECT_EQ(0, installer.will_start_called());
EXPECT_EQ(0, installer.will_redirect_called());
EXPECT_EQ(0, installer.will_fail_called());
EXPECT_EQ(0, installer.will_process_called());
EXPECT_EQ(1, installer.will_commit_without_url_loader_called());
installer.navigation_throttle()->ResumeNavigation();
// Wait for the end of the navigation.
navigation_observer.Wait();
EXPECT_FALSE(observer.is_same_document());
EXPECT_TRUE(observer.has_committed());
EXPECT_FALSE(observer.was_redirected());
EXPECT_FALSE(observer.is_error());
EXPECT_EQ(shell()->web_contents()->GetLastCommittedURL(), about_blank_url);
}
}
// Ensure that a NavigationThrottle can defer and cancel the navigation when
// navigating without a URLLoader. This test covers multiple types of
// navigations that do not require a URLLoader (same-document navigations and
// about:blank).
IN_PROC_BROWSER_TEST_F(NavigationRequestBrowserTest,
ThrottleDeferAndCancelCommitWithoutUrlLoader) {
GURL url(embedded_test_server()->GetURL("/title1.html"));
GURL url_fragment(embedded_test_server()->GetURL("/title1.html#id_1"));
GURL about_blank_url(url::kAboutBlankURL);
// Perform a new-document navigation (setup).
{
TestNavigationThrottleInstaller installer(
shell()->web_contents(), NavigationThrottle::PROCEED,
NavigationThrottle::PROCEED, NavigationThrottle::PROCEED,
NavigationThrottle::PROCEED, NavigationThrottle::PROCEED);
NavigationHandleObserver observer(shell()->web_contents(), url);
EXPECT_TRUE(NavigateToURL(shell(), url));
EXPECT_EQ(1, installer.will_start_called());
EXPECT_EQ(1, installer.will_process_called());
EXPECT_EQ(0, installer.will_commit_without_url_loader_called());
EXPECT_FALSE(observer.is_same_document());
}
// Same-document navigation
{
TestNavigationObserver navigation_observer(shell()->web_contents(), 1);
NavigationHandleObserver observer(shell()->web_contents(), url_fragment);
TestNavigationThrottleInstaller installer(
shell()->web_contents(), NavigationThrottle::DEFER,
NavigationThrottle::DEFER, NavigationThrottle::DEFER,
NavigationThrottle::DEFER, NavigationThrottle::DEFER);
shell()->LoadURL(url_fragment);
// Wait for WillCommitWithoutUrlLoader.
installer.WaitForThrottleWillCommitWithoutUrlLoader();
EXPECT_EQ(0, installer.will_start_called());
EXPECT_EQ(0, installer.will_redirect_called());
EXPECT_EQ(0, installer.will_fail_called());
EXPECT_EQ(0, installer.will_process_called());
EXPECT_EQ(1, installer.will_commit_without_url_loader_called());
// Cancel the deferred navigation.
installer.navigation_throttle()->CancelNavigation(
NavigationThrottle::CANCEL_AND_IGNORE);
// Wait for the end of the navigation.
navigation_observer.Wait();
EXPECT_TRUE(observer.is_same_document());
EXPECT_FALSE(observer.has_committed());
EXPECT_FALSE(observer.was_redirected());
EXPECT_TRUE(observer.is_error());
}
// about:blank
{
TestNavigationObserver navigation_observer(shell()->web_contents(), 1);
NavigationHandleObserver observer(shell()->web_contents(), about_blank_url);
TestNavigationThrottleInstaller installer(
shell()->web_contents(), NavigationThrottle::DEFER,
NavigationThrottle::DEFER, NavigationThrottle::DEFER,
NavigationThrottle::DEFER, NavigationThrottle::DEFER);
shell()->LoadURL(about_blank_url);
// Wait for WillCommitWithoutUrlLoader.
installer.WaitForThrottleWillCommitWithoutUrlLoader();
EXPECT_EQ(0, installer.will_start_called());
EXPECT_EQ(0, installer.will_redirect_called());
EXPECT_EQ(0, installer.will_fail_called());
EXPECT_EQ(0, installer.will_process_called());
EXPECT_EQ(1, installer.will_commit_without_url_loader_called());
// Cancel the deferred navigation.
installer.navigation_throttle()->CancelNavigation(
NavigationThrottle::CANCEL_AND_IGNORE);
// Wait for the end of the navigation.
navigation_observer.Wait();
EXPECT_FALSE(observer.is_same_document());
EXPECT_FALSE(observer.has_committed());
EXPECT_FALSE(observer.was_redirected());
EXPECT_TRUE(observer.is_error());
}
}
// Ensure that a NavigationThrottle can block the navigation and collapse the
// frame owner both on request start as well as after a redirect. Plus, ensure
// that the frame is restored on the subsequent non-error-page navigation.
IN_PROC_BROWSER_TEST_F(NavigationRequestBrowserTest, ThrottleBlockAndCollapse) {
const char kChildFrameId[] = "child0";
GURL main_url(embedded_test_server()->GetURL(
"a.com", "/frame_tree/page_with_one_frame.html"));
GURL blocked_subframe_url(embedded_test_server()->GetURL(
"a.com", "/cross-site/baz.com/title1.html"));
GURL allowed_subframe_url(embedded_test_server()->GetURL(
"a.com", "/cross-site/baz.com/title2.html"));
GURL allowed_subframe_final_url(
embedded_test_server()->GetURL("baz.com", "/title2.html"));
// Exercise both synchronous and deferred throttle check results, and both on
// WillStartRequest and on WillRedirectRequest.
const struct {
NavigationThrottle::ThrottleAction will_start_result;
NavigationThrottle::ThrottleAction will_redirect_result;
bool deferred_block;
} kTestCases[] = {
{NavigationThrottle::BLOCK_REQUEST_AND_COLLAPSE,
NavigationThrottle::PROCEED, false},
{NavigationThrottle::BLOCK_REQUEST_AND_COLLAPSE,
NavigationThrottle::PROCEED, true},
{NavigationThrottle::PROCEED,
NavigationThrottle::BLOCK_REQUEST_AND_COLLAPSE, false},
{NavigationThrottle::PROCEED,
NavigationThrottle::BLOCK_REQUEST_AND_COLLAPSE, true},
};
for (const auto& test_case : kTestCases) {
SCOPED_TRACE(::testing::Message() << test_case.will_start_result << ", "
<< test_case.will_redirect_result << ", "
<< test_case.deferred_block);
std::unique_ptr<TestNavigationThrottleInstaller>
subframe_throttle_installer;
if (test_case.deferred_block) {
subframe_throttle_installer =
std::make_unique<TestDeferringNavigationThrottleInstaller>(
shell()->web_contents(), test_case.will_start_result,
test_case.will_redirect_result, NavigationThrottle::PROCEED,
NavigationThrottle::PROCEED, NavigationThrottle::PROCEED,
blocked_subframe_url);
} else {
subframe_throttle_installer =
std::make_unique<TestNavigationThrottleInstaller>(
shell()->web_contents(), test_case.will_start_result,
test_case.will_redirect_result, NavigationThrottle::PROCEED,
NavigationThrottle::PROCEED, NavigationThrottle::PROCEED,
blocked_subframe_url);
}
{
SCOPED_TRACE("Initial navigation blocked on main frame load.");
NavigationHandleObserver subframe_observer(shell()->web_contents(),
blocked_subframe_url);
ASSERT_TRUE(NavigateToURL(shell(), main_url));
EXPECT_TRUE(subframe_observer.is_error());
EXPECT_TRUE(subframe_observer.has_committed());
EXPECT_EQ(net::ERR_BLOCKED_BY_CLIENT, subframe_observer.net_error_code());
ExpectChildFrameCollapsed(shell(), kChildFrameId,
true /* expect_collapsed */);
}
{
SCOPED_TRACE("Subsequent subframe navigation is allowed.");
NavigationHandleObserver subframe_observer(shell()->web_contents(),
allowed_subframe_url);
ASSERT_TRUE(NavigateIframeToURL(shell()->web_contents(), kChildFrameId,
allowed_subframe_url));
EXPECT_TRUE(subframe_observer.has_committed());
EXPECT_FALSE(subframe_observer.is_error());
EXPECT_EQ(allowed_subframe_final_url,
subframe_observer.last_committed_url());
ExpectChildFrameCollapsed(shell(), kChildFrameId,
false /* expect_collapsed */);
}
{
SCOPED_TRACE("Subsequent subframe navigation is blocked.");
NavigationHandleObserver subframe_observer(shell()->web_contents(),
blocked_subframe_url);
ASSERT_TRUE(NavigateIframeToURL(shell()->web_contents(), kChildFrameId,
blocked_subframe_url));
EXPECT_TRUE(subframe_observer.has_committed());
EXPECT_TRUE(subframe_observer.is_error());
EXPECT_EQ(net::ERR_BLOCKED_BY_CLIENT, subframe_observer.net_error_code());
ExpectChildFrameCollapsed(shell(), kChildFrameId,
true /* expect_collapsed */);
}
}
}
// BLOCK_REQUEST_AND_COLLAPSE should block the navigation in legacy <frame>'s,
// but should not collapse the <frame> element itself for legacy reasons.
IN_PROC_BROWSER_TEST_F(NavigationRequestBrowserTest,
ThrottleBlockAndCollapse_LegacyFrameNotCollapsed) {
const char kChildFrameId[] = "child0";
GURL main_url(embedded_test_server()->GetURL(
"a.com", "/frame_tree/legacy_frameset.html"));
GURL blocked_subframe_url(
embedded_test_server()->GetURL("a.com", "/title1.html"));
GURL allowed_subframe_url(
embedded_test_server()->GetURL("a.com", "/title2.html"));
TestNavigationThrottleInstaller subframe_throttle_installer(
shell()->web_contents(), NavigationThrottle::BLOCK_REQUEST_AND_COLLAPSE,
NavigationThrottle::PROCEED, NavigationThrottle::PROCEED,
NavigationThrottle::PROCEED, NavigationThrottle::PROCEED,
blocked_subframe_url);
{
SCOPED_TRACE("Initial navigation blocked on main frame load.");
NavigationHandleObserver subframe_observer(shell()->web_contents(),
blocked_subframe_url);
ASSERT_TRUE(NavigateToURL(shell(), main_url));
EXPECT_TRUE(subframe_observer.is_error());
EXPECT_TRUE(subframe_observer.has_committed());
EXPECT_EQ(net::ERR_BLOCKED_BY_CLIENT, subframe_observer.net_error_code());
ExpectChildFrameSetAsCollapsedInFTN(shell(), true /* expect_collapsed */);
ExpectChildFrameCollapsedInLayout(shell(), kChildFrameId,
false /* expect_collapsed */);
}
{
SCOPED_TRACE("Subsequent subframe navigation is allowed.");
NavigationHandleObserver subframe_observer(shell()->web_contents(),
allowed_subframe_url);
ASSERT_TRUE(NavigateIframeToURL(shell()->web_contents(), kChildFrameId,
allowed_subframe_url));
EXPECT_TRUE(subframe_observer.has_committed());
EXPECT_FALSE(subframe_observer.is_error());
EXPECT_EQ(allowed_subframe_url, subframe_observer.last_committed_url());
ExpectChildFrameCollapsed(shell(), kChildFrameId,
false /* expect_collapsed */);
}
}
// Checks that the RequestContextType value is properly set.
IN_PROC_BROWSER_TEST_F(NavigationRequestBrowserTest,
VerifyRequestContextTypeForFrameTree) {
GURL main_url(embedded_test_server()->GetURL(
"a.com", "/cross_site_iframe_factory.html?a(b(c))"));
GURL b_url(embedded_test_server()->GetURL(
"b.com", "/cross_site_iframe_factory.html?b(c())"));
GURL c_url(embedded_test_server()->GetURL(
"c.com", "/cross_site_iframe_factory.html?c()"));
TestNavigationThrottleInstaller installer(
shell()->web_contents(), NavigationThrottle::PROCEED,
NavigationThrottle::PROCEED, NavigationThrottle::PROCEED,
NavigationThrottle::PROCEED, NavigationThrottle::PROCEED);
TestNavigationManager main_manager(shell()->web_contents(), main_url);
TestNavigationManager b_manager(shell()->web_contents(), b_url);
TestNavigationManager c_manager(shell()->web_contents(), c_url);
NavigationStartUrlRecorder url_recorder(shell()->web_contents());
// Starts and verifies the main frame navigation.
shell()->LoadURL(main_url);
EXPECT_TRUE(main_manager.WaitForRequestStart());
// For each navigation a new throttle should have been installed.
EXPECT_EQ(1, installer.install_count());
// Checks the only URL recorded so far is the one expected for the main frame.
EXPECT_EQ(main_url, url_recorder.urls().back());
EXPECT_EQ(1ul, url_recorder.urls().size());
// Checks the main frame RequestContextType.
EXPECT_EQ(blink::mojom::RequestContextType::LOCATION,
installer.navigation_throttle()->request_context_type());
// Ditto for frame b navigation.
ASSERT_TRUE(main_manager.WaitForNavigationFinished());
EXPECT_TRUE(b_manager.WaitForRequestStart());
EXPECT_EQ(2, installer.install_count());
EXPECT_EQ(b_url, url_recorder.urls().back());
EXPECT_EQ(2ul, url_recorder.urls().size());
EXPECT_EQ(blink::mojom::RequestContextType::IFRAME,
installer.navigation_throttle()->request_context_type());
// Ditto for frame c navigation.
ASSERT_TRUE(b_manager.WaitForNavigationFinished());
EXPECT_TRUE(c_manager.WaitForRequestStart());
EXPECT_EQ(3, installer.install_count());
EXPECT_EQ(c_url, url_recorder.urls().back());
EXPECT_EQ(3ul, url_recorder.urls().size());
EXPECT_EQ(blink::mojom::RequestContextType::IFRAME,
installer.navigation_throttle()->request_context_type());
// Lets the final navigation finish so that we conclude running the
// RequestContextType checks that happen in TestNavigationThrottle.
ASSERT_TRUE(c_manager.WaitForNavigationFinished());
// Confirms the last navigation did finish.
EXPECT_FALSE(installer.navigation_throttle());
}
// Checks that the RequestContextType value is properly set for an hyper-link.
IN_PROC_BROWSER_TEST_F(NavigationRequestBrowserTest,
VerifyHyperlinkRequestContextType) {
GURL link_url(embedded_test_server()->GetURL("/title2.html"));
GURL document_url(embedded_test_server()->GetURL("/simple_links.html"));
TestNavigationThrottleInstaller installer(
shell()->web_contents(), NavigationThrottle::PROCEED,
NavigationThrottle::PROCEED, NavigationThrottle::PROCEED,
NavigationThrottle::PROCEED, NavigationThrottle::PROCEED);
TestNavigationManager link_manager(shell()->web_contents(), link_url);
NavigationStartUrlRecorder url_recorder(shell()->web_contents());
// Navigate to a page with a link.
EXPECT_TRUE(NavigateToURL(shell(), document_url));
EXPECT_EQ(document_url, url_recorder.urls().back());
EXPECT_EQ(1ul, url_recorder.urls().size());
// Starts the navigation from a link click and then check it.
EXPECT_TRUE(WaitForLoadStop(shell()->web_contents()));
EXPECT_EQ(true, EvalJs(shell(), "clickSameSiteLink();"));
EXPECT_TRUE(link_manager.WaitForRequestStart());
EXPECT_EQ(link_url, url_recorder.urls().back());
EXPECT_EQ(2ul, url_recorder.urls().size());
EXPECT_EQ(blink::mojom::RequestContextType::HYPERLINK,
installer.navigation_throttle()->request_context_type());
// Finishes the last navigation.
ASSERT_TRUE(link_manager.WaitForNavigationFinished());
EXPECT_FALSE(installer.navigation_throttle());
}
// Checks that the RequestContextType value is properly set for an form (POST).
IN_PROC_BROWSER_TEST_F(NavigationRequestBrowserTest,
VerifyFormRequestContextType) {
GURL document_url(
embedded_test_server()->GetURL("/session_history/form.html"));
GURL post_url(embedded_test_server()->GetURL("/echotitle"));
TestNavigationThrottleInstaller installer(
shell()->web_contents(), NavigationThrottle::PROCEED,
NavigationThrottle::PROCEED, NavigationThrottle::PROCEED,
NavigationThrottle::PROCEED, NavigationThrottle::PROCEED);
TestNavigationManager post_manager(shell()->web_contents(), post_url);
NavigationStartUrlRecorder url_recorder(shell()->web_contents());
// Navigate to a page with a form.
EXPECT_TRUE(NavigateToURL(shell(), document_url));
EXPECT_EQ(document_url, url_recorder.urls().back());
EXPECT_EQ(1ul, url_recorder.urls().size());
// Executes the form POST navigation and then check it.
EXPECT_TRUE(WaitForLoadStop(shell()->web_contents()));
GURL submit_url("javascript:submitForm('isubmit')");
shell()->LoadURL(submit_url);
EXPECT_TRUE(post_manager.WaitForRequestStart());
EXPECT_EQ(post_url, url_recorder.urls().back());
EXPECT_EQ(2ul, url_recorder.urls().size());
EXPECT_EQ(blink::mojom::RequestContextType::FORM,
installer.navigation_throttle()->request_context_type());
// Finishes the last navigation.
ASSERT_TRUE(post_manager.WaitForNavigationFinished());
EXPECT_FALSE(installer.navigation_throttle());
}
// Checks that the error code is properly set on the NavigationHandle when a
// NavigationThrottle cancels.
IN_PROC_BROWSER_TEST_F(NavigationRequestBrowserTest,
ErrorCodeOnThrottleCancelNavigation) {
const GURL kUrl = embedded_test_server()->GetURL("/title1.html");
const GURL kRedirectingUrl =
embedded_test_server()->GetURL("/server-redirect?" + kUrl.spec());
{
// Set up a NavigationThrottle that will cancel the navigation in
// WillStartRequest.
TestNavigationThrottleInstaller installer(
shell()->web_contents(), NavigationThrottle::CANCEL_AND_IGNORE,
NavigationThrottle::PROCEED, NavigationThrottle::PROCEED,
NavigationThrottle::PROCEED, NavigationThrottle::PROCEED);
NavigationHandleObserver observer(shell()->web_contents(), kUrl);
// Try to navigate to the url. The navigation should be canceled and the
// NavigationHandle should have the right error code.
EXPECT_FALSE(NavigateToURL(shell(), kUrl));
EXPECT_EQ(net::ERR_ABORTED, observer.net_error_code());
}
{
// Set up a NavigationThrottle that will cancel the navigation in
// WillRedirectRequest.
TestNavigationThrottleInstaller installer(
shell()->web_contents(), NavigationThrottle::PROCEED,
NavigationThrottle::CANCEL_AND_IGNORE, NavigationThrottle::PROCEED,
NavigationThrottle::PROCEED, NavigationThrottle::PROCEED);
NavigationHandleObserver observer(shell()->web_contents(), kRedirectingUrl);
// Try to navigate to the url. The navigation should be canceled and the
// NavigationHandle should have the right error code.
EXPECT_FALSE(NavigateToURL(shell(), kRedirectingUrl));
EXPECT_EQ(net::ERR_ABORTED, observer.net_error_code());
}
{
// Set up a NavigationThrottle that will cancel the navigation in
// WillProcessResponse.
TestNavigationThrottleInstaller installer(
shell()->web_contents(), NavigationThrottle::PROCEED,
NavigationThrottle::PROCEED, NavigationThrottle::PROCEED,
NavigationThrottle::CANCEL_AND_IGNORE, NavigationThrottle::PROCEED);
NavigationHandleObserver observer(shell()->web_contents(), kUrl);
// Try to navigate to the url. The navigation should be canceled and the
// NavigationHandle should have the right error code.
EXPECT_FALSE(NavigateToURL(shell(), kUrl));
EXPECT_EQ(net::ERR_ABORTED, observer.net_error_code());
}
{
// Set up a NavigationThrottle that will block the navigation in
// WillStartRequest.
TestNavigationThrottleInstaller installer(
shell()->web_contents(), NavigationThrottle::BLOCK_REQUEST,
NavigationThrottle::PROCEED, NavigationThrottle::PROCEED,
NavigationThrottle::PROCEED, NavigationThrottle::PROCEED);
NavigationHandleObserver observer(shell()->web_contents(), kUrl);
// Try to navigate to the url. The navigation should be canceled and the
// NavigationHandle should have the right error code.
EXPECT_FALSE(NavigateToURL(shell(), kUrl));
EXPECT_EQ(net::ERR_BLOCKED_BY_CLIENT, observer.net_error_code());
}
// Set up a NavigationThrottle that will block the navigation in
// WillRedirectRequest.
TestNavigationThrottleInstaller installer(
shell()->web_contents(), NavigationThrottle::PROCEED,
NavigationThrottle::BLOCK_REQUEST, NavigationThrottle::PROCEED,
NavigationThrottle::PROCEED, NavigationThrottle::PROCEED);
NavigationHandleObserver observer(shell()->web_contents(), kRedirectingUrl);
// Try to navigate to the url. The navigation should be canceled and the
// NavigationHandle should have the right error code.
EXPECT_FALSE(NavigateToURL(shell(), kRedirectingUrl));
EXPECT_EQ(net::ERR_BLOCKED_BY_CLIENT, observer.net_error_code());
}
// Checks that there's no UAF if NavigationRequest::WillStartRequest cancels the
// navigation.
IN_PROC_BROWSER_TEST_F(NavigationRequestBrowserTest,
CancelNavigationInWillStartRequest) {
const GURL kUrl1 = embedded_test_server()->GetURL("/title1.html");
const GURL kUrl2 = embedded_test_server()->GetURL("/title2.html");
// First make a successful commit, as this issue only reproduces when there
// are existing entries (i.e. when NavigationControllerImpl::GetVisibleEntry
// has safe_to_show_pending=false).
EXPECT_TRUE(NavigateToURL(shell(), kUrl1));
// To take the path that doesn't run beforeunload, so that
// NavigationControllerImpl::NavigateToPendingEntry is on the botttom of the
// stack when NavigationRequest::WillStartRequest is called.
CrashTab(shell()->web_contents());
// Set up a NavigationThrottle that will cancel the navigation in
// WillStartRequest.
TestNavigationThrottleInstaller installer(
shell()->web_contents(), NavigationThrottle::CANCEL_AND_IGNORE,
NavigationThrottle::PROCEED, NavigationThrottle::PROCEED,
NavigationThrottle::PROCEED, NavigationThrottle::PROCEED);
EXPECT_FALSE(NavigateToURL(shell(), kUrl2));
}
// Verify that a cross-process navigation in a frame for which the current
// renderer process is not live will not result in leaking a
// RenderProcessHost. See https://crbug.com/949977.
IN_PROC_BROWSER_TEST_F(NavigationRequestBrowserTest,
NoLeakFromStartingSiteInstance) {
IsolateOriginsForTesting(embedded_test_server(), shell()->web_contents(),
{"b.com"});
GURL url_a = embedded_test_server()->GetURL("a.com", "/title1.html");
EXPECT_TRUE(NavigateToURL(shell(), url_a));
// Kill the a.com process, to test what happens with the next navigation.
scoped_refptr<SiteInstance> site_instance_a =
shell()->web_contents()->GetPrimaryMainFrame()->GetSiteInstance();
EXPECT_TRUE(site_instance_a->HasProcess());
RenderProcessHost* process_1 = site_instance_a->GetProcess();
RenderProcessHostWatcher process_exit_observer_1(
process_1, content::RenderProcessHostWatcher::WATCH_FOR_PROCESS_EXIT);
RenderProcessHostWatcher rph_gone_observer_1(
process_1, content::RenderProcessHostWatcher::WATCH_FOR_HOST_DESTRUCTION);
process_1->Shutdown(RESULT_CODE_KILLED);
process_exit_observer_1.Wait();
// Start to navigate the sad tab to another site.
GURL url_b = embedded_test_server()->GetURL("b.com", "/title2.html");
TestNavigationManager navigation_b(shell()->web_contents(), url_b);
shell()->web_contents()->GetController().LoadURL(
url_b, Referrer(), ui::PAGE_TRANSITION_TYPED, std::string());
EXPECT_TRUE(navigation_b.WaitForRequestStart());
// The starting SiteInstance should be the SiteInstance of the current
// RenderFrameHost.
scoped_refptr<SiteInstance> starting_site_instance =
navigation_b.GetNavigationHandle()->GetStartingSiteInstance();
EXPECT_EQ(shell()->web_contents()->GetPrimaryMainFrame()->GetSiteInstance(),
starting_site_instance);
if (ShouldSkipEarlyCommitPendingForCrashedFrame()) {
EXPECT_EQ(GURL("http://a.com"), starting_site_instance->GetSiteURL());
} else {
// Because of the sad tab, this is actually the b.com SiteInstance, which
// commits immediately after starting the navigation and has a process.
EXPECT_EQ(GURL("http://b.com"), starting_site_instance->GetSiteURL());
}
EXPECT_TRUE(starting_site_instance->HasProcess());
// In https://crbug.com/949977, we used the a.com SiteInstance here and didn't
// have a process, and an observer called GetOrCreateProcess, creating a
// process. This RPH never went away, even after the SiteInstance was gone.
// Simulate this by creating a new RPH for site_instance_a directly. Note that
// the actual process may not get created (only if the spare process is in
// use), so wait for RPH destruction rather than process exit.
RenderProcessHost* rph_2 = site_instance_a->GetOrCreateProcess();
RenderProcessHostWatcher process_exit_observer_2(
rph_2, content::RenderProcessHostWatcher::WATCH_FOR_HOST_DESTRUCTION);
ASSERT_TRUE(navigation_b.WaitForNavigationFinished());
// Ensure RPH 1 is destroyed, which happens at commit time even before the fix
// for the bug.
rph_gone_observer_1.Wait();
// Navigate to another process. This isn't necessary to trigger the original
// leak (when the starting SiteInstance was a.com), but it lets the test
// finish in the case that the starting SiteInstance is b.com, since b.com's
// process goes away with this navigation.
// TODO(creis): There's still a slight risk that other buggy code could find
// site_instance_a and call GetOrCreateProcess() on it, causing a leak. We'll
// add a backup fix and test for that in a followup CL.
GURL url_c = embedded_test_server()->GetURL("c.com", "/title1.html");
EXPECT_TRUE(NavigateToURL(shell()->web_contents(), url_c));
// Remove all references to site_instance_a so that we can be sure its process
// gets cleaned up. Pruning the NavigationEntry for url_a on the tab simulates
// closing the tab (from that SiteInstance's perspective).
site_instance_a = nullptr;
starting_site_instance = nullptr;
shell()->web_contents()->GetController().PruneAllButLastCommitted();
// Wait for rph_2 to exit when it's not used. This wouldn't happen when the
// bug was present.
process_exit_observer_2.Wait();
}
// Specialized test that verifies the NavigationHandle gets the HTTPS upgraded
// URL from the very beginning of the navigation.
class NavigationRequestHttpsUpgradeBrowserTest
: public NavigationRequestBrowserTest {
public:
void CheckHttpsUpgradedIframeNavigation(const GURL& start_url,
const GURL& iframe_secure_url) {
ASSERT_TRUE(start_url.SchemeIs(url::kHttpScheme));
ASSERT_TRUE(iframe_secure_url.SchemeIs(url::kHttpsScheme));
NavigationStartUrlRecorder url_recorder(shell()->web_contents());
TestNavigationThrottleInstaller installer(
shell()->web_contents(), NavigationThrottle::PROCEED,
NavigationThrottle::PROCEED, NavigationThrottle::PROCEED,
NavigationThrottle::PROCEED, NavigationThrottle::PROCEED);
TestNavigationManager navigation_manager(shell()->web_contents(),
iframe_secure_url);
// Load the page and wait for the frame load with the expected URL.
// Note: if the test times out while waiting then a navigation to
// iframe_secure_url never happened and the expected upgrade may not be
// working.
shell()->LoadURL(start_url);
EXPECT_TRUE(navigation_manager.WaitForRequestStart());
// The main frame should have finished navigating while the iframe should
// have just started.
EXPECT_EQ(2, installer.will_start_called());
EXPECT_EQ(0, installer.will_redirect_called());
EXPECT_EQ(1, installer.will_process_called());
// Check the correct start URLs have been registered.
EXPECT_EQ(iframe_secure_url, url_recorder.urls().back());
EXPECT_EQ(start_url, url_recorder.urls().front());
EXPECT_EQ(2ul, url_recorder.urls().size());
}
};
// Tests that the start URL is HTTPS upgraded for a same site navigation.
IN_PROC_BROWSER_TEST_F(NavigationRequestHttpsUpgradeBrowserTest,
StartUrlIsHttpsUpgradedSameSite) {
GURL start_url(embedded_test_server()->GetURL(
"example.com", "/https_upgrade_same_site.html"));
// Builds the expected upgraded same site URL.
GURL::Replacements replace_scheme;
replace_scheme.SetSchemeStr("https");
GURL cross_site_iframe_secure_url =
embedded_test_server()
->GetURL("example.com", "/title1.html")
.ReplaceComponents(replace_scheme);
CheckHttpsUpgradedIframeNavigation(start_url, cross_site_iframe_secure_url);
}
// Tests that the start URL is HTTPS upgraded for a cross site navigation.
IN_PROC_BROWSER_TEST_F(NavigationRequestHttpsUpgradeBrowserTest,
StartUrlIsHttpsUpgradedCrossSite) {
GURL start_url(
embedded_test_server()->GetURL("/https_upgrade_cross_site.html"));
GURL cross_site_iframe_secure_url("https://other.com/title1.html");
CheckHttpsUpgradedIframeNavigation(start_url, cross_site_iframe_secure_url);
}
IN_PROC_BROWSER_TEST_F(NavigationRequestBrowserTest,
BrowserInitiatedMainFrameReload) {
GURL url = embedded_test_server()->GetURL("/hello.html");
EXPECT_TRUE(NavigateToURL(shell(), url));
NavigationHandleObserver handle_observer(shell()->web_contents(), url);
TestNavigationObserver navigation_observer(shell()->web_contents(), 1);
shell()->Reload();
navigation_observer.Wait();
EXPECT_EQ(handle_observer.reload_type(), ReloadType::NORMAL);
}
IN_PROC_BROWSER_TEST_F(NavigationRequestBrowserTest,
BrowserInitiatedSubFrameReload) {
GURL url = embedded_test_server()->GetURL("/page_with_iframe.html");
EXPECT_TRUE(NavigateToURL(shell(), url));
NavigationHandleObserver handle_observer(
shell()->web_contents(), embedded_test_server()->GetURL("/title1.html"));
TestNavigationObserver navigation_observer(shell()->web_contents(), 1);
RenderFrameHostImpl* main_frame = static_cast<RenderFrameHostImpl*>(
shell()->web_contents()->GetPrimaryMainFrame());
ASSERT_EQ(1u, main_frame->child_count());
FrameTreeNode* child = main_frame->child_at(0u);
auto* navigation_controller = static_cast<NavigationControllerImpl*>(
&shell()->web_contents()->GetController());
navigation_controller->ReloadFrame(child);
navigation_observer.Wait();
EXPECT_EQ(handle_observer.reload_type(), ReloadType::NORMAL);
EXPECT_FALSE(handle_observer.is_main_frame());
}
IN_PROC_BROWSER_TEST_F(NavigationRequestBrowserTest,
RendererInitiatedMainFrameReload) {
GURL url = embedded_test_server()->GetURL("/hello.html");
EXPECT_TRUE(NavigateToURL(shell(), url));
NavigationHandleObserver observer(shell()->web_contents(), url);
EXPECT_TRUE(ExecJs(shell(), "location.reload();"));
EXPECT_EQ(observer.reload_type(), ReloadType::NORMAL);
}
IN_PROC_BROWSER_TEST_F(NavigationRequestBrowserTest,
RendererInitiatedSubFrameReload) {
GURL url = embedded_test_server()->GetURL("/page_with_iframe.html");
EXPECT_TRUE(NavigateToURL(shell(), url));
NavigationHandleObserver handle_observer(
shell()->web_contents(), embedded_test_server()->GetURL("/title1.html"));
EXPECT_TRUE(ExecJs(shell(),
"document.getElementById('test_iframe')."
"contentWindow.location.reload();"));
EXPECT_EQ(handle_observer.reload_type(), ReloadType::NORMAL);
EXPECT_FALSE(handle_observer.is_main_frame());
}
// Ensure that browser-initiated same-document navigations are detected and
// don't issue network requests. See crbug.com/663777.
// Browser-initiated same-document navigations should trigger a
// WillCommitWithoutUrlLoader() callback, instead of the WillStartRequest()
// and WillProcessResponse() callbacks used when there is a network request.
IN_PROC_BROWSER_TEST_F(NavigationRequestBrowserTest,
SameDocumentBrowserInitiatedNoReload) {
GURL url(embedded_test_server()->GetURL("/title1.html"));
GURL url_fragment_1(embedded_test_server()->GetURL("/title1.html#id_1"));
GURL url_fragment_2(embedded_test_server()->GetURL("/title1.html#id_2"));
// 1) Perform a new-document navigation.
{
TestNavigationThrottleInstaller installer(
shell()->web_contents(), NavigationThrottle::PROCEED,
NavigationThrottle::PROCEED, NavigationThrottle::PROCEED,
NavigationThrottle::PROCEED, NavigationThrottle::PROCEED);
NavigationHandleObserver observer(shell()->web_contents(), url);
EXPECT_TRUE(NavigateToURL(shell(), url));
EXPECT_EQ(1, installer.will_start_called());
EXPECT_EQ(1, installer.will_process_called());
EXPECT_EQ(0, installer.will_commit_without_url_loader_called());
EXPECT_FALSE(observer.is_same_document());
}
// 2) Perform a same-document navigation by adding a fragment.
{
TestNavigationThrottleInstaller installer(
shell()->web_contents(), NavigationThrottle::PROCEED,
NavigationThrottle::PROCEED, NavigationThrottle::PROCEED,
NavigationThrottle::PROCEED, NavigationThrottle::PROCEED);
NavigationHandleObserver observer(shell()->web_contents(), url_fragment_1);
EXPECT_TRUE(NavigateToURL(shell(), url_fragment_1));
EXPECT_EQ(0, installer.will_start_called());
EXPECT_EQ(0, installer.will_process_called());
EXPECT_EQ(1, installer.will_commit_without_url_loader_called());
EXPECT_TRUE(observer.is_same_document());
}
// 3) Perform a same-document navigation by modifying the fragment.
{
TestNavigationThrottleInstaller installer(
shell()->web_contents(), NavigationThrottle::PROCEED,
NavigationThrottle::PROCEED, NavigationThrottle::PROCEED,
NavigationThrottle::PROCEED, NavigationThrottle::PROCEED);
NavigationHandleObserver observer(shell()->web_contents(), url_fragment_2);
EXPECT_TRUE(NavigateToURL(shell(), url_fragment_2));
EXPECT_EQ(0, installer.will_start_called());
EXPECT_EQ(0, installer.will_process_called());
EXPECT_EQ(1, installer.will_commit_without_url_loader_called());
EXPECT_TRUE(observer.is_same_document());
}
// 4) Redo the last navigation, and it should be treated as fragment
// navigation.
{
TestNavigationThrottleInstaller installer(
shell()->web_contents(), NavigationThrottle::PROCEED,
NavigationThrottle::PROCEED, NavigationThrottle::PROCEED,
NavigationThrottle::PROCEED, NavigationThrottle::PROCEED);
NavigationHandleObserver observer(shell()->web_contents(), url_fragment_2);
EXPECT_TRUE(NavigateToURL(shell(), url_fragment_2));
EXPECT_EQ(0, installer.will_start_called());
EXPECT_EQ(0, installer.will_process_called());
EXPECT_EQ(1, installer.will_commit_without_url_loader_called());
EXPECT_TRUE(observer.is_same_document());
}
// 5) Perform a new-document navigation by removing the fragment.
{
TestNavigationThrottleInstaller installer(
shell()->web_contents(), NavigationThrottle::PROCEED,
NavigationThrottle::PROCEED, NavigationThrottle::PROCEED,
NavigationThrottle::PROCEED, NavigationThrottle::PROCEED);
NavigationHandleObserver observer(shell()->web_contents(), url);
EXPECT_TRUE(NavigateToURL(shell(), url));
EXPECT_EQ(1, installer.will_start_called());
EXPECT_EQ(1, installer.will_process_called());
EXPECT_EQ(0, installer.will_commit_without_url_loader_called());
EXPECT_FALSE(observer.is_same_document());
}
}
class NavigationRequestHostResolutionFailureTest : public ContentBrowserTest {
protected:
void SetUpOnMainThread() override {
host_resolver()->AddSimulatedTimeoutFailure("*");
ASSERT_TRUE(embedded_test_server()->Start());
}
};
IN_PROC_BROWSER_TEST_F(NavigationRequestHostResolutionFailureTest,
HostResolutionFailure) {
GURL url(embedded_test_server()->GetURL("example.com", "/title1.html"));
NavigationHandleObserver observer(shell()->web_contents(), url);
EXPECT_FALSE(NavigateToURL(shell(), url));
EXPECT_TRUE(observer.has_committed());
EXPECT_TRUE(observer.is_error());
EXPECT_EQ(net::ERR_NAME_NOT_RESOLVED, observer.net_error_code());
EXPECT_EQ(net::ERR_DNS_TIMED_OUT, observer.resolve_error_info().error);
}
// Record and list the navigations that are started and finished.
class NavigationLogger : public WebContentsObserver {
public:
explicit NavigationLogger(WebContents* web_contents)
: WebContentsObserver(web_contents) {}
void DidStartNavigation(NavigationHandle* navigation_handle) override {
started_navigation_urls_.push_back(navigation_handle->GetURL());
}
void DidRedirectNavigation(NavigationHandle* navigation_handle) override {
redirected_navigation_urls_.push_back(navigation_handle->GetURL());
}
void DidFinishNavigation(NavigationHandle* navigation_handle) override {
finished_navigation_urls_.push_back(navigation_handle->GetURL());
}
const std::vector<GURL>& started_navigation_urls() const {
return started_navigation_urls_;
}
const std::vector<GURL>& redirected_navigation_urls() const {
return redirected_navigation_urls_;
}
const std::vector<GURL>& finished_navigation_urls() const {
return finished_navigation_urls_;
}
private:
std::vector<GURL> started_navigation_urls_;
std::vector<GURL> redirected_navigation_urls_;
std::vector<GURL> finished_navigation_urls_;
};
// Verifies that when a navigation is blocked after a redirect, the renderer
// doesn't try to commit an error page to the pre-redirect URL. This would cause
// a NavigationHandle mismatch and a new NavigationHandle creation to commit
// the error page. This test makes sure that only one NavigationHandle is used
// for committing the error page. See https://crbug.com/695421
IN_PROC_BROWSER_TEST_F(NavigationRequestBrowserTest, BlockedOnRedirect) {
const GURL kUrl = embedded_test_server()->GetURL("/title1.html");
const GURL kRedirectingUrl =
embedded_test_server()->GetURL("/server-redirect?" + kUrl.spec());
// Set up a NavigationThrottle that will block the navigation in
// WillRedirectRequest.
TestNavigationThrottleInstaller installer(
shell()->web_contents(), NavigationThrottle::PROCEED,
NavigationThrottle::BLOCK_REQUEST, NavigationThrottle::PROCEED,
NavigationThrottle::PROCEED, NavigationThrottle::PROCEED);
NavigationHandleObserver observer(shell()->web_contents(), kRedirectingUrl);
NavigationLogger logger(shell()->web_contents());
// Try to navigate to the url. The navigation should be canceled and the
// NavigationHandle should have the right error code.
EXPECT_FALSE(NavigateToURL(shell(), kRedirectingUrl));
// EXPECT_EQ(net::ERR_BLOCKED_BY_CLIENT, observer.net_error_code());
// Only one navigation is expected to happen.
std::vector<GURL> started_navigation = {kRedirectingUrl};
EXPECT_EQ(started_navigation, logger.started_navigation_urls());
std::vector<GURL> finished_navigation = {kUrl};
EXPECT_EQ(finished_navigation, logger.finished_navigation_urls());
}
// Tests that when a navigation starts while there's an existing one, the first
// one has the right error code set on its navigation handle.
IN_PROC_BROWSER_TEST_F(NavigationRequestBrowserTest, ErrorCodeOnCancel) {
GURL slow_url = embedded_test_server()->GetURL("/slow?60");
NavigationHandleObserver observer(shell()->web_contents(), slow_url);
shell()->LoadURL(slow_url);
GURL url2(embedded_test_server()->GetURL("/title1.html"));
TestNavigationObserver same_tab_observer(shell()->web_contents(), 1);
shell()->LoadURL(url2);
same_tab_observer.Wait();
EXPECT_EQ(net::ERR_ABORTED, observer.net_error_code());
}
// Tests that when a renderer-initiated request redirects to a URL that the
// renderer can't access, the right error code is set on the NavigationHandle.
IN_PROC_BROWSER_TEST_F(NavigationRequestBrowserTest, ErrorCodeOnRedirect) {
GURL url(embedded_test_server()->GetURL("/title1.html"));
EXPECT_TRUE(NavigateToURL(shell(), url));
GURL redirect_url =
embedded_test_server()->GetURL(std::string("/server-redirect?") +
blink::kChromeUINetworkErrorsListingURL);
NavigationHandleObserver observer(shell()->web_contents(), redirect_url);
TestNavigationObserver same_tab_observer(shell()->web_contents(), 1);
EXPECT_TRUE(ExecJs(shell(), base::StringPrintf("location.href = '%s';",
redirect_url.spec().c_str())));
same_tab_observer.Wait();
EXPECT_EQ(net::ERR_UNSAFE_REDIRECT, observer.net_error_code());
}
// Test to verify that error pages caused by NavigationThrottle blocking a
// request in the main frame from being made are properly committed in a
// separate error page process.
IN_PROC_BROWSER_TEST_F(NavigationRequestBrowserTest,
ErrorPageBlockedNavigation) {
GURL start_url(embedded_test_server()->GetURL("foo.com", "/title1.html"));
GURL blocked_url(embedded_test_server()->GetURL("bar.com", "/title2.html"));
{
NavigationHandleObserver observer(shell()->web_contents(), start_url);
EXPECT_TRUE(NavigateToURL(shell(), start_url));
EXPECT_TRUE(observer.has_committed());
EXPECT_FALSE(observer.is_error());
}
scoped_refptr<SiteInstance> site_instance =
shell()->web_contents()->GetPrimaryMainFrame()->GetSiteInstance();
auto installer = std::make_unique<TestNavigationThrottleInstaller>(
shell()->web_contents(), NavigationThrottle::BLOCK_REQUEST,
NavigationThrottle::PROCEED, NavigationThrottle::PROCEED,
NavigationThrottle::PROCEED, NavigationThrottle::PROCEED);
{
// A blocked, renderer-initiated navigation in the main frame should commit
// an error page in a new process.
NavigationHandleObserver observer(shell()->web_contents(), blocked_url);
TestNavigationObserver navigation_observer(shell()->web_contents(), 1);
EXPECT_TRUE(
ExecJs(shell(), base::StringPrintf("location.href = '%s'",
blocked_url.spec().c_str())));
navigation_observer.Wait();
EXPECT_TRUE(observer.has_committed());
EXPECT_TRUE(observer.is_error());
if (SiteIsolationPolicy::IsErrorPageIsolationEnabled(true)) {
EXPECT_NE(
site_instance,
shell()->web_contents()->GetPrimaryMainFrame()->GetSiteInstance());
EXPECT_EQ(kUnreachableWebDataURL, shell()
->web_contents()
->GetPrimaryMainFrame()
->GetSiteInstance()
->GetSiteURL());
} else {
EXPECT_EQ(
site_instance,
shell()->web_contents()->GetPrimaryMainFrame()->GetSiteInstance());
}
}
{
// Reloading the blocked document from the browser process still ends up
// in the error page process.
int process_id = shell()
->web_contents()
->GetPrimaryMainFrame()
->GetProcess()
->GetDeprecatedID();
NavigationHandleObserver observer(shell()->web_contents(), blocked_url);
TestNavigationObserver navigation_observer(shell()->web_contents(), 1);
shell()->Reload();
navigation_observer.Wait();
EXPECT_TRUE(observer.has_committed());
EXPECT_TRUE(observer.is_error());
if (SiteIsolationPolicy::IsErrorPageIsolationEnabled(true)) {
EXPECT_EQ(kUnreachableWebDataURL, shell()
->web_contents()
->GetPrimaryMainFrame()
->GetSiteInstance()
->GetSiteURL());
EXPECT_EQ(process_id, shell()
->web_contents()
->GetPrimaryMainFrame()
->GetProcess()
->GetDeprecatedID());
} else if (AreAllSitesIsolatedForTesting()) {
EXPECT_NE(
site_instance,
shell()->web_contents()->GetPrimaryMainFrame()->GetSiteInstance());
} else {
EXPECT_EQ(
site_instance,
shell()->web_contents()->GetPrimaryMainFrame()->GetSiteInstance());
}
}
installer.reset();
{
// With the throttle uninstalled, going back should return to |start_url| in
// the same process, and clear the error page.
NavigationHandleObserver observer(shell()->web_contents(), start_url);
TestNavigationObserver navigation_observer(shell()->web_contents(), 1);
shell()->GoBackOrForward(-1);
navigation_observer.Wait();
EXPECT_TRUE(observer.has_committed());
EXPECT_FALSE(observer.is_error());
EXPECT_EQ(
site_instance,
shell()->web_contents()->GetPrimaryMainFrame()->GetSiteInstance());
}
installer = std::make_unique<TestNavigationThrottleInstaller>(
shell()->web_contents(), NavigationThrottle::BLOCK_REQUEST,
NavigationThrottle::PROCEED, NavigationThrottle::PROCEED,
NavigationThrottle::PROCEED, NavigationThrottle::PROCEED);
{
// A blocked, browser-initiated navigation should commit an error page in a
// different process.
NavigationHandleObserver observer(shell()->web_contents(), blocked_url);
TestNavigationObserver navigation_observer(shell()->web_contents(), 1);
EXPECT_FALSE(NavigateToURL(shell(), blocked_url));
navigation_observer.Wait();
EXPECT_TRUE(observer.has_committed());
EXPECT_TRUE(observer.is_error());
EXPECT_NE(
site_instance,
shell()->web_contents()->GetPrimaryMainFrame()->GetSiteInstance());
if (SiteIsolationPolicy::IsErrorPageIsolationEnabled(true)) {
EXPECT_EQ(kUnreachableWebDataURL, shell()
->web_contents()
->GetPrimaryMainFrame()
->GetSiteInstance()
->GetSiteURL());
}
}
installer.reset();
{
// A blocked subframe navigation should commit an error page in the error
// page process or stay in the same process, based on the isolation policy.
EXPECT_TRUE(NavigateToURL(shell(), start_url));
const std::string javascript =
"var i = document.createElement('iframe');"
"i.src = '" +
blocked_url.spec() +
"';"
"document.body.appendChild(i);";
installer = std::make_unique<TestNavigationThrottleInstaller>(
shell()->web_contents(), NavigationThrottle::BLOCK_REQUEST,
NavigationThrottle::PROCEED, NavigationThrottle::PROCEED,
NavigationThrottle::PROCEED, NavigationThrottle::PROCEED);
content::RenderFrameHost* rfh =
shell()->web_contents()->GetPrimaryMainFrame();
scoped_refptr<SiteInstance> initial_site_instance = rfh->GetSiteInstance();
TestNavigationObserver navigation_observer(shell()->web_contents(), 1);
ASSERT_TRUE(content::ExecJs(rfh, javascript));
navigation_observer.Wait();
FrameTreeNode* root = static_cast<WebContentsImpl*>(shell()->web_contents())
->GetPrimaryFrameTree()
.root();
ASSERT_EQ(1u, root->child_count());
FrameTreeNode* child = root->child_at(0u);
EXPECT_TRUE(IsExpectedSubframeErrorTransition(
initial_site_instance.get(),
child->current_frame_host()->GetSiteInstance()));
}
}
// Test to verify that error pages caused by network error or other
// recoverable error are properly committed in the process for the
// destination URL.
IN_PROC_BROWSER_TEST_F(NavigationRequestBrowserTest, ErrorPageNetworkError) {
GURL start_url(embedded_test_server()->GetURL("foo.com", "/title1.html"));
GURL error_url(embedded_test_server()->GetURL("/close-socket"));
EXPECT_NE(start_url.host(), error_url.host());
GetIOThreadTaskRunner({})->PostTask(
FROM_HERE, base::BindOnce(&net::URLRequestFailedJob::AddUrlHandler));
{
NavigationHandleObserver observer(shell()->web_contents(), start_url);
EXPECT_TRUE(NavigateToURL(shell(), start_url));
EXPECT_TRUE(observer.has_committed());
EXPECT_FALSE(observer.is_error());
}
scoped_refptr<SiteInstance> site_instance =
shell()->web_contents()->GetPrimaryMainFrame()->GetSiteInstance();
{
NavigationHandleObserver observer(shell()->web_contents(), error_url);
EXPECT_FALSE(NavigateToURL(shell(), error_url));
EXPECT_TRUE(observer.has_committed());
EXPECT_TRUE(observer.is_error());
EXPECT_NE(
site_instance,
shell()->web_contents()->GetPrimaryMainFrame()->GetSiteInstance());
if (SiteIsolationPolicy::IsErrorPageIsolationEnabled(true)) {
EXPECT_EQ(kUnreachableWebDataURL, shell()
->web_contents()
->GetPrimaryMainFrame()
->GetSiteInstance()
->GetSiteURL());
}
}
}
class ReadyToCommitObserver : public WebContentsObserver {
public:
explicit ReadyToCommitObserver(WebContents* web_contents) {
WebContentsObserver::Observe(web_contents);
}
bool ReadyToCommitNavigationWasCalled() const {
return ready_to_commit_navigation_called_;
}
protected:
void ReadyToCommitNavigation(NavigationHandle* navigation_handle) override {
ready_to_commit_navigation_called_ = true;
}
bool ready_to_commit_navigation_called_ = false;
};
// Ensure that adding a deferring condition that's already satisfied when
// checked (i.e. can return synchronously) doesn't block commit.
IN_PROC_BROWSER_TEST_F(NavigationRequestBrowserTest,
SynchronouslyCompleteCommitDeferringCondition) {
GURL simple_url(embedded_test_server()->GetURL("/simple_page.html"));
TestNavigationManager manager(shell()->web_contents(), simple_url);
WebContents* web_contents = shell()->web_contents();
ReadyToCommitObserver observer(web_contents);
MockCommitDeferringConditionInstaller installer(
simple_url, CommitDeferringCondition::Result::kProceed);
shell()->LoadURL(simple_url);
ASSERT_TRUE(manager.WaitForResponse());
manager.ResumeNavigation();
// Ready to commit should be reached synchronously after a response.
EXPECT_TRUE(installer.condition().WasInvoked());
EXPECT_TRUE(observer.ReadyToCommitNavigationWasCalled());
EXPECT_TRUE(manager.GetNavigationHandle()->IsWaitingToCommit());
ASSERT_TRUE(manager.WaitForNavigationFinished());
}
// Ensure asynchronously deferring conditions block the navigation when it's
// ready to commit.
IN_PROC_BROWSER_TEST_F(NavigationRequestBrowserTest,
AsyncCommitDeferringCondition) {
GURL simple_url(embedded_test_server()->GetURL("/simple_page.html"));
TestNavigationManager manager(shell()->web_contents(), simple_url);
WebContents* web_contents = shell()->web_contents();
MockCommitDeferringConditionInstaller installer1(
simple_url, CommitDeferringCondition::Result::kDefer);
MockCommitDeferringConditionInstaller installer2(
simple_url, CommitDeferringCondition::Result::kDefer);
ReadyToCommitObserver observer(web_contents);
shell()->LoadURL(simple_url);
ASSERT_TRUE(manager.WaitForResponse());
manager.ResumeNavigation();
NavigationRequest* request =
static_cast<NavigationRequest*>(manager.GetNavigationHandle());
// The navigation should not have proceeded through to ReadyToCommit because
// the first condition is deferring it. The second condition should not be
// checked until the first is resolved.
EXPECT_LT(request->state(), NavigationRequest::READY_TO_COMMIT);
EXPECT_FALSE(observer.ReadyToCommitNavigationWasCalled());
EXPECT_TRUE(installer1.condition().WasInvoked());
EXPECT_FALSE(installer2.condition().WasInvoked());
EXPECT_TRUE(request->IsCommitDeferringConditionDeferredForTesting());
// Resume from the first condition. This should now block on the second
// condition.
installer1.condition().CallResumeClosure();
EXPECT_LT(request->state(), NavigationRequest::READY_TO_COMMIT);
EXPECT_FALSE(observer.ReadyToCommitNavigationWasCalled());
EXPECT_TRUE(installer2.condition().WasInvoked());
// Resuming from the second condition should now resume the navigaiton. This
// should call ReadyToCommit and commit the navigation.
installer2.condition().CallResumeClosure();
EXPECT_TRUE(observer.ReadyToCommitNavigationWasCalled());
EXPECT_EQ(request->state(), NavigationRequest::READY_TO_COMMIT);
EXPECT_FALSE(request->IsCommitDeferringConditionDeferredForTesting());
ASSERT_TRUE(manager.WaitForNavigationFinished());
}
// Ensure a navigation can be cancelled while an asynchronously deferring
// condition is blocking commit.
IN_PROC_BROWSER_TEST_F(NavigationRequestBrowserTest,
CancelWhileCommitDeferred) {
GURL simple_url(embedded_test_server()->GetURL("/simple_page.html"));
TestNavigationManager manager(shell()->web_contents(), simple_url);
WebContents* web_contents = shell()->web_contents();
MockCommitDeferringConditionInstaller installer1(
simple_url, CommitDeferringCondition::Result::kDefer);
// We'll cancel the navigation while the first condition is deferred so this
// is added only to make sure it's never invoked.
MockCommitDeferringConditionInstaller installer2(
simple_url, CommitDeferringCondition::Result::kDefer);
shell()->LoadURL(simple_url);
ASSERT_TRUE(manager.WaitForResponse());
manager.ResumeNavigation();
NavigationRequest* request =
static_cast<NavigationRequest*>(manager.GetNavigationHandle());
// The navigation should have passed all checks but is now deferred from
// committing by |condition|.
EXPECT_LT(request->state(), NavigationRequest::READY_TO_COMMIT);
EXPECT_TRUE(installer1.condition().WasInvoked());
EXPECT_TRUE(request->IsCommitDeferringConditionDeferredForTesting());
// While the commit is deferred, cancel the navigation. This should delete
// the navigation request.
EXPECT_FALSE(installer1.condition().IsDestroyed());
web_contents->Stop();
ASSERT_TRUE(manager.WaitForNavigationFinished());
EXPECT_EQ(manager.GetNavigationHandle(), nullptr);
EXPECT_TRUE(installer1.condition().IsDestroyed());
EXPECT_TRUE(installer2.condition().IsDestroyed());
// Call resume on `installer1`'s condition, as could happen when e.g. the
// renderer responds after the navigation is stopped. Make sure we don't
// crash.
installer1.condition().CallResumeClosure();
EXPECT_FALSE(installer2.condition().WasInvoked());
}
// Ensure throttles registered by tests using RegisterThrottleForTesting() are
// executed after those registered by the WebContents' browser client (i.e. how
// non-test throttles are normally registered).
IN_PROC_BROWSER_TEST_F(NavigationRequestBrowserTest,
RegisterThrottleForTestingIsLast) {
WebContents* web_contents = shell()->web_contents();
GURL simple_url(embedded_test_server()->GetURL("/simple_page.html"));
TestNavigationThrottle* client_throttle = nullptr;
// Set the client to register a TestNavigationThrottle that defers in
// WillStartRequest. We'll save a pointer to this throttle in
// |client_throttle| when its registered.
content::ShellContentBrowserClient::Get()
->set_create_throttles_for_navigation_callback(base::BindLambdaForTesting(
[&client_throttle](
content::NavigationThrottleRegistry& registry) -> void {
std::unique_ptr<TestNavigationThrottle> throttle(
new TestNavigationThrottle(
®istry.GetNavigationHandle(), NavigationThrottle::DEFER,
NavigationThrottle::PROCEED, NavigationThrottle::PROCEED,
NavigationThrottle::PROCEED, NavigationThrottle::PROCEED,
base::DoNothing(), base::DoNothing(), base::DoNothing(),
base::DoNothing(), base::DoNothing()));
client_throttle = throttle.get();
registry.AddThrottle(std::move(throttle));
}));
// Add another similar throttle using the installer which will use
// RegisterThrottleForTesting and registers throttles in DidStartNavigation,
// before browser client throttles are registered.
TestNavigationThrottleInstaller test_throttle_installer(
web_contents, NavigationThrottle::DEFER, NavigationThrottle::PROCEED,
NavigationThrottle::PROCEED, NavigationThrottle::PROCEED,
NavigationThrottle::PROCEED);
// Start navigating.
TestNavigationManager manager(shell()->web_contents(), simple_url);
shell()->LoadURL(simple_url);
auto* handle = manager.GetNavigationHandle();
auto* runner =
NavigationRequest::From(handle)->GetNavigationThrottleRunnerForTesting();
// The navigation should have been deferred by one of our throttles. Ensure
// it's the client throttle since we explicitly want test throttles to
// execute after all others.
ASSERT_TRUE(handle->IsDeferredForTesting());
ASSERT_NE(client_throttle, nullptr);
EXPECT_EQ(runner->GetDeferringThrottle(), client_throttle);
// Now when we resume we should get deferred by the other throttle. This
// should be the throttle installed via RegisterThrottleForTesting.
client_throttle->ResumeNavigation();
ASSERT_TRUE(handle->IsDeferredForTesting());
EXPECT_EQ(runner->GetDeferringThrottle(),
test_throttle_installer.navigation_throttle());
// Finish the navigation.
test_throttle_installer.navigation_throttle()->ResumeNavigation();
ASSERT_TRUE(manager.WaitForNavigationFinished());
}
// Tests the case where a browser-initiated navigation to a normal webpage is
// blocked (net::ERR_BLOCKED_BY_CLIENT) while departing from a privileged WebUI
// page (chrome://gpu). It is a security risk for the error page to commit in
// the privileged process.
IN_PROC_BROWSER_TEST_F(NavigationRequestBrowserTest, BlockedRequestAfterWebUI) {
GURL web_ui_url(GetWebUIURL("gpu"));
WebContents* web_contents = shell()->web_contents();
// Navigate to the initial page.
EXPECT_FALSE(web_contents->GetPrimaryMainFrame()->GetEnabledBindings().Has(
BindingsPolicyValue::kWebUi));
EXPECT_TRUE(NavigateToURL(shell(), web_ui_url));
EXPECT_TRUE(web_contents->GetPrimaryMainFrame()->GetEnabledBindings().Has(
BindingsPolicyValue::kWebUi));
scoped_refptr<SiteInstance> web_ui_process = web_contents->GetSiteInstance();
// Start a new, non-webUI navigation that will be blocked by a
// NavigationThrottle.
GURL blocked_url("http://blocked-by-throttle.example.cc");
TestNavigationThrottleInstaller installer(
web_contents, NavigationThrottle::BLOCK_REQUEST,
NavigationThrottle::PROCEED, NavigationThrottle::PROCEED,
NavigationThrottle::PROCEED, NavigationThrottle::PROCEED);
NavigationHandleObserver commit_observer(web_contents, blocked_url);
EXPECT_FALSE(NavigateToURL(shell(), blocked_url));
NavigationEntry* last_committed =
web_contents->GetController().GetLastCommittedEntry();
EXPECT_TRUE(last_committed);
EXPECT_EQ(blocked_url, last_committed->GetVirtualURL());
EXPECT_EQ(PAGE_TYPE_ERROR, last_committed->GetPageType());
EXPECT_NE(web_ui_process.get(), web_contents->GetSiteInstance());
EXPECT_TRUE(commit_observer.has_committed());
EXPECT_TRUE(commit_observer.is_error());
EXPECT_FALSE(commit_observer.is_renderer_initiated());
}
// Redirects to renderer debug URLs caused problems.
// See https://crbug.com/728398.
IN_PROC_BROWSER_TEST_F(NavigationRequestBrowserTest,
RedirectToRendererDebugUrl) {
GURL url(embedded_test_server()->GetURL("/title1.html"));
EXPECT_TRUE(NavigateToURL(shell(), url));
const GURL kTestUrls[] = {GURL("javascript:window.alert('hello')"),
GURL(blink::kChromeUIBadCastCrashURL),
GURL(blink::kChromeUICrashURL),
GURL(blink::kChromeUIDumpURL),
GURL(blink::kChromeUIKillURL),
GURL(blink::kChromeUIHangURL),
GURL(blink::kChromeUIShorthangURL),
GURL(blink::kChromeUIMemoryExhaustURL)};
for (const auto& test_url : kTestUrls) {
SCOPED_TRACE(testing::Message() << "renderer_debug_url = " << test_url);
GURL redirecting_url =
embedded_test_server()->GetURL("/server-redirect?" + test_url.spec());
NavigationHandleObserver observer(shell()->web_contents(), redirecting_url);
NavigationLogger logger(shell()->web_contents());
// Try to navigate to the url. The navigation should be canceled and the
// NavigationHandle should have the right error code. Note that javascript
// URLS use ERR_ABORTED rather than ERR_UNSAFE_REDIRECT due to
// https://crbug.com/941653.
EXPECT_FALSE(NavigateToURL(shell(), redirecting_url));
int expected_err_code = test_url.SchemeIs("javascript")
? net::ERR_ABORTED
: net::ERR_UNSAFE_REDIRECT;
EXPECT_EQ(expected_err_code, observer.net_error_code());
// Both WebContentsObserver::{DidStartNavigation, DidFinishNavigation}
// are called, but no WebContentsObserver::DidRedirectNavigation.
std::vector<GURL> started_navigation = {redirecting_url};
std::vector<GURL> redirected_navigation; // Empty.
std::vector<GURL> finished_navigation = {redirecting_url};
EXPECT_EQ(started_navigation, logger.started_navigation_urls());
EXPECT_EQ(redirected_navigation, logger.redirected_navigation_urls());
EXPECT_EQ(finished_navigation, logger.finished_navigation_urls());
}
}
// Check that iframe with embedded credentials are blocked.
// See https://crbug.com/755892.
// TODO(crbug.com/40799853): Enable the test again.
IN_PROC_BROWSER_TEST_F(NavigationRequestBrowserTest,
DISABLED_BlockCredentialedSubresources) {
const struct {
GURL main_url;
GURL iframe_url;
bool blocked;
} kTestCases[] = {
// Normal case with no credential in neither of the urls.
{GURL("http://a.com/frame_tree/page_with_one_frame.html"),
GURL("http://a.com/title1.html"), false},
// Username in the iframe, but nothing in the main frame.
{GURL("http://a.com/frame_tree/page_with_one_frame.html"),
GURL("http://user@a.com/title1.html"), true},
// Username and password in the iframe, but none in the main frame.
{GURL("http://a.com/frame_tree/page_with_one_frame.html"),
GURL("http://user:pass@a.com/title1.html"), true},
// Username and password in the main frame, but none in the iframe.
{GURL("http://user:pass@a.com/frame_tree/page_with_one_frame.html"),
GURL("http://a.com/title1.html"), false},
// Same usernames in both frames.
// Relative URLs on top-level pages that were loaded with embedded
// credentials should load correctly.
{GURL("http://user@a.com/frame_tree/page_with_one_frame.html"),
GURL("http://user@a.com/title1.html"), false},
// Same usernames and passwords in both frames.
// Relative URLs on top-level pages that were loaded with embedded
// credentials should load correctly.
{GURL("http://user:pass@a.com/frame_tree/page_with_one_frame.html"),
GURL("http://user:pass@a.com/title1.html"), false},
// Different usernames.
{GURL("http://user@a.com/frame_tree/page_with_one_frame.html"),
GURL("http://wrong@a.com/title1.html"), true},
// Different passwords.
{GURL("http://user:pass@a.com/frame_tree/page_with_one_frame.html"),
GURL("http://user:wrong@a.com/title1.html"), true},
// Different usernames and same passwords.
{GURL("http://user:pass@a.com/frame_tree/page_with_one_frame.html"),
GURL("http://wrong:pass@a.com/title1.html"), true},
// Different origins.
{GURL("http://user:pass@a.com/frame_tree/page_with_one_frame.html"),
GURL("http://user:pass@b.com/title1.html"), true},
};
for (const auto& test_case : kTestCases) {
// Modify the URLs port to use the embedded test server's port.
std::string port_str(base::NumberToString(embedded_test_server()->port()));
GURL::Replacements set_port;
set_port.SetPortStr(port_str);
GURL main_url(test_case.main_url.ReplaceComponents(set_port));
GURL iframe_url_final(test_case.iframe_url.ReplaceComponents(set_port));
GURL iframe_url_with_redirect = GURL(embedded_test_server()->GetURL(
"/server-redirect?" + iframe_url_final.spec()));
ASSERT_TRUE(NavigateToURL(shell(), main_url));
// Blocking the request must work, even after a redirect.
for (bool redirect : {false, true}) {
const GURL& iframe_url =
redirect ? iframe_url_with_redirect : iframe_url_final;
SCOPED_TRACE(::testing::Message()
<< std::endl
<< "- main_url = " << main_url << std::endl
<< "- iframe_url = " << iframe_url << std::endl);
NavigationHandleObserver subframe_observer(shell()->web_contents(),
iframe_url);
TestNavigationThrottleInstaller installer(
shell()->web_contents(), NavigationThrottle::PROCEED,
NavigationThrottle::PROCEED, NavigationThrottle::PROCEED,
NavigationThrottle::PROCEED, NavigationThrottle::PROCEED);
NavigateIframeToURL(shell()->web_contents(), "child0", iframe_url);
FrameTreeNode* root =
static_cast<WebContentsImpl*>(shell()->web_contents())
->GetPrimaryFrameTree()
.root();
ASSERT_EQ(1u, root->child_count());
if (test_case.blocked) {
EXPECT_EQ(redirect, !!installer.will_start_called());
EXPECT_FALSE(installer.will_process_called());
EXPECT_FALSE(subframe_observer.has_committed());
EXPECT_TRUE(subframe_observer.last_committed_url().is_empty());
EXPECT_NE(iframe_url_final, root->child_at(0u)->current_url());
} else {
EXPECT_TRUE(installer.will_start_called());
EXPECT_TRUE(installer.will_process_called());
EXPECT_TRUE(subframe_observer.has_committed());
EXPECT_EQ(iframe_url_final, subframe_observer.last_committed_url());
EXPECT_EQ(iframe_url_final, root->child_at(0u)->current_url());
}
}
}
}
IN_PROC_BROWSER_TEST_F(NavigationRequestBrowserTest_IsolateAllSites,
StartToCommitMetrics) {
enum class FrameType {
kMain,
kSub,
};
enum class ProcessType {
kCross,
kSame,
};
enum class TransitionType {
kNew,
kReload,
kBackForward,
};
// Uses the provided ProcessType, FrameType, and TransitionType expected for
// this navigation to generate all combinations of Navigation.StartToCommit
// metrics.
auto check_navigation = [](const base::HistogramTester& histograms,
ProcessType process_type, FrameType frame_type,
TransitionType transition_type) {
const std::map<FrameType, std::string> kFrameSuffixes = {
{FrameType::kMain, ".MainFrame"}, {FrameType::kSub, ".Subframe"}};
const std::map<ProcessType, std::string> kProcessSuffixes = {
{ProcessType::kCross, ".CrossProcess"},
{ProcessType::kSame, ".SameProcess"}};
const std::map<TransitionType, std::string> kTransitionSuffixes = {
{TransitionType::kNew, ".NewNavigation"},
{TransitionType::kReload, ".Reload"},
{TransitionType::kBackForward, ".BackForward"},
};
// Add the suffix to all existing histogram names, and append the results to
// |names|.
std::vector<std::string> names{"Navigation.StartToCommit"};
auto add_suffix = [&names](std::vector<std::string> suffixes) {
size_t original_size = names.size();
for (size_t i = 0; i < original_size; i++) {
for (const std::string& suffix : suffixes) {
names.push_back(names[i] + suffix);
}
}
};
add_suffix({kProcessSuffixes.at(process_type)});
add_suffix({kFrameSuffixes.at(frame_type)});
add_suffix({kTransitionSuffixes.at(transition_type),
".ForegroundProcessPriority"});
// Check that all generated histogram names are logged exactly once.
for (const auto& name : names) {
histograms.ExpectTotalCount(name, 1);
}
// Check that no additional histograms with the StartToCommit prefix were
// logged.
base::HistogramTester::CountsMap counts =
histograms.GetTotalCountsForPrefix("Navigation.StartToCommit");
int32_t total_counts = 0;
for (const auto& it : counts) {
total_counts += it.second;
}
EXPECT_EQ(static_cast<int32_t>(names.size()), total_counts);
};
// Main frame tests.
EXPECT_TRUE(
NavigateToURL(shell(), embedded_test_server()->GetURL("/hello.html")));
{
base::HistogramTester histograms;
GURL url(embedded_test_server()->GetURL("/title1.html"));
EXPECT_TRUE(NavigateToURL(shell(), url));
check_navigation(histograms, ProcessType::kSame, FrameType::kMain,
TransitionType::kNew);
}
{
base::HistogramTester histograms;
GURL url(embedded_test_server()->GetURL("b.com", "/title1.html"));
EXPECT_TRUE(NavigateToURL(shell(), url));
check_navigation(histograms, ProcessType::kCross, FrameType::kMain,
TransitionType::kNew);
}
{
base::HistogramTester histograms;
ReloadBlockUntilNavigationsComplete(shell(), 1);
check_navigation(histograms, ProcessType::kSame, FrameType::kMain,
TransitionType::kReload);
}
{
base::HistogramTester histograms;
TestNavigationObserver nav_observer(shell()->web_contents());
shell()->GoBackOrForward(-1);
nav_observer.Wait();
check_navigation(histograms, ProcessType::kCross, FrameType::kMain,
TransitionType::kBackForward);
}
{
base::HistogramTester histograms;
TestNavigationObserver nav_observer(shell()->web_contents());
shell()->GoBackOrForward(-1);
nav_observer.Wait();
check_navigation(histograms, ProcessType::kSame, FrameType::kMain,
TransitionType::kBackForward);
}
{
base::HistogramTester histograms;
int previous_process_id = shell()
->web_contents()
->GetPrimaryMainFrame()
->GetProcess()
->GetDeprecatedID();
EXPECT_TRUE(NavigateToURL(shell(), GURL(url::kAboutBlankURL)));
bool process_changed = (previous_process_id != shell()
->web_contents()
->GetPrimaryMainFrame()
->GetProcess()
->GetDeprecatedID());
check_navigation(histograms,
process_changed ? ProcessType::kCross : ProcessType::kSame,
FrameType::kMain, TransitionType::kNew);
}
// Subframe tests. All of these tests just navigate a frame within
// page_with_iframe.html.
EXPECT_TRUE(NavigateToURL(
shell(), embedded_test_server()->GetURL("/page_with_iframe.html")));
FrameTreeNode* first_child =
static_cast<WebContentsImpl*>(shell()->web_contents())
->GetPrimaryFrameTree()
.root()
->child_at(0);
{
base::HistogramTester histograms;
EXPECT_TRUE(NavigateToURLFromRenderer(
first_child, embedded_test_server()->GetURL("c.com", "/title1.html")));
check_navigation(histograms, ProcessType::kCross, FrameType::kSub,
TransitionType::kNew);
}
{
base::HistogramTester histograms;
TestFrameNavigationObserver nav_observer(first_child);
EXPECT_TRUE(ExecJs(first_child, "location.reload();"));
nav_observer.Wait();
// location.reload triggers the PAGE_TRANSITION_AUTO_SUBFRAME which
// corresponds to NewNavigation.
check_navigation(histograms, ProcessType::kSame, FrameType::kSub,
TransitionType::kNew);
}
{
base::HistogramTester histograms;
shell()->GoBackOrForward(-1);
EXPECT_TRUE(WaitForLoadStop(shell()->web_contents()));
// History back triggers the PAGE_TRANSITION_AUTO_SUBFRAME which corresponds
// to NewNavigation.
check_navigation(histograms, ProcessType::kCross, FrameType::kSub,
TransitionType::kNew);
}
EXPECT_TRUE(NavigateToURLFromRenderer(
first_child, embedded_test_server()->GetURL("/simple_links.html")));
{
base::HistogramTester histograms;
TestFrameNavigationObserver nav_observer(first_child);
EXPECT_TRUE(ExecJs(first_child, "clickSameSiteLink();"));
nav_observer.Wait();
// Link clicking will trigger PAGE_TRANSITION_MANUAL_SUBFRAME which
// corresponds to NewNavigation.
check_navigation(histograms, ProcessType::kSame, FrameType::kSub,
TransitionType::kNew);
}
}
// Verify that the TimeToReadyToCommit2 metrics are correctly logged for
// SameProcess vs CrossProcess as well as MainFrame vs Subframe cases.
IN_PROC_BROWSER_TEST_F(NavigationRequestBrowserTest,
TimeToReadyToCommitMetrics) {
EXPECT_TRUE(
NavigateToURL(shell(), embedded_test_server()->GetURL("/hello.html")));
// Check that only SameProcess version is logged and not CrossProcess.
{
base::HistogramTester histograms;
GURL url(embedded_test_server()->GetURL("/title1.html"));
EXPECT_TRUE(NavigateToURL(shell(), url));
base::HistogramTester::CountsMap expected_counts = {
{"Navigation.TimeToReadyToCommit2.MainFrame", 1},
{"Navigation.TimeToReadyToCommit2.MainFrame.NewNavigation", 1},
{"Navigation.TimeToReadyToCommit2.NewNavigation", 1},
{"Navigation.TimeToReadyToCommit2.SameProcess", 1},
{"Navigation.TimeToReadyToCommit2.SameProcess.NewNavigation", 1}};
EXPECT_THAT(
histograms.GetTotalCountsForPrefix("Navigation.TimeToReadyToCommit2."),
testing::ContainerEq(expected_counts));
}
// Navigate cross-process and ensure that only CrossProcess is logged.
{
base::HistogramTester histograms;
GURL url(embedded_test_server()->GetURL("a.com", "/title2.html"));
EXPECT_TRUE(NavigateToURL(shell(), url));
base::HistogramTester::CountsMap expected_counts = {
{"Navigation.TimeToReadyToCommit2.MainFrame", 1},
{"Navigation.TimeToReadyToCommit2.MainFrame.NewNavigation", 1},
{"Navigation.TimeToReadyToCommit2.NewNavigation", 1},
{"Navigation.TimeToReadyToCommit2.CrossProcess", 1},
{"Navigation.TimeToReadyToCommit2.CrossProcess.NewNavigation", 1}};
EXPECT_THAT(
histograms.GetTotalCountsForPrefix("Navigation.TimeToReadyToCommit2."),
testing::ContainerEq(expected_counts));
}
// Add a new subframe.
FrameTreeNode* root = static_cast<WebContentsImpl*>(shell()->web_contents())
->GetPrimaryFrameTree()
.root();
EXPECT_TRUE(ExecJs(
root, "document.body.appendChild(document.createElement('iframe'));"));
// Navigate subframe cross-site and ensure Subframe metrics are logged.
{
base::HistogramTester histograms;
GURL url(embedded_test_server()->GetURL("b.com", "/title3.html"));
EXPECT_TRUE(NavigateToURLFromRenderer(root->child_at(0), url));
std::string navigation_type =
AreAllSitesIsolatedForTesting() ? "CrossProcess" : "SameProcess";
base::HistogramTester::CountsMap expected_counts = {
{"Navigation.TimeToReadyToCommit2.Subframe", 1},
{"Navigation.TimeToReadyToCommit2.Subframe.NewNavigation", 1},
{"Navigation.TimeToReadyToCommit2.NewNavigation", 1},
{base::StringPrintf("Navigation.TimeToReadyToCommit2.%s",
navigation_type.c_str()),
1},
{base::StringPrintf("Navigation.TimeToReadyToCommit2.%s.NewNavigation",
navigation_type.c_str()),
1}};
EXPECT_THAT(
histograms.GetTotalCountsForPrefix("Navigation.TimeToReadyToCommit2."),
testing::ContainerEq(expected_counts));
}
}
IN_PROC_BROWSER_TEST_F(NavigationRequestDownloadBrowserTest, IsDownload) {
GURL url(embedded_test_server()->GetURL("/download-test1.lib"));
NavigationHandleObserver observer(shell()->web_contents(), url);
EXPECT_TRUE(NavigateToURLAndExpectNoCommit(shell(), url));
EXPECT_FALSE(observer.has_committed());
EXPECT_TRUE(observer.is_download());
}
IN_PROC_BROWSER_TEST_F(NavigationRequestDownloadBrowserTest,
DownloadFalseForHtmlResponse) {
GURL url(embedded_test_server()->GetURL("/title1.html"));
NavigationHandleObserver observer(shell()->web_contents(), url);
EXPECT_TRUE(NavigateToURL(shell(), url));
EXPECT_TRUE(observer.has_committed());
EXPECT_FALSE(observer.is_download());
}
IN_PROC_BROWSER_TEST_F(NavigationRequestDownloadBrowserTest,
DownloadFalseFor404) {
GURL url(embedded_test_server()->GetURL("/page404.html"));
NavigationHandleObserver observer(shell()->web_contents(), url);
EXPECT_TRUE(NavigateToURL(shell(), url));
EXPECT_TRUE(observer.has_committed());
EXPECT_FALSE(observer.is_download());
}
IN_PROC_BROWSER_TEST_F(NavigationRequestDownloadBrowserTest,
DownloadFalseForFailedNavigation) {
GURL url(embedded_test_server()->GetURL("/download-test1.lib"));
NavigationHandleObserver observer(shell()->web_contents(), url);
TestNavigationThrottleInstaller installer(
shell()->web_contents(), NavigationThrottle::CANCEL,
NavigationThrottle::PROCEED, NavigationThrottle::PROCEED,
NavigationThrottle::PROCEED, NavigationThrottle::PROCEED);
EXPECT_TRUE(NavigateToURLAndExpectNoCommit(shell(), url));
EXPECT_FALSE(observer.has_committed());
EXPECT_TRUE(observer.is_error());
EXPECT_FALSE(observer.is_download());
}
IN_PROC_BROWSER_TEST_F(NavigationRequestDownloadBrowserTest,
RedirectToDownload) {
GURL redirect_url(
embedded_test_server()->GetURL("/cross-site/bar.com/download-test1.lib"));
NavigationHandleObserver observer(shell()->web_contents(), redirect_url);
EXPECT_TRUE(NavigateToURLAndExpectNoCommit(shell(), redirect_url));
EXPECT_FALSE(observer.has_committed());
EXPECT_TRUE(observer.was_redirected());
EXPECT_TRUE(observer.is_download());
}
IN_PROC_BROWSER_TEST_F(NavigationRequestDownloadBrowserTest,
RedirectToDownloadFails) {
GURL redirect_url(
embedded_test_server()->GetURL("/cross-site/bar.com/download-test1.lib"));
NavigationHandleObserver observer(shell()->web_contents(), redirect_url);
TestNavigationThrottleInstaller installer(
shell()->web_contents(), NavigationThrottle::PROCEED,
NavigationThrottle::CANCEL, NavigationThrottle::PROCEED,
NavigationThrottle::PROCEED, NavigationThrottle::PROCEED);
EXPECT_FALSE(NavigateToURL(shell(), redirect_url));
EXPECT_FALSE(observer.has_committed());
EXPECT_FALSE(observer.is_download());
EXPECT_TRUE(observer.is_error());
EXPECT_TRUE(observer.was_redirected());
}
// Set of tests that check the various NavigationThrottle events can be used
// with custom error pages.
class NavigationRequestThrottleResultWithErrorPageBrowserTest
: public NavigationRequestBrowserTest,
public ::testing::WithParamInterface<NavigationThrottle::ThrottleAction> {
};
IN_PROC_BROWSER_TEST_P(NavigationRequestThrottleResultWithErrorPageBrowserTest,
WillStartRequest) {
NavigationThrottle::ThrottleAction action = GetParam();
if (action == NavigationThrottle::CANCEL_AND_IGNORE) {
// There is no support for CANCEL_AND_IGNORE and a custom error page.
return;
}
if (action == NavigationThrottle::BLOCK_REQUEST_AND_COLLAPSE) {
// This can only be returned from sub frame navigations.
return;
}
if (action == NavigationThrottle::PROCEED ||
action == NavigationThrottle::DEFER) {
// Neither is relevant for what we want to test i.e. error pages.
return;
}
if (action == NavigationThrottle::BLOCK_RESPONSE) {
// BLOCK_RESPONSE can't be used with WillStartRequest.
return;
}
GURL url(embedded_test_server()->GetURL("/title1.html"));
InstallThrottleAndTestNavigationCommittedWithErrorPage(
url, action, TestNavigationThrottleInstaller::WILL_START_REQUEST);
}
IN_PROC_BROWSER_TEST_P(NavigationRequestThrottleResultWithErrorPageBrowserTest,
WillRedirectRequest) {
NavigationThrottle::ThrottleAction action = GetParam();
if (action == NavigationThrottle::CANCEL_AND_IGNORE) {
// There is no support for CANCEL_AND_IGNORE and a custom error page.
return;
}
if (action == NavigationThrottle::PROCEED ||
action == NavigationThrottle::DEFER) {
// Neither is relevant for what we want to test i.e. error pages.
return;
}
if (action == NavigationThrottle::BLOCK_REQUEST_AND_COLLAPSE) {
// This can only be returned from sub frame navigations.
return;
}
if (action == NavigationThrottle::BLOCK_RESPONSE) {
// BLOCK_RESPONSE can't be used with WillRedirectRequest.
return;
}
GURL url(embedded_test_server()->GetURL("/cross-site/foo.com/title1.html"));
InstallThrottleAndTestNavigationCommittedWithErrorPage(
url, action, TestNavigationThrottleInstaller::WILL_REDIRECT_REQUEST);
}
IN_PROC_BROWSER_TEST_P(NavigationRequestThrottleResultWithErrorPageBrowserTest,
WillFailRequest) {
NavigationThrottle::ThrottleAction action = GetParam();
if (action == NavigationThrottle::PROCEED ||
action == NavigationThrottle::DEFER) {
// Neither is relevant for what we want to test i.e. error pages.
return;
}
if (action == NavigationThrottle::BLOCK_REQUEST ||
action == NavigationThrottle::BLOCK_REQUEST_AND_COLLAPSE) {
// BLOCK_REQUEST, BLOCK_REQUEST_AND_COLLAPSE, can't be used with
// WillFailRequest.
return;
}
net::EmbeddedTestServer https_server(net::EmbeddedTestServer::TYPE_HTTPS);
https_server.SetSSLConfig(net::EmbeddedTestServer::CERT_MISMATCHED_NAME);
ASSERT_TRUE(https_server.Start());
const GURL url = https_server.GetURL("/title1.html");
InstallThrottleAndTestNavigationCommittedWithErrorPage(
url, action, TestNavigationThrottleInstaller::WILL_FAIL_REQUEST);
}
IN_PROC_BROWSER_TEST_P(NavigationRequestThrottleResultWithErrorPageBrowserTest,
WillProcessResponse) {
NavigationThrottle::ThrottleAction action = GetParam();
if (action == NavigationThrottle::CANCEL_AND_IGNORE) {
// There is no support for CANCEL_AND_IGNORE and a custom error page.
return;
}
if (action == NavigationThrottle::PROCEED ||
action == NavigationThrottle::DEFER) {
// Neither is relevant for what we want to test i.e. error pages.
return;
}
if (action == NavigationThrottle::BLOCK_REQUEST ||
action == NavigationThrottle::BLOCK_REQUEST_AND_COLLAPSE) {
// BLOCK_REQUEST and BLOCK_REQUEST_AND_COLLAPSE can't be used with
// WillProcessResponse.
return;
}
GURL url(embedded_test_server()->GetURL("/title1.html"));
InstallThrottleAndTestNavigationCommittedWithErrorPage(
url, action, TestNavigationThrottleInstaller::WILL_PROCESS_RESPONSE);
}
INSTANTIATE_TEST_SUITE_P(
All,
NavigationRequestThrottleResultWithErrorPageBrowserTest,
testing::Range(NavigationThrottle::ThrottleAction::FIRST,
NavigationThrottle::ThrottleAction::LAST));
// The set of tests...
// * NavigationRequestDownloadBrowserTest.AllowedResourceDownloaded
// * NavigationRequestDownloadBrowserTest.AllowedResourceNotDownloaded
// * NavigationRequestDownloadBrowserTest.Disallowed
//
// ...covers every combination of possible states for:
// * CommonNavigationParams::download_policy (allow vs disallow)
// * NavigationHandle::IsDownload()
//
// Download policies that enumerate allowed / disallowed options are not tested
// here.
IN_PROC_BROWSER_TEST_F(NavigationRequestDownloadBrowserTest,
AllowedResourceDownloaded) {
GURL simple_url(embedded_test_server()->GetURL("/simple_page.html"));
TestNavigationManager manager(shell()->web_contents(), simple_url);
NavigationHandleObserver handle_observer(shell()->web_contents(), simple_url);
// Download is allowed.
shell()->LoadURL(simple_url);
EXPECT_TRUE(manager.WaitForRequestStart());
FrameTreeNode* root = static_cast<WebContentsImpl*>(shell()->web_contents())
->GetPrimaryMainFrame()
->frame_tree_node();
EXPECT_TRUE(root->navigation_request()
->common_params()
.download_policy.IsDownloadAllowed());
// This is not a download (though allowed), so the response should be
// rendered.
EXPECT_TRUE(manager.WaitForResponse());
EXPECT_TRUE(root->navigation_request()->response_should_be_rendered());
// The response is not handled as a download.
ASSERT_TRUE(manager.WaitForNavigationFinished());
EXPECT_FALSE(handle_observer.is_download());
}
// See NavigationRequestDownloadBrowserTest.AllowedResourceNotDownloaded
IN_PROC_BROWSER_TEST_F(NavigationRequestDownloadBrowserTest,
AllowedResourceNotDownloaded) {
GURL download_url(embedded_test_server()->GetURL("/download-test1.lib"));
TestNavigationManager manager(shell()->web_contents(), download_url);
NavigationHandleObserver handle_observer(shell()->web_contents(),
download_url);
// Download is allowed.
shell()->LoadURL(download_url);
EXPECT_TRUE(manager.WaitForRequestStart());
FrameTreeNode* root = static_cast<WebContentsImpl*>(shell()->web_contents())
->GetPrimaryMainFrame()
->frame_tree_node();
EXPECT_TRUE(root->navigation_request()
->common_params()
.download_policy.IsDownloadAllowed());
// Downloads do not need to be rendered, and should not be rendered.
EXPECT_TRUE(manager.WaitForResponse());
EXPECT_FALSE(root->navigation_request()->response_should_be_rendered());
// The response is handled as a download.
ASSERT_TRUE(manager.WaitForNavigationFinished());
EXPECT_TRUE(handle_observer.is_download());
}
// See NavigationRequestDownloadBrowserTest.AllowedResourceNotDownloaded
IN_PROC_BROWSER_TEST_F(NavigationRequestDownloadBrowserTest, Disallowed) {
GURL download_url(embedded_test_server()->GetURL("/download-test1.lib"));
// An URL is allowed to be a download iff it is not a view-source URL.
GURL view_source_url =
GURL(content::kViewSourceScheme + std::string(":") + download_url.spec());
NavigationHandleObserver handle_observer(shell()->web_contents(),
download_url);
TestNavigationManager manager(shell()->web_contents(), download_url);
// Download is not allowed.
shell()->LoadURL(view_source_url);
EXPECT_TRUE(manager.WaitForRequestStart());
FrameTreeNode* root = static_cast<WebContentsImpl*>(shell()->web_contents())
->GetPrimaryMainFrame()
->frame_tree_node();
EXPECT_TRUE(
root->navigation_request()->common_params().download_policy.IsType(
blink::NavigationDownloadType::kViewSource));
EXPECT_FALSE(root->navigation_request()
->common_params()
.download_policy.IsDownloadAllowed());
// The response is not handled as a download.
ASSERT_TRUE(manager.WaitForNavigationFinished());
EXPECT_FALSE(handle_observer.is_download());
}
class NavigationRequestBackForwardBrowserTest
: public NavigationRequestBrowserTest,
public WebContentsObserver {
protected:
void SetUpOnMainThread() override {
NavigationRequestBrowserTest::SetUpOnMainThread();
WebContentsObserver::Observe(shell()->web_contents());
}
void DidFinishNavigation(NavigationHandle* navigation_handle) override {
if (navigation_handle->HasCommitted()) {
offsets_.push_back(navigation_handle->GetNavigationEntryOffset());
}
}
std::vector<int64_t> offsets_;
};
IN_PROC_BROWSER_TEST_F(NavigationRequestBackForwardBrowserTest,
NavigationEntryOffsets) {
const GURL url1(embedded_test_server()->GetURL("/title1.html"));
const GURL url2(embedded_test_server()->GetURL("/title2.html"));
const GURL url3(embedded_test_server()->GetURL("/title3.html"));
EXPECT_TRUE(NavigateToURL(shell(), url1));
// The navigation entries are:
// [*url1].
{
TestNavigationObserver navigation_observer(shell()->web_contents());
shell()->Reload();
navigation_observer.WaitForNavigationFinished();
}
// The navigation entries are:
// [*url1].
EXPECT_TRUE(NavigateToURL(shell(), url2));
// The navigation entries are:
// [url1, *url2].
EXPECT_TRUE(NavigateToURL(shell(), url3));
// The navigation entries are:
// [url1, url2, *url3].
{
TestNavigationObserver navigation_observer(shell()->web_contents());
shell()->GoBackOrForward(-1);
navigation_observer.WaitForNavigationFinished();
}
// The navigation entries are:
// [url1, *url2, url3].
{
TestNavigationObserver navigation_observer(shell()->web_contents());
shell()->GoBackOrForward(-1);
navigation_observer.WaitForNavigationFinished();
}
// The navigation entries are:
// [*url1, url2, url3].
{
TestNavigationObserver navigation_observer(shell()->web_contents());
shell()->GoBackOrForward(1);
navigation_observer.WaitForNavigationFinished();
}
// The navigation entries are:
// [url1, *url2, url3].
// Navigations 1, 3, 4 are regular navigations.
// Navigation 2 is a reload.
// Navigaations 5 and 6 are back navigations.
// Navigation 7 is a forward navigation.
EXPECT_THAT(offsets_, testing::ElementsAre(1, 0, 1, 1, -1, -1, 1));
}
IN_PROC_BROWSER_TEST_F(NavigationRequestBackForwardBrowserTest,
NavigationEntryOffsetsForSubframes) {
const GURL url1(embedded_test_server()->GetURL("/title1.html"));
const GURL url1_fragment1(
embedded_test_server()->GetURL("/title1.html#id_1"));
const GURL url2(embedded_test_server()->GetURL(
"b.com", "/frame_tree/page_with_one_frame.html"));
const char kChildFrameId[] = "child0";
EXPECT_TRUE(NavigateToURL(shell(), url1));
// The navigation entries are:
// [*url1].
EXPECT_TRUE(NavigateToURL(shell(), url1_fragment1));
// The navigation entries are:
// [url1, *url1_fragment1].
EXPECT_TRUE(NavigateToURL(shell(), url2));
// The navigation entries are:
// [url1, url1_fragment1, *url2(subframe)].
EXPECT_TRUE(
NavigateIframeToURL(shell()->web_contents(), kChildFrameId, url1));
// The navigation entries are:
// [url1, url1_fragment1, url2(subframe), *url2(url1)].
EXPECT_TRUE(NavigateToURL(shell(), url1));
// The navigation entries are:
// [url1, url1_fragment1, url2(subframe), url2(url1), *url1].
{
// We are waiting for two navigations here: main frame and subframe.
// However, when back/forward cache is enabled, back navigation to a page
// with subframes will not trigger a subframe navigation (since the
// subframe is cached with the page).
TestNavigationObserver navigation_observer(
shell()->web_contents(), IsBackForwardCacheEnabled() ? 1 : 2);
shell()->GoBackOrForward(-1);
navigation_observer.WaitForNavigationFinished();
}
// The navigation entries are:
// [url1, url1_fragment1, url2(subframe), *url2(url1), url1].
{
TestNavigationObserver navigation_observer(shell()->web_contents());
shell()->GoBackOrForward(-1);
navigation_observer.WaitForNavigationFinished();
}
// The navigation entries are:
// [url1, url1_fragment1, *url2(subframe), url2(url1), url1].
{
TestNavigationObserver navigation_observer(shell()->web_contents());
shell()->GoBackOrForward(-1);
navigation_observer.WaitForNavigationFinished();
}
// The navigation entries are:
// [url1, *url1_fragment1, url2(subframe), url2(url1), url1].
{
TestNavigationObserver navigation_observer(shell()->web_contents());
shell()->GoBackOrForward(-1);
navigation_observer.WaitForNavigationFinished();
}
// The navigation entries are:
// [*url1, url1_fragment1, url2(subframe), url2(url1), url1].
{
TestNavigationObserver navigation_observer(shell()->web_contents());
shell()->GoBackOrForward(4);
navigation_observer.WaitForNavigationFinished();
}
// The navigation entries are:
// [url1, url1_fragment1, url2(subframe), url2(url1), *url1].
// New navigations have offset 1, back navigations have offset -1 and the last
// navigations have offset 3 as requested.
// Note that all subframe navigations have offset 1 regardless of whether they
// result in a new entry being generated or not.
if (IsBackForwardCacheEnabled()) {
// When back/forward cache is enabled, back navigation to a page with
// subframes will not trigger a subframe navigation (since the subframe is
// cached with the page and won't need to be reconstructed/navigated).
EXPECT_THAT(offsets_,
testing::ElementsAre(1, 1, 1, 0, 1, 1, -1, -1, -1, -1, 4));
} else {
EXPECT_THAT(offsets_,
testing::ElementsAre(1, 1, 1, 0, 1, 1, -1, 1, -1, -1, -1, 4));
}
}
IN_PROC_BROWSER_TEST_F(NavigationRequestBackForwardBrowserTest,
NavigationEntryLimit) {
const GURL url1(embedded_test_server()->GetURL("/title1.html"));
static_cast<NavigationControllerImpl*>(
&shell()->web_contents()->GetController())
->set_max_entry_count_for_testing(3);
for (int i = 0; i < 5; ++i) {
EXPECT_TRUE(NavigateToURL(shell(), url1));
}
// Expect that the offsets are still 1 even when we hit the entry count limit.
EXPECT_THAT(offsets_, testing::ElementsAre(1, 1, 1, 1, 1));
}
IN_PROC_BROWSER_TEST_F(NavigationRequestBackForwardBrowserTest,
SameUrlNavigationFromAddressBar) {
const GURL url1(embedded_test_server()->GetURL("/title1.html"));
// NavigateToURL is treated like an address bar navigation because it uses
// NavigateToURLBlockUntilNavigationsComplete, which sets that transition
// type.
EXPECT_TRUE(NavigateToURL(shell(), url1));
EXPECT_TRUE(NavigateToURL(shell(), url1));
// The second navigation has an offset of 1 because the estimated
// offset is calculated at the time when the navigation request is created and
// it is created as a regular navigation without should_replace_current_entry
// set. The estimated offset is not updated when should_replace_current_entry
// is updated to true later on in NavigationRequest::StartNavigation.
// We should consider fixing this to report an offset of 0 instead.
EXPECT_THAT(offsets_, testing::ElementsAre(1, 1));
}
IN_PROC_BROWSER_TEST_F(NavigationRequestBackForwardBrowserTest,
LocationReplace) {
const GURL url1(embedded_test_server()->GetURL("/title1.html"));
EXPECT_TRUE(NavigateToURL(shell(), url1));
FrameTreeNode* root = static_cast<WebContentsImpl*>(shell()->web_contents())
->GetPrimaryFrameTree()
.root();
{
TestNavigationObserver navigation_observer(shell()->web_contents());
EXPECT_TRUE(ExecJs(root, "window.location.replace('#frag');"));
navigation_observer.WaitForNavigationFinished();
}
// The second navigation replaces the current navigation entry and should have
// offset of zero.
EXPECT_THAT(offsets_, testing::ElementsAre(1, 0));
}
// Tests that the correct net::AuthChallengeInfo is exposed from the
// NavigationHandle when the page requests authentication.
IN_PROC_BROWSER_TEST_F(NavigationRequestBrowserTest, AuthChallengeInfo) {
GURL url(embedded_test_server()->GetURL("/auth-basic"));
NavigationHandleObserver observer(shell()->web_contents(), url);
EXPECT_TRUE(NavigateToURL(shell(), url));
EXPECT_TRUE(observer.has_committed());
ASSERT_TRUE(observer.auth_challenge_info().has_value());
EXPECT_FALSE(observer.auth_challenge_info()->is_proxy);
EXPECT_EQ(url::SchemeHostPort(url),
observer.auth_challenge_info()->challenger);
EXPECT_EQ("basic", observer.auth_challenge_info()->scheme);
EXPECT_EQ("testrealm", observer.auth_challenge_info()->realm);
EXPECT_EQ("Basic realm=\"testrealm\"",
observer.auth_challenge_info()->challenge);
EXPECT_EQ("/auth-basic", observer.auth_challenge_info()->path);
}
class TestMixedContentWebContentsDelegate : public WebContentsDelegate {
public:
TestMixedContentWebContentsDelegate() = default;
TestMixedContentWebContentsDelegate(
const TestMixedContentWebContentsDelegate&) = delete;
TestMixedContentWebContentsDelegate& operator=(
const TestMixedContentWebContentsDelegate&) = delete;
bool passive_insecure_content_found() {
return passive_insecure_content_found_;
}
// WebContentsDelegate:
void PassiveInsecureContentFound(const GURL& resource_url) override {
passive_insecure_content_found_ = true;
}
private:
bool passive_insecure_content_found_ = false;
};
// Tests that an iframe with a non-webby scheme is not treated as mixed
// content. See https://crbug.com/621131.
IN_PROC_BROWSER_TEST_F(NavigationRequestBrowserTest,
NonWebbyIframeIsNotMixedContent) {
net::EmbeddedTestServer https_server(net::EmbeddedTestServer::TYPE_HTTPS);
https_server.ServeFilesFromSourceDirectory(GetTestDataFilePath());
ASSERT_TRUE(https_server.Start());
GURL url(https_server.GetURL("/title1.html"));
ASSERT_TRUE(NavigateToURL(shell(), url));
// Inject a test delegate to observe when mixed content is detected.
WebContents* contents = shell()->web_contents();
TestMixedContentWebContentsDelegate test_delegate;
contents->SetDelegate(&test_delegate);
// Insert an iframe and navigate it to a non-webby scheme. It shouldn't be
// treated as mixed content.
GURL non_webby_url("foo://bar");
TestNavigationObserver observer(contents);
ASSERT_NE(false,
EvalJs(contents,
JsReplace("var iframe = document.createElement('iframe');"
"iframe.src = $1;"
"document.body.appendChild(iframe);",
non_webby_url)));
observer.Wait();
EXPECT_FALSE(test_delegate.passive_insecure_content_found());
}
// Tests that a NavigationRequest's RFH can be retrieved during a synchronous
// renderer commit same-document navigation (regardless of whether the
// navigation commits or not).
IN_PROC_BROWSER_TEST_F(NavigationRequestBrowserTest,
GetRFHDuringSyncRendererCommitSameDocumentNavigation) {
const GURL url(embedded_test_server()->GetURL("/title1.html"));
const GURL same_doc_url(embedded_test_server()->GetURL("/title1.html#foo"));
EXPECT_TRUE(NavigateToURL(shell(), url));
WebContents* web_contents = shell()->web_contents();
// Test sync-renderer-commit same-document navigation that commits.
{
TestNavigationManager navigation_manager(web_contents, same_doc_url);
testing::NiceMock<MockWebContentsObserver> observer(web_contents);
EXPECT_CALL(observer, DidFinishNavigation(testing::_))
.WillOnce(testing::Invoke([](NavigationHandle* navigation_handle) {
NavigationRequest* request =
NavigationRequest::From(navigation_handle);
EXPECT_TRUE(request->is_synchronous_renderer_commit());
EXPECT_TRUE(navigation_handle->GetRenderFrameHost());
}));
EXPECT_TRUE(ExecJs(web_contents, "location.href = '#foo';"));
ASSERT_TRUE(navigation_manager.WaitForNavigationFinished());
}
EXPECT_TRUE(NavigateToURL(shell(), GURL(url::kAboutBlankURL)));
WebContents* popup = nullptr;
{
WebContentsAddedObserver popup_observer;
ASSERT_TRUE(
ExecJs(web_contents,
JsReplace("var w = window.open($1, 'my-popup')", GURL())));
popup = popup_observer.GetWebContents();
}
// Test sync-renderer-commit same-document navigation that doesn't commit.
{
testing::NiceMock<MockWebContentsObserver> observer(popup);
EXPECT_CALL(observer, DidFinishNavigation(testing::_))
.WillOnce(testing::Invoke([](NavigationHandle* navigation_handle) {
NavigationRequest* request =
NavigationRequest::From(navigation_handle);
EXPECT_TRUE(request->is_synchronous_renderer_commit());
EXPECT_TRUE(navigation_handle->GetRenderFrameHost());
}));
TestNavigationManager navigation_manager(popup, GURL("about:blank#foo"));
EXPECT_TRUE(
ExecJs(web_contents, "w.history.replaceState({}, '', '#foo');"));
ASSERT_TRUE(navigation_manager.WaitForNavigationFinished());
}
}
// Tests that a NavigationRequest's RFH can be retrieved during a synchronous
// renderer commit initial-about-blank navigation (regardless of whether the
// navigation commits or not).
IN_PROC_BROWSER_TEST_F(NavigationRequestBrowserTest,
GetRFHDuringInitialAboutBlankNavigation) {
EXPECT_TRUE(
NavigateToURL(shell(), embedded_test_server()->GetURL("/title1.html")));
WebContentsImpl* web_contents =
static_cast<WebContentsImpl*>(shell()->web_contents());
// Test initial-about-blank navigation that commits.
{
testing::NiceMock<MockWebContentsObserver> observer(web_contents);
EXPECT_CALL(observer, DidFinishNavigation(testing::_))
.WillOnce(testing::Invoke([](NavigationHandle* navigation_handle) {
NavigationRequest* request =
NavigationRequest::From(navigation_handle);
EXPECT_TRUE(request->is_synchronous_renderer_commit());
EXPECT_TRUE(navigation_handle->GetRenderFrameHost());
}));
CreateSubframe(web_contents, "subframe", GURL(),
/*wait_for_navigation*/ true);
}
WebContentsImpl* popup = nullptr;
{
WebContentsAddedObserver popup_observer;
ASSERT_TRUE(
ExecJs(web_contents,
JsReplace("var w = window.open($1, 'my-popup')", GURL())));
popup = static_cast<WebContentsImpl*>(popup_observer.GetWebContents());
}
// Test initial-about-blank navigation that doesn't commit.
{
testing::NiceMock<MockWebContentsObserver> observer(popup);
EXPECT_CALL(observer, DidFinishNavigation(testing::_))
.WillOnce(testing::Invoke([](NavigationHandle* navigation_handle) {
NavigationRequest* request =
NavigationRequest::From(navigation_handle);
EXPECT_TRUE(request->is_synchronous_renderer_commit());
EXPECT_TRUE(navigation_handle->GetRenderFrameHost());
// Ensure that response_should_be_rendered() is true even for pages
// that do not require a URLLoader.
EXPECT_TRUE(request->response_should_be_rendered());
}));
CreateSubframe(popup, "popup_subframe", GURL(),
/*wait_for_navigation*/ true);
}
}
// Verify that when navigating to a site that doesn't require a dedicated
// process from a initial siteless SiteInstance, the SiteInstance sets its site
// at ready-to-commit time (rather than at DidCommitNavigation time).
IN_PROC_BROWSER_TEST_F(NavigationRequestBrowserTest,
SiteIsSetAtResponseTimeWithoutSiteIsolation) {
// A custom ContentBrowserClient to turn off strict site isolation.
class NoSiteIsolationContentBrowserClient
: public ContentBrowserTestContentBrowserClient {
public:
bool ShouldEnableStrictSiteIsolation() override { return false; }
} no_site_isolation_client;
// The test should start in a blank shell with a siteless SiteInstance.
EXPECT_FALSE(
static_cast<SiteInstanceImpl*>(shell()->web_contents()->GetSiteInstance())
->HasSite());
// Start a navigation and wait for response. Note that this won't require a
// dedicated process due to the custom ContentBrowserClient.
GURL main_url(embedded_test_server()->GetURL("bar.com", "/title1.html"));
TestNavigationManager manager(shell()->web_contents(), main_url);
shell()->web_contents()->GetController().LoadURL(
main_url, Referrer(), ui::PAGE_TRANSITION_LINK, std::string());
EXPECT_TRUE(manager.WaitForResponse());
// At this point, the navigation should be processing the response but not
// committed yet. It should have already determined the final
// RenderFrameHost, which should just be the initial RenderFrameHost.
NavigationRequest* request =
static_cast<NavigationRequest*>(manager.GetNavigationHandle());
EXPECT_EQ(request->state(), NavigationRequest::WILL_PROCESS_RESPONSE);
EXPECT_EQ(shell()->web_contents()->GetPrimaryMainFrame(),
request->GetRenderFrameHost());
// The navigation will stay in the initial SiteInstance, and that
// SiteInstance's site should now be set.
EXPECT_TRUE(
static_cast<SiteInstanceImpl*>(shell()->web_contents()->GetSiteInstance())
->HasSite());
// The process should also be considered used at this point.
EXPECT_FALSE(
shell()->web_contents()->GetPrimaryMainFrame()->GetProcess()->IsUnused());
// Ensure the navigation finishes before we restore the ContentBrowserClient
// which would turn strict site isolation back on. Otherwise, the navigation
// commit may fail citadel protection checks at test teardown.
EXPECT_TRUE(manager.WaitForNavigationFinished());
EXPECT_TRUE(manager.was_successful());
}
// Check that a subframe can load an error page with an about:srcdoc URL, and
// that the origin does not inherit the parent's origin (i.e., behaves like all
// error pages) in this case. In practice, this path may be taken by the heavy
// ads intervention (for an example, see the
// HeavyAdInterventionEnabled_ErrorPageLoaded test).
IN_PROC_BROWSER_TEST_F(NavigationRequestBrowserTest,
OriginForSrcdocErrorPageInSubframe) {
// Start on a page with a blank subframe.
GURL start_url =
embedded_test_server()->GetURL("a.test", "/page_with_blank_iframe.html");
EXPECT_TRUE(NavigateToURL(shell(), start_url));
// Do a srcdoc navigation in the subframe.
EXPECT_TRUE(
ExecJs(shell(), "document.querySelector('iframe').srcdoc='foo';"));
EXPECT_TRUE(WaitForLoadStop(shell()->web_contents()));
FrameTreeNode* root = static_cast<WebContentsImpl*>(shell()->web_contents())
->GetPrimaryFrameTree()
.root();
RenderFrameHostImpl* subframe_rfh = root->child_at(0)->current_frame_host();
EXPECT_EQ(GURL("about:srcdoc"), subframe_rfh->GetLastCommittedURL());
// Navigate the subframe to a post-commit error page, reusing its current
// srcdoc URL. A post-commit error page provides a way to reach an error
// page for a srcdoc subframe; note that it isn't possible to use
// NavigationThrottles to block srcdoc navigations, since throttles don't
// currently run in that case.
TestNavigationObserver navigation_observer(shell()->web_contents(), 1);
shell()->web_contents()->GetController().LoadPostCommitErrorPage(
subframe_rfh, subframe_rfh->GetLastCommittedURL(), "error_page_contents");
navigation_observer.Wait();
EXPECT_FALSE(navigation_observer.last_navigation_succeeded());
// Verify that the origin of the srcdoc frame's parent wasn't inherited and
// also wasn't used for the precursor. The error page's origin should be
// opaque without a valid precursor.
url::Origin origin =
root->child_at(0)->current_frame_host()->GetLastCommittedOrigin();
EXPECT_TRUE(origin.opaque());
EXPECT_FALSE(origin.GetTupleOrPrecursorTupleIfOpaque().IsValid());
}
// Verify that when navigation 1, which starts in an initial siteless
// SiteInstance and results in an error page, races with navigation 2, which
// requires a dedicated process and wants to reuse an existing process,
// navigation 2 does not incorrectly reuse navigation 1's process.
IN_PROC_BROWSER_TEST_F(NavigationRequestBrowserTest,
ErrorPageMarksProcessAsUsed) {
// The scenario in this test originally led to a site isolation bypass only
// when error page isolation for main frames is turned off. Do this via a
// custom ContentBrowserClient.
class NoErrorPageIsolationContentBrowserClient
: public ContentBrowserTestContentBrowserClient {
public:
bool ShouldIsolateErrorPage(bool in_main_frame) override { return false; }
} no_error_isolation_client;
// Set the process limit to 1. This will force main frame navigations to
// attempt to reuse existing processes.
RenderProcessHost::SetMaxRendererProcessCount(1);
// The test should start in a blank shell with a siteless SiteInstance.
EXPECT_FALSE(
static_cast<SiteInstanceImpl*>(shell()->web_contents()->GetSiteInstance())
->HasSite());
// Set up a foo.com URL which will fail to load.
GURL foo_url(embedded_test_server()->GetURL("foo.com", "/title1.html"));
std::unique_ptr<URLLoaderInterceptor> interceptor =
URLLoaderInterceptor::SetupRequestFailForURL(foo_url,
net::ERR_CONNECTION_REFUSED);
// Set up a throttle that will be used to wait for WillFailRequest() and then
// defer the navigation.
TestNavigationThrottleInstaller installer(
shell()->web_contents(),
NavigationThrottle::PROCEED /* will_start_result */,
NavigationThrottle::PROCEED /* will_redirect_result */,
NavigationThrottle::DEFER /* will_fail_result */,
NavigationThrottle::PROCEED /* will_process_result */,
NavigationThrottle::PROCEED /* will_commit_without_url_loader_result */);
// Start a navigation to foo.com that will result in an error.
shell()->web_contents()->GetController().LoadURL(
foo_url, Referrer(), ui::PAGE_TRANSITION_LINK, std::string());
// Wait for WillFailRequest(). After this point, we will have picked the
// final RenderFrameHost for the error page.
installer.WaitForThrottleWillFail();
// Create a new tab and navigate it to a different site. Ensure this site
// requires a dedicated process, even on Android.
GURL bar_url(embedded_test_server()->GetURL("bar.com", "/title1.html"));
auto* policy = ChildProcessSecurityPolicyImpl::GetInstance();
policy->AddFutureIsolatedOrigins(
{url::Origin::Create(bar_url)},
ChildProcessSecurityPolicy::IsolatedOriginSource::TEST);
Shell* new_shell = CreateBrowser();
EXPECT_TRUE(NavigateToURL(new_shell, bar_url));
// Resume the error page navigation. It should be able to finish without
// crashing.
installer.navigation_throttle()->ResumeNavigation();
EXPECT_FALSE(WaitForLoadStop(shell()->web_contents()));
EXPECT_TRUE(
shell()->web_contents()->GetPrimaryMainFrame()->IsErrorDocument());
// Ensure that bar.com didn't reuse the foo.com error page process.
EXPECT_NE(shell()->web_contents()->GetPrimaryMainFrame()->GetProcess(),
new_shell->web_contents()->GetPrimaryMainFrame()->GetProcess());
}
// Check that a renderer-initiated navigation from an error page to about:blank
// honors the initiator origin when selecting the SiteInstance and process for
// about:blank.
IN_PROC_BROWSER_TEST_F(NavigationRequestBrowserTest,
NavigateToAboutBlankFromErrorPage) {
GURL url(embedded_test_server()->GetURL("a.com", "/title1.html"));
std::unique_ptr<URLLoaderInterceptor> url_interceptor =
URLLoaderInterceptor::SetupRequestFailForURL(url, net::ERR_DNS_TIMED_OUT);
// Start off with navigation to a.com, which results in an error page.
WebContents* web_contents = shell()->web_contents();
{
TestNavigationObserver observer(web_contents);
ASSERT_FALSE(NavigateToURL(shell(), url));
EXPECT_FALSE(observer.last_navigation_succeeded());
if (SiteIsolationPolicy::IsErrorPageIsolationEnabled(true)) {
EXPECT_EQ(
GURL(kUnreachableWebDataURL),
web_contents->GetPrimaryMainFrame()->GetSiteInstance()->GetSiteURL());
}
}
// Now, do a renderer-initiated navigation to about:blank out of the error
// page. We don't expect error pages to normally do this, but this might
// still be possible via DevTools or automation.
GURL about_blank(url::kAboutBlankURL);
{
TestNavigationObserver observer(web_contents);
EXPECT_TRUE(ExecJs(web_contents, "location = 'about:blank';"));
observer.Wait();
EXPECT_TRUE(observer.last_navigation_succeeded());
EXPECT_EQ(about_blank, observer.last_navigation_url());
}
RenderFrameHostImpl* rfh =
static_cast<RenderFrameHostImpl*>(web_contents->GetPrimaryMainFrame());
EXPECT_NE(GURL(kUnreachableWebDataURL), rfh->GetSiteInstance()->GetSiteURL());
// Note that the error page's origin was opaque with a.com as the precursor.
// This becomes the initiator origin for the about:blank navigation, and it
// should end up as the final origin for the blank document. See
// https://crbug.com/585649.
EXPECT_TRUE(rfh->GetLastCommittedOrigin().opaque());
EXPECT_EQ(
"a.com",
rfh->GetLastCommittedOrigin().GetTupleOrPrecursorTupleIfOpaque().host());
// Because about:blank's origin is opaque with a.com as the precursor, its
// SiteInstance and process should also correspond to a.com, rather than be
// left unassigned/unused.
//
// This covers an interesting and rare corner case, where an about:blank
// navigation can't use the source SiteInstance, which would normally keep it
// in the initiator's process and SiteInstance. This is because the
// navigation originates from an error page process, which is incompatible
// with a non-error navigation to about:blank. In this case, a new
// SiteInstance and process will be created, and they should still reflect
// about:blank's committed origin, rather than end up in an unlocked process
// and an unassigned SiteInstance. See https://crbug.com/1426928.
EXPECT_FALSE(rfh->GetProcess()->IsUnused());
if (AreAllSitesIsolatedForTesting()) {
EXPECT_EQ("http://a.com/", rfh->GetSiteInstance()->GetSiteURL());
EXPECT_TRUE(rfh->GetProcess()->GetProcessLock().is_locked_to_site());
EXPECT_EQ("http://a.com/", rfh->GetProcess()->GetProcessLock().site_url());
} else {
EXPECT_TRUE(rfh->GetProcess()->GetProcessLock().allows_any_site());
}
}
using CSPEmbeddedEnforcementBrowserTest = NavigationRequestBrowserTest;
IN_PROC_BROWSER_TEST_F(CSPEmbeddedEnforcementBrowserTest,
CheckCSPEmbeddedEnforcement) {
// We need one initial navigation to set up everything.
EXPECT_TRUE(NavigateToURL(shell(), embedded_test_server()->GetURL(
"www.example.org", "/empty.html")));
struct TestCase {
const char* name;
const char* required_csp;
const char* frame_url;
const char* allow_csp_from;
const char* returned_csp;
bool expect_allow;
} cases[] = {
{
"No required csp",
"",
"www.not-example.org",
nullptr,
nullptr,
true,
},
{
"Required csp - Same origin",
"script-src 'none'",
"www.example.org",
nullptr,
nullptr,
false,
},
{
"Required csp - Cross origin",
"script-src 'none'",
"www.not-example.org",
nullptr,
nullptr,
false,
},
{
"Required csp - Cross origin with Allow-CSP-From",
"script-src 'none'",
"www.not-example.org",
"*",
nullptr,
true,
},
{
"Required csp - Cross origin with wrong Allow-CSP-From",
"script-src 'none'",
"www.not-example.org",
"www.another-example.org",
nullptr,
false,
},
{
"Required csp - Cross origin with non-subsuming CSPs",
"script-src 'none'",
"www.not-example.org",
nullptr,
"style-src 'none'",
false,
},
{
"Required csp - Cross origin with subsuming CSPs",
"script-src 'none'",
"www.not-example.org",
nullptr,
"script-src 'none'",
true,
},
{
"Required csp - Cross origin with wrong Allow-CSP-From but subsuming "
"CSPs",
"script-src 'none'",
"www.not-example.org",
"www.another-example.org",
"script-src 'none'",
true,
},
};
for (auto test : cases) {
SCOPED_TRACE(test.name);
std::string headers;
if (test.returned_csp) {
headers +=
base::StringPrintf("Content-Security-Policy: %s&", test.returned_csp);
}
if (test.allow_csp_from) {
headers += base::StringPrintf("Allow-CSP-From: %s&", test.allow_csp_from);
}
GURL frame_url = embedded_test_server()->GetURL(test.frame_url,
"/set-header?" + headers);
content::TestNavigationManager observer(shell()->web_contents(), frame_url);
EXPECT_TRUE(ExecJs(shell()->web_contents(),
JsReplace(R"(
const iframe = document.createElement("iframe");
iframe.src = $2;
if ($1)
iframe.csp = $1;
document.body.appendChild(iframe);
)",
test.required_csp, frame_url)));
ASSERT_TRUE(observer.WaitForNavigationFinished());
EXPECT_EQ(test.expect_allow, observer.was_successful());
}
}
class NavigationRequestFencedFrameBrowserTest
: public NavigationRequestBrowserTest {
public:
NavigationRequestFencedFrameBrowserTest() = default;
~NavigationRequestFencedFrameBrowserTest() override = default;
NavigationRequestFencedFrameBrowserTest(
const NavigationRequestFencedFrameBrowserTest&) = delete;
NavigationRequestFencedFrameBrowserTest& operator=(
const NavigationRequestFencedFrameBrowserTest&) = delete;
void SetUpOnMainThread() override {
https_server()->SetSSLConfig(net::EmbeddedTestServer::CERT_TEST_NAMES);
https_server()->ServeFilesFromSourceDirectory(GetTestDataFilePath());
net::test_server::RegisterDefaultHandlers(https_server());
ASSERT_TRUE(https_server()->Start());
NavigationRequestBrowserTest::SetUpOnMainThread();
}
content::test::FencedFrameTestHelper& fenced_frame_test_helper() {
return fenced_frame_helper_;
}
net::EmbeddedTestServer* https_server() { return &https_server_; }
private:
content::test::FencedFrameTestHelper fenced_frame_helper_;
net::EmbeddedTestServer https_server_{net::EmbeddedTestServer::TYPE_HTTPS};
};
IN_PROC_BROWSER_TEST_F(
NavigationRequestFencedFrameBrowserTest,
ShouldRespectOutermostFrameCOEPParentAndChildOnInsecureContent) {
// Navigate |untrustworthy_url| to test if a fenced frame sets the outermost
// main frame's COEP.
GURL untrustworthy_url =
embedded_test_server()->GetURL("a.test", "/title1.html");
EXPECT_TRUE(NavigateToURL(shell(), untrustworthy_url));
// Create a fenced frame on an insecure content and its document should have
// the COEP of the outermost main frame.
GURL fenced_frame_url = embedded_test_server()->GetURL(
"a.test",
"/set-header?"
"Supports-Loading-Mode: fenced-frame&"
"Cross-Origin-Embedder-Policy: require-corp");
content::RenderFrameHostImpl* fenced_frame_host =
static_cast<content::RenderFrameHostImpl*>(
fenced_frame_test_helper().CreateFencedFrame(
shell()->web_contents()->GetPrimaryMainFrame(),
fenced_frame_url));
ASSERT_TRUE(fenced_frame_host);
EXPECT_EQ(network::mojom::CrossOriginEmbedderPolicyValue::kNone,
fenced_frame_host->cross_origin_embedder_policy().value);
}
IN_PROC_BROWSER_TEST_F(
NavigationRequestFencedFrameBrowserTest,
RespectOutermostFrameCOEPParentOnInsecureContentAndChildOnSecureContent) {
// Navigate |untrustworthy_url| to test if a fenced frame sets the outermost
// main frame's COEP.
GURL untrustworthy_url =
embedded_test_server()->GetURL("a.test", "/title1.html");
EXPECT_TRUE(NavigateToURL(shell(), untrustworthy_url));
// Create a fenced frame on a secure content and its document should have the
// COEP of the outermost main frame.
GURL fenced_frame_url =
https_server()->GetURL("a.test",
"/set-header?"
"Supports-Loading-Mode: fenced-frame&"
"Cross-Origin-Embedder-Policy: require-corp");
content::RenderFrameHostImpl* fenced_frame_host =
static_cast<content::RenderFrameHostImpl*>(
fenced_frame_test_helper().CreateFencedFrame(
shell()->web_contents()->GetPrimaryMainFrame(),
fenced_frame_url));
ASSERT_TRUE(fenced_frame_host);
EXPECT_EQ(network::mojom::CrossOriginEmbedderPolicyValue::kNone,
fenced_frame_host->cross_origin_embedder_policy().value);
}
// Ensure that fenced frames don't enable the view source mode since navigations
// in fenced frames to view-sources URLs are blocked.
IN_PROC_BROWSER_TEST_F(NavigationRequestFencedFrameBrowserTest,
ViewSourceNavigation_FencedFrame) {
EXPECT_TRUE(
NavigateToURL(shell(), embedded_test_server()->GetURL("/title1.html")));
GURL fenced_frame_url =
embedded_test_server()->GetURL("/fenced_frames/title1.html");
RenderFrameHost* fenced_frame_host =
fenced_frame_test_helper().CreateFencedFrame(
shell()->web_contents()->GetPrimaryMainFrame(), fenced_frame_url);
EXPECT_NE(nullptr, fenced_frame_host);
GURL view_source_url(kViewSourceScheme + std::string(":") +
fenced_frame_url.spec());
WebContentsConsoleObserver console_observer(shell()->web_contents());
console_observer.SetPattern("Not allowed to load local resource: " +
view_source_url.spec());
// Attempt to navigate to a view source url in the fenced frame.
EXPECT_EQ(view_source_url.spec(),
EvalJs(fenced_frame_host,
JsReplace(R"({location.href = $1;})", view_source_url)));
ASSERT_TRUE(console_observer.Wait());
// Original page shouldn't navigate away.
EXPECT_EQ(fenced_frame_url, fenced_frame_host->GetLastCommittedURL());
EXPECT_FALSE(shell()
->web_contents()
->GetController()
.GetLastCommittedEntry()
->IsViewSourceMode());
}
class NavigationRequestPrerenderBrowserTest
: public NavigationRequestBrowserTest {
public:
NavigationRequestPrerenderBrowserTest() {
prerender_helper_ =
std::make_unique<test::PrerenderTestHelper>(base::BindRepeating(
&NavigationRequestPrerenderBrowserTest::web_contents,
base::Unretained(this)));
}
~NavigationRequestPrerenderBrowserTest() override = default;
NavigationRequestPrerenderBrowserTest(
const NavigationRequestPrerenderBrowserTest&) = delete;
NavigationRequestPrerenderBrowserTest& operator=(
const NavigationRequestPrerenderBrowserTest&) = delete;
void SetUpOnMainThread() override {
NavigationRequestBrowserTest::SetUpOnMainThread();
https_server_ = std::make_unique<net::EmbeddedTestServer>(
net::EmbeddedTestServer::TYPE_HTTPS);
https_server_->AddDefaultHandlers(GetTestDataFilePath());
https_server_->SetSSLConfig(net::EmbeddedTestServer::CERT_TEST_NAMES);
ASSERT_TRUE(https_server()->Start());
}
protected:
net::EmbeddedTestServer* https_server() { return https_server_.get(); }
test::PrerenderTestHelper& prerender_helper() { return *prerender_helper_; }
WebContents* web_contents() { return shell()->web_contents(); }
private:
std::unique_ptr<net::EmbeddedTestServer> https_server_;
std::unique_ptr<test::PrerenderTestHelper> prerender_helper_;
};
// Make sure if a main frame page served with a COOP header attempts to navigate
// itself to about:srcdoc that we handle it correctly.
IN_PROC_BROWSER_TEST_F(NavigationRequestBrowserTest,
CoopWithMainframeAboutSrcdocNavigation) {
std::unique_ptr<net::EmbeddedTestServer> https_server =
std::make_unique<net::EmbeddedTestServer>(
net::EmbeddedTestServer::TYPE_HTTPS);
https_server->AddDefaultHandlers(GetTestDataFilePath());
https_server->SetSSLConfig(net::EmbeddedTestServer::CERT_TEST_NAMES);
ASSERT_TRUE(https_server->Start());
GURL url(https_server->GetURL("a.test",
"/location_equals_about_srcdoc_script.html"));
// Navigate to a document that sets COOP and immediately navigates the
// mainframe to about:srcdoc.
TestNavigationObserver navigation_observer(shell()->web_contents());
// Since the redirect to about:srcdoc in the page's script is expected to
// fail, use EXPECT_FALSE here.
EXPECT_FALSE(NavigateToURL(shell(), url));
navigation_observer.Wait();
// Verify that the second navigation was attempted and failed.
EXPECT_FALSE(navigation_observer.last_navigation_succeeded());
EXPECT_EQ(net::ERR_INVALID_URL, navigation_observer.last_net_error_code());
EXPECT_EQ(GURL(url::kAboutSrcdocURL),
navigation_observer.last_navigation_url());
}
// Same as CoopWithMainframeAboutSrcdocNavigation above, except instead of a
// single, redirected navigation, we get two distinct navigations in this case.
IN_PROC_BROWSER_TEST_F(NavigationRequestBrowserTest,
CoopWithMainframeAboutSrcdocNavigation2) {
std::unique_ptr<net::EmbeddedTestServer> https_server =
std::make_unique<net::EmbeddedTestServer>(
net::EmbeddedTestServer::TYPE_HTTPS);
https_server->AddDefaultHandlers(GetTestDataFilePath());
https_server->SetSSLConfig(net::EmbeddedTestServer::CERT_TEST_NAMES);
ASSERT_TRUE(https_server->Start());
GURL url(https_server->GetURL("a.test",
"/set-header?"
"cross-origin-opener-policy: same-origin"));
// Navigate to a document that sets COOP.
EXPECT_TRUE(NavigateToURL(shell(), url));
content::RenderFrameHostImpl* main_frame =
static_cast<content::RenderFrameHostImpl*>(
shell()->web_contents()->GetPrimaryMainFrame());
EXPECT_EQ(network::mojom::CrossOriginOpenerPolicyValue::kSameOrigin,
main_frame->cross_origin_opener_policy().value);
// Navigate main frame to about:srcdoc.
TestNavigationObserver navigation_observer(shell()->web_contents());
EXPECT_TRUE(ExecJs(main_frame, "location = 'about:srcdoc';"));
navigation_observer.Wait();
// Verify that the second navigation was attempted and failed.
EXPECT_FALSE(navigation_observer.last_navigation_succeeded());
EXPECT_EQ(net::ERR_INVALID_URL, navigation_observer.last_net_error_code());
EXPECT_EQ(GURL(url::kAboutSrcdocURL),
navigation_observer.last_navigation_url());
}
IN_PROC_BROWSER_TEST_F(NavigationRequestPrerenderBrowserTest,
CoopCoepCheckWithPrerender) {
GURL url(
https_server()->GetURL("a.test",
"/set-header"
"?cross-origin-opener-policy: same-origin"
"&cross-origin-embedder-policy: require-corp"));
// Navigate to a document that sets COOP and COEP.
EXPECT_TRUE(NavigateToURL(shell(), url));
content::RenderFrameHostImpl* primary_main_frame =
static_cast<content::RenderFrameHostImpl*>(
shell()->web_contents()->GetPrimaryMainFrame());
EXPECT_EQ(network::mojom::CrossOriginOpenerPolicyValue::kSameOriginPlusCoep,
primary_main_frame->cross_origin_opener_policy().value);
EXPECT_EQ(network::mojom::CrossOriginEmbedderPolicyValue::kRequireCorp,
primary_main_frame->cross_origin_embedder_policy().value);
// Add a prerender.
FrameTreeNodeId host_id = prerender_helper().AddPrerender(
https_server()->GetURL("a.test", "/title1.html?prerendering"));
content::RenderFrameHostImpl* prerender_main_frame =
static_cast<content::RenderFrameHostImpl*>(
prerender_helper().GetPrerenderedMainFrameHost(host_id));
// The prerender rfh's polices are none.
EXPECT_EQ(network::mojom::CrossOriginEmbedderPolicyValue::kNone,
prerender_main_frame->cross_origin_embedder_policy().value);
EXPECT_EQ(network::mojom::CrossOriginOpenerPolicyValue::kUnsafeNone,
prerender_main_frame->cross_origin_opener_policy().value);
// Prerendering should not affect the primary rfh's polices.
EXPECT_EQ(network::mojom::CrossOriginOpenerPolicyValue::kSameOriginPlusCoep,
primary_main_frame->cross_origin_opener_policy().value);
EXPECT_EQ(network::mojom::CrossOriginEmbedderPolicyValue::kRequireCorp,
primary_main_frame->cross_origin_embedder_policy().value);
}
enum class TestMPArchType {
kPrerender,
kFencedFrame,
};
class NavigationRequestMPArchBrowserTest
: public NavigationRequestBrowserTest,
public testing::WithParamInterface<TestMPArchType> {
public:
NavigationRequestMPArchBrowserTest() {
switch (GetParam()) {
case TestMPArchType::kPrerender:
prerender_helper_ =
std::make_unique<test::PrerenderTestHelper>(base::BindRepeating(
&NavigationRequestMPArchBrowserTest::web_contents,
base::Unretained(this)));
break;
case TestMPArchType::kFencedFrame:
fenced_frame_helper_ =
std::make_unique<content::test::FencedFrameTestHelper>();
break;
}
}
~NavigationRequestMPArchBrowserTest() override = default;
NavigationRequestMPArchBrowserTest(
const NavigationRequestMPArchBrowserTest&) = delete;
NavigationRequestMPArchBrowserTest& operator=(
const NavigationRequestMPArchBrowserTest&) = delete;
protected:
test::PrerenderTestHelper& prerender_helper() { return *prerender_helper_; }
test::FencedFrameTestHelper& fenced_frame_test_helper() {
return *fenced_frame_helper_;
}
WebContents* web_contents() { return shell()->web_contents(); }
private:
base::test::ScopedFeatureList scoped_feature_list_;
std::unique_ptr<test::PrerenderTestHelper> prerender_helper_;
std::unique_ptr<test::FencedFrameTestHelper> fenced_frame_helper_;
};
INSTANTIATE_TEST_SUITE_P(All,
NavigationRequestMPArchBrowserTest,
::testing::Values(TestMPArchType::kPrerender,
TestMPArchType::kFencedFrame));
IN_PROC_BROWSER_TEST_P(NavigationRequestMPArchBrowserTest,
ShouldNotUpdateHistory) {
const auto get_observer = [&](WebContents* web_contents) {
return DidFinishNavigationObserver(
web_contents,
base::BindLambdaForTesting([](NavigationHandle* navigation_handle) {
DCHECK_EQ(navigation_handle->GetNavigatingFrameType(),
GetParam() == TestMPArchType::kPrerender
? FrameType::kPrerenderMainFrame
: GetParam() == TestMPArchType::kFencedFrame
? FrameType::kFencedFrameRoot
: FrameType::kPrimaryMainFrame);
EXPECT_FALSE(navigation_handle->ShouldUpdateHistory());
}));
};
{
DidFinishNavigationObserver observer(
web_contents(),
base::BindLambdaForTesting([](NavigationHandle* navigation_handle) {
DCHECK_EQ(navigation_handle->GetNavigatingFrameType(),
FrameType::kPrimaryMainFrame);
EXPECT_TRUE(navigation_handle->ShouldUpdateHistory());
}));
// Navigate the primary page.
EXPECT_TRUE(
NavigateToURL(shell(), embedded_test_server()->GetURL("/title1.html")));
}
{
switch (GetParam()) {
case TestMPArchType::kPrerender: {
const auto prerender_observer = get_observer(web_contents());
// Load a page in the prerender.
prerender_helper().AddPrerender(
embedded_test_server()->GetURL("/title1.html?prendering"));
break;
}
case TestMPArchType::kFencedFrame: {
const auto fenced_frame_observer = get_observer(web_contents());
// Create a fenced frame.
ASSERT_TRUE(fenced_frame_test_helper().CreateFencedFrame(
web_contents()->GetPrimaryMainFrame(),
embedded_test_server()->GetURL("/fenced_frames/title1.html")));
break;
}
}
}
}
// Tests that when trying to commit an error page for a failed navigation, but
// the renderer process of the error page crashed, the navigation won't commit
// and the browser won't crash.
// Regression test for https://crbug.com/1444360.
IN_PROC_BROWSER_TEST_F(NavigationRequestBrowserTest,
RendererCrashedBeforeCommitErrorPage) {
// Navigate to `url_a` first.
GURL url_a(embedded_test_server()->GetURL("a.com", "/title1.html"));
ASSERT_TRUE(NavigateToURL(shell(), url_a));
// Set up an URLLoaderInterceptor which will cause future navigations to fail.
auto url_loader_interceptor = std::make_unique<URLLoaderInterceptor>(
base::BindRepeating([](URLLoaderInterceptor::RequestParams* params) {
network::URLLoaderCompletionStatus status;
status.error_code = net::ERR_NOT_IMPLEMENTED;
params->client->OnComplete(status);
return true;
}));
// Do a navigation to `url_b1` that will fail and commit an error page. This
// is important so that the next error page navigation won't need to create a
// speculative RenderFrameHost (unless RenderDocument is enabled) and won't
// get cancelled earlier than commit time due to speculative RFH deletion.
GURL url_b1(embedded_test_server()->GetURL("b.com", "/title1.html"));
EXPECT_FALSE(NavigateToURL(shell(), url_b1));
EXPECT_EQ(shell()->web_contents()->GetLastCommittedURL(), url_b1);
EXPECT_TRUE(
shell()->web_contents()->GetPrimaryMainFrame()->IsErrorDocument());
// For the next navigation, set up a throttle that will be used to wait for
// WillFailRequest() and then defer the navigation, so that we can crash the
// error page process first.
TestNavigationThrottleInstaller installer(
shell()->web_contents(),
NavigationThrottle::PROCEED /* will_start_result */,
NavigationThrottle::PROCEED /* will_redirect_result */,
NavigationThrottle::DEFER /* will_fail_result */,
NavigationThrottle::PROCEED /* will_process_result */,
NavigationThrottle::PROCEED /* will_commit_without_url_loader_result */);
// Start a navigation to `url_b2` that will also fail, but before it commits
// an error page, cause the error page process to crash.
GURL url_b2(embedded_test_server()->GetURL("b.com", "/title2.html"));
TestNavigationManager manager(shell()->web_contents(), url_b2);
shell()->LoadURL(url_b2);
EXPECT_TRUE(manager.WaitForRequestStart());
// Resume the navigation and wait for WillFailRequest(). After this point, we
// will have picked the final RenderFrameHost & RenderProcessHost for the
// failed navigation.
manager.ResumeNavigation();
installer.WaitForThrottleWillFail();
// Ensure that response_should_be_rendered() is true even for error pages.
EXPECT_TRUE(static_cast<WebContentsImpl*>(shell()->web_contents())
->GetPrimaryMainFrame()
->frame_tree_node()
->navigation_request()
->response_should_be_rendered());
// Kill the error page process. This will cause the navigation to `url_b2` to
// return early in `NavigationRequest::ReadyToCommitNavigation()` and not
// commit a new error page.
RenderProcessHost* process_to_crash =
manager.GetNavigationHandle()->GetRenderFrameHost()->GetProcess();
ASSERT_TRUE(process_to_crash->IsInitializedAndNotDead());
RenderProcessHostWatcher crash_observer(
process_to_crash, RenderProcessHostWatcher::WATCH_FOR_PROCESS_EXIT);
process_to_crash->Shutdown(0);
crash_observer.Wait();
ASSERT_FALSE(process_to_crash->IsInitializedAndNotDead());
// Resume the navigation, which won't commit.
if (!ShouldCreateNewHostForAllFrames()) {
installer.navigation_throttle()->ResumeNavigation();
}
EXPECT_TRUE(manager.WaitForNavigationFinished());
EXPECT_FALSE(WaitForLoadStop(shell()->web_contents()));
// The tab stayed at `url_b1` as the `url_b2` navigation didn't commit.
EXPECT_EQ(shell()->web_contents()->GetLastCommittedURL(), url_b1);
}
namespace {
constexpr char kResponseBody[] = "response-body-contents";
// HTTP response template with adjustable header and body contents.
const char kResponseTemplate[] =
"HTTP/1.1 200 OK\r\n"
"%s"
"\r\n"
"%s";
// Test version of a NavigationThrottle that requests the response body.
class ResponseBodyNavigationThrottle : public NavigationThrottle {
public:
explicit ResponseBodyNavigationThrottle(NavigationHandle* handle)
: NavigationThrottle(handle) {}
ResponseBodyNavigationThrottle(const ResponseBodyNavigationThrottle&) =
delete;
ResponseBodyNavigationThrottle& operator=(
const ResponseBodyNavigationThrottle&) = delete;
~ResponseBodyNavigationThrottle() override = default;
NavigationThrottle::ThrottleCheckResult WillProcessResponse() override {
// It is safe to use base::Unretained as the NavigationThrottle will not be
// destroyed before the callback is called.
navigation_handle()->GetResponseBody(
base::BindOnce(&ResponseBodyNavigationThrottle::OnResponseBodyReady,
base::Unretained(this)));
return NavigationThrottle::DEFER;
}
const char* GetNameForLogging() override {
return "ResponseBodyNavigationThrottle";
}
bool was_callback_called() const { return was_callback_called_; }
const std::string& response_body() const { return response_body_; }
private:
void OnResponseBodyReady(const std::string& response_body) {
was_callback_called_ = true;
response_body_ = response_body;
Resume();
}
bool was_callback_called_ = false;
std::string response_body_;
};
} // namespace
class NavigationRequestResponseBodyBrowserTest
: public NavigationRequestBrowserTest {
protected:
void SetUpOnMainThread() override {
host_resolver()->AddRule("*", "127.0.0.1");
}
};
IN_PROC_BROWSER_TEST_F(NavigationRequestResponseBodyBrowserTest, Received) {
net::test_server::ControllableHttpResponse response(embedded_test_server(),
"/target.html");
ASSERT_TRUE(embedded_test_server()->Start());
ResponseBodyNavigationThrottle* client_throttle = nullptr;
// Set the client to register a ResponseBodyNavigationThrottle. Save a pointer
// to this throttle in `client_throttle` on registration.
content::ShellContentBrowserClient::Get()
->set_create_throttles_for_navigation_callback(base::BindLambdaForTesting(
[&client_throttle](
content::NavigationThrottleRegistry& registry) -> void {
auto throttle = std::make_unique<ResponseBodyNavigationThrottle>(
®istry.GetNavigationHandle());
client_throttle = throttle.get();
registry.AddThrottle(std::move(throttle));
}));
// Start navigating.
GURL simple_url(embedded_test_server()->GetURL("/target.html"));
TestNavigationManager manager(shell()->web_contents(), simple_url);
shell()->LoadURL(simple_url);
EXPECT_TRUE(manager.WaitForRequestStart());
manager.ResumeNavigation();
// Build the response with no headers and some body text.
response.WaitForRequest();
response.Send(base::StringPrintf(kResponseTemplate, "", kResponseBody));
response.Done();
ASSERT_TRUE(manager.WaitForResponse());
ASSERT_NE(nullptr, client_throttle);
EXPECT_TRUE(client_throttle->was_callback_called());
EXPECT_EQ(kResponseBody, client_throttle->response_body());
// Finish the navigation.
ASSERT_TRUE(manager.WaitForNavigationFinished());
}
IN_PROC_BROWSER_TEST_F(NavigationRequestResponseBodyBrowserTest,
ContentLengthZero) {
net::test_server::ControllableHttpResponse response(embedded_test_server(),
"/target.html");
ASSERT_TRUE(embedded_test_server()->Start());
ResponseBodyNavigationThrottle* client_throttle = nullptr;
// Set the client to register a ResponseBodyNavigationThrottle. Save a pointer
// to this throttle in `client_throttle` on registration.
content::ShellContentBrowserClient::Get()
->set_create_throttles_for_navigation_callback(base::BindLambdaForTesting(
[&client_throttle](
content::NavigationThrottleRegistry& registry) -> void {
auto throttle = std::make_unique<ResponseBodyNavigationThrottle>(
®istry.GetNavigationHandle());
client_throttle = throttle.get();
registry.AddThrottle(std::move(throttle));
}));
// Start navigating.
GURL simple_url(embedded_test_server()->GetURL("/target.html"));
TestNavigationManager manager(shell()->web_contents(), simple_url);
shell()->LoadURL(simple_url);
EXPECT_TRUE(manager.WaitForRequestStart());
manager.ResumeNavigation();
// Build the response with Content-Length: 0 and some body text.
response.WaitForRequest();
response.Send(base::StringPrintf(kResponseTemplate, "Content-Length: 0",
kResponseBody));
response.Done();
ASSERT_TRUE(manager.WaitForResponse());
ASSERT_NE(nullptr, client_throttle);
EXPECT_TRUE(client_throttle->was_callback_called());
// The received response body is empty due to the Content-Length value.
EXPECT_EQ(std::string(), client_throttle->response_body());
// Finish the navigation.
ASSERT_TRUE(manager.WaitForNavigationFinished());
}
IN_PROC_BROWSER_TEST_F(NavigationRequestResponseBodyBrowserTest,
BodyLargerThanDataPipeSize) {
ASSERT_TRUE(embedded_test_server()->Start());
ResponseBodyNavigationThrottle* client_throttle = nullptr;
// Set the client to register a ResponseBodyNavigationThrottle. Save a pointer
// to this throttle in `client_throttle` on registration.
content::ShellContentBrowserClient::Get()
->set_create_throttles_for_navigation_callback(base::BindLambdaForTesting(
[&client_throttle](
content::NavigationThrottleRegistry& registry) -> void {
auto throttle = std::make_unique<ResponseBodyNavigationThrottle>(
®istry.GetNavigationHandle());
client_throttle = throttle.get();
registry.AddThrottle(std::move(throttle));
}));
// Start navigating to a page with a large body (>5 million characters).
GURL simple_url(embedded_test_server()->GetURL("/long_response_body.html"));
TestNavigationManager manager(shell()->web_contents(), simple_url);
shell()->LoadURL(simple_url);
ASSERT_TRUE(manager.WaitForResponse());
ASSERT_NE(nullptr, client_throttle);
EXPECT_TRUE(client_throttle->was_callback_called());
// Ensure that the received response body contains text from the target page.
EXPECT_NE(client_throttle->response_body().npos,
client_throttle->response_body().find(
"Test page with a long response body"));
// The initial response body chunk may be smaller than the max data pipe size.
EXPECT_LE(client_throttle->response_body().length(),
network::GetDataPipeDefaultAllocationSize(
network::DataPipeAllocationSize::kLargerSizeIfPossible));
// Finish the navigation.
ASSERT_TRUE(manager.WaitForNavigationFinished());
}
// Helper class to turn off strict site isolation, to allow testing dynamic
// isolated origins added for future BrowsingInstances.
class NavigationRequestNoSiteIsolationBrowserTest
: public NavigationRequestBrowserTest {
public:
void SetUpCommandLine(base::CommandLine* command_line) override {
command_line->AppendSwitch(switches::kDisableSiteIsolation);
command_line->RemoveSwitch(switches::kSitePerProcess);
NavigationRequestBrowserTest::SetUpCommandLine(command_line);
}
};
// Test the early swap metrics logged when performing the early swap out of the
// initial RenderFrameHost. Currently, the vast majority of navigations are
// allowed to reuse the initial RFH. One exception is a navigation to a
// future-isolated origin, which forces a BrowsingInstance swap so that the
// isolation can take effect right away, so this is the case this test
// exercises.
IN_PROC_BROWSER_TEST_F(NavigationRequestNoSiteIsolationBrowserTest,
EarlySwapMetrics_InitialFrame) {
base::HistogramTester histograms;
EXPECT_FALSE(SiteIsolationPolicy::UseDedicatedProcessesForAllSites());
// Isolate bar.com in future BrowsingInstances.
GURL bar_url(embedded_test_server()->GetURL("bar.com", "/title1.html"));
auto* policy = ChildProcessSecurityPolicyImpl::GetInstance();
policy->AddFutureIsolatedOrigins(
{url::Origin::Create(bar_url)},
ChildProcessSecurityPolicy::IsolatedOriginSource::TEST);
// Navigate the initial frame to bar.com which requires isolation. Currently,
// the isolation heuristics force a BrowsingInstance and a RenderFrameHost
// swap, so the initial RFH cannot be reused for such a URL, and hence we
// should create a speculative RenderFrameHost and swap it in early because
// the initial frame is not live.
ASSERT_FALSE(
shell()->web_contents()->GetPrimaryMainFrame()->IsRenderFrameLive());
ASSERT_TRUE(NavigateToURL(shell(), bar_url));
histograms.ExpectUniqueSample(
"Navigation.EarlyRenderFrameHostSwapType",
NavigationRequest::EarlyRenderFrameHostSwapType::kInitialFrame, 1);
histograms.ExpectUniqueSample(
"Navigation.EarlyRenderFrameHostSwap.HasCommitted", 1, 1);
histograms.ExpectUniqueSample(
"Navigation.EarlyRenderFrameHostSwap.IsInOutermostMainFrame", 1, 1);
}
// Test that same-site cross-origin navigations keep user activation even when
// site isolation is disabled.
IN_PROC_BROWSER_TEST_F(NavigationRequestNoSiteIsolationBrowserTest,
UserActivationSameSite) {
GURL main_url(embedded_test_server()->GetURL(
"a.com", "/cross_site_iframe_factory.html?a(b)"));
EXPECT_TRUE(NavigateToURL(shell(), main_url));
// It is safe to obtain the root frame tree node here, as it doesn't change.
FrameTreeNode* root = static_cast<WebContentsImpl*>(shell()->web_contents())
->GetPrimaryFrameTree()
.root();
FrameTreeNode* child = root->child_at(0);
// Sanity check that there is no sticky user activation at first.
EXPECT_FALSE(child->current_frame_host()->HasStickyUserActivation());
EXPECT_EQ(false, EvalJs(child->current_frame_host(),
"navigator.userActivation.hasBeenActive",
EXECUTE_SCRIPT_NO_USER_GESTURE));
// Load cross-origin same-site page into iframe and verify there is still no
// sticky user activation.
GURL first_http_url(
embedded_test_server()->GetURL("subdomain.b.com", "/title1.html"));
EXPECT_TRUE(
NavigateToURLFromRendererWithoutUserGesture(child, first_http_url));
EXPECT_FALSE(child->current_frame_host()->HasStickyUserActivation());
EXPECT_EQ(false, EvalJs(child->current_frame_host(),
"navigator.userActivation.hasBeenActive",
EXECUTE_SCRIPT_NO_USER_GESTURE));
// Give the child iframe user activation.
EXPECT_TRUE(ExecJs(child, "// No-op script"));
EXPECT_TRUE(child->current_frame_host()->HasStickyUserActivation());
EXPECT_EQ(true, EvalJs(child->current_frame_host(),
"navigator.userActivation.hasBeenActive",
EXECUTE_SCRIPT_NO_USER_GESTURE));
// Perform another cross-origin same-site navigation in the iframe.
GURL second_http_url(embedded_test_server()->GetURL("b.com", "/title1.html"));
EXPECT_TRUE(
NavigateToURLFromRendererWithoutUserGesture(child, second_http_url));
// The cross-origin same-site navigation should keep the sticky user
// activation from the previous page.
EXPECT_TRUE(child->current_frame_host()->HasStickyUserActivation());
EXPECT_EQ(true, EvalJs(child->current_frame_host(),
"navigator.userActivation.hasBeenActive",
EXECUTE_SCRIPT_NO_USER_GESTURE));
// Ensure that top-level navigations can still happen.
EXPECT_TRUE(ExecJs(child->current_frame_host(),
JsReplace("window.open($1, $2)", first_http_url, "_top"),
EXECUTE_SCRIPT_NO_USER_GESTURE));
EXPECT_TRUE(WaitForLoadStop(shell()->web_contents()));
EXPECT_EQ(first_http_url, shell()->web_contents()->GetLastCommittedURL());
}
// Test that navigating the outermost main frame to a javascript: url does not
// preserve user activation state.
IN_PROC_BROWSER_TEST_F(NavigationRequestNoSiteIsolationBrowserTest,
UserActivationJavascriptUrlMainFrame) {
GURL main_url(embedded_test_server()->GetURL("a.com", "/title1.html"));
EXPECT_TRUE(NavigateToURL(shell(), main_url));
// It is safe to obtain the root frame tree node here, as it doesn't change.
FrameTreeNode* root = static_cast<WebContentsImpl*>(shell()->web_contents())
->GetPrimaryFrameTree()
.root();
// Sanity check that there is no sticky user activation at first.
EXPECT_FALSE(root->current_frame_host()->HasStickyUserActivation());
EXPECT_EQ(false, EvalJs(root->current_frame_host(),
"navigator.userActivation.hasBeenActive",
EXECUTE_SCRIPT_NO_USER_GESTURE));
// Give the root frame user activation.
EXPECT_TRUE(ExecJs(root, "// No-op script"));
EXPECT_TRUE(root->current_frame_host()->HasStickyUserActivation());
EXPECT_EQ(true, EvalJs(root->current_frame_host(),
"navigator.userActivation.hasBeenActive",
EXECUTE_SCRIPT_NO_USER_GESTURE));
// Perform a javascript URL navigation.
GURL javascript_url("javascript:'foo'");
EXPECT_TRUE(ExecJs(shell()->web_contents(),
JsReplace("location.href = $1", javascript_url),
EXECUTE_SCRIPT_NO_USER_GESTURE));
EXPECT_EQ("foo", EvalJs(shell()->web_contents(), "document.body.innerText",
EXECUTE_SCRIPT_NO_USER_GESTURE));
// The navigation to the javascript: URL should not keep the sticky user
// activation from the previous page.
// TODO(crbug.com/328296079) The browser and renderer's sticky activation
// state should not be out of sync. Update this test when fixing that bug to
// check that the browser-side clears sticky user activation.
EXPECT_TRUE(root->current_frame_host()->HasStickyUserActivation());
EXPECT_EQ(false, EvalJs(root->current_frame_host(),
"navigator.userActivation.hasBeenActive",
EXECUTE_SCRIPT_NO_USER_GESTURE));
}
// Test that navigating an iframe to a javascript: url preserves the user
// activation state.
IN_PROC_BROWSER_TEST_F(NavigationRequestNoSiteIsolationBrowserTest,
UserActivationJavascriptUrlChildFrame) {
GURL main_url(embedded_test_server()->GetURL(
"a.com", "/cross_site_iframe_factory.html?a(b)"));
EXPECT_TRUE(NavigateToURL(shell(), main_url));
// It is safe to obtain the root frame tree node here, as it doesn't change.
FrameTreeNode* root = static_cast<WebContentsImpl*>(shell()->web_contents())
->GetPrimaryFrameTree()
.root();
FrameTreeNode* child = root->child_at(0);
// Sanity check that there is no sticky user activation at first.
EXPECT_FALSE(child->current_frame_host()->HasStickyUserActivation());
EXPECT_EQ(false, EvalJs(child->current_frame_host(),
"navigator.userActivation.hasBeenActive",
EXECUTE_SCRIPT_NO_USER_GESTURE));
// Give the child iframe user activation.
EXPECT_TRUE(ExecJs(child, "// No-op script"));
EXPECT_TRUE(child->current_frame_host()->HasStickyUserActivation());
EXPECT_EQ(true, EvalJs(child->current_frame_host(),
"navigator.userActivation.hasBeenActive",
EXECUTE_SCRIPT_NO_USER_GESTURE));
// Perform a javascript URL navigation in the iframe.
GURL javascript_url("javascript:'foo'");
EXPECT_TRUE(ExecJs(child->current_frame_host(),
JsReplace("location.href = $1", javascript_url),
EXECUTE_SCRIPT_NO_USER_GESTURE));
EXPECT_EQ("foo",
EvalJs(child->current_frame_host(), "document.body.innerText",
EXECUTE_SCRIPT_NO_USER_GESTURE));
// The navigation to the javascript: URL should keep the sticky user
// activation from the previous page.
EXPECT_TRUE(child->current_frame_host()->HasStickyUserActivation());
EXPECT_EQ(true, EvalJs(child->current_frame_host(),
"navigator.userActivation.hasBeenActive",
EXECUTE_SCRIPT_NO_USER_GESTURE));
}
IN_PROC_BROWSER_TEST_F(NavigationRequestBrowserTest,
EarlySwapMetrics_CrashNoCommit) {
GURL url_a(embedded_test_server()->GetURL("a.test", "/title1.html"));
{
base::HistogramTester histograms;
// Ensure that a normal navigation doesn't log early swap metrics.
ASSERT_TRUE(NavigateToURL(shell(), url_a));
histograms.ExpectUniqueSample(
"Navigation.EarlyRenderFrameHostSwapType",
NavigationRequest::EarlyRenderFrameHostSwapType::kNone, 1);
histograms.ExpectTotalCount(
"Navigation.EarlyRenderFrameHostSwap.HasCommitted", 0);
histograms.ExpectTotalCount(
"Navigation.EarlyRenderFrameHostSwap.IsInOutermostMainFrame", 0);
}
// Crash the main frame.
RenderProcessHost* process =
shell()->web_contents()->GetPrimaryMainFrame()->GetProcess();
RenderProcessHostWatcher crash_observer(
process, RenderProcessHostWatcher::WATCH_FOR_PROCESS_EXIT);
process->Shutdown(0);
crash_observer.Wait();
ASSERT_FALSE(
shell()->web_contents()->GetPrimaryMainFrame()->IsRenderFrameLive());
{
base::HistogramTester histograms;
// Load a page that results in a 204 error. This should result in an early
// RFH swap that leaves the new RFH in a blank state. The HasCommitted
// early swap metric should be logged as false.
GURL url_204(embedded_test_server()->GetURL("a.test", "/nocontent"));
EXPECT_TRUE(NavigateToURLAndExpectNoCommit(shell(), url_204));
histograms.ExpectUniqueSample(
"Navigation.EarlyRenderFrameHostSwapType",
NavigationRequest::EarlyRenderFrameHostSwapType::kCrashedFrame, 1);
histograms.ExpectUniqueSample(
"Navigation.EarlyRenderFrameHostSwap.HasCommitted", 0, 1);
histograms.ExpectUniqueSample(
"Navigation.EarlyRenderFrameHostSwap.IsInOutermostMainFrame", 1, 1);
}
}
IN_PROC_BROWSER_TEST_F(NavigationRequestBrowserTest,
EarlySwapMetrics_CrashedSubframe) {
// Needed to guarantee that the subframe will be an OOPIF on Android.
IsolateAllSitesForTesting(base::CommandLine::ForCurrentProcess());
GURL url(embedded_test_server()->GetURL(
"a.com", "/cross_site_iframe_factory.html?a(b)"));
ASSERT_TRUE(NavigateToURL(shell(), url));
FrameTreeNode* root = static_cast<WebContentsImpl*>(shell()->web_contents())
->GetPrimaryFrameTree()
.root();
RenderFrameHostImpl* subframe_rfh = root->child_at(0)->current_frame_host();
// Crash the subframe.
RenderProcessHost* child_process = subframe_rfh->GetProcess();
RenderProcessHostWatcher crash_observer(
child_process, RenderProcessHostWatcher::WATCH_FOR_PROCESS_EXIT);
child_process->Shutdown(0);
crash_observer.Wait();
ASSERT_FALSE(subframe_rfh->IsRenderFrameLive());
{
base::HistogramTester histograms;
// Navigate the subframe, which should result in an early RFH swap.
GURL subframe_url(embedded_test_server()->GetURL("c.com", "/title1.html"));
TestNavigationObserver load_observer(shell()->web_contents());
EXPECT_TRUE(
ExecJs(shell(), JsReplace("frames[0].location = $1", subframe_url)));
load_observer.Wait();
histograms.ExpectUniqueSample(
"Navigation.EarlyRenderFrameHostSwapType",
NavigationRequest::EarlyRenderFrameHostSwapType::kCrashedFrame, 1);
histograms.ExpectUniqueSample(
"Navigation.EarlyRenderFrameHostSwap.HasCommitted", 1, 1);
histograms.ExpectUniqueSample(
"Navigation.EarlyRenderFrameHostSwap.IsInOutermostMainFrame", 0, 1);
}
}
IN_PROC_BROWSER_TEST_F(NavigationRequestBrowserTest,
EarlySwapMetrics_NoSwapForWebUI) {
base::HistogramTester histograms;
// Navigate the initial frame to a WebUI URL. The initial RFH should be reused
// for such a URL, and hence there should be no early swap recorded in the
// metrics.
ASSERT_FALSE(
shell()->web_contents()->GetPrimaryMainFrame()->IsRenderFrameLive());
GURL web_ui_url(GetWebUIURL("gpu"));
ASSERT_TRUE(NavigateToURL(shell(), web_ui_url));
histograms.ExpectUniqueSample(
"Navigation.EarlyRenderFrameHostSwapType",
NavigationRequest::EarlyRenderFrameHostSwapType::kNone, 1);
histograms.ExpectTotalCount(
"Navigation.EarlyRenderFrameHostSwap.HasCommitted", 0);
histograms.ExpectTotalCount(
"Navigation.EarlyRenderFrameHostSwap.IsInOutermostMainFrame", 0);
}
// Check the output of NavigationHandle::SandboxFlagsInitiator() when the
// navigation is initiated from the omnibox. It must be `kNone`.
IN_PROC_BROWSER_TEST_F(NavigationRequestBrowserTest,
InitiatorSandboxFlags_BrowserInitiated) {
GURL url_initiator = embedded_test_server()->GetURL(
"a.com", "/set-header?Content-Security-Policy: sandbox allow-scripts");
ASSERT_TRUE(NavigateToURL(shell(), url_initiator));
GURL url_target = embedded_test_server()->GetURL("a.com", "/");
TestNavigationManager manager(shell()->web_contents(), url_target);
shell()->LoadURL(url_target);
EXPECT_TRUE(manager.WaitForRequestStart());
ASSERT_TRUE(manager.GetNavigationHandle());
EXPECT_EQ(manager.GetNavigationHandle()->SandboxFlagsInitiator(),
network::mojom::WebSandboxFlags::kNone);
EXPECT_EQ(manager.GetNavigationHandle()->SandboxFlagsInherited(),
network::mojom::WebSandboxFlags::kNone);
}
// Check the output of NavigationHandle::SandboxFlagsInitiator() when the
// navigation is initiated by the top-level document. It must match.
IN_PROC_BROWSER_TEST_F(NavigationRequestBrowserTest,
InitiatorSandboxFlags_DocumentInitiated) {
GURL url_initiator = embedded_test_server()->GetURL(
"a.com", "/set-header?Content-Security-Policy: sandbox allow-scripts");
ASSERT_TRUE(NavigateToURL(shell(), url_initiator));
GURL url_target = embedded_test_server()->GetURL("a.com", "/");
TestNavigationManager manager(shell()->web_contents(), url_target);
EXPECT_TRUE(ExecJs(shell()->web_contents(),
JsReplace("location.href = $1", url_target)));
EXPECT_TRUE(manager.WaitForRequestStart());
ASSERT_TRUE(manager.GetNavigationHandle());
EXPECT_EQ(manager.GetNavigationHandle()->SandboxFlagsInitiator(),
network::mojom::WebSandboxFlags::kAll &
~network::mojom::WebSandboxFlags::kScripts &
~network::mojom::WebSandboxFlags::kAutomaticFeatures);
EXPECT_EQ(manager.GetNavigationHandle()->SandboxFlagsInherited(),
network::mojom::WebSandboxFlags::kNone);
}
// Check the output of NavigationHandle::SandboxFlagsInitiator() when the
// navigation is initiated by a sandboxed iframe.
IN_PROC_BROWSER_TEST_F(NavigationRequestBrowserTest,
InitiatorSandboxFlags_SandboxedIframe) {
// Create the parent document:
GURL parent_url = embedded_test_server()->GetURL("a.com", "/title1.html");
ASSERT_TRUE(NavigateToURL(shell(), parent_url));
// Create the child frame. It has sandbox flags from the
// Content-Security-Policy and from its iframe.sandbox flags:
GURL url_initiator = embedded_test_server()->GetURL(
"a.com",
"/set-header?Content-Security-Policy: sandbox allow-scripts allow-forms");
EXPECT_TRUE(ExecJs(shell()->web_contents(), JsReplace(R"(
const iframe = document.createElement("iframe");
iframe.src = $1;
iframe.sandbox = "allow-scripts allow-popups";
document.body.appendChild(iframe);
)",
url_initiator)));
EXPECT_TRUE(WaitForLoadStop(shell()->web_contents()));
RenderFrameHostImpl* main_frame = static_cast<RenderFrameHostImpl*>(
shell()->web_contents()->GetPrimaryMainFrame());
ASSERT_EQ(1u, main_frame->child_count());
// Navigate the child frame.
GURL url_target = embedded_test_server()->GetURL("a.com", "/");
TestNavigationManager manager(shell()->web_contents(), url_target);
EXPECT_TRUE(ExecJs(main_frame->child_at(0),
JsReplace("location.href = $1", url_target)));
EXPECT_TRUE(manager.WaitForRequestStart());
ASSERT_TRUE(manager.GetNavigationHandle());
EXPECT_EQ(manager.GetNavigationHandle()->SandboxFlagsInitiator(),
// `allow-script`:
network::mojom::WebSandboxFlags::kAll &
~network::mojom::WebSandboxFlags::kScripts &
~network::mojom::WebSandboxFlags::kAutomaticFeatures);
EXPECT_EQ(
manager.GetNavigationHandle()->SandboxFlagsInherited(),
//`allow-scripts allow-popups`:
network::mojom::WebSandboxFlags::kAll &
~network::mojom::WebSandboxFlags::kScripts &
~network::mojom::WebSandboxFlags::kPopups &
~network::mojom::WebSandboxFlags::kTopNavigationToCustomProtocols &
~network::mojom::WebSandboxFlags::kAutomaticFeatures);
}
// Tests the scenario when a navigation without URLLoader is cancelled and an
// error page is committed using the same NavigationRequest.
// See https://crbug.com/1487944.
IN_PROC_BROWSER_TEST_F(
NavigationRequestBrowserTest,
ThrottleDeferAndCancelCommitWithoutUrlLoaderWithErrorPage) {
GURL url(embedded_test_server()->GetURL("/title1.html"));
GURL about_blank_url(url::kAboutBlankURL);
// Perform a new-document navigation (setup).
EXPECT_TRUE(NavigateToURL(shell(), url));
// Navigate to about:blank so the NavigationRequest is expected to commit
// without URL loader.
{
TestNavigationObserver navigation_observer(shell()->web_contents(), 1);
NavigationHandleObserver observer(shell()->web_contents(), about_blank_url);
TestNavigationThrottleInstaller installer(
shell()->web_contents(), NavigationThrottle::DEFER,
NavigationThrottle::DEFER, NavigationThrottle::DEFER,
NavigationThrottle::DEFER, NavigationThrottle::DEFER);
shell()->LoadURL(about_blank_url);
// Wait for WillCommitWithoutUrlLoader.
installer.WaitForThrottleWillCommitWithoutUrlLoader();
EXPECT_EQ(0, installer.will_start_called());
EXPECT_EQ(0, installer.will_redirect_called());
EXPECT_EQ(0, installer.will_fail_called());
EXPECT_EQ(0, installer.will_process_called());
EXPECT_EQ(1, installer.will_commit_without_url_loader_called());
// Cancel the deferred navigation with `net::ERR_BLOCKED_BY_RESPONSE`, so
// the NavigationRequest will be used for an error page commit.
installer.navigation_throttle()->CancelNavigation(
{NavigationThrottle::CANCEL_AND_IGNORE, net::ERR_BLOCKED_BY_RESPONSE});
// Wait for the end of the navigation.
navigation_observer.Wait();
EXPECT_FALSE(observer.is_same_document());
EXPECT_TRUE(observer.has_committed());
EXPECT_FALSE(observer.was_redirected());
EXPECT_TRUE(observer.is_error());
EXPECT_TRUE(
shell()->web_contents()->GetPrimaryMainFrame()->IsErrorDocument());
}
}
// data: URLs should have opaque origins with nonce that is stable across a
// navigation, which is stored as the tentative origin to commit.
IN_PROC_BROWSER_TEST_F(NavigationRequestBrowserTest,
TentativeOriginToCommitIsStable_Data) {
// Start a navigation to a data URL with an opaque origin.
const std::string data = "<html><title>One</title><body>foo</body></html>";
const GURL data_url = GURL("data:text/html;charset=utf-8," + data);
TestNavigationManager navigation_manager(contents(), data_url);
shell()->LoadURL(data_url);
EXPECT_TRUE(navigation_manager.WaitForRequestStart());
// Get a copy of the computed origin at an early stage, both from the
// NavigationRequest and the UrlInfo, where the values are set and used.
NavigationRequest* data_request =
contents()->GetPrimaryFrameTree().root()->navigation_request();
std::optional<url::Origin> data_tentative_origin_to_commit =
data_request->GetTentativeOriginAtRequestTime();
EXPECT_TRUE(data_tentative_origin_to_commit.has_value());
std::optional<url::Origin> url_info_origin =
data_request->GetUrlInfo().origin;
EXPECT_TRUE(url_info_origin.has_value());
EXPECT_EQ(data_tentative_origin_to_commit, url_info_origin);
// Verify that the committed origin at the end matches the initial one.
EXPECT_TRUE(navigation_manager.WaitForNavigationFinished());
url::Origin data_committed_origin =
contents()->GetPrimaryMainFrame()->GetLastCommittedOrigin();
EXPECT_EQ(data_tentative_origin_to_commit.value(), data_committed_origin);
EXPECT_EQ(url_info_origin.value(), data_committed_origin);
}
} // namespace content
|