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
|
// Copyright 2014 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 <stdint.h>
#include <map>
#include <memory>
#include <string>
#include "base/barrier_closure.h"
#include "base/base64url.h"
#include "base/command_line.h"
#include "base/functional/bind.h"
#include "base/memory/raw_ptr.h"
#include "base/run_loop.h"
#include "base/strings/utf_string_conversions.h"
#include "base/test/bind.h"
#include "base/test/metrics/histogram_tester.h"
#include "base/test/scoped_feature_list.h"
#include "build/build_config.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/browsing_data/chrome_browsing_data_remover_constants.h"
#include "chrome/browser/content_settings/cookie_settings_factory.h"
#include "chrome/browser/content_settings/host_content_settings_map_factory.h"
#include "chrome/browser/gcm/gcm_profile_service_factory.h"
#include "chrome/browser/gcm/instance_id/instance_id_profile_service_factory.h"
#include "chrome/browser/notifications/notification_display_service_tester.h"
#include "chrome/browser/notifications/notification_handler.h"
#include "chrome/browser/permissions/crowd_deny_fake_safe_browsing_database_manager.h"
#include "chrome/browser/permissions/crowd_deny_preload_data.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/push_messaging/push_messaging_app_identifier.h"
#include "chrome/browser/push_messaging/push_messaging_constants.h"
#include "chrome/browser/push_messaging/push_messaging_features.h"
#include "chrome/browser/push_messaging/push_messaging_service_factory.h"
#include "chrome/browser/push_messaging/push_messaging_service_impl.h"
#include "chrome/browser/push_messaging/push_messaging_unsubscribed_entry.h"
#include "chrome/browser/push_messaging/push_messaging_utils.h"
#include "chrome/browser/safe_browsing/test_safe_browsing_service.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/tabs/tab_strip_model.h"
#include "chrome/common/buildflags.h"
#include "chrome/common/channel_info.h"
#include "chrome/common/chrome_features.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/test/base/in_process_browser_test.h"
#include "chrome/test/base/ui_test_utils.h"
#include "components/browsing_data/content/browsing_data_helper.h"
#include "components/content_settings/core/browser/cookie_settings.h"
#include "components/content_settings/core/browser/host_content_settings_map.h"
#include "components/content_settings/core/common/content_settings.h"
#include "components/content_settings/core/common/content_settings_types.h"
#include "components/gcm_driver/common/gcm_message.h"
#include "components/gcm_driver/fake_gcm_profile_service.h"
#include "components/gcm_driver/gcm_client.h"
#include "components/gcm_driver/instance_id/fake_gcm_driver_for_instance_id.h"
#include "components/gcm_driver/instance_id/instance_id_driver.h"
#include "components/gcm_driver/instance_id/instance_id_profile_service.h"
#include "components/keep_alive_registry/keep_alive_registry.h"
#include "components/keep_alive_registry/keep_alive_types.h"
#include "components/network_session_configurator/common/network_switches.h"
#include "components/permissions/permission_request_manager.h"
#include "components/site_engagement/content/site_engagement_score.h"
#include "components/site_engagement/content/site_engagement_service.h"
#include "content/public/browser/browsing_data_remover.h"
#include "content/public/browser/web_contents.h"
#include "content/public/common/content_features.h"
#include "content/public/common/content_switches.h"
#include "content/public/test/browser_test.h"
#include "content/public/test/browser_test_utils.h"
#include "content/public/test/browsing_data_remover_test_util.h"
#include "content/public/test/prerender_test_util.h"
#include "net/base/features.h"
#include "net/dns/mock_host_resolver.h"
#include "net/test/embedded_test_server/embedded_test_server.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "third_party/blink/public/mojom/push_messaging/push_messaging.mojom.h"
#include "third_party/blink/public/mojom/push_messaging/push_messaging_status.mojom.h"
#include "ui/base/window_open_disposition.h"
#include "ui/message_center/public/cpp/notification.h"
namespace {
using testing::ElementsAre;
using testing::IsEmpty;
using testing::Property;
const char kManifestSenderId[] = "1234567890";
const int32_t kApplicationServerKeyLength = 65;
enum class PushSubscriptionKeyFormat { kOmitKey, kBinary, kBase64UrlEncoded };
// NIST P-256 public key made available to tests. Must be an uncompressed
// point in accordance with SEC1 2.3.3.
const uint8_t kApplicationServerKey[kApplicationServerKeyLength] = {
0x04, 0x55, 0x52, 0x6A, 0xA5, 0x6E, 0x8E, 0xAA, 0x47, 0x97, 0x36,
0x10, 0xC1, 0x66, 0x3C, 0x1E, 0x65, 0xBF, 0xA1, 0x7B, 0xEE, 0x48,
0xC9, 0xC6, 0xBB, 0xBF, 0x02, 0x18, 0x53, 0x72, 0x1D, 0x0C, 0x7B,
0xA9, 0xE3, 0x11, 0xB7, 0x03, 0x52, 0x21, 0xD3, 0x71, 0x90, 0x13,
0xA8, 0xC1, 0xCF, 0xED, 0x20, 0xF7, 0x1F, 0xD1, 0x7F, 0xF2, 0x76,
0xB6, 0x01, 0x20, 0xD8, 0x35, 0xA5, 0xD9, 0x3C, 0x43, 0xFD};
// URL-safe base64 encoded version of the |kApplicationServerKey|.
const char kEncodedApplicationServerKey[] =
"BFVSaqVujqpHlzYQwWY8HmW_oXvuSMnGu78CGFNyHQx7qeMRtwNSIdNxkBOowc_tIPcf0X_ydr"
"YBINg1pdk8Q_0";
// From chrome/browser/push_messaging/push_messaging_manager.cc
const char* kIncognitoWarningPattern =
"Chrome currently does not support the Push API in incognito mode "
"(https://crbug.com/401439). There is deliberately no way to "
"feature-detect this, since incognito mode needs to be undetectable by "
"websites.";
std::string GetTestApplicationServerKey(bool base64_url_encoded = false) {
std::string application_server_key;
if (base64_url_encoded) {
base::Base64UrlEncode(reinterpret_cast<const char*>(kApplicationServerKey),
base::Base64UrlEncodePolicy::OMIT_PADDING,
&application_server_key);
} else {
application_server_key = std::string(std::begin(kApplicationServerKey),
std::end(kApplicationServerKey));
}
return application_server_key;
}
void LegacyRegisterCallback(base::OnceClosure done_callback,
std::string* out_registration_id,
gcm::GCMClient::Result* out_result,
const std::string& registration_id,
gcm::GCMClient::Result result) {
if (out_registration_id)
*out_registration_id = registration_id;
if (out_result)
*out_result = result;
std::move(done_callback).Run();
}
void DidRegister(base::OnceClosure done_callback,
const std::string& registration_id,
const GURL& endpoint,
const std::optional<base::Time>& expiration_time,
const std::vector<uint8_t>& p256dh,
const std::vector<uint8_t>& auth,
blink::mojom::PushRegistrationStatus status) {
EXPECT_EQ(blink::mojom::PushRegistrationStatus::SUCCESS_FROM_PUSH_SERVICE,
status);
std::move(done_callback).Run();
}
void InstanceIDResultCallback(base::OnceClosure done_callback,
instance_id::InstanceID::Result* out_result,
instance_id::InstanceID::Result result) {
DCHECK(out_result);
*out_result = result;
std::move(done_callback).Run();
}
} // namespace
class PushMessagingBrowserTestBase : public InProcessBrowserTest {
public:
PushMessagingBrowserTestBase()
: scoped_testing_factory_installer_(
base::BindRepeating(&gcm::FakeGCMProfileService::Build)),
gcm_service_(nullptr),
gcm_driver_(nullptr) {}
~PushMessagingBrowserTestBase() override = default;
PushMessagingBrowserTestBase(const PushMessagingBrowserTestBase&) = delete;
PushMessagingBrowserTestBase& operator=(const PushMessagingBrowserTestBase&) =
delete;
// InProcessBrowserTest:
void SetUp() override {
https_server_ = std::make_unique<net::EmbeddedTestServer>(
net::EmbeddedTestServer::TYPE_HTTPS);
https_server_->ServeFilesFromSourceDirectory(GetChromeTestDataDir());
content::SetupCrossSiteRedirector(https_server_.get());
site_engagement::SiteEngagementScore::SetParamValuesForTesting();
InProcessBrowserTest::SetUp();
}
void SetUpCommandLine(base::CommandLine* command_line) override {
// Enable experimental features for subscription restrictions.
command_line->AppendSwitch(
switches::kEnableExperimentalWebPlatformFeatures);
// HTTPS server only serves a valid cert for localhost, so this is needed to
// load webby domains like "embedded.com" without an interstitial.
command_line->AppendSwitch(switches::kIgnoreCertificateErrors);
}
// InProcessBrowserTest:
void SetUpOnMainThread() override {
host_resolver()->AddRule("*", "127.0.0.1");
ASSERT_TRUE(https_server_->Start());
KeyedService* keyed_service =
gcm::GCMProfileServiceFactory::GetForProfile(GetBrowser()->profile());
if (keyed_service) {
gcm_service_ = static_cast<gcm::FakeGCMProfileService*>(keyed_service);
gcm_driver_ = static_cast<instance_id::FakeGCMDriverForInstanceID*>(
gcm_service_->driver());
}
notification_tester_ = std::make_unique<NotificationDisplayServiceTester>(
GetBrowser()->profile());
push_service_ =
PushMessagingServiceFactory::GetForProfile(GetBrowser()->profile());
LoadTestPage();
}
void TearDownOnMainThread() override {
notification_tester_.reset();
InProcessBrowserTest::TearDownOnMainThread();
}
// Calls should be wrapped in the ASSERT_NO_FATAL_FAILURE() macro.
void RestartPushService() {
Profile* profile = GetBrowser()->profile();
PushMessagingServiceFactory::GetInstance()->SetTestingFactory(
profile, BrowserContextKeyedServiceFactory::TestingFactory());
ASSERT_EQ(nullptr, PushMessagingServiceFactory::GetForProfile(profile));
PushMessagingServiceFactory::GetInstance()->RestoreFactoryForTests(profile);
PushMessagingServiceImpl::InitializeForProfile(profile);
push_service_ = PushMessagingServiceFactory::GetForProfile(profile);
}
// Helper function to test if a Keep Alive is registered while avoiding the
// platform checks. Returns a boolean so that assertion failures are reported
// at the right line.
// Returns true when KeepAlives are not supported by the platform, or when
// the registration state is equal to the expectation.
bool IsRegisteredKeepAliveEqualTo(bool expectation) {
#if BUILDFLAG(ENABLE_BACKGROUND_MODE)
return expectation ==
KeepAliveRegistry::GetInstance()->IsOriginRegistered(
KeepAliveOrigin::IN_FLIGHT_PUSH_MESSAGE);
#else
return true;
#endif
}
void LoadTestPage(const std::string& path) {
ASSERT_TRUE(ui_test_utils::NavigateToURL(GetBrowser(),
https_server_->GetURL(path)));
}
void LoadTestPage() { LoadTestPage(GetTestURL()); }
void LoadTestPageWithoutManifest() { LoadTestPage(GetNoManifestTestURL()); }
content::EvalJsResult RunScript(const std::string& script) {
return RunScript(script, nullptr);
}
content::EvalJsResult RunScript(const std::string& script,
content::WebContents* web_contents) {
if (!web_contents) {
web_contents = GetBrowser()->tab_strip_model()->GetActiveWebContents();
}
return content::EvalJs(web_contents->GetPrimaryMainFrame(), script);
}
gcm::GCMAppHandler* GetAppHandler() {
return gcm_driver_->GetAppHandler(kPushMessagingAppIdentifierPrefix);
}
permissions::PermissionRequestManager* GetPermissionRequestManager() {
return permissions::PermissionRequestManager::FromWebContents(
GetBrowser()->tab_strip_model()->GetActiveWebContents());
}
// Calls should be wrapped in the ASSERT_NO_FATAL_FAILURE() macro.
void RequestAndAcceptPermission();
// Calls should be wrapped in the ASSERT_NO_FATAL_FAILURE() macro.
void RequestAndDenyPermission();
// Sets out_token to the subscription token (not including server URL).
// Calls should be wrapped in the ASSERT_NO_FATAL_FAILURE() macro.
void SubscribeSuccessfully(
PushSubscriptionKeyFormat key_format = PushSubscriptionKeyFormat::kBinary,
std::string* out_token = nullptr);
// Sets up the state corresponding to a dangling push subscription whose
// service worker registration no longer exists. Some users may be left with
// such orphaned subscriptions due to service worker unregistrations not
// clearing push subscriptions in the past. This allows us to emulate that.
// Calls should be wrapped in the ASSERT_NO_FATAL_FAILURE() macro.
void SetupOrphanedPushSubscription(std::string* out_app_id);
// Legacy subscribe path using GCMDriver rather than Instance IDs. Only
// for testing that we maintain support for existing stored registrations.
// Calls should be wrapped in the ASSERT_NO_FATAL_FAILURE() macro.
void LegacySubscribeSuccessfully(std::string* out_subscription_id = nullptr);
// Strips server URL from a registration endpoint to get subscription token.
// Calls should be wrapped in the ASSERT_NO_FATAL_FAILURE() macro.
void EndpointToToken(const std::string& endpoint,
bool standard_protocol = true,
std::string* out_token = nullptr);
blink::mojom::PushSubscriptionPtr GetSubscriptionForAppIdentifier(
const PushMessagingAppIdentifier& app_identifier) {
blink::mojom::PushSubscriptionPtr result;
base::RunLoop run_loop;
push_service_->GetPushSubscriptionFromAppIdentifier(
app_identifier,
base::BindLambdaForTesting(
[&](blink::mojom::PushSubscriptionPtr subscription) {
result = std::move(subscription);
run_loop.Quit();
}));
run_loop.Run();
return result;
}
// Deletes an Instance ID from the GCM Store but keeps the push subscription
// stored in the PushMessagingAppIdentifier map and Service Worker DB.
// Calls should be wrapped in the ASSERT_NO_FATAL_FAILURE() macro.
void DeleteInstanceIDAsIfGCMStoreReset(const std::string& app_id);
PushMessagingAppIdentifier GetAppIdentifierForServiceWorkerRegistration(
int64_t service_worker_registration_id);
void SendMessageAndWaitUntilHandled(
const PushMessagingAppIdentifier& app_identifier,
const gcm::IncomingMessage& message);
net::EmbeddedTestServer* https_server() const { return https_server_.get(); }
// Returns a vector of the currently displayed Notification objects.
std::vector<message_center::Notification> GetDisplayedNotifications() {
return notification_tester_->GetDisplayedNotificationsForType(
NotificationHandler::Type::WEB_PERSISTENT);
}
// Returns the number of notifications that are currently being shown.
size_t GetNotificationCount() { return GetDisplayedNotifications().size(); }
// Removes all shown notifications.
void RemoveAllNotifications() {
notification_tester_->RemoveAllNotifications(
NotificationHandler::Type::WEB_PERSISTENT, true /* by_user */);
}
// To be called when delivery of a push message has finished. The |run_loop|
// will be told to quit after |messages_required| messages were received.
void OnDeliveryFinished(std::vector<size_t>* number_of_notifications_shown,
base::OnceClosure done_closure) {
DCHECK(number_of_notifications_shown);
number_of_notifications_shown->push_back(GetNotificationCount());
std::move(done_closure).Run();
}
PushMessagingServiceImpl* push_service() const { return push_service_; }
void SetSiteEngagementScore(const GURL& url, double score) {
site_engagement::SiteEngagementService* service =
site_engagement::SiteEngagementService::Get(GetBrowser()->profile());
service->ResetBaseScoreForURL(url, score);
EXPECT_EQ(score, service->GetScore(url));
}
// Matches |tag| against the notification's ID to see if the notification's
// js-provided tag could have been |tag|. This is not perfect as it might
// return true for a |tag| that is a substring of the original tag.
static bool TagEquals(const message_center::Notification& notification,
const std::string& tag) {
return std::string::npos != notification.id().find(tag);
}
protected:
virtual std::string GetTestURL() { return "/push_messaging/test.html"; }
virtual std::string GetNoManifestTestURL() {
return "/push_messaging/test_no_manifest.html";
}
virtual Browser* GetBrowser() const { return browser(); }
gcm::GCMProfileServiceFactory::ScopedTestingFactoryInstaller
scoped_testing_factory_installer_;
raw_ptr<gcm::FakeGCMProfileService, DanglingUntriaged> gcm_service_;
raw_ptr<instance_id::FakeGCMDriverForInstanceID, DanglingUntriaged>
gcm_driver_;
base::HistogramTester histogram_tester_;
std::unique_ptr<NotificationDisplayServiceTester> notification_tester_;
private:
std::unique_ptr<net::EmbeddedTestServer> https_server_;
raw_ptr<PushMessagingServiceImpl, DanglingUntriaged> push_service_;
};
void PushMessagingBrowserTestBase::RequestAndAcceptPermission() {
GetPermissionRequestManager()->set_auto_response_for_test(
permissions::PermissionRequestManager::ACCEPT_ALL);
ASSERT_EQ("permission status - granted",
RunScript("requestNotificationPermission();"));
}
void PushMessagingBrowserTestBase::RequestAndDenyPermission() {
GetPermissionRequestManager()->set_auto_response_for_test(
permissions::PermissionRequestManager::DENY_ALL);
ASSERT_EQ("permission status - denied",
RunScript("requestNotificationPermission();"));
}
void PushMessagingBrowserTestBase::SubscribeSuccessfully(
PushSubscriptionKeyFormat key_format,
std::string* out_token) {
ASSERT_EQ("ok - service worker registered",
RunScript("registerServiceWorker()"));
ASSERT_NO_FATAL_FAILURE(RequestAndAcceptPermission());
switch (key_format) {
case PushSubscriptionKeyFormat::kBinary:
ASSERT_EQ("manifest removed", RunScript("removeManifest()"));
ASSERT_NO_FATAL_FAILURE(
EndpointToToken(RunScript("documentSubscribePush()").ExtractString(),
true, out_token));
break;
case PushSubscriptionKeyFormat::kBase64UrlEncoded:
ASSERT_EQ("manifest removed", RunScript("removeManifest()"));
ASSERT_NO_FATAL_FAILURE(EndpointToToken(
RunScript("documentSubscribePushWithBase64URLEncodedString()")
.ExtractString(),
true, out_token));
break;
case PushSubscriptionKeyFormat::kOmitKey:
// Test backwards compatibility with old ID based subscriptions.
ASSERT_NO_FATAL_FAILURE(EndpointToToken(
RunScript("documentSubscribePushWithoutKey()").ExtractString(), false,
out_token));
break;
default:
NOTREACHED();
}
}
void PushMessagingBrowserTestBase::SetupOrphanedPushSubscription(
std::string* out_app_id) {
ASSERT_NO_FATAL_FAILURE(RequestAndAcceptPermission());
GURL requesting_origin =
https_server()->GetURL("/").DeprecatedGetOriginAsURL();
// Use 1234LL as it's unlikely to collide with an active service worker
// registration id (they increment from 0).
const int64_t service_worker_registration_id = 1234LL;
auto options = blink::mojom::PushSubscriptionOptions::New();
options->user_visible_only = true;
std::string test_application_server_key = GetTestApplicationServerKey();
options->application_server_key = std::vector<uint8_t>(
test_application_server_key.begin(), test_application_server_key.end());
base::RunLoop run_loop;
push_service()->SubscribeFromWorker(
requesting_origin, service_worker_registration_id,
/*render_process_id=*/-1, std::move(options),
base::BindOnce(&DidRegister, run_loop.QuitClosure()));
run_loop.Run();
PushMessagingAppIdentifier app_identifier =
PushMessagingAppIdentifier::FindByServiceWorker(
GetBrowser()->profile(), requesting_origin,
service_worker_registration_id);
ASSERT_FALSE(app_identifier.is_null());
*out_app_id = app_identifier.app_id();
}
void PushMessagingBrowserTestBase::LegacySubscribeSuccessfully(
std::string* out_subscription_id) {
// Create a non-InstanceID GCM registration. Have to directly access
// GCMDriver, since this codepath has been deleted from Push.
ASSERT_EQ("ok - service worker registered",
RunScript("registerServiceWorker()"));
ASSERT_NO_FATAL_FAILURE(RequestAndAcceptPermission());
GURL requesting_origin =
https_server()->GetURL("/").DeprecatedGetOriginAsURL();
int64_t service_worker_registration_id = 0LL;
PushMessagingAppIdentifier app_identifier =
PushMessagingAppIdentifier::LegacyGenerateForTesting(
requesting_origin, service_worker_registration_id);
push_service_->IncreasePushSubscriptionCount(1, true /* is_pending */);
std::string subscription_id;
{
base::RunLoop run_loop;
gcm::GCMClient::Result register_result = gcm::GCMClient::UNKNOWN_ERROR;
gcm_driver_->Register(
app_identifier.app_id(), {kManifestSenderId},
base::BindOnce(&LegacyRegisterCallback, run_loop.QuitClosure(),
&subscription_id, ®ister_result));
run_loop.Run();
ASSERT_EQ(gcm::GCMClient::SUCCESS, register_result);
}
app_identifier.PersistToPrefs(GetBrowser()->profile());
push_service_->IncreasePushSubscriptionCount(1, false /* is_pending */);
push_service_->DecreasePushSubscriptionCount(1, true /* was_pending */);
{
base::RunLoop run_loop;
push_service_->StorePushSubscriptionForTesting(
GetBrowser()->profile(), requesting_origin,
service_worker_registration_id, subscription_id, kManifestSenderId,
run_loop.QuitClosure());
run_loop.Run();
}
if (out_subscription_id)
*out_subscription_id = subscription_id;
}
void PushMessagingBrowserTestBase::EndpointToToken(const std::string& endpoint,
bool standard_protocol,
std::string* out_token) {
size_t last_slash = endpoint.rfind('/');
ASSERT_NE(last_slash, std::string::npos);
ASSERT_EQ(base::FeatureList::IsEnabled(
features::kPushMessagingGcmEndpointEnvironment)
? push_messaging::GetGcmEndpointForChannel(chrome::GetChannel())
: kPushMessagingGcmEndpoint,
endpoint.substr(0, last_slash + 1));
ASSERT_LT(last_slash + 1, endpoint.length()); // Token must not be empty.
if (out_token)
*out_token = endpoint.substr(last_slash + 1);
}
PushMessagingAppIdentifier
PushMessagingBrowserTestBase::GetAppIdentifierForServiceWorkerRegistration(
int64_t service_worker_registration_id) {
GURL origin = https_server()->GetURL("/").DeprecatedGetOriginAsURL();
PushMessagingAppIdentifier app_identifier =
PushMessagingAppIdentifier::FindByServiceWorker(
GetBrowser()->profile(), origin, service_worker_registration_id);
EXPECT_FALSE(app_identifier.is_null());
return app_identifier;
}
void PushMessagingBrowserTestBase::DeleteInstanceIDAsIfGCMStoreReset(
const std::string& app_id) {
// Delete the Instance ID directly, keeping the push subscription stored in
// the PushMessagingAppIdentifier map and the Service Worker database. This
// simulates the GCM Store getting reset but failing to clear push
// subscriptions, either because the store got reset before
// 93ec793ac69a542b2213297737178a55d069fd0d (Chrome 56), or because a race
// condition (e.g. shutdown) prevents PushMessagingServiceImpl::OnStoreReset
// from clearing all subscriptions.
instance_id::InstanceIDProfileService* instance_id_profile_service =
instance_id::InstanceIDProfileServiceFactory::GetForProfile(
GetBrowser()->profile());
DCHECK(instance_id_profile_service);
instance_id::InstanceIDDriver* instance_id_driver =
instance_id_profile_service->driver();
DCHECK(instance_id_driver);
instance_id::InstanceID::Result delete_result =
instance_id::InstanceID::UNKNOWN_ERROR;
base::RunLoop run_loop;
instance_id_driver->GetInstanceID(app_id)->DeleteID(base::BindOnce(
&InstanceIDResultCallback, run_loop.QuitClosure(), &delete_result));
run_loop.Run();
ASSERT_EQ(instance_id::InstanceID::SUCCESS, delete_result);
}
void PushMessagingBrowserTestBase::SendMessageAndWaitUntilHandled(
const PushMessagingAppIdentifier& app_identifier,
const gcm::IncomingMessage& message) {
base::RunLoop run_loop;
push_service()->SetMessageCallbackForTesting(run_loop.QuitClosure());
push_service()->OnMessage(app_identifier.app_id(), message);
run_loop.Run();
}
class PushMessagingBrowserTest : public PushMessagingBrowserTestBase {
public:
PushMessagingBrowserTest() {
disabled_features_.push_back(features::kPushMessagingDisallowSenderIDs);
}
void SetUp() override {
feature_list_.InitWithFeatures(enabled_features_, disabled_features_);
PushMessagingBrowserTestBase::SetUp();
}
protected:
std::vector<base::test::FeatureRef> enabled_features_{};
std::vector<base::test::FeatureRef> disabled_features_{};
private:
base::test::ScopedFeatureList feature_list_;
};
// This class is used to execute PushMessagingBrowserTest tests with
// third-party storage partitioning both enabled/disabled.
class PushMessagingPartitionedBrowserTest
: public PushMessagingBrowserTest,
public testing::WithParamInterface<bool> {
public:
PushMessagingPartitionedBrowserTest() {
if (GetParam()) {
enabled_features_.push_back(
net::features::kThirdPartyStoragePartitioning);
} else {
disabled_features_.push_back(
net::features::kThirdPartyStoragePartitioning);
}
}
};
INSTANTIATE_TEST_SUITE_P(PushMessagingPartitionedBrowserTest,
PushMessagingPartitionedBrowserTest,
testing::Values(true, false));
IN_PROC_BROWSER_TEST_F(PushMessagingBrowserTest,
SubscribeWithoutKeySuccessNotificationsGranted) {
ASSERT_NO_FATAL_FAILURE(
SubscribeSuccessfully(PushSubscriptionKeyFormat::kOmitKey));
EXPECT_EQ(kManifestSenderId, gcm_driver_->last_gettoken_authorized_entity());
EXPECT_EQ(GetAppIdentifierForServiceWorkerRegistration(0LL).app_id(),
gcm_driver_->last_gettoken_app_id());
}
IN_PROC_BROWSER_TEST_F(PushMessagingBrowserTest,
SubscribeSuccessNotificationsGranted) {
ASSERT_NO_FATAL_FAILURE(SubscribeSuccessfully());
EXPECT_EQ(kEncodedApplicationServerKey,
gcm_driver_->last_gettoken_authorized_entity());
EXPECT_EQ(GetAppIdentifierForServiceWorkerRegistration(0LL).app_id(),
gcm_driver_->last_gettoken_app_id());
}
IN_PROC_BROWSER_TEST_F(PushMessagingBrowserTest,
SubscribeSuccessNotificationsGrantedWithBase64URLKey) {
ASSERT_NO_FATAL_FAILURE(
SubscribeSuccessfully(PushSubscriptionKeyFormat::kBase64UrlEncoded));
EXPECT_EQ(kEncodedApplicationServerKey,
gcm_driver_->last_gettoken_authorized_entity());
EXPECT_EQ(GetAppIdentifierForServiceWorkerRegistration(0LL).app_id(),
gcm_driver_->last_gettoken_app_id());
}
IN_PROC_BROWSER_TEST_F(PushMessagingBrowserTest,
SubscribeSuccessNotificationsPrompt) {
ASSERT_EQ("ok - service worker registered",
RunScript("registerServiceWorker()"));
GetPermissionRequestManager()->set_auto_response_for_test(
permissions::PermissionRequestManager::ACCEPT_ALL);
// Both of these methods EXPECT that they succeed.
ASSERT_NO_FATAL_FAILURE(
EndpointToToken(RunScript("documentSubscribePush()").ExtractString()));
GetAppIdentifierForServiceWorkerRegistration(0LL);
}
IN_PROC_BROWSER_TEST_F(PushMessagingBrowserTest,
SubscribeFailureNotificationsBlocked) {
ASSERT_EQ("ok - service worker registered",
RunScript("registerServiceWorker()"));
ASSERT_NO_FATAL_FAILURE(RequestAndDenyPermission());
EXPECT_EQ("NotAllowedError - Registration failed - permission denied",
RunScript("documentSubscribePush()"));
}
IN_PROC_BROWSER_TEST_F(PushMessagingBrowserTest, SubscribeFailureNoManifest) {
ASSERT_EQ("ok - service worker registered",
RunScript("registerServiceWorker()"));
ASSERT_NO_FATAL_FAILURE(RequestAndAcceptPermission());
ASSERT_EQ("manifest removed", RunScript("removeManifest()"));
EXPECT_EQ(
"AbortError - Registration failed - missing applicationServerKey, and "
"manifest empty or missing",
RunScript("documentSubscribePushWithoutKey()"));
}
IN_PROC_BROWSER_TEST_F(PushMessagingBrowserTest, SubscribeFailureNoSenderId) {
ASSERT_EQ("ok - service worker registered",
RunScript("registerServiceWorker()"));
ASSERT_NO_FATAL_FAILURE(RequestAndAcceptPermission());
ASSERT_EQ("sender id removed from manifest",
RunScript("swapManifestNoSenderId()"));
EXPECT_EQ(
"AbortError - Registration failed - missing applicationServerKey, and "
"gcm_sender_id not found in manifest",
RunScript("documentSubscribePushWithoutKey()"));
}
IN_PROC_BROWSER_TEST_F(PushMessagingBrowserTest,
RegisterFailureEmptyPushSubscriptionOptions) {
ASSERT_EQ("ok - service worker registered",
RunScript("registerServiceWorker()"));
ASSERT_NO_FATAL_FAILURE(RequestAndAcceptPermission());
EXPECT_EQ("NotAllowedError - Registration failed - permission denied",
RunScript("documentSubscribePushWithEmptyOptions()"));
}
IN_PROC_BROWSER_TEST_F(PushMessagingBrowserTest, SubscribeWithInvalidation) {
std::string token1, token2, token3;
ASSERT_NO_FATAL_FAILURE(
SubscribeSuccessfully(PushSubscriptionKeyFormat::kBinary, &token1));
ASSERT_FALSE(token1.empty());
// Repeated calls to |subscribe()| should yield the same token.
ASSERT_NO_FATAL_FAILURE(
SubscribeSuccessfully(PushSubscriptionKeyFormat::kBinary, &token2));
ASSERT_EQ(token1, token2);
PushMessagingAppIdentifier app_identifier =
PushMessagingAppIdentifier::FindByServiceWorker(
GetBrowser()->profile(),
https_server()->GetURL("/").DeprecatedGetOriginAsURL(),
0LL /* service_worker_registration_id */);
ASSERT_FALSE(app_identifier.is_null());
EXPECT_EQ(app_identifier.app_id(), gcm_driver_->last_gettoken_app_id());
// Delete the InstanceID. This captures two scenarios: either the database was
// corrupted, or the subscription was invalidated by the server.
ASSERT_NO_FATAL_FAILURE(
DeleteInstanceIDAsIfGCMStoreReset(app_identifier.app_id()));
EXPECT_EQ(app_identifier.app_id(), gcm_driver_->last_deletetoken_app_id());
// Repeated calls to |subscribe()| will now (silently) result in a new token.
ASSERT_NO_FATAL_FAILURE(
SubscribeSuccessfully(PushSubscriptionKeyFormat::kBinary, &token3));
ASSERT_FALSE(token3.empty());
EXPECT_NE(token1, token3);
}
IN_PROC_BROWSER_TEST_F(PushMessagingBrowserTest, SubscribeWorker) {
ASSERT_EQ("ok - service worker registered",
RunScript("registerServiceWorker()"));
ASSERT_NO_FATAL_FAILURE(RequestAndAcceptPermission());
LoadTestPage(); // Reload to become controlled.
ASSERT_EQ("true - is controlled", RunScript("isControlled()"));
// Try to subscribe from a worker without a key. This should fail.
EXPECT_EQ(
"AbortError - Registration failed - missing applicationServerKey, and "
"gcm_sender_id not found in manifest",
RunScript("workerSubscribePushNoKey()"));
// Now run the subscribe with a key. This should succeed.
ASSERT_NO_FATAL_FAILURE(
EndpointToToken(RunScript("workerSubscribePush()").ExtractString(),
true /* standard_protocol */));
EXPECT_EQ("unsubscribe result: true", RunScript("unsubscribePush()"));
}
IN_PROC_BROWSER_TEST_F(PushMessagingBrowserTest,
SubscribeWorkerWithBase64URLEncodedString) {
ASSERT_EQ("ok - service worker registered",
RunScript("registerServiceWorker()"));
ASSERT_NO_FATAL_FAILURE(RequestAndAcceptPermission());
LoadTestPage(); // Reload to become controlled.
ASSERT_EQ("true - is controlled", RunScript("isControlled()"));
// Try to subscribe from a worker without a key. This should fail.
EXPECT_EQ(
"AbortError - Registration failed - missing applicationServerKey, and "
"gcm_sender_id not found in manifest",
RunScript("workerSubscribePushNoKey()"));
// Now run the subscribe with a key. This should succeed.
ASSERT_NO_FATAL_FAILURE(EndpointToToken(
RunScript("workerSubscribePushWithBase64URLEncodedString()")
.ExtractString(),
true /* standard_protocol */));
EXPECT_EQ("unsubscribe result: true", RunScript("unsubscribePush()"));
}
IN_PROC_BROWSER_TEST_F(PushMessagingBrowserTest,
ResubscribeWithoutKeyAfterSubscribingWithKeyInManifest) {
ASSERT_EQ("ok - service worker registered",
RunScript("registerServiceWorker()"));
ASSERT_NO_FATAL_FAILURE(RequestAndAcceptPermission());
LoadTestPage(); // Reload to become controlled.
ASSERT_EQ("true - is controlled", RunScript("isControlled()"));
// Run the subscription from the document without a key, this will trigger
// the code to read sender id from the manifest and will write it to the
// datastore.
std::string token1;
ASSERT_NO_FATAL_FAILURE(EndpointToToken(
RunScript("documentSubscribePushWithoutKey()").ExtractString(),
false /* standard_protocol */, &token1));
ASSERT_EQ("manifest removed", RunScript("removeManifest()"));
// Try to resubscribe from the document without a key or manifest.
// This should fail.
EXPECT_EQ(
"AbortError - Registration failed - missing applicationServerKey, "
"and manifest empty or missing",
RunScript("documentSubscribePushWithoutKey()"));
// Now run the subscribe from the service worker without a key.
// In this case, the sender id should be read from the datastore.
std::string token2;
ASSERT_NO_FATAL_FAILURE(
EndpointToToken(RunScript("workerSubscribePushNoKey()").ExtractString(),
false /* standard_protocol */, &token2));
EXPECT_EQ(token1, token2);
EXPECT_EQ("unsubscribe result: true", RunScript("unsubscribePush()"));
// After unsubscribing, subscribe again from the worker with no key.
// The sender id should again be read from the datastore, so the
// subcribe should succeed, and we should get a new subscription token.
std::string token3;
ASSERT_NO_FATAL_FAILURE(
EndpointToToken(RunScript("workerSubscribePushNoKey()").ExtractString(),
false /* standard_protocol */, &token3));
EXPECT_NE(token1, token3);
EXPECT_EQ("unsubscribe result: true", RunScript("unsubscribePush()"));
}
IN_PROC_BROWSER_TEST_F(
PushMessagingBrowserTest,
ResubscribeWithoutKeyAfterSubscribingFromDocumentWithP256Key) {
ASSERT_EQ("ok - service worker registered",
RunScript("registerServiceWorker()"));
ASSERT_NO_FATAL_FAILURE(RequestAndAcceptPermission());
LoadTestPageWithoutManifest(); // Reload to become controlled.
ASSERT_EQ("true - is controlled", RunScript("isControlled()"));
// Run the subscription from the document with a key.
ASSERT_NO_FATAL_FAILURE(
EndpointToToken(RunScript("documentSubscribePush()").ExtractString()));
// Try to resubscribe from the document without a key - should fail.
EXPECT_EQ(
"AbortError - Registration failed - missing applicationServerKey, "
"and manifest empty or missing",
RunScript("documentSubscribePushWithoutKey()"));
// Now try to resubscribe from the service worker without a key.
// This should also fail as the original key was not numeric.
EXPECT_EQ(
"AbortError - Registration failed - missing applicationServerKey, "
"and gcm_sender_id not found in manifest",
RunScript("workerSubscribePushNoKey()"));
EXPECT_EQ("unsubscribe result: true", RunScript("unsubscribePush()"));
// After unsubscribing, try to resubscribe again without a key.
// This should again fail.
EXPECT_EQ(
"AbortError - Registration failed - missing applicationServerKey, "
"and gcm_sender_id not found in manifest",
RunScript("workerSubscribePushNoKey()"));
}
IN_PROC_BROWSER_TEST_F(
PushMessagingBrowserTest,
ResubscribeWithoutKeyAfterSubscribingFromWorkerWithP256Key) {
ASSERT_EQ("ok - service worker registered",
RunScript("registerServiceWorker()"));
ASSERT_NO_FATAL_FAILURE(RequestAndAcceptPermission());
LoadTestPageWithoutManifest(); // Reload to become controlled.
ASSERT_EQ("true - is controlled", RunScript("isControlled()"));
// Run the subscribe from the service worker with a key.
// This should succeed.
ASSERT_NO_FATAL_FAILURE(
EndpointToToken(RunScript("workerSubscribePush()").ExtractString(),
true /* standard_protocol */));
// Try to resubscribe from the document without a key - should fail.
EXPECT_EQ(
"AbortError - Registration failed - missing applicationServerKey, "
"and manifest empty or missing",
RunScript("documentSubscribePushWithoutKey()"));
// Now try to resubscribe from the service worker without a key.
// This should also fail as the original key was not numeric.
EXPECT_EQ(
"AbortError - Registration failed - missing applicationServerKey, and "
"gcm_sender_id not found in manifest",
RunScript("workerSubscribePushNoKey()"));
EXPECT_EQ("unsubscribe result: true", RunScript("unsubscribePush()"));
// After unsubscribing, try to resubscribe again without a key.
// This should again fail.
EXPECT_EQ(
"AbortError - Registration failed - missing applicationServerKey, "
"and gcm_sender_id not found in manifest",
RunScript("workerSubscribePushNoKey()"));
}
IN_PROC_BROWSER_TEST_F(
PushMessagingBrowserTest,
ResubscribeWithoutKeyAfterSubscribingFromDocumentWithNumber) {
ASSERT_EQ("ok - service worker registered",
RunScript("registerServiceWorker()"));
ASSERT_NO_FATAL_FAILURE(RequestAndAcceptPermission());
LoadTestPageWithoutManifest(); // Reload to become controlled.
ASSERT_EQ("true - is controlled", RunScript("isControlled()"));
// Run the subscribe from the document with a numeric key.
// This should succeed.
std::string token1;
ASSERT_NO_FATAL_FAILURE(EndpointToToken(
RunScript("documentSubscribePushWithNumericKey()").ExtractString(),
false /* standard_protocol */, &token1));
// Try to resubscribe from the document without a key - should fail.
EXPECT_EQ(
"AbortError - Registration failed - missing applicationServerKey, "
"and manifest empty or missing",
RunScript("documentSubscribePushWithoutKey()"));
// Now run the subscribe from the service worker without a key.
// In this case, the sender id should be read from the datastore.
// Note, we would rather this failed as we only really want to support
// no-key subscribes after subscribing with a numeric gcm sender id in the
// manifest, not a numeric applicationServerKey, but for code simplicity
// this case is allowed.
std::string token2;
ASSERT_NO_FATAL_FAILURE(
EndpointToToken(RunScript("workerSubscribePushNoKey()").ExtractString(),
false /* standard_protocol */, &token2));
EXPECT_EQ(token1, token2);
EXPECT_EQ("unsubscribe result: true", RunScript("unsubscribePush()"));
// After unsubscribing, subscribe again from the worker with no key.
// The sender id should again be read from the datastore, so the
// subcribe should succeed, and we should get a new subscription token.
std::string token3;
ASSERT_NO_FATAL_FAILURE(
EndpointToToken(RunScript("workerSubscribePushNoKey()").ExtractString(),
false /* standard_protocol */, &token3));
EXPECT_NE(token1, token3);
EXPECT_EQ("unsubscribe result: true", RunScript("unsubscribePush()"));
}
IN_PROC_BROWSER_TEST_F(
PushMessagingBrowserTest,
ResubscribeWithoutKeyAfterSubscribingFromWorkerWithNumber) {
ASSERT_EQ("ok - service worker registered",
RunScript("registerServiceWorker()"));
ASSERT_NO_FATAL_FAILURE(RequestAndAcceptPermission());
LoadTestPageWithoutManifest(); // Reload to become controlled.
ASSERT_EQ("true - is controlled", RunScript("isControlled()"));
// Run the subscribe from the service worker with a numeric key.
// This should succeed.
std::string token1;
ASSERT_NO_FATAL_FAILURE(EndpointToToken(
RunScript("workerSubscribePushWithNumericKey()").ExtractString(),
false /* standard_protocol */, &token1));
// Try to resubscribe from the document without a key - should fail.
EXPECT_EQ(
"AbortError - Registration failed - missing applicationServerKey, "
"and manifest empty or missing",
RunScript("documentSubscribePushWithoutKey()"));
// Now run the subscribe from the service worker without a key.
// In this case, the sender id should be read from the datastore.
// Note, we would rather this failed as we only really want to support
// no-key subscribes after subscribing with a numeric gcm sender id in the
// manifest, not a numeric applicationServerKey, but for code simplicity
// this case is allowed.
std::string token2;
ASSERT_NO_FATAL_FAILURE(
EndpointToToken(RunScript("workerSubscribePushNoKey()").ExtractString(),
false /* standard_protocol */, &token2));
EXPECT_EQ(token1, token2);
EXPECT_EQ("unsubscribe result: true", RunScript("unsubscribePush()"));
// After unsubscribing, subscribe again from the worker with no key.
// The sender id should again be read from the datastore, so the
// subcribe should succeed, and we should get a new subscription token.
std::string token3;
ASSERT_NO_FATAL_FAILURE(
EndpointToToken(RunScript("workerSubscribePushNoKey()").ExtractString(),
false /* standard_protocol */, &token3));
EXPECT_NE(token1, token3);
EXPECT_EQ("unsubscribe result: true", RunScript("unsubscribePush()"));
}
IN_PROC_BROWSER_TEST_F(PushMessagingBrowserTest, ResubscribeWithMismatchedKey) {
ASSERT_EQ("ok - service worker registered",
RunScript("registerServiceWorker()"));
ASSERT_NO_FATAL_FAILURE(RequestAndAcceptPermission());
LoadTestPage(); // Reload to become controlled.
ASSERT_EQ("true - is controlled", RunScript("isControlled()"));
// Run the subscribe from the service worker with a key.
// This should succeed.
std::string token1;
ASSERT_NO_FATAL_FAILURE(EndpointToToken(
RunScript("workerSubscribePushWithNumericKey('11111')").ExtractString(),
false /* standard_protocol */, &token1));
// Try to resubscribe with a different key - should fail.
EXPECT_EQ(
"InvalidStateError - Registration failed - A subscription with a "
"different applicationServerKey (or gcm_sender_id) already exists; to "
"change the applicationServerKey, unsubscribe then resubscribe.",
RunScript("workerSubscribePushWithNumericKey('22222')"));
// Try to resubscribe with the original key - should succeed.
std::string token2;
ASSERT_NO_FATAL_FAILURE(EndpointToToken(
RunScript("workerSubscribePushWithNumericKey('11111')").ExtractString(),
false /* standard_protocol */, &token2));
EXPECT_EQ(token1, token2);
EXPECT_EQ("unsubscribe result: true", RunScript("unsubscribePush()"));
// Resubscribe with a different key after unsubscribing.
// Should succeed, and we should get a new subscription token.
std::string token3;
ASSERT_NO_FATAL_FAILURE(EndpointToToken(
RunScript("workerSubscribePushWithNumericKey('22222')").ExtractString(),
false /* standard_protocol */, &token3));
EXPECT_NE(token1, token3);
EXPECT_EQ("unsubscribe result: true", RunScript("unsubscribePush()"));
}
IN_PROC_BROWSER_TEST_F(PushMessagingBrowserTest, SubscribePersisted) {
// First, test that Service Worker registration IDs are assigned in order of
// registering the Service Workers, and the (fake) push subscription ids are
// assigned in order of push subscription (even when these orders are
// different).
std::string token1;
ASSERT_NO_FATAL_FAILURE(
SubscribeSuccessfully(PushSubscriptionKeyFormat::kBinary, &token1));
PushMessagingAppIdentifier sw0_identifier =
GetAppIdentifierForServiceWorkerRegistration(0LL);
EXPECT_EQ(sw0_identifier.app_id(), gcm_driver_->last_gettoken_app_id());
LoadTestPage("/push_messaging/subscope1/test.html");
ASSERT_EQ("ok - service worker registered",
RunScript("registerServiceWorker()"));
LoadTestPage("/push_messaging/subscope2/test.html");
ASSERT_EQ("ok - service worker registered",
RunScript("registerServiceWorker()"));
// Note that we need to reload the page after registering, otherwise
// navigator.serviceWorker.ready is going to be resolved with the parent
// Service Worker which still controls the page.
LoadTestPage("/push_messaging/subscope2/test.html");
std::string token2;
ASSERT_NO_FATAL_FAILURE(
SubscribeSuccessfully(PushSubscriptionKeyFormat::kBinary, &token2));
EXPECT_NE(token1, token2);
PushMessagingAppIdentifier sw2_identifier =
GetAppIdentifierForServiceWorkerRegistration(2LL);
EXPECT_EQ(sw2_identifier.app_id(), gcm_driver_->last_gettoken_app_id());
LoadTestPage("/push_messaging/subscope1/test.html");
std::string token3;
ASSERT_NO_FATAL_FAILURE(
SubscribeSuccessfully(PushSubscriptionKeyFormat::kBinary, &token3));
EXPECT_NE(token1, token3);
EXPECT_NE(token2, token3);
PushMessagingAppIdentifier sw1_identifier =
GetAppIdentifierForServiceWorkerRegistration(1LL);
EXPECT_EQ(sw1_identifier.app_id(), gcm_driver_->last_gettoken_app_id());
// Now test that the Service Worker registration IDs and push subscription IDs
// generated above were persisted to SW storage, by checking that they are
// unchanged despite requesting them in a different order.
LoadTestPage("/push_messaging/subscope1/test.html");
std::string token4;
ASSERT_NO_FATAL_FAILURE(
SubscribeSuccessfully(PushSubscriptionKeyFormat::kBinary, &token4));
EXPECT_EQ(token3, token4);
EXPECT_EQ(sw1_identifier.app_id(), gcm_driver_->last_gettoken_app_id());
LoadTestPage("/push_messaging/subscope2/test.html");
std::string token5;
ASSERT_NO_FATAL_FAILURE(
SubscribeSuccessfully(PushSubscriptionKeyFormat::kBinary, &token5));
EXPECT_EQ(token2, token5);
EXPECT_EQ(sw2_identifier.app_id(), gcm_driver_->last_gettoken_app_id());
LoadTestPage();
std::string token6;
ASSERT_NO_FATAL_FAILURE(
SubscribeSuccessfully(PushSubscriptionKeyFormat::kBinary, &token6));
EXPECT_EQ(token1, token6);
EXPECT_EQ(sw0_identifier.app_id(), gcm_driver_->last_gettoken_app_id());
}
IN_PROC_BROWSER_TEST_F(PushMessagingBrowserTest, AppHandlerOnlyIfSubscribed) {
// This test restarts the push service to simulate restarting the browser.
EXPECT_NE(push_service(), GetAppHandler());
ASSERT_NO_FATAL_FAILURE(RestartPushService());
EXPECT_NE(push_service(), GetAppHandler());
ASSERT_NO_FATAL_FAILURE(SubscribeSuccessfully());
EXPECT_EQ(push_service(), GetAppHandler());
ASSERT_NO_FATAL_FAILURE(RestartPushService());
EXPECT_EQ(push_service(), GetAppHandler());
// Unsubscribe.
base::RunLoop run_loop;
push_service()->SetUnsubscribeCallbackForTesting(run_loop.QuitClosure());
EXPECT_EQ("unsubscribe result: true", RunScript("unsubscribePush()"));
// The app handler is only guaranteed to be unregistered once the unsubscribe
// callback for testing has been run (PushSubscription.unsubscribe() usually
// resolves before that, in order to avoid blocking on network retries etc).
run_loop.Run();
EXPECT_NE(push_service(), GetAppHandler());
ASSERT_NO_FATAL_FAILURE(RestartPushService());
EXPECT_NE(push_service(), GetAppHandler());
}
IN_PROC_BROWSER_TEST_F(PushMessagingBrowserTest, PushEventSuccess) {
ASSERT_NO_FATAL_FAILURE(SubscribeSuccessfully());
PushMessagingAppIdentifier app_identifier =
GetAppIdentifierForServiceWorkerRegistration(0LL);
ASSERT_EQ("false - is not controlled", RunScript("isControlled()"));
LoadTestPage(); // Reload to become controlled.
ASSERT_EQ("true - is controlled", RunScript("isControlled()"));
EXPECT_TRUE(IsRegisteredKeepAliveEqualTo(false));
gcm::IncomingMessage message;
message.sender_id = GetTestApplicationServerKey();
message.raw_data = "testdata";
message.decrypted = true;
push_service()->OnMessage(app_identifier.app_id(), message);
EXPECT_TRUE(IsRegisteredKeepAliveEqualTo(true));
EXPECT_EQ("testdata", RunScript("resultQueue.pop()"));
// Check that we record this case in UMA.
histogram_tester_.ExpectUniqueSample(
"PushMessaging.DeliveryStatus",
static_cast<int>(blink::mojom::PushEventStatus::SUCCESS), 1);
}
IN_PROC_BROWSER_TEST_F(PushMessagingBrowserTest, PushEventOnShutdown) {
ASSERT_NO_FATAL_FAILURE(SubscribeSuccessfully());
PushMessagingAppIdentifier app_identifier =
GetAppIdentifierForServiceWorkerRegistration(0LL);
ASSERT_EQ("false - is not controlled", RunScript("isControlled()"));
LoadTestPage(); // Reload to become controlled.
ASSERT_EQ("true - is controlled", RunScript("isControlled()"));
EXPECT_TRUE(IsRegisteredKeepAliveEqualTo(false));
gcm::IncomingMessage message;
message.sender_id = GetTestApplicationServerKey();
message.raw_data = "testdata";
message.decrypted = true;
push_service()->OnAppTerminating();
push_service()->OnMessage(app_identifier.app_id(), message);
EXPECT_TRUE(IsRegisteredKeepAliveEqualTo(false));
}
IN_PROC_BROWSER_TEST_F(PushMessagingBrowserTest, PushEventWithoutPayload) {
ASSERT_NO_FATAL_FAILURE(SubscribeSuccessfully());
PushMessagingAppIdentifier app_identifier =
GetAppIdentifierForServiceWorkerRegistration(0LL);
LoadTestPage(); // Reload to become controlled.
ASSERT_EQ("true - is controlled", RunScript("isControlled()"));
gcm::IncomingMessage message;
message.sender_id = GetTestApplicationServerKey();
message.decrypted = false;
push_service()->OnMessage(app_identifier.app_id(), message);
EXPECT_EQ("[NULL]", RunScript("resultQueue.pop()"));
}
IN_PROC_BROWSER_TEST_F(PushMessagingBrowserTest, LegacyPushEvent) {
ASSERT_NO_FATAL_FAILURE(LegacySubscribeSuccessfully());
PushMessagingAppIdentifier app_identifier =
GetAppIdentifierForServiceWorkerRegistration(0LL);
LoadTestPage(); // Reload to become controlled.
ASSERT_EQ("true - is controlled", RunScript("isControlled()"));
gcm::IncomingMessage message;
message.sender_id = kManifestSenderId;
message.decrypted = false;
push_service()->OnMessage(app_identifier.app_id(), message);
EXPECT_EQ("[NULL]", RunScript("resultQueue.pop()"));
}
// Some users may have gotten into a state in the past where they still have
// a subscription even though the service worker was unregistered.
// Emulate this and test a push message triggers unsubscription.
IN_PROC_BROWSER_TEST_F(PushMessagingBrowserTest, PushEventNoServiceWorker) {
std::string app_id;
ASSERT_NO_FATAL_FAILURE(SetupOrphanedPushSubscription(&app_id));
// Try to send a push message.
gcm::IncomingMessage message;
message.sender_id = GetTestApplicationServerKey();
message.raw_data = "testdata";
message.decrypted = true;
base::RunLoop run_loop;
push_service()->SetMessageCallbackForTesting(run_loop.QuitClosure());
EXPECT_TRUE(IsRegisteredKeepAliveEqualTo(false));
push_service()->OnMessage(app_id, message);
EXPECT_TRUE(IsRegisteredKeepAliveEqualTo(true));
run_loop.Run();
EXPECT_TRUE(IsRegisteredKeepAliveEqualTo(false));
// No push data should have been received.
EXPECT_EQ("null", RunScript("String(resultQueue.popImmediately())"));
// Check that we record this case in UMA.
histogram_tester_.ExpectUniqueSample(
"PushMessaging.DeliveryStatus",
static_cast<int>(blink::mojom::PushEventStatus::NO_SERVICE_WORKER), 1);
// Missing Service Workers should trigger an automatic unsubscription attempt.
EXPECT_EQ(app_id, gcm_driver_->last_deletetoken_app_id());
histogram_tester_.ExpectUniqueSample(
"PushMessaging.UnregistrationReason",
static_cast<int>(
blink::mojom::PushUnregistrationReason::DELIVERY_NO_SERVICE_WORKER),
1);
// |app_identifier| should no longer be stored in prefs.
PushMessagingAppIdentifier stored_app_identifier =
PushMessagingAppIdentifier::FindByAppId(GetBrowser()->profile(), app_id);
EXPECT_TRUE(stored_app_identifier.is_null());
}
// Tests receiving messages for a subscription that no longer exists.
IN_PROC_BROWSER_TEST_F(PushMessagingBrowserTest, NoSubscription) {
ASSERT_NO_FATAL_FAILURE(SubscribeSuccessfully());
PushMessagingAppIdentifier app_identifier =
GetAppIdentifierForServiceWorkerRegistration(0LL);
LoadTestPage(); // Reload to become controlled.
ASSERT_EQ("true - is controlled", RunScript("isControlled()"));
EXPECT_EQ("unsubscribe result: true", RunScript("unsubscribePush()"));
histogram_tester_.ExpectUniqueSample(
"PushMessaging.UnregistrationReason",
static_cast<int>(blink::mojom::PushUnregistrationReason::JAVASCRIPT_API),
1);
gcm::IncomingMessage message;
message.sender_id = GetTestApplicationServerKey();
message.raw_data = "testdata";
message.decrypted = true;
SendMessageAndWaitUntilHandled(app_identifier, message);
// No push data should have been received.
EXPECT_EQ("null", RunScript("String(resultQueue.popImmediately())"));
// Check that we record this case in UMA.
histogram_tester_.ExpectUniqueSample(
"PushMessaging.DeliveryStatus",
static_cast<int>(blink::mojom::PushEventStatus::UNKNOWN_APP_ID), 1);
// Missing subscriptions should trigger an automatic unsubscription attempt.
EXPECT_EQ(app_identifier.app_id(), gcm_driver_->last_deletetoken_app_id());
histogram_tester_.ExpectBucketCount(
"PushMessaging.UnregistrationReason",
static_cast<int>(
blink::mojom::PushUnregistrationReason::DELIVERY_UNKNOWN_APP_ID),
1);
}
// Tests receiving messages for an origin that does not have permission, but
// somehow still has a subscription (as happened in https://crbug.com/633310).
IN_PROC_BROWSER_TEST_F(PushMessagingBrowserTest, PushEventWithoutPermission) {
ASSERT_NO_FATAL_FAILURE(SubscribeSuccessfully());
PushMessagingAppIdentifier app_identifier =
GetAppIdentifierForServiceWorkerRegistration(0LL);
LoadTestPage(); // Reload to become controlled.
ASSERT_EQ("true - is controlled", RunScript("isControlled()"));
// Revoke notifications permission, but first disable the
// PushMessagingServiceImpl's OnContentSettingChanged handler so that it
// doesn't automatically unsubscribe, since we want to test the case where
// there is still a subscription.
HostContentSettingsMapFactory::GetForProfile(GetBrowser()->profile())
->RemoveObserver(push_service());
HostContentSettingsMapFactory::GetForProfile(GetBrowser()->profile())
->ClearSettingsForOneType(ContentSettingsType::NOTIFICATIONS);
base::RunLoop().RunUntilIdle();
gcm::IncomingMessage message;
message.sender_id = GetTestApplicationServerKey();
message.raw_data = "testdata";
message.decrypted = true;
SendMessageAndWaitUntilHandled(app_identifier, message);
// No push data should have been received.
EXPECT_EQ("null", RunScript("String(resultQueue.popImmediately())"));
// Check that we record this case in UMA.
histogram_tester_.ExpectUniqueSample(
"PushMessaging.DeliveryStatus",
static_cast<int>(blink::mojom::PushEventStatus::PERMISSION_DENIED), 1);
// Missing permission should trigger an automatic unsubscription attempt.
EXPECT_EQ(app_identifier.app_id(), gcm_driver_->last_deletetoken_app_id());
EXPECT_EQ("false - not subscribed", RunScript("hasSubscription()"));
GURL origin = https_server()->GetURL("/").DeprecatedGetOriginAsURL();
PushMessagingAppIdentifier app_identifier_afterwards =
PushMessagingAppIdentifier::FindByServiceWorker(GetBrowser()->profile(),
origin, 0LL);
EXPECT_TRUE(app_identifier_afterwards.is_null());
histogram_tester_.ExpectUniqueSample(
"PushMessaging.UnregistrationReason",
static_cast<int>(
blink::mojom::PushUnregistrationReason::DELIVERY_PERMISSION_DENIED),
1);
}
IN_PROC_BROWSER_TEST_F(PushMessagingBrowserTest,
PushEventEnforcesUserVisibleNotification) {
ASSERT_NO_FATAL_FAILURE(SubscribeSuccessfully());
PushMessagingAppIdentifier app_identifier =
GetAppIdentifierForServiceWorkerRegistration(0LL);
ASSERT_EQ("false - is not controlled", RunScript("isControlled()"));
LoadTestPage(); // Reload to become controlled.
ASSERT_EQ("true - is controlled", RunScript("isControlled()"));
RemoveAllNotifications();
ASSERT_EQ(0u, GetNotificationCount());
// We'll need to specify the web_contents in which to eval script, since we're
// going to run script in a background tab.
content::WebContents* web_contents =
GetBrowser()->tab_strip_model()->GetActiveWebContents();
// Set the site engagement score for the site. Setting it to 10 means it
// should have a budget of 4, enough for two non-shown notification, which
// cost 2 each.
SetSiteEngagementScore(web_contents->GetLastCommittedURL(), 10.0);
// If the site is visible in an active tab, we should not force a notification
// to be shown. Try it twice, since we allow one mistake per 10 push events.
gcm::IncomingMessage message;
message.sender_id = GetTestApplicationServerKey();
message.decrypted = true;
for (int n = 0; n < 2; n++) {
message.raw_data = "testdata";
SendMessageAndWaitUntilHandled(app_identifier, message);
EXPECT_EQ("testdata", RunScript("resultQueue.pop()"));
EXPECT_EQ(0u, GetNotificationCount());
}
// Open a blank foreground tab so site is no longer visible.
ui_test_utils::NavigateToURLWithDisposition(
GetBrowser(), GURL("about:blank"),
WindowOpenDisposition::NEW_FOREGROUND_TAB,
ui_test_utils::BROWSER_TEST_WAIT_FOR_TAB);
// If the Service Worker push event handler shows a notification, we
// should not show a forced one.
message.raw_data = "shownotification";
SendMessageAndWaitUntilHandled(app_identifier, message);
EXPECT_EQ("shownotification", RunScript("resultQueue.pop()", web_contents));
EXPECT_EQ(1u, GetNotificationCount());
EXPECT_TRUE(TagEquals(GetDisplayedNotifications()[0], "push_test_tag"));
RemoveAllNotifications();
// If the Service Worker push event handler does not show a notification, we
// should show a forced one, but only once the origin is out of budget.
message.raw_data = "testdata";
for (int n = 0; n < 2; n++) {
// First two missed notifications shouldn't force a default one.
SendMessageAndWaitUntilHandled(app_identifier, message);
EXPECT_EQ("testdata", RunScript("resultQueue.pop()", web_contents));
EXPECT_EQ(0u, GetNotificationCount());
}
// Third missed notification should trigger a default notification, since the
// origin will be out of budget.
message.raw_data = "testdata";
SendMessageAndWaitUntilHandled(app_identifier, message);
EXPECT_EQ("testdata", RunScript("resultQueue.pop()", web_contents));
{
std::vector<message_center::Notification> notifications =
GetDisplayedNotifications();
ASSERT_EQ(notifications.size(), 1u);
EXPECT_TRUE(
TagEquals(notifications[0], kPushMessagingForcedNotificationTag));
EXPECT_TRUE(notifications[0].silent());
}
// The notification will be automatically dismissed when the developer shows
// a new notification themselves at a later point in time.
base::RunLoop notification_closed_run_loop;
notification_tester_->SetNotificationClosedClosure(
notification_closed_run_loop.QuitClosure());
message.raw_data = "shownotification";
SendMessageAndWaitUntilHandled(app_identifier, message);
EXPECT_EQ("shownotification", RunScript("resultQueue.pop()", web_contents));
// Wait for the default notification to dismiss.
notification_closed_run_loop.Run();
{
std::vector<message_center::Notification> notifications =
GetDisplayedNotifications();
ASSERT_EQ(notifications.size(), 1u);
EXPECT_FALSE(
TagEquals(notifications[0], kPushMessagingForcedNotificationTag));
}
}
IN_PROC_BROWSER_TEST_F(PushMessagingBrowserTest,
PushEventAllowSilentPushCommandLineFlag) {
ASSERT_NO_FATAL_FAILURE(SubscribeSuccessfully());
PushMessagingAppIdentifier app_identifier =
GetAppIdentifierForServiceWorkerRegistration(0LL);
EXPECT_EQ(app_identifier.app_id(), gcm_driver_->last_gettoken_app_id());
EXPECT_EQ(kEncodedApplicationServerKey,
gcm_driver_->last_gettoken_authorized_entity());
ASSERT_EQ("false - is not controlled", RunScript("isControlled()"));
LoadTestPage(); // Reload to become controlled.
ASSERT_EQ("true - is controlled", RunScript("isControlled()"));
RemoveAllNotifications();
ASSERT_EQ(0u, GetNotificationCount());
// We'll need to specify the web_contents in which to eval script, since we're
// going to run script in a background tab.
content::WebContents* web_contents =
GetBrowser()->tab_strip_model()->GetActiveWebContents();
SetSiteEngagementScore(web_contents->GetLastCommittedURL(), 5.0);
ui_test_utils::NavigateToURLWithDisposition(
GetBrowser(), GURL("about:blank"),
WindowOpenDisposition::NEW_FOREGROUND_TAB,
ui_test_utils::BROWSER_TEST_WAIT_FOR_TAB);
// Send a missed notification to use up the budget.
gcm::IncomingMessage message;
message.sender_id = GetTestApplicationServerKey();
message.raw_data = "testdata";
message.decrypted = true;
SendMessageAndWaitUntilHandled(app_identifier, message);
EXPECT_EQ("testdata", RunScript("resultQueue.pop()", web_contents));
EXPECT_EQ(0u, GetNotificationCount());
// If the Service Worker push event handler does not show a notification, we
// should show a forced one providing there is no foreground tab and the
// origin ran out of budget.
SendMessageAndWaitUntilHandled(app_identifier, message);
EXPECT_EQ("testdata", RunScript("resultQueue.pop()", web_contents));
// Because the --allow-silent-push command line flag has not been passed,
// this should have shown a default notification.
{
std::vector<message_center::Notification> notifications =
GetDisplayedNotifications();
ASSERT_EQ(notifications.size(), 1u);
EXPECT_TRUE(
TagEquals(notifications[0], kPushMessagingForcedNotificationTag));
EXPECT_TRUE(notifications[0].silent());
}
RemoveAllNotifications();
// Send the message again, but this time with the -allow-silent-push command
// line flag set. The default notification should *not* be shown.
base::CommandLine::ForCurrentProcess()->AppendSwitch(
switches::kAllowSilentPush);
SendMessageAndWaitUntilHandled(app_identifier, message);
EXPECT_EQ("testdata", RunScript("resultQueue.pop()", web_contents));
ASSERT_EQ(0u, GetNotificationCount());
}
class PushMessagingBrowserTestWithAbusiveOriginPermissionRevocation
: public PushMessagingBrowserTestBase {
public:
PushMessagingBrowserTestWithAbusiveOriginPermissionRevocation() = default;
using SiteReputation = CrowdDenyPreloadData::SiteReputation;
void CreatedBrowserMainParts(
content::BrowserMainParts* browser_main_parts) override {
PushMessagingBrowserTestBase::CreatedBrowserMainParts(browser_main_parts);
testing_preload_data_.emplace();
fake_database_manager_ =
base::MakeRefCounted<CrowdDenyFakeSafeBrowsingDatabaseManager>();
test_safe_browsing_factory_ =
std::make_unique<safe_browsing::TestSafeBrowsingServiceFactory>();
test_safe_browsing_factory_->SetTestDatabaseManager(
fake_database_manager_.get());
safe_browsing::SafeBrowsingServiceInterface::RegisterFactory(
test_safe_browsing_factory_.get());
}
void AddToPreloadDataBlocklist(
const GURL& origin,
chrome_browser_crowd_deny::
SiteReputation_NotificationUserExperienceQuality reputation_type) {
SiteReputation reputation;
reputation.set_notification_ux_quality(reputation_type);
testing_preload_data_->SetOriginReputation(url::Origin::Create(origin),
std::move(reputation));
}
void AddToSafeBrowsingBlocklist(const GURL& url) {
safe_browsing::ThreatMetadata test_metadata;
test_metadata.api_permissions.emplace("NOTIFICATIONS");
fake_database_manager_->SetSimulatedMetadataForUrl(url, test_metadata);
}
private:
base::test::ScopedFeatureList feature_list_;
std::optional<testing::ScopedCrowdDenyPreloadDataOverride>
testing_preload_data_;
scoped_refptr<CrowdDenyFakeSafeBrowsingDatabaseManager>
fake_database_manager_;
std::unique_ptr<safe_browsing::TestSafeBrowsingServiceFactory>
test_safe_browsing_factory_;
};
IN_PROC_BROWSER_TEST_F(
PushMessagingBrowserTestWithAbusiveOriginPermissionRevocation,
PushEventPermissionRevoked) {
ASSERT_NO_FATAL_FAILURE(SubscribeSuccessfully());
PushMessagingAppIdentifier app_identifier =
GetAppIdentifierForServiceWorkerRegistration(0LL);
LoadTestPage(); // Reload to become controlled.
ASSERT_EQ("true - is controlled", RunScript("isControlled()"));
// Add an origin to blocking lists after service worker is registered.
AddToPreloadDataBlocklist(
https_server()->GetURL("/").DeprecatedGetOriginAsURL(),
SiteReputation::ABUSIVE_CONTENT);
AddToSafeBrowsingBlocklist(
https_server()->GetURL("/").DeprecatedGetOriginAsURL());
gcm::IncomingMessage message;
message.sender_id = GetTestApplicationServerKey();
message.raw_data = "testdata";
message.decrypted = true;
SendMessageAndWaitUntilHandled(app_identifier, message);
// No push data should have been received.
EXPECT_EQ("null", RunScript("String(resultQueue.popImmediately())"));
// Check that we record this case in UMA.
histogram_tester_.ExpectUniqueSample(
"PushMessaging.DeliveryStatus",
static_cast<int>(
blink::mojom::PushEventStatus::PERMISSION_REVOKED_ABUSIVE),
1);
// Missing permission should trigger an automatic unsubscription attempt.
EXPECT_EQ(app_identifier.app_id(), gcm_driver_->last_deletetoken_app_id());
EXPECT_EQ("false - not subscribed", RunScript("hasSubscription()"));
GURL origin = https_server()->GetURL("/").DeprecatedGetOriginAsURL();
PushMessagingAppIdentifier app_identifier_afterwards =
PushMessagingAppIdentifier::FindByServiceWorker(GetBrowser()->profile(),
origin, 0LL);
EXPECT_TRUE(app_identifier_afterwards.is_null());
// 1st event - blink::mojom::PushUnregistrationReason::PERMISSION_REVOKED.
// 2nd event -
// blink::mojom::PushUnregistrationReason::PERMISSION_REVOKED_ABUSIVE.
histogram_tester_.ExpectTotalCount("PushMessaging.UnregistrationReason", 2);
histogram_tester_.ExpectBucketCount(
"PushMessaging.UnregistrationReason",
blink::mojom::PushUnregistrationReason::PERMISSION_REVOKED_ABUSIVE, 1);
histogram_tester_.ExpectBucketCount(
"PushMessaging.UnregistrationReason",
blink::mojom::PushUnregistrationReason::PERMISSION_REVOKED, 1);
}
// That test verifies that an origin is not revoked because it is not on
// SafeBrowsing blocking list.
IN_PROC_BROWSER_TEST_F(
PushMessagingBrowserTestWithAbusiveOriginPermissionRevocation,
OriginIsNotOnSafeBrowsingBlockingList) {
// The origin should be marked as |ABUSIVE_CONTENT| on |CrowdDenyPreloadData|
// otherwise the permission revocation logic will not be triggered.
AddToPreloadDataBlocklist(
https_server()->GetURL("/").DeprecatedGetOriginAsURL(),
SiteReputation::ABUSIVE_CONTENT);
ASSERT_NO_FATAL_FAILURE(SubscribeSuccessfully());
PushMessagingAppIdentifier app_identifier =
GetAppIdentifierForServiceWorkerRegistration(0LL);
ASSERT_EQ("false - is not controlled", RunScript("isControlled()"));
LoadTestPage(); // Reload to become controlled.
ASSERT_EQ("true - is controlled", RunScript("isControlled()"));
EXPECT_TRUE(IsRegisteredKeepAliveEqualTo(false));
gcm::IncomingMessage message;
message.sender_id = GetTestApplicationServerKey();
message.raw_data = "testdata";
message.decrypted = true;
push_service()->OnMessage(app_identifier.app_id(), message);
EXPECT_TRUE(IsRegisteredKeepAliveEqualTo(true));
EXPECT_EQ("testdata", RunScript("resultQueue.pop()"));
// Check that we record this case in UMA.
histogram_tester_.ExpectUniqueSample(
"PushMessaging.DeliveryStatus",
static_cast<int>(blink::mojom::PushEventStatus::SUCCESS), 1);
}
IN_PROC_BROWSER_TEST_F(PushMessagingBrowserTestBase,
PushEventIgnoresScheduledNotificationsForEnforcement) {
ASSERT_NO_FATAL_FAILURE(SubscribeSuccessfully());
PushMessagingAppIdentifier app_identifier =
GetAppIdentifierForServiceWorkerRegistration(0LL);
LoadTestPage(); // Reload to become controlled.
RemoveAllNotifications();
// We'll need to specify the web_contents in which to eval script, since we're
// going to run script in a background tab.
content::WebContents* web_contents =
GetBrowser()->tab_strip_model()->GetActiveWebContents();
// Initialize site engagement score to have no budget for silent pushes.
SetSiteEngagementScore(web_contents->GetLastCommittedURL(), 0);
ui_test_utils::NavigateToURLWithDisposition(
GetBrowser(), GURL("about:blank"),
WindowOpenDisposition::NEW_FOREGROUND_TAB,
ui_test_utils::BROWSER_TEST_WAIT_FOR_TAB);
gcm::IncomingMessage message;
message.sender_id = GetTestApplicationServerKey();
message.raw_data = "shownotification-with-showtrigger";
message.decrypted = true;
// If the Service Worker push event handler only schedules a notification, we
// should show a forced one providing there is no foreground tab and the
// origin ran out of budget.
SendMessageAndWaitUntilHandled(app_identifier, message);
EXPECT_EQ("shownotification-with-showtrigger",
RunScript("resultQueue.pop()", web_contents));
// Because scheduled notifications do not count as displayed notifications,
// this should have shown a default notification.
std::vector<message_center::Notification> notifications =
GetDisplayedNotifications();
ASSERT_EQ(notifications.size(), 1u);
EXPECT_TRUE(TagEquals(notifications[0], kPushMessagingForcedNotificationTag));
EXPECT_TRUE(notifications[0].silent());
}
IN_PROC_BROWSER_TEST_F(PushMessagingBrowserTest,
PushEventEnforcesUserVisibleNotificationAfterQueue) {
ASSERT_NO_FATAL_FAILURE(SubscribeSuccessfully());
PushMessagingAppIdentifier app_identifier =
GetAppIdentifierForServiceWorkerRegistration(0LL);
ASSERT_EQ("false - is not controlled", RunScript("isControlled()"));
LoadTestPage(); // Reload to become controlled.
ASSERT_EQ("true - is controlled", RunScript("isControlled()"));
// Fire off two push messages in sequence, only the second one of which will
// display a notification. The additional round-trip and I/O required by the
// second message, which shows a notification, should give us a reasonable
// confidence that the ordering will be maintained.
std::vector<size_t> number_of_notifications_shown;
gcm::IncomingMessage message;
message.sender_id = GetTestApplicationServerKey();
message.decrypted = true;
{
base::RunLoop run_loop;
push_service()->SetMessageCallbackForTesting(base::BindRepeating(
&PushMessagingBrowserTestBase::OnDeliveryFinished,
base::Unretained(this), &number_of_notifications_shown,
base::BarrierClosure(2 /* num_closures */, run_loop.QuitClosure())));
message.raw_data = "testdata";
push_service()->OnMessage(app_identifier.app_id(), message);
message.raw_data = "shownotification";
push_service()->OnMessage(app_identifier.app_id(), message);
run_loop.Run();
}
ASSERT_EQ(2u, number_of_notifications_shown.size());
EXPECT_EQ(0u, number_of_notifications_shown[0]);
EXPECT_EQ(1u, number_of_notifications_shown[1]);
}
IN_PROC_BROWSER_TEST_F(PushMessagingBrowserTest,
PushEventNotificationWithoutEventWaitUntil) {
content::WebContents* web_contents =
GetBrowser()->tab_strip_model()->GetActiveWebContents();
ASSERT_NO_FATAL_FAILURE(SubscribeSuccessfully());
PushMessagingAppIdentifier app_identifier =
GetAppIdentifierForServiceWorkerRegistration(0LL);
ASSERT_EQ("false - is not controlled", RunScript("isControlled()"));
LoadTestPage(); // Reload to become controlled.
ASSERT_EQ("true - is controlled", RunScript("isControlled()"));
base::RunLoop run_loop;
base::RepeatingClosure quit_barrier =
base::BarrierClosure(2 /* num_closures */, run_loop.QuitClosure());
push_service()->SetMessageCallbackForTesting(quit_barrier);
notification_tester_->SetNotificationAddedClosure(quit_barrier);
gcm::IncomingMessage message;
message.sender_id = GetTestApplicationServerKey();
message.raw_data = "shownotification-without-waituntil";
message.decrypted = true;
EXPECT_TRUE(IsRegisteredKeepAliveEqualTo(false));
push_service()->OnMessage(app_identifier.app_id(), message);
EXPECT_TRUE(IsRegisteredKeepAliveEqualTo(true));
EXPECT_EQ("immediate:shownotification-without-waituntil",
RunScript("resultQueue.pop()", web_contents));
run_loop.Run();
EXPECT_TRUE(IsRegisteredKeepAliveEqualTo(false));
ASSERT_EQ(1u, GetNotificationCount());
EXPECT_TRUE(TagEquals(GetDisplayedNotifications()[0], "push_test_tag"));
// Verify that the renderer process hasn't crashed.
EXPECT_EQ("permission status - granted",
RunScript("pushManagerPermissionState()"));
}
IN_PROC_BROWSER_TEST_F(PushMessagingBrowserTest, PermissionStateSaysPrompt) {
ASSERT_EQ("ok - service worker registered",
RunScript("registerServiceWorker()"));
ASSERT_EQ("permission status - prompt",
RunScript("pushManagerPermissionState()"));
}
IN_PROC_BROWSER_TEST_F(PushMessagingBrowserTest, PermissionStateSaysGranted) {
ASSERT_EQ("ok - service worker registered",
RunScript("registerServiceWorker()"));
ASSERT_NO_FATAL_FAILURE(RequestAndAcceptPermission());
ASSERT_NO_FATAL_FAILURE(
EndpointToToken(RunScript("documentSubscribePush()").ExtractString()));
EXPECT_EQ("permission status - granted",
RunScript("pushManagerPermissionState()"));
}
IN_PROC_BROWSER_TEST_F(PushMessagingBrowserTest, PermissionStateSaysDenied) {
ASSERT_EQ("ok - service worker registered",
RunScript("registerServiceWorker()"));
ASSERT_NO_FATAL_FAILURE(RequestAndDenyPermission());
EXPECT_EQ("NotAllowedError - Registration failed - permission denied",
RunScript("documentSubscribePush()"));
EXPECT_EQ("permission status - denied",
RunScript("pushManagerPermissionState()"));
}
IN_PROC_BROWSER_TEST_P(PushMessagingPartitionedBrowserTest, CrossOriginFrame) {
const GURL kEmbedderURL = https_server()->GetURL(
"embedder.com", "/push_messaging/framed_test.html");
const GURL kRequesterURL = https_server()->GetURL("requester.com", "/");
CookieSettingsFactory::GetForProfile(browser()->profile())
->SetCookieSetting(kRequesterURL, CONTENT_SETTING_ALLOW);
ASSERT_TRUE(ui_test_utils::NavigateToURL(GetBrowser(), kEmbedderURL));
auto* web_contents = GetBrowser()->tab_strip_model()->GetActiveWebContents();
LOG(ERROR) << web_contents->GetLastCommittedURL();
auto* subframe =
content::ChildFrameAt(web_contents->GetPrimaryMainFrame(), 0u);
ASSERT_TRUE(subframe);
// A cross-origin subframe that had not been granted the NOTIFICATIONS
// permission previously should see it as "denied", not be able to request it,
// and not be able to use the Push and Web Notification API. It is verified
// that no prompts are shown by auto-accepting and still expecting the
// permission to be denied.
GetPermissionRequestManager()->set_auto_response_for_test(
permissions::PermissionRequestManager::ACCEPT_ALL);
EXPECT_EQ("permission status - denied",
content::EvalJs(subframe, "requestNotificationPermission();"));
ASSERT_EQ("ok - service worker registered",
content::EvalJs(subframe, "registerServiceWorker()"));
EXPECT_EQ("permission status - denied",
content::EvalJs(subframe, "pushManagerPermissionState()"));
EXPECT_EQ("permission status - denied",
content::EvalJs(subframe, "notificationPermissionState()"));
EXPECT_EQ("permission status - denied",
content::EvalJs(subframe, "notificationPermissionAPIState()"));
EXPECT_EQ("NotAllowedError - Registration failed - permission denied",
content::EvalJs(subframe, "documentSubscribePush()"));
// A cross-origin subframe that had been granted the NOTIFICATIONS permission
// previously (in a first-party context) should see it as "granted", and be
// able to use the Push and Web Notifications APIs.
HostContentSettingsMapFactory::GetForProfile(GetBrowser()->profile())
->SetContentSettingDefaultScope(kRequesterURL, kRequesterURL,
ContentSettingsType::NOTIFICATIONS,
CONTENT_SETTING_ALLOW);
GetPermissionRequestManager()->set_auto_response_for_test(
permissions::PermissionRequestManager::DENY_ALL);
EXPECT_EQ("permission status - granted",
content::EvalJs(subframe, "requestNotificationPermission();"));
EXPECT_EQ("permission status - granted",
content::EvalJs(subframe, "pushManagerPermissionState()"));
EXPECT_EQ("permission status - granted",
content::EvalJs(subframe, "notificationPermissionState()"));
EXPECT_EQ("permission status - granted",
content::EvalJs(subframe, "notificationPermissionAPIState()"));
ASSERT_NO_FATAL_FAILURE(EndpointToToken(
content::EvalJs(subframe, "documentSubscribePush()").ExtractString()));
}
IN_PROC_BROWSER_TEST_F(PushMessagingBrowserTest, UnsubscribeSuccess) {
std::string token1;
ASSERT_NO_FATAL_FAILURE(
SubscribeSuccessfully(PushSubscriptionKeyFormat::kOmitKey, &token1));
EXPECT_EQ("ok - stored", RunScript("storePushSubscription()"));
// Resolves true if there was a subscription.
EXPECT_EQ("unsubscribe result: true", RunScript("unsubscribePush()"));
histogram_tester_.ExpectUniqueSample(
"PushMessaging.UnregistrationReason",
static_cast<int>(blink::mojom::PushUnregistrationReason::JAVASCRIPT_API),
1);
EXPECT_THAT(PushMessagingUnsubscribedEntry::GetAll(GetBrowser()->profile()),
IsEmpty());
// Resolves false if there was no longer a subscription.
EXPECT_EQ("unsubscribe result: false",
RunScript("unsubscribeStoredPushSubscription()"));
histogram_tester_.ExpectUniqueSample(
"PushMessaging.UnregistrationReason",
static_cast<int>(blink::mojom::PushUnregistrationReason::JAVASCRIPT_API),
2);
EXPECT_THAT(PushMessagingUnsubscribedEntry::GetAll(GetBrowser()->profile()),
IsEmpty());
// TODO(johnme): Test that doesn't reject if there was a network error (should
// deactivate subscription locally anyway).
// TODO(johnme): Test that doesn't reject if there were other push service
// errors (should deactivate subscription locally anyway).
// Unsubscribing (with an existing reference to a PushSubscription), after
// replacing the Service Worker, actually still works, as the Service Worker
// registration is unchanged.
std::string token2;
ASSERT_NO_FATAL_FAILURE(
SubscribeSuccessfully(PushSubscriptionKeyFormat::kOmitKey, &token2));
EXPECT_NE(token1, token2);
EXPECT_EQ("ok - stored", RunScript("storePushSubscription()"));
EXPECT_EQ("ok - service worker replaced",
RunScript("replaceServiceWorker()"));
EXPECT_EQ("unsubscribe result: true",
RunScript("unsubscribeStoredPushSubscription()"));
histogram_tester_.ExpectUniqueSample(
"PushMessaging.UnregistrationReason",
static_cast<int>(blink::mojom::PushUnregistrationReason::JAVASCRIPT_API),
3);
// Unsubscribing (with an existing reference to a PushSubscription), after
// unregistering the Service Worker, should fail.
std::string token3;
ASSERT_NO_FATAL_FAILURE(
SubscribeSuccessfully(PushSubscriptionKeyFormat::kOmitKey, &token3));
EXPECT_NE(token1, token3);
EXPECT_NE(token2, token3);
EXPECT_EQ("ok - stored", RunScript("storePushSubscription()"));
// Unregister service worker and wait for callback.
base::RunLoop run_loop;
push_service()->SetServiceWorkerUnregisteredCallbackForTesting(
run_loop.QuitClosure());
EXPECT_EQ("service worker unregistration status: true",
RunScript("unregisterServiceWorker()"));
run_loop.Run();
// Unregistering should have triggered an automatic unsubscribe.
histogram_tester_.ExpectBucketCount(
"PushMessaging.UnregistrationReason",
static_cast<int>(
blink::mojom::PushUnregistrationReason::SERVICE_WORKER_UNREGISTERED),
1);
histogram_tester_.ExpectTotalCount("PushMessaging.UnregistrationReason", 4);
// Now manual unsubscribe should return false.
EXPECT_EQ("unsubscribe result: false",
RunScript("unsubscribeStoredPushSubscription()"));
}
// Push subscriptions used to be non-InstanceID GCM registrations. Still need
// to be able to unsubscribe these, even though new ones are no longer created.
// Flaky on some Win and Linux buildbots. See crbug.com/835382.
#if BUILDFLAG(IS_WIN) || BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS)
#define MAYBE_LegacyUnsubscribeSuccess DISABLED_LegacyUnsubscribeSuccess
#else
#define MAYBE_LegacyUnsubscribeSuccess LegacyUnsubscribeSuccess
#endif
IN_PROC_BROWSER_TEST_F(PushMessagingBrowserTest,
MAYBE_LegacyUnsubscribeSuccess) {
std::string subscription_id1;
ASSERT_NO_FATAL_FAILURE(LegacySubscribeSuccessfully(&subscription_id1));
EXPECT_EQ("ok - stored", RunScript("storePushSubscription()"));
// Resolves true if there was a subscription.
gcm_service_->AddExpectedUnregisterResponse(gcm::GCMClient::SUCCESS);
EXPECT_EQ("unsubscribe result: true", RunScript("unsubscribePush()"));
histogram_tester_.ExpectUniqueSample(
"PushMessaging.UnregistrationReason",
static_cast<int>(blink::mojom::PushUnregistrationReason::JAVASCRIPT_API),
1);
// Resolves false if there was no longer a subscription.
EXPECT_EQ("unsubscribe result: false",
RunScript("unsubscribeStoredPushSubscription()"));
histogram_tester_.ExpectUniqueSample(
"PushMessaging.UnregistrationReason",
static_cast<int>(blink::mojom::PushUnregistrationReason::JAVASCRIPT_API),
2);
// Doesn't reject if there was a network error (deactivates subscription
// locally anyway).
std::string subscription_id2;
ASSERT_NO_FATAL_FAILURE(LegacySubscribeSuccessfully(&subscription_id2));
EXPECT_NE(subscription_id1, subscription_id2);
gcm_service_->AddExpectedUnregisterResponse(gcm::GCMClient::NETWORK_ERROR);
EXPECT_EQ("unsubscribe result: true", RunScript("unsubscribePush()"));
histogram_tester_.ExpectUniqueSample(
"PushMessaging.UnregistrationReason",
static_cast<int>(blink::mojom::PushUnregistrationReason::JAVASCRIPT_API),
3);
EXPECT_EQ("false - not subscribed", RunScript("hasSubscription()"));
// Doesn't reject if there were other push service errors (deactivates
// subscription locally anyway).
std::string subscription_id3;
ASSERT_NO_FATAL_FAILURE(LegacySubscribeSuccessfully(&subscription_id3));
EXPECT_NE(subscription_id1, subscription_id3);
EXPECT_NE(subscription_id2, subscription_id3);
gcm_service_->AddExpectedUnregisterResponse(
gcm::GCMClient::INVALID_PARAMETER);
EXPECT_EQ("unsubscribe result: true", RunScript("unsubscribePush()"));
histogram_tester_.ExpectUniqueSample(
"PushMessaging.UnregistrationReason",
static_cast<int>(blink::mojom::PushUnregistrationReason::JAVASCRIPT_API),
4);
// Unsubscribing (with an existing reference to a PushSubscription), after
// replacing the Service Worker, actually still works, as the Service Worker
// registration is unchanged.
std::string subscription_id4;
ASSERT_NO_FATAL_FAILURE(LegacySubscribeSuccessfully(&subscription_id4));
EXPECT_NE(subscription_id1, subscription_id4);
EXPECT_NE(subscription_id2, subscription_id4);
EXPECT_NE(subscription_id3, subscription_id4);
EXPECT_EQ("ok - stored", RunScript("storePushSubscription()"));
EXPECT_EQ("ok - service worker replaced",
RunScript("replaceServiceWorker()"));
EXPECT_EQ("unsubscribe result: true",
RunScript("unsubscribeStoredPushSubscription()"));
histogram_tester_.ExpectUniqueSample(
"PushMessaging.UnregistrationReason",
static_cast<int>(blink::mojom::PushUnregistrationReason::JAVASCRIPT_API),
5);
// Unsubscribing (with an existing reference to a PushSubscription), after
// unregistering the Service Worker, should fail.
std::string subscription_id5;
ASSERT_NO_FATAL_FAILURE(LegacySubscribeSuccessfully(&subscription_id5));
EXPECT_NE(subscription_id1, subscription_id5);
EXPECT_NE(subscription_id2, subscription_id5);
EXPECT_NE(subscription_id3, subscription_id5);
EXPECT_NE(subscription_id4, subscription_id5);
EXPECT_EQ("ok - stored", RunScript("storePushSubscription()"));
// Unregister service worker and wait for callback.
base::RunLoop run_loop;
push_service()->SetServiceWorkerUnregisteredCallbackForTesting(
run_loop.QuitClosure());
EXPECT_EQ("service worker unregistration status: true",
RunScript("unregisterServiceWorker()"));
run_loop.Run();
// Unregistering should have triggered an automatic unsubscribe.
histogram_tester_.ExpectBucketCount(
"PushMessaging.UnregistrationReason",
static_cast<int>(
blink::mojom::PushUnregistrationReason::SERVICE_WORKER_UNREGISTERED),
1);
histogram_tester_.ExpectTotalCount("PushMessaging.UnregistrationReason", 6);
// Now manual unsubscribe should return false.
EXPECT_EQ("unsubscribe result: false",
RunScript("unsubscribeStoredPushSubscription()"));
}
IN_PROC_BROWSER_TEST_F(PushMessagingBrowserTest, UnsubscribeOffline) {
EXPECT_NE(push_service(), GetAppHandler());
std::string token;
ASSERT_NO_FATAL_FAILURE(
SubscribeSuccessfully(PushSubscriptionKeyFormat::kBinary, &token));
gcm_service_->set_offline(true);
// Should quickly resolve true after deleting local state (rather than waiting
// until unsubscribing over the network exceeds the maximum backoff duration).
EXPECT_EQ("unsubscribe result: true", RunScript("unsubscribePush()"));
histogram_tester_.ExpectUniqueSample(
"PushMessaging.UnregistrationReason",
static_cast<int>(blink::mojom::PushUnregistrationReason::JAVASCRIPT_API),
1);
// Since the service is offline, the network request to GCM is still being
// retried, so the app handler shouldn't have been unregistered yet.
EXPECT_EQ(push_service(), GetAppHandler());
// But restarting the push service will unregister the app handler, since the
// subscription is no longer stored in the PushMessagingAppIdentifier map.
ASSERT_NO_FATAL_FAILURE(RestartPushService());
EXPECT_NE(push_service(), GetAppHandler());
}
IN_PROC_BROWSER_TEST_F(PushMessagingBrowserTest,
UnregisteringServiceWorkerUnsubscribes) {
ASSERT_NO_FATAL_FAILURE(SubscribeSuccessfully());
LoadTestPage(); // Reload to become controlled.
ASSERT_EQ("true - is controlled", RunScript("isControlled()"));
// Unregister the worker, and wait for callback to complete.
base::RunLoop run_loop;
push_service()->SetServiceWorkerUnregisteredCallbackForTesting(
run_loop.QuitClosure());
ASSERT_EQ("service worker unregistration status: true",
RunScript("unregisterServiceWorker()"));
run_loop.Run();
// This should have unregistered the push subscription.
histogram_tester_.ExpectUniqueSample(
"PushMessaging.UnregistrationReason",
static_cast<int>(
blink::mojom::PushUnregistrationReason::SERVICE_WORKER_UNREGISTERED),
1);
// We should not be able to look up the app id.
GURL origin = https_server()->GetURL("/").DeprecatedGetOriginAsURL();
PushMessagingAppIdentifier app_identifier =
PushMessagingAppIdentifier::FindByServiceWorker(
GetBrowser()->profile(), origin,
0LL /* service_worker_registration_id */);
EXPECT_TRUE(app_identifier.is_null());
EXPECT_THAT(PushMessagingUnsubscribedEntry::GetAll(GetBrowser()->profile()),
IsEmpty());
}
IN_PROC_BROWSER_TEST_F(PushMessagingBrowserTest,
ServiceWorkerDatabaseDeletionUnsubscribes) {
ASSERT_NO_FATAL_FAILURE(SubscribeSuccessfully());
LoadTestPage(); // Reload to become controlled.
ASSERT_EQ("true - is controlled", RunScript("isControlled()"));
// Pretend as if the Service Worker database went away, and wait for callback
// to complete.
base::RunLoop run_loop;
push_service()->SetServiceWorkerDatabaseWipedCallbackForTesting(
run_loop.QuitClosure());
push_service()->DidDeleteServiceWorkerDatabase();
run_loop.Run();
// This should have unregistered the push subscription.
histogram_tester_.ExpectUniqueSample(
"PushMessaging.UnregistrationReason",
static_cast<int>(blink::mojom::PushUnregistrationReason::
SERVICE_WORKER_DATABASE_WIPED),
1);
// There should not be any subscriptions left.
EXPECT_EQ(PushMessagingAppIdentifier::GetCount(GetBrowser()->profile()), 0u);
EXPECT_THAT(PushMessagingUnsubscribedEntry::GetAll(GetBrowser()->profile()),
IsEmpty());
}
IN_PROC_BROWSER_TEST_F(PushMessagingBrowserTest,
UnregisteringServiceWorkerDeletesUnsubscribedEntries) {
ASSERT_NO_FATAL_FAILURE(SubscribeSuccessfully());
EXPECT_EQ("true - subscribed", RunScript("hasSubscription()"));
GURL origin = https_server()->GetURL("/").DeprecatedGetOriginAsURL();
{
base::RunLoop run_loop;
push_service()->SetContentSettingChangedCallbackForTesting(
run_loop.QuitClosure());
HostContentSettingsMapFactory::GetForProfile(GetBrowser()->profile())
->SetContentSettingDefaultScope(origin, GURL(),
ContentSettingsType::NOTIFICATIONS,
CONTENT_SETTING_BLOCK);
run_loop.Run();
}
// There should be no subscription but one unsubscribed entry.
EXPECT_EQ(PushMessagingAppIdentifier::GetCount(GetBrowser()->profile()), 0u);
EXPECT_THAT(
PushMessagingUnsubscribedEntry::GetAll(GetBrowser()->profile()),
ElementsAre(Property(&PushMessagingUnsubscribedEntry::origin, origin)));
// Unregister service worker and wait for callback.
{
base::RunLoop run_loop;
push_service()->SetServiceWorkerUnregisteredCallbackForTesting(
run_loop.QuitClosure());
EXPECT_EQ("service worker unregistration status: true",
RunScript("unregisterServiceWorker()"));
run_loop.Run();
}
// There should be no subscription and no unsubscribed entry anymore.
EXPECT_EQ(PushMessagingAppIdentifier::GetCount(GetBrowser()->profile()), 0u);
EXPECT_THAT(PushMessagingUnsubscribedEntry::GetAll(GetBrowser()->profile()),
IsEmpty());
}
IN_PROC_BROWSER_TEST_F(
PushMessagingBrowserTest,
ServiceWorkerDatabaseDeletionDeletesUnsubscribedEntries) {
ASSERT_NO_FATAL_FAILURE(SubscribeSuccessfully());
EXPECT_EQ("true - subscribed", RunScript("hasSubscription()"));
GURL origin = https_server()->GetURL("/").DeprecatedGetOriginAsURL();
{
base::RunLoop run_loop;
push_service()->SetContentSettingChangedCallbackForTesting(
run_loop.QuitClosure());
HostContentSettingsMapFactory::GetForProfile(GetBrowser()->profile())
->SetContentSettingDefaultScope(origin, GURL(),
ContentSettingsType::NOTIFICATIONS,
CONTENT_SETTING_BLOCK);
run_loop.Run();
}
// There should be no subscription but one unsubscribed entry.
EXPECT_EQ(PushMessagingAppIdentifier::GetCount(GetBrowser()->profile()), 0u);
EXPECT_THAT(
PushMessagingUnsubscribedEntry::GetAll(GetBrowser()->profile()),
ElementsAre(Property(&PushMessagingUnsubscribedEntry::origin, origin)));
// Pretend as if the Service Worker database went away, and wait for callback
// to complete.
{
base::RunLoop run_loop;
push_service()->SetServiceWorkerDatabaseWipedCallbackForTesting(
run_loop.QuitClosure());
push_service()->DidDeleteServiceWorkerDatabase();
run_loop.Run();
}
// There should be no subscription and no unsubscribed entry anymore.
EXPECT_EQ(PushMessagingAppIdentifier::GetCount(GetBrowser()->profile()), 0u);
EXPECT_THAT(PushMessagingUnsubscribedEntry::GetAll(GetBrowser()->profile()),
IsEmpty());
}
IN_PROC_BROWSER_TEST_F(PushMessagingBrowserTest,
InvalidGetSubscriptionUnsubscribes) {
ASSERT_NO_FATAL_FAILURE(SubscribeSuccessfully());
GURL origin = https_server()->GetURL("/").DeprecatedGetOriginAsURL();
PushMessagingAppIdentifier app_identifier1 =
PushMessagingAppIdentifier::FindByServiceWorker(
GetBrowser()->profile(), origin,
0LL /* service_worker_registration_id */);
ASSERT_FALSE(app_identifier1.is_null());
ASSERT_NO_FATAL_FAILURE(
DeleteInstanceIDAsIfGCMStoreReset(app_identifier1.app_id()));
// Push messaging should not yet be aware of the InstanceID being deleted.
histogram_tester_.ExpectTotalCount("PushMessaging.UnregistrationReason", 0);
// We should still be able to look up the app id.
PushMessagingAppIdentifier app_identifier2 =
PushMessagingAppIdentifier::FindByServiceWorker(
GetBrowser()->profile(), origin,
0LL /* service_worker_registration_id */);
EXPECT_FALSE(app_identifier2.is_null());
EXPECT_EQ(app_identifier1.app_id(), app_identifier2.app_id());
// Now call PushManager.getSubscription(). It should return null.
EXPECT_EQ("false - not subscribed", RunScript("hasSubscription()"));
// This should have unsubscribed the push subscription.
histogram_tester_.ExpectUniqueSample(
"PushMessaging.UnregistrationReason",
static_cast<int>(blink::mojom::PushUnregistrationReason::
GET_SUBSCRIPTION_STORAGE_CORRUPT),
1);
// We should no longer be able to look up the app id.
PushMessagingAppIdentifier app_identifier3 =
PushMessagingAppIdentifier::FindByServiceWorker(
GetBrowser()->profile(), origin,
0LL /* service_worker_registration_id */);
EXPECT_TRUE(app_identifier3.is_null());
EXPECT_THAT(PushMessagingUnsubscribedEntry::GetAll(GetBrowser()->profile()),
IsEmpty());
}
IN_PROC_BROWSER_TEST_F(PushMessagingBrowserTest,
GlobalResetPushPermissionUnsubscribes) {
ASSERT_NO_FATAL_FAILURE(SubscribeSuccessfully());
EXPECT_EQ("true - subscribed", RunScript("hasSubscription()"));
EXPECT_EQ("permission status - granted",
RunScript("pushManagerPermissionState()"));
base::RunLoop run_loop;
push_service()->SetContentSettingChangedCallbackForTesting(
run_loop.QuitClosure());
HostContentSettingsMapFactory::GetForProfile(GetBrowser()->profile())
->ClearSettingsForOneType(ContentSettingsType::NOTIFICATIONS);
run_loop.Run();
EXPECT_EQ("permission status - prompt",
RunScript("pushManagerPermissionState()"));
EXPECT_EQ("false - not subscribed", RunScript("hasSubscription()"));
histogram_tester_.ExpectUniqueSample(
"PushMessaging.UnregistrationReason",
static_cast<int>(
blink::mojom::PushUnregistrationReason::PERMISSION_REVOKED),
1);
EXPECT_THAT(PushMessagingUnsubscribedEntry::GetAll(GetBrowser()->profile()),
ElementsAre(Property(
&PushMessagingUnsubscribedEntry::origin,
https_server()->GetURL("/").DeprecatedGetOriginAsURL())));
}
IN_PROC_BROWSER_TEST_F(PushMessagingBrowserTest,
LocalResetPushPermissionUnsubscribes) {
ASSERT_NO_FATAL_FAILURE(SubscribeSuccessfully());
EXPECT_EQ("true - subscribed", RunScript("hasSubscription()"));
EXPECT_EQ("permission status - granted",
RunScript("pushManagerPermissionState()"));
base::RunLoop run_loop;
push_service()->SetContentSettingChangedCallbackForTesting(
run_loop.QuitClosure());
GURL origin = https_server()->GetURL("/").DeprecatedGetOriginAsURL();
HostContentSettingsMapFactory::GetForProfile(GetBrowser()->profile())
->SetContentSettingDefaultScope(origin, origin,
ContentSettingsType::NOTIFICATIONS,
CONTENT_SETTING_DEFAULT);
run_loop.Run();
EXPECT_EQ("permission status - prompt",
RunScript("pushManagerPermissionState()"));
EXPECT_EQ("false - not subscribed", RunScript("hasSubscription()"));
histogram_tester_.ExpectUniqueSample(
"PushMessaging.UnregistrationReason",
static_cast<int>(
blink::mojom::PushUnregistrationReason::PERMISSION_REVOKED),
1);
EXPECT_THAT(
PushMessagingUnsubscribedEntry::GetAll(GetBrowser()->profile()),
ElementsAre(Property(&PushMessagingUnsubscribedEntry::origin, origin)));
}
IN_PROC_BROWSER_TEST_F(PushMessagingBrowserTest,
DenyPushPermissionUnsubscribes) {
ASSERT_NO_FATAL_FAILURE(SubscribeSuccessfully());
EXPECT_EQ("true - subscribed", RunScript("hasSubscription()"));
EXPECT_EQ("permission status - granted",
RunScript("pushManagerPermissionState()"));
base::RunLoop run_loop;
push_service()->SetContentSettingChangedCallbackForTesting(
run_loop.QuitClosure());
GURL origin = https_server()->GetURL("/").DeprecatedGetOriginAsURL();
HostContentSettingsMapFactory::GetForProfile(GetBrowser()->profile())
->SetContentSettingDefaultScope(origin, origin,
ContentSettingsType::NOTIFICATIONS,
CONTENT_SETTING_BLOCK);
run_loop.Run();
EXPECT_EQ("permission status - denied",
RunScript("pushManagerPermissionState()"));
EXPECT_EQ("false - not subscribed", RunScript("hasSubscription()"));
histogram_tester_.ExpectUniqueSample(
"PushMessaging.UnregistrationReason",
static_cast<int>(
blink::mojom::PushUnregistrationReason::PERMISSION_REVOKED),
1);
EXPECT_THAT(
PushMessagingUnsubscribedEntry::GetAll(GetBrowser()->profile()),
ElementsAre(Property(&PushMessagingUnsubscribedEntry::origin, origin)));
}
IN_PROC_BROWSER_TEST_F(PushMessagingBrowserTest,
GlobalResetNotificationsPermissionUnsubscribes) {
ASSERT_NO_FATAL_FAILURE(SubscribeSuccessfully());
EXPECT_EQ("true - subscribed", RunScript("hasSubscription()"));
EXPECT_EQ("permission status - granted",
RunScript("pushManagerPermissionState()"));
base::RunLoop run_loop;
push_service()->SetContentSettingChangedCallbackForTesting(
run_loop.QuitClosure());
HostContentSettingsMapFactory::GetForProfile(GetBrowser()->profile())
->ClearSettingsForOneType(ContentSettingsType::NOTIFICATIONS);
run_loop.Run();
EXPECT_EQ("permission status - prompt",
RunScript("pushManagerPermissionState()"));
EXPECT_EQ("false - not subscribed", RunScript("hasSubscription()"));
histogram_tester_.ExpectUniqueSample(
"PushMessaging.UnregistrationReason",
static_cast<int>(
blink::mojom::PushUnregistrationReason::PERMISSION_REVOKED),
1);
EXPECT_THAT(PushMessagingUnsubscribedEntry::GetAll(GetBrowser()->profile()),
ElementsAre(Property(
&PushMessagingUnsubscribedEntry::origin,
https_server()->GetURL("/").DeprecatedGetOriginAsURL())));
}
IN_PROC_BROWSER_TEST_F(PushMessagingBrowserTest,
LocalResetNotificationsPermissionUnsubscribes) {
ASSERT_NO_FATAL_FAILURE(SubscribeSuccessfully());
EXPECT_EQ("true - subscribed", RunScript("hasSubscription()"));
EXPECT_EQ("permission status - granted",
RunScript("pushManagerPermissionState()"));
base::RunLoop run_loop;
push_service()->SetContentSettingChangedCallbackForTesting(
run_loop.QuitClosure());
GURL origin = https_server()->GetURL("/").DeprecatedGetOriginAsURL();
HostContentSettingsMapFactory::GetForProfile(GetBrowser()->profile())
->SetContentSettingDefaultScope(origin, GURL(),
ContentSettingsType::NOTIFICATIONS,
CONTENT_SETTING_DEFAULT);
run_loop.Run();
EXPECT_EQ("permission status - prompt",
RunScript("pushManagerPermissionState()"));
EXPECT_EQ("false - not subscribed", RunScript("hasSubscription()"));
histogram_tester_.ExpectUniqueSample(
"PushMessaging.UnregistrationReason",
static_cast<int>(
blink::mojom::PushUnregistrationReason::PERMISSION_REVOKED),
1);
EXPECT_THAT(
PushMessagingUnsubscribedEntry::GetAll(GetBrowser()->profile()),
ElementsAre(Property(&PushMessagingUnsubscribedEntry::origin, origin)));
}
IN_PROC_BROWSER_TEST_F(PushMessagingBrowserTest,
DenyNotificationsPermissionUnsubscribes) {
ASSERT_NO_FATAL_FAILURE(SubscribeSuccessfully());
EXPECT_EQ("true - subscribed", RunScript("hasSubscription()"));
EXPECT_EQ("permission status - granted",
RunScript("pushManagerPermissionState()"));
base::RunLoop run_loop;
push_service()->SetContentSettingChangedCallbackForTesting(
run_loop.QuitClosure());
GURL origin = https_server()->GetURL("/").DeprecatedGetOriginAsURL();
HostContentSettingsMapFactory::GetForProfile(GetBrowser()->profile())
->SetContentSettingDefaultScope(origin, GURL(),
ContentSettingsType::NOTIFICATIONS,
CONTENT_SETTING_BLOCK);
run_loop.Run();
EXPECT_EQ("permission status - denied",
RunScript("pushManagerPermissionState()"));
EXPECT_EQ("false - not subscribed", RunScript("hasSubscription()"));
histogram_tester_.ExpectUniqueSample(
"PushMessaging.UnregistrationReason",
static_cast<int>(
blink::mojom::PushUnregistrationReason::PERMISSION_REVOKED),
1);
EXPECT_THAT(
PushMessagingUnsubscribedEntry::GetAll(GetBrowser()->profile()),
ElementsAre(Property(&PushMessagingUnsubscribedEntry::origin, origin)));
}
IN_PROC_BROWSER_TEST_F(PushMessagingBrowserTest,
GrantAlreadyGrantedPermissionDoesNotUnsubscribe) {
ASSERT_NO_FATAL_FAILURE(SubscribeSuccessfully());
EXPECT_EQ("true - subscribed", RunScript("hasSubscription()"));
EXPECT_EQ("permission status - granted",
RunScript("pushManagerPermissionState()"));
base::RunLoop run_loop;
push_service()->SetContentSettingChangedCallbackForTesting(
run_loop.QuitClosure());
GURL origin = https_server()->GetURL("/").DeprecatedGetOriginAsURL();
HostContentSettingsMapFactory::GetForProfile(GetBrowser()->profile())
->SetContentSettingDefaultScope(origin, GURL(),
ContentSettingsType::NOTIFICATIONS,
CONTENT_SETTING_ALLOW);
run_loop.Run();
EXPECT_EQ("permission status - granted",
RunScript("pushManagerPermissionState()"));
EXPECT_EQ("true - subscribed", RunScript("hasSubscription()"));
histogram_tester_.ExpectTotalCount("PushMessaging.UnregistrationReason", 0);
EXPECT_THAT(PushMessagingUnsubscribedEntry::GetAll(GetBrowser()->profile()),
IsEmpty());
}
// This test is testing some non-trivial content settings rules and make sure
// that they are respected with regards to automatic unsubscription. In other
// words, it checks that the push service does not end up unsubscribing origins
// that have push permission with some non-common rules.
IN_PROC_BROWSER_TEST_F(PushMessagingBrowserTest,
AutomaticUnsubscriptionFollowsContentSettingRules) {
ASSERT_NO_FATAL_FAILURE(SubscribeSuccessfully());
EXPECT_EQ("true - subscribed", RunScript("hasSubscription()"));
EXPECT_EQ("permission status - granted",
RunScript("pushManagerPermissionState()"));
base::RunLoop run_loop;
push_service()->SetContentSettingChangedCallbackForTesting(
base::BarrierClosure(2, run_loop.QuitClosure()));
GURL origin = https_server()->GetURL("/").DeprecatedGetOriginAsURL();
HostContentSettingsMapFactory::GetForProfile(GetBrowser()->profile())
->SetDefaultContentSetting(ContentSettingsType::NOTIFICATIONS,
CONTENT_SETTING_ALLOW);
HostContentSettingsMapFactory::GetForProfile(GetBrowser()->profile())
->SetContentSettingDefaultScope(origin, GURL(),
ContentSettingsType::NOTIFICATIONS,
CONTENT_SETTING_DEFAULT);
run_loop.Run();
// The two first rules should give |origin| the permission to use Push even
// if the rules it used to have have been reset.
// The Push service should not unsubscribe |origin| because at no point it was
// left without permission to use Push.
EXPECT_EQ("permission status - granted",
RunScript("pushManagerPermissionState()"));
EXPECT_EQ("true - subscribed", RunScript("hasSubscription()"));
histogram_tester_.ExpectTotalCount("PushMessaging.UnregistrationReason", 0);
EXPECT_THAT(PushMessagingUnsubscribedEntry::GetAll(GetBrowser()->profile()),
IsEmpty());
}
// Checks automatically unsubscribing due to a revoked permission after
// previously clearing site data, under legacy conditions (ie. when
// unregistering a worker did not unsubscribe from push.)
IN_PROC_BROWSER_TEST_F(
PushMessagingBrowserTest,
ResetPushPermissionAfterClearingSiteDataUnderLegacyConditions) {
std::string app_id;
ASSERT_NO_FATAL_FAILURE(SetupOrphanedPushSubscription(&app_id));
// Simulate a user clearing site data (including Service Workers, crucially).
content::BrowsingDataRemover* remover =
GetBrowser()->profile()->GetBrowsingDataRemover();
content::BrowsingDataRemoverCompletionObserver observer(remover);
remover->RemoveAndReply(
base::Time(), base::Time::Max(),
chrome_browsing_data_remover::DATA_TYPE_SITE_DATA,
content::BrowsingDataRemover::ORIGIN_TYPE_UNPROTECTED_WEB, &observer);
observer.BlockUntilCompletion();
base::RunLoop run_loop;
push_service()->SetContentSettingChangedCallbackForTesting(
run_loop.QuitClosure());
// This shouldn't (asynchronously) cause a DCHECK.
// TODO(johnme): Get this test running on Android with legacy GCM
// registrations, which have a different codepath due to sender_id being
// required for unsubscribing there.
HostContentSettingsMapFactory::GetForProfile(GetBrowser()->profile())
->ClearSettingsForOneType(ContentSettingsType::NOTIFICATIONS);
run_loop.Run();
// |app_identifier| should no longer be stored in prefs.
PushMessagingAppIdentifier stored_app_identifier =
PushMessagingAppIdentifier::FindByAppId(GetBrowser()->profile(), app_id);
EXPECT_TRUE(stored_app_identifier.is_null());
histogram_tester_.ExpectUniqueSample(
"PushMessaging.UnregistrationReason",
static_cast<int>(
blink::mojom::PushUnregistrationReason::PERMISSION_REVOKED),
1);
base::RunLoop().RunUntilIdle();
// Revoked permission should trigger an automatic unsubscription attempt.
EXPECT_EQ(app_id, gcm_driver_->last_deletetoken_app_id());
}
IN_PROC_BROWSER_TEST_F(PushMessagingBrowserTest, EncryptionKeyUniqueness) {
std::string token1;
ASSERT_NO_FATAL_FAILURE(
SubscribeSuccessfully(PushSubscriptionKeyFormat::kOmitKey, &token1));
std::string first_public_key = RunScript("GetP256dh()").ExtractString();
EXPECT_GE(first_public_key.size(), 32u);
EXPECT_EQ("unsubscribe result: true", RunScript("unsubscribePush()"));
std::string token2;
ASSERT_NO_FATAL_FAILURE(
SubscribeSuccessfully(PushSubscriptionKeyFormat::kBinary, &token2));
EXPECT_NE(token1, token2);
std::string second_public_key = RunScript("GetP256dh()").ExtractString();
EXPECT_GE(second_public_key.size(), 32u);
EXPECT_NE(first_public_key, second_public_key);
}
class PushMessagingIncognitoBrowserTest : public PushMessagingBrowserTestBase {
public:
PushMessagingIncognitoBrowserTest()
: prerender_helper_(base::BindRepeating(
&PushMessagingIncognitoBrowserTest::web_contents,
base::Unretained(this))) {}
~PushMessagingIncognitoBrowserTest() override = default;
// PushMessagingBrowserTest:
void SetUpOnMainThread() override {
incognito_browser_ = CreateIncognitoBrowser();
// We SetUp here rather than in SetUp since the https_server isn't yet
// created at that time.
prerender_helper_.RegisterServerRequestMonitor(https_server());
PushMessagingBrowserTestBase::SetUpOnMainThread();
}
Browser* GetBrowser() const override { return incognito_browser_; }
content::WebContents* web_contents() {
return GetBrowser()->tab_strip_model()->GetActiveWebContents();
}
protected:
content::test::PrerenderTestHelper prerender_helper_;
raw_ptr<Browser, AcrossTasksDanglingUntriaged> incognito_browser_ = nullptr;
};
// Regression test for https://crbug.com/476474
IN_PROC_BROWSER_TEST_F(PushMessagingIncognitoBrowserTest,
IncognitoGetSubscriptionDoesNotHang) {
ASSERT_TRUE(GetBrowser()->profile()->IsOffTheRecord());
ASSERT_EQ("ok - service worker registered",
RunScript("registerServiceWorker()"));
// In Incognito mode the promise returned by getSubscription should not hang,
// it should just fulfill with null.
ASSERT_EQ("false - not subscribed", RunScript("hasSubscription()"));
}
IN_PROC_BROWSER_TEST_F(PushMessagingIncognitoBrowserTest, WarningToCorrectRFH) {
ASSERT_TRUE(GetBrowser()->profile()->IsOffTheRecord());
content::WebContentsConsoleObserver console_observer(web_contents());
console_observer.SetPattern(kIncognitoWarningPattern);
// Filter out the main frame host of the currently active page.
console_observer.SetFilter(base::BindLambdaForTesting(
[&](const content::WebContentsConsoleObserver::Message& message) {
return message.source_frame->IsInPrimaryMainFrame();
}));
ASSERT_EQ("ok - service worker registered",
RunScript("registerServiceWorker()"));
ASSERT_EQ("AbortError - Registration failed - permission denied",
RunScript("documentSubscribePush()"));
ASSERT_TRUE(console_observer.Wait());
EXPECT_EQ(1u, console_observer.messages().size());
}
// TODO(crbug.com/40204670): This test hits the issue. Re-enable after it
// is fixed.
IN_PROC_BROWSER_TEST_F(PushMessagingIncognitoBrowserTest,
DISABLED_WarningToCorrectRFH_Prerender) {
ASSERT_TRUE(GetBrowser()->profile()->IsOffTheRecord());
// Load an initial page.
const GURL initial_url(https_server()->GetURL(GetTestURL()));
prerender_helper_.NavigatePrimaryPage(initial_url);
// Register a service worker. This must be done in the primary page as the
// service worker registration in a prerendered page is deferred until
// prerender page activation.
ASSERT_EQ("ok - service worker registered",
content::EvalJs(web_contents()->GetPrimaryMainFrame(),
"registerServiceWorker()"));
// Start a prerender with the push messaging test URL.
const GURL prerendering_url(
https_server()->GetURL(GetTestURL() + "?prerendering"));
content::FrameTreeNodeId host_id =
prerender_helper_.AddPrerender(prerendering_url);
content::test::PrerenderHostObserver prerender_observer(*web_contents(),
host_id);
ASSERT_TRUE(prerender_helper_.GetHostForUrl(prerendering_url));
content::WebContentsConsoleObserver console_observer(web_contents());
console_observer.SetPattern(kIncognitoWarningPattern);
// Filter out the main frame host of the prerendered page.
content::RenderFrameHost* prerender_rfh =
prerender_helper_.GetPrerenderedMainFrameHost(host_id);
console_observer.SetFilter(base::BindLambdaForTesting(
[&](const content::WebContentsConsoleObserver::Message& message) {
return message.source_frame == prerender_rfh;
}));
// Use ExecuteScriptAsync because binding of blink::mojom::PushMessaging
// is deferred for the prerendered page. Script execution will finish after
// the activation.
ExecuteScriptAsync(prerender_rfh, "documentSubscribePush()");
// Activate the prerendered page and wait for a response of script execution.
content::DOMMessageQueue message_queue(web_contents());
prerender_helper_.NavigatePrimaryPage(prerendering_url);
// Make sure that the prerender was activated.
ASSERT_TRUE(prerender_observer.was_activated());
std::string script_result;
do {
ASSERT_TRUE(message_queue.WaitForMessage(&script_result));
} while (script_result !=
"\"AbortError - Registration failed - permission denied\"");
ASSERT_TRUE(console_observer.Wait());
EXPECT_EQ(1u, console_observer.messages().size());
}
class PushMessagingDisallowSenderIdsBrowserTest
: public PushMessagingBrowserTestBase {
public:
PushMessagingDisallowSenderIdsBrowserTest() {
scoped_feature_list_.InitAndEnableFeature(
features::kPushMessagingDisallowSenderIDs);
}
~PushMessagingDisallowSenderIdsBrowserTest() override = default;
private:
base::test::ScopedFeatureList scoped_feature_list_;
};
IN_PROC_BROWSER_TEST_F(PushMessagingDisallowSenderIdsBrowserTest,
SubscriptionWithSenderIdFails) {
ASSERT_EQ("ok - service worker registered",
RunScript("registerServiceWorker()"));
ASSERT_NO_FATAL_FAILURE(RequestAndAcceptPermission());
LoadTestPage(); // Reload to become controlled.
ASSERT_EQ("true - is controlled", RunScript("isControlled()"));
// Attempt to create a subscription with a GCM Sender ID ("numeric key"),
// which should fail because the kPushMessagingDisallowSenderIDs feature has
// been enabled for this test.
EXPECT_EQ(
"AbortError - Registration failed - GCM Sender IDs are no longer "
"supported, please upgrade to VAPID authentication instead",
RunScript("documentSubscribePushWithNumericKey()"));
}
class PushSubscriptionWithExpirationTimeTest
: public PushMessagingBrowserTestBase {
public:
PushSubscriptionWithExpirationTimeTest() {
scoped_feature_list_.InitAndEnableFeature(
features::kPushSubscriptionWithExpirationTime);
}
~PushSubscriptionWithExpirationTimeTest() override = default;
// Checks whether |expiration_time| lies in the future and is in the
// valid format (seconds elapsed since Unix time)
bool IsExpirationTimeValid(const std::string& expiration_time);
private:
base::test::ScopedFeatureList scoped_feature_list_;
};
bool PushSubscriptionWithExpirationTimeTest::IsExpirationTimeValid(
const std::string& expiration_time) {
int64_t output;
if (!base::StringToInt64(expiration_time, &output))
return false;
return base::Time::Now().InMillisecondsFSinceUnixEpochIgnoringNull() < output;
}
IN_PROC_BROWSER_TEST_F(PushSubscriptionWithExpirationTimeTest,
SubscribeGetSubscriptionWithExpirationTime) {
ASSERT_EQ("ok - service worker registered",
RunScript("registerServiceWorker()"));
ASSERT_NO_FATAL_FAILURE(RequestAndAcceptPermission());
LoadTestPage(); // Reload to become controlled.
ASSERT_EQ("true - is controlled", RunScript("isControlled()"));
// Subscribe with expiration time enabled, should get a subscription with
// expiration time in the future back
std::string subscription_expiration_time =
RunScript("documentSubscribePushGetExpirationTime()").ExtractString();
EXPECT_TRUE(IsExpirationTimeValid(subscription_expiration_time));
// Get subscription should also yield a subscription with expiration time
std::string get_subscription_expiration_time =
RunScript("GetSubscriptionExpirationTime()").ExtractString();
EXPECT_TRUE(IsExpirationTimeValid(get_subscription_expiration_time));
// Both methods should return the same expiration time
ASSERT_EQ(subscription_expiration_time, get_subscription_expiration_time);
}
IN_PROC_BROWSER_TEST_F(PushSubscriptionWithExpirationTimeTest,
GetSubscriptionWithExpirationTime) {
ASSERT_NO_FATAL_FAILURE(SubscribeSuccessfully());
EXPECT_EQ("true - subscribed", RunScript("hasSubscription()"));
// Get subscription should also yield a subscription with expiration time
EXPECT_TRUE(IsExpirationTimeValid(
RunScript("GetSubscriptionExpirationTime()").ExtractString()));
}
class PushSubscriptionWithoutExpirationTimeTest
: public PushMessagingBrowserTestBase {
public:
PushSubscriptionWithoutExpirationTimeTest() {
// Override current feature list to ensure having
// |kPushSubscriptionWithExpirationTime| disabled
scoped_feature_list_.InitAndDisableFeature(
features::kPushSubscriptionWithExpirationTime);
}
~PushSubscriptionWithoutExpirationTimeTest() override = default;
private:
base::test::ScopedFeatureList scoped_feature_list_;
};
IN_PROC_BROWSER_TEST_F(PushSubscriptionWithoutExpirationTimeTest,
SubscribeDocumentExpirationTimeNull) {
ASSERT_EQ("ok - service worker registered",
RunScript("registerServiceWorker()"));
ASSERT_NO_FATAL_FAILURE(RequestAndAcceptPermission());
LoadTestPage(); // Reload to become controlled.
ASSERT_EQ("true - is controlled", RunScript("isControlled()"));
// When |features::kPushSubscriptionWithExpirationTime| is disabled,
// expiration time should be null
EXPECT_EQ("null", RunScript("documentSubscribePushGetExpirationTime()"));
}
class PushSubscriptionChangeEventOnInvalidationTest
: public PushMessagingBrowserTestBase {
public:
PushSubscriptionChangeEventOnInvalidationTest() {
scoped_feature_list_.InitWithFeatures(
{features::kPushSubscriptionChangeEventOnInvalidation,
features::kPushSubscriptionWithExpirationTime},
{});
}
~PushSubscriptionChangeEventOnInvalidationTest() override = default;
private:
base::test::ScopedFeatureList scoped_feature_list_;
};
IN_PROC_BROWSER_TEST_F(PushSubscriptionChangeEventOnInvalidationTest,
PushSubscriptionChangeEventSuccess) {
// Create the |old_subscription| by subscribing and unsubscribing again
ASSERT_NO_FATAL_FAILURE(SubscribeSuccessfully());
PushMessagingAppIdentifier app_identifier =
GetAppIdentifierForServiceWorkerRegistration(0LL);
blink::mojom::PushSubscriptionPtr old_subscription =
GetSubscriptionForAppIdentifier(app_identifier);
EXPECT_EQ("unsubscribe result: true", RunScript("unsubscribePush()"));
// There should be no subscription since we unsubscribed
EXPECT_EQ(PushMessagingAppIdentifier::GetCount(GetBrowser()->profile()), 0u);
// Create a |new_subscription| by resubscribing
ASSERT_NO_FATAL_FAILURE(SubscribeSuccessfully());
app_identifier = GetAppIdentifierForServiceWorkerRegistration(0LL);
blink::mojom::PushSubscriptionPtr new_subscription =
GetSubscriptionForAppIdentifier(app_identifier);
// Save the endpoints to compare with the JS result
GURL old_endpoint = old_subscription->endpoint;
GURL new_endpoint = new_subscription->endpoint;
ASSERT_EQ("false - is not controlled", RunScript("isControlled()"));
LoadTestPage(); // Reload to become controlled.
ASSERT_EQ("true - is controlled", RunScript("isControlled()"));
base::RunLoop run_loop;
push_service()->FirePushSubscriptionChangeForAppIdentifier(
app_identifier, run_loop.QuitClosure(), std::move(new_subscription),
std::move(old_subscription));
run_loop.Run();
// Compare old subscription
EXPECT_EQ(old_endpoint.spec(), RunScript("resultQueue.pop()"));
// Compare new subscription
EXPECT_EQ(new_endpoint.spec(), RunScript("resultQueue.pop()"));
}
IN_PROC_BROWSER_TEST_F(PushSubscriptionChangeEventOnInvalidationTest,
FiredAfterPermissionRevoked) {
ASSERT_NO_FATAL_FAILURE(SubscribeSuccessfully());
EXPECT_EQ("true - subscribed", RunScript("hasSubscription()"));
EXPECT_EQ("permission status - granted",
RunScript("pushManagerPermissionState()"));
ASSERT_EQ("false - is not controlled", RunScript("isControlled()"));
LoadTestPage(); // Reload to become controlled.
ASSERT_EQ("true - is controlled", RunScript("isControlled()"));
PushMessagingAppIdentifier app_identifier =
GetAppIdentifierForServiceWorkerRegistration(0LL);
auto old_subscription = GetSubscriptionForAppIdentifier(app_identifier);
base::RunLoop run_loop;
push_service()->SetContentSettingChangedCallbackForTesting(
run_loop.QuitClosure());
HostContentSettingsMapFactory::GetForProfile(GetBrowser()->profile())
->SetContentSettingDefaultScope(app_identifier.origin(), GURL(),
ContentSettingsType::NOTIFICATIONS,
CONTENT_SETTING_BLOCK);
run_loop.Run();
EXPECT_EQ("permission status - denied",
RunScript("pushManagerPermissionState()"));
// Check if the pushsubscriptionchangeevent arrived in the document and
// whether the |old_subscription| has the expected endpoint and
// |new_subscription| is null
EXPECT_EQ(old_subscription->endpoint.spec(), RunScript("resultQueue.pop()"));
EXPECT_EQ("null", RunScript("resultQueue.pop()"));
}
IN_PROC_BROWSER_TEST_F(PushSubscriptionChangeEventOnInvalidationTest,
OnInvalidation) {
ASSERT_NO_FATAL_FAILURE(SubscribeSuccessfully());
EXPECT_EQ("true - subscribed", RunScript("hasSubscription()"));
ASSERT_EQ("false - is not controlled", RunScript("isControlled()"));
LoadTestPage(); // Reload to become controlled.
ASSERT_EQ("true - is controlled", RunScript("isControlled()"));
PushMessagingAppIdentifier app_identifier =
GetAppIdentifierForServiceWorkerRegistration(0LL);
ASSERT_FALSE(app_identifier.is_null());
base::RunLoop run_loop;
push_service()->SetInvalidationCallbackForTesting(run_loop.QuitClosure());
push_service()->OnSubscriptionInvalidation(app_identifier.app_id());
run_loop.Run();
// Old subscription should be gone
PushMessagingAppIdentifier deleted_identifier =
PushMessagingAppIdentifier::FindByAppId(GetBrowser()->profile(),
app_identifier.app_id());
EXPECT_TRUE(deleted_identifier.is_null());
// New subscription with a different app id should exist
PushMessagingAppIdentifier new_identifier =
PushMessagingAppIdentifier::FindByServiceWorker(
GetBrowser()->profile(), app_identifier.origin(),
app_identifier.service_worker_registration_id());
EXPECT_FALSE(new_identifier.is_null());
base::RunLoop().RunUntilIdle();
// Expect `pushsubscriptionchange` event that is not null
EXPECT_NE("null", RunScript("resultQueue.pop()"));
EXPECT_NE("null", RunScript("resultQueue.pop()"));
}
using PushSubscriptionChangeEventOnResubscribeTest =
PushMessagingBrowserTestBase;
IN_PROC_BROWSER_TEST_F(PushSubscriptionChangeEventOnResubscribeTest,
FiredAfterPermissionBlockedAndRegranted) {
ASSERT_NO_FATAL_FAILURE(SubscribeSuccessfully());
EXPECT_EQ("true - subscribed", RunScript("hasSubscription()"));
EXPECT_EQ("permission status - granted",
RunScript("pushManagerPermissionState()"));
ASSERT_EQ("false - is not controlled", RunScript("isControlled()"));
LoadTestPage(); // Reload to become controlled.
ASSERT_EQ("true - is controlled", RunScript("isControlled()"));
PushMessagingAppIdentifier app_identifier =
GetAppIdentifierForServiceWorkerRegistration(0LL);
{
base::RunLoop run_loop;
push_service()->SetContentSettingChangedCallbackForTesting(
run_loop.QuitClosure());
HostContentSettingsMapFactory::GetForProfile(GetBrowser()->profile())
->SetContentSettingDefaultScope(app_identifier.origin(), GURL(),
ContentSettingsType::NOTIFICATIONS,
CONTENT_SETTING_BLOCK);
run_loop.Run();
}
EXPECT_EQ("permission status - denied",
RunScript("pushManagerPermissionState()"));
{
base::RunLoop run_loop;
push_service()->SetContentSettingChangedCallbackForTesting(
run_loop.QuitClosure());
HostContentSettingsMapFactory::GetForProfile(GetBrowser()->profile())
->SetContentSettingDefaultScope(app_identifier.origin(), GURL(),
ContentSettingsType::NOTIFICATIONS,
CONTENT_SETTING_ALLOW);
run_loop.Run();
}
histogram_tester_.ExpectBucketCount("PushMessaging.NumUnsubscribedEntries", 1,
1);
histogram_tester_.ExpectBucketCount(
"PushMessaging."
"PushSubscriptionChangeForNotificationPermissionChangeFired",
1, 1);
EXPECT_EQ("permission status - granted",
RunScript("pushManagerPermissionState()"));
// Check if the `pushsubscriptionchange` event arrived in the service worker.
// Upon firing the `pushsubscriptionchange` event, the service worker will
// respond to the test runner with the old and new endpoints. Both will be
// NULL when the event fires after permission has been reset, as the old
// subscription had already been deleted and no new subscription is created
// automatically.
EXPECT_EQ("null", RunScript("resultQueue.pop()"));
EXPECT_EQ("null", RunScript("resultQueue.pop()"));
// The unsubscribed entry should not be deleted yet, since the subscription
// has not been recreated.
EXPECT_THAT(PushMessagingUnsubscribedEntry::GetAll(GetBrowser()->profile()),
ElementsAre(Property(&PushMessagingUnsubscribedEntry::origin,
app_identifier.origin())));
EXPECT_EQ("false - not subscribed", RunScript("hasSubscription()"));
// Now resubscribe from the worker.
ASSERT_NO_FATAL_FAILURE(
EndpointToToken(RunScript("workerSubscribePush()").ExtractString(),
true /* standard_protocol */));
EXPECT_EQ("true - subscribed", RunScript("hasSubscription()"));
// Now the unsubscribed entry should have been deleted.
EXPECT_THAT(PushMessagingUnsubscribedEntry::GetAll(GetBrowser()->profile()),
IsEmpty());
}
IN_PROC_BROWSER_TEST_F(PushSubscriptionChangeEventOnResubscribeTest,
FiredAfterPermissionResetAndRegranted) {
ASSERT_NO_FATAL_FAILURE(SubscribeSuccessfully());
EXPECT_EQ("true - subscribed", RunScript("hasSubscription()"));
EXPECT_EQ("permission status - granted",
RunScript("pushManagerPermissionState()"));
ASSERT_EQ("false - is not controlled", RunScript("isControlled()"));
LoadTestPage(); // Reload to become controlled.
ASSERT_EQ("true - is controlled", RunScript("isControlled()"));
PushMessagingAppIdentifier app_identifier =
GetAppIdentifierForServiceWorkerRegistration(0LL);
{
base::RunLoop run_loop;
push_service()->SetContentSettingChangedCallbackForTesting(
run_loop.QuitClosure());
HostContentSettingsMapFactory::GetForProfile(GetBrowser()->profile())
->SetContentSettingDefaultScope(app_identifier.origin(), GURL(),
ContentSettingsType::NOTIFICATIONS,
CONTENT_SETTING_ASK);
run_loop.Run();
}
EXPECT_EQ("permission status - prompt",
RunScript("pushManagerPermissionState()"));
{
base::RunLoop run_loop;
push_service()->SetContentSettingChangedCallbackForTesting(
run_loop.QuitClosure());
HostContentSettingsMapFactory::GetForProfile(GetBrowser()->profile())
->SetContentSettingDefaultScope(app_identifier.origin(), GURL(),
ContentSettingsType::NOTIFICATIONS,
CONTENT_SETTING_ALLOW);
run_loop.Run();
}
histogram_tester_.ExpectBucketCount("PushMessaging.NumUnsubscribedEntries", 1,
1);
histogram_tester_.ExpectBucketCount(
"PushMessaging."
"PushSubscriptionChangeForNotificationPermissionChangeFired",
1, 1);
EXPECT_EQ("permission status - granted",
RunScript("pushManagerPermissionState()"));
// Check if the `pushsubscriptionchange` event arrived in the service worker.
// Upon firing the `pushsubscriptionchange` event, the service worker will
// respond to the test runner with the old and new endpoints. Both will be
// NULL when the event fires after permission has been reset, as the old
// subscription had already been deleted and no new subscription is created
// automatically.
EXPECT_EQ("null", RunScript("resultQueue.pop()"));
EXPECT_EQ("null", RunScript("resultQueue.pop()"));
// The unsubscribed entry should not be deleted yet, since the subscription
// has not been recreated.
EXPECT_THAT(PushMessagingUnsubscribedEntry::GetAll(GetBrowser()->profile()),
ElementsAre(Property(&PushMessagingUnsubscribedEntry::origin,
app_identifier.origin())));
EXPECT_EQ("false - not subscribed", RunScript("hasSubscription()"));
// Now resubscribe from the worker.
ASSERT_NO_FATAL_FAILURE(
EndpointToToken(RunScript("workerSubscribePush()").ExtractString(),
true /* standard_protocol */));
EXPECT_EQ("true - subscribed", RunScript("hasSubscription()"));
// Now the unsubscribed entry should have been deleted.
EXPECT_THAT(PushMessagingUnsubscribedEntry::GetAll(GetBrowser()->profile()),
IsEmpty());
}
IN_PROC_BROWSER_TEST_F(PushSubscriptionChangeEventOnResubscribeTest,
FiredAfterGlobalPermissionResetAndRegranted) {
ASSERT_NO_FATAL_FAILURE(SubscribeSuccessfully());
EXPECT_EQ("true - subscribed", RunScript("hasSubscription()"));
EXPECT_EQ("permission status - granted",
RunScript("pushManagerPermissionState()"));
ASSERT_EQ("false - is not controlled", RunScript("isControlled()"));
LoadTestPage(); // Reload to become controlled.
ASSERT_EQ("true - is controlled", RunScript("isControlled()"));
PushMessagingAppIdentifier app_identifier =
GetAppIdentifierForServiceWorkerRegistration(0LL);
{
base::RunLoop run_loop;
push_service()->SetContentSettingChangedCallbackForTesting(
run_loop.QuitClosure());
HostContentSettingsMapFactory::GetForProfile(GetBrowser()->profile())
->ClearSettingsForOneType(ContentSettingsType::NOTIFICATIONS);
run_loop.Run();
}
EXPECT_EQ("permission status - prompt",
RunScript("pushManagerPermissionState()"));
{
base::RunLoop run_loop;
push_service()->SetContentSettingChangedCallbackForTesting(
run_loop.QuitClosure());
HostContentSettingsMapFactory::GetForProfile(GetBrowser()->profile())
->SetContentSettingDefaultScope(app_identifier.origin(), GURL(),
ContentSettingsType::NOTIFICATIONS,
CONTENT_SETTING_ALLOW);
run_loop.Run();
}
histogram_tester_.ExpectBucketCount("PushMessaging.NumUnsubscribedEntries", 1,
1);
histogram_tester_.ExpectBucketCount(
"PushMessaging."
"PushSubscriptionChangeForNotificationPermissionChangeFired",
1, 1);
EXPECT_EQ("permission status - granted",
RunScript("pushManagerPermissionState()"));
// Check if the `pushsubscriptionchange` event arrived in the service worker.
// Upon firing the `pushsubscriptionchange` event, the service worker will
// respond to the test runner with the old and new endpoints. Both will be
// NULL when the event fires after permission has been reset, as the old
// subscription had already been deleted and no new subscription is created
// automatically.
EXPECT_EQ("null", RunScript("resultQueue.pop()"));
EXPECT_EQ("null", RunScript("resultQueue.pop()"));
// The unsubscribed entry should not be deleted yet, since the subscription
// has not been recreated.
EXPECT_THAT(PushMessagingUnsubscribedEntry::GetAll(GetBrowser()->profile()),
ElementsAre(Property(&PushMessagingUnsubscribedEntry::origin,
app_identifier.origin())));
EXPECT_EQ("false - not subscribed", RunScript("hasSubscription()"));
// Now resubscribe from the worker.
ASSERT_NO_FATAL_FAILURE(
EndpointToToken(RunScript("workerSubscribePush()").ExtractString(),
true /* standard_protocol */));
EXPECT_EQ("true - subscribed", RunScript("hasSubscription()"));
// Now the unsubscribed entry should have been deleted.
EXPECT_THAT(PushMessagingUnsubscribedEntry::GetAll(GetBrowser()->profile()),
IsEmpty());
}
IN_PROC_BROWSER_TEST_F(PushSubscriptionChangeEventOnResubscribeTest,
NotFiredForWildcardContentSettingRegranted) {
ASSERT_EQ("ok - service worker registered",
RunScript("registerServiceWorker()"));
ASSERT_EQ("manifest removed", RunScript("removeManifest()"));
{
base::RunLoop run_loop;
push_service()->SetContentSettingChangedCallbackForTesting(
run_loop.QuitClosure());
HostContentSettingsMapFactory::GetForProfile(GetBrowser()->profile())
->SetContentSettingCustomScope(ContentSettingsPattern::Wildcard(),
ContentSettingsPattern::Wildcard(),
ContentSettingsType::NOTIFICATIONS,
CONTENT_SETTING_ALLOW);
run_loop.Run();
}
ASSERT_NO_FATAL_FAILURE(EndpointToToken(
RunScript("documentSubscribePush()").ExtractString(), true, nullptr));
EXPECT_EQ("true - subscribed", RunScript("hasSubscription()"));
EXPECT_EQ("permission status - granted",
RunScript("pushManagerPermissionState()"));
ASSERT_EQ("false - is not controlled", RunScript("isControlled()"));
LoadTestPage(); // Reload to become controlled.
ASSERT_EQ("true - is controlled", RunScript("isControlled()"));
PushMessagingAppIdentifier app_identifier =
GetAppIdentifierForServiceWorkerRegistration(0LL);
{
base::RunLoop run_loop;
push_service()->SetContentSettingChangedCallbackForTesting(
run_loop.QuitClosure());
HostContentSettingsMapFactory::GetForProfile(GetBrowser()->profile())
->SetContentSettingCustomScope(ContentSettingsPattern::Wildcard(),
ContentSettingsPattern::Wildcard(),
ContentSettingsType::NOTIFICATIONS,
CONTENT_SETTING_BLOCK);
run_loop.Run();
}
EXPECT_EQ("permission status - denied",
RunScript("pushManagerPermissionState()"));
EXPECT_EQ("false - not subscribed", RunScript("hasSubscription()"));
// There should be one unsubscribed entry.
EXPECT_THAT(PushMessagingUnsubscribedEntry::GetAll(GetBrowser()->profile()),
ElementsAre(Property(&PushMessagingUnsubscribedEntry::origin,
app_identifier.origin())));
{
base::RunLoop run_loop;
push_service()->SetContentSettingChangedCallbackForTesting(
run_loop.QuitClosure());
HostContentSettingsMapFactory::GetForProfile(GetBrowser()->profile())
->SetContentSettingCustomScope(ContentSettingsPattern::Wildcard(),
ContentSettingsPattern::Wildcard(),
ContentSettingsType::NOTIFICATIONS,
CONTENT_SETTING_ALLOW);
run_loop.Run();
}
EXPECT_EQ("permission status - granted",
RunScript("pushManagerPermissionState()"));
// The unsubscribed entry should not be deleted.
EXPECT_THAT(PushMessagingUnsubscribedEntry::GetAll(GetBrowser()->profile()),
ElementsAre(Property(&PushMessagingUnsubscribedEntry::origin,
app_identifier.origin())));
EXPECT_EQ("false - not subscribed", RunScript("hasSubscription()"));
// The `pushsubscriptionchange` event should not have been fired. Since it's
// difficult to deterministically check that that didn't happen, we instead
// rely on UMA metrics.
histogram_tester_.ExpectUniqueSample(
"PushMessaging."
"PushSubscriptionChangeForNotificationPermissionChangeFired",
0, 3);
histogram_tester_.ExpectBucketCount("PushMessaging.NumUnsubscribedEntries", 1,
0);
histogram_tester_.ExpectBucketCount("PushMessaging.NumUnsubscribedEntries", 0,
3);
}
class PushSubscriptionChangeEventOnResubscribeWithAutoResubscribeTest
: public PushSubscriptionChangeEventOnResubscribeTest {
protected:
std::string GetTestURL() override {
return PushSubscriptionChangeEventOnResubscribeTest::GetTestURL() +
"?autoResubscribe=true";
}
};
IN_PROC_BROWSER_TEST_F(
PushSubscriptionChangeEventOnResubscribeWithAutoResubscribeTest,
ServiceWorkersResubscribesSuccessfullyAfterRegrant) {
ASSERT_NO_FATAL_FAILURE(SubscribeSuccessfully());
EXPECT_EQ("true - subscribed", RunScript("hasSubscription()"));
EXPECT_EQ("permission status - granted",
RunScript("pushManagerPermissionState()"));
ASSERT_EQ("false - is not controlled", RunScript("isControlled()"));
LoadTestPage(); // Reload to become controlled.
ASSERT_EQ("true - is controlled", RunScript("isControlled()"));
PushMessagingAppIdentifier app_identifier =
GetAppIdentifierForServiceWorkerRegistration(0LL);
{
base::RunLoop run_loop;
push_service()->SetContentSettingChangedCallbackForTesting(
run_loop.QuitClosure());
HostContentSettingsMapFactory::GetForProfile(GetBrowser()->profile())
->SetContentSettingDefaultScope(app_identifier.origin(), GURL(),
ContentSettingsType::NOTIFICATIONS,
CONTENT_SETTING_BLOCK);
run_loop.Run();
}
EXPECT_EQ("permission status - denied",
RunScript("pushManagerPermissionState()"));
{
base::RunLoop run_loop;
push_service()->SetContentSettingChangedCallbackForTesting(
run_loop.QuitClosure());
HostContentSettingsMapFactory::GetForProfile(GetBrowser()->profile())
->SetContentSettingDefaultScope(app_identifier.origin(), GURL(),
ContentSettingsType::NOTIFICATIONS,
CONTENT_SETTING_ALLOW);
run_loop.Run();
}
histogram_tester_.ExpectBucketCount("PushMessaging.NumUnsubscribedEntries", 1,
1);
histogram_tester_.ExpectBucketCount(
"PushMessaging."
"PushSubscriptionChangeForNotificationPermissionChangeFired",
1, 1);
EXPECT_EQ("permission status - granted",
RunScript("pushManagerPermissionState()"));
// Check if the `pushsubscriptionchange` event arrived in the service worker.
// Upon firing the `pushsubscriptionchange` event, the service worker will
// respond to the test runner with the old and new endpoints. Both will be
// NULL when the event fires after permission has been reset, as the old
// subscription had already been deleted and no new subscription is created
// automatically. Afterwards, the service worker will immediately try to
// resubscribe and send to the test runner the new endpoint.
EXPECT_EQ("null", RunScript("resultQueue.pop()"));
EXPECT_EQ("null", RunScript("resultQueue.pop()"));
auto got_new_endpoint = RunScript("resultQueue.pop()");
blink::mojom::PushSubscriptionPtr new_subscription =
GetSubscriptionForAppIdentifier(app_identifier);
EXPECT_EQ(new_subscription->endpoint, got_new_endpoint);
// Now the unsubscribed entry should have been deleted.
EXPECT_THAT(PushMessagingUnsubscribedEntry::GetAll(GetBrowser()->profile()),
IsEmpty());
EXPECT_EQ("true - subscribed", RunScript("hasSubscription()"));
}
|