1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497 5498 5499 5500 5501 5502 5503 5504 5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551 5552 5553 5554 5555 5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584 5585 5586 5587 5588 5589 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607 5608 5609 5610 5611 5612 5613 5614 5615 5616 5617 5618 5619 5620 5621 5622 5623 5624 5625 5626 5627 5628 5629 5630 5631 5632 5633 5634 5635 5636 5637 5638 5639 5640 5641 5642 5643 5644 5645 5646 5647 5648 5649 5650 5651 5652 5653 5654 5655 5656 5657 5658 5659 5660 5661 5662 5663 5664 5665 5666 5667 5668 5669 5670 5671 5672 5673 5674 5675 5676 5677 5678 5679 5680 5681 5682 5683 5684 5685 5686 5687 5688 5689 5690 5691 5692 5693 5694 5695 5696 5697 5698 5699 5700 5701 5702 5703 5704 5705 5706 5707 5708 5709 5710 5711 5712 5713 5714 5715 5716 5717 5718 5719 5720 5721 5722 5723 5724 5725 5726 5727 5728 5729 5730 5731 5732 5733 5734 5735 5736 5737 5738 5739 5740 5741 5742 5743 5744 5745 5746 5747 5748 5749 5750 5751 5752 5753 5754 5755 5756 5757 5758 5759 5760 5761 5762 5763 5764 5765 5766 5767 5768 5769 5770 5771 5772 5773 5774 5775 5776 5777 5778 5779 5780 5781 5782 5783 5784 5785 5786 5787 5788 5789 5790 5791 5792 5793 5794 5795 5796 5797 5798 5799 5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815 5816 5817 5818 5819 5820 5821 5822 5823 5824 5825 5826 5827 5828 5829 5830 5831 5832 5833 5834 5835 5836 5837 5838 5839 5840 5841 5842 5843 5844 5845 5846 5847 5848 5849 5850 5851 5852 5853 5854 5855 5856 5857 5858 5859 5860 5861 5862 5863 5864 5865 5866 5867 5868 5869 5870 5871 5872 5873 5874 5875 5876 5877 5878 5879 5880 5881 5882 5883 5884 5885 5886 5887 5888 5889 5890 5891 5892 5893 5894 5895 5896 5897 5898 5899 5900 5901 5902 5903 5904 5905 5906 5907 5908 5909 5910 5911 5912 5913 5914 5915 5916 5917 5918 5919 5920 5921 5922 5923 5924 5925 5926 5927 5928 5929 5930 5931 5932 5933 5934 5935 5936 5937 5938 5939 5940 5941 5942 5943 5944 5945 5946 5947 5948 5949 5950 5951 5952 5953 5954 5955 5956 5957 5958 5959 5960 5961 5962 5963 5964 5965 5966 5967 5968 5969 5970 5971 5972 5973 5974 5975 5976 5977 5978 5979 5980 5981 5982 5983 5984 5985 5986 5987 5988 5989 5990 5991 5992 5993 5994 5995 5996 5997 5998 5999 6000 6001 6002 6003 6004 6005 6006 6007 6008 6009 6010 6011 6012 6013 6014 6015 6016 6017 6018 6019 6020 6021 6022 6023 6024 6025 6026 6027 6028 6029 6030 6031 6032 6033 6034 6035 6036 6037 6038 6039 6040 6041 6042 6043 6044 6045 6046 6047 6048 6049 6050 6051 6052 6053 6054 6055 6056 6057 6058 6059 6060 6061 6062 6063 6064 6065 6066 6067 6068 6069 6070 6071 6072 6073 6074 6075 6076 6077 6078 6079 6080 6081 6082 6083 6084 6085 6086 6087 6088 6089 6090 6091 6092 6093 6094 6095 6096 6097 6098 6099 6100 6101 6102 6103 6104 6105 6106 6107 6108 6109 6110 6111 6112 6113 6114 6115 6116 6117 6118 6119 6120 6121 6122 6123 6124 6125 6126 6127 6128 6129 6130 6131 6132 6133 6134 6135 6136 6137 6138 6139 6140 6141 6142 6143 6144 6145 6146 6147 6148 6149 6150 6151 6152 6153 6154 6155 6156 6157 6158 6159 6160 6161 6162 6163 6164 6165 6166 6167 6168 6169 6170 6171 6172 6173 6174 6175 6176 6177 6178 6179 6180 6181 6182 6183 6184 6185 6186 6187 6188 6189 6190 6191 6192 6193 6194 6195 6196 6197 6198 6199 6200 6201 6202 6203 6204 6205 6206 6207 6208 6209 6210 6211 6212 6213 6214 6215 6216 6217 6218 6219 6220 6221 6222 6223 6224 6225 6226 6227 6228 6229 6230 6231 6232 6233 6234 6235 6236 6237 6238 6239 6240 6241 6242 6243 6244 6245 6246 6247 6248 6249 6250 6251 6252 6253 6254 6255 6256 6257 6258 6259 6260 6261 6262 6263 6264 6265 6266 6267 6268 6269 6270 6271 6272 6273 6274 6275 6276 6277 6278 6279 6280 6281 6282 6283 6284 6285 6286 6287 6288 6289 6290 6291 6292 6293 6294 6295 6296 6297 6298 6299 6300 6301 6302 6303 6304 6305 6306 6307 6308 6309 6310 6311 6312 6313 6314 6315 6316 6317 6318 6319 6320 6321 6322 6323 6324 6325 6326 6327 6328 6329 6330 6331 6332 6333 6334 6335 6336 6337 6338 6339 6340 6341 6342 6343 6344 6345 6346 6347 6348 6349 6350 6351 6352 6353 6354 6355 6356 6357 6358 6359 6360 6361 6362 6363 6364 6365 6366 6367 6368 6369 6370 6371 6372 6373 6374 6375 6376 6377 6378 6379 6380 6381 6382 6383 6384 6385 6386 6387 6388 6389 6390 6391 6392 6393 6394 6395 6396 6397 6398 6399 6400 6401 6402 6403 6404 6405 6406 6407 6408 6409 6410 6411 6412 6413 6414 6415 6416 6417 6418 6419 6420 6421 6422 6423 6424 6425 6426 6427 6428 6429 6430 6431 6432 6433 6434 6435 6436 6437 6438 6439 6440 6441 6442 6443 6444 6445 6446 6447 6448 6449 6450 6451 6452 6453 6454 6455 6456 6457 6458 6459 6460 6461 6462 6463 6464 6465 6466 6467 6468 6469 6470 6471 6472 6473 6474 6475 6476 6477 6478 6479 6480 6481 6482 6483 6484 6485 6486 6487 6488 6489 6490 6491 6492 6493 6494 6495 6496 6497 6498 6499 6500 6501 6502 6503 6504 6505 6506 6507 6508 6509 6510 6511 6512 6513 6514 6515 6516 6517 6518 6519 6520 6521 6522 6523 6524 6525 6526 6527 6528 6529 6530 6531 6532 6533 6534 6535 6536 6537 6538 6539 6540 6541 6542 6543 6544 6545 6546 6547 6548 6549 6550 6551 6552 6553 6554 6555 6556 6557 6558 6559 6560 6561 6562 6563 6564 6565 6566 6567 6568 6569 6570 6571 6572 6573 6574 6575 6576 6577 6578 6579 6580 6581 6582 6583 6584 6585 6586 6587 6588 6589 6590 6591 6592 6593 6594 6595 6596 6597 6598 6599 6600 6601 6602 6603 6604 6605 6606 6607 6608 6609 6610 6611 6612 6613 6614 6615 6616 6617 6618 6619 6620 6621 6622 6623 6624 6625 6626 6627 6628 6629 6630 6631 6632 6633 6634 6635 6636 6637 6638 6639 6640 6641 6642 6643 6644 6645 6646 6647 6648 6649 6650 6651 6652 6653 6654 6655 6656 6657 6658 6659 6660 6661 6662 6663 6664 6665 6666 6667 6668 6669 6670 6671 6672 6673 6674 6675 6676 6677 6678 6679 6680 6681 6682 6683 6684 6685 6686 6687 6688 6689 6690 6691 6692 6693 6694 6695 6696 6697 6698 6699 6700 6701 6702 6703 6704 6705 6706 6707 6708 6709 6710 6711 6712 6713 6714 6715 6716 6717 6718 6719 6720 6721 6722 6723 6724 6725 6726 6727 6728 6729 6730 6731 6732 6733 6734 6735 6736 6737 6738 6739 6740 6741 6742 6743 6744 6745 6746 6747 6748 6749 6750 6751 6752 6753 6754 6755 6756 6757 6758 6759 6760 6761 6762 6763 6764 6765 6766 6767 6768 6769 6770 6771 6772 6773 6774 6775 6776 6777 6778 6779 6780 6781 6782 6783 6784 6785 6786 6787 6788 6789 6790 6791 6792 6793 6794 6795 6796 6797 6798 6799 6800 6801 6802 6803 6804 6805 6806 6807 6808 6809 6810 6811 6812 6813 6814 6815 6816 6817 6818 6819 6820 6821 6822 6823 6824 6825 6826 6827 6828 6829 6830 6831 6832 6833 6834 6835 6836 6837 6838 6839 6840 6841 6842 6843 6844 6845 6846 6847 6848 6849 6850 6851 6852 6853 6854 6855 6856 6857 6858 6859 6860 6861 6862 6863 6864 6865 6866 6867 6868 6869 6870 6871 6872 6873 6874 6875 6876 6877 6878 6879 6880 6881 6882 6883 6884 6885 6886 6887 6888 6889 6890 6891 6892 6893 6894 6895 6896 6897 6898 6899 6900 6901 6902 6903 6904 6905 6906 6907 6908 6909 6910 6911 6912 6913 6914 6915 6916 6917 6918 6919 6920 6921 6922 6923 6924 6925 6926 6927 6928 6929 6930 6931 6932 6933 6934 6935 6936 6937 6938 6939 6940 6941 6942 6943 6944 6945 6946 6947 6948 6949 6950 6951 6952 6953 6954 6955 6956 6957 6958 6959 6960 6961 6962 6963 6964 6965 6966 6967 6968 6969 6970 6971 6972 6973 6974 6975 6976 6977 6978 6979 6980 6981 6982 6983 6984 6985 6986 6987 6988 6989 6990 6991 6992 6993 6994 6995 6996 6997 6998 6999 7000 7001 7002 7003 7004 7005 7006 7007 7008 7009 7010 7011 7012 7013 7014 7015 7016 7017 7018 7019 7020 7021 7022 7023 7024 7025 7026 7027 7028 7029 7030 7031 7032 7033 7034 7035 7036 7037 7038 7039 7040 7041 7042 7043 7044 7045 7046 7047 7048 7049 7050 7051 7052 7053 7054 7055 7056 7057 7058 7059 7060 7061 7062 7063 7064 7065 7066 7067 7068 7069 7070 7071 7072 7073 7074 7075 7076 7077 7078 7079 7080 7081 7082 7083 7084 7085 7086 7087 7088 7089 7090 7091 7092 7093 7094 7095 7096 7097 7098 7099 7100 7101 7102 7103 7104 7105 7106 7107 7108 7109 7110 7111 7112 7113 7114 7115 7116 7117 7118 7119 7120 7121 7122 7123 7124 7125 7126 7127 7128 7129 7130 7131 7132 7133 7134 7135 7136 7137 7138 7139 7140 7141 7142 7143 7144 7145 7146 7147 7148 7149 7150 7151 7152 7153 7154 7155 7156 7157 7158 7159 7160 7161 7162 7163 7164 7165 7166 7167 7168 7169 7170 7171 7172 7173 7174 7175 7176 7177 7178 7179 7180 7181 7182 7183 7184 7185 7186 7187 7188 7189 7190 7191 7192 7193 7194 7195 7196 7197 7198 7199 7200 7201 7202 7203 7204 7205 7206 7207 7208 7209 7210 7211 7212 7213 7214 7215 7216 7217 7218 7219 7220 7221 7222 7223 7224 7225 7226 7227 7228 7229 7230 7231 7232 7233 7234 7235 7236 7237 7238 7239 7240 7241 7242 7243 7244 7245 7246 7247 7248 7249 7250 7251 7252 7253 7254 7255 7256 7257 7258 7259 7260 7261 7262 7263 7264 7265 7266 7267 7268 7269 7270 7271 7272 7273 7274 7275 7276 7277 7278 7279 7280 7281 7282 7283 7284 7285 7286 7287 7288 7289 7290 7291 7292 7293 7294 7295 7296 7297 7298 7299 7300 7301 7302 7303 7304 7305 7306 7307 7308 7309 7310 7311 7312 7313 7314 7315 7316 7317 7318 7319 7320 7321 7322 7323 7324 7325 7326 7327 7328 7329 7330 7331 7332 7333 7334 7335 7336 7337 7338 7339 7340 7341 7342 7343 7344 7345 7346 7347 7348 7349 7350 7351 7352 7353 7354 7355 7356 7357 7358 7359 7360 7361 7362 7363 7364 7365 7366 7367 7368 7369 7370 7371 7372 7373 7374 7375 7376 7377 7378 7379 7380 7381 7382 7383 7384 7385 7386 7387 7388 7389 7390 7391 7392 7393 7394 7395 7396 7397 7398 7399 7400 7401 7402 7403 7404 7405 7406 7407 7408 7409 7410 7411 7412 7413 7414 7415 7416 7417 7418 7419 7420 7421 7422 7423 7424 7425 7426 7427 7428 7429 7430 7431 7432 7433 7434 7435 7436 7437 7438 7439 7440 7441 7442 7443 7444 7445 7446 7447 7448 7449 7450 7451 7452 7453 7454 7455 7456 7457 7458 7459 7460 7461 7462 7463 7464 7465 7466 7467 7468 7469 7470 7471 7472 7473 7474 7475 7476 7477 7478 7479 7480 7481 7482 7483 7484 7485 7486 7487 7488 7489 7490 7491 7492 7493 7494 7495 7496 7497 7498 7499 7500 7501 7502 7503 7504 7505 7506 7507 7508 7509 7510 7511 7512 7513 7514 7515 7516 7517 7518 7519 7520 7521 7522 7523 7524 7525 7526 7527 7528 7529 7530 7531 7532 7533 7534 7535 7536 7537 7538 7539 7540 7541 7542 7543 7544 7545 7546 7547 7548 7549 7550 7551 7552 7553 7554 7555 7556 7557 7558 7559 7560 7561 7562 7563 7564 7565 7566 7567 7568 7569 7570 7571 7572 7573 7574 7575 7576 7577 7578 7579 7580 7581 7582 7583 7584 7585 7586 7587 7588 7589 7590 7591 7592 7593 7594 7595 7596 7597 7598 7599 7600 7601 7602 7603 7604 7605 7606 7607 7608 7609 7610 7611 7612 7613 7614 7615 7616 7617 7618 7619 7620 7621 7622 7623 7624 7625 7626 7627 7628 7629 7630 7631 7632 7633 7634 7635 7636 7637 7638 7639 7640 7641 7642 7643 7644 7645 7646 7647 7648 7649 7650 7651 7652 7653 7654 7655 7656 7657 7658 7659 7660 7661 7662 7663 7664 7665 7666 7667 7668 7669 7670 7671 7672 7673 7674 7675 7676 7677 7678 7679 7680 7681 7682 7683 7684 7685 7686 7687 7688 7689 7690 7691 7692 7693 7694 7695 7696 7697 7698 7699 7700 7701 7702 7703 7704 7705 7706 7707 7708 7709 7710 7711 7712 7713 7714 7715 7716 7717 7718 7719 7720 7721 7722 7723 7724 7725 7726 7727 7728 7729 7730 7731 7732 7733 7734 7735 7736 7737 7738 7739 7740 7741 7742 7743 7744 7745 7746 7747 7748 7749 7750 7751 7752 7753 7754 7755 7756 7757 7758 7759 7760 7761 7762 7763 7764 7765 7766 7767 7768 7769 7770 7771 7772 7773 7774 7775 7776 7777 7778 7779 7780 7781 7782 7783 7784 7785 7786 7787 7788 7789 7790 7791 7792 7793 7794 7795 7796 7797 7798 7799 7800 7801 7802 7803 7804 7805 7806 7807 7808 7809 7810 7811 7812 7813 7814 7815 7816 7817 7818 7819 7820 7821 7822 7823 7824 7825 7826 7827 7828 7829 7830 7831 7832 7833 7834 7835 7836 7837 7838 7839 7840 7841 7842 7843 7844 7845 7846 7847 7848 7849 7850 7851 7852 7853 7854 7855 7856 7857 7858 7859 7860 7861 7862 7863 7864 7865 7866 7867 7868 7869 7870 7871 7872 7873 7874 7875 7876 7877 7878 7879 7880 7881 7882 7883 7884 7885 7886 7887 7888 7889 7890 7891 7892 7893 7894 7895 7896 7897 7898 7899 7900 7901 7902 7903 7904 7905 7906 7907 7908 7909 7910 7911 7912 7913 7914 7915 7916 7917 7918 7919 7920 7921 7922 7923 7924 7925 7926 7927 7928 7929 7930 7931 7932 7933 7934 7935
|
// Copyright 2013 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <memory>
#include <set>
#include <string>
#include <string_view>
#include <utility>
#include <vector>
#include "base/command_line.h"
#include "base/containers/contains.h"
#include "base/feature_list.h"
#include "base/files/file_path.h"
#include "base/files/file_util.h"
#include "base/files/scoped_temp_dir.h"
#include "base/functional/bind.h"
#include "base/location.h"
#include "base/memory/raw_ptr.h"
#include "base/memory/scoped_refptr.h"
#include "base/process/process.h"
#include "base/run_loop.h"
#include "base/strings/strcat.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_util.h"
#include "base/strings/stringprintf.h"
#include "base/strings/utf_string_conversions.h"
#include "base/task/single_thread_task_runner.h"
#include "base/test/bind.h"
#include "base/test/run_until.h"
#include "base/test/scoped_feature_list.h"
#include "base/test/test_file_util.h"
#include "base/test/test_future.h"
#include "base/test/test_mock_time_task_runner.h"
#include "base/test/test_timeouts.h"
#include "base/threading/thread_restrictions.h"
#include "base/uuid.h"
#include "build/build_config.h"
#include "chrome/app/chrome_command_ids.h"
#include "chrome/browser/apps/platform_apps/app_browsertest_util.h"
#include "chrome/browser/bluetooth/web_bluetooth_test_utils.h"
#include "chrome/browser/chrome_content_browser_client.h"
#include "chrome/browser/devtools/devtools_window_testing.h"
#include "chrome/browser/hid/chrome_hid_delegate.h"
#include "chrome/browser/hid/hid_chooser_context.h"
#include "chrome/browser/hid/hid_chooser_context_factory.h"
#include "chrome/browser/interstitials/security_interstitial_page_test_utils.h"
#include "chrome/browser/lifetime/application_lifetime_desktop.h"
#include "chrome/browser/net/profile_network_context_service.h"
#include "chrome/browser/net/profile_network_context_service_factory.h"
#include "chrome/browser/preloading/prefetch/no_state_prefetch/no_state_prefetch_link_manager_factory.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/renderer_context_menu/render_view_context_menu.h"
#include "chrome/browser/renderer_context_menu/render_view_context_menu_test_util.h"
#include "chrome/browser/safe_browsing/test_safe_browsing_service.h"
#include "chrome/browser/serial/serial_chooser_context.h"
#include "chrome/browser/serial/serial_chooser_context_factory.h"
#include "chrome/browser/task_manager/task_manager_browsertest_util.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_commands.h"
#include "chrome/browser/ui/browser_dialogs.h"
#include "chrome/browser/ui/hid/hid_chooser_controller.h"
#include "chrome/browser/ui/login/login_handler.h"
#include "chrome/browser/ui/views/file_system_access/file_system_access_test_utils.h"
#include "chrome/browser/usb/usb_browser_test_utils.h"
#include "chrome/browser/usb/usb_chooser_context.h"
#include "chrome/browser/usb/usb_chooser_context_factory.h"
#include "chrome/common/chrome_features.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/pref_names.h"
#include "chrome/common/webui_url_constants.h"
#include "chrome/test/base/tracing.h"
#include "chrome/test/base/ui_test_utils.h"
#include "components/download/public/common/download_task_runner.h"
#include "components/find_in_page/find_tab_helper.h"
#include "components/guest_view/browser/guest_view_manager.h"
#include "components/guest_view/browser/guest_view_manager_delegate.h"
#include "components/guest_view/browser/guest_view_manager_factory.h"
#include "components/guest_view/browser/test_guest_view_manager.h"
#include "components/no_state_prefetch/browser/no_state_prefetch_link_manager.h"
#include "components/performance_manager/public/graph/frame_node.h"
#include "components/performance_manager/public/performance_manager.h"
#include "components/permissions/mock_chooser_controller_view.h"
#include "components/permissions/test/mock_permission_prompt_factory.h"
#include "components/prefs/pref_service.h"
#include "components/safe_browsing/core/browser/db/fake_database_manager.h"
#include "components/security_interstitials/content/security_interstitial_tab_helper.h"
#include "components/version_info/channel.h"
#include "components/version_info/version_info.h"
#include "components/web_modal/web_contents_modal_dialog_manager.h"
#include "content/public/browser/browser_task_traits.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/content_browser_client.h"
#include "content/public/browser/hid_chooser.h"
#include "content/public/browser/navigation_handle.h"
#include "content/public/browser/render_frame_host.h"
#include "content/public/browser/render_process_host.h"
#include "content/public/browser/render_process_host_creation_observer.h"
#include "content/public/browser/render_view_host.h"
#include "content/public/browser/render_widget_host.h"
#include "content/public/browser/render_widget_host_observer.h"
#include "content/public/browser/render_widget_host_view.h"
#include "content/public/browser/site_isolation_policy.h"
#include "content/public/browser/web_contents.h"
#include "content/public/browser/web_contents_delegate.h"
#include "content/public/common/content_client.h"
#include "content/public/common/content_features.h"
#include "content/public/common/content_switches.h"
#include "content/public/common/result_codes.h"
#include "content/public/common/url_constants.h"
#include "content/public/test/bluetooth_test_utils.h"
#include "content/public/test/browser_test.h"
#include "content/public/test/browser_test_utils.h"
#include "content/public/test/content_browser_test_content_browser_client.h"
#include "content/public/test/content_mock_cert_verifier.h"
#include "content/public/test/download_test_observer.h"
#include "content/public/test/fake_speech_recognition_manager.h"
#include "content/public/test/fenced_frame_test_util.h"
#include "content/public/test/find_test_utils.h"
#include "content/public/test/hit_test_region_observer.h"
#include "content/public/test/no_renderer_crashes_assertion.h"
#include "content/public/test/scoped_accessibility_mode_override.h"
#include "content/public/test/test_file_error_injector.h"
#include "content/public/test/test_frame_navigation_observer.h"
#include "content/public/test/test_navigation_observer.h"
#include "content/public/test/test_utils.h"
#include "content/public/test/url_loader_interceptor.h"
#include "extensions/browser/api/declarative/rules_cache_delegate.h"
#include "extensions/browser/api/declarative/rules_registry.h"
#include "extensions/browser/api/declarative/rules_registry_service.h"
#include "extensions/browser/api/declarative/test_rules_registry.h"
#include "extensions/browser/api/declarative_webrequest/webrequest_constants.h"
#include "extensions/browser/api/extensions_api_client.h"
#include "extensions/browser/app_window/native_app_window.h"
#include "extensions/browser/guest_view/web_view/web_view_guest.h"
#include "extensions/browser/guest_view/web_view/web_view_renderer_state.h"
#include "extensions/browser/process_map.h"
#include "extensions/common/extension.h"
#include "extensions/common/extension_features.h"
#include "extensions/common/extensions_client.h"
#include "extensions/common/features/feature_channel.h"
#include "extensions/common/mojom/context_type.mojom.h"
#include "extensions/test/extension_test_message_listener.h"
#include "media/base/media_switches.h"
#include "net/dns/mock_host_resolver.h"
#include "net/ssl/client_cert_identity_test_util.h"
#include "net/ssl/client_cert_store.h"
#include "net/test/embedded_test_server/embedded_test_server.h"
#include "net/test/embedded_test_server/http_request.h"
#include "net/test/embedded_test_server/http_response.h"
#include "net/test/test_data_directory.h"
#include "pdf/buildflags.h"
#include "ppapi/buildflags/buildflags.h"
#include "services/device/public/cpp/test/fake_hid_manager.h"
#include "services/device/public/cpp/test/fake_serial_port_manager.h"
#include "services/device/public/cpp/test/fake_usb_device_manager.h"
#include "services/device/public/cpp/test/scoped_geolocation_overrider.h"
#include "services/device/public/mojom/hid.mojom.h"
#include "services/device/public/mojom/serial.mojom.h"
#include "services/network/public/cpp/features.h"
#include "services/network/public/cpp/network_switches.h"
#include "third_party/blink/public/common/features.h"
#include "third_party/blink/public/common/input/web_mouse_event.h"
#include "third_party/blink/public/common/page/page_zoom.h"
#include "third_party/blink/public/common/switches.h"
#include "ui/accessibility/ax_mode.h"
#include "ui/accessibility/ax_updates_and_events.h"
#include "ui/display/display_switches.h"
#include "ui/events/gesture_detection/gesture_configuration.h"
#include "ui/gfx/geometry/point.h"
#include "ui/latency/latency_info.h"
#include "ui/shell_dialogs/select_file_dialog.h"
#include "url/url_constants.h"
#if BUILDFLAG(IS_CHROMEOS)
#include "ash/constants/ash_features.h"
#include "ash/webui/settings/public/constants/routes.mojom.h"
#include "chrome/browser/ash/system_web_apps/system_web_app_manager.h"
#endif
#if defined(USE_AURA)
#include "ui/aura/env.h"
#include "ui/aura/env_observer.h"
#include "ui/aura/window.h"
#endif
#if BUILDFLAG(ENABLE_PPAPI)
#include "content/public/test/ppapi_test_utils.h"
#endif
#if BUILDFLAG(ENABLE_PDF)
#include "base/test/with_feature_override.h"
#include "chrome/browser/pdf/pdf_extension_test_util.h"
#include "chrome/browser/pdf/test_pdf_viewer_stream_manager.h"
#include "pdf/pdf_features.h"
#endif // BUILDFLAG(ENABLE_PDF)
using extensions::ContextMenuMatcher;
using extensions::ExtensionsAPIClient;
using extensions::MenuItem;
using guest_view::GuestViewManager;
using guest_view::TestGuestViewManager;
using guest_view::TestGuestViewManagerFactory;
using prerender::NoStatePrefetchLinkManager;
using prerender::NoStatePrefetchLinkManagerFactory;
using task_manager::browsertest_util::MatchAboutBlankTab;
using task_manager::browsertest_util::MatchAnyApp;
using task_manager::browsertest_util::MatchAnyBackground;
using task_manager::browsertest_util::MatchAnyTab;
using task_manager::browsertest_util::MatchAnyWebView;
using task_manager::browsertest_util::MatchApp;
using task_manager::browsertest_util::MatchBackground;
using task_manager::browsertest_util::MatchWebView;
using task_manager::browsertest_util::WaitForTaskManagerRows;
using testing::Return;
using ui::MenuModel;
namespace {
const char kEmptyResponsePath[] = "/close-socket";
const char kRedirectResponsePath[] = "/server-redirect";
const char kUserAgentRedirectResponsePath[] = "/detect-user-agent";
const char kCacheResponsePath[] = "/cache-control-response";
const char kRedirectResponseFullPath[] =
"/extensions/platform_apps/web_view/shim/guest_redirect.html";
// Web Bluetooth
constexpr char kFakeBluetoothDeviceName[] = "Test Device";
constexpr char kDeviceAddress[] = "00:00:00:00:00:00";
constexpr char kHeartRateUUIDString[] = "0000180d-0000-1000-8000-00805f9b34fb";
class RenderWidgetHostVisibilityObserver
: public content::RenderWidgetHostObserver {
public:
RenderWidgetHostVisibilityObserver(content::RenderWidgetHost* host,
base::OnceClosure hidden_callback)
: hidden_callback_(std::move(hidden_callback)) {
observation_.Observe(host);
}
~RenderWidgetHostVisibilityObserver() override = default;
RenderWidgetHostVisibilityObserver(
const RenderWidgetHostVisibilityObserver&) = delete;
RenderWidgetHostVisibilityObserver& operator=(
const RenderWidgetHostVisibilityObserver&) = delete;
bool hidden_observed() const { return hidden_observed_; }
private:
// content::RenderWidgetHostObserver:
void RenderWidgetHostVisibilityChanged(content::RenderWidgetHost* host,
bool became_visible) override {
if (!became_visible) {
hidden_observed_ = true;
std::move(hidden_callback_).Run();
}
}
void RenderWidgetHostDestroyed(content::RenderWidgetHost* host) override {
EXPECT_TRUE(observation_.IsObservingSource(host));
observation_.Reset();
}
base::OnceClosure hidden_callback_;
base::ScopedObservation<content::RenderWidgetHost,
content::RenderWidgetHostObserver>
observation_{this};
bool hidden_observed_ = false;
};
// Watches for context menu to be shown, sets a boolean if it is shown.
class ContextMenuShownObserver {
public:
ContextMenuShownObserver() {
RenderViewContextMenu::RegisterMenuShownCallbackForTesting(base::BindOnce(
&ContextMenuShownObserver::OnMenuShown, base::Unretained(this)));
}
ContextMenuShownObserver(const ContextMenuShownObserver&) = delete;
ContextMenuShownObserver& operator=(const ContextMenuShownObserver&) = delete;
~ContextMenuShownObserver() = default;
void OnMenuShown(RenderViewContextMenu* context_menu) {
shown_ = true;
base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
FROM_HERE, base::BindOnce(&RenderViewContextMenuBase::Cancel,
base::Unretained(context_menu)));
base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
FROM_HERE, run_loop_.QuitClosure());
}
void Wait() { run_loop_.Run(); }
bool shown() { return shown_; }
private:
bool shown_ = false;
base::RunLoop run_loop_;
};
class EmbedderWebContentsObserver : public content::WebContentsObserver {
public:
explicit EmbedderWebContentsObserver(content::WebContents* web_contents)
: WebContentsObserver(web_contents) {}
EmbedderWebContentsObserver(const EmbedderWebContentsObserver&) = delete;
EmbedderWebContentsObserver& operator=(const EmbedderWebContentsObserver&) =
delete;
// WebContentsObserver.
void PrimaryMainFrameRenderProcessGone(
base::TerminationStatus status) override {
terminated_ = true;
run_loop_.Quit();
}
void WaitForEmbedderRenderProcessTerminate() {
if (terminated_)
return;
run_loop_.Run();
}
private:
bool terminated_ = false;
base::RunLoop run_loop_;
};
void ExecuteScriptWaitForTitle(content::WebContents* web_contents,
const char* script,
const char* title) {
std::u16string expected_title(base::ASCIIToUTF16(title));
std::u16string error_title(u"error");
content::TitleWatcher title_watcher(web_contents, expected_title);
title_watcher.AlsoWaitForTitle(error_title);
EXPECT_TRUE(content::ExecJs(web_contents, script));
EXPECT_EQ(expected_title, title_watcher.WaitAndGetTitle());
}
#if defined(USE_AURA)
// Waits for select control shown/closed.
class SelectControlWaiter : public aura::WindowObserver,
public aura::EnvObserver {
public:
SelectControlWaiter() { aura::Env::GetInstance()->AddObserver(this); }
SelectControlWaiter(const SelectControlWaiter&) = delete;
SelectControlWaiter& operator=(const SelectControlWaiter&) = delete;
~SelectControlWaiter() override {
aura::Env::GetInstance()->RemoveObserver(this);
for (aura::Window* window : observed_windows_) {
window->RemoveObserver(this);
}
}
void Wait(bool wait_for_widget_shown) {
wait_for_widget_shown_ = wait_for_widget_shown;
run_loop_ = std::make_unique<base::RunLoop>();
run_loop_->Run();
base::RunLoop().RunUntilIdle();
}
void OnWindowVisibilityChanged(aura::Window* window, bool visible) override {
if (wait_for_widget_shown_ && visible)
run_loop_->Quit();
}
void OnWindowInitialized(aura::Window* window) override {
if (window->GetType() != aura::client::WINDOW_TYPE_MENU)
return;
window->AddObserver(this);
observed_windows_.insert(window);
}
void OnWindowDestroyed(aura::Window* window) override {
observed_windows_.erase(window);
if (!wait_for_widget_shown_ && observed_windows_.empty())
run_loop_->Quit();
}
private:
std::unique_ptr<base::RunLoop> run_loop_;
std::set<raw_ptr<aura::Window, SetExperimental>> observed_windows_;
bool wait_for_widget_shown_ = false;
};
// Simulate real click with delay between mouse down and up.
class LeftMouseClick {
public:
explicit LeftMouseClick(content::RenderFrameHost* render_frame_host)
: render_frame_host_(render_frame_host),
mouse_event_(blink::WebInputEvent::Type::kMouseDown,
blink::WebInputEvent::kNoModifiers,
blink::WebInputEvent::GetStaticTimeStampForTests()) {
mouse_event_.button = blink::WebMouseEvent::Button::kLeft;
}
LeftMouseClick(const LeftMouseClick&) = delete;
LeftMouseClick& operator=(const LeftMouseClick&) = delete;
~LeftMouseClick() {
DCHECK(click_completed_);
}
void Click(const gfx::Point& point, int duration_ms) {
DCHECK(click_completed_);
click_completed_ = false;
mouse_event_.SetType(blink::WebInputEvent::Type::kMouseDown);
mouse_event_.SetPositionInWidget(point.x(), point.y());
const gfx::Rect offset =
render_frame_host_->GetRenderWidgetHost()->GetView()->GetViewBounds();
mouse_event_.SetPositionInScreen(point.x() + offset.x(),
point.y() + offset.y());
mouse_event_.click_count = 1;
render_frame_host_->GetRenderWidgetHost()->ForwardMouseEvent(mouse_event_);
base::SingleThreadTaskRunner::GetCurrentDefault()->PostDelayedTask(
FROM_HERE,
base::BindOnce(&LeftMouseClick::SendMouseUp, base::Unretained(this)),
base::Milliseconds(duration_ms));
}
// Wait for click completed.
void Wait() {
if (click_completed_)
return;
run_loop_ = std::make_unique<base::RunLoop>();
run_loop_->Run();
}
private:
void SendMouseUp() {
mouse_event_.SetType(blink::WebInputEvent::Type::kMouseUp);
render_frame_host_->GetRenderWidgetHost()->ForwardMouseEvent(mouse_event_);
click_completed_ = true;
if (run_loop_)
run_loop_->Quit();
}
// Unowned pointer.
raw_ptr<content::RenderFrameHost> render_frame_host_;
std::unique_ptr<base::RunLoop> run_loop_;
blink::WebMouseEvent mouse_event_;
bool click_completed_ = true;
};
#endif
} // namespace
// This class intercepts media access request from the embedder. The request
// should be triggered only if the embedder API (from tests) allows the request
// in Javascript.
// We do not issue the actual media request; the fact that the request reached
// embedder's WebContents is good enough for our tests. This is also to make
// the test run successfully on trybots.
class MockWebContentsDelegate : public content::WebContentsDelegate {
public:
MockWebContentsDelegate() = default;
MockWebContentsDelegate(const MockWebContentsDelegate&) = delete;
MockWebContentsDelegate& operator=(const MockWebContentsDelegate&) = delete;
~MockWebContentsDelegate() override = default;
void RequestMediaAccessPermission(
content::WebContents* web_contents,
const content::MediaStreamRequest& request,
content::MediaResponseCallback callback) override {
requested_ = true;
if (request_run_loop_)
request_run_loop_->Quit();
}
bool CheckMediaAccessPermission(content::RenderFrameHost* render_frame_host,
const url::Origin& security_origin,
blink::mojom::MediaStreamType type) override {
checked_ = true;
if (check_run_loop_)
check_run_loop_->Quit();
return true;
}
void WaitForRequestMediaPermission() {
if (requested_)
return;
request_run_loop_ = std::make_unique<base::RunLoop>();
request_run_loop_->Run();
}
void WaitForCheckMediaPermission() {
if (checked_)
return;
check_run_loop_ = std::make_unique<base::RunLoop>();
check_run_loop_->Run();
}
private:
bool requested_ = false;
bool checked_ = false;
std::unique_ptr<base::RunLoop> request_run_loop_;
std::unique_ptr<base::RunLoop> check_run_loop_;
};
// This class intercepts download request from the guest.
class MockDownloadWebContentsDelegate : public content::WebContentsDelegate {
public:
explicit MockDownloadWebContentsDelegate(
content::WebContentsDelegate* orig_delegate)
: orig_delegate_(orig_delegate) {}
MockDownloadWebContentsDelegate(const MockDownloadWebContentsDelegate&) =
delete;
MockDownloadWebContentsDelegate& operator=(
const MockDownloadWebContentsDelegate&) = delete;
~MockDownloadWebContentsDelegate() override = default;
void CanDownload(const GURL& url,
const std::string& request_method,
base::OnceCallback<void(bool)> callback) override {
orig_delegate_->CanDownload(
url, request_method,
base::BindOnce(&MockDownloadWebContentsDelegate::DownloadDecided,
base::Unretained(this), std::move(callback)));
}
void WaitForCanDownload(bool expect_allow) {
EXPECT_FALSE(waiting_for_decision_);
waiting_for_decision_ = true;
if (decision_made_) {
EXPECT_EQ(expect_allow, last_download_allowed_);
return;
}
expect_allow_ = expect_allow;
run_loop_ = std::make_unique<base::RunLoop>();
run_loop_->Run();
}
void DownloadDecided(base::OnceCallback<void(bool)> callback, bool allow) {
EXPECT_FALSE(decision_made_);
decision_made_ = true;
if (waiting_for_decision_) {
EXPECT_EQ(expect_allow_, allow);
if (run_loop_)
run_loop_->Quit();
std::move(callback).Run(allow);
return;
}
last_download_allowed_ = allow;
std::move(callback).Run(allow);
}
void Reset() {
waiting_for_decision_ = false;
decision_made_ = false;
}
private:
raw_ptr<content::WebContentsDelegate> orig_delegate_;
bool waiting_for_decision_ = false;
bool expect_allow_ = false;
bool decision_made_ = false;
bool last_download_allowed_ = false;
std::unique_ptr<base::RunLoop> run_loop_;
};
class WebViewTestBase : public extensions::PlatformAppBrowserTest {
protected:
void SetUp() override {
if (UsesFakeSpeech()) {
// SpeechRecognition test specific SetUp.
fake_speech_recognition_manager_ =
std::make_unique<content::FakeSpeechRecognitionManager>();
fake_speech_recognition_manager_->set_should_send_fake_response(true);
// Inject the fake manager factory so that the test result is returned to
// the web page.
content::SpeechRecognitionManager::SetManagerForTesting(
fake_speech_recognition_manager_.get());
}
extensions::PlatformAppBrowserTest::SetUp();
}
void TearDown() override {
if (UsesFakeSpeech()) {
// SpeechRecognition test specific TearDown.
content::SpeechRecognitionManager::SetManagerForTesting(nullptr);
}
extensions::PlatformAppBrowserTest::TearDown();
}
void SetUpOnMainThread() override {
extensions::PlatformAppBrowserTest::SetUpOnMainThread();
geolocation_overrider_ =
std::make_unique<device::ScopedGeolocationOverrider>(10, 20);
host_resolver()->AddRule("*", "127.0.0.1");
}
void SetUpCommandLine(base::CommandLine* command_line) override {
command_line->AppendSwitchASCII(blink::switches::kJavaScriptFlags,
"--expose-gc");
extensions::PlatformAppBrowserTest::SetUpCommandLine(command_line);
}
// Handles |request| by serving a redirect response if the |User-Agent| is
// foobar.
static std::unique_ptr<net::test_server::HttpResponse>
UserAgentResponseHandler(const std::string& path,
const GURL& redirect_target,
const net::test_server::HttpRequest& request) {
if (!base::StartsWith(path, request.relative_url,
base::CompareCase::SENSITIVE)) {
return nullptr;
}
auto it = request.headers.find("User-Agent");
EXPECT_TRUE(it != request.headers.end());
if (!base::StartsWith("foobar", it->second, base::CompareCase::SENSITIVE))
return nullptr;
std::unique_ptr<net::test_server::BasicHttpResponse> http_response(
new net::test_server::BasicHttpResponse);
http_response->set_code(net::HTTP_MOVED_PERMANENTLY);
http_response->AddCustomHeader("Location", redirect_target.spec());
return std::move(http_response);
}
// Handles |request| by serving a redirect response.
static std::unique_ptr<net::test_server::HttpResponse>
RedirectResponseHandler(const std::string& path,
const GURL& redirect_target,
const net::test_server::HttpRequest& request) {
if (!base::StartsWith(path, request.relative_url,
base::CompareCase::SENSITIVE)) {
return nullptr;
}
std::unique_ptr<net::test_server::BasicHttpResponse> http_response(
new net::test_server::BasicHttpResponse);
http_response->set_code(net::HTTP_MOVED_PERMANENTLY);
http_response->AddCustomHeader("Location", redirect_target.spec());
return std::move(http_response);
}
// Handles |request| by serving an empty response.
static std::unique_ptr<net::test_server::HttpResponse> EmptyResponseHandler(
const std::string& path,
const net::test_server::HttpRequest& request) {
if (base::StartsWith(path, request.relative_url,
base::CompareCase::SENSITIVE))
return std::unique_ptr<net::test_server::HttpResponse>(
new net::test_server::RawHttpResponse("", ""));
return nullptr;
}
// Handles |request| by serving cache-able response.
static std::unique_ptr<net::test_server::HttpResponse>
CacheControlResponseHandler(const std::string& path,
const net::test_server::HttpRequest& request) {
if (!base::StartsWith(path, request.relative_url,
base::CompareCase::SENSITIVE)) {
return nullptr;
}
std::unique_ptr<net::test_server::BasicHttpResponse> http_response(
new net::test_server::BasicHttpResponse);
http_response->AddCustomHeader("Cache-control", "max-age=3600");
http_response->set_content_type("text/plain");
http_response->set_content("dummy text");
return std::move(http_response);
}
// Shortcut to return the current MenuManager.
extensions::MenuManager* menu_manager() {
return extensions::MenuManager::Get(browser()->profile());
}
// This gets all the items that any extension has registered for possible
// inclusion in context menus.
MenuItem::List GetItems() {
MenuItem::List result;
std::set<MenuItem::ExtensionKey> extension_ids =
menu_manager()->ExtensionIds();
std::set<MenuItem::ExtensionKey>::iterator i;
for (i = extension_ids.begin(); i != extension_ids.end(); ++i) {
const MenuItem::OwnedList* list = menu_manager()->MenuItems(*i);
for (const auto& item : *list)
result.push_back(item.get());
}
return result;
}
enum TestServer {
NEEDS_TEST_SERVER,
NO_TEST_SERVER
};
void TestHelper(const std::string& test_name,
const std::string& app_location,
TestServer test_server) {
// For serving guest pages.
if (test_server == NEEDS_TEST_SERVER) {
if (!InitializeEmbeddedTestServer()) {
LOG(ERROR) << "FAILED TO START TEST SERVER.";
return;
}
embedded_test_server()->RegisterRequestHandler(base::BindRepeating(
&WebViewTestBase::RedirectResponseHandler, kRedirectResponsePath,
embedded_test_server()->GetURL(kRedirectResponseFullPath)));
embedded_test_server()->RegisterRequestHandler(base::BindRepeating(
&WebViewTestBase::EmptyResponseHandler, kEmptyResponsePath));
embedded_test_server()->RegisterRequestHandler(base::BindRepeating(
&WebViewTestBase::UserAgentResponseHandler,
kUserAgentRedirectResponsePath,
embedded_test_server()->GetURL(kRedirectResponseFullPath)));
embedded_test_server()->RegisterRequestHandler(base::BindRepeating(
&WebViewTestBase::CacheControlResponseHandler, kCacheResponsePath));
EmbeddedTestServerAcceptConnections();
}
LoadAndLaunchPlatformApp(app_location.c_str(), "Launched");
// Flush any pending events to make sure we start with a clean slate.
content::RunAllPendingInMessageLoop();
content::WebContents* embedder_web_contents =
GetFirstAppWindowWebContents();
if (!embedder_web_contents) {
LOG(ERROR) << "UNABLE TO FIND EMBEDDER WEB CONTENTS.";
return;
}
ExtensionTestMessageListener done_listener("TEST_PASSED");
done_listener.set_failure_message("TEST_FAILED");
// Note that domAutomationController may not exist for some tests so we
// must use the ExecuteScriptAsync.
content::ExecuteScriptAsync(
embedder_web_contents,
base::StrCat({"try { runTest('", test_name,
"'); } catch (e) { "
" console.log('UNABLE TO START TEST.'); "
" console.log(e); "
" chrome.test.sendMessage('TEST_FAILED'); "
"}"}));
ASSERT_TRUE(done_listener.WaitUntilSatisfied());
}
// Runs media_access/allow tests.
void MediaAccessAPIAllowTestHelper(const std::string& test_name);
// Runs media_access/deny tests, each of them are run separately otherwise
// they timeout (mostly on Windows).
void MediaAccessAPIDenyTestHelper(const std::string& test_name) {
ASSERT_TRUE(StartEmbeddedTestServer()); // For serving guest pages.
LoadAndLaunchPlatformApp("web_view/media_access/deny", "loaded");
content::WebContents* embedder_web_contents =
GetFirstAppWindowWebContents();
ASSERT_TRUE(embedder_web_contents);
ExtensionTestMessageListener test_run_listener("PASSED");
test_run_listener.set_failure_message("FAILED");
EXPECT_TRUE(
content::ExecJs(embedder_web_contents,
base::StrCat({"startDenyTest('", test_name, "')"})));
ASSERT_TRUE(test_run_listener.WaitUntilSatisfied());
}
// Loads an app with a <webview> in it, returns once a guest is created.
void LoadAppWithGuest(const std::string& app_path) {
ExtensionTestMessageListener launched_listener("WebViewTest.LAUNCHED");
launched_listener.set_failure_message("WebViewTest.FAILURE");
LoadAndLaunchPlatformApp(app_path.c_str(), &launched_listener);
guest_view_ = GetGuestViewManager()->WaitForSingleGuestViewCreated();
}
void SendMessageToEmbedder(const std::string& message) {
EXPECT_TRUE(
content::ExecJs(GetEmbedderWebContents(),
base::StrCat({"onAppCommand('", message, "');"})));
}
void SendMessageToEmbedderAsync(const std::string& message) {
content::ExecuteScriptAsync(
GetEmbedderWebContents(),
base::StrCat({"onAppCommand('", message, "');"}));
}
void SendMessageToGuestAndWait(const std::string& message,
const std::string& wait_message) {
std::unique_ptr<ExtensionTestMessageListener> listener;
if (!wait_message.empty()) {
listener = std::make_unique<ExtensionTestMessageListener>(wait_message);
}
EXPECT_TRUE(content::ExecJs(
GetGuestViewManager()->WaitForSingleGuestRenderFrameHostCreated(),
base::StrCat({"onAppCommand('", message, "');"})));
if (listener) {
ASSERT_TRUE(listener->WaitUntilSatisfied());
}
}
// Opens the context menu by simulating a mouse right-click at (1,1) relative
// to the guest's |RenderWidgethostView|. The mouse event is forwarded
// directly to the guest RWHV.
void OpenContextMenu(content::RenderFrameHost* guest_main_frame) {
ASSERT_TRUE(guest_main_frame);
blink::WebMouseEvent mouse_event(
blink::WebInputEvent::Type::kMouseDown,
blink::WebInputEvent::kNoModifiers,
blink::WebInputEvent::GetStaticTimeStampForTests());
mouse_event.button = blink::WebMouseEvent::Button::kRight;
// (1, 1) is chosen to make sure we click inside the guest.
mouse_event.SetPositionInWidget(1, 1);
auto* guest_rwh = guest_main_frame->GetRenderWidgetHost();
guest_rwh->ForwardMouseEvent(mouse_event);
mouse_event.SetType(blink::WebInputEvent::Type::kMouseUp);
guest_rwh->ForwardMouseEvent(mouse_event);
}
guest_view::GuestViewBase* GetGuestView() { return guest_view_; }
content::WebContents* GetGuestWebContents() {
return guest_view_->web_contents();
}
content::RenderFrameHost* GetGuestRenderFrameHost() {
return guest_view_->GetGuestMainFrame();
}
content::WebContents* GetEmbedderWebContents() {
if (!embedder_web_contents_) {
embedder_web_contents_ = GetFirstAppWindowWebContents();
}
return embedder_web_contents_;
}
TestGuestViewManager* GetGuestViewManager() {
return factory_.GetOrCreateTestGuestViewManager(
browser()->profile(),
ExtensionsAPIClient::Get()->CreateGuestViewManagerDelegate());
}
WebViewTestBase() = default;
~WebViewTestBase() override = default;
private:
bool UsesFakeSpeech() {
const testing::TestInfo* const test_info =
testing::UnitTest::GetInstance()->current_test_info();
// SpeechRecognition test specific SetUp.
constexpr std::string_view name = "SpeechRecognitionAPI_HasPermissionAllow";
return std::string_view(test_info->name()).starts_with(name);
}
std::unique_ptr<device::ScopedGeolocationOverrider> geolocation_overrider_;
std::unique_ptr<content::FakeSpeechRecognitionManager>
fake_speech_recognition_manager_;
TestGuestViewManagerFactory factory_;
// Note that these are only set if you launch app using LoadAppWithGuest().
raw_ptr<guest_view::GuestViewBase, AcrossTasksDanglingUntriaged> guest_view_ =
nullptr;
raw_ptr<content::WebContents, AcrossTasksDanglingUntriaged>
embedder_web_contents_ = nullptr;
};
// Used to disable tests running under the MPArch GuestView implementation.
// TODO(crbug.com/40202416): Usage of this will be removed as the implementation
// progresses.
#define SKIP_FOR_MPARCH() \
if (base::FeatureList::IsEnabled(features::kGuestViewMPArch)) { \
GTEST_SKIP() \
<< "MPArch implementation skipped. https://crbug.com/40202416"; \
} \
static_assert(true) /* semicolon here */
class WebViewTest : public WebViewTestBase,
public testing::WithParamInterface<bool> {
public:
WebViewTest() {
scoped_feature_list_.InitWithFeatureState(features::kGuestViewMPArch,
GetParam());
}
static std::string DescribeParams(
const testing::TestParamInfo<ParamType>& info) {
return info.param ? "MPArch" : "InnerWebContents";
}
private:
base::test::ScopedFeatureList scoped_feature_list_;
};
INSTANTIATE_TEST_SUITE_P(/* no prefix */,
WebViewTest,
testing::Bool(),
WebViewTest::DescribeParams);
// The following test suites are created to group tests based on specific
// features of <webview>.
using WebViewSizeTest = WebViewTest;
using WebViewVisibilityTest = WebViewTest;
using WebViewSpeechAPITest = WebViewTest;
using WebViewAccessibilityTest = WebViewTest;
using WebViewNewWindowTest = WebViewTest;
INSTANTIATE_TEST_SUITE_P(/* no prefix */,
WebViewSizeTest,
testing::Bool(),
WebViewSizeTest::DescribeParams);
INSTANTIATE_TEST_SUITE_P(/* no prefix */,
WebViewVisibilityTest,
testing::Bool(),
WebViewVisibilityTest::DescribeParams);
INSTANTIATE_TEST_SUITE_P(/* no prefix */,
WebViewSpeechAPITest,
testing::Bool(),
WebViewSpeechAPITest::DescribeParams);
INSTANTIATE_TEST_SUITE_P(/* no prefix */,
WebViewAccessibilityTest,
testing::Bool(),
WebViewAccessibilityTest::DescribeParams);
INSTANTIATE_TEST_SUITE_P(/* no prefix */,
WebViewNewWindowTest,
testing::Bool(),
WebViewNewWindowTest::DescribeParams);
class WebViewDPITest : public WebViewTest {
protected:
void SetUpCommandLine(base::CommandLine* command_line) override {
WebViewTest::SetUpCommandLine(command_line);
command_line->AppendSwitchASCII(switches::kForceDeviceScaleFactor,
base::NumberToString(scale()));
}
static float scale() { return 2.0f; }
};
INSTANTIATE_TEST_SUITE_P(/* no prefix */,
WebViewDPITest,
testing::Bool(),
WebViewDPITest::DescribeParams);
IN_PROC_BROWSER_TEST_P(WebViewTest, Basic) {
ASSERT_TRUE(StartEmbeddedTestServer());
LoadAppWithGuest("web_view/simple");
}
class WebContentsAudioMutedObserver : public content::WebContentsObserver {
public:
explicit WebContentsAudioMutedObserver(content::WebContents* web_contents)
: WebContentsObserver(web_contents) {}
WebContentsAudioMutedObserver(const WebContentsAudioMutedObserver&) = delete;
WebContentsAudioMutedObserver& operator=(
const WebContentsAudioMutedObserver&) = delete;
// WebContentsObserver.
void DidUpdateAudioMutingState(bool muted) override {
muting_update_observed_ = true;
run_loop_.Quit();
}
void WaitForUpdate() { run_loop_.Run(); }
bool muting_update_observed() { return muting_update_observed_; }
private:
base::RunLoop run_loop_;
bool muting_update_observed_ = false;
};
class IsAudibleObserver : public content::WebContentsObserver {
public:
explicit IsAudibleObserver(content::WebContents* contents)
: WebContentsObserver(contents) {}
IsAudibleObserver(const IsAudibleObserver&) = delete;
IsAudibleObserver& operator=(const IsAudibleObserver&) = delete;
~IsAudibleObserver() override = default;
void WaitForCurrentlyAudible(bool audible) {
// If there's no state change to observe then return right away.
if (web_contents()->IsCurrentlyAudible() == audible)
return;
run_loop_ = std::make_unique<base::RunLoop>();
run_loop_->Run();
EXPECT_EQ(audible, web_contents()->IsCurrentlyAudible());
EXPECT_EQ(audible, audible_);
}
private:
void OnAudioStateChanged(bool audible) override {
audible_ = audible;
run_loop_->Quit();
}
bool audible_ = false;
std::unique_ptr<base::RunLoop> run_loop_;
};
IN_PROC_BROWSER_TEST_P(WebViewTest, AudibilityStatePropagates) {
ASSERT_TRUE(StartEmbeddedTestServer()); // For serving guest audio.
LoadAppWithGuest("web_view/simple");
content::WebContents* embedder = GetEmbedderWebContents();
content::WebContents* guest_contents = GetGuestWebContents();
IsAudibleObserver embedder_obs(embedder);
EXPECT_FALSE(embedder->IsCurrentlyAudible());
EXPECT_FALSE(guest_contents->IsCurrentlyAudible());
// Just in case we get console error messages from the guest, we should
// surface them in the test output.
EXPECT_TRUE(
content::ExecJs(embedder,
"wv = document.getElementsByTagName('webview')[0];"
"wv.addEventListener('consolemessage', function (e) {"
" console.log('WebViewTest Guest: ' + e.message);"
"});"));
// Inject JS to start audio.
GURL audio_url = embedded_test_server()->GetURL(
"/extensions/platform_apps/web_view/simple/ping.mp3");
std::string setup_audio_script = base::StrCat(
{"ae = document.createElement('audio'); ae.src='", audio_url.spec(),
"'; document.body.appendChild(ae); ae.play();"});
EXPECT_TRUE(content::ExecJs(GetGuestRenderFrameHost(), setup_audio_script,
content::EXECUTE_SCRIPT_NO_RESOLVE_PROMISES));
// Wait for audio to start.
embedder_obs.WaitForCurrentlyAudible(true);
EXPECT_TRUE(embedder->IsCurrentlyAudible());
EXPECT_TRUE(guest_contents->IsCurrentlyAudible());
// Wait for audio to stop.
embedder_obs.WaitForCurrentlyAudible(false);
EXPECT_FALSE(embedder->IsCurrentlyAudible());
EXPECT_FALSE(guest_contents->IsCurrentlyAudible());
}
IN_PROC_BROWSER_TEST_P(WebViewTest, SetAudioMuted) {
ASSERT_TRUE(StartEmbeddedTestServer());
LoadAppWithGuest("web_view/simple");
auto* guest = GetGuestViewManager()->GetLastGuestViewCreated();
auto* web_view_guest = extensions::WebViewGuest::FromGuestViewBase(guest);
content::WebContents* owner_web_contents = GetEmbedderWebContents();
// The audio muted state for both WebContents and the WebViewGuest should be
// false.
EXPECT_FALSE(owner_web_contents->IsAudioMuted());
EXPECT_FALSE(web_view_guest->IsAudioMuted());
// Verify that the audio muted state can change for the webview when the owner
// WebContents is unmuted.
web_view_guest->SetAudioMuted(true);
EXPECT_FALSE(owner_web_contents->IsAudioMuted());
EXPECT_TRUE(web_view_guest->IsAudioMuted());
web_view_guest->SetAudioMuted(false);
EXPECT_FALSE(owner_web_contents->IsAudioMuted());
EXPECT_FALSE(web_view_guest->IsAudioMuted());
// Verify that the audio muted state changes to muted for the webview when the
// owner WebContents is muted, and WebViewGuest remembers the muted setting of
// the guest WebContents.
owner_web_contents->SetAudioMuted(true);
EXPECT_TRUE(owner_web_contents->IsAudioMuted());
EXPECT_TRUE(web_view_guest->IsAudioMuted());
web_view_guest->SetAudioMuted(true);
EXPECT_TRUE(owner_web_contents->IsAudioMuted());
EXPECT_TRUE(web_view_guest->IsAudioMuted());
// Verify that the audio muted state cannot change from muted for the webview
// when the owner WebContents is muted and the WebViewGuest remembers the set
// audio muted state for the guest.
web_view_guest->SetAudioMuted(false);
EXPECT_TRUE(owner_web_contents->IsAudioMuted());
EXPECT_TRUE(web_view_guest->IsAudioMuted());
// Verify that the audio muted state changes to the last set audio state for
// the webview when the owner WebContents changes to unmuted.
owner_web_contents->SetAudioMuted(false);
EXPECT_FALSE(owner_web_contents->IsAudioMuted());
EXPECT_FALSE(web_view_guest->IsAudioMuted());
owner_web_contents->SetAudioMuted(true);
web_view_guest->SetAudioMuted(true);
owner_web_contents->SetAudioMuted(false);
EXPECT_FALSE(owner_web_contents->IsAudioMuted());
EXPECT_TRUE(web_view_guest->IsAudioMuted());
}
IN_PROC_BROWSER_TEST_P(WebViewTest, WebViewRespectsInsets) {
LoadAppWithGuest("web_view/simple");
content::RenderWidgetHostView* guest_host_view =
GetGuestView()->GetGuestMainFrame()->GetView();
auto insets = gfx::Insets::TLBR(0, 0, 100, 0);
gfx::Rect expected(guest_host_view->GetVisibleViewportSize());
expected.Inset(insets);
guest_host_view->SetInsets(gfx::Insets::TLBR(0, 0, 100, 0));
gfx::Size size_after = guest_host_view->GetVisibleViewportSize();
EXPECT_EQ(expected.size(), size_after);
}
IN_PROC_BROWSER_TEST_P(WebViewTest, ShutdownBeforeAttach) {
LoadAndLaunchPlatformApp("web_view/app_creates_webview",
"WebViewTest.LAUNCHED");
SendMessageToEmbedderAsync("create-guest-and-stall-attachment");
GetGuestViewManager()->WaitForSingleGuestViewCreated();
// After guest creation, but before attachment, shutdown the embedder to
// verify that we can shutdown safely in this state.
CloseAppWindow(GetFirstAppWindow());
}
IN_PROC_BROWSER_TEST_P(WebViewTest, AudioMutesWhileAttached) {
LoadAppWithGuest("web_view/simple");
content::WebContents* embedder = GetEmbedderWebContents();
extensions::WebViewGuest* web_view_guest =
extensions::WebViewGuest::FromGuestViewBase(GetGuestView());
EXPECT_FALSE(embedder->IsAudioMuted());
EXPECT_FALSE(web_view_guest->IsAudioMuted());
embedder->SetAudioMuted(true);
EXPECT_TRUE(embedder->IsAudioMuted());
EXPECT_TRUE(web_view_guest->IsAudioMuted());
embedder->SetAudioMuted(false);
EXPECT_FALSE(embedder->IsAudioMuted());
EXPECT_FALSE(web_view_guest->IsAudioMuted());
}
IN_PROC_BROWSER_TEST_P(WebViewTest, AudioMutesOnAttach) {
LoadAndLaunchPlatformApp("web_view/app_creates_webview",
"WebViewTest.LAUNCHED");
content::WebContents* embedder = GetEmbedderWebContents();
embedder->SetAudioMuted(true);
EXPECT_TRUE(embedder->IsAudioMuted());
SendMessageToEmbedder("create-guest");
auto* guest_view = GetGuestViewManager()->WaitForSingleGuestViewCreated();
content::WebContents* guest_contents = guest_view->web_contents();
extensions::WebViewGuest* web_view_guest =
extensions::WebViewGuest::FromGuestViewBase(guest_view);
CHECK(web_view_guest);
EXPECT_TRUE(embedder->IsAudioMuted());
WebContentsAudioMutedObserver observer(guest_contents);
// If the guest hasn't attached yet, it may not have received the muting
// update, in which case we should wait until it does.
if (!web_view_guest->IsAudioMuted()) {
observer.WaitForUpdate();
}
EXPECT_TRUE(web_view_guest->IsAudioMuted());
}
IN_PROC_BROWSER_TEST_P(WebViewTest, AudioStateJavascriptAPI) {
base::CommandLine::ForCurrentProcess()->AppendSwitchASCII(
switches::kAutoplayPolicy,
switches::autoplay::kNoUserGestureRequiredPolicy);
ASSERT_TRUE(StartEmbeddedTestServer()); // For serving guest pages.
ASSERT_TRUE(RunExtensionTest("platform_apps/web_view/audio_state_api",
{.launch_as_platform_app = true}))
<< message_;
}
// Test that WebView does not override autoplay policy.
IN_PROC_BROWSER_TEST_P(WebViewTest, AutoplayPolicy) {
base::CommandLine::ForCurrentProcess()->AppendSwitchASCII(
switches::kAutoplayPolicy,
switches::autoplay::kDocumentUserActivationRequiredPolicy);
ASSERT_TRUE(StartEmbeddedTestServer());
ASSERT_TRUE(RunExtensionTest("platform_apps/web_view/autoplay",
{.launch_as_platform_app = true}))
<< message_;
}
// This test exercises the webview spatial navigation API
// TODO(crbug.com/41493388): Flaky timeouts on Mac and Cros.
#if BUILDFLAG(IS_MAC) || BUILDFLAG(IS_CHROMEOS)
#define MAYBE_SpatialNavigationJavascriptAPI \
DISABLED_SpatialNavigationJavascriptAPI
#else
#define MAYBE_SpatialNavigationJavascriptAPI SpatialNavigationJavascriptAPI
#endif
IN_PROC_BROWSER_TEST_P(WebViewTest, MAYBE_SpatialNavigationJavascriptAPI) {
base::CommandLine::ForCurrentProcess()->AppendSwitch(
switches::kEnableSpatialNavigation);
ExtensionTestMessageListener next_step_listener("TEST_STEP_PASSED");
next_step_listener.set_failure_message("TEST_STEP_FAILED");
LoadAndLaunchPlatformApp("web_view/spatial_navigation_state_api",
"WebViewTest.LAUNCHED");
// Check that spatial navigation is initialized in the beginning
ASSERT_TRUE(next_step_listener.WaitUntilSatisfied());
next_step_listener.Reset();
content::WebContents* embedder = GetEmbedderWebContents();
// Spatial navigation enabled at this point, moves focus one element
content::SimulateKeyPress(embedder, ui::DomKey::ARROW_RIGHT,
ui::DomCode::ARROW_RIGHT, ui::VKEY_RIGHT, false,
false, false, false);
// Check that focus has moved one element
ASSERT_TRUE(next_step_listener.WaitUntilSatisfied());
next_step_listener.Reset();
// Moves focus again
content::SimulateKeyPress(embedder, ui::DomKey::ARROW_RIGHT,
ui::DomCode::ARROW_RIGHT, ui::VKEY_RIGHT, false,
false, false, false);
// Check that focus has moved one element
ASSERT_TRUE(next_step_listener.WaitUntilSatisfied());
next_step_listener.Reset();
// Check that spatial navigation was manually disabled
ASSERT_TRUE(next_step_listener.WaitUntilSatisfied());
next_step_listener.Reset();
// Spatial navigation disabled at this point, RIGHT key has no effect
content::SimulateKeyPress(embedder, ui::DomKey::ARROW_RIGHT,
ui::DomCode::ARROW_RIGHT, ui::VKEY_RIGHT, false,
false, false, false);
// Move focus one element to the left via SHIFT+TAB
content::SimulateKeyPress(embedder, ui::DomKey::TAB, ui::DomCode::TAB,
ui::VKEY_TAB, false, true, false, false);
// Check that focus has moved to the left
ASSERT_TRUE(next_step_listener.WaitUntilSatisfied());
}
// This test verifies that hiding the guest triggers visibility change
// notifications.
IN_PROC_BROWSER_TEST_P(WebViewVisibilityTest, GuestVisibilityChanged) {
LoadAppWithGuest("web_view/visibility_changed");
base::RunLoop run_loop;
RenderWidgetHostVisibilityObserver observer(
GetGuestRenderFrameHost()->GetRenderWidgetHost(), run_loop.QuitClosure());
// Handled in platform_apps/web_view/visibility_changed/main.js
SendMessageToEmbedder("hide-guest");
if (!observer.hidden_observed())
run_loop.Run();
}
// This test verifies that hiding the embedder also hides the guest.
IN_PROC_BROWSER_TEST_P(WebViewVisibilityTest, EmbedderVisibilityChanged) {
LoadAppWithGuest("web_view/visibility_changed");
base::RunLoop run_loop;
RenderWidgetHostVisibilityObserver observer(
GetGuestRenderFrameHost()->GetRenderWidgetHost(), run_loop.QuitClosure());
// Handled in platform_apps/web_view/visibility_changed/main.js
SendMessageToEmbedder("hide-embedder");
if (!observer.hidden_observed())
run_loop.Run();
}
// This test verifies that reloading the embedder reloads the guest (and doest
// not crash).
IN_PROC_BROWSER_TEST_P(WebViewTest, ReloadEmbedder) {
// Just load a guest from other test, we do not want to add a separate
// platform_app for this test.
LoadAppWithGuest("web_view/visibility_changed");
ExtensionTestMessageListener launched_again_listener("WebViewTest.LAUNCHED");
GetEmbedderWebContents()->GetController().Reload(content::ReloadType::NORMAL,
false);
ASSERT_TRUE(launched_again_listener.WaitUntilSatisfied());
}
// This test ensures JavaScript errors ("Cannot redefine property") do not
// happen when a <webview> is removed from DOM and added back.
IN_PROC_BROWSER_TEST_P(WebViewTest, AddRemoveWebView_AddRemoveWebView) {
ASSERT_TRUE(StartEmbeddedTestServer()); // For serving guest pages.
ASSERT_TRUE(RunExtensionTest("platform_apps/web_view/addremove",
{.launch_as_platform_app = true}))
<< message_;
}
IN_PROC_BROWSER_TEST_P(WebViewSizeTest, AutoSize) {
ASSERT_TRUE(RunExtensionTest("platform_apps/web_view/autosize",
{.launch_as_platform_app = true}))
<< message_;
}
// Test for http://crbug.com/419611.
IN_PROC_BROWSER_TEST_P(WebViewTest, DisplayNoneSetSrc) {
LoadAndLaunchPlatformApp("web_view/display_none_set_src",
"WebViewTest.LAUNCHED");
// Navigate the guest while it's in "display: none" state.
SendMessageToEmbedder("navigate-guest");
GetGuestViewManager()->WaitForSingleGuestViewCreated();
// Now attempt to navigate the guest again.
SendMessageToEmbedder("navigate-guest");
ExtensionTestMessageListener test_passed_listener("WebViewTest.PASSED");
// Making the guest visible would trigger loadstop.
SendMessageToEmbedder("show-guest");
EXPECT_TRUE(test_passed_listener.WaitUntilSatisfied());
}
// Checks that {allFrames: true} injects script correctly to subframes
// inside <webview>.
IN_PROC_BROWSER_TEST_P(WebViewTest, ExecuteScript) {
ASSERT_TRUE(RunExtensionTest(
"platform_apps/web_view/common",
{.custom_arg = "execute_script", .launch_as_platform_app = true}))
<< message_;
}
IN_PROC_BROWSER_TEST_P(WebViewTest, ExecuteCode) {
ASSERT_TRUE(RunExtensionTest(
"platform_apps/web_view/common",
{.custom_arg = "execute_code", .launch_as_platform_app = true}))
<< message_;
}
IN_PROC_BROWSER_TEST_P(WebViewSizeTest, Shim_TestAutosizeAfterNavigation) {
TestHelper("testAutosizeAfterNavigation", "web_view/shim", NO_TEST_SERVER);
}
IN_PROC_BROWSER_TEST_P(WebViewTest, Shim_TestAllowTransparencyAttribute) {
TestHelper("testAllowTransparencyAttribute", "web_view/shim", NO_TEST_SERVER);
}
IN_PROC_BROWSER_TEST_P(WebViewDPITest, Shim_TestAutosizeHeight) {
TestHelper("testAutosizeHeight", "web_view/shim", NO_TEST_SERVER);
}
IN_PROC_BROWSER_TEST_P(WebViewSizeTest, Shim_TestAutosizeHeight) {
TestHelper("testAutosizeHeight", "web_view/shim", NO_TEST_SERVER);
}
IN_PROC_BROWSER_TEST_P(WebViewDPITest, Shim_TestAutosizeBeforeNavigation) {
TestHelper("testAutosizeBeforeNavigation", "web_view/shim", NO_TEST_SERVER);
}
IN_PROC_BROWSER_TEST_P(WebViewSizeTest, Shim_TestAutosizeBeforeNavigation) {
TestHelper("testAutosizeBeforeNavigation", "web_view/shim", NO_TEST_SERVER);
}
IN_PROC_BROWSER_TEST_P(WebViewDPITest, Shim_TestAutosizeRemoveAttributes) {
TestHelper("testAutosizeRemoveAttributes", "web_view/shim", NO_TEST_SERVER);
}
IN_PROC_BROWSER_TEST_P(WebViewSizeTest, Shim_TestAutosizeRemoveAttributes) {
TestHelper("testAutosizeRemoveAttributes", "web_view/shim", NO_TEST_SERVER);
}
// This test is disabled due to being flaky. http://crbug.com/282116
IN_PROC_BROWSER_TEST_P(WebViewSizeTest,
DISABLED_Shim_TestAutosizeWithPartialAttributes) {
TestHelper("testAutosizeWithPartialAttributes",
"web_view/shim",
NO_TEST_SERVER);
}
IN_PROC_BROWSER_TEST_P(WebViewTest, Shim_TestAPIMethodExistence) {
TestHelper("testAPIMethodExistence", "web_view/shim", NO_TEST_SERVER);
}
IN_PROC_BROWSER_TEST_P(WebViewTest,
Shim_TestCustomElementCallbacksInaccessible) {
TestHelper("testCustomElementCallbacksInaccessible", "web_view/shim",
NO_TEST_SERVER);
}
// Tests the existence of WebRequest API event objects on the request
// object, on the webview element, and hanging directly off webview.
IN_PROC_BROWSER_TEST_P(WebViewTest, Shim_TestWebRequestAPIExistence) {
TestHelper("testWebRequestAPIExistence", "web_view/shim", NO_TEST_SERVER);
}
// Tests that addListener call succeeds on webview's WebRequest API events.
IN_PROC_BROWSER_TEST_P(WebViewTest, Shim_TestWebRequestAPIAddListener) {
TestHelper("testWebRequestAPIAddListener", "web_view/shim", NO_TEST_SERVER);
}
IN_PROC_BROWSER_TEST_P(WebViewTest, Shim_TestWebRequestAPIErrorOccurred) {
TestHelper("testWebRequestAPIErrorOccurred", "web_view/shim", NO_TEST_SERVER);
}
#if defined(USE_AURA)
// Test validates that select tag can be shown and hidden in webview safely
// using quick touch.
IN_PROC_BROWSER_TEST_P(WebViewTest, SelectShowHide) {
LoadAppWithGuest("web_view/select");
content::WebContents* embedder_contents = GetFirstAppWindowWebContents();
ASSERT_TRUE(embedder_contents);
std::vector<content::RenderFrameHost*> guest_frames_list;
GetGuestViewManager()->GetGuestRenderFrameHostList(&guest_frames_list);
ASSERT_EQ(1u, guest_frames_list.size());
content::RenderFrameHost* guest_frame = guest_frames_list[0];
const gfx::Rect embedder_rect = embedder_contents->GetContainerBounds();
const gfx::Rect guest_rect =
guest_frame->GetRenderWidgetHost()->GetView()->GetViewBounds();
const gfx::Point click_point(guest_rect.x() - embedder_rect.x() + 10,
guest_rect.y() - embedder_rect.y() + 10);
LeftMouseClick mouse_click(guest_frame);
SelectControlWaiter select_control_waiter;
for (int i = 0; i < 5; ++i) {
const int click_duration_ms = 10 + i * 25;
mouse_click.Click(click_point, click_duration_ms);
select_control_waiter.Wait(true);
mouse_click.Wait();
mouse_click.Click(click_point, click_duration_ms);
select_control_waiter.Wait(false);
mouse_click.Wait();
}
}
#endif
IN_PROC_BROWSER_TEST_P(WebViewTest, Shim_TestChromeExtensionURL) {
TestHelper("testChromeExtensionURL", "web_view/shim", NO_TEST_SERVER);
}
IN_PROC_BROWSER_TEST_P(WebViewTest, Shim_TestChromeExtensionRelativePath) {
TestHelper("testChromeExtensionRelativePath",
"web_view/shim",
NO_TEST_SERVER);
}
IN_PROC_BROWSER_TEST_P(WebViewTest,
Shim_TestContentInitiatedNavigationToDataUrlBlocked) {
TestHelper("testContentInitiatedNavigationToDataUrlBlocked", "web_view/shim",
NO_TEST_SERVER);
}
IN_PROC_BROWSER_TEST_P(WebViewTest, Shim_TestDisplayNoneWebviewLoad) {
TestHelper("testDisplayNoneWebviewLoad", "web_view/shim", NO_TEST_SERVER);
}
#if BUILDFLAG(IS_WIN) || BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) || \
BUILDFLAG(IS_MAC)
#define MAYBE_Shim_TestDisplayNoneWebviewRemoveChild \
DISABLED_Shim_TestDisplayNoneWebviewRemoveChild
#else
#define MAYBE_Shim_TestDisplayNoneWebviewRemoveChild \
Shim_TestDisplayNoneWebviewRemoveChild
#endif
// Flaky on most desktop platforms: https://crbug.com/1115106.
IN_PROC_BROWSER_TEST_P(WebViewTest,
MAYBE_Shim_TestDisplayNoneWebviewRemoveChild) {
TestHelper("testDisplayNoneWebviewRemoveChild",
"web_view/shim", NO_TEST_SERVER);
}
IN_PROC_BROWSER_TEST_P(WebViewTest, Shim_TestDisplayBlock) {
TestHelper("testDisplayBlock", "web_view/shim", NO_TEST_SERVER);
}
IN_PROC_BROWSER_TEST_P(WebViewTest,
Shim_TestInlineScriptFromAccessibleResources) {
TestHelper("testInlineScriptFromAccessibleResources",
"web_view/shim",
NO_TEST_SERVER);
}
IN_PROC_BROWSER_TEST_P(WebViewTest, Shim_TestInvalidChromeExtensionURL) {
TestHelper("testInvalidChromeExtensionURL", "web_view/shim", NO_TEST_SERVER);
}
IN_PROC_BROWSER_TEST_P(WebViewTest, Shim_TestEventName) {
content::ScopedAllowRendererCrashes scoped_allow_renderer_crashes;
TestHelper("testEventName", "web_view/shim", NO_TEST_SERVER);
}
IN_PROC_BROWSER_TEST_P(WebViewTest, Shim_TestOnEventProperty) {
TestHelper("testOnEventProperties", "web_view/shim", NO_TEST_SERVER);
}
IN_PROC_BROWSER_TEST_P(WebViewTest, Shim_TestLoadProgressEvent) {
TestHelper("testLoadProgressEvent", "web_view/shim", NO_TEST_SERVER);
}
IN_PROC_BROWSER_TEST_P(WebViewTest, Shim_TestDestroyOnEventListener) {
TestHelper("testDestroyOnEventListener", "web_view/shim", NO_TEST_SERVER);
}
IN_PROC_BROWSER_TEST_P(WebViewTest, Shim_TestCannotMutateEventName) {
TestHelper("testCannotMutateEventName", "web_view/shim", NO_TEST_SERVER);
}
IN_PROC_BROWSER_TEST_P(WebViewTest, Shim_TestPartitionChangeAfterNavigation) {
TestHelper("testPartitionChangeAfterNavigation",
"web_view/shim",
NO_TEST_SERVER);
}
IN_PROC_BROWSER_TEST_P(WebViewTest,
Shim_TestPartitionRemovalAfterNavigationFails) {
TestHelper("testPartitionRemovalAfterNavigationFails",
"web_view/shim",
NO_TEST_SERVER);
}
IN_PROC_BROWSER_TEST_P(WebViewTest, Shim_TestAddContentScript) {
TestHelper("testAddContentScript", "web_view/shim", NEEDS_TEST_SERVER);
}
IN_PROC_BROWSER_TEST_P(WebViewTest, Shim_TestAddMultipleContentScripts) {
TestHelper("testAddMultipleContentScripts", "web_view/shim",
NEEDS_TEST_SERVER);
}
IN_PROC_BROWSER_TEST_P(
WebViewTest,
Shim_TestAddContentScriptWithSameNameShouldOverwriteTheExistingOne) {
TestHelper("testAddContentScriptWithSameNameShouldOverwriteTheExistingOne",
"web_view/shim", NEEDS_TEST_SERVER);
}
IN_PROC_BROWSER_TEST_P(
WebViewTest,
Shim_TestAddContentScriptToOneWebViewShouldNotInjectToTheOtherWebView) {
TestHelper("testAddContentScriptToOneWebViewShouldNotInjectToTheOtherWebView",
"web_view/shim", NEEDS_TEST_SERVER);
}
IN_PROC_BROWSER_TEST_P(WebViewTest, Shim_TestAddAndRemoveContentScripts) {
TestHelper("testAddAndRemoveContentScripts", "web_view/shim",
NEEDS_TEST_SERVER);
}
IN_PROC_BROWSER_TEST_P(WebViewNewWindowTest,
Shim_TestAddContentScriptsWithNewWindowAPI) {
#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_MAC)
GTEST_SKIP() << "Flaky on Linux and Mac; http://crbug.com/1182801";
#else
TestHelper("testAddContentScriptsWithNewWindowAPI", "web_view/shim",
NEEDS_TEST_SERVER);
#endif // BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_MAC)
}
IN_PROC_BROWSER_TEST_P(
WebViewTest,
Shim_TestContentScriptIsInjectedAfterTerminateAndReloadWebView) {
content::ScopedAllowRendererCrashes scoped_allow_renderer_crashes;
TestHelper("testContentScriptIsInjectedAfterTerminateAndReloadWebView",
"web_view/shim", NEEDS_TEST_SERVER);
}
IN_PROC_BROWSER_TEST_P(WebViewTest,
Shim_TestContentScriptExistsAsLongAsWebViewTagExists) {
TestHelper("testContentScriptExistsAsLongAsWebViewTagExists", "web_view/shim",
NEEDS_TEST_SERVER);
}
IN_PROC_BROWSER_TEST_P(WebViewTest, Shim_TestAddContentScriptWithCode) {
TestHelper("testAddContentScriptWithCode", "web_view/shim",
NEEDS_TEST_SERVER);
}
IN_PROC_BROWSER_TEST_P(
WebViewTest,
Shim_TestAddMultipleContentScriptsWithCodeAndCheckGeneratedScriptUrl) {
TestHelper("testAddMultipleContentScriptsWithCodeAndCheckGeneratedScriptUrl",
"web_view/shim", NEEDS_TEST_SERVER);
}
IN_PROC_BROWSER_TEST_P(WebViewTest, Shim_TestExecuteScriptFail) {
TestHelper("testExecuteScriptFail", "web_view/shim", NEEDS_TEST_SERVER);
}
IN_PROC_BROWSER_TEST_P(WebViewTest, Shim_TestExecuteScript) {
TestHelper("testExecuteScript", "web_view/shim", NO_TEST_SERVER);
}
// Flaky and likely not testing the right assertion. https://crbug.com/703727
IN_PROC_BROWSER_TEST_P(
WebViewTest,
DISABLED_Shim_TestExecuteScriptIsAbortedWhenWebViewSourceIsChanged) {
TestHelper("testExecuteScriptIsAbortedWhenWebViewSourceIsChanged",
"web_view/shim",
NO_TEST_SERVER);
}
IN_PROC_BROWSER_TEST_P(
WebViewTest,
Shim_TestExecuteScriptIsAbortedWhenWebViewSourceIsInvalid) {
TestHelper("testExecuteScriptIsAbortedWhenWebViewSourceIsInvalid",
"web_view/shim",
NO_TEST_SERVER);
}
IN_PROC_BROWSER_TEST_P(WebViewTest, Shim_TestTerminateAfterExit) {
content::ScopedAllowRendererCrashes scoped_allow_renderer_crashes;
TestHelper("testTerminateAfterExit", "web_view/shim", NO_TEST_SERVER);
}
IN_PROC_BROWSER_TEST_P(WebViewTest, Shim_TestAssignSrcAfterCrash) {
content::ScopedAllowRendererCrashes scoped_allow_renderer_crashes;
TestHelper("testAssignSrcAfterCrash", "web_view/shim", NO_TEST_SERVER);
}
IN_PROC_BROWSER_TEST_P(WebViewTest,
Shim_TestNavOnConsecutiveSrcAttributeChanges) {
TestHelper("testNavOnConsecutiveSrcAttributeChanges",
"web_view/shim",
NO_TEST_SERVER);
}
IN_PROC_BROWSER_TEST_P(WebViewTest, Shim_TestNavOnSrcAttributeChange) {
TestHelper("testNavOnSrcAttributeChange", "web_view/shim", NO_TEST_SERVER);
}
IN_PROC_BROWSER_TEST_P(WebViewTest, Shim_TestNavigateAfterResize) {
TestHelper("testNavigateAfterResize", "web_view/shim", NO_TEST_SERVER);
}
IN_PROC_BROWSER_TEST_P(WebViewTest, Shim_TestNestedCrossOriginSubframes) {
TestHelper("testNestedCrossOriginSubframes",
"web_view/shim", NEEDS_TEST_SERVER);
}
#if BUILDFLAG(IS_MAC)
// Flaky on Mac. See https://crbug.com/674904.
#define MAYBE_Shim_TestNestedSubframes DISABLED_Shim_TestNestedSubframes
#else
#define MAYBE_Shim_TestNestedSubframes Shim_TestNestedSubframes
#endif
IN_PROC_BROWSER_TEST_P(WebViewTest, MAYBE_Shim_TestNestedSubframes) {
TestHelper("testNestedSubframes", "web_view/shim", NO_TEST_SERVER);
}
IN_PROC_BROWSER_TEST_P(WebViewTest, Shim_TestRemoveSrcAttribute) {
TestHelper("testRemoveSrcAttribute", "web_view/shim", NO_TEST_SERVER);
}
IN_PROC_BROWSER_TEST_P(WebViewTest, Shim_TestReassignSrcAttribute) {
TestHelper("testReassignSrcAttribute", "web_view/shim", NO_TEST_SERVER);
}
IN_PROC_BROWSER_TEST_P(WebViewNewWindowTest, Shim_TestNewWindow) {
TestHelper("testNewWindow", "web_view/shim", NEEDS_TEST_SERVER);
// The first <webview> tag in the test will run window.open(), which the
// embedder will translate into an injected second <webview> tag. Ensure
// that the two <webview>'s remain in the same BrowsingInstance and
// StoragePartition.
GetGuestViewManager()->WaitForNumGuestsCreated(2);
std::vector<content::RenderFrameHost*> guest_rfh_list;
GetGuestViewManager()->GetGuestRenderFrameHostList(&guest_rfh_list);
ASSERT_EQ(2u, guest_rfh_list.size());
auto* guest1 = guest_rfh_list[0];
auto* guest2 = guest_rfh_list[1];
ASSERT_NE(guest1, guest2);
auto* guest_instance1 = guest1->GetSiteInstance();
auto* guest_instance2 = guest2->GetSiteInstance();
EXPECT_TRUE(guest_instance1->IsGuest());
EXPECT_TRUE(guest_instance2->IsGuest());
EXPECT_EQ(guest_instance1->GetStoragePartitionConfig(),
guest_instance2->GetStoragePartitionConfig());
EXPECT_TRUE(guest_instance1->IsRelatedSiteInstance(guest_instance2));
}
IN_PROC_BROWSER_TEST_P(WebViewNewWindowTest, Shim_TestNewWindowTwoListeners) {
TestHelper("testNewWindowTwoListeners", "web_view/shim", NEEDS_TEST_SERVER);
}
IN_PROC_BROWSER_TEST_P(WebViewNewWindowTest,
Shim_TestNewWindowNoPreventDefault) {
TestHelper("testNewWindowNoPreventDefault",
"web_view/shim",
NEEDS_TEST_SERVER);
}
IN_PROC_BROWSER_TEST_P(WebViewNewWindowTest, Shim_TestNewWindowNoReferrerLink) {
GURL newwindow_url("about:blank#noreferrer");
content::TestNavigationObserver observer(newwindow_url);
observer.StartWatchingNewWebContents();
observer.set_wait_event(
content::TestNavigationObserver::WaitEvent::kNavigationFinished);
TestHelper("testNewWindowNoReferrerLink", "web_view/shim", NEEDS_TEST_SERVER);
// The first <webview> tag in the test will run window.open(), which the
// embedder will translate into an injected second <webview> tag. Ensure
// that both <webview>'s are in guest SiteInstances and in the same
// StoragePartition.
GetGuestViewManager()->WaitForNumGuestsCreated(2);
std::vector<content::RenderFrameHost*> guest_rfh_list;
GetGuestViewManager()->GetGuestRenderFrameHostList(&guest_rfh_list);
ASSERT_EQ(2u, guest_rfh_list.size());
auto* guest1_rfh = guest_rfh_list[0];
auto* guest2_rfh = guest_rfh_list[1];
ASSERT_NE(guest1_rfh, guest2_rfh);
auto* guest_instance1 = guest1_rfh->GetSiteInstance();
auto* guest_instance2 = guest2_rfh->GetSiteInstance();
EXPECT_TRUE(guest_instance1->IsGuest());
EXPECT_TRUE(guest_instance2->IsGuest());
EXPECT_EQ(guest_instance1->GetStoragePartitionConfig(),
guest_instance2->GetStoragePartitionConfig());
// The new guest should be in a different BrowsingInstance.
EXPECT_FALSE(guest_instance1->IsRelatedSiteInstance(guest_instance2));
// Check that the source SiteInstance used when the first guest opened the
// new noreferrer window is also a guest SiteInstance in the same
// StoragePartition.
observer.Wait();
if (base::FeatureList::IsEnabled(features::kGuestViewMPArch)) {
// Since this is a noopener we don't propagate the source site instance.
ASSERT_FALSE(observer.last_source_site_instance());
} else {
ASSERT_TRUE(observer.last_source_site_instance());
EXPECT_TRUE(observer.last_source_site_instance()->IsGuest());
EXPECT_EQ(observer.last_source_site_instance()->GetStoragePartitionConfig(),
guest_instance1->GetStoragePartitionConfig());
}
}
IN_PROC_BROWSER_TEST_P(WebViewNewWindowTest,
Shim_TestWebViewAndEmbedderInNewWindow) {
TestHelper("testWebViewAndEmbedderInNewWindow", "web_view/shim",
NEEDS_TEST_SERVER);
content::WebContents* embedder_web_contents = GetFirstAppWindowWebContents();
ASSERT_TRUE(embedder_web_contents);
// Make sure opener and owner for the empty_guest source are different.
// In general, we should have two guests and two embedders and all four
// should be different.
std::vector<content::RenderFrameHost*> guest_rfh_list;
GetGuestViewManager()->GetGuestRenderFrameHostList(&guest_rfh_list);
ASSERT_EQ(2u, guest_rfh_list.size());
content::RenderFrameHost* new_window_guest_frame = guest_rfh_list[0];
content::RenderFrameHost* empty_guest_frame = guest_rfh_list[1];
EXPECT_TRUE(empty_guest_frame->GetProcess()->IsForGuestsOnly());
guest_view::GuestViewBase* empty_guest_view =
GetGuestViewManager()->GetLastGuestViewCreated();
ASSERT_EQ(empty_guest_view->GetGuestMainFrame(), empty_guest_frame);
ASSERT_NE(empty_guest_view->GetGuestMainFrame(), new_window_guest_frame);
content::WebContents* empty_guest_embedder =
empty_guest_view->embedder_web_contents();
ASSERT_TRUE(empty_guest_embedder);
ASSERT_NE(empty_guest_embedder->GetPrimaryMainFrame(), empty_guest_frame);
if (!base::FeatureList::IsEnabled(features::kGuestViewMPArch)) {
// TODO(crbug.com/40202416): Introduce a test helper to expose the opener as
// a `content::Page`.
content::RenderFrameHost* empty_guest_opener =
empty_guest_view->web_contents()
->GetFirstWebContentsInLiveOriginalOpenerChain()
->GetPrimaryMainFrame();
ASSERT_TRUE(empty_guest_opener);
ASSERT_NE(empty_guest_opener, empty_guest_embedder->GetPrimaryMainFrame());
}
// The JS part of this test, we've already checked the opener relationship of
// the two webviews. We also need to check the window reference from the
// initial window.open call in the opener. We need to do this from the C++
// part in order to run script in the main world.
EXPECT_EQ(true,
content::EvalJs(new_window_guest_frame, "!!window.newWindow"));
EXPECT_EQ(url::kAboutBlankURL,
content::EvalJs(new_window_guest_frame,
"window.newWindow.location.href"));
}
IN_PROC_BROWSER_TEST_P(WebViewNewWindowTest,
Shim_TestWebViewAndEmbedderInNewWindow_Noopener) {
TestHelper("testWebViewAndEmbedderInNewWindow_Noopener", "web_view/shim",
NEEDS_TEST_SERVER);
}
IN_PROC_BROWSER_TEST_P(WebViewNewWindowTest,
Shim_TestNewWindowAttachToExisting) {
TestHelper("testNewWindowAttachToExisting", "web_view/shim",
NEEDS_TEST_SERVER);
}
IN_PROC_BROWSER_TEST_P(WebViewNewWindowTest, Shim_TestNewWindowNoDeadlock) {
TestHelper("testNewWindowNoDeadlock", "web_view/shim", NEEDS_TEST_SERVER);
}
// This is a regression test for crbug.com/1309302. It launches an app
// with two iframes and a webview within each of the iframes. The
// purpose of the test is to ensure that webRequest subevent names are
// unique across all webviews within the app.
IN_PROC_BROWSER_TEST_P(WebViewTest, TwoIframesWebRequest) {
ASSERT_TRUE(StartEmbeddedTestServer()); // For serving webview pages.
ExtensionTestMessageListener ready1("ready1", ReplyBehavior::kWillReply);
ExtensionTestMessageListener ready2("ready2", ReplyBehavior::kWillReply);
LoadAndLaunchPlatformApp("web_view/two_iframes_web_request", "Launched");
EXPECT_TRUE(ready1.WaitUntilSatisfied());
EXPECT_TRUE(ready2.WaitUntilSatisfied());
ExtensionTestMessageListener finished1("success1");
finished1.set_failure_message("fail1");
ExtensionTestMessageListener finished2("success2");
finished2.set_failure_message("fail2");
// Reply to the listeners to start the navigations and wait for the
// results.
ready1.Reply("");
ready2.Reply("");
EXPECT_TRUE(finished1.WaitUntilSatisfied());
EXPECT_TRUE(finished2.WaitUntilSatisfied());
}
IN_PROC_BROWSER_TEST_P(WebViewNewWindowTest,
NewWindow_AttachAfterOpenerDestroyed) {
TestHelper("testNewWindowAttachAfterOpenerDestroyed", "web_view/newwindow",
NEEDS_TEST_SERVER);
}
IN_PROC_BROWSER_TEST_P(WebViewNewWindowTest, NewWindow_AttachInSubFrame) {
TestHelper("testNewWindowAttachInSubFrame", "web_view/newwindow",
NEEDS_TEST_SERVER);
}
IN_PROC_BROWSER_TEST_P(WebViewNewWindowTest,
NewWindow_NewWindowNameTakesPrecedence) {
TestHelper("testNewWindowNameTakesPrecedence", "web_view/newwindow",
NEEDS_TEST_SERVER);
}
IN_PROC_BROWSER_TEST_P(WebViewNewWindowTest,
NewWindow_WebViewNameTakesPrecedence) {
TestHelper("testNewWindowWebViewNameTakesPrecedence", "web_view/newwindow",
NEEDS_TEST_SERVER);
}
IN_PROC_BROWSER_TEST_P(WebViewNewWindowTest, NewWindow_NoName) {
TestHelper("testNewWindowNoName", "web_view/newwindow", NEEDS_TEST_SERVER);
}
IN_PROC_BROWSER_TEST_P(WebViewNewWindowTest, NewWindow_Redirect) {
TestHelper("testNewWindowRedirect", "web_view/newwindow", NEEDS_TEST_SERVER);
}
IN_PROC_BROWSER_TEST_P(WebViewNewWindowTest, NewWindow_Close) {
TestHelper("testNewWindowClose", "web_view/newwindow", NEEDS_TEST_SERVER);
}
IN_PROC_BROWSER_TEST_P(WebViewNewWindowTest, NewWindow_DeferredAttachment) {
TestHelper("testNewWindowDeferredAttachment", "web_view/newwindow",
NEEDS_TEST_SERVER);
}
IN_PROC_BROWSER_TEST_P(WebViewNewWindowTest, NewWindow_ExecuteScript) {
TestHelper("testNewWindowExecuteScript", "web_view/newwindow",
NEEDS_TEST_SERVER);
}
IN_PROC_BROWSER_TEST_P(WebViewNewWindowTest, NewWindow_DeclarativeWebRequest) {
TestHelper("testNewWindowDeclarativeWebRequest", "web_view/newwindow",
NEEDS_TEST_SERVER);
}
IN_PROC_BROWSER_TEST_P(WebViewNewWindowTest,
NewWindow_DiscardAfterOpenerDestroyed) {
TestHelper("testNewWindowDiscardAfterOpenerDestroyed", "web_view/newwindow",
NEEDS_TEST_SERVER);
}
IN_PROC_BROWSER_TEST_P(WebViewNewWindowTest, NewWindow_WebRequest) {
TestHelper("testNewWindowWebRequest", "web_view/newwindow",
NEEDS_TEST_SERVER);
}
// A custom elements bug needs to be addressed to enable this test:
// See http://crbug.com/282477 for more information.
IN_PROC_BROWSER_TEST_P(WebViewNewWindowTest,
DISABLED_NewWindow_WebRequestCloseWindow) {
TestHelper("testNewWindowWebRequestCloseWindow", "web_view/newwindow",
NEEDS_TEST_SERVER);
}
IN_PROC_BROWSER_TEST_P(WebViewNewWindowTest,
NewWindow_WebRequestRemoveElement) {
TestHelper("testNewWindowWebRequestRemoveElement", "web_view/newwindow",
NEEDS_TEST_SERVER);
}
// Ensure that when one <webview> makes a window.open() call that references
// another <webview> by name, the opener is updated without a crash. Regression
// test for https://crbug.com/1013553.
IN_PROC_BROWSER_TEST_P(WebViewNewWindowTest, NewWindow_UpdateOpener) {
TestHelper("testNewWindowAndUpdateOpener", "web_view/newwindow",
NEEDS_TEST_SERVER);
// The first <webview> tag in the test will run window.open(), which the
// embedder will translate into an injected second <webview> tag, after which
// test control will return here. Wait until there are two guests; i.e.,
// until the second <webview>'s guest is also created.
GetGuestViewManager()->WaitForNumGuestsCreated(2);
std::vector<content::RenderFrameHost*> guest_rfh_list;
GetGuestViewManager()->GetGuestRenderFrameHostList(&guest_rfh_list);
ASSERT_EQ(2u, guest_rfh_list.size());
content::RenderFrameHost* guest1 = guest_rfh_list[0];
content::RenderFrameHost* guest2 = guest_rfh_list[1];
ASSERT_NE(guest1, guest2);
// Change first guest's window.name to "foo" and check that it does not
// have an opener to start with.
EXPECT_TRUE(content::ExecJs(guest1, "window.name = 'foo'"));
EXPECT_EQ("foo", content::EvalJs(guest1, "window.name"));
EXPECT_EQ(true, content::EvalJs(guest1, "window.opener == null"));
// Create a subframe in the second guest. This is needed because the crash
// in crbug.com/1013553 only happened when trying to incorrectly create
// proxies for a subframe.
EXPECT_TRUE(content::ExecJs(
guest2, "document.body.appendChild(document.createElement('iframe'));"));
// Update the opener of |guest1| to point to |guest2|. This triggers
// creation of proxies on the new opener chain, which should not crash.
EXPECT_TRUE(content::ExecJs(guest2, "window.open('', 'foo');"));
// Ensure both guests have the proper opener relationship set up. Namely,
// each guest's opener should point to the other guest, creating a cycle.
EXPECT_EQ(true, content::EvalJs(guest1, "window.opener.opener === window"));
EXPECT_EQ(true, content::EvalJs(guest2, "window.opener.opener === window"));
}
IN_PROC_BROWSER_TEST_P(WebViewNewWindowTest,
NewWindow_OpenerDestroyedWhileUnattached) {
TestHelper("testNewWindowOpenerDestroyedWhileUnattached",
"web_view/newwindow", NEEDS_TEST_SERVER);
ASSERT_EQ(2u, GetGuestViewManager()->num_guests_created());
// We have two guests in this test, one is the initial one, the other
// is the newwindow one.
// Before the embedder goes away, both the guests should go away.
// This ensures that unattached guests are gone if opener is gone.
GetGuestViewManager()->WaitForAllGuestsDeleted();
}
// Creates a guest in a unattached state, then confirms that calling
// |RenderFrameHost::ForEachRenderFrameHost| on the embedder will include the
// guest's frame.
IN_PROC_BROWSER_TEST_P(WebViewNewWindowTest,
NewWindow_UnattachedVisitedByForEachRenderFrameHost) {
TestHelper("testNewWindowDeferredAttachmentIndefinitely",
"web_view/newwindow", NEEDS_TEST_SERVER);
// The test creates two guests, one of which is created but left in an
// unattached state.
GetGuestViewManager()->WaitForNumGuestsCreated(2);
content::WebContents* embedder = GetEmbedderWebContents();
auto* unattached_guest = GetGuestViewManager()->GetLastGuestViewCreated();
ASSERT_TRUE(unattached_guest);
ASSERT_EQ(embedder, unattached_guest->owner_web_contents());
ASSERT_FALSE(unattached_guest->attached());
ASSERT_FALSE(unattached_guest->embedder_web_contents());
std::vector<content::RenderFrameHost*> guest_rfh_list;
GetGuestViewManager()->GetGuestRenderFrameHostList(&guest_rfh_list);
ASSERT_EQ(2u, guest_rfh_list.size());
content::RenderFrameHost* unattached_guest_rfh =
unattached_guest->GetGuestMainFrame();
content::RenderFrameHost* other_guest_rfh =
(guest_rfh_list[0] == unattached_guest_rfh) ? guest_rfh_list[1]
: guest_rfh_list[0];
content::RenderFrameHost* embedder_main_frame =
embedder->GetPrimaryMainFrame();
EXPECT_THAT(content::CollectAllRenderFrameHosts(embedder_main_frame),
testing::UnorderedElementsAre(
embedder_main_frame, other_guest_rfh, unattached_guest_rfh));
// In either case, GetParentOrOuterDocument does not escape GuestViews.
EXPECT_EQ(nullptr, other_guest_rfh->GetParentOrOuterDocument());
EXPECT_EQ(nullptr, unattached_guest_rfh->GetParentOrOuterDocument());
EXPECT_EQ(other_guest_rfh, other_guest_rfh->GetOutermostMainFrame());
EXPECT_EQ(unattached_guest_rfh,
unattached_guest_rfh->GetOutermostMainFrame());
// GetParentOrOuterDocumentOrEmbedder does escape GuestViews.
EXPECT_EQ(embedder_main_frame,
other_guest_rfh->GetParentOrOuterDocumentOrEmbedder());
EXPECT_EQ(embedder_main_frame,
other_guest_rfh->GetOutermostMainFrameOrEmbedder());
// The unattached guest should still be considered to have an embedder.
EXPECT_EQ(embedder_main_frame,
unattached_guest_rfh->GetParentOrOuterDocumentOrEmbedder());
EXPECT_EQ(embedder_main_frame,
unattached_guest_rfh->GetOutermostMainFrameOrEmbedder());
EXPECT_EQ(embedder,
unattached_guest->web_contents()->GetResponsibleWebContents());
}
// Creates a guest in a unattached state, then confirms that calling
// the various view methods return null.
IN_PROC_BROWSER_TEST_P(WebViewNewWindowTest,
NewWindow_UnattachedVerifyViewMethods) {
// TODO(crbug.com/40202416): This test doesn't apply for MPArch and
// can be removed when the InnerWebContents version is removed.
SKIP_FOR_MPARCH();
TestHelper("testNewWindowDeferredAttachmentIndefinitely",
"web_view/newwindow", NEEDS_TEST_SERVER);
GetGuestViewManager()->WaitForNumGuestsCreated(2);
content::WebContents* embedder = GetEmbedderWebContents();
auto* unattached_guest = GetGuestViewManager()->GetLastGuestViewCreated();
ASSERT_TRUE(unattached_guest);
ASSERT_EQ(embedder, unattached_guest->owner_web_contents());
ASSERT_FALSE(unattached_guest->attached());
ASSERT_FALSE(unattached_guest->embedder_web_contents());
ASSERT_FALSE(unattached_guest->web_contents()->GetNativeView());
ASSERT_FALSE(unattached_guest->web_contents()->GetContentNativeView());
ASSERT_FALSE(unattached_guest->web_contents()->GetTopLevelNativeWindow());
}
IN_PROC_BROWSER_TEST_P(WebViewTest, Shim_TestContentLoadEvent) {
TestHelper("testContentLoadEvent", "web_view/shim", NO_TEST_SERVER);
}
IN_PROC_BROWSER_TEST_P(WebViewTest, Shim_TestContentLoadEventWithDisplayNone) {
TestHelper("testContentLoadEventWithDisplayNone",
"web_view/shim",
NO_TEST_SERVER);
}
IN_PROC_BROWSER_TEST_P(WebViewTest, Shim_TestDeclarativeWebRequestAPI) {
TestHelper("testDeclarativeWebRequestAPI",
"web_view/shim",
NEEDS_TEST_SERVER);
}
IN_PROC_BROWSER_TEST_P(WebViewTest,
Shim_TestDeclarativeWebRequestAPISendMessage) {
TestHelper("testDeclarativeWebRequestAPISendMessage",
"web_view/shim",
NEEDS_TEST_SERVER);
}
IN_PROC_BROWSER_TEST_P(
WebViewTest,
Shim_TestDeclarativeWebRequestAPISendMessageSecondWebView) {
TestHelper("testDeclarativeWebRequestAPISendMessageSecondWebView",
"web_view/shim", NEEDS_TEST_SERVER);
}
IN_PROC_BROWSER_TEST_P(WebViewTest, Shim_TestWebRequestAPI) {
TestHelper("testWebRequestAPI", "web_view/shim", NEEDS_TEST_SERVER);
}
IN_PROC_BROWSER_TEST_P(WebViewTest, Shim_TestWebRequestAPIOnlyForInstance) {
TestHelper("testWebRequestAPIOnlyForInstance", "web_view/shim",
NEEDS_TEST_SERVER);
}
IN_PROC_BROWSER_TEST_P(WebViewTest, Shim_TestWebRequestAPIWithHeaders) {
TestHelper("testWebRequestAPIWithHeaders",
"web_view/shim",
NEEDS_TEST_SERVER);
}
IN_PROC_BROWSER_TEST_P(WebViewTest, Shim_TestWebRequestAPIGoogleProperty) {
TestHelper("testWebRequestAPIGoogleProperty",
"web_view/shim",
NO_TEST_SERVER);
}
IN_PROC_BROWSER_TEST_P(WebViewTest,
Shim_TestWebRequestListenerSurvivesReparenting) {
TestHelper("testWebRequestListenerSurvivesReparenting",
"web_view/shim",
NEEDS_TEST_SERVER);
}
IN_PROC_BROWSER_TEST_P(WebViewTest, Shim_TestLoadStartLoadRedirect) {
TestHelper("testLoadStartLoadRedirect", "web_view/shim", NEEDS_TEST_SERVER);
}
IN_PROC_BROWSER_TEST_P(WebViewTest,
Shim_TestLoadAbortChromeExtensionURLWrongPartition) {
TestHelper("testLoadAbortChromeExtensionURLWrongPartition",
"web_view/shim",
NO_TEST_SERVER);
}
IN_PROC_BROWSER_TEST_P(WebViewTest, Shim_TestLoadAbortEmptyResponse) {
TestHelper("testLoadAbortEmptyResponse", "web_view/shim", NEEDS_TEST_SERVER);
}
IN_PROC_BROWSER_TEST_P(WebViewTest, Shim_TestLoadAbortIllegalChromeURL) {
TestHelper("testLoadAbortIllegalChromeURL",
"web_view/shim",
NO_TEST_SERVER);
}
IN_PROC_BROWSER_TEST_P(WebViewTest, Shim_TestLoadAbortIllegalFileURL) {
TestHelper("testLoadAbortIllegalFileURL", "web_view/shim", NO_TEST_SERVER);
}
IN_PROC_BROWSER_TEST_P(WebViewTest, Shim_TestLoadAbortIllegalJavaScriptURL) {
TestHelper("testLoadAbortIllegalJavaScriptURL",
"web_view/shim",
NO_TEST_SERVER);
}
IN_PROC_BROWSER_TEST_P(WebViewTest, Shim_TestLoadAbortInvalidNavigation) {
TestHelper("testLoadAbortInvalidNavigation", "web_view/shim", NO_TEST_SERVER);
}
IN_PROC_BROWSER_TEST_P(WebViewTest, Shim_TestLoadAbortNonWebSafeScheme) {
TestHelper("testLoadAbortNonWebSafeScheme", "web_view/shim", NO_TEST_SERVER);
}
IN_PROC_BROWSER_TEST_P(WebViewTest, Shim_TestReload) {
TestHelper("testReload", "web_view/shim", NO_TEST_SERVER);
}
IN_PROC_BROWSER_TEST_P(WebViewTest, Shim_TestReloadAfterTerminate) {
content::ScopedAllowRendererCrashes scoped_allow_renderer_crashes;
TestHelper("testReloadAfterTerminate", "web_view/shim", NO_TEST_SERVER);
}
IN_PROC_BROWSER_TEST_P(WebViewTest, Shim_TestGetProcessId) {
TestHelper("testGetProcessId", "web_view/shim", NO_TEST_SERVER);
}
IN_PROC_BROWSER_TEST_P(WebViewVisibilityTest, Shim_TestHiddenBeforeNavigation) {
TestHelper("testHiddenBeforeNavigation", "web_view/shim", NO_TEST_SERVER);
}
IN_PROC_BROWSER_TEST_P(WebViewTest, Shim_TestRemoveWebviewOnExit) {
content::ScopedAllowRendererCrashes scoped_allow_renderer_crashes;
ASSERT_TRUE(StartEmbeddedTestServer()); // For serving guest pages.
// Launch the app and wait until it's ready to load a test.
LoadAndLaunchPlatformApp("web_view/shim", "Launched");
content::WebContents* embedder_web_contents = GetFirstAppWindowWebContents();
ASSERT_TRUE(embedder_web_contents);
// Run the test and wait until the guest WebContents is available and has
// finished loading.
ExtensionTestMessageListener guest_loaded_listener("guest-loaded");
EXPECT_TRUE(content::ExecJs(embedder_web_contents,
"runTest('testRemoveWebviewOnExit')"));
auto* guest_view = GetGuestViewManager()->WaitForSingleGuestViewCreated();
EXPECT_TRUE(guest_view);
EXPECT_TRUE(guest_view->GetGuestMainFrame()->GetProcess()->IsForGuestsOnly());
ASSERT_TRUE(guest_loaded_listener.WaitUntilSatisfied());
// Tell the embedder to kill the guest.
EXPECT_TRUE(
content::ExecJs(embedder_web_contents, "removeWebviewOnExitDoCrash();"));
// Wait until the guest WebContents is destroyed.
GetGuestViewManager()->WaitForLastGuestDeleted();
}
// Remove <webview> immediately after navigating it.
// This is a regression test for http://crbug.com/276023.
IN_PROC_BROWSER_TEST_P(WebViewTest, Shim_TestRemoveWebviewAfterNavigation) {
TestHelper("testRemoveWebviewAfterNavigation",
"web_view/shim",
NO_TEST_SERVER);
}
IN_PROC_BROWSER_TEST_P(WebViewTest, Shim_TestNavigationToExternalProtocol) {
TestHelper("testNavigationToExternalProtocol",
"web_view/shim",
NO_TEST_SERVER);
}
IN_PROC_BROWSER_TEST_P(WebViewSizeTest,
Shim_TestResizeWebviewWithDisplayNoneResizesContent) {
TestHelper("testResizeWebviewWithDisplayNoneResizesContent",
"web_view/shim",
NO_TEST_SERVER);
}
IN_PROC_BROWSER_TEST_P(WebViewSizeTest, Shim_TestResizeWebviewResizesContent) {
TestHelper("testResizeWebviewResizesContent",
"web_view/shim",
NO_TEST_SERVER);
}
class WebViewSSLErrorTest : public WebViewTest {
public:
WebViewSSLErrorTest() = default;
~WebViewSSLErrorTest() override = default;
// Loads the guest at "web_view/ssl/https_page.html" with an SSL error, and
// asserts the security interstitial is displayed within the guest instead of
// through the embedder's WebContents.
void SSLTestHelper() {
// Configures the HTTPS server so we can load a page with a SSL error inside
// a guest.
https_server_.SetSSLConfig(net::EmbeddedTestServer::CERT_MISMATCHED_NAME);
https_server_.ServeFilesFromSourceDirectory(GetChromeTestDataDir());
ASSERT_TRUE(https_server_.Start());
LoadAndLaunchPlatformApp("web_view/ssl", "EmbedderLoaded");
LoadEmptyGuest();
const auto target_url = https_server_.GetURL(
"/extensions/platform_apps/web_view/ssl/https_page.html");
SetGuestURL(target_url, /*expect_successful_navigation=*/false);
// Guest's `target_url` is served by an HTTP server with a cert error.
// A security error within a guest should not cause an interstitial to be
// shown in the embedder.
// Note: for the InnerWebContents case, the guest and the embedder will have
// different WebContents, so we don't expect the interstitial to be
// associated with the embedder's WebContents. But in the MPArch case,
// there's only one WebContents, so the guest's interstitial page is
// associated with the embedder's WebContents.
auto* guest = GetGuestViewManager()->GetLastGuestViewCreated();
ASSERT_EQ(GetParam(),
GetFirstAppWindowWebContents() == guest->web_contents());
ASSERT_EQ(GetFirstAppWindowWebContents() == guest->web_contents(),
chrome_browser_interstitials::IsShowingInterstitial(
GetFirstAppWindowWebContents()));
ASSERT_TRUE(guest->GetGuestMainFrame()->IsErrorDocument());
ASSERT_TRUE(chrome_browser_interstitials::IsShowingInterstitial(
guest->web_contents()));
}
void LoadEmptyGuest() {
// Creates the guest, and asserts its successful creation.
content::WebContents* embedder_web_contents =
GetFirstAppWindowWebContents();
ExtensionTestMessageListener guest_added("GuestAddedToDom");
EXPECT_TRUE(content::ExecJs(embedder_web_contents, "createGuest();"));
ASSERT_TRUE(guest_added.WaitUntilSatisfied());
auto* guest_main_frame =
GetGuestViewManager()->WaitForSingleGuestRenderFrameHostCreated();
ASSERT_TRUE(guest_main_frame->GetProcess()->IsForGuestsOnly());
}
// Loads the `guest_url` by setting the `src` of the guest. This helper
// assumes the app is loaded, and assumes the app already has a guest created.
void SetGuestURL(const GURL& guest_url, bool expect_successful_navigation) {
auto* embedder_web_contents = GetFirstAppWindowWebContents();
ASSERT_TRUE(embedder_web_contents);
auto* guest_main_frame =
GetGuestViewManager()->GetLastGuestRenderFrameHostCreated();
ASSERT_TRUE(guest_main_frame);
content::TestFrameNavigationObserver guest_navi_obs(guest_main_frame);
ASSERT_TRUE(
content::ExecJs(embedder_web_contents,
content::JsReplace("loadGuestUrl($1);", guest_url)));
guest_navi_obs.Wait();
// Do not dereference `guest_main_frame` beyond here as it can be destroyed
// at this point.
ASSERT_EQ(guest_navi_obs.last_navigation_succeeded(),
expect_successful_navigation);
if (expect_successful_navigation) {
ASSERT_EQ(guest_navi_obs.last_net_error_code(), net::Error::OK);
ASSERT_EQ(guest_navi_obs.last_committed_url(), guest_url);
} else {
// `https_server_` in `WebViewSSLErrorTest::SSLTestHelper` is configured
// with `CERT_MISMATCHED_NAME`.
ASSERT_EQ(guest_navi_obs.last_net_error_code(),
net::Error::ERR_CERT_COMMON_NAME_INVALID);
// `TestFrameNavigationObserver`'s `last_committed_url_` is only set if
// the navigation does not result in an error page.
ASSERT_EQ(guest_navi_obs.last_committed_url(), GURL());
}
}
protected:
// Starts a HTTPS server so we can load HTTPS pages, possibly with SSL errors,
// inside guests.
net::EmbeddedTestServer https_server_{net::EmbeddedTestServer::TYPE_HTTPS};
};
INSTANTIATE_TEST_SUITE_P(/* no prefix */,
WebViewSSLErrorTest,
testing::Bool(),
WebViewSSLErrorTest::DescribeParams);
// Test makes sure that an interstitial is shown in `<webview>` with an SSL
// error.
// Flaky on Win dbg: crbug.com/779973
#if BUILDFLAG(IS_WIN) && !defined(NDEBUG)
#define MAYBE_ShowInterstitialForSSLError DISABLED_ShowInterstitialForSSLError
#else
#define MAYBE_ShowInterstitialForSSLError ShowInterstitialForSSLError
#endif
IN_PROC_BROWSER_TEST_P(WebViewSSLErrorTest, MAYBE_ShowInterstitialForSSLError) {
SSLTestHelper();
}
// Ensure that when a guest is created and navigated to a URL that triggers an
// SSL interstitial, and then the "Back to safety" button is activated on the
// interstitial, the guest doesn't crash trying to load the NTP (the usual
// known-safe page used to navigate back from such interstitials when there's
// no other page in history to go to). See https://crbug.com/1444221.
IN_PROC_BROWSER_TEST_P(WebViewSSLErrorTest, NavigateBackFromSSLError) {
SSLTestHelper();
auto* guest = GetGuestViewManager()->GetLastGuestViewCreated();
// Simulate invoking the "Back to safety" button. This should dismiss the
// interstitial and navigate the guest to a known safe URL that can always
// load in a guest (in this case, about:blank).
security_interstitials::SecurityInterstitialTabHelper* helper =
security_interstitials::SecurityInterstitialTabHelper::FromWebContents(
guest->web_contents());
ASSERT_TRUE(helper);
auto* interstitial = helper->GetBlockingPageForFrame(
guest->GetGuestMainFrame()->GetFrameTreeNodeId());
ASSERT_TRUE(interstitial);
// Set observers for the navigation
content::TestNavigationObserver nav_observer(guest->web_contents(), 1);
nav_observer.set_wait_event(
content::TestNavigationObserver::WaitEvent::kNavigationFinished);
content::TestFrameNavigationObserver frame_nav_observer(
guest->GetGuestMainFrame());
// Give command to go back.
interstitial->CommandReceived(base::NumberToString(
security_interstitials::SecurityInterstitialCommand::CMD_DONT_PROCEED));
if (GetParam()) {
frame_nav_observer.Wait();
} else {
nav_observer.Wait();
}
ASSERT_FALSE(guest->GetGuestMainFrame()->IsErrorDocument());
ASSERT_FALSE(chrome_browser_interstitials::IsShowingInterstitial(
guest->web_contents()));
// We should be at the "safe" url now.
EXPECT_EQ(GURL(url::kAboutBlankURL),
guest->GetGuestMainFrame()->GetLastCommittedURL());
}
IN_PROC_BROWSER_TEST_P(WebViewSSLErrorTest, NavigateThroughSSLError) {
SSLTestHelper();
// Recreate `target_url` for use outside SSLTestHelper.
const auto target_url = https_server_.GetURL(
"/extensions/platform_apps/web_view/ssl/https_page.html");
auto* guest = GetGuestViewManager()->GetLastGuestViewCreated();
// Simulate invoking the "proceed" button. This should dismiss the
// interstitial and navigate the guest to the unsafe URL that was the target
// of the initial navigation.
security_interstitials::SecurityInterstitialTabHelper* helper =
security_interstitials::SecurityInterstitialTabHelper::FromWebContents(
guest->web_contents());
ASSERT_TRUE(helper);
auto* interstitial = helper->GetBlockingPageForFrame(
guest->GetGuestMainFrame()->GetFrameTreeNodeId());
ASSERT_TRUE(interstitial);
// Set observers for the navigation
content::TestNavigationObserver nav_observer(guest->web_contents(), 1);
nav_observer.set_wait_event(
content::TestNavigationObserver::WaitEvent::kNavigationFinished);
content::TestFrameNavigationObserver frame_nav_observer(
guest->GetGuestMainFrame());
// Give command to proceed.
interstitial->CommandReceived(base::NumberToString(
security_interstitials::SecurityInterstitialCommand::CMD_PROCEED));
if (GetParam()) {
frame_nav_observer.Wait();
} else {
nav_observer.Wait();
}
ASSERT_FALSE(guest->GetGuestMainFrame()->IsErrorDocument());
ASSERT_FALSE(chrome_browser_interstitials::IsShowingInterstitial(
guest->web_contents()));
// Make sure that "proceeding" took us to the expected url.
EXPECT_EQ(target_url, guest->GetGuestMainFrame()->GetLastCommittedURL());
}
// Test makes sure that the interstitial is registered in the
// `RenderWidgetHostInputEventRouter` when inside a `<webview>`.
// Flaky on Win dbg: crbug.com/779973
#if BUILDFLAG(IS_WIN) && !defined(NDEBUG)
#define MAYBE_InterstitialPageRouteEvents DISABLED_InterstitialPageRouteEvents
#else
#define MAYBE_InterstitialPageRouteEvents InterstitialPageRouteEvents
#endif
IN_PROC_BROWSER_TEST_P(WebViewSSLErrorTest, MAYBE_InterstitialPageRouteEvents) {
SSLTestHelper();
std::vector<content::RenderWidgetHostView*> hosts =
content::GetInputEventRouterRenderWidgetHostViews(
GetFirstAppWindowWebContents());
ASSERT_TRUE(base::Contains(
hosts, GetFirstAppWindowWebContents()->GetPrimaryMainFrame()->GetView()));
auto* guest_main_frame =
GetGuestViewManager()->GetLastGuestRenderFrameHostCreated();
ASSERT_TRUE(guest_main_frame);
ASSERT_TRUE(base::Contains(hosts, guest_main_frame->GetView()));
}
// Test makes sure that the browser does not crash when a `<webview>` navigates
// out of an interstitial caused by a SSL error.
// Flaky on Win dbg: crbug.com/779973
#if BUILDFLAG(IS_WIN) && !defined(NDEBUG)
#define MAYBE_InterstitialPageDetach DISABLED_InterstitialPageDetach
#else
#define MAYBE_InterstitialPageDetach InterstitialPageDetach
#endif
IN_PROC_BROWSER_TEST_P(WebViewSSLErrorTest, MAYBE_InterstitialPageDetach) {
SSLTestHelper();
// Navigate to about:blank
const GURL blank(url::kAboutBlankURL);
SetGuestURL(blank, /*expect_successful_navigation=*/true);
}
// This test makes sure the browser process does not crash if app is closed
// while an interstitial is being shown in guest.
// Flaky on Win dbg: crbug.com/779973
#if BUILDFLAG(IS_WIN) && !defined(NDEBUG)
#define MAYBE_InterstitialTearDown DISABLED_InterstitialTearDown
#else
#define MAYBE_InterstitialTearDown InterstitialTearDown
#endif
IN_PROC_BROWSER_TEST_P(WebViewSSLErrorTest, MAYBE_InterstitialTearDown) {
SSLTestHelper();
// Now close the app while the interstitial is being shown in the guest.
extensions::AppWindow* window = GetFirstAppWindow();
window->GetBaseWindow()->Close();
}
// This test makes sure the browser process does not crash if browser is shut
// down while an interstitial is being shown in guest.
IN_PROC_BROWSER_TEST_P(WebViewSSLErrorTest,
InterstitialTearDownOnBrowserShutdown) {
SSLTestHelper();
// Now close the app while the interstitial is being shown in the guest.
extensions::AppWindow* window = GetFirstAppWindow();
window->GetBaseWindow()->Close();
// The error page is not destroyed immediately, so the
// `RenderWidgetHostViewChildFrame` for it is still there, closing all
// renderer processes will cause the RWHVGuest's `RenderProcessGone()`
// shutdown path to be exercised.
chrome::CloseAllBrowsers();
}
// This allows us to specify URLs which trigger Safe Browsing.
class WebViewSafeBrowsingTest : public WebViewTest {
public:
WebViewSafeBrowsingTest()
: safe_browsing_factory_(
std::make_unique<safe_browsing::TestSafeBrowsingServiceFactory>()) {
}
void SetUpOnMainThread() override {
host_resolver()->AddRule("*", "127.0.0.1");
WebViewTest::SetUpOnMainThread();
}
protected:
void CreatedBrowserMainParts(
content::BrowserMainParts* browser_main_parts) override {
fake_safe_browsing_database_manager_ =
base::MakeRefCounted<safe_browsing::FakeSafeBrowsingDatabaseManager>(
content::GetUIThreadTaskRunner({}));
safe_browsing_factory_->SetTestDatabaseManager(
fake_safe_browsing_database_manager_.get());
safe_browsing::SafeBrowsingService::RegisterFactory(
safe_browsing_factory_.get());
WebViewTest::CreatedBrowserMainParts(browser_main_parts);
}
void TearDown() override {
WebViewTest::TearDown();
safe_browsing::SafeBrowsingService::RegisterFactory(nullptr);
}
void AddDangerousUrl(const GURL& dangerous_url) {
fake_safe_browsing_database_manager_->AddDangerousUrl(
dangerous_url, safe_browsing::SBThreatType::SB_THREAT_TYPE_URL_MALWARE);
}
private:
scoped_refptr<safe_browsing::FakeSafeBrowsingDatabaseManager>
fake_safe_browsing_database_manager_;
std::unique_ptr<safe_browsing::TestSafeBrowsingServiceFactory>
safe_browsing_factory_;
};
INSTANTIATE_TEST_SUITE_P(/* no prefix */,
WebViewSafeBrowsingTest,
testing::Bool(),
WebViewSafeBrowsingTest::DescribeParams);
IN_PROC_BROWSER_TEST_P(WebViewSafeBrowsingTest,
Shim_TestLoadAbortSafeBrowsing) {
SKIP_FOR_MPARCH(); // TODO(crbug.com/40202416): Enable test for MPArch.
// We start the test server here, instead of in TestHelper, because we need
// to know the URL to treat as dangerous before running the rest of the test.
ASSERT_TRUE(StartEmbeddedTestServer());
AddDangerousUrl(embedded_test_server()->GetURL("evil.com", "/title1.html"));
TestHelper("testLoadAbortSafeBrowsing", "web_view/shim", NO_TEST_SERVER);
}
// Tests that loading an HTTPS page in a guest <webview> with HTTPS-First Mode
// enabled doesn't crash nor shows error page.
// Regression test for crbug.com/1233889
IN_PROC_BROWSER_TEST_P(WebViewSSLErrorTest, GuestLoadsHttpsWithoutError) {
browser()->profile()->GetPrefs()->SetBoolean(prefs::kHttpsOnlyModeEnabled,
true);
https_server_.ServeFilesFromSourceDirectory(GetChromeTestDataDir());
ASSERT_TRUE(https_server_.Start());
GURL guest_url = https_server_.GetURL("/simple.html");
LoadAndLaunchPlatformApp("web_view/ssl", "EmbedderLoaded");
LoadEmptyGuest();
SetGuestURL(guest_url, /*expect_successful_navigation=*/true);
// Page should load without any error / crash.
auto* embedder_main_frame =
GetFirstAppWindowWebContents()->GetPrimaryMainFrame();
auto* guest_main_frame =
GetGuestViewManager()->GetLastGuestRenderFrameHostCreated();
ASSERT_FALSE(guest_main_frame->IsErrorDocument());
ASSERT_FALSE(embedder_main_frame->IsErrorDocument());
ASSERT_FALSE(chrome_browser_interstitials::IsShowingInterstitial(
GetFirstAppWindowWebContents()));
}
// Tests that loading an HTTP page in a guest <webview> with HTTPS-First Mode
// enabled doesn't crash and doesn't trigger the error page.
IN_PROC_BROWSER_TEST_P(WebViewSSLErrorTest, GuestLoadsHttpWithoutError) {
browser()->profile()->GetPrefs()->SetBoolean(prefs::kHttpsOnlyModeEnabled,
true);
ASSERT_TRUE(StartEmbeddedTestServer());
GURL guest_url = embedded_test_server()->GetURL("/simple.html");
LoadAndLaunchPlatformApp("web_view/ssl", "EmbedderLoaded");
LoadEmptyGuest();
SetGuestURL(guest_url, /*expect_successful_navigation=*/true);
// Page should load without any error / crash.
auto* embedder_main_frame =
GetFirstAppWindowWebContents()->GetPrimaryMainFrame();
auto* guest_main_frame =
GetGuestViewManager()->GetLastGuestRenderFrameHostCreated();
ASSERT_FALSE(guest_main_frame->IsErrorDocument());
ASSERT_FALSE(embedder_main_frame->IsErrorDocument());
ASSERT_FALSE(chrome_browser_interstitials::IsShowingInterstitial(
GetFirstAppWindowWebContents()));
}
// Verify that guests cannot be navigated to disallowed URLs, such as
// chrome:// URLs, directly via the content/public API. The enforcement for
// this typically happens in the embedder layer, catching cases where the
// embedder navigates a guest, but Chrome features could bypass that
// enforcement by directly navigating guests. This test verifies that if that
// were to happen, //content would still gracefully disallow attempts to load
// disallowed URLs in guests without crashing.
IN_PROC_BROWSER_TEST_P(WebViewTest, CannotNavigateGuestToChromeURL) {
ASSERT_TRUE(StartEmbeddedTestServer());
// Load an app with a <webview> guest that starts at a data: URL.
LoadAppWithGuest("web_view/simple");
auto* guest = GetGuestViewManager()->GetLastGuestViewCreated();
auto* guest_main_frame = guest->GetGuestMainFrame();
GURL original_url = guest_main_frame->GetLastCommittedURL();
// Try to navigate <webview> to a chrome: URL directly.
GURL chrome_url(chrome::kChromeUINewTabURL);
content::TestFrameNavigationObserver observer(guest_main_frame);
guest->GetController().LoadURL(chrome_url, content::Referrer(),
ui::PAGE_TRANSITION_AUTO_TOPLEVEL,
std::string());
// The navigation should be aborted, and the last committed URL should
// remain unchanged.
EXPECT_FALSE(observer.navigation_started());
EXPECT_EQ(original_url, guest_main_frame->GetLastCommittedURL());
EXPECT_NE(chrome_url, guest_main_frame->GetLastCommittedURL());
}
IN_PROC_BROWSER_TEST_P(WebViewTest, ShimSrcAttribute) {
// TODO(crbug.com/40202416): Re-enable after fixing MPArch-related flakiness.
SKIP_FOR_MPARCH();
ASSERT_TRUE(RunExtensionTest("platform_apps/web_view/src_attribute",
{.launch_as_platform_app = true}))
<< message_;
}
// This test verifies that prerendering has been disabled inside <webview>.
// This test is here rather than in PrerenderBrowserTest for testing convenience
// only. If it breaks then this is a bug in the prerenderer.
IN_PROC_BROWSER_TEST_P(WebViewTest, NoPrerenderer) {
ASSERT_TRUE(StartEmbeddedTestServer());
LoadAndLaunchPlatformApp("web_view/noprerenderer", "guest-loaded");
auto* guest_rfh =
GetGuestViewManager()->WaitForSingleGuestRenderFrameHostCreated();
ASSERT_TRUE(guest_rfh);
NoStatePrefetchLinkManager* no_state_prefetch_link_manager =
NoStatePrefetchLinkManagerFactory::GetForBrowserContext(
guest_rfh->GetBrowserContext());
ASSERT_TRUE(no_state_prefetch_link_manager != nullptr);
EXPECT_TRUE(no_state_prefetch_link_manager->IsEmpty());
}
// Verify that existing <webview>'s are detected when the task manager starts
// up.
IN_PROC_BROWSER_TEST_P(WebViewTest, TaskManagerExistingWebView) {
ASSERT_TRUE(StartEmbeddedTestServer());
LoadAndLaunchPlatformApp("web_view/task_manager", "guest-loaded");
ASSERT_TRUE(
GetGuestViewManager()->WaitForSingleGuestRenderFrameHostCreated());
chrome::ShowTaskManager(browser()); // Show task manager AFTER guest loads.
const char* guest_title = "WebViewed test content";
const char* app_name = "<webview> task manager test";
ASSERT_NO_FATAL_FAILURE(WaitForTaskManagerRows(1, MatchWebView(guest_title)));
ASSERT_NO_FATAL_FAILURE(WaitForTaskManagerRows(1, MatchAboutBlankTab()));
ASSERT_NO_FATAL_FAILURE(WaitForTaskManagerRows(1, MatchApp(app_name)));
ASSERT_NO_FATAL_FAILURE(WaitForTaskManagerRows(1, MatchBackground(app_name)));
ASSERT_NO_FATAL_FAILURE(WaitForTaskManagerRows(1, MatchAnyWebView()));
ASSERT_NO_FATAL_FAILURE(WaitForTaskManagerRows(1, MatchAnyTab()));
ASSERT_NO_FATAL_FAILURE(WaitForTaskManagerRows(1, MatchAnyApp()));
ASSERT_NO_FATAL_FAILURE(WaitForTaskManagerRows(1, MatchAnyBackground()));
}
// Verify that the task manager notices the creation of new <webview>'s.
IN_PROC_BROWSER_TEST_P(WebViewTest, TaskManagerNewWebView) {
ASSERT_TRUE(StartEmbeddedTestServer());
chrome::ShowTaskManager(browser()); // Show task manager BEFORE guest loads.
LoadAndLaunchPlatformApp("web_view/task_manager", "guest-loaded");
ASSERT_TRUE(
GetGuestViewManager()->WaitForSingleGuestRenderFrameHostCreated());
const char* guest_title = "WebViewed test content";
const char* app_name = "<webview> task manager test";
ASSERT_NO_FATAL_FAILURE(WaitForTaskManagerRows(1, MatchWebView(guest_title)));
ASSERT_NO_FATAL_FAILURE(WaitForTaskManagerRows(1, MatchAboutBlankTab()));
ASSERT_NO_FATAL_FAILURE(WaitForTaskManagerRows(1, MatchApp(app_name)));
ASSERT_NO_FATAL_FAILURE(WaitForTaskManagerRows(1, MatchBackground(app_name)));
ASSERT_NO_FATAL_FAILURE(WaitForTaskManagerRows(1, MatchAnyWebView()));
ASSERT_NO_FATAL_FAILURE(WaitForTaskManagerRows(1, MatchAnyTab()));
ASSERT_NO_FATAL_FAILURE(WaitForTaskManagerRows(1, MatchAnyApp()));
ASSERT_NO_FATAL_FAILURE(WaitForTaskManagerRows(1, MatchAnyBackground()));
}
// The guest tasks should show up again after re-opening the task manager.
IN_PROC_BROWSER_TEST_P(WebViewTest, TaskManagerShowAndHide) {
ASSERT_TRUE(StartEmbeddedTestServer());
LoadAndLaunchPlatformApp("web_view/task_manager", "guest-loaded");
ASSERT_TRUE(
GetGuestViewManager()->WaitForSingleGuestRenderFrameHostCreated());
const char* guest_title = "WebViewed test content";
{
SCOPED_TRACE("first show");
chrome::ShowTaskManager(browser());
ASSERT_NO_FATAL_FAILURE(
WaitForTaskManagerRows(1, MatchWebView(guest_title)));
}
chrome::HideTaskManager();
{
SCOPED_TRACE("second show");
chrome::ShowTaskManager(browser());
ASSERT_NO_FATAL_FAILURE(
WaitForTaskManagerRows(1, MatchWebView(guest_title)));
}
}
IN_PROC_BROWSER_TEST_P(WebViewTest, TaskEntryDeletedAfterGuestKilled) {
ASSERT_TRUE(StartEmbeddedTestServer());
LoadAndLaunchPlatformApp("web_view/task_manager", "guest-loaded");
ASSERT_TRUE(
GetGuestViewManager()->WaitForSingleGuestRenderFrameHostCreated());
const char* guest_title = "WebViewed test content";
ASSERT_NO_FATAL_FAILURE(WaitForTaskManagerRows(1, MatchWebView(guest_title)));
{
content::RenderFrameHostWrapper crashed(
GetGuestViewManager()->GetLastGuestRenderFrameHostCreated());
content::RenderProcessHostWatcher crashed_obs(
crashed->GetProcess(),
content::RenderProcessHostWatcher::WATCH_FOR_PROCESS_EXIT);
crashed->GetProcess()->Shutdown(content::RESULT_CODE_KILLED);
crashed_obs.Wait();
ASSERT_TRUE(crashed.WaitUntilRenderFrameDeleted());
}
ASSERT_NO_FATAL_FAILURE(WaitForTaskManagerRows(0, MatchAnyWebView()));
}
// This tests cookie isolation for packaged apps with webview tags. It navigates
// the main browser window to a page that sets a cookie and loads an app with
// multiple webview tags. Each tag sets a cookie and the test checks the proper
// storage isolation is enforced.
IN_PROC_BROWSER_TEST_P(WebViewTest, CookieIsolation) {
ASSERT_TRUE(StartEmbeddedTestServer());
// Navigate the browser to a page which writes a sample cookie
// The cookie is "testCookie=1"
GURL set_cookie_url = embedded_test_server()->GetURL(
"/extensions/platform_apps/web_view/cookie_isolation/set_cookie.html");
GURL::Replacements replace_host;
replace_host.SetHostStr("localhost");
set_cookie_url = set_cookie_url.ReplaceComponents(replace_host);
ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), set_cookie_url));
ASSERT_TRUE(RunExtensionTest("platform_apps/web_view/cookie_isolation",
{.launch_as_platform_app = true}))
<< message_;
// Finally, verify that the browser cookie has not changed.
int cookie_size;
std::string cookie_value;
ui_test_utils::GetCookies(GURL("http://localhost"),
browser()->tab_strip_model()->GetWebContentsAt(0),
&cookie_size, &cookie_value);
EXPECT_EQ("testCookie=1", cookie_value);
}
// This tests that in-memory storage partitions are reset on browser restart,
// but persistent ones maintain state for cookies and HTML5 storage.
IN_PROC_BROWSER_TEST_P(WebViewTest, PRE_StoragePersistence) {
ASSERT_TRUE(StartEmbeddedTestServer());
// We don't care where the main browser is on this test.
ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), GURL("about:blank")));
ASSERT_TRUE(RunExtensionTest(
"platform_apps/web_view/storage_persistence",
{.custom_arg = "PRE_StoragePersistence", .launch_as_platform_app = true}))
<< message_;
content::EnsureCookiesFlushed(profile());
}
// This is the post-reset portion of the StoragePersistence test. See
// PRE_StoragePersistence for main comment.
IN_PROC_BROWSER_TEST_P(WebViewTest, StoragePersistence) {
ASSERT_TRUE(StartEmbeddedTestServer());
// We don't care where the main browser is on this test.
ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), GURL("about:blank")));
ASSERT_TRUE(RunExtensionTest(
"platform_apps/web_view/storage_persistence",
{.custom_arg = "StoragePersistence", .launch_as_platform_app = true}))
<< message_;
}
// This tests DOM storage isolation for packaged apps with webview tags. It
// loads an app with multiple webview tags and each tag sets DOM storage
// entries, which the test checks to ensure proper storage isolation is
// enforced.
IN_PROC_BROWSER_TEST_P(WebViewTest, DOMStorageIsolation) {
ASSERT_TRUE(StartEmbeddedTestServer());
GURL navigate_to_url = embedded_test_server()->GetURL(
"/extensions/platform_apps/web_view/dom_storage_isolation/page.html");
GURL::Replacements replace_host;
replace_host.SetHostStr("localhost");
navigate_to_url = navigate_to_url.ReplaceComponents(replace_host);
ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), navigate_to_url));
ASSERT_TRUE(RunExtensionTest("platform_apps/web_view/dom_storage_isolation",
{.launch_as_platform_app = true}));
// Verify that the browser tab's local/session storage does not have the same
// values which were stored by the webviews.
std::string get_local_storage(
"window.localStorage.getItem('foo') || 'badval'");
std::string get_session_storage(
"window.localStorage.getItem('baz') || 'badval'");
EXPECT_EQ("badval",
content::EvalJs(browser()->tab_strip_model()->GetWebContentsAt(0),
get_local_storage));
EXPECT_EQ("badval",
content::EvalJs(browser()->tab_strip_model()->GetWebContentsAt(0),
get_session_storage));
}
// This tests how guestviews should or should not be able to find each other
// depending on whether they are in the same storage partition or not.
// This is a regression test for https://crbug.com/794079 (where two guestviews
// in the same storage partition stopped being able to find each other).
// This is also a regression test for https://crbug.com/802278 (setting of
// a guestview as an opener should not leak any memory).
IN_PROC_BROWSER_TEST_P(WebViewTest, FindabilityIsolation) {
ASSERT_TRUE(StartEmbeddedTestServer());
GURL navigate_to_url = embedded_test_server()->GetURL(
"/extensions/platform_apps/web_view/findability_isolation/page.html");
GURL::Replacements replace_host;
replace_host.SetHostStr("localhost");
navigate_to_url = navigate_to_url.ReplaceComponents(replace_host);
ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), navigate_to_url));
ASSERT_TRUE(RunExtensionTest("platform_apps/web_view/findability_isolation",
{.launch_as_platform_app = true}));
}
// This tests IndexedDB isolation for packaged apps with webview tags. It loads
// an app with multiple webview tags and each tag creates an IndexedDB record,
// which the test checks to ensure proper storage isolation is enforced.
IN_PROC_BROWSER_TEST_P(WebViewTest, IndexedDBIsolation) {
ASSERT_TRUE(StartEmbeddedTestServer());
ASSERT_TRUE(RunExtensionTest("platform_apps/web_view/isolation_indexeddb",
{.launch_as_platform_app = true}))
<< message_;
}
// This test ensures that closing app window on 'loadcommit' does not crash.
// The test launches an app with guest and closes the window on loadcommit. It
// then launches the app window again. The process is repeated 3 times.
// TODO(crbug.com/40621838): The test is flaky (crash) on ChromeOS debug and
// ASan/LSan
#if BUILDFLAG(IS_CHROMEOS) && (!defined(NDEBUG) || defined(ADDRESS_SANITIZER))
#define MAYBE_CloseOnLoadcommit DISABLED_CloseOnLoadcommit
#else
#define MAYBE_CloseOnLoadcommit CloseOnLoadcommit
#endif
IN_PROC_BROWSER_TEST_P(WebViewTest, MAYBE_CloseOnLoadcommit) {
LoadAndLaunchPlatformApp("web_view/close_on_loadcommit",
"done-close-on-loadcommit");
}
IN_PROC_BROWSER_TEST_P(WebViewTest, MediaAccessAPIDeny_TestDeny) {
MediaAccessAPIDenyTestHelper("testDeny");
}
IN_PROC_BROWSER_TEST_P(WebViewTest,
MediaAccessAPIDeny_TestDenyThenAllowThrows) {
MediaAccessAPIDenyTestHelper("testDenyThenAllowThrows");
}
IN_PROC_BROWSER_TEST_P(WebViewTest,
MediaAccessAPIDeny_TestDenyWithPreventDefault) {
MediaAccessAPIDenyTestHelper("testDenyWithPreventDefault");
}
IN_PROC_BROWSER_TEST_P(WebViewTest,
MediaAccessAPIDeny_TestNoListenersImplyDeny) {
MediaAccessAPIDenyTestHelper("testNoListenersImplyDeny");
}
IN_PROC_BROWSER_TEST_P(WebViewTest,
MediaAccessAPIDeny_TestNoPreventDefaultImpliesDeny) {
MediaAccessAPIDenyTestHelper("testNoPreventDefaultImpliesDeny");
}
void WebViewTestBase::MediaAccessAPIAllowTestHelper(
const std::string& test_name) {
ASSERT_TRUE(StartEmbeddedTestServer()); // For serving guest pages.
LoadAndLaunchPlatformApp("web_view/media_access/allow", "Launched");
content::WebContents* embedder_web_contents = GetFirstAppWindowWebContents();
ASSERT_TRUE(embedder_web_contents);
std::unique_ptr<MockWebContentsDelegate> mock(new MockWebContentsDelegate());
embedder_web_contents->SetDelegate(mock.get());
ExtensionTestMessageListener done_listener("TEST_PASSED");
done_listener.set_failure_message("TEST_FAILED");
EXPECT_TRUE(
content::ExecJs(embedder_web_contents,
base::StrCat({"startAllowTest('", test_name, "')"})));
ASSERT_TRUE(done_listener.WaitUntilSatisfied());
mock->WaitForRequestMediaPermission();
}
IN_PROC_BROWSER_TEST_P(WebViewTest, OpenURLFromTab_CurrentTab_Abort) {
LoadAppWithGuest("web_view/simple");
// Verify that OpenURLFromTab with a window disposition of CURRENT_TAB will
// navigate the current <webview>.
ExtensionTestMessageListener load_listener("WebViewTest.LOADSTOP");
// Navigating to a file URL is forbidden inside a <webview>.
content::OpenURLParams params(GURL("file://foo"), content::Referrer(),
WindowOpenDisposition::CURRENT_TAB,
ui::PAGE_TRANSITION_AUTO_TOPLEVEL,
true /* is_renderer_initiated */);
params.source_render_frame_id = GetGuestRenderFrameHost()->GetRoutingID();
params.source_render_process_id =
GetGuestRenderFrameHost()->GetProcess()->GetID().GetUnsafeValue();
GetGuestWebContents()->OpenURL(params, /*navigation_handle_callback=*/{});
ASSERT_TRUE(load_listener.WaitUntilSatisfied());
// Verify that the <webview> ends up at about:blank.
EXPECT_EQ(GURL(url::kAboutBlankURL),
GetGuestRenderFrameHost()->GetLastCommittedURL());
}
// A navigation to a web-safe URL should succeed, even if it is not renderer-
// initiated, such as a navigation from the PDF viewer.
IN_PROC_BROWSER_TEST_P(WebViewTest, OpenURLFromTab_CurrentTab_Succeed) {
LoadAppWithGuest("web_view/simple");
// Verify that OpenURLFromTab with a window disposition of CURRENT_TAB will
// navigate the current <webview>.
ExtensionTestMessageListener load_listener("WebViewTest.LOADSTOP");
GURL test_url("http://www.google.com");
content::OpenURLParams params(
test_url, content::Referrer(), WindowOpenDisposition::CURRENT_TAB,
ui::PAGE_TRANSITION_AUTO_TOPLEVEL, false /* is_renderer_initiated */);
params.source_render_frame_id = GetGuestRenderFrameHost()->GetRoutingID();
params.source_render_process_id =
GetGuestRenderFrameHost()->GetProcess()->GetID().GetUnsafeValue();
GetGuestWebContents()->OpenURL(params, /*navigation_handle_callback=*/{});
ASSERT_TRUE(load_listener.WaitUntilSatisfied());
EXPECT_EQ(test_url, GetGuestRenderFrameHost()->GetLastCommittedURL());
}
IN_PROC_BROWSER_TEST_P(WebViewNewWindowTest, OpenURLFromTab_NewWindow_Abort) {
LoadAppWithGuest("web_view/simple");
// Verify that OpenURLFromTab with a window disposition of NEW_BACKGROUND_TAB
// will trigger the <webview>'s New Window API.
ExtensionTestMessageListener new_window_listener("WebViewTest.NEWWINDOW");
// Navigating to a file URL is forbidden inside a <webview>.
content::OpenURLParams params(GURL("file://foo"), content::Referrer(),
WindowOpenDisposition::NEW_BACKGROUND_TAB,
ui::PAGE_TRANSITION_AUTO_TOPLEVEL,
true /* is_renderer_initiated */);
params.source_render_frame_id = GetGuestRenderFrameHost()->GetRoutingID();
params.source_render_process_id =
GetGuestRenderFrameHost()->GetProcess()->GetID().GetUnsafeValue();
GetGuestWebContents()->OpenURL(params, /*navigation_handle_callback=*/{});
ASSERT_TRUE(new_window_listener.WaitUntilSatisfied());
// Verify that a new guest was created.
content::RenderFrameHost* new_guest_rfh =
GetGuestViewManager()->GetLastGuestRenderFrameHostCreated();
EXPECT_NE(GetGuestRenderFrameHost(), new_guest_rfh);
// Verify that the new <webview> guest ends up at about:blank.
EXPECT_EQ(GURL(url::kAboutBlankURL), new_guest_rfh->GetLastCommittedURL());
}
// Verify that we handle gracefully having two webviews in the same
// BrowsingInstance with COOP values that would normally make it impossible
// (meaning outside of webviews special case) to group them together.
// This is a regression test for https://crbug.com/1243711.
IN_PROC_BROWSER_TEST_P(WebViewNewWindowTest,
NewWindow_DifferentCoopStatesInRelatedWebviews) {
// Reusing testNewWindowAndUpdateOpener because it is a convenient way to
// obtain 2 webviews in the same BrowsingInstance. The javascript does
// nothing more than that.
TestHelper("testNewWindowAndUpdateOpener", "web_view/newwindow",
NEEDS_TEST_SERVER);
GetGuestViewManager()->WaitForNumGuestsCreated(2);
std::vector<content::RenderFrameHost*> guest_rfh_list;
GetGuestViewManager()->GetGuestRenderFrameHostList(&guest_rfh_list);
ASSERT_EQ(2u, guest_rfh_list.size());
content::RenderFrameHost* guest1 = guest_rfh_list[0];
content::RenderFrameHost* guest2 = guest_rfh_list[1];
ASSERT_NE(guest1, guest2);
// COOP headers are only served over HTTPS. Instantiate an HTTPS server.
net::EmbeddedTestServer https_server(net::EmbeddedTestServer::TYPE_HTTPS);
https_server.SetSSLConfig(net::EmbeddedTestServer::CERT_OK);
https_server.AddDefaultHandlers(GetChromeTestDataDir());
ASSERT_TRUE(https_server.Start());
// Navigate one of the <webview> to a COOP: Same-Origin page.
GURL coop_url(
https_server.GetURL("/set-header?"
"Cross-Origin-Opener-Policy: same-origin"));
// We should not crash trying to load the COOP page.
EXPECT_TRUE(content::NavigateToURLFromRenderer(guest2, coop_url));
}
// This test creates a situation where we have two unattached webviews which
// have an opener relationship, and ensures that we can shutdown safely. See
// https://crbug.com/1450397.
IN_PROC_BROWSER_TEST_P(WebViewNewWindowTest, DestroyOpenerBeforeAttachment) {
// This test doesn't work with MPArch based <webview>s as they can't navigate
// before attachment is complete. The scenario this test attempts to repro is
// not possible if the guest can't navigate before attachment (it will not be
// able to open a window before attachment).
// TODO(crbug.com/40202416): Remove this test entirely when we remove the
// inner WebContents implementation.
SKIP_FOR_MPARCH();
TestHelper("testDestroyOpenerBeforeAttachment", "web_view/newwindow",
NEEDS_TEST_SERVER);
GetGuestViewManager()->WaitForNumGuestsCreated(2);
content::RenderProcessHost* embedder_rph =
GetEmbedderWebContents()->GetPrimaryMainFrame()->GetProcess();
content::RenderProcessHostWatcher kill_observer(
embedder_rph, content::RenderProcessHostWatcher::WATCH_FOR_PROCESS_EXIT);
EXPECT_TRUE(embedder_rph->Shutdown(content::RESULT_CODE_KILLED));
kill_observer.Wait();
}
IN_PROC_BROWSER_TEST_P(WebViewTest, ContextMenuInspectElement) {
LoadAppWithGuest("web_view/context_menus/basic");
content::RenderFrameHost* guest_rfh = GetGuestRenderFrameHost();
ASSERT_TRUE(guest_rfh);
content::ContextMenuParams params;
TestRenderViewContextMenu menu(*guest_rfh, params);
menu.Init();
// Expect "Inspect" to be shown as we are running webview in a chrome app.
EXPECT_TRUE(menu.IsItemPresent(IDC_CONTENT_CONTEXT_INSPECTELEMENT));
}
#if BUILDFLAG(IS_CHROMEOS)
class WebViewChromeOSTest : public WebViewTestBase,
public testing::WithParamInterface<bool> {
public:
WebViewChromeOSTest() {
scoped_feature_list_.InitWithFeatureStates(
{{features::kGuestViewMPArch, GetParam()}});
}
~WebViewChromeOSTest() override = default;
static std::string DescribeParams(
const testing::TestParamInfo<ParamType>& info) {
return base::StringPrintf("%s", info.param ? "MPArch" : "InnerWebContents");
}
private:
base::test::ScopedFeatureList scoped_feature_list_;
};
INSTANTIATE_TEST_SUITE_P(WebViewTests,
WebViewChromeOSTest,
testing::Bool(),
WebViewChromeOSTest::DescribeParams);
#endif
// This test executes the context menu command 'LanguageSettings'.
// On Ash, this will open the language settings in the OS Settings app.
// Elsewhere, it will load chrome://settings/languages in a browser window.
// In either case, this is a browser-initiated operation and so we expect it
// to succeed if the embedder is allowed to perform the operation.
#if BUILDFLAG(IS_CHROMEOS)
IN_PROC_BROWSER_TEST_P(WebViewChromeOSTest, ContextMenuLanguageSettings) {
#else
IN_PROC_BROWSER_TEST_P(WebViewTest, ContextMenuLanguageSettings) {
#endif
LoadAppWithGuest("web_view/context_menus/basic");
content::WebContents* embedder = GetEmbedderWebContents();
ASSERT_TRUE(embedder);
#if BUILDFLAG(IS_CHROMEOS)
ash::SystemWebAppManager::Get(browser()->profile())
->InstallSystemAppsForTesting();
#endif
content::WebContentsAddedObserver web_contents_added_observer;
GURL page_url("http://www.google.com");
std::unique_ptr<TestRenderViewContextMenu> menu(
TestRenderViewContextMenu::Create(GetGuestRenderFrameHost(), page_url));
menu->ExecuteCommand(IDC_CONTENT_CONTEXT_LANGUAGE_SETTINGS, 0);
// Verify that a new WebContents has been created that is at the appropriate
// Language Settings page.
content::WebContents* new_contents =
web_contents_added_observer.GetWebContents();
#if BUILDFLAG(IS_CHROMEOS)
EXPECT_EQ(GURL(chrome::kChromeUIOSSettingsURL)
.Resolve(chromeos::settings::mojom::kLanguagesSubpagePath),
new_contents->GetVisibleURL());
#else
EXPECT_EQ(GURL(chrome::kChromeUISettingsURL)
.Resolve(chrome::kLanguageOptionsSubPage),
new_contents->GetVisibleURL());
#endif
}
IN_PROC_BROWSER_TEST_P(WebViewTest, ContextMenusAPI_Basic) {
LoadAppWithGuest("web_view/context_menus/basic");
content::WebContents* embedder = GetEmbedderWebContents();
ASSERT_TRUE(embedder);
// 1. Basic property test.
ExecuteScriptWaitForTitle(embedder, "checkProperties()", "ITEM_CHECKED");
// 2. Create a menu item and wait for created callback to be called.
ExecuteScriptWaitForTitle(embedder, "createMenuItem()", "ITEM_CREATED");
// 3. Click the created item, wait for the click handlers to fire from JS.
ExtensionTestMessageListener click_listener("ITEM_CLICKED");
GURL page_url("http://www.google.com");
// Create and build our test context menu.
std::unique_ptr<TestRenderViewContextMenu> menu(
TestRenderViewContextMenu::Create(GetGuestRenderFrameHost(), page_url));
// Look for the extension item in the menu, and execute it.
int command_id = ContextMenuMatcher::ConvertToExtensionsCustomCommandId(0);
ASSERT_TRUE(menu->IsCommandIdEnabled(command_id));
menu->ExecuteCommand(command_id, 0);
// Wait for embedder's script to tell us its onclick fired, it does
// chrome.test.sendMessage('ITEM_CLICKED')
ASSERT_TRUE(click_listener.WaitUntilSatisfied());
// 4. Update the item's title and verify.
ExecuteScriptWaitForTitle(embedder, "updateMenuItem()", "ITEM_UPDATED");
MenuItem::List items = GetItems();
ASSERT_EQ(1u, items.size());
MenuItem* item = items.at(0);
EXPECT_EQ("new_title", item->title());
// 5. Remove the item.
ExecuteScriptWaitForTitle(embedder, "removeItem()", "ITEM_REMOVED");
MenuItem::List items_after_removal = GetItems();
ASSERT_EQ(0u, items_after_removal.size());
// 6. Add some more items.
ExecuteScriptWaitForTitle(
embedder, "createThreeMenuItems()", "ITEM_MULTIPLE_CREATED");
MenuItem::List items_after_insertion = GetItems();
ASSERT_EQ(3u, items_after_insertion.size());
// 7. Test removeAll().
ExecuteScriptWaitForTitle(embedder, "removeAllItems()", "ITEM_ALL_REMOVED");
MenuItem::List items_after_all_removal = GetItems();
ASSERT_EQ(0u, items_after_all_removal.size());
}
IN_PROC_BROWSER_TEST_P(WebViewTest, ContextMenusAPI_PreventDefault) {
LoadAppWithGuest("web_view/context_menus/basic");
auto* guest_main_frame =
GetGuestViewManager()->GetLastGuestRenderFrameHostCreated();
ASSERT_TRUE(guest_main_frame);
content::WebContents* embedder = GetEmbedderWebContents();
ASSERT_TRUE(embedder);
// Add a preventDefault() call on context menu event so context menu
// does not show up.
ExtensionTestMessageListener prevent_default_listener(
"WebViewTest.CONTEXT_MENU_DEFAULT_PREVENTED");
EXPECT_TRUE(content::ExecJs(embedder, "registerPreventDefault()"));
ContextMenuShownObserver context_menu_shown_observer;
OpenContextMenu(guest_main_frame);
EXPECT_TRUE(prevent_default_listener.WaitUntilSatisfied());
// Expect the menu to not show up.
EXPECT_EQ(false, context_menu_shown_observer.shown());
// Now remove the preventDefault() and expect context menu to be shown.
ExecuteScriptWaitForTitle(
embedder, "removePreventDefault()", "PREVENT_DEFAULT_LISTENER_REMOVED");
OpenContextMenu(guest_main_frame);
// We expect to see a context menu for the second call to |OpenContextMenu|.
context_menu_shown_observer.Wait();
EXPECT_EQ(true, context_menu_shown_observer.shown());
}
// Tests that a context menu is created when right-clicking in the webview. This
// also tests that the 'contextmenu' event is handled correctly.
IN_PROC_BROWSER_TEST_P(WebViewTest, TestContextMenu) {
LoadAppWithGuest("web_view/context_menus/basic");
auto* guest_main_frame =
GetGuestViewManager()->WaitForSingleGuestRenderFrameHostCreated();
ASSERT_TRUE(guest_main_frame);
auto close_menu_and_stop_run_loop = [](base::OnceClosure closure,
RenderViewContextMenu* context_menu) {
base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
FROM_HERE, base::BindOnce(&RenderViewContextMenuBase::Cancel,
base::Unretained(context_menu)));
base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
FROM_HERE, std::move(closure));
};
base::RunLoop run_loop;
RenderViewContextMenu::RegisterMenuShownCallbackForTesting(
base::BindOnce(close_menu_and_stop_run_loop, run_loop.QuitClosure()));
OpenContextMenu(guest_main_frame);
// Wait for the context menu to be visible.
run_loop.Run();
}
IN_PROC_BROWSER_TEST_P(WebViewTest, MediaAccessAPIAllow_TestAllow) {
MediaAccessAPIAllowTestHelper("testAllow");
}
IN_PROC_BROWSER_TEST_P(WebViewTest, MediaAccessAPIAllow_TestAllowAndThenDeny) {
MediaAccessAPIAllowTestHelper("testAllowAndThenDeny");
}
IN_PROC_BROWSER_TEST_P(WebViewTest, MediaAccessAPIAllow_TestAllowTwice) {
MediaAccessAPIAllowTestHelper("testAllowTwice");
}
IN_PROC_BROWSER_TEST_P(WebViewTest, MediaAccessAPIAllow_TestAllowAsync) {
MediaAccessAPIAllowTestHelper("testAllowAsync");
}
IN_PROC_BROWSER_TEST_P(WebViewTest, MediaAccessAPIAllow_TestCheck) {
ASSERT_TRUE(StartEmbeddedTestServer()); // For serving guest pages.
LoadAndLaunchPlatformApp("web_view/media_access/check", "Launched");
content::WebContents* embedder_web_contents = GetFirstAppWindowWebContents();
ASSERT_TRUE(embedder_web_contents);
std::unique_ptr<MockWebContentsDelegate> mock(new MockWebContentsDelegate());
embedder_web_contents->SetDelegate(mock.get());
ExtensionTestMessageListener done_listener("TEST_PASSED");
done_listener.set_failure_message("TEST_FAILED");
EXPECT_TRUE(content::ExecJs(embedder_web_contents, "startCheckTest('')"));
ASSERT_TRUE(done_listener.WaitUntilSatisfied());
mock->WaitForCheckMediaPermission();
}
// Checks that window.screenX/screenY/screenLeft/screenTop works correctly for
// guests.
IN_PROC_BROWSER_TEST_P(WebViewTest, ScreenCoordinates) {
ASSERT_TRUE(RunExtensionTest(
"platform_apps/web_view/common",
{.custom_arg = "screen_coordinates", .launch_as_platform_app = true}))
<< message_;
}
// TODO(crbug.com/40677344): This test leaks memory.
#if defined(LEAK_SANITIZER)
#define MAYBE_TearDownTest DISABLED_TearDownTest
#else
#define MAYBE_TearDownTest TearDownTest
#endif
IN_PROC_BROWSER_TEST_P(WebViewTest, MAYBE_TearDownTest) {
const extensions::Extension* extension =
LoadAndLaunchPlatformApp("web_view/simple", "WebViewTest.LAUNCHED");
extensions::AppWindow* window = nullptr;
if (!GetAppWindowCount())
window = CreateAppWindow(browser()->profile(), extension);
else
window = GetFirstAppWindow();
CloseAppWindow(window);
// Load the app again.
LoadAndLaunchPlatformApp("web_view/simple", "WebViewTest.LAUNCHED");
}
// Tests that an app can inject a content script into a webview, and that it can
// send cross-origin requests with CORS headers.
IN_PROC_BROWSER_TEST_P(WebViewTest, ContentScriptFetch) {
TestHelper("testContentScriptFetch", "web_view/content_script_fetch",
NEEDS_TEST_SERVER);
}
// In following GeolocationAPIEmbedderHasNoAccess* tests, embedder (i.e. the
// platform app) does not have geolocation permission for this test.
// No matter what the API does, geolocation permission would be denied.
// Note that the test name prefix must be "GeolocationAPI".
IN_PROC_BROWSER_TEST_P(WebViewTest, GeolocationAPIEmbedderHasNoAccessAllow) {
TestHelper("testDenyDenies",
"web_view/geolocation/embedder_has_no_permission",
NEEDS_TEST_SERVER);
}
IN_PROC_BROWSER_TEST_P(WebViewTest, GeolocationAPIEmbedderHasNoAccessDeny) {
TestHelper("testDenyDenies",
"web_view/geolocation/embedder_has_no_permission",
NEEDS_TEST_SERVER);
}
// In following GeolocationAPIEmbedderHasAccess* tests, embedder (i.e. the
// platform app) has geolocation permission
//
// Note that these are run separately because OverrideGeolocation() doesn't
// mock out geolocation for multiple navigator.geolocation calls properly and
// the tests become flaky.
//
// GeolocationAPI* test 1 of 3.
IN_PROC_BROWSER_TEST_P(WebViewTest, GeolocationAPIEmbedderHasAccessAllow) {
TestHelper("testAllow",
"web_view/geolocation/embedder_has_permission",
NEEDS_TEST_SERVER);
}
// GeolocationAPI* test 2 of 3.
IN_PROC_BROWSER_TEST_P(WebViewTest, GeolocationAPIEmbedderHasAccessDeny) {
TestHelper("testDeny",
"web_view/geolocation/embedder_has_permission",
NEEDS_TEST_SERVER);
}
// GeolocationAPI* test 3 of 3.
// Currently disabled until crbug.com/526788 is fixed.
IN_PROC_BROWSER_TEST_P(WebViewTest,
GeolocationAPIEmbedderHasAccessMultipleBridgeIdAllow) {
TestHelper("testMultipleBridgeIdAllow",
"web_view/geolocation/embedder_has_permission", NEEDS_TEST_SERVER);
}
IN_PROC_BROWSER_TEST_P(WebViewTest,
PermissionsAPIEmbedderHasAccessAllowGeolocation) {
TestHelper("testAllowGeolocation",
"web_view/permissions_test/embedder_has_permission",
NEEDS_TEST_SERVER);
}
IN_PROC_BROWSER_TEST_P(WebViewTest,
PermissionsAPIEmbedderHasAccessDenyGeolocation) {
TestHelper("testDenyGeolocation",
"web_view/permissions_test/embedder_has_permission",
NEEDS_TEST_SERVER);
}
IN_PROC_BROWSER_TEST_P(WebViewTest,
PermissionsAPIEmbedderHasAccessAllowCamera) {
TestHelper("testAllowCamera",
"web_view/permissions_test/embedder_has_permission",
NEEDS_TEST_SERVER);
}
IN_PROC_BROWSER_TEST_P(WebViewTest, PermissionsAPIEmbedderHasAccessDenyCamera) {
TestHelper("testDenyCamera",
"web_view/permissions_test/embedder_has_permission",
NEEDS_TEST_SERVER);
}
IN_PROC_BROWSER_TEST_P(WebViewTest,
PermissionsAPIEmbedderHasAccessAllowMicrophone) {
TestHelper("testAllowMicrophone",
"web_view/permissions_test/embedder_has_permission",
NEEDS_TEST_SERVER);
}
IN_PROC_BROWSER_TEST_P(WebViewTest,
PermissionsAPIEmbedderHasAccessDenyMicrophone) {
TestHelper("testDenyMicrophone",
"web_view/permissions_test/embedder_has_permission",
NEEDS_TEST_SERVER);
}
IN_PROC_BROWSER_TEST_P(WebViewTest, PermissionsAPIEmbedderHasAccessAllowMedia) {
TestHelper("testAllowMedia",
"web_view/permissions_test/embedder_has_permission",
NEEDS_TEST_SERVER);
}
IN_PROC_BROWSER_TEST_P(WebViewTest, PermissionsAPIEmbedderHasAccessDenyMedia) {
TestHelper("testDenyMedia",
"web_view/permissions_test/embedder_has_permission",
NEEDS_TEST_SERVER);
}
class MockHidDelegate : public ChromeHidDelegate {
public:
// Simulates opening the HID device chooser dialog and selecting an item. The
// chooser automatically selects the device under index 0.
void OnWebViewHidPermissionRequestCompleted(
base::WeakPtr<HidChooser> chooser,
content::GlobalRenderFrameHostId embedder_rfh_id,
std::vector<blink::mojom::HidDeviceFilterPtr> filters,
std::vector<blink::mojom::HidDeviceFilterPtr> exclusion_filters,
content::HidChooser::Callback callback,
bool allow) override {
if (!allow) {
std::move(callback).Run(std::vector<device::mojom::HidDeviceInfoPtr>());
return;
}
auto* render_frame_host = content::RenderFrameHost::FromID(embedder_rfh_id);
ASSERT_TRUE(render_frame_host);
chooser_controller_ = std::make_unique<HidChooserController>(
render_frame_host, std::move(filters), std::move(exclusion_filters),
std::move(callback));
mock_chooser_view_ =
std::make_unique<permissions::MockChooserControllerView>();
chooser_controller_->set_view(mock_chooser_view_.get());
EXPECT_CALL(*mock_chooser_view_.get(), OnOptionsInitialized)
.WillOnce(
testing::Invoke([this] { chooser_controller_->Select({0}); }));
}
private:
std::unique_ptr<HidChooserController> chooser_controller_;
std::unique_ptr<permissions::MockChooserControllerView> mock_chooser_view_;
};
class WebHidWebViewTest : public WebViewTest {
class TestContentBrowserClient : public ChromeContentBrowserClient {
public:
// ContentBrowserClient:
content::HidDelegate* GetHidDelegate() override { return &delegate_; }
private:
MockHidDelegate delegate_;
};
public:
WebHidWebViewTest() {
scoped_feature_list_.InitAndEnableFeature(
extensions_features::kEnableWebHidInWebView);
}
~WebHidWebViewTest() override {
content::SetBrowserClientForTesting(original_client_.get());
}
void SetUpOnMainThread() override {
WebViewTest::SetUpOnMainThread();
original_client_ = content::SetBrowserClientForTesting(&overriden_client_);
BindHidManager();
AddTestDevice();
}
void BindHidManager() {
mojo::PendingRemote<device::mojom::HidManager> pending_remote;
hid_manager_.Bind(pending_remote.InitWithNewPipeAndPassReceiver());
base::test::TestFuture<std::vector<device::mojom::HidDeviceInfoPtr>>
devices_future;
auto* chooser_context =
HidChooserContextFactory::GetForProfile(browser()->profile());
chooser_context->SetHidManagerForTesting(std::move(pending_remote),
devices_future.GetCallback());
EXPECT_TRUE(devices_future.Wait());
}
void AddTestDevice() {
hid_manager_.CreateAndAddDevice("1", 0, 0, "Test HID Device", "",
device::mojom::HidBusType::kHIDBusTypeUSB);
}
private:
TestContentBrowserClient overriden_client_;
raw_ptr<content::ContentBrowserClient> original_client_ = nullptr;
device::FakeHidManager hid_manager_;
base::test::ScopedFeatureList scoped_feature_list_;
};
INSTANTIATE_TEST_SUITE_P(/* no prefix */,
WebHidWebViewTest,
testing::Bool(),
WebHidWebViewTest::DescribeParams);
IN_PROC_BROWSER_TEST_P(WebHidWebViewTest,
PermissionsAPIEmbedderHasAccessAllowHid) {
ExtensionTestMessageListener activation_provider(
"performUserActivationInWebview");
activation_provider.SetOnSatisfied(
base::BindLambdaForTesting([&](const std::string&) {
// Activate the web view frame by executing a no-op script.
// This is needed because `requestDevice` method of HID API requires a
// window to satisfy the user activation requirement.
EXPECT_TRUE(content::ExecJs(
GetGuestViewManager()->GetLastGuestRenderFrameHostCreated(),
"// No-op script"));
}));
TestHelper("testAllowHid",
"web_view/permissions_test/embedder_has_permission",
NEEDS_TEST_SERVER);
}
IN_PROC_BROWSER_TEST_P(WebHidWebViewTest,
PermissionsAPIEmbedderHasAccessDenyHid) {
ExtensionTestMessageListener activation_provider(
"performUserActivationInWebview");
activation_provider.SetOnSatisfied(
base::BindLambdaForTesting([&](const std::string&) {
// Activate the web view frame by executing a no-op script.
// This is needed because `requestDevice` method of HID API requires a
// window to satisfy the user activation requirement.
EXPECT_TRUE(content::ExecJs(
GetGuestViewManager()->GetLastGuestRenderFrameHostCreated(),
"// No-op script"));
}));
TestHelper("testDenyHid", "web_view/permissions_test/embedder_has_permission",
NEEDS_TEST_SERVER);
}
// Tests that closing the app window before the HID request is answered will
// work correctly. This is meant to verify that no mojo callbacks will be
// dropped in such case.
IN_PROC_BROWSER_TEST_P(WebHidWebViewTest,
PermissionsAPIEmbedderHasAccessCloseWindowHid) {
ExtensionTestMessageListener activation_provider(
"performUserActivationInWebview");
activation_provider.SetOnSatisfied(
base::BindLambdaForTesting([&](const std::string&) {
// Activate the web view frame by executing a no-op script.
// This is needed because `requestDevice` method of HID API requires a
// window to satisfy the user activation requirement.
EXPECT_TRUE(content::ExecJs(
GetGuestViewManager()->GetLastGuestRenderFrameHostCreated(),
"// No-op script"));
}));
TestHelper("testHidCloseWindow",
"web_view/permissions_test/embedder_has_permission",
NEEDS_TEST_SERVER);
extensions::AppWindow* window = GetFirstAppWindow();
CloseAppWindow(window);
}
IN_PROC_BROWSER_TEST_P(WebViewTest,
PermissionsAPIEmbedderHasNoAccessAllowGeolocation) {
TestHelper("testAllowGeolocation",
"web_view/permissions_test/embedder_has_no_permission",
NEEDS_TEST_SERVER);
}
IN_PROC_BROWSER_TEST_P(WebViewTest,
PermissionsAPIEmbedderHasNoAccessDenyGeolocation) {
TestHelper("testDenyGeolocation",
"web_view/permissions_test/embedder_has_no_permission",
NEEDS_TEST_SERVER);
}
IN_PROC_BROWSER_TEST_P(WebViewTest,
PermissionsAPIEmbedderHasNoAccessAllowCamera) {
TestHelper("testAllowCamera",
"web_view/permissions_test/embedder_has_no_permission",
NEEDS_TEST_SERVER);
}
IN_PROC_BROWSER_TEST_P(WebViewTest,
PermissionsAPIEmbedderHasNoAccessDenyCamera) {
TestHelper("testDenyCamera",
"web_view/permissions_test/embedder_has_no_permission",
NEEDS_TEST_SERVER);
}
IN_PROC_BROWSER_TEST_P(WebViewTest,
PermissionsAPIEmbedderHasNoAccessAllowMicrophone) {
TestHelper("testAllowMicrophone",
"web_view/permissions_test/embedder_has_no_permission",
NEEDS_TEST_SERVER);
}
IN_PROC_BROWSER_TEST_P(WebViewTest,
PermissionsAPIEmbedderHasNoAccessDenyMicrophone) {
TestHelper("testDenyMicrophone",
"web_view/permissions_test/embedder_has_no_permission",
NEEDS_TEST_SERVER);
}
IN_PROC_BROWSER_TEST_P(WebViewTest,
PermissionsAPIEmbedderHasNoAccessAllowMedia) {
TestHelper("testAllowMedia",
"web_view/permissions_test/embedder_has_no_permission",
NEEDS_TEST_SERVER);
}
IN_PROC_BROWSER_TEST_P(WebViewTest,
PermissionsAPIEmbedderHasNoAccessDenyMedia) {
TestHelper("testDenyMedia",
"web_view/permissions_test/embedder_has_no_permission",
NEEDS_TEST_SERVER);
}
// Tests that
// BrowserPluginGeolocationPermissionContext::CancelGeolocationPermissionRequest
// is handled correctly (and does not crash).
IN_PROC_BROWSER_TEST_P(WebViewTest, GeolocationAPICancelGeolocation) {
ASSERT_TRUE(StartEmbeddedTestServer()); // For serving guest pages.
ASSERT_TRUE(
RunExtensionTest("platform_apps/web_view/geolocation/cancel_request",
{.launch_as_platform_app = true}))
<< message_;
}
IN_PROC_BROWSER_TEST_P(WebViewTest, DISABLED_GeolocationRequestGone) {
ASSERT_TRUE(StartEmbeddedTestServer()); // For serving guest pages.
ASSERT_TRUE(RunExtensionTest(
"platform_apps/web_view/geolocation/geolocation_request_gone",
{.launch_as_platform_app = true}))
<< message_;
}
// In following FilesystemAPIRequestFromMainThread* tests, guest request
// filesystem access from main thread of the guest.
// FileSystemAPIRequestFromMainThread* test 1 of 3
IN_PROC_BROWSER_TEST_P(WebViewTest, FileSystemAPIRequestFromMainThreadAllow) {
TestHelper("testAllow", "web_view/filesystem/main", NEEDS_TEST_SERVER);
}
// FileSystemAPIRequestFromMainThread* test 2 of 3.
IN_PROC_BROWSER_TEST_P(WebViewTest, FileSystemAPIRequestFromMainThreadDeny) {
TestHelper("testDeny", "web_view/filesystem/main", NEEDS_TEST_SERVER);
}
// FileSystemAPIRequestFromMainThread* test 3 of 3.
IN_PROC_BROWSER_TEST_P(WebViewTest,
FileSystemAPIRequestFromMainThreadDefaultAllow) {
TestHelper("testDefaultAllow", "web_view/filesystem/main", NEEDS_TEST_SERVER);
}
// In following FilesystemAPIRequestFromWorker* tests, guest create a worker
// to request filesystem access from worker thread.
// FileSystemAPIRequestFromWorker* test 1 of 3
IN_PROC_BROWSER_TEST_P(WebViewTest, FileSystemAPIRequestFromWorkerAllow) {
TestHelper("testAllow", "web_view/filesystem/worker", NEEDS_TEST_SERVER);
}
// FileSystemAPIRequestFromWorker* test 2 of 3.
IN_PROC_BROWSER_TEST_P(WebViewTest, FileSystemAPIRequestFromWorkerDeny) {
TestHelper("testDeny", "web_view/filesystem/worker", NEEDS_TEST_SERVER);
}
// FileSystemAPIRequestFromWorker* test 3 of 3.
IN_PROC_BROWSER_TEST_P(WebViewTest,
FileSystemAPIRequestFromWorkerDefaultAllow) {
TestHelper(
"testDefaultAllow", "web_view/filesystem/worker", NEEDS_TEST_SERVER);
}
// In following FilesystemAPIRequestFromSharedWorkerOfSingleWebViewGuest* tests,
// embedder contains a single webview guest. The guest creates a shared worker
// to request filesystem access from worker thread.
// FileSystemAPIRequestFromSharedWorkerOfSingleWebViewGuest* test 1 of 3
IN_PROC_BROWSER_TEST_P(
WebViewTest,
FileSystemAPIRequestFromSharedWorkerOfSingleWebViewGuestAllow) {
TestHelper("testAllow",
"web_view/filesystem/shared_worker/single",
NEEDS_TEST_SERVER);
}
// FileSystemAPIRequestFromSharedWorkerOfSingleWebViewGuest* test 2 of 3.
IN_PROC_BROWSER_TEST_P(
WebViewTest,
FileSystemAPIRequestFromSharedWorkerOfSingleWebViewGuestDeny) {
TestHelper("testDeny",
"web_view/filesystem/shared_worker/single",
NEEDS_TEST_SERVER);
}
// FileSystemAPIRequestFromSharedWorkerOfSingleWebViewGuest* test 3 of 3.
IN_PROC_BROWSER_TEST_P(
WebViewTest,
FileSystemAPIRequestFromSharedWorkerOfSingleWebViewGuestDefaultAllow) {
TestHelper(
"testDefaultAllow",
"web_view/filesystem/shared_worker/single",
NEEDS_TEST_SERVER);
}
// In following FilesystemAPIRequestFromSharedWorkerOfMultiWebViewGuests* tests,
// embedder contains mutiple webview guests. Each guest creates a shared worker
// to request filesystem access from worker thread.
// FileSystemAPIRequestFromSharedWorkerOfMultiWebViewGuests* test 1 of 3
IN_PROC_BROWSER_TEST_P(
WebViewTest,
FileSystemAPIRequestFromSharedWorkerOfMultiWebViewGuestsAllow) {
TestHelper("testAllow",
"web_view/filesystem/shared_worker/multiple",
NEEDS_TEST_SERVER);
}
// FileSystemAPIRequestFromSharedWorkerOfMultiWebViewGuests* test 2 of 3.
IN_PROC_BROWSER_TEST_P(
WebViewTest,
FileSystemAPIRequestFromSharedWorkerOfMultiWebViewGuestsDeny) {
TestHelper("testDeny",
"web_view/filesystem/shared_worker/multiple",
NEEDS_TEST_SERVER);
}
// FileSystemAPIRequestFromSharedWorkerOfMultiWebViewGuests* test 3 of 3.
IN_PROC_BROWSER_TEST_P(
WebViewTest,
FileSystemAPIRequestFromSharedWorkerOfMultiWebViewGuestsDefaultAllow) {
TestHelper(
"testDefaultAllow",
"web_view/filesystem/shared_worker/multiple",
NEEDS_TEST_SERVER);
}
IN_PROC_BROWSER_TEST_P(WebViewTest, ClearData) {
ASSERT_TRUE(StartEmbeddedTestServer()); // For serving guest pages.
ASSERT_TRUE(RunExtensionTest(
"platform_apps/web_view/common",
{.custom_arg = "cleardata", .launch_as_platform_app = true}))
<< message_;
}
IN_PROC_BROWSER_TEST_P(WebViewTest, ClearSessionCookies) {
ASSERT_TRUE(StartEmbeddedTestServer()); // For serving guest pages.
ASSERT_TRUE(RunExtensionTest(
"platform_apps/web_view/common",
{.custom_arg = "cleardata_session", .launch_as_platform_app = true}))
<< message_;
}
IN_PROC_BROWSER_TEST_P(WebViewTest, ClearPersistentCookies) {
ASSERT_TRUE(StartEmbeddedTestServer()); // For serving guest pages.
ASSERT_TRUE(RunExtensionTest(
"platform_apps/web_view/common",
{.custom_arg = "cleardata_persistent", .launch_as_platform_app = true}))
<< message_;
}
// Regression test for https://crbug.com/615429.
IN_PROC_BROWSER_TEST_P(WebViewTest, ClearDataTwice) {
ASSERT_TRUE(StartEmbeddedTestServer()); // For serving guest pages.
ASSERT_TRUE(RunExtensionTest(
"platform_apps/web_view/common",
{.custom_arg = "cleardata_twice", .launch_as_platform_app = true}))
<< message_;
}
#if BUILDFLAG(IS_WIN)
// Test is disabled on Windows because it fails often (~9% time)
// http://crbug.com/489088
#define MAYBE_ClearDataCache DISABLED_ClearDataCache
#else
#define MAYBE_ClearDataCache ClearDataCache
#endif
IN_PROC_BROWSER_TEST_P(WebViewTest, MAYBE_ClearDataCache) {
TestHelper("testClearCache", "web_view/clear_data_cache", NEEDS_TEST_SERVER);
}
IN_PROC_BROWSER_TEST_P(WebViewTest, ConsoleMessage) {
ASSERT_TRUE(RunExtensionTest(
"platform_apps/web_view/common",
{.custom_arg = "console_messages", .launch_as_platform_app = true}))
<< message_;
}
IN_PROC_BROWSER_TEST_P(WebViewTest, DownloadPermission) {
SKIP_FOR_MPARCH(); // TODO(crbug.com/40202416): Enable test for MPArch.
ASSERT_TRUE(StartEmbeddedTestServer()); // For serving guest pages.
LoadAndLaunchPlatformApp("web_view/download", "guest-loaded");
auto* guest_view_base =
GetGuestViewManager()->WaitForSingleGuestViewCreated();
ASSERT_TRUE(guest_view_base);
auto* guest_render_frame_host = guest_view_base->GetGuestMainFrame();
std::unique_ptr<content::DownloadTestObserver> completion_observer(
new content::DownloadTestObserverTerminal(
guest_render_frame_host->GetBrowserContext()->GetDownloadManager(), 1,
content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_FAIL));
// Replace WebContentsDelegate with mock version so we can intercept download
// requests.
std::unique_ptr<MockDownloadWebContentsDelegate> mock_delegate(
new MockDownloadWebContentsDelegate(guest_view_base));
guest_view_base->web_contents()->SetDelegate(mock_delegate.get());
// Start test.
// 1. Guest requests a download that its embedder denies.
EXPECT_TRUE(content::ExecJs(guest_render_frame_host,
"startDownload('download-link-1')"));
mock_delegate->WaitForCanDownload(false); // Expect to not allow.
mock_delegate->Reset();
// 2. Guest requests a download that its embedder allows.
EXPECT_TRUE(content::ExecJs(guest_render_frame_host,
"startDownload('download-link-2')"));
mock_delegate->WaitForCanDownload(true); // Expect to allow.
mock_delegate->Reset();
// 3. Guest requests a download that its embedder ignores, this implies deny.
EXPECT_TRUE(content::ExecJs(guest_render_frame_host,
"startDownload('download-link-3')"));
mock_delegate->WaitForCanDownload(false); // Expect to not allow.
completion_observer->WaitForFinished();
}
namespace {
const char kDownloadPathPrefix[] = "/download_cookie_isolation_test";
// EmbeddedTestServer request handler for use with DownloadCookieIsolation test.
// Responds with the next status code 200 if the 'Cookie' header sent with the
// request matches the query() part of the URL. Otherwise, fails the request
// with an HTTP 403. The body of the response is the value of the Cookie
// header.
std::unique_ptr<net::test_server::HttpResponse> HandleDownloadRequestWithCookie(
const net::test_server::HttpRequest& request) {
if (!base::StartsWith(request.relative_url, kDownloadPathPrefix,
base::CompareCase::SENSITIVE)) {
return nullptr;
}
std::string cookie_to_expect = request.GetURL().query();
const auto cookie_header_it = request.headers.find("cookie");
std::unique_ptr<net::test_server::BasicHttpResponse> response;
// Return a 403 if there's no cookie or if the cookie doesn't match.
if (cookie_header_it == request.headers.end() ||
cookie_header_it->second != cookie_to_expect) {
response = std::make_unique<net::test_server::BasicHttpResponse>();
response->set_code(net::HTTP_FORBIDDEN);
response->set_content_type("text/plain");
response->set_content("Forbidden");
return std::move(response);
}
// We have a cookie. Send some content along with the next status code.
response = std::make_unique<net::test_server::BasicHttpResponse>();
response->set_code(net::HTTP_OK);
response->set_content_type("application/octet-stream");
response->set_content(cookie_to_expect);
return std::move(response);
}
// Class for waiting for download manager to be initiailized.
class DownloadManagerWaiter : public content::DownloadManager::Observer {
public:
explicit DownloadManagerWaiter(content::DownloadManager* download_manager)
: initialized_(false), download_manager_(download_manager) {
download_manager_->AddObserver(this);
}
~DownloadManagerWaiter() override { download_manager_->RemoveObserver(this); }
void WaitForInitialized() {
if (initialized_ || download_manager_->IsManagerInitialized())
return;
base::RunLoop run_loop;
quit_closure_ = run_loop.QuitClosure();
run_loop.Run();
}
void OnManagerInitialized() override {
initialized_ = true;
if (quit_closure_)
std::move(quit_closure_).Run();
}
private:
base::OnceClosure quit_closure_;
bool initialized_;
raw_ptr<content::DownloadManager> download_manager_;
};
} // namespace
// Downloads initiated from isolated guest parititons should use their
// respective cookie stores. In addition, if those downloads are resumed, they
// should continue to use their respective cookie stores.
IN_PROC_BROWSER_TEST_P(WebViewTest, DownloadCookieIsolation) {
SKIP_FOR_MPARCH(); // TODO(crbug.com/40202416): Enable test for MPArch.
embedded_test_server()->RegisterRequestHandler(
base::BindRepeating(&HandleDownloadRequestWithCookie));
ASSERT_TRUE(StartEmbeddedTestServer()); // For serving guest pages.
LoadAndLaunchPlatformApp("web_view/download_cookie_isolation",
"created-webviews");
content::WebContents* web_contents = GetFirstAppWindowWebContents();
ASSERT_TRUE(web_contents);
content::DownloadManager* download_manager =
web_contents->GetBrowserContext()->GetDownloadManager();
scoped_refptr<content::TestFileErrorInjector> error_injector(
content::TestFileErrorInjector::Create(download_manager));
content::TestFileErrorInjector::FileErrorInfo error_info(
content::TestFileErrorInjector::FILE_OPERATION_STREAM_COMPLETE, 0,
download::DOWNLOAD_INTERRUPT_REASON_SERVER_FAILED);
error_info.stream_offset = 0;
error_injector->InjectError(error_info);
auto download_op = [&](std::string cookie) {
// DownloadTestObserverInterrupted does not seem to reliably wait for
// multiple failed downloads, so we perform one download at a time.
content::DownloadTestObserverInterrupted interrupted_observer(
download_manager, 1,
content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_FAIL);
EXPECT_TRUE(content::ExecJs(
web_contents,
base::StrCat(
{"startDownload('", cookie, "', '",
embedded_test_server()->GetURL(kDownloadPathPrefix).spec(),
"?cookie=", cookie, "')"})));
// This maps to DOWNLOAD_INTERRUPT_REASON_SERVER_FAILED.
interrupted_observer.WaitForFinished();
};
// Both downloads should fail due to the error that was injected above to the
// download manager.
download_op("first");
// Note that the second webview uses an in-memory partition.
download_op("second");
error_injector->ClearError();
content::DownloadManager::DownloadVector downloads;
download_manager->GetAllDownloads(&downloads);
ASSERT_EQ(2u, downloads.size());
CloseAppWindow(GetFirstAppWindow());
std::unique_ptr<content::DownloadTestObserver> completion_observer(
new content::DownloadTestObserverTerminal(
download_manager, 2,
content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_FAIL));
for (download::DownloadItem* download : downloads) {
ASSERT_TRUE(download->CanResume());
EXPECT_EQ(download::DOWNLOAD_INTERRUPT_REASON_SERVER_FAILED,
download->GetLastReason());
download->Resume(false);
}
completion_observer->WaitForFinished();
base::ScopedAllowBlockingForTesting allow_blocking;
std::set<std::string> cookies;
for (download::DownloadItem* download : downloads) {
ASSERT_EQ(download::DownloadItem::COMPLETE, download->GetState());
ASSERT_TRUE(base::PathExists(download->GetTargetFilePath()));
std::string content;
ASSERT_TRUE(
base::ReadFileToString(download->GetTargetFilePath(), &content));
// Note that the contents of the file is the value of the cookie.
EXPECT_EQ(content, download->GetURL().query());
cookies.insert(content);
}
ASSERT_EQ(2u, cookies.size());
ASSERT_TRUE(cookies.find("cookie=first") != cookies.end());
ASSERT_TRUE(cookies.find("cookie=second") != cookies.end());
}
IN_PROC_BROWSER_TEST_P(WebViewTest, PRE_DownloadCookieIsolation_CrossSession) {
SKIP_FOR_MPARCH(); // TODO(crbug.com/40202416): Enable test for MPArch.
embedded_test_server()->RegisterRequestHandler(
base::BindRepeating(&HandleDownloadRequestWithCookie));
ASSERT_TRUE(StartEmbeddedTestServer()); // For serving guest pages.
LoadAndLaunchPlatformApp("web_view/download_cookie_isolation",
"created-webviews");
scoped_refptr<base::TestMockTimeTaskRunner> task_runner(
new base::TestMockTimeTaskRunner);
download::SetDownloadDBTaskRunnerForTesting(task_runner);
content::WebContents* web_contents = GetFirstAppWindowWebContents();
ASSERT_TRUE(web_contents);
content::DownloadManager* download_manager =
web_contents->GetBrowserContext()->GetDownloadManager();
scoped_refptr<content::TestFileErrorInjector> error_injector(
content::TestFileErrorInjector::Create(download_manager));
content::TestFileErrorInjector::FileErrorInfo error_info(
content::TestFileErrorInjector::FILE_OPERATION_STREAM_COMPLETE, 0,
download::DOWNLOAD_INTERRUPT_REASON_SERVER_FAILED);
error_info.stream_offset = 0;
error_injector->InjectError(error_info);
auto download_op = [&](std::string cookie) {
// DownloadTestObserverInterrupted does not seem to reliably wait for
// multiple failed downloads, so we perform one download at a time.
content::DownloadTestObserverInterrupted interrupted_observer(
download_manager, 1,
content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_FAIL);
EXPECT_TRUE(content::ExecJs(
web_contents,
base::StrCat(
{"startDownload('", cookie, "', '",
embedded_test_server()->GetURL(kDownloadPathPrefix).spec(),
"?cookie=", cookie, "')"})));
// This maps to DOWNLOAD_INTERRUPT_REASON_SERVER_FAILED.
interrupted_observer.WaitForFinished();
};
// Both downloads should fail due to the error that was injected above to the
// download manager.
download_op("first");
// Note that the second webview uses an in-memory partition.
download_op("second");
// Wait for both downloads to be stored.
task_runner->FastForwardUntilNoTasksRemain();
content::EnsureCookiesFlushed(profile());
}
IN_PROC_BROWSER_TEST_P(WebViewTest, DownloadCookieIsolation_CrossSession) {
SKIP_FOR_MPARCH(); // TODO(crbug.com/40202416): Enable test for MPArch.
embedded_test_server()->RegisterRequestHandler(
base::BindRepeating(&HandleDownloadRequestWithCookie));
ASSERT_TRUE(StartEmbeddedTestServer()); // For serving guest pages.
scoped_refptr<base::TestMockTimeTaskRunner> task_runner(
new base::TestMockTimeTaskRunner);
download::SetDownloadDBTaskRunnerForTesting(task_runner);
content::BrowserContext* browser_context = profile();
content::DownloadManager* download_manager =
browser_context->GetDownloadManager();
task_runner->FastForwardUntilNoTasksRemain();
DownloadManagerWaiter waiter(download_manager);
waiter.WaitForInitialized();
content::DownloadManager::DownloadVector saved_downloads;
download_manager->GetAllDownloads(&saved_downloads);
ASSERT_EQ(2u, saved_downloads.size());
content::DownloadManager::DownloadVector downloads;
// We can't trivially resume the previous downloads because they are going to
// try to talk to the old EmbeddedTestServer instance. We need to update the
// URL to point to the new instance, which should only differ by the port
// number.
for (download::DownloadItem* download : saved_downloads) {
const std::string port_string =
base::NumberToString(embedded_test_server()->port());
GURL::Replacements replacements;
replacements.SetPortStr(port_string);
std::vector<GURL> url_chain;
url_chain.push_back(download->GetURL().ReplaceComponents(replacements));
downloads.push_back(download_manager->CreateDownloadItem(
base::Uuid::GenerateRandomV4().AsLowercaseString(),
download->GetId() + 2, download->GetFullPath(),
download->GetTargetFilePath(), url_chain, download->GetReferrerUrl(),
download_manager
->SerializedEmbedderDownloadDataToStoragePartitionConfig(
download->GetSerializedEmbedderDownloadData()),
download->GetTabUrl(), download->GetTabReferrerUrl(),
download->GetRequestInitiator(), download->GetMimeType(),
download->GetOriginalMimeType(), download->GetStartTime(),
download->GetEndTime(), download->GetETag(),
download->GetLastModifiedTime(), download->GetReceivedBytes(),
download->GetTotalBytes(), download->GetHash(), download->GetState(),
download->GetDangerType(), download->GetLastReason(),
download->GetOpened(), download->GetLastAccessTime(),
download->IsTransient(), download->GetReceivedSlices()));
}
content::DownloadTestObserverTerminal completion_observer(
download_manager, 2,
content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_FAIL);
for (download::DownloadItem* download : downloads) {
ASSERT_TRUE(download->CanResume());
ASSERT_TRUE(download->GetFullPath().empty());
ASSERT_TRUE(download::DOWNLOAD_INTERRUPT_REASON_CRASH ==
download->GetLastReason() ||
download::DOWNLOAD_INTERRUPT_REASON_SERVER_FAILED ==
download->GetLastReason());
download->Resume(true);
}
completion_observer.WaitForFinished();
// Of the two downloads, ?cookie=first will succeed and ?cookie=second will
// fail. The latter fails because the underlying storage partition was not
// persisted.
download::DownloadItem* succeeded_download = downloads[0];
download::DownloadItem* failed_download = downloads[1];
if (downloads[0]->GetState() == download::DownloadItem::INTERRUPTED)
std::swap(succeeded_download, failed_download);
ASSERT_EQ(download::DownloadItem::COMPLETE, succeeded_download->GetState());
base::ScopedAllowBlockingForTesting allow_blocking;
ASSERT_TRUE(base::PathExists(succeeded_download->GetTargetFilePath()));
std::string content;
ASSERT_TRUE(base::ReadFileToString(succeeded_download->GetTargetFilePath(),
&content));
// This is the cookie that should've been stored in the persisted storage
// partition.
EXPECT_STREQ("cookie=first", content.c_str());
ASSERT_EQ(download::DownloadItem::INTERRUPTED, failed_download->GetState());
EXPECT_EQ(download::DOWNLOAD_INTERRUPT_REASON_SERVER_FORBIDDEN,
failed_download->GetLastReason());
}
// This test makes sure loading <webview> does not crash when there is an
// extension which has content script allowlisted/forced.
IN_PROC_BROWSER_TEST_P(WebViewTest, AllowlistedContentScript) {
// Allowlist the extension for running content script we are going to load.
extensions::ExtensionsClient::ScriptingAllowlist allowlist;
const std::string extension_id = "imeongpbjoodlnmlakaldhlcmijmhpbb";
allowlist.push_back(extension_id);
extensions::ExtensionsClient::Get()->SetScriptingAllowlist(allowlist);
// Load the extension.
const extensions::Extension* content_script_allowlisted_extension =
LoadExtension(test_data_dir_.AppendASCII(
"platform_apps/web_view/extension_api/content_script"));
ASSERT_TRUE(content_script_allowlisted_extension);
ASSERT_EQ(extension_id, content_script_allowlisted_extension->id());
// Now load an app with <webview>.
LoadAndLaunchPlatformApp("web_view/content_script_allowlisted",
"TEST_PASSED");
}
IN_PROC_BROWSER_TEST_P(WebViewTest, SendMessageToExtensionFromGuest) {
// Load the extension as a normal, non-component extension.
const extensions::Extension* extension =
LoadExtension(test_data_dir_.AppendASCII(
"platform_apps/web_view/extension_api/component_extension"));
ASSERT_TRUE(extension);
TestHelper("testNonComponentExtension", "web_view/component_extension",
NEEDS_TEST_SERVER);
}
IN_PROC_BROWSER_TEST_P(WebViewTest, SendMessageToComponentExtensionFromGuest) {
const extensions::Extension* component_extension =
LoadExtensionAsComponent(test_data_dir_.AppendASCII(
"platform_apps/web_view/extension_api/component_extension"));
ASSERT_TRUE(component_extension);
TestHelper("testComponentExtension", "web_view/component_extension",
NEEDS_TEST_SERVER);
content::WebContents* embedder_web_contents = GetFirstAppWindowWebContents();
ASSERT_TRUE(embedder_web_contents);
// Retrive the guestProcessId and guestRenderFrameRoutingId from the
// extension.
int guest_process_id =
content::EvalJs(embedder_web_contents->GetPrimaryMainFrame(),
"window.guestProcessId")
.ExtractInt();
int guest_render_frame_routing_id =
content::EvalJs(embedder_web_contents->GetPrimaryMainFrame(),
"window.guestRenderFrameRoutingId")
.ExtractInt();
// Verify that the guest related info (guest_process_id and
// guest_render_frame_routing_id) actually points to a WebViewGuest.
ASSERT_TRUE(extensions::WebViewGuest::FromRenderFrameHostId(
content::GlobalRenderFrameHostId(guest_process_id,
guest_render_frame_routing_id)));
}
IN_PROC_BROWSER_TEST_P(WebViewTest, SetPropertyOnDocumentReady) {
ASSERT_TRUE(RunExtensionTest("platform_apps/web_view/document_ready",
{.launch_as_platform_app = true}))
<< message_;
}
IN_PROC_BROWSER_TEST_P(WebViewTest, SetPropertyOnDocumentInteractive) {
ASSERT_TRUE(RunExtensionTest("platform_apps/web_view/document_interactive",
{.launch_as_platform_app = true}))
<< message_;
}
IN_PROC_BROWSER_TEST_P(WebViewSpeechAPITest,
SpeechRecognitionAPI_HasPermissionAllow) {
ASSERT_TRUE(RunExtensionTest(
"platform_apps/web_view/speech_recognition_api",
{.custom_arg = "allowTest", .launch_as_platform_app = true}))
<< message_;
}
IN_PROC_BROWSER_TEST_P(WebViewSpeechAPITest,
SpeechRecognitionAPI_HasPermissionDeny) {
ASSERT_TRUE(RunExtensionTest(
"platform_apps/web_view/speech_recognition_api",
{.custom_arg = "denyTest", .launch_as_platform_app = true}))
<< message_;
}
IN_PROC_BROWSER_TEST_P(WebViewSpeechAPITest,
SpeechRecognitionAPI_NoPermission) {
ASSERT_TRUE(
RunExtensionTest("platform_apps/web_view/common",
{.custom_arg = "speech_recognition_api_no_permission",
.launch_as_platform_app = true}))
<< message_;
}
// Tests overriding user agent.
IN_PROC_BROWSER_TEST_P(WebViewTest, UserAgent) {
ASSERT_TRUE(RunExtensionTest(
"platform_apps/web_view/common",
{.custom_arg = "useragent", .launch_as_platform_app = true}))
<< message_;
}
// TODO(crbug.com/40260430): Test is flaky.
#if BUILDFLAG(IS_MAC)
#define MAYBE_UserAgent_NewWindow DISABLED_UserAgent_NewWindow
#else
#define MAYBE_UserAgent_NewWindow UserAgent_NewWindow
#endif
IN_PROC_BROWSER_TEST_P(WebViewNewWindowTest, MAYBE_UserAgent_NewWindow) {
ASSERT_TRUE(RunExtensionTest(
"platform_apps/web_view/common",
{.custom_arg = "useragent_newwindow", .launch_as_platform_app = true}))
<< message_;
}
IN_PROC_BROWSER_TEST_P(WebViewTest, NoPermission) {
ASSERT_TRUE(RunExtensionTest("platform_apps/web_view/nopermission",
{.launch_as_platform_app = true}))
<< message_;
}
IN_PROC_BROWSER_TEST_P(WebViewTest, Dialog_TestAlertDialog) {
TestHelper("testAlertDialog", "web_view/dialog", NO_TEST_SERVER);
}
IN_PROC_BROWSER_TEST_P(WebViewTest, TestConfirmDialog) {
TestHelper("testConfirmDialog", "web_view/dialog", NO_TEST_SERVER);
}
IN_PROC_BROWSER_TEST_P(WebViewTest, Dialog_TestConfirmDialogCancel) {
TestHelper("testConfirmDialogCancel", "web_view/dialog", NO_TEST_SERVER);
}
IN_PROC_BROWSER_TEST_P(WebViewTest, Dialog_TestConfirmDialogDefaultCancel) {
TestHelper("testConfirmDialogDefaultCancel",
"web_view/dialog",
NO_TEST_SERVER);
}
IN_PROC_BROWSER_TEST_P(WebViewTest, Dialog_TestConfirmDialogDefaultGCCancel) {
TestHelper("testConfirmDialogDefaultGCCancel",
"web_view/dialog",
NO_TEST_SERVER);
}
IN_PROC_BROWSER_TEST_P(WebViewTest, Dialog_TestPromptDialog) {
TestHelper("testPromptDialog", "web_view/dialog", NO_TEST_SERVER);
}
IN_PROC_BROWSER_TEST_P(WebViewTest, NoContentSettingsAPI) {
// Load the extension.
const extensions::Extension* content_settings_extension =
LoadExtension(
test_data_dir_.AppendASCII(
"platform_apps/web_view/extension_api/content_settings"));
ASSERT_TRUE(content_settings_extension);
TestHelper("testPostMessageCommChannel", "web_view/shim", NO_TEST_SERVER);
}
class WebViewCaptureTest : public WebViewTest {
public:
WebViewCaptureTest() = default;
~WebViewCaptureTest() override = default;
void SetUp() override {
EnablePixelOutput();
WebViewTest::SetUp();
}
};
INSTANTIATE_TEST_SUITE_P(/* no prefix */,
WebViewCaptureTest,
testing::Bool(),
WebViewCaptureTest::DescribeParams);
IN_PROC_BROWSER_TEST_P(WebViewTest, Shim_TestZoomAPI) {
TestHelper("testZoomAPI", "web_view/shim", NO_TEST_SERVER);
}
IN_PROC_BROWSER_TEST_P(WebViewTest, Shim_TestFindAPI) {
SKIP_FOR_MPARCH(); // TODO(crbug.com/40202416): Enable test for MPArch.
TestHelper("testFindAPI", "web_view/shim", NO_TEST_SERVER);
}
// crbug.com/710486
#if defined(MEMORY_SANITIZER)
#define MAYBE_Shim_TestFindAPI_findupdate DISABLED_Shim_TestFindAPI_findupdate
#else
#define MAYBE_Shim_TestFindAPI_findupdate Shim_TestFindAPI_findupdate
#endif
IN_PROC_BROWSER_TEST_P(WebViewTest, MAYBE_Shim_TestFindAPI_findupdate) {
SKIP_FOR_MPARCH(); // TODO(crbug.com/40202416): Enable test for MPArch.
TestHelper("testFindAPI_findupdate", "web_view/shim", NO_TEST_SERVER);
}
IN_PROC_BROWSER_TEST_P(WebViewTest, Shim_testFindInMultipleWebViews) {
SKIP_FOR_MPARCH(); // TODO(crbug.com/40202416): Enable test for MPArch.
TestHelper("testFindInMultipleWebViews", "web_view/shim", NO_TEST_SERVER);
}
IN_PROC_BROWSER_TEST_P(WebViewTest, Shim_TestFindAfterTerminate) {
content::ScopedAllowRendererCrashes scoped_allow_renderer_crashes;
TestHelper("testFindAfterTerminate", "web_view/shim", NO_TEST_SERVER);
}
IN_PROC_BROWSER_TEST_P(WebViewTest, Shim_TestLoadDataAPI) {
SKIP_FOR_MPARCH(); // TODO(crbug.com/40202416): Enable test for MPArch.
TestHelper("testLoadDataAPI", "web_view/shim", NEEDS_TEST_SERVER);
// Ensure that the guest process is locked after the loadDataWithBaseURL
// navigation and is allowed to access resources belonging to the base URL's
// origin.
content::RenderFrameHost* guest_main_frame =
GetGuestViewManager()->WaitForSingleGuestRenderFrameHostCreated();
ASSERT_TRUE(guest_main_frame);
EXPECT_TRUE(guest_main_frame->GetSiteInstance()->RequiresDedicatedProcess());
EXPECT_TRUE(
guest_main_frame->GetProcess()->IsProcessLockedToSiteForTesting());
auto* security_policy = content::ChildProcessSecurityPolicy::GetInstance();
url::Origin base_origin =
url::Origin::Create(embedded_test_server()->GetURL("localhost", "/"));
EXPECT_TRUE(security_policy->CanAccessDataForOrigin(
guest_main_frame->GetProcess()->GetDeprecatedID(), base_origin));
// Ensure the process doesn't have access to some other origin. This
// verifies that site isolation is enforced.
url::Origin another_origin =
url::Origin::Create(embedded_test_server()->GetURL("foo.com", "/"));
EXPECT_FALSE(security_policy->CanAccessDataForOrigin(
guest_main_frame->GetProcess()->GetDeprecatedID(), another_origin));
}
IN_PROC_BROWSER_TEST_P(WebViewTest, Shim_TestLoadDataAPIAccessibleResources) {
SKIP_FOR_MPARCH(); // TODO(crbug.com/40202416): Enable test for MPArch.
TestHelper("testLoadDataAPIAccessibleResources", "web_view/shim",
NEEDS_TEST_SERVER);
}
IN_PROC_BROWSER_TEST_P(WebViewTest, LoadDataAPINotRelativeToAnotherExtension) {
ASSERT_TRUE(StartEmbeddedTestServer());
const extensions::Extension* other_extension =
LoadExtension(test_data_dir_.AppendASCII("simple_with_file"));
LoadAppWithGuest("web_view/simple");
content::WebContents* embedder = GetEmbedderWebContents();
content::RenderFrameHost* guest = GetGuestView()->GetGuestMainFrame();
content::TestFrameNavigationObserver fail_if_webview_navigates(guest);
ASSERT_TRUE(content::ExecJs(
embedder, content::JsReplace(
"var webview = document.querySelector('webview'); "
"webview.loadDataWithBaseUrl('data:text/html,hello', $1);",
other_extension->url())));
// We expect the call to loadDataWithBaseUrl to fail and not cause a
// navigation. Since loadDataWithBaseUrl doesn't notify when it fails, we
// resort to a timeout here. If |fail_if_webview_navigates| doesn't see a
// navigation in that time, we consider the test to have passed.
base::RunLoop run_loop;
base::SingleThreadTaskRunner::GetCurrentDefault()->PostDelayedTask(
FROM_HERE, run_loop.QuitClosure(), TestTimeouts::tiny_timeout());
run_loop.Run();
EXPECT_FALSE(fail_if_webview_navigates.navigation_started());
}
// This test verifies that the resize and contentResize events work correctly.
IN_PROC_BROWSER_TEST_P(WebViewSizeTest, Shim_TestResizeEvents) {
TestHelper("testResizeEvents", "web_view/shim", NO_TEST_SERVER);
}
IN_PROC_BROWSER_TEST_P(WebViewTest, Shim_TestPerOriginZoomMode) {
TestHelper("testPerOriginZoomMode", "web_view/shim", NO_TEST_SERVER);
}
IN_PROC_BROWSER_TEST_P(WebViewTest, Shim_TestPerViewZoomMode) {
TestHelper("testPerViewZoomMode", "web_view/shim", NO_TEST_SERVER);
}
IN_PROC_BROWSER_TEST_P(WebViewTest, Shim_TestDisabledZoomMode) {
TestHelper("testDisabledZoomMode", "web_view/shim", NO_TEST_SERVER);
}
IN_PROC_BROWSER_TEST_P(WebViewTest, Shim_TestZoomBeforeNavigation) {
TestHelper("testZoomBeforeNavigation", "web_view/shim", NO_TEST_SERVER);
}
IN_PROC_BROWSER_TEST_P(WebViewTest, HttpAuth) {
ASSERT_TRUE(StartEmbeddedTestServer());
LoadAppWithGuest("web_view/simple");
const GURL auth_url = embedded_test_server()->GetURL("/auth-basic");
// There are two navigations occurring here. The first fails due to the need
// for auth. After it's supplied, a second navigation will succeed.
// This listener is only used for the non-mparch case.
content::TestNavigationObserver nav_observer(GetGuestWebContents(), 2);
nav_observer.set_wait_event(
content::TestNavigationObserver::WaitEvent::kNavigationFinished);
// We add a frame navigation observer for the MPArch case.
content::TestFrameNavigationObserver frame_nav_observer(
GetGuestRenderFrameHost());
EXPECT_TRUE(
content::ExecJs(GetGuestRenderFrameHost(),
content::JsReplace("location.href = $1;", auth_url)));
ASSERT_TRUE(base::test::RunUntil(
[]() { return LoginHandler::GetAllLoginHandlersForTest().size() == 1; }));
LoginHandler* login_handler =
LoginHandler::GetAllLoginHandlersForTest().front();
login_handler->SetAuth(u"basicuser", u"secret");
frame_nav_observer.Wait();
if (!GetParam()) {
nav_observer.Wait();
}
EXPECT_TRUE(frame_nav_observer.last_navigation_succeeded());
EXPECT_FALSE(GetGuestRenderFrameHost()->IsErrorDocument());
}
IN_PROC_BROWSER_TEST_P(WebViewTest, HttpAuthIdentical) {
ASSERT_TRUE(StartEmbeddedTestServer());
LoadAppWithGuest("web_view/simple");
const GURL auth_url = embedded_test_server()->GetURL("/auth-basic");
content::NavigationController* tab_controller =
&browser()->tab_strip_model()->GetActiveWebContents()->GetController();
// There are two navigations occurring here. The first fails due to the need
// for auth. After it's supplied, a second navigation will succeed.
// This listener is only used for the non-mparch case.
content::TestNavigationObserver guest_nav_observer(GetGuestWebContents(), 2);
guest_nav_observer.set_wait_event(
content::TestNavigationObserver::WaitEvent::kNavigationFinished);
// We add a frame navigation observer for the MPArch case.
content::TestFrameNavigationObserver frame_nav_observer(
GetGuestRenderFrameHost());
EXPECT_TRUE(
content::ExecJs(GetGuestRenderFrameHost(),
content::JsReplace("location.href = $1;", auth_url)));
ASSERT_TRUE(base::test::RunUntil(
[]() { return LoginHandler::GetAllLoginHandlersForTest().size() == 1; }));
// While the login UI is showing for the app, navigate a tab to the same URL
// requiring auth.
tab_controller->LoadURL(auth_url, content::Referrer(),
ui::PAGE_TRANSITION_TYPED, std::string());
ASSERT_TRUE(base::test::RunUntil(
[]() { return LoginHandler::GetAllLoginHandlersForTest().size() == 2; }));
// Both the guest and the tab should be prompting for credentials and the auth
// challenge should be the same. Normally, the login code de-duplicates
// identical challenges if multiple prompts are shown for them. However,
// credentials can't be shared across StoragePartitions. So providing
// credentials within the guest should not affect the tab.
ASSERT_EQ(2u, LoginHandler::GetAllLoginHandlersForTest().size());
LoginHandler* guest_login_handler =
LoginHandler::GetAllLoginHandlersForTest().front();
LoginHandler* tab_login_handler =
LoginHandler::GetAllLoginHandlersForTest().back();
EXPECT_EQ(tab_controller,
&tab_login_handler->web_contents()->GetController());
EXPECT_TRUE(guest_login_handler->auth_info().MatchesExceptPath(
tab_login_handler->auth_info()));
guest_login_handler->SetAuth(u"basicuser", u"secret");
frame_nav_observer.Wait();
if (!GetParam()) {
guest_nav_observer.WaitForNavigationFinished();
}
// The tab should still be prompting for credentials.
ASSERT_EQ(1u, LoginHandler::GetAllLoginHandlersForTest().size());
EXPECT_EQ(tab_login_handler,
LoginHandler::GetAllLoginHandlersForTest().front());
}
namespace {
class NullWebContentsDelegate : public content::WebContentsDelegate {
public:
NullWebContentsDelegate() = default;
~NullWebContentsDelegate() override = default;
};
// A stub ClientCertStore that returns a FakeClientCertIdentity.
class ClientCertStoreStub : public net::ClientCertStore {
public:
explicit ClientCertStoreStub(net::ClientCertIdentityList list)
: list_(std::move(list)) {}
~ClientCertStoreStub() override = default;
// net::ClientCertStore:
void GetClientCerts(
scoped_refptr<const net::SSLCertRequestInfo> cert_request_info,
ClientCertListCallback callback) override {
std::move(callback).Run(std::move(list_));
if (quit_closure_) {
// Call the quit closure asynchronously, so it's ordered after the cert
// selector.
base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
FROM_HERE, std::move(quit_closure_));
}
}
static void SetQuitClosure(base::OnceClosure quit_closure) {
quit_closure_ = std::move(quit_closure);
}
private:
net::ClientCertIdentityList list_;
// Called the next time GetClientCerts is called.
static base::OnceClosure quit_closure_;
};
// static
base::OnceClosure ClientCertStoreStub::quit_closure_;
} // namespace
class WebViewCertificateSelectorTest : public WebViewTest {
public:
void SetUpOnMainThread() override {
WebViewTest::SetUpOnMainThread();
ProfileNetworkContextServiceFactory::GetForContext(browser()->profile())
->set_client_cert_store_factory_for_testing(base::BindRepeating(
&WebViewCertificateSelectorTest::CreateCertStore));
net::SSLServerConfig ssl_config;
ssl_config.client_cert_type =
net::SSLServerConfig::ClientCertType::REQUIRE_CLIENT_CERT;
https_server_.SetSSLConfig(net::EmbeddedTestServer::CERT_OK, ssl_config);
https_server_.AddDefaultHandlers(GetChromeTestDataDir());
ASSERT_TRUE(https_server_.Start());
ASSERT_TRUE(StartEmbeddedTestServer());
}
net::EmbeddedTestServer& https_server() { return https_server_; }
web_modal::WebContentsModalDialogManager* GetModalDialogManager(
content::WebContents* embedder_web_contents) {
web_modal::WebContentsModalDialogManager* manager =
web_modal::WebContentsModalDialogManager::FromWebContents(
embedder_web_contents);
EXPECT_TRUE(manager);
return manager;
}
private:
static std::unique_ptr<net::ClientCertStore> CreateCertStore() {
net::ClientCertIdentityList cert_identity_list;
{
base::ScopedAllowBlockingForTesting allow_blocking;
std::unique_ptr<net::FakeClientCertIdentity> cert_identity =
net::FakeClientCertIdentity::CreateFromCertAndKeyFiles(
net::GetTestCertsDirectory(), "client_1.pem", "client_1.pk8");
EXPECT_TRUE(cert_identity.get());
if (cert_identity)
cert_identity_list.push_back(std::move(cert_identity));
}
return std::make_unique<ClientCertStoreStub>(std::move(cert_identity_list));
}
net::EmbeddedTestServer https_server_{net::EmbeddedTestServer::TYPE_HTTPS};
};
INSTANTIATE_TEST_SUITE_P(/* no prefix */,
WebViewCertificateSelectorTest,
testing::Bool(),
WebViewCertificateSelectorTest::DescribeParams);
// Ensure a guest triggering a client certificate dialog does not crash.
IN_PROC_BROWSER_TEST_P(WebViewCertificateSelectorTest,
CertificateSelectorForGuest) {
LoadAppWithGuest("web_view/simple");
content::RenderFrameHost* guest_rfh = GetGuestRenderFrameHost();
const GURL client_cert_url =
https_server().GetURL("/ssl/browser_use_client_cert_store.html");
base::RunLoop run_loop;
ClientCertStoreStub::SetQuitClosure(run_loop.QuitClosure());
EXPECT_TRUE(content::ExecJs(
guest_rfh, content::JsReplace("location.href = $1;", client_cert_url)));
run_loop.Run();
auto* manager = GetModalDialogManager(GetEmbedderWebContents());
EXPECT_TRUE(manager->IsDialogActive());
manager->CloseAllDialogs();
}
// Ensure a guest triggering a client certificate dialog does not crash.
// This considers the case where a guest view is in use that has been
// inadvertently broken by misuse of WebContentsDelegates. This has seemingly
// happened multiple times for various dialogs and signin flows (see
// https://crbug.com/1076696 and https://crbug.com/1306988 ), so let's test that
// if we are in this situation, we at least don't crash.
IN_PROC_BROWSER_TEST_P(WebViewCertificateSelectorTest,
CertificateSelectorForGuestMisconfigured) {
// TODO(crbug.com/40202416): This test doesn't apply for MPArch and
// can be removed when the InnerWebContents version is removed.
SKIP_FOR_MPARCH();
LoadAppWithGuest("web_view/simple");
content::WebContents* guest_contents = GetGuestWebContents();
const GURL client_cert_url =
https_server().GetURL("/ssl/browser_use_client_cert_store.html");
auto* guest_delegate = guest_contents->GetDelegate();
NullWebContentsDelegate null_delegate;
// This is intentionally incorrect. The guest WebContents' delegate should
// remain a guest_view::GuestViewBase.
guest_contents->SetDelegate(&null_delegate);
base::RunLoop run_loop;
ClientCertStoreStub::SetQuitClosure(run_loop.QuitClosure());
EXPECT_TRUE(content::ExecJs(
guest_contents,
content::JsReplace("location.href = $1;", client_cert_url)));
run_loop.Run();
auto* manager = GetModalDialogManager(GetEmbedderWebContents());
EXPECT_TRUE(manager->IsDialogActive());
manager->CloseAllDialogs();
guest_contents->SetDelegate(guest_delegate);
}
// Test fixture to run the test on multiple channels.
class WebViewChannelTest : public WebViewTestBase,
public testing::WithParamInterface<
testing::tuple<version_info::Channel, bool>> {
public:
WebViewChannelTest() : channel_(GetChannelParam()) {
scoped_feature_list_.InitWithFeatureState(features::kGuestViewMPArch,
testing::get<1>(GetParam()));
}
version_info::Channel GetChannelParam() {
return testing::get<0>(GetParam());
}
WebViewChannelTest(const WebViewChannelTest&) = delete;
WebViewChannelTest& operator=(const WebViewChannelTest&) = delete;
static std::string DescribeParams(
const testing::TestParamInfo<ParamType>& info) {
const auto [channel, mparch] = info.param;
return base::StringPrintf("%s_%s",
channel == version_info::Channel::STABLE
? "StableChannel"
: "NonStableChannel",
mparch ? "MPArch" : "InnerWebContents");
}
private:
extensions::ScopedCurrentChannel channel_;
base::test::ScopedFeatureList scoped_feature_list_;
};
// This test verify that the set of rules registries of a webview will be
// removed from RulesRegistryService after the webview is gone.
// TODO(crbug.com/40231831): The test has the same callstack caused by the race
// with ScopedFeatureList as the issue describes.
#if BUILDFLAG(IS_MAC)
#define MAYBE_Shim_TestRulesRegistryIDAreRemovedAfterWebViewIsGone \
DISABLED_Shim_TestRulesRegistryIDAreRemovedAfterWebViewIsGone
#else
#define MAYBE_Shim_TestRulesRegistryIDAreRemovedAfterWebViewIsGone \
Shim_TestRulesRegistryIDAreRemovedAfterWebViewIsGone
#endif
IN_PROC_BROWSER_TEST_P(
WebViewChannelTest,
MAYBE_Shim_TestRulesRegistryIDAreRemovedAfterWebViewIsGone) {
ASSERT_EQ(extensions::GetCurrentChannel(), GetChannelParam());
SCOPED_TRACE(base::StrCat(
{"Testing Channel ", version_info::GetChannelString(GetChannelParam())}));
LoadAppWithGuest("web_view/rules_registry");
content::WebContents* embedder_web_contents = GetEmbedderWebContents();
ASSERT_TRUE(embedder_web_contents);
std::unique_ptr<EmbedderWebContentsObserver> observer(
new EmbedderWebContentsObserver(embedder_web_contents));
guest_view::GuestViewBase* guest_view = GetGuestView();
ASSERT_TRUE(guest_view);
// Register rule for the guest.
Profile* profile = browser()->profile();
int rules_registry_id =
extensions::WebViewGuest::GetOrGenerateRulesRegistryID(
guest_view->owner_rfh()->GetProcess()->GetDeprecatedID(),
guest_view->view_instance_id());
extensions::RulesRegistryService* registry_service =
extensions::RulesRegistryService::Get(profile);
extensions::TestRulesRegistry* rules_registry =
new extensions::TestRulesRegistry("ui", rules_registry_id);
registry_service->RegisterRulesRegistry(base::WrapRefCounted(rules_registry));
EXPECT_TRUE(
registry_service->HasRulesRegistryForTesting(rules_registry_id, "ui"));
content::ScopedAllowRendererCrashes scoped_allow_renderer_crashes;
// Kill the embedder's render process, so the webview will go as well.
embedder_web_contents->GetPrimaryMainFrame()
->GetProcess()
->GetProcess()
.Terminate(0, false);
observer->WaitForEmbedderRenderProcessTerminate();
EXPECT_FALSE(
registry_service->HasRulesRegistryForTesting(rules_registry_id, "ui"));
}
IN_PROC_BROWSER_TEST_P(WebViewChannelTest,
Shim_WebViewWebRequestRegistryHasNoPersistentCache) {
ASSERT_EQ(extensions::GetCurrentChannel(), GetChannelParam());
SCOPED_TRACE(base::StrCat(
{"Testing Channel ", version_info::GetChannelString(GetChannelParam())}));
LoadAppWithGuest("web_view/rules_registry");
guest_view::GuestViewBase* guest_view = GetGuestView();
ASSERT_TRUE(guest_view);
Profile* profile = browser()->profile();
extensions::RulesRegistryService* registry_service =
extensions::RulesRegistryService::Get(profile);
int rules_registry_id =
extensions::WebViewGuest::GetOrGenerateRulesRegistryID(
guest_view->owner_rfh()->GetProcess()->GetDeprecatedID(),
guest_view->view_instance_id());
// Get an existing registered rule for the guest.
extensions::RulesRegistry* registry =
registry_service
->GetRulesRegistry(
rules_registry_id,
extensions::declarative_webrequest_constants::kOnRequest)
.get();
ASSERT_TRUE(registry);
ASSERT_TRUE(registry->rules_cache_delegate_for_testing());
EXPECT_EQ(extensions::RulesCacheDelegate::Type::kEphemeral,
registry->rules_cache_delegate_for_testing()->type());
}
INSTANTIATE_TEST_SUITE_P(
WebViewTests,
WebViewChannelTest,
testing::Combine(testing::Values(version_info::Channel::UNKNOWN,
version_info::Channel::STABLE),
testing::Bool()),
WebViewChannelTest::DescribeParams);
// This test verifies that webview.contentWindow works inside an iframe.
IN_PROC_BROWSER_TEST_P(WebViewTest, Shim_TestWebViewInsideFrame) {
LoadAppWithGuest("web_view/inside_iframe");
}
// <webview> screenshot capture fails with ubercomp.
// See http://crbug.com/327035.
IN_PROC_BROWSER_TEST_P(WebViewCaptureTest, DISABLED_Shim_ScreenshotCapture) {
SKIP_FOR_MPARCH(); // TODO(crbug.com/40202416): Enable test for MPArch.
TestHelper("testScreenshotCapture", "web_view/shim", NO_TEST_SERVER);
}
// Test is disabled because it times out often.
// http://crbug.com/403325
IN_PROC_BROWSER_TEST_P(WebViewTest, DISABLED_WebViewInBackgroundPage) {
SKIP_FOR_MPARCH(); // TODO(crbug.com/40202416): Enable test for MPArch.
ASSERT_TRUE(StartEmbeddedTestServer());
ASSERT_TRUE(RunExtensionTest("platform_apps/web_view/background"))
<< message_;
}
// This test verifies that the allowtransparency attribute properly propagates.
IN_PROC_BROWSER_TEST_P(WebViewTest, AllowTransparencyAndAllowScalingPropagate) {
LoadAppWithGuest("web_view/simple");
ASSERT_TRUE(GetGuestView());
extensions::WebViewGuest* guest =
extensions::WebViewGuest::FromGuestViewBase(GetGuestView());
ASSERT_TRUE(guest->allow_transparency());
ASSERT_TRUE(guest->allow_scaling());
}
IN_PROC_BROWSER_TEST_P(WebViewTest, BasicPostMessage) {
ASSERT_TRUE(StartEmbeddedTestServer()); // For serving guest pages.
ASSERT_TRUE(RunExtensionTest("platform_apps/web_view/post_message/basic",
{.launch_as_platform_app = true}))
<< message_;
}
// Tests that webviews do get garbage collected.
IN_PROC_BROWSER_TEST_P(WebViewTest, Shim_TestGarbageCollect) {
TestHelper("testGarbageCollect", "web_view/shim", NO_TEST_SERVER);
GetGuestViewManager()->WaitForSingleViewGarbageCollected();
}
IN_PROC_BROWSER_TEST_P(WebViewTest, Shim_TestCloseNewWindowCleanup) {
TestHelper("testCloseNewWindowCleanup", "web_view/shim", NEEDS_TEST_SERVER);
auto* gvm = GetGuestViewManager();
gvm->WaitForLastGuestDeleted();
ASSERT_EQ(gvm->num_embedder_processes_destroyed(), 0);
}
// Ensure that focusing a WebView while it is already focused does not blur the
// guest content.
IN_PROC_BROWSER_TEST_P(WebViewTest, Shim_TestFocusWhileFocused) {
TestHelper("testFocusWhileFocused", "web_view/shim", NO_TEST_SERVER);
}
#if BUILDFLAG(ENABLE_PDF)
class WebViewPdfTest
: public WebViewTestBase,
public testing::WithParamInterface<testing::tuple<bool, bool>> {
public:
WebViewPdfTest() {
scoped_feature_list_.InitWithFeatureStates(
{{chrome_pdf::features::kPdfOopif, testing::get<0>(GetParam())},
{features::kGuestViewMPArch, testing::get<1>(GetParam())}});
}
static std::string DescribeParams(
const testing::TestParamInfo<ParamType>& info) {
const auto [pdf_oopif, mparch] = info.param;
return base::StringPrintf(
"%s_%s", pdf_oopif ? "PdfOopifEnabled" : "PdfOopifDisabled",
mparch ? "MPArch" : "InnerWebContents");
}
bool UseOopif() const { return testing::get<0>(GetParam()); }
pdf::TestPdfViewerStreamManager* GetTestPdfViewerStreamManager(
content::WebContents* contents) {
return factory_.GetTestPdfViewerStreamManager(contents);
}
// Waits until the PDF has loaded in the given `web_view_rfh`.
testing::AssertionResult WaitUntilPdfLoaded(
content::RenderFrameHost* web_view_rfh) {
if (UseOopif()) {
auto* web_contents =
content::WebContents::FromRenderFrameHost(web_view_rfh);
return GetTestPdfViewerStreamManager(web_contents)
->WaitUntilPdfLoaded(web_view_rfh);
}
return pdf_extension_test_util::EnsurePDFHasLoaded(web_view_rfh);
}
private:
pdf::TestPdfViewerStreamManagerFactory factory_;
base::test::ScopedFeatureList scoped_feature_list_;
};
// Test that the PDF viewer has the same bounds as the WebView.
IN_PROC_BROWSER_TEST_P(WebViewPdfTest, PdfContainerBounds) {
SKIP_FOR_MPARCH(); // TODO(crbug.com/40202416): Enable test for MPArch.
TestHelper("testPDFInWebview", "web_view/shim", NO_TEST_SERVER);
// OOPIF PDF should only have one guest for the WebView. GuestView PDF should
// have a second guest for the PDF (`MimeHandlerViewGuest`).
const size_t expected_guest_count = UseOopif() ? 1u : 2u;
std::vector<content::RenderFrameHost*> guest_rfh_list;
GetGuestViewManager()->WaitForNumGuestsCreated(expected_guest_count);
GetGuestViewManager()->GetGuestRenderFrameHostList(&guest_rfh_list);
ASSERT_EQ(expected_guest_count, guest_rfh_list.size());
content::RenderFrameHost* web_view_rfh = guest_rfh_list[0];
// Make sure the PDF loaded.
ASSERT_TRUE(WaitUntilPdfLoaded(web_view_rfh));
content::RenderFrameHost* extension_rfh =
UseOopif() ? pdf_extension_test_util::GetPdfExtensionHostFromEmbedder(
web_view_rfh, /*allow_multiple_frames=*/false)
: guest_rfh_list[1];
ASSERT_TRUE(extension_rfh);
gfx::Rect web_view_container_bounds =
web_view_rfh->GetRenderWidgetHost()->GetView()->GetViewBounds();
gfx::Rect extension_container_bounds =
extension_rfh->GetRenderWidgetHost()->GetView()->GetViewBounds();
EXPECT_EQ(web_view_container_bounds.origin(),
extension_container_bounds.origin());
}
// Test that context menu Back/Forward items in a WebView affect the embedder
// WebContents. See crbug.com/587355.
IN_PROC_BROWSER_TEST_P(WebViewPdfTest, ContextMenuNavigationInWebView) {
SKIP_FOR_MPARCH(); // TODO(crbug.com/40202416): Enable test for MPArch.
TestHelper("testNavigateToPDFInWebview", "web_view/shim", NO_TEST_SERVER);
// OOPIF PDF should only have one guest for the WebView. GuestView PDF should
// have a second guest for the PDF (`MimeHandlerViewGuest`).
const size_t expected_guest_count = UseOopif() ? 1u : 2u;
std::vector<content::RenderFrameHost*> guest_rfh_list;
GetGuestViewManager()->WaitForNumGuestsCreated(expected_guest_count);
GetGuestViewManager()->GetGuestRenderFrameHostList(&guest_rfh_list);
ASSERT_EQ(expected_guest_count, guest_rfh_list.size());
content::RenderFrameHost* web_view_rfh = guest_rfh_list[0];
// Make sure the PDF loaded.
ASSERT_TRUE(WaitUntilPdfLoaded(web_view_rfh));
content::RenderFrameHost* extension_rfh =
UseOopif() ? pdf_extension_test_util::GetPdfExtensionHostFromEmbedder(
web_view_rfh, /*allow_multiple_frames=*/false)
: guest_rfh_list[1];
ASSERT_TRUE(extension_rfh);
// Ensure the <webview> has a previous entry, so we can navigate back to it.
EXPECT_EQ(true,
content::EvalJs(GetEmbedderWebContents(),
"document.querySelector('webview').canGoBack();"));
// Open a context menu for the PDF viewer. Since the <webview> can
// navigate back, the Back item should be enabled.
content::ContextMenuParams params;
TestRenderViewContextMenu menu(*extension_rfh, params);
menu.Init();
ASSERT_TRUE(menu.IsCommandIdEnabled(IDC_BACK));
// Verify that the Back item causes the <webview> to navigate back to the
// previous entry.
content::TestFrameNavigationObserver observer(web_view_rfh);
menu.ExecuteCommand(IDC_BACK, 0);
observer.Wait();
std::vector<content::RenderFrameHost*> guest_rfh_list2;
GetGuestViewManager()->GetGuestRenderFrameHostList(&guest_rfh_list2);
ASSERT_EQ(1u, guest_rfh_list2.size());
content::RenderFrameHost* web_view_rfh2 = guest_rfh_list2[0];
EXPECT_EQ(GURL(url::kAboutBlankURL), web_view_rfh2->GetLastCommittedURL());
// The following should not crash. See https://crbug.com/331796663
GetFirstAppWindowWebContents()->GetFocusedFrame();
}
IN_PROC_BROWSER_TEST_P(WebViewPdfTest, Shim_TestDialogInPdf) {
SKIP_FOR_MPARCH(); // TODO(crbug.com/40202416): Enable test for MPArch.
TestHelper("testDialogInPdf", "web_view/shim", NO_TEST_SERVER);
}
// TODO(crbug.com/40268279): Stop testing both modes after OOPIF PDF viewer
// launches.
INSTANTIATE_TEST_SUITE_P(/* no prefix */,
WebViewPdfTest,
testing::Combine(testing::Bool(), testing::Bool()),
WebViewPdfTest::DescribeParams);
#endif // BUILDFLAG(ENABLE_PDF)
IN_PROC_BROWSER_TEST_P(WebViewTest, Shim_TestMailtoLink) {
TestHelper("testMailtoLink", "web_view/shim", NEEDS_TEST_SERVER);
}
// Tests that a renderer navigation from an unattached guest that results in a
// server redirect works properly.
IN_PROC_BROWSER_TEST_P(WebViewTest,
Shim_TestRendererNavigationRedirectWhileUnattached) {
TestHelper("testRendererNavigationRedirectWhileUnattached",
"web_view/shim", NEEDS_TEST_SERVER);
}
IN_PROC_BROWSER_TEST_P(WebViewTest, Shim_TestRemoveBeforeAttach) {
TestHelper("testRemoveBeforeAttach", "web_view/shim", NO_TEST_SERVER);
// Ensure browser side state for the immediately destroyed guest is cleared
// without having to wait for the embedder to be closed.
// If it's not cleared then this will timeout.
GetGuestViewManager()->WaitForAllGuestsDeleted();
}
// Tests that the embedder can create a blob URL and navigate a WebView to it.
// See https://crbug.com/652077.
// Also tests that the embedder can't navigate to a blob URL created by a
// WebView. See https://crbug.com/1106890.
IN_PROC_BROWSER_TEST_P(WebViewTest, Shim_TestBlobURL) {
TestHelper("testBlobURL", "web_view/shim", NEEDS_TEST_SERVER);
}
// Tests that no error page is shown when WebRequest blocks a navigation.
IN_PROC_BROWSER_TEST_P(WebViewTest, Shim_TestWebRequestBlockedNavigation) {
SKIP_FOR_MPARCH(); // TODO(crbug.com/40202416): Enable test for MPArch.
TestHelper("testWebRequestBlockedNavigation", "web_view/shim",
NEEDS_TEST_SERVER);
}
// Tests that a WebView accessible resource can actually be loaded from a
// webpage in a WebView.
IN_PROC_BROWSER_TEST_P(WebViewTest, LoadWebviewAccessibleResource) {
TestHelper("testLoadWebviewAccessibleResource",
"web_view/load_webview_accessible_resource", NEEDS_TEST_SERVER);
}
// Tests that a WebView can be navigated to a WebView accessible resource.
IN_PROC_BROWSER_TEST_P(WebViewTest, NavigateGuestToWebviewAccessibleResource) {
TestHelper("testNavigateGuestToWebviewAccessibleResource",
"web_view/load_webview_accessible_resource", NO_TEST_SERVER);
// Ensure that the <webview> process isn't considered an extension process,
// even though the last committed URL is an extension URL.
content::RenderFrameHost* guest =
GetGuestViewManager()->GetLastGuestRenderFrameHostCreated();
GURL guest_url(guest->GetLastCommittedURL());
EXPECT_TRUE(guest_url.SchemeIs(extensions::kExtensionScheme));
auto* process_map = extensions::ProcessMap::Get(guest->GetBrowserContext());
auto* guest_process = guest->GetProcess();
EXPECT_FALSE(process_map->Contains(guest_process->GetDeprecatedID()));
EXPECT_FALSE(
process_map->GetExtensionIdForProcess(guest_process->GetDeprecatedID()));
extensions::ExtensionRegistry* registry =
extensions::ExtensionRegistry::Get(browser()->profile());
const extensions::Extension* extension =
registry->enabled_extensions().GetByID(guest_url.host());
EXPECT_EQ(extensions::mojom::ContextType::kUnprivilegedExtension,
process_map->GetMostLikelyContextType(
extension, guest_process->GetDeprecatedID(), &guest_url));
}
// Tests that a WebView can reload a WebView accessible resource. See
// https://crbug.com/691941.
IN_PROC_BROWSER_TEST_P(WebViewTest, ReloadWebviewAccessibleResource) {
TestHelper("testReloadWebviewAccessibleResource",
"web_view/load_webview_accessible_resource", NEEDS_TEST_SERVER);
content::WebContents* embedder_contents = GetEmbedderWebContents();
content::RenderFrameHost* web_view_frame =
GetGuestViewManager()->GetLastGuestRenderFrameHostCreated();
ASSERT_TRUE(embedder_contents);
ASSERT_TRUE(web_view_frame);
GURL embedder_url(embedder_contents->GetLastCommittedURL());
GURL webview_url(embedder_url.DeprecatedGetOriginAsURL().spec() +
"assets/foo.html");
EXPECT_EQ(webview_url, web_view_frame->GetLastCommittedURL());
}
IN_PROC_BROWSER_TEST_P(WebViewTest,
CookiesEnabledAfterWebviewAccessibleResource) {
TestHelper("testCookiesEnabledAfterWebviewAccessibleResource",
"web_view/load_webview_accessible_resource", NEEDS_TEST_SERVER);
}
// Tests that webviews cannot embed accessible resources in iframes.
// https://crbug.com/1430991.
IN_PROC_BROWSER_TEST_P(WebViewTest, CannotIframeWebviewAccessibleResource) {
SKIP_FOR_MPARCH(); // TODO(crbug.com/40202416): Enable test for MPArch.
TestHelper("testIframeWebviewAccessibleResource",
"web_view/load_webview_accessible_resource", NEEDS_TEST_SERVER);
content::RenderFrameHost* web_view_frame =
GetGuestViewManager()->GetLastGuestRenderFrameHostCreated();
ASSERT_TRUE(web_view_frame);
content::RenderFrameHost* child_frame =
content::ChildFrameAt(web_view_frame, 0);
ASSERT_TRUE(child_frame);
// The frame should never have committed to the extension resource.
// The JS file verifies the load error.
EXPECT_EQ(GURL(), child_frame->GetLastCommittedURL());
}
// Tests that webviews navigated to accessible resources can call certain
// extension APIs.
IN_PROC_BROWSER_TEST_P(WebViewTest,
CallingExtensionAPIsFromWebviewAccessibleResource) {
TestHelper("testNavigateGuestToWebviewAccessibleResource",
"web_view/load_webview_accessible_resource", NO_TEST_SERVER);
content::WebContents* embedder_contents = GetEmbedderWebContents();
content::RenderFrameHost* web_view_frame =
GetGuestViewManager()->GetLastGuestRenderFrameHostCreated();
ASSERT_TRUE(embedder_contents);
ASSERT_TRUE(web_view_frame);
// The embedder and the webview should be in separate site instances and
// processes, even though they're for the same extension.
EXPECT_NE(embedder_contents->GetPrimaryMainFrame()->GetProcess(),
web_view_frame->GetProcess());
EXPECT_NE(embedder_contents->GetPrimaryMainFrame()->GetSiteInstance(),
web_view_frame->GetSiteInstance());
GURL embedder_url(embedder_contents->GetLastCommittedURL());
GURL accessible_resource_url =
embedder_url.GetWithEmptyPath().Resolve("assets/foo.html");
EXPECT_EQ(accessible_resource_url, web_view_frame->GetLastCommittedURL());
// Try calling an extension API function. The extension frame, being embedded
// in a webview, has fewer permissions that other extension contexts*. Try the
// i18n.getAcceptLanguages() API. We choose this API because:
// - It is exposed to the embedded frame.
// - It is a "regular" extension API function that goes through the request /
// response flow in ExtensionFunctionDispatcher, unlike extension message
// APIs.
// *TODO(crbug.com/40263329): The exact set of APIs and type of
// context this is is a bit fuzzy. In practice, it's basically the same set
// as is exposed to content scripts.
static constexpr char kGetAcceptLanguages[] =
R"(new Promise(resolve => {
chrome.i18n.getAcceptLanguages((languages) => {
let result = 'success';
if (chrome.runtime.lastError) {
result = 'Error: ' + chrome.runtime.lastError;
} else if (!languages || !Array.isArray(languages) ||
!languages.includes('en')) {
result = 'Invalid return result: ' + JSON.stringify(languages);
}
resolve(result);
});
});)";
EXPECT_EQ("success", content::EvalJs(web_view_frame, kGetAcceptLanguages));
// Finally, try accessing a privileged API, which shouldn't be available to
// the embedded resource.
static constexpr char kCallAppWindowCreate[] =
R"(var message;
if (chrome.app && chrome.app.window) {
message = 'chrome.app.window unexpectedly available.';
} else {
message = 'success';
}
message;)";
EXPECT_EQ("success", content::EvalJs(web_view_frame, kCallAppWindowCreate));
}
// Tests that a WebView can navigate an iframe to a blob URL that it creates
// while its main frame is at a WebView accessible resource.
IN_PROC_BROWSER_TEST_P(WebViewTest, BlobInWebviewAccessibleResource) {
TestHelper("testBlobInWebviewAccessibleResource",
"web_view/load_webview_accessible_resource", NEEDS_TEST_SERVER);
content::WebContents* embedder_contents = GetEmbedderWebContents();
content::RenderFrameHost* webview_rfh =
GetGuestViewManager()->GetLastGuestRenderFrameHostCreated();
ASSERT_TRUE(embedder_contents);
ASSERT_TRUE(webview_rfh);
GURL embedder_url(embedder_contents->GetLastCommittedURL());
GURL webview_url(embedder_url.DeprecatedGetOriginAsURL().spec() +
"assets/foo.html");
EXPECT_EQ(webview_url, webview_rfh->GetLastCommittedURL());
content::RenderFrameHost* blob_frame = ChildFrameAt(webview_rfh, 0);
EXPECT_TRUE(blob_frame->GetLastCommittedURL().SchemeIsBlob());
EXPECT_EQ("Blob content",
content::EvalJs(blob_frame, "document.body.innerText;"));
}
// Tests that a WebView cannot load a webview-inaccessible resource. See
// https://crbug.com/640072.
IN_PROC_BROWSER_TEST_P(WebViewTest, LoadWebviewInaccessibleResource) {
SKIP_FOR_MPARCH(); // TODO(crbug.com/40202416): Enable test for MPArch.
TestHelper("testLoadWebviewInaccessibleResource",
"web_view/load_webview_accessible_resource", NEEDS_TEST_SERVER);
content::WebContents* embedder_contents = GetEmbedderWebContents();
content::RenderFrameHost* web_view_frame =
GetGuestViewManager()->GetLastGuestRenderFrameHostCreated();
ASSERT_TRUE(embedder_contents);
ASSERT_TRUE(web_view_frame);
// Check that the webview stays at the first page that it loaded (foo.html),
// and does not commit inaccessible.html.
GURL embedder_url(embedder_contents->GetLastCommittedURL());
GURL foo_url(embedder_url.DeprecatedGetOriginAsURL().spec() +
"assets/foo.html");
EXPECT_EQ(foo_url, web_view_frame->GetLastCommittedURL());
}
// Ensure that only app resources accessible to the webview can be loaded in a
// webview even if the webview commits an app frame.
IN_PROC_BROWSER_TEST_P(WebViewTest,
LoadAccessibleSubresourceInAppWebviewFrame) {
TestHelper("testLoadAccessibleSubresourceInAppWebviewFrame",
"web_view/load_webview_accessible_resource", NEEDS_TEST_SERVER);
}
IN_PROC_BROWSER_TEST_P(WebViewTest,
InaccessibleResourceDoesNotLoadInAppWebviewFrame) {
TestHelper("testInaccessibleResourceDoesNotLoadInAppWebviewFrame",
"web_view/load_webview_accessible_resource", NEEDS_TEST_SERVER);
}
// Makes sure that a webview will display correctly after reloading it after a
// crash.
// TODO(crbug.com/40286295): Flaky on Win,Mac,ChromeOS,Linux.
IN_PROC_BROWSER_TEST_P(WebViewTest, DISABLED_ReloadAfterCrash) {
// Load guest and wait for it to appear.
LoadAppWithGuest("web_view/simple");
EXPECT_TRUE(GetGuestView()->GetGuestMainFrame()->GetView());
content::RenderFrameSubmissionObserver frame_observer(
GetGuestView()->GetGuestMainFrame());
frame_observer.WaitForMetadataChange();
// Kill guest.
auto* rph = GetGuestView()->GetGuestMainFrame()->GetProcess();
content::RenderProcessHostWatcher crash_observer(
rph, content::RenderProcessHostWatcher::WATCH_FOR_PROCESS_EXIT);
EXPECT_TRUE(rph->Shutdown(content::RESULT_CODE_KILLED));
crash_observer.Wait();
EXPECT_FALSE(GetGuestView()->GetGuestMainFrame()->GetView());
// Reload guest and make sure it appears.
content::TestFrameNavigationObserver load_observer(
GetGuestView()->GetGuestMainFrame());
EXPECT_TRUE(ExecJs(GetEmbedderWebContents(),
"document.querySelector('webview').reload()"));
load_observer.Wait();
EXPECT_TRUE(GetGuestView()->GetGuestMainFrame()->GetView());
// Ensure that the guest produces a new frame.
frame_observer.WaitForAnyFrameSubmission();
}
// The presence of DomAutomationController interferes with these tests, so we
// disable it.
class WebViewTestNoDomAutomationController : public WebViewTest {
public:
~WebViewTestNoDomAutomationController() override = default;
void SetUpInProcessBrowserTestFixture() override {
WebViewTest::SetUpInProcessBrowserTestFixture();
// DomAutomationController is added in BrowserTestBase::SetUp, so we need
// to remove it here instead of in SetUpCommandLine.
base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
base::CommandLine new_command_line(command_line->GetProgram());
base::CommandLine::SwitchMap switches = command_line->GetSwitches();
switches.erase(switches::kDomAutomationController);
for (const auto& s : switches)
new_command_line.AppendSwitchNative(s.first, s.second);
*command_line = new_command_line;
}
};
INSTANTIATE_TEST_SUITE_P(/* no prefix */,
WebViewTestNoDomAutomationController,
testing::Bool(),
WebViewTestNoDomAutomationController::DescribeParams);
// Tests that a webview inside an iframe can load and that it is destroyed when
// the iframe is detached.
// We need to disable DomAutomationController because it forces the creation of
// a script context. We want to test that we handle the case where there is no
// script context for the iframe. See crbug.com/788914
IN_PROC_BROWSER_TEST_P(WebViewTestNoDomAutomationController,
LoadWebviewInsideIframe) {
TestHelper("testLoadWebviewInsideIframe",
"web_view/load_webview_inside_iframe", NEEDS_TEST_SERVER);
ASSERT_TRUE(GetGuestViewManager()->GetLastGuestRenderFrameHostCreated());
// Remove the iframe.
content::ExecuteScriptAsync(GetEmbedderWebContents(),
"document.querySelector('iframe').remove()");
// Wait for guest to be destroyed.
GetGuestViewManager()->WaitForLastGuestDeleted();
}
IN_PROC_BROWSER_TEST_P(WebViewAccessibilityTest, LoadWebViewAccessibility) {
content::ScopedAccessibilityModeOverride mode_override(ui::kAXModeComplete);
LoadAppWithGuest("web_view/focus_accessibility");
content::WebContents* web_contents = GetFirstAppWindowWebContents();
content::WaitForAccessibilityTreeToContainNodeWithName(web_contents,
"Guest button");
}
IN_PROC_BROWSER_TEST_P(WebViewAccessibilityTest, FocusAccessibility) {
SKIP_FOR_MPARCH(); // TODO(crbug.com/40202416): Enable test for MPArch.
content::ScopedAccessibilityModeOverride mode_override(ui::kAXModeComplete);
LoadAppWithGuest("web_view/focus_accessibility");
content::WebContents* web_contents = GetFirstAppWindowWebContents();
// Wait for focus to land on the "root web area" role, representing
// focus on the main document itself.
while (content::GetFocusedAccessibilityNodeInfo(web_contents).role !=
ax::mojom::Role::kRootWebArea) {
content::WaitForAccessibilityFocusChange();
}
// Now keep pressing the Tab key until focus lands on a button.
while (content::GetFocusedAccessibilityNodeInfo(web_contents).role !=
ax::mojom::Role::kButton) {
content::SimulateKeyPress(web_contents, ui::DomKey::FromCharacter('\t'),
ui::DomCode::TAB, ui::VKEY_TAB, false, false,
false, false);
content::WaitForAccessibilityFocusChange();
}
// Ensure that we hit the button inside the guest frame labeled
// "Guest button".
ui::AXNodeData node_data =
content::GetFocusedAccessibilityNodeInfo(web_contents);
EXPECT_EQ("Guest button",
node_data.GetStringAttribute(ax::mojom::StringAttribute::kName));
}
// Validate that an inner frame within a guest WebContents correctly receives
// focus when requested by accessibility. Previously the root
// BrowserAccessibilityManager would not be updated due to how we were updating
// the AXTreeData.
// The test was disabled. See crbug.com/1141313.
IN_PROC_BROWSER_TEST_P(WebViewAccessibilityTest,
DISABLED_FocusAccessibilityNestedFrame) {
content::ScopedAccessibilityModeOverride mode_override(ui::kAXModeComplete);
LoadAppWithGuest("web_view/focus_accessibility");
content::WebContents* web_contents = GetFirstAppWindowWebContents();
// Wait for focus to land on the "root web area" role, representing
// focus on the main document itself.
while (content::GetFocusedAccessibilityNodeInfo(web_contents).role !=
ax::mojom::Role::kRootWebArea) {
content::WaitForAccessibilityFocusChange();
}
// Now keep pressing the Tab key until focus lands on a text field.
// This is testing that the inner frame within the guest WebContents receives
// focus, and that the focus state is accurately reflected in the accessiblity
// state.
while (content::GetFocusedAccessibilityNodeInfo(web_contents).role !=
ax::mojom::Role::kTextField) {
content::SimulateKeyPress(web_contents, ui::DomKey::FromCharacter('\t'),
ui::DomCode::TAB, ui::VKEY_TAB, false, false,
false, false);
content::WaitForAccessibilityFocusChange();
}
ui::AXNodeData node_data =
content::GetFocusedAccessibilityNodeInfo(web_contents);
EXPECT_EQ("InnerFrameTextField",
node_data.GetStringAttribute(ax::mojom::StringAttribute::kName));
}
class WebContentsAccessibilityEventWatcher
: public content::WebContentsObserver {
public:
WebContentsAccessibilityEventWatcher(content::WebContents* web_contents,
ax::mojom::Event event)
: content::WebContentsObserver(web_contents), event_(event), count_(0) {}
~WebContentsAccessibilityEventWatcher() override = default;
void Wait() {
if (count_ == 0) {
run_loop_ = std::make_unique<base::RunLoop>();
run_loop_->Run();
}
}
void AccessibilityEventReceived(
const ui::AXUpdatesAndEvents& event_bundle) override {
bool found = false;
int event_node_id = 0;
for (auto& event : event_bundle.events) {
if (event.event_type == event_) {
event_node_id = event.id;
found = true;
break;
}
}
if (!found)
return;
for (auto& update : event_bundle.updates) {
for (auto& node : update.nodes) {
if (node.id == event_node_id) {
count_++;
node_data_ = node;
run_loop_->Quit();
return;
}
}
}
}
size_t count() const { return count_; }
const ui::AXNodeData& node_data() const { return node_data_; }
private:
std::unique_ptr<base::RunLoop> run_loop_;
ax::mojom::Event event_;
ui::AXNodeData node_data_;
size_t count_;
};
IN_PROC_BROWSER_TEST_P(WebViewAccessibilityTest, DISABLED_TouchAccessibility) {
content::ScopedAccessibilityModeOverride mode_override(ui::kAXModeComplete);
LoadAppWithGuest("web_view/touch_accessibility");
content::WebContents* web_contents = GetFirstAppWindowWebContents();
content::WebContents* guest_web_contents = GetGuestWebContents();
// Listen for accessibility events on both WebContents.
WebContentsAccessibilityEventWatcher main_event_watcher(
web_contents, ax::mojom::Event::kHover);
WebContentsAccessibilityEventWatcher guest_event_watcher(
guest_web_contents, ax::mojom::Event::kHover);
// Send an accessibility touch event to the main WebContents, but
// positioned on top of the button inside the inner WebView.
blink::WebMouseEvent accessibility_touch_event(
blink::WebInputEvent::Type::kMouseMove,
blink::WebInputEvent::kIsTouchAccessibility,
blink::WebInputEvent::GetStaticTimeStampForTests());
accessibility_touch_event.SetPositionInWidget(95, 55);
web_contents->GetPrimaryMainFrame()
->GetRenderViewHost()
->GetWidget()
->ForwardMouseEvent(accessibility_touch_event);
// Ensure that we got just a single hover event on the guest WebContents,
// and that it was fired on a button.
guest_event_watcher.Wait();
ui::AXNodeData hit_node = guest_event_watcher.node_data();
EXPECT_EQ(1U, guest_event_watcher.count());
EXPECT_EQ(ax::mojom::Role::kButton, hit_node.role);
EXPECT_EQ(0U, main_event_watcher.count());
}
class WebViewGuestScrollTest
: public WebViewTestBase,
public testing::WithParamInterface<testing::tuple<bool, bool>> {
public:
WebViewGuestScrollTest() {
scoped_feature_list_.InitWithFeatureState(features::kGuestViewMPArch,
testing::get<1>(GetParam()));
}
bool GetScrollParam() { return testing::get<0>(GetParam()); }
static std::string DescribeParams(
const testing::TestParamInfo<ParamType>& info) {
const auto [disable_scroll, mparch] = info.param;
return base::StringPrintf(
"%s_%s", disable_scroll ? "ScrollDisabled" : "ScrollEnabled",
mparch ? "MPArch" : "InnerWebContents");
}
private:
base::test::ScopedFeatureList scoped_feature_list_;
};
class WebViewGuestScrollTouchTest : public WebViewGuestScrollTest {
protected:
void SetUpCommandLine(base::CommandLine* command_line) override {
WebViewGuestScrollTest::SetUpCommandLine(command_line);
command_line->AppendSwitchASCII(
switches::kTouchEventFeatureDetection,
switches::kTouchEventFeatureDetectionEnabled);
}
};
// Tests that scrolls bubble from guest to embedder.
// Create two test instances, one where the guest body is scrollable and the
// other where the body is not scrollable: fast-path scrolling will generate
// different ack results in between these two cases.
INSTANTIATE_TEST_SUITE_P(WebViewScrollBubbling,
WebViewGuestScrollTest,
testing::Combine(testing::Bool(), testing::Bool()),
WebViewGuestScrollTest::DescribeParams);
IN_PROC_BROWSER_TEST_P(WebViewGuestScrollTest, TestGuestWheelScrollsBubble) {
LoadAppWithGuest("web_view/scrollable_embedder_and_guest");
if (GetScrollParam())
SendMessageToGuestAndWait("set_overflow_hidden", "overflow_is_hidden");
content::WebContents* embedder_contents = GetEmbedderWebContents();
content::RenderFrameSubmissionObserver embedder_frame_observer(
embedder_contents);
std::vector<content::RenderFrameHost*> guest_rfh_list;
GetGuestViewManager()->WaitForNumGuestsCreated(1u);
GetGuestViewManager()->GetGuestRenderFrameHostList(&guest_rfh_list);
ASSERT_EQ(1u, guest_rfh_list.size());
content::RenderFrameHost* guest_rfh = guest_rfh_list[0];
content::RenderFrameSubmissionObserver guest_frame_observer(guest_rfh);
content::RenderWidgetHostView* guest_host_view = guest_rfh->GetView();
gfx::Rect embedder_rect = embedder_contents->GetContainerBounds();
gfx::Rect guest_rect = guest_host_view->GetViewBounds();
guest_rect.set_x(guest_rect.x() - embedder_rect.x());
guest_rect.set_y(guest_rect.y() - embedder_rect.y());
embedder_rect.set_x(0);
embedder_rect.set_y(0);
gfx::PointF default_offset;
embedder_frame_observer.WaitForScrollOffset(default_offset);
// Send scroll gesture to embedder & verify.
// Make sure wheel events don't get filtered.
float scroll_magnitude = 15.f;
display::ScreenInfo screen_info = guest_host_view->GetScreenInfo();
{
// Scroll the embedder from a position in the embedder that is not over
// the guest.
gfx::Point embedder_scroll_location = gfx::ScaleToRoundedPoint(
gfx::Point(embedder_rect.x() + embedder_rect.width() / 2,
(embedder_rect.y() + guest_rect.y()) / 2),
1 / screen_info.device_scale_factor);
gfx::PointF expected_offset(
0.f, scroll_magnitude * screen_info.device_scale_factor);
content::SimulateMouseEvent(embedder_contents,
blink::WebInputEvent::Type::kMouseMove,
embedder_scroll_location);
content::SimulateMouseWheelEvent(embedder_contents,
embedder_scroll_location,
gfx::Vector2d(0, -scroll_magnitude),
blink::WebMouseWheelEvent::kPhaseBegan);
embedder_frame_observer.WaitForScrollOffset(expected_offset);
}
guest_frame_observer.WaitForScrollOffset(default_offset);
// Send scroll gesture to guest and verify embedder scrolls.
// Perform a scroll gesture of the same magnitude, but in the opposite
// direction and centered over the GuestView this time.
guest_rect = guest_rfh->GetView()->GetViewBounds();
embedder_rect = embedder_contents->GetContainerBounds();
guest_rect.set_x(guest_rect.x() - embedder_rect.x());
guest_rect.set_y(guest_rect.y() - embedder_rect.y());
{
gfx::Point guest_scroll_location = gfx::ScaleToRoundedPoint(
gfx::Point(guest_rect.x() + guest_rect.width() / 2, guest_rect.y()),
1 / screen_info.device_scale_factor);
content::SimulateMouseEvent(embedder_contents,
blink::WebInputEvent::Type::kMouseMove,
guest_scroll_location);
content::SimulateMouseWheelEvent(embedder_contents, guest_scroll_location,
gfx::Vector2d(0, scroll_magnitude),
blink::WebMouseWheelEvent::kPhaseChanged);
embedder_frame_observer.WaitForScrollOffset(default_offset);
}
}
// Test that when we bubble scroll from a guest, the guest does not also
// consume the scroll.
IN_PROC_BROWSER_TEST_P(WebViewGuestScrollTest,
ScrollLatchingPreservedInGuests) {
LoadAppWithGuest("web_view/scrollable_embedder_and_guest");
content::WebContents* embedder_contents = GetEmbedderWebContents();
content::RenderFrameSubmissionObserver embedder_frame_observer(
embedder_contents);
std::vector<content::RenderFrameHost*> guest_rfh_list;
GetGuestViewManager()->WaitForNumGuestsCreated(1u);
GetGuestViewManager()->GetGuestRenderFrameHostList(&guest_rfh_list);
ASSERT_EQ(1u, guest_rfh_list.size());
content::RenderFrameHost* guest_rfh = guest_rfh_list[0];
content::RenderFrameSubmissionObserver guest_frame_observer(guest_rfh);
content::RenderWidgetHostView* guest_host_view = guest_rfh->GetView();
gfx::PointF default_offset;
guest_frame_observer.WaitForScrollOffset(default_offset);
embedder_frame_observer.WaitForScrollOffset(default_offset);
gfx::PointF guest_scroll_location(1, 1);
gfx::PointF guest_scroll_location_in_root =
guest_host_view->TransformPointToRootCoordSpaceF(guest_scroll_location);
// When the guest is already scrolled to the top, scroll up so that we bubble
// scroll.
blink::WebGestureEvent scroll_begin(
blink::WebGestureEvent::Type::kGestureScrollBegin,
blink::WebInputEvent::kNoModifiers,
blink::WebInputEvent::GetStaticTimeStampForTests(),
blink::WebGestureDevice::kTouchpad);
scroll_begin.SetPositionInWidget(guest_scroll_location);
scroll_begin.SetPositionInScreen(guest_scroll_location_in_root);
scroll_begin.data.scroll_begin.delta_x_hint = 0;
scroll_begin.data.scroll_begin.delta_y_hint = 5;
content::SimulateGestureEvent(guest_rfh->GetRenderWidgetHost(), scroll_begin,
ui::LatencyInfo());
content::InputEventAckWaiter update_waiter(
guest_rfh->GetRenderWidgetHost(),
base::BindRepeating([](blink::mojom::InputEventResultSource,
blink::mojom::InputEventResultState state,
const blink::WebInputEvent& event) {
return event.GetType() ==
blink::WebGestureEvent::Type::kGestureScrollUpdate &&
state != blink::mojom::InputEventResultState::kConsumed;
}));
blink::WebGestureEvent scroll_update(
blink::WebGestureEvent::Type::kGestureScrollUpdate,
blink::WebInputEvent::kNoModifiers,
blink::WebInputEvent::GetStaticTimeStampForTests(),
scroll_begin.SourceDevice());
scroll_update.SetPositionInWidget(scroll_begin.PositionInWidget());
scroll_update.SetPositionInScreen(scroll_begin.PositionInScreen());
scroll_update.data.scroll_update.delta_x =
scroll_begin.data.scroll_begin.delta_x_hint;
scroll_update.data.scroll_update.delta_y =
scroll_begin.data.scroll_begin.delta_y_hint;
content::SimulateGestureEvent(guest_rfh->GetRenderWidgetHost(), scroll_update,
ui::LatencyInfo());
update_waiter.Wait();
update_waiter.Reset();
// TODO(jonross): This test is only waiting on InputEventAckWaiter, but has an
// implicit wait on frame submission. InputEventAckWaiter needs to be updated
// to support VizDisplayCompositor, when it is, it should be tied to frame
// tokens which will allow for synchronizing with frame submission for further
// verifying metadata (crbug.com/812012)
guest_frame_observer.WaitForScrollOffset(default_offset);
// Now we switch directions and scroll down. The guest can scroll in this
// direction, but since we're bubbling, the guest should not consume this.
scroll_update.data.scroll_update.delta_y = -5;
content::SimulateGestureEvent(guest_rfh->GetRenderWidgetHost(), scroll_update,
ui::LatencyInfo());
update_waiter.Wait();
guest_frame_observer.WaitForScrollOffset(default_offset);
}
INSTANTIATE_TEST_SUITE_P(WebViewScrollBubbling,
WebViewGuestScrollTouchTest,
testing::Combine(testing::Bool(), testing::Bool()),
WebViewGuestScrollTouchTest::DescribeParams);
IN_PROC_BROWSER_TEST_P(WebViewGuestScrollTouchTest,
TestGuestGestureScrollsBubble) {
// Just in case we're running ChromeOS tests, we need to make sure the
// debounce interval is set to zero so our back-to-back gesture-scrolls don't
// get munged together. Since the first scroll will be put on the fast
// (compositor) path, while the second one should always be slow-path so it
// gets to BrowserPlugin, having them merged is definitely an error.
ui::GestureConfiguration* gesture_config =
ui::GestureConfiguration::GetInstance();
gesture_config->set_scroll_debounce_interval_in_ms(0);
LoadAppWithGuest("web_view/scrollable_embedder_and_guest");
if (GetScrollParam())
SendMessageToGuestAndWait("set_overflow_hidden", "overflow_is_hidden");
content::WebContents* embedder_contents = GetEmbedderWebContents();
content::RenderFrameSubmissionObserver embedder_frame_observer(
embedder_contents);
std::vector<content::RenderFrameHost*> guest_rfh_list;
GetGuestViewManager()->WaitForNumGuestsCreated(1u);
GetGuestViewManager()->GetGuestRenderFrameHostList(&guest_rfh_list);
ASSERT_EQ(1u, guest_rfh_list.size());
content::RenderFrameHost* guest_frame = guest_rfh_list[0];
content::RenderFrameSubmissionObserver guest_frame_observer(guest_frame);
gfx::Rect embedder_rect = embedder_contents->GetContainerBounds();
gfx::Rect guest_rect = guest_frame->GetView()->GetViewBounds();
guest_rect.set_x(guest_rect.x() - embedder_rect.x());
guest_rect.set_y(guest_rect.y() - embedder_rect.y());
embedder_rect.set_x(0);
embedder_rect.set_y(0);
gfx::PointF default_offset;
embedder_frame_observer.WaitForScrollOffset(default_offset);
// Send scroll gesture to embedder & verify.
float gesture_distance = 15.f;
{
// Scroll the embedder from a position in the embedder that is not over
// the guest.
gfx::Point embedder_scroll_location(
embedder_rect.x() + embedder_rect.width() / 2,
(embedder_rect.y() + guest_rect.y()) / 2);
gfx::PointF expected_offset(0.f, gesture_distance);
content::SimulateGestureScrollSequence(
embedder_contents, embedder_scroll_location,
gfx::Vector2dF(0, -gesture_distance));
embedder_frame_observer.WaitForScrollOffset(expected_offset);
}
// Check that the guest has not scrolled.
guest_frame_observer.WaitForScrollOffset(default_offset);
// Send scroll gesture to guest and verify embedder scrolls.
// Perform a scroll gesture of the same magnitude, but in the opposite
// direction and centered over the GuestView this time.
guest_rect = guest_frame->GetView()->GetViewBounds();
{
gfx::Point guest_scroll_location(guest_rect.width() / 2,
guest_rect.height() / 2);
content::SimulateGestureScrollSequence(guest_frame->GetRenderWidgetHost(),
guest_scroll_location,
gfx::Vector2dF(0, gesture_distance));
embedder_frame_observer.WaitForScrollOffset(default_offset);
}
}
// This runs the chrome://chrome-signin page which includes an OOPIF-<webview>
// of accounts.google.com.
class ChromeSignInWebViewTest : public WebViewTest {
public:
ChromeSignInWebViewTest() = default;
~ChromeSignInWebViewTest() override = default;
protected:
void WaitForWebViewInDom() {
auto* web_contents = browser()->tab_strip_model()->GetActiveWebContents();
auto* script =
"var count = 10;"
"var interval;"
"interval = setInterval(function(){"
" if (document.querySelector('inline-login-app').shadowRoot"
" .querySelector('webview')) {"
" document.title = 'success';"
" console.log('FOUND webview');"
" clearInterval(interval);"
" } else if (count == 0) {"
" document.title = 'error';"
" clearInterval(interval);"
" } else {"
" count -= 1;"
" }"
"}, 1000);";
ExecuteScriptWaitForTitle(web_contents, script, "success");
}
};
INSTANTIATE_TEST_SUITE_P(/* no prefix */,
ChromeSignInWebViewTest,
testing::Bool(),
ChromeSignInWebViewTest::DescribeParams);
#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_MAC) || BUILDFLAG(IS_WIN)
// This verifies the fix for http://crbug.com/667708.
IN_PROC_BROWSER_TEST_P(ChromeSignInWebViewTest,
ClosingChromeSignInShouldNotCrash) {
SKIP_FOR_MPARCH(); // TODO(crbug.com/40202416): Enable test for MPArch.
GURL signin_url{"chrome://chrome-signin/?reason=5"};
ASSERT_TRUE(AddTabAtIndex(0, signin_url, ui::PAGE_TRANSITION_TYPED));
ASSERT_TRUE(AddTabAtIndex(1, signin_url, ui::PAGE_TRANSITION_TYPED));
WaitForWebViewInDom();
chrome::CloseTab(browser());
}
#endif
// This test verifies that unattached guests are not included as the inner
// WebContents. The test verifies this by triggering a find-in-page request on a
// page with both an attached and an unattached <webview> and verifies that,
// unlike the attached guest, no find requests are sent for the unattached
// guest. For more context see https://crbug.com/897465.
IN_PROC_BROWSER_TEST_P(ChromeSignInWebViewTest,
NoFindInPageForUnattachedGuest) {
SKIP_FOR_MPARCH(); // TODO(crbug.com/40202416): Enable test for MPArch.
GURL signin_url{"chrome://chrome-signin/?reason=5"};
ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), signin_url));
// Navigate a tab to a page with a <webview>.
auto* embedder_web_contents =
browser()->tab_strip_model()->GetActiveWebContents();
auto* attached_guest_view =
GetGuestViewManager()->WaitForSingleGuestViewCreated();
ASSERT_TRUE(attached_guest_view);
auto* find_helper =
find_in_page::FindTabHelper::FromWebContents(embedder_web_contents);
// Wait until a first GuestView is attached.
GetGuestViewManager()->WaitUntilAttached(attached_guest_view);
base::RunLoop run_loop;
// This callback is called before attaching a second GuestView.
GetGuestViewManager()->SetWillAttachCallback(
base::BindLambdaForTesting([&](guest_view::GuestViewBase* guest_view) {
ASSERT_TRUE(guest_view);
ASSERT_FALSE(guest_view->attached());
auto* attached_guest_rfh = attached_guest_view->GetGuestMainFrame();
auto* unattached_guest_rfh = guest_view->GetGuestMainFrame();
EXPECT_NE(unattached_guest_rfh, attached_guest_rfh);
find_helper->StartFinding(u"doesn't matter", true, true, false);
auto pending = content::GetRenderFrameHostsWithPendingFindResults(
embedder_web_contents);
// Request for main frame of the tab.
EXPECT_EQ(1U,
pending.count(embedder_web_contents->GetPrimaryMainFrame()));
// Request for main frame of the attached guest.
EXPECT_EQ(1U, pending.count(attached_guest_rfh));
// No request for the unattached guest.
EXPECT_EQ(0U, pending.count(unattached_guest_rfh));
run_loop.Quit();
}));
// Now add a new <webview> and wait until its guest WebContents is created.
ExecuteScriptAsync(embedder_web_contents,
"var webview = document.createElement('webview');"
"webview.src = 'data:text/html,foo';"
"document.body.appendChild(webview);");
run_loop.Run();
}
// Ensure that WebRequest events are not dispatched to pages that are not the
// embedder of the source webview.
// See also testWebRequestAPIOnlyForInstance.
IN_PROC_BROWSER_TEST_P(ChromeSignInWebViewTest,
TestWebRequestOnlyDispatchToEmbedder) {
SKIP_FOR_MPARCH(); // TODO(crbug.com/40202416): Enable test for MPArch.
ASSERT_TRUE(StartEmbeddedTestServer());
// Load a WebUI with a webview. For testing convenience, we use the existing
// chrome signin page.
const GURL signin_url{"chrome://chrome-signin/?reason=5"};
ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), signin_url));
WaitForWebViewInDom();
content::WebContents* tab_contents =
browser()->tab_strip_model()->GetActiveWebContents();
// Set an onBeforeRequest handler on the WebUI's webview.
EXPECT_TRUE(content::ExecJs(
tab_contents,
"let wv = document.querySelector( "
" 'inline-login-app').shadowRoot.querySelector('webview'); "
"window.sawRequest = false; "
"wv.request.onBeforeRequest.addListener((details) => { "
" console.log('Unexpected request event', details.url); "
" window.sawRequest = true; "
" return {cancel: true}; "
"}, {types: ['main_frame'], urls: ['<all_urls>']}, "
"['blocking']);"));
// Launch an app that creates and loads its own webview. The app will get
// WebRequest events for its webview.
TestHelper("testWebRequestAPI", "web_view/shim", NO_TEST_SERVER);
// The WebUI should not see the events for the app's webview.
EXPECT_EQ(false, content::EvalJs(tab_contents, "window.sawRequest;"));
}
// This test class makes "isolated.com" an isolated origin, to be used in
// testing isolated origins inside of a WebView.
class IsolatedOriginWebViewTest : public WebViewTest {
public:
IsolatedOriginWebViewTest() = default;
~IsolatedOriginWebViewTest() override = default;
protected:
void SetUpCommandLine(base::CommandLine* command_line) override {
ASSERT_TRUE(embedded_test_server()->InitializeAndListen());
std::string origin =
embedded_test_server()->GetURL("isolated.com", "/").spec();
command_line->AppendSwitchASCII(switches::kIsolateOrigins, origin);
WebViewTest::SetUpCommandLine(command_line);
}
void SetUpOnMainThread() override {
host_resolver()->AddRule("*", "127.0.0.1");
embedded_test_server()->StartAcceptingConnections();
WebViewTest::SetUpOnMainThread();
}
};
INSTANTIATE_TEST_SUITE_P(/* no prefix */,
IsolatedOriginWebViewTest,
testing::Bool(),
IsolatedOriginWebViewTest::DescribeParams);
// Test isolated origins inside a WebView, and make sure that loading an
// isolated origin in a regular tab's subframe doesn't reuse a WebView process
// that had loaded it previously, which would result in renderer kills. See
// https://crbug.com/751916 and https://crbug.com/751920.
IN_PROC_BROWSER_TEST_P(IsolatedOriginWebViewTest, IsolatedOriginInWebview) {
LoadAppWithGuest("web_view/simple");
guest_view::GuestViewBase* guest = GetGuestView();
// Navigate <webview> to an isolated origin.
GURL isolated_url(
embedded_test_server()->GetURL("isolated.com", "/title1.html"));
{
content::TestFrameNavigationObserver load_observer(
guest->GetGuestMainFrame());
EXPECT_TRUE(ExecJs(guest->GetGuestMainFrame(),
"location.href = '" + isolated_url.spec() + "';"));
load_observer.Wait();
}
EXPECT_TRUE(guest->GetGuestMainFrame()->GetSiteInstance()->IsGuest());
// Now, navigate <webview> to a regular page with a subframe.
GURL foo_url(embedded_test_server()->GetURL("foo.com", "/iframe.html"));
{
content::TestFrameNavigationObserver load_observer(
guest->GetGuestMainFrame());
EXPECT_TRUE(ExecJs(guest->GetGuestMainFrame(),
"location.href = '" + foo_url.spec() + "';"));
load_observer.Wait();
}
// Navigate subframe in <webview> to an isolated origin.
EXPECT_TRUE(NavigateToURLFromRenderer(
ChildFrameAt(guest->GetGuestMainFrame(), 0), isolated_url));
// Since <webview> supports site isolation, the subframe will be in its own
// SiteInstance and process.
content::RenderFrameHost* webview_subframe =
ChildFrameAt(guest->GetGuestMainFrame(), 0);
EXPECT_NE(webview_subframe->GetProcess(),
guest->GetGuestMainFrame()->GetProcess());
EXPECT_NE(webview_subframe->GetSiteInstance(),
guest->GetGuestMainFrame()->GetSiteInstance());
// Load a page with subframe in a regular tab.
ASSERT_TRUE(AddTabAtIndex(0, foo_url, ui::PAGE_TRANSITION_TYPED));
content::WebContents* tab =
browser()->tab_strip_model()->GetActiveWebContents();
// Navigate that subframe to an isolated origin. This should not join the
// WebView process, which has isolated.foo.com committed in a different
// storage partition.
EXPECT_TRUE(NavigateIframeToURL(tab, "test", isolated_url));
content::RenderFrameHost* subframe =
ChildFrameAt(tab->GetPrimaryMainFrame(), 0);
EXPECT_NE(guest->GetGuestMainFrame()->GetProcess(), subframe->GetProcess());
// Check that the guest process hasn't crashed.
EXPECT_TRUE(guest->GetGuestMainFrame()->IsRenderFrameLive());
// Check that accessing a foo.com cookie from the WebView doesn't result in a
// renderer kill. This might happen if we erroneously applied an isolated.com
// origin lock to the WebView process when committing isolated.com.
EXPECT_EQ(true, EvalJs(guest->GetGuestMainFrame(),
"document.cookie = 'foo=bar';\n"
"document.cookie == 'foo=bar';\n"));
}
// This test is similar to IsolatedOriginInWebview above, but loads an isolated
// origin in a <webview> subframe *after* loading the same isolated origin in a
// regular tab's subframe. The isolated origin's subframe in the <webview>
// subframe should not reuse the regular tab's subframe process. See
// https://crbug.com/751916 and https://crbug.com/751920.
IN_PROC_BROWSER_TEST_P(IsolatedOriginWebViewTest,
LoadIsolatedOriginInWebviewAfterLoadingInRegularTab) {
LoadAppWithGuest("web_view/simple");
guest_view::GuestViewBase* guest = GetGuestView();
// Load a page with subframe in a regular tab.
GURL foo_url(embedded_test_server()->GetURL("foo.com", "/iframe.html"));
ASSERT_TRUE(AddTabAtIndex(0, foo_url, ui::PAGE_TRANSITION_TYPED));
content::WebContents* tab =
browser()->tab_strip_model()->GetActiveWebContents();
// Navigate that subframe to an isolated origin.
GURL isolated_url(
embedded_test_server()->GetURL("isolated.com", "/title1.html"));
EXPECT_TRUE(NavigateIframeToURL(tab, "test", isolated_url));
content::RenderFrameHost* subframe =
ChildFrameAt(tab->GetPrimaryMainFrame(), 0);
EXPECT_NE(tab->GetPrimaryMainFrame()->GetProcess(), subframe->GetProcess());
// Navigate <webview> to a regular page with an isolated origin subframe.
{
content::TestFrameNavigationObserver load_observer(
guest->GetGuestMainFrame());
EXPECT_TRUE(ExecJs(guest->GetGuestMainFrame(),
"location.href = '" + foo_url.spec() + "';"));
load_observer.Wait();
}
EXPECT_TRUE(NavigateToURLFromRenderer(
ChildFrameAt(guest->GetGuestMainFrame(), 0), isolated_url));
// Since <webview> supports site isolation, the subframe will be in its own
// SiteInstance and process.
content::RenderFrameHost* webview_subframe =
ChildFrameAt(guest->GetGuestMainFrame(), 0);
EXPECT_NE(webview_subframe->GetProcess(),
guest->GetGuestMainFrame()->GetProcess());
EXPECT_NE(webview_subframe->GetSiteInstance(),
guest->GetGuestMainFrame()->GetSiteInstance());
// The isolated origin subframe in <webview> shouldn't share the process with
// the isolated origin subframe in the regular tab.
EXPECT_NE(webview_subframe->GetProcess(), subframe->GetProcess());
// Check that the guest and regular tab processes haven't crashed.
EXPECT_TRUE(guest->GetGuestMainFrame()->IsRenderFrameLive());
EXPECT_TRUE(tab->GetPrimaryMainFrame()->IsRenderFrameLive());
EXPECT_TRUE(subframe->IsRenderFrameLive());
// Check that accessing a foo.com cookie from the WebView doesn't result in a
// renderer kill. This might happen if we erroneously applied an isolated.com
// origin lock to the WebView process when committing isolated.com.
EXPECT_EQ(true, EvalJs(guest->GetGuestMainFrame(),
"document.cookie = 'foo=bar';\n"
"document.cookie == 'foo=bar';\n"));
}
// Sends an auto-resize message to the RenderWidgetHost and ensures that the
// auto-resize transaction is handled and produces a single response message
// from guest to embedder.
IN_PROC_BROWSER_TEST_P(WebViewTest, AutoResizeMessages) {
LoadAppWithGuest("web_view/simple");
// Helper function as this test requires inspecting a number of content::
// internal objects.
EXPECT_TRUE(content::TestGuestAutoresize(GetEmbedderWebContents(),
GetGuestRenderFrameHost()));
}
// Test that a guest sees the synthetic wheel events of a touchpad pinch.
IN_PROC_BROWSER_TEST_P(WebViewTest, TouchpadPinchSyntheticWheelEvents) {
ASSERT_TRUE(StartEmbeddedTestServer());
LoadAppWithGuest("web_view/touchpad_pinch");
content::RenderFrameHost* render_frame_host =
GetGuestView()->GetGuestMainFrame();
content::WaitForHitTestData(render_frame_host);
content::RenderWidgetHost* render_widget_host =
render_frame_host->GetRenderWidgetHost();
// Ensure the compositor thread is aware of the wheel listener.
content::MainThreadFrameObserver synchronize_threads(render_widget_host);
synchronize_threads.Wait();
ExtensionTestMessageListener synthetic_wheel_listener("Seen wheel event");
const gfx::Rect guest_rect = render_widget_host->GetView()->GetViewBounds();
const gfx::Point pinch_position(guest_rect.width() / 2,
guest_rect.height() / 2);
content::SimulateGesturePinchSequence(render_widget_host, pinch_position,
1.23,
blink::WebGestureDevice::kTouchpad);
ASSERT_TRUE(synthetic_wheel_listener.WaitUntilSatisfied());
}
// Tests that we can open and close a devtools window that inspects a contents
// containing a guest view without crashing.
IN_PROC_BROWSER_TEST_P(WebViewTest, OpenAndCloseDevTools) {
LoadAppWithGuest("web_view/simple");
content::WebContents* embedder = GetEmbedderWebContents();
DevToolsWindow* devtools = DevToolsWindowTesting::OpenDevToolsWindowSync(
embedder, false /* is_docked */);
DevToolsWindowTesting::CloseDevToolsWindowSync(devtools);
}
// Tests that random extensions cannot inject content scripts into a platform
// app's own webview, but the owner platform app can. Regression test for
// crbug.com/1205675.
IN_PROC_BROWSER_TEST_P(WebViewTest, NoExtensionScriptsInjectedInWebview) {
ASSERT_TRUE(StartEmbeddedTestServer()); // For serving guest pages.
// Load an extension which injects a content script at document_end. The
// script injects a new element into the DOM.
LoadExtension(
test_data_dir_.AppendASCII("api_test/content_scripts/inject_div"));
// Load a platform app which creates a webview and injects a content script
// into it at document_idle, after document_end. The script expects that the
// webview's DOM has not been modified (in this case, by the extension's
// content script).
ExtensionTestMessageListener app_content_script_listener(
"WebViewTest.NO_ELEMENT_INJECTED");
app_content_script_listener.set_failure_message(
"WebViewTest.UNKNOWN_ELEMENT_INJECTED");
LoadAppWithGuest("web_view/a_com_webview");
// The app's content script should have been injected, but the extension's
// content script should not have.
EXPECT_TRUE(app_content_script_listener.WaitUntilSatisfied())
<< "'" << app_content_script_listener.message()
<< "' message was not receieved";
}
// Regression test for https://crbug.com/1014385
// We load an extension whose background page attempts to declare variables with
// names that are the same as guest view types. The declarations should not be
// syntax errors.
using GuestViewExtensionNameCollisionTest = extensions::ExtensionBrowserTest;
IN_PROC_BROWSER_TEST_F(GuestViewExtensionNameCollisionTest,
GuestViewNamesDoNotCollideWithExtensions) {
ExtensionTestMessageListener loaded_listener("LOADED");
const extensions::Extension* extension =
LoadExtension(test_data_dir_.AppendASCII(
"platform_apps/web_view/no_extension_name_collision"));
ASSERT_TRUE(loaded_listener.WaitUntilSatisfied());
const std::string script =
"chrome.test.sendScriptResult("
" window.testPassed ? 'PASSED' : 'FAILED');";
const base::Value test_passed =
ExecuteScriptInBackgroundPage(extension->id(), script);
EXPECT_EQ("PASSED", test_passed);
}
class LocalNetworkAccessWebViewTest : public WebViewTest {
public:
LocalNetworkAccessWebViewTest() {
std::vector<base::test::FeatureRefAndParams> enabled_features = {
{network::features::kLocalNetworkAccessChecks,
{{"LocalNetworkAccessChecksWarn", "false"}}}};
std::vector<base::test::FeatureRef> disabled_features;
if (GetParam()) {
enabled_features.push_back({features::kGuestViewMPArch, {}});
} else {
disabled_features.push_back(features::kGuestViewMPArch);
}
features_.InitWithFeaturesAndParameters(std::move(enabled_features),
std::move(disabled_features));
}
void SetUpCommandLine(base::CommandLine* command_line) override {
WebViewTest::SetUpCommandLine(command_line);
// Clear default from InProcessBrowserTest as test doesn't want 127.0.0.1 in
// the public address space
command_line->AppendSwitchASCII(network::switches::kIpAddressSpaceOverrides,
"");
}
private:
base::test::ScopedFeatureList features_;
};
INSTANTIATE_TEST_SUITE_P(/* no prefix */,
LocalNetworkAccessWebViewTest,
testing::Bool(),
LocalNetworkAccessWebViewTest::DescribeParams);
// Verify that Local Network Access has the correct understanding of guests.
// The loopback/local/public classification should not be affected by being
// within a guest. See https://crbug.com/1167698 for details.
//
// Note: This test is put in this file for convenience of reusing the entire
// app testing infrastructure. Other similar tests that do not require that
// infrastructure live in LocalNetworkAccessBrowserTest.*
IN_PROC_BROWSER_TEST_P(LocalNetworkAccessWebViewTest, ClassificationInGuest) {
LoadAppWithGuest("web_view/simple");
content::RenderFrameHost* guest_frame_host = GetGuestRenderFrameHost();
ASSERT_TRUE(guest_frame_host);
EXPECT_TRUE(guest_frame_host->GetSiteInstance()->IsGuest());
// We'll try to fetch a local page with Access-Control-Allow-Origin: *, to
// avoid having origin issues on top of privateness issues.
auto server = std::make_unique<net::EmbeddedTestServer>();
server->AddDefaultHandlers(GetChromeTestDataDir());
EXPECT_TRUE(server->Start());
GURL fetch_url = server->GetURL("/cors-ok.txt");
// The webview "simple" page is a first navigation to a raw data url. It is
// currently considered public (internally
// `network::mojom::IPAddressSpace::kUnknown`).
EXPECT_THAT(content::EvalJs(
guest_frame_host,
content::JsReplace("fetch($1).then(response => response.ok)",
fetch_url)),
content::EvalJsResult::IsError());
}
// Verify that navigating a <webview> subframe to a disallowed extension
// resource (where the extension ID doesn't match the <webview> owner) doesn't
// result in a renderer kill. See https://crbug.com/1204094.
IN_PROC_BROWSER_TEST_P(WebViewTest, LoadDisallowedExtensionURLInSubframe) {
SKIP_FOR_MPARCH(); // TODO(crbug.com/40202416): Enable test for MPArch.
ASSERT_TRUE(StartEmbeddedTestServer());
base::RunLoop run_loop;
LoadAppWithGuest("web_view/simple");
content::RenderFrameHost* guest = GetGuestView()->GetGuestMainFrame();
const extensions::Extension* extension = LoadExtension(
test_data_dir_.AppendASCII("web_accessible_resources/subframe"));
ASSERT_TRUE(extension);
GURL extension_url =
extension->ResolveExtensionURL("web_accessible_page.html");
GURL iframe_url(embedded_test_server()->GetURL("/title1.html"));
std::string setup_iframe_script = R"(
var iframe = document.createElement('iframe');
iframe.id = 'subframe';
document.body.appendChild(iframe);
)";
EXPECT_TRUE(content::ExecJs(guest, setup_iframe_script));
content::RenderFrameHost* webview_subframe = ChildFrameAt(guest, 0);
EXPECT_TRUE(content::NavigateToURLFromRenderer(webview_subframe, iframe_url));
// Navigate the subframe to an unrelated extension URL. This shouldn't
// terminate the renderer. If it does, this test will fail via
// content::NoRendererCrashesAssertion().
webview_subframe = ChildFrameAt(guest, 0);
EXPECT_FALSE(
content::NavigateToURLFromRenderer(webview_subframe, extension_url));
// The navigation should be aborted and the iframe should be left at its old
// URL.
EXPECT_EQ(webview_subframe->GetLastCommittedURL(), iframe_url);
}
class PopupWaiter : public content::WebContentsObserver {
public:
PopupWaiter(content::WebContents* opener, base::OnceClosure on_popup)
: content::WebContentsObserver(opener), on_popup_(std::move(on_popup)) {}
// WebContentsObserver:
// Note that `DidOpenRequestedURL` is used as it fires precisely after a new
// WebContents is created but before it is shown. This timing is necessary for
// the `ShutdownWithUnshownPopup` test.
void DidOpenRequestedURL(content::WebContents* new_contents,
content::RenderFrameHost* source_render_frame_host,
const GURL& url,
const content::Referrer& referrer,
WindowOpenDisposition disposition,
ui::PageTransition transition,
bool started_from_context_menu,
bool renderer_initiated) override {
if (on_popup_) {
std::move(on_popup_).Run();
}
}
private:
base::OnceClosure on_popup_;
};
// Test destroying an opener webview while the created window has not been
// shown by the renderer. Between the time of the renderer creating and showing
// the new window, the created guest WebContents is owned by content/ and not by
// WebViewGuest. See `WebContentsImpl::pending_contents_` for details. When we
// destroy the new WebViewGuest, content/ must ensure that the guest WebContents
// is destroyed safely.
//
// This test is conceptually similar to
// testNewWindowOpenerDestroyedWhileUnattached, but for this test, we have
// precise timing requirements that need to be controlled by the browser such
// that we shutdown while the new window is pending.
//
// Regression test for https://crbug.com/1442516
IN_PROC_BROWSER_TEST_P(WebViewTest, ShutdownWithUnshownPopup) {
SKIP_FOR_MPARCH(); // TODO(crbug.com/40202416): Enable test for MPArch.
ASSERT_TRUE(StartEmbeddedTestServer());
// Core classes in content often record trace events during destruction.
// Enable tracing to test that writing traces with partially destructed
// objects is done safely.
ASSERT_TRUE(tracing::BeginTracing("content,navigation"));
LoadAppWithGuest("web_view/simple");
base::RunLoop run_loop;
PopupWaiter popup_waiter(GetGuestWebContents(), run_loop.QuitClosure());
content::ExecuteScriptAsync(GetGuestRenderFrameHost(),
"window.open(location.href);");
run_loop.Run();
CloseAppWindow(GetFirstAppWindow());
}
IN_PROC_BROWSER_TEST_P(WebViewTest, InsertIntoIframe) {
TestHelper("testInsertIntoIframe", "web_view/shim", NEEDS_TEST_SERVER);
}
IN_PROC_BROWSER_TEST_P(WebViewTest, CreateAndInsertInIframe) {
TestHelper("testCreateAndInsertInIframe", "web_view/shim", NEEDS_TEST_SERVER);
}
IN_PROC_BROWSER_TEST_P(WebViewTest, InsertIntoMainFrameFromIframe) {
TestHelper("testInsertIntoMainFrameFromIframe", "web_view/shim",
NEEDS_TEST_SERVER);
}
IN_PROC_BROWSER_TEST_P(WebViewTest, InsertIntoOtherWindow) {
TestHelper("testInsertIntoOtherWindow", "web_view/shim", NEEDS_TEST_SERVER);
}
IN_PROC_BROWSER_TEST_P(WebViewTest, CreateAndInsertInOtherWindow) {
TestHelper("testCreateAndInsertInOtherWindow", "web_view/shim",
NEEDS_TEST_SERVER);
}
IN_PROC_BROWSER_TEST_P(WebViewTest, InsertFromOtherWindow) {
TestHelper("testInsertFromOtherWindow", "web_view/shim", NEEDS_TEST_SERVER);
}
IN_PROC_BROWSER_TEST_P(WebViewTest, InsertIntoDetachedIframe) {
TestHelper("testInsertIntoDetachedIframe", "web_view/shim",
NEEDS_TEST_SERVER);
// Round-trip to ensure the embedder did not crash.
EXPECT_EQ(true, content::EvalJs(GetFirstAppWindowWebContents(), "true"));
}
// Ensure that if a <webview>'s name is set, the guest preserves the
// corresponding window.name across navigations and after a crash and reload.
IN_PROC_BROWSER_TEST_P(WebViewTest, PreserveNameAcrossNavigationsAndCrashes) {
ASSERT_TRUE(StartEmbeddedTestServer());
LoadAppWithGuest("web_view/simple");
GetGuestViewManager()->WaitForSingleGuestRenderFrameHostCreated();
content::WebContents* embedder = GetEmbedderWebContents();
EXPECT_TRUE(
ExecJs(embedder, "document.querySelector('webview').name = 'foo';"));
extensions::WebViewGuest* guest =
extensions::WebViewGuest::FromGuestViewBase(GetGuestView());
EXPECT_EQ("foo", guest->name());
// Changing the <webview> attribute also changes the current guest
// document's window.name (see webViewInternal.setName).
EXPECT_EQ("foo", content::EvalJs(GetGuestRenderFrameHost(), "window.name"));
// Ensure that the guest's new window.name is preserved across navigations.
const GURL url_1 = embedded_test_server()->GetURL("a.test", "/title1.html");
EXPECT_TRUE(
content::NavigateToURLFromRenderer(GetGuestRenderFrameHost(), url_1));
EXPECT_EQ("foo", content::EvalJs(GetGuestRenderFrameHost(), "window.name"));
const GURL url_2 = embedded_test_server()->GetURL("b.test", "/title1.html");
EXPECT_TRUE(
content::NavigateToURLFromRenderer(GetGuestRenderFrameHost(), url_2));
EXPECT_EQ("foo", content::EvalJs(GetGuestRenderFrameHost(), "window.name"));
// Crash the guest.
auto* rph = GetGuestRenderFrameHost()->GetProcess();
content::RenderProcessHostWatcher crash_observer(
rph, content::RenderProcessHostWatcher::WATCH_FOR_PROCESS_EXIT);
EXPECT_TRUE(rph->Shutdown(content::RESULT_CODE_KILLED));
crash_observer.Wait();
// Reload guest and make sure its window.name is preserved.
content::TestFrameNavigationObserver load_observer(GetGuestRenderFrameHost());
EXPECT_TRUE(ExecJs(embedder, "document.querySelector('webview').reload()"));
load_observer.Wait();
EXPECT_EQ("foo", content::EvalJs(GetGuestRenderFrameHost(), "window.name"));
}
#if BUILDFLAG(ENABLE_PPAPI)
class WebViewPPAPITest : public WebViewTest {
protected:
void SetUpCommandLine(base::CommandLine* command_line) override {
WebViewTest::SetUpCommandLine(command_line);
ASSERT_TRUE(ppapi::RegisterTestPlugin(command_line));
}
};
INSTANTIATE_TEST_SUITE_P(/* no prefix */,
WebViewPPAPITest,
testing::Bool(),
WebViewPPAPITest::DescribeParams);
IN_PROC_BROWSER_TEST_P(WebViewPPAPITest, Shim_TestPlugin) {
TestHelper("testPlugin", "web_view/shim", NO_TEST_SERVER);
}
IN_PROC_BROWSER_TEST_P(WebViewPPAPITest, Shim_TestPluginLoadPermission) {
TestHelper("testPluginLoadPermission", "web_view/shim", NO_TEST_SERVER);
}
#endif // BUILDFLAG(ENABLE_PPAPI)
// Domain which the Webstore hosted app is associated with in production.
constexpr char kWebstoreURL[] = "https://chrome.google.com/";
// Domain which the new Webstore is associated with in production.
constexpr char kNewWebstoreURL[] = "https://chromewebstore.google.com/";
// Domain for testing an overridden Webstore URL.
constexpr char kWebstoreURLOverride[] = "https://webstore.override.test.com/";
// Helper class for setting up and testing webview behavior with the Chrome
// Webstore. The test param contains the Webstore URL to test.
class WebstoreWebViewTest
: public WebViewTestBase,
public testing::WithParamInterface<testing::tuple<GURL, bool>> {
public:
WebstoreWebViewTest()
: https_server_(net::EmbeddedTestServer::TYPE_HTTPS),
webstore_url_(testing::get<0>(GetParam())) {
scoped_feature_list_.InitWithFeatureState(features::kGuestViewMPArch,
testing::get<1>(GetParam()));
}
WebstoreWebViewTest(const WebstoreWebViewTest&) = delete;
WebstoreWebViewTest& operator=(const WebstoreWebViewTest&) = delete;
~WebstoreWebViewTest() override = default;
void SetUpCommandLine(base::CommandLine* command_line) override {
// Serve files from the extensions test directory as it has a
// /webstore/ directory, which the Webstore hosted app expects for the URL
// it is associated with.
https_server_.ServeFilesFromSourceDirectory("chrome/test/data/extensions");
ASSERT_TRUE(https_server_.InitializeAndListen());
command_line->AppendSwitchASCII(
network::switches::kHostResolverRules,
"MAP * " + https_server_.host_port_pair().ToString());
// Only override the webstore URL if this test case is testing the override.
if (webstore_url().spec() == kWebstoreURLOverride) {
command_line->AppendSwitchASCII(::switches::kAppsGalleryURL,
kWebstoreURLOverride);
}
mock_cert_verifier_.SetUpCommandLine(command_line);
WebViewTestBase::SetUpCommandLine(command_line);
}
void SetUpOnMainThread() override {
https_server_.StartAcceptingConnections();
mock_cert_verifier_.mock_cert_verifier()->set_default_result(net::OK);
WebViewTestBase::SetUpOnMainThread();
}
void SetUpInProcessBrowserTestFixture() override {
WebViewTestBase::SetUpInProcessBrowserTestFixture();
mock_cert_verifier_.SetUpInProcessBrowserTestFixture();
}
void TearDownInProcessBrowserTestFixture() override {
WebViewTestBase::TearDownInProcessBrowserTestFixture();
mock_cert_verifier_.TearDownInProcessBrowserTestFixture();
}
net::EmbeddedTestServer* https_server() { return &https_server_; }
GURL webstore_url() { return webstore_url_; }
// Provides meaningful param names.
static std::string DescribeParams(
const testing::TestParamInfo<ParamType>& info) {
const auto& [webstore_url_str, mparch] = info.param;
std::string name_for_url = [&]() {
GURL webstore_url(webstore_url_str);
if (webstore_url.spec() == kWebstoreURL) {
return "OldWebstore";
}
if (webstore_url.spec() == kWebstoreURLOverride) {
return "WebstoreOverride";
}
return "NewWebstore";
}();
return base::StringPrintf("%s_%s", name_for_url,
mparch ? "MPArch" : "InnerWebContents");
}
private:
net::EmbeddedTestServer https_server_;
content::ContentMockCertVerifier mock_cert_verifier_;
GURL webstore_url_;
base::test::ScopedFeatureList scoped_feature_list_;
};
INSTANTIATE_TEST_SUITE_P(
WebViewTests,
WebstoreWebViewTest,
testing::Combine(testing::Values(GURL(kWebstoreURL),
GURL(kWebstoreURLOverride),
GURL(kNewWebstoreURL)),
testing::Bool()),
WebstoreWebViewTest::DescribeParams);
// Ensure that an attempt to load Chrome Web Store in a <webview> is blocked
// and does not result in a renderer kill. See https://crbug.com/1197674.
IN_PROC_BROWSER_TEST_P(WebstoreWebViewTest, NoRendererKillWithChromeWebStore) {
LoadAppWithGuest("web_view/simple");
content::RenderFrameHost* guest = GetGuestRenderFrameHost();
ASSERT_TRUE(guest);
// Navigate <webview> to a Chrome Web Store URL. This should result in an
// error and shouldn't lead to a renderer kill. Note: the webstore hosted app
// requires the path to start with /webstore/, so for simplicity we serve a
// page from this path for all the different webstore URLs under test.
const GURL url = webstore_url().Resolve("/webstore/mock_store.html");
content::TestFrameNavigationObserver error_observer(guest);
EXPECT_TRUE(ExecJs(guest, "location.href = '" + url.spec() + "';"));
error_observer.Wait();
EXPECT_EQ(net::ERR_BLOCKED_BY_CLIENT, error_observer.last_net_error_code());
guest = GetGuestRenderFrameHost();
EXPECT_TRUE(guest->IsRenderFrameLive());
// Double-check that after the attempted navigation the <webview> is not
// considered an extension process and does not have the privileged webstore
// API.
auto* process_map = extensions::ProcessMap::Get(guest->GetBrowserContext());
EXPECT_FALSE(process_map->Contains(guest->GetProcess()->GetDeprecatedID()));
EXPECT_FALSE(process_map->GetExtensionIdForProcess(
guest->GetProcess()->GetDeprecatedID()));
EXPECT_EQ(false, content::EvalJs(guest, "!!chrome.webstorePrivate"));
}
// This is a group of tests that check site isolation properties in <webview>
// guests. Note that site isolation in <webview> is always enabled.
class SitePerProcessWebViewTest : public WebViewTest {
protected:
[[nodiscard]] bool BrowserInitNavigationToUrl(
guest_view::GuestViewBase* guest,
const GURL& url) {
if (base::FeatureList::IsEnabled(features::kGuestViewMPArch)) {
content::NavigationController::LoadURLParams params(url);
// Some tests need a transition that will allow a BrowsingInstance swap.
params.transition_type = ui::PageTransitionFromInt(
ui::PAGE_TRANSITION_TYPED | ui::PAGE_TRANSITION_FROM_ADDRESS_BAR);
content::TestFrameNavigationObserver load_observer(
guest->GetGuestMainFrame());
guest->GetController().LoadURLWithParams(params);
load_observer.Wait();
return load_observer.last_navigation_succeeded();
} else {
return content::NavigateToURL(guest->web_contents(), url);
}
}
};
INSTANTIATE_TEST_SUITE_P(/* no prefix */,
SitePerProcessWebViewTest,
testing::Bool(),
SitePerProcessWebViewTest::DescribeParams);
// Checks basic site isolation properties when a <webview> main frame and
// subframe navigate cross-site.
IN_PROC_BROWSER_TEST_P(SitePerProcessWebViewTest, SimpleNavigations) {
ASSERT_TRUE(StartEmbeddedTestServer());
// Load an app with a <webview> guest that starts at a data: URL.
LoadAppWithGuest("web_view/simple");
guest_view::GuestViewBase* guest = GetGuestView();
ASSERT_TRUE(guest);
// Ensure the <webview>'s SiteInstance is for a guest.
content::RenderFrameHost* main_frame = guest->GetGuestMainFrame();
auto original_id = main_frame->GetGlobalId();
scoped_refptr<content::SiteInstance> starting_instance =
main_frame->GetSiteInstance();
EXPECT_TRUE(starting_instance->IsGuest());
EXPECT_TRUE(starting_instance->GetProcess()->IsForGuestsOnly());
EXPECT_FALSE(starting_instance->GetStoragePartitionConfig().is_default());
// Navigate <webview> to a cross-site page with a same-site iframe.
const GURL start_url =
embedded_test_server()->GetURL("a.test", "/iframe.html");
{
content::TestFrameNavigationObserver load_observer(main_frame);
EXPECT_TRUE(
ExecJs(main_frame, "location.href = '" + start_url.spec() + "';"));
load_observer.Wait();
}
// Expect that the main frame swapped SiteInstances and RenderFrameHosts but
// stayed in the same BrowsingInstance and StoragePartition.
main_frame = guest->GetGuestMainFrame();
EXPECT_TRUE(main_frame->GetSiteInstance()->IsGuest());
EXPECT_TRUE(main_frame->GetProcess()->IsForGuestsOnly());
EXPECT_NE(main_frame->GetGlobalId(), original_id);
EXPECT_NE(starting_instance, main_frame->GetSiteInstance());
EXPECT_TRUE(
starting_instance->IsRelatedSiteInstance(main_frame->GetSiteInstance()));
EXPECT_EQ(starting_instance->GetStoragePartitionConfig(),
main_frame->GetSiteInstance()->GetStoragePartitionConfig());
EXPECT_EQ(
starting_instance->GetOrCreateProcessForTesting()->GetStoragePartition(),
main_frame->GetProcess()->GetStoragePartition());
// Ensure the guest SiteInstance reflects the proper site and actually uses
// site isolation.
EXPECT_EQ("http://a.test/",
main_frame->GetSiteInstance()->GetSiteURL().spec());
EXPECT_TRUE(main_frame->GetSiteInstance()->RequiresDedicatedProcess());
EXPECT_TRUE(main_frame->GetProcess()->IsProcessLockedToSiteForTesting());
// Navigate <webview> subframe cross-site. Check that it ends up in a
// separate guest SiteInstance and process, but same StoragePartition.
const GURL frame_url =
embedded_test_server()->GetURL("b.test", "/title1.html");
content::RenderFrameHost* subframe = content::ChildFrameAt(main_frame, 0);
ASSERT_TRUE(subframe);
EXPECT_TRUE(NavigateToURLFromRenderer(subframe, frame_url));
subframe = content::ChildFrameAt(main_frame, 0);
EXPECT_NE(main_frame->GetSiteInstance(), subframe->GetSiteInstance());
EXPECT_NE(main_frame->GetProcess(), subframe->GetProcess());
EXPECT_TRUE(subframe->GetSiteInstance()->IsGuest());
EXPECT_TRUE(subframe->GetProcess()->IsForGuestsOnly());
EXPECT_TRUE(main_frame->GetSiteInstance()->IsRelatedSiteInstance(
subframe->GetSiteInstance()));
EXPECT_EQ(subframe->GetSiteInstance()->GetStoragePartitionConfig(),
main_frame->GetSiteInstance()->GetStoragePartitionConfig());
EXPECT_EQ(subframe->GetProcess()->GetStoragePartition(),
main_frame->GetProcess()->GetStoragePartition());
EXPECT_EQ("http://b.test/", subframe->GetSiteInstance()->GetSiteURL().spec());
EXPECT_TRUE(subframe->GetSiteInstance()->RequiresDedicatedProcess());
EXPECT_TRUE(subframe->GetProcess()->IsProcessLockedToSiteForTesting());
}
// Check that site-isolated guests can navigate to error pages. Due to error
// page isolation, error pages in guests should end up in a new error
// SiteInstance, which should still be a guest SiteInstance in the guest's
// StoragePartition.
IN_PROC_BROWSER_TEST_P(SitePerProcessWebViewTest, ErrorPageIsolation) {
ASSERT_TRUE(StartEmbeddedTestServer());
ASSERT_TRUE(content::SiteIsolationPolicy::IsErrorPageIsolationEnabled(
/*in_main_frame=*/true));
// Load an app with a <webview> guest that starts at a data: URL.
LoadAppWithGuest("web_view/simple");
ASSERT_TRUE(GetGuestRenderFrameHost());
scoped_refptr<content::SiteInstance> first_instance =
GetGuestRenderFrameHost()->GetSiteInstance();
EXPECT_TRUE(first_instance->IsGuest());
// Navigate <webview> to an error page.
const GURL error_url =
embedded_test_server()->GetURL("a.test", "/iframe.html");
auto interceptor = content::URLLoaderInterceptor::SetupRequestFailForURL(
error_url, net::ERR_NAME_NOT_RESOLVED);
{
content::TestFrameNavigationObserver load_observer(
GetGuestRenderFrameHost());
EXPECT_TRUE(ExecJs(GetGuestRenderFrameHost(),
"location.href = '" + error_url.spec() + "';"));
load_observer.Wait();
EXPECT_FALSE(load_observer.last_navigation_succeeded());
EXPECT_TRUE(GetGuestRenderFrameHost()->IsErrorDocument());
}
// The error page's SiteInstance should require a dedicated process due to
// error page isolation, but it should still be considered a guest and should
// stay in the guest's StoragePartition.
scoped_refptr<content::SiteInstance> error_instance =
GetGuestRenderFrameHost()->GetSiteInstance();
EXPECT_TRUE(error_instance->RequiresDedicatedProcess());
EXPECT_NE(error_instance, first_instance);
EXPECT_TRUE(error_instance->IsGuest());
EXPECT_EQ(first_instance->GetStoragePartitionConfig(),
error_instance->GetStoragePartitionConfig());
// Navigate to a normal page and then repeat the above with an
// embedder-initiated navigation to an error page.
EXPECT_TRUE(BrowserInitNavigationToUrl(
GetGuestView(),
embedded_test_server()->GetURL("b.test", "/iframe.html")));
EXPECT_FALSE(GetGuestRenderFrameHost()->IsErrorDocument());
EXPECT_NE(GetGuestRenderFrameHost()->GetSiteInstance(), error_instance);
content::WebContents* embedder = GetEmbedderWebContents();
{
content::TestFrameNavigationObserver load_observer(
GetGuestRenderFrameHost());
EXPECT_TRUE(ExecJs(embedder, "document.querySelector('webview').src = '" +
error_url.spec() + "';"));
load_observer.Wait();
EXPECT_FALSE(load_observer.last_navigation_succeeded());
EXPECT_TRUE(GetGuestRenderFrameHost()->IsErrorDocument());
}
scoped_refptr<content::SiteInstance> second_error_instance =
GetGuestRenderFrameHost()->GetSiteInstance();
EXPECT_TRUE(second_error_instance->RequiresDedicatedProcess());
EXPECT_TRUE(second_error_instance->IsGuest());
EXPECT_EQ(first_instance->GetStoragePartitionConfig(),
second_error_instance->GetStoragePartitionConfig());
// Because we swapped BrowsingInstances above, this error page SiteInstance
// should be different from the first error page SiteInstance, but it should
// be in the same StoragePartition.
EXPECT_NE(error_instance, second_error_instance);
EXPECT_EQ(error_instance->GetStoragePartitionConfig(),
second_error_instance->GetStoragePartitionConfig());
}
// Ensure that the browser doesn't crash when a subframe in a <webview> is
// navigated to an unknown scheme. This used to be the case due to a mismatch
// between the error page's SiteInstance and the origin to commit as calculated
// in NavigationRequest. See https://crbug.com/1366450.
IN_PROC_BROWSER_TEST_P(SitePerProcessWebViewTest, ErrorPageInSubframe) {
ASSERT_TRUE(StartEmbeddedTestServer());
// Load an app with a <webview> guest that starts at a data: URL.
LoadAppWithGuest("web_view/simple");
ASSERT_TRUE(GetGuestRenderFrameHost());
scoped_refptr<content::SiteInstance> first_instance =
GetGuestRenderFrameHost()->GetSiteInstance();
EXPECT_TRUE(first_instance->IsGuest());
// Navigate <webview> to a page with an iframe.
const GURL first_url =
embedded_test_server()->GetURL("a.test", "/iframe.html");
{
content::TestFrameNavigationObserver load_observer(
GetGuestRenderFrameHost());
EXPECT_TRUE(ExecJs(GetGuestRenderFrameHost(),
"location.href = '" + first_url.spec() + "';"));
load_observer.Wait();
EXPECT_TRUE(load_observer.last_navigation_succeeded());
}
// At this point, the guest's iframe should already be loaded. Navigate
// it to an unknown scheme, which will result in an error. This shouldn't
// crash the browser.
content::RenderFrameHost* guest_subframe =
ChildFrameAt(GetGuestRenderFrameHost(), 0);
int initial_process_id = guest_subframe->GetProcess()->GetDeprecatedID();
const GURL error_url = GURL("unknownscheme:foo");
{
content::TestFrameNavigationObserver load_observer(guest_subframe);
EXPECT_TRUE(
ExecJs(guest_subframe, "location.href = '" + error_url.spec() + "';"));
load_observer.Wait();
EXPECT_FALSE(load_observer.last_navigation_succeeded());
auto* error_rfh = ChildFrameAt(GetGuestRenderFrameHost(), 0);
EXPECT_TRUE(error_rfh->IsErrorDocument());
// Double-check that the error page has an opaque origin, and that the
// precursor doesn't point to a.test.
url::Origin error_origin = error_rfh->GetLastCommittedOrigin();
EXPECT_TRUE(error_origin.opaque());
EXPECT_FALSE(error_origin.GetTupleOrPrecursorTupleIfOpaque().IsValid());
// The error page should not load in the initiator's process.
EXPECT_NE(initial_process_id, error_rfh->GetProcess()->GetDeprecatedID());
}
}
// Checks that a main frame navigation in a <webview> can swap
// BrowsingInstances while staying in the same StoragePartition.
IN_PROC_BROWSER_TEST_P(SitePerProcessWebViewTest, BrowsingInstanceSwap) {
ASSERT_TRUE(StartEmbeddedTestServer());
// Load an app with a <webview> guest that starts at a data: URL.
LoadAppWithGuest("web_view/simple");
ASSERT_TRUE(GetGuestRenderFrameHost());
// Navigate <webview> to a page on a.test.
const GURL first_url =
embedded_test_server()->GetURL("a.test", "/iframe.html");
{
content::TestFrameNavigationObserver load_observer(
GetGuestRenderFrameHost());
EXPECT_TRUE(ExecJs(GetGuestRenderFrameHost(),
"location.href = '" + first_url.spec() + "';"));
load_observer.Wait();
}
scoped_refptr<content::SiteInstance> first_instance =
GetGuestRenderFrameHost()->GetSiteInstance();
EXPECT_TRUE(first_instance->IsGuest());
EXPECT_TRUE(first_instance->GetProcess()->IsForGuestsOnly());
// Navigate <webview> to a cross-site page and use a browser-initiated
// navigation to force a BrowsingInstance swap.
const GURL second_url =
embedded_test_server()->GetURL("b.test", "/title1.html");
EXPECT_TRUE(BrowserInitNavigationToUrl(GetGuestView(), second_url));
scoped_refptr<content::SiteInstance> second_instance =
GetGuestRenderFrameHost()->GetSiteInstance();
// Ensure that a new unrelated guest SiteInstance was created, and that the
// StoragePartition didn't change.
EXPECT_TRUE(second_instance->IsGuest());
EXPECT_TRUE(second_instance->GetProcess()->IsForGuestsOnly());
EXPECT_NE(first_instance, second_instance);
EXPECT_FALSE(first_instance->IsRelatedSiteInstance(second_instance.get()));
EXPECT_EQ(first_instance->GetStoragePartitionConfig(),
second_instance->GetStoragePartitionConfig());
EXPECT_EQ(
first_instance->GetOrCreateProcessForTesting()->GetStoragePartition(),
second_instance->GetProcess()->GetStoragePartition());
}
// Helper class to count the number of guest processes created.
class GuestProcessCreationObserver
: public content::RenderProcessHostCreationObserver {
public:
GuestProcessCreationObserver() = default;
~GuestProcessCreationObserver() override = default;
GuestProcessCreationObserver(const GuestProcessCreationObserver&) = delete;
GuestProcessCreationObserver& operator=(const GuestProcessCreationObserver&) =
delete;
// content::RenderProcessHostCreationObserver:
void OnRenderProcessHostCreated(
content::RenderProcessHost* process_host) override {
if (process_host->IsForGuestsOnly())
guest_process_count_++;
}
size_t guess_process_count() { return guest_process_count_; }
private:
size_t guest_process_count_ = 0U;
};
// Checks that a cross-process navigation in a <webview> does not unnecessarily
// recreate the guest process at OnResponseStarted time.
IN_PROC_BROWSER_TEST_P(SitePerProcessWebViewTest,
NoExtraGuestProcessAtResponseTime) {
ASSERT_TRUE(StartEmbeddedTestServer());
// Load an app with a <webview> guest that starts at a data: URL.
LoadAppWithGuest("web_view/simple");
ASSERT_TRUE(GetGuestView());
// Start a navigation in the <webview> to a cross-site page and use a
// browser-initiated navigation to force a BrowsingInstance swap.
const GURL guest_url =
embedded_test_server()->GetURL("a.test", "/title1.html");
GuestProcessCreationObserver observer;
EXPECT_TRUE(BrowserInitNavigationToUrl(GetGuestView(), guest_url));
// This should only trigger creation of one additional guest process. There
// used to be a bug where a speculative RenderFrameHost that was created
// initially was incorrectly thrown away and recreated when the response was
// received, leading to an additional wasted guest process. Note that since
// speculative RenderFrameHosts aren't exposed outside of content/, we can't
// directly observe them here.
EXPECT_EQ(1U, observer.guess_process_count());
}
// Test that both webview-initiated and embedder-initiated navigations to
// about:blank behave sanely.
IN_PROC_BROWSER_TEST_P(SitePerProcessWebViewTest, NavigateToAboutBlank) {
ASSERT_TRUE(StartEmbeddedTestServer());
// Load an app with a <webview> guest that starts at a data: URL.
LoadAppWithGuest("web_view/simple");
ASSERT_TRUE(GetGuestRenderFrameHost());
scoped_refptr<content::SiteInstance> first_instance =
GetGuestRenderFrameHost()->GetSiteInstance();
EXPECT_TRUE(first_instance->IsGuest());
EXPECT_TRUE(first_instance->GetProcess()->IsForGuestsOnly());
// Ask <webview> to navigate itself to about:blank. This should stay in the
// same SiteInstance.
const GURL blank_url(url::kAboutBlankURL);
EXPECT_TRUE(
content::NavigateToURLFromRenderer(GetGuestRenderFrameHost(), blank_url));
scoped_refptr<content::SiteInstance> second_instance =
GetGuestRenderFrameHost()->GetSiteInstance();
EXPECT_EQ(first_instance, second_instance);
// Navigate <webview> away to another page. This should swap
// BrowsingInstances as it's a cross-site browser-initiated navigation.
const GURL second_url =
embedded_test_server()->GetURL("b.test", "/title1.html");
EXPECT_TRUE(BrowserInitNavigationToUrl(GetGuestView(), second_url));
ASSERT_TRUE(GetGuestRenderFrameHost());
scoped_refptr<content::SiteInstance> third_instance =
GetGuestRenderFrameHost()->GetSiteInstance();
EXPECT_TRUE(third_instance->IsGuest());
EXPECT_TRUE(third_instance->GetProcess()->IsForGuestsOnly());
EXPECT_NE(first_instance, third_instance);
EXPECT_FALSE(first_instance->IsRelatedSiteInstance(third_instance.get()));
EXPECT_EQ(first_instance->GetStoragePartitionConfig(),
third_instance->GetStoragePartitionConfig());
EXPECT_EQ(
first_instance->GetOrCreateProcessForTesting()->GetStoragePartition(),
third_instance->GetProcess()->GetStoragePartition());
// Ask embedder to navigate the webview back to about:blank. This should
// stay in the same SiteInstance.
content::WebContents* embedder = GetEmbedderWebContents();
{
content::TestFrameNavigationObserver load_observer(
GetGuestRenderFrameHost());
EXPECT_TRUE(ExecJs(embedder, "document.querySelector('webview').src = '" +
blank_url.spec() + "';"));
load_observer.Wait();
}
scoped_refptr<content::SiteInstance> fourth_instance =
GetGuestRenderFrameHost()->GetSiteInstance();
EXPECT_EQ(fourth_instance, third_instance);
}
// Test that site-isolated <webview> doesn't crash when its initial navigation
// is to an about:blank URL.
IN_PROC_BROWSER_TEST_P(SitePerProcessWebViewTest, Shim_BlankWebview) {
TestHelper("testBlankWebview", "web_view/shim", NO_TEST_SERVER);
content::RenderFrameHost* guest_rfh =
GetGuestViewManager()->WaitForSingleGuestRenderFrameHostCreated();
ASSERT_TRUE(guest_rfh);
scoped_refptr<content::SiteInstance> site_instance =
guest_rfh->GetSiteInstance();
EXPECT_TRUE(site_instance->IsGuest());
EXPECT_TRUE(site_instance->GetProcess()->IsForGuestsOnly());
}
// Checks that content scripts work when a <webview> navigates across multiple
// processes.
IN_PROC_BROWSER_TEST_P(SitePerProcessWebViewTest, ContentScript) {
SKIP_FOR_MPARCH(); // TODO(crbug.com/40202416): Enable test for MPArch.
ASSERT_TRUE(StartEmbeddedTestServer());
// Load an app with a <webview> guest that starts at a data: URL.
LoadAppWithGuest("web_view/simple");
content::WebContents* embedder = GetEmbedderWebContents();
content::RenderFrameHost* main_frame = GetGuestRenderFrameHost();
ASSERT_TRUE(main_frame);
auto* web_view_renderer_state =
extensions::WebViewRendererState::GetInstance();
// Ensure the <webview>'s SiteInstance is for a guest.
scoped_refptr<content::SiteInstance> starting_instance =
main_frame->GetSiteInstance();
EXPECT_TRUE(starting_instance->IsGuest());
// There should be no <webview> content scripts yet.
{
extensions::WebViewRendererState::WebViewInfo info;
ASSERT_TRUE(web_view_renderer_state->GetInfo(
main_frame->GetProcess()->GetDeprecatedID(), main_frame->GetRoutingID(),
&info));
EXPECT_TRUE(info.content_script_ids.empty());
}
// WebViewRendererState should have an entry for a single guest instance.
ASSERT_EQ(1u, web_view_renderer_state->guest_count_for_testing());
// Navigate <webview> to a.test. This should swap processes. Wait for the
// old RenderFrameHost to be destroyed and check that there's still a single
// guest instance.
const GURL start_url =
embedded_test_server()->GetURL("a.test", "/title1.html");
{
content::RenderFrameDeletedObserver deleted_observer(main_frame);
EXPECT_TRUE(BrowserInitNavigationToUrl(GetGuestView(), start_url));
deleted_observer.WaitUntilDeleted();
ASSERT_EQ(1u, web_view_renderer_state->guest_count_for_testing());
}
// Inject a content script.
{
const char kContentScriptTemplate[] = R"(
var webview = document.querySelector('webview');
webview.addContentScripts([{
name: 'rule',
matches: ['*://*/*'],
js: { code: $1 },
run_at: 'document_start'}]);
)";
const char kContentScript[] = R"(
chrome.test.sendMessage("Hello from content script!");
)";
EXPECT_TRUE(content::ExecJs(
embedder, content::JsReplace(kContentScriptTemplate, kContentScript)));
// Ensure the new content script is now tracked for the <webview> in the
// browser process.
main_frame = GetGuestRenderFrameHost();
{
extensions::WebViewRendererState::WebViewInfo info;
ASSERT_TRUE(web_view_renderer_state->GetInfo(
main_frame->GetProcess()->GetDeprecatedID(),
main_frame->GetRoutingID(), &info));
EXPECT_EQ(1U, info.content_script_ids.size());
}
}
// Navigate <webview> cross-site and ensure the new content script runs.
ExtensionTestMessageListener script_listener("Hello from content script!");
const GURL second_url =
embedded_test_server()->GetURL("b.test", "/title1.html");
{
content::RenderFrameDeletedObserver deleted_observer(main_frame);
EXPECT_TRUE(BrowserInitNavigationToUrl(GetGuestView(), second_url));
deleted_observer.WaitUntilDeleted();
ASSERT_EQ(1u, web_view_renderer_state->guest_count_for_testing());
}
EXPECT_TRUE(script_listener.WaitUntilSatisfied());
// Check that the content script is tracked for the new <webview> process.
main_frame = GetGuestRenderFrameHost();
EXPECT_TRUE(main_frame->GetSiteInstance()->IsGuest());
EXPECT_NE(main_frame->GetSiteInstance(), starting_instance);
{
extensions::WebViewRendererState::WebViewInfo info;
ASSERT_TRUE(web_view_renderer_state->GetInfo(
main_frame->GetProcess()->GetDeprecatedID(), main_frame->GetRoutingID(),
&info));
EXPECT_EQ(1U, info.content_script_ids.size());
}
// Remove the <webview> and ensure no guests remain in WebViewRendererState.
{
content::RenderFrameDeletedObserver deleted_observer(main_frame);
EXPECT_TRUE(content::ExecJs(embedder,
"document.querySelector('webview').remove()"));
deleted_observer.WaitUntilDeleted();
ASSERT_EQ(0u, web_view_renderer_state->guest_count_for_testing());
}
}
// Checks that content scripts work in an out-of-process iframe in a <webview>
// tag.
// TODO(crbug.com/40864752): Fix flakiness on win-rel and mac.
#if BUILDFLAG(IS_WIN) || BUILDFLAG(IS_MAC)
#define MAYBE_ContentScriptInOOPIF DISABLED_ContentScriptInOOPIF
#else
#define MAYBE_ContentScriptInOOPIF ContentScriptInOOPIF
#endif
IN_PROC_BROWSER_TEST_P(SitePerProcessWebViewTest, MAYBE_ContentScriptInOOPIF) {
ASSERT_TRUE(StartEmbeddedTestServer());
// Load an app with a <webview> guest that starts at a data: URL.
LoadAppWithGuest("web_view/simple");
content::WebContents* embedder = GetEmbedderWebContents();
content::RenderFrameHost* main_frame = GetGuestRenderFrameHost();
ASSERT_TRUE(main_frame);
auto* web_view_renderer_state =
extensions::WebViewRendererState::GetInstance();
// WebViewRendererState should have an entry for a single guest instance.
ASSERT_EQ(1u, web_view_renderer_state->guest_count_for_testing());
// Inject a content script that targets title1.html and is enabled for all
// frames (so that it works in subframes).
{
const char kContentScriptTemplate[] = R"(
var webview = document.querySelector('webview');
webview.addContentScripts([{
name: 'rule',
matches: ['*://*/title1.html'],
all_frames: true,
js: { code: $1 },
run_at: 'document_start'}]);
)";
const char kContentScript[] = R"(
chrome.test.sendMessage("Hello from content script!");
)";
EXPECT_TRUE(content::ExecJs(
embedder, content::JsReplace(kContentScriptTemplate, kContentScript)));
}
// Navigate <webview> to a page with a same-site subframe.
const GURL start_url =
embedded_test_server()->GetURL("a.test", "/iframe.html");
{
content::RenderFrameDeletedObserver deleted_observer(main_frame);
EXPECT_TRUE(BrowserInitNavigationToUrl(GetGuestView(), start_url));
deleted_observer.WaitUntilDeleted();
// There should be two guest frames at this point.
ASSERT_EQ(2u, web_view_renderer_state->guest_count_for_testing());
}
main_frame = GetGuestRenderFrameHost();
content::RenderFrameHost* subframe = content::ChildFrameAt(main_frame, 0);
// Navigate <webview> subframe cross-site to a URL that matches the content
// script pattern and ensure the new content script runs.
ExtensionTestMessageListener script_listener("Hello from content script!");
const GURL frame_url =
embedded_test_server()->GetURL("b.test", "/title1.html");
{
content::RenderFrameDeletedObserver deleted_observer(subframe);
EXPECT_TRUE(NavigateToURLFromRenderer(subframe, frame_url));
deleted_observer.WaitUntilDeleted();
subframe = content::ChildFrameAt(main_frame, 0);
EXPECT_TRUE(subframe->IsCrossProcessSubframe());
// There should still be two guest frames (main frame and new subframe).
ASSERT_EQ(2u, web_view_renderer_state->guest_count_for_testing());
}
EXPECT_TRUE(script_listener.WaitUntilSatisfied());
}
// Check that with site-isolated <webview>, two same-site OOPIFs in two
// unrelated <webview> tags share the same process due to the subframe process
// reuse policy.
IN_PROC_BROWSER_TEST_P(SitePerProcessWebViewTest, SubframeProcessReuse) {
SKIP_FOR_MPARCH(); // TODO(crbug.com/40202416): Enable test for MPArch.
ASSERT_TRUE(StartEmbeddedTestServer());
// Load an app with a <webview> guest that starts at a data: URL.
LoadAppWithGuest("web_view/simple");
guest_view::GuestViewBase* guest = GetGuestView();
ASSERT_TRUE(guest);
GetGuestViewManager()->WaitUntilAttached(guest);
// Navigate <webview> to a cross-site page with a same-site iframe.
const GURL start_url =
embedded_test_server()->GetURL("a.test", "/iframe.html");
EXPECT_TRUE(BrowserInitNavigationToUrl(guest, start_url));
// Navigate <webview> subframe cross-site.
const GURL frame_url =
embedded_test_server()->GetURL("b.test", "/title1.html");
content::RenderFrameHost* subframe =
content::ChildFrameAt(guest->GetGuestMainFrame(), 0);
EXPECT_TRUE(NavigateToURLFromRenderer(subframe, frame_url));
// Attach a second <webview>.
ASSERT_TRUE(content::ExecJs(
GetEmbedderWebContents(),
base::StrCat({"const w = document.createElement('webview'); w.src = '",
start_url.spec(), "'; document.body.appendChild(w);"})));
GetGuestViewManager()->WaitForNumGuestsCreated(2u);
auto* guest2 = GetGuestViewManager()->GetLastGuestViewCreated();
ASSERT_NE(guest, guest2);
GetGuestViewManager()->WaitUntilAttached(guest2);
// Navigate second <webview> cross-site. Use NavigateToURL() to swap
// BrowsingInstances.
const GURL second_guest_url =
embedded_test_server()->GetURL("c.test", "/iframe.html");
EXPECT_TRUE(BrowserInitNavigationToUrl(guest2, second_guest_url));
EXPECT_NE(guest->GetGuestMainFrame()->GetSiteInstance(),
guest2->GetGuestMainFrame()->GetSiteInstance());
EXPECT_NE(guest->GetGuestMainFrame()->GetProcess(),
guest2->GetGuestMainFrame()->GetProcess());
EXPECT_FALSE(
guest->GetGuestMainFrame()->GetSiteInstance()->IsRelatedSiteInstance(
guest2->GetGuestMainFrame()->GetSiteInstance()));
// Navigate second <webview> subframe to the same site as the first <webview>
// subframe, ending up with A(B) in `guest` and C(B) in `guest2`. These
// subframes should be in the same (guest's) StoragePartition, but different
// SiteInstances and BrowsingInstances. Nonetheless, due to the subframe
// reuse policy, they should share the same process.
content::RenderFrameHost* subframe2 =
content::ChildFrameAt(guest2->GetGuestMainFrame(), 0);
ASSERT_TRUE(subframe2);
EXPECT_TRUE(NavigateToURLFromRenderer(subframe2, frame_url));
subframe = content::ChildFrameAt(guest->GetGuestMainFrame(), 0);
subframe2 = content::ChildFrameAt(guest2->GetGuestMainFrame(), 0);
EXPECT_NE(subframe->GetSiteInstance(), subframe2->GetSiteInstance());
EXPECT_EQ(subframe->GetSiteInstance()->GetStoragePartitionConfig(),
subframe2->GetSiteInstance()->GetStoragePartitionConfig());
EXPECT_EQ(subframe->GetProcess(), subframe2->GetProcess());
}
// Helper class to turn off strict site isolation while still using site
// isolation paths for <webview>. This forces <webview> to use the default
// SiteInstance or default SiteInstanceGroup paths. The helper also defines one
// isolated origin at isolated.com, which takes precedence over the command-line
// switch to disable site isolation and can be used to test a combination of
// SiteInstances that require and don't require dedicated processes.
// This test is parameterized to run in MPArch or InnerWebContents mode, and
// DefaultSiteInstance or DefaultSiteInstanceGroup mode, totaling 4
// configurations.
class WebViewWithDefaultSiteInstanceTest
: public WebViewTestBase,
public testing::WithParamInterface<testing::tuple<bool, bool>> {
public:
WebViewWithDefaultSiteInstanceTest() = default;
~WebViewWithDefaultSiteInstanceTest() override = default;
WebViewWithDefaultSiteInstanceTest(
const WebViewWithDefaultSiteInstanceTest&) = delete;
WebViewWithDefaultSiteInstanceTest& operator=(
const WebViewWithDefaultSiteInstanceTest&) = delete;
void SetUpCommandLine(base::CommandLine* command_line) override {
command_line->AppendSwitch(switches::kDisableSiteIsolation);
command_line->AppendSwitchASCII(switches::kIsolateOrigins,
"http://isolated.com");
feature_list_.InitWithFeatureStates(
{{features::kGuestViewMPArch, testing::get<0>(GetParam())},
{features::kDefaultSiteInstanceGroups, testing::get<1>(GetParam())}});
WebViewTestBase::SetUpCommandLine(command_line);
}
content::test::FencedFrameTestHelper& fenced_frame_test_helper() {
return fenced_frame_test_helper_;
}
static std::string DescribeParams(
const testing::TestParamInfo<ParamType>& info) {
const auto [mparch, site_instance_group] = info.param;
return base::StringPrintf("%s_%s", mparch ? "MPArch" : "InnerWebContents",
site_instance_group ? "DefaultSiteInstanceGroups"
: "DefaultSiteInstances");
}
private:
content::test::FencedFrameTestHelper fenced_frame_test_helper_;
base::test::ScopedFeatureList feature_list_;
};
INSTANTIATE_TEST_SUITE_P(/* no prefix */,
WebViewWithDefaultSiteInstanceTest,
testing::Combine(testing::Bool(), testing::Bool()),
WebViewWithDefaultSiteInstanceTest::DescribeParams);
// Check that when strict site isolation is turned off (via a command-line
// flag or from chrome://flags), the <webview> site isolation paths still
// work. In particular, <webview> navigations should use a default
// SiteInstance or default SiteInstanceGroup which should still be considered
// a guest SiteInstance in the guest's StoragePartition. Cross-site
// navigations in the guest should stay in the same SiteInstance or
// SiteInstanceGroup, and the guest process shouldn't be locked.
IN_PROC_BROWSER_TEST_P(WebViewWithDefaultSiteInstanceTest, SimpleNavigations) {
ASSERT_TRUE(StartEmbeddedTestServer());
// Load an app with a <webview> guest that starts at a data: URL.
LoadAppWithGuest("web_view/simple");
content::RenderFrameHost* main_frame = GetGuestRenderFrameHost();
ASSERT_TRUE(main_frame);
auto original_id = main_frame->GetGlobalId();
scoped_refptr<content::SiteInstance> starting_instance =
main_frame->GetSiteInstance();
// Because this test runs without strict site isolation, the <webview>
// process shouldn't be locked. However, the <webview>'s process and
// SiteInstance should still be for a guest.
EXPECT_FALSE(
starting_instance->GetProcess()->IsProcessLockedToSiteForTesting());
EXPECT_FALSE(starting_instance->RequiresDedicatedProcess());
EXPECT_TRUE(starting_instance->IsGuest());
EXPECT_TRUE(starting_instance->GetProcess()->IsForGuestsOnly());
EXPECT_FALSE(starting_instance->GetStoragePartitionConfig().is_default());
// Navigate <webview> to a cross-site page with a same-site iframe.
const GURL start_url =
embedded_test_server()->GetURL("a.test", "/iframe.html");
{
content::TestFrameNavigationObserver load_observer(main_frame);
EXPECT_TRUE(
ExecJs(main_frame, "location.href = '" + start_url.spec() + "';"));
load_observer.Wait();
}
// Expect that we stayed in the same (default) SiteInstance or
// SiteInstanceGroup.
main_frame = GetGuestRenderFrameHost();
ASSERT_TRUE(main_frame);
if (base::FeatureList::IsEnabled(features::kDefaultSiteInstanceGroups)) {
EXPECT_NE(starting_instance, main_frame->GetSiteInstance());
EXPECT_EQ(starting_instance->GetSiteInstanceGroupId(),
main_frame->GetSiteInstance()->GetSiteInstanceGroupId());
} else {
EXPECT_EQ(starting_instance, main_frame->GetSiteInstance());
if (!main_frame->ShouldChangeRenderFrameHostOnSameSiteNavigation()) {
// The RenderFrameHost will stay the same when we don't change
// RenderFrameHosts on same-SiteInstance navigations.
EXPECT_EQ(main_frame->GetGlobalId(), original_id);
}
}
EXPECT_FALSE(main_frame->GetSiteInstance()->RequiresDedicatedProcess());
EXPECT_FALSE(main_frame->GetProcess()->IsProcessLockedToSiteForTesting());
// Navigate <webview> subframe cross-site. Check that it stays in the same
// process, and SiteInstance/Group.
const GURL frame_url =
embedded_test_server()->GetURL("b.test", "/title1.html");
content::RenderFrameHost* subframe = content::ChildFrameAt(main_frame, 0);
ASSERT_TRUE(subframe);
EXPECT_TRUE(NavigateToURLFromRenderer(subframe, frame_url));
subframe = content::ChildFrameAt(main_frame, 0);
if (base::FeatureList::IsEnabled(features::kDefaultSiteInstanceGroups)) {
EXPECT_NE(main_frame->GetSiteInstance(), subframe->GetSiteInstance());
EXPECT_EQ(main_frame->GetSiteInstance()->GetSiteInstanceGroupId(),
subframe->GetSiteInstance()->GetSiteInstanceGroupId());
} else {
EXPECT_EQ(main_frame->GetSiteInstance(), subframe->GetSiteInstance());
}
EXPECT_EQ(main_frame->GetProcess(), subframe->GetProcess());
EXPECT_TRUE(subframe->GetSiteInstance()->IsGuest());
EXPECT_FALSE(subframe->GetSiteInstance()->RequiresDedicatedProcess());
EXPECT_FALSE(subframe->GetProcess()->IsProcessLockedToSiteForTesting());
}
// Similar to the test above, but also exercises navigations to an isolated
// origin, which takes precedence over switches::kDisableSiteIsolation. In
// this setup, navigations to the isolated origin should use a normal
// SiteInstance that requires a dedicated process, while all other navigations
// should use the default SiteInstance or default SiteInstanceGroup and an
// unlocked process.
IN_PROC_BROWSER_TEST_P(WebViewWithDefaultSiteInstanceTest, IsolatedOrigin) {
ASSERT_TRUE(StartEmbeddedTestServer());
// Load an app with a <webview> guest that starts at a data: URL.
LoadAppWithGuest("web_view/simple");
content::RenderFrameHost* main_frame = GetGuestRenderFrameHost();
ASSERT_TRUE(main_frame);
auto original_id = main_frame->GetGlobalId();
scoped_refptr<content::SiteInstance> starting_instance =
main_frame->GetSiteInstance();
// Because this test runs without strict site isolation, the <webview>
// process shouldn't be locked. However, the <webview>'s process and
// SiteInstance should still be for a guest.
EXPECT_FALSE(
starting_instance->GetProcess()->IsProcessLockedToSiteForTesting());
EXPECT_FALSE(starting_instance->RequiresDedicatedProcess());
EXPECT_TRUE(starting_instance->IsGuest());
EXPECT_TRUE(starting_instance->GetProcess()->IsForGuestsOnly());
EXPECT_FALSE(starting_instance->GetStoragePartitionConfig().is_default());
// Navigate to an isolated origin. Isolated origins take precedence over
// switches::kDisableSiteIsolation, so we should swap SiteInstances and
// processes, ending up in a locked process.
const GURL start_url =
embedded_test_server()->GetURL("isolated.com", "/iframe.html");
{
content::TestFrameNavigationObserver load_observer(main_frame);
EXPECT_TRUE(
ExecJs(main_frame, "location.href = '" + start_url.spec() + "';"));
load_observer.Wait();
}
main_frame = GetGuestRenderFrameHost();
ASSERT_TRUE(main_frame);
EXPECT_NE(main_frame->GetGlobalId(), original_id);
EXPECT_NE(starting_instance, main_frame->GetSiteInstance());
EXPECT_TRUE(main_frame->GetSiteInstance()->RequiresDedicatedProcess());
EXPECT_TRUE(main_frame->GetProcess()->IsProcessLockedToSiteForTesting());
// Navigate a subframe on the isolated origin cross-site to a non-isolated
// URL. The subframe should go back into a default SiteInstance in a
// different unlocked process.
const GURL frame_url =
embedded_test_server()->GetURL("b.test", "/title1.html");
content::RenderFrameHost* subframe = content::ChildFrameAt(main_frame, 0);
{
content::TestFrameNavigationObserver subframe_load_observer(subframe);
EXPECT_TRUE(
ExecJs(subframe, "location.href = '" + frame_url.spec() + "';"));
subframe_load_observer.Wait();
}
subframe = content::ChildFrameAt(main_frame, 0);
ASSERT_TRUE(subframe);
EXPECT_NE(main_frame->GetSiteInstance(), subframe->GetSiteInstance());
EXPECT_NE(main_frame->GetProcess(), subframe->GetProcess());
EXPECT_TRUE(subframe->GetSiteInstance()->IsGuest());
EXPECT_FALSE(subframe->GetSiteInstance()->RequiresDedicatedProcess());
EXPECT_FALSE(subframe->GetProcess()->IsProcessLockedToSiteForTesting());
// Check that all frames stayed in the same guest StoragePartition.
EXPECT_EQ(main_frame->GetSiteInstance()->GetStoragePartitionConfig(),
subframe->GetSiteInstance()->GetStoragePartitionConfig());
EXPECT_EQ(main_frame->GetSiteInstance()->GetStoragePartitionConfig(),
starting_instance->GetStoragePartitionConfig());
}
IN_PROC_BROWSER_TEST_P(WebViewWithDefaultSiteInstanceTest, FencedFrame) {
TestHelper("testAddFencedFrame", "web_view/shim", NEEDS_TEST_SERVER);
auto* guest_rfh =
GetGuestViewManager()->WaitForSingleGuestRenderFrameHostCreated();
std::vector<content::RenderFrameHost*> rfhs =
content::CollectAllRenderFrameHosts(guest_rfh);
ASSERT_EQ(rfhs.size(), 2u);
ASSERT_EQ(rfhs[0], guest_rfh);
content::RenderFrameHostWrapper fenced_frame(rfhs[1]);
EXPECT_TRUE(fenced_frame->IsFencedFrameRoot());
content::SiteInstance* fenced_frame_site_instance =
fenced_frame->GetSiteInstance();
EXPECT_FALSE(fenced_frame->IsErrorDocument());
EXPECT_NE(fenced_frame_site_instance, guest_rfh->GetSiteInstance());
EXPECT_TRUE(fenced_frame_site_instance->IsGuest());
EXPECT_EQ(fenced_frame_site_instance->GetStoragePartitionConfig(),
guest_rfh->GetSiteInstance()->GetStoragePartitionConfig());
EXPECT_EQ(fenced_frame->GetProcess(), guest_rfh->GetProcess());
}
class WebViewFencedFrameTest
: public WebViewTestBase,
public testing::WithParamInterface<testing::tuple<bool, bool>> {
public:
WebViewFencedFrameTest() {
scoped_feature_list_.InitWithFeatureStates(
{{features::kIsolateFencedFrames, testing::get<0>(GetParam())},
{features::kGuestViewMPArch, testing::get<1>(GetParam())}});
}
~WebViewFencedFrameTest() override = default;
content::test::FencedFrameTestHelper& fenced_frame_test_helper() {
return fenced_frame_test_helper_;
}
static std::string DescribeParams(
const testing::TestParamInfo<ParamType>& info) {
const auto [isolate_fenced_frames, mparch] = info.param;
return base::StringPrintf("%s_%s",
isolate_fenced_frames
? "IsolateFencedFramesEnabled"
: "IsolateFencedFramesDisabled",
mparch ? "MPArch" : "InnerWebContents");
}
private:
content::test::FencedFrameTestHelper fenced_frame_test_helper_;
base::test::ScopedFeatureList scoped_feature_list_;
};
INSTANTIATE_TEST_SUITE_P(WebViewTests,
WebViewFencedFrameTest,
testing::Combine(testing::Bool(), testing::Bool()),
WebViewFencedFrameTest::DescribeParams);
IN_PROC_BROWSER_TEST_P(WebViewFencedFrameTest, ZoomFencedFrame) {
TestHelper("testZoomFencedFrame", "web_view/shim", NEEDS_TEST_SERVER);
// Verify setup is correct.
auto* guest_rfh =
GetGuestViewManager()->WaitForSingleGuestRenderFrameHostCreated();
std::vector<content::RenderFrameHost*> rfhs =
content::CollectAllRenderFrameHosts(guest_rfh);
ASSERT_EQ(rfhs.size(), 2u);
ASSERT_EQ(rfhs[0], guest_rfh);
content::RenderFrameHostWrapper fenced_frame(rfhs[1]);
EXPECT_TRUE(fenced_frame->IsFencedFrameRoot());
// Query zoom level of FencedFrame's RenderWidgetHost, make sure it matches
// the expected zoom level.
auto* fenced_frame_rwh = fenced_frame->GetRenderWidgetHost();
// See Javascript fcn testZoomFencedFrame for source of the 0.95 zoom factor.
double expected_zoom_level = blink::ZoomFactorToZoomLevel(0.95);
// Guest has `expected_zoom_level`.
EXPECT_DOUBLE_EQ(expected_zoom_level, content::GetPendingZoomLevel(
guest_rfh->GetRenderWidgetHost()));
// FencedFrame has `expected_zoom_level`.
EXPECT_DOUBLE_EQ(expected_zoom_level,
content::GetPendingZoomLevel(fenced_frame_rwh));
// Verify webview's embedder has expected zoom.
auto* embedder_web_contents = GetFirstAppWindowWebContents();
auto* embedder_rwh =
embedder_web_contents->GetPrimaryMainFrame()->GetRenderWidgetHost();
EXPECT_DOUBLE_EQ(blink::ZoomFactorToZoomLevel(1.0),
content::GetPendingZoomLevel(embedder_rwh));
}
IN_PROC_BROWSER_TEST_P(WebViewFencedFrameTest,
FencedFrameInGuestHasGuestSiteInstance) {
SKIP_FOR_MPARCH(); // TODO(crbug.com/40202416): Enable test for MPArch.
TestHelper("testAddFencedFrame", "web_view/shim", NEEDS_TEST_SERVER);
auto* guest_rfh =
GetGuestViewManager()->WaitForSingleGuestRenderFrameHostCreated();
std::vector<content::RenderFrameHost*> rfhs =
content::CollectAllRenderFrameHosts(guest_rfh);
ASSERT_EQ(rfhs.size(), 2u);
ASSERT_EQ(rfhs[0], guest_rfh);
content::RenderFrameHostWrapper ff_rfh(rfhs[1]);
EXPECT_NE(ff_rfh->GetSiteInstance(), guest_rfh->GetSiteInstance());
EXPECT_TRUE(guest_rfh->GetSiteInstance()->IsGuest());
EXPECT_TRUE(ff_rfh->GetSiteInstance()->IsGuest());
EXPECT_EQ(ff_rfh->GetSiteInstance()->GetStoragePartitionConfig(),
guest_rfh->GetSiteInstance()->GetStoragePartitionConfig());
// The fenced frame will be in a different process from the embedding guest
// only if Process Isolation for Fenced Frames is enabled.
if (content::SiteIsolationPolicy::
IsProcessIsolationForFencedFramesEnabled()) {
EXPECT_NE(ff_rfh->GetProcess(), guest_rfh->GetProcess());
} else {
EXPECT_EQ(ff_rfh->GetProcess(), guest_rfh->GetProcess());
}
// Add a second fenced frame (same-site with the first fenced frame).
auto* ff_rfh_2 = fenced_frame_test_helper().CreateFencedFrame(
guest_rfh, ff_rfh->GetLastCommittedURL());
EXPECT_NE(ff_rfh_2->GetSiteInstance(), ff_rfh->GetSiteInstance());
EXPECT_EQ(ff_rfh->GetProcess(), ff_rfh_2->GetProcess());
}
class WebViewUsbTest : public WebViewTest {
public:
WebViewUsbTest() = default;
~WebViewUsbTest() override = default;
void SetUpOnMainThread() override {
WebViewTest::SetUpOnMainThread();
fake_device_info_ = device_manager_.CreateAndAddDevice(
0, 0, "Test Manufacturer", "Test Device", "123456");
mojo::PendingRemote<device::mojom::UsbDeviceManager> device_manager;
device_manager_.AddReceiver(
device_manager.InitWithNewPipeAndPassReceiver());
UsbChooserContextFactory::GetForProfile(browser()->profile())
->SetDeviceManagerForTesting(std::move(device_manager));
test_content_browser_client_.SetAsBrowserClient();
}
void TearDownOnMainThread() override {
test_content_browser_client_.UnsetAsBrowserClient();
WebViewTest::TearDownOnMainThread();
}
void UseFakeChooser() {
test_content_browser_client_.delegate().UseFakeChooser();
}
private:
device::FakeUsbDeviceManager device_manager_;
device::mojom::UsbDeviceInfoPtr fake_device_info_;
TestUsbContentBrowserClient test_content_browser_client_;
};
INSTANTIATE_TEST_SUITE_P(/* no prefix */,
WebViewUsbTest,
testing::Bool(),
WebViewUsbTest::DescribeParams);
IN_PROC_BROWSER_TEST_P(WebViewUsbTest, Shim_TestCannotRequestUsb) {
TestHelper("testCannotRequestUsb", "web_view/shim", NEEDS_TEST_SERVER);
}
IN_PROC_BROWSER_TEST_P(WebViewUsbTest, Shim_TestCannotReuseUsbPairedInTab) {
// We start the test server here, instead of in TestHelper, because we need
// to know the origin used in both the tab and webview before running the rest
// of the test.
ASSERT_TRUE(StartEmbeddedTestServer());
const GURL url = embedded_test_server()->GetURL("localhost", "/title1.html");
ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), url));
content::WebContents* tab_web_contents =
browser()->tab_strip_model()->GetActiveWebContents();
UseFakeChooser();
// Request permission to access the fake device in the tab. The fake chooser
// will automatically select the item representing the fake device, granting
// the permission.
EXPECT_EQ("123456", EvalJs(tab_web_contents,
R"((async () => {
let device =
await navigator.usb.requestDevice({filters: []});
return device.serialNumber;
})())"));
EXPECT_EQ(content::ListValueOf("123456"), EvalJs(tab_web_contents,
R"((async () => {
let devices = await navigator.usb.getDevices();
return devices.map(device => device.serialNumber);
})())"));
// Have the embedder create a webview which navigates to the same origin and
// attempts to use the paired device. The granted permission should not be
// available for that context.
TestHelper("testCannotReuseUsbPairedInTab", "web_view/shim", NO_TEST_SERVER);
}
IN_PROC_BROWSER_TEST_P(WebViewTest, Shim_TestCannotRequestFonts) {
TestHelper("testCannotRequestFonts", "web_view/shim", NEEDS_TEST_SERVER);
}
IN_PROC_BROWSER_TEST_P(WebViewTest, Shim_TestCannotRequestFontsGrantedInTab) {
// We start the test server here, instead of in TestHelper, because we need
// to know the origin used in both the tab and webview before running the rest
// of the test.
ASSERT_TRUE(StartEmbeddedTestServer());
const GURL url = embedded_test_server()->GetURL("localhost", "/title1.html");
ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), url));
content::WebContents* tab_web_contents =
browser()->tab_strip_model()->GetActiveWebContents();
// Grant access to fonts from a tab.
permissions::MockPermissionPromptFactory tab_prompt_factory(
permissions::PermissionRequestManager::FromWebContents(tab_web_contents));
tab_prompt_factory.set_response_type(
permissions::PermissionRequestManager::AutoResponseType::ACCEPT_ALL);
EXPECT_TRUE(content::ExecJs(tab_web_contents,
R"((async () => {
await window.queryLocalFonts();
})())"));
// Have the embedder create a webview which navigates to the same origin and
// attempts to access fonts. The granted permission should not be
// available for that context.
TestHelper("testCannotRequestFonts", "web_view/shim", NO_TEST_SERVER);
}
class WebViewSerialTest : public WebViewTest {
public:
void SetUpOnMainThread() override {
WebViewTest::SetUpOnMainThread();
mojo::PendingRemote<device::mojom::SerialPortManager> port_manager;
port_manager_.AddReceiver(port_manager.InitWithNewPipeAndPassReceiver());
context()->SetPortManagerForTesting(std::move(port_manager));
}
void TearDownOnMainThread() override { WebViewTest::TearDownOnMainThread(); }
device::FakeSerialPortManager& port_manager() { return port_manager_; }
SerialChooserContext* context() {
return SerialChooserContextFactory::GetForProfile(browser()->profile());
}
void CreatePortAndGrantPermissionToOrigin(const url::Origin& origin) {
// Create port and grant permission to it.
auto port = device::mojom::SerialPortInfo::New();
port->token = base::UnguessableToken::Create();
context()->GrantPortPermission(origin, *port);
port_manager().AddPort(std::move(port));
}
private:
device::FakeSerialPortManager port_manager_;
};
INSTANTIATE_TEST_SUITE_P(/* no prefix */,
WebViewSerialTest,
testing::Bool(),
WebViewSerialTest::DescribeParams);
IN_PROC_BROWSER_TEST_P(WebViewSerialTest,
Shim_TestEnabledInTabButNotInWebView) {
// We start the test server here, instead of in TestHelper, because we need
// to know the origin used in both the tab and webview.
ASSERT_TRUE(StartEmbeddedTestServer());
const GURL url = embedded_test_server()->GetURL("localhost", "/title1.html");
url::Origin origin = url::Origin::Create(url);
CreatePortAndGrantPermissionToOrigin(origin);
ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), url));
content::WebContents* tab_web_contents =
browser()->tab_strip_model()->GetActiveWebContents();
// Test that serial works in a tab.
EXPECT_EQ(1, EvalJs(tab_web_contents,
R"(
(async () => {
const ports = await navigator.serial.getPorts().then(ports => ports.length);
return ports;
})();
)"));
// Have the embedder create a webview which navigates to the same origin and
// attempts to use serial.
TestHelper("testSerialDisabled", "web_view/shim", NO_TEST_SERVER);
}
class WebViewBluetoothTest : public WebViewTest {
public:
void SetUpOnMainThread() override {
WebViewTest::SetUpOnMainThread();
// Hook up the test bluetooth delegate.
SetFakeBlueboothAdapter();
old_browser_client_ = content::SetBrowserClientForTesting(&browser_client_);
}
void TearDownOnMainThread() override {
content::SetBrowserClientForTesting(old_browser_client_);
WebViewTest::TearDownOnMainThread();
}
void SetUpCommandLine(base::CommandLine* command_line) override {
// Sets up the blink runtime feature for accessing to navigator.bluetooth.
command_line->AppendSwitch(
switches::kEnableExperimentalWebPlatformFeatures);
WebViewTest::SetUpCommandLine(command_line);
}
void SetFakeBlueboothAdapter() {
adapter_ = new FakeBluetoothAdapter();
EXPECT_CALL(*adapter_, IsPresent()).WillRepeatedly(Return(true));
EXPECT_CALL(*adapter_, IsPowered()).WillRepeatedly(Return(true));
content::SetBluetoothAdapter(adapter_);
// Other parts of Chrome may keep a reference to the bluetooth adapter.
// Since we do not verify any expectations, it is okay to leak this mock.
testing::Mock::AllowLeak(adapter_.get());
}
void AddFakeDevice(const std::string& device_address) {
const device::BluetoothUUID kHeartRateUUID(kHeartRateUUIDString);
auto fake_device =
std::make_unique<testing::NiceMock<device::MockBluetoothDevice>>(
adapter_.get(), /*bluetooth_class=*/0u, kFakeBluetoothDeviceName,
device_address,
/*paired=*/true,
/*connected=*/true);
fake_device->AddUUID(kHeartRateUUID);
fake_device->AddMockService(
std::make_unique<testing::NiceMock<device::MockBluetoothGattService>>(
fake_device.get(), kHeartRateUUIDString, kHeartRateUUID,
/*is_primary=*/true));
adapter_->AddMockDevice(std::move(fake_device));
}
void SetDeviceToSelect(const std::string& device_address) {
browser_client_.bluetooth_delegate()->SetDeviceToSelect(device_address);
}
private:
scoped_refptr<FakeBluetoothAdapter> adapter_;
BluetoothTestContentBrowserClient browser_client_;
raw_ptr<content::ContentBrowserClient> old_browser_client_ = nullptr;
};
INSTANTIATE_TEST_SUITE_P(/* no prefix */,
WebViewBluetoothTest,
testing::Bool(),
WebViewBluetoothTest::DescribeParams);
IN_PROC_BROWSER_TEST_P(WebViewBluetoothTest,
Shim_TestEnabledInTabButNotInWebView) {
// We start the test server here, instead of in TestHelper, because we
// need to know the origin used in the tab.
ASSERT_TRUE(StartEmbeddedTestServer());
const GURL url = embedded_test_server()->GetURL("localhost", "/title1.html");
url::Origin origin = url::Origin::Create(url);
ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), url));
content::WebContents* tab_web_contents =
browser()->tab_strip_model()->GetActiveWebContents();
AddFakeDevice(kDeviceAddress);
SetDeviceToSelect(kDeviceAddress);
// Test that Bluetooth works in a tab.
constexpr char kBluetoothTestScript[] = R"(
(async () => {
try {
const device = await navigator.bluetooth.requestDevice({
filters: [{services: ['heart_rate']}]
});
return device.name;
} catch (e) {
return e.name + ': ' + e.message;
}
})();
)";
EXPECT_EQ(kFakeBluetoothDeviceName,
EvalJs(tab_web_contents, kBluetoothTestScript));
// Have the embedder create a webview which navigates to the same origin
// and attempts to use Bluetooth.
TestHelper("testBluetoothDisabled", "web_view/shim", NO_TEST_SERVER);
}
class WebViewFileSystemAccessTest : public WebViewTest {
public:
void SetUpOnMainThread() override {
ASSERT_TRUE(
temp_dir_.CreateUniqueTempDirUnderPath(base::GetTempDirForTesting()));
WebViewTest::SetUpOnMainThread();
}
void TearDownOnMainThread() override {
ASSERT_TRUE(temp_dir_.Delete());
WebViewTest::TearDownOnMainThread();
}
base::FilePath CreateTestFile() {
base::ScopedAllowBlockingForTesting allow_blocking;
base::FilePath result;
EXPECT_TRUE(base::CreateTemporaryFileInDir(temp_dir_.GetPath(), &result));
return result;
}
private:
base::ScopedTempDir temp_dir_;
};
INSTANTIATE_TEST_SUITE_P(/* no prefix */,
WebViewFileSystemAccessTest,
testing::Bool(),
WebViewFileSystemAccessTest::DescribeParams);
// This test provides coverage for existing FSA behavior in WebView, which may
// not be the desired behavior.
// TODO(crbug.com/352520731): Embedder should allow filesystem permission for
// the content embedded inside <webview> to use FSA.
IN_PROC_BROWSER_TEST_P(WebViewFileSystemAccessTest,
Shim_TestEnabledInTabAndWebView) {
SKIP_FOR_MPARCH(); // TODO(crbug.com/40202416): Enable test for MPArch.
constexpr char kSuccessResult[] = "SUCCESS";
constexpr char kFailResult[] = "FAIL";
ASSERT_TRUE(StartEmbeddedTestServer());
const GURL url = embedded_test_server()->GetURL("localhost", "/title1.html");
ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), url));
content::WebContents* tab_web_contents =
browser()->tab_strip_model()->GetActiveWebContents();
// Set up file picker for testing.
const base::FilePath test_file = CreateTestFile();
ui::SelectFileDialog::SetFactory(
std::make_unique<SelectPredeterminedFileDialogFactory>(
std::vector<base::FilePath>{test_file}));
// Test that File System Access works in a tab.
auto kFileSystemAccessTestScript =
content::JsReplace(R"(
(async function() {
try {
const [handle] = await showOpenFilePicker({
types: [
{
description: 'All files',
accept: {
'*/*': ['.txt', '.pdf', '.jpg', '.png'],
},
},
],
});
await handle.getFile();
return $1;
} catch (error) {
return $2;
}
})();
)",
kSuccessResult, kFailResult);
EXPECT_EQ(kSuccessResult,
EvalJs(tab_web_contents, kFileSystemAccessTestScript));
// Have the embedder create a webview and attempt to use file picker.
TestHelper("testFileSystemAccessAvailable", "web_view/shim", NO_TEST_SERVER);
}
IN_PROC_BROWSER_TEST_P(WebViewTest, PerformanceManager) {
ASSERT_TRUE(StartEmbeddedTestServer());
LoadAppWithGuest("web_view/simple");
auto* guest = GetGuestViewManager()->GetLastGuestViewCreated();
content::WebContents* owner_web_contents = GetEmbedderWebContents();
auto main_frame_node =
performance_manager::PerformanceManager::GetFrameNodeForRenderFrameHost(
owner_web_contents->GetPrimaryMainFrame());
ASSERT_TRUE(main_frame_node);
auto inner_root_frame_node =
performance_manager::PerformanceManager::GetFrameNodeForRenderFrameHost(
guest->GetGuestMainFrame());
ASSERT_TRUE(inner_root_frame_node);
// Make sure the guest view node does not have a parent frame node.
// <webviews> have an outer document instead of a parent frame node.
EXPECT_EQ(inner_root_frame_node->GetParentFrameNode(), nullptr);
// The outer document of the guest view is available.
EXPECT_EQ(inner_root_frame_node->GetParentOrOuterDocumentOrEmbedder(),
main_frame_node.get());
}
|