1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497 5498 5499 5500 5501 5502 5503 5504 5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551 5552 5553 5554 5555 5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584 5585 5586 5587 5588 5589 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607 5608 5609 5610 5611 5612 5613 5614 5615 5616 5617 5618 5619 5620 5621 5622 5623 5624 5625 5626 5627 5628 5629 5630 5631 5632 5633 5634 5635 5636 5637 5638 5639 5640 5641 5642 5643 5644 5645 5646 5647 5648 5649 5650 5651 5652 5653 5654 5655 5656 5657 5658 5659 5660 5661 5662 5663 5664 5665 5666 5667 5668 5669 5670 5671 5672 5673 5674 5675 5676 5677 5678 5679 5680 5681 5682 5683 5684 5685 5686 5687 5688 5689 5690 5691 5692 5693 5694 5695 5696 5697 5698 5699 5700 5701 5702 5703 5704 5705 5706 5707 5708 5709 5710 5711 5712 5713 5714 5715 5716 5717 5718 5719 5720 5721 5722 5723 5724 5725 5726 5727 5728 5729 5730 5731 5732 5733 5734 5735 5736 5737 5738 5739 5740 5741 5742 5743 5744 5745 5746 5747 5748 5749 5750 5751 5752 5753 5754 5755 5756 5757 5758 5759 5760 5761 5762 5763 5764 5765 5766 5767 5768 5769 5770 5771 5772 5773 5774 5775 5776 5777 5778 5779 5780 5781 5782 5783 5784 5785 5786 5787 5788 5789 5790 5791 5792 5793 5794 5795 5796 5797 5798 5799 5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815 5816 5817 5818 5819 5820 5821 5822 5823 5824 5825 5826 5827 5828 5829 5830 5831 5832 5833 5834 5835 5836 5837 5838 5839 5840 5841 5842 5843 5844 5845 5846 5847 5848 5849 5850 5851 5852 5853 5854 5855 5856 5857 5858 5859 5860 5861 5862 5863 5864 5865 5866 5867 5868 5869 5870 5871 5872 5873 5874 5875 5876 5877 5878 5879 5880 5881 5882 5883 5884 5885 5886 5887 5888 5889 5890 5891 5892 5893 5894 5895 5896 5897 5898 5899 5900 5901 5902 5903 5904 5905 5906 5907 5908 5909 5910 5911 5912 5913 5914 5915 5916 5917 5918 5919 5920 5921 5922 5923 5924 5925 5926 5927 5928 5929 5930 5931 5932 5933 5934 5935 5936 5937 5938 5939 5940 5941 5942 5943 5944 5945 5946 5947 5948 5949 5950 5951 5952 5953 5954 5955 5956 5957 5958 5959 5960 5961 5962 5963 5964 5965 5966 5967 5968 5969 5970 5971 5972 5973 5974 5975 5976 5977 5978 5979 5980 5981 5982 5983 5984 5985 5986 5987 5988 5989 5990 5991 5992 5993 5994 5995 5996 5997 5998 5999 6000 6001 6002 6003 6004 6005 6006 6007 6008 6009 6010 6011 6012 6013 6014 6015 6016 6017 6018 6019 6020 6021 6022 6023 6024 6025 6026 6027 6028 6029 6030 6031 6032 6033 6034 6035 6036 6037 6038 6039 6040 6041 6042 6043 6044 6045 6046 6047 6048 6049 6050 6051 6052 6053 6054 6055 6056 6057 6058 6059 6060 6061 6062 6063 6064 6065 6066 6067 6068 6069 6070 6071 6072 6073 6074 6075 6076 6077 6078 6079 6080 6081 6082 6083 6084 6085 6086 6087 6088 6089 6090 6091 6092 6093 6094 6095 6096 6097 6098 6099 6100 6101 6102 6103 6104 6105 6106 6107 6108 6109 6110 6111 6112 6113 6114 6115 6116 6117 6118 6119 6120 6121 6122 6123 6124 6125 6126 6127 6128 6129 6130 6131 6132 6133 6134 6135 6136 6137 6138 6139 6140 6141 6142 6143 6144 6145 6146 6147 6148 6149 6150 6151 6152 6153 6154 6155 6156 6157 6158 6159 6160 6161 6162 6163 6164 6165 6166 6167 6168 6169 6170 6171 6172 6173 6174 6175 6176 6177 6178 6179 6180 6181 6182 6183 6184 6185 6186 6187 6188 6189 6190 6191 6192 6193 6194 6195 6196 6197 6198 6199 6200 6201 6202 6203 6204 6205 6206 6207 6208 6209 6210 6211 6212 6213 6214 6215 6216 6217 6218 6219 6220 6221 6222 6223 6224 6225 6226 6227 6228 6229 6230 6231 6232 6233 6234 6235 6236 6237 6238 6239 6240 6241 6242 6243 6244 6245 6246 6247 6248 6249 6250 6251 6252 6253 6254 6255 6256 6257 6258 6259 6260 6261 6262 6263 6264 6265 6266 6267 6268 6269 6270 6271 6272 6273 6274 6275 6276 6277 6278 6279 6280 6281 6282 6283 6284 6285 6286 6287 6288 6289 6290 6291 6292 6293 6294 6295 6296 6297 6298 6299 6300 6301 6302 6303 6304 6305 6306 6307 6308 6309 6310 6311 6312 6313 6314 6315 6316 6317 6318 6319 6320 6321 6322 6323 6324 6325 6326 6327 6328 6329 6330 6331 6332 6333 6334 6335 6336 6337 6338 6339 6340 6341 6342 6343 6344 6345 6346 6347 6348 6349 6350 6351 6352 6353 6354 6355 6356 6357 6358 6359 6360 6361 6362 6363 6364 6365 6366 6367 6368 6369 6370 6371 6372 6373 6374 6375 6376 6377 6378 6379 6380 6381 6382 6383 6384 6385 6386 6387 6388 6389 6390 6391 6392 6393 6394 6395 6396 6397 6398 6399 6400 6401 6402 6403 6404 6405 6406 6407 6408 6409 6410 6411 6412 6413 6414 6415 6416 6417 6418 6419 6420 6421 6422 6423 6424 6425 6426 6427 6428 6429 6430 6431 6432 6433 6434 6435 6436 6437 6438 6439 6440 6441 6442 6443 6444 6445 6446 6447 6448 6449 6450 6451 6452 6453 6454 6455 6456 6457 6458 6459 6460 6461 6462 6463 6464 6465 6466 6467 6468 6469 6470 6471 6472 6473 6474 6475 6476 6477 6478 6479 6480 6481 6482 6483 6484 6485 6486 6487 6488 6489 6490 6491 6492 6493 6494 6495 6496 6497 6498 6499 6500 6501 6502 6503 6504 6505 6506 6507 6508 6509 6510 6511 6512 6513 6514 6515 6516 6517 6518 6519 6520 6521 6522 6523 6524 6525 6526 6527 6528 6529 6530 6531 6532 6533 6534 6535 6536 6537 6538 6539 6540 6541 6542 6543 6544 6545 6546 6547 6548 6549 6550 6551 6552 6553 6554 6555 6556 6557 6558 6559 6560 6561 6562 6563 6564 6565 6566 6567 6568 6569 6570 6571 6572 6573 6574 6575 6576 6577 6578 6579 6580 6581 6582 6583 6584 6585 6586 6587 6588 6589 6590 6591 6592 6593 6594 6595 6596 6597 6598 6599 6600 6601 6602 6603 6604 6605 6606 6607 6608 6609 6610 6611 6612 6613 6614 6615 6616 6617 6618 6619 6620 6621 6622 6623 6624 6625 6626 6627 6628 6629 6630 6631 6632 6633 6634 6635 6636 6637 6638 6639 6640 6641 6642 6643 6644 6645 6646 6647 6648 6649 6650 6651 6652 6653 6654 6655 6656 6657 6658 6659 6660 6661 6662 6663 6664 6665 6666 6667 6668 6669 6670 6671 6672 6673 6674 6675 6676 6677 6678 6679 6680 6681 6682 6683 6684 6685 6686 6687 6688 6689 6690 6691 6692 6693 6694 6695 6696 6697 6698 6699 6700 6701 6702 6703 6704 6705 6706 6707 6708 6709 6710 6711 6712 6713 6714 6715 6716 6717 6718 6719 6720 6721 6722 6723 6724 6725 6726 6727 6728 6729 6730 6731 6732 6733 6734 6735 6736 6737 6738 6739 6740 6741 6742 6743 6744 6745 6746 6747 6748 6749 6750 6751 6752 6753 6754 6755 6756 6757 6758 6759 6760 6761 6762 6763 6764 6765 6766 6767 6768 6769 6770 6771 6772 6773 6774 6775 6776 6777 6778 6779 6780 6781 6782 6783 6784 6785 6786 6787 6788 6789 6790 6791 6792 6793 6794 6795 6796 6797 6798 6799 6800 6801 6802 6803 6804 6805 6806 6807 6808 6809 6810 6811 6812 6813 6814 6815 6816 6817 6818 6819 6820 6821 6822 6823 6824 6825 6826 6827 6828 6829 6830 6831 6832 6833 6834 6835 6836 6837 6838 6839 6840 6841 6842 6843 6844 6845 6846 6847 6848 6849 6850 6851 6852 6853 6854 6855 6856 6857 6858 6859 6860 6861 6862 6863 6864 6865 6866 6867 6868 6869 6870 6871 6872 6873 6874 6875 6876 6877 6878 6879 6880 6881 6882 6883 6884 6885 6886 6887 6888 6889 6890 6891 6892 6893 6894 6895 6896 6897 6898 6899 6900 6901 6902 6903 6904 6905 6906 6907 6908 6909 6910 6911 6912 6913 6914 6915 6916 6917 6918 6919 6920 6921 6922 6923 6924 6925 6926 6927 6928 6929 6930 6931 6932 6933 6934 6935 6936 6937 6938 6939 6940 6941 6942 6943 6944 6945 6946 6947 6948 6949 6950 6951 6952 6953 6954 6955 6956 6957 6958 6959 6960 6961 6962 6963 6964 6965 6966 6967 6968 6969 6970 6971 6972 6973 6974 6975 6976 6977 6978 6979 6980 6981 6982 6983 6984 6985 6986 6987 6988 6989 6990 6991 6992 6993 6994 6995 6996 6997 6998 6999 7000 7001 7002 7003 7004 7005 7006 7007 7008 7009 7010 7011 7012 7013 7014 7015 7016 7017 7018 7019 7020 7021 7022 7023 7024 7025 7026 7027 7028 7029 7030 7031 7032 7033 7034 7035 7036 7037 7038 7039 7040 7041 7042 7043 7044 7045 7046 7047 7048 7049 7050 7051 7052 7053 7054 7055 7056 7057 7058 7059 7060 7061 7062 7063 7064 7065 7066 7067 7068 7069 7070 7071 7072 7073 7074 7075 7076 7077 7078 7079 7080 7081 7082 7083 7084 7085 7086 7087 7088 7089 7090 7091 7092 7093 7094 7095 7096 7097 7098 7099 7100 7101 7102 7103 7104 7105 7106 7107 7108 7109 7110 7111 7112 7113 7114 7115 7116 7117 7118 7119 7120 7121 7122 7123 7124 7125 7126 7127 7128 7129 7130 7131 7132 7133 7134 7135 7136 7137 7138 7139 7140 7141 7142 7143 7144 7145 7146 7147 7148 7149 7150 7151 7152 7153 7154 7155 7156 7157 7158 7159 7160 7161 7162 7163 7164 7165 7166 7167 7168 7169 7170 7171 7172 7173 7174 7175 7176 7177 7178 7179 7180 7181 7182 7183 7184 7185 7186 7187 7188 7189 7190 7191 7192 7193 7194 7195 7196 7197 7198 7199 7200 7201 7202 7203 7204 7205 7206 7207 7208 7209 7210 7211 7212 7213 7214 7215 7216 7217 7218 7219 7220 7221 7222 7223 7224 7225 7226 7227 7228 7229 7230 7231 7232 7233 7234 7235 7236 7237 7238 7239 7240 7241 7242 7243 7244 7245 7246 7247 7248 7249 7250 7251 7252 7253 7254 7255 7256 7257 7258 7259 7260 7261 7262 7263 7264 7265 7266 7267 7268 7269 7270 7271 7272 7273 7274 7275 7276 7277 7278 7279 7280 7281 7282 7283 7284 7285 7286 7287 7288 7289 7290 7291 7292 7293 7294 7295 7296 7297 7298 7299 7300 7301 7302 7303 7304 7305 7306 7307 7308 7309 7310 7311 7312 7313 7314 7315 7316 7317 7318 7319 7320 7321 7322 7323 7324 7325 7326 7327 7328 7329 7330 7331 7332 7333 7334 7335 7336 7337 7338 7339 7340 7341 7342 7343 7344 7345 7346 7347 7348 7349 7350 7351 7352 7353 7354 7355 7356 7357 7358 7359 7360 7361 7362 7363 7364 7365 7366 7367 7368 7369 7370 7371 7372 7373 7374 7375 7376 7377 7378 7379 7380 7381 7382 7383 7384 7385 7386 7387 7388 7389 7390 7391 7392 7393 7394 7395 7396 7397 7398 7399 7400 7401 7402 7403 7404 7405 7406 7407 7408 7409 7410 7411 7412 7413 7414 7415 7416 7417 7418 7419 7420 7421 7422 7423 7424 7425 7426 7427 7428 7429 7430 7431 7432 7433 7434 7435 7436 7437 7438 7439 7440 7441 7442 7443 7444 7445 7446 7447 7448 7449 7450 7451 7452 7453 7454 7455 7456 7457 7458 7459 7460 7461 7462 7463 7464 7465 7466 7467 7468 7469 7470 7471 7472 7473 7474 7475 7476 7477 7478 7479 7480 7481 7482 7483 7484 7485 7486 7487 7488 7489 7490 7491 7492 7493 7494 7495 7496 7497 7498 7499 7500 7501 7502 7503 7504 7505 7506 7507 7508 7509 7510 7511 7512 7513 7514 7515 7516 7517 7518 7519 7520 7521 7522 7523 7524 7525 7526 7527 7528 7529 7530 7531 7532 7533 7534 7535 7536 7537 7538 7539 7540 7541 7542 7543 7544 7545 7546 7547 7548 7549 7550 7551 7552 7553 7554 7555 7556 7557 7558 7559 7560 7561 7562 7563 7564 7565 7566 7567 7568 7569 7570 7571 7572 7573 7574 7575 7576 7577 7578 7579 7580 7581 7582 7583 7584 7585 7586 7587 7588 7589 7590 7591 7592 7593 7594 7595 7596 7597 7598 7599 7600 7601 7602 7603 7604 7605 7606 7607 7608 7609 7610 7611 7612 7613 7614 7615 7616 7617 7618 7619 7620 7621 7622 7623 7624 7625 7626 7627 7628 7629 7630 7631 7632 7633 7634 7635 7636 7637 7638 7639 7640 7641 7642 7643 7644 7645 7646 7647 7648 7649 7650 7651 7652 7653 7654 7655 7656 7657 7658 7659 7660 7661 7662 7663 7664 7665 7666 7667 7668 7669 7670 7671 7672 7673 7674 7675 7676 7677 7678 7679 7680 7681 7682 7683 7684 7685 7686 7687 7688 7689 7690 7691 7692 7693 7694 7695 7696 7697 7698 7699 7700 7701 7702 7703 7704 7705 7706 7707 7708 7709 7710 7711 7712 7713 7714 7715 7716 7717 7718 7719 7720 7721 7722 7723 7724 7725 7726 7727 7728 7729 7730 7731 7732 7733 7734 7735 7736 7737 7738 7739 7740 7741 7742 7743 7744 7745 7746 7747 7748 7749 7750 7751 7752 7753 7754 7755 7756 7757 7758 7759 7760 7761 7762 7763 7764 7765 7766 7767 7768 7769 7770 7771 7772 7773 7774 7775 7776 7777 7778 7779 7780 7781 7782 7783 7784 7785 7786 7787 7788 7789 7790 7791 7792 7793 7794 7795 7796 7797 7798 7799 7800 7801 7802 7803 7804 7805 7806 7807 7808 7809 7810 7811 7812 7813 7814 7815 7816 7817 7818 7819 7820 7821 7822 7823 7824 7825 7826 7827 7828 7829 7830 7831 7832 7833 7834 7835 7836 7837 7838 7839 7840 7841 7842 7843 7844 7845 7846 7847 7848 7849 7850 7851 7852 7853 7854 7855 7856 7857 7858 7859 7860 7861 7862 7863 7864 7865 7866 7867 7868 7869 7870 7871 7872 7873 7874 7875 7876 7877 7878 7879 7880 7881 7882 7883 7884 7885 7886 7887 7888 7889 7890 7891 7892 7893 7894 7895 7896 7897 7898 7899 7900 7901 7902 7903 7904 7905 7906 7907 7908 7909 7910 7911 7912 7913 7914 7915 7916 7917 7918 7919 7920 7921 7922 7923 7924 7925 7926 7927 7928 7929 7930 7931 7932 7933 7934 7935 7936 7937 7938 7939 7940 7941 7942 7943 7944 7945 7946 7947 7948 7949 7950 7951 7952 7953 7954 7955 7956 7957 7958 7959 7960 7961 7962 7963 7964 7965 7966 7967 7968 7969 7970 7971 7972 7973 7974 7975 7976 7977 7978 7979 7980 7981 7982 7983 7984 7985 7986 7987 7988 7989 7990 7991 7992 7993 7994 7995 7996 7997 7998 7999 8000 8001 8002 8003 8004 8005 8006 8007 8008 8009 8010 8011 8012 8013 8014 8015 8016 8017 8018 8019 8020 8021 8022 8023 8024 8025 8026 8027 8028 8029 8030 8031 8032 8033 8034 8035 8036 8037 8038 8039 8040 8041 8042 8043 8044 8045 8046 8047 8048 8049 8050 8051 8052 8053 8054 8055 8056 8057 8058 8059 8060 8061 8062 8063 8064 8065 8066 8067 8068 8069 8070 8071 8072 8073 8074 8075 8076 8077 8078 8079 8080 8081 8082 8083 8084 8085 8086 8087 8088 8089 8090 8091 8092 8093 8094 8095 8096 8097 8098 8099 8100 8101 8102 8103 8104 8105 8106 8107 8108 8109 8110 8111 8112 8113 8114 8115 8116 8117 8118 8119 8120 8121 8122 8123 8124 8125 8126 8127 8128 8129 8130 8131 8132 8133 8134 8135 8136 8137 8138 8139 8140 8141 8142 8143 8144 8145 8146 8147 8148 8149 8150 8151 8152 8153 8154 8155 8156 8157 8158 8159 8160 8161 8162 8163 8164 8165 8166 8167 8168 8169 8170 8171 8172 8173 8174 8175 8176 8177 8178 8179 8180 8181 8182 8183 8184 8185 8186 8187 8188 8189 8190 8191 8192 8193 8194 8195 8196 8197 8198 8199 8200 8201 8202 8203 8204 8205 8206 8207 8208 8209 8210 8211 8212 8213 8214 8215 8216 8217 8218 8219 8220 8221 8222 8223 8224 8225 8226 8227 8228 8229 8230 8231 8232 8233 8234 8235 8236 8237 8238 8239 8240 8241 8242 8243 8244 8245 8246 8247 8248 8249 8250 8251 8252 8253 8254 8255 8256 8257 8258 8259 8260 8261 8262 8263 8264 8265 8266 8267 8268 8269 8270 8271 8272 8273 8274 8275 8276 8277 8278 8279 8280 8281 8282 8283 8284 8285 8286 8287 8288 8289 8290 8291 8292 8293 8294 8295 8296 8297 8298 8299 8300 8301 8302 8303 8304 8305 8306 8307 8308 8309 8310 8311 8312 8313 8314 8315 8316 8317 8318 8319 8320 8321 8322 8323 8324 8325 8326 8327 8328 8329 8330 8331 8332 8333 8334 8335 8336 8337 8338 8339 8340 8341 8342 8343 8344 8345 8346 8347 8348 8349 8350 8351 8352 8353 8354 8355 8356 8357 8358 8359 8360 8361 8362 8363 8364 8365 8366 8367 8368 8369 8370 8371 8372 8373 8374 8375 8376 8377 8378 8379 8380 8381 8382 8383 8384 8385 8386 8387 8388 8389 8390 8391 8392 8393 8394 8395 8396 8397 8398 8399 8400 8401 8402 8403 8404 8405 8406 8407 8408 8409 8410 8411 8412 8413 8414 8415 8416 8417 8418 8419 8420 8421 8422 8423 8424 8425 8426 8427 8428 8429 8430 8431 8432 8433 8434 8435 8436 8437 8438 8439 8440 8441 8442 8443 8444 8445 8446 8447 8448 8449 8450 8451 8452 8453 8454 8455 8456 8457 8458 8459 8460 8461 8462 8463 8464 8465 8466 8467 8468 8469 8470 8471 8472 8473 8474 8475 8476 8477 8478 8479 8480 8481 8482 8483 8484 8485 8486 8487 8488 8489 8490 8491 8492 8493 8494 8495 8496 8497 8498 8499 8500 8501 8502 8503 8504 8505 8506 8507 8508 8509 8510 8511 8512 8513 8514 8515 8516 8517 8518 8519 8520 8521 8522 8523 8524 8525 8526 8527 8528 8529 8530 8531 8532 8533 8534 8535 8536 8537 8538 8539 8540 8541 8542 8543 8544 8545 8546 8547 8548 8549 8550 8551 8552 8553 8554 8555 8556 8557 8558 8559 8560 8561 8562 8563 8564 8565 8566 8567 8568 8569 8570 8571 8572 8573 8574 8575 8576 8577 8578 8579 8580 8581 8582 8583 8584 8585 8586 8587 8588 8589 8590 8591 8592 8593 8594 8595 8596 8597 8598 8599 8600 8601 8602 8603 8604 8605 8606 8607 8608 8609 8610 8611 8612 8613 8614 8615 8616 8617 8618 8619 8620 8621 8622 8623 8624 8625 8626 8627 8628 8629 8630 8631 8632 8633 8634 8635 8636 8637 8638 8639 8640 8641 8642 8643 8644 8645 8646 8647 8648 8649 8650 8651 8652 8653 8654 8655 8656 8657 8658 8659 8660 8661 8662 8663 8664 8665 8666 8667 8668 8669 8670 8671 8672 8673 8674 8675 8676 8677 8678 8679 8680 8681 8682 8683 8684 8685 8686 8687 8688 8689 8690 8691 8692 8693 8694 8695 8696 8697 8698 8699 8700 8701 8702 8703 8704 8705 8706 8707 8708 8709 8710 8711 8712 8713 8714 8715 8716 8717 8718 8719 8720 8721 8722 8723 8724 8725 8726 8727 8728 8729 8730 8731 8732 8733 8734 8735 8736 8737 8738 8739 8740 8741 8742 8743 8744 8745 8746 8747 8748 8749 8750 8751 8752 8753 8754 8755 8756 8757 8758 8759 8760 8761 8762 8763 8764 8765 8766 8767 8768 8769 8770 8771 8772 8773 8774 8775 8776 8777 8778 8779 8780 8781 8782 8783 8784 8785 8786 8787 8788 8789 8790 8791 8792 8793 8794 8795 8796 8797 8798 8799 8800 8801 8802 8803 8804 8805 8806 8807 8808 8809 8810 8811 8812 8813 8814 8815 8816 8817 8818 8819 8820 8821 8822 8823 8824 8825 8826 8827 8828 8829 8830 8831 8832 8833 8834 8835 8836 8837 8838 8839 8840 8841 8842 8843 8844 8845 8846 8847 8848 8849 8850 8851 8852 8853 8854 8855 8856 8857 8858 8859 8860 8861 8862 8863 8864 8865 8866 8867 8868 8869 8870 8871 8872 8873 8874 8875 8876 8877 8878 8879 8880 8881 8882 8883 8884 8885 8886 8887 8888 8889 8890 8891 8892 8893 8894 8895 8896 8897 8898 8899 8900 8901 8902 8903 8904 8905 8906 8907 8908 8909 8910 8911 8912 8913 8914 8915 8916 8917 8918 8919 8920 8921 8922 8923 8924 8925 8926 8927 8928 8929 8930 8931 8932 8933 8934 8935 8936 8937 8938 8939 8940 8941 8942 8943 8944 8945 8946 8947 8948 8949 8950 8951 8952 8953 8954 8955 8956 8957 8958 8959 8960 8961 8962 8963 8964 8965 8966 8967 8968 8969 8970 8971 8972 8973 8974 8975 8976 8977 8978 8979 8980 8981 8982 8983 8984 8985 8986 8987 8988 8989 8990 8991 8992 8993 8994 8995 8996 8997 8998 8999 9000 9001 9002 9003 9004 9005 9006 9007 9008 9009 9010 9011 9012 9013 9014 9015 9016 9017 9018 9019 9020 9021 9022 9023 9024 9025 9026 9027 9028 9029 9030 9031 9032 9033 9034 9035 9036 9037 9038 9039 9040
|
// Copyright 2017 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <stddef.h>
#include <algorithm>
#include <array>
#include <memory>
#include <optional>
#include <set>
#include <string>
#include <utility>
#include <vector>
#include "base/auto_reset.h"
#include "base/containers/contains.h"
#include "base/containers/to_value_list.h"
#include "base/files/file_util.h"
#include "base/files/scoped_temp_dir.h"
#include "base/functional/bind.h"
#include "base/json/json_string_value_serializer.h"
#include "base/memory/raw_ptr.h"
#include "base/memory/scoped_refptr.h"
#include "base/path_service.h"
#include "base/rand_util.h"
#include "base/run_loop.h"
#include "base/sequence_checker.h"
#include "base/strings/string_number_conversions.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/single_thread_task_runner.h"
#include "base/test/bind.h"
#include "base/test/metrics/histogram_tester.h"
#include "base/test/scoped_feature_list.h"
#include "base/test/simple_test_clock.h"
#include "base/test/test_timeouts.h"
#include "base/test/values_test_util.h"
#include "base/thread_annotations.h"
#include "base/threading/thread_restrictions.h"
#include "base/time/time.h"
#include "base/values.h"
#include "build/build_config.h"
#include "chrome/browser/extensions/extension_action_runner.h"
#include "chrome/browser/extensions/extension_browsertest.h"
#include "chrome/browser/extensions/extension_tab_util.h"
#include "chrome/browser/extensions/extension_util.h"
#include "chrome/browser/extensions/load_error_reporter.h"
#include "chrome/browser/extensions/permissions/active_tab_permission_granter.h"
#include "chrome/browser/extensions/permissions/scripting_permissions_modifier.h"
#include "chrome/browser/extensions/test_extension_action_dispatcher_observer.h"
#include "chrome/browser/net/profile_network_context_service.h"
#include "chrome/browser/net/profile_network_context_service_factory.h"
#include "chrome/browser/privacy_sandbox/privacy_sandbox_settings_factory.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/common/chrome_features.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/webui_url_constants.h"
#include "components/prefs/pref_service.h"
#include "components/privacy_sandbox/privacy_sandbox_attestations/privacy_sandbox_attestations.h"
#include "components/privacy_sandbox/privacy_sandbox_attestations/scoped_privacy_sandbox_attestations.h"
#include "components/privacy_sandbox/privacy_sandbox_settings.h"
#include "components/proxy_config/proxy_config_dictionary.h"
#include "components/proxy_config/proxy_config_pref_names.h"
#include "components/version_info/channel.h"
#include "components/web_package/web_bundle_builder.h"
#include "content/public/browser/browser_context.h"
#include "content/public/browser/browser_task_traits.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/navigation_entry.h"
#include "content/public/browser/render_frame_host.h"
#include "content/public/browser/storage_partition.h"
#include "content/public/browser/webui_config_map.h"
#include "content/public/common/content_features.h"
#include "content/public/common/url_constants.h"
#include "content/public/test/back_forward_cache_util.h"
#include "content/public/test/browser_test.h"
#include "content/public/test/browser_test_utils.h"
#include "content/public/test/privacy_sandbox_coordinator_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/test_utils.h"
#include "content/public/test/web_transport_simple_test_server.h"
#include "extensions/browser/api/declarative_net_request/action_tracker.h"
#include "extensions/browser/api/declarative_net_request/composite_matcher.h"
#include "extensions/browser/api/declarative_net_request/constants.h"
#include "extensions/browser/api/declarative_net_request/declarative_net_request_api.h"
#include "extensions/browser/api/declarative_net_request/file_backed_ruleset_source.h"
#include "extensions/browser/api/declarative_net_request/prefs_helper.h"
#include "extensions/browser/api/declarative_net_request/rules_monitor_service.h"
#include "extensions/browser/api/declarative_net_request/ruleset_manager.h"
#include "extensions/browser/api/declarative_net_request/ruleset_matcher.h"
#include "extensions/browser/api/declarative_net_request/test_utils.h"
#include "extensions/browser/api/declarative_net_request/utils.h"
#include "extensions/browser/api/web_request/web_request_api.h"
#include "extensions/browser/api/web_request/web_request_info.h"
#include "extensions/browser/blocked_action_type.h"
#include "extensions/browser/browsertest_util.h"
#include "extensions/browser/disable_reason.h"
#include "extensions/browser/extension_action.h"
#include "extensions/browser/extension_action_manager.h"
#include "extensions/browser/extension_prefs.h"
#include "extensions/browser/extension_registry.h"
#include "extensions/browser/extension_util.h"
#include "extensions/browser/install_prefs_helper.h"
#include "extensions/browser/test_extension_registry_observer.h"
#include "extensions/browser/warning_service.h"
#include "extensions/browser/warning_set.h"
#include "extensions/common/api/declarative_net_request/constants.h"
#include "extensions/common/api/declarative_net_request/test_utils.h"
#include "extensions/common/api/extension_action/action_info.h"
#include "extensions/common/constants.h"
#include "extensions/common/error_utils.h"
#include "extensions/common/extension_features.h"
#include "extensions/common/extension_id.h"
#include "extensions/common/features/feature_channel.h"
#include "extensions/common/file_util.h"
#include "extensions/common/permissions/permissions_data.h"
#include "extensions/common/switches.h"
#include "extensions/common/url_pattern.h"
#include "extensions/common/url_pattern_set.h"
#include "extensions/test/extension_background_page_waiter.h"
#include "extensions/test/extension_test_message_listener.h"
#include "ipc/ipc_message.h"
#include "net/base/net_errors.h"
#include "net/dns/mock_host_resolver.h"
#include "net/http/http_request_headers.h"
#include "net/http/http_status_code.h"
#include "net/test/embedded_test_server/controllable_http_response.h"
#include "net/test/embedded_test_server/default_handlers.h"
#include "net/test/embedded_test_server/embedded_test_server.h"
#include "net/test/embedded_test_server/http_request.h"
#include "net/test/embedded_test_server/http_response.h"
#include "net/test/embedded_test_server/install_default_websocket_handlers.h"
#include "net/test/spawned_test_server/spawned_test_server.h"
#include "net/test/test_data_directory.h"
#include "net/traffic_annotation/network_traffic_annotation_test_helper.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 "testing/gmock/include/gmock/gmock.h"
#include "third_party/blink/public/common/features.h"
#include "ui/webui/untrusted_web_ui_browsertest_util.h"
#if !BUILDFLAG(IS_ANDROID)
#include "chrome/browser/extensions/extension_service.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_tabstrip.h"
#include "chrome/browser/ui/tabs/tab_strip_model.h"
#include "chrome/test/base/ui_test_utils.h"
#endif
namespace extensions::declarative_net_request {
namespace {
namespace dnr_api = api::declarative_net_request;
using ::testing::ElementsAreArray;
using ::testing::UnorderedElementsAre;
using ::testing::UnorderedElementsAreArray;
constexpr char kDefaultRulesetID[] = "id";
// Returns true if |window.scriptExecuted| is true for the given frame.
bool WasFrameWithScriptLoaded(content::RenderFrameHost* render_frame_host) {
if (!render_frame_host) {
return false;
}
return content::EvalJs(render_frame_host, "!!window.scriptExecuted")
.ExtractBool();
}
// Helper to wait for ruleset load in response to extension load.
class RulesetLoadObserver : public RulesMonitorService::TestObserver {
public:
RulesetLoadObserver(RulesMonitorService* service,
const ExtensionId& extension_id)
: service_(service), extension_id_(extension_id) {
service_->SetObserverForTest(this);
}
~RulesetLoadObserver() override { service_->SetObserverForTest(nullptr); }
void Wait() { run_loop_.Run(); }
private:
// RulesMonitorService::TestObserver override:
void OnRulesetLoadComplete(const ExtensionId& extension_id) override {
if (extension_id_ == extension_id)
run_loop_.Quit();
}
const raw_ptr<RulesMonitorService> service_;
const ExtensionId extension_id_;
base::RunLoop run_loop_;
};
// Helper to block ruleset loads from completing on the UI thread.
class RulesetLoaderThrottle {
public:
RulesetLoaderThrottle() {
throttle_callback_ = base::BindRepeating(
&RulesetLoaderThrottle::AddPendingRequest, base::Unretained(this));
ruleset_throttle_override_ =
RulesMonitorService::SetLoadRulesetThrottleCallbackForTesting(
&throttle_callback_);
}
~RulesetLoaderThrottle() = default;
// Waits until a ruleset load request is enqueued. Once the caller is
// unblocked, it can do whatever it pleases before letting all the pending
// load ruleset requests finish on the UI thread by calling Resume().
void WaitForLoaderRequest() {
if (pending_requests_.empty()) {
base::RunLoop run_loop;
quit_closure_ = run_loop.QuitWhenIdleClosure();
run_loop.Run();
}
ASSERT_TRUE(!pending_requests_.empty());
}
// Resumes all pending requests by letting them finish on the UI thread and
// resets the throttle.
void Resume() {
ruleset_throttle_override_.reset();
for (auto& request : pending_requests_) {
std::move(request).Run();
}
}
private:
// Queues a ruleset load request in `pending_requests_` and unblocks the
// caller of WaitForLoaderRequest() if needed.
void AddPendingRequest(base::OnceClosure request) {
pending_requests_.push_back(std::move(request));
if (quit_closure_) {
std::move(quit_closure_).Run();
}
}
// A list of ruleset load requests that are pending completion on the UI
// thread.
std::vector<base::OnceClosure> pending_requests_;
LoadRulesetThrottleCallback throttle_callback_;
std::optional<base::AutoReset<LoadRulesetThrottleCallback*>>
ruleset_throttle_override_;
base::OnceClosure quit_closure_;
};
class DeclarativeNetRequestBrowserTest
: public ExtensionBrowserTest,
public ::testing::WithParamInterface<
::testing::tuple<ExtensionLoadType, bool>> {
public:
DeclarativeNetRequestBrowserTest() {
feature_list_.InitWithFeatures(
/*enabled_features=*/
{network::features::kInterestGroupStorage,
blink::features::kAdInterestGroupAPI, blink::features::kFledge,
blink::features::kFledgeBiddingAndAuctionServer,
blink::features::kFencedFrames,
blink::features::kFencedFramesAPIChanges,
blink::features::kFencedFramesDefaultMode,
features::kPrivacySandboxAdsAPIsOverride},
/*disabled_features=*/
{// TODO(crbug.com/40248833): Use HTTPS URLs in tests to avoid
// having to disable these features.
features::kHttpsUpgrades, features::kHttpsFirstModeIncognito});
net::test_server::RegisterDefaultHandlers(embedded_test_server());
}
DeclarativeNetRequestBrowserTest(const DeclarativeNetRequestBrowserTest&) =
delete;
DeclarativeNetRequestBrowserTest& operator=(
const DeclarativeNetRequestBrowserTest&) = delete;
// Returns the path of the files served by the EmbeddedTestServer.
static base::FilePath GetHttpServerPath() {
base::FilePath test_root_path;
base::PathService::Get(chrome::DIR_TEST_DATA, &test_root_path);
test_root_path = test_root_path.AppendASCII("extensions")
.AppendASCII("declarative_net_request");
return test_root_path;
}
void SetUpCommandLine(base::CommandLine* command_line) override {
ExtensionBrowserTest::SetUpCommandLine(command_line);
if (GetAllowChromeURLs()) {
command_line->AppendSwitch(switches::kExtensionsOnChromeURLs);
} else {
command_line->RemoveSwitch(switches::kExtensionsOnChromeURLs);
}
}
// ExtensionBrowserTest overrides:
void SetUpOnMainThread() override {
ExtensionBrowserTest::SetUpOnMainThread();
embedded_test_server()->ServeFilesFromDirectory(GetHttpServerPath());
embedded_test_server()->RegisterRequestMonitor(
base::BindRepeating(&DeclarativeNetRequestBrowserTest::MonitorRequest,
base::Unretained(this)));
content::SetupCrossSiteRedirector(embedded_test_server());
ASSERT_TRUE(embedded_test_server()->Start());
// Map all hosts to localhost.
host_resolver()->AddRule("*", "127.0.0.1");
CreateTempDir();
InitializeRulesetManagerObserver();
}
void TearDownOnMainThread() override {
// Ensure |ruleset_manager_observer_| gets destructed on the UI thread.
ruleset_manager_observer_.reset();
ExtensionBrowserTest::TearDownOnMainThread();
}
// Handler to monitor the requests which reach the EmbeddedTestServer. This
// will be run on EmbeddedTestServers' IO threads. Public so it can be bound
// in test bodies.
void MonitorRequest(const net::test_server::HttpRequest& request) {
base::AutoLock lock(requests_to_server_lock_);
requests_to_server_[request.GetURL()] = request;
if (url_to_wait_for_ == request.GetURL()) {
ASSERT_TRUE(wait_for_request_run_loop_);
url_to_wait_for_ = GURL();
wait_for_request_run_loop_->Quit();
}
}
protected:
ExtensionLoadType GetLoadType() { return testing::get<0>(GetParam()); }
bool GetAllowChromeURLs() { return testing::get<1>(GetParam()); }
// Returns the number of extensions with active rulesets.
size_t extensions_with_rulesets_count() {
return ruleset_manager()->GetMatcherCountForTest();
}
RulesetManagerObserver* ruleset_manager_observer() {
return ruleset_manager_observer_.get();
}
// Waits till the number of extensions with active rulesets is |count|.
void WaitForExtensionsWithRulesetsCount(size_t count) {
ruleset_manager_observer()->WaitForExtensionsWithRulesetsCount(count);
}
#if !BUILDFLAG(IS_ANDROID)
content::WebContents* web_contents(Browser* browser) const {
return browser->tab_strip_model()->GetActiveWebContents();
}
#endif
content::WebContents* web_contents() const { return GetActiveWebContents(); }
content::RenderFrameHost* GetPrimaryMainFrame() const {
return GetActiveWebContents()->GetPrimaryMainFrame();
}
content::RenderFrameHost* GetFrameByName(const std::string& name) const {
return content::FrameMatchingPredicate(
web_contents()->GetPrimaryPage(),
base::BindRepeating(&content::FrameMatchesName, name));
}
content::PageType GetPageType(content::WebContents* web_contents) const {
return web_contents->GetController().GetLastCommittedEntry()->GetPageType();
}
RulesMonitorService* rules_monitor_service() {
return RulesMonitorService::Get(profile());
}
RulesetManager* ruleset_manager() {
return rules_monitor_service()->ruleset_manager();
}
const Extension* last_loaded_extension() {
return extension_registry()->enabled_extensions().GetByID(
last_loaded_extension_id());
}
content::PageType GetPageType() const {
return GetPageType(GetActiveWebContents());
}
std::string GetPageBody() const {
const char* script = "document.body.innerText.trim()";
return content::EvalJs(web_contents(), script).ExtractString();
}
std::string GetPageCookie() const {
const char* script = "document.cookie";
return content::EvalJs(web_contents(), script).ExtractString();
}
void set_config_flags(unsigned flags) { flags_ = flags; }
// Loads an extension with the given `rulesets` in the given `directory`.
// Generates a fatal failure if the extension failed to load. `hosts`
// specifies the host permissions the extensions should have. Waits until the
// ruleset is loaded.
void LoadExtensionWithRulesets(const std::vector<TestRulesetInfo>& rulesets,
const std::string& directory,
const std::vector<std::string>& hosts) {
bool has_enabled_rulesets = std::ranges::any_of(
rulesets,
[](const TestRulesetInfo& ruleset) { return ruleset.enabled; });
size_t expected_extensions_with_rulesets_count_change =
has_enabled_rulesets ? 1 : 0;
LoadExtensionInternal(rulesets, directory, hosts,
expected_extensions_with_rulesets_count_change,
/*has_dynamic_ruleset=*/false,
/*is_extension_update=*/false,
/*is_delayed_update=*/false);
}
// Similar to LoadExtensionWithRulesets above but updates the last loaded
// extension instead. `expected_extensions_with_rulesets_count_change`
// corresponds to the expected change in the number of extensions with
// rulesets after extension update. `has_dynamic_ruleset` should be true if
// the installed extension has a dynamic ruleset. If `is_delayed_update` is
// set to true, then a delayed update will be simulated by receiving the new
// version's update first, then reloading the extension to finish the update.
void UpdateLastLoadedExtension(
const std::vector<TestRulesetInfo>& new_rulesets,
const std::string& new_directory,
const std::vector<std::string>& new_hosts,
int expected_extensions_with_rulesets_count_change,
bool has_dynamic_ruleset,
bool is_delayed_update) {
LoadExtensionInternal(new_rulesets, new_directory, new_hosts,
expected_extensions_with_rulesets_count_change,
has_dynamic_ruleset, /*is_extension_update=*/true,
is_delayed_update);
}
// Specialization of LoadExtensionWithRulesets above for an extension with a
// single static ruleset.
void LoadExtensionWithRules(const std::vector<TestRule>& rules,
const std::string& directory,
const std::vector<std::string>& hosts) {
constexpr char kJSONRulesFilename[] = "rules_file.json";
LoadExtensionWithRulesets(
{TestRulesetInfo(kDefaultRulesetID, kJSONRulesFilename,
ToListValue(rules))},
directory, hosts);
}
// Returns a url with |filter| as a substring.
GURL GetURLForFilter(const std::string& filter) const {
return embedded_test_server()->GetURL(
"abc.com", "/pages_with_script/index.html?" + filter);
}
void LoadExtensionWithRules(const std::vector<TestRule>& rules) {
LoadExtensionWithRules(rules, "test_extension", {} /* hosts */);
}
// Returns true if the navigation to given |url| is blocked.
bool IsNavigationBlocked(const GURL& url) {
content::WebContents* web_contents = GetActiveWebContents();
// content::NavigateToURL() returns false if `url` failed to load.
bool loaded = content::NavigateToURL(web_contents, url);
if (!loaded && content::IsLastCommittedEntryOfPageType(
web_contents, content::PageType::PAGE_TYPE_ERROR)) {
return true;
}
// Mimic ui_test_utils::NavigateToURL().
content::WaitForLoadStop(web_contents);
return !WasFrameWithScriptLoaded(GetPrimaryMainFrame());
}
void VerifyNavigations(const std::vector<GURL>& expected_blocked_urls,
const std::vector<GURL>& expected_allowed_urls) {
for (const GURL& url : expected_blocked_urls)
EXPECT_TRUE(IsNavigationBlocked(url)) << url;
for (const GURL& url : expected_allowed_urls)
EXPECT_FALSE(IsNavigationBlocked(url)) << url;
}
std::string ExecuteScriptInBackgroundPageAndReturnString(
const ExtensionId& extension_id,
const std::string& script,
browsertest_util::ScriptUserActivation script_user_activation =
browsertest_util::ScriptUserActivation::kActivate) {
base::Value result = ExecuteScriptInBackgroundPage(extension_id, script,
script_user_activation);
return result.is_string() ? result.GetString() : "";
}
TestRule CreateMainFrameBlockRule(const std::string& filter) {
TestRule rule = CreateGenericRule();
rule.condition->url_filter = filter;
rule.condition->resource_types = std::vector<std::string>({"main_frame"});
return rule;
}
void AddDynamicRules(const ExtensionId& extension_id,
const std::vector<TestRule>& rules) {
UpdateRules(extension_id, {}, rules, RulesetScope::kDynamic);
}
void RemoveDynamicRules(const ExtensionId& extension_id,
const std::vector<int>& rule_ids) {
UpdateRules(extension_id, rule_ids, {}, RulesetScope::kDynamic);
}
void UpdateSessionRules(const ExtensionId& extension_id,
const std::vector<int>& rule_ids_to_remove,
const std::vector<TestRule>& rules_to_add) {
UpdateRules(extension_id, rule_ids_to_remove, rules_to_add,
RulesetScope::kSession);
}
void UpdateEnabledRulesets(
const ExtensionId& extension_id,
const std::vector<std::string>& ruleset_ids_to_remove,
const std::vector<std::string>& ruleset_ids_to_add) {
std::string result = UpdateEnabledRulesetsInternal(
extension_id, ruleset_ids_to_remove, ruleset_ids_to_add);
ASSERT_EQ("success", result);
}
void UpdateEnabledRulesetsAndFail(
const ExtensionId& extension_id,
const std::vector<std::string>& ruleset_ids_to_remove,
const std::vector<std::string>& ruleset_ids_to_add,
std::string expected_error) {
std::string result = UpdateEnabledRulesetsInternal(
extension_id, ruleset_ids_to_remove, ruleset_ids_to_add);
ASSERT_NE("success", result);
EXPECT_EQ(expected_error, result);
}
void UpdateStaticRules(const ExtensionId& extension_id,
const std::string& ruleset_id,
const std::vector<int>& rule_ids_to_disable,
const std::vector<int>& rule_ids_to_enable) {
static constexpr char kScript[] = R"(
chrome.declarativeNetRequest.updateStaticRules(
{rulesetId: $1, disableRuleIds: $2, enableRuleIds: $3},
() => {
chrome.test.sendScriptResult(chrome.runtime.lastError ?
chrome.runtime.lastError.message : 'success');
});
)";
base::Value::List ids_to_disable = base::ToValueList(rule_ids_to_disable);
base::Value::List ids_to_enable = base::ToValueList(rule_ids_to_enable);
const std::string script = content::JsReplace(
kScript, ruleset_id, base::Value(std::move(ids_to_disable)),
base::Value(std::move(ids_to_enable)));
std::string result =
ExecuteScriptInBackgroundPageAndReturnString(extension_id, script);
ASSERT_EQ("success", result);
}
base::flat_set<int> GetDisabledRuleIdsFromMatcher(
const std::string& ruleset_id_string) {
return GetDisabledRuleIdsFromMatcherForTesting(
*ruleset_manager(), *last_loaded_extension(), ruleset_id_string);
}
void VerifyGetDisabledRuleIds(
const ExtensionId& extension_id,
const std::string& ruleset_id_string,
const std::vector<int>& expected_disabled_rule_ids) {
static constexpr char kScript[] = R"(
chrome.declarativeNetRequest.getDisabledRuleIds(
{rulesetId: $1},
(disabledRuleIds) => {
if (chrome.runtime.lastError) {
chrome.test.sendScriptResult(
'error: ' + chrome.runtime.lastError.message);
return;
}
if (!disabledRuleIds) {
chrome.test.sendScriptResult('no result');
return;
}
let actual = JSON.stringify(disabledRuleIds);
let expected = JSON.stringify($2);
chrome.test.sendScriptResult(actual == expected
? 'success'
: ['expected:', expected, '; actual:', actual].join(''));
});
)";
base::Value::List expected = base::ToValueList(expected_disabled_rule_ids);
std::string result = ExecuteScriptInBackgroundPageAndReturnString(
extension_id,
content::JsReplace(kScript, ruleset_id_string, std::move(expected)));
ASSERT_EQ("success", result);
}
void VerifyPublicRulesetIds(
const Extension* extension,
const std::vector<std::string>& expected_ruleset_ids) {
ASSERT_TRUE(extension);
CompositeMatcher* composite_matcher =
ruleset_manager()->GetMatcherForExtension(extension->id());
if (!composite_matcher) {
// The extension could've been loaded with no enabled rulesets. This is
// the only case where `composite_matcher` may be null.
ASSERT_TRUE(expected_ruleset_ids.empty());
return;
}
ASSERT_TRUE(composite_matcher);
EXPECT_THAT(GetPublicRulesetIDs(*extension, *composite_matcher),
UnorderedElementsAreArray(expected_ruleset_ids));
}
std::string SetExtensionActionOptions(const ExtensionId& extension_id,
const std::string& options) {
static constexpr char kSetExtensionActionOptionsScript[] = R"(
chrome.declarativeNetRequest.setExtensionActionOptions(%s,
() => {
chrome.test.sendScriptResult(chrome.runtime.lastError ?
chrome.runtime.lastError.message : 'success');
}
);
)";
return ExecuteScriptInBackgroundPageAndReturnString(
extension_id,
base::StringPrintf(kSetExtensionActionOptionsScript, options.c_str()));
}
// Navigates to `url` in the active tab. Blocks until the navigation
// completes. The navigation may result in an error page.
void NavigateToURL(const GURL& url) {
content::WebContents* web_contents = GetActiveWebContents();
content::NavigateToURLBlockUntilNavigationsComplete(
web_contents, url, /*number_of_navigations=*/1,
/*ignore_uncommitted_navigations=*/false);
// Mimic ui_test_utils::NavigateToURL().
content::WaitForLoadStop(web_contents);
}
// Navigates frame with name |frame_name| to |url|.
void NavigateFrame(const std::string& frame_name,
const GURL& url,
bool use_frame_referrer = true) {
content::TestNavigationObserver navigation_observer(
web_contents(), 1 /*number_of_navigations*/);
const char* referrer_policy = use_frame_referrer ? "origin" : "no-referrer";
ASSERT_TRUE(content::ExecJs(
GetPrimaryMainFrame(),
base::StringPrintf(R"(
document.getElementsByName('%s')[0].referrerPolicy = '%s';
document.getElementsByName('%s')[0].src = '%s';)",
frame_name.c_str(), referrer_policy,
frame_name.c_str(), url.spec().c_str())));
navigation_observer.Wait();
}
// Removes frame with name `frame_name` from the DOM, changes its src to
// `url`, and then adds it back to the DOM to trigger the navigation.
void RemoveNavigateAndReAddFrame(const std::string& frame_name,
const GURL& url) {
content::TestNavigationObserver navigation_observer(
web_contents(), 1 /*number_of_navigations*/);
ASSERT_TRUE(content::ExecJs(GetPrimaryMainFrame(),
content::JsReplace(R"(
{
const frame = document.getElementsByName($1)[0];
const parentElement = frame.parentElement;
frame.remove();
frame.src = $2;
parentElement.appendChild(frame);
})",
frame_name, url)));
navigation_observer.Wait();
}
// Verifies whether the frame with name `frame_name` is collapsed.
void TestFrameCollapse(const std::string& frame_name, bool expect_collapsed) {
SCOPED_TRACE(base::StringPrintf("Testing frame %s", frame_name.c_str()));
content::RenderFrameHost* frame = GetFrameByName(frame_name);
ASSERT_TRUE(frame);
EXPECT_EQ(!expect_collapsed, WasFrameWithScriptLoaded(frame));
constexpr char kScript[] = R"(
var iframe = document.getElementsByName('%s')[0];
var collapsed = iframe.clientWidth === 0 && iframe.clientHeight === 0;
collapsed;
)";
EXPECT_EQ(expect_collapsed,
content::EvalJs(GetPrimaryMainFrame(),
base::StringPrintf(kScript, frame_name.c_str())));
}
// Calls getMatchedRules for |extension_id| and optionally, the |tab_id| and
// returns comma separated pairs of rule_id and tab_id, with each pair
// delimited by '|'. Matched Rules are sorted in ascending order by ruleId,
// and ties are resolved by the tabId (in ascending order.)
// E.g. "<rule_1>,<tab_1>|<rule_2>,<tab_2>|<rule_3>,<tab_3>"
std::string GetRuleAndTabIdsMatched(const ExtensionId& extension_id,
std::optional<int> tab_id) {
static constexpr char kGetMatchedRulesScript[] = R"(
chrome.declarativeNetRequest.getMatchedRules({%s}, (rules) => {
// |ruleAndTabIds| is a list of `${ruleId},${tabId}`
var ruleAndTabIds = rules.rulesMatchedInfo.map(rule => {
return [rule.rule.ruleId, rule.tabId];
}).sort((a, b) => {
// Sort ascending by rule ID, and resolve ties by tab ID.
const idDiff = a.ruleId - b.ruleId;
return (idDiff != 0) ? idDiff : a.tabId - b.tabId;
}).map(ruleAndTabId => ruleAndTabId.join());
// Join the comma separated (ruleId,tabId) pairs with '|'.
chrome.test.sendScriptResult(ruleAndTabIds.join('|'));
});
)";
std::string tab_id_param =
tab_id ? base::StringPrintf("tabId: %d", *tab_id) : "";
return ExecuteScriptInBackgroundPageAndReturnString(
extension_id,
base::StringPrintf(kGetMatchedRulesScript, tab_id_param.c_str()),
browsertest_util::ScriptUserActivation::kDontActivate);
}
// Calls getMatchedRules for `extension_id` and optionally, the `tab_id` and
// only rule matches more recent than `timestamp`. Returns a comma separated
// list of rule_ids, Matched Rules are sorted in ascending order by ruleId,
// and ties are resolved by the tabId (in ascending order.)
// E.g. "<rule_1>,<rule_2>,<rule_3>"
std::string GetRuleIdsMatched(const ExtensionId& extension_id,
base::Time timestamp) {
static constexpr char kGetMatchedRulesScript[] = R"(
chrome.declarativeNetRequest.getMatchedRules(%s, (rules) => {
var ruleIds = rules.rulesMatchedInfo.map(rule => rule.rule.ruleId)
.sort();
chrome.test.sendScriptResult(ruleIds.join(','));
});
)";
double js_timestamp = timestamp.InMillisecondsFSinceUnixEpochIgnoringNull();
std::string param_string =
base::StringPrintf("{minTimeStamp: %f}", js_timestamp);
return ExecuteScriptInBackgroundPageAndReturnString(
extension_id,
base::StringPrintf(kGetMatchedRulesScript, param_string.c_str()),
browsertest_util::ScriptUserActivation::kDontActivate);
}
// Calls getMatchedRules for |extension_id| and optionally, |tab_id| and
// |timestamp|. Returns the matched rule count for rules more recent than
// |timestamp| if specified, and are associated with the tab specified by
// |tab_id| or all tabs if |tab_id| is not specified. |script_user_activation|
// specifies if the call should be treated as a user gesture. Returns any API
// error if the call fails.
std::string GetMatchedRuleCount(
const ExtensionId& extension_id,
std::optional<int> tab_id,
std::optional<base::Time> timestamp,
browsertest_util::ScriptUserActivation script_user_activation =
browsertest_util::ScriptUserActivation::kDontActivate) {
static constexpr char kGetMatchedRulesScript[] = R"(
chrome.declarativeNetRequest.getMatchedRules(%s, (rules) => {
if (chrome.runtime.lastError) {
chrome.test.sendScriptResult(chrome.runtime.lastError.message);
return;
}
var rule_count = rules.rulesMatchedInfo.length;
chrome.test.sendScriptResult(rule_count.toString());
});
)";
double timestamp_in_js =
timestamp.has_value()
? timestamp->InMillisecondsFSinceUnixEpochIgnoringNull()
: 0;
std::string param_string =
tab_id.has_value()
? base::StringPrintf("{tabId: %d, minTimeStamp: %f}", *tab_id,
timestamp_in_js)
: base::StringPrintf("{minTimeStamp: %f}", timestamp_in_js);
return ExecuteScriptInBackgroundPageAndReturnString(
extension_id,
base::StringPrintf(kGetMatchedRulesScript, param_string.c_str()),
script_user_activation);
}
std::string GetAvailableStaticRuleCount(const ExtensionId& extension_id) {
static constexpr char kGetAvailableStaticRuleCountScript[] = R"(
chrome.declarativeNetRequest.getAvailableStaticRuleCount((rule_count) => {
if (chrome.runtime.lastError) {
chrome.test.sendScriptResult(chrome.runtime.lastError.message);
return;
}
chrome.test.sendScriptResult(rule_count.toString());
});
)";
return ExecuteScriptInBackgroundPageAndReturnString(
extension_id, kGetAvailableStaticRuleCountScript,
browsertest_util::ScriptUserActivation::kDontActivate);
}
std::map<GURL, net::test_server::HttpRequest> GetAndResetRequestsToServer() {
base::AutoLock lock(requests_to_server_lock_);
auto results = std::move(requests_to_server_);
requests_to_server_.clear();
return results;
}
// Waits until MonitorRequest() has observed `url_to_wait_for` at least once
// since the last time GetAndResetRequestsToServer() was invoked. Returns
// instantly if `url_to_wait_for` has already been observed.
void WaitForRequest(const GURL& url_to_wait_for) {
{
base::AutoLock lock(requests_to_server_lock_);
DCHECK(url_to_wait_for_.is_empty());
DCHECK(!wait_for_request_run_loop_);
if (requests_to_server_.count(url_to_wait_for))
return;
url_to_wait_for_ = url_to_wait_for;
wait_for_request_run_loop_ = std::make_unique<base::RunLoop>();
}
wait_for_request_run_loop_->Run();
wait_for_request_run_loop_.reset();
}
TestRule CreateModifyHeadersRule(
int id,
int priority,
const std::string& url_filter,
std::optional<std::vector<TestHeaderInfo>> request_headers,
std::optional<std::vector<TestHeaderInfo>> response_headers) {
TestRule rule = CreateGenericRule();
rule.id = id;
rule.priority = priority;
rule.condition->url_filter = url_filter;
rule.condition->resource_types = std::vector<std::string>({"sub_frame"});
rule.action->type = "modifyHeaders";
rule.action->request_headers = std::move(request_headers);
rule.action->response_headers = std::move(response_headers);
return rule;
}
void CreateTempDir() { ASSERT_TRUE(temp_dir_.CreateUniqueTempDir()); }
void InitializeRulesetManagerObserver() {
ruleset_manager_observer_ =
std::make_unique<RulesetManagerObserver>(ruleset_manager());
}
net::EmbeddedTestServer* https_server() {
if (!https_server_)
InitializeHttpsServer();
return https_server_.get();
}
private:
enum class RulesetScope { kDynamic, kSession };
void UpdateRules(const ExtensionId& extension_id,
const std::vector<int>& rule_ids_to_remove,
const std::vector<TestRule>& rules_to_add,
RulesetScope scope) {
static constexpr char kScript[] = R"(
chrome.declarativeNetRequest.%s(
{addRules: $1, removeRuleIds: $2},
function() {
chrome.test.sendScriptResult(chrome.runtime.lastError ?
chrome.runtime.lastError.message : 'success');
});
)";
const char* function_name = nullptr;
switch (scope) {
case RulesetScope::kDynamic:
function_name = "updateDynamicRules";
break;
case RulesetScope::kSession:
function_name = "updateSessionRules";
break;
}
const std::string script =
content::JsReplace(base::StringPrintf(kScript, function_name),
base::ToValueList(rules_to_add, &TestRule::ToValue),
base::ToValueList(rule_ids_to_remove));
ASSERT_EQ("success", ExecuteScriptInBackgroundPageAndReturnString(
extension_id, script));
}
// Helper to load an extension. `has_dynamic_ruleset` should be true if the
// extension has a dynamic ruleset on load. If `is_extension_update`, the last
// loaded extension is updated.
void LoadExtensionInternal(const std::vector<TestRulesetInfo>& rulesets,
const std::string& directory,
const std::vector<std::string>& hosts,
int expected_extensions_with_rulesets_count_change,
bool has_dynamic_ruleset,
bool is_extension_update,
bool is_delayed_update) {
CHECK(!is_extension_update || GetLoadType() == ExtensionLoadType::PACKED);
// The "crx" directory is reserved for use by this test fixture.
CHECK_NE("crx", directory);
base::ScopedAllowBlockingForTesting scoped_allow_blocking;
base::HistogramTester tester;
base::FilePath extension_dir = temp_dir_.GetPath().AppendASCII(directory);
ASSERT_FALSE(base::PathExists(extension_dir));
EXPECT_TRUE(base::CreateDirectory(extension_dir));
WriteManifestAndRulesets(extension_dir, rulesets, hosts, flags_,
directory /* extension_name */);
ExtensionTestMessageListener background_page_ready_listener("ready");
size_t current_ruleset_count = extensions_with_rulesets_count();
const Extension* extension = nullptr;
switch (GetLoadType()) {
case ExtensionLoadType::PACKED: {
#if BUILDFLAG(IS_ANDROID)
FAIL() << "Android does not yet support packed extensions.";
#else
base::FilePath crx_dir =
temp_dir_.GetPath().AppendASCII("crx").AppendASCII(directory);
base::FilePath crx_path = crx_dir.AppendASCII("temp.crx");
base::FilePath pem_path;
if (is_extension_update)
pem_path = last_pem_path_;
else
last_pem_path_ = crx_dir.AppendASCII("temp.pem");
ASSERT_FALSE(base::PathExists(crx_dir));
ASSERT_TRUE(base::CreateDirectory(crx_dir));
ASSERT_EQ(crx_path,
PackExtensionWithOptions(extension_dir, crx_path, pem_path,
last_pem_path_ /* pem_out_path */
));
if (is_extension_update) {
const ExtensionId& extension_id = last_loaded_extension_id();
if (is_delayed_update) {
// TODO(kelvinjiang): When background script goes away, a different
// method will be needed to trigger a delayed update.
ASSERT_TRUE(flags_ & kConfig_HasBackgroundScript);
ASSERT_TRUE(flags_ & kConfig_ListenForOnUpdateAvailable);
UpdateExtensionWaitForIdle(extension_id, crx_path,
/*expected_change=*/0);
// Force a reload of the extension to complete the delayed update.
// This invalidates the existing `extension` pointer so it needs to
// be set again after the reload.
extension_registrar()->ReloadExtension(extension_id);
extension =
ExtensionRegistry::Get(profile())->enabled_extensions().GetByID(
extension_id);
} else {
extension = UpdateExtension(extension_id, crx_path,
/*expected_change=*/0);
}
} else {
extension = InstallExtensionWithPermissionsGranted(
crx_path, /*expected_change=*/1);
}
break;
#endif // BUILDFLAG(IS_ANDROID)
}
case ExtensionLoadType::UNPACKED:
extension = LoadExtension(extension_dir);
break;
}
ASSERT_TRUE(extension);
WaitForExtensionsWithRulesetsCount(
current_ruleset_count + expected_extensions_with_rulesets_count_change);
size_t expected_enabled_rulesets_count = has_dynamic_ruleset ? 1 : 0;
size_t expected_manifest_enabled_rules_count = 0;
bool has_enabled_rulesets = false;
for (const TestRulesetInfo& info : rulesets) {
size_t rules_count = info.rules_value.GetList().size();
if (info.enabled) {
has_enabled_rulesets = true;
expected_enabled_rulesets_count++;
expected_manifest_enabled_rules_count += rules_count;
}
}
// The histograms below are not logged for unpacked extensions.
if (GetLoadType() == ExtensionLoadType::PACKED) {
size_t expected_histogram_counts = has_enabled_rulesets ? 1 : 0;
tester.ExpectTotalCount(kIndexAndPersistRulesTimeHistogram,
expected_histogram_counts);
tester.ExpectBucketCount(kManifestEnabledRulesCountHistogram,
/*sample=*/expected_manifest_enabled_rules_count,
expected_histogram_counts);
}
tester.ExpectTotalCount(
"Extensions.DeclarativeNetRequest.CreateVerifiedMatcherTime",
expected_enabled_rulesets_count);
tester.ExpectUniqueSample(kLoadRulesetResultHistogram,
/*sample=*/LoadRulesetResult::kSuccess,
expected_enabled_rulesets_count);
auto ruleset_filter = FileBackedRulesetSource::RulesetFilter::kIncludeAll;
if (GetLoadType() == ExtensionLoadType::PACKED) {
ruleset_filter =
FileBackedRulesetSource::RulesetFilter::kIncludeManifestEnabled;
}
EXPECT_TRUE(AreAllIndexedStaticRulesetsValid(*extension, profile(),
ruleset_filter));
// Wait for the background page to load if needed.
if (flags_ & kConfig_HasBackgroundScript) {
ASSERT_TRUE(background_page_ready_listener.WaitUntilSatisfied());
ASSERT_EQ(extension->id(),
background_page_ready_listener.extension_id_for_message());
}
// Ensure no load errors were reported.
EXPECT_TRUE(LoadErrorReporter::GetInstance()->GetErrors()->empty());
}
std::string UpdateEnabledRulesetsInternal(
const ExtensionId& extension_id,
const std::vector<std::string>& ruleset_ids_to_remove,
const std::vector<std::string>& ruleset_ids_to_add) {
static constexpr char kScript[] = R"(
chrome.declarativeNetRequest.updateEnabledRulesets({
disableRulesetIds: $1,
enableRulesetIds: $2
}, () => {
chrome.test.sendScriptResult(chrome.runtime.lastError ?
chrome.runtime.lastError.message : 'success');
});
)";
const std::string script =
content::JsReplace(kScript, base::ToValueList(ruleset_ids_to_remove),
base::ToValueList(ruleset_ids_to_add));
return ExecuteScriptInBackgroundPageAndReturnString(
extension_id, script,
browsertest_util::ScriptUserActivation::kDontActivate);
}
void InitializeHttpsServer() {
https_server_ = std::make_unique<net::EmbeddedTestServer>(
net::test_server::EmbeddedTestServer::TYPE_HTTPS);
https_server_->SetSSLConfig(net::EmbeddedTestServer::CERT_OK);
https_server_->AddDefaultHandlers();
https_server_->ServeFilesFromDirectory(GetHttpServerPath());
https_server_->RegisterRequestMonitor(
base::BindRepeating(&DeclarativeNetRequestBrowserTest::MonitorRequest,
base::Unretained(this)));
}
base::test::ScopedFeatureList feature_list_;
base::ScopedTempDir temp_dir_;
unsigned flags_ = ConfigFlag::kConfig_None;
// Requests observed by the EmbeddedTestServer. This is accessed on both the
// UI and the EmbeddedTestServer's IO thread. Access is protected by
// `requests_to_server_lock_`.
std::map<GURL, net::test_server::HttpRequest> requests_to_server_
GUARDED_BY(requests_to_server_lock_);
// URL that `wait_for_request_run_loop_` is currently waiting to observe.
GURL url_to_wait_for_ GUARDED_BY(requests_to_server_lock_);
// RunLoop to quit when a request for `url_to_wait_for_` is observed.
std::unique_ptr<base::RunLoop> wait_for_request_run_loop_;
base::Lock requests_to_server_lock_;
std::unique_ptr<RulesetManagerObserver> ruleset_manager_observer_;
// Path to the PEM file for the last installed packed extension.
base::FilePath last_pem_path_;
// Most tests don't use this, so it is initialized lazily.
std::unique_ptr<net::EmbeddedTestServer> https_server_;
};
using DeclarativeNetRequestBrowserTest_Packed =
DeclarativeNetRequestBrowserTest;
using DeclarativeNetRequestBrowserTest_Unpacked =
DeclarativeNetRequestBrowserTest;
// Tests the "urlFilter" and "regexFilter" property of a declarative rule
// condition.
// TODO: test times out on win, mac and linux. http://crbug.com/900447.
IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest,
DISABLED_BlockRequests_UrlFilter) {
struct {
std::string filter;
int id;
bool is_regex_rule;
} rules_data[] = {
{"pages_with_script/*ex", 1, false},
{"||a.b.com", 2, false},
{"|http://*.us", 3, false},
{"pages_with_script/page2.html|", 4, false},
{"|http://msn*/pages_with_script/page.html|", 5, false},
{"%20", 6, false}, // Block any urls with space.
{"%C3%A9", 7, false}, // Percent-encoded non-ascii character é.
// Internationalized domain "â±´ase.com" in punycode.
{"|http://xn--ase-7z0b.com", 8, false},
{R"((http|https)://(\w+\.){1,2}com.*reg$)", 9, true},
{R"(\d+\.google\.com)", 10, true},
};
// Rule |i| is the rule with id |i|.
struct {
std::string hostname;
std::string path;
bool expect_main_frame_loaded;
} test_cases[] = {
{"example.com", "/pages_with_script/index.html", false}, // Rule 1
{"example.com", "/pages_with_script/page.html", true},
{"a.b.com", "/pages_with_script/page.html", false}, // Rule 2
{"c.a.b.com", "/pages_with_script/page.html", false}, // Rule 2
{"b.com", "/pages_with_script/page.html", true},
{"example.us", "/pages_with_script/page.html", false}, // Rule 3
{"example.jp", "/pages_with_script/page.html", true},
{"example.jp", "/pages_with_script/page2.html", false}, // Rule 4
{"example.jp", "/pages_with_script/page2.html?q=hello", true},
{"msn.test", "/pages_with_script/page.html", false}, // Rule 5
{"msn.test", "/pages_with_script/page.html?q=hello", true},
{"a.msn.test", "/pages_with_script/page.html", true},
{"abc.com", "/pages_with_script/page.html?q=hi bye", false}, // Rule 6
{"abc.com", "/pages_with_script/page.html?q=hi%20bye", false}, // Rule 6
{"abc.com", "/pages_with_script/page.html?q=hibye", true},
{"abc.com",
"/pages_with_script/page.html?q=" + base::WideToUTF8(L"\u00E9"),
false}, // Rule 7
{base::WideToUTF8(L"\x2c74"
L"ase.com"),
"/pages_with_script/page.html", false}, // Rule 8
{"abc.com", "/pages_with_script/page2.html?reg", false}, // Rule 9
{"abc.com", "/pages_with_script/page2.html?reg1", true},
{"w1.w2.com", "/pages_with_script/page2.html?reg", false}, // Rule 9
{"w1.w2.w3.com", "/pages_with_script/page2.html?reg", true},
{"24.google.com", "/pages_with_script/page.html", false}, // Rule 10
{"xyz.google.com", "/pages_with_script/page.html", true},
};
// Load the extension.
std::vector<TestRule> rules;
for (const auto& rule_data : rules_data) {
TestRule rule = CreateGenericRule();
rule.condition->url_filter.reset();
if (rule_data.is_regex_rule)
rule.condition->regex_filter = rule_data.filter;
else
rule.condition->url_filter = rule_data.filter;
rule.condition->resource_types = std::vector<std::string>({"main_frame"});
rule.id = rule_data.id;
rules.push_back(rule);
}
ASSERT_NO_FATAL_FAILURE(LoadExtensionWithRules(rules));
// Verify that the extension correctly intercepts network requests.
for (const auto& test_case : test_cases) {
GURL url =
embedded_test_server()->GetURL(test_case.hostname, test_case.path);
SCOPED_TRACE(base::StringPrintf("Testing %s", url.spec().c_str()));
// content::NavigateToURL() returns false if the URL was not loaded.
EXPECT_EQ(content::NavigateToURL(GetActiveWebContents(), url),
test_case.expect_main_frame_loaded);
EXPECT_EQ(test_case.expect_main_frame_loaded,
WasFrameWithScriptLoaded(GetPrimaryMainFrame()));
content::PageType expected_page_type = test_case.expect_main_frame_loaded
? content::PAGE_TYPE_NORMAL
: content::PAGE_TYPE_ERROR;
EXPECT_EQ(expected_page_type, GetPageType());
}
}
// Tests the matching behavior of the separator ('^') character.
IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest,
BlockRequests_Separator) {
TestRule rule = CreateGenericRule();
rule.condition->url_filter =
std::string("pages_with_script/page2.html?q=bye^");
rule.condition->resource_types = std::vector<std::string>({"main_frame"});
ASSERT_NO_FATAL_FAILURE(LoadExtensionWithRules({rule}));
// '^' (Separator character) matches anything except a letter, a digit or
// one of the following: _ - . %.
struct {
std::string url_path;
bool expect_main_frame_loaded;
} test_cases[] = {
{"/pages_with_script/page2.html?q=bye&x=1", false},
{"/pages_with_script/page2.html?q=bye#x=1", false},
{"/pages_with_script/page2.html?q=bye:", false},
{"/pages_with_script/page2.html?q=bye3", true},
{"/pages_with_script/page2.html?q=byea", true},
{"/pages_with_script/page2.html?q=bye_", true},
{"/pages_with_script/page2.html?q=bye-", true},
{"/pages_with_script/page2.html?q=bye%", true},
{"/pages_with_script/page2.html?q=bye.", true},
};
for (const auto& test_case : test_cases) {
GURL url = embedded_test_server()->GetURL("google.com", test_case.url_path);
SCOPED_TRACE(base::StringPrintf("Testing %s", url.spec().c_str()));
// content::NavigateToURL() returns false if the URL was not loaded.
EXPECT_EQ(content::NavigateToURL(GetActiveWebContents(), url),
test_case.expect_main_frame_loaded);
EXPECT_EQ(test_case.expect_main_frame_loaded,
WasFrameWithScriptLoaded(GetPrimaryMainFrame()));
content::PageType expected_page_type = test_case.expect_main_frame_loaded
? content::PAGE_TYPE_NORMAL
: content::PAGE_TYPE_ERROR;
EXPECT_EQ(expected_page_type, GetPageType());
}
}
IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest,
BlockRequests_SeparatorMatchesEndOfURL) {
TestRule rule = CreateGenericRule();
rule.condition->url_filter = std::string("page2.html^");
rule.condition->resource_types = std::vector<std::string>({"main_frame"});
ASSERT_NO_FATAL_FAILURE(LoadExtensionWithRules({rule}));
GURL url = embedded_test_server()->GetURL("google.com",
"/pages_with_script/page2.html");
// content::NavigateToURL() returns false if the URL was not loaded.
EXPECT_FALSE(content::NavigateToURL(GetActiveWebContents(), url));
EXPECT_FALSE(WasFrameWithScriptLoaded(GetPrimaryMainFrame()));
EXPECT_EQ(content::PAGE_TYPE_ERROR, GetPageType());
}
// Tests case sensitive url filters.
IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest,
BlockRequests_IsUrlFilterCaseSensitive) {
struct {
std::string url_filter;
size_t id;
bool is_url_filter_case_sensitive;
} rules_data[] = {{"pages_with_script/index.html?q=hello", 1, false},
{"pages_with_script/page.html?q=hello", 2, true}};
std::vector<TestRule> rules;
for (const auto& rule_data : rules_data) {
TestRule rule = CreateGenericRule();
rule.condition->url_filter = rule_data.url_filter;
rule.id = rule_data.id;
rule.condition->is_url_filter_case_sensitive =
rule_data.is_url_filter_case_sensitive;
rule.condition->resource_types = std::vector<std::string>({"main_frame"});
rules.push_back(rule);
}
ASSERT_NO_FATAL_FAILURE(LoadExtensionWithRules(rules));
// Rule |i| is the rule with id |i|.
struct {
std::string hostname;
std::string path;
bool expect_main_frame_loaded;
} test_cases[] = {
{"example.com", "/pages_with_script/index.html?q=hello",
false}, // Rule 1
{"example.com", "/pages_with_script/index.html?q=HELLO",
false}, // Rule 1
{"example.com", "/pages_with_script/page.html?q=hello", false}, // Rule 2
{"example.com", "/pages_with_script/page.html?q=HELLO", true},
};
for (const auto& test_case : test_cases) {
GURL url =
embedded_test_server()->GetURL(test_case.hostname, test_case.path);
SCOPED_TRACE(base::StringPrintf("Testing %s", url.spec().c_str()));
NavigateToURL(url);
EXPECT_EQ(test_case.expect_main_frame_loaded,
WasFrameWithScriptLoaded(GetPrimaryMainFrame()));
content::PageType expected_page_type = test_case.expect_main_frame_loaded
? content::PAGE_TYPE_NORMAL
: content::PAGE_TYPE_ERROR;
EXPECT_EQ(expected_page_type, GetPageType());
}
}
// Tests the "domains" and "excludedDomains" property of a declarative rule
// condition.
IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest,
BlockRequests_Domains) {
struct {
std::string url_filter;
size_t id;
std::vector<std::string> domains;
std::vector<std::string> excluded_domains;
} rules_data[] = {{"child_frame.html?frame=1",
1,
{"x.com", "xn--tst-bma.com" /* punycode for tést.com */},
{"a.x.com"}},
{"child_frame.html?frame=2", 2, {}, {"a.y.com"}}};
std::vector<TestRule> rules;
for (const auto& rule_data : rules_data) {
TestRule rule = CreateGenericRule();
rule.condition->url_filter = rule_data.url_filter;
rule.id = rule_data.id;
// An empty list is not allowed for the "domains" property.
if (!rule_data.domains.empty())
rule.condition->domains = rule_data.domains;
rule.condition->excluded_domains = rule_data.excluded_domains;
rule.condition->resource_types = std::vector<std::string>({"sub_frame"});
rules.push_back(rule);
}
ASSERT_NO_FATAL_FAILURE(LoadExtensionWithRules(rules));
// Rule |i| is the rule with id |i|.
struct {
std::string main_frame_hostname;
bool expect_frame_1_loaded;
bool expect_frame_2_loaded;
} test_cases[] = {
{"x.com", false /* Rule 1 */, false /* Rule 2 */},
{base::WideToUTF8(L"tést.com"), false /*Rule 1*/, false /*Rule 2*/},
{"b.x.com", false /* Rule 1 - Subdomain matches */, false /* Rule 2 */},
{"a.x.com", true, false /* Rule 2 */},
{"b.a.x.com", true, false /* Rule 2 */},
{"y.com", true, false /* Rule 2*/},
{"a.y.com", true, true},
{"b.a.y.com", true, true},
{"google.com", true, false /* Rule 2 */},
};
for (const auto& test_case : test_cases) {
GURL url = embedded_test_server()->GetURL(test_case.main_frame_hostname,
"/page_with_two_frames.html");
SCOPED_TRACE(base::StringPrintf("Testing %s", url.spec().c_str()));
NavigateToURL(url);
content::RenderFrameHost* main_frame = GetPrimaryMainFrame();
EXPECT_TRUE(WasFrameWithScriptLoaded(main_frame));
EXPECT_EQ(content::PAGE_TYPE_NORMAL, GetPageType());
content::RenderFrameHost* child_1 = content::ChildFrameAt(main_frame, 0);
content::RenderFrameHost* child_2 = content::ChildFrameAt(main_frame, 1);
EXPECT_EQ(test_case.expect_frame_1_loaded,
WasFrameWithScriptLoaded(child_1));
EXPECT_EQ(test_case.expect_frame_2_loaded,
WasFrameWithScriptLoaded(child_2));
}
}
#if BUILDFLAG(IS_ANDROID)
// TODO(crbug.com/371298229): Flaky on Android.
#define MAYBE_BlockRequests_RequestDomains DISABLED_BlockRequests_RequestDomains
#else
#define MAYBE_BlockRequests_RequestDomains BlockRequests_RequestDomains
#endif
// Tests the "requestDomains" and "excludedRequestDomains" properties of
// declarativeNetRequest rule conditions.
IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest,
MAYBE_BlockRequests_RequestDomains) {
struct {
size_t id;
std::vector<std::string> request_domains;
std::vector<std::string> excluded_request_domains;
} rules_data[] = {
{1, {"x.com", "y.com"}, {"a.x.com"}},
{2, {/* all domains */}, {"z.com", "a.x.com", "y.com"}},
};
std::vector<TestRule> rules;
for (const auto& rule_data : rules_data) {
TestRule rule = CreateGenericRule();
rule.condition->url_filter = "child_frame.html";
rule.id = rule_data.id;
// An empty list is not allowed for the "request_domains" property.
if (!rule_data.request_domains.empty())
rule.condition->request_domains = rule_data.request_domains;
rule.condition->excluded_request_domains =
rule_data.excluded_request_domains;
rule.condition->resource_types = std::vector<std::string>({"sub_frame"});
rules.push_back(rule);
}
ASSERT_NO_FATAL_FAILURE(LoadExtensionWithRules(rules));
GURL url = embedded_test_server()->GetURL(
"example.com",
"/request_domain_test.html?w.com,x.com,subdomain.x.com,y.com,a.x.com,"
"subdomain.a.x.com,z.com");
NavigateToURL(url);
ASSERT_TRUE(WasFrameWithScriptLoaded(GetPrimaryMainFrame()));
ASSERT_EQ(content::PAGE_TYPE_NORMAL, GetPageType());
struct {
std::string domain;
bool expect_frame_loaded;
} cases[] = {
{"x.com", false /* Rule 1 */},
{"subdomain.x.com", false /* Rule 1 - Subdomain matches */},
{"a.x.com", true},
{"subdomain.a.x.com", true},
{"y.com", false /* Rule 1 */},
{"z.com", true},
{"w.com", false /* Rule 2 */},
};
for (const auto& test_case : cases) {
SCOPED_TRACE(
base::StringPrintf("Testing domain %s", test_case.domain.c_str()));
content::RenderFrameHost* child = GetFrameByName(test_case.domain);
EXPECT_TRUE(child);
EXPECT_EQ(test_case.expect_frame_loaded, WasFrameWithScriptLoaded(child));
}
}
// Tests the "domainType" property of a declarative rule condition.
IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest,
BlockRequests_DomainType) {
struct {
std::string url_filter;
size_t id;
std::optional<std::string> domain_type;
} rules_data[] = {
{"child_frame.html?case=1", 1, std::string("firstParty")},
{"child_frame.html?case=2", 2, std::string("thirdParty")},
{"child_frame.html?case=3", 3, std::nullopt},
};
std::vector<TestRule> rules;
for (const auto& rule_data : rules_data) {
TestRule rule = CreateGenericRule();
rule.condition->url_filter = rule_data.url_filter;
rule.id = rule_data.id;
rule.condition->domain_type = rule_data.domain_type;
rule.condition->resource_types = std::vector<std::string>({"sub_frame"});
rules.push_back(rule);
}
ASSERT_NO_FATAL_FAILURE(LoadExtensionWithRules(rules));
GURL url =
embedded_test_server()->GetURL("example.com", "/domain_type_test.html");
NavigateToURL(url);
ASSERT_TRUE(WasFrameWithScriptLoaded(GetPrimaryMainFrame()));
ASSERT_EQ(content::PAGE_TYPE_NORMAL, GetPageType());
// The loaded page will consist of four pairs of iframes named
// first_party_[1..4] and third_party_[1..4], with url path
// child_frame.html?case=[1..4] respectively.
struct {
std::string child_frame_name;
bool expect_frame_loaded;
} cases[] = {
// Url matched by rule 1. Only the first party frame is blocked.
{"first_party_1", false},
{"third_party_1", true},
// Url matched by rule 2. Only the third party frame is blocked.
{"first_party_2", true},
{"third_party_2", false},
// Url matched by rule 3. Both the first and third party frames are
// blocked.
{"first_party_3", false},
{"third_party_3", false},
// No matching rule.
{"first_party_4", true},
{"third_party_4", true},
};
for (const auto& test_case : cases) {
SCOPED_TRACE(base::StringPrintf("Testing child frame named %s",
test_case.child_frame_name.c_str()));
content::RenderFrameHost* child =
GetFrameByName(test_case.child_frame_name);
EXPECT_TRUE(child);
EXPECT_EQ(test_case.expect_frame_loaded, WasFrameWithScriptLoaded(child));
}
}
// Tests that main frame navigations to Web origins initiated by
// chrome-untrusted:// can be blocked.
IN_PROC_BROWSER_TEST_P(
DeclarativeNetRequestBrowserTest,
BlockRequests_WebMainFrameNavigationsFromChromeUntrusted) {
content::WebUIConfigMap::GetInstance().AddUntrustedWebUIConfig(
std::make_unique<ui::TestUntrustedWebUIConfig>("test"));
content::WebUIConfigMap::GetInstance().AddUntrustedWebUIConfig(
std::make_unique<ui::TestUntrustedWebUIConfig>("test2"));
TestRule rule = CreateGenericRule();
rule.id = 1;
rule.condition->url_filter = "title2.html";
rule.condition->resource_types = {"main_frame"};
ASSERT_NO_FATAL_FAILURE(LoadExtensionWithRules({rule}));
// Opens a chrome-untrusted:// page.
NavigateToURL(GURL("chrome-untrusted://test/title1.html"));
auto* web_contents = GetActiveWebContents();
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", "/title2.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();
EXPECT_FALSE(navigation_observer.last_navigation_succeeded());
}
{
// 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();
EXPECT_TRUE(navigation_observer.last_navigation_succeeded());
}
{
// The page itself navigates to a Web origin.
const GURL web_url =
embedded_test_server()->GetURL("example.com", "/title2.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();
EXPECT_FALSE(navigation_observer.last_navigation_succeeded());
}
}
// Tests that subframe navigations to Web origins initiated by
// chrome-untrusted:// can't be blocked.
IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest,
CanNotBlockSubframeNavigationsFromChromeUntrusted) {
content::TestUntrustedDataSourceHeaders headers;
headers.child_src = "child-src *;";
content::WebUIConfigMap::GetInstance().AddUntrustedWebUIConfig(
std::make_unique<ui::TestUntrustedWebUIConfig>("test", headers));
TestRule rule = CreateGenericRule();
rule.id = 1;
rule.condition->url_filter = "title2.html";
rule.condition->resource_types = {"main_frame"};
ASSERT_NO_FATAL_FAILURE(LoadExtensionWithRules({rule}));
// Opens a chrome-untrusted:// page.
NavigateToURL(GURL("chrome-untrusted://test/title1.html"));
auto* web_contents = GetActiveWebContents();
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());
}
// Tests allowing rules for blocks.
IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest, AllowBlock) {
const int kNumRequests = 6;
TestRule rule = CreateGenericRule();
int id = kMinValidID;
// Block all main-frame requests ending with numbers 1 to |kNumRequests|.
std::vector<TestRule> rules;
for (int i = 1; i <= kNumRequests; ++i) {
rule.id = id++;
rule.condition->url_filter = base::StringPrintf("num=%d|", i);
rule.condition->resource_types = std::vector<std::string>({"main_frame"});
rule.priority = 1;
rules.push_back(rule);
}
// Allow all main-frame requests ending with even numbers from 1 to
// |kNumRequests|.
for (int i = 2; i <= kNumRequests; i += 2) {
rule.id = id++;
rule.condition->url_filter = base::StringPrintf("num=%d|", i);
rule.condition->resource_types = std::vector<std::string>({"main_frame"});
rule.action->type = std::string("allow");
rule.priority = 2;
rules.push_back(rule);
}
ASSERT_NO_FATAL_FAILURE(LoadExtensionWithRules(rules));
for (int i = 1; i <= kNumRequests; ++i) {
GURL url = embedded_test_server()->GetURL(
"example.com",
base::StringPrintf("/pages_with_script/page.html?num=%d", i));
SCOPED_TRACE(base::StringPrintf("Testing %s", url.spec().c_str()));
NavigateToURL(url);
// All requests ending with odd numbers should be blocked.
const bool page_should_load = (i % 2 == 0);
EXPECT_EQ(page_should_load,
WasFrameWithScriptLoaded(GetPrimaryMainFrame()));
content::PageType expected_page_type =
page_should_load ? content::PAGE_TYPE_NORMAL : content::PAGE_TYPE_ERROR;
EXPECT_EQ(expected_page_type, GetPageType());
}
}
// Tests allowing rules for redirects.
IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest, AllowRedirect) {
set_config_flags(ConfigFlag::kConfig_HasBackgroundScript);
const GURL static_redirect_url = embedded_test_server()->GetURL(
"example.com", base::StringPrintf("/pages_with_script/page2.html"));
const GURL dynamic_redirect_url = embedded_test_server()->GetURL(
"abc.com", base::StringPrintf("/pages_with_script/page.html"));
// Create 2 static and 2 dynamic rules.
struct {
std::string url_filter;
int id;
int priority;
std::string action_type;
std::optional<std::string> redirect_url;
} rules_data[] = {
{"google.com", 1, 1, "redirect", static_redirect_url.spec()},
{"num=1|", 2, 3, "allow", std::nullopt},
{"1|", 3, 4, "redirect", dynamic_redirect_url.spec()},
{"num=3|", 4, 2, "allow", std::nullopt},
};
std::vector<TestRule> rules;
for (const auto& rule_data : rules_data) {
TestRule rule = CreateGenericRule();
rule.id = rule_data.id;
rule.priority = rule_data.priority;
rule.condition->url_filter = rule_data.url_filter;
rule.condition->resource_types = std::vector<std::string>({"main_frame"});
rule.action->type = rule_data.action_type;
rule.action->redirect.emplace();
rule.action->redirect->url = rule_data.redirect_url;
rules.push_back(rule);
}
std::vector<TestRule> static_rules;
static_rules.push_back(rules[0]);
static_rules.push_back(rules[1]);
std::vector<TestRule> dynamic_rules;
dynamic_rules.push_back(rules[2]);
dynamic_rules.push_back(rules[3]);
ASSERT_NO_FATAL_FAILURE(LoadExtensionWithRules(
static_rules, "test_extension", {URLPattern::kAllUrlsPattern}));
auto get_url = [this](int i) {
return embedded_test_server()->GetURL(
"google.com",
base::StringPrintf("/pages_with_script/page.html?num=%d", i));
};
struct {
GURL initial_url;
GURL expected_final_url;
} static_test_cases[] = {
{get_url(0), static_redirect_url},
{get_url(1), get_url(1)},
{get_url(3), static_redirect_url},
};
for (const auto& test_case : static_test_cases) {
GURL url = test_case.initial_url;
SCOPED_TRACE(base::StringPrintf("Testing %s", url.spec().c_str()));
NavigateToURL(url);
EXPECT_TRUE(WasFrameWithScriptLoaded(GetPrimaryMainFrame()));
GURL final_url = web_contents()->GetLastCommittedURL();
EXPECT_EQ(test_case.expected_final_url, final_url);
}
// Now add dynamic rules. These should share the priority space with static
// rules.
const ExtensionId& extension_id = last_loaded_extension_id();
ASSERT_NO_FATAL_FAILURE(AddDynamicRules(extension_id, dynamic_rules));
// Test that dynamic and static rules are in the same priority space.
struct {
GURL initial_url;
GURL expected_final_url;
} dynamic_test_cases[] = {
{get_url(1), dynamic_redirect_url},
{get_url(3), get_url(3)},
};
for (const auto& test_case : dynamic_test_cases) {
GURL url = test_case.initial_url;
SCOPED_TRACE(base::StringPrintf("Testing %s", url.spec().c_str()));
NavigateToURL(url);
EXPECT_TRUE(WasFrameWithScriptLoaded(GetPrimaryMainFrame()));
GURL final_url = web_contents()->GetLastCommittedURL();
EXPECT_EQ(test_case.expected_final_url, final_url);
}
}
// Test is flaky on win. http://crbug.com/1241762.
#if BUILDFLAG(IS_WIN)
#define MAYBE_Enable_Disable_Reload_Uninstall \
DISABLED_Enable_Disable_Reload_Uninstall
#else
#define MAYBE_Enable_Disable_Reload_Uninstall Enable_Disable_Reload_Uninstall
#endif
// Tests that the extension ruleset is active only when the extension is
// enabled.
IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest,
MAYBE_Enable_Disable_Reload_Uninstall) {
set_config_flags(ConfigFlag::kConfig_HasBackgroundScript);
// Block all main frame requests to "static.example".
TestRule rule = CreateGenericRule();
rule.condition->url_filter = std::string("static.example");
rule.condition->resource_types = std::vector<std::string>({"main_frame"});
ASSERT_NO_FATAL_FAILURE(LoadExtensionWithRules({rule}));
const ExtensionId& extension_id = last_loaded_extension_id();
// Add dynamic rule to block requests to "dynamic.example".
rule.condition->url_filter = std::string("dynamic.example");
ASSERT_NO_FATAL_FAILURE(AddDynamicRules(extension_id, {rule}));
// Add session-scoped rule to block requests to "session.example".
rule.condition->url_filter = std::string("session.example");
ASSERT_NO_FATAL_FAILURE(UpdateSessionRules(extension_id, {}, {rule}));
constexpr char kUrlPath[] = "/pages_with_script/index.html";
GURL static_rule_url =
embedded_test_server()->GetURL("static.example", kUrlPath);
GURL dynamic_rule_url =
embedded_test_server()->GetURL("dynamic.example", kUrlPath);
GURL session_rule_url =
embedded_test_server()->GetURL("session.example", kUrlPath);
auto test_extension_enabled = [&](bool expected_enabled) {
EXPECT_EQ(expected_enabled,
ExtensionRegistry::Get(profile())->enabled_extensions().Contains(
extension_id));
// Ensure the various registered rules work correctly if the extension is
// enabled.
EXPECT_EQ(expected_enabled, IsNavigationBlocked(static_rule_url));
EXPECT_EQ(expected_enabled, IsNavigationBlocked(dynamic_rule_url));
EXPECT_EQ(expected_enabled, IsNavigationBlocked(session_rule_url));
};
{
SCOPED_TRACE("Testing extension after load");
EXPECT_EQ(1u, extensions_with_rulesets_count());
test_extension_enabled(true);
}
{
SCOPED_TRACE("Testing DisableExtension");
DisableExtension(extension_id, {disable_reason::DISABLE_USER_ACTION});
WaitForExtensionsWithRulesetsCount(0);
test_extension_enabled(false);
}
#if !BUILDFLAG(IS_ANDROID)
// TODO(crbug.com/391920604, crbug.com/391920206): Port to desktop Android
// when EnableExtension(), ReloadExtension(), and UninstallExtension() are
// supported.
{
SCOPED_TRACE("Testing EnableExtension");
EnableExtension(extension_id);
WaitForExtensionsWithRulesetsCount(1);
test_extension_enabled(true);
}
{
SCOPED_TRACE("Testing ReloadExtension");
// Don't use ExtensionBrowserTest::ReloadExtension since it waits for the
// extension to be loaded again. But we need to use our custom waiting logic
// below.
extension_registrar()->ReloadExtension(extension_id);
WaitForExtensionsWithRulesetsCount(0);
WaitForExtensionsWithRulesetsCount(1);
test_extension_enabled(true);
}
{
SCOPED_TRACE("Testing UninstallExtension");
UninstallExtension(extension_id);
WaitForExtensionsWithRulesetsCount(0);
test_extension_enabled(false);
}
#endif // !BUILDFLAG(IS_ANDROID)
}
// Tests that multiple enabled extensions with declarative rulesets having
// blocking rules behave correctly.
IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest,
BlockRequests_MultipleExtensions) {
struct {
std::string url_filter;
int id;
bool add_to_first_extension;
bool add_to_second_extension;
} rules_data[] = {
{"block_both.com", 1, true, true},
{"block_first.com", 2, true, false},
{"block_second.com", 3, false, true},
};
std::vector<TestRule> rules_1, rules_2;
for (const auto& rule_data : rules_data) {
TestRule rule = CreateGenericRule();
rule.condition->url_filter = rule_data.url_filter;
rule.condition->resource_types = std::vector<std::string>({"main_frame"});
rule.id = rule_data.id;
if (rule_data.add_to_first_extension)
rules_1.push_back(rule);
if (rule_data.add_to_second_extension)
rules_2.push_back(rule);
}
ASSERT_NO_FATAL_FAILURE(LoadExtensionWithRules(
rules_1, "extension_1", {URLPattern::kAllUrlsPattern}));
ASSERT_NO_FATAL_FAILURE(LoadExtensionWithRules(
rules_2, "extension_2", {URLPattern::kAllUrlsPattern}));
struct {
std::string host;
bool expect_main_frame_loaded;
} test_cases[] = {
{"block_both.com", false},
{"block_first.com", false},
{"block_second.com", false},
{"block_none.com", true},
};
for (const auto& test_case : test_cases) {
GURL url = embedded_test_server()->GetURL(test_case.host,
"/pages_with_script/page.html");
SCOPED_TRACE(base::StringPrintf("Testing %s", url.spec().c_str()));
NavigateToURL(url);
EXPECT_EQ(test_case.expect_main_frame_loaded,
WasFrameWithScriptLoaded(GetPrimaryMainFrame()));
content::PageType expected_page_type = test_case.expect_main_frame_loaded
? content::PAGE_TYPE_NORMAL
: content::PAGE_TYPE_ERROR;
EXPECT_EQ(expected_page_type, GetPageType());
}
}
// Tests that multiple enabled extensions with declarative rulesets having
// redirect rules behave correctly with preference given to more recently
// installed extensions.
IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest,
RedirectRequests_MultipleExtensions) {
const int kNumExtensions = 4;
auto redirect_url_for_extension_number = [this](size_t num) {
return embedded_test_server()
->GetURL(base::NumberToString(num) + ".com",
"/pages_with_script/index.html")
.spec();
};
TestRule rule = CreateGenericRule();
rule.id = kMinValidID;
rule.priority = kMinValidPriority;
rule.action->type = std::string("redirect");
rule.condition->url_filter = std::string("example.com");
rule.condition->resource_types = std::vector<std::string>({"main_frame"});
base::Time last_extension_install_time = base::Time::Min();
// Add |kNumExtensions| each redirecting example.com to a different redirect
// url.
for (size_t i = 1; i <= kNumExtensions; ++i) {
rule.action->redirect.emplace();
rule.action->redirect->url = redirect_url_for_extension_number(i);
ASSERT_NO_FATAL_FAILURE(LoadExtensionWithRules(
{rule}, base::NumberToString(i), {URLPattern::kAllUrlsPattern}));
// Verify that the install time of this extension is greater than the last
// extension.
base::Time install_time = GetLastUpdateTime(ExtensionPrefs::Get(profile()),
last_loaded_extension_id());
EXPECT_GT(install_time, last_extension_install_time);
last_extension_install_time = install_time;
}
// Load a url on example.com. It should be redirected to the redirect url
// corresponding to the most recently installed extension.
GURL url = embedded_test_server()->GetURL("example.com",
"/pages_with_script/page.html");
NavigateToURL(url);
EXPECT_EQ(content::PAGE_TYPE_NORMAL, GetPageType());
EXPECT_TRUE(WasFrameWithScriptLoaded(GetPrimaryMainFrame()));
GURL final_url = web_contents()->GetLastCommittedURL();
EXPECT_EQ(GURL(redirect_url_for_extension_number(kNumExtensions)), final_url);
}
// Tests a combination of blocking and redirect rules.
IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest, BlockAndRedirect) {
auto get_url_for_host = [this](std::string hostname) {
return embedded_test_server()
->GetURL(hostname, "/pages_with_script/index.html")
.spec();
};
struct {
std::string url_filter;
int id;
int priority;
std::string action_type;
std::optional<std::string> redirect_url;
} rules_data[] = {
{"example.com", 1, 1, "redirect", get_url_for_host("yahoo.com")},
{"yahoo.com", 2, 1, "redirect", get_url_for_host("google.com")},
{"abc.com", 3, 1, "redirect", get_url_for_host("def.com")},
{"def.com", 4, 2, "block", std::nullopt},
{"def.com", 5, 1, "redirect", get_url_for_host("xyz.com")},
{"ghi*", 6, 1, "redirect", get_url_for_host("ghijk.com")},
};
// Load the extension.
std::vector<TestRule> rules;
for (const auto& rule_data : rules_data) {
TestRule rule = CreateGenericRule();
rule.condition->url_filter = rule_data.url_filter;
rule.id = rule_data.id;
rule.priority = rule_data.priority;
rule.condition->resource_types = std::vector<std::string>({"main_frame"});
rule.action->type = rule_data.action_type;
rule.action->redirect.emplace();
rule.action->redirect->url = rule_data.redirect_url;
rules.push_back(rule);
}
ASSERT_NO_FATAL_FAILURE(LoadExtensionWithRules(
rules, "test_extension", {URLPattern::kAllUrlsPattern}));
struct {
std::string hostname;
bool expected_main_frame_loaded;
std::optional<GURL> expected_final_url;
std::optional<size_t> expected_redirect_chain_length;
} test_cases[] = {
// example.com -> yahoo.com -> google.com.
{"example.com", true, GURL(get_url_for_host("google.com")), 3},
// yahoo.com -> google.com.
{"yahoo.com", true, GURL(get_url_for_host("google.com")), 2},
// abc.com -> def.com (blocked).
// Note def.com won't be redirected since blocking rules are given
// priority over redirect rules.
{"abc.com", false, std::nullopt, std::nullopt},
// def.com (blocked).
{"def.com", false, std::nullopt, std::nullopt},
// ghi.com -> ghijk.com.
// Though ghijk.com still matches the redirect rule for |ghi*|, it will
// not redirect to itself.
{"ghi.com", true, GURL(get_url_for_host("ghijk.com")), 2},
};
for (const auto& test_case : test_cases) {
std::string url = get_url_for_host(test_case.hostname);
SCOPED_TRACE(base::StringPrintf("Testing %s", url.c_str()));
NavigateToURL(GURL(url));
EXPECT_EQ(test_case.expected_main_frame_loaded,
WasFrameWithScriptLoaded(GetPrimaryMainFrame()));
if (!test_case.expected_final_url) {
EXPECT_EQ(content::PAGE_TYPE_ERROR, GetPageType());
} else {
EXPECT_EQ(content::PAGE_TYPE_NORMAL, GetPageType());
GURL final_url = web_contents()->GetLastCommittedURL();
EXPECT_EQ(*test_case.expected_final_url, final_url);
EXPECT_EQ(*test_case.expected_redirect_chain_length,
web_contents()
->GetController()
.GetLastCommittedEntry()
->GetRedirectChain()
.size());
}
}
}
// Tests that the redirect url within an extension ruleset is chosen based on
// the highest priority matching rule.
IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest, RedirectPriority) {
const size_t kNumPatternTypes = 7;
auto hostname_for_number = [](size_t num) {
return base::NumberToString(num) + ".com";
};
auto redirect_url_for_priority = [this,
hostname_for_number](size_t priority) {
return embedded_test_server()
->GetURL(hostname_for_number(priority + 1),
"/pages_with_script/index.html")
.spec();
};
std::vector<TestRule> rules;
TestRule rule = CreateGenericRule();
int id = kMinValidID;
for (size_t i = 1; i <= kNumPatternTypes; i++) {
// For pattern type |i|, add |i| rules with priority from 1 to |i|, each
// with a different redirect url.
std::string pattern = hostname_for_number(i) + "*page.html";
for (size_t j = 1; j <= i; j++) {
rule.id = id++;
rule.priority = j;
rule.action->type = std::string("redirect");
rule.action->redirect.emplace();
rule.action->redirect->url = redirect_url_for_priority(j);
rule.condition->url_filter = pattern;
rule.condition->resource_types = std::vector<std::string>({"main_frame"});
rules.push_back(rule);
}
}
// Shuffle the rules to ensure that the order in which rules are added has no
// effect on the test.
base::RandomShuffle(rules.begin(), rules.end());
ASSERT_NO_FATAL_FAILURE(LoadExtensionWithRules(
rules, "test_extension", {URLPattern::kAllUrlsPattern}));
for (size_t i = 0; i <= kNumPatternTypes + 1; ++i) {
GURL url = embedded_test_server()->GetURL(hostname_for_number(i),
"/pages_with_script/page.html");
SCOPED_TRACE(base::StringPrintf("Testing %s", url.spec().c_str()));
NavigateToURL(url);
EXPECT_EQ(content::PAGE_TYPE_NORMAL, GetPageType());
EXPECT_TRUE(WasFrameWithScriptLoaded(GetPrimaryMainFrame()));
GURL final_url = web_contents()->GetLastCommittedURL();
bool expect_redirection = i >= 1 && i <= kNumPatternTypes;
if (expect_redirection) {
// For pattern type |i|, the highest prioirity for any rule was |i|.
EXPECT_EQ(GURL(redirect_url_for_priority(i)), final_url);
} else {
EXPECT_EQ(url, final_url);
}
}
}
// Test that upgradeScheme rules will change the scheme of matching requests to
// https.
IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest, UpgradeRules) {
auto get_url_for_host = [this](std::string hostname) {
return embedded_test_server()->GetURL(hostname,
"/pages_with_script/index.html");
};
GURL google_url = get_url_for_host("google.com");
struct {
std::string url_filter;
int id;
int priority;
std::string action_type;
std::optional<std::string> redirect_url;
} rules_data[] = {
{"exa*", 1, 4, "upgradeScheme", std::nullopt},
{"|http:*yahoo", 2, 100, "redirect", "http://other.com"},
// Since the test server can only display http requests, redirect all
// https requests to google.com in the end.
// TODO(crbug.com/41471360): Add a https test server to display https
// pages so this redirect rule can be removed.
{"|https*", 3, 6, "redirect", google_url.spec()},
{"exact.com", 4, 5, "block", std::nullopt},
};
// Load the extension.
std::vector<TestRule> rules;
for (const auto& rule_data : rules_data) {
TestRule rule = CreateGenericRule();
rule.condition->url_filter = rule_data.url_filter;
rule.id = rule_data.id;
rule.priority = rule_data.priority;
rule.condition->resource_types = std::vector<std::string>({"main_frame"});
rule.action->type = rule_data.action_type;
rule.action->redirect.emplace();
rule.action->redirect->url = rule_data.redirect_url;
rules.push_back(rule);
}
ASSERT_NO_FATAL_FAILURE(LoadExtensionWithRules(
rules, "test_extension", {URLPattern::kAllUrlsPattern}));
// Now load an extension with another ruleset, except this extension has no
// host permissions.
TestRule upgrade_rule = CreateGenericRule();
upgrade_rule.condition->url_filter = "yahoo";
upgrade_rule.id = kMinValidID;
upgrade_rule.priority = kMinValidPriority;
upgrade_rule.condition->resource_types =
std::vector<std::string>({"main_frame"});
upgrade_rule.action->type = "upgradeScheme";
ASSERT_NO_FATAL_FAILURE(LoadExtensionWithRules(
std::vector<TestRule>({upgrade_rule}), "test_extension_2", {}));
struct {
std::string hostname;
// |expected_final_url| is null if the request is expected to be blocked.
std::optional<GURL> expected_final_url;
} test_cases[] = {
{"exact.com", std::nullopt},
// http://example.com -> https://example.com/ -> http://google.com
{"example.com", google_url},
// test_extension_2 should upgrade the scheme for http://yahoo.com
// despite having no host permissions. Note that this request is not
// matched with test_extension_1's ruleset as test_extension_2 is
// installed more recently.
// http://yahoo.com -> https://yahoo.com/ -> http://google.com
{"yahoo.com", google_url},
};
for (const auto& test_case : test_cases) {
GURL url = get_url_for_host(test_case.hostname);
SCOPED_TRACE(base::StringPrintf("Testing %s", url.spec().c_str()));
NavigateToURL(url);
if (!test_case.expected_final_url) {
EXPECT_EQ(content::PAGE_TYPE_ERROR, GetPageType());
} else {
EXPECT_EQ(content::PAGE_TYPE_NORMAL, GetPageType());
const GURL& final_url = web_contents()->GetLastCommittedURL();
EXPECT_EQ(*test_case.expected_final_url, final_url);
}
}
}
// Tests that only extensions enabled in incognito mode affect network requests
// from an incognito context.
IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest,
BlockRequests_Incognito) {
// Block all main-frame requests to example.com.
TestRule rule = CreateGenericRule();
rule.condition->url_filter = std::string("example.com");
rule.condition->resource_types = std::vector<std::string>({"main_frame"});
ASSERT_NO_FATAL_FAILURE(LoadExtensionWithRules({rule}));
const ExtensionId& extension_id = last_loaded_extension_id();
GURL url = embedded_test_server()->GetURL("example.com",
"/pages_with_script/page.html");
auto test_enabled_in_incognito = [&](bool expected_enabled_in_incognito) {
EXPECT_EQ(expected_enabled_in_incognito,
util::IsIncognitoEnabled(extension_id, profile()));
// The url should be blocked in normal context.
NavigateToURL(url);
EXPECT_FALSE(WasFrameWithScriptLoaded(GetPrimaryMainFrame()));
EXPECT_EQ(content::PAGE_TYPE_ERROR, GetPageType());
// In incognito context, the url should be blocked if the extension is
// enabled in incognito mode.
content::WebContents* tab = PlatformOpenURLOffTheRecord(profile(), url);
EXPECT_EQ(!expected_enabled_in_incognito,
WasFrameWithScriptLoaded(tab->GetPrimaryMainFrame()));
content::PageType expected_page_type = expected_enabled_in_incognito
? content::PAGE_TYPE_ERROR
: content::PAGE_TYPE_NORMAL;
EXPECT_EQ(expected_page_type, GetPageType(tab));
};
{
// By default, the extension will be disabled in incognito.
SCOPED_TRACE("Testing extension after load");
test_enabled_in_incognito(false);
}
{
// Enable the extension in incognito mode.
SCOPED_TRACE("Testing extension after enabling it in incognito");
util::SetIsIncognitoEnabled(extension_id, profile(), true /*enabled*/);
// Toggling the incognito mode reloads the extension. Wait for it to reload.
WaitForExtensionsWithRulesetsCount(0);
WaitForExtensionsWithRulesetsCount(1);
test_enabled_in_incognito(true);
}
{
// Disable the extension in incognito mode.
SCOPED_TRACE("Testing extension after disabling it in incognito");
util::SetIsIncognitoEnabled(extension_id, profile(), false /*enabled*/);
// Toggling the incognito mode reloads the extension. Wait for it to reload.
WaitForExtensionsWithRulesetsCount(0);
WaitForExtensionsWithRulesetsCount(1);
test_enabled_in_incognito(false);
}
}
// Tests the declarativeNetRequestWithHostAccess permission.
IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest, HostAccessPermission) {
std::vector<TestRule> rules;
int rule_id = kMinValidID;
auto get_url = [this](const std::string& host, const std::string& query) {
std::string path = "/pages_with_script/index.html?q=" + query;
return embedded_test_server()->GetURL(host, path);
};
{
TestRule rule = CreateMainFrameBlockRule("block");
rule.id = rule_id++;
rules.push_back(rule);
}
{
TestRule rule = CreateGenericRule(rule_id++);
rule.condition->url_filter = "redirect";
rule.condition->resource_types = std::vector<std::string>({"main_frame"});
rule.action->type = "redirect";
rule.action->redirect.emplace();
rule.action->redirect->url = get_url("final.com", "final").spec();
rules.push_back(rule);
}
{
TestRule rule = CreateGenericRule(rule_id++);
rule.condition->url_filter = "|http://*upgrade";
rule.condition->resource_types = std::vector<std::string>({"main_frame"});
rule.action->type = "upgradeScheme";
rules.push_back(rule);
}
{
// Have a rule which redirects upgraded https requests to a special url. It
// might seem that this can be avoided by using a HTTPS test server but it
// doesn't seem trivial to listen to the same port on both http and https.
TestRule rule = CreateGenericRule(rule_id++);
rule.condition->url_filter = "|https://*upgrade";
rule.condition->resource_types = std::vector<std::string>({"main_frame"});
rule.action->type = "redirect";
rule.action->redirect.emplace();
rule.action->redirect->url = get_url("https.com", "https").spec();
rules.push_back(rule);
}
set_config_flags(
ConfigFlag::kConfig_HasDelarativeNetRequestWithHostAccessPermission |
ConfigFlag::kConfig_OmitDeclarativeNetRequestPermission);
ASSERT_NO_FATAL_FAILURE(
LoadExtensionWithRules(rules, "directory", {"*://allowed.com:*/*"}));
struct {
GURL url;
// nullopt if expected to be blocked.
std::optional<GURL> expected_final_url;
} cases[] = {
{get_url("allowed.com", "block"), std::nullopt},
{get_url("notallowed.com", "block"), get_url("notallowed.com", "block")},
{get_url("allowed.com", "redirect"), get_url("final.com", "final")},
{get_url("notallowed.com", "redirect"),
get_url("notallowed.com", "redirect")},
// This should be upgraded first and then match the https->http rule.
{get_url("allowed.com", "upgrade"), get_url("https.com", "https")},
{get_url("notallowed.com", "upgrade"),
get_url("notallowed.com", "upgrade")},
};
for (const auto& test_case : cases) {
SCOPED_TRACE(
base::StringPrintf("Testing %s", test_case.url.spec().c_str()));
if (!test_case.expected_final_url) {
EXPECT_TRUE(IsNavigationBlocked(test_case.url));
continue;
}
NavigateToURL(test_case.url);
EXPECT_EQ(content::PAGE_TYPE_NORMAL, GetPageType());
EXPECT_EQ(*test_case.expected_final_url,
web_contents()->GetLastCommittedURL());
}
}
#if (BUILDFLAG(IS_MAC) && !defined(NDEBUG)) || BUILDFLAG(IS_ANDROID)
// Times out on mac-debug: https://crbug.com/1159418
// Flaky on Android: https://crbug.com/371298229
#define MAYBE_ChromeURLS DISABLED_ChromeURLS
#else
#define MAYBE_ChromeURLS ChromeURLS
#endif
// Ensure extensions can't intercept chrome:// urls, even after explicitly
// requesting access to <all_urls>.
IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest, MAYBE_ChromeURLS) {
// Have the extension block all chrome:// urls.
TestRule rule = CreateGenericRule();
rule.condition->url_filter =
std::string(content::kChromeUIScheme) + url::kStandardSchemeSeparator;
ASSERT_NO_FATAL_FAILURE(LoadExtensionWithRules({rule}));
std::vector<const char*> test_urls = {
chrome::kChromeUIFlagsURL, chrome::kChromeUIAboutURL,
chrome::kChromeUIExtensionsURL, chrome::kChromeUIVersionURL};
for (const char* url : test_urls) {
NavigateToURL(GURL(url));
EXPECT_EQ(content::PAGE_TYPE_NORMAL, GetPageType());
}
}
#if !BUILDFLAG(IS_ANDROID)
// Test that a packed extension with a DNR ruleset behaves correctly after
// browser restart.
// TODO(crbug.com/391924202): Port to desktop Android once it supports packed
// extensions.
IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest_Packed,
PRE_BrowserRestart) {
// This is not tested for unpacked extensions since the unpacked extension
// directory won't be persisted across browser restarts.
ASSERT_EQ(ExtensionLoadType::PACKED, GetLoadType());
set_config_flags(ConfigFlag::kConfig_HasBackgroundScript);
// Block all main frame requests to "static.com".
TestRule rule = CreateGenericRule();
rule.condition->url_filter = std::string("static.com");
rule.condition->resource_types = std::vector<std::string>({"main_frame"});
ASSERT_NO_FATAL_FAILURE(LoadExtensionWithRules({rule}, "extension", {}));
const ExtensionId& extension_id = last_loaded_extension_id();
// Add dynamic rule to block main-frame requests to "dynamic.com".
rule.condition->url_filter = std::string("dynamic.com");
ASSERT_NO_FATAL_FAILURE(AddDynamicRules(extension_id, {rule}));
// Add session rule to block main-frame requests to "session.com".
rule.condition->url_filter = std::string("session.com");
ASSERT_NO_FATAL_FAILURE(UpdateSessionRules(extension_id, {}, {rule}));
CompositeMatcher* composite_matcher =
ruleset_manager()->GetMatcherForExtension(extension_id);
ASSERT_TRUE(composite_matcher);
EXPECT_THAT(
GetPublicRulesetIDs(*last_loaded_extension(), *composite_matcher),
UnorderedElementsAre(kDefaultRulesetID, dnr_api::DYNAMIC_RULESET_ID,
dnr_api::SESSION_RULESET_ID));
EXPECT_TRUE(IsNavigationBlocked(embedded_test_server()->GetURL(
"static.com", "/pages_with_script/index.html")));
EXPECT_TRUE(IsNavigationBlocked(embedded_test_server()->GetURL(
"dynamic.com", "/pages_with_script/index.html")));
EXPECT_TRUE(IsNavigationBlocked(embedded_test_server()->GetURL(
"session.com", "/pages_with_script/index.html")));
EXPECT_FALSE(IsNavigationBlocked(embedded_test_server()->GetURL(
"unmatched.com", "/pages_with_script/index.html")));
}
IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest_Packed,
BrowserRestart) {
// This is not tested for unpacked extensions since the unpacked extension
// directory won't be persisted across browser restarts.
ASSERT_EQ(ExtensionLoadType::PACKED, GetLoadType());
const Extension* extension = nullptr;
for (const auto& ext : extension_registry()->enabled_extensions()) {
if (ext->name() == "extension") {
extension = ext.get();
break;
}
}
ASSERT_TRUE(extension);
// The session-scoped ruleset should not be enabled after the browser
// restarts. However both the static and dynamic ruleset enabled in the last
// session should be enabled.
CompositeMatcher* composite_matcher =
ruleset_manager()->GetMatcherForExtension(extension->id());
ASSERT_TRUE(composite_matcher);
EXPECT_THAT(
GetPublicRulesetIDs(*extension, *composite_matcher),
UnorderedElementsAre(kDefaultRulesetID, dnr_api::DYNAMIC_RULESET_ID));
// Ensure that the DNR extension enabled in previous browser session still
// correctly blocks network requests.
EXPECT_TRUE(IsNavigationBlocked(embedded_test_server()->GetURL(
"static.com", "/pages_with_script/index.html")));
EXPECT_TRUE(IsNavigationBlocked(embedded_test_server()->GetURL(
"dynamic.com", "/pages_with_script/index.html")));
EXPECT_FALSE(IsNavigationBlocked(embedded_test_server()->GetURL(
"session.com", "/pages_with_script/index.html")));
EXPECT_FALSE(IsNavigationBlocked(embedded_test_server()->GetURL(
"unmatched.com", "/pages_with_script/index.html")));
}
// Tests than an extension can omit the "declarative_net_request" manifest key
// but can still use dynamic rules.
// TODO(crbug.com/392953825): Port to desktop Android once EnableExtension() is
// supported there.
IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest, ZeroRulesets) {
set_config_flags(ConfigFlag::kConfig_HasBackgroundScript |
ConfigFlag::kConfig_OmitDeclarativeNetRequestKey);
ASSERT_NO_FATAL_FAILURE(LoadExtensionWithRulesets(
{} /* rulesets */, "extension_directory", {} /* hosts */));
const ExtensionId& extension_id = last_loaded_extension_id();
const GURL url = embedded_test_server()->GetURL(
"example.com", "/pages_with_script/page.html");
EXPECT_FALSE(IsNavigationBlocked(url));
// Add dynamic rule to block main-frame requests to "page.html".
TestRule rule = CreateGenericRule();
rule.condition->url_filter = std::string("page.html");
rule.condition->resource_types = std::vector<std::string>({"main_frame"});
EXPECT_EQ(0u, extensions_with_rulesets_count());
ASSERT_NO_FATAL_FAILURE(AddDynamicRules(extension_id, {rule}));
WaitForExtensionsWithRulesetsCount(1);
EXPECT_TRUE(IsNavigationBlocked(url));
DisableExtension(extension_id);
WaitForExtensionsWithRulesetsCount(0);
EXPECT_FALSE(IsNavigationBlocked(url));
EnableExtension(extension_id);
WaitForExtensionsWithRulesetsCount(1);
EXPECT_TRUE(IsNavigationBlocked(url));
}
#endif // !BUILDFLAG(IS_ANDROID)
// Ensure that when an extension blocks a main-frame request using
// declarativeNetRequest, the resultant error page attributes this to an
// extension.
IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest,
ErrorPageForBlockedMainFrameNavigation) {
ASSERT_NO_FATAL_FAILURE(
LoadExtensionWithRules({CreateMainFrameBlockRule("example.com")}));
NavigateToURL(GetURLForFilter("example.com"));
EXPECT_EQ(content::PAGE_TYPE_ERROR, GetPageType());
std::string body =
content::EvalJs(web_contents(), "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."));
}
// Test an extension with multiple static rulesets.
IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest, MultipleRulesets) {
set_config_flags(ConfigFlag::kConfig_HasBackgroundScript);
const int kNumStaticRulesets = 4;
const char* kStaticFilterPrefix = "static";
std::vector<GURL> expected_blocked_urls;
std::vector<TestRulesetInfo> rulesets;
std::vector<GURL> expected_allowed_urls;
for (int i = 0; i < kNumStaticRulesets; ++i) {
std::vector<TestRule> rules;
std::string id = kStaticFilterPrefix + base::NumberToString(i);
rules.push_back(CreateMainFrameBlockRule(id));
// Enable even indexed rulesets by default.
bool enabled = i % 2 == 0;
if (enabled)
expected_blocked_urls.push_back(GetURLForFilter(id));
else
expected_allowed_urls.push_back(GetURLForFilter(id));
rulesets.emplace_back(id, ToListValue(rules), enabled);
}
ASSERT_NO_FATAL_FAILURE(LoadExtensionWithRulesets(
rulesets, "extension_directory", {} /* hosts */));
const ExtensionId& extension_id = last_loaded_extension_id();
// Also add a dynamic rule blocking pages with string "dynamic".
const char* kDynamicFilter = "dynamic";
ASSERT_NO_FATAL_FAILURE(AddDynamicRules(
extension_id, {CreateMainFrameBlockRule(kDynamicFilter)}));
expected_blocked_urls.push_back(GetURLForFilter(kDynamicFilter));
expected_allowed_urls.push_back(GetURLForFilter("no_such_rule"));
VerifyNavigations(expected_blocked_urls, expected_allowed_urls);
}
// Ensure that Blink's in-memory cache is cleared on adding/removing rulesets.
IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest, RendererCacheCleared) {
// Observe requests to RulesetManager to monitor requests to script.js.
GURL observed_url =
embedded_test_server()->GetURL("example.com", "/cached/script.js");
GURL url = embedded_test_server()->GetURL(
"example.com", "/cached/page_with_cacheable_script.html");
// With no extension loaded, the request to the script should succeed.
NavigateToURL(url);
EXPECT_EQ(content::PAGE_TYPE_NORMAL, GetPageType());
EXPECT_TRUE(WasFrameWithScriptLoaded(GetPrimaryMainFrame()));
// NOTE: RulesetMatcher will not see network requests if no rulesets are
// active.
bool expect_request_seen =
base::FeatureList::IsEnabled(
extensions_features::kForceWebRequestProxyForTest);
EXPECT_EQ(expect_request_seen,
base::Contains(ruleset_manager_observer()->GetAndResetRequestSeen(),
observed_url));
// Another request to |url| should not cause a network request for
// script.js since it will be served by the renderer's in-memory
// cache.
NavigateToURL(url);
EXPECT_EQ(content::PAGE_TYPE_NORMAL, GetPageType());
EXPECT_TRUE(WasFrameWithScriptLoaded(GetPrimaryMainFrame()));
EXPECT_FALSE(base::Contains(
ruleset_manager_observer()->GetAndResetRequestSeen(), observed_url));
// Now block requests to script.js.
TestRule rule = CreateGenericRule();
rule.condition->url_filter = std::string("script.js");
ASSERT_NO_FATAL_FAILURE(LoadExtensionWithRules({rule}));
// Adding an extension ruleset should have cleared the renderer's in-memory
// cache. Hence the browser process will observe the request to
// script.js and block it.
NavigateToURL(url);
EXPECT_EQ(content::PAGE_TYPE_NORMAL, GetPageType());
EXPECT_FALSE(WasFrameWithScriptLoaded(GetPrimaryMainFrame()));
EXPECT_TRUE(base::Contains(
ruleset_manager_observer()->GetAndResetRequestSeen(), observed_url));
// Disable the extension.
DisableExtension(last_loaded_extension_id(),
{disable_reason::DISABLE_USER_ACTION});
WaitForExtensionsWithRulesetsCount(0);
// Disabling the extension should cause the request to succeed again. The
// request for the script will again be observed by the browser since it's not
// in the renderer's in-memory cache.
NavigateToURL(url);
EXPECT_EQ(content::PAGE_TYPE_NORMAL, GetPageType());
EXPECT_TRUE(WasFrameWithScriptLoaded(GetPrimaryMainFrame()));
EXPECT_EQ(expect_request_seen,
base::Contains(ruleset_manager_observer()->GetAndResetRequestSeen(),
observed_url));
}
// Tests that proxy requests aren't intercepted. See https://crbug.com/794674.
IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest,
PacRequestsBypassRules) {
// Load the extension.
std::vector<TestRule> rules;
TestRule rule = CreateGenericRule();
rule.condition->url_filter = std::string("*pac");
rule.id = 1;
rules.push_back(rule);
ASSERT_NO_FATAL_FAILURE(LoadExtensionWithRules(rules));
// 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();
// Verify that the extension can't intercept the network request.
NavigateToURL(
GURL("http://does.not.resolve.test/pages_with_script/page.html"));
EXPECT_TRUE(WasFrameWithScriptLoaded(GetPrimaryMainFrame()));
EXPECT_EQ(content::PAGE_TYPE_NORMAL, GetPageType());
}
// Ensure that an extension can't intercept requests on the chrome-extension
// scheme.
IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest,
InterceptExtensionScheme) {
// Load two extensions. One blocks all urls, and the other blocks urls with
// "google.com" as a substring.
std::vector<TestRule> rules_1;
TestRule rule = CreateGenericRule();
rule.condition->url_filter = std::string("*");
rules_1.push_back(rule);
std::vector<TestRule> rules_2;
rule = CreateGenericRule();
rule.condition->url_filter = std::string("google.com");
rules_2.push_back(rule);
ASSERT_NO_FATAL_FAILURE(LoadExtensionWithRules(
rules_1, "extension_1", {URLPattern::kAllUrlsPattern}));
const ExtensionId& extension_id_1 = last_loaded_extension_id();
ASSERT_NO_FATAL_FAILURE(LoadExtensionWithRules(
rules_2, "extension_2", {URLPattern::kAllUrlsPattern}));
const ExtensionId& extension_id_2 = last_loaded_extension_id();
auto get_manifest_url = [](const ExtensionId& extension_id) {
return GURL(base::StringPrintf("%s://%s/manifest.json",
extensions::kExtensionScheme,
extension_id.c_str()));
};
// Extension 1 should not be able to block the request to its own
// manifest.json or that of the Extension 2, even with "<all_urls>" host
// permissions.
NavigateToURL(get_manifest_url(extension_id_1));
GURL final_url = web_contents()->GetLastCommittedURL();
EXPECT_EQ(content::PAGE_TYPE_NORMAL, GetPageType());
NavigateToURL(get_manifest_url(extension_id_2));
EXPECT_EQ(content::PAGE_TYPE_NORMAL, GetPageType());
}
// Ensures that any <img> elements blocked by the API are collapsed.
IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest, ImageCollapsed) {
// Loads a page with an image and returns whether the image was collapsed.
auto is_image_collapsed = [this]() {
NavigateToURL(embedded_test_server()->GetURL("google.com", "/image.html"));
EXPECT_EQ(content::PAGE_TYPE_NORMAL, GetPageType());
const std::string script = "!!window.imageCollapsed;";
return content::EvalJs(web_contents(), script).ExtractBool();
};
// Initially the image shouldn't be collapsed.
EXPECT_FALSE(is_image_collapsed());
// Load an extension which blocks all images.
std::vector<TestRule> rules;
TestRule rule = CreateGenericRule();
rule.condition->url_filter = std::string("*");
rule.condition->resource_types = std::vector<std::string>({"image"});
rules.push_back(rule);
ASSERT_NO_FATAL_FAILURE(LoadExtensionWithRules(rules));
// Now the image request should be blocked and the corresponding DOM element
// should be collapsed.
EXPECT_TRUE(is_image_collapsed());
}
// Ensures that any <iframe> elements whose document load is blocked by the API,
// are collapsed.
IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest, IFrameCollapsed) {
const std::string kFrameName1 = "frame1";
const std::string kFrameName2 = "frame2";
const GURL page_url = embedded_test_server()->GetURL(
"google.com", "/page_with_two_frames.html");
// Load a page with two iframes (|kFrameName1| and |kFrameName2|). Initially
// both the frames should be loaded successfully.
NavigateToURL(page_url);
ASSERT_TRUE(WasFrameWithScriptLoaded(GetPrimaryMainFrame()));
{
SCOPED_TRACE("No extension loaded");
TestFrameCollapse(kFrameName1, false);
TestFrameCollapse(kFrameName2, false);
}
// Now load an extension which blocks all requests with "frame=1" in its url.
TestRule rule = CreateGenericRule();
rule.condition->url_filter = std::string("frame=1");
ASSERT_NO_FATAL_FAILURE(LoadExtensionWithRules({rule}));
// Reloading the page should cause |kFrameName1| to be collapsed.
NavigateToURL(page_url);
ASSERT_TRUE(WasFrameWithScriptLoaded(GetPrimaryMainFrame()));
{
SCOPED_TRACE("Extension loaded initial");
TestFrameCollapse(kFrameName1, true);
TestFrameCollapse(kFrameName2, false);
}
// Now interchange the "src" of the two frames. This should cause
// |kFrameName2| to be collapsed and |kFrameName1| to be un-collapsed.
GURL frame_url_1 = GetFrameByName(kFrameName1)->GetLastCommittedURL();
GURL frame_url_2 = GetFrameByName(kFrameName2)->GetLastCommittedURL();
NavigateFrame(kFrameName1, frame_url_2);
NavigateFrame(kFrameName2, frame_url_1);
{
SCOPED_TRACE("Extension loaded src swapped");
TestFrameCollapse(kFrameName1, false);
TestFrameCollapse(kFrameName2, true);
}
// Remove the frames from the DOM, swap the "src" of the frames,
// then add them back to the DOM. `kFrameName1` should be blocked
// and therefore collapsed.
RemoveNavigateAndReAddFrame(kFrameName1, frame_url_1);
RemoveNavigateAndReAddFrame(kFrameName2, frame_url_2);
{
SCOPED_TRACE("Removed src-swapped and readded to DOM");
TestFrameCollapse(kFrameName1, true);
TestFrameCollapse(kFrameName2, false);
}
// Remove the frames from the DOM again, but this time add them back
// without changing their "src". `kFrameName1` should still be
// collapsed.
RemoveNavigateAndReAddFrame(kFrameName1, frame_url_1);
RemoveNavigateAndReAddFrame(kFrameName2, frame_url_2);
{
SCOPED_TRACE("Removed and readded to DOM");
TestFrameCollapse(kFrameName1, true);
TestFrameCollapse(kFrameName2, false);
}
}
#if !BUILDFLAG(IS_ANDROID)
// Tests that we correctly reindex a corrupted ruleset. This is only tested for
// packed extensions, since the JSON ruleset is reindexed on each extension
// load for unpacked extensions, so corruption is not an issue.
// TODO(crbug.com/391924202): Port to desktop Android once packed extensions
// are supported.
IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest_Packed,
CorruptedIndexedRuleset) {
set_config_flags(ConfigFlag::kConfig_HasBackgroundScript);
// Load an extension which blocks all main-frame requests to "google.com".
TestRule rule = CreateGenericRule();
rule.condition->url_filter = std::string("||google.com");
rule.condition->resource_types = std::vector<std::string>({"main_frame"});
ASSERT_NO_FATAL_FAILURE(LoadExtensionWithRules({rule}));
const ExtensionId& extension_id = last_loaded_extension_id();
// Add a dynamic rule to block main-frame requests to "example.com".
rule.condition->url_filter = std::string("||example.com");
ASSERT_NO_FATAL_FAILURE(AddDynamicRules(extension_id, {rule}));
const GURL static_rule_url = embedded_test_server()->GetURL(
"google.com", "/pages_with_script/index.html");
const GURL dynamic_rule_url = embedded_test_server()->GetURL(
"example.com", "/pages_with_script/index.html");
const GURL unblocked_url = embedded_test_server()->GetURL(
"yahoo.com", "/pages_with_script/index.html");
const Extension* extension = last_loaded_extension();
std::vector<FileBackedRulesetSource> static_sources =
FileBackedRulesetSource::CreateStatic(
*extension, FileBackedRulesetSource::RulesetFilter::kIncludeAll);
ASSERT_EQ(1u, static_sources.size());
FileBackedRulesetSource dynamic_source =
FileBackedRulesetSource::CreateDynamic(profile(), extension->id());
// Loading the extension should cause some main frame requests to be blocked.
{
SCOPED_TRACE("Page load after loading extension");
EXPECT_TRUE(IsNavigationBlocked(static_rule_url));
EXPECT_TRUE(IsNavigationBlocked(dynamic_rule_url));
EXPECT_FALSE(IsNavigationBlocked(unblocked_url));
}
// Helper to overwrite an indexed ruleset file with arbitrary data to mimic
// corruption, while maintaining the correct version header.
auto corrupt_file_for_checksum_mismatch =
[](const base::FilePath& indexed_path) {
base::ScopedAllowBlockingForTesting scoped_allow_blocking;
std::string corrupted_data = GetVersionHeaderForTesting() + "data";
ASSERT_TRUE(base::WriteFile(indexed_path, corrupted_data));
};
// Helper to reload the extension and ensure it is working.
auto test_extension_works_after_reload = [&]() {
EXPECT_EQ(1u, extensions_with_rulesets_count());
DisableExtension(extension_id);
WaitForExtensionsWithRulesetsCount(0);
EnableExtension(extension_id);
WaitForExtensionsWithRulesetsCount(1);
EXPECT_TRUE(IsNavigationBlocked(static_rule_url));
EXPECT_TRUE(IsNavigationBlocked(dynamic_rule_url));
EXPECT_FALSE(IsNavigationBlocked(unblocked_url));
};
const char* kReindexHistogram =
"Extensions.DeclarativeNetRequest.RulesetReindexSuccessful";
// Test static ruleset re-indexing.
{
SCOPED_TRACE("Static ruleset corruption");
corrupt_file_for_checksum_mismatch(static_sources[0].indexed_path());
base::HistogramTester tester;
test_extension_works_after_reload();
// Loading the static ruleset would fail initially due to checksum mismatch
// but will succeed on re-indexing.
tester.ExpectBucketCount(kReindexHistogram, true /*sample*/, 1 /*count*/);
// Count of 2 because we load both static and dynamic rulesets.
tester.ExpectBucketCount(kLoadRulesetResultHistogram,
LoadRulesetResult::kSuccess /* sample */,
2 /* count */);
}
// Test dynamic ruleset re-indexing.
{
SCOPED_TRACE("Dynamic ruleset corruption");
corrupt_file_for_checksum_mismatch(dynamic_source.indexed_path());
base::HistogramTester tester;
test_extension_works_after_reload();
// Loading the dynamic ruleset would have failed initially due to checksum
// mismatch and later succeeded on re-indexing.
tester.ExpectBucketCount(kReindexHistogram, true /*sample*/, 1 /*count*/);
// Count of 2 because we load both static and dynamic rulesets.
tester.ExpectBucketCount(kLoadRulesetResultHistogram,
LoadRulesetResult::kSuccess /* sample */,
2 /* count */);
}
// Go crazy and corrupt both static and dynamic rulesets.
{
SCOPED_TRACE("Static and dynamic ruleset corruption");
corrupt_file_for_checksum_mismatch(dynamic_source.indexed_path());
corrupt_file_for_checksum_mismatch(static_sources[0].indexed_path());
base::HistogramTester tester;
test_extension_works_after_reload();
// Loading the ruleset would have failed initially due to checksum mismatch
// and later succeeded.
tester.ExpectBucketCount(kReindexHistogram, true /*sample*/, 2 /*count*/);
// Count of 2 because we load both static and dynamic rulesets.
tester.ExpectBucketCount(kLoadRulesetResultHistogram,
LoadRulesetResult::kSuccess /* sample */,
2 /* count */);
}
}
// Tests that we reindex rulesets on checksum mismatch.
// TODO(crbug.com/392953825): Port to desktop Android once EnableExtension()
// is supported.
IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest,
RulesetLoadReindexOnChecksumMismatch) {
const size_t kNumStaticRulesets = 4;
const char* kStaticFilterPrefix = "static";
std::vector<TestRulesetInfo> rulesets;
std::vector<GURL> urls_for_indices;
for (size_t i = 0; i < kNumStaticRulesets; ++i) {
std::vector<TestRule> rules;
std::string id = kStaticFilterPrefix + base::NumberToString(i);
rules.push_back(CreateMainFrameBlockRule(id));
urls_for_indices.push_back(GetURLForFilter(id));
rulesets.emplace_back(id, ToListValue(rules));
}
ASSERT_NO_FATAL_FAILURE(
LoadExtensionWithRulesets(rulesets, "extension_directory", /*hosts=*/{}));
const ExtensionId& extension_id = last_loaded_extension_id();
EXPECT_TRUE(ruleset_manager()->GetMatcherForExtension(extension_id));
const Extension* extension = last_loaded_extension();
ASSERT_TRUE(extension);
std::vector<FileBackedRulesetSource> sources =
FileBackedRulesetSource::CreateStatic(
*extension, FileBackedRulesetSource::RulesetFilter::kIncludeAll);
ASSERT_EQ(kNumStaticRulesets, sources.size());
// Mimic extension prefs corruption by overwriting the indexed ruleset
// checksum for the first, third and fourth rulesets.
const int kInvalidRulesetChecksum = -1;
std::vector<int> corrupted_ruleset_indices = {0, 2, 3};
std::vector<int> non_corrupted_ruleset_indices = {1};
PrefsHelper helper(*ExtensionPrefs::Get(profile()));
for (int index : corrupted_ruleset_indices) {
helper.SetStaticRulesetChecksum(extension_id, sources[index].id(),
kInvalidRulesetChecksum);
}
DisableExtension(extension_id);
WaitForExtensionsWithRulesetsCount(0);
EXPECT_FALSE(ruleset_manager()->GetMatcherForExtension(extension_id));
// Reindexing and loading corrupted rulesets should succeed.
// TODO(crbug.com/380434972): Check that a content verification job has been
// started in case ruleset files are corrupted.
base::HistogramTester tester;
EnableExtension(extension_id);
WaitForExtensionsWithRulesetsCount(1);
EXPECT_TRUE(ruleset_manager()->GetMatcherForExtension(extension_id));
// Verify that loading all rulesets succeeded since the previously corrupt
// rulesets were reindexed successfully.
tester.ExpectTotalCount(kLoadRulesetResultHistogram, rulesets.size());
EXPECT_EQ(rulesets.size(), static_cast<size_t>(tester.GetBucketCount(
kLoadRulesetResultHistogram,
/*sample=*/LoadRulesetResult::kSuccess)));
// Verify that re-indexing the corrupted rulesets succeeded.
tester.ExpectUniqueSample(
"Extensions.DeclarativeNetRequest.RulesetReindexSuccessful",
/*sample=*/true,
/*expected_bucket_count=*/corrupted_ruleset_indices.size());
// Finally verify that all rulesets still work fine.
std::vector<GURL> expected_blocked_urls;
for (int index : non_corrupted_ruleset_indices)
expected_blocked_urls.push_back(urls_for_indices[index]);
for (int index : corrupted_ruleset_indices)
expected_blocked_urls.push_back(urls_for_indices[index]);
VerifyNavigations(expected_blocked_urls,
/*expected_allowed_urls=*/std::vector<GURL>());
}
#endif // !BUILDFLAG(IS_ANDROID)
// Tests that checksum mismatches resulting from prefs corruption shouldn't
// prevent rulesets from being re-enabled.
IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest,
UpdateEnabledRulesetsChecksumMismatch) {
set_config_flags(ConfigFlag::kConfig_HasBackgroundScript);
// Load an extension that blocks navigations to google.com.
std::vector<TestRule> rules = {CreateMainFrameBlockRule("google")};
auto ruleset = TestRulesetInfo("id1", ToListValue(rules), true);
constexpr char kDirectory1[] = "dir1";
const int kInvalidRulesetChecksum = -1;
ASSERT_NO_FATAL_FAILURE(
LoadExtensionWithRulesets({ruleset}, kDirectory1, /*hosts=*/{}));
// Verify that the navigation is blocked.
std::vector<GURL> google_url({GetURLForFilter("google")});
VerifyNavigations(google_url, /*expected_allowed_urls=*/std::vector<GURL>());
const ExtensionId& extension_id = last_loaded_extension_id();
ExtensionPrefs* prefs = ExtensionPrefs::Get(profile());
ASSERT_TRUE(prefs);
int expected_checksum = kInvalidRulesetChecksum;
PrefsHelper helper(*prefs);
EXPECT_TRUE(helper.GetStaticRulesetChecksum(
extension_id, kMinValidStaticRulesetID, expected_checksum));
// Disable the ruleset and verify that navigations to google.com are no longer
// blocked.
ASSERT_NO_FATAL_FAILURE(UpdateEnabledRulesets(extension_id, {"id1"}, {}));
VerifyNavigations(/*expected_blocked_urls=*/std::vector<GURL>(), google_url);
// Simulate a prefs corruption.
helper.SetStaticRulesetChecksum(extension_id, kMinValidStaticRulesetID,
kInvalidRulesetChecksum);
base::HistogramTester tester;
// Try to enable the ruleset again; there should be no errors.
ASSERT_NO_FATAL_FAILURE(UpdateEnabledRulesets(extension_id, {}, {"id1"}));
// Verify that the checksum has been updated and is equal to its
// pre-corruption value and that reindexing has succeeded.
// TODO(crbug.com/380434972): Check that a content verification job has been
// started in case ruleset files are corrupted.
EXPECT_EQ(1u, static_cast<size_t>(tester.GetBucketCount(
kLoadRulesetResultHistogram,
/*sample=*/LoadRulesetResult::kSuccess)));
// Verify that re-indexing the corrupted rulesets succeeded.
tester.ExpectUniqueSample(
"Extensions.DeclarativeNetRequest.RulesetReindexSuccessful",
/*sample=*/true, /*expected_bucket_count=*/1u);
int actual_checksum = kInvalidRulesetChecksum;
EXPECT_TRUE(helper.GetStaticRulesetChecksum(
extension_id, kMinValidStaticRulesetID, actual_checksum));
EXPECT_EQ(expected_checksum, actual_checksum);
// Verify that the navigation is blocked after re-enabling the ruleset.
VerifyNavigations(google_url, /*expected_allowed_urls=*/std::vector<GURL>());
}
#if !BUILDFLAG(IS_ANDROID)
// Tests that we reindex the extension rulesets in case its ruleset format
// version is not the same as one used by Chrome.
// TODO(crbug.com/391924202): Port to desktop Android once packed extensions
// are supported.
IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest_Packed,
ReindexOnRulesetVersionMismatch) {
set_config_flags(ConfigFlag::kConfig_HasBackgroundScript);
TestRule rule = CreateGenericRule();
rule.condition->url_filter = std::string("*");
const int kNumStaticRulesets = 4;
std::vector<TestRulesetInfo> rulesets;
for (int i = 0; i < kNumStaticRulesets; ++i)
rulesets.emplace_back(base::NumberToString(i), ToListValue({rule}));
ASSERT_NO_FATAL_FAILURE(LoadExtensionWithRulesets(
rulesets, "extension_directory", {} /* hosts */));
const ExtensionId& extension_id = last_loaded_extension_id();
EXPECT_TRUE(ruleset_manager()->GetMatcherForExtension(extension_id));
// Add a dynamic rule.
AddDynamicRules(extension_id, {rule});
DisableExtension(extension_id);
WaitForExtensionsWithRulesetsCount(0);
EXPECT_FALSE(ruleset_manager()->GetMatcherForExtension(extension_id));
// Now change the current indexed ruleset format version. This should cause a
// version mismatch when the extension is loaded again, but re-indexing should
// still succeed.
ScopedIncrementRulesetVersion scoped_version_change =
CreateScopedIncrementRulesetVersionForTesting();
// Also override the checksum value for the indexed ruleset to simulate a
// flatbuffer schema change. This will ensure that the checksum of the
// re-indexed file differs from the current checksum.
const int kTestChecksum = 100;
OverrideGetChecksumForTest(kTestChecksum);
base::HistogramTester tester;
EnableExtension(extension_id);
WaitForExtensionsWithRulesetsCount(1);
EXPECT_TRUE(ruleset_manager()->GetMatcherForExtension(extension_id));
// We add 1 to include the dynamic ruleset.
const int kNumRulesets = kNumStaticRulesets + 1;
// Verify that loading the static and dynamic rulesets would cause reindexing
// due to version header mismatch and later succeeded.
tester.ExpectUniqueSample(
"Extensions.DeclarativeNetRequest.RulesetReindexSuccessful",
true /*sample*/, kNumRulesets /*count*/);
EXPECT_EQ(kNumRulesets,
tester.GetBucketCount(kLoadRulesetResultHistogram,
LoadRulesetResult::kSuccess /*sample*/));
// Ensure that the new checksum was correctly persisted in prefs.
ExtensionPrefs* prefs = ExtensionPrefs::Get(profile());
const Extension* extension = last_loaded_extension();
std::vector<FileBackedRulesetSource> static_sources =
FileBackedRulesetSource::CreateStatic(
*extension, FileBackedRulesetSource::RulesetFilter::kIncludeAll);
ASSERT_EQ(static_cast<size_t>(kNumStaticRulesets), static_sources.size());
int checksum = kTestChecksum + 1;
PrefsHelper helper(*prefs);
for (const FileBackedRulesetSource& source : static_sources) {
EXPECT_TRUE(
helper.GetStaticRulesetChecksum(extension_id, source.id(), checksum));
EXPECT_EQ(kTestChecksum, checksum);
// Reset checksum for the next test.
checksum = kTestChecksum + 1;
}
EXPECT_TRUE(helper.GetDynamicRulesetChecksum(extension_id, checksum));
EXPECT_EQ(kTestChecksum, checksum);
}
// Tests that static ruleset preferences are deleted on uninstall for an edge
// case where ruleset loading is completed after extension uninstallation.
// Regression test for crbug.com/1067441.
// TODO(crbug.com/392953825): Port to desktop Android once EnableExtension() is
// supported.
IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest,
RulesetPrefsDeletedOnUninstall) {
ASSERT_NO_FATAL_FAILURE(LoadExtensionWithRules({} /* rules */));
const ExtensionId& extension_id = last_loaded_extension_id();
const Extension* extension = last_loaded_extension();
std::vector<FileBackedRulesetSource> static_sources =
FileBackedRulesetSource::CreateStatic(
*extension, FileBackedRulesetSource::RulesetFilter::kIncludeAll);
ASSERT_EQ(1u, static_sources.size());
DisableExtension(extension_id);
WaitForExtensionsWithRulesetsCount(0);
ExtensionPrefs* prefs = ExtensionPrefs::Get(profile());
PrefsHelper helper(*prefs);
int checksum = -1;
EXPECT_TRUE(helper.GetStaticRulesetChecksum(
extension_id, static_sources[0].id(), checksum));
// Now change the current indexed ruleset format version. This should cause a
// version mismatch when the extension is loaded again, but re-indexing should
// still succeed.
ScopedIncrementRulesetVersion scoped_version_change =
CreateScopedIncrementRulesetVersionForTesting();
// Also override the checksum value for the indexed ruleset to simulate a
// flatbuffer schema change. This will ensure that the checksum of the
// re-indexed file differs from the current checksum.
const int kTestChecksum = checksum + 1;
OverrideGetChecksumForTest(kTestChecksum);
base::HistogramTester tester;
RulesetLoadObserver load_observer(rules_monitor_service(), extension_id);
// Now enable the extension, causing the asynchronous extension ruleset load
// which further results in an asynchronous re-indexing task. Immediately
// uninstall the extension to ensure that the uninstallation precedes
// completion of ruleset load.
EnableExtension(extension_id);
UninstallExtension(extension_id);
load_observer.Wait();
// Verify that reindexing succeeded.
tester.ExpectUniqueSample(
"Extensions.DeclarativeNetRequest.RulesetReindexSuccessful",
true /*sample*/, 1 /*count*/);
// Verify that the prefs for the static ruleset were deleted successfully.
EXPECT_FALSE(helper.GetStaticRulesetChecksum(
extension_id, static_sources[0].id(), checksum));
}
// Tests that redirecting requests using the declarativeNetRequest API works
// with runtime host permissions.
// Disabled due to flakes across all desktop platforms; see
// https://crbug.com/1274533
IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest,
DISABLED_WithheldPermissions_Redirect) {
// Load an extension which redirects all script requests made to
// "b.com/subresources/not_a_valid_script.js", to
// "b.com/subresources/script.js".
TestRule rule = CreateGenericRule();
rule.condition->url_filter =
std::string("b.com/subresources/not_a_valid_script.js");
rule.condition->resource_types = std::vector<std::string>({"script"});
rule.priority = kMinValidPriority;
rule.action->type = std::string("redirect");
rule.action->redirect.emplace();
rule.action->redirect->url =
embedded_test_server()->GetURL("b.com", "/subresources/script.js").spec();
std::vector<std::string> host_permissions = {"*://a.com/", "*://b.com/*"};
ASSERT_NO_FATAL_FAILURE(LoadExtensionWithRules(
{rule}, "extension" /* directory */, host_permissions));
const Extension* extension = last_loaded_extension();
ASSERT_TRUE(extension);
auto verify_script_redirected = [this, extension](
const GURL& page_url,
bool expect_script_redirected,
int expected_blocked_actions) {
ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), page_url));
// The page should have loaded correctly.
EXPECT_EQ(content::PAGE_TYPE_NORMAL, GetPageType());
EXPECT_EQ(expect_script_redirected,
WasFrameWithScriptLoaded(GetPrimaryMainFrame()));
// The EmbeddedTestServer sees requests after the hostname has been
// resolved.
const GURL requested_script_url =
embedded_test_server()->GetURL("/subresources/not_a_valid_script.js");
const GURL redirected_script_url =
embedded_test_server()->GetURL("/subresources/script.js");
std::map<GURL, net::test_server::HttpRequest> seen_requests =
GetAndResetRequestsToServer();
EXPECT_EQ(!expect_script_redirected,
base::Contains(seen_requests, requested_script_url));
EXPECT_EQ(expect_script_redirected,
base::Contains(seen_requests, redirected_script_url));
ExtensionActionRunner* runner =
ExtensionActionRunner::GetForWebContents(web_contents());
ASSERT_TRUE(runner);
EXPECT_EQ(expected_blocked_actions,
runner->GetBlockedActions(extension->id()));
};
{
const GURL page_url = embedded_test_server()->GetURL(
"example.com", "/cross_site_script.html");
SCOPED_TRACE(
base::StringPrintf("Navigating to %s", page_url.spec().c_str()));
// The extension should not redirect the script request. It has access to
// the |requested_script_url| but not its initiator |page_url|.
bool expect_script_redirected = false;
verify_script_redirected(page_url, expect_script_redirected,
BLOCKED_ACTION_NONE);
}
{
const GURL page_url =
embedded_test_server()->GetURL("a.com", "/cross_site_script.html");
SCOPED_TRACE(
base::StringPrintf("Navigating to %s", page_url.spec().c_str()));
// The extension should redirect the script request. It has access to both
// the |requested_script_url| and its initiator |page_url|.
bool expect_script_redirected = true;
verify_script_redirected(page_url, expect_script_redirected,
BLOCKED_ACTION_NONE);
}
// Withhold access to all hosts.
ScriptingPermissionsModifier scripting_modifier(
profile(), base::WrapRefCounted(extension));
scripting_modifier.SetWithholdHostPermissions(true);
{
const GURL page_url =
embedded_test_server()->GetURL("a.com", "/cross_site_script.html");
SCOPED_TRACE(base::StringPrintf("Navigating to %s with all hosts withheld",
page_url.spec().c_str()));
// The extension should not redirect the script request. It's access to both
// the |requested_script_url| and its initiator |page_url| is withheld.
bool expect_script_redirected = false;
verify_script_redirected(page_url, expect_script_redirected,
BLOCKED_ACTION_WEB_REQUEST);
}
// Grant access to only "b.com".
scripting_modifier.GrantHostPermission(GURL("http://b.com"));
{
const GURL page_url =
embedded_test_server()->GetURL("a.com", "/cross_site_script.html");
SCOPED_TRACE(base::StringPrintf("Navigating to %s with a.com withheld",
page_url.spec().c_str()));
// The extension should not redirect the script request. It has access to
// the |requested_script_url|, but its access to the request initiator
// |page_url| is withheld.
bool expect_script_redirected = false;
verify_script_redirected(page_url, expect_script_redirected,
BLOCKED_ACTION_WEB_REQUEST);
}
// Grant access to only "a.com".
scripting_modifier.RemoveAllGrantedHostPermissions();
scripting_modifier.GrantHostPermission(GURL("http://a.com"));
{
const GURL page_url =
embedded_test_server()->GetURL("a.com", "/cross_site_script.html");
SCOPED_TRACE(base::StringPrintf("Navigating to %s with b.com withheld",
page_url.spec().c_str()));
// The extension should redirect the script request. It's access to the
// |requested_script_url| is withheld, but it has access to its initiator
// |page_url|.
bool expect_script_redirected = true;
verify_script_redirected(page_url, expect_script_redirected,
BLOCKED_ACTION_NONE);
}
}
// Ensures that withholding permissions has no effect on blocking requests using
// the declarative net request API.
// TODO(crbug.com/393147570): Port to desktop Android when the permissions API
// and ScriptingPermissionsModifier are available.
IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest,
WithheldPermissions_Block) {
// Load an extension with access to <all_urls> which blocks all script
// requests made on example.com.
TestRule rule = CreateGenericRule();
rule.condition->url_filter = std::string("*");
rule.condition->domains = std::vector<std::string>({"example.com"});
rule.condition->resource_types = std::vector<std::string>({"script"});
ASSERT_NO_FATAL_FAILURE(LoadExtensionWithRules(
{rule}, "test_extension", {URLPattern::kAllUrlsPattern}));
const Extension* extension = last_loaded_extension();
ASSERT_TRUE(extension);
EXPECT_TRUE(extension->permissions_data()
->active_permissions()
.HasEffectiveAccessToAllHosts());
// Withhold access to all hosts.
ScriptingPermissionsModifier scripting_modifier(
profile(), base::WrapRefCounted(extension));
scripting_modifier.SetWithholdHostPermissions(true);
EXPECT_EQ(
extension->permissions_data()->active_permissions().explicit_hosts(),
URLPatternSet(
{URLPattern(URLPattern::SCHEME_CHROMEUI, "chrome://favicon/*")}));
// Request made by index.html to script.js should be blocked despite the
// extension having no active host permissions to the request.
NavigateToURL(embedded_test_server()->GetURL(
"example.com", "/pages_with_script/index.html"));
EXPECT_FALSE(WasFrameWithScriptLoaded(GetPrimaryMainFrame()));
// Sanity check that the script.js request is not blocked if does not match a
// rule.
NavigateToURL(embedded_test_server()->GetURL(
"foo.com", "/pages_with_script/index.html"));
EXPECT_TRUE(WasFrameWithScriptLoaded(GetPrimaryMainFrame()));
}
#endif // !BUILDFLAG(IS_ANDROID)
// Tests the dynamic rule support.
IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest, DynamicRules) {
set_config_flags(ConfigFlag::kConfig_HasBackgroundScript);
// Add an extension which blocks main-frame requests to "yahoo.com".
TestRule block_static_rule = CreateGenericRule();
block_static_rule.condition->resource_types =
std::vector<std::string>({"main_frame"});
block_static_rule.condition->url_filter = std::string("||yahoo.com");
ASSERT_NO_FATAL_FAILURE(LoadExtensionWithRules(
{block_static_rule}, "test_extension", {URLPattern::kAllUrlsPattern}));
const char* kUrlPath = "/pages_with_script/index.html";
GURL yahoo_url = embedded_test_server()->GetURL("yahoo.com", kUrlPath);
GURL google_url = embedded_test_server()->GetURL("google.com", kUrlPath);
EXPECT_TRUE(IsNavigationBlocked(yahoo_url));
EXPECT_FALSE(IsNavigationBlocked(google_url));
// Add dynamic rules to block "google.com" and redirect pages on "example.com"
// to |dynamic_redirect_url|.
TestRule block_dynamic_rule = block_static_rule;
block_dynamic_rule.condition->url_filter = std::string("||google.com");
block_dynamic_rule.id = kMinValidID;
GURL dynamic_redirect_url =
embedded_test_server()->GetURL("dynamic.com", kUrlPath);
TestRule redirect_rule = CreateGenericRule();
redirect_rule.condition->url_filter = std::string("||example.com");
redirect_rule.condition->resource_types =
std::vector<std::string>({"main_frame"});
redirect_rule.priority = kMinValidPriority;
redirect_rule.action->type = std::string("redirect");
redirect_rule.action->redirect.emplace();
redirect_rule.action->redirect->url = dynamic_redirect_url.spec();
redirect_rule.id = kMinValidID + 1;
ASSERT_NO_FATAL_FAILURE(AddDynamicRules(last_loaded_extension_id(),
{block_dynamic_rule, redirect_rule}));
EXPECT_TRUE(IsNavigationBlocked(google_url));
EXPECT_TRUE(IsNavigationBlocked(yahoo_url));
// Navigate to a page on "example.com". It should be redirected to
// |dynamic_redirect_url|.
GURL example_url = embedded_test_server()->GetURL("example.com", kUrlPath);
NavigateToURL(example_url);
EXPECT_EQ(content::PAGE_TYPE_NORMAL, GetPageType());
EXPECT_TRUE(WasFrameWithScriptLoaded(GetPrimaryMainFrame()));
EXPECT_EQ(dynamic_redirect_url, web_contents()->GetLastCommittedURL());
// Now add a dynamic rule to allow requests to yahoo.com.
TestRule allow_rule = block_static_rule;
allow_rule.id = kMinValidID + 2;
allow_rule.action->type = std::string("allow");
ASSERT_NO_FATAL_FAILURE(
AddDynamicRules(last_loaded_extension_id(), {allow_rule}));
// Dynamic ruleset gets more priority over the static ruleset and yahoo.com is
// not blocked.
EXPECT_FALSE(IsNavigationBlocked(yahoo_url));
// Now remove the |block_rule| and |allow_rule|. Rule ids not present will be
// ignored.
ASSERT_NO_FATAL_FAILURE(RemoveDynamicRules(
last_loaded_extension_id(),
{*block_dynamic_rule.id, *allow_rule.id, kMinValidID + 100}));
EXPECT_FALSE(IsNavigationBlocked(google_url));
EXPECT_TRUE(IsNavigationBlocked(yahoo_url));
}
// Tests rules using the Redirect dictionary.
IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest, Redirect) {
TestRule rule1 = CreateGenericRule();
rule1.condition->resource_types = std::vector<std::string>({"main_frame"});
rule1.id = kMinValidID;
rule1.condition->url_filter = std::string("ex");
rule1.action->type = std::string("redirect");
rule1.priority = kMinValidPriority;
rule1.action->redirect.emplace();
rule1.action->redirect->url =
embedded_test_server()
->GetURL("google.com", "/pages_with_script/index.html")
.spec();
TestRule rule2 = CreateGenericRule();
rule2.condition->resource_types = std::vector<std::string>({"main_frame"});
rule2.id = kMinValidID + 1;
rule2.condition->url_filter = std::string("example.com");
rule2.action->type = std::string("redirect");
rule2.priority = kMinValidPriority + 1;
rule2.action->redirect.emplace();
rule2.action->redirect->extension_path = "/manifest.json?query#fragment";
TestRule rule3 = CreateGenericRule();
rule3.condition->resource_types = std::vector<std::string>({"main_frame"});
rule3.id = kMinValidID + 2;
rule3.condition->url_filter = std::string("||example.com");
rule3.action->type = std::string("redirect");
rule3.priority = kMinValidPriority + 2;
rule3.action->redirect.emplace();
rule3.action->redirect->transform.emplace();
auto& transform = rule3.action->redirect->transform;
transform->host = "new.host.com";
transform->path = "/pages_with_script/page.html";
transform->query = "?new_query";
transform->fragment = "#new_fragment";
TestRule rule4 = CreateGenericRule();
rule4.condition->resource_types = std::vector<std::string>({"main_frame"});
rule4.id = kMinValidID + 3;
rule4.condition->url_filter.reset();
rule4.condition->regex_filter = R"(^(.+?)://(abc|def)\.exy\.com(.*)$)";
rule4.action->type = std::string("redirect");
rule4.priority = kMinValidPriority + 1;
rule4.action->redirect.emplace();
rule4.action->redirect->regex_substitution = R"(\1://www.\2.com\3)";
ASSERT_NO_FATAL_FAILURE(
LoadExtensionWithRules({rule1, rule2, rule3, rule4}, "test_extension",
{URLPattern::kAllUrlsPattern}));
struct {
GURL url;
GURL expected_url;
} cases[] = {{embedded_test_server()->GetURL("example.com",
"/pages_with_script/index.html"),
// Because of higher priority, the transform rule is chosen.
embedded_test_server()->GetURL(
"new.host.com",
"/pages_with_script/page.html?new_query#new_fragment")},
// Because of higher priority, the extensionPath rule is chosen.
{embedded_test_server()->GetURL(
"xyz.com", "/pages_with_script/index.html?example.com"),
GURL("chrome-extension://" + last_loaded_extension_id() +
"/manifest.json?query#fragment")},
{embedded_test_server()->GetURL("ex.com",
"/pages_with_script/index.html"),
embedded_test_server()->GetURL(
"google.com", "/pages_with_script/index.html")},
// Because of a priority higher than |rule1|, |rule4| is chosen.
{embedded_test_server()->GetURL("abc.exy.com",
"/pages_with_script/page.html"),
embedded_test_server()->GetURL("www.abc.com",
"/pages_with_script/page.html")},
{embedded_test_server()->GetURL("xyz.exy.com",
"/pages_with_script/page.html"),
embedded_test_server()->GetURL(
"google.com", "/pages_with_script/index.html")}};
for (const auto& test_case : cases) {
SCOPED_TRACE("Testing " + test_case.url.spec());
NavigateToURL(test_case.url);
EXPECT_EQ(test_case.expected_url, web_contents()->GetLastCommittedURL());
}
}
#if !BUILDFLAG(IS_ANDROID)
// Test that the badge text for an extension will update to reflect the number
// of actions taken on requests matching the extension's ruleset.
// TODO(crbug.com/371298229): Port to desktop Android when extension badges are
// supported.
IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest,
ActionsMatchedCountAsBadgeText) {
// Load the extension with a background script so scripts can be run from its
// generated background page. Also grant the feedback permission for the
// extension so it has access to the getMatchedRules API function.
set_config_flags(ConfigFlag::kConfig_HasBackgroundScript |
ConfigFlag::kConfig_HasFeedbackPermission);
auto get_url_for_host = [this](std::string hostname) {
return embedded_test_server()->GetURL(hostname,
"/pages_with_script/index.html");
};
// This page simulates a user clicking on a link, so that the next page it
// navigates to has a Referrer header.
auto get_url_with_referrer = [this](std::string hostname) {
return embedded_test_server()->GetURL(hostname, "/simulate_click.html");
};
const std::string kFrameName1 = "frame1";
const GURL page_url = embedded_test_server()->GetURL(
"norulesmatched.com", "/page_with_two_frames.html");
struct {
std::string url_filter;
int id;
int priority;
std::string action_type;
std::optional<std::string> redirect_url;
std::optional<std::vector<TestHeaderInfo>> request_headers;
} rules_data[] = {
{"abc.com", 1, 1, "block", std::nullopt, std::nullopt},
{"def.com", 2, 1, "redirect", "http://zzz.com", std::nullopt},
{"jkl.com", 3, 1, "modifyHeaders", std::nullopt,
std::vector<TestHeaderInfo>(
{TestHeaderInfo("referer", "remove", std::nullopt)})},
{"abcd.com", 4, 1, "block", std::nullopt, std::nullopt},
{"abcd", 5, 1, "allow", std::nullopt, std::nullopt},
};
// Load the extension.
std::vector<TestRule> rules;
for (const auto& rule_data : rules_data) {
TestRule rule = CreateGenericRule();
rule.condition->url_filter = rule_data.url_filter;
rule.id = rule_data.id;
rule.priority = rule_data.priority;
rule.condition->resource_types =
std::vector<std::string>({"main_frame", "sub_frame"});
rule.action->type = rule_data.action_type;
rule.action->redirect.emplace();
rule.action->redirect->url = rule_data.redirect_url;
rule.action->request_headers = rule_data.request_headers;
rules.push_back(rule);
}
ASSERT_NO_FATAL_FAILURE(LoadExtensionWithRules(
rules, "test_extension", {URLPattern::kAllUrlsPattern}));
const ExtensionId& extension_id = last_loaded_extension_id();
const Extension* dnr_extension = last_loaded_extension();
PrefsHelper helper(*ExtensionPrefs::Get(profile()));
helper.SetUseActionCountAsBadgeText(extension_id, true);
ExtensionAction* action =
ExtensionActionManager::Get(web_contents()->GetBrowserContext())
->GetExtensionAction(*dnr_extension);
struct {
std::string frame_hostname;
std::string expected_badge_text;
bool has_referrer_header;
} test_cases[] = {
// zzz.com does not match any rules, so no badge text should be displayed.
{"zzz.com", "", false},
// abc.com is blocked by a matching rule and should increment the badge
// text.
{"abc.com", "1", false},
// def.com is redirected by a matching rule and should increment the badge
// text.
{"def.com", "2", false},
// jkl.com matches with a modifyHeaders rule which removes the referer
// header, but has no headers. Therefore no action is taken and the badge
// text stays the same.
{"jkl.com", "2", false},
// jkl.com matches with a modifyHeaders rule and has a referer header.
// Therefore the badge text should be incremented.
{"jkl.com", "3", true},
// abcd.com matches both a block rule and an allow rule. Since the allow
// rule overrides the block rule, no action is taken and the badge text
// stays the same,
{"abcd.com", "3", false},
};
ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), page_url));
ASSERT_TRUE(WasFrameWithScriptLoaded(GetPrimaryMainFrame()));
// Verify that the badge text is empty when navigation finishes because no
// actions have been matched.
int first_tab_id = ExtensionTabUtil::GetTabId(web_contents());
EXPECT_EQ("", action->GetDisplayBadgeText(first_tab_id));
for (const auto& test_case : test_cases) {
GURL url = test_case.has_referrer_header
? get_url_with_referrer(test_case.frame_hostname)
: get_url_for_host(test_case.frame_hostname);
SCOPED_TRACE(base::StringPrintf("Testing %s", url.spec().c_str()));
NavigateFrame(kFrameName1, url, false /* use_frame_referrer */);
EXPECT_EQ(test_case.expected_badge_text,
action->GetDisplayBadgeText(first_tab_id));
}
std::string first_tab_badge_text = action->GetDisplayBadgeText(first_tab_id);
const GURL second_tab_url = get_url_for_host("nomatch.com");
ui_test_utils::NavigateToURLWithDisposition(
browser(), second_tab_url, WindowOpenDisposition::NEW_FOREGROUND_TAB,
ui_test_utils::BROWSER_TEST_WAIT_FOR_LOAD_STOP);
ASSERT_EQ(2, browser()->tab_strip_model()->count());
ASSERT_TRUE(browser()->tab_strip_model()->IsTabSelected(1));
int second_tab_id = ExtensionTabUtil::GetTabId(web_contents());
EXPECT_EQ("", action->GetDisplayBadgeText(second_tab_id));
// Verify that the badge text for the first tab is unaffected.
EXPECT_EQ(first_tab_badge_text, action->GetDisplayBadgeText(first_tab_id));
// Verify that the correct rules are returned via getMatchedRules. Returns "|"
// separated pairs of <rule_id>,<ruleset_id>, sorted by rule ids, e.g.
// "ruleId1,rulesetId1|ruleId2,rulesetId2".
auto get_matched_rules = [this](int tab_id) {
static constexpr char kGetMatchedRulesScript[] = R"(
chrome.declarativeNetRequest.getMatchedRules({tabId: %d}, (matches) => {
// Sort by |ruleId|.
matches.rulesMatchedInfo.sort((a, b) => a.rule.ruleId - b.rule.ruleId);
var ruleAndRulesetIDs = matches.rulesMatchedInfo.map(
match => [match.rule.ruleId, match.rule.rulesetId].join());
chrome.test.sendScriptResult(ruleAndRulesetIDs.join('|'));
});
)";
return ExecuteScriptInBackgroundPageAndReturnString(
last_loaded_extension_id(),
base::StringPrintf(kGetMatchedRulesScript, tab_id),
browsertest_util::ScriptUserActivation::kDontActivate);
};
DeclarativeNetRequestGetMatchedRulesFunction::
set_disable_throttling_for_tests(true);
// Four rules should be matched on the tab with |first_tab_id|:
// - the block rule for abc.com (ruleId = 1)
// - the redirect rule for def.com (ruleId = 2)
// - the modifyHeaders rule for jkl.com (ruleId = 3)
// - the allow rule for abcd.com (ruleId = 5)
EXPECT_EQ(base::StringPrintf("1,%s|2,%s|3,%s|5,%s", kDefaultRulesetID,
kDefaultRulesetID, kDefaultRulesetID,
kDefaultRulesetID),
get_matched_rules(first_tab_id));
// No rule should be matched on the tab with |second_tab_id|.
EXPECT_EQ("", get_matched_rules(second_tab_id));
}
#endif // !BUILDFLAG(IS_ANDROID)
// Ensure web request events are still dispatched even if DNR blocks/redirects
// the request. (Regression test for crbug.com/999744).
IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest, WebRequestEvents) {
// Load the extension with a background script so scripts can be run from its
// generated background page.
set_config_flags(ConfigFlag::kConfig_HasBackgroundScript);
TestRule rule = CreateGenericRule();
rule.condition->url_filter = "||example.com";
rule.condition->resource_types = std::vector<std::string>({"main_frame"});
ASSERT_NO_FATAL_FAILURE(LoadExtensionWithRules(
{rule}, "test_extension", {URLPattern::kAllUrlsPattern}));
GURL url = embedded_test_server()->GetURL("example.com",
"/pages_with_script/index.html");
// Set up web request listeners listening to request to |url|.
static constexpr char kWebRequestListenerScript[] = R"(
let filter = {'urls' : ['%s'], 'types' : ['main_frame']};
let onBeforeRequestSeen = false;
chrome.webRequest.onBeforeRequest.addListener(() => {
onBeforeRequestSeen = true;
}, filter);
// The request will fail since it will be blocked by DNR.
chrome.webRequest.onErrorOccurred.addListener(() => {
if (onBeforeRequestSeen)
chrome.test.sendMessage('PASS');
}, filter);
chrome.test.sendMessage('INSTALLED');
)";
ExtensionTestMessageListener pass_listener("PASS");
ExtensionTestMessageListener installed_listener("INSTALLED");
ExecuteScriptInBackgroundPageNoWait(
last_loaded_extension_id(),
base::StringPrintf(kWebRequestListenerScript, url.spec().c_str()));
// Wait for the web request listeners to be installed before navigating.
ASSERT_TRUE(installed_listener.WaitUntilSatisfied());
NavigateToURL(url);
ASSERT_FALSE(WasFrameWithScriptLoaded(GetPrimaryMainFrame()));
EXPECT_TRUE(pass_listener.WaitUntilSatisfied());
}
// Ensure Declarative Net Request gets priority over the web request API.
IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest, WebRequestPriority) {
// Load the extension with a background script so scripts can be run from its
// generated background page.
set_config_flags(ConfigFlag::kConfig_HasBackgroundScript);
GURL url = embedded_test_server()->GetURL("example.com",
"/pages_with_script/index.html");
GURL redirect_url = embedded_test_server()->GetURL(
"redirect.com", "/pages_with_script/index.html");
TestRule example_com_redirect_rule = CreateGenericRule();
example_com_redirect_rule.condition->url_filter = "||example.com";
example_com_redirect_rule.condition->resource_types =
std::vector<std::string>({"main_frame"});
example_com_redirect_rule.action->type = std::string("redirect");
example_com_redirect_rule.action->redirect.emplace();
example_com_redirect_rule.action->redirect->url = redirect_url.spec();
example_com_redirect_rule.priority = kMinValidPriority;
ASSERT_NO_FATAL_FAILURE(
LoadExtensionWithRules({example_com_redirect_rule}, "test_extension",
{URLPattern::kAllUrlsPattern}));
// Set up a web request listener to block the request to example.com.
static constexpr char kWebRequestBlockScript[] = R"(
let filter = {'urls' : ['%s'], 'types' : ['main_frame']};
chrome.webRequest.onBeforeRequest.addListener((details) => {
chrome.test.sendMessage('SEEN')
}, filter, ['blocking']);
chrome.test.sendMessage('INSTALLED');
)";
ExtensionTestMessageListener seen_listener("SEEN");
ExtensionTestMessageListener installed_listener("INSTALLED");
ExecuteScriptInBackgroundPageNoWait(
last_loaded_extension_id(),
base::StringPrintf(kWebRequestBlockScript, url.spec().c_str()));
// Wait for the web request listeners to be installed before navigating.
ASSERT_TRUE(installed_listener.WaitUntilSatisfied());
NavigateToURL(url);
// Ensure the response from the web request listener was ignored and the
// request was redirected.
ASSERT_TRUE(WasFrameWithScriptLoaded(GetPrimaryMainFrame()));
EXPECT_EQ(web_contents()->GetLastCommittedURL(), redirect_url);
// Ensure onBeforeRequest is seen by the web request extension.
EXPECT_TRUE(seen_listener.WaitUntilSatisfied());
}
#if !BUILDFLAG(IS_ANDROID)
// Tests filtering based on the tab ID of the request.
// TODO(crbug.com/371298229): Port to desktop Android when we have better
// support for the tab strip (e.g. ActivateTabAt()).
IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest, TabIdFiltering) {
set_config_flags(ConfigFlag::kConfig_HasBackgroundScript);
constexpr char kUrlPath[] = "/pages_with_script/index.html";
GURL url = embedded_test_server()->GetURL("example.com", kUrlPath);
// Open three tabs to `url`.
ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), url));
int first_tab_id = ExtensionTabUtil::GetTabId(web_contents());
ui_test_utils::NavigateToURLWithDisposition(
browser(), url, WindowOpenDisposition::NEW_FOREGROUND_TAB,
ui_test_utils::BROWSER_TEST_WAIT_FOR_LOAD_STOP);
int second_tab_id = ExtensionTabUtil::GetTabId(web_contents());
ASSERT_NE(first_tab_id, second_tab_id);
ui_test_utils::NavigateToURLWithDisposition(
browser(), url, WindowOpenDisposition::NEW_FOREGROUND_TAB,
ui_test_utils::BROWSER_TEST_WAIT_FOR_LOAD_STOP);
TabStripModel* tab_strip_model = browser()->tab_strip_model();
ASSERT_EQ(3, tab_strip_model->count());
int third_tab_id = ExtensionTabUtil::GetTabId(web_contents());
ASSERT_NE(first_tab_id, third_tab_id);
int rule_id = kMinValidID;
constexpr char kHost[] = "foo.com";
auto create_redirect_rule = [&kHost](int id,
const std::string& redirect_host) {
TestRule rule = CreateGenericRule(id);
rule.action->type = "redirect";
rule.action->redirect.emplace();
rule.action->redirect->transform.emplace();
rule.action->redirect->transform->host = redirect_host;
rule.condition->resource_types =
std::vector<std::string>({"main_frame", "xmlhttprequest"});
rule.condition->url_filter = kHost;
return rule;
};
// Add a rule which redirects hosts on all requests on the `first_tab_id` to
// "rule1.com".
TestRule rule1 = create_redirect_rule(rule_id++, "rule1.com");
rule1.condition->tab_ids = std::vector<int>({first_tab_id});
// Add a rule which redirects hosts on all non-tab specific requests to
// "rule2.com".
TestRule rule2 = create_redirect_rule(rule_id++, "rule2.com");
rule2.condition->tab_ids = std::vector<int>({-1});
// Add a regex rule which redirects hosts on all requests (except those from
// the excluded tabs below) to "rule3.com".
TestRule rule3 = create_redirect_rule(rule_id++, "rule3.com");
rule3.condition->excluded_tab_ids =
std::vector<int>({first_tab_id, second_tab_id, -1});
rule3.condition->url_filter = std::nullopt;
rule3.condition->regex_filter = std::string(kHost);
ASSERT_NO_FATAL_FAILURE(LoadExtensionWithRules(
{}, "test_extension", {URLPattern::kAllUrlsPattern}));
ASSERT_NO_FATAL_FAILURE(UpdateSessionRules(last_loaded_extension_id(), {},
{rule1, rule2, rule3}));
constexpr char kFetchTemplate[] = R"(
(async function func() {
let url = '%s';
const response = await fetch(url);
return response.ok ? response.url : 'bad response';
})();
)";
constexpr char kFetchPath[] = "/subresources/xhr_target.txt";
GURL fetch_url = embedded_test_server()->GetURL(kHost, kFetchPath);
std::string script =
base::StringPrintf(kFetchTemplate, fetch_url.spec().c_str());
GURL new_url = embedded_test_server()->GetURL(kHost, kUrlPath);
struct Cases {
int expected_tab_id;
std::string expected_host;
};
auto cases = std::to_array<Cases>({
{first_tab_id, "rule1.com"},
{second_tab_id, kHost},
{third_tab_id, "rule3.com"},
});
for (size_t i = 0; i < std::size(cases); i++) {
SCOPED_TRACE(base::StringPrintf("Testing case %zu", i));
// Navigate the i'th tab to `new_url`.
tab_strip_model->ActivateTabAt(static_cast<int>(i));
EXPECT_EQ(cases[i].expected_tab_id,
ExtensionTabUtil::GetTabId(web_contents()));
// Verify tab ID filtering works on a main-frame request.
ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), new_url));
EXPECT_EQ(embedded_test_server()->GetURL(cases[i].expected_host, kUrlPath),
web_contents()->GetLastCommittedURL());
// Verify tab ID filtering works on a subresource request.
EXPECT_EQ(
embedded_test_server()->GetURL(cases[i].expected_host, kFetchPath),
content::EvalJs(web_contents(), script));
}
// Test matching against requests which don't originate from a tab (tab ID of
// -1) by performing a fetch from a shared worker.
ASSERT_TRUE(ui_test_utils::NavigateToURL(
browser(),
embedded_test_server()->GetURL(kHost, "/fetch_from_shared_worker.html")));
// This navigation should have matched the third rule.
ASSERT_EQ(embedded_test_server()->GetURL("rule3.com",
"/fetch_from_shared_worker.html"),
web_contents()->GetLastCommittedURL());
EXPECT_EQ(embedded_test_server()->GetURL("rule2.com", kFetchPath),
content::EvalJs(web_contents(),
base::StringPrintf("fetchFromSharedWorker('%s');",
fetch_url.spec().c_str())));
}
// Test that the extension cannot retrieve the number of actions matched
// from the badge text by calling chrome.browserAction.getBadgeText, unless
// it has the declarativeNetRequestFeedback permission or activeTab is granted
// for the tab. Not supported on Android because Android only supports manifest
// V3, which does not support chrome.browserAction.
IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest,
GetBadgeTextForActionsMatched) {
auto query_badge_text = [this](const ExtensionId& extension_id, int tab_id) {
static constexpr char kBadgeTextQueryScript[] = R"(
chrome.browserAction.getBadgeText({tabId: %d}, badgeText => {
chrome.test.sendScriptResult(badgeText);
});
)";
return ExecuteScriptInBackgroundPageAndReturnString(
extension_id, base::StringPrintf(kBadgeTextQueryScript, tab_id));
};
TestRule rule = CreateGenericRule();
rule.condition->url_filter = "def.com";
rule.id = kMinValidID;
rule.condition->resource_types = std::vector<std::string>({"sub_frame"});
rule.action->type = "block";
set_config_flags(ConfigFlag::kConfig_HasBackgroundScript |
ConfigFlag::kConfig_HasActiveTab);
// Create the first extension.
ASSERT_NO_FATAL_FAILURE(LoadExtensionWithRules(
{rule}, "test_extension", {URLPattern::kAllUrlsPattern}));
const Extension* extension_1 = last_loaded_extension();
ExtensionAction* action_1 =
ExtensionActionManager::Get(web_contents()->GetBrowserContext())
->GetExtensionAction(*extension_1);
TestRule rule_2 = CreateGenericRule();
rule_2.condition->url_filter = "ghi.com";
rule_2.id = kMinValidID;
rule_2.condition->resource_types = std::vector<std::string>({"sub_frame"});
rule_2.action->type = "block";
set_config_flags(ConfigFlag::kConfig_HasBackgroundScript |
ConfigFlag::kConfig_HasFeedbackPermission);
// Create the second extension with the feedback permission.
ASSERT_NO_FATAL_FAILURE(LoadExtensionWithRules(
{rule_2}, "test_extension_2", {URLPattern::kAllUrlsPattern}));
const Extension* extension_2 = last_loaded_extension();
ExtensionAction* action_2 =
ExtensionActionManager::Get(web_contents()->GetBrowserContext())
->GetExtensionAction(*extension_2);
const std::string default_badge_text = "asdf";
action_1->SetBadgeText(ExtensionAction::kDefaultTabId, default_badge_text);
action_2->SetBadgeText(ExtensionAction::kDefaultTabId, default_badge_text);
// Navigate to a page with two frames, no requests should be blocked
// initially.
const GURL page_url =
embedded_test_server()->GetURL("abc.com", "/page_with_two_frames.html");
ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), page_url));
ActiveTabPermissionGranter* active_tab_granter =
ActiveTabPermissionGranter::FromWebContents(web_contents());
ASSERT_TRUE(active_tab_granter);
// The preference is initially turned off. Both the visible badge text and the
// badge text queried by the extension using getBadgeText() should return the
// default badge text.
int first_tab_id = ExtensionTabUtil::GetTabId(web_contents());
EXPECT_EQ(default_badge_text, action_1->GetDisplayBadgeText(first_tab_id));
EXPECT_EQ(default_badge_text, action_2->GetDisplayBadgeText(first_tab_id));
EXPECT_EQ(default_badge_text,
query_badge_text(extension_1->id(), first_tab_id));
EXPECT_EQ(default_badge_text,
query_badge_text(extension_2->id(), first_tab_id));
EXPECT_EQ(SetExtensionActionOptions(extension_1->id(),
"{displayActionCountAsBadgeText: true}"),
"success");
EXPECT_EQ(SetExtensionActionOptions(extension_2->id(),
"{displayActionCountAsBadgeText: true}"),
"success");
// After enabling the preference the visible badge text should remain as the
// default initially, as the action count for the tab is still 0 for both
// extensions.
EXPECT_EQ(default_badge_text, action_1->GetDisplayBadgeText(first_tab_id));
EXPECT_EQ(default_badge_text, action_2->GetDisplayBadgeText(first_tab_id));
// Since the preference is on for the current tab, attempting to query the
// badge text should return the placeholder text instead of the matched action
// count for |extension_1|.
EXPECT_EQ(declarative_net_request::kActionCountPlaceholderBadgeText,
query_badge_text(extension_1->id(), first_tab_id));
// The placeholder should not be returned if the declarativeNetRequestFeedback
// permission is enabled.
EXPECT_EQ(default_badge_text,
query_badge_text(extension_2->id(), first_tab_id));
// |extension_1| should block this frame navigation.
NavigateFrame("frame1", embedded_test_server()->GetURL("def.com", "/"));
// |extension_2| should block this frame navigation.
NavigateFrame("frame2", embedded_test_server()->GetURL("ghi.com", "/"));
// One action was matched, and this should be reflected in the badge text.
EXPECT_EQ("1", action_1->GetDisplayBadgeText(first_tab_id));
EXPECT_EQ("1", action_2->GetDisplayBadgeText(first_tab_id));
// The placeholder should still be returned for the first extension, but the
// second extension with permission should now return the action count.
EXPECT_EQ(declarative_net_request::kActionCountPlaceholderBadgeText,
query_badge_text(extension_1->id(), first_tab_id));
EXPECT_EQ("1", query_badge_text(extension_2->id(), first_tab_id));
// Tab-specific badge text should take priority over the action count and
// placeholder text.
action_1->SetBadgeText(first_tab_id, "text_1");
action_2->SetBadgeText(first_tab_id, "text_2");
EXPECT_EQ("text_1", query_badge_text(extension_1->id(), first_tab_id));
EXPECT_EQ("text_2", query_badge_text(extension_2->id(), first_tab_id));
action_1->ClearBadgeText(first_tab_id);
action_2->ClearBadgeText(first_tab_id);
// Querying the badge text with the activeTab access for the current tab
// should provide the matched action count.
active_tab_granter->GrantIfRequested(extension_1);
EXPECT_EQ("1", query_badge_text(extension_1->id(), first_tab_id));
// Revoking activeTab should cause the placeholder text to be returned again
// since we don't have the declarativeNetRequestFeedback permission.
active_tab_granter->RevokeForTesting();
EXPECT_EQ(declarative_net_request::kActionCountPlaceholderBadgeText,
query_badge_text(extension_1->id(), first_tab_id));
EXPECT_EQ(SetExtensionActionOptions(extension_1->id(),
"{displayActionCountAsBadgeText: false}"),
"success");
EXPECT_EQ(SetExtensionActionOptions(extension_2->id(),
"{displayActionCountAsBadgeText: false}"),
"success");
// Switching the preference off should cause the extension queried badge text
// to be the explicitly set badge text for this tab if it exists. In this
// case, the queried badge text should be the default badge text.
EXPECT_EQ(default_badge_text,
query_badge_text(extension_1->id(), first_tab_id));
EXPECT_EQ(default_badge_text,
query_badge_text(extension_2->id(), first_tab_id));
// The displayed badge text should be the default badge text now that the
// preference is off.
EXPECT_EQ(default_badge_text, action_1->GetDisplayBadgeText(first_tab_id));
EXPECT_EQ(default_badge_text, action_2->GetDisplayBadgeText(first_tab_id));
// Verify that turning off the preference deletes the DNR action count within
// the extension action.
EXPECT_FALSE(action_1->HasDNRActionCount(first_tab_id));
EXPECT_FALSE(action_2->HasDNRActionCount(first_tab_id));
}
// Test that enabling the "displayActionCountAsBadgeText" preference using
// setExtensionActionOptions will update all browsers sharing the same browser
// context.
// TODO(crbug.com/393172599): Port to desktop Android when we support multiple
// windows in browser tests.
IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest,
ActionCountPreferenceMultipleWindows) {
// Load the extension with a background script so scripts can be run from its
// generated background page.
set_config_flags(ConfigFlag::kConfig_HasBackgroundScript);
TestRule rule = CreateGenericRule();
rule.condition->url_filter = "abc.com";
rule.id = kMinValidID;
rule.condition->resource_types = std::vector<std::string>({"main_frame"});
rule.action->type = "block";
std::vector<TestRule> rules({rule});
ASSERT_NO_FATAL_FAILURE(LoadExtensionWithRules(
{rules}, "test_extension", {URLPattern::kAllUrlsPattern}));
const ExtensionId& extension_id = last_loaded_extension_id();
const Extension* dnr_extension = last_loaded_extension();
ExtensionAction* extension_action =
ExtensionActionManager::Get(web_contents()->GetBrowserContext())
->GetExtensionAction(*dnr_extension);
const GURL page_url = embedded_test_server()->GetURL(
"abc.com", "/pages_with_script/index.html");
ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), page_url));
int first_browser_tab_id = ExtensionTabUtil::GetTabId(web_contents());
EXPECT_EQ("", extension_action->GetDisplayBadgeText(first_browser_tab_id));
// Now create a new browser with the same profile as |browser()| and navigate
// to |page_url|.
Browser* second_browser = CreateBrowser(profile());
ASSERT_TRUE(ui_test_utils::NavigateToURL(second_browser, page_url));
content::WebContents* second_browser_contents =
second_browser->tab_strip_model()->GetActiveWebContents();
int second_browser_tab_id =
ExtensionTabUtil::GetTabId(second_browser_contents);
EXPECT_EQ("", extension_action->GetDisplayBadgeText(second_browser_tab_id));
// Set up an observer to listen for ExtensionAction updates for the active web
// contents of both browser windows.
TestExtensionActionDispatcherObserver test_dispatcher_observer(
profile(), extension_id, {web_contents(), second_browser_contents});
EXPECT_EQ(SetExtensionActionOptions(extension_id,
"{displayActionCountAsBadgeText: true}"),
"success");
// Wait until ExtensionActionDispatcher::NotifyChange is called, then perform
// a sanity check that one action was matched, and this is reflected in the
// badge text.
test_dispatcher_observer.Wait();
EXPECT_EQ("1", extension_action->GetDisplayBadgeText(first_browser_tab_id));
// The badge text for the second browser window should also update to the
// matched action count because the second browser shares the same browser
// context as the first.
EXPECT_EQ("1", extension_action->GetDisplayBadgeText(second_browser_tab_id));
}
// Test that the action matched badge text for an extension is visible in an
// incognito context if the extension is incognito enabled.
// Test is disabled on Mac. See https://crbug.com/1280116
// TODO(crbug.com/393179880): Port to desktop Android when we support browser
// actions and badging.
#if BUILDFLAG(IS_MAC)
#define MAYBE_ActionsMatchedCountAsBadgeTextIncognito \
DISABLED_ActionsMatchedCountAsBadgeTextIncognito
#else
#define MAYBE_ActionsMatchedCountAsBadgeTextIncognito \
ActionsMatchedCountAsBadgeTextIncognito
#endif
IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest,
MAYBE_ActionsMatchedCountAsBadgeTextIncognito) {
TestRule rule = CreateGenericRule();
rule.condition->url_filter = "abc.com";
rule.id = kMinValidID;
rule.condition->resource_types = std::vector<std::string>({"main_frame"});
rule.action->type = "block";
std::vector<TestRule> rules({rule});
ASSERT_NO_FATAL_FAILURE(LoadExtensionWithRules(
{rules}, "test_extension", {URLPattern::kAllUrlsPattern}));
const ExtensionId& extension_id = last_loaded_extension_id();
util::SetIsIncognitoEnabled(extension_id, profile(), true /*enabled*/);
PrefsHelper helper(*ExtensionPrefs::Get(profile()));
helper.SetUseActionCountAsBadgeText(extension_id, true);
Browser* incognito_browser = CreateIncognitoBrowser();
ASSERT_TRUE(
ui_test_utils::NavigateToURL(incognito_browser, GURL("http://abc.com")));
content::WebContents* incognito_contents =
incognito_browser->tab_strip_model()->GetActiveWebContents();
const Extension* dnr_extension = last_loaded_extension();
ExtensionAction* incognito_action =
ExtensionActionManager::Get(incognito_contents->GetBrowserContext())
->GetExtensionAction(*dnr_extension);
EXPECT_EQ("1", incognito_action->GetDisplayBadgeText(
ExtensionTabUtil::GetTabId(incognito_contents)));
}
// Test that the actions matched badge text for an extension will be reset
// when a main-frame navigation finishes.
// TODO(crbug.com/393179880): Port to desktop Android when we support browser
// actions and badging.
IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest,
// TODO(crbug.com/40843749): Re-enable this test
DISABLED_ActionsMatchedCountAsBadgeTextMainFrame) {
auto get_url_for_host = [this](std::string hostname) {
return embedded_test_server()->GetURL(hostname,
"/pages_with_script/index.html");
};
auto get_set_cookie_url = [this](std::string hostname) {
return embedded_test_server()->GetURL(hostname, "/set-cookie?a=b");
};
struct {
std::string url_filter;
int id;
int priority;
std::string action_type;
std::vector<std::string> resource_types;
std::optional<std::string> redirect_url;
std::optional<std::vector<TestHeaderInfo>> response_headers;
} rules_data[] = {
{"abc.com", 1, 1, "block", std::vector<std::string>({"script"}),
std::nullopt, std::nullopt},
{"||def.com", 2, 1, "redirect", std::vector<std::string>({"main_frame"}),
get_url_for_host("abc.com").spec(), std::nullopt},
{"gotodef.com", 3, 1, "redirect",
std::vector<std::string>({"main_frame"}),
get_url_for_host("def.com").spec(), std::nullopt},
{"ghi.com", 4, 1, "block", std::vector<std::string>({"main_frame"}),
std::nullopt, std::nullopt},
{"gotosetcookie.com", 5, 1, "redirect",
std::vector<std::string>({"main_frame"}),
get_set_cookie_url("setcookie.com").spec(), std::nullopt},
{"setcookie.com", 6, 1, "modifyHeaders",
std::vector<std::string>({"main_frame"}), std::nullopt,
std::vector<TestHeaderInfo>(
{TestHeaderInfo("set-cookie", "remove", std::nullopt)})},
};
// Load the extension.
std::vector<TestRule> rules;
for (const auto& rule_data : rules_data) {
TestRule rule = CreateGenericRule();
rule.condition->url_filter = rule_data.url_filter;
rule.id = rule_data.id;
rule.priority = rule_data.priority;
rule.condition->resource_types = rule_data.resource_types;
rule.action->type = rule_data.action_type;
rule.action->redirect.emplace();
rule.action->redirect->url = rule_data.redirect_url;
rule.action->response_headers = rule_data.response_headers;
rules.push_back(rule);
}
ASSERT_NO_FATAL_FAILURE(LoadExtensionWithRules(
rules, "test_extension", {URLPattern::kAllUrlsPattern}));
const Extension* dnr_extension = last_loaded_extension();
PrefsHelper helper(*ExtensionPrefs::Get(profile()));
helper.SetUseActionCountAsBadgeText(last_loaded_extension_id(), true);
ExtensionAction* action =
ExtensionActionManager::Get(web_contents()->GetBrowserContext())
->GetExtensionAction(*dnr_extension);
struct {
std::string frame_hostname;
std::string expected_badge_text;
} test_cases[] = {
// The request to ghi.com should be blocked, so the badge text should be 1
// once navigation finishes.
{"ghi.com", "1"},
// The script on get_url_for_host("abc.com") matches with a rule and
// should increment the badge text.
{"abc.com", "1"},
// No rules match, so there should be no badge text once navigation
// finishes.
{"nomatch.com", ""},
// The request to def.com will redirect to get_url_for_host("abc.com") and
// the script on abc.com should match with a rule.
{"def.com", "2"},
// Same as the above test, except with an additional redirect from
// gotodef.com to def.com caused by a rule match. Therefore the badge text
// should be 3.
{"gotodef.com", "3"},
// The request to gotosetcookie.com will match with a rule and redirect to
// setcookie.com. The Set-Cookie header on setcookie.com will also match
// with a rule and get removed. Therefore the badge text should be 2.
{"gotosetcookie.com", "2"},
};
int first_tab_id = ExtensionTabUtil::GetTabId(web_contents());
for (const auto& test_case : test_cases) {
GURL url = get_url_for_host(test_case.frame_hostname);
SCOPED_TRACE(base::StringPrintf("Testing %s", url.spec().c_str()));
ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), url));
EXPECT_EQ(test_case.expected_badge_text,
action->GetDisplayBadgeText(first_tab_id));
}
}
// TODO(crbug.com/393179880): Port to desktop Android when we support browser
// actions and badging.
IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest,
ModifyHeadersBadgeText) {
auto get_referer_url = [this](const std::string& host) {
return embedded_test_server()->GetURL(host, "/set-header?referer: none");
};
auto get_set_cookie_url = [this](const std::string& host) {
return embedded_test_server()->GetURL(host, "/set-cookie?a=b");
};
auto get_no_headers_url = [this](const std::string& host) {
return embedded_test_server()->GetURL(host,
"/pages_with_script/index.html");
};
const std::string kFrameName1 = "frame1";
const GURL page_url = embedded_test_server()->GetURL(
"nomatch.com", "/page_with_two_frames.html");
// Create an extension with rules and get the ExtensionAction for it.
TestRule example_set_cookie_rule = CreateModifyHeadersRule(
kMinValidID, kMinValidPriority, "example.com", std::nullopt,
std::vector<TestHeaderInfo>(
{TestHeaderInfo("set-cookie", "remove", std::nullopt)}));
TestRule both_headers_rule = CreateModifyHeadersRule(
kMinValidID + 1, kMinValidPriority, "google.com",
std::vector<TestHeaderInfo>(
{TestHeaderInfo("referer", "remove", std::nullopt)}),
std::vector<TestHeaderInfo>(
{TestHeaderInfo("set-cookie", "remove", std::nullopt)}));
TestRule abc_set_cookie_rule = CreateModifyHeadersRule(
kMinValidID + 2, kMinValidPriority, "abc.com", std::nullopt,
std::vector<TestHeaderInfo>(
{TestHeaderInfo("set-cookie", "remove", std::nullopt)}));
TestRule abc_referer_rule = CreateModifyHeadersRule(
kMinValidID + 3, kMinValidPriority, "abc.com",
std::vector<TestHeaderInfo>(
{TestHeaderInfo("referer", "remove", std::nullopt)}),
std::nullopt);
TestRule ext1_set_custom_request_header_rule = CreateModifyHeadersRule(
kMinValidID + 4, kMinValidPriority, "def.com",
std::vector<TestHeaderInfo>({TestHeaderInfo("header1", "set", "ext_1")}),
std::nullopt);
TestRule ext1_add_custom_response_header_rule = CreateModifyHeadersRule(
kMinValidID + 5, kMinValidPriority, "ghi.com", std::nullopt,
std::vector<TestHeaderInfo>(
{TestHeaderInfo("header2", "append", "ext_1")}));
ASSERT_NO_FATAL_FAILURE(LoadExtensionWithRules(
{example_set_cookie_rule, both_headers_rule, abc_set_cookie_rule,
abc_referer_rule, ext1_set_custom_request_header_rule,
ext1_add_custom_response_header_rule},
"extension_1", {URLPattern::kAllUrlsPattern}));
const ExtensionId& extension_1_id = last_loaded_extension_id();
PrefsHelper helper(*ExtensionPrefs::Get(profile()));
helper.SetUseActionCountAsBadgeText(extension_1_id, true);
ExtensionAction* extension_1_action =
ExtensionActionManager::Get(web_contents()->GetBrowserContext())
->GetExtensionAction(
*extension_registry()->enabled_extensions().GetByID(
extension_1_id));
// Create another extension which removes the referer header from example.com
// and get the ExtensionAction for it.
TestRule example_referer_rule = CreateModifyHeadersRule(
kMinValidID, kMinValidPriority, "example.com",
std::vector<TestHeaderInfo>(
{TestHeaderInfo("referer", "remove", std::nullopt)}),
std::nullopt);
TestRule ext2_set_custom_request_header_rule = CreateModifyHeadersRule(
kMinValidID + 4, kMinValidPriority, "def.com",
std::vector<TestHeaderInfo>({TestHeaderInfo("header1", "set", "ext_2")}),
std::nullopt);
TestRule ext2_add_custom_response_header_rule = CreateModifyHeadersRule(
kMinValidID + 5, kMinValidPriority, "ghi.com", std::nullopt,
std::vector<TestHeaderInfo>(
{TestHeaderInfo("header2", "append", "ext_2")}));
ASSERT_NO_FATAL_FAILURE(LoadExtensionWithRules(
{example_referer_rule, ext2_set_custom_request_header_rule,
ext2_add_custom_response_header_rule},
"extension_2", {URLPattern::kAllUrlsPattern}));
const ExtensionId& extension_2_id = last_loaded_extension_id();
helper.SetUseActionCountAsBadgeText(extension_2_id, true);
ExtensionAction* extension_2_action =
ExtensionActionManager::Get(web_contents()->GetBrowserContext())
->GetExtensionAction(
*extension_registry()->enabled_extensions().GetByID(
extension_2_id));
struct {
GURL url;
bool use_referrer;
std::string expected_ext_1_badge_text;
std::string expected_ext_2_badge_text;
} test_cases[] = {
// This request only has a Set-Cookie header. Only the badge text for the
// extension with a remove Set-Cookie header rule should be incremented.
{get_set_cookie_url("example.com"), false, "1", ""},
// This request only has a Referer header. Only the badge text for the
// extension with a remove Referer header rule should be incremented.
{get_referer_url("example.com"), true, "1", "1"},
// This request has both a Referer and a Set-Cookie header. The badge text
// for both extensions should be incremented.
{get_set_cookie_url("example.com"), true, "2", "2"},
// This request with a Referer and Set-Cookie header matches with one rule
// from |extension_1| and so the action count for |extension_1| should
// only increment by one,
{get_set_cookie_url("google.com"), true, "3", "2"},
// This request with a Referer and Set-Cookie header matches with two
// separate rules from |extension_1| and so the action count for
// |extension_1| should increment by two.
{get_set_cookie_url("abc.com"), true, "5", "2"},
// This request without headers matches rules to set the header1 request
// header from both extensions. Since |extension_2| was installed later
// than |extension_1|, only the rule from |extension_2| should take effect
// and so the action count for |extension_2| should increment by one.
{get_no_headers_url("def.com"), false, "5", "3"},
// This request without headers matches rules to append the header2
// response header from both extensions. Since each extension has a rule
// which has taken effect, the action count for both extensions should
// increment by one.
{get_no_headers_url("ghi.com"), false, "6", "4"},
};
ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), page_url));
ASSERT_TRUE(WasFrameWithScriptLoaded(GetPrimaryMainFrame()));
int first_tab_id = ExtensionTabUtil::GetTabId(web_contents());
EXPECT_EQ("", extension_1_action->GetDisplayBadgeText(first_tab_id));
EXPECT_EQ("", extension_2_action->GetDisplayBadgeText(first_tab_id));
for (const auto& test_case : test_cases) {
SCOPED_TRACE(base::StringPrintf("Testing URL: %s, using referrer: %s",
test_case.url.spec().c_str(),
base::ToString(test_case.use_referrer)));
NavigateFrame(kFrameName1, test_case.url, test_case.use_referrer);
EXPECT_EQ(test_case.expected_ext_1_badge_text,
extension_1_action->GetDisplayBadgeText(first_tab_id));
EXPECT_EQ(test_case.expected_ext_2_badge_text,
extension_2_action->GetDisplayBadgeText(first_tab_id));
}
}
// Test that the setExtensionActionOptions tabUpdate option works correctly.
// TODO(crbug.com/393179880): Port to desktop Android when we support browser
// actions and badging.
IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest,
ActionsMatchedCountAsBadgeTextTabUpdate) {
// Load the extension with a background script so scripts can be run from its
// generated background page.
set_config_flags(ConfigFlag::kConfig_HasBackgroundScript);
// Set up an extension with a blocking rule.
TestRule rule = CreateGenericRule();
rule.condition->url_filter = std::string("||abc.com");
rule.condition->resource_types = std::vector<std::string>({"sub_frame"});
ASSERT_NO_FATAL_FAILURE(LoadExtensionWithRules(
{rule}, "extension", {URLPattern::kAllUrlsPattern}));
const Extension* extension = last_loaded_extension();
ExtensionAction* action =
ExtensionActionManager::Get(web_contents()->GetBrowserContext())
->GetExtensionAction(*extension);
const std::string default_badge_text = "asdf";
action->SetBadgeText(ExtensionAction::kDefaultTabId, default_badge_text);
// Display action count as badge text for |extension|.
EXPECT_EQ(SetExtensionActionOptions(extension->id(),
"{displayActionCountAsBadgeText: true}"),
"success");
// Navigate to a page with two frames, the same-origin one should be blocked.
const GURL page_url =
embedded_test_server()->GetURL("abc.com", "/page_with_two_frames.html");
ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), page_url));
int tab_id = ExtensionTabUtil::GetTabId(web_contents());
// Verify that the initial badge text reflects that the same-origin frame was
// blocked.
EXPECT_EQ("1", action->GetDisplayBadgeText(tab_id));
// Increment the action count.
EXPECT_EQ(SetExtensionActionOptions(
extension->id(),
base::StringPrintf("{tabUpdate: {tabId: %d, increment: 10}}",
tab_id)),
"success");
EXPECT_EQ("11", action->GetDisplayBadgeText(tab_id));
// An increment of 0 is ignored.
EXPECT_EQ(
SetExtensionActionOptions(
extension->id(),
base::StringPrintf("{tabUpdate: {tabId: %d, increment: 0}}", tab_id)),
"success");
EXPECT_EQ("11", action->GetDisplayBadgeText(tab_id));
// If the tab doesn't exist an error should be shown.
EXPECT_EQ(
SetExtensionActionOptions(
extension->id(),
base::StringPrintf("{tabUpdate: {tabId: %d, increment: 10}}", 999)),
ErrorUtils::FormatErrorMessage(declarative_net_request::kTabNotFoundError,
"999"));
EXPECT_EQ("11", action->GetDisplayBadgeText(tab_id));
// The action count should continue to increment when an action is taken.
NavigateFrame("frame1", page_url);
EXPECT_EQ("12", action->GetDisplayBadgeText(tab_id));
// The action count can be decremented.
EXPECT_EQ(SetExtensionActionOptions(
extension->id(),
base::StringPrintf("{tabUpdate: {tabId: %d, increment: -5}}",
tab_id)),
"success");
EXPECT_EQ("7", action->GetDisplayBadgeText(tab_id));
// Check that the action count cannot be decremented below 0. We fallback to
// displaying the default badge text when the action count is 0.
EXPECT_EQ(SetExtensionActionOptions(
extension->id(),
base::StringPrintf("{tabUpdate: {tabId: %d, increment: -10}}",
tab_id)),
"success");
EXPECT_EQ(default_badge_text, action->GetDisplayBadgeText(tab_id));
EXPECT_EQ(SetExtensionActionOptions(
extension->id(),
base::StringPrintf("{tabUpdate: {tabId: %d, increment: -1}}",
tab_id)),
"success");
EXPECT_EQ(default_badge_text, action->GetDisplayBadgeText(tab_id));
EXPECT_EQ(
SetExtensionActionOptions(
extension->id(),
base::StringPrintf("{tabUpdate: {tabId: %d, increment: 3}}", tab_id)),
"success");
EXPECT_EQ("3", action->GetDisplayBadgeText(tab_id));
// The action count cannot be incremented if the display action as badge text
// feature is not enabled.
EXPECT_EQ(
SetExtensionActionOptions(
extension->id(),
base::StringPrintf("{displayActionCountAsBadgeText: false, "
"tabUpdate: {tabId: %d, increment: 10}}",
tab_id)),
declarative_net_request::kIncrementActionCountWithoutUseAsBadgeTextError);
EXPECT_EQ(default_badge_text, action->GetDisplayBadgeText(tab_id));
// Any increment to the action count should not be ignored if we're enabling
// the preference.
EXPECT_EQ(SetExtensionActionOptions(
extension->id(),
base::StringPrintf("{displayActionCountAsBadgeText: true, "
"tabUpdate: {tabId: %d, increment: 5}}",
tab_id)),
"success");
EXPECT_EQ("8", action->GetDisplayBadgeText(tab_id));
}
#endif // !BUILDFLAG(IS_ANDROID)
// Test that the onRuleMatchedDebug event is only available for unpacked
// extensions.
IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest,
OnRuleMatchedDebugAvailability) {
// Load the extension with a background script so scripts can be run from its
// generated background page. Also grant the feedback permission for the
// extension so it can have access to the onRuleMatchedDebug event when
// unpacked.
set_config_flags(ConfigFlag::kConfig_HasBackgroundScript |
ConfigFlag::kConfig_HasFeedbackPermission);
ASSERT_NO_FATAL_FAILURE(LoadExtensionWithRules(
{}, "test_extension", {URLPattern::kAllUrlsPattern}));
static constexpr char kGetOnRuleMatchedDebugScript[] = R"(
const hasEvent = !!chrome.declarativeNetRequest.onRuleMatchedDebug ?
'true' : 'false';
chrome.test.sendScriptResult(hasEvent);
)";
std::string actual_event_availability =
ExecuteScriptInBackgroundPageAndReturnString(
last_loaded_extension_id(), kGetOnRuleMatchedDebugScript);
std::string expected_event_availability =
base::ToString(GetLoadType() == ExtensionLoadType::UNPACKED);
ASSERT_EQ(expected_event_availability, actual_event_availability);
}
// Test that the onRuleMatchedDebug event returns the correct number of matched
// rules for a request which is matched with multiple rules.
IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest_Unpacked,
OnRuleMatchedDebugMultipleRules) {
// This is only tested for unpacked extensions since the onRuleMatchedDebug
// event is only available for unpacked extensions.
ASSERT_EQ(ExtensionLoadType::UNPACKED, GetLoadType());
// Load the extension with a background script so scripts can be run from its
// generated background page. Also grant the feedback permission for the
// extension so it has access to the onRuleMatchedDebug event.
set_config_flags(ConfigFlag::kConfig_HasBackgroundScript |
ConfigFlag::kConfig_HasFeedbackPermission);
const std::string kFrameName1 = "frame1";
const std::string sub_frame_host = "abc.com";
const GURL page_url = embedded_test_server()->GetURL(
"nomatch.com", "/page_with_two_frames.html");
TestRule abc_referer_rule = CreateModifyHeadersRule(
kMinValidID, kMinValidPriority, sub_frame_host,
std::vector<TestHeaderInfo>(
{TestHeaderInfo("referer", "remove", std::nullopt)}),
std::nullopt);
TestRule abc_set_cookie_rule = CreateModifyHeadersRule(
kMinValidID + 1, kMinValidPriority, sub_frame_host, std::nullopt,
std::vector<TestHeaderInfo>(
{TestHeaderInfo("set-cookie", "remove", std::nullopt)}));
// Load an extension with removeHeaders rules for the Referer and Set-Cookie
// headers.
ASSERT_NO_FATAL_FAILURE(
LoadExtensionWithRules({abc_set_cookie_rule, abc_referer_rule},
"extension_1", {URLPattern::kAllUrlsPattern}));
NavigateToURL(page_url);
ASSERT_TRUE(WasFrameWithScriptLoaded(GetPrimaryMainFrame()));
// Start the onRuleMatchedDebug observer.
static constexpr char kOnRuleMatchedDebugScript[] = R"(
var matchedRules = [];
var onRuleMatchedDebugCallback = (rule) => {
matchedRules.push(rule);
};
chrome.declarativeNetRequest.onRuleMatchedDebug.addListener(
onRuleMatchedDebugCallback);
chrome.test.sendScriptResult('ready');
)";
ASSERT_EQ("ready", ExecuteScriptInBackgroundPage(last_loaded_extension_id(),
kOnRuleMatchedDebugScript));
auto set_cookie_and_referer_url =
embedded_test_server()->GetURL(sub_frame_host, "/set-cookie?a=b");
NavigateFrame(kFrameName1, set_cookie_and_referer_url);
// Now query the onRuleMatchedDebug results.
static constexpr char kQueryMatchedRulesScript[] = R"(
chrome.declarativeNetRequest.onRuleMatchedDebug.removeListener(
onRuleMatchedDebugCallback);
var ruleIds = matchedRules.map(matchedRule => matchedRule.rule.ruleId);
chrome.test.sendScriptResult(ruleIds.sort().join());
)";
std::string matched_rule_ids = ExecuteScriptInBackgroundPageAndReturnString(
last_loaded_extension_id(), kQueryMatchedRulesScript);
// The request to |set_cookie_and_referer_url| should be matched with the
// Referer rule (ruleId 1) and the Set-Cookie rule (ruleId 2).
EXPECT_EQ("1,2", matched_rule_ids);
}
#if !BUILDFLAG(IS_ANDROID)
// Test that getMatchedRules returns the correct rules when called by different
// extensions with rules matched by requests initiated from different tabs.
// TODO(crbug.com/371298229): Port to desktop Android when we have better
// support for the tab strip (e.g. ActivateTabAt()).
IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest,
GetMatchedRulesMultipleTabs) {
// Load the extension with a background script so scripts can be run from its
// generated background page. Also grant the feedback permission for the
// extension so it has access to the getMatchedRules API function.
set_config_flags(ConfigFlag::kConfig_HasBackgroundScript |
ConfigFlag::kConfig_HasFeedbackPermission);
DeclarativeNetRequestGetMatchedRulesFunction::
set_disable_throttling_for_tests(true);
// Sub-frames are used for navigations instead of the main-frame to allow
// multiple requests to be made without triggering a main-frame navigation,
// which would move rules attributed to the previous main-frame to the unknown
// tab ID.
const std::string kFrameName1 = "frame1";
const GURL page_url = embedded_test_server()->GetURL(
"nomatch.com", "/page_with_two_frames.html");
auto get_url_for_host = [this](std::string hostname) {
return embedded_test_server()->GetURL(hostname,
"/pages_with_script/index.html");
};
auto create_block_rule = [](int id, const std::string& url_filter) {
TestRule rule = CreateGenericRule();
rule.id = id;
rule.condition->url_filter = url_filter;
rule.condition->resource_types = std::vector<std::string>({"sub_frame"});
rule.action->type = "block";
return rule;
};
TestRule abc_rule = create_block_rule(kMinValidID, "abc.com");
TestRule def_rule = create_block_rule(kMinValidID + 1, "def.com");
ASSERT_NO_FATAL_FAILURE(
LoadExtensionWithRules({abc_rule}, "extension_1", {}));
auto extension_1_id = last_loaded_extension_id();
ASSERT_NO_FATAL_FAILURE(
LoadExtensionWithRules({def_rule}, "extension_2", {}));
auto extension_2_id = last_loaded_extension_id();
ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), page_url));
ASSERT_TRUE(WasFrameWithScriptLoaded(GetPrimaryMainFrame()));
const int first_tab_id = ExtensionTabUtil::GetTabId(web_contents());
// Navigate to abc.com. The rule from |extension_1| should match for
// |first_tab_id|.
NavigateFrame(kFrameName1, get_url_for_host("abc.com"));
// Navigate to abc.com. The rule from |extension_2| should match for
// |first_tab_id|.
NavigateFrame(kFrameName1, get_url_for_host("def.com"));
ui_test_utils::NavigateToURLWithDisposition(
browser(), page_url, WindowOpenDisposition::NEW_FOREGROUND_TAB,
ui_test_utils::BROWSER_TEST_WAIT_FOR_LOAD_STOP);
ASSERT_EQ(2, browser()->tab_strip_model()->count());
ASSERT_TRUE(browser()->tab_strip_model()->IsTabSelected(1));
ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), page_url));
ASSERT_TRUE(WasFrameWithScriptLoaded(GetPrimaryMainFrame()));
const int second_tab_id = ExtensionTabUtil::GetTabId(web_contents());
// Navigate to abc.com from the second tab. The rule from |extension_1| should
// match for |second_tab_id|.
NavigateFrame(kFrameName1, get_url_for_host("abc.com"));
int abc_id = *abc_rule.id;
int def_id = *def_rule.id;
struct {
ExtensionId extension_id;
std::optional<int> tab_id;
std::string expected_rule_and_tab_ids;
} test_cases[] = {
// No rules should be matched for |extension_1| and the unknown tab ID.
{extension_1_id, extension_misc::kUnknownTabId, ""},
// No filter is specified for |extension_1|, therefore two MatchedRuleInfo
// should be returned:
// (abc_id, first_tab_id) and (abc_id, second_tab_id)
{extension_1_id, std::nullopt,
base::StringPrintf("%d,%d|%d,%d", abc_id, first_tab_id, abc_id,
second_tab_id)},
// Filtering by tab_id = |first_tab_id| should return one MatchedRuleInfo:
// (abc_id, first_tab_id)
{extension_1_id, first_tab_id,
base::StringPrintf("%d,%d", abc_id, first_tab_id)},
// Filtering by tab_id = |second_tab_id| should return one
// MatchedRuleInfo: (abc_id, second_tab_id)
{extension_1_id, second_tab_id,
base::StringPrintf("%d,%d", abc_id, second_tab_id)},
// For |extension_2|, filtering by tab_id = |first_tab_id| should return
// one MatchedRuleInfo: (def_id, first_tab_id)
{extension_2_id, first_tab_id,
base::StringPrintf("%d,%d", def_id, first_tab_id)},
// Since no rules from |extension_2| was matched for the second tab,
// getMatchedRules should not return any rules.
{extension_2_id, second_tab_id, ""}};
for (const auto& test_case : test_cases) {
if (test_case.tab_id) {
SCOPED_TRACE(base::StringPrintf(
"Testing getMatchedRules for tab %d and extension %s",
*test_case.tab_id, test_case.extension_id.c_str()));
} else {
SCOPED_TRACE(base::StringPrintf(
"Testing getMatchedRules for all tabs and extension %s",
test_case.extension_id.c_str()));
}
std::string actual_rule_and_tab_ids =
GetRuleAndTabIdsMatched(test_case.extension_id, test_case.tab_id);
EXPECT_EQ(test_case.expected_rule_and_tab_ids, actual_rule_and_tab_ids);
}
// Close the second tab opened.
browser()->tab_strip_model()->CloseSelectedTabs();
ASSERT_EQ(1, browser()->tab_strip_model()->count());
ASSERT_TRUE(browser()->tab_strip_model()->IsTabSelected(0));
std::string actual_rule_and_tab_ids =
GetRuleAndTabIdsMatched(extension_1_id, std::nullopt);
// The matched rule info for the second tab should have its tab ID changed to
// the unknown tab ID after the second tab has been closed.
EXPECT_EQ(
base::StringPrintf("%d,%d|%d,%d", abc_id, extension_misc::kUnknownTabId,
abc_id, first_tab_id),
actual_rule_and_tab_ids);
}
// Test that rules matched for main-frame navigations are attributed will be
// reset when a main-frame navigation finishes.
// TODO(crbug.com/393191910): Port to desktop Android. Currently fails but does
// not produce any failure logs or a stack.
IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest,
GetMatchedRulesMainFrame) {
// Load the extension with a background script so scripts can be run from its
// generated background page. Also grant the feedback permission for the
// extension so it has access to the getMatchedRules API function.
set_config_flags(ConfigFlag::kConfig_HasBackgroundScript |
ConfigFlag::kConfig_HasFeedbackPermission);
DeclarativeNetRequestGetMatchedRulesFunction::
set_disable_throttling_for_tests(true);
const std::string test_host = "abc.com";
GURL page_url = embedded_test_server()->GetURL(
test_host, "/pages_with_script/index.html");
TestRule rule = CreateGenericRule();
rule.id = kMinValidID;
rule.condition->url_filter = test_host;
rule.condition->resource_types = std::vector<std::string>({"main_frame"});
rule.action->type = "block";
ASSERT_NO_FATAL_FAILURE(LoadExtensionWithRules({rule}, "extension_1", {}));
// Navigate to abc.com.
ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), page_url));
std::string actual_rule_and_tab_ids =
GetRuleAndTabIdsMatched(last_loaded_extension_id(), std::nullopt);
// Since the block rule for abc.com is matched for the main-frame navigation
// request, it should be attributed to the current tab.
const int first_tab_id = ExtensionTabUtil::GetTabId(web_contents());
std::string expected_rule_and_tab_ids =
base::StringPrintf("%d,%d", *rule.id, first_tab_id);
EXPECT_EQ(expected_rule_and_tab_ids, actual_rule_and_tab_ids);
// Navigate to abc.com again.
ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), page_url));
actual_rule_and_tab_ids =
GetRuleAndTabIdsMatched(last_loaded_extension_id(), std::nullopt);
// The same block rule is matched for this navigation request, and should be
// attributed to the current tab. Since the main-frame for which the older
// matched rule is associated with is no longer active, the older matched
// rule's tab ID should be changed to the unknown tab ID.
expected_rule_and_tab_ids =
base::StringPrintf("%d,%d|%d,%d", *rule.id, extension_misc::kUnknownTabId,
*rule.id, first_tab_id);
EXPECT_EQ(expected_rule_and_tab_ids, actual_rule_and_tab_ids);
// Navigate to nomatch,com.
ASSERT_TRUE(ui_test_utils::NavigateToURL(
browser(), embedded_test_server()->GetURL(
"nomatch.com", "/pages_with_script/index.html")));
// No rules should be matched for the navigation request to nomatch.com and
// all rules previously attributed to |first_tab_id| should now be attributed
// to the unknown tab ID as a result of the navigation. Therefore
// GetMatchedRules should return no matched rules.
actual_rule_and_tab_ids =
GetRuleAndTabIdsMatched(last_loaded_extension_id(), first_tab_id);
EXPECT_EQ("", actual_rule_and_tab_ids);
}
// Test that getMatchedRules only returns rules more recent than the provided
// timestamp.
// TODO(crbug.com/393191910): Port to desktop Android. Currently fails but does
// not produce any failure logs or a stack.
IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest,
GetMatchedRulesTimestampFiltering) {
base::Time start_time = base::Time::Now();
base::SimpleTestClock clock_;
clock_.SetNow(start_time);
rules_monitor_service()->action_tracker().SetClockForTests(&clock_);
// Load the extension with a background script so scripts can be run from its
// generated background page. Also grant the feedback permission for the
// extension so it has access to the getMatchedRules API function.
set_config_flags(ConfigFlag::kConfig_HasBackgroundScript |
ConfigFlag::kConfig_HasFeedbackPermission);
DeclarativeNetRequestGetMatchedRulesFunction::
set_disable_throttling_for_tests(true);
const std::string kFrameName1 = "frame1";
const GURL page_url = embedded_test_server()->GetURL(
"nomatch.com", "/page_with_two_frames.html");
const std::string example_host = "example.com";
const GURL sub_frame_url = embedded_test_server()->GetURL(
example_host, "/pages_with_script/index.html");
TestRule rule = CreateGenericRule();
rule.id = kMinValidID;
rule.condition->url_filter = example_host;
rule.condition->resource_types = std::vector<std::string>({"sub_frame"});
rule.action->type = "block";
ASSERT_NO_FATAL_FAILURE(LoadExtensionWithRules({rule}, "extension_1", {}));
const ExtensionId& extension_id = last_loaded_extension_id();
NavigateToURL(page_url);
// Using subframes here to make requests without triggering main-frame
// navigations. This request will match with the block rule for example.com at
// |start_time|.
NavigateFrame(kFrameName1, sub_frame_url);
static constexpr char getMatchedRuleTimestampScript[] = R"(
chrome.declarativeNetRequest.getMatchedRules((rules) => {
var rule_count = rules.rulesMatchedInfo.length;
var timestamp = rule_count === 1 ?
rules.rulesMatchedInfo[0].timeStamp.toString() : '';
chrome.test.sendScriptResult(timestamp);
});
)";
std::string timestamp_string = ExecuteScriptInBackgroundPageAndReturnString(
extension_id, getMatchedRuleTimestampScript,
browsertest_util::ScriptUserActivation::kDontActivate);
double matched_rule_timestamp;
ASSERT_TRUE(base::StringToDouble(timestamp_string, &matched_rule_timestamp));
// Verify that the rule was matched at |start_time|.
EXPECT_DOUBLE_EQ(start_time.InMillisecondsFSinceUnixEpochIgnoringNull(),
matched_rule_timestamp);
// Advance the clock to capture a timestamp after when the first request was
// made.
clock_.Advance(base::Milliseconds(100));
base::Time timestamp_1 = clock_.Now();
clock_.Advance(base::Milliseconds(100));
// Navigate to example.com again. This should cause |rule| to be matched.
NavigateFrame(kFrameName1, sub_frame_url);
// Advance the clock to capture a timestamp after when the second request was
// made.
clock_.Advance(base::Milliseconds(100));
base::Time timestamp_2 = clock_.Now();
int first_tab_id = ExtensionTabUtil::GetTabId(web_contents());
// Two rules should be matched on |first_tab_id|.
std::string rule_count = GetMatchedRuleCount(extension_id, first_tab_id,
std::nullopt /* timestamp */);
EXPECT_EQ("2", rule_count);
// Only one rule should be matched on |first_tab_id| after |timestamp_1|.
rule_count = GetMatchedRuleCount(extension_id, first_tab_id, timestamp_1);
EXPECT_EQ("1", rule_count);
// No rules should be matched on |first_tab_id| after |timestamp_2|.
rule_count = GetMatchedRuleCount(extension_id, first_tab_id, timestamp_2);
EXPECT_EQ("0", rule_count);
rules_monitor_service()->action_tracker().SetClockForTests(nullptr);
}
// Test that getMatchedRules will only return matched rules for individual tabs
// where activeTab is granted.
// TODO(crbug.com/393147570): Port to desktop Android when the permissions API
// and ActiveTabPermissionsGranter are available.
IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest,
GetMatchedRulesActiveTab) {
// Load the extension with a background script so scripts can be run from its
// generated background page.
set_config_flags(ConfigFlag::kConfig_HasBackgroundScript |
ConfigFlag::kConfig_HasActiveTab);
DeclarativeNetRequestGetMatchedRulesFunction::
set_disable_throttling_for_tests(true);
const std::string test_host = "abc.com";
GURL page_url = embedded_test_server()->GetURL(
test_host, "/pages_with_script/index.html");
TestRule rule = CreateGenericRule();
rule.id = kMinValidID;
rule.condition->url_filter = test_host;
rule.condition->resource_types = std::vector<std::string>({"main_frame"});
rule.action->type = "block";
ASSERT_NO_FATAL_FAILURE(LoadExtensionWithRules({rule}, "extension_1", {}));
const ExtensionId& extension_id = last_loaded_extension_id();
// Navigate to |page_url| which will cause |rule| to be matched.
ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), page_url));
int first_tab_id = ExtensionTabUtil::GetTabId(web_contents());
// Open a new tab and navigate to |page_url| which will cause |rule| to be
// matched.
ui_test_utils::NavigateToURLWithDisposition(
browser(), page_url, WindowOpenDisposition::NEW_FOREGROUND_TAB,
ui_test_utils::BROWSER_TEST_WAIT_FOR_LOAD_STOP);
ASSERT_EQ(2, browser()->tab_strip_model()->count());
ASSERT_TRUE(browser()->tab_strip_model()->IsTabSelected(1));
// Get the ActiveTabPermissionGranter for the second tab.
ActiveTabPermissionGranter* active_tab_granter =
ActiveTabPermissionGranter::FromWebContents(web_contents());
ASSERT_TRUE(active_tab_granter);
const Extension* dnr_extension = last_loaded_extension();
// Grant the activeTab permission for the second tab.
active_tab_granter->GrantIfRequested(dnr_extension);
int second_tab_id = ExtensionTabUtil::GetTabId(web_contents());
// Calling getMatchedRules with no tab ID specified should result in an error
// since the extension does not have the feedback permission.
EXPECT_EQ(declarative_net_request::kErrorGetMatchedRulesMissingPermissions,
GetMatchedRuleCount(extension_id, std::nullopt /* tab_id */,
std::nullopt /* timestamp */));
// Calling getMatchedRules for a tab without the activeTab permission granted
// should result in an error.
EXPECT_EQ(declarative_net_request::kErrorGetMatchedRulesMissingPermissions,
GetMatchedRuleCount(extension_id, first_tab_id,
std::nullopt /* timestamp */));
// Calling getMatchedRules for a tab with the activeTab permission granted
// should return the rules matched for that tab.
EXPECT_EQ("1", GetMatchedRuleCount(extension_id, second_tab_id,
std::nullopt /* timestamp */));
}
#endif // !BUILDFLAG(IS_ANDROID)
// Test that getMatchedRules will not be throttled if the call is associated
// with a user gesture.
IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest,
GetMatchedRulesNoThrottlingIfUserGesture) {
// Load the extension with a background script so scripts can be run from its
// generated background page. Also grant the feedback permission for the
// extension so it has access to the getMatchedRules API function.
set_config_flags(ConfigFlag::kConfig_HasBackgroundScript |
ConfigFlag::kConfig_HasFeedbackPermission);
// Ensure that GetMatchedRules is being throttled.
DeclarativeNetRequestGetMatchedRulesFunction::
set_disable_throttling_for_tests(false);
ASSERT_NO_FATAL_FAILURE(LoadExtensionWithRules({}));
const ExtensionId& extension_id = last_loaded_extension_id();
auto get_matched_rules_count = [this, &extension_id](bool user_gesture) {
auto user_gesture_setting =
user_gesture ? browsertest_util::ScriptUserActivation::kActivate
: browsertest_util::ScriptUserActivation::kDontActivate;
return GetMatchedRuleCount(extension_id, std::nullopt /* tab_id */,
std::nullopt /* timestamp */,
user_gesture_setting);
};
// Call getMatchedRules without a user gesture, until the quota is reached.
// None of these calls should return an error.
for (int i = 1; i <= dnr_api::MAX_GETMATCHEDRULES_CALLS_PER_INTERVAL; ++i) {
SCOPED_TRACE(base::StringPrintf(
"Testing getMatchedRules call without user gesture %d of %d", i,
dnr_api::MAX_GETMATCHEDRULES_CALLS_PER_INTERVAL));
EXPECT_EQ("0", get_matched_rules_count(false));
}
// Calling getMatchedRules without a user gesture should return an error after
// the quota has been reached.
EXPECT_EQ(
"This request exceeds the MAX_GETMATCHEDRULES_CALLS_PER_INTERVAL quota.",
get_matched_rules_count(false));
// Calling getMatchedRules with a user gesture should not return an error even
// after the quota has been reached.
EXPECT_EQ("0", get_matched_rules_count(true));
}
#if !BUILDFLAG(IS_ANDROID)
// Tests extension update for an extension using declarativeNetRequest.
// TODO(crbug.com/391924202): Port to desktop Android once packed extensions are
// supported.
IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest_Packed,
ExtensionRemovesOneRulesetOnUpdate) {
auto create_single_rule_ruleset = [this](
const std::string& ruleset_id_and_path,
bool enabled,
const std::string& filter) {
std::vector<TestRule> rules = {CreateMainFrameBlockRule(filter)};
return TestRulesetInfo(ruleset_id_and_path, ToListValue(rules), enabled);
};
set_config_flags(ConfigFlag::kConfig_HasBackgroundScript);
std::vector<TestRulesetInfo> rulesets = {
create_single_rule_ruleset("id1", true, "google"),
create_single_rule_ruleset("id2", false, "yahoo"),
create_single_rule_ruleset("id3", true, "example"),
};
constexpr char kDirectory1[] = "dir1";
ASSERT_NO_FATAL_FAILURE(
LoadExtensionWithRulesets(rulesets, kDirectory1, {} /* hosts */));
const ExtensionId& extension_id = last_loaded_extension_id();
const Extension* extension = last_loaded_extension();
ExtensionPrefs* prefs = ExtensionPrefs::Get(profile());
ASSERT_TRUE(prefs);
// Since this is a packed extension, rulesets are only indexed when they are
// first enabled. The second ruleset has not been enabled yet, so it shouldn't
// have been indexed yet either.
int checksum = -1;
PrefsHelper helper(*prefs);
EXPECT_TRUE(helper.GetStaticRulesetChecksum(
extension_id, kMinValidStaticRulesetID, checksum));
EXPECT_FALSE(helper.GetStaticRulesetChecksum(
extension_id, RulesetID(kMinValidStaticRulesetID.value() + 1), checksum));
EXPECT_TRUE(helper.GetStaticRulesetChecksum(
extension_id, RulesetID(kMinValidStaticRulesetID.value() + 2), checksum));
// Also add a dynamic rule.
ASSERT_NO_FATAL_FAILURE(
AddDynamicRules(extension_id, {CreateMainFrameBlockRule("dynamic")}));
// Also update the set of enabled static rulesets.
ASSERT_NO_FATAL_FAILURE(
UpdateEnabledRulesets(extension_id, {"id1"}, {"id2", "id3"}));
CompositeMatcher* composite_matcher =
ruleset_manager()->GetMatcherForExtension(extension_id);
ASSERT_TRUE(composite_matcher);
EXPECT_THAT(GetPublicRulesetIDs(*extension, *composite_matcher),
UnorderedElementsAre("id2", "id3", dnr_api::DYNAMIC_RULESET_ID));
// Also sanity check the extension prefs entry for the rulesets. Note that
// the second static ruleset now should have been indexed since it has now
// been enabled.
int dynamic_checksum_1 = -1;
EXPECT_TRUE(helper.GetStaticRulesetChecksum(
extension_id, kMinValidStaticRulesetID, checksum));
EXPECT_TRUE(helper.GetStaticRulesetChecksum(
extension_id, RulesetID(kMinValidStaticRulesetID.value() + 1), checksum));
EXPECT_TRUE(helper.GetStaticRulesetChecksum(
extension_id, RulesetID(kMinValidStaticRulesetID.value() + 2), checksum));
EXPECT_FALSE(helper.GetStaticRulesetChecksum(
extension_id, RulesetID(kMinValidStaticRulesetID.value() + 3), checksum));
EXPECT_TRUE(
helper.GetDynamicRulesetChecksum(extension_id, dynamic_checksum_1));
std::optional<std::set<RulesetID>> enabled_static_rulesets =
helper.GetEnabledStaticRulesets(extension_id);
ASSERT_TRUE(enabled_static_rulesets);
EXPECT_THAT(
*enabled_static_rulesets,
UnorderedElementsAre(RulesetID(kMinValidStaticRulesetID.value() + 1),
RulesetID(kMinValidStaticRulesetID.value() + 2)));
std::vector<TestRulesetInfo> new_rulesets = {
create_single_rule_ruleset("id1", true, "yahoo"),
create_single_rule_ruleset("new_id2", false, "msn")};
const char* kDirectory2 = "dir2";
ASSERT_NO_FATAL_FAILURE(UpdateLastLoadedExtension(
new_rulesets, kDirectory2, {} /* hosts */,
0 /* expected_extensions_with_rulesets_count_change */,
true /* has_dynamic_ruleset */, false /* is_delayed_update */));
extension = extension_registry()->enabled_extensions().GetByID(extension_id);
composite_matcher = ruleset_manager()->GetMatcherForExtension(extension_id);
ASSERT_TRUE(composite_matcher);
EXPECT_THAT(GetPublicRulesetIDs(*extension, *composite_matcher),
UnorderedElementsAre("id1", dnr_api::DYNAMIC_RULESET_ID));
int dynamic_checksum_2;
EXPECT_TRUE(helper.GetStaticRulesetChecksum(
extension_id, kMinValidStaticRulesetID, checksum));
EXPECT_FALSE(helper.GetStaticRulesetChecksum(
extension_id, RulesetID(kMinValidStaticRulesetID.value() + 1), checksum));
EXPECT_FALSE(helper.GetStaticRulesetChecksum(
extension_id, RulesetID(kMinValidStaticRulesetID.value() + 2), checksum));
EXPECT_TRUE(
helper.GetDynamicRulesetChecksum(extension_id, dynamic_checksum_2));
EXPECT_EQ(dynamic_checksum_2, dynamic_checksum_1);
// Ensure the preference for enabled static rulesets is cleared on extension
// update.
EXPECT_FALSE(helper.GetEnabledStaticRulesets(extension_id));
}
// Tests extension update for an extension using declarativeNetRequest.
// TODO(crbug.com/391924202): Port to desktop Android once packed extensions are
// supported.
IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest_Packed,
ExtensionRemovesAllRulesetsOnUpdate) {
auto create_single_rule_ruleset = [this](
const std::string& ruleset_id_and_path,
bool enabled,
const std::string& filter) {
std::vector<TestRule> rules = {CreateMainFrameBlockRule(filter)};
return TestRulesetInfo(ruleset_id_and_path, ToListValue(rules), enabled);
};
std::vector<TestRulesetInfo> rulesets = {
create_single_rule_ruleset("id1", true, "google"),
create_single_rule_ruleset("id2", true, "example")};
const char* kDirectory1 = "dir1";
ASSERT_NO_FATAL_FAILURE(
LoadExtensionWithRulesets(rulesets, kDirectory1, {} /* hosts */));
const ExtensionId& extension_id = last_loaded_extension_id();
const Extension* extension = last_loaded_extension();
CompositeMatcher* composite_matcher =
ruleset_manager()->GetMatcherForExtension(extension_id);
ASSERT_TRUE(composite_matcher);
EXPECT_THAT(GetPublicRulesetIDs(*extension, *composite_matcher),
UnorderedElementsAre("id1", "id2"));
// Also sanity check the extension prefs entry for the rulesets.
ExtensionPrefs* prefs = ExtensionPrefs::Get(profile());
ASSERT_TRUE(prefs);
PrefsHelper helper(*prefs);
int checksum = -1;
EXPECT_TRUE(helper.GetStaticRulesetChecksum(
extension_id, kMinValidStaticRulesetID, checksum));
EXPECT_TRUE(helper.GetStaticRulesetChecksum(
extension_id, RulesetID(kMinValidStaticRulesetID.value() + 1), checksum));
EXPECT_FALSE(helper.GetDynamicRulesetChecksum(extension_id, checksum));
const char* kDirectory2 = "dir2";
ASSERT_NO_FATAL_FAILURE(UpdateLastLoadedExtension(
{} /* new_rulesets */, kDirectory2, {} /* hosts */,
-1 /* expected_extensions_with_rulesets_count_change */,
false /* has_dynamic_ruleset */, false /* is_delayed_update */));
extension = extension_registry()->enabled_extensions().GetByID(extension_id);
composite_matcher = ruleset_manager()->GetMatcherForExtension(extension_id);
EXPECT_FALSE(composite_matcher);
// Ensure the prefs entry are cleared appropriately.
EXPECT_FALSE(helper.GetStaticRulesetChecksum(
extension_id, kMinValidStaticRulesetID, checksum));
EXPECT_FALSE(helper.GetStaticRulesetChecksum(
extension_id, RulesetID(kMinValidStaticRulesetID.value() + 1), checksum));
EXPECT_FALSE(helper.GetDynamicRulesetChecksum(extension_id, checksum));
}
// Tests that persisted disabled static rule ids are no longer kept after an
// extension update.
// TODO(crbug.com/391924202): Port to desktop Android once packed extensions are
// supported.
IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest_Packed,
PackedUpdateAfterUpdateStaticRules) {
set_config_flags(ConfigFlag::kConfig_HasBackgroundScript);
std::string ruleset_id = "ruleset1";
std::vector<TestRulesetInfo> rulesets = {TestRulesetInfo(
ruleset_id, ToListValue({CreateGenericRule(1), CreateGenericRule(2),
CreateGenericRule(3)}))};
const char* kDirectory1 = "dir1";
ASSERT_NO_FATAL_FAILURE(
LoadExtensionWithRulesets(rulesets, kDirectory1, {} /* hosts */));
const Extension* extension = last_loaded_extension();
CompositeMatcher* composite_matcher =
ruleset_manager()->GetMatcherForExtension(last_loaded_extension_id());
ASSERT_TRUE(composite_matcher);
EXPECT_THAT(GetPublicRulesetIDs(*extension, *composite_matcher),
UnorderedElementsAre(ruleset_id));
EXPECT_THAT(GetDisabledRuleIdsFromMatcher(ruleset_id), testing::IsEmpty());
VerifyGetDisabledRuleIds(last_loaded_extension_id(), ruleset_id, {});
UpdateStaticRules(last_loaded_extension_id(), ruleset_id,
{2} /* rule_ids_to_disable */, {} /* rule_ids_to_enable */);
EXPECT_THAT(GetDisabledRuleIdsFromMatcher(ruleset_id), ElementsAreArray({2}));
VerifyGetDisabledRuleIds(last_loaded_extension_id(), ruleset_id, {2});
const char* kDirectory2 = "dir2";
ASSERT_NO_FATAL_FAILURE(UpdateLastLoadedExtension(
rulesets, kDirectory2, {} /* hosts */,
0 /* expected_extensions_with_rulesets_count_change */,
false /* has_dynamic_ruleset */, false /* is_delayed_update */));
extension = last_loaded_extension();
composite_matcher =
ruleset_manager()->GetMatcherForExtension(last_loaded_extension_id());
EXPECT_TRUE(composite_matcher);
EXPECT_THAT(GetPublicRulesetIDs(*extension, *composite_matcher),
UnorderedElementsAre(ruleset_id));
EXPECT_THAT(GetDisabledRuleIdsFromMatcher(ruleset_id), testing::IsEmpty());
VerifyGetDisabledRuleIds(last_loaded_extension_id(), ruleset_id, {});
}
// Tests that prefs from the older version of the extension such as ruleset
// checksums and enabled static rulesets are reset when the extension goes
// through a delayed update.
// Regression for crbug.com/40285683.
// TODO(crbug.com/391924202): Port to desktop Android once packed extensions are
// supported.
IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest_Packed,
RemoveStalePrefsOnDelayedUpdate) {
set_config_flags(ConfigFlag::kConfig_HasBackgroundScript |
ConfigFlag::kConfig_ListenForOnUpdateAvailable);
ExtensionPrefs* prefs = ExtensionPrefs::Get(profile());
PrefsHelper helper(*prefs);
auto is_checksum_in_prefs = [this, &helper](const RulesetID& ruleset_id) {
int checksum;
return helper.GetStaticRulesetChecksum(last_loaded_extension_id(),
ruleset_id, checksum);
};
// Load one extension with one ruleset that is disabled by default.
std::string ruleset_id = "ruleset1";
std::vector<TestRulesetInfo> rulesets = {
TestRulesetInfo(ruleset_id, ToListValue({CreateGenericRule(1)}), false)};
static constexpr char kDirectory1[] = "dir1";
ASSERT_NO_FATAL_FAILURE(
LoadExtensionWithRulesets(rulesets, kDirectory1, {} /* hosts */));
VerifyPublicRulesetIds(last_loaded_extension(), {});
// Now enable the ruleset and check that prefs are updated with the ruleset's
// checksum and the extension's set of enabled rulesets.
ASSERT_NO_FATAL_FAILURE(
UpdateEnabledRulesets(last_loaded_extension_id(), {}, {ruleset_id}));
VerifyPublicRulesetIds(last_loaded_extension(), {ruleset_id});
std::optional<std::set<RulesetID>> enabled_static_rulesets =
helper.GetEnabledStaticRulesets(last_loaded_extension_id());
EXPECT_THAT(
enabled_static_rulesets.value_or(std::set<RulesetID>()),
UnorderedElementsAre(RulesetID(kMinValidStaticRulesetID.value())));
EXPECT_TRUE(is_checksum_in_prefs(kMinValidStaticRulesetID));
// Update the extension with a slightly different ruleset that's disabled by
// default (so the checksum changes) and make it a delayed update.
static constexpr char kDirectory2[] = "dir2";
ASSERT_NO_FATAL_FAILURE(UpdateLastLoadedExtension(
{TestRulesetInfo(ruleset_id, ToListValue({CreateGenericRule(2)}), false)},
kDirectory2, {} /* hosts */,
-1 /* expected_extensions_with_rulesets_count_change */, false,
true /* is_delayed_update */));
// Verify that no rulesets are enabled and the prefs contain no checksums nor
// any enabled ruleset ids.
VerifyPublicRulesetIds(last_loaded_extension(), {});
EXPECT_FALSE(helper.GetEnabledStaticRulesets(last_loaded_extension_id()));
EXPECT_FALSE(is_checksum_in_prefs(kMinValidStaticRulesetID));
// Enable the ruleset again (this operation should succeed) and check the
// updated state.
ASSERT_NO_FATAL_FAILURE(
UpdateEnabledRulesets(last_loaded_extension_id(), {}, {ruleset_id}));
VerifyPublicRulesetIds(last_loaded_extension(), {ruleset_id});
enabled_static_rulesets =
helper.GetEnabledStaticRulesets(last_loaded_extension_id());
EXPECT_THAT(
enabled_static_rulesets.value_or(std::set<RulesetID>()),
UnorderedElementsAre(RulesetID(kMinValidStaticRulesetID.value())));
EXPECT_TRUE(is_checksum_in_prefs(kMinValidStaticRulesetID));
}
// Fixture to test the "allowAllRequests" action.
// TODO(crbug.com/393191910): Port to desktop Android. These tests fail with
// no logging and no stack.
class DeclarativeNetRequestAllowAllRequestsBrowserTest
: public DeclarativeNetRequestBrowserTest {
public:
struct RuleData {
int id;
int priority;
std::string action_type;
std::string url_filter;
bool is_regex_rule;
std::optional<std::vector<std::string>> resource_types;
std::optional<std::vector<std::string>> request_methods;
};
DeclarativeNetRequestAllowAllRequestsBrowserTest() = default;
void RunTest(const std::vector<RuleData>& rule_data,
const std::vector<std::string>& paths_seen,
const std::vector<std::string>& paths_not_seen,
bool post_navigation = false) {
std::vector<TestRule> test_rules;
for (const auto& rule : rule_data) {
TestRule test_rule = CreateGenericRule();
test_rule.id = rule.id;
test_rule.priority = rule.priority;
test_rule.action->type = rule.action_type;
test_rule.condition->url_filter.reset();
if (rule.is_regex_rule)
test_rule.condition->regex_filter = rule.url_filter;
else
test_rule.condition->url_filter = rule.url_filter;
test_rule.condition->resource_types = rule.resource_types;
test_rule.condition->request_methods = rule.request_methods;
test_rules.push_back(test_rule);
}
ASSERT_NO_FATAL_FAILURE(LoadExtensionWithRules(test_rules));
GURL page_url = embedded_test_server()->GetURL(
"example.com", post_navigation ? "/post_to_page_with_two_frames.html"
: "/page_with_two_frames.html");
ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), page_url));
std::map<GURL, net::test_server::HttpRequest> requests_seen =
GetAndResetRequestsToServer();
for (const auto& path : paths_seen) {
GURL expected_request_url = embedded_test_server()->GetURL(path);
EXPECT_TRUE(base::Contains(requests_seen, expected_request_url))
<< expected_request_url.spec()
<< " was not requested from the server.";
}
for (const auto& path : paths_not_seen) {
GURL expected_request_url = embedded_test_server()->GetURL(path);
EXPECT_FALSE(base::Contains(requests_seen, expected_request_url))
<< expected_request_url.spec() << " request seen unexpectedly.";
}
}
protected:
// Requests made when the browser is navigated to
// "http://example.com/page_with_two_frames.html".
std::vector<std::string> requests = {
{"/page_with_two_frames.html"}, // 0
{"/subresources/script.js"}, // 1
{"/child_frame.html?frame=1"}, // 2
{"/subresources/script.js?frameId=1"}, // 3
{"/child_frame.html?frame=2"}, // 4
{"/subresources/script.js?frameId=2"}, // 5
};
};
// TODO(crbug.com/40853402): Re-enable this test. It was disabled because of
// flakiness.
IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestAllowAllRequestsBrowserTest,
DISABLED_Test1) {
std::vector<RuleData> rule_data = {
{1, 4, "allowAllRequests", "page_with_two_frames\\.html", true,
std::vector<std::string>({"main_frame"})},
{2, 3, "block", "script.js|", false},
{3, 5, "block", "script.js?frameId=1", false},
{4, 3, "block", "script\\.js?frameId=2", true}};
// Requests:
// -/page_with_two_frames.html (Matching rule=1)
// -/subresources/script.js (Matching rule=[1,2] Winner=1)
// -/child_frame.html?frame=1 (Matching Rule=1)
// -/subresources/script.js?frameId=1 (Matching Rule=[1,3] Winner=3)
// -/child_frame.html?frame=2 (Matching Rule=1)
// -/subresources/script.js?frameId=2 (Matching Rule=1,4 Winner=1)
// Hence only requests[3] is blocked.
RunTest(rule_data,
{requests[0], requests[1], requests[2], requests[4], requests[5]},
{requests[3]});
}
IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestAllowAllRequestsBrowserTest,
Test2) {
std::vector<RuleData> rule_data = {
{1, 4, "allowAllRequests", "page_with_two_frames.html", false,
std::vector<std::string>({"main_frame"})},
{2, 5, "block", "script\\.js", true},
{3, 6, "allowAllRequests", "child_frame.html", false,
std::vector<std::string>({"sub_frame"})},
{4, 7, "block", "frame=1", true}};
// Requests:
// -/page_with_two_frames.html (Matching rule=1)
// -/subresources/script.js (Matching rule=[1,2] Winner=2, Blocked)
// -/child_frame.html?frame=1 (Matching Rule=[1,3,4] Winner=4, Blocked)
// -/subresources/script.js?frameId=1 (Source Frame was blocked)
// -/child_frame.html?frame=2 (Matching Rule=[1,3] Winner=3)
// -/subresources/script.js?frameId=2 (Matching Rule=[1,2,3] Winner=3)
RunTest(rule_data, {requests[0], requests[4], requests[5]},
{requests[1], requests[2], requests[3]});
}
IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestAllowAllRequestsBrowserTest,
Test3) {
std::vector<RuleData> rule_data = {
{1, 1, "allowAllRequests", "page_with_two_frames.html", false,
std::vector<std::string>({"main_frame"})},
{2, 5, "block", ".*", true},
};
// Requests:
// -/page_with_two_frames.html (Matching rule=1)
// -/subresources/script.js (Matching rule=[1,2] Winner=2)
// -/child_frame.html?frame=1 (Matching Rule=[1,2] Winner=2)
// -/subresources/script.js?frameId=1 (Source Frame was blocked)
// -/child_frame.html?frame=2 (Matching Rule=[1,2] Winner=2)
// -/subresources/script.js?frameId=2 (Source frame was blocked)
// Hence only the main-frame request goes through.
RunTest(rule_data, {requests[0]},
{requests[1], requests[2], requests[3], requests[4], requests[5]});
}
// TODO(crbug.com/40853402): Re-enable this test. It was disabled because of
// flakiness.
IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestAllowAllRequestsBrowserTest,
DISABLED_Test4) {
std::vector<RuleData> rule_data = {
{1, 6, "allowAllRequests", "page_with_two_frames\\.html", true,
std::vector<std::string>({"main_frame"})},
{2, 5, "block", "*", false},
};
// Requests:
// -/page_with_two_frames.html (Matching rule=1)
// -/subresources/script.js (Matching rule=[1,2] Winner=1)
// -/child_frame.html?frame=1 (Matching Rule=[1,2] Winner=1)
// -/subresources/script.js?frameId=1 (Matching Rule=[1,2] Winner=1)
// -/child_frame.html?frame=2 (Matching Rule=[1,2] Winner=1)
// -/subresources/script.js?frameId=2 (Matching Rule=[1,2] Winner=1)
// Hence all requests go through.
RunTest(rule_data,
{requests[0], requests[1], requests[2], requests[3], requests[4],
requests[5]},
{});
}
// TODO(crbug.com/40846422): Re-enable this test on MAC
#if BUILDFLAG(IS_MAC)
#define MAYBE_TestPostNavigationMatched DISABLED_TestPostNavigationMatched
#else
#define MAYBE_TestPostNavigationMatched TestPostNavigationMatched
#endif
IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestAllowAllRequestsBrowserTest,
MAYBE_TestPostNavigationMatched) {
std::vector<RuleData> rule_data = {
{1, 6, "allowAllRequests", "page_with_two_frames\\.html", true,
std::vector<std::string>({"main_frame"}),
std::vector<std::string>({"post"})},
{2, 5, "block", "*", false},
};
// Requests:
// -/page_with_two_frames.html (Matching rule=1)
// -/subresources/script.js (Matching rule=[1,2] Winner=1)
// -/child_frame.html?frame=1 (Matching Rule=[1,2] Winner=1)
// -/subresources/script.js?frameId=1 (Matching Rule=[1,2] Winner=1)
// -/child_frame.html?frame=2 (Matching Rule=[1,2] Winner=1)
// -/subresources/script.js?frameId=2 (Matching Rule=[1,2] Winner=1)
// Hence all requests go through.
RunTest(rule_data,
{requests[0], requests[1], requests[2], requests[3], requests[4],
requests[5]},
{}, true);
}
// TODO(crbug.com/40852913): Re-enable this test on MAC
#if BUILDFLAG(IS_MAC)
#define MAYBE_TestPostNavigationNotMatched DISABLED_TestPostNavigationNotMatched
#else
#define MAYBE_TestPostNavigationNotMatched TestPostNavigationNotMatched
#endif
IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestAllowAllRequestsBrowserTest,
MAYBE_TestPostNavigationNotMatched) {
std::vector<RuleData> rule_data = {
{1, 6, "allowAllRequests", "page_with_two_frames\\.html", true,
std::vector<std::string>({"main_frame"}),
std::vector<std::string>({"get"})},
{2, 5, "block", "*", false},
};
// Requests:
// -/page_with_two_frames.html (No matches)
// -/subresources/script.js (Matching rule 2)
// -/child_frame.html?frame=1 (Matching rule 2)
// -/subresources/script.js?frameId=1 (Matching rule 2)
// -/child_frame.html?frame=2 (Matching rule 2)
// -/subresources/script.js?frameId=2 (Matching rule 2)
// Hence requests are blocked.
RunTest(rule_data, {requests[0]},
{requests[1], requests[2], requests[3], requests[4], requests[5]},
true);
}
// Tests that when an extension is updated but loses the declarativeNetRequest
// permission, its dynamic ruleset is not enabled.
// TODO(crbug.com/391924202): Port to desktop Android once it supports packed
// extensions.
IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest_Packed,
UpdateRespectsPermission) {
set_config_flags(ConfigFlag::kConfig_HasBackgroundScript);
// Load an extension with no rulesets and add a dynamic rule.
ASSERT_NO_FATAL_FAILURE(LoadExtensionWithRulesets(
{} /* rulesets */, "ext" /* directory */, {} /* hosts */));
const ExtensionId& extension_id = last_loaded_extension_id();
AddDynamicRules(extension_id, {CreateGenericRule()});
VerifyPublicRulesetIds(last_loaded_extension(),
{dnr_api::DYNAMIC_RULESET_ID});
// Now update the extension such that it loses the declarativeNetRequest
// permission and manifest key.
set_config_flags(ConfigFlag::kConfig_HasBackgroundScript |
ConfigFlag::kConfig_OmitDeclarativeNetRequestPermission |
ConfigFlag::kConfig_OmitDeclarativeNetRequestKey);
ASSERT_NO_FATAL_FAILURE(UpdateLastLoadedExtension(
{} /* new_rulesets */, "new_dir" /* new_directory */, {} /* new_hosts */,
-1 /* expected_extensions_with_rulesets_count_change */,
false /* has_dynamic_ruleset */, false /* is_delayed_update */));
// Verify that the extension doesn't have any enabled rulesets since it lacks
// the declarativeNetRequest permission.
EXPECT_FALSE(ruleset_manager()->GetMatcherForExtension(extension_id));
// Now update the extension again but this time with the declarativeNetRequest
// permission. With the permission added back, its pre-update dynamic ruleset
// should be enabled again.
set_config_flags(ConfigFlag::kConfig_HasBackgroundScript);
ASSERT_NO_FATAL_FAILURE(UpdateLastLoadedExtension(
{} /* new_rulesets */, "new_dir2" /* new_directory */, {} /* new_hosts */,
1 /* expected_extensions_with_rulesets_count_change */,
true /* has_dynamic_ruleset */, false /* is_delayed_update */));
VerifyPublicRulesetIds(last_loaded_extension(),
{dnr_api::DYNAMIC_RULESET_ID});
}
#endif // !BUILDFLAG(IS_ANDROID)
// Test fixture to verify that host permissions for the request url and the
// request initiator are properly checked when redirecting requests. Loads an
// example.com url with four sub-frames named frame_[1..4] from hosts
// frame_[1..4].com. These subframes point to invalid sources. The initiator for
// these frames will be example.com. Loads an extension which redirects these
// sub-frames to a valid source. Verifies that the correct frames are redirected
// depending on the host permissions for the extension.
class DeclarativeNetRequestHostPermissionsBrowserTest
: public DeclarativeNetRequestBrowserTest {
public:
DeclarativeNetRequestHostPermissionsBrowserTest() = default;
DeclarativeNetRequestHostPermissionsBrowserTest(
const DeclarativeNetRequestHostPermissionsBrowserTest&) = delete;
DeclarativeNetRequestHostPermissionsBrowserTest& operator=(
const DeclarativeNetRequestHostPermissionsBrowserTest&) = delete;
protected:
struct FrameRedirectResult {
std::string child_frame_name;
bool expect_frame_redirected;
};
void LoadExtensionWithHostPermissions(const std::vector<std::string>& hosts) {
TestRule rule = CreateGenericRule();
rule.priority = kMinValidPriority;
rule.condition->url_filter = std::string("not_a_valid_child_frame.html");
rule.condition->resource_types = std::vector<std::string>({"sub_frame"});
rule.action->type = std::string("redirect");
rule.action->redirect.emplace();
rule.action->redirect->url =
embedded_test_server()->GetURL("foo.com", "/child_frame.html").spec();
ASSERT_NO_FATAL_FAILURE(
LoadExtensionWithRules({rule}, "test_extension", hosts));
}
void RunTests(const std::vector<FrameRedirectResult>& expected_results) {
ASSERT_EQ(4u, expected_results.size());
GURL url = embedded_test_server()->GetURL("example.com",
"/page_with_four_frames.html");
NavigateToURL(url);
ASSERT_TRUE(WasFrameWithScriptLoaded(GetPrimaryMainFrame()));
for (const auto& frame_result : expected_results) {
SCOPED_TRACE(base::StringPrintf("Testing child frame named %s",
frame_result.child_frame_name.c_str()));
content::RenderFrameHost* child =
GetFrameByName(frame_result.child_frame_name);
ASSERT_TRUE(child);
EXPECT_EQ(frame_result.expect_frame_redirected,
WasFrameWithScriptLoaded(child));
}
}
std::string GetMatchPatternForDomain(const std::string& domain) const {
return "*://*." + domain + ".com/*";
}
};
IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestHostPermissionsBrowserTest,
AllURLs1) {
// All frames should be redirected since the extension has access to all
// hosts.
ASSERT_NO_FATAL_FAILURE(LoadExtensionWithHostPermissions({"<all_urls>"}));
RunTests({{"frame_1", true},
{"frame_2", true},
{"frame_3", true},
{"frame_4", true}});
}
IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestHostPermissionsBrowserTest,
NoPermissions) {
// The extension has no host permissions. No frames should be redirected.
ASSERT_NO_FATAL_FAILURE(LoadExtensionWithHostPermissions({}));
RunTests({{"frame_1", false},
{"frame_2", false},
{"frame_3", false},
{"frame_4", false}});
}
IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestHostPermissionsBrowserTest,
SubframesRequireNoInitiatorPermissions) {
// The extension has access to requests to "frame_1.com" and "frame_2.com".
// These should be redirected. Note: extensions don't need access to the
// initiator of a navigation request to redirect it (See crbug.com/918137).
ASSERT_NO_FATAL_FAILURE(
LoadExtensionWithHostPermissions({GetMatchPatternForDomain("frame_1"),
GetMatchPatternForDomain("frame_2")}));
RunTests({{"frame_1", true},
{"frame_2", true},
{"frame_3", false},
{"frame_4", false}});
}
#if !BUILDFLAG(IS_ANDROID)
// Fixture to test the "resourceTypes" and "excludedResourceTypes" fields of a
// declarative rule condition.
// TODO(crbug.com/393191910): Port to desktop Android. These tests fail with
// no logging and no stack.
class DeclarativeNetRequestResourceTypeBrowserTest
: public DeclarativeNetRequestBrowserTest {
public:
DeclarativeNetRequestResourceTypeBrowserTest() = default;
DeclarativeNetRequestResourceTypeBrowserTest(
const DeclarativeNetRequestResourceTypeBrowserTest&) = delete;
DeclarativeNetRequestResourceTypeBrowserTest& operator=(
const DeclarativeNetRequestResourceTypeBrowserTest&) = delete;
protected:
// TODO(crbug.com/40508457): Add tests for "object", "ping", "other", "font",
// "csp_report".
enum ResourceTypeMask {
kNone = 0,
kSubframe = 1 << 0,
kStylesheet = 1 << 1,
kScript = 1 << 2,
kImage = 1 << 3,
kXHR = 1 << 4,
kMedia = 1 << 5,
kWebSocket = 1 << 6,
kAll = (1 << 7) - 1
};
struct TestCase {
std::string hostname;
int blocked_mask;
};
void RunTests(const std::vector<TestCase>& test_cases) {
// Start a web socket test server to test the websocket resource type.
net::EmbeddedTestServer websocket_test_server(
net::EmbeddedTestServer::TYPE_HTTP);
net::test_server::InstallDefaultWebSocketHandlers(&websocket_test_server);
ASSERT_TRUE(websocket_test_server.Start());
// The |websocket_url| will echo the message we send to it.
GURL websocket_url = net::test_server::GetWebSocketURL(
websocket_test_server, "/echo-with-no-extension");
auto execute_script = [](content::RenderFrameHost* frame,
const std::string& script) {
return content::EvalJs(frame, script).ExtractBool();
};
for (const auto& test_case : test_cases) {
GURL url = embedded_test_server()->GetURL(test_case.hostname,
"/subresources.html");
SCOPED_TRACE(base::StringPrintf("Testing %s", url.spec().c_str()));
ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), url));
ASSERT_EQ(content::PAGE_TYPE_NORMAL, GetPageType());
content::RenderFrameHost* frame = GetPrimaryMainFrame();
// sub-frame.
EXPECT_EQ(!(test_case.blocked_mask & kSubframe),
execute_script(frame, "!!window.frameLoaded;"));
// stylesheet
EXPECT_EQ(!(test_case.blocked_mask & kStylesheet),
execute_script(frame, "testStylesheet();"));
// script
EXPECT_EQ(!(test_case.blocked_mask & kScript),
execute_script(frame, "testScript();"));
// image
EXPECT_EQ(!(test_case.blocked_mask & kImage),
execute_script(frame, "testImage();"));
// xhr
EXPECT_EQ(!(test_case.blocked_mask & kXHR),
execute_script(frame, "testXHR();"));
// media
EXPECT_EQ(!(test_case.blocked_mask & kMedia),
execute_script(frame, "testMedia();"));
// websocket
EXPECT_EQ(!(test_case.blocked_mask & kWebSocket),
execute_script(
frame, base::StringPrintf("testWebSocket('%s');",
websocket_url.spec().c_str())));
}
}
// Loads an extension to test blocking different resource types.
void LoadExtension() {
struct {
std::string domain;
size_t id;
std::vector<std::string> resource_types;
std::vector<std::string> excluded_resource_types;
} rules_data[] = {
{"block_subframe.com", 1, {"sub_frame"}, {}},
{"block_stylesheet.com", 2, {"stylesheet"}, {}},
{"block_script.com", 3, {"script"}, {}},
{"block_image.com", 4, {"image"}, {}},
{"block_xhr.com", 5, {"xmlhttprequest"}, {}},
{"block_media.com", 6, {"media"}, {}},
{"block_websocket.com", 7, {"websocket"}, {}},
{"block_image_and_stylesheet.com", 8, {"image", "stylesheet"}, {}},
{"block_subframe_and_xhr.com", 11, {"sub_frame", "xmlhttprequest"}, {}},
{"block_all.com", 9, {}, {}},
{"block_all_but_xhr_and_script.com",
10,
{},
{"xmlhttprequest", "script"}},
};
std::vector<TestRule> rules;
for (const auto& rule_data : rules_data) {
TestRule rule = CreateGenericRule();
// The "resourceTypes" property (i.e. |rule.condition->resource_types|)
// should not be an empty list. It should either be omitted or be a non-
// empty list.
if (rule_data.resource_types.empty())
rule.condition->resource_types = std::nullopt;
else
rule.condition->resource_types = rule_data.resource_types;
rule.condition->excluded_resource_types =
rule_data.excluded_resource_types;
rule.id = rule_data.id;
rule.condition->domains = std::vector<std::string>({rule_data.domain});
// Don't specify the urlFilter, which should behaves the same as "*".
rule.condition->url_filter = std::nullopt;
rules.push_back(rule);
}
LoadExtensionWithRules(rules);
}
};
// These are split into two tests to prevent a timeout. See crbug.com/787957.
IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestResourceTypeBrowserTest, Test1) {
ASSERT_NO_FATAL_FAILURE(LoadExtension());
RunTests({{"block_subframe.com", kSubframe},
{"block_stylesheet.com", kStylesheet},
{"block_script.com", kScript},
{"block_image.com", kImage},
{"block_xhr.com", kXHR},
{"block_media.com", kMedia}});
}
IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestResourceTypeBrowserTest, Test2) {
ASSERT_NO_FATAL_FAILURE(LoadExtension());
RunTests({{"block_websocket.com", kWebSocket},
{"block_image_and_stylesheet.com", kImage | kStylesheet},
{"block_subframe_and_xhr.com", kSubframe | kXHR},
{"block_all.com", kAll},
{"block_all_but_xhr_and_script.com", kAll & ~kXHR & ~kScript},
{"block_none.com", kNone}});
}
#endif // !BUILDFLAG(IS_ANDROID)
class DeclarativeNetRequestSubresourceWebBundlesBrowserTest
: public DeclarativeNetRequestBrowserTest {
public:
DeclarativeNetRequestSubresourceWebBundlesBrowserTest() = default;
void SetUpOnMainThread() override {
ExtensionBrowserTest::SetUpOnMainThread();
CreateTempDir();
InitializeRulesetManagerObserver();
}
protected:
bool TryLoadScript(const std::string& script_src) {
content::WebContents* web_contents = 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 = 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_;
};
// Test for https://crbug.com/1355162.
// Ensure the following happens when DeclarativeNetRequest API blocks a
// WebBundle:
// - A request for the WebBundle fails.
// - A subresource request associated with the bundle fail.
// - A window.load is fired. In other words, any request shouldn't remain
// pending forever.
IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestSubresourceWebBundlesBrowserTest,
WebBundleRequestCanceled) {
// Add a rule to block the bundle.
TestRule rule = CreateGenericRule();
std::vector<TestRule> rules;
rule.id = kMinValidID;
rule.condition->url_filter = "web_bundle.wbn|";
rule.priority = 1;
rules.push_back(rule);
ASSERT_NO_FATAL_FAILURE(LoadExtensionWithRules(rules));
static constexpr char kPageHtml[] = R"(
<title>Loaded</title>
<body>
<script>
(async () => {
const window_load = new Promise((resolve) => {
window.addEventListener("load", () => {
resolve();
});
});
const wbn_url =
new URL('./web_bundle.wbn', location.href).toString();
const pass_js_url = new URL('./pass.js', location.href).toString();
const script_web_bundle = document.createElement('script');
script_web_bundle.type = 'webbundle';
script_web_bundle.textContent = JSON.stringify({
source: wbn_url,
resources: [pass_js_url]
});
const web_bundle_error = new Promise((resolve) => {
script_web_bundle.addEventListener("error", () => {
resolve();
});
});
document.body.appendChild(script_web_bundle);
const script_js = document.createElement('script');
script_js.src = pass_js_url;
const script_js_error = new Promise((resolve) => {
script_js.addEventListener("error", () => {
resolve();
});
});
document.body.appendChild(script_js);
await Promise.all([window_load, web_bundle_error, script_js_error]);
document.title = "success";
})();
</script>
</body>
)";
std::string web_bundle;
RegisterWebBundleRequestHandler("/web_bundle.wbn", &web_bundle);
RegisterRequestHandler("/test.html", "text/html", kPageHtml);
ASSERT_TRUE(embedded_test_server()->Start());
// Create a web bundle, which can be empty in this test.
web_package::WebBundleBuilder builder;
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 = GetActiveWebContents();
NavigateToURL(page_url);
EXPECT_EQ(page_url, web_contents->GetLastCommittedURL());
std::u16string expected_title = u"success";
content::TitleWatcher title_watcher(web_contents, expected_title);
EXPECT_EQ(expected_title, title_watcher.WaitAndGetTitle());
}
// Ensure DeclarativeNetRequest API can block the requests for the subresources
// inside the web bundle.
IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestSubresourceWebBundlesBrowserTest,
RequestCanceled) {
TestRule rule = CreateGenericRule();
std::vector<TestRule> rules;
rule.id = kMinValidID;
rule.condition->url_filter = "cancel.js|";
rule.condition->resource_types = std::vector<std::string>({"script"});
rule.priority = 1;
rules.push_back(rule);
ASSERT_NO_FATAL_FAILURE(LoadExtensionWithRules(rules));
static constexpr char kPageHtml[] = 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 script = document.createElement('script');
script.type = 'webbundle';
script.textContent = JSON.stringify({
source: wbn_url,
resources: [pass_js_url, cancel_js_url]
});
document.body.appendChild(script);
})();
</script>
</body>
)";
std::string web_bundle;
RegisterWebBundleRequestHandler("/web_bundle.wbn", &web_bundle);
RegisterRequestHandler("/test.html", "text/html", kPageHtml);
ASSERT_TRUE(embedded_test_server()->Start());
// 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"}}, "");
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 = GetActiveWebContents();
NavigateToURL(page_url);
EXPECT_EQ(page_url, web_contents->GetLastCommittedURL());
std::u16string expected_title = u"script loaded";
content::TitleWatcher title_watcher(web_contents, expected_title);
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_title, title_watcher.WaitAndGetTitle());
EXPECT_FALSE(TryLoadScript("cancel.js"));
}
// Ensure DeclarativeNetRequest API can block the requests for the subresources
// inside the web bundle whose URL is uuid-in-package:.
IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestSubresourceWebBundlesBrowserTest,
RequestCanceledUuidInPackageUrl) {
static constexpr char pass_js_url[] =
"uuid-in-package:fc80c15b-69e9-4a45-ab41-9c90d2b55976";
static constexpr char cancel_js_url[] =
"uuid-in-package:15d749ad-7d9f-49d9-94f7-83a866e7fef8";
TestRule rule = CreateGenericRule();
std::vector<TestRule> rules;
rule.id = kMinValidID;
rule.condition->url_filter = std::string(cancel_js_url) + "|";
rule.condition->resource_types = {"script"};
rule.priority = 1;
rules.push_back(rule);
ASSERT_NO_FATAL_FAILURE(LoadExtensionWithRules(rules));
static constexpr char kHtmlTemplate[] = R"(
<title>Loaded</title>
<body>
<script>
(() => {
const wbn_url =
new URL('./web_bundle.wbn', location.href).toString();
const pass_js_url = '%s';
const cancel_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]
});
document.body.appendChild(script);
})();
</script>
</body>
)";
const std::string page_html =
base::StringPrintf(kHtmlTemplate, pass_js_url, cancel_js_url);
std::string web_bundle;
RegisterWebBundleRequestHandler("/web_bundle.wbn", &web_bundle);
RegisterRequestHandler("/test.html", "text/html", page_html);
ASSERT_TRUE(embedded_test_server()->Start());
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"}}, "");
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 = GetActiveWebContents();
NavigateToURL(page_url);
EXPECT_EQ(page_url, web_contents->GetLastCommittedURL());
std::u16string expected_title = u"script loaded";
content::TitleWatcher title_watcher(web_contents, expected_title);
EXPECT_TRUE(TryLoadScript(pass_js_url));
// Check that the pass_js_url script in the web bundle is correctly loaded
// even when the extension with blocking handler intercepted the request.
EXPECT_EQ(expected_title, title_watcher.WaitAndGetTitle());
EXPECT_FALSE(TryLoadScript(cancel_js_url));
}
// Ensure DeclarativeNetRequest API can redirect the requests for the
// subresources inside the web bundle.
IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestSubresourceWebBundlesBrowserTest,
RequestRedirected) {
static constexpr 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(embedded_test_server()->Start());
// 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());
struct {
std::string url_filter;
std::string redirect_url_path;
} rules_data[] = {
{"redirect.js|", "/redirected.js"},
{"redirect_to_unlisted.js|", "/redirected_to_unlisted.js"},
{"redirect_to_server.js|", "/redirected_to_server.js"},
};
std::vector<TestRule> rules;
int rule_id = kMinValidID;
int rule_priority = 1;
for (const auto& rule_data : rules_data) {
TestRule rule = CreateGenericRule();
rule.id = rule_id++;
rule.priority = rule_priority++;
rule.condition->url_filter = rule_data.url_filter;
rule.condition->resource_types = std::vector<std::string>({"script"});
rule.action->type = "redirect";
rule.action->redirect.emplace();
rule.action->redirect->url =
embedded_test_server()->GetURL(rule_data.redirect_url_path).spec();
rules.push_back(rule);
}
ASSERT_NO_FATAL_FAILURE(LoadExtensionWithRules(
rules, "test_extension", {URLPattern::kAllUrlsPattern}));
GURL page_url = embedded_test_server()->GetURL("/test.html");
content::WebContents* web_contents = GetActiveWebContents();
NavigateToURL(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
// DeclarativeNetRequest API.
IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestSubresourceWebBundlesBrowserTest,
WebBundleRequestRedirected) {
std::string web_bundle;
RegisterWebBundleRequestHandler("/redirect.wbn", &web_bundle);
RegisterWebBundleRequestHandler("/redirected.wbn", &web_bundle);
ASSERT_TRUE(embedded_test_server()->Start());
// 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());
std::vector<TestRule> rules;
TestRule rule = CreateGenericRule();
rule.id = kMinValidID;
rule.priority = 1;
rule.condition->url_filter = "redirect.wbn|";
rule.condition->resource_types = std::vector<std::string>({"webbundle"});
rule.action->type = "redirect";
rule.action->redirect.emplace();
rule.action->redirect->url =
embedded_test_server()->GetURL("/redirected.wbn").spec();
rules.push_back(rule);
ASSERT_NO_FATAL_FAILURE(LoadExtensionWithRules(
rules, "test_extension", {URLPattern::kAllUrlsPattern}));
NavigateToURL(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));
}
#if !BUILDFLAG(IS_ANDROID)
class DeclarativeNetRequestGlobalRulesBrowserTest
: public DeclarativeNetRequestBrowserTest {
public:
DeclarativeNetRequestGlobalRulesBrowserTest() = default;
protected:
void VerifyExtensionAllocationInPrefs(
const ExtensionId& extension_id,
std::optional<int> expected_rules_count) {
int actual_rules_count = 0;
PrefsHelper helper(*ExtensionPrefs::Get(profile()));
bool has_allocated_rules_count =
helper.GetAllocatedGlobalRuleCount(extension_id, actual_rules_count);
EXPECT_EQ(expected_rules_count.has_value(), has_allocated_rules_count);
if (expected_rules_count.has_value())
EXPECT_EQ(*expected_rules_count, actual_rules_count);
}
void VerifyKeepExcessAllocation(const ExtensionId& extension_id,
bool expected_keep_allocation) {
PrefsHelper helper(*ExtensionPrefs::Get(profile()));
EXPECT_EQ(expected_keep_allocation,
helper.GetKeepExcessAllocation(extension_id));
}
private:
// Override the API guaranteed minimum to prevent a timeout on loading the
// extension.
base::AutoReset<int> guaranteed_minimum_override_ =
CreateScopedStaticGuaranteedMinimumOverrideForTesting(1);
// Similarly, override the global limit to prevent a timeout.
base::AutoReset<int> global_limit_override_ =
CreateScopedGlobalStaticRuleLimitOverrideForTesting(2);
};
using DeclarativeNetRequestGlobalRulesBrowserTest_Packed =
DeclarativeNetRequestGlobalRulesBrowserTest;
// Test that extensions with allocated global rules keep their allocations after
// the browser restarts.
// TODO(crbug.com/391924202): Port to desktop Android once packed extensions
// are supported.
IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestGlobalRulesBrowserTest_Packed,
PRE_GlobalRulesBrowserRestart) {
// This is not tested for unpacked extensions since the unpacked extension
// directory won't be persisted across browser restarts.
ASSERT_EQ(ExtensionLoadType::PACKED, GetLoadType());
// Sanity check that the extension can index and enable up to
// |rule_limit_override_| + |global_limit_override_| rules.
ASSERT_EQ(3, GetMaximumRulesPerRuleset());
ASSERT_NO_FATAL_FAILURE(
LoadExtensionWithRules({CreateGenericRule(1), CreateGenericRule(2)},
"extension_1", {} /* hosts */));
const ExtensionId first_extension_id = last_loaded_extension_id();
ASSERT_NO_FATAL_FAILURE(
LoadExtensionWithRules({CreateGenericRule(1), CreateGenericRule(2)},
"extension_2", {} /* hosts */));
const ExtensionId second_extension_id = last_loaded_extension_id();
std::vector<TestRulesetInfo> rulesets;
rulesets.emplace_back("ruleset_1", ToListValue({CreateGenericRule(1)}));
rulesets.emplace_back("ruleset_2", ToListValue({CreateGenericRule(2)}));
ASSERT_NO_FATAL_FAILURE(
LoadExtensionWithRulesets(rulesets, "extension_3", {} /* hosts */));
const Extension* third_extension = last_loaded_extension();
CompositeMatcher* composite_matcher =
ruleset_manager()->GetMatcherForExtension(third_extension->id());
ASSERT_TRUE(composite_matcher);
// Check that the third extension only has |ruleset_1| enabled.
EXPECT_THAT(GetPublicRulesetIDs(*third_extension, *composite_matcher),
UnorderedElementsAre("ruleset_1"));
// First and second extension should have 1 rule in the global pool, third
// extension should have none because one of its rulesets is not enabled since
// the global limit is reached.
VerifyExtensionAllocationInPrefs(first_extension_id, 1);
VerifyExtensionAllocationInPrefs(second_extension_id, 1);
VerifyExtensionAllocationInPrefs(third_extension->id(), std::nullopt);
}
// TODO(crbug.com/391924202): Port to desktop Android once packed extensions
// are supported.
IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestGlobalRulesBrowserTest_Packed,
GlobalRulesBrowserRestart) {
// This is not tested for unpacked extensions since the unpacked extension
// directory won't be persisted across browser restarts.
ASSERT_EQ(ExtensionLoadType::PACKED, GetLoadType());
// Sanity check that the extension can index and enable up to
// |rule_limit_override| + |global_limit_override| rules.
ASSERT_EQ(3, GetMaximumRulesPerRuleset());
PrefsHelper helper(*ExtensionPrefs::Get(profile()));
std::map<std::string, size_t> allocated_rule_counts;
std::map<std::string, const Extension*> extensions_by_name;
for (const auto& extension : extension_registry()->enabled_extensions()) {
extensions_by_name[extension->name()] = extension.get();
int allocated_rule_count = 0;
if (helper.GetAllocatedGlobalRuleCount(extension->id(),
allocated_rule_count)) {
DCHECK_GE(allocated_rule_count, 0);
allocated_rule_counts[extension->name()] = allocated_rule_count;
}
}
// Check that all three extensions have the same rulesets enabled as before
// the browser restart.
VerifyPublicRulesetIds(extensions_by_name["extension_1"],
{kDefaultRulesetID});
VerifyPublicRulesetIds(extensions_by_name["extension_2"],
{kDefaultRulesetID});
VerifyPublicRulesetIds(extensions_by_name["extension_3"], {"ruleset_1"});
EXPECT_THAT(allocated_rule_counts,
UnorderedElementsAre(std::make_pair("extension_1", 1),
std::make_pair("extension_2", 1)));
}
// Test that an extension will not have its allocation reclaimed on load if it
// is the first load after a packed update.
// TODO(crbug.com/391924202): Port to desktop Android once packed extensions
// are supported.
IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestGlobalRulesBrowserTest_Packed,
PackedUpdateAndReload) {
// This is not tested for unpacked extensions since the unpacked extension
// directory won't be persisted across browser restarts.
ASSERT_EQ(ExtensionLoadType::PACKED, GetLoadType());
// Load the extension with a background page so updateEnabledRulesets can be
// called.
set_config_flags(ConfigFlag::kConfig_HasBackgroundScript);
std::vector<TestRulesetInfo> rulesets;
rulesets.emplace_back(
"ruleset_1", ToListValue({CreateGenericRule(1), CreateGenericRule(2)}));
rulesets.emplace_back("ruleset_2", ToListValue({CreateGenericRule(3)}),
false /* enabled */);
ASSERT_NO_FATAL_FAILURE(
LoadExtensionWithRulesets(rulesets, "test_extension", {} /* hosts */));
// Check that the extension only has |ruleset_1| enabled.
VerifyPublicRulesetIds(last_loaded_extension(), {"ruleset_1"});
// There should be one rule allocated.
VerifyExtensionAllocationInPrefs(last_loaded_extension_id(), 1);
// Enable |ruleset_2| and verify the allocation.
ASSERT_NO_FATAL_FAILURE(
UpdateEnabledRulesets(last_loaded_extension_id(), {}, {"ruleset_2"}));
VerifyPublicRulesetIds(last_loaded_extension(), {"ruleset_1", "ruleset_2"});
VerifyExtensionAllocationInPrefs(last_loaded_extension_id(), 2);
// Update the extension. This should keep the allocated rule count in prefs
// but not the set of enabled rulesets.
UpdateLastLoadedExtension(
rulesets, "test_extension2", {} /* hosts */,
0 /* expected_extensions_with_rulesets_count_change */,
false /* has_dynamic_ruleset */, false /* is_delayed_update */);
VerifyPublicRulesetIds(last_loaded_extension(), {"ruleset_1"});
VerifyExtensionAllocationInPrefs(last_loaded_extension_id(), 2);
// Disable then enable the extension to trigger another extension load.
DisableExtension(last_loaded_extension_id());
WaitForExtensionsWithRulesetsCount(0);
EnableExtension(last_loaded_extension_id());
WaitForExtensionsWithRulesetsCount(1);
// Since this is the second load after an update, the unused allocation should
// be reclaimed.
VerifyExtensionAllocationInPrefs(last_loaded_extension_id(), 1);
}
// Tests that excess allocation is no longer kept after an update once the
// current allocation exceeds the allocation from before the update.
// TODO(crbug.com/391924202): Port to desktop Android once packed extensions
// are supported.
IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestGlobalRulesBrowserTest_Packed,
UpdateEnabledRulesetsAfterPackedUpdate) {
// This is not tested for unpacked extensions since the unpacked extension
// directory won't be persisted across browser restarts.
ASSERT_EQ(ExtensionLoadType::PACKED, GetLoadType());
// Load the extension with a background page so updateEnabledRulesets can be
// called.
set_config_flags(ConfigFlag::kConfig_HasBackgroundScript);
std::vector<TestRulesetInfo> rulesets;
rulesets.emplace_back("ruleset_1", ToListValue({CreateGenericRule(1)}));
rulesets.emplace_back("ruleset_2", ToListValue({CreateGenericRule(2)}),
false /* enabled */);
rulesets.emplace_back("big_ruleset",
ToListValue({CreateGenericRule(3), CreateGenericRule(4),
CreateGenericRule(5)}),
false /* enabled */);
ASSERT_NO_FATAL_FAILURE(
LoadExtensionWithRulesets(rulesets, "test_extension", {} /* hosts */));
// Enable |ruleset_2|.
ASSERT_NO_FATAL_FAILURE(
UpdateEnabledRulesets(last_loaded_extension_id(), {}, {"ruleset_2"}));
VerifyPublicRulesetIds(last_loaded_extension(), {"ruleset_1", "ruleset_2"});
// There should be one rule allocated.
VerifyExtensionAllocationInPrefs(last_loaded_extension_id(), 1);
// Update the extension. This should keep the allocated rule count in prefs
// but not the set of enabled rulesets.
UpdateLastLoadedExtension(
rulesets, "test_extension2", {} /* hosts */,
0 /* expected_extensions_with_rulesets_count_change */,
false /* has_dynamic_ruleset */, false /* is_delayed_update */);
VerifyPublicRulesetIds(last_loaded_extension(), {"ruleset_1"});
VerifyExtensionAllocationInPrefs(last_loaded_extension_id(), 1);
VerifyKeepExcessAllocation(last_loaded_extension_id(), true);
// Adding |big_ruleset| should fail right now, and should not change the
// allocation.
ASSERT_NO_FATAL_FAILURE(UpdateEnabledRulesetsAndFail(
last_loaded_extension_id(), {}, {"big_ruleset"},
kEnabledRulesetsRuleCountExceeded));
VerifyPublicRulesetIds(last_loaded_extension(), {"ruleset_1"});
VerifyExtensionAllocationInPrefs(last_loaded_extension_id(), 1);
VerifyKeepExcessAllocation(last_loaded_extension_id(), true);
// Removing |ruleset_1| should not change the allocation.
ASSERT_NO_FATAL_FAILURE(
UpdateEnabledRulesets(last_loaded_extension_id(), {"ruleset_1"}, {}));
VerifyPublicRulesetIds(last_loaded_extension(), {});
VerifyExtensionAllocationInPrefs(last_loaded_extension_id(), 1);
VerifyKeepExcessAllocation(last_loaded_extension_id(), true);
// Adding |big_ruleset| should succeed now, and should increase the allocation
// past the value from just before the update.
ASSERT_NO_FATAL_FAILURE(
UpdateEnabledRulesets(last_loaded_extension_id(), {}, {"big_ruleset"}));
VerifyPublicRulesetIds(last_loaded_extension(), {"big_ruleset"});
VerifyExtensionAllocationInPrefs(last_loaded_extension_id(), 2);
VerifyKeepExcessAllocation(last_loaded_extension_id(), false);
// Removing |big_ruleset| should now drop the allocation down to 0 since the
// excess allocation has been exceeded and no longer needs to be kept.
ASSERT_NO_FATAL_FAILURE(
UpdateEnabledRulesets(last_loaded_extension_id(), {"big_ruleset"}, {}));
VerifyPublicRulesetIds(last_loaded_extension(), {});
VerifyExtensionAllocationInPrefs(last_loaded_extension_id(), std::nullopt);
VerifyKeepExcessAllocation(last_loaded_extension_id(), false);
}
// Test that GetAvailableStaticRuleCount includes the excess unused allocation
// after an extension update.
// TODO(crbug.com/40883375): Deflake and re-enable.
// TODO(crbug.com/391924202): Port to desktop Android once packed extensions
// are supported.
IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestGlobalRulesBrowserTest_Packed,
DISABLED_GetAvailableStaticRuleCountAfterPackedUpdate) {
// This is not tested for unpacked extensions since the unpacked extension
// directory won't be persisted across browser restarts.
ASSERT_EQ(ExtensionLoadType::PACKED, GetLoadType());
// Load the extension with a background page so updateEnabledRulesets can be
// called.
set_config_flags(ConfigFlag::kConfig_HasBackgroundScript);
std::vector<TestRulesetInfo> rulesets;
rulesets.emplace_back("ruleset_1", ToListValue({CreateGenericRule(1)}));
rulesets.emplace_back("ruleset_2", ToListValue({CreateGenericRule(2)}));
rulesets.emplace_back("ruleset_3", ToListValue({CreateGenericRule(3)}),
false /* enabled */);
ASSERT_NO_FATAL_FAILURE(
LoadExtensionWithRulesets(rulesets, "test_extension", {} /* hosts */));
// Enable |ruleset_3|.
ASSERT_NO_FATAL_FAILURE(
UpdateEnabledRulesets(last_loaded_extension_id(), {}, {"ruleset_3"}));
VerifyPublicRulesetIds(last_loaded_extension(),
{"ruleset_1", "ruleset_2", "ruleset_3"});
// There should be two rules allocated.
VerifyExtensionAllocationInPrefs(last_loaded_extension_id(), 2);
// There should not be any more rules available.
EXPECT_EQ("0", GetAvailableStaticRuleCount(last_loaded_extension_id()));
// Update the extension. This should keep the allocated rule count in prefs
// but not the set of enabled rulesets.
UpdateLastLoadedExtension(
rulesets, "test_extension2", {} /* hosts */,
0 /* expected_extensions_with_rulesets_count_change */,
false /* has_dynamic_ruleset */, false /* is_delayed_update */);
VerifyPublicRulesetIds(last_loaded_extension(), {"ruleset_1", "ruleset_2"});
VerifyExtensionAllocationInPrefs(last_loaded_extension_id(), 2);
// Since there are two rules enabled, and one rule that's allocated but
// unused, there should be one rule available.
EXPECT_EQ("1", GetAvailableStaticRuleCount(last_loaded_extension_id()));
// Disabling |ruleset_1| and |ruleset_2| should not decrease the allocation,
// but should increase the number of rules available.
ASSERT_NO_FATAL_FAILURE(
UpdateEnabledRulesets(last_loaded_extension_id(), {"ruleset_2"}, {}));
VerifyPublicRulesetIds(last_loaded_extension(), {"ruleset_1"});
VerifyExtensionAllocationInPrefs(last_loaded_extension_id(), 2);
EXPECT_EQ("2", GetAvailableStaticRuleCount(last_loaded_extension_id()));
ASSERT_NO_FATAL_FAILURE(
UpdateEnabledRulesets(last_loaded_extension_id(), {"ruleset_1"}, {}));
VerifyPublicRulesetIds(last_loaded_extension(), {});
VerifyExtensionAllocationInPrefs(last_loaded_extension_id(), 2);
EXPECT_EQ("3", GetAvailableStaticRuleCount(last_loaded_extension_id()));
}
#endif // !BUILDFLAG(IS_ANDROID)
// Tests the "requestMethods" and "excludedRequestMethods" property of a
// declarative rule condition.
IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest,
BlockRequests_Methods) {
struct {
int id;
std::string url_filter;
std::vector<std::string> request_methods;
std::vector<std::string> excluded_request_methods;
} rules_data[] = {{1, "default", {}, {}},
{2, "included", {"head", "put", "other"}, {}},
{3, "excluded", {}, {"options", "patch", "other"}},
{4, "combination", {"get"}, {"put"}}};
std::vector<TestRule> rules;
for (const auto& rule_data : rules_data) {
TestRule rule = CreateGenericRule(rule_data.id);
rule.condition->url_filter = rule_data.url_filter;
// An empty list is not allowed for the "requestMethods" property.
if (!rule_data.request_methods.empty())
rule.condition->request_methods = rule_data.request_methods;
rule.condition->excluded_request_methods =
rule_data.excluded_request_methods;
rules.push_back(rule);
}
ASSERT_NO_FATAL_FAILURE(LoadExtensionWithRules(rules));
struct {
std::string path;
std::string expected_blocked_request_methods;
} test_cases[] = {
{"default", "DELETE,GET,HEAD,OPTIONS,PATCH,POST,PUT,UNKNOWN"},
{"included", "HEAD,PUT,UNKNOWN"},
{"excluded", "DELETE,GET,HEAD,POST,PUT"},
{"combination", "GET"}};
static constexpr char kPerformRequestWithAllMethodsScript[] = R"(
{
const allRequestMethods = ["DELETE", "GET", "HEAD", "OPTIONS", "PATCH",
"POST", "PUT", "UNKNOWN"];
const url = "/empty.html?%s";
let blockedMethods = [];
Promise.allSettled(
allRequestMethods.map(method =>
fetch(url, {method}).catch(() => { blockedMethods.push(method); })
)
).then(() => blockedMethods.sort().join());
}
)";
GURL url = embedded_test_server()->GetURL("abc.com", "/empty.html");
NavigateToURL(url);
content::RenderFrameHost* main_frame = GetPrimaryMainFrame();
for (const auto& test_case : test_cases) {
SCOPED_TRACE(base::StringPrintf("Path: %s", test_case.path.c_str()));
EXPECT_EQ(
test_case.expected_blocked_request_methods,
content::EvalJs(main_frame,
base::StringPrintf(kPerformRequestWithAllMethodsScript,
test_case.path.c_str())));
}
}
#if !BUILDFLAG(IS_ANDROID)
// Tests that the "requestMethods" and "excludedRequestMethods" properties of a
// rule condition are considered properly for WebSocket requests.
// TODO(crbug.com/371298229): Port to desktop Android. The RemoteTestServer
// fails to start with an assertion about `spawner_url_base_` being empty.
IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest,
BlockRequests_WebSocket) {
// Load an extension with some DNR rules that have different request method
// conditions.
std::vector<TestRule> rules;
TestRule rule1 = CreateGenericRule(1);
rule1.condition->url_filter = "default";
rules.push_back(rule1);
TestRule rule2 = CreateGenericRule(2);
rule2.condition->url_filter = "all_methods";
rule2.condition->request_methods = {"delete", "get", "head", "options",
"patch", "post", "put"};
rules.push_back(rule2);
TestRule rule3 = CreateGenericRule(3);
rule3.condition->url_filter = "some_methods";
rule3.condition->request_methods = {"get", "put"};
rules.push_back(rule3);
TestRule rule4 = CreateGenericRule(4);
rule4.condition->url_filter = "all_methods_excluded";
rule4.condition->excluded_request_methods = {
"delete", "get", "head", "options", "patch", "post", "put"};
rules.push_back(rule4);
TestRule rule5 = CreateGenericRule(5);
rule5.condition->url_filter = "some_methods_excluded";
rule5.condition->excluded_request_methods = {"get", "put"};
rules.push_back(rule5);
ASSERT_NO_FATAL_FAILURE(LoadExtensionWithRules(rules));
// Start a web socket test server.
net::SpawnedTestServer websocket_test_server(
net::SpawnedTestServer::TYPE_WS, net::GetWebSocketTestDataDirectory());
ASSERT_TRUE(websocket_test_server.Start());
std::string websocket_url =
websocket_test_server.GetURL("echo-with-no-extension").spec();
static constexpr char kOpenWebSocketsScript[] = R"(
{
const websocketUrl = "%s";
const testCases = ["default", "all_methods", "some_methods",
"all_methods_excluded", "some_methods_excluded"];
let blockedTestCases = [];
Promise.allSettled(
testCases.map(testCase =>
new Promise(resolve =>
{
let websocket = new WebSocket(websocketUrl + "?" + testCase);
websocket.addEventListener("open", event =>
{
websocket.close();
resolve();
});
websocket.addEventListener("error", event =>
{
blockedTestCases.push(testCase);
resolve();
});
})
)
).then(() => blockedTestCases.sort().join());
}
)";
content::RenderFrameHost* main_frame = GetPrimaryMainFrame();
EXPECT_EQ(
"all_methods_excluded,default,some_methods_excluded",
content::EvalJs(main_frame, base::StringPrintf(kOpenWebSocketsScript,
websocket_url.c_str())));
}
// TODO(crbug.com/393191910): Port to desktop Android. These tests fail with
// no logging and no stack.
class DeclarativeNetRequestWebTransportTest
: public DeclarativeNetRequestBrowserTest {
public:
DeclarativeNetRequestWebTransportTest() { webtransport_server_.Start(); }
void SetUpCommandLine(base::CommandLine* command_line) override {
DeclarativeNetRequestBrowserTest::SetUpCommandLine(command_line);
webtransport_server_.SetUpCommandLine(command_line);
}
protected:
content::WebTransportSimpleTestServer webtransport_server_;
};
// Tests that the "requestMethods" and "excludedRequestMethods" properties of a
// rule condition are considered properly for WebTransport requests.
IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestWebTransportTest, BlockRequests) {
ASSERT_TRUE(https_server()->Start());
// Load an extension with some rules that have different request method
// conditions.
std::vector<TestRule> rules;
// We need to prefix "echo" so that the server accepts it.
TestRule rule1 = CreateGenericRule(1);
rule1.condition->url_filter = "echo1_default";
rules.push_back(rule1);
TestRule rule2 = CreateGenericRule(2);
rule2.condition->url_filter = "echo2_include";
rule2.condition->request_methods = {"connect"};
rules.push_back(rule2);
TestRule rule4 = CreateGenericRule(3);
rule4.condition->url_filter = "echo3_exclude";
rule4.condition->excluded_request_methods = {"connect"};
rules.push_back(rule4);
ASSERT_NO_FATAL_FAILURE(LoadExtensionWithRules(rules));
NavigateToURL(https_server()->GetURL("/echo"));
static constexpr char kOpenWebTransportScript[] = R"((
async () =>
{
const testCases = ["echo1_default", "echo2_include", "echo3_exclude" ];
let blockedTestCases = [];
await Promise.allSettled(
testCases.map(testCase =>
new Promise(async (resolve) =>
{
try {
const transport = new WebTransport(
`https://localhost:%d/${testCase}`);
await transport.ready;
} catch (e) {
blockedTestCases.push(testCase);
}
resolve();
})
)
);
return blockedTestCases.sort().join();
}
)())";
content::RenderFrameHost* main_frame = GetPrimaryMainFrame();
EXPECT_EQ("echo1_default,echo2_include",
content::EvalJs(main_frame,
base::StringPrintf(
kOpenWebTransportScript,
webtransport_server_.server_address().port())));
}
#endif // !BUILDFLAG(IS_ANDROID)
// Tests that Protected Audience requests can have their headers modified by the
// declarativeNetRequest API.
IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest,
ProtectedAudienceNetworkRequestsModifyHeaders) {
privacy_sandbox::ScopedPrivacySandboxAttestations scoped_attestations(
privacy_sandbox::PrivacySandboxAttestations::CreateForTesting());
// Mark all Privacy Sandbox APIs as attested since the test case is testing
// behaviors not related to attestations.
privacy_sandbox::PrivacySandboxAttestations::GetInstance()
->SetAllPrivacySandboxAttestedForTesting(true);
static constexpr char kAddedHeaderName[] = "Header-Name";
static constexpr char kAddedHeaderValue[] = "Header-Value";
ASSERT_TRUE(https_server()->Start());
PrivacySandboxSettingsFactory::GetForProfile(profile())
->SetAllPrivacySandboxAllowedForTesting();
NavigateToURL(https_server()->GetURL("/interest_group/fenced_frame.html"));
GURL bidding_logic_url =
https_server()->GetURL("/interest_group/bidding_logic.js");
GURL bidding_signals_url =
https_server()->GetURL("/interest_group/bidding_signals.cbor");
GURL decision_logic_url =
https_server()->GetURL("/interest_group/decision_logic.js");
GURL scoring_signals_url =
https_server()->GetURL("/interest_group/scoring_signals.cbor");
GURL bidder_report_url = https_server()->GetURL("/echo?bidder_report");
GURL decision_report_url = https_server()->GetURL("/echo?decision_report");
// Set up a coordinator and server key for the Origin shared by the bidding
// and scoring signals URLs, so can use it as a trusted scoring signals URL.
// This test does not set up decoding the encrypted request or sending an
// encrypted response to it, since all it checks is that headers can be added
// to the request it makes.
const url::Origin kCoordinatorOrigin =
url::Origin::Create(GURL("https://coordinator.test"));
ConfigureTestPrivacySandboxCoordinatorKeys(
web_contents()
->GetBrowserContext()
->GetDefaultStoragePartition()
->GetInterestGroupManager(),
content::InterestGroupManager::TrustedServerAPIType::kTrustedKeyValue,
kCoordinatorOrigin, {https_server()->GetOrigin()});
// URL of the winning ad. Isn't actually tested anywhere in this test, but a
// fenced frame is navigated to it, so best to use a URL with known behavior.
// A random hostname will end up trying to connect to localhost, which could
// end up talking to some other server running locally.
GURL ad_url = https_server()->GetURL("/echo");
// Add an interest group.
EXPECT_EQ("done", content::EvalJs(web_contents(),
content::JsReplace(
R"(
(function() {
navigator.joinAdInterestGroup({
name: 'cars',
owner: $1,
biddingLogicURL: $2,
trustedBiddingSignalsURL: $3,
trustedBiddingSignalsCoordinator: $4,
userBiddingSignals: [],
ads: [{
renderURL: 'https://example.com/render',
metadata: {ad: 'metadata', here: [1, 2, 3]}
}]
}, /*joinDurationSec=*/ 300);
return 'done';
})();
)",
url::Origin::Create(bidding_logic_url),
bidding_logic_url, bidding_signals_url,
kCoordinatorOrigin)));
// Create an extension to add a header to all requests.
TestRule custom_response_header_rule = CreateModifyHeadersRule(
1 /* id */, 1 /* priority */, "*",
// request_headers
std::vector<TestHeaderInfo>(
{TestHeaderInfo(kAddedHeaderName, "set", kAddedHeaderValue)}),
std::nullopt);
// CreateModifyHeadersRule() applies to subframes only by default, so clear
// that.
custom_response_header_rule.condition->resource_types = std::nullopt;
ASSERT_NO_FATAL_FAILURE(
LoadExtensionWithRules({custom_response_header_rule}, "test_extension",
{URLPattern::kAllUrlsPattern}));
std::string run_auction_command = content::JsReplace(
R"(
(async function() {
let config = await navigator.runAdAuction({
seller: $1,
decisionLogicURL: $2,
interestGroupBuyers: [$1],
trustedScoringSignalsURL: $3,
trustedScoringSignalsCoordinator: $4,
});
document.querySelector('fencedframe').config =
new FencedFrameConfig(config);
return config;
})()
)",
url::Origin::Create(decision_logic_url), decision_logic_url,
scoring_signals_url, kCoordinatorOrigin);
// The auction should return a unique URN URL.
GURL ad_urn(
content::EvalJs(web_contents(), run_auction_command).ExtractString());
EXPECT_TRUE(ad_urn.SchemeIs(url::kUrnScheme));
// Wait to see both the report request of both worklets.
WaitForRequest(bidder_report_url);
WaitForRequest(decision_report_url);
// Clear observed URLs.
std::map<GURL, net::test_server::HttpRequest> requests =
GetAndResetRequestsToServer();
// Make sure the add headers rule was applied to all requests related to the
// auction.
for (const GURL& expected_url :
{bidding_logic_url, bidding_signals_url, decision_logic_url,
scoring_signals_url, bidder_report_url, decision_report_url}) {
auto request = requests.find(expected_url);
ASSERT_NE(request, requests.end());
auto added_header = request->second.headers.find(kAddedHeaderName);
ASSERT_NE(added_header, request->second.headers.end());
EXPECT_EQ(kAddedHeaderValue, added_header->second);
}
}
// Tests that Protected Audience requests can be blocked by the
// declarativeNetRequest API.
IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest,
ProtectedAudienceNetworkRequestsBlockRequests) {
privacy_sandbox::ScopedPrivacySandboxAttestations scoped_attestations(
privacy_sandbox::PrivacySandboxAttestations::CreateForTesting());
// Mark all Privacy Sandbox APIs as attested since the test case is testing
// behaviors not related to attestations.
privacy_sandbox::PrivacySandboxAttestations::GetInstance()
->SetAllPrivacySandboxAttestedForTesting(true);
ASSERT_TRUE(https_server()->Start());
PrivacySandboxSettingsFactory::GetForProfile(profile())
->SetAllPrivacySandboxAllowedForTesting();
NavigateToURL(https_server()->GetURL("/interest_group/fenced_frame.html"));
GURL bidding_logic_url =
https_server()->GetURL("/interest_group/bidding_logic.js");
GURL decision_logic_url =
https_server()->GetURL("/interest_group/decision_logic.js");
GURL bidder_report_url = https_server()->GetURL("/echo?bidder_report");
GURL decision_report_url = https_server()->GetURL("/echo?decision_report");
// URL of the winning ad. Isn't actually tested anywhere in this test, but a
// fenced frame is navigated to it, so best to use a URL with known behavior.
// A random hostname will end up trying to connect to localhost, which could
// end up talking to some other server running locally.
GURL ad_url = https_server()->GetURL("/echo");
// Add an interest group.
EXPECT_EQ("done", content::EvalJs(
web_contents(),
content::JsReplace(
R"(
(function() {
navigator.joinAdInterestGroup({
name: 'cars',
owner: $1,
biddingLogicURL: $2,
userBiddingSignals: [],
ads: [{
renderURL: 'https://example.com/render',
metadata: {ad: 'metadata', here: [1, 2, 3]}
}]
}, /*joinDurationSec=*/ 300);
return 'done';
})();
)",
url::Origin::Create(bidding_logic_url).Serialize(),
bidding_logic_url)));
std::string run_auction_command = content::JsReplace(
R"(
(async function() {
let config = await navigator.runAdAuction({
seller: $1,
decisionLogicURL: $2,
interestGroupBuyers: [$1],
});
document.querySelector('fencedframe').config =
new FencedFrameConfig(config);
return config;
})()
)",
url::Origin::Create(decision_logic_url).Serialize(),
decision_logic_url.spec());
// Add a rule to block the bidder's report URL.
TestRule block_report_rule = CreateGenericRule();
block_report_rule.condition->url_filter = bidder_report_url.spec() + "^";
block_report_rule.id = 1;
ASSERT_NO_FATAL_FAILURE(LoadExtensionWithRules(
{block_report_rule}, "test_extension2", {URLPattern::kAllUrlsPattern}));
// Run the auction.
GURL ad_urn = GURL(
content::EvalJs(web_contents(), run_auction_command).ExtractString());
EXPECT_TRUE(ad_urn.SchemeIs(url::kUrnScheme));
// Wait for the decision script's report URL to be requested.
WaitForRequest(decision_report_url);
// The bidder script should be blocked. Unfortunately, there's no way to wait
// for the bidder script to not be requested. Instead, just wait for an
// addition "tiny timeout" delay, and make sure it was not requested.
base::RunLoop run_loop;
base::SingleThreadTaskRunner::GetCurrentDefault()->PostDelayedTask(
FROM_HERE, run_loop.QuitClosure(), TestTimeouts::tiny_timeout());
run_loop.Run();
EXPECT_EQ(0u, GetAndResetRequestsToServer().count(bidder_report_url));
}
// Tests that if the declarativeNetRequest API tries to redirect Protected
// Audience requests, the request is blocked by the Protected Audience logic,
// which doesn't allow redirects, instead of being redirected.
IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest,
ProtectedAudienceNetworkRequestsBlockRedirect) {
privacy_sandbox::ScopedPrivacySandboxAttestations scoped_attestations(
privacy_sandbox::PrivacySandboxAttestations::CreateForTesting());
// Mark all Privacy Sandbox APIs as attested since the test case is testing
// behaviors not related to attestations.
privacy_sandbox::PrivacySandboxAttestations::GetInstance()
->SetAllPrivacySandboxAttestedForTesting(true);
ASSERT_TRUE(https_server()->Start());
PrivacySandboxSettingsFactory::GetForProfile(profile())
->SetAllPrivacySandboxAllowedForTesting();
NavigateToURL(https_server()->GetURL("/interest_group/fenced_frame.html"));
GURL bidding_logic_url =
https_server()->GetURL("/interest_group/bidding_logic.js");
GURL decision_logic_url =
https_server()->GetURL("/interest_group/decision_logic.js");
GURL bidder_report_url = https_server()->GetURL("/echo?bidder_report");
GURL decision_report_url = https_server()->GetURL("/echo?decision_report");
// Add an interest group.
EXPECT_EQ("done", content::EvalJs(
web_contents(),
content::JsReplace(
R"(
(function() {
navigator.joinAdInterestGroup({
name: 'cars',
owner: $1,
biddingLogicURL: $2,
userBiddingSignals: [],
ads: [{
renderURL: 'https://example.com/render',
metadata: {ad: 'metadata', here: [1, 2, 3]}
}]
}, /*joinDurationSec=*/ 300);
return 'done';
})();
)",
url::Origin::Create(bidding_logic_url).Serialize(),
bidding_logic_url)));
std::string run_auction_command = content::JsReplace(
R"(
(async function() {
let config = await navigator.runAdAuction({
seller: $1,
decisionLogicURL: $2,
interestGroupBuyers: [$1],
});
document.querySelector('fencedframe').config =
new FencedFrameConfig(config);
return config;
})()
)",
url::Origin::Create(decision_logic_url).Serialize(),
decision_logic_url.spec());
// Add an extension which redirects requests for the bidding script to a URL
// that serves an identical bidding script.
TestRule redirect_bidding_logic_rule = CreateGenericRule();
redirect_bidding_logic_rule.condition->url_filter =
bidding_logic_url.spec() + "^";
redirect_bidding_logic_rule.id = 2;
redirect_bidding_logic_rule.action->type = "redirect";
redirect_bidding_logic_rule.action->redirect.emplace();
redirect_bidding_logic_rule.action->redirect->url =
https_server()->GetURL("/interest_group/bidding_logic2.js").spec();
ASSERT_NO_FATAL_FAILURE(
LoadExtensionWithRules({redirect_bidding_logic_rule}, "test_extension3",
{URLPattern::kAllUrlsPattern}));
// Redirecting a bidder script, even to another bidder script, should cause
// the request to fail, which causes the entire auction to fail, since there's
// only one bidder script.
EXPECT_EQ(nullptr, content::EvalJs(web_contents(), run_auction_command));
}
#if !BUILDFLAG(IS_ANDROID)
// TODO(crbug.com/393191910): Port to desktop Android. These tests fail with
// no logging and no stack.
class DeclarativeNetRequestBackForwardCacheBrowserTest
: public DeclarativeNetRequestBrowserTest {
public:
DeclarativeNetRequestBackForwardCacheBrowserTest() {
feature_list_.InitWithFeaturesAndParameters(
content::GetDefaultEnabledBackForwardCacheFeaturesForTesting(
{{features::kBackForwardCache, {}}}),
content::GetDefaultDisabledBackForwardCacheFeaturesForTesting());
}
// Setups the back forward cache with one entry (a.com) and returns a
// RenderFrameDeletedObserver that watches for it being destroyed.
std::unique_ptr<content::RenderFrameDeletedObserver>
NavigateForBackForwardCache() {
GURL url_a(embedded_test_server()->GetURL("a.com", "/title1.html"));
GURL url_b(embedded_test_server()->GetURL("b.com", "/title1.html"));
// 1) Navigate to A.
content::RenderFrameHost* render_frame_host_a =
ui_test_utils::NavigateToURL(browser(), url_a);
auto delete_observer_render_frame_host_a =
std::make_unique<content::RenderFrameDeletedObserver>(
render_frame_host_a);
// 2) Navigate to B.
content::RenderFrameHost* render_frame_host_b =
ui_test_utils::NavigateToURL(browser(), url_b);
// Ensure that |render_frame_host_a| is in the cache.
EXPECT_FALSE(delete_observer_render_frame_host_a->deleted());
EXPECT_NE(render_frame_host_a, render_frame_host_b);
EXPECT_EQ(render_frame_host_a->GetLifecycleState(),
content::RenderFrameHost::LifecycleState::kInBackForwardCache);
return delete_observer_render_frame_host_a;
}
private:
base::test::ScopedFeatureList feature_list_;
};
// Ensure that Back Forward is cleared on adding dynamic rules.
IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBackForwardCacheBrowserTest,
BackForwardCacheClearedOnAddingDynamicRules) {
set_config_flags(ConfigFlag::kConfig_HasBackgroundScript);
// Now block requests to script.js.
TestRule rule = CreateGenericRule();
rule.condition->url_filter = std::string("script.js");
ASSERT_NO_FATAL_FAILURE(LoadExtensionWithRules({rule}));
auto bfcache_render_frame_host_delete_observer =
NavigateForBackForwardCache();
const ExtensionId& extension_id = last_loaded_extension_id();
// Add dynamic rule.
rule.condition->url_filter = std::string("dynamic.com");
ASSERT_NO_FATAL_FAILURE(AddDynamicRules(extension_id, {rule}));
// Expect that |render_frame_host_a| is destroyed as the cache would get
// cleared due to addition of new rule.
bfcache_render_frame_host_delete_observer->WaitUntilDeleted();
}
// Ensure that Back Forward is cleared on updating session rules.
IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBackForwardCacheBrowserTest,
BackForwardCacheClearedOnUpdatingSessionRules) {
set_config_flags(ConfigFlag::kConfig_HasBackgroundScript);
// Now block requests to script.js.
TestRule rule = CreateGenericRule();
rule.condition->url_filter = std::string("script.js");
ASSERT_NO_FATAL_FAILURE(LoadExtensionWithRules({rule}));
auto bfcache_render_frame_host_delete_observer =
NavigateForBackForwardCache();
const ExtensionId& extension_id = last_loaded_extension_id();
// Add session-scoped rule to block requests to "session.example".
rule.condition->url_filter = std::string("session.example");
ASSERT_NO_FATAL_FAILURE(UpdateSessionRules(extension_id, {}, {rule}));
// Expect that |render_frame_host_a| is destroyed as the cache would get
// cleared due to addition of new rule.
bfcache_render_frame_host_delete_observer->WaitUntilDeleted();
}
// Ensure that Back Forward is cleared on updating enabled rulesets.
IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBackForwardCacheBrowserTest,
BackForwardCacheClearedOnUpdatingEnabledRulesets) {
set_config_flags(ConfigFlag::kConfig_HasBackgroundScript);
std::vector<TestRulesetInfo> rulesets;
rulesets.emplace_back("ruleset_1", ToListValue({CreateGenericRule(1)}));
rulesets.emplace_back("ruleset_2", ToListValue({CreateGenericRule(2)}),
false /* enabled */);
ASSERT_NO_FATAL_FAILURE(
LoadExtensionWithRulesets(rulesets, "test_extension", {} /* hosts */));
auto bfcache_render_frame_host_delete_observer =
NavigateForBackForwardCache();
const ExtensionId& extension_id = last_loaded_extension_id();
// Enable |ruleset_2|.
ASSERT_NO_FATAL_FAILURE(
UpdateEnabledRulesets(extension_id, {}, {"ruleset_2"}));
// Expect that |render_frame_host_a| is destroyed as the cache would get
// cleared due to addition of new ruleset.
bfcache_render_frame_host_delete_observer->WaitUntilDeleted();
}
// Ensure that Back Forward is cleared on new extension.
IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBackForwardCacheBrowserTest,
BackForwardCacheClearedOnAddExtension) {
set_config_flags(ConfigFlag::kConfig_HasBackgroundScript);
auto bfcache_render_frame_host_delete_observer =
NavigateForBackForwardCache();
// Now block requests to script.js.
TestRule rule = CreateGenericRule();
rule.condition->url_filter = std::string("script.js");
ASSERT_NO_FATAL_FAILURE(LoadExtensionWithRules({rule}));
// Expect that |render_frame_host_a| is destroyed as the cache would get
// cleared due to addition of new rule.
bfcache_render_frame_host_delete_observer->WaitUntilDeleted();
}
// TODO(crbug.com/393191910): Port to desktop Android. These tests fail with
// no logging and no stack.
class DeclarativeNetRequestControllableResponseTest
: public DeclarativeNetRequestBrowserTest {
public:
DeclarativeNetRequestControllableResponseTest() = default;
void SetUpOnMainThread() override {
// The controllable response handler needs to be set up first before the
// test server can be started, which is why the SetUpOnMainThread from the
// super class which starts the test server is called afterwards here.
controllable_http_response_.emplace(embedded_test_server(),
"/pages_with_script/index.html");
DeclarativeNetRequestBrowserTest::SetUpOnMainThread();
}
protected:
net::test_server::ControllableHttpResponse& controllable_http_response() {
return *controllable_http_response_;
}
private:
std::optional<net::test_server::ControllableHttpResponse>
controllable_http_response_;
};
// Test that DNR actions from an extension are cleaned up when the extension is
// disabled. This fixes a crash/bug where DNR actions such as modifyHeaders
// which are created on the OnBeforeRequest phase when an extension was enabled
// are supposed to take effect in a later request stage but the extension may no
// longer be enabled at that point.
// Regression for crbug.com/40072083 which would've caused a crash in this test.
IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestControllableResponseTest,
EraseActionsOnExtensionDisabled) {
// Create an extension with a rule that modifies response headers. This
// extension will match its rule during OnBeforeRequest but the rule would not
// be applied until OnHeadersReceived which is after when the request is sent
// and the response has started.
TestRule headers_rule = CreateModifyHeadersRule(
kMinValidID, kMinValidPriority, "google.com", std::nullopt,
std::vector<TestHeaderInfo>(
{TestHeaderInfo("resp-header", "append", "resp-value")}));
headers_rule.condition->resource_types =
std::vector<std::string>({"main_frame"});
ASSERT_NO_FATAL_FAILURE(LoadExtensionWithRules(
{headers_rule}, "extension_1", {URLPattern::kAllUrlsPattern}));
const ExtensionId& extension_id = last_loaded_extension_id();
const GURL page_url = embedded_test_server()->GetURL(
"google.com", "/pages_with_script/index.html");
ui_test_utils::NavigateToURLWithDisposition(
browser(), page_url, WindowOpenDisposition::NEW_FOREGROUND_TAB,
ui_test_utils::BROWSER_TEST_WAIT_FOR_TAB);
controllable_http_response().WaitForRequest();
content::WebContents* web_contents =
browser()->tab_strip_model()->GetActiveWebContents();
controllable_http_response().Send(net::HTTP_OK, "text/html",
"<html>Hello, World!</html>");
// Disable the extension after the response has been sent but before the
// request has finished.
DisableExtension(extension_id);
controllable_http_response().Done();
// Block until the web contents have been fully loaded to be certain that the
// web request event router finishes processing all events after the request
// has finished, such as OnHeadersReceived, and that the extension will be
// disabled at that point. The test should not crash at this point.
// TODO(crbug.com/40072083): Follow up with verifying the values of response
// headers. This may require initiating a request from a JS script injected
// into the page.
ASSERT_TRUE(content::WaitForLoadStop(web_contents));
EXPECT_FALSE(extension_registrar()->IsExtensionEnabled(extension_id));
}
#endif // !BUILDFLAG(IS_ANDROID)
class DNRMatchResponseHeadersBrowserTest
: public DeclarativeNetRequestBrowserTest {
public:
DNRMatchResponseHeadersBrowserTest() {
scoped_feature_list_.InitAndEnableFeature(
extensions_features::kDeclarativeNetRequestResponseHeaderMatching);
}
private:
// TODO(crbug.com/40727004): Once feature is launched to stable and feature
// flag can be removed, replace usages of this test class with just
// DeclarativeNetRequestBrowserTest.
base::test::ScopedFeatureList scoped_feature_list_;
ScopedCurrentChannel current_channel_override_{version_info::Channel::DEV};
};
// Test that requests matching rules' response header conditions will be
// blocked.
IN_PROC_BROWSER_TEST_P(DNRMatchResponseHeadersBrowserTest, BlockRequests) {
struct {
std::string filter;
int id;
std::string type;
std::vector<TestHeaderCondition> response_header_condition;
} rules_data[] = {
// A rule that allows all requests to setcookie.com if the set-cookie
// header is present with value "cookie=oreo".
{"setcookie.com", 1, "allow",
std::vector<TestHeaderCondition>(
{TestHeaderCondition("set-cookie", {"cookie=oreo"}, {})})},
// A rule that blocks all requests to setcookie.com if the set-cookie
// header is present. Note that if both this and the allow rule above
// matches a request, the allow rule has higher priority and will override
// this rule due to its action type.
{"setcookie.com", 2, "block",
std::vector<TestHeaderCondition>(
{TestHeaderCondition("set-cookie", {}, {})})},
};
// Load the extension.
std::vector<TestRule> rules;
for (const auto& rule_data : rules_data) {
TestRule rule = CreateGenericRule(rule_data.id);
rule.action->type = rule_data.type;
rule.condition->url_filter = rule_data.filter;
rule.condition->resource_types = std::vector<std::string>({"main_frame"});
rule.condition->response_headers = rule_data.response_header_condition;
rules.push_back(std::move(rule));
}
ASSERT_NO_FATAL_FAILURE(LoadExtensionWithRules(std::move(rules)));
struct {
std::string hostname;
std::string path;
bool expect_main_frame_loaded;
} test_cases[] = {
// First test case does not have a set-cookie header and will not match
// with any rules.
{"setcookie.com", "/pages_with_script/index.html", true},
// Second test case will be blocked as it matches with the block rule with
// id 2.
{"setcookie.com", "/set-cookie?cookie=sugar", false},
// Third test case will not be blocked since it matches with the allow
// rule with id 1 which has higher "priority" than the block rule due to
// its action type.
{"setcookie.com", "/set-cookie?cookie=oreo", true}};
// Verify that the extension correctly intercepts network requests.
for (const auto& test_case : test_cases) {
GURL url =
embedded_test_server()->GetURL(test_case.hostname, test_case.path);
SCOPED_TRACE(base::StringPrintf("Testing %s", url.spec().c_str()));
content::TestNavigationObserver nav_observer(web_contents());
NavigateToURL(url);
content::PageType expected_page_type = test_case.expect_main_frame_loaded
? content::PAGE_TYPE_NORMAL
: content::PAGE_TYPE_ERROR;
EXPECT_EQ(expected_page_type, GetPageType());
auto expected_code = test_case.expect_main_frame_loaded
? net::OK
: net::ERR_BLOCKED_BY_CLIENT;
EXPECT_EQ(expected_code, nav_observer.last_net_error_code());
}
}
// Ensures that any <img> elements blocked by the API are collapsed based on
// response header matching.
IN_PROC_BROWSER_TEST_P(DNRMatchResponseHeadersBrowserTest, ImageCollapsed) {
// Loads a page with an image and returns whether the image was collapsed.
auto is_image_collapsed = [this](const std::string& host_name) {
NavigateToURL(embedded_test_server()->GetURL(host_name, "/image.html"));
EXPECT_EQ(content::PAGE_TYPE_NORMAL, GetPageType());
const std::string script = "!!window.imageCollapsed;";
return content::EvalJs(web_contents(), script).ExtractBool();
};
// Initially the image shouldn't be collapsed.
EXPECT_FALSE(is_image_collapsed("matchheader.com"));
EXPECT_FALSE(is_image_collapsed("matchnoheader.com"));
// Load an extension which blocks all images on matchheader.com if there
// exists a set-cookie header, and all on matchnoheaders.com if there is no
// set-cookie header. Note that the image.html path will not have a set-cookie
// header.
TestRule match_header_rule = CreateGenericRule(kMinValidID);
match_header_rule.condition->url_filter = "matchheader.com";
match_header_rule.condition->resource_types =
std::vector<std::string>({"image"});
match_header_rule.condition->response_headers =
std::vector<TestHeaderCondition>(
{TestHeaderCondition("set-cookie", {}, {})});
TestRule match_no_header_rule = CreateGenericRule(kMinValidID + 1);
match_no_header_rule.condition->url_filter = "matchnoheader.com";
match_no_header_rule.condition->resource_types =
std::vector<std::string>({"image"});
match_no_header_rule.condition->excluded_response_headers =
std::vector<TestHeaderCondition>(
{TestHeaderCondition("set-cookie", {}, {})});
std::vector<TestRule> rules;
rules.push_back(std::move(match_header_rule));
rules.push_back(std::move(match_no_header_rule));
ASSERT_NO_FATAL_FAILURE(LoadExtensionWithRules(std::move(rules)));
// Verify that only `match_no_header_rule` will match the request and cause
// the image to be collapsed.
EXPECT_FALSE(is_image_collapsed("matchheader.com"));
EXPECT_TRUE(is_image_collapsed("matchnoheader.com"));
}
// Test that requests can be redirected and upgraded based on response headers.
IN_PROC_BROWSER_TEST_P(DNRMatchResponseHeadersBrowserTest, RedirectAndUpgrade) {
GURL match_header_url = embedded_test_server()->GetURL(
"matchheader.com", "/pages_with_script/index.html");
GURL denied_url = embedded_test_server()->GetURL(
"denied.com", "/pages_with_script/index.html");
GURL upgraded_url = embedded_test_server()->GetURL(
"upgraded.com", "/pages_with_script/index.html");
struct {
std::string filter;
int id;
int priority;
std::string type;
std::optional<std::string> redirect_url;
std::optional<std::vector<TestHeaderCondition>> response_header_condition;
} rules_data[] = {
// A rule for requests made to "matchheader.com" which redirects to
// `denied_url` if a set-cookie header is present but its value is not
// equal to "upgrade-token=valid".
{"matchheader.com", 1, kMinValidPriority, "redirect", denied_url.spec(),
std::vector<TestHeaderCondition>(
{TestHeaderCondition("set-cookie", {}, {"upgrade-token=valid"})})},
// A rule for requests made to "matchheader.com" which upgrades from HTTP
// to HTTPS if a set-cookie header is present with a value of
// "upgrade-token=valid".
{"matchheader.com", 2, kMinValidPriority, "upgradeScheme", std::nullopt,
std::vector<TestHeaderCondition>(
{TestHeaderCondition("set-cookie", {"upgrade-token=valid"}, {})})},
// A rule which redirects all URLs with https scheme to `upgraded_url`.
// Used to test if requests have been upgraded.
// TODO(kelvinjiang): See if we can eliminate this rule by using
// https_server().
{"|https*", 3, kMinValidPriority + 100, "redirect", upgraded_url.spec(),
std::nullopt}};
// Load the extension.
std::vector<TestRule> rules;
for (const auto& rule_data : rules_data) {
TestRule rule = CreateGenericRule(rule_data.id);
rule.action->type = rule_data.type;
rule.priority = rule_data.priority;
rule.condition->url_filter = rule_data.filter;
rule.condition->resource_types = std::vector<std::string>({"main_frame"});
if (rule_data.redirect_url) {
rule.action->redirect.emplace();
rule.action->redirect->url = rule_data.redirect_url;
}
if (rule_data.response_header_condition) {
rule.condition->response_headers = rule_data.response_header_condition;
}
rules.push_back(std::move(rule));
}
ASSERT_NO_FATAL_FAILURE(LoadExtensionWithRules(
rules, "test_extension", {URLPattern::kAllUrlsPattern}));
struct {
std::string hostname;
std::string path;
GURL expected_final_url;
} test_cases[] = {
// Test a request that does not have a set-cookie header, so no rules
// match and a redirect does not happen.
{"matchheader.com", "/pages_with_script/index.html", match_header_url},
// Test a request that does not have a "valid" upgrade token cookie, so it
// gets redirected.
{"matchheader.com", "/set-cookie?upgrade-token=other", denied_url},
// Test a request that has a "valid" upgrade token that will match with
// the upgrade rule with id 2: HTTPS requests can be verified in this
// testing environment by redirecting them to `upgraded_url`.
{"matchheader.com", "/set-cookie?upgrade-token=valid", upgraded_url},
};
for (const auto& test_case : test_cases) {
GURL url =
embedded_test_server()->GetURL(test_case.hostname, test_case.path);
SCOPED_TRACE(base::StringPrintf("Testing %s", url.spec().c_str()));
NavigateToURL(url);
EXPECT_EQ(content::PAGE_TYPE_NORMAL, GetPageType());
const GURL& final_url = web_contents()->GetLastCommittedURL();
EXPECT_EQ(test_case.expected_final_url, final_url);
}
}
// Test interactions between rules that match in the onBeforeRequest phase vs
// the onHeadersReceived phase.
IN_PROC_BROWSER_TEST_P(DNRMatchResponseHeadersBrowserTest,
DifferentRequestPhaseRuleInteractions) {
GURL redirected_url = embedded_test_server()->GetURL(
"redirected.com", "/pages_with_script/index.html");
struct {
std::string filter;
int id;
int priority;
std::string type;
std::optional<std::string> redirect_url = std::nullopt;
std::optional<std::vector<TestHeaderCondition>>
excluded_response_header_condition = std::nullopt;
} rules_data[] = {
// For google.com, there is a block rule in onBeforeRequest and a redirect
// rule in onHeadersReceived. The block rule should take precedence even
// though the redirect rule has higher priority, because
// the block rule will block the request in an earlier request stage than
// when the redirect rule will be matched.
{"google.com", 1, kMinValidPriority, "block"},
{"google.com", 2, kMinValidPriority + 10, "redirect",
redirected_url.spec(),
std::vector<TestHeaderCondition>(
{TestHeaderCondition("nonsense-header", {}, {})})},
// For example.com, there is a redirect rule in onBeforeRequest and a
// block rule in onHeadersReceived. The redirect rule should take
// precedence because it redirects the request in an earlier request stage
// than when the block rule would be matched.
{"example.com", 3, kMinValidPriority, "redirect", redirected_url.spec()},
{"example.com", 4, kMinValidPriority + 10, "block", std::nullopt,
std::vector<TestHeaderCondition>(
{TestHeaderCondition("nonsense-header", {}, {})})},
// For abc.com, there is an allow rule in onBeforeRequest and a block rule
// in onHeadersReceived. The block rule should take precedence because its
// priority exceeds that of the allow rule's.
{"abc.com", 5, kMinValidPriority, "allow"},
{"abc.com", 6, kMinValidPriority + 10, "block", std::nullopt,
std::vector<TestHeaderCondition>(
{TestHeaderCondition("nonsense-header", {}, {})})},
// For def.com, there is an allow rule in onBeforeRequest and a block rule
// in onHeadersReceived. The allow rule should take precedence because its
// priority exceeds that of the block rule's even though the allow rule is
// matched in an earlier request stage.
{"def.com", 7, kMinValidPriority + 10, "allow"},
{"def.com", 8, kMinValidPriority, "block", std::nullopt,
std::vector<TestHeaderCondition>(
{TestHeaderCondition("nonsense-header", {}, {})})},
// For ghi.com, there is a block rule in onBeforeRequest and an allow rule
// with a higher priority in onHeadersReceived. Any request to ghi.com
// should be blocked because there is enough info to match the block rule
// in onBeforeRequest, without the request ever continuing onto later
// stages.
{"ghi.com", 9, kMinValidPriority, "block"},
{"ghi.com", 10, kMinValidPriority + 10, "allow", std::nullopt,
std::vector<TestHeaderCondition>(
{TestHeaderCondition("nonsense-header", {}, {})})},
};
// Load the extension.
std::vector<TestRule> rules;
for (const auto& rule_data : rules_data) {
TestRule rule = CreateGenericRule(rule_data.id);
rule.priority = rule_data.priority;
rule.action->type = rule_data.type;
rule.condition->url_filter = rule_data.filter;
rule.condition->resource_types = std::vector<std::string>({"main_frame"});
if (rule_data.redirect_url) {
rule.action->redirect.emplace();
rule.action->redirect->url = rule_data.redirect_url;
}
if (rule_data.excluded_response_header_condition) {
rule.condition->excluded_response_headers =
rule_data.excluded_response_header_condition;
}
rules.push_back(std::move(rule));
}
ASSERT_NO_FATAL_FAILURE(LoadExtensionWithRules(
rules, "test_extension", {URLPattern::kAllUrlsPattern}));
auto get_url = [this](const std::string& hostname) {
return embedded_test_server()->GetURL(hostname,
"/pages_with_script/index.html");
};
GURL google_url = embedded_test_server()->GetURL(
"google.com", "/pages_with_script/index.html");
GURL example_url = embedded_test_server()->GetURL(
"example.com", "/pages_with_script/index.html");
struct {
std::string hostname;
std::string path;
bool expect_main_frame_loaded;
GURL expected_final_url;
} test_cases[] = {
// The request should be blocked since rule with id 1 should take action
// in the onBeforeRequest stage and rule with id 2 should never be
// matched.
{"google.com", "/pages_with_script/index.html", false, google_url},
// The request should be redirected since rule with id 3 should take
// action in the onBeforeRequest stage and rule with id 4 should never be
// matched.
{"example.com", "/pages_with_script/index.html", true, redirected_url},
// The request should be blocked since the block rule with id 6 has a
// higher priority than the allow rule with id 5 even though both rules
// match.
{"abc.com", "/pages_with_script/index.html", false, get_url("abc.com")},
// The request should not be blocked since the allow rule with id 7 has a
// higher priority than the block rule with id 8 which prevents the block
// rule from taking effect.
{"def.com", "/pages_with_script/index.html", true, get_url("def.com")},
// The request should be blocked since the block rule with id 9 blocks the
// request after matching with it in the onBeforeRequest stage, so it's
// never sent and won't enter subsequent request stages which contain the
// allow rule with id 10.
{"ghi.com", "/pages_with_script/index.html", false, get_url("ghi.com")},
};
// Verify that the extension correctly intercepts network requests.
for (const auto& test_case : test_cases) {
GURL url =
embedded_test_server()->GetURL(test_case.hostname, test_case.path);
SCOPED_TRACE(base::StringPrintf("Testing %s", url.spec().c_str()));
NavigateToURL(url);
content::PageType expected_page_type = test_case.expect_main_frame_loaded
? content::PAGE_TYPE_NORMAL
: content::PAGE_TYPE_ERROR;
EXPECT_EQ(expected_page_type, GetPageType());
const GURL& final_url = web_contents()->GetLastCommittedURL();
EXPECT_EQ(test_case.expected_final_url, final_url);
}
}
#if !BUILDFLAG(IS_ANDROID)
// Test that frames where response header matched allowAllRequests rules will
// prevent lower priority matched rules from taking action on requests made
// under these frames.
// TODO(crbug.com/393191910): Port to desktop Android. This test fails with
// no logging and no stack.
IN_PROC_BROWSER_TEST_P(DNRMatchResponseHeadersBrowserTest, AllowAllRequests) {
std::vector<TestHeaderCondition> blank_header_condition =
std::vector<TestHeaderCondition>(
{TestHeaderCondition("nonsense-header", {}, {})});
struct RuleData {
int id;
int priority;
std::string action_type;
std::string filter;
bool is_regex_rule = false;
std::optional<std::vector<std::string>> resource_types = std::nullopt;
std::optional<std::vector<TestHeaderCondition>>
excluded_response_header_condition = std::nullopt;
} rule_data[] = {
// Create 3 allowAllRequests rules:
// One with priority 3 that matches the main frame, in the onBeforeRequest
// stage.
{1, 3, "allowAllRequests", "page_with_two_frames.html", false,
std::vector<std::string>({"main_frame"})},
// One with priority 5 that matches both frame 1 and 2, in the
// onHeadersReceived stage.
{2, 5, "allowAllRequests", "frame=(1|2)", true,
std::vector<std::string>({"sub_frame"}), blank_header_condition},
// One with priority 7 that matches frame 2, in the onBeforeRequest stage.
{3, 7, "allowAllRequests", "frame=2", true,
std::vector<std::string>({"sub_frame"})},
// Create 3 block rules, each blocking only a particular image file, with
// different priorities.
{4, 2, "block", "image.png", true, std::vector<std::string>({"image"})},
{5, 4, "block", "image_2.png", true, std::vector<std::string>({"image"})},
{6, 6, "block", "image_3.png", true, std::vector<std::string>({"image"})},
};
std::vector<TestRule> rules;
for (const auto& rule : rule_data) {
TestRule test_rule = CreateGenericRule();
test_rule.id = rule.id;
test_rule.priority = rule.priority;
test_rule.action->type = rule.action_type;
test_rule.condition->url_filter.reset();
if (rule.is_regex_rule) {
test_rule.condition->regex_filter = rule.filter;
} else {
test_rule.condition->url_filter = rule.filter;
}
test_rule.condition->resource_types = rule.resource_types;
if (rule.excluded_response_header_condition) {
test_rule.condition->excluded_response_headers =
rule.excluded_response_header_condition;
}
rules.push_back(std::move(test_rule));
}
ASSERT_NO_FATAL_FAILURE(LoadExtensionWithRules(std::move(rules)));
// Navigate to a page with two sub frames.
GURL page_url = embedded_test_server()->GetURL("example.com",
"/page_with_two_frames.html");
NavigateToURL(page_url);
// Attempts to add an image element for the image denoted by `image_path` to
// the specified `frame`. Returns true if the image was successfully added and
// loaded and false otherwise (e.g. if the image was not loaded/collapsed) if
// it was blocked by a DNR rule.
auto test_image_added = [](content::RenderFrameHost* frame,
const std::string& image_path) {
const char kTestImageScript[] = R"(
var img = document.createElement('img');
new Promise(resolve => {
img.addEventListener('load', () => {
resolve(true);
});
img.addEventListener('error', () => {
resolve(false);
});
img.src = '%s';
document.body.appendChild(img);
});
)";
return content::EvalJs(
frame, base::StringPrintf(kTestImageScript, image_path.c_str()))
.ExtractBool();
};
// Attempt to add images onto the main frame. Only `image.png` should be added
// since the allowAllRequests rule with id 1 exceeds the priority of the block
// rule for `image.png`.
content::RenderFrameHost* main_frame = GetPrimaryMainFrame();
EXPECT_TRUE(test_image_added(main_frame, "subresources/image.png"));
EXPECT_FALSE(test_image_added(main_frame, "subresources/image_2.png"));
EXPECT_FALSE(test_image_added(main_frame, "subresources/image_3.png"));
// Attempt to add images onto `frame_1`. `image.png` and `image_2.png` should
// be added since the max priority matching allowAllRequests rule for
// `frame_1` has id 2 (it "wins" over the rule with id 1 that has a lower
// priority), and its priority exceeds that of the block rules for `image.png`
// and `image_2.png`.
content::RenderFrameHost* frame_1 = GetFrameByName("frame1");
EXPECT_TRUE(test_image_added(frame_1, "subresources/image.png"));
EXPECT_TRUE(test_image_added(frame_1, "subresources/image_2.png"));
EXPECT_FALSE(test_image_added(frame_1, "subresources/image_3.png"));
// Attempt to add images onto `frame_2`. All 3 images should be loaded since
// the max priority allowAllRequests rule for this frame out-prioritizes all
// block rules.
content::RenderFrameHost* frame_2 = GetFrameByName("frame2");
EXPECT_TRUE(test_image_added(frame_2, "subresources/image.png"));
EXPECT_TRUE(test_image_added(frame_2, "subresources/image_2.png"));
EXPECT_TRUE(test_image_added(frame_2, "subresources/image_3.png"));
}
#endif // !BUILDFLAG(IS_ANDROID)
// Test that an onBeforeRequest block rule for a frame will still override an
// onHeadersReceived allowAllRequests rule with a higher priority.
IN_PROC_BROWSER_TEST_P(DNRMatchResponseHeadersBrowserTest,
AllowAllRequests_BlockedFrame) {
// Add a block rule for google.com sub frames.
TestRule block_frame_rule = CreateGenericRule(kMinValidID);
block_frame_rule.action->type = "block";
block_frame_rule.condition->url_filter = "google.com";
block_frame_rule.condition->resource_types =
std::vector<std::string>({"sub_frame"});
// Add an allowAllRequests rule that is matched in onHeadersReceived, for all
// sub frames.
TestRule allow_frame_rule = CreateGenericRule(kMinValidID + 1);
allow_frame_rule.priority = kMinValidPriority + 22;
allow_frame_rule.action->type = "allowAllRequests";
allow_frame_rule.condition->url_filter = "|https*";
allow_frame_rule.condition->resource_types =
std::vector<std::string>({"sub_frame"});
allow_frame_rule.condition->excluded_response_headers =
std::vector<TestHeaderCondition>(
{TestHeaderCondition("nonsense-header", {}, {})});
std::vector<TestRule> rules;
rules.push_back(std::move(block_frame_rule));
rules.push_back(std::move(allow_frame_rule));
ASSERT_NO_FATAL_FAILURE(LoadExtensionWithRules(std::move(rules)));
const GURL page_url = embedded_test_server()->GetURL(
"example.com", "/page_with_two_frames.html");
NavigateToURL(page_url);
const std::string kFrameName1 = "frame1";
const std::string kFrameName2 = "frame2";
// Navigate frame1 to example.com: it shouldn't be collapsed since
// `block_frame_rule` does not match it.
NavigateFrame(kFrameName1,
embedded_test_server()->GetURL(
"example.com", "/pages_with_script/index.html"));
// Navigate frame2 to google.com: it should be collapsed since
// `block_frame_rule` matches it and prevents `allow_frame_rule` from matching
// despite the latter rule's higher priority.
NavigateFrame(kFrameName2,
embedded_test_server()->GetURL(
"google.com", "/pages_with_script/index.html"));
TestFrameCollapse(kFrameName1, false);
TestFrameCollapse(kFrameName2, true);
}
// Verify that getMatchedRules returns the correct rule matches for rules which
// match on response headers.
// TODO(crbug.com/crbug.com/371298229): Flaky on Android.
#if BUILDFLAG(IS_ANDROID)
#define MAYBE_GetMatchedRules_SingleExtension \
DISABLED_GetMatchedRules_SingleExtension
#else
#define MAYBE_GetMatchedRules_SingleExtension GetMatchedRules_SingleExtension
#endif
IN_PROC_BROWSER_TEST_P(DNRMatchResponseHeadersBrowserTest,
MAYBE_GetMatchedRules_SingleExtension) {
set_config_flags(ConfigFlag::kConfig_HasBackgroundScript |
ConfigFlag::kConfig_HasFeedbackPermission);
DeclarativeNetRequestGetMatchedRulesFunction::
set_disable_throttling_for_tests(true);
std::vector<TestHeaderCondition> blank_header_condition =
std::vector<TestHeaderCondition>(
{TestHeaderCondition("nonsense-header", {}, {})});
std::vector<TestHeaderInfo> blank_req_header_action =
std::vector<TestHeaderInfo>({TestHeaderInfo("req-header", "set", "val")});
std::vector<TestHeaderInfo> blank_resp_header_action =
std::vector<TestHeaderInfo>(
{TestHeaderInfo("resp-header", "append", "val")});
struct RuleData {
int id;
int priority;
std::string action_type;
std::string filter;
std::optional<std::vector<TestHeaderCondition>> header_condition =
std::nullopt;
std::optional<std::vector<TestHeaderInfo>> request_headers = std::nullopt;
std::optional<std::vector<TestHeaderInfo>> response_headers = std::nullopt;
} rule_data[] = {
// Used for all sub-tests. Allows all main-frame requests at the
// onHeadersReceived stage.
{1, 100, "allow", "*", blank_header_condition},
// Used for sub-test 1.
{2, 1, "block", "a.test"},
// Used for sub-test 2.
{3, 1, "allow", "b.test"},
{4, 99, "block", "b.test", blank_header_condition},
// Used for sub-test 3.
{5, 1000, "allow", "c.test"},
{6, 1, "block", "c.test", blank_header_condition},
{7, 1001, "block", "c.test2", blank_header_condition},
// Used for sub-test 4.
{8, 1000, "modifyHeaders", "d.test", std::nullopt,
blank_req_header_action},
// Used for sub-test 5.
{9, 1, "modifyHeaders", "e.test", std::nullopt, std::nullopt,
blank_resp_header_action},
{10, 200, "modifyHeaders", "e.test2", std::nullopt, std::nullopt,
blank_resp_header_action},
// Used for sub-test 6.
{11, 1, "modifyHeaders", "f.test", blank_header_condition, std::nullopt,
blank_resp_header_action},
{12, 200, "modifyHeaders", "f.test2", blank_header_condition,
std::nullopt, blank_resp_header_action},
// Used for sub-test 7.
{13, 1000, "modifyHeaders", "g.test", std::nullopt,
blank_req_header_action},
{14, 102, "allow", "g.test"},
{15, 101, "block", "g.test", blank_header_condition},
};
std::vector<TestRule> rules;
for (const auto& rule : rule_data) {
TestRule test_rule = CreateGenericRule();
test_rule.id = rule.id;
test_rule.priority = rule.priority;
test_rule.action->type = rule.action_type;
test_rule.action->request_headers = rule.request_headers;
test_rule.action->response_headers = rule.response_headers;
test_rule.condition->url_filter.reset();
test_rule.condition->url_filter = rule.filter;
test_rule.condition->resource_types =
std::vector<std::string>({"main_frame"});
test_rule.condition->excluded_response_headers = rule.header_condition;
rules.push_back(std::move(test_rule));
}
ASSERT_NO_FATAL_FAILURE(LoadExtensionWithRules(
std::move(rules), "test_extension", {URLPattern::kAllUrlsPattern}));
struct {
std::string hostname;
std::string expected_matched_rules;
} test_cases[] = {
// Sub-test 1:
// The request is blocked before making it to onHeadersReceived so only
// rule 2 (block) should match.
{"a.test", "2"},
// Sub-test 2:
// Both allow rules from both phases (1 and 3) should match since rule 1
// supercedes rule 3 based on priority in the onHeadersReceived phase.
// Note that rule 1 prevents rule 4 from blocking the request based on
// priority.
{"b.test", "1,3"},
// Sub-test 3:
// For the first request, only rule 5 is matched since it outprioritizes
// rule 1 as an allow rule and prevents rule 6 from blocking the request.
// For the second request, rule 7 outprioritizes rule 1 and 5 and blocks
// the request but both 5 and 7 are matched since they operate on
// different request stages.
{"c.test", "5"},
{"c.test2", "5,7"},
// Sub-test 4:
// Rule 8 only modifies request headers so it is matched in the
// onBeforeSendHeaders phase, which is before rule 1 is matched.
{"d.test", "1,8"},
// Sub-test 5:
// For the first request, rule 9 is outprioritized by rule 1 so it will
// not modify response headers, and rule 1 matches.
// For the second request, rule 10 DOES outprioritize rule 1 and modifies
// response headers, so only it matches.
{"e.test", "1"},
{"e.test2", "10"},
// Sub-test 6:
// Same as sub-test 5 except the modify header rules now match on response
// header conditions in the onHeadersReceived phase.
{"f.test", "1"},
{"f.test2", "12"},
// Sub-test 7:
// In OnBeforeRequest, rule 13 (modify request headers) matches since it
// outprioritizes rule 14 (allow). However, rule 14 carries over to
// OnHeadersReceived where it outprioritizes both rules 1 and 15 (it
// prevents the latter rule from blocking the request) so it is matched.
{"g.test", "13,14"},
};
for (const auto& test_case : test_cases) {
base::Time start_time = base::Time::Now();
GURL url = embedded_test_server()->GetURL(test_case.hostname,
"/pages_with_script/index.html");
SCOPED_TRACE(base::StringPrintf("Testing %s", url.spec().c_str()));
NavigateToURL(url);
// Get the rule ids matched for the navigation request sent above.
std::string actual_rules_matched =
GetRuleIdsMatched(last_loaded_extension_id(), start_time);
EXPECT_EQ(test_case.expected_matched_rules, actual_rules_matched);
}
}
// Verify that getMatchedRules returns the correct rule matches for rules which
// match on response headers between different extensions.
// TODO(crbug.com/crbug.com/371298229): Flaky on Android.
#if BUILDFLAG(IS_ANDROID)
#define MAYBE_GetMatchedRules_MultipleExtensions \
DISABLED_GetMatchedRules_MultipleExtensions
#else
#define MAYBE_GetMatchedRules_MultipleExtensions \
GetMatchedRules_MultipleExtensions
#endif
IN_PROC_BROWSER_TEST_P(DNRMatchResponseHeadersBrowserTest,
MAYBE_GetMatchedRules_MultipleExtensions) {
set_config_flags(ConfigFlag::kConfig_HasBackgroundScript |
ConfigFlag::kConfig_HasFeedbackPermission);
DeclarativeNetRequestGetMatchedRulesFunction::
set_disable_throttling_for_tests(true);
auto create_rule = [](int id, int priority, const std::string& action_type,
const std::string& filter, bool headers_received_rule) {
TestRule test_rule = CreateGenericRule();
test_rule.id = id;
test_rule.priority = priority;
test_rule.action->type = action_type;
test_rule.condition->url_filter.reset();
test_rule.condition->url_filter = filter;
test_rule.condition->resource_types =
std::vector<std::string>({"main_frame"});
if (headers_received_rule) {
test_rule.condition->excluded_response_headers =
std::vector<TestHeaderCondition>(
{TestHeaderCondition("nonsense-header", {}, {})});
}
return test_rule;
};
auto before_request_allow = create_rule(1, 100, "allow", "google.com", false);
auto headers_received_allow = create_rule(2, 10, "allow", "google", true);
ASSERT_NO_FATAL_FAILURE(LoadExtensionWithRules(
{std::move(before_request_allow), std::move(headers_received_allow)},
"test_extension", {}));
auto extension_1_id = last_loaded_extension_id();
auto extension_2_allow = create_rule(3, 1, "allow", "google.xyz", false);
ASSERT_NO_FATAL_FAILURE(LoadExtensionWithRules({std::move(extension_2_allow)},
"test_extension_2", {}));
auto extension_2_id = last_loaded_extension_id();
// TODO(crbug.com/40727004): Expand this test by introducing a block rule from
// extension 1 that would've been bypassed by `before_request_allow` in the
// onHeadersReceived phase.
struct {
std::string hostname;
std::string ext_1_expected_matched_rules;
std::string ext_2_expected_matched_rules;
} test_cases[] = {
// This request only matches `before_request_allow`.
{"google.com", "1", ""},
// In onBeforeRequest, `extension_2_allow` takes precedence over
// `before_request_allow` since extension 2 was more recently installed.
// Once the request reaches onHeadersReceived, `headers_received_allow`
// matches, but only `extension_2_allow` should be tracked since it
// carries over to onHeadersReceived and outprioritizes
// `headers_received_allow`.
{"google.xyz", "", "3"},
};
for (const auto& test_case : test_cases) {
base::Time start_time = base::Time::Now();
GURL url = embedded_test_server()->GetURL(test_case.hostname,
"/pages_with_script/index.html");
SCOPED_TRACE(base::StringPrintf("Testing %s", url.spec().c_str()));
NavigateToURL(url);
// Get the rule ids matched for both extensions for the navigation request
// sent above.
std::string ext_1_rules_matched =
GetRuleIdsMatched(extension_1_id, start_time);
EXPECT_EQ(test_case.ext_1_expected_matched_rules, ext_1_rules_matched);
std::string ext_2_rules_matched =
GetRuleIdsMatched(extension_2_id, start_time);
EXPECT_EQ(test_case.ext_2_expected_matched_rules, ext_2_rules_matched);
}
}
#if !BUILDFLAG(IS_ANDROID)
// Test that modifyHeaders rules matched in both onBeforeRequest and
// onHeadersReceived phases will perform the correct action(s) on the request.
// TODO(crbug.com/393191910): Port to desktop Android. This test fails with
// no logging and no stack.
IN_PROC_BROWSER_TEST_P(DNRMatchResponseHeadersBrowserTest,
ModifyHeaders_SingleExtension) {
std::vector<TestHeaderCondition> blank_header_condition =
std::vector<TestHeaderCondition>(
{TestHeaderCondition("nonsense-header", {}, {})});
set_config_flags(ConfigFlag::kConfig_HasBackgroundScript |
ConfigFlag::kConfig_HasFeedbackPermission);
DeclarativeNetRequestGetMatchedRulesFunction::
set_disable_throttling_for_tests(true);
struct RuleData {
int id;
int priority;
std::string action_type;
std::string filter;
std::optional<std::vector<TestHeaderInfo>> response_headers_action =
std::nullopt;
std::optional<std::vector<TestHeaderCondition>> exclude_header_condition =
std::nullopt;
std::optional<std::vector<TestHeaderCondition>> header_condition =
std::nullopt;
} rule_data[] = {
// Used for sub-test 1, all parts.
{1, 2, "modifyHeaders", "a.test",
std::vector<TestHeaderInfo>(
{TestHeaderInfo("set-cookie", "set", "key1=val1")})},
{2, 1, "modifyHeaders", "a.test",
std::vector<TestHeaderInfo>(
{TestHeaderInfo("set-cookie", "set", "key2=val2")}),
blank_header_condition},
// Used for sub-test 1, part 2.
{3, 4, "modifyHeaders", "a.test2",
std::vector<TestHeaderInfo>(
{TestHeaderInfo("set-cookie", "remove", std::nullopt)}),
blank_header_condition},
// Used for sub-test 2, all parts.
{4, 5, "modifyHeaders", "b.test",
std::vector<TestHeaderInfo>(
{TestHeaderInfo("set-cookie", "append", "key4=val4")})},
{5, 3, "modifyHeaders", "b.test",
std::vector<TestHeaderInfo>(
{TestHeaderInfo("set-cookie", "append", "key5=val5")}),
blank_header_condition},
{6, 1, "modifyHeaders", "b.test",
std::vector<TestHeaderInfo>(
{TestHeaderInfo("set-cookie", "append", "key6=val6")})},
// Used for sub-test 2, part 2.
{7, 4, "allow", "b.test2"},
// Used for sub-test 2, part 3. Note that this rule will match on the
// original value of response headers, before they are modified by
// extensions.
{8, 2, "allow", "b.test3", std::nullopt, std::nullopt,
std::vector<TestHeaderCondition>(
{TestHeaderCondition("set-cookie", {"orig-key=val"}, {})})},
};
std::vector<TestRule> rules;
for (const auto& rule : rule_data) {
TestRule test_rule = CreateGenericRule();
test_rule.id = rule.id;
test_rule.priority = rule.priority;
test_rule.action->type = rule.action_type;
if (rule.action_type == "modifyHeaders") {
test_rule.action->response_headers = rule.response_headers_action;
}
test_rule.condition->url_filter.reset();
test_rule.condition->url_filter = rule.filter;
test_rule.condition->resource_types =
std::vector<std::string>({"main_frame"});
test_rule.condition->response_headers = rule.header_condition;
test_rule.condition->excluded_response_headers =
rule.exclude_header_condition;
rules.push_back(std::move(test_rule));
}
ASSERT_NO_FATAL_FAILURE(LoadExtensionWithRules(
std::move(rules), "test_extension", {URLPattern::kAllUrlsPattern}));
struct {
std::string hostname;
std::string expected_matched_rules;
std::string expected_set_cookie_value;
} test_cases[] = {
// Sub-test 1: Test that even if rules are matched across different
// request phases, the highest priority rule takes precedence in modifying
// headers.
// Part 1: rule 1 (matched in onBeforeRequest) sets the header.
{"a.test", "1", "key1=val1"},
// Part 2: rule 3 (matched in onHeadersReceived) removes the header.
{"a.test2", "3", ""},
// Sub-test 2: Test that multiple header actions are applied in descending
// order of priority, and that matched allow rules will prevent lower
// priority modifyHeaders rules from taking effect, even if these matches
// happen in different request phases.
// Part 1: Rules 4, 5 and 6 match the request and their append operations
// are applied onto the header with the highest priority rule (rule 4)
// being applied first.
{"b.test", "4,5,6", "orig-key=val; key4=val4; key5=val5; key6=val6"},
// Part 2: Rule 7 (matched in onBeforeRequest) outprioritizes rules 5 and
// 6.
{"b.test2", "4", "orig-key=val; key4=val4"},
// Part 3: Rule 8 (matched in onHeadersReceived) outprioritizes rule 6.
{"b.test3", "4,5", "orig-key=val; key4=val4; key5=val5"},
};
for (const auto& test_case : test_cases) {
base::Time start_time = base::Time::Now();
auto set_cookie_url = embedded_test_server()->GetURL(
test_case.hostname, "/set-cookie?orig-key=val");
SCOPED_TRACE(
base::StringPrintf("Testing %s", set_cookie_url.spec().c_str()));
NavigateToURL(set_cookie_url);
// Get the rule ids matched for the navigation request sent above.
std::string actual_rules_matched =
GetRuleIdsMatched(last_loaded_extension_id(), start_time);
EXPECT_EQ(test_case.expected_matched_rules, actual_rules_matched);
// Verify the value of the set-cookie header.
EXPECT_EQ(test_case.expected_set_cookie_value, GetPageCookie());
}
}
// Test inter-extension interactions for modifyHeaders rules matched in both
// onBeforeRequest and onHeadersReceived phases.
// TODO(crbug.com/393191910): Port to desktop Android. This test fails with
// no logging and no stack.
IN_PROC_BROWSER_TEST_P(DNRMatchResponseHeadersBrowserTest,
ModifyHeaders_MultipleExtensions) {
set_config_flags(ConfigFlag::kConfig_HasBackgroundScript |
ConfigFlag::kConfig_HasFeedbackPermission);
DeclarativeNetRequestGetMatchedRulesFunction::
set_disable_throttling_for_tests(true);
auto create_rule =
[](int id, int priority, const std::string& filter,
bool headers_received_rule,
const std::vector<TestHeaderInfo>& response_headers_action) {
TestRule test_rule = CreateGenericRule();
test_rule.id = id;
test_rule.priority = priority;
test_rule.action->type = "modifyHeaders";
test_rule.action->response_headers = response_headers_action;
test_rule.condition->url_filter.reset();
test_rule.condition->url_filter = filter;
test_rule.condition->resource_types =
std::vector<std::string>({"main_frame"});
if (headers_received_rule) {
test_rule.condition->excluded_response_headers =
std::vector<TestHeaderCondition>(
{TestHeaderCondition("nonsense-header", {}, {})});
}
return test_rule;
};
auto ext_1_append =
create_rule(1, 100, "google", false,
{TestHeaderInfo("set-cookie", "append", "key1=ext1")});
ASSERT_NO_FATAL_FAILURE(
LoadExtensionWithRules({std::move(ext_1_append)}, "test_extension",
{URLPattern::kAllUrlsPattern}));
auto extension_1_id = last_loaded_extension_id();
auto ext_2_append =
create_rule(2, 1, "google.ca", true,
{TestHeaderInfo("set-cookie", "append", "key2=ext2")});
auto ext_2_remove =
create_rule(3, 1, "google.xyz", true,
{TestHeaderInfo("set-cookie", "remove", std::nullopt)});
ASSERT_NO_FATAL_FAILURE(LoadExtensionWithRules(
{std::move(ext_2_append), std::move(ext_2_remove)}, "test_extension_2",
{URLPattern::kAllUrlsPattern}));
auto extension_2_id = last_loaded_extension_id();
struct {
std::string hostname;
std::string ext_1_expected_matched_rules;
std::string ext_2_expected_matched_rules;
std::string expected_set_cookie_value;
} test_cases[] = {
// Only `ext_1_append` matches.
{"google.com", "1", "", "orig-key=val; key1=ext1"},
// Both `ext_1_append` and `ext_2_append` match, with `ext_2_append`
// taking precedence and adding to the header first since its extension
// was more recently installed.
{"google.ca", "1", "2", "orig-key=val; key2=ext2; key1=ext1"},
// Only `ext_2_remove` is applied since it takes precedence over
// `ext_1_append` (and prevents `ext_1_append` from adding to the header)
// since its extension was more recently installed.
{"google.xyz", "", "3", ""},
};
for (const auto& test_case : test_cases) {
base::Time start_time = base::Time::Now();
auto set_cookie_url = embedded_test_server()->GetURL(
test_case.hostname, "/set-cookie?orig-key=val");
SCOPED_TRACE(
base::StringPrintf("Testing %s", set_cookie_url.spec().c_str()));
NavigateToURL(set_cookie_url);
// Get the rule ids matched for both extensions for the navigation request
// sent above.
std::string ext_1_rules_matched =
GetRuleIdsMatched(extension_1_id, start_time);
EXPECT_EQ(test_case.ext_1_expected_matched_rules, ext_1_rules_matched);
std::string ext_2_rules_matched =
GetRuleIdsMatched(extension_2_id, start_time);
EXPECT_EQ(test_case.ext_2_expected_matched_rules, ext_2_rules_matched);
// Verify the value of the set-cookie header.
EXPECT_EQ(test_case.expected_set_cookie_value, GetPageCookie());
}
}
#endif // !BUILDFLAG(IS_ANDROID)
// Fixture for use by tests that care about the --extensions-on-chrome-urls
// switch.
using DeclarativeNetRequestAllowChromeURLsBrowserTest =
DeclarativeNetRequestBrowserTest;
// Ensure that an extension can block requests that it initiated, but not
// non-navigation requests that other extensions initiated, unless the
// --extensions-on-chrome-urls switch is used.
IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestAllowChromeURLsBrowserTest,
CrossExtensionRequestBlocking) {
set_config_flags(ConfigFlag::kConfig_HasBackgroundScript |
ConfigFlag::kConfig_HasFeedbackPermission |
ConfigFlag::kConfig_HasManifestSandbox);
DeclarativeNetRequestGetMatchedRulesFunction::
set_disable_throttling_for_tests(true);
constexpr char kFetchTemplate[] = R"(
fetch('%s').then(response =>
response.ok ? 'success' : ('Unexpected Server Error: ' + response.status)
).catch(e =>
'failed'
).then(result => {
// EvalJs uses the return value, but
// ExecuteScriptInBackgroundPageAndReturnString waits for the
// sendScriptResult call. Both are needed here since EvalJs can't be used
// for the background ServiceWorkers and
// ExecuteScriptInBackgroundPageAndReturnString can't be used for the
// manifest sandbox pages.
if (typeof chrome?.test?.sendScriptResult === 'function') {
chrome.test.sendScriptResult(result);
}
return result;
});
)";
// Extension 1 - Blocks requests to google.com.
TestRule blocking_rule = CreateGenericRule(kMinValidID);
blocking_rule.id = 1;
blocking_rule.action->type = "block";
blocking_rule.condition->url_filter = "google.com";
blocking_rule.condition->resource_types =
std::vector<std::string>({"xmlhttprequest"});
ASSERT_NO_FATAL_FAILURE(
LoadExtensionWithRules({std::move(blocking_rule)}, "test_extension_1",
{URLPattern::kAllUrlsPattern}));
const Extension* extension_1 = last_loaded_extension();
content::RenderFrameHost* extension_1_sandbox = NavigateToURLInNewTab(
extension_1->GetResourceURL(kManifestSandboxPageFilepath));
// Extension 2 - Doesn't block any requests.
ASSERT_NO_FATAL_FAILURE(LoadExtensionWithRules(
{}, "test_extension_2", {URLPattern::kAllUrlsPattern}));
const Extension* extension_2 = last_loaded_extension();
content::RenderFrameHost* extension_2_sandbox = NavigateToURLInNewTab(
extension_2->GetResourceURL(kManifestSandboxPageFilepath));
struct {
std::string hostname;
bool rule_matches;
} test_cases[] = {{"google.com", true}, {"google.ca", false}};
for (const auto& test_case : test_cases) {
base::Time start_time = base::Time::Now();
GURL fetch_url =
embedded_test_server()->GetURL(test_case.hostname, "/cors-ok.txt");
SCOPED_TRACE(
base::StringPrintf("Testing %s, (Cross-extension blocking allowed: %d)",
fetch_url.spec().c_str(), GetAllowChromeURLs()));
std::string script =
base::StringPrintf(kFetchTemplate, fetch_url.spec().c_str());
bool expected_same_extension_blocked = test_case.rule_matches;
bool expected_cross_extension_blocked =
test_case.rule_matches && GetAllowChromeURLs();
std::string expected_same_extension_outcome =
expected_same_extension_blocked ? "failed" : "success";
std::string expected_cross_extension_outcome =
expected_cross_extension_blocked ? "failed" : "success";
// Each request is attempted twice, once from the extension's background
// ServiceWorker and again from the extension's manifest sandbox page. The
// blocking rule will match both or neither, so the match count is always
// incremented by two.
std::string expected_match_count =
base::NumberToString((expected_same_extension_blocked ? 2 : 0) +
(expected_cross_extension_blocked ? 2 : 0));
// Test requests from the extension background pages.
std::string actual_same_extension_outcome =
ExecuteScriptInBackgroundPageAndReturnString(extension_1->id(), script);
std::string actual_cross_extension_outcome =
ExecuteScriptInBackgroundPageAndReturnString(extension_2->id(), script);
EXPECT_EQ(expected_same_extension_outcome, actual_same_extension_outcome);
EXPECT_EQ(expected_cross_extension_outcome, actual_cross_extension_outcome);
// Test requests from the extension manifest sandbox pages.
std::string actual_same_extension_sandbox_outcome =
content::EvalJs(extension_1_sandbox, script).ExtractString();
std::string actual_cross_extension_sandbox_outcome =
content::EvalJs(extension_2_sandbox, script).ExtractString();
EXPECT_EQ(expected_same_extension_outcome,
actual_same_extension_sandbox_outcome);
EXPECT_EQ(expected_cross_extension_outcome,
actual_cross_extension_sandbox_outcome);
// Also check the rule match count looks right, should be either "4", "2" or
// "0".
EXPECT_EQ(expected_match_count,
GetMatchedRuleCount(extension_1->id(), std::nullopt /* tab_id */,
start_time));
}
}
#if !BUILDFLAG(IS_ANDROID)
// Ensure that extensions can block main_frame navigation requests that other
// extensions initiated, but not sub_frame requests unless the
// --extensions-on-chrome-urls switch is used.
// TODO(crbug.com/393191910): Port to desktop Android. This test fails with
// no logging and no stack.
// TODO(crbug.com/408364840): Re-enable flaky test.
IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestAllowChromeURLsBrowserTest,
DISABLED_CrossExtensionNavigationRequestBlocking) {
set_config_flags(ConfigFlag::kConfig_HasBackgroundScript |
ConfigFlag::kConfig_HasFeedbackPermission |
ConfigFlag::kConfig_HasManifestSandbox);
DeclarativeNetRequestGetMatchedRulesFunction::
set_disable_throttling_for_tests(true);
// Extension 1 - Blocks navigation requests to example.com.
TestRule blocking_rule = CreateGenericRule(kMinValidID);
blocking_rule.id = 1;
blocking_rule.action->type = "block";
blocking_rule.condition->url_filter = "example.com";
blocking_rule.condition->resource_types =
std::vector<std::string>({"main_frame", "sub_frame"});
ASSERT_NO_FATAL_FAILURE(
LoadExtensionWithRules({std::move(blocking_rule)}, "test_extension_1",
{URLPattern::kAllUrlsPattern}));
const Extension* extension_1 = last_loaded_extension();
// Extension 2 - Doesn't block any requests.
ASSERT_NO_FATAL_FAILURE(LoadExtensionWithRules(
{}, "test_extension_2", {URLPattern::kAllUrlsPattern}));
const Extension* extension_2 = last_loaded_extension();
// Initiate main_frame and sub_frame requests via an extension page.
base::Time start_time = base::Time::Now();
GURL extension_page_url = extension_2->GetResourceURL("/manifest.json");
GURL main_frame_url = embedded_test_server()->GetURL("example.com", "/");
GURL sub_frame_url =
embedded_test_server()->GetURL("example.com", "/child_frame.html");
NavigateToURL(extension_page_url);
content::RenderFrameHost* extension_page = GetPrimaryMainFrame();
content::TestNavigationObserver navigation_observer(main_frame_url);
navigation_observer.StartWatchingNewWebContents();
constexpr char kNavigationRequestsTemplate[] = R"(
const frame = document.createElement('iframe');
frame.src = '%s';
document.body.appendChild(frame);
window.open('%s');
)";
ASSERT_TRUE(content::ExecJs(
extension_page, base::StringPrintf(kNavigationRequestsTemplate,
sub_frame_url.spec().c_str(),
main_frame_url.spec().c_str())));
navigation_observer.Wait();
// The main_frame request should be blocked.
content::RenderFrameHost* main_frame = GetPrimaryMainFrame();
EXPECT_FALSE(WasFrameWithScriptLoaded(main_frame));
EXPECT_FALSE(navigation_observer.last_navigation_succeeded());
EXPECT_EQ(navigation_observer.last_net_error_code(),
net::ERR_BLOCKED_BY_CLIENT);
// The sub_frame request shouldn't be blocked, unless the the
// --extensions-on-chrome-urls switch is used.
bool should_iframe_navigation_succeed = !GetAllowChromeURLs();
content::RenderFrameHost* sub_frame =
content::ChildFrameAt(extension_page, 0);
ASSERT_TRUE(sub_frame);
EXPECT_EQ(sub_frame_url, sub_frame->GetLastCommittedURL());
content::WaitForLoadStop(
content::WebContents::FromRenderFrameHost(sub_frame));
EXPECT_EQ(should_iframe_navigation_succeed,
WasFrameWithScriptLoaded(sub_frame));
// The rule should have matched once (the main_frame request), or twice (both
// sub_frame and main_frame requests) if the switch was used.
std::string expected_match_count =
base::NumberToString(should_iframe_navigation_succeed ? 1 : 2);
EXPECT_EQ(expected_match_count,
GetMatchedRuleCount(extension_1->id(), std::nullopt /* tab_id */,
start_time));
}
// A derivative of DeclarativeNetRequestBrowserTest which allows the test to
// wait for ruleset loads to start, and throttle/resume them as needed.
// TODO(crbug.com/391924202): Port to desktop Android once it supports packed
// extensions.
class DeclarativeNetRequestThrottledRulesetLoadBrowserTest
: public DeclarativeNetRequestBrowserTest {
public:
DeclarativeNetRequestThrottledRulesetLoadBrowserTest() = default;
~DeclarativeNetRequestThrottledRulesetLoadBrowserTest() override = default;
void SetUpCommandLine(base::CommandLine* command_line) override {
DeclarativeNetRequestBrowserTest::SetUpCommandLine(command_line);
// After all PRE tests have finished setting up:
// - increment the ruleset version to simulate a chrome update and force
// re-indexing,
// - Add a throttle for ruleset loads.
if (GetTestPreCount() == 0) {
increment_ruleset_version_ =
CreateScopedIncrementRulesetVersionForTesting();
ruleset_loader_throttle_.emplace();
}
}
protected:
static constexpr char kUpdateFlowExtensionId[] =
"amkjakpejnhgnfdohinadnicifljgdgm";
RulesetLoaderThrottle& ruleset_loader_throttle() {
return *ruleset_loader_throttle_;
}
base::FilePath update_flow_extension_path() {
return test_data_dir_.AppendASCII("declarative_net_request/rule_updates");
}
private:
std::optional<ScopedIncrementRulesetVersion> increment_ruleset_version_;
std::optional<RulesetLoaderThrottle> ruleset_loader_throttle_;
};
// Setup: Installs v1 of `kUpdateFlowExtensionId` and waits for its ruleset to
// load.
IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestThrottledRulesetLoadBrowserTest,
PRE_RulesetLoadFromOldExtensionVersion) {
base::ScopedAllowBlockingForTesting allow_blocking;
base::ScopedTempDir scoped_temp_dir;
EXPECT_TRUE(scoped_temp_dir.CreateUniqueTempDir());
base::FilePath pem_path = update_flow_extension_path().AppendASCII("pem.pem");
base::FilePath crx_path = scoped_temp_dir.GetPath().AppendASCII("v1.crx");
base::FilePath result_path =
PackExtensionWithOptions(update_flow_extension_path().AppendASCII("v1"),
crx_path, pem_path, base::FilePath());
EXPECT_EQ(crx_path, result_path);
const Extension* extension =
InstallExtensionWithPermissionsGranted(crx_path, /*expected_change=*/1);
ASSERT_TRUE(extension);
EXPECT_EQ(extension->id(), kUpdateFlowExtensionId);
EXPECT_TRUE(extension_registry()->enabled_extensions().Contains(
kUpdateFlowExtensionId));
WaitForExtensionsWithRulesetsCount(1u);
}
// Test that if a ruleset load initiated from an older extension version
// completes, then it should be a no-op and the newer extension attempting to
// load a ruleset with the same ID should succeed.
// Regression for crbug.com/367440970.
IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestThrottledRulesetLoadBrowserTest,
RulesetLoadFromOldExtensionVersion) {
scoped_refptr<const Extension> extension =
extension_registry()->enabled_extensions().GetByID(
kUpdateFlowExtensionId);
ASSERT_TRUE(extension);
EXPECT_EQ("1", extension->version().GetString());
// Wait for `extension` to start loading its rulesets.
ruleset_loader_throttle().WaitForLoaderRequest();
base::ScopedAllowBlockingForTesting allow_blocking;
base::ScopedTempDir scoped_temp_dir;
EXPECT_TRUE(scoped_temp_dir.CreateUniqueTempDir());
// Update `extension` to v2 with a packed update.
base::FilePath pem_path = update_flow_extension_path().AppendASCII("pem.pem");
base::FilePath crx_path = scoped_temp_dir.GetPath().AppendASCII("v2.crx");
base::FilePath result_path =
PackExtensionWithOptions(update_flow_extension_path().AppendASCII("v2"),
crx_path, pem_path, base::FilePath());
EXPECT_EQ(crx_path, result_path);
UpdateExtension(kUpdateFlowExtensionId, crx_path, /*expected_change=*/0);
extension = extension_registry()->enabled_extensions().GetByID(
kUpdateFlowExtensionId);
ASSERT_TRUE(extension);
EXPECT_EQ("2", extension->version().GetString());
// Wait for the extension to "start" by waiting for its background service
// worker.
ExtensionBackgroundPageWaiter(profile(), *extension)
.WaitForBackgroundInitialized();
RulesetLoadObserver ruleset_load_observer(rules_monitor_service(),
kUpdateFlowExtensionId);
// `extension` v1's ruleset should still be loading after being re-indexed as
// a result of the simulated Chrome update. Note that v2 does not load any
// rulesets since it does not enable any by default from its manifest.
ruleset_loader_throttle().Resume();
// Let the ruleset loads finish.
ruleset_load_observer.Wait();
// Attempt to enable the ruleset from `extension` v2. It should still succeed.
UpdateEnabledRulesets(kUpdateFlowExtensionId, {}, {"ruleset"});
}
#endif // !BUILDFLAG(IS_ANDROID)
#if BUILDFLAG(IS_ANDROID)
// TODO(crbug.com/391924202): Add packed extensions once supported on Android.
const auto kExtensionLoadTypes = ::testing::Values(ExtensionLoadType::UNPACKED);
#else
const auto kExtensionLoadTypes =
::testing::Values(ExtensionLoadType::PACKED, ExtensionLoadType::UNPACKED);
#endif
INSTANTIATE_TEST_SUITE_P(All,
DeclarativeNetRequestBrowserTest,
::testing::Combine(kExtensionLoadTypes,
::testing::Values(false)));
INSTANTIATE_TEST_SUITE_P(All,
DeclarativeNetRequestHostPermissionsBrowserTest,
::testing::Combine(kExtensionLoadTypes,
::testing::Values(false)));
#if !BUILDFLAG(IS_ANDROID)
INSTANTIATE_TEST_SUITE_P(
All,
DeclarativeNetRequestResourceTypeBrowserTest,
::testing::Combine(::testing::Values(ExtensionLoadType::PACKED,
ExtensionLoadType::UNPACKED),
::testing::Values(false)));
#endif
INSTANTIATE_TEST_SUITE_P(All,
DeclarativeNetRequestSubresourceWebBundlesBrowserTest,
::testing::Combine(kExtensionLoadTypes,
::testing::Values(false)));
#if !BUILDFLAG(IS_ANDROID)
INSTANTIATE_TEST_SUITE_P(
All,
DeclarativeNetRequestBrowserTest_Packed,
::testing::Combine(::testing::Values(ExtensionLoadType::PACKED),
::testing::Values(false)));
#endif // !BUILDFLAG(IS_ANDROID)
INSTANTIATE_TEST_SUITE_P(
All,
DeclarativeNetRequestBrowserTest_Unpacked,
::testing::Combine(::testing::Values(ExtensionLoadType::UNPACKED),
::testing::Values(false)));
#if !BUILDFLAG(IS_ANDROID)
INSTANTIATE_TEST_SUITE_P(
All,
DeclarativeNetRequestGlobalRulesBrowserTest_Packed,
::testing::Combine(::testing::Values(ExtensionLoadType::PACKED),
::testing::Values(false)));
INSTANTIATE_TEST_SUITE_P(
All,
DeclarativeNetRequestAllowAllRequestsBrowserTest,
::testing::Combine(::testing::Values(ExtensionLoadType::PACKED,
ExtensionLoadType::UNPACKED),
::testing::Values(false)));
INSTANTIATE_TEST_SUITE_P(
All,
DeclarativeNetRequestWebTransportTest,
::testing::Combine(::testing::Values(ExtensionLoadType::PACKED,
ExtensionLoadType::UNPACKED),
::testing::Values(false)));
INSTANTIATE_TEST_SUITE_P(
All,
DeclarativeNetRequestBackForwardCacheBrowserTest,
::testing::Combine(::testing::Values(ExtensionLoadType::PACKED,
ExtensionLoadType::UNPACKED),
::testing::Values(false)));
INSTANTIATE_TEST_SUITE_P(
All,
DeclarativeNetRequestControllableResponseTest,
::testing::Combine(::testing::Values(ExtensionLoadType::PACKED,
ExtensionLoadType::UNPACKED),
::testing::Values(false)));
#endif
INSTANTIATE_TEST_SUITE_P(All,
DNRMatchResponseHeadersBrowserTest,
::testing::Combine(kExtensionLoadTypes,
::testing::Values(false)));
INSTANTIATE_TEST_SUITE_P(All,
DeclarativeNetRequestAllowChromeURLsBrowserTest,
::testing::Combine(kExtensionLoadTypes,
::testing::Bool()));
#if !BUILDFLAG(IS_ANDROID)
INSTANTIATE_TEST_SUITE_P(
All,
DeclarativeNetRequestThrottledRulesetLoadBrowserTest,
::testing::Combine(::testing::Values(ExtensionLoadType::PACKED),
::testing::Values(false)));
#endif // !BUILDFLAG(IS_ANDROID)
} // namespace
} // namespace extensions::declarative_net_request
|