1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497 5498 5499 5500 5501 5502 5503 5504 5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551 5552 5553 5554 5555 5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584 5585 5586 5587 5588 5589 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607 5608 5609 5610 5611 5612 5613 5614 5615 5616 5617 5618 5619 5620 5621 5622 5623 5624 5625 5626 5627 5628 5629 5630 5631 5632 5633 5634 5635 5636 5637 5638 5639 5640 5641 5642 5643 5644 5645 5646 5647 5648 5649 5650 5651 5652 5653 5654 5655 5656 5657 5658 5659 5660 5661 5662 5663 5664 5665 5666 5667 5668 5669 5670 5671 5672 5673 5674 5675 5676 5677 5678 5679 5680 5681 5682 5683 5684 5685 5686 5687 5688 5689 5690 5691 5692 5693 5694 5695 5696 5697 5698 5699 5700 5701 5702 5703 5704 5705 5706 5707 5708 5709 5710 5711 5712 5713 5714 5715 5716 5717 5718 5719 5720 5721 5722 5723 5724 5725 5726 5727 5728 5729 5730 5731 5732 5733 5734 5735 5736 5737 5738 5739 5740 5741 5742 5743 5744 5745 5746 5747 5748 5749 5750 5751 5752 5753 5754 5755 5756 5757 5758 5759 5760 5761 5762 5763 5764 5765 5766 5767 5768 5769 5770 5771 5772 5773 5774 5775 5776 5777 5778 5779 5780 5781 5782 5783 5784 5785 5786 5787 5788 5789 5790 5791 5792 5793 5794 5795 5796 5797 5798 5799 5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815 5816 5817 5818 5819 5820 5821 5822 5823 5824 5825 5826 5827 5828 5829 5830 5831 5832 5833 5834 5835 5836 5837 5838 5839 5840 5841 5842 5843 5844 5845 5846 5847 5848 5849 5850 5851 5852 5853 5854 5855 5856 5857 5858 5859 5860 5861 5862 5863 5864 5865 5866 5867 5868 5869 5870 5871 5872 5873 5874 5875 5876 5877 5878 5879 5880 5881 5882 5883 5884 5885 5886 5887 5888 5889 5890 5891 5892 5893 5894 5895 5896 5897 5898 5899 5900 5901 5902 5903 5904 5905 5906 5907 5908 5909 5910 5911 5912 5913 5914 5915 5916 5917 5918 5919 5920 5921 5922 5923 5924 5925 5926 5927 5928 5929 5930 5931 5932 5933 5934 5935 5936 5937 5938 5939 5940 5941 5942 5943 5944 5945 5946 5947 5948 5949 5950 5951 5952 5953 5954 5955 5956 5957 5958 5959 5960 5961 5962 5963 5964 5965 5966 5967 5968 5969 5970 5971 5972 5973 5974 5975 5976 5977 5978 5979 5980 5981 5982 5983 5984 5985 5986 5987 5988 5989 5990 5991 5992 5993 5994 5995 5996 5997 5998 5999 6000 6001 6002 6003 6004 6005 6006 6007 6008 6009 6010 6011 6012 6013 6014 6015 6016 6017 6018 6019 6020 6021 6022 6023 6024 6025 6026 6027 6028 6029 6030 6031 6032 6033 6034 6035 6036 6037 6038 6039 6040 6041 6042 6043 6044 6045 6046 6047 6048 6049 6050 6051 6052 6053 6054 6055 6056 6057 6058 6059 6060 6061 6062 6063 6064 6065 6066 6067 6068 6069 6070 6071 6072 6073 6074 6075 6076 6077 6078 6079 6080 6081 6082 6083 6084 6085 6086 6087 6088 6089 6090 6091 6092 6093 6094 6095 6096 6097 6098 6099 6100 6101 6102 6103 6104 6105 6106 6107 6108 6109 6110 6111 6112 6113 6114 6115 6116 6117 6118 6119 6120 6121 6122 6123 6124 6125 6126 6127 6128 6129 6130 6131 6132 6133 6134 6135 6136 6137 6138 6139 6140 6141 6142 6143 6144 6145 6146 6147 6148 6149 6150 6151 6152 6153 6154 6155 6156 6157 6158 6159 6160 6161 6162 6163 6164 6165 6166 6167 6168 6169 6170 6171 6172 6173 6174 6175 6176 6177 6178 6179 6180 6181 6182 6183 6184 6185 6186 6187 6188 6189 6190 6191 6192 6193 6194 6195 6196 6197 6198 6199 6200 6201 6202 6203 6204 6205 6206 6207 6208 6209 6210 6211 6212 6213 6214 6215 6216 6217 6218 6219 6220 6221 6222 6223 6224 6225 6226 6227 6228 6229 6230 6231 6232 6233 6234 6235 6236 6237 6238 6239 6240 6241 6242 6243 6244 6245 6246 6247 6248 6249 6250 6251 6252 6253 6254 6255 6256 6257 6258 6259 6260 6261 6262 6263 6264 6265 6266 6267 6268 6269 6270 6271 6272 6273 6274 6275 6276 6277 6278 6279 6280 6281 6282 6283 6284 6285 6286 6287 6288 6289 6290 6291 6292 6293 6294 6295 6296 6297 6298 6299 6300 6301 6302 6303 6304 6305 6306 6307 6308 6309 6310 6311 6312 6313 6314 6315 6316 6317 6318 6319 6320 6321 6322 6323 6324 6325 6326 6327 6328 6329 6330 6331 6332 6333 6334 6335 6336 6337 6338 6339 6340 6341 6342 6343 6344 6345 6346 6347 6348 6349 6350 6351 6352 6353 6354 6355 6356 6357 6358 6359 6360 6361 6362 6363 6364 6365 6366 6367 6368 6369 6370 6371 6372 6373 6374 6375 6376 6377 6378 6379 6380 6381 6382 6383 6384 6385 6386 6387 6388 6389 6390 6391 6392 6393 6394 6395 6396 6397 6398 6399 6400 6401 6402 6403 6404 6405 6406 6407 6408 6409 6410 6411 6412 6413 6414 6415 6416 6417 6418 6419 6420 6421 6422 6423 6424 6425 6426 6427 6428 6429 6430 6431 6432 6433 6434 6435 6436 6437 6438 6439 6440 6441 6442 6443 6444 6445 6446 6447 6448 6449 6450 6451 6452 6453 6454 6455 6456 6457 6458 6459 6460 6461 6462 6463 6464 6465 6466 6467 6468 6469 6470 6471 6472 6473 6474 6475 6476 6477 6478 6479 6480 6481 6482 6483 6484 6485 6486 6487 6488 6489 6490 6491 6492 6493 6494 6495 6496 6497 6498 6499 6500 6501 6502 6503 6504 6505 6506 6507 6508 6509 6510 6511 6512 6513 6514 6515 6516 6517 6518 6519 6520 6521 6522 6523 6524 6525 6526 6527 6528 6529 6530 6531 6532 6533 6534 6535 6536 6537 6538 6539 6540 6541 6542 6543 6544 6545 6546 6547 6548 6549 6550 6551 6552 6553 6554 6555 6556 6557 6558 6559 6560 6561 6562 6563 6564 6565 6566 6567 6568 6569 6570 6571 6572 6573 6574 6575 6576 6577 6578 6579 6580 6581 6582 6583 6584 6585 6586 6587 6588 6589 6590 6591 6592 6593 6594 6595 6596 6597 6598 6599 6600 6601 6602 6603 6604 6605 6606 6607 6608 6609 6610 6611 6612 6613 6614 6615 6616 6617 6618 6619 6620 6621 6622 6623 6624 6625 6626 6627 6628 6629 6630 6631 6632 6633 6634 6635 6636 6637 6638 6639 6640 6641 6642 6643 6644 6645 6646 6647 6648 6649 6650 6651 6652 6653 6654 6655 6656 6657 6658 6659 6660 6661 6662 6663 6664 6665 6666 6667 6668 6669 6670 6671 6672 6673 6674 6675 6676 6677 6678 6679 6680 6681 6682 6683 6684 6685 6686 6687 6688 6689 6690 6691 6692 6693 6694 6695 6696 6697 6698 6699 6700 6701 6702 6703 6704 6705 6706 6707 6708 6709 6710 6711 6712 6713 6714 6715 6716 6717 6718 6719 6720 6721 6722 6723 6724 6725 6726 6727 6728 6729 6730 6731 6732 6733 6734 6735 6736 6737 6738 6739 6740 6741 6742 6743 6744 6745 6746 6747 6748 6749 6750 6751 6752 6753 6754 6755 6756 6757 6758 6759 6760 6761 6762 6763 6764 6765 6766 6767 6768 6769 6770 6771 6772 6773 6774 6775 6776 6777 6778 6779 6780 6781 6782 6783 6784 6785 6786 6787 6788 6789 6790 6791 6792 6793 6794 6795 6796 6797 6798 6799 6800 6801 6802 6803 6804 6805 6806 6807 6808 6809 6810 6811 6812 6813 6814 6815 6816 6817 6818 6819 6820 6821 6822 6823 6824 6825 6826 6827 6828 6829 6830 6831 6832 6833 6834 6835 6836 6837 6838 6839 6840 6841 6842 6843 6844 6845 6846 6847 6848 6849 6850 6851 6852 6853 6854 6855 6856 6857 6858 6859 6860 6861 6862 6863 6864 6865 6866 6867 6868 6869 6870 6871 6872 6873 6874 6875 6876 6877 6878 6879 6880 6881 6882 6883 6884 6885 6886 6887 6888 6889 6890 6891 6892 6893 6894 6895 6896 6897 6898 6899 6900 6901 6902 6903 6904 6905 6906 6907 6908 6909 6910 6911 6912 6913 6914 6915 6916 6917 6918 6919 6920 6921 6922 6923 6924 6925 6926 6927 6928 6929 6930 6931 6932 6933 6934 6935 6936 6937 6938 6939 6940 6941 6942 6943 6944 6945 6946 6947 6948 6949 6950 6951 6952 6953 6954 6955 6956 6957 6958 6959 6960 6961 6962 6963 6964 6965 6966 6967 6968 6969 6970 6971 6972 6973 6974 6975 6976 6977 6978 6979 6980 6981 6982 6983 6984 6985 6986 6987 6988 6989 6990 6991 6992 6993 6994 6995 6996 6997 6998 6999 7000 7001 7002 7003 7004 7005 7006 7007 7008 7009 7010 7011 7012 7013 7014 7015 7016 7017 7018 7019 7020 7021 7022 7023 7024 7025 7026 7027 7028 7029 7030 7031 7032 7033 7034 7035 7036 7037 7038 7039 7040 7041 7042 7043 7044 7045 7046 7047 7048 7049 7050 7051 7052 7053 7054 7055 7056 7057 7058 7059 7060 7061 7062 7063 7064 7065 7066 7067 7068 7069 7070 7071 7072 7073 7074 7075 7076 7077 7078 7079 7080 7081 7082 7083 7084 7085 7086 7087 7088 7089 7090 7091 7092 7093 7094 7095 7096 7097 7098 7099 7100 7101 7102 7103 7104 7105 7106 7107 7108 7109 7110 7111 7112 7113 7114 7115 7116 7117 7118 7119 7120 7121 7122 7123 7124 7125 7126 7127 7128 7129 7130 7131 7132 7133 7134 7135 7136 7137 7138 7139 7140 7141 7142 7143 7144 7145 7146 7147 7148 7149 7150 7151 7152 7153 7154 7155 7156 7157 7158 7159 7160 7161 7162 7163 7164 7165 7166 7167 7168 7169 7170 7171 7172 7173 7174 7175 7176 7177 7178 7179 7180 7181 7182 7183 7184 7185 7186 7187 7188 7189 7190 7191 7192 7193 7194 7195 7196 7197 7198 7199 7200 7201 7202 7203 7204 7205 7206 7207 7208 7209 7210 7211 7212 7213 7214 7215 7216 7217 7218 7219 7220 7221 7222 7223 7224 7225 7226 7227 7228 7229 7230 7231 7232 7233 7234 7235 7236 7237 7238 7239 7240 7241 7242 7243 7244 7245 7246 7247 7248 7249 7250 7251 7252 7253 7254 7255 7256 7257 7258 7259 7260 7261 7262 7263 7264 7265 7266 7267 7268 7269 7270 7271 7272 7273 7274 7275 7276 7277 7278 7279 7280 7281 7282 7283 7284 7285 7286 7287 7288 7289 7290 7291 7292 7293 7294 7295 7296 7297 7298 7299 7300 7301 7302 7303 7304 7305 7306 7307 7308 7309 7310 7311 7312 7313 7314 7315 7316 7317 7318 7319 7320 7321 7322 7323 7324 7325 7326 7327 7328 7329 7330 7331 7332 7333 7334 7335 7336 7337 7338 7339 7340 7341 7342 7343 7344 7345 7346 7347 7348 7349 7350 7351 7352 7353 7354 7355 7356 7357 7358 7359 7360 7361 7362 7363 7364 7365 7366 7367 7368 7369 7370 7371 7372 7373 7374 7375 7376 7377 7378 7379 7380 7381 7382 7383 7384 7385 7386 7387 7388 7389 7390 7391 7392 7393 7394 7395 7396 7397 7398 7399 7400 7401 7402 7403 7404 7405 7406 7407 7408 7409 7410 7411 7412 7413 7414 7415 7416 7417 7418 7419 7420 7421 7422 7423 7424 7425 7426 7427 7428 7429 7430 7431 7432 7433 7434 7435 7436 7437 7438 7439 7440 7441 7442 7443 7444 7445 7446 7447 7448 7449 7450 7451 7452 7453 7454 7455 7456 7457 7458 7459 7460 7461 7462 7463 7464 7465 7466 7467 7468 7469 7470 7471 7472 7473 7474 7475 7476 7477 7478 7479 7480 7481 7482 7483 7484 7485 7486 7487 7488 7489 7490 7491 7492 7493 7494 7495 7496 7497 7498 7499 7500 7501 7502 7503 7504 7505 7506 7507 7508 7509 7510 7511 7512 7513 7514 7515 7516 7517 7518 7519 7520 7521 7522 7523 7524 7525 7526 7527 7528 7529 7530 7531 7532 7533 7534 7535 7536 7537 7538 7539 7540 7541 7542 7543 7544 7545 7546 7547 7548 7549 7550 7551 7552 7553 7554 7555 7556 7557 7558 7559 7560 7561 7562 7563 7564 7565 7566 7567 7568 7569 7570 7571 7572 7573 7574 7575 7576 7577 7578 7579 7580 7581 7582 7583 7584 7585 7586 7587 7588 7589 7590 7591 7592 7593 7594 7595 7596 7597 7598 7599 7600 7601 7602 7603 7604 7605 7606 7607 7608 7609 7610 7611 7612 7613 7614 7615 7616 7617 7618 7619 7620 7621 7622 7623 7624 7625 7626 7627 7628 7629 7630 7631 7632 7633 7634 7635 7636 7637 7638 7639 7640 7641 7642 7643 7644 7645 7646 7647 7648 7649 7650 7651 7652 7653 7654 7655 7656 7657 7658 7659 7660 7661 7662 7663 7664 7665 7666 7667 7668 7669 7670 7671 7672 7673 7674 7675 7676 7677 7678 7679 7680 7681 7682 7683 7684 7685 7686 7687 7688 7689 7690 7691 7692 7693 7694 7695 7696 7697 7698 7699 7700 7701 7702 7703 7704 7705 7706 7707 7708 7709 7710 7711 7712 7713 7714 7715 7716 7717 7718 7719 7720 7721 7722 7723 7724 7725 7726 7727 7728 7729 7730 7731 7732 7733 7734 7735 7736 7737 7738 7739 7740 7741 7742 7743 7744 7745 7746 7747 7748 7749 7750 7751 7752 7753 7754 7755 7756 7757 7758 7759 7760 7761 7762 7763 7764 7765 7766 7767 7768 7769 7770 7771 7772 7773 7774 7775 7776 7777 7778 7779 7780 7781 7782 7783 7784 7785 7786 7787 7788 7789 7790 7791 7792 7793 7794 7795 7796 7797 7798 7799 7800 7801 7802 7803 7804 7805 7806 7807 7808 7809 7810 7811 7812 7813 7814 7815 7816 7817 7818 7819 7820 7821 7822 7823 7824 7825 7826 7827 7828 7829 7830 7831 7832 7833 7834 7835 7836 7837 7838 7839 7840 7841 7842 7843 7844 7845 7846 7847 7848 7849 7850 7851 7852 7853 7854 7855 7856 7857 7858 7859 7860 7861 7862 7863 7864 7865 7866 7867 7868 7869 7870 7871 7872 7873 7874 7875 7876 7877 7878 7879 7880 7881 7882 7883 7884 7885 7886 7887 7888 7889 7890 7891 7892 7893 7894 7895 7896 7897 7898 7899 7900 7901 7902 7903 7904 7905 7906 7907 7908 7909 7910 7911 7912 7913 7914 7915 7916 7917 7918 7919 7920 7921 7922 7923 7924 7925 7926 7927 7928 7929 7930 7931 7932 7933 7934 7935 7936 7937 7938 7939 7940 7941 7942 7943 7944 7945 7946 7947 7948 7949 7950 7951 7952 7953 7954 7955 7956 7957 7958 7959 7960 7961 7962 7963 7964 7965 7966 7967 7968 7969 7970 7971 7972 7973 7974 7975 7976 7977 7978 7979 7980 7981 7982 7983 7984 7985 7986 7987 7988 7989 7990 7991 7992 7993 7994 7995 7996 7997 7998 7999 8000 8001 8002 8003 8004 8005 8006 8007 8008
|
// Copyright 2012 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <array>
#include <memory>
#include <optional>
#include <utility>
#include <vector>
#include "base/base64.h"
#include "base/command_line.h"
#include "base/containers/contains.h"
#include "base/files/file_util.h"
#include "base/functional/bind.h"
#include "base/json/json_reader.h"
#include "base/memory/ptr_util.h"
#include "base/memory/raw_ptr.h"
#include "base/run_loop.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_split.h"
#include "base/strings/stringprintf.h"
#include "base/strings/to_string.h"
#include "base/strings/utf_string_conversions.h"
#include "base/synchronization/lock.h"
#include "base/task/sequenced_task_runner.h"
#include "base/test/bind.h"
#include "base/test/metrics/histogram_tester.h"
#include "base/test/run_until.h"
#include "base/test/scoped_feature_list.h"
#include "base/test/test_future.h"
#include "base/time/time.h"
#include "base/time/time_override.h"
#include "base/values.h"
#include "build/build_config.h"
#include "build/chromeos_buildflags.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/devtools/protocol/devtools_protocol_test_support.h"
#include "chrome/browser/devtools/url_constants.h"
#include "chrome/browser/extensions/chrome_test_extension_loader.h"
#include "chrome/browser/extensions/error_console/error_console.h"
#include "chrome/browser/extensions/error_console/error_console_test_observer.h"
#include "chrome/browser/extensions/extension_action_runner.h"
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/browser/extensions/extension_browser_test_util.h"
#include "chrome/browser/extensions/extension_tab_util.h"
#include "chrome/browser/extensions/extension_util.h"
#include "chrome/browser/extensions/extension_with_management_policy_apitest.h"
#include "chrome/browser/extensions/permissions/active_tab_permission_granter.h"
#include "chrome/browser/extensions/permissions/scripting_permissions_modifier.h"
#include "chrome/browser/net/profile_network_context_service.h"
#include "chrome/browser/net/profile_network_context_service_factory.h"
#include "chrome/browser/net/system_network_context_manager.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/profiles/profile_destroyer.h"
#include "chrome/browser/profiles/profile_manager.h"
#include "chrome/common/chrome_features.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/url_constants.h"
#include "chrome/test/base/search_test_utils.h"
#include "components/embedder_support/switches.h"
#include "components/google/core/common/google_switches.h"
#include "components/policy/core/common/mock_configuration_policy_provider.h"
#include "components/policy/policy_constants.h"
#include "components/prefs/pref_service.h"
#include "components/proxy_config/proxy_config_dictionary.h"
#include "components/proxy_config/proxy_config_pref_names.h"
#include "components/ukm/test_ukm_recorder.h"
#include "components/web_package/web_bundle_builder.h"
#include "content/public/browser/browser_task_traits.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/navigation_controller.h"
#include "content/public/browser/navigation_entry.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_view_host.h"
#include "content/public/browser/render_widget_host.h"
#include "content/public/browser/storage_partition.h"
#include "content/public/browser/web_contents.h"
#include "content/public/browser/webui_config_map.h"
#include "content/public/common/content_features.h"
#include "content/public/common/page_type.h"
#include "content/public/test/browser_test.h"
#include "content/public/test/browser_test_utils.h"
#include "content/public/test/prerender_test_util.h"
#include "content/public/test/simple_url_loader_test_helper.h"
#include "content/public/test/test_navigation_observer.h"
#include "content/public/test/url_loader_interceptor.h"
#include "content/public/test/url_loader_monitor.h"
#include "content/public/test/web_transport_simple_test_server.h"
#include "extensions/browser/api/web_request/extension_web_request_event_router.h"
#include "extensions/browser/api/web_request/web_request_api.h"
#include "extensions/browser/background_script_executor.h"
#include "extensions/browser/blocked_action_type.h"
#include "extensions/browser/extension_prefs.h"
#include "extensions/browser/extension_registrar.h"
#include "extensions/browser/extension_registry.h"
#include "extensions/browser/install_prefs_helper.h"
#include "extensions/browser/process_manager.h"
#include "extensions/browser/service_worker/service_worker_task_queue.h"
#include "extensions/browser/service_worker/service_worker_test_utils.h"
#include "extensions/buildflags/buildflags.h"
#include "extensions/common/extension_builder.h"
#include "extensions/common/extension_features.h"
#include "extensions/common/features/feature.h"
#include "extensions/common/mojom/event_router.mojom-test-utils.h"
#include "extensions/test/extension_test_message_listener.h"
#include "extensions/test/result_catcher.h"
#include "extensions/test/test_extension_dir.h"
#include "google_apis/gaia/gaia_switches.h"
#include "mojo/public/cpp/bindings/pending_remote.h"
#include "mojo/public/cpp/bindings/remote.h"
#include "net/base/features.h"
#include "net/base/network_isolation_key.h"
#include "net/cookies/site_for_cookies.h"
#include "net/dns/mock_host_resolver.h"
#include "net/http/http_util.h"
#include "net/test/embedded_test_server/default_handlers.h"
#include "net/test/embedded_test_server/embedded_test_server.h"
#include "net/test/embedded_test_server/http_request.h"
#include "net/test/embedded_test_server/http_response.h"
#include "net/test/embedded_test_server/request_handler_util.h"
#include "net/test/test_data_directory.h"
#include "net/traffic_annotation/network_traffic_annotation_test_helper.h"
#include "services/metrics/public/cpp/metrics_utils.h"
#include "services/metrics/public/cpp/ukm_builders.h"
#include "services/metrics/public/cpp/ukm_source_id.h"
#include "services/metrics/public/mojom/ukm_interface.mojom.h"
#include "services/network/public/cpp/features.h"
#include "services/network/public/cpp/resource_request.h"
#include "services/network/public/cpp/simple_url_loader.h"
#include "services/network/public/cpp/url_loader_factory_builder.h"
#include "services/network/public/mojom/fetch_api.mojom.h"
#include "services/network/test/test_url_loader_client.h"
#include "third_party/blink/public/common/features.h"
#include "third_party/blink/public/common/input/web_input_event.h"
#include "third_party/blink/public/common/service_worker/service_worker_status_code.h"
#include "ui/webui/untrusted_web_ui_browsertest_util.h" // nogncheck
#include "url/origin.h"
#if BUILDFLAG(IS_ANDROID)
#include "chrome/browser/android/tab_android.h"
#include "chrome/browser/ui/android/tab_model/tab_model.h"
#include "chrome/browser/ui/android/tab_model/tab_model_list.h"
#include "chrome/test/base/android/android_ui_test_utils.h"
#endif
#if !BUILDFLAG(IS_ANDROID)
#include "chrome/browser/extensions/test_extension_action_dispatcher_observer.h"
#include "chrome/browser/new_tab_page/one_google_bar/one_google_bar_loader.h"
#include "chrome/browser/new_tab_page/one_google_bar/one_google_bar_service.h"
#include "chrome/browser/new_tab_page/one_google_bar/one_google_bar_service_factory.h"
#include "chrome/browser/search/search.h"
#include "chrome/browser/search_engines/template_url_service_factory.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_navigator_params.h" // nogncheck
#include "chrome/browser/ui/login/login_handler.h" // nogncheck
#include "chrome/browser/ui/search/ntp_test_utils.h"
#include "chrome/browser/ui/tabs/tab_strip_model.h"
#include "chrome/test/base/ui_test_utils.h"
#include "ui/base/ui_base_features.h"
#endif // !BUILDFLAG(IS_ANDROID)
#if BUILDFLAG(IS_CHROMEOS)
#include "chrome/browser/ash/profiles/profile_helper.h"
#endif // BUILDFLAG(IS_CHROMEOS)
static_assert(BUILDFLAG(ENABLE_EXTENSIONS_CORE));
using content::WebContents;
namespace extensions {
namespace {
// This is the public key of tools/origin_trials/eftest.key, used to validate
// origin trial tokens generated by tools/origin_trials/generate_token.py.
constexpr char kOriginTrialPublicKeyForTesting[] =
"dRCs+TocuKkocNKa0AtZ4awrt9XKH2SQCI6o4FY6BNA=";
// Observer that listens for messages from chrome.test.sendMessage to allow them
// to be used to trigger browser initiated naviagations from the javascript for
// testing purposes.
class NavigateTabMessageHandler {
public:
explicit NavigateTabMessageHandler(Profile* profile) : profile_(profile) {
navigate_listener_.SetOnRepeatedlySatisfied(base::BindRepeating(
&NavigateTabMessageHandler::HandleNavigateTabMessage,
base::Unretained(this)));
}
~NavigateTabMessageHandler() = default;
private:
void HandleNavigateTabMessage(const std::string& message) {
std::optional<base::Value> command = base::JSONReader::Read(message);
if (command && command->is_dict()) { // Check the message decoded from JSON
base::Value::Dict* data = command->GetDict().FindDict("navigate");
if (data) {
int tab_id = data->FindInt("tabId").value();
GURL url = GURL(*data->FindString("url"));
ASSERT_TRUE(url.is_valid());
content::WebContents* contents = nullptr;
ExtensionTabUtil::GetTabById(
tab_id, profile_, profile_->HasPrimaryOTRProfile(), &contents);
ASSERT_NE(contents, nullptr)
<< "Could not find tab with id: " << tab_id;
content::NavigationController::LoadURLParams params(url);
contents->GetController().LoadURLWithParams(params);
}
}
navigate_listener_.Reset();
}
raw_ptr<Profile, DanglingUntriaged> profile_;
ExtensionTestMessageListener navigate_listener_;
};
// A helper class that intercepts the
// `EventRouter::RemoveListenerForServiceWorker()` mojom receiver method and
// does *not* forward the call onto the real `EventRouter` browser
// implementation.
class EventRouterInterceptorForStopListenerRemoval
: public mojom::EventRouterInterceptorForTesting {
public:
EventRouterInterceptorForStopListenerRemoval(
content::BrowserContext* browser_context,
int worker_renderer_process_id)
: browser_context_(browser_context) {
auto* event_router = extensions::EventRouter::Get(browser_context_);
CHECK(event_router) << "There is no EventRouter for browser context when "
"creating the event router interceptor.";
event_router->SwapReceiverForTesting(worker_renderer_process_id, this);
}
mojom::EventRouter* GetForwardingInterface() override {
// This should be non-null if this interface is still receiving events. This
// causes all methods other than `RemoveListenerForServiceWorker()` to be
// sent along to the real implementation.
auto* event_router = extensions::EventRouter::Get(browser_context_);
CHECK(event_router)
<< "There is no `EventRouter` for browser context when attempting to "
"forward a mojom call to the real `EventRouter` implementation";
return event_router;
}
protected:
// mojom::EventRouter:
void RemoveListenerForServiceWorker(
mojom::EventListenerPtr event_listener) override {
// Don't call the real `EventRouter::RemoveListenerForServiceWorker()`
// method to simulate that the worker never finishing stopping and informing
// the browser to remove the listener.
}
private:
raw_ptr<content::BrowserContext> browser_context_;
};
// Sends an XHR request to the provided host, port, and path, and responds when
// the request was sent.
const char kPerformXhrJs[] =
"var url = 'http://%s:%d/%s';\n"
"var xhr = new XMLHttpRequest();\n"
"xhr.open('GET', url);\n"
"new Promise(resolve => {"
" xhr.onload = function() {\n"
" resolve(true);\n"
" };\n"
" xhr.onerror = function() {\n"
" resolve(false);\n"
" };\n"
" xhr.send();\n"
"});\n";
// Header values set by the server and by the extension.
const char kHeaderValueFromExtension[] = "ValueFromExtension";
const char kHeaderValueFromServer[] = "ValueFromServer";
#if !BUILDFLAG(IS_ANDROID)
constexpr char kCORSUrl[] = "http://cors.test/cors";
constexpr char kCORSProxyUser[] = "testuser";
constexpr char kCORSProxyPass[] = "testpass";
constexpr char kCustomPreflightHeader[] = "x-testheader";
#endif
// Performs an XHR in the given |frame|, replying when complete.
void PerformXhrInFrame(content::RenderFrameHost* frame,
const std::string& host,
int port,
const std::string& page) {
EXPECT_EQ(true, EvalJs(frame, base::StringPrintf(kPerformXhrJs, host.c_str(),
port, page.c_str())));
}
base::Value ExecuteScriptAndReturnValue(const ExtensionId& extension_id,
content::BrowserContext* context,
const std::string& script) {
return BackgroundScriptExecutor::ExecuteScript(
context, extension_id, script,
BackgroundScriptExecutor::ResultCapture::kSendScriptResult);
}
#if !BUILDFLAG(IS_ANDROID)
std::optional<bool> ExecuteScriptAndReturnBool(const ExtensionId& extension_id,
content::BrowserContext* context,
const std::string& script) {
std::optional<bool> result;
base::Value script_result =
ExecuteScriptAndReturnValue(extension_id, context, script);
if (script_result.is_bool()) {
result = script_result.GetBool();
}
return result;
}
std::optional<std::string> ExecuteScriptAndReturnString(
const ExtensionId& extension_id,
content::BrowserContext* context,
const std::string& script) {
std::optional<std::string> result;
base::Value script_result =
ExecuteScriptAndReturnValue(extension_id, context, script);
if (script_result.is_string()) {
result = script_result.GetString();
}
return result;
}
#endif // !BUILDFLAG(IS_ANDROID)
// Returns the current count of a variable stored in the |extension| background
// script context (either background page or service worker). Returns -1 if
// something goes awry.
int GetCountFromBackgroundScript(const Extension* extension,
content::BrowserContext* context,
const std::string& variable_name) {
const std::string script = base::StringPrintf(
"chrome.test.sendScriptResult(%s)", variable_name.c_str());
base::Value value =
ExecuteScriptAndReturnValue(extension->id(), context, script);
if (!value.is_int()) {
return -1;
}
return value.GetInt();
}
// Returns the current count of webRequests received by the |extension| in
// the background script, either background page or service worker. Assumes the
// extension stores a value on the `self` object. Returns -1 if something goes
// awry.
int GetWebRequestCountFromBackgroundScript(const Extension* extension,
content::BrowserContext* context) {
return GetCountFromBackgroundScript(extension, context,
"self.webRequestCount");
}
// Returns true if the |extension|'s background script saw an event for a
// request with the given |hostname| (|hostname| should exclude port).
bool HasSeenWebRequestInBackgroundScript(const Extension* extension,
content::BrowserContext* context,
const std::string& hostname) {
const std::string script = base::StringPrintf(
R"(chrome.test.sendScriptResult(
self.requestedHostnames.includes('%s'));)",
hostname.c_str());
base::Value value =
ExecuteScriptAndReturnValue(extension->id(), context, script);
DCHECK(value.is_bool());
return value.GetBool();
}
void WaitForExtraHeadersListener(base::WaitableEvent* event,
content::BrowserContext* browser_context) {
if (BrowserContextKeyedAPIFactory<WebRequestAPI>::Get(browser_context)
->HasExtraHeadersListenerForTesting()) {
event->Signal();
return;
}
base::SequencedTaskRunner::GetCurrentDefault()->PostTask(
FROM_HERE,
base::BindOnce(&WaitForExtraHeadersListener, event, browser_context));
}
} // namespace
class ExtensionWebRequestApiTest : public ExtensionApiTest {
public:
explicit ExtensionWebRequestApiTest(
ContextType context_type = ContextType::kFromManifest)
: ExtensionApiTest(context_type) {
feature_list_.InitWithFeatures(
/*enabled_features=*/{},
// TODO(crbug.com/40248833): Use HTTPS URLs in tests to avoid having to
// disable this feature.
/*disabled_features=*/
{features::kHttpsUpgrades, features::kHttpsFirstModeIncognito});
}
ExtensionWebRequestApiTest(const ExtensionWebRequestApiTest&) = delete;
ExtensionWebRequestApiTest& operator=(const ExtensionWebRequestApiTest&) =
delete;
~ExtensionWebRequestApiTest() override = default;
void SetUpOnMainThread() override {
ExtensionApiTest::SetUpOnMainThread();
host_resolver()->AddRule("*", "127.0.0.1");
navigation_handler_ =
std::make_unique<NavigateTabMessageHandler>(profile());
}
void SetUpCommandLine(base::CommandLine* command_line) override {
ExtensionApiTest::SetUpCommandLine(command_line);
command_line->AppendSwitchASCII(switches::kGaiaUrl, "http://gaia.com");
command_line->AppendSwitchASCII(embedder_support::kOriginTrialPublicKey,
kOriginTrialPublicKeyForTesting);
}
void RunPermissionTest(const char* extension_directory,
bool load_extension_with_incognito_permission,
bool wait_for_extension_loaded_in_incognito,
const char* expected_content_regular_window,
const char* exptected_content_incognito_window,
ContextType context_type);
mojo::PendingRemote<network::mojom::URLLoaderFactory>
CreateURLLoaderFactory() {
network::mojom::URLLoaderFactoryParamsPtr params =
network::mojom::URLLoaderFactoryParams::New();
params->process_id = network::mojom::kBrowserProcessId;
params->automatically_assign_isolation_info = true;
params->is_orb_enabled = false;
mojo::PendingRemote<network::mojom::URLLoaderFactory> loader_factory;
profile()
->GetDefaultStoragePartition()
->GetNetworkContext()
->CreateURLLoaderFactory(
loader_factory.InitWithNewPipeAndPassReceiver(), std::move(params));
return loader_factory;
}
void InstallWebRequestExtension(const std::string& name) {
constexpr char kManifest[] = R"({
"name": "%s",
"version": "1",
"manifest_version": 2,
"permissions": [
"webRequest"
]
})";
TestExtensionDir dir;
dir.WriteManifest(base::StringPrintf(kManifest, name.c_str()));
LoadExtension(dir.UnpackedPath());
test_dirs_.push_back(std::move(dir));
}
void OpenUrlInNewTab(const GURL& url) {
#if BUILDFLAG(IS_ANDROID)
android_ui_test_utils::OpenUrlInNewTab(profile(), web_contents(), url);
#else
ASSERT_TRUE(ui_test_utils::NavigateToURLWithDisposition(
browser(), url, WindowOpenDisposition::NEW_FOREGROUND_TAB,
ui_test_utils::BROWSER_TEST_WAIT_FOR_LOAD_STOP));
#endif
}
private:
base::test::ScopedFeatureList feature_list_;
std::vector<TestExtensionDir> test_dirs_;
std::unique_ptr<NavigateTabMessageHandler> navigation_handler_;
};
IN_PROC_BROWSER_TEST_F(ExtensionWebRequestApiTest,
WebRequestApiClearsBindingOnFirstListener) {
// Skip if the proxy is forced since the bindings will never be cleared in
// that case.
if (base::FeatureList::IsEnabled(
extensions_features::kForceWebRequestProxyForTest)) {
return;
}
mojo::Remote<network::mojom::URLLoaderFactory> loader_factory(
CreateURLLoaderFactory());
bool has_connection_error = false;
loader_factory.set_disconnect_handler(
base::BindLambdaForTesting([&]() { has_connection_error = true; }));
InstallWebRequestExtension("extension1");
profile()->GetDefaultStoragePartition()->FlushNetworkInterfaceForTesting();
EXPECT_TRUE(has_connection_error);
loader_factory.reset();
// The second time there should be no connection error.
loader_factory.Bind(CreateURLLoaderFactory());
has_connection_error = false;
loader_factory.set_disconnect_handler(
base::BindLambdaForTesting([&]() { has_connection_error = true; }));
InstallWebRequestExtension("extension2");
profile()->GetDefaultStoragePartition()->FlushNetworkInterfaceForTesting();
EXPECT_FALSE(has_connection_error);
}
// Tests registering webRequest events in multiple contexts in the same
// extension (which will thus be in the same process). Regression test for
// https://crbug.com/1297276.
IN_PROC_BROWSER_TEST_F(ExtensionWebRequestApiTest,
ListenersInMultipleContexts) {
ASSERT_TRUE(StartEmbeddedTestServer());
// Load an extension that has a page with two iframes. Each iframe registers
// a listener for the same event.
static constexpr char kManifest[] =
R"({
"name": "ext",
"manifest_version": 3,
"version": "1",
"permissions": ["webRequest"],
"host_permissions": ["http://example.com/*"]
})";
static constexpr char kParentHtml[] =
R"(<!doctype html>
<html>
Hello world
<iframe src="iframe.html" name="iframe1"></iframe>
<iframe src="iframe.html" name="iframe2"></iframe>
</html>)";
static constexpr char kIframeHtml[] =
R"(<!doctype html>
<html>
Iframe
<script src="iframe.js"></script>
</html>)";
static constexpr char kIframeJs[] =
R"(const frameName = window.name;
chrome.webRequest.onBeforeRequest.addListener(
(details) => {
chrome.test.sendMessage(frameName + ' event');
},
{urls: ['http://example.com/*'], types: ['main_frame']});
chrome.test.sendMessage(frameName + ' ready');)";
TestExtensionDir test_dir;
test_dir.WriteManifest(kManifest);
test_dir.WriteFile(FILE_PATH_LITERAL("parent.html"), kParentHtml);
test_dir.WriteFile(FILE_PATH_LITERAL("iframe.html"), kIframeHtml);
test_dir.WriteFile(FILE_PATH_LITERAL("iframe.js"), kIframeJs);
const Extension* extension = LoadExtension(test_dir.UnpackedPath());
ASSERT_TRUE(extension);
auto* router = WebRequestEventRouter::Get(profile());
ASSERT_TRUE(router);
static constexpr char kEventName[] = "webRequest.onBeforeRequest";
EXPECT_EQ(0u, router->GetListenerCountForTesting(profile(), kEventName));
// Load the extension page and wait for it to register its listeners.
{
ExtensionTestMessageListener listener1("iframe1 ready");
ExtensionTestMessageListener listener2("iframe2 ready");
ASSERT_TRUE(NavigateToURL(extension->GetResourceURL("parent.html")));
ASSERT_TRUE(listener1.WaitUntilSatisfied());
ASSERT_TRUE(listener2.WaitUntilSatisfied());
}
// Two different listeners should be registered.
EXPECT_EQ(2u, router->GetListenerCountForTesting(profile(), kEventName));
// Trigger an event. Both listeners should fire.
{
ExtensionTestMessageListener listener1("iframe1 event");
ExtensionTestMessageListener listener2("iframe2 event");
OpenUrlInNewTab(
embedded_test_server()->GetURL("example.com", "/title1.html"));
EXPECT_TRUE(listener1.WaitUntilSatisfied());
EXPECT_TRUE(listener2.WaitUntilSatisfied());
}
}
// Regression test for https://crbug.com/395985663.
// TODO(crbug.com/399261153): Flaky on Android.
#if BUILDFLAG(IS_ANDROID)
#define MAYBE_ExtensionRequestRedirectToServer \
DISABLED_ExtensionRequestRedirectToServer
#else
#define MAYBE_ExtensionRequestRedirectToServer ExtensionRequestRedirectToServer
#endif
IN_PROC_BROWSER_TEST_F(ExtensionWebRequestApiTest,
MAYBE_ExtensionRequestRedirectToServer) {
ASSERT_TRUE(StartEmbeddedTestServer());
TestExtensionDir test_dir;
test_dir.WriteManifest(R"({
"name": "Extension request redirect to server",
"manifest_version": 2,
"version": "0.1",
"default_locale": "en",
"background": { "scripts": ["background.js"] },
"permissions": ["<all_urls>", "webRequest", "webRequestBlocking"]
})");
test_dir.WriteFile(
FILE_PATH_LITERAL("background.js"),
content::JsReplace(
R"(
chrome.webRequest.onBeforeRequest.addListener(
function(details) {
if (details.url.endsWith('test') &&
details.url.startsWith('chrome-extension')) {
// Redirect "test" chrome-extension:// URL request to the
// HTTP server URL.
return {redirectUrl: $1};
}
},
{urls: ['<all_urls>']},
['blocking']);
(async () => {
const res = await fetch('./test');
const text = await res.text();
const expected = 'p {\n color: __MSG_text_color__;\n}\n';
// "__MSG_text_color__" must not be replaced with "red".
if (text == expected) {
chrome.test.notifyPass();
} else {
chrome.test.notifyFail('Unexpected content :' + text);
}
})();
)",
embedded_test_server()->GetURL(
"/extensions/api_test/content_scripts/css_l10n/test.css")));
{
base::ScopedAllowBlockingForTesting allow_blocking;
ASSERT_TRUE(
base::CopyDirectory(test_data_dir_.AppendASCII("content_scripts")
.AppendASCII("css_l10n")
.AppendASCII("_locales"),
test_dir.UnpackedPath(), true));
}
ResultCatcher result_catcher;
ASSERT_TRUE(LoadExtension(test_dir.UnpackedPath()));
ASSERT_TRUE(result_catcher.GetNextResult()) << result_catcher.message();
}
using ContextType = extensions::browser_test_util::ContextType;
enum class BackgroundResourceFetchTestCase {
kBackgroundResourceFetchEnabled,
kBackgroundResourceFetchDisabled,
};
class ExtensionWebRequestApiTestWithContextType
: public ExtensionWebRequestApiTest,
public testing::WithParamInterface<
std::pair<ContextType, BackgroundResourceFetchTestCase>> {
public:
ExtensionWebRequestApiTestWithContextType()
: ExtensionWebRequestApiTest(GetParam().first) {
std::vector<base::test::FeatureRef> enabled_features;
std::vector<base::test::FeatureRef> disabled_features;
if (IsBackgroundResourceFetchEnabled()) {
enabled_features.push_back(blink::features::kBackgroundResourceFetch);
} else {
disabled_features.push_back(blink::features::kBackgroundResourceFetch);
}
feature_background_resource_fetch_.InitWithFeatures(enabled_features,
disabled_features);
}
ExtensionWebRequestApiTestWithContextType(
const ExtensionWebRequestApiTestWithContextType&) = delete;
ExtensionWebRequestApiTestWithContextType& operator=(
const ExtensionWebRequestApiTestWithContextType&) = delete;
~ExtensionWebRequestApiTestWithContextType() override = default;
struct PrintToStringParamName {
std::string operator()(
const testing::TestParamInfo<
std::pair<ContextType, BackgroundResourceFetchTestCase>>& info)
const {
switch (info.param.second) {
case BackgroundResourceFetchTestCase::kBackgroundResourceFetchEnabled:
return "BackgroundResourceFetchEnabled";
case BackgroundResourceFetchTestCase::kBackgroundResourceFetchDisabled:
return "BackgroundResourceFetchDisabled";
}
}
};
protected:
ContextType GetContextType() const { return GetParam().first; }
private:
bool IsBackgroundResourceFetchEnabled() const {
return GetParam().second ==
BackgroundResourceFetchTestCase::kBackgroundResourceFetchEnabled;
}
base::test::ScopedFeatureList feature_background_resource_fetch_;
};
// Tests that use this class are checking for a sub-resource HSTS upgrade.
// Because kHstsTopLevelNavigationsOnly explicitly disallows sub-resource
// upgrades it needs to be disabled for these tests to pass.
class ExtensionWebRequestApiTestWithContextTypeForHstsTopLevelNavigationOnly
: public ExtensionWebRequestApiTestWithContextType {
public:
ExtensionWebRequestApiTestWithContextTypeForHstsTopLevelNavigationOnly() {
scoped_feature_list_.InitAndDisableFeature(
net::features::kHstsTopLevelNavigationsOnly);
}
private:
base::test::ScopedFeatureList scoped_feature_list_;
};
// This test suite verifies extension functionality in the service worker
// context, required for Manifest V3 and later.
//
// The test harness attempts to automatically convert Manifest V2 extensions to
// Manifest V3 for testing in ContextType::kServiceWorker. However, some
// Manifest V2 features are incompatible with Manifest V3 (e.g.,
// `webRequestBlocking`) and prevent automatic conversion. Extensions using
// these features must be manually migrated to Manifest V3 to be included in
// this test suite.
class ExtensionWebRequestApiTestWithContextTypeMV3
: public ExtensionWebRequestApiTestWithContextType {
public:
ExtensionWebRequestApiTestWithContextTypeMV3() = default;
ExtensionWebRequestApiTestWithContextTypeMV3(
const ExtensionWebRequestApiTestWithContextTypeMV3&) = delete;
ExtensionWebRequestApiTestWithContextTypeMV3& operator=(
const ExtensionWebRequestApiTestWithContextTypeMV3&) = delete;
~ExtensionWebRequestApiTestWithContextTypeMV3() override = default;
};
INSTANTIATE_TEST_SUITE_P(
ServiceWorker,
ExtensionWebRequestApiTestWithContextTypeMV3,
::testing::Values(
std::make_pair(
ContextType::kServiceWorker,
BackgroundResourceFetchTestCase::kBackgroundResourceFetchEnabled),
std::make_pair(
ContextType::kServiceWorker,
BackgroundResourceFetchTestCase::kBackgroundResourceFetchDisabled)),
ExtensionWebRequestApiTestWithContextType::PrintToStringParamName());
IN_PROC_BROWSER_TEST_P(ExtensionWebRequestApiTestWithContextTypeMV3,
WebRequestApi) {
ASSERT_TRUE(StartEmbeddedTestServer());
ASSERT_TRUE(RunExtensionTest("webrequest/test_api")) << message_;
}
INSTANTIATE_TEST_SUITE_P(
PersistentBackground,
ExtensionWebRequestApiTestWithContextType,
::testing::Values(
std::make_pair(
ContextType::kPersistentBackground,
BackgroundResourceFetchTestCase::kBackgroundResourceFetchEnabled),
std::make_pair(
ContextType::kPersistentBackground,
BackgroundResourceFetchTestCase::kBackgroundResourceFetchDisabled)),
ExtensionWebRequestApiTestWithContextType::PrintToStringParamName());
// These tests use webRequestBlocking and/or declarativeWebRequest.
// See crbug.com/332512510.
INSTANTIATE_TEST_SUITE_P(
ServiceWorker,
ExtensionWebRequestApiTestWithContextType,
::testing::Values(
std::make_pair(
ContextType::kServiceWorkerMV2,
BackgroundResourceFetchTestCase::kBackgroundResourceFetchEnabled),
std::make_pair(
ContextType::kServiceWorkerMV2,
BackgroundResourceFetchTestCase::kBackgroundResourceFetchDisabled)),
ExtensionWebRequestApiTestWithContextType::PrintToStringParamName());
INSTANTIATE_TEST_SUITE_P(
PersistentBackground,
ExtensionWebRequestApiTestWithContextTypeForHstsTopLevelNavigationOnly,
::testing::Values(
std::make_pair(
ContextType::kPersistentBackground,
BackgroundResourceFetchTestCase::kBackgroundResourceFetchEnabled),
std::make_pair(
ContextType::kPersistentBackground,
BackgroundResourceFetchTestCase::kBackgroundResourceFetchDisabled)),
ExtensionWebRequestApiTestWithContextType::PrintToStringParamName());
// These tests use webRequestBlocking and/or declarativeWebRequest.
// See crbug.com/332512510.
INSTANTIATE_TEST_SUITE_P(
ServiceWorker,
ExtensionWebRequestApiTestWithContextTypeForHstsTopLevelNavigationOnly,
::testing::Values(
std::make_pair(
ContextType::kServiceWorkerMV2,
BackgroundResourceFetchTestCase::kBackgroundResourceFetchEnabled),
std::make_pair(
ContextType::kServiceWorkerMV2,
BackgroundResourceFetchTestCase::kBackgroundResourceFetchDisabled)),
ExtensionWebRequestApiTestWithContextType::PrintToStringParamName());
// TODO(crbug.com/371324825): Enable more tests for Android build.
#if !BUILDFLAG(IS_ANDROID)
class DevToolsFrontendInWebRequestApiTest : public ExtensionApiTest {
public:
DevToolsFrontendInWebRequestApiTest() {
// TODO(crbug.com/40248833): Use HTTPS URLs in tests to avoid having to
// disable this feature.
feature_list_.InitAndDisableFeature(features::kHttpsUpgrades);
}
void SetUpOnMainThread() override {
ExtensionApiTest::SetUpOnMainThread();
host_resolver()->AddRule("*", "127.0.0.1");
int port = embedded_test_server()->port();
url_loader_interceptor_ = std::make_unique<content::URLLoaderInterceptor>(
base::BindRepeating(&DevToolsFrontendInWebRequestApiTest::OnIntercept,
base::Unretained(this), port));
navigation_handler_ =
std::make_unique<NavigateTabMessageHandler>(profile());
}
void TearDownOnMainThread() override {
url_loader_interceptor_.reset();
ExtensionApiTest::TearDownOnMainThread();
}
void SetUpCommandLine(base::CommandLine* command_line) override {
ExtensionApiTest::SetUpCommandLine(command_line);
test_root_dir_ = test_data_dir_.AppendASCII("webrequest");
embedded_test_server()->ServeFilesFromDirectory(test_root_dir_);
ASSERT_TRUE(StartEmbeddedTestServer());
command_line->AppendSwitchASCII(
switches::kCustomDevtoolsFrontend,
embedded_test_server()
->GetURL("customfrontend.example.com", "/devtoolsfrontend/")
.spec());
}
private:
bool OnIntercept(int test_server_port,
content::URLLoaderInterceptor::RequestParams* params) {
// The devtools remote frontend URLs are hardcoded into Chrome and are
// requested by some of the tests here to exercise their behavior with
// respect to WebRequest.
//
// We treat any URL request not targeting the test server as targeting the
// remote frontend, and we intercept them to fulfill from test data rather
// than hitting the network.
if (params->url_request.url.EffectiveIntPort() == test_server_port) {
return false;
}
std::string status_line;
std::string contents;
GetFileContents(
test_root_dir_.AppendASCII(params->url_request.url.path().substr(1)),
&status_line, &contents);
content::URLLoaderInterceptor::WriteResponse(status_line, contents,
params->client.get());
return true;
}
static void GetFileContents(const base::FilePath& path,
std::string* status_line,
std::string* contents) {
base::ScopedAllowBlockingForTesting allow_io;
if (!base::ReadFileToString(path, contents)) {
*status_line = "HTTP/1.0 404 Not Found\n\n";
return;
}
std::string content_type;
if (path.Extension() == FILE_PATH_LITERAL(".html")) {
content_type = "Content-type: text/html\n";
} else if (path.Extension() == FILE_PATH_LITERAL(".js")) {
content_type = "Content-type: application/javascript\n";
}
*status_line =
base::StringPrintf("HTTP/1.0 200 OK\n%s\n", content_type.c_str());
}
base::test::ScopedFeatureList feature_list_;
base::FilePath test_root_dir_;
std::unique_ptr<content::URLLoaderInterceptor> url_loader_interceptor_;
std::unique_ptr<NavigateTabMessageHandler> navigation_handler_;
};
#endif // !BUILDFLAG(IS_ANDROID)
IN_PROC_BROWSER_TEST_P(ExtensionWebRequestApiTestWithContextType,
WebRequestApi) {
ASSERT_TRUE(StartEmbeddedTestServer());
ASSERT_TRUE(RunExtensionTest("webrequest/test_api")) << message_;
}
#if !BUILDFLAG(IS_ANDROID)
IN_PROC_BROWSER_TEST_P(ExtensionWebRequestApiTestWithContextType,
WebRequestSimple) {
ASSERT_TRUE(StartEmbeddedTestServer());
ASSERT_TRUE(RunExtensionTest("webrequest/test_simple")) << message_;
}
// TODO(crbug.com/333791060): Parameterized test is flaky on multiple bots.
IN_PROC_BROWSER_TEST_P(ExtensionWebRequestApiTestWithContextType,
DISABLED_WebRequestComplex) {
ASSERT_TRUE(StartEmbeddedTestServer());
ASSERT_TRUE(RunExtensionTest("webrequest/test_complex")) << message_;
}
class ExtensionDevToolsProtocolTest
: public ExtensionWebRequestApiTestWithContextType,
public content::TestDevToolsProtocolClient {
protected:
void Attach() { AttachToWebContents(web_contents()); }
void TearDownOnMainThread() override {
DetachProtocolClient();
ExtensionWebRequestApiTest::TearDownOnMainThread();
}
content::WebContents* web_contents() {
return browser()->tab_strip_model()->GetWebContentsAt(0);
}
};
INSTANTIATE_TEST_SUITE_P(
PersistentBackground,
ExtensionDevToolsProtocolTest,
::testing::Values(
std::make_pair(
ContextType::kPersistentBackground,
BackgroundResourceFetchTestCase::kBackgroundResourceFetchEnabled),
std::make_pair(
ContextType::kPersistentBackground,
BackgroundResourceFetchTestCase::kBackgroundResourceFetchDisabled)),
ExtensionWebRequestApiTestWithContextType::PrintToStringParamName());
// These tests use webRequestBlocking and/or declarativeWebRequest.
// See crbug.com/332512510.
INSTANTIATE_TEST_SUITE_P(
ServiceWorker,
ExtensionDevToolsProtocolTest,
::testing::Values(
std::make_pair(
ContextType::kServiceWorkerMV2,
BackgroundResourceFetchTestCase::kBackgroundResourceFetchEnabled),
std::make_pair(
ContextType::kServiceWorkerMV2,
BackgroundResourceFetchTestCase::kBackgroundResourceFetchDisabled)),
ExtensionWebRequestApiTestWithContextType::PrintToStringParamName());
IN_PROC_BROWSER_TEST_P(ExtensionDevToolsProtocolTest,
HeaderOverriddenByExtension) {
Attach();
ASSERT_TRUE(embedded_test_server()->Start());
TestExtensionDir test_dir;
test_dir.WriteManifest(R"({
"name": "Header Override Test",
"manifest_version": 2,
"version": "0.1",
"background": { "scripts": ["background.js"], "persistent": true },
"permissions": ["<all_urls>", "webRequest", "webRequestBlocking"]
})");
test_dir.WriteFile(FILE_PATH_LITERAL("background.js"), R"(
chrome.webRequest.onHeadersReceived.addListener(function(details) {
var headers = details.responseHeaders;
headers.push({name: "extensionHeaderName",
value: "extensionHeaderValue"});
return {responseHeaders: headers};
},
{urls: ['<all_urls>']},
['responseHeaders', 'extraHeaders', 'blocking']);
chrome.test.sendMessage('ready');
)");
ExtensionTestMessageListener listener("ready");
ASSERT_TRUE(LoadExtension(test_dir.UnpackedPath()));
EXPECT_TRUE(listener.WaitUntilSatisfied());
SendCommand("Network.enable", base::Value::Dict(), true);
const GURL url(
embedded_test_server()->GetURL("/set-cookie?cookieName=cookieValue"));
ui_test_utils::NavigateToURLWithDisposition(
browser(), url, WindowOpenDisposition::CURRENT_TAB,
ui_test_utils::BROWSER_TEST_NO_WAIT);
// Check that `Network.responseReceived` contains the response header added
// by the extension
base::Value::Dict response_received_result =
WaitForNotification("Network.responseReceived", false);
auto* extension_header = response_received_result.FindByDottedPath(
"response.headers.extensionHeaderName");
ASSERT_TRUE(extension_header);
ASSERT_EQ(*extension_header, "extensionHeaderValue");
// Check that the cookie as specified in the original headers has been set
auto* get_all_cookies_result =
SendCommand("Network.getAllCookies", base::Value::Dict(), true);
const base::Value::List* cookies =
get_all_cookies_result->FindList("cookies");
ASSERT_TRUE(cookies);
ASSERT_EQ(cookies->size(), 1u);
ASSERT_TRUE(cookies->front().is_dict());
auto* cookie_name = cookies->front().GetDict().FindString("name");
ASSERT_TRUE(cookie_name);
ASSERT_EQ(*cookie_name, "cookieName");
auto* cookie_value = cookies->front().GetDict().FindString("value");
ASSERT_TRUE(cookie_value);
ASSERT_EQ(*cookie_value, "cookieValue");
}
IN_PROC_BROWSER_TEST_P(ExtensionDevToolsProtocolTest,
HeaderOverrideViaProtocolAllowedByExtension) {
Attach();
ASSERT_TRUE(embedded_test_server()->Start());
TestExtensionDir test_dir;
test_dir.WriteManifest(R"({
"name": "Header Override Test",
"manifest_version": 2,
"version": "0.1",
"background": { "scripts": ["background.js"], "persistent": true },
"permissions": ["<all_urls>", "webRequest", "webRequestBlocking"]
})");
test_dir.WriteFile(FILE_PATH_LITERAL("background.js"), R"(
chrome.webRequest.onHeadersReceived.addListener(function(details) {
var headers = details.responseHeaders;
headers.push({name: "extensionHeaderName",
value: "extensionHeaderValue"});
return {responseHeaders: headers};
},
{urls: ['<all_urls>']},
['responseHeaders', 'extraHeaders', 'blocking']);
chrome.test.sendMessage('ready');
)");
ExtensionTestMessageListener listener("ready");
ASSERT_TRUE(LoadExtension(test_dir.UnpackedPath()));
EXPECT_TRUE(listener.WaitUntilSatisfied());
SendCommand("Network.enable", base::Value::Dict(), true);
base::Value::Dict enable_params;
base::Value::List patterns;
base::Value::Dict pattern;
pattern.Set("requestStage", "Response");
patterns.Append(std::move(pattern));
enable_params.Set("patterns", std::move(patterns));
SendCommand("Fetch.enable", std::move(enable_params), true);
const GURL url(
embedded_test_server()->GetURL("/set-cookie?cookieName=cookieValue"));
ui_test_utils::NavigateToURLWithDisposition(
browser(), url, WindowOpenDisposition::CURRENT_TAB,
ui_test_utils::BROWSER_TEST_NO_WAIT);
base::Value::Dict request_paused_result =
WaitForNotification("Fetch.requestPaused", true);
std::string* request_id = request_paused_result.FindString("requestId");
// Checks that `Fetch.requestPaused` contains the response headers added by
// the extension
base::Value::List* response_headers =
request_paused_result.FindListByDottedPath("responseHeaders");
auto* header_name = response_headers->back().GetDict().FindString("name");
ASSERT_TRUE(header_name);
ASSERT_EQ(*header_name, "extensionHeaderName");
auto* header_value = response_headers->back().GetDict().FindString("value");
ASSERT_TRUE(header_value);
ASSERT_EQ(*header_value, "extensionHeaderValue");
// Response headers are replaced by new overrides
base::Value::Dict params;
params.Set("requestId", *request_id);
base::Value::Dict header_1;
header_1.Set("name", "firstName");
header_1.Set("value", "firstValue");
base::Value::Dict header_2;
header_2.Set("name", "secondName");
header_2.Set("value", "secondValue");
base::Value::List headers;
headers.Append(std::move(header_1));
headers.Append(std::move(header_2));
params.Set("responseHeaders", std::move(headers));
params.Set("responseCode", 200);
params.Set("body", "");
SendCommand("Fetch.fulfillRequest", std::move(params), false);
// Check that `Network.responseReceived` contains the response headers as
// specified via `Fetch.fulfillRequest`
base::Value::Dict response_received_result =
WaitForNotification("Network.responseReceived", false);
auto* first_header =
response_received_result.FindByDottedPath("response.headers.firstName");
ASSERT_TRUE(first_header);
ASSERT_EQ(*first_header, "firstValue");
auto* second_header =
response_received_result.FindByDottedPath("response.headers.secondName");
ASSERT_TRUE(second_header);
ASSERT_EQ(*second_header, "secondValue");
ASSERT_EQ(response_received_result.FindByDottedPath("response.headers")
->GetDict()
.size(),
2u);
// Check that the cookie as specified in the original headers has been set
auto* get_all_cookies_result =
SendCommand("Network.getAllCookies", base::Value::Dict(), true);
const base::Value::List* cookies =
get_all_cookies_result->FindList("cookies");
ASSERT_TRUE(cookies);
ASSERT_EQ(cookies->size(), 1u);
auto* cookie_name = cookies->front().GetDict().FindString("name");
ASSERT_TRUE(cookie_name);
ASSERT_EQ(*cookie_name, "cookieName");
auto* cookie_value = cookies->front().GetDict().FindString("value");
ASSERT_TRUE(cookie_value);
ASSERT_EQ(*cookie_value, "cookieValue");
}
// TODO(crbug.com/40168662) The test is flaky on multiple bots.
IN_PROC_BROWSER_TEST_F(ExtensionWebRequestApiTest, DISABLED_WebRequestTypes) {
ASSERT_TRUE(StartEmbeddedTestServer());
ASSERT_TRUE(RunExtensionTest("webrequest/test_types")) << message_;
}
// Test that a request to an OpenSearch description document (OSDD) generates
// an event with the expected details.
// Flaky on Windows and Mac: https://crbug.com/1218893
#if BUILDFLAG(IS_WIN) || BUILDFLAG(IS_MAC)
#define MAYBE_WebRequestTestOSDD DISABLED_WebRequestTestOSDD
#else
#define MAYBE_WebRequestTestOSDD WebRequestTestOSDD
#endif
IN_PROC_BROWSER_TEST_P(ExtensionWebRequestApiTestWithContextType,
MAYBE_WebRequestTestOSDD) {
// An OSDD request is only generated when a main frame at is loaded at /, so
// serve osdd/index.html from the root of the test server:
embedded_test_server()->ServeFilesFromDirectory(
test_data_dir_.AppendASCII("webrequest/osdd"));
ASSERT_TRUE(StartEmbeddedTestServer());
search_test_utils::WaitForTemplateURLServiceToLoad(
TemplateURLServiceFactory::GetForProfile(profile()));
ASSERT_TRUE(RunExtensionTest("webrequest/test_osdd")) << message_;
}
// Test that the webRequest events are dispatched with the expected details when
// a frame or tab is removed while a response is being received.
IN_PROC_BROWSER_TEST_F(ExtensionWebRequestApiTest,
WebRequestUnloadAfterRequest) {
ASSERT_TRUE(StartEmbeddedTestServer());
ASSERT_TRUE(
RunExtensionTest("webrequest", {.extension_url = "test_unload.html?1"}))
<< message_;
ASSERT_TRUE(
RunExtensionTest("webrequest", {.extension_url = "test_unload.html?2"}))
<< message_;
ASSERT_TRUE(
RunExtensionTest("webrequest", {.extension_url = "test_unload.html?3"}))
<< message_;
ASSERT_TRUE(
RunExtensionTest("webrequest", {.extension_url = "test_unload.html?4"}))
<< message_;
}
// Test that the webRequest events are dispatched with the expected details when
// a frame or tab is immediately removed after starting a request.
// Flaky on all platforms. See crbug.com/780369 for detail.
IN_PROC_BROWSER_TEST_F(ExtensionWebRequestApiTest,
DISABLED_WebRequestUnloadImmediately) {
ASSERT_TRUE(StartEmbeddedTestServer());
ASSERT_TRUE(
RunExtensionTest("webrequest", {.extension_url = "test_unload.html?5"}))
<< message_;
ASSERT_TRUE(
RunExtensionTest("webrequest", {.extension_url = "test_unload.html?6"}))
<< message_;
}
enum class ProfileMode {
kUserProfile,
kIncognito,
};
struct ARTestParams {
ProfileMode profile_mode;
ContextType context_type;
};
class ExtensionWebRequestApiAuthRequiredTest
: public ExtensionWebRequestApiTest,
public testing::WithParamInterface<ARTestParams> {
public:
ExtensionWebRequestApiAuthRequiredTest()
: ExtensionWebRequestApiTest(GetParam().context_type) {}
~ExtensionWebRequestApiAuthRequiredTest() override = default;
ExtensionWebRequestApiAuthRequiredTest(
const ExtensionWebRequestApiAuthRequiredTest&) = delete;
ExtensionWebRequestApiAuthRequiredTest& operator=(
ExtensionWebRequestApiAuthRequiredTest&) = delete;
protected:
static bool GetEnableIncognito() {
return GetParam().profile_mode == ProfileMode::kIncognito;
}
static std::string FormatCustomArg(const char* test_name) {
static constexpr char custom_arg_format[] =
R"({"testName": "%s", "runInIncognito": %s})";
return base::StringPrintf(custom_arg_format, test_name,
base::ToString(GetEnableIncognito()));
}
};
IN_PROC_BROWSER_TEST_P(ExtensionWebRequestApiAuthRequiredTest,
WebRequestAuthRequired) {
ASSERT_TRUE(StartEmbeddedTestServer());
// If running in incognito, create an incognito browser so the test
// framework can create an incognito window.
const bool incognito = GetEnableIncognito();
if (incognito) {
CreateIncognitoBrowser(profile());
}
ASSERT_TRUE(RunExtensionTest(
"webrequest/test_auth_required",
{.custom_arg = FormatCustomArg("authRequiredNonBlocking").c_str()},
{.allow_in_incognito = incognito}))
<< message_;
ASSERT_TRUE(RunExtensionTest(
"webrequest/test_auth_required",
{.custom_arg = FormatCustomArg("authRequiredSyncNoAction").c_str()},
{.allow_in_incognito = incognito}))
<< message_;
ASSERT_TRUE(RunExtensionTest(
"webrequest/test_auth_required",
{.custom_arg = FormatCustomArg("authRequiredSyncCancelAuth").c_str()},
{.allow_in_incognito = incognito}))
<< message_;
ASSERT_TRUE(RunExtensionTest(
"webrequest/test_auth_required",
{.custom_arg = FormatCustomArg("authRequiredSyncSetAuth").c_str()},
{.allow_in_incognito = incognito}))
<< message_;
}
IN_PROC_BROWSER_TEST_P(ExtensionWebRequestApiAuthRequiredTest,
WebRequestAuthRequiredAsync) {
ASSERT_TRUE(StartEmbeddedTestServer());
// If running in incognito, create an incognito browser so the tests
// run in an incognito window.
const bool incognito = GetEnableIncognito();
if (incognito) {
CreateIncognitoBrowser(profile());
}
ASSERT_TRUE(RunExtensionTest(
"webrequest/test_auth_required_async",
{.custom_arg = FormatCustomArg("authRequiredAsyncNoAction").c_str()},
{.allow_in_incognito = incognito}))
<< message_;
ASSERT_TRUE(RunExtensionTest(
"webrequest/test_auth_required_async",
{.custom_arg = FormatCustomArg("authRequiredAsyncCancelAuth").c_str()},
{.allow_in_incognito = incognito}))
<< message_;
ASSERT_TRUE(RunExtensionTest(
"webrequest/test_auth_required_async",
{.custom_arg = FormatCustomArg("authRequiredAsyncSetAuth").c_str()},
{.allow_in_incognito = incognito}))
<< message_;
}
// This is flaky on wide variety of platforms (beyond that tracked previously in
// https://crbug.com/998369). See https://crbug.com/1026001.
IN_PROC_BROWSER_TEST_P(ExtensionWebRequestApiAuthRequiredTest,
DISABLED_WebRequestAuthRequiredParallel) {
const bool incognito = GetEnableIncognito();
if (incognito) {
CreateIncognitoBrowser(profile());
}
const char* const custom_arg = incognito ? R"({"runInIncognito": true})"
: R"({"runInIncognito": false})";
ASSERT_TRUE(StartEmbeddedTestServer());
ASSERT_TRUE(RunExtensionTest("webrequest/test_auth_required_parallel",
{.custom_arg = custom_arg},
{.allow_in_incognito = incognito}))
<< message_;
}
INSTANTIATE_TEST_SUITE_P(
PersistentBackground,
ExtensionWebRequestApiAuthRequiredTest,
::testing::Values(ARTestParams(ProfileMode::kUserProfile,
ContextType::kPersistentBackground)));
INSTANTIATE_TEST_SUITE_P(
PersistentBackgroundIncognito,
ExtensionWebRequestApiAuthRequiredTest,
::testing::Values(ARTestParams(ProfileMode::kIncognito,
ContextType::kPersistentBackground)));
// These tests use webRequestBlocking and/or declarativeWebRequest.
// See crbug.com/332512510.
INSTANTIATE_TEST_SUITE_P(
ServiceWorker,
ExtensionWebRequestApiAuthRequiredTest,
::testing::Values(ARTestParams(ProfileMode::kUserProfile,
ContextType::kServiceWorkerMV2)));
INSTANTIATE_TEST_SUITE_P(
ServiceWorkerIncognito,
ExtensionWebRequestApiAuthRequiredTest,
::testing::Values(ARTestParams(ProfileMode::kIncognito,
ContextType::kServiceWorkerMV2)));
struct AuthRequiredServiceWorkerTestParams {
bool under_service_worker_control;
ContextType context_type;
};
// OnAuthRequired tests for subresource and sub frame, under service worker
// control and not under service worker control.
class ExtensionWebRequestApiAuthRequiredTestVariousContext
: public testing::WithParamInterface<AuthRequiredServiceWorkerTestParams>,
public ExtensionApiTest {
public:
ExtensionWebRequestApiAuthRequiredTestVariousContext()
: ExtensionApiTest(GetParam().context_type) {}
~ExtensionWebRequestApiAuthRequiredTestVariousContext() override = default;
ExtensionWebRequestApiAuthRequiredTestVariousContext(
const ExtensionWebRequestApiAuthRequiredTestVariousContext&) = delete;
ExtensionWebRequestApiAuthRequiredTestVariousContext& operator=(
const ExtensionWebRequestApiAuthRequiredTestVariousContext&) = delete;
void InstallRequestOnAuthRequiredTypeReportingExtension() {
TestExtensionDir test_dir;
test_dir.WriteManifest(R"({
"name": "Web Request onAuthRequired Type Reporting Extension",
"manifest_version": 2,
"version": "0.1",
"background": { "scripts": ["background.js"], "persistent": true },
"permissions": ["<all_urls>", "webRequest", "webRequestBlocking"]
})");
// Extension script that will send message about the request type of
// onAuthRequired event, and cancel the request.
static constexpr char kBackgroundScript[] = R"(
console.log('extension running');
chrome.webRequest.onAuthRequired.addListener(
function(details, callback) {
console.log('onAuthRequired fired for ' + details.type);
chrome.test.sendMessage(details.type);
return {cancel: true};
},
{urls: ['<all_urls>']},
['blocking']);
chrome.test.sendMessage('ready');
)";
test_dir.WriteFile(FILE_PATH_LITERAL("background.js"), kBackgroundScript);
ExtensionTestMessageListener listener("ready");
ASSERT_TRUE(LoadExtension(test_dir.UnpackedPath()));
EXPECT_TRUE(listener.WaitUntilSatisfied());
}
void RegisterServiceWorker() {
GURL url =
embedded_test_server()->GetURL("/workers/service_worker_setup.html");
EXPECT_TRUE(ui_test_utils::NavigateToURL(browser(), url));
EXPECT_EQ("ok", EvalJs(browser()->tab_strip_model()->GetActiveWebContents(),
"setup();"));
}
void RunCommonTestSetup() {
embedded_test_server()->ServeFilesFromSourceDirectory("content/test/data");
ASSERT_TRUE(embedded_test_server()->Start());
InstallRequestOnAuthRequiredTypeReportingExtension();
// Register a service worker for a variation of the test and not register it
// for another variation, so that we can verify that onAuthRequired event is
// fired regardless of whether the page is under service worker control.
if (GetParam().under_service_worker_control) {
RegisterServiceWorker();
}
// Navigate to the test page.
EXPECT_TRUE(ui_test_utils::NavigateToURL(
browser(), embedded_test_server()->GetURL("/workers/simple.html")));
}
// Ensures auth required event is received for subresource fetch.
void RunAuthRequiredTestForSubResource() {
RunCommonTestSetup();
// Make a fetch from the test page for a resource that requires auth.
ExtensionTestMessageListener listener("xmlhttprequest");
static constexpr char kSubResourceUrl[] =
"/auth-basic/auth_required_subresource?realm=auth_required_subresource";
std::string fetch_url =
embedded_test_server()->GetURL(kSubResourceUrl).spec();
EXPECT_EQ(401, EvalJs(browser()->tab_strip_model()->GetActiveWebContents(),
"try_fetch_status('" + fetch_url + "');"));
EXPECT_TRUE(listener.WaitUntilSatisfied());
}
// Ensures auth required event is received for sub frame navigation.
void RunAuthRequiredTestForSubFrame() {
RunCommonTestSetup();
// Add an iframe for a source that requires auth.
ExtensionTestMessageListener listener("sub_frame");
static constexpr char kSubFrameUrl[] =
"/auth-basic/auth_required_subframe?realm=auth_required_subframe";
std::string frame_url = embedded_test_server()->GetURL(kSubFrameUrl).spec();
static constexpr char kAddIframeScript[] = R"(
const el = document.createElement('iframe');
el.src = $1;
document.body.appendChild(el);
)";
content::EvalJsResult result =
EvalJs(browser()->tab_strip_model()->GetActiveWebContents(),
content::JsReplace(kAddIframeScript, frame_url));
ASSERT_THAT(result, content::EvalJsResult::IsOk());
EXPECT_TRUE(listener.WaitUntilSatisfied());
}
};
INSTANTIATE_TEST_SUITE_P(PersistentBackgroundWithServiceWorker,
ExtensionWebRequestApiAuthRequiredTestVariousContext,
::testing::Values(AuthRequiredServiceWorkerTestParams(
true,
ContextType::kPersistentBackground)));
INSTANTIATE_TEST_SUITE_P(PersistentBackgroundWithoutServiceWorker,
ExtensionWebRequestApiAuthRequiredTestVariousContext,
::testing::Values(AuthRequiredServiceWorkerTestParams(
false,
ContextType::kPersistentBackground)));
INSTANTIATE_TEST_SUITE_P(ServiceWorkerExtensionWithServiceWorker,
ExtensionWebRequestApiAuthRequiredTestVariousContext,
::testing::Values(AuthRequiredServiceWorkerTestParams(
true,
ContextType::kServiceWorkerMV2)));
INSTANTIATE_TEST_SUITE_P(ServiceWorkerExtensionWithoutServiceWorker,
ExtensionWebRequestApiAuthRequiredTestVariousContext,
::testing::Values(AuthRequiredServiceWorkerTestParams(
false,
ContextType::kServiceWorkerMV2)));
IN_PROC_BROWSER_TEST_P(ExtensionWebRequestApiAuthRequiredTestVariousContext,
SubFrame) {
RunAuthRequiredTestForSubFrame();
}
IN_PROC_BROWSER_TEST_P(ExtensionWebRequestApiAuthRequiredTestVariousContext,
SubResource) {
RunAuthRequiredTestForSubResource();
}
IN_PROC_BROWSER_TEST_P(ExtensionWebRequestApiTestWithContextType,
WebRequestBlocking) {
ASSERT_TRUE(StartEmbeddedTestServer());
ASSERT_TRUE(RunExtensionTest("webrequest/test_blocking",
{.custom_arg = R"({"testSuite": "normal"})"}))
<< message_;
}
// This test times out regularly on win_rel trybots. See http://crbug.com/122178
// Also on Linux/ChromiumOS debug, ASAN and MSAN builds.
// https://crbug.com/670415
// Slower and flaky tests should be isolated in the "slow" group of tests in
// the JS file. This prevents losing test coverage for those tests that are
// not causing timeouts and flakes.
// TODO(crbug.com/40916455): Investigate the flakiness across all
// platforms and re-enable.
IN_PROC_BROWSER_TEST_P(ExtensionWebRequestApiTestWithContextType,
DISABLED_WebRequestBlockingSlow) {
ASSERT_TRUE(StartEmbeddedTestServer());
ASSERT_TRUE(RunExtensionTest("webrequest/test_blocking",
{.custom_arg = R"({"testSuite": "slow"})"}))
<< message_;
}
IN_PROC_BROWSER_TEST_P(ExtensionWebRequestApiTestWithContextType,
WebRequestBlockingSetCookieHeader) {
ASSERT_TRUE(StartEmbeddedTestServer());
ASSERT_TRUE(RunExtensionTest("webrequest/test_blocking_cookie")) << message_;
}
IN_PROC_BROWSER_TEST_P(ExtensionWebRequestApiTestWithContextType,
WebRequestExtraHeaders) {
ASSERT_TRUE(StartEmbeddedTestServer());
ASSERT_TRUE(RunExtensionTest("webrequest/test_extra_headers")) << message_;
}
// Flaky on all platforms: https://crbug.com/1003661
IN_PROC_BROWSER_TEST_P(ExtensionWebRequestApiTestWithContextType,
DISABLED_WebRequestExtraHeaders_Auth) {
ASSERT_TRUE(StartEmbeddedTestServer());
ASSERT_TRUE(RunExtensionTest("webrequest/test_extra_headers_auth"))
<< message_;
}
IN_PROC_BROWSER_TEST_P(ExtensionWebRequestApiTestWithContextType,
WebRequestChangeCSPHeaders) {
ASSERT_TRUE(StartEmbeddedTestServer());
ASSERT_TRUE(RunExtensionTest("webrequest/test_change_csp_headers"))
<< message_;
}
// TODO: crbug.com/1450976 - Re-enable tests on Mac and CrOS.
#if BUILDFLAG(IS_MAC) || BUILDFLAG(IS_CHROMEOS)
#define MAYBE_WebRequestCORSWithExtraHeaders \
DISABLED_WebRequestCORSWithExtraHeaders
#else
#define MAYBE_WebRequestCORSWithExtraHeaders WebRequestCORSWithExtraHeaders
#endif
IN_PROC_BROWSER_TEST_P(ExtensionWebRequestApiTestWithContextType,
MAYBE_WebRequestCORSWithExtraHeaders) {
ASSERT_TRUE(StartEmbeddedTestServer());
ASSERT_TRUE(RunExtensionTest("webrequest/test_cors")) << message_;
}
#if defined(ADDRESS_SANITIZER)
#define MAYBE_WebRequestRedirects DISABLED_WebRequestRedirects
#else
#define MAYBE_WebRequestRedirects WebRequestRedirects
#endif
IN_PROC_BROWSER_TEST_P(ExtensionWebRequestApiTestWithContextType,
MAYBE_WebRequestRedirects) {
ASSERT_TRUE(StartEmbeddedTestServer());
ASSERT_TRUE(RunExtensionTest("webrequest/test_redirects")) << message_;
}
IN_PROC_BROWSER_TEST_P(ExtensionWebRequestApiTestWithContextType,
WebRequestRedirectsWithExtraHeaders) {
ASSERT_TRUE(StartEmbeddedTestServer());
ASSERT_TRUE(RunExtensionTest("webrequest/test_redirects",
{.custom_arg = R"({"useExtraHeaders": true})"}))
<< message_;
}
// Tests that redirects from secure to insecure don't send the referrer header.
IN_PROC_BROWSER_TEST_P(ExtensionWebRequestApiTestWithContextType,
WebRequestRedirectsToInsecure) {
ASSERT_TRUE(StartEmbeddedTestServer());
GURL insecure_destination =
embedded_test_server()->GetURL("/extensions/test_file.html");
net::EmbeddedTestServer https_test_server(
net::EmbeddedTestServer::TYPE_HTTPS);
https_test_server.ServeFilesFromDirectory(test_data_dir_);
ASSERT_TRUE(https_test_server.Start());
GURL url = https_test_server.GetURL("/webrequest/simulate_click.html");
base::Value::List custom_args;
custom_args.Append(url.spec());
custom_args.Append(insecure_destination.spec());
std::string config_string;
base::JSONWriter::Write(custom_args, &config_string);
ASSERT_TRUE(RunExtensionTest("webrequest/test_redirects_from_secure",
{.custom_arg = config_string.c_str()}))
<< message_;
}
// Tests redirects around workers. To test service workers, the HTTPS test
// server is used.
// TODO(crbug.com/40255652): test is flaky on linux-chromeos-rel.
// TODO(crbug.com/40259518): test is flaky on Mac10.14.
// TODO(crbug.com/40282182): test is flaky on linux tests.
// TODO(crbug.com/393555373): test is flaky on Windows.
#if BUILDFLAG(IS_CHROMEOS) || BUILDFLAG(IS_MAC) || BUILDFLAG(IS_LINUX) || \
BUILDFLAG(IS_WIN)
#define MAYBE_WebRequestRedirectsWorkers DISABLED_WebRequestRedirectsWorkers
#else
#define MAYBE_WebRequestRedirectsWorkers WebRequestRedirectsWorkers
#endif
IN_PROC_BROWSER_TEST_P(ExtensionWebRequestApiTestWithContextType,
MAYBE_WebRequestRedirectsWorkers) {
ASSERT_TRUE(StartEmbeddedTestServer());
net::EmbeddedTestServer https_test_server(
net::EmbeddedTestServer::TYPE_HTTPS);
https_test_server.ServeFilesFromDirectory(test_data_dir_);
ASSERT_TRUE(https_test_server.Start());
GURL base_url =
https_test_server.GetURL("/webrequest/test_redirects_workers/page/");
base::Value::Dict custom_args;
custom_args.Set("base_url", base_url.spec());
std::string config_string;
base::JSONWriter::Write(custom_args, &config_string);
ASSERT_TRUE(RunExtensionTest("webrequest/test_redirects_workers",
{.custom_arg = config_string.c_str()}))
<< message_;
}
// TODO(crbug.com/40916455): test is flaky on multiple platforms.
IN_PROC_BROWSER_TEST_P(ExtensionWebRequestApiTestWithContextType,
DISABLED_WebRequestSubresourceRedirects) {
ASSERT_TRUE(StartEmbeddedTestServer());
ASSERT_TRUE(RunExtensionTest("webrequest/test_subresource_redirects"))
<< message_;
}
// TODO(crbug.com/40916455): test is flaky on multiple platforms.
IN_PROC_BROWSER_TEST_P(
ExtensionWebRequestApiTestWithContextType,
DISABLED_WebRequestSubresourceRedirectsWithExtraHeaders) {
ASSERT_TRUE(StartEmbeddedTestServer());
ASSERT_TRUE(RunExtensionTest("webrequest/test_subresource_redirects",
{.custom_arg = R"({"useExtraHeaders": true})"}))
<< message_;
}
IN_PROC_BROWSER_TEST_P(ExtensionWebRequestApiTestWithContextType,
WebRequestNewTab) {
ASSERT_TRUE(StartEmbeddedTestServer());
// Wait for the extension to set itself up and return control to us.
ASSERT_TRUE(RunExtensionTest("webrequest/test_new_tab")) << message_;
WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents();
EXPECT_TRUE(content::WaitForLoadStop(tab));
ResultCatcher catcher;
ExtensionRegistry* registry = ExtensionRegistry::Get(browser()->profile());
const Extension* extension =
registry->enabled_extensions().GetByID(last_loaded_extension_id());
GURL url = extension->GetResourceURL("newTab/a.html");
ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), url));
// There's a link on a.html with target=_blank. Click on it to open it in a
// new tab.
blink::WebMouseEvent mouse_event(
blink::WebInputEvent::Type::kMouseDown,
blink::WebInputEvent::kNoModifiers,
blink::WebInputEvent::GetStaticTimeStampForTests());
mouse_event.button = blink::WebMouseEvent::Button::kLeft;
mouse_event.SetPositionInWidget(7, 7);
mouse_event.click_count = 1;
tab->GetPrimaryMainFrame()
->GetRenderViewHost()
->GetWidget()
->ForwardMouseEvent(mouse_event);
mouse_event.SetType(blink::WebInputEvent::Type::kMouseUp);
tab->GetPrimaryMainFrame()
->GetRenderViewHost()
->GetWidget()
->ForwardMouseEvent(mouse_event);
ASSERT_TRUE(catcher.GetNextResult()) << catcher.message();
}
IN_PROC_BROWSER_TEST_P(ExtensionWebRequestApiTestWithContextType,
WebRequestDeclarative1) {
ASSERT_TRUE(StartEmbeddedTestServer());
ASSERT_TRUE(RunExtensionTest("webrequest/test_declarative",
{.custom_arg = R"({"testSuite": "normal1"})"}))
<< message_;
}
// This test fixture runs all of the broken and flaky tests. It's disabled
// until these tests are fixed and moved to the set of tests that aren't
// broken or flaky. Should tests become flaky, they can be moved here.
// See https://crbug.com/846555.
IN_PROC_BROWSER_TEST_P(ExtensionWebRequestApiTestWithContextType,
DISABLED_WebRequestDeclarative1Broken) {
ASSERT_TRUE(StartEmbeddedTestServer());
ASSERT_TRUE(RunExtensionTest("webrequest/test_declarative",
{.custom_arg = R"({"testSuite": "broken"})"}))
<< message_;
}
IN_PROC_BROWSER_TEST_P(ExtensionWebRequestApiTestWithContextType,
WebRequestDeclarative2) {
ASSERT_TRUE(StartEmbeddedTestServer());
ASSERT_TRUE(RunExtensionTest("webrequest/test_declarative",
{.custom_arg = R"({"testSuite": "normal2"})"}))
<< message_;
}
void ExtensionWebRequestApiTest::RunPermissionTest(
const char* extension_directory,
bool load_extension_with_incognito_permission,
bool wait_for_extension_loaded_in_incognito,
const char* expected_content_regular_window,
const char* exptected_content_incognito_window,
ContextType context_type) {
ResultCatcher catcher;
catcher.RestrictToBrowserContext(browser()->profile());
ResultCatcher catcher_incognito;
catcher_incognito.RestrictToBrowserContext(
browser()->profile()->GetPrimaryOTRProfile(/*create_if_needed=*/true));
ExtensionTestMessageListener listener("done");
ExtensionTestMessageListener listener_incognito("done_incognito");
ASSERT_TRUE(LoadExtension(
test_data_dir_.AppendASCII("webrequest_permissions")
.AppendASCII(extension_directory),
{.allow_in_incognito = load_extension_with_incognito_permission,
.context_type = context_type}));
// Test that navigation in regular window is properly redirected.
EXPECT_TRUE(listener.WaitUntilSatisfied());
// This navigation should be redirected.
ASSERT_TRUE(ui_test_utils::NavigateToURL(
browser(), embedded_test_server()->GetURL("/extensions/test_file.html")));
WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents();
EXPECT_EQ(expected_content_regular_window,
content::EvalJs(tab, "document.body.textContent"));
// Test that navigation in OTR window is properly redirected.
Browser* otr_browser =
OpenURLOffTheRecord(browser()->profile(), GURL("about:blank"));
if (wait_for_extension_loaded_in_incognito) {
EXPECT_TRUE(listener_incognito.WaitUntilSatisfied());
}
// This navigation should be redirected if
// load_extension_with_incognito_permission is true.
ASSERT_TRUE(ui_test_utils::NavigateToURL(
otr_browser,
embedded_test_server()->GetURL("/extensions/test_file.html")));
WebContents* otr_tab = otr_browser->tab_strip_model()->GetActiveWebContents();
EXPECT_EQ(exptected_content_incognito_window,
content::EvalJs(otr_tab, "document.body.textContent"));
}
IN_PROC_BROWSER_TEST_P(ExtensionWebRequestApiTestWithContextType,
WebRequestDeclarativePermissionSpanning1) {
// Test spanning with incognito permission.
ASSERT_TRUE(StartEmbeddedTestServer());
RunPermissionTest("spanning", true, false, "redirected1", "redirected1",
GetContextType());
}
IN_PROC_BROWSER_TEST_P(ExtensionWebRequestApiTestWithContextType,
WebRequestDeclarativePermissionSpanning2) {
// Test spanning without incognito permission.
ASSERT_TRUE(StartEmbeddedTestServer());
RunPermissionTest("spanning", false, false, "redirected1", "",
GetContextType());
}
IN_PROC_BROWSER_TEST_P(ExtensionWebRequestApiTestWithContextType,
WebRequestDeclarativePermissionSplit1) {
// Test split with incognito permission.
ASSERT_TRUE(StartEmbeddedTestServer());
RunPermissionTest("split", true, true, "redirected1", "redirected2",
GetContextType());
}
IN_PROC_BROWSER_TEST_P(ExtensionWebRequestApiTestWithContextType,
WebRequestDeclarativePermissionSplit2) {
// Test split without incognito permission.
ASSERT_TRUE(StartEmbeddedTestServer());
RunPermissionTest("split", false, false, "redirected1", "", GetContextType());
}
// TODO(crbug.com/41010858): Cure these flaky tests.
// TODO(crbug.com/40734863): Bulk-disabled as part of mac arm64 bot greening
// TODO(crbug.com/40773828): Further disabled due to ongoing flakiness.
IN_PROC_BROWSER_TEST_F(ExtensionWebRequestApiTest, DISABLED_PostData1) {
// Test HTML form POST data access with the default and "url" encoding.
ASSERT_TRUE(StartEmbeddedTestServer());
ASSERT_TRUE(
RunExtensionTest("webrequest", {.extension_url = "test_post1.html"}))
<< message_;
}
IN_PROC_BROWSER_TEST_F(ExtensionWebRequestApiTest, DISABLED_PostData2) {
// Test HTML form POST data access with the multipart and plaintext encoding.
ASSERT_TRUE(StartEmbeddedTestServer());
ASSERT_TRUE(
RunExtensionTest("webrequest", {.extension_url = "test_post2.html"}))
<< message_;
}
IN_PROC_BROWSER_TEST_P(ExtensionWebRequestApiTestWithContextType,
DeclarativeSendMessage) {
ASSERT_TRUE(StartEmbeddedTestServer());
ASSERT_TRUE(RunExtensionTest("webrequest_sendmessage")) << message_;
}
// Check that reloading an extension that runs in incognito split mode and
// has two active background pages with registered events does not crash the
// browser. Regression test for http://crbug.com/40309927
// TODO(crbug.com/40897394): Flaky on Linux.
#if BUILDFLAG(IS_LINUX)
#define MAYBE_IncognitoSplitModeReload DISABLED_IncognitoSplitModeReload
#else
#define MAYBE_IncognitoSplitModeReload IncognitoSplitModeReload
#endif
IN_PROC_BROWSER_TEST_P(ExtensionWebRequestApiTestWithContextType,
MAYBE_IncognitoSplitModeReload) {
ASSERT_TRUE(StartEmbeddedTestServer());
// Wait for rules to be set up.
ExtensionTestMessageListener listener("done");
ExtensionTestMessageListener listener_incognito("done_incognito");
const Extension* extension =
LoadExtension(test_data_dir_.AppendASCII("webrequest_reload"),
{.allow_in_incognito = true});
ASSERT_TRUE(extension);
OpenURLOffTheRecord(browser()->profile(), GURL("about:blank"));
EXPECT_TRUE(listener.WaitUntilSatisfied());
EXPECT_TRUE(listener_incognito.WaitUntilSatisfied());
// Reload extension and wait for rules to be set up again. This should not
// crash the browser.
ExtensionTestMessageListener listener2("done");
ExtensionTestMessageListener listener_incognito2("done_incognito");
ReloadExtension(extension->id());
EXPECT_TRUE(listener2.WaitUntilSatisfied());
EXPECT_TRUE(listener_incognito2.WaitUntilSatisfied());
}
IN_PROC_BROWSER_TEST_P(ExtensionWebRequestApiTestWithContextType,
ExtensionRequests) {
ASSERT_TRUE(StartEmbeddedTestServer());
ExtensionTestMessageListener listener_main1("web_request_status1",
ReplyBehavior::kWillReply);
ExtensionTestMessageListener listener_main2("web_request_status2",
ReplyBehavior::kWillReply);
ExtensionTestMessageListener listener_app("app_done");
ExtensionTestMessageListener listener_extension("extension_done");
// Set up webRequest listener
ASSERT_TRUE(
LoadExtension(test_data_dir_.AppendASCII("webrequest_extensions/main")));
EXPECT_TRUE(listener_main1.WaitUntilSatisfied());
EXPECT_TRUE(listener_main2.WaitUntilSatisfied());
// Perform some network activity in an app and another extension.
ASSERT_TRUE(
LoadExtension(test_data_dir_.AppendASCII("webrequest_extensions/app"),
{.context_type = ContextType::kFromManifest}));
ASSERT_TRUE(LoadExtension(
test_data_dir_.AppendASCII("webrequest_extensions/extension"),
{.context_type = ContextType::kFromManifest}));
EXPECT_TRUE(listener_app.WaitUntilSatisfied());
EXPECT_TRUE(listener_extension.WaitUntilSatisfied());
// Load a page, a content script from "webrequest_extensions/extension" will
// ping us when it is ready.
ExtensionTestMessageListener listener_pageready("contentscript_ready",
ReplyBehavior::kWillReply);
ASSERT_TRUE(ui_test_utils::NavigateToURL(
browser(), embedded_test_server()->GetURL(
"/extensions/test_file.html?match_webrequest_test")));
EXPECT_TRUE(listener_pageready.WaitUntilSatisfied());
// The extension and app-generated requests should not have triggered any
// webRequest event filtered by type 'xmlhttprequest'.
// (check this here instead of before the navigation, in case the webRequest
// event routing is slow for some reason).
ExtensionTestMessageListener listener_result;
listener_main1.Reply("");
EXPECT_TRUE(listener_result.WaitUntilSatisfied());
EXPECT_EQ("Did not intercept any requests.", listener_result.message());
ExtensionTestMessageListener listener_contentscript("contentscript_done");
ExtensionTestMessageListener listener_framescript("framescript_done");
// Proceed with the final tests: Let the content script fire a request and
// then load an iframe which also fires a XHR request.
listener_pageready.Reply("");
EXPECT_TRUE(listener_contentscript.WaitUntilSatisfied());
EXPECT_TRUE(listener_framescript.WaitUntilSatisfied());
// Collect the visited URLs. The content script and subframe does not run in
// the extension's process, so the requests should be visible to the main
// extension.
listener_result.Reset();
listener_main2.Reply("");
EXPECT_TRUE(listener_result.WaitUntilSatisfied());
// The extension frame does run in the extension's process. Any requests made
// by it should not be visible to other extensions, since they won't have
// access to the request initiator.
//
// OTOH, the content script executes fetches/XHRs as-if they were initiated by
// the webpage that the content script got injected into. Here, the webpage
// has origin of http://127.0.0.1:<some port>, and so the webRequest API
// extension should have access to the request.
EXPECT_EQ("Intercepted requests: ?contentscript", listener_result.message());
}
#endif // !BUILDFLAG(IS_ANDROID)
IN_PROC_BROWSER_TEST_F(ExtensionWebRequestApiTest, HostedAppRequest) {
ASSERT_TRUE(StartEmbeddedTestServer());
GURL hosted_app_url(embedded_test_server()->GetURL(
"/extensions/api_test/webrequest_hosted_app/index.html"));
scoped_refptr<const Extension> hosted_app =
ExtensionBuilder()
.SetManifest(
base::Value::Dict()
.Set("name", "Some hosted app")
.Set("version", "1")
.Set("manifest_version", 2)
.Set("app",
base::Value::Dict().Set(
"launch", base::Value::Dict().Set(
"web_url", hosted_app_url.spec()))))
.Build();
extension_registrar()->AddExtension(hosted_app);
ExtensionTestMessageListener listener1("main_frame");
ExtensionTestMessageListener listener2("xmlhttprequest");
ASSERT_TRUE(
LoadExtension(test_data_dir_.AppendASCII("webrequest_hosted_app")));
ASSERT_TRUE(NavigateToURL(hosted_app_url));
EXPECT_TRUE(listener1.WaitUntilSatisfied());
EXPECT_TRUE(listener2.WaitUntilSatisfied());
}
#if !BUILDFLAG(IS_ANDROID)
// Tests that WebRequest works with runtime host permissions.
IN_PROC_BROWSER_TEST_P(ExtensionWebRequestApiTestWithContextType,
WebRequestWithWithheldPermissions) {
content::SetupCrossSiteRedirector(embedded_test_server());
ASSERT_TRUE(embedded_test_server()->Start());
// Load an extension that registers a listener for webRequest events, and
// wait until it's initialized.
ExtensionTestMessageListener listener("ready");
const Extension* extension =
LoadExtension(test_data_dir_.AppendASCII("webrequest_activetab"));
ASSERT_TRUE(extension) << message_;
ScriptingPermissionsModifier(profile(), base::WrapRefCounted(extension))
.SetWithholdHostPermissions(true);
EXPECT_TRUE(listener.WaitUntilSatisfied());
// Navigate the browser to a page in a new tab. The page at "a.com" has two
// two cross-origin iframes to "b.com" and "c.com".
const std::string kHost = "a.com";
GURL url = embedded_test_server()->GetURL(kHost, "/iframe_cross_site.html");
NavigateParams params(browser(), url, ui::PAGE_TRANSITION_LINK);
params.disposition = WindowOpenDisposition::NEW_FOREGROUND_TAB;
ui_test_utils::NavigateToURL(¶ms);
content::WebContents* web_contents =
browser()->tab_strip_model()->GetActiveWebContents();
ASSERT_TRUE(web_contents);
ExtensionActionRunner* runner =
ExtensionActionRunner::GetForWebContents(web_contents);
ASSERT_TRUE(runner);
int port = embedded_test_server()->port();
const std::string kXhrPath = "simple.html";
// The extension shouldn't have currently received any webRequest events,
// since it doesn't have any permissions.
{
EXPECT_EQ(0, GetWebRequestCountFromBackgroundScript(extension, profile()));
content::RenderFrameHostWrapper main_frame(
web_contents->GetPrimaryMainFrame());
content::RenderFrameHostWrapper child_frame(
ChildFrameAt(main_frame.get(), 0));
ASSERT_TRUE(child_frame);
const std::string kChildHost = child_frame->GetLastCommittedURL().host();
// The extension shouldn't be able to intercept the xhr requests since it
// doesn't have any permissions.
PerformXhrInFrame(main_frame.get(), kHost, port, kXhrPath);
PerformXhrInFrame(child_frame.get(), kChildHost, port, kXhrPath);
EXPECT_EQ(0, GetWebRequestCountFromBackgroundScript(extension, profile()));
EXPECT_EQ(BLOCKED_ACTION_WEB_REQUEST,
runner->GetBlockedActions(extension->id()));
// Grant activeTab permission.
runner->accept_bubble_for_testing(true);
runner->RunAction(extension, true);
base::RunLoop().RunUntilIdle();
EXPECT_TRUE(content::WaitForLoadStop(web_contents));
}
// The runner will have refreshed the page, and the extension will have
// received access to the main-frame ("a.com"). It should still not be able to
// intercept the cross-origin sub-frame requests to "b.com" and "c.com".
content::RenderFrameHostWrapper main_frame(
web_contents->GetPrimaryMainFrame());
content::RenderFrameHostWrapper child_frame(
ChildFrameAt(main_frame.get(), 0));
const std::string kChildHost = child_frame->GetLastCommittedURL().host();
ASSERT_TRUE(child_frame);
EXPECT_TRUE(
HasSeenWebRequestInBackgroundScript(extension, profile(), "a.com"));
EXPECT_FALSE(
HasSeenWebRequestInBackgroundScript(extension, profile(), "b.com"));
EXPECT_FALSE(
HasSeenWebRequestInBackgroundScript(extension, profile(), "c.com"));
// The withheld sub-frame requests should not show up as a blocked action.
EXPECT_EQ(BLOCKED_ACTION_NONE, runner->GetBlockedActions(extension->id()));
int request_count =
GetWebRequestCountFromBackgroundScript(extension, profile());
// ... and the extension should receive future events.
PerformXhrInFrame(main_frame.get(), kHost, port, kXhrPath);
++request_count;
EXPECT_EQ(request_count,
GetWebRequestCountFromBackgroundScript(extension, profile()));
// However, activeTab only grants access to the main frame, not to child
// frames. As such, trying to XHR in the child frame should still fail.
PerformXhrInFrame(child_frame.get(), kChildHost, port, kXhrPath);
EXPECT_EQ(request_count,
GetWebRequestCountFromBackgroundScript(extension, profile()));
// But since there's no way for the user to currently grant access to child
// frames, this shouldn't show up as a blocked action.
EXPECT_EQ(BLOCKED_ACTION_NONE, runner->GetBlockedActions(extension->id()));
// Revoke the extension's tab permissions.
ActiveTabPermissionGranter* granter =
ActiveTabPermissionGranter::FromWebContents(web_contents);
ASSERT_TRUE(granter);
granter->RevokeForTesting();
base::RunLoop().RunUntilIdle();
// The extension should no longer receive webRequest events since they are
// withheld. The extension icon should get updated to show the wants-to-run
// badge UI.
TestExtensionActionDispatcherObserver action_updated_waiter(profile(),
extension->id());
PerformXhrInFrame(main_frame.get(), kHost, port, kXhrPath);
action_updated_waiter.Wait();
EXPECT_EQ(web_contents, action_updated_waiter.last_web_contents());
EXPECT_EQ(request_count,
GetWebRequestCountFromBackgroundScript(extension, profile()));
EXPECT_EQ(BLOCKED_ACTION_WEB_REQUEST,
runner->GetBlockedActions(extension->id()));
}
// Test that extensions with granted runtime host permissions to a tab can
// intercept cross-origin requests from that tab.
IN_PROC_BROWSER_TEST_P(ExtensionWebRequestApiTestWithContextType,
WebRequestWithheldPermissionsCrossOriginRequests) {
content::SetupCrossSiteRedirector(embedded_test_server());
ASSERT_TRUE(embedded_test_server()->Start());
// Load an extension that registers a listener for webRequest events, and
// wait until it's initialized.
ExtensionTestMessageListener listener("ready");
const Extension* extension =
LoadExtension(test_data_dir_.AppendASCII("webrequest_activetab"));
ASSERT_TRUE(extension) << message_;
ScriptingPermissionsModifier(profile(), base::WrapRefCounted(extension))
.SetWithholdHostPermissions(true);
EXPECT_TRUE(listener.WaitUntilSatisfied());
ASSERT_TRUE(ui_test_utils::NavigateToURL(
browser(), embedded_test_server()->GetURL(
"a.com", "/extensions/cross_site_script.html")));
const std::string kCrossSiteHost("b.com");
EXPECT_FALSE(HasSeenWebRequestInBackgroundScript(extension, profile(),
kCrossSiteHost));
content::WebContents* web_contents =
browser()->tab_strip_model()->GetActiveWebContents();
ExtensionActionRunner* runner =
ExtensionActionRunner::GetForWebContents(web_contents);
ASSERT_TRUE(runner);
EXPECT_EQ(BLOCKED_ACTION_WEB_REQUEST,
runner->GetBlockedActions(extension->id()));
// Grant runtime host permission to the page. The page should refresh. Even
// though the request is for b.com (and the extension only has access to
// a.com), it should still see the request. This is necessary for extensions
// with webRequest to work with runtime host permissions.
// https://crbug.com/851722.
runner->accept_bubble_for_testing(true);
runner->RunAction(extension, true /* grant tab permissions */);
base::RunLoop().RunUntilIdle();
EXPECT_TRUE(content::WaitForLoadStop(web_contents));
EXPECT_EQ(BLOCKED_ACTION_NONE, runner->GetBlockedActions(extension->id()));
EXPECT_TRUE(HasSeenWebRequestInBackgroundScript(extension, profile(),
kCrossSiteHost));
}
// Tests behavior when an extension has withheld access to a request's URL, but
// not the initiator's (tab's) URL. Regression test for
// https://crbug.com/891586.
IN_PROC_BROWSER_TEST_P(ExtensionWebRequestApiTestWithContextType,
WithheldHostPermissionsForCrossOriginWithoutInitiator) {
content::SetupCrossSiteRedirector(embedded_test_server());
ASSERT_TRUE(embedded_test_server()->Start());
// TODO(devlin): This is essentially copied from the webrequest_activetab
// API test extension, but has different permissions. Maybe it's worth having
// all tests use a common pattern?
TestExtensionDir test_dir;
test_dir.WriteManifest(
R"({
"name": "Web Request Withheld Hosts",
"manifest_version": 2,
"version": "0.1",
"background": { "scripts": ["background.js"], "persistent": true },
"permissions": ["*://b.com:*/*", "webRequest"]
})");
test_dir.WriteFile(FILE_PATH_LITERAL("background.js"),
R"(self.webRequestCount = 0;
self.requestedHostnames = [];
chrome.webRequest.onBeforeRequest.addListener(function(details) {
++self.webRequestCount;
self.requestedHostnames.push((new URL(details.url)).hostname);
}, {urls:['<all_urls>']});
chrome.test.sendMessage('ready');)");
// Load an extension that registers a listener for webRequest events, and
// wait until it's initialized.
ExtensionTestMessageListener listener("ready");
const Extension* extension = LoadExtension(test_dir.UnpackedPath());
ASSERT_TRUE(extension) << message_;
ScriptingPermissionsModifier(profile(), base::WrapRefCounted(extension))
.SetWithholdHostPermissions(true);
EXPECT_TRUE(listener.WaitUntilSatisfied());
// Navigate to example.com, which has a cross-site script to b.com.
ASSERT_TRUE(ui_test_utils::NavigateToURL(
browser(), embedded_test_server()->GetURL(
"example.com", "/extensions/cross_site_script.html")));
content::WebContents* web_contents =
browser()->tab_strip_model()->GetActiveWebContents();
ExtensionActionRunner* runner =
ExtensionActionRunner::GetForWebContents(web_contents);
ASSERT_TRUE(runner);
// Even though the extension has access to b.com, it shouldn't show that it
// wants to run, because example.com is not a requested host.
EXPECT_EQ(BLOCKED_ACTION_NONE, runner->GetBlockedActions(extension->id()));
EXPECT_FALSE(
HasSeenWebRequestInBackgroundScript(extension, profile(), "b.com"));
// Navigating to b.com (so that the script is hosted on the same origin as
// the WebContents) should show the extension wants to run.
ASSERT_TRUE(ui_test_utils::NavigateToURL(
browser(), embedded_test_server()->GetURL(
"b.com", "/extensions/cross_site_script.html")));
EXPECT_EQ(BLOCKED_ACTION_WEB_REQUEST,
runner->GetBlockedActions(extension->id()));
}
#endif // !BUILDFLAG(IS_ANDROID)
// Verify that requests to clientsX.google.com are protected properly.
// First test requests from a standard renderer and then a request from the
// browser process.
IN_PROC_BROWSER_TEST_P(ExtensionWebRequestApiTestWithContextTypeMV3,
WebRequestClientsGoogleComProtection) {
ASSERT_TRUE(embedded_test_server()->Start());
// Load an extension that registers a listener for webRequest events, and
// wait until it's initialized.
ExtensionTestMessageListener listener("ready");
const Extension* extension = LoadExtension(
test_data_dir_.AppendASCII("webrequest_clients_google_com"));
ASSERT_TRUE(extension) << message_;
EXPECT_TRUE(listener.WaitUntilSatisfied());
auto get_clients_google_request_count = [this, extension]() {
return GetCountFromBackgroundScript(extension, profile(),
"self.clientsGoogleWebRequestCount");
};
auto get_yahoo_request_count = [this, extension]() {
return GetCountFromBackgroundScript(extension, profile(),
"self.yahooWebRequestCount");
};
EXPECT_EQ(0, get_clients_google_request_count());
EXPECT_EQ(0, get_yahoo_request_count());
auto* web_contents = GetActiveWebContents();
GURL main_frame_url =
embedded_test_server()->GetURL("www.example.com", "/simple.html");
EXPECT_TRUE(NavigateToURL(main_frame_url));
content::WaitForLoadStop(web_contents);
EXPECT_EQ(0, get_clients_google_request_count());
EXPECT_EQ(0, get_yahoo_request_count());
// Attempt to issue a request to clients1.google.com from the renderer. This
// will fail, but should still be visible to the WebRequest API.
const char kRequest[] = R"(
var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://clients1.google.com');
new Promise(resolve => {
xhr.onload = () => {resolve(true);};
xhr.onerror = () => {resolve(false);};
xhr.send();
});
)";
EXPECT_EQ(false, EvalJs(web_contents->GetPrimaryMainFrame(), kRequest));
// Requests always fail due to cross origin nature.
EXPECT_EQ(1, get_clients_google_request_count());
EXPECT_EQ(0, get_yahoo_request_count());
auto make_browser_request = [this](const GURL& url) {
auto request = std::make_unique<network::ResourceRequest>();
request->url = url;
request->credentials_mode = network::mojom::CredentialsMode::kOmit;
request->destination = network::mojom::RequestDestination::kEmpty;
request->resource_type =
static_cast<int>(blink::mojom::ResourceType::kSubResource);
auto* url_loader_factory = profile()
->GetDefaultStoragePartition()
->GetURLLoaderFactoryForBrowserProcess()
.get();
content::SimpleURLLoaderTestHelper loader_helper;
auto loader = network::SimpleURLLoader::Create(
std::move(request), TRAFFIC_ANNOTATION_FOR_TESTS);
loader->DownloadToStringOfUnboundedSizeUntilCrashAndDie(
url_loader_factory, loader_helper.GetCallbackDeprecated());
// Wait for the response to complete.
loader_helper.WaitForCallback();
EXPECT_TRUE(loader_helper.response_body());
EXPECT_EQ(200, loader->ResponseInfo()->headers->response_code());
};
// Now perform a request to "client1.google.com" from the browser process.
// This should *not* be visible to the WebRequest API. We should still have
// only seen the single render-initiated request from the first half of the
// test.
make_browser_request(
embedded_test_server()->GetURL("clients1.google.com", "/simple.html"));
EXPECT_EQ(1, get_clients_google_request_count());
// Other non-navigation browser requests should also be hidden from
// extensions.
make_browser_request(
embedded_test_server()->GetURL("yahoo.com", "/simple.html"));
EXPECT_EQ(0, get_yahoo_request_count());
}
// Verify that requests for PAC scripts are protected properly.
IN_PROC_BROWSER_TEST_P(ExtensionWebRequestApiTestWithContextTypeMV3,
WebRequestPacRequestProtection) {
ASSERT_TRUE(embedded_test_server()->Start());
// Load an extension that registers a listener for webRequest events, and
// wait until it's initialized.
ExtensionTestMessageListener listener("ready");
const Extension* extension =
LoadExtension(test_data_dir_.AppendASCII("webrequest_pac_request"));
ASSERT_TRUE(extension) << message_;
EXPECT_TRUE(listener.WaitUntilSatisfied());
// Configure a PAC script. Need to do this after the extension is loaded, so
// that the PAC isn't already loaded by the time the extension starts
// affecting requests.
PrefService* pref_service = profile()->GetPrefs();
pref_service->SetDict(proxy_config::prefs::kProxy,
ProxyConfigDictionary::CreatePacScript(
embedded_test_server()->GetURL("/self.pac").spec(),
true /* pac_mandatory */));
// Flush the proxy configuration change over the Mojo pipe to avoid any races.
ProfileNetworkContextServiceFactory::GetForContext(profile())
->FlushProxyConfigMonitorForTesting();
// Navigate to a page. The URL doesn't matter.
ASSERT_TRUE(NavigateToURL(GURL("http://does.not.resolve.test/title2.html")));
// The extension should not have seen the PAC request.
EXPECT_EQ(0, GetCountFromBackgroundScript(extension, profile(),
"self.pacRequestCount"));
// The extension should have seen the request for the main frame.
EXPECT_EQ(1, GetCountFromBackgroundScript(extension, profile(),
"self.title2RequestCount"));
// The PAC request should have succeeded, as should the subsequent URL
// request.
EXPECT_EQ(content::PAGE_TYPE_NORMAL, GetActiveWebContents()
->GetController()
.GetLastCommittedEntry()
->GetPageType());
}
// Checks that the Dice response header is protected for Gaia URLs, but not
// other URLs.
IN_PROC_BROWSER_TEST_P(ExtensionWebRequestApiTestWithContextType,
WebRequestDiceHeaderProtection) {
// Load an extension that registers a listener for webRequest events, and
// wait until it is initialized.
ExtensionTestMessageListener listener("ready");
const Extension* extension =
LoadExtension(test_data_dir_.AppendASCII("webrequest_dice_header"));
ASSERT_TRUE(extension) << message_;
EXPECT_TRUE(listener.WaitUntilSatisfied());
ASSERT_TRUE(embedded_test_server()->Start());
// Setup a web contents observer to inspect the response headers after the
// extension was run.
class TestWebContentsObserver : public content::WebContentsObserver {
public:
explicit TestWebContentsObserver(content::WebContents* contents)
: WebContentsObserver(contents) {}
void DidFinishNavigation(
content::NavigationHandle* navigation_handle) override {
// Check that the extension cannot add a Dice header.
const net::HttpResponseHeaders* headers =
navigation_handle->GetResponseHeaders();
std::optional<std::string> dice_header_value =
headers->GetNormalizedHeader("X-Chrome-ID-Consistency-Response");
EXPECT_TRUE(dice_header_value);
dice_header_value_ = dice_header_value.value_or(std::string());
std::optional<std::string> new_header_value =
headers->GetNormalizedHeader("X-New-Header");
EXPECT_TRUE(new_header_value);
new_header_value_ = new_header_value.value_or(std::string());
std::optional<std::string> control_header_value =
headers->GetNormalizedHeader("X-Control");
EXPECT_TRUE(control_header_value);
control_header_value_ = control_header_value.value_or(std::string());
did_finish_navigation_called_ = true;
}
bool did_finish_navigation_called() const {
return did_finish_navigation_called_;
}
const std::string& dice_header_value() const { return dice_header_value_; }
const std::string& new_header_value() const { return new_header_value_; }
const std::string& control_header_value() const {
return control_header_value_;
}
void Clear() {
did_finish_navigation_called_ = false;
dice_header_value_.clear();
new_header_value_.clear();
control_header_value_.clear();
}
private:
bool did_finish_navigation_called_ = false;
std::string dice_header_value_;
std::string new_header_value_;
std::string control_header_value_;
};
TestWebContentsObserver test_webcontents_observer(GetActiveWebContents());
// Navigate to the Gaia URL intercepted by the extension.
GURL url =
embedded_test_server()->GetURL("gaia.com", "/extensions/dice.html");
ASSERT_TRUE(NavigateToURL(url));
// Check that the Dice header was not changed by the extension.
EXPECT_TRUE(test_webcontents_observer.did_finish_navigation_called());
EXPECT_EQ(kHeaderValueFromServer,
test_webcontents_observer.dice_header_value());
EXPECT_EQ(kHeaderValueFromExtension,
test_webcontents_observer.new_header_value());
EXPECT_EQ(kHeaderValueFromExtension,
test_webcontents_observer.control_header_value());
// Check that the Dice header cannot be read by the extension.
EXPECT_EQ(0, GetCountFromBackgroundScript(extension, profile(),
"self.diceResponseHeaderCount"));
EXPECT_EQ(1, GetCountFromBackgroundScript(extension, profile(),
"self.controlResponseHeaderCount"));
// Navigate to a non-Gaia URL intercepted by the extension.
test_webcontents_observer.Clear();
url = embedded_test_server()->GetURL("example.com", "/extensions/dice.html");
ASSERT_TRUE(NavigateToURL(url));
// Check that the Dice header was changed by the extension.
EXPECT_TRUE(test_webcontents_observer.did_finish_navigation_called());
EXPECT_EQ(kHeaderValueFromExtension,
test_webcontents_observer.dice_header_value());
EXPECT_EQ(kHeaderValueFromExtension,
test_webcontents_observer.new_header_value());
EXPECT_EQ(kHeaderValueFromExtension,
test_webcontents_observer.control_header_value());
// Check that the Dice header can be read by the extension.
EXPECT_EQ(1, GetCountFromBackgroundScript(extension, profile(),
"self.diceResponseHeaderCount"));
EXPECT_EQ(2, GetCountFromBackgroundScript(extension, profile(),
"self.controlResponseHeaderCount"));
}
#if !BUILDFLAG(IS_ANDROID)
// Test that the webRequest events are dispatched for the WebSocket handshake
// requests.
// TODO(crbug.com/40715657): Test is flaky on multiple platforms.
IN_PROC_BROWSER_TEST_F(ExtensionWebRequestApiTest, DISABLED_WebSocketRequest) {
ASSERT_TRUE(StartEmbeddedTestServer());
ASSERT_TRUE(StartWebSocketServer(net::GetWebSocketTestDataDirectory()));
ASSERT_TRUE(
RunExtensionTest("webrequest", {.extension_url = "test_websocket.html"}))
<< message_;
}
// Test that the webRequest events are dispatched for the WebSocket handshake
// requests when authenrication is requested by server.
// TODO(crbug.com/40168662) Re-enable test
IN_PROC_BROWSER_TEST_F(ExtensionWebRequestApiTest,
DISABLED_WebSocketRequestAuthRequired) {
ASSERT_TRUE(StartEmbeddedTestServer());
ASSERT_TRUE(StartWebSocketServer(net::GetWebSocketTestDataDirectory(), true));
ASSERT_TRUE(RunExtensionTest("webrequest",
{.extension_url = "test_websocket_auth.html"}))
<< message_;
}
// Test that the webRequest events are dispatched for the WebSocket handshake
// requests.
IN_PROC_BROWSER_TEST_F(ExtensionWebRequestApiTest, WebSocketRequestOnWorker) {
ASSERT_TRUE(StartEmbeddedTestServer());
ASSERT_TRUE(StartWebSocketServer(net::GetWebSocketTestDataDirectory()));
ASSERT_TRUE(RunExtensionTest("webrequest",
{.extension_url = "test_websocket_worker.html"}))
<< message_;
}
// Tests that a clean close from the server is not reported as an error when
// there is a race between OnDropChannel and SendFrame.
// Regression test for https://crbug.com/937790.
//
// TODO(b:332825952): Flaky on linux-chromeos-dbg
#if BUILDFLAG(IS_CHROMEOS)
#define MAYBE_WebSocketCleanClose DISABLED_WebSocketCleanClose
#else
#define MAYBE_WebSocketCleanClose WebSocketCleanClose
#endif
IN_PROC_BROWSER_TEST_F(ExtensionWebRequestApiTest, MAYBE_WebSocketCleanClose) {
ASSERT_TRUE(StartEmbeddedTestServer());
ASSERT_TRUE(StartWebSocketServer(net::GetWebSocketTestDataDirectory()));
ASSERT_TRUE(RunExtensionTest(
"webrequest", {.extension_url = "test_websocket_clean_close.html"}))
<< message_;
}
class ExtensionWebRequestApiWebTransportTest
: public ExtensionWebRequestApiTest {
public:
ExtensionWebRequestApiWebTransportTest() { server_.Start(); }
void SetUpCommandLine(base::CommandLine* command_line) override {
ExtensionWebRequestApiTest::SetUpCommandLine(command_line);
server_.SetUpCommandLine(command_line);
}
void SetUpOnMainThread() override {
ExtensionWebRequestApiTest::SetUpOnMainThread();
ASSERT_TRUE(StartEmbeddedTestServer());
GetTestConfig()->Set("testWebTransportPort",
server_.server_address().port());
}
protected:
bool RunTest(const char* page_url) {
return RunExtensionTest("webrequest", {.extension_url = page_url});
}
content::WebTransportSimpleTestServer server_;
};
// Test that the webRequest events are dispatched for the WebTransport
// handshake.
// TODO(crbug.com/326122304): Re-enable this test
IN_PROC_BROWSER_TEST_F(ExtensionWebRequestApiWebTransportTest, DISABLED_Main) {
ASSERT_TRUE(RunTest("test_webtransport.html")) << message_;
}
// Test that the webRequest events are dispatched for the WebTransport
// handshake in a dedicated worker.
IN_PROC_BROWSER_TEST_F(ExtensionWebRequestApiWebTransportTest,
DedicaterWorker) {
ASSERT_TRUE(RunTest("test_webtransport_dedicated_worker.html")) << message_;
}
// Test that the webRequest events are dispatched for the WebTransport
// handshake in a shared worker.
IN_PROC_BROWSER_TEST_F(ExtensionWebRequestApiWebTransportTest, SharedWorker) {
ASSERT_TRUE(RunTest("test_webtransport_shared_worker.html")) << message_;
}
// Test that the webRequest events are dispatched for the WebTransport
// handshake in a service worker.
IN_PROC_BROWSER_TEST_F(ExtensionWebRequestApiWebTransportTest, ServiceWorker) {
ASSERT_TRUE(RunTest("test_webtransport_service_worker.html")) << message_;
}
#endif // !BUILDFLAG(IS_ANDROID)
// Test behavior when intercepting requests from a browser-initiated url fetch.
IN_PROC_BROWSER_TEST_P(ExtensionWebRequestApiTestWithContextType,
WebRequestURLLoaderInterception) {
// Create an extension that intercepts (and blocks) requests to example.com.
TestExtensionDir test_dir;
test_dir.WriteManifest(
R"({
"name": "web_request_browser_interception",
"description": "tests that browser requests aren't intercepted",
"version": "0.1",
"permissions": ["webRequest", "webRequestBlocking", "*://*/*"],
"manifest_version": 2,
"background": { "scripts": ["background.js"], "persistent": true }
})");
test_dir.WriteFile(FILE_PATH_LITERAL("background.js"),
R"(chrome.webRequest.onBeforeRequest.addListener(
function(details) {
return {cancel: details.url.indexOf('example.com') != -1};
},
{urls: ["<all_urls>"]},
["blocking"]);
chrome.test.sendMessage('ready');)");
const Extension* extension = nullptr;
{
ExtensionTestMessageListener listener("ready");
extension = LoadExtension(test_dir.UnpackedPath());
ASSERT_TRUE(extension);
EXPECT_TRUE(listener.WaitUntilSatisfied());
}
// Taken from test/data/extensions/body1.html.
const char kGoogleBodyContent[] = "dog";
const char kGoogleFullContent[] = "<html>\n<body>dog</body>\n</html>\n";
// Taken from test/data/extensions/body2.html.
const char kExampleBodyContent[] = "cat";
const char kExampleFullContent[] = "<html>\n<body>cat</body>\n</html>\n";
embedded_test_server()->RegisterRequestHandler(base::BindLambdaForTesting(
[&](const net::test_server::HttpRequest& request)
-> std::unique_ptr<net::test_server::HttpResponse> {
std::unique_ptr<net::test_server::BasicHttpResponse> response(
new net::test_server::BasicHttpResponse);
if (request.relative_url == "/extensions/body1.html") {
response->set_code(net::HTTP_OK);
response->set_content(kGoogleFullContent);
return std::move(response);
} else if (request.relative_url == "/extensions/body2.html") {
response->set_code(net::HTTP_OK);
response->set_content(kExampleFullContent);
return std::move(response);
}
return nullptr;
}));
ASSERT_TRUE(StartEmbeddedTestServer());
GURL google_url =
embedded_test_server()->GetURL("google.com", "/extensions/body1.html");
// First, check normal requests (e.g., navigations) to verify the extension
// is working correctly.
auto* web_contents = GetActiveWebContents();
ASSERT_TRUE(NavigateToURL(google_url));
EXPECT_EQ(google_url, web_contents->GetLastCommittedURL());
// google.com should succeed.
EXPECT_EQ(kGoogleBodyContent,
content::EvalJs(GetActiveWebContents(),
"document.body.textContent.trim();"));
GURL example_url =
embedded_test_server()->GetURL("example.com", "/extensions/body2.html");
// Navigation to example.com should fail.
ASSERT_FALSE(NavigateToURL(example_url));
{
content::NavigationEntry* nav_entry =
web_contents->GetController().GetLastCommittedEntry();
ASSERT_TRUE(nav_entry);
EXPECT_EQ(content::PAGE_TYPE_ERROR, nav_entry->GetPageType());
EXPECT_NE(
kExampleBodyContent,
content::EvalJs(web_contents, "document.body.textContent.trim();"));
}
// A callback allow waiting for a response to complete with an expected status
// and given content.
auto make_browser_request =
[](network::mojom::URLLoaderFactory* url_loader_factory, const GURL& url,
const std::optional<std::string>& expected_response,
int expected_net_code) {
auto request = std::make_unique<network::ResourceRequest>();
request->url = url;
request->credentials_mode = network::mojom::CredentialsMode::kOmit;
content::SimpleURLLoaderTestHelper simple_loader_helper;
auto simple_loader = network::SimpleURLLoader::Create(
std::move(request), TRAFFIC_ANNOTATION_FOR_TESTS);
simple_loader->DownloadToStringOfUnboundedSizeUntilCrashAndDie(
url_loader_factory, simple_loader_helper.GetCallbackDeprecated());
simple_loader_helper.WaitForCallback();
if (expected_response.has_value()) {
EXPECT_TRUE(!!simple_loader_helper.response_body());
EXPECT_EQ(*simple_loader_helper.response_body(), *expected_response);
EXPECT_EQ(200,
simple_loader->ResponseInfo()->headers->response_code());
} else {
EXPECT_FALSE(!!simple_loader_helper.response_body());
EXPECT_EQ(simple_loader->NetError(), expected_net_code);
}
};
// Next, try a series of requests through URLRequestFetchers (rather than a
// renderer).
auto* url_loader_factory = profile()
->GetDefaultStoragePartition()
->GetURLLoaderFactoryForBrowserProcess()
.get();
{
// google.com should be unaffected by the extension and should succeed.
SCOPED_TRACE("google.com with Profile's url loader");
make_browser_request(url_loader_factory, google_url, kGoogleFullContent,
net::OK);
}
{
// example.com should also succeed since non-navigation browser-initiated
// requests are hidden from extensions. See crbug.com/884932.
SCOPED_TRACE("example.com with Profile's url loader");
make_browser_request(url_loader_factory, example_url, kExampleFullContent,
net::OK);
}
// Requests going through the system network context manager should always
// succeed.
SystemNetworkContextManager* system_network_context_manager =
g_browser_process->system_network_context_manager();
network::mojom::URLLoaderFactory* system_url_loader_factory =
system_network_context_manager->GetURLLoaderFactory();
{
// google.com should succeed (again).
SCOPED_TRACE("google.com with System's network context manager");
make_browser_request(system_url_loader_factory, google_url,
kGoogleFullContent, net::OK);
}
{
// example.com should also succeed, since it's not through the profile's
// request context.
SCOPED_TRACE("example.com with System's network context manager");
make_browser_request(system_url_loader_factory, example_url,
kExampleFullContent, net::OK);
}
}
// Test that extensions need host permissions to both the request url and
// initiator to intercept a request.
IN_PROC_BROWSER_TEST_P(ExtensionWebRequestApiTestWithContextTypeMV3,
InitiatorAccessRequired) {
ASSERT_TRUE(StartEmbeddedTestServer());
ExtensionTestMessageListener listener("ready");
const Extension* extension = LoadExtension(
test_data_dir_.AppendASCII("webrequest_permissions/initiator"));
ASSERT_TRUE(extension) << message_;
EXPECT_TRUE(listener.WaitUntilSatisfied());
content::WebContents* web_contents = GetActiveWebContents();
ASSERT_TRUE(web_contents);
struct TestCase {
std::string navigate_before_start;
std::string xhr_domain;
std::string expected_initiator;
} testcases[] = {{"example.com", "example.com", "example.com"},
{"example2.com", "example3.com", "example2.com"},
// No access to the initiator.
{"no-permission.com", "example4.com", ""},
// No access to the request url.
{"example.com", "no-permission.com", ""}};
int port = embedded_test_server()->port();
int expected_requests_intercepted_count = 0;
for (const auto& testcase : testcases) {
SCOPED_TRACE(testcase.navigate_before_start + ":" + testcase.xhr_domain +
":" + testcase.expected_initiator);
ExtensionTestMessageListener initiator_listener;
initiator_listener.set_extension_id(extension->id());
ASSERT_TRUE(NavigateToURL(embedded_test_server()->GetURL(
testcase.navigate_before_start, "/extensions/body1.html")));
content::WaitForLoadStop(web_contents);
PerformXhrInFrame(web_contents->GetPrimaryMainFrame(), testcase.xhr_domain,
port, "extensions/api_test/webrequest/xhr/data.json");
// Ensure that the extension wasn't able to intercept the request if it
// didn't have permission to the initiator or the request url.
if (!testcase.expected_initiator.empty()) {
++expected_requests_intercepted_count;
}
// Run a script in the extensions background page to ensure that we have
// received the initiator message from the extension.
ASSERT_EQ(expected_requests_intercepted_count,
GetCountFromBackgroundScript(extension, profile(),
"self.requestsIntercepted"));
if (testcase.expected_initiator.empty()) {
EXPECT_FALSE(initiator_listener.was_satisfied());
} else {
ASSERT_TRUE(initiator_listener.was_satisfied());
EXPECT_EQ("http://" + testcase.expected_initiator + ":" +
base::NumberToString(port),
initiator_listener.message());
}
}
}
// TODO(crbug.com/409180663): test is failing on MSan, UBSan and ASan
#if defined(MEMORY_SANITIZER) || defined(UNDEFINED_SANITIZER) || \
defined(ADDRESS_SANITIZER)
#define MAYBE_WebRequestApiDoesNotCrashOnErrorAfterProfileDestroyed \
DISABLED_WebRequestApiDoesNotCrashOnErrorAfterProfileDestroyed
#else
#define MAYBE_WebRequestApiDoesNotCrashOnErrorAfterProfileDestroyed \
WebRequestApiDoesNotCrashOnErrorAfterProfileDestroyed
#endif // defined(MEMORY_SANITIZER) || defined(UNDEFINED_SANITIZER) ||
// defined(ADDRESS_SANITIZER)
#if !BUILDFLAG(IS_ANDROID)
// Regression test for http://crbug.com/878366.
// TODO(crbug.com/371324825): Port to desktop Android. The test crashes during
// Profile creation because Android requires a "startup data profile key".
IN_PROC_BROWSER_TEST_F(
ExtensionWebRequestApiTest,
MAYBE_WebRequestApiDoesNotCrashOnErrorAfterProfileDestroyed) {
ASSERT_TRUE(StartEmbeddedTestServer());
// Create a profile that will be destroyed later.
base::ScopedAllowBlockingForTesting allow_blocking;
#if BUILDFLAG(IS_CHROMEOS)
ash::ProfileHelper::SetAlwaysReturnPrimaryUserForTesting(true);
#endif // BUILDFLAG(IS_CHROMEOS)
ProfileManager* profile_manager = g_browser_process->profile_manager();
std::unique_ptr<Profile> temp_profile = Profile::CreateProfile(
profile_manager->user_data_dir().AppendASCII("profile"), nullptr,
Profile::CreateMode::kSynchronous);
// Create a WebRequestAPI instance that we can control the lifetime of.
auto api = std::make_unique<WebRequestAPI>(temp_profile.get());
// Make sure we are proxying for |temp_profile|.
api->ForceProxyForTesting();
temp_profile->GetDefaultStoragePartition()->FlushNetworkInterfaceForTesting();
network::URLLoaderFactoryBuilder factory_builder;
auto temp_web_contents =
WebContents::Create(WebContents::CreateParams(temp_profile.get()));
content::RenderFrameHost* frame = temp_web_contents->GetPrimaryMainFrame();
EXPECT_TRUE(api->MaybeProxyURLLoaderFactory(
frame->GetProcess()->GetBrowserContext(), frame,
frame->GetProcess()->GetDeprecatedID(),
content::ContentBrowserClient::URLLoaderFactoryType::kDocumentSubResource,
std::nullopt, ukm::kInvalidSourceIdObj, factory_builder, nullptr,
nullptr));
temp_web_contents.reset();
auto params = network::mojom::URLLoaderFactoryParams::New();
params->process_id = 0;
mojo::Remote<network::mojom::URLLoaderFactory> factory(
std::move(factory_builder)
.Finish<mojo::PendingRemote<network::mojom::URLLoaderFactory>>(
temp_profile->GetDefaultStoragePartition()->GetNetworkContext(),
std::move(params)));
network::TestURLLoaderClient client;
mojo::PendingRemote<network::mojom::URLLoader> loader;
network::ResourceRequest resource_request;
resource_request.url = embedded_test_server()->GetURL("/hung");
factory->CreateLoaderAndStart(
loader.InitWithNewPipeAndPassReceiver(), 0,
network::mojom::kURLLoadOptionNone, resource_request,
client.CreateRemote(),
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS));
// Destroy profile, unbind client to cause a connection error, and delete the
// WebRequestAPI. This will cause the connection error that will reach the
// proxy before the ProxySet shutdown code runs on the IO thread.
api->Shutdown();
// We are about to destroy a profile. In production that will only happen
// as part of the destruction of BrowserProcess's ProfileManager. This
// happens in PostMainMessageLoopRun(). This means that to have this test
// represent production we have to make sure that no tasks are pending on the
// main thread before we destroy the profile. We also would need to prohibit
// the posting of new tasks on the main thread as in production the main
// thread's message loop will not be accepting them. We fallback on flushing
// the ThreadPool here to avoid the posts coming from it.
content::RunAllTasksUntilIdle();
ProfileDestroyer::DestroyOriginalProfileWhenAppropriate(
std::move(temp_profile));
client.Unbind();
api.reset();
}
#endif // !BUILDFLAG(IS_ANDROID)
// Tests that webRequest API can inspect window.open() requests initiated from
// chrome-untrusted:// pages to Web origins, but not other WebUI origins.
IN_PROC_BROWSER_TEST_F(ExtensionWebRequestApiTest,
OpenNewTabFromChromeUntrusted) {
ASSERT_TRUE(StartEmbeddedTestServer());
content::WebUIConfigMap::GetInstance().AddUntrustedWebUIConfig(
std::make_unique<ui::TestUntrustedWebUIConfig>("test"));
content::WebUIConfigMap::GetInstance().AddUntrustedWebUIConfig(
std::make_unique<ui::TestUntrustedWebUIConfig>("test2"));
// Loads a test extension.
ExtensionTestMessageListener listener("ready");
const Extension* extension =
LoadExtension(test_data_dir_.AppendASCII("webrequest_activetab"));
ASSERT_TRUE(extension) << message_;
EXPECT_TRUE(listener.WaitUntilSatisfied());
// Opens a chrome-untrusted:// page.
auto* web_contents = GetActiveWebContents();
ASSERT_TRUE(NavigateToURL(GURL("chrome-untrusted://test/title1.html")));
content::WaitForLoadStop(web_contents);
auto* rfh = web_contents->GetPrimaryMainFrame();
{
// Trigger a `window.open()` to a Web origin from chrome-untrusted:// page.
const GURL web_url =
embedded_test_server()->GetURL("example.com", "/simple.html");
content::TestNavigationObserver navigation_observer(web_url);
navigation_observer.StartWatchingNewWebContents();
ASSERT_TRUE(content::ExecJs(
rfh, content::JsReplace("window.open($1, '_blank');", web_url.spec())));
navigation_observer.Wait();
ASSERT_TRUE(navigation_observer.last_navigation_succeeded());
// The extension should see the request to the Web origin.
EXPECT_TRUE(HasSeenWebRequestInBackgroundScript(extension, profile(),
web_url.host()));
}
{
// Trigger a `window.open()` to a WebUI origin from chrome-untrusted://
// page.
const GURL webui_url = GURL("chrome-untrusted://test2/title2.html");
content::TestNavigationObserver navigation_observer(webui_url);
navigation_observer.StartWatchingNewWebContents();
ASSERT_TRUE(content::ExecJs(
rfh,
content::JsReplace("window.open($1, '_blank');", webui_url.spec())));
navigation_observer.Wait();
ASSERT_TRUE(navigation_observer.last_navigation_succeeded());
// The extension shouldn't see the request to the WebUI pages.
EXPECT_FALSE(HasSeenWebRequestInBackgroundScript(extension, profile(),
webui_url.host()));
}
}
// Tests that webRequest API can inspect a chrome-untrusted:// main frame
// navigating itself to Web origins.
IN_PROC_BROWSER_TEST_F(ExtensionWebRequestApiTest,
NavigateMainFrameToWebOriginFromChromeUntrusted) {
ASSERT_TRUE(StartEmbeddedTestServer());
content::WebUIConfigMap::GetInstance().AddUntrustedWebUIConfig(
std::make_unique<ui::TestUntrustedWebUIConfig>("test"));
// Loads a test extension.
ExtensionTestMessageListener listener("ready");
const Extension* extension =
LoadExtension(test_data_dir_.AppendASCII("webrequest_activetab"));
ASSERT_TRUE(extension) << message_;
EXPECT_TRUE(listener.WaitUntilSatisfied());
// Opens a chrome-untrusted:// page.
auto* web_contents = GetActiveWebContents();
ASSERT_TRUE(NavigateToURL(GURL("chrome-untrusted://test/title1.html")));
content::WaitForLoadStop(web_contents);
auto* rfh = web_contents->GetPrimaryMainFrame();
// Navigate the main frame itself to Web origin, this extension should see
// the request.
const auto web_url =
embedded_test_server()->GetURL("example.com", "/simple.html");
content::TestNavigationObserver navigation_observer(web_url);
navigation_observer.WatchExistingWebContents();
ASSERT_TRUE(content::ExecJs(
rfh, content::JsReplace("location.href=$1;", web_url.spec())));
navigation_observer.Wait();
ASSERT_TRUE(navigation_observer.last_navigation_succeeded());
EXPECT_TRUE(HasSeenWebRequestInBackgroundScript(extension, profile(),
web_url.host()));
}
// Tests that webRequest API can't inspect a chrome-untrusted:// main frame
// navigating itself to another WebUI origin.
IN_PROC_BROWSER_TEST_F(ExtensionWebRequestApiTest,
NavigateMainFrameToWebUIOriginFromChromeUntrusted) {
ASSERT_TRUE(StartEmbeddedTestServer());
content::WebUIConfigMap::GetInstance().AddUntrustedWebUIConfig(
std::make_unique<ui::TestUntrustedWebUIConfig>("test"));
content::WebUIConfigMap::GetInstance().AddUntrustedWebUIConfig(
std::make_unique<ui::TestUntrustedWebUIConfig>("test2"));
// Loads a test extension.
ExtensionTestMessageListener listener("ready");
const Extension* extension =
LoadExtension(test_data_dir_.AppendASCII("webrequest_activetab"));
ASSERT_TRUE(extension) << message_;
EXPECT_TRUE(listener.WaitUntilSatisfied());
// Opens a chrome-untrusted:// page.
auto* web_contents = GetActiveWebContents();
ASSERT_TRUE(NavigateToURL(GURL("chrome-untrusted://test/title1.html")));
content::WaitForLoadStop(web_contents);
auto* rfh = web_contents->GetPrimaryMainFrame();
// Navigate the main frame itself to Web origin, this extension should see
// the request.
const auto webui_url = GURL("chrome-untrusted://test2/title2.html");
content::TestNavigationObserver navigation_observer(webui_url);
navigation_observer.WatchExistingWebContents();
ASSERT_TRUE(content::ExecJs(
rfh, content::JsReplace("location.href=$1;", webui_url.spec())));
navigation_observer.Wait();
ASSERT_TRUE(navigation_observer.last_navigation_succeeded());
EXPECT_FALSE(HasSeenWebRequestInBackgroundScript(extension, profile(),
webui_url.host()));
}
// Tests that webRequest API can't inspect a subframe inside chrome-untrusted://
// navigating to a Web origin.
IN_PROC_BROWSER_TEST_F(ExtensionWebRequestApiTest,
SubframeNavigationsInChromeUntrustedPage) {
ASSERT_TRUE(StartEmbeddedTestServer());
// Allow embedding child frames;
content::TestUntrustedDataSourceHeaders headers;
headers.child_src = "child-src *;";
content::WebUIConfigMap::GetInstance().AddUntrustedWebUIConfig(
std::make_unique<ui::TestUntrustedWebUIConfig>("test", headers));
// Loads a test extension.
ExtensionTestMessageListener listener("ready");
const Extension* extension =
LoadExtension(test_data_dir_.AppendASCII("webrequest_activetab"));
ASSERT_TRUE(extension) << message_;
EXPECT_TRUE(listener.WaitUntilSatisfied());
// Opens a chrome-untrusted:// page.
auto* web_contents = GetActiveWebContents();
ASSERT_TRUE(NavigateToURL(GURL("chrome-untrusted://test/title1.html")));
content::WaitForLoadStop(web_contents);
auto* rfh = web_contents->GetPrimaryMainFrame();
// Start a subframe navigation to Web origin.
const auto web_url =
embedded_test_server()->GetURL("example.com", "/simple.html");
content::TestNavigationObserver navigation_observer(web_url);
navigation_observer.WatchExistingWebContents();
ASSERT_TRUE(content::ExecJs(rfh, content::JsReplace(R"javascript(
const el = document.createElement("iframe");
document.body.appendChild(el);
el.src = $1;
)javascript",
web_url.spec())));
navigation_observer.Wait();
ASSERT_TRUE(navigation_observer.last_navigation_succeeded());
EXPECT_FALSE(HasSeenWebRequestInBackgroundScript(extension, profile(),
web_url.host()));
}
#if !BUILDFLAG(IS_ANDROID)
// Test fixture which sets a custom NTP Page.
// Not ported to desktop Android because the Android NTP is native UI.
class NTPInterceptionWebRequestAPITest
: public ExtensionApiTest,
public testing::WithParamInterface<ContextType> {
public:
NTPInterceptionWebRequestAPITest()
: ExtensionApiTest(GetParam()),
https_test_server_(net::EmbeddedTestServer::TYPE_HTTPS) {}
NTPInterceptionWebRequestAPITest(const NTPInterceptionWebRequestAPITest&) =
delete;
NTPInterceptionWebRequestAPITest& operator=(
const NTPInterceptionWebRequestAPITest&) = delete;
~NTPInterceptionWebRequestAPITest() override = default;
// ExtensionApiTest override:
void SetUpOnMainThread() override {
ExtensionApiTest::SetUpOnMainThread();
test_data_dir_ = test_data_dir_.AppendASCII("webrequest")
.AppendASCII("ntp_request_interception");
https_test_server_.ServeFilesFromDirectory(test_data_dir_);
ASSERT_TRUE(https_test_server_.Start());
GURL ntp_url = https_test_server_.GetURL("/fake_ntp.html");
ntp_test_utils::SetUserSelectedDefaultSearchProvider(
profile(), https_test_server_.base_url().spec(), ntp_url.spec());
}
const net::EmbeddedTestServer* https_test_server() const {
return &https_test_server_;
}
private:
net::EmbeddedTestServer https_test_server_;
};
INSTANTIATE_TEST_SUITE_P(PersistentBackground,
NTPInterceptionWebRequestAPITest,
::testing::Values(ContextType::kPersistentBackground));
INSTANTIATE_TEST_SUITE_P(ServiceWorker,
NTPInterceptionWebRequestAPITest,
::testing::Values(ContextType::kServiceWorker));
// Ensures that requests made by the NTP Instant renderer are hidden from the
// Web Request API. Regression test for crbug.com/797461.
IN_PROC_BROWSER_TEST_P(NTPInterceptionWebRequestAPITest,
NTPRendererRequestsHidden) {
// Loads an extension which tries to intercept requests to
// "fake_ntp_script.js", which will be loaded as part of the NTP renderer.
ExtensionTestMessageListener listener("ready", ReplyBehavior::kWillReply);
const Extension* extension =
LoadExtension(test_data_dir_.AppendASCII("extension"));
ASSERT_TRUE(extension);
EXPECT_TRUE(listener.WaitUntilSatisfied());
// Wait for webRequest listeners to be set up.
profile()->GetDefaultStoragePartition()->FlushNetworkInterfaceForTesting();
// Have the extension listen for requests to |fake_ntp_script.js|.
listener.Reply(https_test_server()->GetURL("/fake_ntp_script.js").spec());
// Returns true if the given extension was able to intercept the request to
// "fake_ntp_script.js".
auto was_script_request_intercepted =
[this](const ExtensionId& extension_id) {
const std::optional<bool> result = ExecuteScriptAndReturnBool(
extension_id, profile(), "getAndResetRequestIntercepted();");
DCHECK(result);
return *result;
};
// Returns true if the given |web_contents| has window.scriptExecuted set to
// true;
auto was_ntp_script_loaded = [](content::WebContents* web_contents) {
return content::EvalJs(web_contents, "!!window.scriptExecuted;")
.ExtractBool();
};
WebContents* web_contents =
browser()->tab_strip_model()->GetActiveWebContents();
// Navigate to the NTP. The request for "fake_ntp_script.js" should not have
// reached the extension, since it was made by the instant NTP renderer, which
// is semi-privileged.
ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(),
GURL(chrome::kChromeUINewTabURL)));
EXPECT_TRUE(was_ntp_script_loaded(web_contents));
ASSERT_TRUE(search::IsInstantNTP(web_contents));
EXPECT_FALSE(was_script_request_intercepted(extension->id()));
// However, when a normal webpage requests the same script, the request should
// be seen by the extension.
ASSERT_TRUE(ui_test_utils::NavigateToURL(
browser(), https_test_server()->GetURL("/page_with_ntp_script.html")));
EXPECT_TRUE(was_ntp_script_loaded(web_contents));
ASSERT_FALSE(search::IsInstantNTP(web_contents));
EXPECT_TRUE(was_script_request_intercepted(extension->id()));
}
// Test fixture testing that requests made for the OneGoogleBar on behalf of
// the WebUI NTP can't be intercepted by extensions.
class WebUiNtpInterceptionWebRequestAPITest
: public ExtensionApiTest,
public OneGoogleBarServiceObserver,
public testing::WithParamInterface<ContextType> {
public:
WebUiNtpInterceptionWebRequestAPITest()
: ExtensionApiTest(GetParam()),
https_test_server_(net::EmbeddedTestServer::TYPE_HTTPS) {}
WebUiNtpInterceptionWebRequestAPITest(
const WebUiNtpInterceptionWebRequestAPITest&) = delete;
WebUiNtpInterceptionWebRequestAPITest& operator=(
const WebUiNtpInterceptionWebRequestAPITest&) = delete;
~WebUiNtpInterceptionWebRequestAPITest() override = default;
// ExtensionApiTest override:
void SetUp() override {
https_test_server_.RegisterRequestMonitor(base::BindRepeating(
&WebUiNtpInterceptionWebRequestAPITest::MonitorRequest,
base::Unretained(this)));
ASSERT_TRUE(https_test_server_.InitializeAndListen());
ExtensionApiTest::SetUp();
}
void SetUpCommandLine(base::CommandLine* command_line) override {
ExtensionApiTest::SetUpCommandLine(command_line);
command_line->AppendSwitchASCII(switches::kGoogleBaseURL,
https_test_server_.base_url().spec());
}
void SetUpOnMainThread() override {
ExtensionApiTest::SetUpOnMainThread();
https_test_server_.StartAcceptingConnections();
one_google_bar_url_ =
one_google_bar_service()->loader_for_testing()->GetLoadURLForTesting();
// Can't declare |runloop_| as a data member on the stack since it needs to
// be be constructed from a single-threaded context.
runloop_ = std::make_unique<base::RunLoop>();
one_google_bar_service()->AddObserver(this);
}
// OneGoogleBarServiceObserver overrides:
void OnOneGoogleBarDataUpdated() override { runloop_->Quit(); }
void OnOneGoogleBarServiceShuttingDown() override {
one_google_bar_service()->RemoveObserver(this);
}
GURL one_google_bar_url() const { return one_google_bar_url_; }
// Waits for OneGoogleBar data to be updated. Should only be used once.
void WaitForOneGoogleBarDataUpdate() { runloop_->Run(); }
bool GetAndResetOneGoogleBarRequestSeen() {
base::AutoLock lock(lock_);
bool result = one_google_bar_request_seen_;
one_google_bar_request_seen_ = false;
return result;
}
private:
OneGoogleBarService* one_google_bar_service() {
return OneGoogleBarServiceFactory::GetForProfile(profile());
}
void MonitorRequest(const net::test_server::HttpRequest& request) {
if (request.GetURL() == one_google_bar_url_) {
base::AutoLock lock(lock_);
one_google_bar_request_seen_ = true;
}
}
net::EmbeddedTestServer https_test_server_;
std::unique_ptr<base::RunLoop> runloop_;
// Initialized on the UI thread in SetUpOnMainThread. Read on UI and Embedded
// Test Server IO thread thereafter.
GURL one_google_bar_url_;
// Accessed on multiple threads- UI and Embedded Test Server IO thread. Access
// requires acquiring |lock_|.
bool one_google_bar_request_seen_ = false;
base::Lock lock_;
};
INSTANTIATE_TEST_SUITE_P(PersistentBackground,
WebUiNtpInterceptionWebRequestAPITest,
::testing::Values(ContextType::kPersistentBackground));
INSTANTIATE_TEST_SUITE_P(ServiceWorker,
WebUiNtpInterceptionWebRequestAPITest,
::testing::Values(ContextType::kServiceWorker));
// TODO(https://crbug.com/407399340): Failing on various bots;
// msan, asan, dbg, code coverage, chromeos-rel.
IN_PROC_BROWSER_TEST_P(WebUiNtpInterceptionWebRequestAPITest,
DISABLED_OneGoogleBarRequestsHidden) {
// Loads an extension which tries to intercept requests to the OneGoogleBar.
ExtensionTestMessageListener listener("ready", ReplyBehavior::kWillReply);
const Extension* extension =
LoadExtension(test_data_dir_.AppendASCII("webrequest")
.AppendASCII("ntp_request_interception")
.AppendASCII("extension"));
ASSERT_TRUE(extension);
EXPECT_TRUE(listener.WaitUntilSatisfied());
// Have the extension listen for requests to |one_google_bar_url()|.
listener.Reply(one_google_bar_url().spec());
// Returns true if the given extension was able to intercept the request to
// |one_google_bar_url()|.
auto was_script_request_intercepted =
[this](const ExtensionId& extension_id) {
std::optional<bool> result = ExecuteScriptAndReturnBool(
extension_id, profile(), "getAndResetRequestIntercepted();");
DCHECK(result);
return *result;
};
ASSERT_FALSE(GetAndResetOneGoogleBarRequestSeen());
ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(),
GURL(chrome::kChromeUINewTabURL)));
ASSERT_EQ(ntp_test_utils::GetFinalNtpUrl(browser()->profile()),
browser()
->tab_strip_model()
->GetActiveWebContents()
->GetLastCommittedURL());
WaitForOneGoogleBarDataUpdate();
ASSERT_TRUE(GetAndResetOneGoogleBarRequestSeen());
// Ensure that the extension wasn't able to intercept the request.
EXPECT_FALSE(was_script_request_intercepted(extension->id()));
// A normal request to |one_google_bar_url()| (i.e. not made by
// OneGoogleBarFetcher) should be intercepted by extensions.
ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), one_google_bar_url()));
EXPECT_TRUE(was_script_request_intercepted(extension->id()));
ASSERT_TRUE(GetAndResetOneGoogleBarRequestSeen());
}
// Ensure that devtools frontend requests are hidden from the webRequest API.
IN_PROC_BROWSER_TEST_F(DevToolsFrontendInWebRequestApiTest, HiddenRequests) {
ASSERT_TRUE(
RunExtensionTest("webrequest", {.extension_url = "test_devtools.html"}))
<< message_;
}
#endif // !BUILDFLAG(IS_ANDROID)
class WebRequestApiTestWithManagementPolicy
: public ExtensionApiTestWithManagementPolicy,
public testing::WithParamInterface<ContextType> {
public:
WebRequestApiTestWithManagementPolicy()
: ExtensionApiTestWithManagementPolicy(GetParam()) {}
~WebRequestApiTestWithManagementPolicy() override = default;
WebRequestApiTestWithManagementPolicy(
const WebRequestApiTestWithManagementPolicy&) = delete;
WebRequestApiTestWithManagementPolicy& operator=(
const WebRequestApiTestWithManagementPolicy&) = delete;
};
INSTANTIATE_TEST_SUITE_P(PersistentBackground,
WebRequestApiTestWithManagementPolicy,
::testing::Values(ContextType::kPersistentBackground));
INSTANTIATE_TEST_SUITE_P(ServiceWorker,
WebRequestApiTestWithManagementPolicy,
::testing::Values(ContextType::kServiceWorker));
// Tests that the webRequest events aren't dispatched when the request initiator
// is protected by policy.
IN_PROC_BROWSER_TEST_P(WebRequestApiTestWithManagementPolicy,
InitiatorProtectedByPolicy) {
// We expect that no request will be hidden or modification blocked. This
// means that the request to example.com will be seen by the extension.
{
ExtensionManagementPolicyUpdater pref(&policy_provider_);
pref.AddPolicyBlockedHost("*", "*://notexample.com");
}
ASSERT_TRUE(StartEmbeddedTestServer());
// Host navigated to.
const std::string example_com = "example.com";
// URL of a page that initiates a cross domain requests when navigated to.
const GURL extension_test_url = embedded_test_server()->GetURL(
example_com,
"/extensions/api_test/webrequest/policy_blocked/ref_remote_js.html");
ExtensionTestMessageListener listener("ready");
const Extension* extension =
LoadExtension(test_data_dir_.AppendASCII("webrequest/policy_blocked"));
ASSERT_TRUE(extension) << message_;
EXPECT_TRUE(listener.WaitUntilSatisfied());
// Extension communicates back using this listener name.
const std::string listener_message = "protected_origin";
// The number of requests initiated by a protected origin is tracked in
// the extension's background page under this variable name.
const std::string request_counter_name = "self.protectedOriginCount";
EXPECT_EQ(0, GetCountFromBackgroundScript(extension, profile(),
request_counter_name));
// Wait until all remote Javascript files have been blocked / pulled down.
ASSERT_TRUE(NavigateToURL(extension_test_url));
content::WaitForLoadStop(GetActiveWebContents());
// Domain that hosts javascript file referenced by example_com.
const std::string example2_com = "example2.com";
// The server saw a request for the remote Javascript file.
EXPECT_TRUE(BrowsedTo(example2_com));
// The request was seen by the extension.
EXPECT_EQ(1, GetCountFromBackgroundScript(extension, profile(),
request_counter_name));
// Clear the list of domains the server has seen.
ClearRequestLog();
// Make sure we've cleared the embedded server history.
EXPECT_FALSE(BrowsedTo(example2_com));
// Set the policy to hide requests to example.com or any resource
// it includes. We expect that in this test, the request to example2.com
// will not be seen by the extension.
{
ExtensionManagementPolicyUpdater pref(&policy_provider_);
pref.AddPolicyBlockedHost("*", "*://" + example_com);
}
// Wait until all remote Javascript files have been pulled down.
ASSERT_TRUE(NavigateToURL(extension_test_url));
content::WaitForLoadStop(GetActiveWebContents());
// The server saw a request for the remote Javascript file.
EXPECT_TRUE(BrowsedTo(example2_com));
// The request was hidden from the extension.
EXPECT_EQ(1, GetCountFromBackgroundScript(extension, profile(),
request_counter_name));
}
// Tests that the webRequest events aren't dispatched when the URL of the
// request is protected by policy.
IN_PROC_BROWSER_TEST_P(WebRequestApiTestWithManagementPolicy,
UrlProtectedByPolicy) {
// Host protected by policy.
const std::string protected_domain = "example.com";
{
ExtensionManagementPolicyUpdater pref(&policy_provider_);
pref.AddPolicyBlockedHost("*", "*://" + protected_domain);
}
ASSERT_TRUE(StartEmbeddedTestServer());
LoadExtension(test_data_dir_.AppendASCII("webrequest/policy_blocked"));
// Listen in case extension sees the request.
ExtensionTestMessageListener before_request_listener("protected_url");
// Path to resolve during test navigations.
const std::string test_path = "/defaultresponse?protected_url";
// Navigate to the protected domain and wait until page fully loads.
ASSERT_TRUE(NavigateToURL(
embedded_test_server()->GetURL(protected_domain, test_path)));
content::WaitForLoadStop(GetActiveWebContents());
// The server saw a request for the protected site.
EXPECT_TRUE(BrowsedTo(protected_domain));
// The request was hidden from the extension.
EXPECT_FALSE(before_request_listener.was_satisfied());
// Host not protected by policy.
const std::string unprotected_domain = "notblockedexample.com";
// Now we'll test browsing to a non-protected website where we expect the
// extension to see the request.
ASSERT_TRUE(NavigateToURL(
embedded_test_server()->GetURL(unprotected_domain, test_path)));
content::WaitForLoadStop(GetActiveWebContents());
// The server saw a request for the non-protected site.
EXPECT_TRUE(BrowsedTo(unprotected_domain));
// The request was visible from the extension.
EXPECT_TRUE(before_request_listener.was_satisfied());
}
// Test that no webRequest events are seen for a protected host during normal
// navigation. This replicates most of the tests from
// WebRequestWithWithheldPermissions with a protected host. Granting a tab
// specific permission shouldn't bypass our policy.
IN_PROC_BROWSER_TEST_P(WebRequestApiTestWithManagementPolicy,
WebRequestProtectedByPolicy) {
// Host protected by policy.
const std::string protected_domain = "example.com";
{
ExtensionManagementPolicyUpdater pref(&policy_provider_);
pref.AddPolicyBlockedHost("*", "*://" + protected_domain);
}
ASSERT_TRUE(StartEmbeddedTestServer());
ExtensionTestMessageListener listener("ready");
const Extension* extension =
LoadExtension(test_data_dir_.AppendASCII("webrequest_activetab"));
ASSERT_TRUE(extension) << message_;
ScriptingPermissionsModifier(profile(), base::WrapRefCounted(extension))
.SetWithholdHostPermissions(true);
EXPECT_TRUE(listener.WaitUntilSatisfied());
// Navigate the browser to a page in a new tab.
NavigateToURLInNewTab(
embedded_test_server()->GetURL(protected_domain, "/empty.html"));
content::WebContents* web_contents = GetActiveWebContents();
ASSERT_TRUE(web_contents);
ExtensionActionRunner* runner =
ExtensionActionRunner::GetForWebContents(web_contents);
ASSERT_TRUE(runner);
int port = embedded_test_server()->port();
const std::string kXhrPath = "simple.html";
// The extension shouldn't have currently received any webRequest events,
// since it doesn't have permission (and shouldn't receive any from an XHR).
EXPECT_EQ(0, GetWebRequestCountFromBackgroundScript(extension, profile()));
PerformXhrInFrame(web_contents->GetPrimaryMainFrame(), protected_domain, port,
kXhrPath);
EXPECT_EQ(0, GetWebRequestCountFromBackgroundScript(extension, profile()));
// Grant activeTab permission, and perform another XHR. The extension should
// still be blocked due to ExtensionSettings policy on example.com.
// Only records ACCESS_WITHHELD, not ACCESS_DENIED, this is why it matches
// BLOCKED_ACTION_NONE.
EXPECT_EQ(BLOCKED_ACTION_NONE, runner->GetBlockedActions(extension->id()));
runner->accept_bubble_for_testing(true);
runner->RunAction(extension, true);
base::RunLoop().RunUntilIdle();
EXPECT_TRUE(content::WaitForLoadStop(web_contents));
EXPECT_EQ(BLOCKED_ACTION_NONE, runner->GetBlockedActions(extension->id()));
int xhr_count = GetWebRequestCountFromBackgroundScript(extension, profile());
// ... which means that we should have a non-zero xhr count if the policy
// didn't block the events.
EXPECT_EQ(0, xhr_count);
// And the extension should also block future events.
PerformXhrInFrame(web_contents->GetPrimaryMainFrame(), protected_domain, port,
kXhrPath);
EXPECT_EQ(0, GetWebRequestCountFromBackgroundScript(extension, profile()));
}
#if !BUILDFLAG(IS_ANDROID)
// A test fixture which mocks the Time::Now() function to ensure that the
// default clock returns monotonically increasing time.
class ExtensionWebRequestMockedClockTest
: public ExtensionWebRequestApiTestWithContextType {
public:
ExtensionWebRequestMockedClockTest()
: scoped_time_clock_override_(&ExtensionWebRequestMockedClockTest::Now,
nullptr,
nullptr) {}
ExtensionWebRequestMockedClockTest(
const ExtensionWebRequestMockedClockTest&) = delete;
ExtensionWebRequestMockedClockTest& operator=(
const ExtensionWebRequestMockedClockTest&) = delete;
private:
static base::Time Now() {
static base::Time now_time = base::Time::UnixEpoch();
now_time += base::Milliseconds(1);
return now_time;
}
base::subtle::ScopedTimeClockOverrides scoped_time_clock_override_;
};
INSTANTIATE_TEST_SUITE_P(
PersistentBackground,
ExtensionWebRequestMockedClockTest,
::testing::Values(
std::make_pair(
ContextType::kPersistentBackground,
BackgroundResourceFetchTestCase::kBackgroundResourceFetchEnabled),
std::make_pair(
ContextType::kPersistentBackground,
BackgroundResourceFetchTestCase::kBackgroundResourceFetchDisabled)),
ExtensionWebRequestApiTestWithContextType::PrintToStringParamName());
// These tests use webRequestBlocking and/or declarativeWebRequest.
// See crbug.com/332512510.
INSTANTIATE_TEST_SUITE_P(
ServiceWorker,
ExtensionWebRequestMockedClockTest,
::testing::Values(
std::make_pair(
ContextType::kServiceWorkerMV2,
BackgroundResourceFetchTestCase::kBackgroundResourceFetchEnabled),
std::make_pair(
ContextType::kServiceWorkerMV2,
BackgroundResourceFetchTestCase::kBackgroundResourceFetchDisabled)),
ExtensionWebRequestApiTestWithContextType::PrintToStringParamName());
// Tests that we correctly dispatch the OnActionIgnored event on an extension
// if the extension's proposed redirect is ignored.
// TODO(crbug.com/391920604): Port to desktop Android when ReloadExtension()
// is supported.
IN_PROC_BROWSER_TEST_P(ExtensionWebRequestMockedClockTest,
OnActionIgnored_Redirect) {
ASSERT_TRUE(StartEmbeddedTestServer());
// Load the two extensions. They redirect "google.com" main-frame urls to
// the corresponding "example.com and "foo.com" urls.
base::FilePath test_dir =
test_data_dir_.AppendASCII("webrequest/on_action_ignored");
// Load the first extension.
ExtensionTestMessageListener ready_1_listener("ready_1");
const Extension* extension_1 =
LoadExtension(test_dir.AppendASCII("extension_1"));
ASSERT_TRUE(extension_1);
ASSERT_TRUE(ready_1_listener.WaitUntilSatisfied());
const ExtensionId extension_id_1 = extension_1->id();
// Load the second extension.
ExtensionTestMessageListener ready_2_listener("ready_2");
const Extension* extension_2 =
LoadExtension(test_dir.AppendASCII("extension_2"));
ASSERT_TRUE(extension_2);
ASSERT_TRUE(ready_2_listener.WaitUntilSatisfied());
const ExtensionId extension_id_2 = extension_2->id();
const ExtensionPrefs* prefs = ExtensionPrefs::Get(profile());
EXPECT_LT(GetLastUpdateTime(prefs, extension_id_1),
GetLastUpdateTime(prefs, extension_id_2));
// The extensions will notify the browser if their proposed redirect was
// successful or not.
ExtensionTestMessageListener redirect_ignored_listener("redirect_ignored");
ExtensionTestMessageListener redirect_successful_listener(
"redirect_successful");
const GURL url = embedded_test_server()->GetURL("google.com", "/simple.html");
const GURL expected_redirect_url_1 =
embedded_test_server()->GetURL("example.com", "/simple.html");
const GURL expected_redirect_url_2 =
embedded_test_server()->GetURL("foo.com", "/simple.html");
ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), url));
content::WebContents* web_contents =
browser()->tab_strip_model()->GetActiveWebContents();
ASSERT_TRUE(web_contents);
// The second extension is the latest installed, hence it's redirect url
// should take precedence.
EXPECT_EQ(expected_redirect_url_2, web_contents->GetLastCommittedURL());
EXPECT_TRUE(redirect_ignored_listener.WaitUntilSatisfied());
EXPECT_EQ(extension_id_1,
redirect_ignored_listener.extension_id_for_message());
EXPECT_TRUE(redirect_successful_listener.WaitUntilSatisfied());
EXPECT_EQ(extension_id_2,
redirect_successful_listener.extension_id_for_message());
// Now let |extension_1| be installed after |extension_2|. For an unpacked
// extension, reloading is equivalent to a reinstall.
ready_1_listener.Reset();
ReloadExtension(extension_id_1);
ASSERT_TRUE(ready_1_listener.WaitUntilSatisfied());
EXPECT_LT(GetLastUpdateTime(prefs, extension_id_2),
GetLastUpdateTime(prefs, extension_id_1));
redirect_ignored_listener.Reset();
redirect_successful_listener.Reset();
ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), url));
// The first extension is the latest installed, hence it's redirect url
// should take precedence.
EXPECT_EQ(expected_redirect_url_1, web_contents->GetLastCommittedURL());
EXPECT_TRUE(redirect_ignored_listener.WaitUntilSatisfied());
EXPECT_EQ(extension_id_2,
redirect_ignored_listener.extension_id_for_message());
EXPECT_TRUE(redirect_successful_listener.WaitUntilSatisfied());
EXPECT_EQ(extension_id_1,
redirect_successful_listener.extension_id_for_message());
}
#endif // !BUILDFLAG(IS_ANDROID)
// Regression test for http://crbug.com/1074282.
IN_PROC_BROWSER_TEST_P(ExtensionWebRequestApiTestWithContextType,
StaleHeadersAfterRedirect) {
TestExtensionDir test_dir;
test_dir.WriteManifest(R"({
"name": "Web Request Stale Headers Test",
"manifest_version": 2,
"version": "0.1",
"background": { "scripts": ["background.js"], "persistent": true },
"permissions": ["<all_urls>", "webRequest", "webRequestBlocking"]
})");
test_dir.WriteFile(FILE_PATH_LITERAL("background.js"), R"(
self.locationCount = 0;
self.requestCount = 0;
chrome.test.sendMessage('ready', function(reply) {
chrome.webRequest.onResponseStarted.addListener(function(details) {
self.requestCount++;
var headers = details.responseHeaders;
for (var i = 0; i < headers.length; i++) {
if (headers[i].name === 'Location') {
self.locationCount++;
}
}
},
{urls: ['<all_urls>'], types: ['xmlhttprequest']},
['responseHeaders', 'extraHeaders']
);
});
)");
ExtensionTestMessageListener listener("ready", ReplyBehavior::kWillReply);
const Extension* extension = LoadExtension(test_dir.UnpackedPath());
ASSERT_TRUE(extension);
EXPECT_TRUE(listener.WaitUntilSatisfied());
auto task_runner = base::SequencedTaskRunner::GetCurrentDefault();
embedded_test_server()->RegisterRequestHandler(base::BindLambdaForTesting(
[&](const net::test_server::HttpRequest& request)
-> std::unique_ptr<net::test_server::HttpResponse> {
if (request.relative_url != "/redirect-and-wait") {
return nullptr;
}
// Wait for the listener to be installed before proceeding.
base::WaitableEvent unblock(
base::WaitableEvent::ResetPolicy::AUTOMATIC,
base::WaitableEvent::InitialState::NOT_SIGNALED);
// Post a task to the UI thread since the request handler runs on a
// background thread.
task_runner->PostTask(FROM_HERE, base::BindLambdaForTesting([&] {
listener.Reply("");
WaitForExtraHeadersListener(&unblock,
profile());
}));
unblock.Wait();
auto http_response =
std::make_unique<net::test_server::BasicHttpResponse>();
http_response->set_code(net::HTTP_MOVED_PERMANENTLY);
http_response->AddCustomHeader(
"Location", embedded_test_server()->GetURL("/echo").spec());
return http_response;
}));
ASSERT_TRUE(embedded_test_server()->Start());
// Navigate to a basic page so XHR requests work.
auto* web_contents = GetActiveWebContents();
ASSERT_TRUE(NavigateToURL(embedded_test_server()->GetURL("/echo")));
content::WaitForLoadStop(web_contents);
// Make a XHR request which redirects. The final response should not include
// the Location header.
PerformXhrInFrame(web_contents->GetPrimaryMainFrame(),
embedded_test_server()->host_port_pair().host(),
embedded_test_server()->port(), "redirect-and-wait");
EXPECT_EQ(
GetCountFromBackgroundScript(extension, profile(), "self.requestCount"),
1);
EXPECT_EQ(
GetCountFromBackgroundScript(extension, profile(), "self.locationCount"),
0);
}
IN_PROC_BROWSER_TEST_P(ExtensionWebRequestApiTestWithContextType,
ChangeHeaderUMAs) {
using RequestHeaderType =
extension_web_request_api_helpers::RequestHeaderType;
using ResponseHeaderType =
extension_web_request_api_helpers::ResponseHeaderType;
ASSERT_TRUE(embedded_test_server()->Start());
TestExtensionDir test_dir;
test_dir.WriteManifest(R"({
"name": "Web Request UMA Test",
"manifest_version": 2,
"version": "0.1",
"background": { "scripts": ["background.js"], "persistent": true },
"permissions": ["<all_urls>", "webRequest", "webRequestBlocking"]
})");
test_dir.WriteFile(FILE_PATH_LITERAL("background.js"), R"(
chrome.webRequest.onBeforeSendHeaders.addListener(function(details) {
var headers = details.requestHeaders;
for (var i = 0; i < headers.length; i++) {
if (headers[i].name.toLowerCase() == 'user-agent') {
headers[i].value = 'foo';
break;
}
}
headers.push({name: 'Foo1', value: 'Bar1'});
headers.push({name: 'Foo2', value: 'Bar2'});
headers.push({name: 'DNT', value: '0'});
return {requestHeaders: headers};
}, {urls: ['*://*/set-cookie*']},
['blocking', 'requestHeaders', 'extraHeaders']);
chrome.webRequest.onHeadersReceived.addListener(function(details) {
var headers = details.responseHeaders;
for (var i = 0; i < headers.length; i++) {
if (headers[i].name.toLowerCase() == 'set-cookie' &&
headers[i].value == 'key1=val1') {
headers.splice(i, 1);
i--;
} else if (headers[i].name == 'Content-Length') {
headers[i].value = '0';
}
}
headers.push({name: 'Foo3', value: 'Bar3'});
headers.push({name: 'Foo4', value: 'Bar4'});
return {responseHeaders: headers};
}, {urls: ['*://*/set-cookie*']},
['blocking', 'responseHeaders', 'extraHeaders']);
chrome.test.sendMessage('ready');
)");
ExtensionTestMessageListener listener("ready");
ASSERT_TRUE(LoadExtension(test_dir.UnpackedPath()));
EXPECT_TRUE(listener.WaitUntilSatisfied());
base::HistogramTester tester;
ASSERT_TRUE(NavigateToURL(
embedded_test_server()->GetURL("/set-cookie?key1=val1&key2=val2")));
content::WaitForLoadStop(GetActiveWebContents());
// Changed histograms should record kUserAgent request header along with
// kSetCookie and kContentLength response headers.
tester.ExpectUniqueSample("Extensions.WebRequest.RequestHeaderChanged",
RequestHeaderType::kUserAgent, 1);
EXPECT_THAT(
tester.GetAllSamples("Extensions.WebRequest.ResponseHeaderChanged"),
::testing::UnorderedElementsAre(
base::Bucket(static_cast<base::HistogramBase::Sample32>(
ResponseHeaderType::kSetCookie),
1),
base::Bucket(static_cast<base::HistogramBase::Sample32>(
ResponseHeaderType::kContentLength),
1)));
// Added request header histogram should record kOther and kDNT.
EXPECT_THAT(tester.GetAllSamples("Extensions.WebRequest.RequestHeaderAdded"),
::testing::UnorderedElementsAre(
base::Bucket(static_cast<base::HistogramBase::Sample32>(
RequestHeaderType::kDnt),
1),
base::Bucket(static_cast<base::HistogramBase::Sample32>(
RequestHeaderType::kOther),
2)));
// Added response header histogram should record kOther.
tester.ExpectUniqueSample("Extensions.WebRequest.ResponseHeaderAdded",
ResponseHeaderType::kOther, 2);
// Histograms for removed headers should record kNone.
tester.ExpectUniqueSample("Extensions.WebRequest.RequestHeaderRemoved",
RequestHeaderType::kNone, 1);
tester.ExpectUniqueSample("Extensions.WebRequest.ResponseHeaderRemoved",
ResponseHeaderType::kNone, 1);
}
IN_PROC_BROWSER_TEST_P(ExtensionWebRequestApiTestWithContextType,
RemoveHeaderUMAs) {
using RequestHeaderType =
extension_web_request_api_helpers::RequestHeaderType;
using ResponseHeaderType =
extension_web_request_api_helpers::ResponseHeaderType;
ASSERT_TRUE(embedded_test_server()->Start());
TestExtensionDir test_dir;
test_dir.WriteManifest(R"({
"name": "Web Request UMA Test",
"manifest_version": 2,
"version": "0.1",
"background": { "scripts": ["background.js"], "persistent": true },
"permissions": ["<all_urls>", "webRequest", "webRequestBlocking"]
})");
test_dir.WriteFile(FILE_PATH_LITERAL("background.js"), R"(
chrome.webRequest.onBeforeSendHeaders.addListener(function(details) {
var headers = details.requestHeaders;
for (var i = 0; i < headers.length; i++) {
if (headers[i].name.toLowerCase() == 'user-agent') {
headers.splice(i, 1);
break;
}
}
return {requestHeaders: headers};
}, {urls: ['*://*/set-cookie*']},
['blocking', 'requestHeaders', 'extraHeaders']);
chrome.webRequest.onHeadersReceived.addListener(function(details) {
var headers = details.responseHeaders;
for (var i = 0; i < headers.length; i++) {
if (headers[i].name.toLowerCase() == 'set-cookie') {
headers.splice(i, 1);
break;
}
}
return {responseHeaders: headers};
}, {urls: ['*://*/set-cookie*']},
['blocking', 'responseHeaders', 'extraHeaders']);
chrome.test.sendMessage('ready');
)");
ExtensionTestMessageListener listener("ready");
ASSERT_TRUE(LoadExtension(test_dir.UnpackedPath()));
EXPECT_TRUE(listener.WaitUntilSatisfied());
base::HistogramTester tester;
ASSERT_TRUE(
NavigateToURL(embedded_test_server()->GetURL("/set-cookie?Foo=Bar")));
content::WaitForLoadStop(GetActiveWebContents());
// Histograms for removed headers should record kUserAgent and kSetCookie.
tester.ExpectUniqueSample("Extensions.WebRequest.RequestHeaderRemoved",
RequestHeaderType::kUserAgent, 1);
tester.ExpectUniqueSample("Extensions.WebRequest.ResponseHeaderRemoved",
ResponseHeaderType::kSetCookie, 1);
// Histograms for changed headers should record kNone.
tester.ExpectUniqueSample("Extensions.WebRequest.RequestHeaderChanged",
RequestHeaderType::kNone, 1);
tester.ExpectUniqueSample("Extensions.WebRequest.ResponseHeaderChanged",
ResponseHeaderType::kNone, 1);
// Histograms for added headers should record kNone.
tester.ExpectUniqueSample("Extensions.WebRequest.RequestHeaderAdded",
RequestHeaderType::kNone, 1);
tester.ExpectUniqueSample("Extensions.WebRequest.ResponseHeaderAdded",
ResponseHeaderType::kNone, 1);
}
struct SWTestParams {
// This parameter is for opt_extraInfoSpec passed to addEventListener.
// 'blocking' and 'requestHeaders' if it's false, and 'extraHeaders' in
// addition to them if it's true.
bool extra_info_spec;
ContextType context_type;
};
class ServiceWorkerWebRequestApiTest
: public testing::WithParamInterface<SWTestParams>,
public ExtensionApiTest {
public:
ServiceWorkerWebRequestApiTest()
: ExtensionApiTest(GetParam().context_type) {}
~ServiceWorkerWebRequestApiTest() override = default;
ServiceWorkerWebRequestApiTest(const ServiceWorkerWebRequestApiTest&) =
delete;
ServiceWorkerWebRequestApiTest& operator=(
const ServiceWorkerWebRequestApiTest&) = delete;
// The options passed as opt_extraInfoSpec to addEventListener.
enum class ExtraInfoSpec {
// 'blocking', 'requestHeaders'
kDefault,
// kDefault + 'extraHeaders'
kExtraHeaders
};
static ExtraInfoSpec GetExtraInfoSpec() {
return GetParam().extra_info_spec ? ExtraInfoSpec::kExtraHeaders
: ExtraInfoSpec::kDefault;
}
void InstallRequestHeaderModifyingExtension() {
TestExtensionDir test_dir;
test_dir.WriteManifest(R"({
"name": "Web Request Header Modifying Extension",
"manifest_version": 2,
"version": "0.1",
"background": { "scripts": ["background.js"], "persistent": true },
"permissions": ["<all_urls>", "webRequest", "webRequestBlocking"]
})");
const char kBackgroundScript[] = R"(
chrome.webRequest.onBeforeSendHeaders.addListener(function(details) {
details.requestHeaders.push({name: 'foo', value: 'bar'});
details.requestHeaders.push({
name: 'frameId',
value: details.frameId.toString()
});
details.requestHeaders.push({
name: 'resourceType',
value: details.type
});
return {requestHeaders: details.requestHeaders};
},
{urls: ['*://*/echoheader*']},
[%s]);
chrome.test.sendMessage('ready');
)";
std::string opt_extra_info_spec = "'blocking', 'requestHeaders'";
if (GetExtraInfoSpec() == ExtraInfoSpec::kExtraHeaders) {
opt_extra_info_spec += ", 'extraHeaders'";
}
test_dir.WriteFile(
FILE_PATH_LITERAL("background.js"),
base::StringPrintf(kBackgroundScript, opt_extra_info_spec.c_str()));
ExtensionTestMessageListener listener("ready");
ASSERT_TRUE(LoadExtension(test_dir.UnpackedPath()));
EXPECT_TRUE(listener.WaitUntilSatisfied());
}
void RegisterServiceWorker(const std::string& worker_path,
const std::optional<std::string>& scope) {
GURL url = embedded_test_server()->GetURL(
"/service_worker/create_service_worker.html");
EXPECT_TRUE(NavigateToURL(url));
std::string script = content::JsReplace("register($1, $2);", worker_path,
scope ? *scope : std::string());
EXPECT_EQ("DONE", EvalJs(GetActiveWebContents(), script));
}
// Ensures requests made by the |worker_script_name| service worker can be
// intercepted by extensions.
void RunServiceWorkerFetchTest(const std::string& worker_script_name) {
embedded_test_server()->ServeFilesFromSourceDirectory("content/test/data");
ASSERT_TRUE(embedded_test_server()->Start());
// Install the test extension.
InstallRequestHeaderModifyingExtension();
// Register a service worker and navigate to a page it controls.
RegisterServiceWorker(worker_script_name, std::nullopt);
EXPECT_TRUE(NavigateToURL(embedded_test_server()->GetURL(
"/service_worker/fetch_from_page.html")));
// Make a fetch from the controlled page. Depending on the worker script,
// the fetch might go to the service worker and be re-issued, or might
// fallback to network, or skip the worker, etc. In any case, this function
// expects a network request to happen, and that the extension modify the
// headers of the request before it goes to network. Verify that it was able
// to inject a header of "foo=bar".
EXPECT_EQ("bar", EvalJs(GetActiveWebContents(),
"fetch_from_page('/echoheader?foo');"));
}
};
INSTANTIATE_TEST_SUITE_P(
PersistentBackgroundWithExtraHeaders,
ServiceWorkerWebRequestApiTest,
::testing::Values(SWTestParams(true, ContextType::kPersistentBackground)));
INSTANTIATE_TEST_SUITE_P(
PersistentBackground,
ServiceWorkerWebRequestApiTest,
::testing::Values(SWTestParams(false, ContextType::kPersistentBackground)));
// These tests use webRequestBlocking and/or declarativeWebRequest.
// See crbug.com/332512510.
INSTANTIATE_TEST_SUITE_P(
ServiceWorkerWithExtraHeaders,
ServiceWorkerWebRequestApiTest,
::testing::Values(SWTestParams(true, ContextType::kServiceWorkerMV2)));
INSTANTIATE_TEST_SUITE_P(
ServiceWorker,
ServiceWorkerWebRequestApiTest,
::testing::Values(SWTestParams(false, ContextType::kServiceWorkerMV2)));
IN_PROC_BROWSER_TEST_P(ServiceWorkerWebRequestApiTest, ServiceWorkerFetch) {
RunServiceWorkerFetchTest("fetch_event_respond_with_fetch.js");
}
IN_PROC_BROWSER_TEST_P(ServiceWorkerWebRequestApiTest, ServiceWorkerFallback) {
RunServiceWorkerFetchTest("fetch_event_pass_through.js");
}
IN_PROC_BROWSER_TEST_P(ServiceWorkerWebRequestApiTest,
ServiceWorkerNoFetchHandler) {
RunServiceWorkerFetchTest("empty.js");
}
IN_PROC_BROWSER_TEST_P(ServiceWorkerWebRequestApiTest,
ServiceWorkerFallbackAfterRedirect) {
embedded_test_server()->ServeFilesFromSourceDirectory("content/test/data");
ASSERT_TRUE(embedded_test_server()->Start());
InstallRequestHeaderModifyingExtension();
RegisterServiceWorker("/fetch_event_passthrough.js", "/echoheader");
// Make sure the request is intercepted with no redirect.
ASSERT_TRUE(NavigateToURL(embedded_test_server()->GetURL("/echoheader?foo")));
content::WebContents* web_contents = GetActiveWebContents();
EXPECT_EQ("bar", EvalJs(web_contents, "document.body.textContent;"));
// Make sure the request is intercepted with a redirect.
GURL redirect_url = embedded_test_server()->GetURL(
"/server-redirect?" +
embedded_test_server()->GetURL("/echoheader?foo").spec());
ASSERT_TRUE(NavigateToURL(redirect_url));
EXPECT_EQ("bar", EvalJs(web_contents, "document.body.textContent;"));
}
// An extension should be able to modify the request header for service worker
// script by using WebRequest API.
IN_PROC_BROWSER_TEST_P(ServiceWorkerWebRequestApiTest, ServiceWorkerScript) {
// The extension to be used in this test adds foo=bar request header.
const char kScriptPath[] = "/echoheader_service_worker.js";
// The request handler below will run on the EmbeddedTestServer's IO thread.
// Hence guard access to |served_service_worker_count| and |foo_header_value|
// using a lock.
base::Lock lock;
int served_service_worker_count = 0;
std::string foo_header_value;
// Capture the value of a request header foo, which should be added if
// extension modifies the request header.
embedded_test_server()->RegisterRequestHandler(base::BindLambdaForTesting(
[&](const net::test_server::HttpRequest& request)
-> std::unique_ptr<net::test_server::HttpResponse> {
if (request.relative_url != kScriptPath) {
return nullptr;
}
base::AutoLock auto_lock(lock);
++served_service_worker_count;
foo_header_value.clear();
if (request.headers.find("foo") != request.headers.end()) {
foo_header_value = request.headers.at("foo");
}
auto response = std::make_unique<net::test_server::BasicHttpResponse>();
response->set_code(net::HTTP_OK);
response->set_content_type("text/javascript");
response->AddCustomHeader("Cache-Control", "no-cache");
response->set_content("// empty");
return response;
}));
ASSERT_TRUE(embedded_test_server()->Start());
InstallRequestHeaderModifyingExtension();
content::WebContents* web_contents = GetActiveWebContents();
GURL url = embedded_test_server()->GetURL(
"/service_worker/create_service_worker.html");
EXPECT_TRUE(NavigateToURL(url));
// Register a service worker. The worker script should have "foo: bar" request
// header added by the extension.
std::string script =
content::JsReplace("register($1, './in-scope');", kScriptPath);
EXPECT_EQ("DONE", EvalJs(web_contents, script));
{
base::AutoLock auto_lock(lock);
EXPECT_EQ(1, served_service_worker_count);
EXPECT_EQ("bar", foo_header_value);
}
// Update the worker. The worker should have "foo: bar" request header in the
// request for update checking.
EXPECT_TRUE(NavigateToURL(url));
EXPECT_EQ("DONE", EvalJs(web_contents, "update('./in-scope');"));
{
base::AutoLock auto_lock(lock);
EXPECT_EQ(2, served_service_worker_count);
EXPECT_EQ("bar", foo_header_value);
}
}
// An extension should be able to modify the request header for module service
// worker script by using WebRequest API.
IN_PROC_BROWSER_TEST_P(ServiceWorkerWebRequestApiTest,
ModuleServiceWorkerScript) {
// The extension to be used in this test adds foo=bar request header.
constexpr char kScriptPath[] = "/echoheader_service_worker.js";
// The request handler below will run on the EmbeddedTestServer's IO thread.
// Hence guard access to |served_service_worker_count| and |foo_header_value|
// using a lock.
base::Lock lock;
int served_service_worker_count = 0;
std::string foo_header_value;
// Capture the value of a request header foo, which should be added if
// extension modifies the request header.
embedded_test_server()->RegisterRequestHandler(base::BindLambdaForTesting(
[&](const net::test_server::HttpRequest& request)
-> std::unique_ptr<net::test_server::HttpResponse> {
if (request.relative_url != kScriptPath) {
return nullptr;
}
base::AutoLock auto_lock(lock);
++served_service_worker_count;
foo_header_value.clear();
if (base::Contains(request.headers, "foo")) {
foo_header_value = request.headers.at("foo");
}
auto response = std::make_unique<net::test_server::BasicHttpResponse>();
response->set_code(net::HTTP_OK);
response->set_content_type("text/javascript");
response->AddCustomHeader("Cache-Control", "no-cache");
response->set_content("// empty");
return response;
}));
ASSERT_TRUE(embedded_test_server()->Start());
InstallRequestHeaderModifyingExtension();
content::WebContents* web_contents = GetActiveWebContents();
GURL url = embedded_test_server()->GetURL(
"/service_worker/create_service_worker.html");
EXPECT_TRUE(NavigateToURL(url));
// Register a service worker. `EvalJs` is blocked until the request handler
// serves the worker script. The worker script should have "foo: bar" request
// header added by the extension.
std::string script =
content::JsReplace("register($1, './in-scope', 'module');", kScriptPath);
EXPECT_EQ("DONE", EvalJs(web_contents, script));
{
base::AutoLock auto_lock(lock);
EXPECT_EQ(1, served_service_worker_count);
EXPECT_EQ("bar", foo_header_value);
}
// Update the worker. `EvalJs` is blocked until the request handler serves the
// worker script. The worker should have "foo: bar" request header in the
// request for update checking.
EXPECT_TRUE(NavigateToURL(url));
EXPECT_EQ("DONE", EvalJs(web_contents, "update('./in-scope');"));
{
base::AutoLock auto_lock(lock);
EXPECT_EQ(2, served_service_worker_count);
EXPECT_EQ("bar", foo_header_value);
}
}
// An extension should be able to modify the request header for module service
// worker script with static import by using WebRequest API.
IN_PROC_BROWSER_TEST_P(ServiceWorkerWebRequestApiTest,
ModuleServiceWorkerScriptWithStaticImport) {
// The extension to be used in this test adds foo=bar request header.
constexpr char kScriptPath[] = "/static-import-worker.js";
constexpr char kImportedScriptPath[] = "/echoheader_service_worker.js";
// The request handler below will run on the EmbeddedTestServer's IO thread.
// Hence guard access to |served_service_worker_count| and |foo_header_value|
// using a lock.
base::Lock lock;
int served_service_worker_count = 0;
std::string foo_header_value;
// Capture the value of a request header foo, which should be added if
// extension modifies the request header.
embedded_test_server()->RegisterRequestHandler(base::BindLambdaForTesting(
[&](const net::test_server::HttpRequest& request)
-> std::unique_ptr<net::test_server::HttpResponse> {
// Handle the top-level worker script.
if (request.relative_url == kScriptPath) {
base::AutoLock auto_lock(lock);
++served_service_worker_count;
auto response =
std::make_unique<net::test_server::BasicHttpResponse>();
response->set_code(net::HTTP_OK);
response->set_content_type("text/javascript");
response->AddCustomHeader("Cache-Control", "no-cache");
response->set_content("import './echoheader_service_worker.js';");
return response;
}
// Handle the static-imported script.
if (request.relative_url == kImportedScriptPath) {
base::AutoLock auto_lock(lock);
++served_service_worker_count;
foo_header_value.clear();
if (base::Contains(request.headers, "foo")) {
foo_header_value = request.headers.at("foo");
}
auto response =
std::make_unique<net::test_server::BasicHttpResponse>();
response->set_code(net::HTTP_OK);
response->set_content_type("text/javascript");
response->AddCustomHeader("Cache-Control", "no-cache");
response->set_content("// empty");
return response;
}
return nullptr;
}));
ASSERT_TRUE(embedded_test_server()->Start());
InstallRequestHeaderModifyingExtension();
content::WebContents* web_contents = GetActiveWebContents();
GURL url = embedded_test_server()->GetURL(
"/service_worker/create_service_worker.html");
EXPECT_TRUE(NavigateToURL(url));
// Register a service worker. The worker script should have "foo: bar" request
// header added by the extension.
std::string script =
content::JsReplace("register($1, './in-scope', 'module');", kScriptPath);
EXPECT_EQ("DONE", EvalJs(web_contents, script));
{
base::AutoLock auto_lock(lock);
EXPECT_EQ(2, served_service_worker_count);
EXPECT_EQ("bar", foo_header_value);
}
// Update the worker. The worker should have "foo: bar" request header in the
// request for update checking.
EXPECT_TRUE(NavigateToURL(url));
EXPECT_EQ("DONE", EvalJs(web_contents, "update('./in-scope');"));
{
base::AutoLock auto_lock(lock);
EXPECT_EQ(4, served_service_worker_count);
EXPECT_EQ("bar", foo_header_value);
}
}
// Ensure that extensions can intercept service worker navigation preload
// requests.
IN_PROC_BROWSER_TEST_P(ServiceWorkerWebRequestApiTest,
ServiceWorkerNavigationPreload) {
ASSERT_TRUE(embedded_test_server()->Start());
// Install the test extension.
InstallRequestHeaderModifyingExtension();
// Register a service worker that uses navigation preload.
RegisterServiceWorker("/service_worker/navigation_preload_worker.js",
"/echoheader");
// Navigate to "/echoheader". The browser will detect that the service worker
// above is registered with this scope and has navigation preload enabled.
// So it will send the navigation preload request to network while at the same
// time starting up the service worker. The service worker will get the
// response for the navigation preload request, and respond with it to create
// the page.
GURL url = embedded_test_server()->GetURL(
"/echoheader?frameId&resourceType&service-worker-navigation-preload");
ASSERT_TRUE(NavigateToURL(url));
content::WebContents* web_contents = GetActiveWebContents();
// Since the request was to "/echoheader", the response describes the request
// headers.
//
// The expectation is "0\nmain_frame\ntrue" because...
//
// 1) The extension is expected to add a "frameId: {id}" header, where {id} is
// details.frameId. This id is 0 for the main frame.
// 2) The extension is similarly expected to add a "resourceType: {type}"
// header, where {type} is details.type.
// 3) The browser adds a "service-worker-navigation-preload: true" header for
// navigation preload requests, so also sanity check that header to prove
// that this test is really testing the navigation preload request.
EXPECT_EQ("0\nmain_frame\ntrue",
EvalJs(web_contents, "document.body.textContent;"));
// Repeat the test from an iframe, to test that details.frameId and resource
// type is populated correctly.
const char kAddIframe[] = R"(
(async () => {
const iframe = document.createElement('iframe');
await new Promise(resolve => {
iframe.src = $1;
iframe.onload = resolve;
document.body.appendChild(iframe);
});
const result = iframe.contentWindow.document.body.textContent;
// Expect "{frameId}\nsub_frame\ntrue" where {frameId} is a positive
// integer.
const split = result.split('\n');
if (parseInt(split[0]) > 0 && split[1] == 'sub_frame' &&
split[2] == 'true') {
return 'ok';
}
return 'bad result: ' + result;
})();
)";
EXPECT_EQ("ok", EvalJs(web_contents, content::JsReplace(kAddIframe, url)));
}
#if !BUILDFLAG(IS_ANDROID)
// Ensure we don't strip off initiator incorrectly in web request events when
// both the normal and incognito contexts are active. Regression test for
// crbug.com/934398.
// TODO(crbug.com/41493389): enable this flaky test
#if BUILDFLAG(IS_LINUX) && defined(ADDRESS_SANITIZER) && defined(LEAK_SANITIZER)
#define MAYBE_Initiator_SpanningIncognito DISABLED_Initiator_SpanningIncognito
#else
#define MAYBE_Initiator_SpanningIncognito Initiator_SpanningIncognito
#endif
IN_PROC_BROWSER_TEST_P(ExtensionWebRequestApiTestWithContextType,
MAYBE_Initiator_SpanningIncognito) {
embedded_test_server()->ServeFilesFromSourceDirectory("chrome/test/data");
ASSERT_TRUE(embedded_test_server()->Start());
ExtensionTestMessageListener ready_listener("ready");
const Extension* extension =
LoadExtension(test_data_dir_.AppendASCII("webrequest")
.AppendASCII("initiator_spanning"));
ASSERT_TRUE(extension);
// Save the ID because enabling the extension for incognito mode will
// invalidate |extension|.
const ExtensionId extension_id = extension->id();
EXPECT_TRUE(ready_listener.WaitUntilSatisfied());
Browser* incognito_browser = CreateIncognitoBrowser(profile());
ASSERT_TRUE(incognito_browser);
// iframe.html loads an iframe to title1.html. The extension listens for the
// request to title1.html and records the request initiator.
GURL url = embedded_test_server()->GetURL("google.com", "/iframe.html");
const std::string url_origin = url::Origin::Create(url).Serialize();
static constexpr char kScript[] = R"(
chrome.test.sendScriptResult(JSON.stringify(self.initiators));
self.initiators = [];
)";
ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), url));
std::optional<std::string> result =
ExecuteScriptAndReturnString(extension_id, profile(), kScript);
ASSERT_TRUE(result);
EXPECT_EQ(base::StringPrintf("[\"%s\"]", url_origin.c_str()), *result);
// The extension isn't enabled in incognito. Se we shouldn't intercept the
// request to |url|.
ASSERT_TRUE(ui_test_utils::NavigateToURL(incognito_browser, url));
result = ExecuteScriptAndReturnString(extension_id, profile(), kScript);
ASSERT_TRUE(result);
EXPECT_EQ("[]", *result);
// Now enable the extension in incognito.
extension = nullptr;
ready_listener.Reset();
extensions::util::SetIsIncognitoEnabled(extension_id, profile(),
true /* enabled */);
EXPECT_TRUE(ready_listener.WaitUntilSatisfied());
// Now we should be able to intercept the incognito request.
ASSERT_TRUE(ui_test_utils::NavigateToURL(incognito_browser, url));
result = ExecuteScriptAndReturnString(extension_id, profile(), kScript);
ASSERT_TRUE(result);
EXPECT_EQ(base::StringPrintf("[\"%s\"]", url_origin.c_str()), *result);
}
// Ensure we don't strip off initiator incorrectly in web request events when
// both the normal and incognito contexts are active. Regression test for
// crbug.com/934398.
// Flaky on Linux. See http://crbug.com/1423252
#if BUILDFLAG(IS_LINUX)
#define MAYBE_Initiator_SplitIncognito DISABLED_Initiator_SplitIncognito
#else
#define MAYBE_Initiator_SplitIncognito Initiator_SplitIncognito
#endif
IN_PROC_BROWSER_TEST_P(ExtensionWebRequestApiTestWithContextType,
MAYBE_Initiator_SplitIncognito) {
embedded_test_server()->ServeFilesFromSourceDirectory("chrome/test/data");
ASSERT_TRUE(embedded_test_server()->Start());
ExtensionTestMessageListener ready_listener("ready");
ExtensionTestMessageListener incognito_ready_listener("incognito ready");
const Extension* extension = LoadExtension(
test_data_dir_.AppendASCII("webrequest").AppendASCII("initiator_split"),
{.allow_in_incognito = true});
ASSERT_TRUE(extension);
EXPECT_TRUE(ready_listener.WaitUntilSatisfied());
Browser* incognito_browser = CreateIncognitoBrowser(profile());
ASSERT_TRUE(incognito_browser);
EXPECT_TRUE(incognito_ready_listener.WaitUntilSatisfied());
// iframe.html loads an iframe to title1.html. The extension listens for the
// request to title1.html and records the request initiator.
GURL url_normal =
embedded_test_server()->GetURL("google.com", "/iframe.html");
GURL url_incognito =
embedded_test_server()->GetURL("example.com", "/iframe.html");
const std::string origin_normal = url::Origin::Create(url_normal).Serialize();
const std::string origin_incognito =
url::Origin::Create(url_incognito).Serialize();
static constexpr char kScript[] = R"(
chrome.test.sendScriptResult(JSON.stringify(self.initiators));
self.initiators = [];
)";
ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), url_normal));
ASSERT_TRUE(ui_test_utils::NavigateToURL(incognito_browser, url_incognito));
std::optional<std::string> result =
ExecuteScriptAndReturnString(extension->id(), profile(), kScript);
ASSERT_TRUE(result);
EXPECT_EQ(base::StringPrintf("[\"%s\"]", origin_normal.c_str()), *result);
result = ExecuteScriptAndReturnString(
extension->id(),
profile()->GetPrimaryOTRProfile(/*create_if_needed=*/true), kScript);
ASSERT_TRUE(result);
EXPECT_EQ(base::StringPrintf("[\"%s\"]", origin_incognito.c_str()), *result);
}
#endif // !BUILDFLAG(IS_ANDROID)
// A request handler that sets the Access-Control-Allow-Origin header.
std::unique_ptr<net::test_server::HttpResponse> HandleXHRRequest(
const net::test_server::HttpRequest& request) {
auto http_response = std::make_unique<net::test_server::BasicHttpResponse>();
http_response->set_code(net::HTTP_OK);
http_response->AddCustomHeader("Access-Control-Allow-Origin", "*");
return http_response;
}
// Regression test for http://crbug.com/971206. The responseHeaders should still
// be present in onBeforeRedirect even for HSTS upgrade.
IN_PROC_BROWSER_TEST_P(
ExtensionWebRequestApiTestWithContextTypeForHstsTopLevelNavigationOnly,
ExtraHeadersWithHSTSUpgrade) {
net::EmbeddedTestServer https_test_server(
net::EmbeddedTestServer::TYPE_HTTPS);
https_test_server.RegisterRequestHandler(
base::BindRepeating(&HandleXHRRequest));
ASSERT_TRUE(https_test_server.Start());
TestExtensionDir test_dir;
test_dir.WriteManifest(R"({
"name": "Web Request HSTS Test",
"manifest_version": 2,
"version": "0.1",
"background": { "scripts": ["background.js"], "persistent": true },
"permissions": ["<all_urls>", "webRequest", "webRequestBlocking"]
})");
test_dir.WriteFile(FILE_PATH_LITERAL("background.js"), R"(
chrome.webRequest.onBeforeRedirect.addListener(function(details) {
self.headerCount = details.responseHeaders.length;
}, {urls: ['<all_urls>']},
['responseHeaders', 'extraHeaders']);
chrome.test.sendMessage('ready');
)");
ExtensionTestMessageListener listener("ready");
const Extension* extension = LoadExtension(test_dir.UnpackedPath());
ASSERT_TRUE(extension);
EXPECT_TRUE(listener.WaitUntilSatisfied());
ASSERT_TRUE(NavigateToURL(https_test_server.GetURL("/echo")));
content::StoragePartition* partition =
profile()->GetDefaultStoragePartition();
base::RunLoop run_loop;
partition->GetNetworkContext()->AddHSTS(
https_test_server.host_port_pair().host(),
base::Time::Now() + base::Days(100), true, run_loop.QuitClosure());
run_loop.Run();
PerformXhrInFrame(GetActiveWebContents()->GetPrimaryMainFrame(),
https_test_server.host_port_pair().host(),
https_test_server.port(), "echo");
EXPECT_GT(
GetCountFromBackgroundScript(extension, profile(), "self.headerCount"),
0);
}
#if !BUILDFLAG(IS_ANDROID)
// Ensure that when an extension blocks a main-frame request, the resultant
// error page attributes this to an extension.
IN_PROC_BROWSER_TEST_F(ExtensionWebRequestApiTest,
ErrorPageForBlockedMainFrameNavigation) {
ASSERT_TRUE(StartEmbeddedTestServer());
ASSERT_TRUE(RunExtensionTest(
"webrequest", {.extension_url = "test_simple_cancel_navigation.html"}))
<< message_;
WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents();
std::string body =
content::EvalJs(tab, "document.body.textContent").ExtractString();
EXPECT_TRUE(
base::Contains(body, "This page has been blocked by an extension"));
EXPECT_TRUE(base::Contains(body, "Try disabling your extensions."));
}
// Regression test for https://crbug.com/1019614.
IN_PROC_BROWSER_TEST_P(ExtensionWebRequestApiTestWithContextType,
HSTSUpgradeAfterRedirect) {
net::EmbeddedTestServer https_test_server(
net::EmbeddedTestServer::TYPE_HTTPS);
ASSERT_TRUE(StartEmbeddedTestServer());
ASSERT_TRUE(https_test_server.Start());
TestExtensionDir test_dir;
test_dir.WriteManifest(R"({
"name": "Web Request HSTS Test",
"manifest_version": 2,
"version": "0.1",
"background": { "scripts": ["background.js"], "persistent": true },
"permissions": ["<all_urls>", "webRequest", "webRequestBlocking"]
})");
test_dir.WriteFile(FILE_PATH_LITERAL("background.js"), R"(
chrome.webRequest.onBeforeRedirect.addListener(() => {}, {
urls: [ '<all_urls>' ]
}, [ 'responseHeaders', 'extraHeaders' ]);
chrome.test.sendMessage('ready');
)");
ExtensionTestMessageListener listener("ready");
const Extension* extension = LoadExtension(test_dir.UnpackedPath());
ASSERT_TRUE(extension);
EXPECT_TRUE(listener.WaitUntilSatisfied());
content::StoragePartition* partition =
profile()->GetDefaultStoragePartition();
base::test::TestFuture<void> hsts_added;
partition->GetNetworkContext()->AddHSTS("hsts.com",
base::Time::Now() + base::Days(100),
true, hsts_added.GetCallback());
ASSERT_TRUE(hsts_added.Wait());
GURL final_url = https_test_server.GetURL("hsts.com", "/echo");
GURL::Replacements replace_scheme;
replace_scheme.SetSchemeStr("http");
GURL http_url = final_url.ReplaceComponents(replace_scheme);
GURL redirect_url = embedded_test_server()->GetURL(
"test.com", "/server-redirect?" + http_url.spec());
ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), redirect_url));
EXPECT_EQ(final_url, browser()
->tab_strip_model()
->GetActiveWebContents()
->GetLastCommittedURL());
}
// Regression test for https://crbug.com/40864513. This test passes if it
// doesn't crash.
// This is a copy of HSTSUpgradeAfterRedirect, but the redirect contains a CSP
// header.
// TODO(https://crbug.com/40864513) Enable this test.
IN_PROC_BROWSER_TEST_P(ExtensionWebRequestApiTestWithContextType,
DISABLED_HSTSUpgradeAfterRedirectWithCSP) {
net::EmbeddedTestServer https_test_server(
net::EmbeddedTestServer::TYPE_HTTPS);
embedded_test_server()->RegisterRequestHandler(base::BindLambdaForTesting(
[](const net::test_server::HttpRequest& request)
-> std::unique_ptr<net::test_server::HttpResponse> {
if (request.relative_url.starts_with("/server-redirect-with-csp")) {
auto response =
std::make_unique<net::test_server::BasicHttpResponse>();
response->AddCustomHeader("Location", request.GetURL().query_piece());
response->AddCustomHeader("Content-Security-Policy",
"frame-ancestors 'none'");
response->set_code(net::HTTP_MOVED_PERMANENTLY);
return response;
}
return nullptr;
}));
ASSERT_TRUE(StartEmbeddedTestServer());
ASSERT_TRUE(https_test_server.Start());
TestExtensionDir test_dir;
test_dir.WriteManifest(R"({
"name": "Web Request HSTS Test",
"manifest_version": 2,
"version": "0.1",
"background": { "scripts": ["background.js"], "persistent": true },
"permissions": ["<all_urls>", "webRequest", "webRequestBlocking"]
})");
test_dir.WriteFile(FILE_PATH_LITERAL("background.js"), R"(
chrome.webRequest.onBeforeRedirect.addListener(() => {}, {
urls: [
'<all_urls>',
]
}, [
'responseHeaders',
'extraHeaders',
]);
chrome.test.sendMessage('ready');
)");
ExtensionTestMessageListener listener("ready");
const Extension* extension = LoadExtension(test_dir.UnpackedPath());
ASSERT_TRUE(extension);
EXPECT_TRUE(listener.WaitUntilSatisfied());
content::StoragePartition* partition =
profile()->GetDefaultStoragePartition();
base::test::TestFuture<void> hsts_added;
partition->GetNetworkContext()->AddHSTS("hsts.com",
base::Time::Now() + base::Days(100),
true, hsts_added.GetCallback());
ASSERT_TRUE(hsts_added.Wait());
GURL final_url = https_test_server.GetURL("hsts.com", "/echo");
GURL::Replacements replace_scheme;
replace_scheme.SetSchemeStr("http");
GURL http_url = final_url.ReplaceComponents(replace_scheme);
GURL redirect_url = embedded_test_server()->GetURL(
"test.com", "/server-redirect-with-csp?" + http_url.spec());
ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), redirect_url));
EXPECT_EQ(final_url, browser()
->tab_strip_model()
->GetActiveWebContents()
->GetLastCommittedURL());
}
struct SWBTestParams {
// The parameter is for opt_extraInfoSpec passed to addEventListener.
// 'blocking' if it's false, and 'extraHeaders' in addition to them
// if it's true.
bool extra_info_spec;
ContextType context_type;
};
class SubresourceWebBundlesWebRequestApiTest
: public testing::WithParamInterface<SWBTestParams>,
public ExtensionApiTest {
public:
SubresourceWebBundlesWebRequestApiTest()
: ExtensionApiTest(GetParam().context_type) {}
~SubresourceWebBundlesWebRequestApiTest() override = default;
SubresourceWebBundlesWebRequestApiTest(
const SubresourceWebBundlesWebRequestApiTest&) = delete;
SubresourceWebBundlesWebRequestApiTest& operator=(
const SubresourceWebBundlesWebRequestApiTest&) = delete;
protected:
// Whether 'extraHeaders' is set in opt_extraInfoSpec of addEventListener.
enum class ExtraInfoSpec {
// No 'extraHeaders'
kDefault,
// with 'extraHeaders'
kExtraHeaders
};
static ExtraInfoSpec GetExtraInfoSpec() {
return GetParam().extra_info_spec ? ExtraInfoSpec::kExtraHeaders
: ExtraInfoSpec::kDefault;
}
bool TryLoadScript(const std::string& script_src) {
content::WebContents* web_contents =
browser()->tab_strip_model()->GetActiveWebContents();
std::string script = base::StringPrintf(R"(
(() => {
const script = document.createElement('script');
return new Promise(resolve => {
script.addEventListener('load', () => {
resolve(true);
});
script.addEventListener('error', () => {
resolve(false);
});
script.src = '%s';
document.body.appendChild(script);
});
})();
)",
script_src.c_str());
return EvalJs(web_contents->GetPrimaryMainFrame(), script).ExtractBool();
}
bool TryLoadBundle(const std::string& href, const std::string& resources) {
content::WebContents* web_contents =
browser()->tab_strip_model()->GetActiveWebContents();
std::string script = base::StringPrintf(R"(
(() => {
const script = document.createElement('script');
script.type = 'webbundle';
return new Promise(resolve => {
script.addEventListener('load', () => {
resolve(true);
});
script.addEventListener('error', () => {
resolve(false);
});
script.textContent = JSON.stringify({
'source': '%s',
'resources': ['%s']
});
document.body.appendChild(script);
});
})();
)",
href.c_str(), resources.c_str());
return EvalJs(web_contents->GetPrimaryMainFrame(), script).ExtractBool();
}
// Registers a request handler for static content.
void RegisterRequestHandler(const std::string& relative_url,
const std::string& content_type,
const std::string& content) {
embedded_test_server()->RegisterRequestHandler(base::BindLambdaForTesting(
[relative_url, content_type,
content](const net::test_server::HttpRequest& request)
-> std::unique_ptr<net::test_server::HttpResponse> {
if (request.relative_url == relative_url) {
auto response =
std::make_unique<net::test_server::BasicHttpResponse>();
response->set_code(net::HTTP_OK);
response->set_content_type(content_type);
response->set_content(content);
return std::move(response);
}
return nullptr;
}));
}
// Registers a request handler for web bundle. This method takes a pointer of
// the content of the web bundle, because we can't create the content of the
// web bundle before starting the server since we need to know the port number
// of the test server due to the same-origin restriction (the origin of
// subresource which is written in the web bundle must be same as the origin
// of the web bundle), and we can't call
// EmbeddedTestServer::RegisterRequestHandler() after starting the server.
void RegisterWebBundleRequestHandler(const std::string& relative_url,
const std::string* web_bundle) {
embedded_test_server()->RegisterRequestHandler(base::BindLambdaForTesting(
[relative_url, web_bundle](const net::test_server::HttpRequest& request)
-> std::unique_ptr<net::test_server::HttpResponse> {
if (request.relative_url == relative_url) {
auto response =
std::make_unique<net::test_server::BasicHttpResponse>();
response->set_code(net::HTTP_OK);
response->set_content_type("application/webbundle");
response->AddCustomHeader("X-Content-Type-Options", "nosniff");
response->set_content(*web_bundle);
return std::move(response);
}
return nullptr;
}));
}
private:
base::test::ScopedFeatureList feature_list_;
};
INSTANTIATE_TEST_SUITE_P(
PersistentBackgroundWithExtraHeaders,
SubresourceWebBundlesWebRequestApiTest,
::testing::Values(SWBTestParams(true, ContextType::kPersistentBackground)));
INSTANTIATE_TEST_SUITE_P(
PersistentBackground,
SubresourceWebBundlesWebRequestApiTest,
::testing::Values(SWBTestParams(false,
ContextType::kPersistentBackground)));
// These tests use webRequestBlocking and/or declarativeWebRequest.
// See crbug.com/332512510.
INSTANTIATE_TEST_SUITE_P(
ServiceWorkerWithExtraHeaders,
SubresourceWebBundlesWebRequestApiTest,
::testing::Values(SWBTestParams(true, ContextType::kServiceWorkerMV2)));
INSTANTIATE_TEST_SUITE_P(
ServiceWorker,
SubresourceWebBundlesWebRequestApiTest,
::testing::Values(SWBTestParams(false, ContextType::kServiceWorkerMV2)));
// Ensure web request listeners can intercept requests for a web bundle and its
// subresources.
// TODO(crbug.com/40801096): Fix flane and re-enable test.
IN_PROC_BROWSER_TEST_P(SubresourceWebBundlesWebRequestApiTest,
DISABLED_RequestIntercepted) {
const std::string uuid_in_package_script_url =
"uuid-in-package:6a059ece-62f4-4c79-a9e2-1c641cbdbaaf";
// Create an extension that intercepts requests.
TestExtensionDir test_dir;
test_dir.WriteManifest(R"({
"name": "Web Request Subresource Web Bundles Test",
"manifest_version": 2,
"version": "0.1",
"background": { "scripts": ["background.js"], "persistent": true },
"permissions": ["<all_urls>", "webRequest"]
})");
std::string opt_extra_info_spec = "";
if (GetExtraInfoSpec() == ExtraInfoSpec::kExtraHeaders) {
opt_extra_info_spec += "'extraHeaders'";
}
test_dir.WriteFile(FILE_PATH_LITERAL("background.js"),
base::StringPrintf(R"(
self.numMainResourceRequests = 0;
self.numWebBundleRequests = 0;
self.numScriptRequests = 0;
self.numUUIDInPackageScriptRequests = 0;
chrome.webRequest.onBeforeRequest.addListener(function(details) {
if (details.url.includes('test.html'))
self.numMainResourceRequests++;
else if (details.url.includes('web_bundle.wbn'))
self.numWebBundleRequests++;
else if (details.url.includes('test.js'))
self.numScriptRequests++;
else if (details.url === '%s')
self.numUUIDInPackageScriptRequests++;
}, {urls: ['<all_urls>']}, [%s]);
chrome.test.sendMessage('ready');
)",
uuid_in_package_script_url.c_str(),
opt_extra_info_spec.c_str()));
const Extension* extension = nullptr;
{
ExtensionTestMessageListener listener("ready");
extension = LoadExtension(test_dir.UnpackedPath());
ASSERT_TRUE(extension);
EXPECT_TRUE(listener.WaitUntilSatisfied());
}
const std::string page_html = base::StringPrintf(
R"(
<title>Loaded</title>
<body>
<script>
(() => {
const wbn_url =
new URL('./web_bundle.wbn', location.href).toString();
const script_url = new URL('./test.js', location.href).toString();
const uuid_in_package_script_url = '%s';
const script_web_bundle = document.createElement('script');
script_web_bundle.type = 'webbundle';
script_web_bundle.textContent = JSON.stringify({
'source': wbn_url,
'resources': [script_url, uuid_in_package_script_url]
});
document.body.appendChild(script);
const script = document.createElement('script');
script.src = script_url;
script.addEventListener('load', () => {
const uuid_in_package_script = document.createElement('script');
uuid_in_package_script.src = uuid_in_package_script_url;
document.body.appendChild(uuid_in_package_script);
});
document.body.appendChild(script);
})();
</script>
</body>
)",
uuid_in_package_script_url.c_str());
std::string web_bundle;
RegisterWebBundleRequestHandler("/web_bundle.wbn", &web_bundle);
RegisterRequestHandler("/test.html", "text/html", page_html);
ASSERT_TRUE(StartEmbeddedTestServer());
// Create a web bundle.
GURL script_url = embedded_test_server()->GetURL("/test.js");
web_package::WebBundleBuilder builder;
builder.AddExchange(
script_url,
{{":status", "200"}, {"content-type", "application/javascript"}},
"document.title = 'ScriptDone';");
builder.AddExchange(
uuid_in_package_script_url,
{{":status", "200"}, {"content-type", "application/javascript"}},
"document.title += ':UUIDInPackageScriptDone';");
std::vector<uint8_t> bundle = builder.CreateBundle();
web_bundle = std::string(bundle.begin(), bundle.end());
GURL page_url = embedded_test_server()->GetURL("/test.html");
content::WebContents* web_contents =
browser()->tab_strip_model()->GetActiveWebContents();
std::u16string expected_title = u"ScriptDone:UUIDInPackageScriptDone";
content::TitleWatcher title_watcher(web_contents, expected_title);
ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), page_url));
EXPECT_EQ(page_url, web_contents->GetLastCommittedURL());
// Check that the scripts in the web bundle are correctly loaded even when the
// extension intercepted the request.
EXPECT_EQ(expected_title, title_watcher.WaitAndGetTitle());
EXPECT_EQ(1, GetCountFromBackgroundScript(extension, profile(),
"self.numMainResourceRequests"));
EXPECT_EQ(1, GetCountFromBackgroundScript(extension, profile(),
"self.numWebBundleRequests"));
EXPECT_EQ(1, GetCountFromBackgroundScript(extension, profile(),
"self.numScriptRequests"));
EXPECT_EQ(
1, GetCountFromBackgroundScript(extension, profile(),
"self.numUUIDInPackageScriptRequests"));
}
// Ensure web request API can block the requests for the subresources inside the
// web bundle.
IN_PROC_BROWSER_TEST_P(SubresourceWebBundlesWebRequestApiTest,
RequestCanceled) {
// Create an extension that blocks a bundle subresource request.
TestExtensionDir test_dir;
test_dir.WriteManifest(R"({
"name": "Web Request Subresource Web Bundles Test",
"manifest_version": 2,
"version": "0.1",
"background": { "scripts": ["background.js"], "persistent": true },
"permissions": ["<all_urls>", "webRequest", "webRequestBlocking"]
})");
std::string pass_uuid_in_package_js_url =
"uuid-in-package:bf50ad1f-899e-42ca-95ac-ca592aa2ecb5";
std::string cancel_uuid_in_package_js_url =
"uuid-in-package:9cc02e52-05b6-466a-8c0e-f22ee86825a8";
std::string opt_extra_info_spec = "'blocking'";
if (GetExtraInfoSpec() == ExtraInfoSpec::kExtraHeaders) {
opt_extra_info_spec += ", 'extraHeaders'";
}
test_dir.WriteFile(FILE_PATH_LITERAL("background.js"),
base::StringPrintf(R"(
self.numPassScriptRequests = 0;
self.numCancelScriptRequests = 0;
self.numUUIDInPackagePassScriptRequests = 0;
self.numUUIDInPackageCancelScriptRequests = 0;
chrome.webRequest.onBeforeRequest.addListener(function(details) {
if (details.url.includes('pass.js')) {
self.numPassScriptRequests++;
return {cancel: false};
} else if (details.url.includes('cancel.js')) {
self.numCancelScriptRequests++;
return {cancel: true};
} else if (details.url === '%s') {
self.numUUIDInPackagePassScriptRequests++;
return {cancel: false};
} else if (details.url === '%s') {
self.numUUIDInPackageCancelScriptRequests++;
return {cancel: true};
}
}, {urls: ['<all_urls>']}, [%s]);
chrome.test.sendMessage('ready');
)",
pass_uuid_in_package_js_url.c_str(),
cancel_uuid_in_package_js_url.c_str(),
opt_extra_info_spec.c_str()));
const Extension* extension = nullptr;
{
ExtensionTestMessageListener listener("ready");
extension = LoadExtension(test_dir.UnpackedPath());
ASSERT_TRUE(extension);
EXPECT_TRUE(listener.WaitUntilSatisfied());
}
std::string page_html = base::StringPrintf(
R"(
<title>Loaded</title>
<body>
<script>
(() => {
const wbn_url = new URL('./web_bundle.wbn', location.href).toString();
const pass_js_url = new URL('./pass.js', location.href).toString();
const cancel_js_url =
new URL('./cancel.js', location.href).toString();
const pass_uuid_in_package_js_url = '%s';
const cancel_uuid_in_package_js_url = '%s';
const script = document.createElement('script');
script.type = 'webbundle';
script.textContent = JSON.stringify({
'source': wbn_url,
'resources': [pass_js_url, cancel_js_url,
pass_uuid_in_package_js_url,
cancel_uuid_in_package_js_url]
});
document.body.appendChild(script);
})();
</script>
</body>
)",
pass_uuid_in_package_js_url.c_str(),
cancel_uuid_in_package_js_url.c_str());
std::string web_bundle;
RegisterWebBundleRequestHandler("/web_bundle.wbn", &web_bundle);
RegisterRequestHandler("/test.html", "text/html", page_html);
ASSERT_TRUE(StartEmbeddedTestServer());
// Create a web bundle.
GURL pass_js_url = embedded_test_server()->GetURL("/pass.js");
GURL cancel_js_url = embedded_test_server()->GetURL("/cancel.js");
web_package::WebBundleBuilder builder;
builder.AddExchange(
pass_js_url,
{{":status", "200"}, {"content-type", "application/javascript"}},
"document.title = 'script loaded';");
builder.AddExchange(
cancel_js_url,
{{":status", "200"}, {"content-type", "application/javascript"}}, "");
builder.AddExchange(
pass_uuid_in_package_js_url,
{{":status", "200"}, {"content-type", "application/javascript"}},
"document.title = 'uuid-in-package script loaded';");
builder.AddExchange(
cancel_uuid_in_package_js_url,
{{":status", "200"}, {"content-type", "application/javascript"}}, "");
std::vector<uint8_t> bundle = builder.CreateBundle();
web_bundle = std::string(bundle.begin(), bundle.end());
GURL page_url = embedded_test_server()->GetURL("/test.html");
content::WebContents* web_contents =
browser()->tab_strip_model()->GetActiveWebContents();
ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), page_url));
EXPECT_EQ(page_url, web_contents->GetLastCommittedURL());
std::u16string expected_title1 = u"script loaded";
content::TitleWatcher title_watcher1(web_contents, expected_title1);
EXPECT_TRUE(TryLoadScript("pass.js"));
// Check that the script in the web bundle is correctly loaded even when the
// extension with blocking handler intercepted the request.
EXPECT_EQ(expected_title1, title_watcher1.WaitAndGetTitle());
EXPECT_FALSE(TryLoadScript("cancel.js"));
std::u16string expected_title2 = u"uuid-in-package script loaded";
content::TitleWatcher title_watcher2(web_contents, expected_title2);
EXPECT_TRUE(TryLoadScript(pass_uuid_in_package_js_url));
// Check that the uuid-in-package script in the web bundle is correctly loaded
// even when the extension with blocking handler intercepted the request.
EXPECT_EQ(expected_title2, title_watcher2.WaitAndGetTitle());
EXPECT_FALSE(TryLoadScript(cancel_uuid_in_package_js_url));
EXPECT_EQ(1, GetCountFromBackgroundScript(extension, profile(),
"self.numPassScriptRequests"));
EXPECT_EQ(1, GetCountFromBackgroundScript(extension, profile(),
"self.numCancelScriptRequests"));
EXPECT_EQ(
1, GetCountFromBackgroundScript(
extension, profile(), "self.numUUIDInPackagePassScriptRequests"));
EXPECT_EQ(1, GetCountFromBackgroundScript(
extension, profile(),
"self.numUUIDInPackageCancelScriptRequests"));
}
// Ensure web request API can change the headers of the subresources inside the
// web bundle.
IN_PROC_BROWSER_TEST_P(SubresourceWebBundlesWebRequestApiTest, ChangeHeader) {
// Create an extension that changes the header of the subresources inside the
// web bundle.
TestExtensionDir test_dir;
test_dir.WriteManifest(R"({
"name": "Web Request Subresource Web Bundles Test",
"manifest_version": 2,
"version": "0.1",
"background": { "scripts": ["background.js"], "persistent": true },
"permissions": ["<all_urls>", "webRequest", "webRequestBlocking"]
})");
std::string opt_extra_info_spec = "'blocking', 'responseHeaders'";
if (GetExtraInfoSpec() == ExtraInfoSpec::kExtraHeaders) {
opt_extra_info_spec += ", 'extraHeaders'";
}
test_dir.WriteFile(FILE_PATH_LITERAL("background.js"),
base::StringPrintf(R"(
chrome.webRequest.onHeadersReceived.addListener(function(details) {
if (!details.url.includes('target.txt')) {
return {cancel: false};
}
const headers = details.responseHeaders;
for (let i = 0; i < headers.length; i++) {
if (headers[i].name.toLowerCase() == 'foo') {
headers[i].value += '-changed';
}
}
headers.push({name: 'foo', value:'inserted'});
return {responseHeaders: headers};
}, {urls: ['<all_urls>']}, [%s]);
chrome.test.sendMessage('ready');
)",
opt_extra_info_spec.c_str()));
const Extension* extension = nullptr;
{
ExtensionTestMessageListener listener("ready");
extension = LoadExtension(test_dir.UnpackedPath());
ASSERT_TRUE(extension);
EXPECT_TRUE(listener.WaitUntilSatisfied());
}
const char kPageHtml[] = R"(
<title>Loaded</title>
<body>
<script>
(async () => {
const wbn_url = new URL('./web_bundle.wbn', location.href).toString();
const target_url = new URL('./target.txt', location.href).toString();
const script = document.createElement('script');
script.type = 'webbundle';
script.textContent = JSON.stringify({
'source': wbn_url,
'resources': [target_url]
});
document.body.appendChild(script);
const res = await fetch(target_url);
document.title = res.status + ':' + res.headers.get('foo');
})();
</script>
</body>
)";
std::string web_bundle;
RegisterWebBundleRequestHandler("/web_bundle.wbn", &web_bundle);
RegisterRequestHandler("/test.html", "text/html", kPageHtml);
ASSERT_TRUE(StartEmbeddedTestServer());
// Create a web bundle.
GURL target_txt_url = embedded_test_server()->GetURL("/target.txt");
web_package::WebBundleBuilder builder;
builder.AddExchange(
target_txt_url,
{{":status", "200"}, {"content-type", "text/plain"}, {"foo", "bar"}},
"Hello world");
std::vector<uint8_t> bundle = builder.CreateBundle();
web_bundle = std::string(bundle.begin(), bundle.end());
GURL page_url = embedded_test_server()->GetURL("/test.html");
content::WebContents* web_contents =
browser()->tab_strip_model()->GetActiveWebContents();
std::u16string expected_title = u"200:bar-changed, inserted";
content::TitleWatcher title_watcher(
browser()->tab_strip_model()->GetActiveWebContents(), expected_title);
ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), page_url));
EXPECT_EQ(page_url, web_contents->GetLastCommittedURL());
EXPECT_EQ(expected_title, title_watcher.WaitAndGetTitle());
}
// Ensure web request API can change the response headers of uuid-in-package:
// URL subresources inside the web bundle.
// Note: Currently we can't directly check the response headers of
// uuid-in-package: URL resources, because CORS requests are not allowed for
// such URLs. So we change the content-type header of a JavaScript file and
// monitor the error handler. Subresources in web bundles should be treated as
// if an artificial `X-Content-Type-Options: nosniff` header field is set. So
// when the content-type is not suitable for script execution, the script
// should fail to load.
IN_PROC_BROWSER_TEST_P(SubresourceWebBundlesWebRequestApiTest,
ChangeHeaderUuidInPackageUrlResource) {
std::string uuid_url = "uuid-in-package:71940cde-d20b-4fb5-b920-38a58a92c516";
// Create an extension that changes the header of the subresources inside
// the web bundle.
TestExtensionDir test_dir;
test_dir.WriteManifest(R"({
"name": "Web Request Subresource Web Bundles Test",
"manifest_version": 2,
"version": "0.1",
"background": { "scripts": ["background.js"], "persistent": true },
"permissions": ["<all_urls>", "webRequest", "webRequestBlocking"]
})");
std::string opt_extra_info_spec = "'blocking', 'responseHeaders'";
if (GetExtraInfoSpec() == ExtraInfoSpec::kExtraHeaders) {
opt_extra_info_spec += ", 'extraHeaders'";
}
static constexpr char kJsTemplate[] = R"(
chrome.webRequest.onHeadersReceived.addListener(function(details) {
if (details.url != '%s') {
return;
}
const headers = details.responseHeaders;
for (let i = 0; i < headers.length; i++) {
if (headers[i].name.toLowerCase() == 'content-type') {
headers[i].value = 'unknown/type';
}
}
return {responseHeaders: headers};
}, {urls: ['<all_urls>']}, [%s]);
chrome.test.sendMessage('ready');
)";
test_dir.WriteFile(FILE_PATH_LITERAL("background.js"),
base::StringPrintf(kJsTemplate, uuid_url.c_str(),
opt_extra_info_spec.c_str()));
const Extension* extension = nullptr;
{
ExtensionTestMessageListener listener("ready");
extension = LoadExtension(test_dir.UnpackedPath());
ASSERT_TRUE(extension);
EXPECT_TRUE(listener.WaitUntilSatisfied());
}
static constexpr char kHtmlTemplate[] = R"(
<title>Loaded</title>
<body>
<script>
(async () => {
const wbn_url = new URL('./web_bundle.wbn', location.href).toString();
const uuid_url = '%s';
const script_web_bundle = document.createElement('script');
script_web_bundle.type = 'webbundle';
script_web_bundle.textContent = JSON.stringify({
'source': wbn_url,
'resources': [uuid_url]
});
const script = document.createElement('script');
script.src = uuid_url;
script.addEventListener('error', () => {
document.title = 'failed to load';
});
document.body.appendChild(script);
})();
</script>
</body>
)";
std::string page_html = base::StringPrintf(kHtmlTemplate, uuid_url.c_str());
std::string web_bundle;
RegisterWebBundleRequestHandler("/web_bundle.wbn", &web_bundle);
RegisterRequestHandler("/test.html", "text/html", page_html);
ASSERT_TRUE(StartEmbeddedTestServer());
// Create a web bundle.
web_package::WebBundleBuilder builder;
builder.AddExchange(
uuid_url,
{{":status", "200"}, {"content-type", "application/javascript"}},
"document.title = 'loaded';");
std::vector<uint8_t> bundle = builder.CreateBundle();
web_bundle = std::string(bundle.begin(), bundle.end());
GURL page_url = embedded_test_server()->GetURL("/test.html");
content::WebContents* web_contents =
browser()->tab_strip_model()->GetActiveWebContents();
std::u16string expected_title = u"failed to load";
content::TitleWatcher title_watcher(
browser()->tab_strip_model()->GetActiveWebContents(), expected_title);
ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), page_url));
EXPECT_EQ(page_url, web_contents->GetLastCommittedURL());
EXPECT_EQ(expected_title, title_watcher.WaitAndGetTitle());
}
// Ensure web request API can redirect the requests for the subresources inside
// the web bundle.
IN_PROC_BROWSER_TEST_P(SubresourceWebBundlesWebRequestApiTest,
RequestRedirected) {
// Create an extension that redirects a bundle subresource request.
TestExtensionDir test_dir;
test_dir.WriteManifest(R"({
"name": "Web Request Subresource Web Bundles Test",
"manifest_version": 2,
"version": "0.1",
"background": { "scripts": ["background.js"], "persistent": true },
"permissions": ["<all_urls>", "webRequest", "webRequestBlocking"]
})");
std::string opt_extra_info_spec = "'blocking'";
if (GetExtraInfoSpec() == ExtraInfoSpec::kExtraHeaders) {
opt_extra_info_spec += ", 'extraHeaders'";
}
test_dir.WriteFile(FILE_PATH_LITERAL("background.js"),
base::StringPrintf(R"(
chrome.webRequest.onBeforeRequest.addListener(function(details) {
if (details.url.includes('redirect.js')) {
const redirectUrl =
details.url.replace('redirect.js', 'redirected.js');
return {redirectUrl: redirectUrl};
} else if (details.url.includes('redirect_to_unlisted.js')) {
const redirectUrl =
details.url.replace('redirect_to_unlisted.js',
'redirected_to_unlisted.js');
return {redirectUrl: redirectUrl};
} else if (details.url.includes('redirect_to_server.js')) {
const redirectUrl =
details.url.replace('redirect_to_server.js',
'redirected_to_server.js');
return {redirectUrl: redirectUrl};
}
}, {urls: ['<all_urls>']}, [%s]);
chrome.test.sendMessage('ready');
)",
opt_extra_info_spec.c_str()));
const Extension* extension = nullptr;
{
ExtensionTestMessageListener listener("ready");
extension = LoadExtension(test_dir.UnpackedPath());
ASSERT_TRUE(extension);
EXPECT_TRUE(listener.WaitUntilSatisfied());
}
const char kPageHtml[] = R"(
<title>Loaded</title>
<body>
<script>
(() => {
const wbn_url = new URL('./web_bundle.wbn', location.href).toString();
const redirect_js_url =
new URL('./redirect.js', location.href).toString();
const redirected_js_url =
new URL('./redirected.js', location.href).toString();
const redirect_to_unlisted_js_url =
new URL('./redirect_to_unlisted.js', location.href).toString();
const redirect_to_server =
new URL('./redirect_to_server.js', location.href).toString();
const script = document.createElement('script');
script.type = 'webbundle';
script.textContent = JSON.stringify({
'source': wbn_url,
'resources': [redirect_js_url, redirected_js_url,
redirect_to_unlisted_js_url, redirect_to_server]
});
document.body.appendChild(script);
})();
</script>
</body>
)";
std::string web_bundle;
RegisterWebBundleRequestHandler("/web_bundle.wbn", &web_bundle);
RegisterRequestHandler("/test.html", "text/html", kPageHtml);
RegisterRequestHandler("/redirect_to_server.js", "application/javascript",
"document.title = 'redirect_to_server';");
ASSERT_TRUE(StartEmbeddedTestServer());
// Create a web bundle.
GURL redirect_js_url = embedded_test_server()->GetURL("/redirect.js");
GURL redirected_js_url = embedded_test_server()->GetURL("/redirected.js");
GURL redirect_to_unlisted_js_url =
embedded_test_server()->GetURL("/redirect_to_unlisted.js");
GURL redirected_to_unlisted_js_url =
embedded_test_server()->GetURL("/redirected_to_unlisted.js");
GURL redirect_to_server_js_url =
embedded_test_server()->GetURL("/redirect_to_server.js");
web_package::WebBundleBuilder builder;
builder.AddExchange(
redirect_js_url,
{{":status", "200"}, {"content-type", "application/javascript"}},
"document.title = 'redirect';");
builder.AddExchange(
redirected_js_url,
{{":status", "200"}, {"content-type", "application/javascript"}},
"document.title = 'redirected';");
builder.AddExchange(
redirect_to_unlisted_js_url,
{{":status", "200"}, {"content-type", "application/javascript"}},
"document.title = 'redirect_to_unlisted';");
builder.AddExchange(
redirected_to_unlisted_js_url,
{{":status", "200"}, {"content-type", "application/javascript"}},
"document.title = 'redirected_to_unlisted';");
builder.AddExchange(
redirect_to_server_js_url,
{{":status", "200"}, {"content-type", "application/javascript"}},
"document.title = 'redirect_to_server';");
std::vector<uint8_t> bundle = builder.CreateBundle();
web_bundle = std::string(bundle.begin(), bundle.end());
GURL page_url = embedded_test_server()->GetURL("/test.html");
content::WebContents* web_contents =
browser()->tab_strip_model()->GetActiveWebContents();
ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), page_url));
EXPECT_EQ(page_url, web_contents->GetLastCommittedURL());
{
std::u16string expected_title = u"redirected";
content::TitleWatcher title_watcher(web_contents, expected_title);
EXPECT_TRUE(TryLoadScript("redirect.js"));
EXPECT_EQ(expected_title, title_watcher.WaitAndGetTitle());
}
{
// In the current implementation, extensions can redirect the request to
// the other resource in the web bundle even if the resource is not listed
// in the resources attribute.
std::u16string expected_title = u"redirected_to_unlisted";
content::TitleWatcher title_watcher(web_contents, expected_title);
EXPECT_TRUE(TryLoadScript("redirect_to_unlisted.js"));
EXPECT_EQ(expected_title, title_watcher.WaitAndGetTitle());
}
// In the current implementation, extensions can't redirect the request to
// outside the web bundle.
EXPECT_FALSE(TryLoadScript("redirect_to_server.js"));
}
// Ensure that request to Subresource WebBundle fails if it is redirected by web
// request API.
IN_PROC_BROWSER_TEST_P(SubresourceWebBundlesWebRequestApiTest,
WebBundleRequestRedirected) {
// Create an extension that redirects "redirect.wbn" to "redirected.wbn".
TestExtensionDir test_dir;
test_dir.WriteManifest(R"({
"name": "Web Request Subresource Web Bundles Test",
"manifest_version": 2,
"version": "0.1",
"background": { "scripts": ["background.js"], "persistent": true },
"permissions": ["<all_urls>", "webRequest", "webRequestBlocking"]
})");
std::string opt_extra_info_spec = "'blocking'";
if (GetExtraInfoSpec() == ExtraInfoSpec::kExtraHeaders) {
opt_extra_info_spec += ", 'extraHeaders'";
}
test_dir.WriteFile(FILE_PATH_LITERAL("background.js"),
base::StringPrintf(R"(
chrome.webRequest.onBeforeRequest.addListener(function(details) {
if (!details.url.includes('redirect.wbn'))
return;
const redirectUrl =
details.url.replace('redirect.wbn', 'redirected.wbn');
return {redirectUrl};
}, {urls: ['<all_urls>']}, [%s]);
chrome.test.sendMessage('ready');
)",
opt_extra_info_spec.c_str()));
const Extension* extension = nullptr;
{
ExtensionTestMessageListener listener("ready");
extension = LoadExtension(test_dir.UnpackedPath());
ASSERT_TRUE(extension);
EXPECT_TRUE(listener.WaitUntilSatisfied());
}
std::string web_bundle;
RegisterWebBundleRequestHandler("/redirect.wbn", &web_bundle);
RegisterWebBundleRequestHandler("/redirected.wbn", &web_bundle);
ASSERT_TRUE(StartEmbeddedTestServer());
// Create a web bundle.
std::string js_url_str = embedded_test_server()->GetURL("/script.js").spec();
web_package::WebBundleBuilder builder;
builder.AddExchange(
js_url_str,
{{":status", "200"}, {"content-type", "application/javascript"}},
"document.title = 'script loaded';");
std::vector<uint8_t> bundle = builder.CreateBundle();
web_bundle = std::string(bundle.begin(), bundle.end());
ASSERT_TRUE(ui_test_utils::NavigateToURL(
browser(), embedded_test_server()->GetURL("/empty.html")));
// In the current implementation, extensions can't redirect requests to
// Subresource WebBundles.
EXPECT_FALSE(TryLoadBundle("redirect.wbn", js_url_str));
// Without redirection, bundle load should succeed.
EXPECT_TRUE(TryLoadBundle("redirected.wbn", js_url_str));
}
// Ensure web request listener can intercept requests for web bundles with the
// resource type "webbundle".
IN_PROC_BROWSER_TEST_P(SubresourceWebBundlesWebRequestApiTest,
WebBundleRequestCanceledWithResourceType) {
// Create an extension that cancels 'webbundle' resource type request in
// chrome.webRequest.onBeforeRequest listener.
TestExtensionDir test_dir;
test_dir.WriteManifest(R"({
"name": "Web Request Subresource Web Bundles Test",
"manifest_version": 2,
"version": "0.1",
"background": { "scripts": ["background.js"], "persistent": true },
"permissions": ["<all_urls>", "webRequest", "webRequestBlocking"]
})");
std::string opt_extra_info_spec = "'blocking'";
if (GetExtraInfoSpec() == ExtraInfoSpec::kExtraHeaders) {
opt_extra_info_spec += ", 'extraHeaders'";
}
test_dir.WriteFile(FILE_PATH_LITERAL("background.js"),
base::StringPrintf(R"(
self.numOnBeforeRequestCalled = 0;
self.unexpectedRequests = [];
chrome.webRequest.onBeforeRequest.addListener(function(details) {
self.numOnBeforeRequestCalled++;
if (details.type != 'webbundle') {
self.unexpectedRequests.push(details);
}
return {cancel: true};
}, {urls: ['<all_urls>'], types: ['webbundle']}, [%s]);
chrome.test.sendMessage('ready');
)",
opt_extra_info_spec.c_str()));
const Extension* extension = nullptr;
{
ExtensionTestMessageListener listener("ready");
extension = LoadExtension(test_dir.UnpackedPath());
ASSERT_TRUE(extension);
EXPECT_TRUE(listener.WaitUntilSatisfied());
}
std::string web_bundle;
RegisterWebBundleRequestHandler("/web_bundle.wbn", &web_bundle);
std::string page_html = R"(
<title>Page loaded</title>
<body>
<script>
(() => {
const script = document.createElement('script');
script.type = 'webbundle';
script.textContent = JSON.stringify({
'source': 'web_bundle.wbn',
'resources': ['cancel.js']
});
script.addEventListener('error', () => {
document.title = 'web_bundle.wbn loading canceled';
});
script.addEventListener('load', () => {
document.title = 'web_bundle.wbn loaded';
});
document.body.appendChild(script);
})();
</script>
</body>
)";
RegisterRequestHandler("/test.html", "text/html", page_html);
std::string pass_js = "document.title = 'pass.js loaded';";
RegisterRequestHandler("/pass.js", "application/javascript", pass_js);
ASSERT_TRUE(StartEmbeddedTestServer());
// Create a web bundle.
web_package::WebBundleBuilder builder;
GURL cancel_js_url = embedded_test_server()->GetURL("/cancel.js");
builder.AddExchange(
cancel_js_url,
{{":status", "200"}, {"content-type", "application/javascript"}},
"document.title = 'cancel.js loaded';");
std::vector<uint8_t> bundle = builder.CreateBundle();
web_bundle = std::string(bundle.begin(), bundle.end());
GURL page_url = embedded_test_server()->GetURL("/test.html");
content::WebContents* web_contents =
browser()->tab_strip_model()->GetActiveWebContents();
ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), page_url));
EXPECT_EQ(page_url, web_contents->GetLastCommittedURL());
std::u16string expected_title1 = u"web_bundle.wbn loading canceled";
content::TitleWatcher title_watcher1(web_contents, expected_title1);
title_watcher1.AlsoWaitForTitle(u"web_bundle.wbn loaded");
// Check that the request for web_bundle.wbn was correctly canceled.
EXPECT_EQ(expected_title1, title_watcher1.WaitAndGetTitle());
// Check that the onBeforeRequest listener is called for the 'webbundle'
// resource type request.
EXPECT_EQ(1, GetCountFromBackgroundScript(extension, profile(),
"self.numOnBeforeRequestCalled"));
static constexpr char kScript[] =
"chrome.test.sendScriptResult(JSON.stringify(self.unexpectedRequests));";
EXPECT_EQ("[]",
ExecuteScriptAndReturnString(extension->id(), profile(), kScript));
// Try 'script' resource type request to check that the onBeforeRequest
// listener is invoked only for a 'webbundle' resource type request.
std::u16string expected_title2 = u"pass.js loaded";
content::TitleWatcher title_watcher2(web_contents, expected_title2);
EXPECT_TRUE(TryLoadScript("pass.js"));
// Check that the pass.js was correctly loaded.
EXPECT_EQ(expected_title2, title_watcher2.WaitAndGetTitle());
// Check that the onBeforeRequest listener is not called for the 'script'
// resource type request.
EXPECT_EQ(1, GetCountFromBackgroundScript(extension, profile(),
"self.numOnBeforeRequestCalled"));
EXPECT_EQ("[]",
ExecuteScriptAndReturnString(extension->id(), profile(), kScript));
}
// TODO(crbug.com/40130781) When we implement variant matching of subresource
// web bundles, we should add test for request header modification.
enum class RedirectType {
kOnBeforeRequest,
kOnHeadersReceived,
};
struct RITestParams {
RedirectType redirect_type;
ContextType context_type;
};
class RedirectInfoWebRequestApiTest
: public testing::WithParamInterface<RITestParams>,
public ExtensionApiTest {
public:
RedirectInfoWebRequestApiTest() : ExtensionApiTest(GetParam().context_type) {
// TODO(crbug.com/40248833): Use HTTPS URLs in tests to avoid having to
// disable this feature.
feature_list_.InitAndDisableFeature(features::kHttpsUpgrades);
}
~RedirectInfoWebRequestApiTest() override = default;
RedirectInfoWebRequestApiTest(const RedirectInfoWebRequestApiTest&) = delete;
RedirectInfoWebRequestApiTest& operator=(
const RedirectInfoWebRequestApiTest&) = delete;
void SetUpOnMainThread() override {
ExtensionApiTest::SetUpOnMainThread();
host_resolver()->AddRule("*", "127.0.0.1");
embedded_test_server()->ServeFilesFromSourceDirectory("content/test/data");
ASSERT_TRUE(StartEmbeddedTestServer());
}
void InstallRequestRedirectingExtension(const std::string& resource_type) {
TestExtensionDir test_dir;
test_dir.WriteManifest(R"({
"name": "Simple Redirect",
"manifest_version": 2,
"version": "0.1",
"background": { "scripts": ["background.js"], "persistent": true },
"permissions": ["<all_urls>", "webRequest", "webRequestBlocking"]
})");
test_dir.WriteFile(FILE_PATH_LITERAL("background.js"),
base::StringPrintf(R"(
chrome.webRequest.%s.addListener(function(details) {
if (details.type == '%s' &&
details.url.includes('hello.html')) {
var redirectUrl =
details.url.replace('original.test', 'redirected.test');
return {redirectUrl: redirectUrl};
}
}, {urls: ['*://original.test/*']}, ['blocking']);
chrome.test.sendMessage('ready');
)",
GetParam().redirect_type ==
RedirectType::kOnBeforeRequest
? "onBeforeRequest"
: "onHeadersReceived",
resource_type.c_str()));
ExtensionTestMessageListener listener("ready");
const Extension* extension = LoadExtension(test_dir.UnpackedPath());
ASSERT_TRUE(extension);
EXPECT_TRUE(listener.WaitUntilSatisfied());
}
private:
TestExtensionDir test_dir_;
base::test::ScopedFeatureList feature_list_;
};
INSTANTIATE_TEST_SUITE_P(
PersistentBackgroundOnBeforeRequest,
RedirectInfoWebRequestApiTest,
::testing::Values(RITestParams(RedirectType::kOnBeforeRequest,
ContextType::kPersistentBackground)));
INSTANTIATE_TEST_SUITE_P(
PersistentBackgroundOnHeadersReceived,
RedirectInfoWebRequestApiTest,
::testing::Values(RITestParams(RedirectType::kOnHeadersReceived,
ContextType::kPersistentBackground)));
// These tests use webRequestBlocking and/or declarativeWebRequest.
// See crbug.com/332512510.
INSTANTIATE_TEST_SUITE_P(
ServiceWorkerOnBeforeRequest,
RedirectInfoWebRequestApiTest,
::testing::Values(RITestParams(RedirectType::kOnBeforeRequest,
ContextType::kServiceWorkerMV2)));
INSTANTIATE_TEST_SUITE_P(
ServiceWorkerOnHeadersReceived,
RedirectInfoWebRequestApiTest,
::testing::Values(RITestParams(RedirectType::kOnHeadersReceived,
ContextType::kServiceWorkerMV2)));
// Test that a main frame request redirected by an extension has the correct
// site_for_cookies and network_isolation_key parameters.
IN_PROC_BROWSER_TEST_P(RedirectInfoWebRequestApiTest,
VerifyRedirectInfoMainFrame) {
InstallRequestRedirectingExtension("main_frame");
content::URLLoaderMonitor monitor;
// Navigate to the URL that should be redirected, and check that the extension
// redirects it.
GURL url = embedded_test_server()->GetURL("original.test", "/hello.html");
EXPECT_TRUE(ui_test_utils::NavigateToURL(browser(), url));
content::WebContents* web_contents =
browser()->tab_strip_model()->GetActiveWebContents();
ASSERT_TRUE(web_contents);
GURL redirected_url =
embedded_test_server()->GetURL("redirected.test", "/hello.html");
EXPECT_EQ(redirected_url, web_contents->GetLastCommittedURL());
// Check the parameters passed to the URLLoaderFactory.
std::optional<network::ResourceRequest> resource_request =
monitor.GetRequestInfo(redirected_url);
ASSERT_TRUE(resource_request.has_value());
EXPECT_TRUE(resource_request->site_for_cookies.IsFirstParty(redirected_url));
ASSERT_TRUE(resource_request->trusted_params);
url::Origin redirected_origin = url::Origin::Create(redirected_url);
EXPECT_TRUE(
resource_request->trusted_params->isolation_info.IsEqualForTesting(
net::IsolationInfo::Create(
net::IsolationInfo::RequestType::kMainFrame, redirected_origin,
redirected_origin,
net::SiteForCookies::FromOrigin(redirected_origin))));
}
// Test that a sub frame request redirected by an extension has the correct
// site_for_cookies and network_isolation_key parameters.
IN_PROC_BROWSER_TEST_P(RedirectInfoWebRequestApiTest,
VerifyBeforeRequestRedirectInfoSubFrame) {
InstallRequestRedirectingExtension("sub_frame");
content::URLLoaderMonitor monitor;
// Navigate to page with an iframe that should be redirected, and check that
// the extension redirects it.
GURL original_iframed_url =
embedded_test_server()->GetURL("original.test", "/hello.html");
GURL page_with_iframe_url = embedded_test_server()->GetURL(
"somewhere-else.test",
net::test_server::GetFilePathWithReplacements(
"/page_with_iframe.html",
base::StringPairs{
{"title1.html", original_iframed_url.spec().c_str()}}));
EXPECT_TRUE(ui_test_utils::NavigateToURL(browser(), page_with_iframe_url));
content::WebContents* web_contents =
browser()->tab_strip_model()->GetActiveWebContents();
ASSERT_TRUE(web_contents);
EXPECT_EQ(page_with_iframe_url, web_contents->GetLastCommittedURL());
content::RenderFrameHostWrapper child_frame(
ChildFrameAt(web_contents->GetPrimaryMainFrame(), 0));
ASSERT_TRUE(child_frame);
GURL redirected_url =
embedded_test_server()->GetURL("redirected.test", "/hello.html");
ASSERT_EQ(redirected_url, child_frame->GetLastCommittedURL());
// Check the parameters passed to the URLLoaderFactory.
std::optional<network::ResourceRequest> resource_request =
monitor.GetRequestInfo(redirected_url);
ASSERT_TRUE(resource_request.has_value());
EXPECT_TRUE(
resource_request->site_for_cookies.IsFirstParty(page_with_iframe_url));
EXPECT_FALSE(resource_request->site_for_cookies.IsFirstParty(redirected_url));
ASSERT_TRUE(resource_request->trusted_params);
url::Origin top_level_origin = url::Origin::Create(page_with_iframe_url);
url::Origin redirected_origin = url::Origin::Create(redirected_url);
EXPECT_TRUE(
resource_request->trusted_params->isolation_info.IsEqualForTesting(
net::IsolationInfo::Create(
net::IsolationInfo::RequestType::kSubFrame, top_level_origin,
redirected_origin,
net::SiteForCookies::FromOrigin(top_level_origin))));
}
// Regression test for crbug.com/1510422 to validate that redirection to an
// invalid URL by extension does not crash the browser.
IN_PROC_BROWSER_TEST_P(RedirectInfoWebRequestApiTest,
VerifyInvalidUrlRedirection) {
TestExtensionDir test_dir;
static constexpr char kInvalidUrl[] = "https://www.invalid.[ss]com/";
test_dir.WriteManifest(R"({
"name": "Simple Redirect",
"manifest_version": 2,
"version": "0.1",
"background": { "scripts": ["background.js"], "persistent": true },
"permissions": ["<all_urls>", "webRequest", "webRequestBlocking"]
})");
test_dir.WriteFile(FILE_PATH_LITERAL("background.js"),
base::StringPrintf(R"(
chrome.webRequest.onBeforeRequest.addListener(function(details) {
if (details.url.includes('hello.html')) {
var redirectUrl = '%s';
return {redirectUrl: redirectUrl};
}
}, {urls: ['*://redirect.test/*']}, ['blocking']);
chrome.test.sendMessage('ready');
)",
kInvalidUrl));
// Since we can't catch the error in the extension's JS, we instead listen to
// the error come into the error console.
ErrorConsoleTestObserver error_observer(2u, profile());
error_observer.EnableErrorCollection();
const Extension* extension = LoadExtension(test_dir.UnpackedPath());
ASSERT_TRUE(extension);
// Navigate to the URL that should be redirected, and check that the extension
// navigation happens successfully.
content::TestNavigationObserver navigation_observer(
browser()->tab_strip_model()->GetActiveWebContents());
GURL url = embedded_test_server()->GetURL("redirect.test", "/hello.html");
EXPECT_TRUE(ui_test_utils::NavigateToURL(browser(), url));
EXPECT_TRUE(navigation_observer.last_navigation_succeeded());
error_observer.WaitForErrors();
const ErrorList& errors =
ErrorConsole::Get(profile())->GetErrorsForExtension(extension->id());
ASSERT_EQ(2u, errors.size());
EXPECT_EQ(
base::ASCIIToUTF16(base::StringPrintf(
"Unchecked runtime.lastError: redirectUrl '%s' is not a valid URL.",
kInvalidUrl)),
errors[1]->message());
}
class ProxyCORSWebRequestApiTest
: public ExtensionApiTest,
public testing::WithParamInterface<ContextType> {
public:
ProxyCORSWebRequestApiTest() : ExtensionApiTest(GetParam()) {}
~ProxyCORSWebRequestApiTest() override = default;
ProxyCORSWebRequestApiTest(const ProxyCORSWebRequestApiTest&) = delete;
ProxyCORSWebRequestApiTest& operator=(const ProxyCORSWebRequestApiTest&) =
delete;
protected:
void SetUpOnMainThread() override {
ExtensionApiTest::SetUpOnMainThread();
host_resolver()->AddRule("*", "127.0.0.1");
ASSERT_TRUE(StartEmbeddedTestServer());
proxy_cors_server_.RegisterRequestHandler(base::BindRepeating(
&ProxyCORSWebRequestApiTest::HandleProxiedCORSRequest,
base::Unretained(this)));
ASSERT_TRUE(proxy_cors_server_.Start());
PrefService* pref_service = browser()->profile()->GetPrefs();
pref_service->SetDict(proxy_config::prefs::kProxy,
ProxyConfigDictionary::CreateFixedServers(
proxy_cors_server_.host_port_pair().ToString(),
"accounts.google.com"));
// Flush the proxy configuration change to avoid any races.
ProfileNetworkContextServiceFactory::GetForContext(browser()->profile())
->FlushProxyConfigMonitorForTesting();
profile()->GetDefaultStoragePartition()->FlushNetworkInterfaceForTesting();
}
std::unique_ptr<net::test_server::HttpResponse> HandleProxiedCORSRequest(
const net::test_server::HttpRequest& request) {
std::string request_url;
// Request url will be replaced by host:port pair of embedded proxy server
// in HttpRequest, extract requested url from request line instead.
std::vector<std::string> request_lines =
base::SplitString(request.all_headers, "\r\n", base::TRIM_WHITESPACE,
base::SPLIT_WANT_NONEMPTY);
if (!request_lines.empty()) {
std::vector<std::string> request_line =
base::SplitString(request_lines[0], " ", base::TRIM_WHITESPACE,
base::SPLIT_WANT_NONEMPTY);
if (request_line.size() > 1) {
request_url = request_line[1];
}
}
if (request_url != kCORSUrl) {
return nullptr;
}
// Handle request as proxy server.
const auto proxy_auth = request.headers.find("Proxy-Authorization");
std::string auth;
if (proxy_auth != request.headers.end()) {
auth = proxy_auth->second;
const std::string auth_method_prefix = "Basic ";
const auto prefix_pos = auth.find(auth_method_prefix);
EXPECT_EQ(0U, prefix_pos);
EXPECT_GT(auth.size(), auth_method_prefix.size());
if (prefix_pos == 0U && auth.size() > auth_method_prefix.size()) {
auth = auth.substr(auth_method_prefix.size());
EXPECT_TRUE(base::Base64Decode(auth, &auth));
} else {
auth.clear();
}
}
if (auth != base::StringPrintf("%s:%s", kCORSProxyUser, kCORSProxyPass)) {
std::unique_ptr<net::test_server::BasicHttpResponse> response =
std::make_unique<net::test_server::BasicHttpResponse>();
response->AddCustomHeader("Proxy-Authenticate",
"Basic realm=\"TestRealm\"");
response->set_code(net::HTTP_PROXY_AUTHENTICATION_REQUIRED);
return response;
}
// Handle request as cors server.
if (request.method == net::test_server::METHOD_OPTIONS) {
const auto preflight_method =
request.headers.find("Access-Control-Request-Method");
const auto preflight_header =
request.headers.find("Access-Control-Request-Headers");
if (preflight_method == request.headers.end() ||
preflight_header == request.headers.end()) {
ADD_FAILURE() << "Expected Access-Control-Request-* headers were not "
"found in preflight request";
std::unique_ptr<net::test_server::BasicHttpResponse> response =
std::make_unique<net::test_server::BasicHttpResponse>();
response->set_code(net::HTTP_BAD_REQUEST);
return response;
}
EXPECT_EQ("GET", preflight_method->second);
EXPECT_EQ(kCustomPreflightHeader, preflight_header->second);
std::unique_ptr<net::test_server::BasicHttpResponse> response =
std::make_unique<net::test_server::BasicHttpResponse>();
response->AddCustomHeader("Access-Control-Allow-Origin", "*");
response->AddCustomHeader("Access-Control-Allow-Methods", "GET");
response->AddCustomHeader("Access-Control-Allow-Headers",
kCustomPreflightHeader);
response->set_code(net::HTTP_NO_CONTENT);
if (preflight_waiter_) {
preflight_waiter_->Quit();
}
return response;
}
EXPECT_EQ(net::test_server::METHOD_GET, request.method);
std::unique_ptr<net::test_server::BasicHttpResponse> response =
std::make_unique<net::test_server::BasicHttpResponse>();
response->AddCustomHeader("Access-Control-Allow-Origin", "*");
response->set_content_type("text/plain");
response->set_content("PASS");
response->set_code(net::HTTP_OK);
return response;
}
// Executes a CORS preflight request on the main frame with a custom preflight
// header.
void ExecuteCorsPreflightedRequest() {
content::WebContents* web_contents =
browser()->tab_strip_model()->GetActiveWebContents();
ASSERT_TRUE(web_contents);
static constexpr char kCORSPreflightedRequest[] = R"(
var xhr = new XMLHttpRequest();
xhr.open('GET', '%s');
xhr.setRequestHeader('%s', 'testvalue');
new Promise(resolve => {
xhr.onload = () => { resolve(true); };
xhr.onerror = () => { resolve(false); };
xhr.send();
});
)";
ExecuteScriptAsyncWithoutUserGesture(
web_contents->GetPrimaryMainFrame(),
base::StringPrintf(kCORSPreflightedRequest, kCORSUrl,
kCustomPreflightHeader));
}
void WaitForPreflightResponse() {
DCHECK(preflight_waiter_);
preflight_waiter_->Run();
preflight_waiter_.reset();
}
// A waiter for a preflight request to complete.
std::unique_ptr<base::RunLoop> preflight_waiter_;
private:
net::EmbeddedTestServer proxy_cors_server_;
};
using ProxyCORSDeclarativeNetRequestApiTest = ProxyCORSWebRequestApiTest;
INSTANTIATE_TEST_SUITE_P(PersistentBackground,
ProxyCORSWebRequestApiTest,
::testing::Values(ContextType::kPersistentBackground));
INSTANTIATE_TEST_SUITE_P(ServiceWorker,
ProxyCORSWebRequestApiTest,
::testing::Values(ContextType::kServiceWorker));
INSTANTIATE_TEST_SUITE_P(/* No prefix */,
ProxyCORSDeclarativeNetRequestApiTest,
::testing::Values(ContextType::kFromManifest));
// Regression test for crbug.com/1212625
// Test that CORS preflight request which requires proxy auth completes
// successfully instead of being cancelled after proxy auth required response.
// This case requires an extension with a webRequest extraHeaders listener that
// matches the preflight request.
IN_PROC_BROWSER_TEST_P(ProxyCORSWebRequestApiTest,
PreflightCompletesSuccessfully) {
ExtensionTestMessageListener ready_listener("ready");
const Extension* extension =
LoadExtension(test_data_dir_.AppendASCII("webrequest_cors_preflight"));
ASSERT_TRUE(extension) << message_;
ASSERT_TRUE(ready_listener.WaitUntilSatisfied());
ASSERT_TRUE(ui_test_utils::NavigateToURL(
browser(), embedded_test_server()->GetURL("/empty.html")));
ExtensionTestMessageListener preflight_listener("cors-preflight-succeeded");
ExecuteCorsPreflightedRequest();
ASSERT_TRUE(base::test::RunUntil(
[]() { return LoginHandler::GetAllLoginHandlersForTest().size() == 1; }));
LoginHandler::GetAllLoginHandlersForTest().front()->SetAuth(
base::ASCIIToUTF16(std::string(kCORSProxyUser)),
base::ASCIIToUTF16(std::string(kCORSProxyPass)));
EXPECT_TRUE(preflight_listener.WaitUntilSatisfied());
EXPECT_EQ(1, GetCountFromBackgroundScript(
extension, profile(), "self.preflightHeadersReceivedCount"));
EXPECT_EQ(
1, GetCountFromBackgroundScript(extension, profile(),
"self.preflightProxyAuthRequiredCount"));
EXPECT_EQ(1, GetCountFromBackgroundScript(
extension, profile(), "self.preflightResponseStartedCount"));
EXPECT_EQ(1, GetCountFromBackgroundScript(
extension, profile(),
"self.preflightResponseStartedSuccessfullyCount"));
}
// Regression for crbug.com/369836605
// Similar to the above test, except the "listener" in this case is a DNR rule
// that would require extraHeaders information but does NOT match on the
// preflight request.
IN_PROC_BROWSER_TEST_P(ProxyCORSDeclarativeNetRequestApiTest,
PreflightCompletesWithNonMatchingDNRRule) {
static constexpr char kManifest[] = R"({
"name": "Simple DNR ModifyHeaders",
"version": "0.1",
"manifest_version": 3,
"permissions": [ "declarativeNetRequest" ],
"host_permissions": [ "https://nomatch.com/*" ],
"declarative_net_request" : {
"rule_resources" : [{
"id": "ruleset",
"enabled": true,
"path": "rules.json"
}]
}
})";
static constexpr char kRules[] = R"([{
"id": 1,
"action": {
"requestHeaders": [
{
"header": "referer",
"operation": "remove"
}
],
"type": "modifyHeaders"
},
"condition": {
"urlFilter": "nomatch.com",
"resourceTypes": ["main_frame"]
}
}])";
// Load an extension with one declarativeNetRequest modifyHeaders rule that
// removes the referer header but will not match any requests from this test.
TestExtensionDir test_dir;
test_dir.WriteManifest(kManifest);
test_dir.WriteFile(FILE_PATH_LITERAL("rules.json"), kRules);
const Extension* extension = LoadExtension(test_dir.UnpackedPath());
ASSERT_TRUE(extension);
preflight_waiter_ = std::make_unique<base::RunLoop>();
ASSERT_TRUE(ui_test_utils::NavigateToURL(
browser(), embedded_test_server()->GetURL("/empty.html")));
ExecuteCorsPreflightedRequest();
ASSERT_TRUE(base::test::RunUntil(
[]() { return LoginHandler::GetAllLoginHandlersForTest().size() == 1; }));
LoginHandler::GetAllLoginHandlersForTest().front()->SetAuth(
base::ASCIIToUTF16(std::string(kCORSProxyUser)),
base::ASCIIToUTF16(std::string(kCORSProxyPass)));
// Wait for the proxy server to return a response for the preflight request
// after auth is provided. If the preflight request was cancelled, then this
// test will not finish.
WaitForPreflightResponse();
}
class ExtensionWebRequestApiFencedFrameTest
: public ExtensionWebRequestApiTest {
protected:
ExtensionWebRequestApiFencedFrameTest() {
feature_list_.InitWithFeaturesAndParameters(
{{blink::features::kFencedFrames, {}},
{blink::features::kFencedFramesAPIChanges, {}},
{blink::features::kFencedFramesDefaultMode, {}},
{features::kPrivacySandboxAdsAPIsOverride, {}},
{blink::features::kFencedFramesLocalUnpartitionedDataAccess, {}}},
{/* disabled_features */});
// Fenced frames are only allowed in secure contexts.
UseHttpsTestServer();
}
~ExtensionWebRequestApiFencedFrameTest() override = default;
private:
base::test::ScopedFeatureList feature_list_;
};
IN_PROC_BROWSER_TEST_F(ExtensionWebRequestApiFencedFrameTest, Load) {
ASSERT_TRUE(StartEmbeddedTestServer());
ASSERT_TRUE(RunExtensionTest("webrequest",
{.extension_url = "test_fenced_frames.html"}))
<< message_;
}
IN_PROC_BROWSER_TEST_F(ExtensionWebRequestApiFencedFrameTest,
DeclarativeSendMessage) {
ASSERT_TRUE(StartEmbeddedTestServer());
ASSERT_TRUE(RunExtensionTest(
"webrequest", {.extension_url = "test_fenced_frames_send_message.html"}))
<< message_;
}
IN_PROC_BROWSER_TEST_F(ExtensionWebRequestApiFencedFrameTest,
NetworkRevocation) {
ASSERT_TRUE(StartEmbeddedTestServer());
ASSERT_TRUE(RunExtensionTest(
"webrequest",
{.extension_url = "test_fenced_frames_network_revocation.html"}))
<< message_;
}
class ExtensionWebRequestApiPrerenderingTest
: public ExtensionWebRequestApiTest {
protected:
ExtensionWebRequestApiPrerenderingTest() = default;
~ExtensionWebRequestApiPrerenderingTest() override = default;
private:
content::test::ScopedPrerenderFeatureList prerender_feature_list_;
};
IN_PROC_BROWSER_TEST_F(ExtensionWebRequestApiPrerenderingTest, Load) {
ASSERT_TRUE(StartEmbeddedTestServer());
ASSERT_TRUE(RunExtensionTest("webrequest",
{.extension_url = "test_prerendering.html"}))
<< message_;
}
IN_PROC_BROWSER_TEST_F(ExtensionWebRequestApiPrerenderingTest, LoadIntoNewTab) {
ASSERT_TRUE(StartEmbeddedTestServer());
ASSERT_TRUE(RunExtensionTest(
"webrequest", {.extension_url = "test_prerendering_into_new_tab.html"}))
<< message_;
}
// A clunky test suite class to allow for waiting for a message to be sent from
// the extension's background context when it starts up. We need this because
// we don't currently have a good way of waiting for a service worker context to
// be fully initialized.
class WebRequestPersistentListenersTest
: public ExtensionWebRequestApiTestWithContextType {
public:
WebRequestPersistentListenersTest()
// Note: Set the listener before triggering the parent
// SetUpOnMainThread to ensure it happens before extensions start
// loading.
: test_listener_(
std::make_unique<ExtensionTestMessageListener>("ready")) {}
~WebRequestPersistentListenersTest() override = default;
void TearDownOnMainThread() override {
test_listener_.reset();
ExtensionWebRequestApiTestWithContextType::TearDownOnMainThread();
}
void WaitForReadyMessage() {
EXPECT_TRUE(test_listener_->WaitUntilSatisfied());
}
private:
std::unique_ptr<ExtensionTestMessageListener> test_listener_;
};
#endif // !BUILDFLAG(IS_ANDROID)
namespace {
constexpr char kGetNumRequests[] =
R"((async function() {
// Wait for any pending storage writes to complete.
await flushStorage();
chrome.storage.local.get(
{requestCount: -1},
(result) => {
chrome.test.sendScriptResult(result.requestCount);
});
})();)";
} // namespace
#if !BUILDFLAG(IS_ANDROID)
// Tests that webRequest listeners are persistent across browser restarts.
IN_PROC_BROWSER_TEST_P(WebRequestPersistentListenersTest,
PRE_TestListenersArePersistent) {
// Load an extension that listens for webRequest events.
ASSERT_TRUE(StartEmbeddedTestServer());
const Extension* extension =
LoadExtension(test_data_dir_.AppendASCII("webrequest_persistent"));
ASSERT_TRUE(extension);
// Navigate to example.com (a site the extension has access to).
ASSERT_TRUE(ui_test_utils::NavigateToURL(
browser(),
embedded_test_server()->GetURL("example.com", "/simple.html")));
// Validate that we have a single request seen by the extension.
base::Value request_count = BackgroundScriptExecutor::ExecuteScript(
profile(), extension->id(), kGetNumRequests,
BackgroundScriptExecutor::ResultCapture::kSendScriptResult);
ASSERT_TRUE(request_count.is_int());
EXPECT_EQ(1, request_count.GetInt());
}
IN_PROC_BROWSER_TEST_P(WebRequestPersistentListenersTest,
TestListenersArePersistent) {
// Find the installed extension and wait for it to fully load.
ASSERT_TRUE(StartEmbeddedTestServer());
const Extension* extension = nullptr;
for (const auto& candidate : extension_registry()->enabled_extensions()) {
if (candidate->name() == "Web Request Persistence") {
extension = candidate.get();
break;
}
}
ASSERT_TRUE(extension);
WaitForExtensionViewsToLoad();
WaitForReadyMessage();
// Navigate once more to example.com.
ASSERT_TRUE(ui_test_utils::NavigateToURL(
browser(),
embedded_test_server()->GetURL("example.com", "/simple.html")));
// We should now have two records seen by the extension.
base::Value request_count = BackgroundScriptExecutor::ExecuteScript(
profile(), extension->id(), kGetNumRequests,
BackgroundScriptExecutor::ResultCapture::kSendScriptResult);
ASSERT_TRUE(request_count.is_int());
EXPECT_EQ(2, request_count.GetInt());
}
INSTANTIATE_TEST_SUITE_P(
PersistentBackground,
WebRequestPersistentListenersTest,
::testing::Values(
std::make_pair(
ContextType::kPersistentBackground,
BackgroundResourceFetchTestCase::kBackgroundResourceFetchEnabled),
std::make_pair(
ContextType::kPersistentBackground,
BackgroundResourceFetchTestCase::kBackgroundResourceFetchDisabled)),
ExtensionWebRequestApiTestWithContextType::PrintToStringParamName());
INSTANTIATE_TEST_SUITE_P(
ServiceWorker,
WebRequestPersistentListenersTest,
::testing::Values(
std::make_pair(
ContextType::kServiceWorker,
BackgroundResourceFetchTestCase::kBackgroundResourceFetchEnabled),
std::make_pair(
ContextType::kServiceWorker,
BackgroundResourceFetchTestCase::kBackgroundResourceFetchDisabled)),
ExtensionWebRequestApiTestWithContextType::PrintToStringParamName());
#endif // !BUILDFLAG(IS_ANDROID)
class ManifestV3WebRequestApiTest : public ExtensionWebRequestApiTest {
public:
ManifestV3WebRequestApiTest() = default;
~ManifestV3WebRequestApiTest() override = default;
#if !BUILDFLAG(IS_ANDROID)
// Loads an extension contained within `test_dir` as a policy-installed
// extension. This is useful because webRequestBlocking is restricted to
// policy-installed extensions in Manifest V3.
// This assumes the extension script will send a "ready" message once it's
// done setting up.
// TODO(crbug.com/391921314): Enable on Android when InstallExtension() is
// supported.
const Extension* LoadPolicyExtension(TestExtensionDir& test_dir) {
// We need a "ready"-style listener here because `InstallExtension()`
// doesn't automagically wait for the extension to finish setting up.
ExtensionTestMessageListener listener("ready");
// Since we may programmatically stop the worker, we also need to wait for
// the registration to be fully stored.
service_worker_test_utils::TestServiceWorkerContextObserver
registration_observer(profile());
base::FilePath packed_path = test_dir.Pack();
const Extension* extension = InstallExtension(
packed_path, 1, mojom::ManifestLocation::kExternalPolicyDownload);
EXPECT_TRUE(extension);
EXPECT_TRUE(listener.WaitUntilSatisfied());
registration_observer.WaitForRegistrationStored();
return extension;
}
#endif // !BUILDFLAG(IS_ANDROID)
WebRequestEventRouter* web_request_router() {
return WebRequestEventRouter::Get(profile());
}
std::optional<WorkerId> GetWorkerIdForExtension(
const ExtensionId& extension_id) {
std::vector<WorkerId> service_workers_for_extension =
ProcessManager::Get(profile())->GetServiceWorkersForExtension(
extension_id);
if (service_workers_for_extension.size() > 1u) {
ADD_FAILURE() << "Expected only one worker for extension: "
<< extension_id
<< " But found incorrect number of workers: "
<< service_workers_for_extension.size();
return std::nullopt;
}
return service_workers_for_extension.empty()
? std::nullopt
: std::optional<WorkerId>(service_workers_for_extension[0]);
}
};
#if !BUILDFLAG(IS_ANDROID)
// Tests a service worker-based extension intercepting requests with
// webRequestBlocking.
// TODO(crbug.com/391921314): Enable on desktop Android when InstallExtension()
// is supported (for LoadPolicyExtension).
IN_PROC_BROWSER_TEST_F(ManifestV3WebRequestApiTest, WebRequestBlocking) {
ASSERT_TRUE(StartEmbeddedTestServer());
static constexpr char kManifest[] =
R"({
"name": "MV3 WebRequest",
"version": "0.1",
"manifest_version": 3,
"permissions": ["webRequest", "webRequestBlocking"],
"host_permissions": [
"http://block.example/*",
"http://allow.example/*"
],
"background": {"service_worker": "background.js"}
})";
// An extension with a listener that cancels any requests that include
// block.example.
static constexpr char kBackgroundJs[] =
R"(chrome.webRequest.onBeforeRequest.addListener(
(details) => {
if (details.url.includes('block.example')) {
return {cancel: true}
}
return {};
},
{urls: ['<all_urls>'], types: ['main_frame']},
['blocking']);
chrome.test.sendMessage('ready');)";
TestExtensionDir test_dir;
test_dir.WriteManifest(kManifest);
test_dir.WriteFile(FILE_PATH_LITERAL("background.js"), kBackgroundJs);
const Extension* extension = LoadPolicyExtension(test_dir);
ASSERT_TRUE(extension);
content::WebContents* web_contents =
browser()->tab_strip_model()->GetActiveWebContents();
// Navigate to allow.example. This should succeed.
{
content::TestNavigationObserver nav_observer(web_contents);
EXPECT_TRUE(ui_test_utils::NavigateToURL(
browser(),
embedded_test_server()->GetURL("allow.example", "/simple.html")));
EXPECT_EQ(net::OK, nav_observer.last_net_error_code());
}
// Now, navigate to block.example. This navigation should be blocked.
{
content::TestNavigationObserver nav_observer(web_contents);
EXPECT_TRUE(ui_test_utils::NavigateToURL(
browser(),
embedded_test_server()->GetURL("block.example", "/simple.html")));
EXPECT_EQ(net::ERR_BLOCKED_BY_CLIENT, nav_observer.last_net_error_code());
}
}
// Tests an extension returning a promise from a webRequest blocking handler to
// deliver an async response. This is only available to policy-installed
// extensions.
IN_PROC_BROWSER_TEST_F(ManifestV3WebRequestApiTest,
WebRequestBlockingWithPromises_PromiseResolves) {
ASSERT_TRUE(StartEmbeddedTestServer());
static constexpr char kManifest[] =
R"({
"name": "MV3 WebRequest",
"version": "0.1",
"manifest_version": 3,
"permissions": ["webRequest", "webRequestBlocking"],
"host_permissions": [
"http://block.example/*",
"http://allow.example/*"
],
"background": {"service_worker": "background.js"}
})";
// An extension with a listener that cancels any requests that include
// block.example.
static constexpr char kBackgroundJs[] =
R"(chrome.webRequest.onBeforeRequest.addListener(
(details) => {
let result = {};
if (details.url.includes('block.example')) {
result.cancel = true;
}
return Promise.resolve(result);
},
{urls: ['<all_urls>'], types: ['main_frame']},
['blocking']);
chrome.test.sendMessage('ready');)";
TestExtensionDir test_dir;
test_dir.WriteManifest(kManifest);
test_dir.WriteFile(FILE_PATH_LITERAL("background.js"), kBackgroundJs);
const Extension* extension = LoadPolicyExtension(test_dir);
ASSERT_TRUE(extension);
content::WebContents* web_contents =
browser()->tab_strip_model()->GetActiveWebContents();
// Navigate to allow.example. This should succeed.
{
content::TestNavigationObserver nav_observer(web_contents);
EXPECT_TRUE(ui_test_utils::NavigateToURL(
browser(),
embedded_test_server()->GetURL("allow.example", "/simple.html")));
EXPECT_EQ(net::OK, nav_observer.last_net_error_code());
}
// Now, navigate to block.example. This navigation should be blocked.
{
content::TestNavigationObserver nav_observer(web_contents);
EXPECT_TRUE(ui_test_utils::NavigateToURL(
browser(),
embedded_test_server()->GetURL("block.example", "/simple.html")));
EXPECT_EQ(net::ERR_BLOCKED_BY_CLIENT, nav_observer.last_net_error_code());
}
}
// Tests an extension returning a promise that rejects from a webRequest
// blocking handler. The request should proceed.
IN_PROC_BROWSER_TEST_F(ManifestV3WebRequestApiTest,
WebRequestBlockingWithPromises_PromiseRejects) {
ASSERT_TRUE(StartEmbeddedTestServer());
static constexpr char kManifest[] =
R"({
"name": "MV3 WebRequest",
"version": "0.1",
"manifest_version": 3,
"permissions": ["webRequest", "webRequestBlocking"],
"host_permissions": [
"http://test.example/*"
],
"background": {"service_worker": "background.js"}
})";
// An extension with a listener that cancels any requests that include
// block.example.
static constexpr char kBackgroundJs[] =
R"(chrome.webRequest.onBeforeRequest.addListener(
(details) => {
return Promise.reject(new Error('Some Error'));
},
{urls: ['<all_urls>'], types: ['main_frame']},
['blocking']);
chrome.test.sendMessage('ready');)";
TestExtensionDir test_dir;
test_dir.WriteManifest(kManifest);
test_dir.WriteFile(FILE_PATH_LITERAL("background.js"), kBackgroundJs);
const Extension* extension = LoadPolicyExtension(test_dir);
ASSERT_TRUE(extension);
content::WebContents* web_contents =
browser()->tab_strip_model()->GetActiveWebContents();
ErrorConsoleTestObserver error_observer(1u, profile());
error_observer.EnableErrorCollection();
ErrorConsole::Get(profile())->SetReportingAllForExtension(extension->id(),
true);
// Navigate to test.example. The extension intercepts the request and returns
// a promise that rejects.
// This results in:
// - An error being logged in the extension context, and
// - The request proceeding.
content::TestNavigationObserver nav_observer(web_contents);
EXPECT_TRUE(ui_test_utils::NavigateToURL(
browser(),
embedded_test_server()->GetURL("test.example", "/simple.html")));
EXPECT_EQ(net::OK, nav_observer.last_net_error_code());
error_observer.WaitForErrors();
const ErrorList& errors =
ErrorConsole::Get(profile())->GetErrorsForExtension(extension->id());
ASSERT_EQ(1u, errors.size());
EXPECT_TRUE(base::StartsWith(errors[0]->message(),
u"Uncaught (in promise) Error: Some Error"))
<< errors[0]->message();
}
// Tests an extension returning a promise that never resolves from a webRequest
// blocking handler. The request should hang forever.
IN_PROC_BROWSER_TEST_F(ManifestV3WebRequestApiTest,
WebRequestBlockingWithPromises_PromiseHangs) {
ASSERT_TRUE(StartEmbeddedTestServer());
static constexpr char kManifest[] =
R"({
"name": "MV3 WebRequest",
"version": "0.1",
"manifest_version": 3,
"permissions": ["webRequest", "webRequestBlocking"],
"host_permissions": [
"http://test.example/*"
],
"background": {"service_worker": "background.js"}
})";
// An extension with a listener that cancels any requests that include
// block.example.
static constexpr char kBackgroundJs[] =
R"(chrome.webRequest.onBeforeRequest.addListener(
(details) => {
setTimeout(() => {
chrome.test.sendMessage('received event');
}, 500);
return new Promise(() => { });
},
{urls: ['<all_urls>'], types: ['main_frame']},
['blocking']);
chrome.test.sendMessage('ready');)";
TestExtensionDir test_dir;
test_dir.WriteManifest(kManifest);
test_dir.WriteFile(FILE_PATH_LITERAL("background.js"), kBackgroundJs);
const Extension* extension = LoadPolicyExtension(test_dir);
ASSERT_TRUE(extension);
content::WebContents* web_contents =
browser()->tab_strip_model()->GetActiveWebContents();
// Navigate to test.example. The extension intercepts this request, and then
// returns a promise that never resolves. This will result in the request
// hanging forever and ever, with no way for the user to do anything about
// it, possibly bricking the entire browser. (This is desired functionality
// for enterprise-installed extensions.)
// There's no good way to validate "will never resolve", but we do our best
// by waiting for an async message from the extension and validating the
// request is still in-flight.
ExtensionTestMessageListener listener("received event");
ui_test_utils::NavigateToURLWithDisposition(
browser(), embedded_test_server()->GetURL("test.example", "/simple.html"),
WindowOpenDisposition::CURRENT_TAB, ui_test_utils::BROWSER_TEST_NO_WAIT);
EXPECT_TRUE(listener.WaitUntilSatisfied());
EXPECT_TRUE(web_contents->IsLoading());
}
#endif // !BUILDFLAG(IS_ANDROID)
// Tests a service worker-based extension registering multiple webRequest events
// in multiple contexts. This ensures the subevent name logic for service worker
// extensions doesn't result in any collisions of listener IDs, similar to the
// issue found in https://crbug.com/1297276.
IN_PROC_BROWSER_TEST_F(ManifestV3WebRequestApiTest,
MultipleListenersAndContexts) {
ASSERT_TRUE(StartEmbeddedTestServer());
static constexpr char kManifest[] =
R"({
"name": "MV3 WebRequest",
"version": "0.1",
"manifest_version": 3,
"permissions": ["webRequest", "storage"],
"host_permissions": [
"http://first.example/*",
"http://second.example/*",
"http://third.example/*"
],
"background": {"service_worker": "background.js"}
})";
// The extension has two contexts: the background service worker (which
// registers two listeners) and a separate page (which also registers a
// listener). This ensures that a) service worker listeners do not conflict
// with each other and b) service worker listeners do not conflict with
// listeners registered in other contexts.
static constexpr char kBackgroundJs[] =
R"(self.firstCount = 0;
self.secondCount = 0;
function firstListener() { ++firstCount; }
function secondListener() { ++secondCount; }
chrome.webRequest.onBeforeRequest.addListener(
firstListener,
{urls: ['http://first.example/*'], types: ['main_frame']}, []);
chrome.webRequest.onBeforeRequest.addListener(
secondListener,
{urls: ['http://second.example/*'], types: ['main_frame']}, []);)";
static constexpr char kPageHtml[] =
R"(<!doctype html>
<html>
Page
<script src="page.js"></script>
</html>)";
static constexpr char kPageJs[] =
R"(self.thirdCount = 0;
function thirdListener() { ++thirdCount; }
chrome.webRequest.onBeforeRequest.addListener(
thirdListener,
{urls: ['http://third.example/*'], types: ['main_frame']}, []);)";
TestExtensionDir test_dir;
test_dir.WriteManifest(kManifest);
test_dir.WriteFile(FILE_PATH_LITERAL("background.js"), kBackgroundJs);
test_dir.WriteFile(FILE_PATH_LITERAL("page.html"), kPageHtml);
test_dir.WriteFile(FILE_PATH_LITERAL("page.js"), kPageJs);
const Extension* extension = LoadExtension(test_dir.UnpackedPath());
ASSERT_TRUE(extension);
// Load the page with the extension listeners.
ASSERT_TRUE(NavigateToURL(extension->GetResourceURL("page.html")));
content::RenderFrameHost* page_host =
GetActiveWebContents()->GetPrimaryMainFrame();
ASSERT_TRUE(page_host);
// At this point, 3 listeners should be registered.
EXPECT_EQ(3u, web_request_router()->GetListenerCountForTesting(
profile(), "webRequest.onBeforeRequest"));
// Convenience lambdas for checking the count received in each listener.
auto get_first_count = [this, extension]() {
return GetCountFromBackgroundScript(extension, profile(), "firstCount");
};
auto get_second_count = [this, extension]() {
return GetCountFromBackgroundScript(extension, profile(), "secondCount");
};
auto get_third_count = [page_host]() {
return content::EvalJs(page_host, "window.thirdCount;").ExtractInt();
};
// No listeners should have fired yet.
EXPECT_EQ(0, get_first_count());
EXPECT_EQ(0, get_second_count());
EXPECT_EQ(0, get_third_count());
// Navigate to first.example (this first navigation needs to happen in a new
// tab so that we don't navigate the extension page).
NavigateToURLInNewTab(
embedded_test_server()->GetURL("first.example", "/title1.html"));
// (Only) the first listener should have fired.
EXPECT_EQ(1, get_first_count());
EXPECT_EQ(0, get_second_count());
EXPECT_EQ(0, get_third_count());
// Navigate to second.example. The second listener should fire.
ASSERT_TRUE(NavigateToURL(
embedded_test_server()->GetURL("second.example", "/title1.html")));
EXPECT_EQ(1, get_first_count());
EXPECT_EQ(1, get_second_count());
EXPECT_EQ(0, get_third_count());
// Navigate to third.example. The third listener should fire.
ASSERT_TRUE(NavigateToURL(
embedded_test_server()->GetURL("third.example", "/title1.html")));
EXPECT_EQ(1, get_first_count());
EXPECT_EQ(1, get_second_count());
EXPECT_EQ(1, get_third_count());
}
#if !BUILDFLAG(IS_ANDROID)
// Tests that a service worker-based extension with webRequestBlocking can
// intercept requests after the service worker stops.
// TODO(crbug.com/391921314): Enable on desktop Android when InstallExtension()
// is supported (for LoadPolicyExtension).
IN_PROC_BROWSER_TEST_F(ManifestV3WebRequestApiTest,
WebRequestBlocking_AfterWorkerShutdown) {
ASSERT_TRUE(StartEmbeddedTestServer());
static constexpr char kManifest[] =
R"({
"name": "MV3 WebRequest",
"version": "0.1",
"manifest_version": 3,
"permissions": ["webRequest", "webRequestBlocking"],
"host_permissions": [
"http://block.example/*"
],
"background": {"service_worker": "background.js"}
})";
// An extension with a listener that cancels any requests that include
// block.example.
static constexpr char kBackgroundJs[] =
R"(chrome.webRequest.onBeforeRequest.addListener(
(details) => {
if (details.url.includes('block.example')) {
return {cancel: true}
}
return {};
},
{urls: ['<all_urls>'], types: ['main_frame']},
['blocking']);
chrome.test.sendMessage('ready');)";
TestExtensionDir test_dir;
test_dir.WriteManifest(kManifest);
test_dir.WriteFile(FILE_PATH_LITERAL("background.js"), kBackgroundJs);
const Extension* extension = LoadPolicyExtension(test_dir);
ASSERT_TRUE(extension);
// A single webRequest listener should be registered.
EXPECT_EQ(1u, web_request_router()->GetListenerCountForTesting(
profile(), "webRequest.onBeforeRequest"));
EXPECT_EQ(0u, web_request_router()->GetInactiveListenerCountForTesting(
profile(), "webRequest.onBeforeRequest"));
// Stop the service worker.
browsertest_util::StopServiceWorkerForExtensionGlobalScope(profile(),
extension->id());
// Note: the task to remove listeners from ExtensionWebRequestEventRouter
// is async; run to flush the posted task.
base::RunLoop().RunUntilIdle();
// The listener should still be registered, but should be counted as an
// inactive listener.
EXPECT_EQ(0u, web_request_router()->GetListenerCountForTesting(
profile(), "webRequest.onBeforeRequest"));
EXPECT_EQ(1u, web_request_router()->GetInactiveListenerCountForTesting(
profile(), "webRequest.onBeforeRequest"));
// Navigate to block.example. The request should be blocked by the extension.
{
content::WebContents* web_contents =
browser()->tab_strip_model()->GetActiveWebContents();
content::TestNavigationObserver nav_observer(web_contents);
EXPECT_TRUE(ui_test_utils::NavigateToURL(
browser(),
embedded_test_server()->GetURL("block.example", "/simple.html")));
EXPECT_EQ(net::ERR_BLOCKED_BY_CLIENT, nav_observer.last_net_error_code());
}
}
#endif // !BUILDFLAG(IS_ANDROID)
// Tests a service worker-based extension using webRequest for observational
// purposes receives events after the worker stops.
IN_PROC_BROWSER_TEST_F(ManifestV3WebRequestApiTest,
WebRequestObservation_AfterWorkerShutdown) {
ASSERT_TRUE(StartEmbeddedTestServer());
static constexpr char kManifest[] =
R"({
"name": "MV3 WebRequest",
"version": "0.1",
"manifest_version": 3,
"permissions": ["webRequest", "storage"],
"host_permissions": [
"http://example.com/*"
],
"background": {"service_worker": "background.js"}
})";
// An extension that stores the number of matched requests in a count in
// extension storage.
// This is very similar to the test extension at
// chrome/test/data/extensions/api_test/webrequest_persistent, but is
// manifest V3. There's enough changes that our loading auto-conversion code
// won't quite work (mostly around permissions vs host_permissions), so we
// need a bit of a duplication here.
static constexpr char kBackgroundJs[] =
R"(let storageComplete = undefined;
let isUsingStorage = false;
// Waits for any pending load to complete to avoid raciness in the
// test.
async function flushStorage() {
console.assert(!storageComplete);
if (!isUsingStorage)
return;
await new Promise((resolve) => {
storageComplete = resolve;
});
storageComplete = undefined;
}
chrome.webRequest.onBeforeRequest.addListener(
async (details) => {
isUsingStorage = true;
let {requestCount} =
await chrome.storage.local.get({requestCount: 0});
requestCount++;
await chrome.storage.local.set({requestCount});
isUsingStorage = false;
if (storageComplete)
storageComplete();
chrome.test.sendMessage('event received');
},
{urls: ['<all_urls>'], types: ['main_frame']});)";
TestExtensionDir test_dir;
test_dir.WriteManifest(kManifest);
test_dir.WriteFile(FILE_PATH_LITERAL("background.js"), kBackgroundJs);
const Extension* extension = LoadExtension(
test_dir.UnpackedPath(), {.wait_for_registration_stored = true});
ASSERT_TRUE(extension);
// A single listener should be registered.
EXPECT_EQ(1u, web_request_router()->GetListenerCountForTesting(
profile(), "webRequest.onBeforeRequest"));
EXPECT_EQ(0u, web_request_router()->GetInactiveListenerCountForTesting(
profile(), "webRequest.onBeforeRequest"));
// Navigate to a URL. The request should be seen by the extension.
EXPECT_TRUE(NavigateToURL(
embedded_test_server()->GetURL("example.com", "/simple.html")));
auto get_request_count = [this, extension]() {
base::Value request_count = BackgroundScriptExecutor::ExecuteScript(
profile(), extension->id(), kGetNumRequests,
BackgroundScriptExecutor::ResultCapture::kSendScriptResult);
return request_count.GetInt();
};
EXPECT_EQ(1, get_request_count());
// Stop the extension's service worker.
browsertest_util::StopServiceWorkerForExtensionGlobalScope(profile(),
extension->id());
// Note: the task to remove listeners from ExtensionWebRequestEventRouter
// is async; run to flush the posted task.
base::RunLoop().RunUntilIdle();
// The listener should still be registered, but should be counted as an
// inactive listener.
EXPECT_EQ(0u, web_request_router()->GetListenerCountForTesting(
profile(), "webRequest.onBeforeRequest"));
EXPECT_EQ(1u, web_request_router()->GetInactiveListenerCountForTesting(
profile(), "webRequest.onBeforeRequest"));
{
// Navigate again. The request should again be seen by the extension.
//
// We need to use a message listener here to ensure we gave the extension
// enough time to start up and have the event fire. Unlike the blocking
// scenario, there's no guarantee this happens by the time navigation
// completes.
ExtensionTestMessageListener listener("event received");
EXPECT_TRUE(NavigateToURL(
embedded_test_server()->GetURL("example.com", "/simple.html")));
EXPECT_TRUE(listener.WaitUntilSatisfied());
}
// The inactive listener should have been reactivated...
EXPECT_EQ(1u, web_request_router()->GetListenerCountForTesting(
profile(), "webRequest.onBeforeRequest"));
EXPECT_EQ(0u, web_request_router()->GetInactiveListenerCountForTesting(
profile(), "webRequest.onBeforeRequest"));
// ... and the extension should have seen the request.
EXPECT_EQ(2, get_request_count());
}
// Tests unloading an extension with lazy listeners while the worker is
// inactive. The listeners should be properly cleaned up.
IN_PROC_BROWSER_TEST_F(
ManifestV3WebRequestApiTest,
ServiceWorkerWithWebRequest_UnloadExtensionWhileWorkerInactive) {
ASSERT_TRUE(StartEmbeddedTestServer());
static constexpr char kManifest[] =
R"({
"name": "MV3 WebRequest",
"version": "0.1",
"manifest_version": 3,
"permissions": ["webRequest"],
"host_permissions": [
"http://example.com/*"
],
"background": {"service_worker": "background.js"}
})";
static constexpr char kBackgroundJs[] =
R"(chrome.webRequest.onBeforeRequest.addListener(
async (details) => { },
{urls: ['<all_urls>'], types: ['main_frame']});)";
TestExtensionDir test_dir;
test_dir.WriteManifest(kManifest);
test_dir.WriteFile(FILE_PATH_LITERAL("background.js"), kBackgroundJs);
const Extension* extension = LoadExtension(
test_dir.UnpackedPath(), {.wait_for_registration_stored = true});
ASSERT_TRUE(extension);
EXPECT_EQ(1u, web_request_router()->GetListenerCountForTesting(
profile(), "webRequest.onBeforeRequest"));
EXPECT_EQ(0u, web_request_router()->GetInactiveListenerCountForTesting(
profile(), "webRequest.onBeforeRequest"));
browsertest_util::StopServiceWorkerForExtensionGlobalScope(profile(),
extension->id());
// Note: the task to remove listeners from ExtensionWebRequestEventRouter
// is async; run to flush the posted task.
base::RunLoop().RunUntilIdle();
EXPECT_EQ(0u, web_request_router()->GetListenerCountForTesting(
profile(), "webRequest.onBeforeRequest"));
EXPECT_EQ(1u, web_request_router()->GetInactiveListenerCountForTesting(
profile(), "webRequest.onBeforeRequest"));
DisableExtension(extension->id());
base::RunLoop().RunUntilIdle();
EXPECT_EQ(0u, web_request_router()->GetListenerCountForTesting(
profile(), "webRequest.onBeforeRequest"));
EXPECT_EQ(0u, web_request_router()->GetInactiveListenerCountForTesting(
profile(), "webRequest.onBeforeRequest"));
}
// Tests a service worker adding and then removing a listener.
IN_PROC_BROWSER_TEST_F(ManifestV3WebRequestApiTest,
ServiceWorkerWithWebRequest_ManuallyRemoveListener) {
ASSERT_TRUE(StartEmbeddedTestServer());
static constexpr char kManifest[] =
R"({
"name": "MV3 WebRequest",
"version": "0.1",
"manifest_version": 3,
"permissions": ["webRequest"],
"host_permissions": [
"http://example.com/*"
],
"background": {"service_worker": "background.js"}
})";
static constexpr char kBackgroundJs[] =
R"(self.firstListenerCount = 0;
self.secondListenerCount = 0;
self.firstListener = function() { ++firstListenerCount; };
self.secondListener = function() { ++secondListenerCount; };
chrome.webRequest.onBeforeRequest.addListener(
firstListener,
{urls: ['<all_urls>'], types: ['main_frame']});
chrome.webRequest.onBeforeRequest.addListener(
secondListener,
{urls: ['<all_urls>'], types: ['main_frame']});)";
TestExtensionDir test_dir;
test_dir.WriteManifest(kManifest);
test_dir.WriteFile(FILE_PATH_LITERAL("background.js"), kBackgroundJs);
const Extension* extension = LoadExtension(
test_dir.UnpackedPath(), {.wait_for_registration_stored = true});
ASSERT_TRUE(extension);
// There should initially be two listeners registered, both active (since
// the service worker is active).
EXPECT_EQ(2u, web_request_router()->GetListenerCountForTesting(
profile(), "webRequest.onBeforeRequest"));
EXPECT_EQ(0u, web_request_router()->GetInactiveListenerCountForTesting(
profile(), "webRequest.onBeforeRequest"));
// Manually remove one of the listeners. This should result in the listener
// being fully removed (not deactivated), so there should only be a single
// listener remaining.
static constexpr char kRemoveListener[] =
R"(chrome.webRequest.onBeforeRequest.removeListener(self.firstListener);
chrome.test.sendScriptResult('');)";
BackgroundScriptExecutor::ExecuteScript(
profile(), extension->id(), kRemoveListener,
BackgroundScriptExecutor::ResultCapture::kSendScriptResult);
// Note: the task to remove listeners from ExtensionWebRequestEventRouter
// is async; run to flush the posted task.
base::RunLoop().RunUntilIdle();
EXPECT_EQ(1u, web_request_router()->GetListenerCountForTesting(
profile(), "webRequest.onBeforeRequest"));
EXPECT_EQ(0u, web_request_router()->GetInactiveListenerCountForTesting(
profile(), "webRequest.onBeforeRequest"));
// Navigate to a page and verify that only the second listener fires.
EXPECT_TRUE(NavigateToURL(
embedded_test_server()->GetURL("example.com", "/simple.html")));
EXPECT_EQ(0, GetCountFromBackgroundScript(extension, profile(),
"firstListenerCount"));
EXPECT_EQ(1, GetCountFromBackgroundScript(extension, profile(),
"secondListenerCount"));
}
// Tests listeners in multiple contexts with lazy event disptaching.
IN_PROC_BROWSER_TEST_F(ManifestV3WebRequestApiTest,
ListenersInMultipleContextsWithLazyDispatch) {
ASSERT_TRUE(StartEmbeddedTestServer());
static constexpr char kManifest[] =
R"({
"name": "MV3 WebRequest",
"version": "0.1",
"manifest_version": 3,
"permissions": ["webRequest"],
"host_permissions": [ "http://example.com/*" ],
"background": {"service_worker": "background.js"}
})";
// The extension has two contexts: the background service worker and a
// separate page, each of which register an identical listener. Each should
// only be invoked once.
static constexpr char kBackgroundJs[] =
R"(self.eventCount = 0;
chrome.webRequest.onBeforeRequest.addListener(
async function() {
++eventCount;
// Perform a rount trip to ensure any events that are coming our
// way get dispatched, and then notify the test.
await chrome.test.waitForRoundTrip('test');
chrome.test.sendMessage('worker received');
},
{urls: ['http://example.com/*'], types: ['main_frame']}, []);)";
static constexpr char kPageHtml[] =
R"(<!doctype html>
<html>
Page
<script src="page.js"></script>
</html>)";
static constexpr char kPageJs[] =
R"(self.eventCount = 0;
chrome.webRequest.onBeforeRequest.addListener(
function() { ++eventCount; },
{urls: ['http://example.com/*'], types: ['main_frame']}, []);)";
TestExtensionDir test_dir;
test_dir.WriteManifest(kManifest);
test_dir.WriteFile(FILE_PATH_LITERAL("background.js"), kBackgroundJs);
test_dir.WriteFile(FILE_PATH_LITERAL("page.html"), kPageHtml);
test_dir.WriteFile(FILE_PATH_LITERAL("page.js"), kPageJs);
const Extension* extension = LoadExtension(
test_dir.UnpackedPath(), {.wait_for_registration_stored = true});
ASSERT_TRUE(extension);
// Load the page with the extension listeners.
ASSERT_TRUE(NavigateToURL(extension->GetResourceURL("page.html")));
content::RenderFrameHost* page_host =
GetActiveWebContents()->GetPrimaryMainFrame();
ASSERT_TRUE(page_host);
// At this point, 2 listeners should be registered.
EXPECT_EQ(2u, web_request_router()->GetListenerCountForTesting(
profile(), "webRequest.onBeforeRequest"));
// Convenience lambdas for checking the count received in each listener.
auto get_worker_event_count = [this, extension]() {
return GetCountFromBackgroundScript(extension, profile(), "eventCount");
};
auto get_page_event_count = [page_host]() {
return content::EvalJs(page_host, "self.eventCount;").ExtractInt();
};
// Stop the extension's service worker. The worker listener should now be
// registered as an inactive listener.
browsertest_util::StopServiceWorkerForExtensionGlobalScope(profile(),
extension->id());
// Note: the task to remove listeners from ExtensionWebRequestEventRouter
// is async; run to flush the posted task.
base::RunLoop().RunUntilIdle();
EXPECT_EQ(1u, web_request_router()->GetListenerCountForTesting(
profile(), "webRequest.onBeforeRequest"));
EXPECT_EQ(1u, web_request_router()->GetInactiveListenerCountForTesting(
profile(), "webRequest.onBeforeRequest"));
{
ExtensionTestMessageListener listener("worker received");
// Navigate to example.com (this navigation needs to happen in a new tab so
// that we don't navigate the extension page).
NavigateToURLInNewTab(
embedded_test_server()->GetURL("example.com", "/title1.html"));
EXPECT_TRUE(listener.WaitUntilSatisfied());
}
// Each listener should have fired exactly once.
EXPECT_EQ(1, get_worker_event_count());
EXPECT_EQ(1, get_page_event_count());
}
// Tests listeners in the extension (extension tab) and extension background
// (service worker) contexts with lazy event dispatching. However, this
// simulates the worker never stopping and notifying that the worker's active
// listener should be removed. Regression test for crbug.com/331358156.
IN_PROC_BROWSER_TEST_F(
ManifestV3WebRequestApiTest,
ListenersInMultipleContextsWithLazyDispatch_ButActiveListenerRemovalStalled) {
ASSERT_TRUE(StartEmbeddedTestServer());
static constexpr char kManifest[] =
R"({
"name": "MV3 WebRequest",
"version": "0.1",
"manifest_version": 3,
"permissions": ["webRequest"],
"host_permissions": [ "http://example.com/*" ],
"background": {"service_worker": "background.js"}
})";
// The extension has two contexts: the background service worker and a
// separate page, each of which register an identical listener. Each should
// only be invoked once.
static constexpr char kBackgroundJs[] =
R"(self.eventCount = 0;
chrome.webRequest.onBeforeRequest.addListener(
async function() {
++eventCount;
// Perform a round trip to ensure any events that are coming our
// way get dispatched, and then notify the test.
await chrome.test.waitForRoundTrip('test');
chrome.test.sendMessage('worker received');
},
{urls: ['http://example.com/*'], types: ['main_frame']}, []);)";
static constexpr char kPageHtml[] =
R"(<!doctype html>
<html>
Page
<script src="page.js"></script>
</html>)";
static constexpr char kPageJs[] =
R"(self.eventCount = 0;
chrome.webRequest.onBeforeRequest.addListener(
function() { ++eventCount; },
{urls: ['http://example.com/*'], types: ['main_frame']}, []);)";
TestExtensionDir test_dir;
test_dir.WriteManifest(kManifest);
test_dir.WriteFile(FILE_PATH_LITERAL("background.js"), kBackgroundJs);
test_dir.WriteFile(FILE_PATH_LITERAL("page.html"), kPageHtml);
test_dir.WriteFile(FILE_PATH_LITERAL("page.js"), kPageJs);
const Extension* extension = LoadExtension(
test_dir.UnpackedPath(), {.wait_for_registration_stored = true});
ASSERT_TRUE(extension);
// Load the page with the extension listeners.
ASSERT_TRUE(NavigateToURL(extension->GetResourceURL("page.html")));
content::RenderFrameHost* page_host =
GetActiveWebContents()->GetPrimaryMainFrame();
ASSERT_TRUE(page_host);
// At this point, 2 listeners should be registered.
EXPECT_EQ(2u, web_request_router()->GetListenerCountForTesting(
profile(), "webRequest.onBeforeRequest"));
// Convenience lambdas for checking the count received in each listener.
auto get_worker_event_count = [this, extension]() {
return GetCountFromBackgroundScript(extension, profile(), "eventCount");
};
auto get_page_event_count = [page_host]() {
return content::EvalJs(page_host, "self.eventCount;").ExtractInt();
};
// Get the soon to be stopped ("previous") worker's `WorkerId`.
std::optional<WorkerId> previous_service_worker_id =
GetWorkerIdForExtension(extension->id());
ASSERT_TRUE(previous_service_worker_id);
// Setup intercept of `EventRouter::RemoveListenerForServiceWorker()` mojom
// call. This simulates the worker renderer thread being very slow/never
// informing the //extensions browser layer that the worker stopped and that
// it's active listeners should be removed.
EventRouterInterceptorForStopListenerRemoval
event_listener_removal_on_stop_interceptor(
profile(), previous_service_worker_id->render_process_id);
// Stop the extension's service worker. The worker listener, due to the
// interceptor, will stay registered as an active listener. However,
// the worker task queue will catch when the worker begins stopping and remove
// the active listener.
browsertest_util::StopServiceWorkerForExtensionGlobalScope(profile(),
extension->id());
EXPECT_EQ(1u, web_request_router()->GetListenerCountForTesting(
profile(), "webRequest.onBeforeRequest"));
EXPECT_EQ(1u, web_request_router()->GetInactiveListenerCountForTesting(
profile(), "webRequest.onBeforeRequest"));
{
ExtensionTestMessageListener listener("worker received");
// Navigate to example.com (this navigation needs to happen in a new tab so
// that we don't navigate the extension page).
NavigateToURLInNewTab(
embedded_test_server()->GetURL("example.com", "/title1.html"));
EXPECT_TRUE(listener.WaitUntilSatisfied());
}
// Each listener should have fired exactly once.
EXPECT_EQ(1, get_worker_event_count());
EXPECT_EQ(1, get_page_event_count());
// Ensure the service worker that responded is a newly started instance.
std::optional<WorkerId> new_instance_service_worker_id =
GetWorkerIdForExtension(extension->id());
ASSERT_TRUE(new_instance_service_worker_id);
EXPECT_NE(*previous_service_worker_id, *new_instance_service_worker_id);
}
#if !BUILDFLAG(IS_ANDROID)
// Tests that an MV3 extension can use the `webRequestAuthProvider` permission
// to intercept and handle `onAuthRequired` events coming from a tab.
// TODO(crbug.com/371324825): Port to desktop Android. The navigation to the
// auth URL fails. Perhaps the webRequestAuthProvider permission isn't working,
// or Android handles http auth differently than desktop platforms.
IN_PROC_BROWSER_TEST_F(ManifestV3WebRequestApiTest, TestOnAuthRequiredTab) {
ASSERT_TRUE(StartEmbeddedTestServer());
static constexpr char kManifest[] =
R"({
"name": "MV3 WebRequest",
"version": "0.1",
"manifest_version": 3,
"permissions": ["webRequest", "webRequestAuthProvider"],
"host_permissions": [ "http://example.com/*" ],
"background": {"service_worker": "background.js"}
})";
// The extension will asynchronously provide the user credentials for the
// request.
static constexpr char kBackgroundJs[] =
R"(chrome.webRequest.onAuthRequired.addListener(
(details, callback) => {
chrome.test.assertEq('mv3authprovider', details.realm);
chrome.test.assertEq(401, details.statusCode);
const authCredentials = {username: 'foo', password: 'secret'};
setTimeout(() => {
callback({authCredentials});
chrome.test.succeed();
}, 20);
},
{urls: ['<all_urls>']},
['asyncBlocking']);)";
TestExtensionDir test_dir;
test_dir.WriteManifest(kManifest);
test_dir.WriteFile(FILE_PATH_LITERAL("background.js"), kBackgroundJs);
const Extension* extension = LoadExtension(test_dir.UnpackedPath());
ASSERT_TRUE(extension);
// Navigate to a special URL that will prompt the user for credentials. The
// request should succeed (verified by the last navigation status) and the
// extension should have received the event (verified by the ResultCatcher).
static constexpr char kRealm[] = "mv3authprovider";
std::string auth_url_path =
base::StringPrintf("/auth-basic/%s/subpath?realm=%s", kRealm, kRealm);
GURL auth_url = embedded_test_server()->GetURL("example.com", auth_url_path);
ResultCatcher result_catcher;
content::TestNavigationObserver navigation_observer(
browser()->tab_strip_model()->GetActiveWebContents());
content::RenderFrameHost* frame_host =
ui_test_utils::NavigateToURL(browser(), auth_url);
ASSERT_TRUE(result_catcher.GetNextResult());
EXPECT_EQ(auth_url, frame_host->GetLastCommittedURL());
EXPECT_TRUE(navigation_observer.last_navigation_succeeded());
}
class OnAuthRequiredApiTest : public ExtensionApiTest {
public:
static constexpr char kTestDomain[] = "a.test";
OnAuthRequiredApiTest() {
// Https is required to use service workers.
// This limits the set of domains with valid certificates. For the purposes
// of this test we will use kTestDomain.
UseHttpsTestServer();
}
~OnAuthRequiredApiTest() override = default;
void SetUpOnMainThread() override {
ExtensionApiTest::SetUpOnMainThread();
host_resolver()->AddRule("*", "127.0.0.1");
embedded_test_server()->ServeFilesFromSourceDirectory("chrome/test/data");
ASSERT_TRUE(StartEmbeddedTestServer());
}
// Returns a URL which requires username/password
GURL MakeAuthUrl() {
static constexpr char kRealm[] = "mv3authprovider";
std::string auth_url_path =
base::StringPrintf("/auth-basic/%s/subpath?realm=%s", kRealm, kRealm);
return embedded_test_server()->GetURL(kTestDomain, auth_url_path);
}
// Loads an extension that implements onAuthRequired. `additional_js` will be
// concatenated to the background.js.
void LoadExtensionWithAdditionalJs(const std::string& additional_js) {
static constexpr char kManifest[] =
R"({
"name": "MV3 WebRequest",
"version": "0.1",
"manifest_version": 3,
"permissions": ["webRequest", "webRequestAuthProvider"],
"host_permissions": [ "http://127.0.0.1/*", "https://a.test/*" ],
"background": {"service_worker": "background.js"}
})";
static constexpr char kBackgroundJs[] =
R"(
let didInterceptAuth = false;
chrome.webRequest.onAuthRequired.addListener(
(details, callback) => {
didInterceptAuth = true;
chrome.test.assertEq('mv3authprovider', details.realm);
chrome.test.assertEq(401, details.statusCode);
const authCredentials = {username: 'foo', password: 'secret'};
callback({authCredentials});
},
{urls: ['<all_urls>']},
['asyncBlocking']);
)";
std::string background_js(kBackgroundJs);
background_js += additional_js;
test_extension_dir_.WriteManifest(kManifest);
test_extension_dir_.WriteFile(FILE_PATH_LITERAL("background.js"),
background_js);
const Extension* extension =
LoadExtension(test_extension_dir_.UnpackedPath());
ASSERT_TRUE(extension);
}
private:
TestExtensionDir test_extension_dir_;
base::ScopedTempDir service_worker_dir_;
};
// Tests that an MV3 extension can use the `webRequestAuthProvider` permission
// to intercept and handle `onAuthRequired` events coming from an extension
// service worker. This test does the following:
// (1) This loads an extension with a service-worker background.js.
// (2) The extension adds a listener to chrome.webRequest.onAuthRequired.
// (3) The extension attempts to fetch a resource that requires http auth.
// (4) This triggers the listener in (3), which supplies credentials
// (5) Checks that the fetch succeeded.
IN_PROC_BROWSER_TEST_F(OnAuthRequiredApiTest,
TestOnAuthRequiredExtensionServiceWorker) {
// After the extension loads, trigger an async request to fetch an http auth
// resource.
std::string additional_js =
R"(
(async function() {
try {
const response = await fetch($1);
if (response.ok) {
chrome.test.assertTrue(didInterceptAuth);
chrome.test.succeed();
} else {
chrome.test.fail();
}
} catch (e) {
chrome.test.fail();
}
})();
)";
additional_js = content::JsReplace(additional_js, MakeAuthUrl());
// Loading the extension triggers the remaining steps of the test.
ResultCatcher result_catcher;
LoadExtensionWithAdditionalJs(additional_js);
ASSERT_TRUE(result_catcher.GetNextResult());
}
// This test is similar to TestOnAuthRequiredExtensionServiceWorker but the
// service worker is hosted by a website instead of the extension istelf.
IN_PROC_BROWSER_TEST_F(OnAuthRequiredApiTest,
TestOnAuthRequiredWebsiteServiceWorker) {
// Load the extension.
LoadExtensionWithAdditionalJs("");
// Navigate to the test page.
GURL requestor_url = embedded_test_server()->GetURL(
kTestDomain, "/ssl/service_worker_fetch/page.html");
ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), requestor_url));
// Perform a fetch from a worker and validate that it succeeds.
content::WebContents* web_contents =
browser()->tab_strip_model()->GetActiveWebContents();
std::string fetch_response =
content::EvalJs(web_contents,
content::JsReplace("doFetchInWorker($1);", MakeAuthUrl()))
.ExtractString();
EXPECT_THAT(fetch_response, testing::HasSubstr("<title>"));
}
// Tests the behavior of an extension that registers an event listener
// asynchronously.
// Regression test for https://crbug.com/1397879 and https://crbug.com/1434212.
IN_PROC_BROWSER_TEST_F(ManifestV3WebRequestApiTest, AsyncListenerRegistration) {
ASSERT_TRUE(StartEmbeddedTestServer());
static constexpr char kManifest[] =
R"({
"name": "MV3 WebRequest",
"version": "0.1",
"manifest_version": 3,
"permissions": ["webRequest", "webRequestBlocking"],
"host_permissions": [
"http://example.com/*"
],
"background": {"service_worker": "background.js"}
})";
// A background context that *conditionally* registers a blocking listener.
// We send a "will_register" message and register the listener once we receive
// the response from that message. If we never receive a response, we never
// register the event listener.
static constexpr char kBackgroundJs[] =
R"(chrome.test.sendMessage('will_register').then(() => {
chrome.webRequest.onBeforeRequest.addListener(
(details) => {
if (details.url.includes('example.com')) {
return {cancel: true}
}
return {};
},
{urls: ['<all_urls>'], types: ['main_frame']},
['blocking']);
chrome.test.sendMessage('registered');
});
// Register an additional event properly so that the service worker
// still has _a_ listener registered in the process.
// https://crbug.com/1434212.
chrome.webRequest.onHeadersReceived.addListener(
(details) => {},
{urls: ['<all_urls>'], types: ['main_frame']},
['blocking']);
chrome.test.sendMessage('ready');)";
// Load the extension and tell it to register the listener.
ExtensionTestMessageListener will_register_listener(
"will_register", ReplyBehavior::kWillReply);
ExtensionTestMessageListener registered_listener("registered");
TestExtensionDir test_dir;
test_dir.WriteManifest(kManifest);
test_dir.WriteFile(FILE_PATH_LITERAL("background.js"), kBackgroundJs);
const Extension* extension = LoadPolicyExtension(test_dir);
ASSERT_TRUE(extension);
ASSERT_TRUE(will_register_listener.WaitUntilSatisfied());
EXPECT_FALSE(registered_listener.was_satisfied());
will_register_listener.Reply("Go for it!");
ASSERT_TRUE(registered_listener.WaitUntilSatisfied());
// A single webRequest listener should be registered.
EXPECT_EQ(1u, web_request_router()->GetListenerCountForTesting(
profile(), "webRequest.onBeforeRequest"));
EXPECT_EQ(0u, web_request_router()->GetInactiveListenerCountForTesting(
profile(), "webRequest.onBeforeRequest"));
const GURL url =
embedded_test_server()->GetURL("example.com", "/simple.html");
// Navigate to example.com to check our setup; the request should be blocked.
{
content::WebContents* web_contents =
browser()->tab_strip_model()->GetActiveWebContents();
content::TestNavigationObserver nav_observer(web_contents);
EXPECT_TRUE(ui_test_utils::NavigateToURL(browser(), url));
EXPECT_EQ(net::ERR_BLOCKED_BY_CLIENT, nav_observer.last_net_error_code());
}
// Stop the service worker.
browsertest_util::StopServiceWorkerForExtensionGlobalScope(profile(),
extension->id());
// Note: the task to remove listeners from ExtensionWebRequestEventRouter
// is async; run to flush the posted task.
base::RunLoop().RunUntilIdle();
// The listener should still be registered, but should be counted as an
// inactive listener.
EXPECT_EQ(0u, web_request_router()->GetListenerCountForTesting(
profile(), "webRequest.onBeforeRequest"));
EXPECT_EQ(1u, web_request_router()->GetInactiveListenerCountForTesting(
profile(), "webRequest.onBeforeRequest"));
// Reset the "will register" listener. However, we'll never reply this time,
// which means the extension will never register the listener again.
will_register_listener.Reset();
// Now, navigate to example.com again. This will wake up the extension service
// worker, but we'll fail to dispatch the event to the extension because the
// listener isn't registered. The request should be allowed to continue.
{
content::WebContents* web_contents =
browser()->tab_strip_model()->GetActiveWebContents();
content::TestNavigationObserver nav_observer(web_contents);
EXPECT_TRUE(ui_test_utils::NavigateToURL(browser(), url));
EXPECT_TRUE(nav_observer.last_navigation_succeeded());
EXPECT_EQ(net::OK, nav_observer.last_net_error_code());
}
// Clean up: ExtensionTestMessageListener requires a reply (or else will
// DCHECK). Wait for it to receive the message (it probably already did, but
// theoretically can race), and send a response.
EXPECT_TRUE(will_register_listener.WaitUntilSatisfied());
will_register_listener.Reply("unused");
}
// Tests behavior when a service worker is stopped while processing an event.
IN_PROC_BROWSER_TEST_F(ManifestV3WebRequestApiTest,
ServiceWorkerGoesAwayWhileHandlingRequest) {
ASSERT_TRUE(StartEmbeddedTestServer());
static constexpr char kManifest[] =
R"({
"name": "MV3 WebRequest",
"version": "0.1",
"manifest_version": 3,
"permissions": ["webRequest", "webRequestBlocking"],
"host_permissions": [
"http://example.com/*"
],
"background": {"service_worker": "background.js"}
})";
// An extension with a listener that will spin forever on example.com
// requests.
static constexpr char kBackgroundJs[] =
R"(chrome.webRequest.onBeforeRequest.addListener(
(details) => {
if (details.url.includes('example.com')) {
chrome.test.sendMessage('received');
// Spin FOREVER.
while (true) { }
}
return {};
},
{urls: ['<all_urls>'], types: ['main_frame']},
['blocking']);
chrome.test.sendMessage('ready');)";
TestExtensionDir test_dir;
test_dir.WriteManifest(kManifest);
test_dir.WriteFile(FILE_PATH_LITERAL("background.js"), kBackgroundJs);
const Extension* extension = LoadPolicyExtension(test_dir);
ASSERT_TRUE(extension);
// A single webRequest listener should be registered.
EXPECT_EQ(1u, web_request_router()->GetListenerCountForTesting(
profile(), "webRequest.onBeforeRequest"));
// Navigate to example.com; the extension will receive the event and spin
// indefinitely.
// We navigate in a new tab to have a better signal of "request started".
// We can't wait for the request to finish, since the extension's listener
// never returns, which blocks the request.
const GURL url =
embedded_test_server()->GetURL("example.com", "/simple.html");
content::TestNavigationObserver nav_observer(url);
nav_observer.StartWatchingNewWebContents();
ExtensionTestMessageListener test_listener("received");
ui_test_utils::NavigateToURLWithDisposition(
browser(), url, WindowOpenDisposition::NEW_FOREGROUND_TAB,
ui_test_utils::BROWSER_TEST_WAIT_FOR_TAB);
content::WebContents* web_contents =
browser()->tab_strip_model()->GetActiveWebContents();
EXPECT_TRUE(test_listener.WaitUntilSatisfied());
// The web contents should still be loading, and should have no last
// committed URL since the extension is blocking the request.
EXPECT_TRUE(web_contents->IsLoading());
EXPECT_EQ(GURL(), web_contents->GetLastCommittedURL());
// Stop the extension service worker.
browsertest_util::StopServiceWorkerForExtensionGlobalScope(profile(),
extension->id());
// The request should be unblocked.
EXPECT_TRUE(content::WaitForLoadStop(web_contents));
EXPECT_TRUE(nav_observer.last_navigation_succeeded());
EXPECT_EQ(url, web_contents->GetLastCommittedURL());
}
// Tests that a MV3 extension that doesn't have the `webRequestAuthProvider`
// permission cannot use blocking listeners for `onAuthRequired`.
IN_PROC_BROWSER_TEST_F(ManifestV3WebRequestApiTest,
TestOnAuthRequired_NoPermission) {
ASSERT_TRUE(StartEmbeddedTestServer());
static constexpr char kManifest[] =
R"({
"name": "MV3 WebRequest",
"version": "0.1",
"manifest_version": 3,
"permissions": ["webRequest"],
"host_permissions": [ "http://example.com/*" ],
"background": {"service_worker": "background.js"}
})";
// The extension tries to add a listener; this will fail asynchronously
// as a part of the webRequestInternal API trying to add the listener.
// This results in runtime.lastError being set, but since it's an
// internal API, there's no way for the extension to catch the error.
static constexpr char kBackgroundJs[] =
R"(chrome.webRequest.onAuthRequired.addListener(
(details, callback) => {},
{urls: ['<all_urls>']},
['asyncBlocking']);)";
// Since we can't catch the error in the extension's JS, we instead listen to
// the error come into the error console.
ErrorConsoleTestObserver error_observer(1u, profile());
error_observer.EnableErrorCollection();
// Load the extension and wait for the error to come.
TestExtensionDir test_dir;
test_dir.WriteManifest(kManifest);
test_dir.WriteFile(FILE_PATH_LITERAL("background.js"), kBackgroundJs);
const Extension* extension = LoadExtension(test_dir.UnpackedPath());
ASSERT_TRUE(extension);
error_observer.WaitForErrors();
const ErrorList& errors =
ErrorConsole::Get(profile())->GetErrorsForExtension(extension->id());
ASSERT_EQ(1u, errors.size());
EXPECT_TRUE(
base::StartsWith(errors[0]->message(),
u"Unchecked runtime.lastError: You do not have "
u"permission to use blocking webRequest listeners."))
<< errors[0]->message();
}
#endif // !BUILDFLAG(IS_ANDROID)
// Tests that an extension that doesn't have the `webView` permission cannot
// manually create and add a WebRequestEvent that specifies a webViewInstanceId.
// TODO(tjudkins): It would be good to also stop this on the JS layer by not
// allowing extensions to manually create and add WebRequestEvents.
// Regression test for crbug.com/1472830
IN_PROC_BROWSER_TEST_F(ManifestV3WebRequestApiTest,
TestWebviewIdSpecifiedOnEvent_NoPermission) {
ASSERT_TRUE(StartEmbeddedTestServer());
static constexpr char kManifest[] =
R"({
"name": "MV3 WebRequest",
"version": "0.1",
"manifest_version": 3,
"permissions": ["webRequest"],
"host_permissions": [ "http://example.com/*" ],
"background": {"service_worker": "background.js"}
})";
// The extension tries to add a listener; this will fail asynchronously
// as a part of the webRequestInternal API trying to add the listener.
// This results in runtime.lastError being set, but since it's an
// internal API, there's no way for the extension to catch the error.
static constexpr char kBackgroundJs[] =
R"(let event = new chrome.webRequest.onBeforeRequest.constructor(
'webRequest.onBeforeRequest',
undefined,
undefined,
undefined,
1); // webViewInstanceId
event.addListener(() => {},
{urls: ['*://*.example.com/*']});)";
// Since we can't catch the error in the extension's JS, we instead listen to
// the error come into the error console.
ErrorConsoleTestObserver error_observer(1u, profile());
error_observer.EnableErrorCollection();
// Load the extension and wait for the error to come.
TestExtensionDir test_dir;
test_dir.WriteManifest(kManifest);
test_dir.WriteFile(FILE_PATH_LITERAL("background.js"), kBackgroundJs);
const Extension* extension = LoadExtension(test_dir.UnpackedPath());
ASSERT_TRUE(extension);
error_observer.WaitForErrors();
const ErrorList& errors =
ErrorConsole::Get(profile())->GetErrorsForExtension(extension->id());
ASSERT_EQ(1u, errors.size());
EXPECT_EQ(u"Unchecked runtime.lastError: Missing webview permission.",
errors[0]->message());
EXPECT_EQ(0u, web_request_router()->GetListenerCountForTesting(
profile(), "webRequest.onBeforeRequest"));
}
#if !BUILDFLAG(IS_ANDROID)
IN_PROC_BROWSER_TEST_F(ManifestV3WebRequestApiTest, RecordUkmOnNavigation) {
ASSERT_TRUE(StartEmbeddedTestServer());
TestExtensionDir test_dir1;
test_dir1.WriteManifest(R"({
"name": "MV3 WebRequest",
"version": "0.1",
"manifest_version": 3,
"content_scripts": [
{
"matches": ["<all_urls>"],
"js": ["contentscript.js"]
}
],
"permissions": [
"webRequest",
"webRequestBlocking",
"webRequestAuthProvider",
"declarativeNetRequest",
"declarativeNetRequestFeedback",
"declarativeNetRequestWithHostAccess"
],
"host_permissions": ["http://a.com/*"],
"background": {"service_worker": "background.js"}
})");
test_dir1.WriteFile(FILE_PATH_LITERAL("contentscript.js"), /*contents=*/"");
test_dir1.WriteFile(FILE_PATH_LITERAL("background.js"),
"chrome.test.sendMessage('ready');");
ASSERT_TRUE(LoadPolicyExtension(test_dir1));
// declarativeWebRequest is only supported by manifest version 2 or lower.
TestExtensionDir test_dir2;
test_dir2.WriteManifest(R"({
"name": "MV2 WebRequest",
"version": "0.1",
"manifest_version": 2,
"content_scripts": [
{
"matches": ["<all_urls>"],
"js": ["contentscript.js"]
}
],
"permissions": [
"declarativeWebRequest",
"http://b.com/*"
],
"background": {"scripts": ["background.js"], "persistent": true}
})");
test_dir2.WriteFile(FILE_PATH_LITERAL("contentscript.js"), /*contents=*/"");
test_dir2.WriteFile(FILE_PATH_LITERAL("background.js"),
"chrome.test.sendMessage('ready');");
ExtensionTestMessageListener listener("ready");
ASSERT_TRUE(LoadExtension(test_dir2.UnpackedPath()));
EXPECT_TRUE(listener.WaitUntilSatisfied());
base::RunLoop ukm_loop;
ukm::TestAutoSetUkmRecorder ukm_recorder;
ukm_recorder.SetOnAddEntryCallback(
ukm::builders::Extensions_OnNavigation::kEntryName,
base::BindLambdaForTesting([&]() {
if (ukm_recorder
.GetMergedEntriesByName(
ukm::builders::Extensions_OnNavigation::kEntryName)
.size() == 2) {
ukm_loop.Quit();
}
}));
const GURL kUrlA = embedded_test_server()->GetURL("a.com", "/simple.html");
EXPECT_TRUE(ui_test_utils::NavigateToURL(browser(), kUrlA));
const GURL kUrlB = embedded_test_server()->GetURL("b.com", "/simple.html");
EXPECT_TRUE(ui_test_utils::NavigateToURL(browser(), kUrlB));
// Waits until UKM data is recorded.
ukm_loop.Run();
const double kBucketSpacing = 2;
auto merged_entries = ukm_recorder.GetMergedEntriesByName(
ukm::builders::Extensions_OnNavigation::kEntryName);
EXPECT_EQ(2u, merged_entries.size());
for (const auto& entry : merged_entries) {
const ukm::mojom::UkmEntry* ukm_entry = entry.second.get();
const GURL& url =
ukm_recorder.GetSourceForSourceId(ukm_entry->source_id)->url();
ukm_recorder.ExpectEntrySourceHasUrl(ukm_entry, url);
ukm::TestAutoSetUkmRecorder::ExpectEntryMetric(
ukm_entry, "EnabledExtensionCount",
ukm::GetExponentialBucketMin(2u, kBucketSpacing));
ukm::TestAutoSetUkmRecorder::ExpectEntryMetric(
ukm_entry, "EnabledExtensionCount.InjectContentScript",
ukm::GetExponentialBucketMin(2u, kBucketSpacing));
ukm::TestAutoSetUkmRecorder::ExpectEntryMetric(
ukm_entry, "EnabledExtensionCount.HaveHostPermissions",
ukm::GetExponentialBucketMin(1u, kBucketSpacing));
if (url == kUrlA) {
ukm::TestAutoSetUkmRecorder::ExpectEntryMetric(
ukm_entry, "WebRequestAuthProviderPermissionCount",
ukm::GetExponentialBucketMin(1u, kBucketSpacing));
ukm::TestAutoSetUkmRecorder::ExpectEntryMetric(
ukm_entry, "WebRequestBlockingPermissionCount",
ukm::GetExponentialBucketMin(1u, kBucketSpacing));
ukm::TestAutoSetUkmRecorder::ExpectEntryMetric(
ukm_entry, "WebRequestPermissionCount",
ukm::GetExponentialBucketMin(1u, kBucketSpacing));
ukm::TestAutoSetUkmRecorder::ExpectEntryMetric(
ukm_entry, "DeclarativeNetRequestFeedbackPermissionCount",
ukm::GetExponentialBucketMin(1u, kBucketSpacing));
ukm::TestAutoSetUkmRecorder::ExpectEntryMetric(
ukm_entry, "DeclarativeNetRequestPermissionCount",
ukm::GetExponentialBucketMin(1u, kBucketSpacing));
ukm::TestAutoSetUkmRecorder::ExpectEntryMetric(
ukm_entry, "DeclarativeNetRequestWithHostAccessPermissionCount",
ukm::GetExponentialBucketMin(1u, kBucketSpacing));
ukm::TestAutoSetUkmRecorder::ExpectEntryMetric(
ukm_entry, "DeclarativeWebRequestPermissionCount",
ukm::GetExponentialBucketMin(0u, kBucketSpacing));
} else if (url == kUrlB) {
ukm::TestAutoSetUkmRecorder::ExpectEntryMetric(
ukm_entry, "WebRequestAuthProviderPermissionCount",
ukm::GetExponentialBucketMin(0u, kBucketSpacing));
ukm::TestAutoSetUkmRecorder::ExpectEntryMetric(
ukm_entry, "WebRequestBlockingPermissionCount",
ukm::GetExponentialBucketMin(0u, kBucketSpacing));
ukm::TestAutoSetUkmRecorder::ExpectEntryMetric(
ukm_entry, "WebRequestPermissionCount",
ukm::GetExponentialBucketMin(0u, kBucketSpacing));
ukm::TestAutoSetUkmRecorder::ExpectEntryMetric(
ukm_entry, "DeclarativeNetRequestFeedbackPermissionCount",
ukm::GetExponentialBucketMin(0u, kBucketSpacing));
ukm::TestAutoSetUkmRecorder::ExpectEntryMetric(
ukm_entry, "DeclarativeNetRequestPermissionCount",
ukm::GetExponentialBucketMin(0u, kBucketSpacing));
ukm::TestAutoSetUkmRecorder::ExpectEntryMetric(
ukm_entry, "DeclarativeNetRequestWithHostAccessPermissionCount",
ukm::GetExponentialBucketMin(0u, kBucketSpacing));
ukm::TestAutoSetUkmRecorder::ExpectEntryMetric(
ukm_entry, "DeclarativeWebRequestPermissionCount",
ukm::GetExponentialBucketMin(1u, kBucketSpacing));
} else {
NOTREACHED();
}
}
}
// Allows test to wait for the failure of a worker registration.
class WorkerRegistrationFailureObserver
: public ServiceWorkerTaskQueue::TestObserver {
public:
explicit WorkerRegistrationFailureObserver(const ExtensionId extension_id)
: extension_id_(extension_id) {
ServiceWorkerTaskQueue::SetObserverForTest(this);
}
~WorkerRegistrationFailureObserver() override {
ServiceWorkerTaskQueue::SetObserverForTest(nullptr);
}
blink::ServiceWorkerStatusCode WaitForWorkerRegistrationFailure() {
if (!status_code_) {
SCOPED_TRACE("Waiting for worker registration to fail");
failure_loop_.Run();
}
return *status_code_;
}
private:
void OnWorkerRegistrationFailed(
const ExtensionId& extension_id,
blink::ServiceWorkerStatusCode status_code) override {
if (extension_id == extension_id_) {
status_code_ = status_code;
failure_loop_.Quit();
}
}
ExtensionId extension_id_;
base::RunLoop failure_loop_;
std::optional<blink::ServiceWorkerStatusCode> status_code_;
};
// Allows test to wait for the call of `ResetURLLoaderFactories()` in
// WebRequestAPI.
class URLLoaderFactoriesResetWaiter : public WebRequestAPI::TestObserver {
public:
URLLoaderFactoriesResetWaiter() { WebRequestAPI::SetObserverForTest(this); }
~URLLoaderFactoriesResetWaiter() override {
WebRequestAPI::SetObserverForTest(nullptr);
}
URLLoaderFactoriesResetWaiter(const URLLoaderFactoriesResetWaiter&) = delete;
URLLoaderFactoriesResetWaiter& operator=(
const URLLoaderFactoriesResetWaiter&) = delete;
void WaitForResetURLLoaderFactoriesCalled() {
SCOPED_TRACE("Waiting for ResetURLLoaderFactories to be called");
url_loader_factory_reset_runloop_.Run();
}
private:
void OnDidResetURLLoaderFactories() override {
url_loader_factory_reset_runloop_.Quit();
}
base::RunLoop url_loader_factory_reset_runloop_;
};
class ManifestV3WebRequestApiTestWithSkipResetServiceWorkerURLLoaderFactories
: public ManifestV3WebRequestApiTest,
public testing::WithParamInterface<bool> {
public:
ManifestV3WebRequestApiTestWithSkipResetServiceWorkerURLLoaderFactories() {
feature_list_.InitWithFeatureState(
extensions_features::kSkipResetServiceWorkerURLLoaderFactories,
GetParam());
}
~ManifestV3WebRequestApiTestWithSkipResetServiceWorkerURLLoaderFactories()
override = default;
private:
base::test::ScopedFeatureList feature_list_;
};
// Tests that the call to `ResetURLLoaderFactories()` performed by WebRequestAPI
// doesn't break the registration process of other extensions.
// Regression test for https://crbug.com/394523691.
IN_PROC_BROWSER_TEST_P(
ManifestV3WebRequestApiTestWithSkipResetServiceWorkerURLLoaderFactories,
ResetURLLoaderFactoryDoesntBreakRegistration) {
// Skip if the proxy is forced since factories will not be reset in that case.
if (base::FeatureList::IsEnabled(
extensions_features::kForceWebRequestProxyForTest)) {
return;
}
bool feature_enabled = GetParam();
ASSERT_TRUE(StartEmbeddedTestServer());
// A simple extension that sends a message and waits for a response in its
// background script.
const ExtensionId extension_id("iegclhlplifhodhkoafiokenjoapiobj");
static constexpr const char kKey[] =
"MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAjzv7dI7Ygyh67VHE1DdidudpYf8P"
"Ffv8iucWvzO+3xpF/Dm5xNo7aQhPNiEaNfHwJQ7lsp4gc+C+4bbaVewBFspTruoSJhZc5uEf"
"qxwovJwN+v1/SUFXTXQmQBv6gs0qZB4gBbl4caNQBlqrFwAMNisnu1V6UROna8rOJQ90D7Nv"
"7TCwoVPKBfVshpFjdDOTeBg4iLctO3S/06QYqaTDrwVceSyHkVkvzBY6tc6mnYX0RZu78J9i"
"L8bdqwfllOhs69cqoHHgrLdI6JdOyiuh6pBP6vxMlzSKWJ3YTNjaQTPwfOYaLMuzdl0v+Ydz"
"afIzV9zwe4Xiskk+5JNGt8b2rQIDAQAB";
static constexpr char kManifest[] =
R"({
"name": "TestExtension",
"manifest_version": 3,
"version": "0.1",
"key": "%s",
"background": {"service_worker": "background.js"}
})";
static constexpr char kBackgroundJs[] =
R"(chrome.test.sendMessage('will_receive').then(() => {
console.log('received');
}))";
TestExtensionDir extension_dir;
extension_dir.WriteManifest(base::StringPrintf(kManifest, kKey));
extension_dir.WriteFile(FILE_PATH_LITERAL("background.js"), kBackgroundJs);
ServiceWorkerTaskQueue* task_queue = ServiceWorkerTaskQueue::Get(profile());
ASSERT_TRUE(task_queue);
WebRequestAPI* web_request_api =
BrowserContextKeyedAPIFactory<WebRequestAPI>::Get(profile());
ASSERT_TRUE(web_request_api);
// Listen to "will_receive" message from the extension.
ExtensionTestMessageListener will_receive_listener("will_receive",
ReplyBehavior::kWillReply);
// Listen to the completion of the registration storage.
service_worker_test_utils::TestServiceWorkerContextObserver
registration_observer(profile());
// Listen for a failure in the worker registration.
WorkerRegistrationFailureObserver worker_failure_observer(extension_id);
// Asynchronously load the extension so we can wait for a step in the loading
// process in the test.
std::optional<base::UnguessableToken> activation_token;
ChromeTestExtensionLoader(profile()).LoadUnpackedExtensionAsync(
extension_dir.UnpackedPath(),
base::BindLambdaForTesting([&](const Extension* extension) {
ASSERT_TRUE(extension);
activation_token =
task_queue->GetCurrentActivationToken(extension->id());
ASSERT_TRUE(activation_token.has_value());
}));
// ...and wait for the moment right after the worker is requested to start
// during the registration process.
registration_observer.WaitForStartWorkerMessageSent();
URLLoaderFactoriesResetWaiter url_loader_factories_reset_waiter;
// Simulate the effect of loading an extension with WebRequestAPI permissions.
// In other words, make sure we're proxying for the current profile.
// This will cause WebRequestAPI to attempt calling
// `ResetURLLoaderFactories()`. Because the extension is still in the early
// phases of starting its worker here, this would break its registration
// before it has a chance of being completed and stored.
// Instead, `ResetURLLoaderFactories()` will skip resetting extension service
// worker URLLoaderFactories used for fetching scripts and sub-resources.
// NOTE: We simulate the call to `ResetURLLoaderFactories()` rather than
// loading an extension with WebRequestAPI permissions, as that would take too
// long and won't trigger the bug in all cases.
web_request_api->ForceProxyForTesting();
if (feature_enabled) {
// SkipResetServiceWorkerURLLoaderFactories feature enabled: expect
// successful execution. Check that the worker is still running and
// functional.
registration_observer.WaitForWorkerStarted();
std::optional<WorkerId> worker_id = GetWorkerIdForExtension(extension_id);
EXPECT_TRUE(worker_id);
SCOPED_TRACE(
"Waiting for extension background to signal that it can send messages");
ASSERT_TRUE(will_receive_listener.WaitUntilSatisfied());
will_receive_listener.Reply("go");
url_loader_factories_reset_waiter.WaitForResetURLLoaderFactoriesCalled();
registration_observer.WaitForRegistrationStored();
} else {
// SkipResetServiceWorkerURLLoaderFactories feature disabled: expect worker
// registration to fail. We have observed that the registration can fail
// with either `kErrorStartWorkerFailed` or `kErrorNetwork` depending on
// when exactly it's interrupted.
auto status_code =
worker_failure_observer.WaitForWorkerRegistrationFailure();
EXPECT_NE(status_code, blink::ServiceWorkerStatusCode::kOk);
}
}
INSTANTIATE_TEST_SUITE_P(
All,
ManifestV3WebRequestApiTestWithSkipResetServiceWorkerURLLoaderFactories,
testing::Bool());
#endif // !BUILDFLAG(IS_ANDROID)
} // namespace extensions
|