1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048
|
// Copyright 2017 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/browsing_data/chrome_browsing_data_remover_delegate.h"
#include <stdint.h>
#include <memory>
#include <set>
#include <string>
#include <string_view>
#include <tuple>
#include <utility>
#include <vector>
#include "base/containers/contains.h"
#include "base/containers/flat_set.h"
#include "base/files/file_util.h"
#include "base/functional/bind.h"
#include "base/json/values_util.h"
#include "base/memory/ptr_util.h"
#include "base/memory/raw_ptr.h"
#include "base/memory/raw_ref.h"
#include "base/memory/weak_ptr.h"
#include "base/run_loop.h"
#include "base/scoped_observation.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/stringprintf.h"
#include "base/strings/utf_string_conversions.h"
#include "base/task/single_thread_task_runner.h"
#include "base/task/thread_pool/thread_pool_instance.h"
#include "base/test/bind.h"
#include "base/test/gtest_util.h"
#include "base/test/metrics/histogram_tester.h"
#include "base/test/scoped_feature_list.h"
#include "base/test/scoped_path_override.h"
#include "base/test/simple_test_clock.h"
#include "base/test/test_future.h"
#include "base/test/test_timeouts.h"
#include "base/time/time.h"
#include "base/uuid.h"
#include "build/build_config.h"
#include "chrome/browser/autocomplete/zero_suggest_cache_service_factory.h"
#include "chrome/browser/autofill/personal_data_manager_factory.h"
#include "chrome/browser/autofill/strike_database_factory.h"
#include "chrome/browser/bookmarks/bookmark_model_factory.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/browsing_data/chrome_browsing_data_remover_constants.h"
#include "chrome/browser/browsing_data/chrome_browsing_data_remover_delegate_factory.h"
#include "chrome/browser/content_settings/host_content_settings_map_factory.h"
#include "chrome/browser/custom_handlers/protocol_handler_registry_factory.h"
#include "chrome/browser/domain_reliability/service_factory.h"
#include "chrome/browser/download/chrome_download_manager_delegate.h"
#include "chrome/browser/download/download_core_service_factory.h"
#include "chrome/browser/download/download_core_service_impl.h"
#include "chrome/browser/favicon/favicon_service_factory.h"
#include "chrome/browser/file_system_access/chrome_file_system_access_permission_context.h"
#include "chrome/browser/file_system_access/file_system_access_permission_context_factory.h"
#include "chrome/browser/history/history_service_factory.h"
#include "chrome/browser/language/url_language_histogram_factory.h"
#include "chrome/browser/media/webrtc/media_device_salt_service_factory.h"
#include "chrome/browser/password_manager/account_password_store_factory.h"
#include "chrome/browser/password_manager/profile_password_store_factory.h"
#include "chrome/browser/permissions/permission_actions_history_factory.h"
#include "chrome/browser/permissions/permission_decision_auto_blocker_factory.h"
#include "chrome/browser/privacy_sandbox/privacy_sandbox_settings_factory.h"
#include "chrome/browser/reading_list/reading_list_model_factory.h"
#include "chrome/browser/safe_browsing/safe_browsing_service.h"
#include "chrome/browser/safe_browsing/verdict_cache_manager_factory.h"
#include "chrome/browser/segmentation_platform/segmentation_platform_service_factory.h"
#include "chrome/browser/segmentation_platform/ukm_data_manager_test_utils.h"
#include "chrome/browser/segmentation_platform/ukm_database_client.h"
#include "chrome/browser/signin/chrome_signin_client_factory.h"
#include "chrome/browser/signin/test_signin_client_builder.h"
#include "chrome/browser/spellchecker/spellcheck_custom_dictionary.h"
#include "chrome/browser/spellchecker/spellcheck_factory.h"
#include "chrome/browser/spellchecker/spellcheck_service.h"
#include "chrome/browser/ssl/stateful_ssl_host_state_delegate_factory.h"
#include "chrome/browser/storage/durable_storage_permission_context.h"
#include "chrome/browser/subresource_filter/subresource_filter_profile_context_factory.h"
#include "chrome/browser/sync/sync_service_factory.h"
#include "chrome/browser/tpcd/metadata/manager_factory.h"
#include "chrome/browser/translate/chrome_translate_client.h"
#include "chrome/browser/trusted_vault/trusted_vault_service_factory.h"
#include "chrome/browser/webdata_services/web_data_service_factory.h"
#include "chrome/browser/webid/federated_identity_permission_context.h"
#include "chrome/common/chrome_constants.h"
#include "chrome/common/chrome_features.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/pref_names.h"
#include "chrome/test/base/fake_profile_manager.h"
#include "chrome/test/base/scoped_testing_local_state.h"
#include "chrome/test/base/testing_browser_process.h"
#include "chrome/test/base/testing_profile.h"
#include "chrome/test/base/testing_profile_manager.h"
#include "components/autofill/core/browser/data_manager/addresses/address_data_manager.h"
#include "components/autofill/core/browser/data_manager/payments/payments_data_manager.h"
#include "components/autofill/core/browser/data_manager/personal_data_manager.h"
#include "components/autofill/core/browser/data_manager/personal_data_manager_test_utils.h"
#include "components/autofill/core/browser/data_model/addresses/autofill_profile.h"
#include "components/autofill/core/browser/data_model/payments/credit_card.h"
#include "components/autofill/core/browser/strike_databases/strike_database.h"
#include "components/autofill/core/browser/test_utils/autofill_test_utils.h"
#include "components/autofill/core/browser/test_utils/test_autofill_clock.h"
#include "components/autofill/core/common/autofill_constants.h"
#include "components/autofill/core/common/autofill_features.h"
#include "components/bookmarks/browser/bookmark_model.h"
#include "components/bookmarks/test/bookmark_test_helpers.h"
#include "components/browsing_data/content/browsing_data_helper.h"
#include "components/browsing_data/core/browsing_data_utils.h"
#include "components/browsing_data/core/features.h"
#include "components/client_hints/common/client_hints.h"
#include "components/content_settings/core/browser/content_settings_info.h"
#include "components/content_settings/core/browser/content_settings_registry.h"
#include "components/content_settings/core/browser/host_content_settings_map.h"
#include "components/content_settings/core/browser/website_settings_info.h"
#include "components/content_settings/core/browser/website_settings_registry.h"
#include "components/content_settings/core/common/content_settings.h"
#include "components/content_settings/core/common/content_settings_constraints.h"
#include "components/content_settings/core/common/content_settings_metadata.h"
#include "components/content_settings/core/common/content_settings_pattern.h"
#include "components/content_settings/core/common/content_settings_utils.h"
#include "components/custom_handlers/protocol_handler.h"
#include "components/custom_handlers/protocol_handler_registry.h"
#include "components/custom_handlers/test_protocol_handler_registry_delegate.h"
#include "components/domain_reliability/clear_mode.h"
#include "components/domain_reliability/monitor.h"
#include "components/favicon/core/favicon_service.h"
#include "components/history/core/browser/history_service.h"
#include "components/history/core/common/pref_names.h"
#include "components/language/core/browser/url_language_histogram.h"
#include "components/media_device_salt/media_device_salt_service.h"
#include "components/omnibox/browser/omnibox_prefs.h"
#include "components/omnibox/browser/zero_suggest_cache_service.h"
#include "components/omnibox/common/omnibox_features.h"
#include "components/os_crypt/sync/os_crypt_mocker.h"
#include "components/password_manager/core/browser/password_manager_test_utils.h"
#include "components/password_manager/core/browser/password_store/mock_password_store_interface.h"
#include "components/password_manager/core/browser/password_store/mock_smart_bubble_stats_store.h"
#include "components/password_manager/core/browser/password_store/password_store_consumer.h"
#include "components/password_manager/core/browser/password_store/password_store_interface.h"
#include "components/payments/content/mock_payment_manifest_web_data_service.h"
#include "components/performance_manager/public/user_tuning/prefs.h"
#include "components/permissions/features.h"
#include "components/permissions/permission_actions_history.h"
#include "components/permissions/permission_decision_auto_blocker.h"
#include "components/permissions/permission_request_data.h"
#include "components/permissions/permission_request_enums.h"
#include "components/permissions/permission_uma_util.h"
#include "components/permissions/permission_util.h"
#include "components/permissions/request_type.h"
#include "components/permissions/resolvers/content_setting_permission_resolver.h"
#include "components/privacy_sandbox/privacy_sandbox_attestations/privacy_sandbox_attestations.h"
#include "components/privacy_sandbox/privacy_sandbox_attestations/scoped_privacy_sandbox_attestations.h"
#include "components/privacy_sandbox/privacy_sandbox_settings.h"
#include "components/privacy_sandbox/privacy_sandbox_test_util.h"
#include "components/reading_list/core/mock_reading_list_model_observer.h"
#include "components/reading_list/core/reading_list_model.h"
#include "components/safe_browsing/core/browser/verdict_cache_manager.h"
#include "components/security_interstitials/content/stateful_ssl_host_state_delegate.h"
#include "components/segmentation_platform/public/features.h"
#include "components/site_engagement/content/site_engagement_service.h"
#include "components/site_isolation/pref_names.h"
#include "components/sync/test/test_sync_service.h"
#include "components/tpcd/metadata/browser/manager.h"
#include "components/tpcd/metadata/browser/parser.h"
#include "components/tpcd/metadata/browser/prefs.h"
#include "components/tpcd/metadata/browser/test_support.h"
#include "components/ukm/test_ukm_recorder.h"
#include "content/public/browser/background_tracing_manager.h"
#include "content/public/browser/browser_context.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/browsing_data_filter_builder.h"
#include "content/public/browser/browsing_data_remover.h"
#include "content/public/browser/network_service_instance.h"
#include "content/public/browser/origin_trials_controller_delegate.h"
#include "content/public/browser/storage_partition.h"
#include "content/public/common/content_features.h"
#include "content/public/test/browser_task_environment.h"
#include "content/public/test/browsing_data_remover_test_util.h"
#include "content/public/test/mock_download_manager.h"
#include "content/public/test/test_utils.h"
#include "mojo/public/cpp/bindings/remote.h"
#include "net/base/features.h"
#include "net/base/isolation_info.h"
#include "net/base/network_anonymization_key.h"
#include "net/cookies/canonical_cookie.h"
#include "net/cookies/cookie_access_result.h"
#include "net/cookies/cookie_partition_key_collection.h"
#include "net/http/http_auth.h"
#include "net/http/http_auth_cache.h"
#include "net/http/http_transaction_factory.h"
#include "net/net_buildflags.h"
#include "net/reporting/reporting_target_type.h"
#include "net/url_request/url_request_context.h"
#include "net/url_request/url_request_context_builder.h"
#include "net/url_request/url_request_test_util.h"
#include "services/cert_verifier/public/mojom/cert_verifier_service_factory.mojom.h"
#include "services/data_decoder/public/cpp/test_support/in_process_data_decoder.h"
#include "services/network/network_context.h"
#include "services/network/network_service.h"
#include "services/network/public/cpp/features.h"
#include "services/network/public/mojom/cookie_manager.mojom.h"
#include "services/network/public/mojom/network_context.mojom.h"
#include "third_party/blink/public/common/origin_trials/scoped_test_origin_trial_policy.h"
#include "third_party/skia/include/core/SkBitmap.h"
#include "ui/gfx/favicon_size.h"
#include "url/gurl.h"
#include "url/origin.h"
#include "url/scheme_host_port.h"
#if BUILDFLAG(IS_ANDROID)
#include "base/android/build_info.h"
#include "chrome/browser/android/customtabs/chrome_origin_verifier.h"
#include "chrome/browser/android/search_permissions/search_permissions_service.h"
#include "chrome/browser/android/webapps/webapp_registry.h"
#include "chrome/browser/ui/android/tab_model/tab_model_list.h"
#include "chrome/browser/ui/android/tab_model/tab_model_test_helper.h"
#include "components/password_manager/core/browser/split_stores_and_local_upm.h"
#include "components/payments/content/browser_binding/browser_bound_keys_deleter_factory.h"
#include "components/payments/content/browser_binding/mock_browser_bound_keys_deleter.h"
#include "testing/gmock/include/gmock/gmock.h"
#else
#include "base/task/current_thread.h"
#include "chrome/browser/new_tab_page/microsoft_auth/microsoft_auth_service.h"
#include "chrome/browser/new_tab_page/microsoft_auth/microsoft_auth_service_factory.h"
#include "chrome/browser/ui/webui/ntp_microsoft_auth/ntp_microsoft_auth_untrusted_ui.mojom.h"
#include "chrome/browser/user_education/browser_user_education_storage_service.h"
#include "chrome/browser/user_education/user_education_service.h"
#include "chrome/browser/user_education/user_education_service_factory.h"
#include "chrome/common/pref_names.h"
#include "chrome/common/webui_url_constants.h"
#include "components/lens/lens_features.h"
#include "components/search/ntp_features.h"
#include "components/services/storage/public/mojom/local_storage_control.mojom.h"
#include "components/services/storage/public/mojom/storage_usage_info.mojom.h"
#include "components/sync_preferences/testing_pref_service_syncable.h"
#include "content/public/browser/host_zoom_map.h"
#include "third_party/blink/public/mojom/dom_storage/storage_area.mojom.h"
#endif // BUILDFLAG(IS_ANDROID)
#if !BUILDFLAG(IS_ANDROID)
#include "base/test/test_future.h"
#include "chrome/browser/ui/web_applications/test/isolated_web_app_test_utils.h"
#include "chrome/browser/web_applications/isolated_web_apps/commands/get_controlled_frame_partition_command.h"
#include "chrome/browser/web_applications/isolated_web_apps/test/isolated_web_app_builder.h"
#include "chrome/browser/web_applications/locks/app_lock.h"
#include "chrome/browser/web_applications/test/fake_web_app_provider.h"
#include "chrome/browser/web_applications/test/web_app_install_test_utils.h"
#include "chrome/browser/web_applications/test/web_app_test_utils.h"
#include "chrome/browser/web_applications/web_app.h"
#include "chrome/browser/web_applications/web_app_command_scheduler.h"
#include "chrome/browser/web_applications/web_app_sync_bridge.h"
#endif // !BUILDFLAG(IS_ANDROID)
#if BUILDFLAG(IS_CHROMEOS)
#include "chrome/browser/ash/login/users/fake_chrome_user_manager.h"
#include "chromeos/ash/components/dbus/attestation/fake_attestation_client.h"
#include "chromeos/dbus/tpm_manager/fake_tpm_manager_client.h"
#include "components/account_id/account_id.h"
#include "components/user_manager/scoped_user_manager.h"
#include "components/user_manager/test_helper.h"
#endif // BUILDFLAG(IS_CHROMEOS)
#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS)
#include "components/crash/core/app/crashpad.h"
#include "components/upload_list/crash_upload_list.h"
#endif // BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS)
#if BUILDFLAG(ENABLE_EXTENSIONS_CORE)
#include "chrome/browser/extensions/mock_extension_special_storage_policy.h"
#endif // BUILDFLAG(ENABLE_EXTENSIONS)
#if BUILDFLAG(ENABLE_PLUGINS)
#include "chrome/browser/plugins/chrome_plugin_service_filter.h"
#include "chrome/browser/plugins/plugin_utils.h"
#endif // BUILDFLAG(ENABLE_PLUGINS)
#if BUILDFLAG(ENABLE_REPORTING)
#include <optional>
#include "base/containers/flat_map.h"
#include "base/unguessable_token.h"
#include "net/network_error_logging/network_error_logging_service.h"
#include "net/reporting/reporting_browsing_data_remover.h"
#include "net/reporting/reporting_policy.h"
#include "net/reporting/reporting_service.h"
#endif // BUILDFLAG(ENABLE_REPORTING)
#if BUILDFLAG(ENABLE_NACL)
#include "chrome/browser/nacl_host/nacl_browser_delegate_impl.h"
#include "components/nacl/browser/nacl_browser.h"
#include "components/nacl/common/buildflags.h"
#endif // BUILDFLAG(ENABLE_NACL)
using base::test::TestFuture;
using content::BrowsingDataFilterBuilder;
using domain_reliability::DomainReliabilityClearMode;
using domain_reliability::DomainReliabilityMonitor;
using testing::_;
using testing::ByRef;
using testing::Eq;
using testing::FloatEq;
using testing::Invoke;
using testing::IsEmpty;
using testing::MakeMatcher;
using testing::Matcher;
using testing::MatcherInterface;
using testing::MatchResultListener;
using testing::Return;
using testing::SizeIs;
using testing::UnorderedElementsAre;
using testing::WithArg;
using testing::WithArgs;
namespace constants = chrome_browsing_data_remover;
namespace {
constexpr int kTopicsAPITestTaxonomyVersion = 1;
const char kTestRegisterableDomain1[] = "host1.com";
const char kTestRegisterableDomain3[] = "host3.com";
// For HTTP auth.
const char kTestRealm[] = "TestRealm";
// Shorthands for origin types.
#if BUILDFLAG(ENABLE_EXTENSIONS_CORE)
const uint64_t kExtension = constants::ORIGIN_TYPE_EXTENSION;
#endif
const uint64_t kProtected =
content::BrowsingDataRemover::ORIGIN_TYPE_PROTECTED_WEB;
const uint64_t kUnprotected =
content::BrowsingDataRemover::ORIGIN_TYPE_UNPROTECTED_WEB;
// Same as the MoveArg<> gmock action, but stores the result in a TestFuture
// (which has no assignment operator).
template <int index, typename T>
auto MoveArgToFuture(TestFuture<T>* future) {
return WithArg<index>([future](T arg) { future->SetValue(std::move(arg)); });
}
// Testers --------------------------------------------------------------------
#if BUILDFLAG(IS_ANDROID)
class TestWebappRegistry : public WebappRegistry {
public:
TestWebappRegistry() : WebappRegistry() {}
void UnregisterWebappsForUrls(
const base::RepeatingCallback<bool(const GURL&)>& url_filter) override {
// Mocks out a JNI call.
}
void ClearWebappHistoryForUrls(
const base::RepeatingCallback<bool(const GURL&)>& url_filter) override {
// Mocks out a JNI call.
}
};
class MockTabModel : public TestTabModel {
public:
explicit MockTabModel(TestingProfile* profile) : TestTabModel(profile) {}
MOCK_METHOD(void,
CloseTabsNavigatedInTimeWindow,
(const base::Time& begin_time, const base::Time& end_time),
(override));
};
#endif
class RemoveCookieTester {
public:
RemoveCookieTester() = default;
RemoveCookieTester(const RemoveCookieTester&) = delete;
RemoveCookieTester& operator=(const RemoveCookieTester&) = delete;
// Returns true, if the given cookie exists in the cookie store.
bool ContainsCookie() {
bool result = false;
base::RunLoop run_loop;
cookie_manager_->GetCookieList(
cookie_url_, net::CookieOptions::MakeAllInclusive(),
net::CookiePartitionKeyCollection(),
base::BindLambdaForTesting(
[&](const net::CookieAccessResultList& cookie_list,
const net::CookieAccessResultList& excluded_cookies) {
std::string cookie_line =
net::CanonicalCookie::BuildCookieLine(cookie_list);
if (cookie_line == "A=1") {
result = true;
} else {
EXPECT_EQ("", cookie_line);
result = false;
}
run_loop.Quit();
}));
run_loop.Run();
return result;
}
void AddCookie() {
base::RunLoop run_loop;
auto cookie = net::CanonicalCookie::CreateForTesting(cookie_url_, "A=1",
base::Time::Now());
cookie_manager_->SetCanonicalCookie(
*cookie, cookie_url_, net::CookieOptions::MakeAllInclusive(),
base::BindLambdaForTesting([&](net::CookieAccessResult result) {
EXPECT_TRUE(result.status.IsInclude());
run_loop.Quit();
}));
run_loop.Run();
}
protected:
void SetCookieManager(
mojo::Remote<network::mojom::CookieManager> cookie_manager) {
cookie_manager_ = std::move(cookie_manager);
}
private:
const GURL cookie_url_{"http://host1.com:1"};
mojo::Remote<network::mojom::CookieManager> cookie_manager_;
};
class RemoveSafeBrowsingCookieTester : public RemoveCookieTester {
public:
explicit RemoveSafeBrowsingCookieTester(Profile* profile)
: browser_process_(TestingBrowserProcess::GetGlobal()) {
// TODO(crbug.com/41437292): Port consumers of the |sb_service| to use the
// interface in components/safe_browsing, and remove this cast.
scoped_refptr<safe_browsing::SafeBrowsingService> sb_service =
static_cast<safe_browsing::SafeBrowsingService*>(
safe_browsing::SafeBrowsingService::CreateSafeBrowsingService());
browser_process_->SetSafeBrowsingService(sb_service.get());
sb_service->Initialize();
base::RunLoop().RunUntilIdle();
// Make sure the safe browsing cookie store has no cookies.
// TODO(mmenke): Is this really needed?
base::RunLoop run_loop;
mojo::Remote<network::mojom::CookieManager> cookie_manager;
sb_service->GetNetworkContext(profile)->GetCookieManager(
cookie_manager.BindNewPipeAndPassReceiver());
cookie_manager->DeleteCookies(
network::mojom::CookieDeletionFilter::New(),
base::BindLambdaForTesting(
[&](uint32_t num_deleted) { run_loop.Quit(); }));
run_loop.Run();
SetCookieManager(std::move(cookie_manager));
}
RemoveSafeBrowsingCookieTester(const RemoveSafeBrowsingCookieTester&) =
delete;
RemoveSafeBrowsingCookieTester& operator=(
const RemoveSafeBrowsingCookieTester&) = delete;
virtual ~RemoveSafeBrowsingCookieTester() {
browser_process_->safe_browsing_service()->ShutDown();
base::RunLoop().RunUntilIdle();
browser_process_->SetSafeBrowsingService(nullptr);
}
private:
raw_ptr<TestingBrowserProcess> browser_process_;
};
class RemoveHistoryTester {
public:
RemoveHistoryTester() = default;
RemoveHistoryTester(const RemoveHistoryTester&) = delete;
RemoveHistoryTester& operator=(const RemoveHistoryTester&) = delete;
[[nodiscard]] bool Init(Profile* profile) {
history_service_ = HistoryServiceFactory::GetForProfile(
profile, ServiceAccessType::EXPLICIT_ACCESS);
if (!history_service_) {
return false;
}
return true;
}
// Returns true, if the given URL exists in the history service.
bool HistoryContainsURL(const GURL& url) {
bool contains_url = false;
base::RunLoop run_loop;
base::CancelableTaskTracker tracker;
history_service_->QueryURL(
url, /*want_visits=*/false,
base::BindLambdaForTesting([&](history::QueryURLResult result) {
contains_url = result.success;
run_loop.Quit();
}),
&tracker);
run_loop.Run();
return contains_url;
}
void AddHistory(const GURL& url, base::Time time) {
history_service_->AddPage(url, time, 0, 0, GURL(), history::RedirectList(),
ui::PAGE_TRANSITION_LINK, history::SOURCE_BROWSED,
false);
}
private:
// TestingProfile owns the history service; we shouldn't delete it.
raw_ptr<history::HistoryService> history_service_ = nullptr;
};
class RemoveFaviconTester {
public:
RemoveFaviconTester() = default;
RemoveFaviconTester(const RemoveFaviconTester&) = delete;
RemoveFaviconTester& operator=(const RemoveFaviconTester&) = delete;
[[nodiscard]] bool Init(Profile* profile) {
// Create the history service if it has not been created yet.
history_service_ = HistoryServiceFactory::GetForProfile(
profile, ServiceAccessType::EXPLICIT_ACCESS);
if (!history_service_) {
return false;
}
favicon_service_ = FaviconServiceFactory::GetForProfile(
profile, ServiceAccessType::EXPLICIT_ACCESS);
if (!favicon_service_) {
return false;
}
return true;
}
// Returns true if there is a favicon stored for |page_url| in the favicon
// database.
bool HasFaviconForPageURL(const GURL& page_url) {
RequestFaviconSyncForPageURL(page_url);
return got_favicon_;
}
// Returns true if:
// - There is a favicon stored for |page_url| in the favicon database.
// - The stored favicon is expired.
bool HasExpiredFaviconForPageURL(const GURL& page_url) {
RequestFaviconSyncForPageURL(page_url);
return got_expired_favicon_;
}
// Adds a visit to history and stores an arbitrary favicon bitmap for
// |page_url|.
void VisitAndAddFavicon(const GURL& page_url) {
history_service_->AddPage(page_url, base::Time::Now(), 0, 0, GURL(),
history::RedirectList(), ui::PAGE_TRANSITION_LINK,
history::SOURCE_BROWSED, false);
SkBitmap bitmap;
bitmap.allocN32Pixels(gfx::kFaviconSize, gfx::kFaviconSize);
bitmap.eraseColor(SK_ColorBLUE);
favicon_service_->SetFavicons({page_url}, page_url,
favicon_base::IconType::kFavicon,
gfx::Image::CreateFrom1xBitmap(bitmap));
}
private:
// Synchronously requests the favicon for |page_url| from the favicon
// database.
void RequestFaviconSyncForPageURL(const GURL& page_url) {
base::RunLoop run_loop;
quit_closure_ = run_loop.QuitClosure();
favicon_service_->GetRawFaviconForPageURL(
page_url, {favicon_base::IconType::kFavicon}, gfx::kFaviconSize,
/*fallback_to_host=*/false,
base::BindOnce(&RemoveFaviconTester::SaveResultAndQuit,
base::Unretained(this)),
&tracker_);
run_loop.Run();
}
// Callback for HistoryService::QueryURL.
void SaveResultAndQuit(const favicon_base::FaviconRawBitmapResult& result) {
got_favicon_ = result.is_valid();
got_expired_favicon_ = result.is_valid() && result.expired;
std::move(quit_closure_).Run();
}
// For favicon requests.
base::CancelableTaskTracker tracker_;
bool got_favicon_ = false;
bool got_expired_favicon_ = false;
base::OnceClosure quit_closure_;
// Owned by TestingProfile.
raw_ptr<history::HistoryService> history_service_ = nullptr;
raw_ptr<favicon::FaviconService> favicon_service_ = nullptr;
};
class RemoveUkmDataTester {
public:
static constexpr auto kSegmentId = segmentation_platform::proto::
OPTIMIZATION_TARGET_SEGMENTATION_CHROME_LOW_USER_ENGAGEMENT;
RemoveUkmDataTester() : test_utils_(&ukm_recorder_) {
test_utils_.PreProfileInit(
{{kSegmentId, test_utils_.GetSamplePageLoadMetadata("SELECT 1")}});
}
RemoveUkmDataTester(const RemoveUkmDataTester&) = delete;
RemoveUkmDataTester& operator=(const RemoveUkmDataTester&) = delete;
[[nodiscard]] bool Init(Profile* profile) {
test_utils_.SetupForProfile(profile);
// Run model overrides to start storing UKM metrics.
test_utils_.WaitForUkmObserverRegistration();
return true;
}
void TearDown(Profile* profile) { test_utils_.WillDestroyProfile(profile); }
[[nodiscard]] bool UkmDatabaseContainsURL(const GURL& url) {
return test_utils_.IsUrlInDatabase(url);
}
void AddURL(const GURL& url, base::Time time) {
test_utils_.RecordPageLoadUkm(url, time);
// Wait for URL to be written to database, UKM recorder needs to run all
// necessary tasks before sending observation.
while (!UkmDatabaseContainsURL(url)) {
base::RunLoop().RunUntilIdle();
}
}
private:
ukm::TestUkmRecorder ukm_recorder_;
segmentation_platform::UkmDataManagerTestUtils test_utils_;
};
std::unique_ptr<KeyedService> BuildProtocolHandlerRegistry(
content::BrowserContext* context) {
Profile* profile = Profile::FromBrowserContext(context);
return std::make_unique<custom_handlers::ProtocolHandlerRegistry>(
profile->GetPrefs(),
std::make_unique<custom_handlers::TestProtocolHandlerRegistryDelegate>());
}
class ClearDomainReliabilityTester {
public:
explicit ClearDomainReliabilityTester(TestingProfile* profile) {
static_cast<ChromeBrowsingDataRemoverDelegate*>(
profile->GetBrowsingDataRemoverDelegate())
->OverrideDomainReliabilityClearerForTesting(base::BindRepeating(
&ClearDomainReliabilityTester::Clear, base::Unretained(this)));
}
unsigned clear_count() const { return clear_count_; }
network::mojom::NetworkContext::DomainReliabilityClearMode last_clear_mode()
const {
return last_clear_mode_;
}
const base::RepeatingCallback<bool(const GURL&)>& last_filter() const {
return last_filter_;
}
private:
void Clear(
content::BrowsingDataFilterBuilder* filter_builder,
network::mojom::NetworkContext_DomainReliabilityClearMode mode,
network::mojom::NetworkContext::ClearDomainReliabilityCallback callback) {
++clear_count_;
last_clear_mode_ = mode;
std::move(callback).Run();
last_filter_ = filter_builder->MatchesAllOriginsAndDomains()
? base::RepeatingCallback<bool(const GURL&)>()
: filter_builder->BuildUrlFilter();
}
unsigned clear_count_ = 0;
network::mojom::NetworkContext::DomainReliabilityClearMode last_clear_mode_;
base::RepeatingCallback<bool(const GURL&)> last_filter_;
};
class RemovePermissionPromptCountsTest {
public:
explicit RemovePermissionPromptCountsTest(TestingProfile* profile)
: autoblocker_(
PermissionDecisionAutoBlockerFactory::GetForProfile(profile)) {}
RemovePermissionPromptCountsTest(const RemovePermissionPromptCountsTest&) =
delete;
RemovePermissionPromptCountsTest& operator=(
const RemovePermissionPromptCountsTest&) = delete;
int GetDismissCount(const GURL& url, ContentSettingsType permission) {
return autoblocker_->GetDismissCount(url, permission);
}
int GetIgnoreCount(const GURL& url, ContentSettingsType permission) {
return autoblocker_->GetIgnoreCount(url, permission);
}
bool RecordIgnoreAndEmbargo(const GURL& url, ContentSettingsType permission) {
return autoblocker_->RecordIgnoreAndEmbargo(url, permission, false);
}
bool RecordDismissAndEmbargo(const GURL& url,
ContentSettingsType permission) {
return autoblocker_->RecordDismissAndEmbargo(url, permission, false);
}
bool IsEmbargoed(const GURL& url, ContentSettingsType permission) {
return autoblocker_->IsEmbargoed(url, permission);
}
private:
raw_ptr<permissions::PermissionDecisionAutoBlocker> autoblocker_;
};
namespace {
class TestTpcdManagerDelegate : public tpcd::metadata::Manager::Delegate {
public:
explicit TestTpcdManagerDelegate(ScopedTestingLocalState& local_state)
: local_state_(local_state) {}
void SetTpcdMetadataGrants(const ContentSettingsForOneType& grants) override {
}
PrefService& GetLocalState() override { return *local_state_->Get(); }
private:
const raw_ref<ScopedTestingLocalState> local_state_;
};
} // namespace
class RemoveTpcdMetadataCohortsTester {
public:
explicit RemoveTpcdMetadataCohortsTester(ScopedTestingLocalState& local_state,
TestingProfile* profile)
: test_delegate_(local_state) {
det_generator_ = new tpcd::metadata::DeterministicGenerator();
manager_ = tpcd::metadata::ManagerFactory::GetForProfile(profile);
manager_->SetRandGeneratorForTesting(det_generator_);
manager_->set_delegate_for_testing(test_delegate_);
}
~RemoveTpcdMetadataCohortsTester() {
det_generator_ = nullptr;
manager_ = nullptr;
}
RemoveTpcdMetadataCohortsTester(const RemoveTpcdMetadataCohortsTester&) =
delete;
RemoveTpcdMetadataCohortsTester& operator=(
const RemoveTpcdMetadataCohortsTester&) = delete;
tpcd::metadata::Parser* GetParser() {
return tpcd::metadata::Parser::GetInstance();
}
tpcd::metadata::Manager* GetManager() { return manager_; }
tpcd::metadata::DeterministicGenerator* GetDetGenerator() {
return det_generator_;
}
private:
TestTpcdManagerDelegate test_delegate_;
raw_ptr<tpcd::metadata::Manager> manager_;
raw_ptr<tpcd::metadata::DeterministicGenerator> det_generator_;
};
// Custom matcher to test the equivalence of two URL filters. Since those are
// blackbox predicates, we can only approximate the equivalence by testing
// whether the filter give the same answer for several URLs. This is currently
// good enough for our testing purposes, to distinguish filters that delete or
// preserve origins, empty and non-empty filters and such.
//
// TODO(msramek): BrowsingDataRemover and some of its backends support URL
// filters, but its constructor currently only takes a single URL and constructs
// its own url filter. If an url filter was directly passed to
// BrowsingDataRemover (what should eventually be the case), we can use the same
// instance in the test as well, and thus simply test
// base::RepeatingCallback::Equals() in this matcher.
class ProbablySameFilterMatcher
: public MatcherInterface<
const base::RepeatingCallback<bool(const GURL&)>&> {
public:
explicit ProbablySameFilterMatcher(
const base::RepeatingCallback<bool(const GURL&)>& filter)
: to_match_(filter) {}
bool MatchAndExplain(const base::RepeatingCallback<bool(const GURL&)>& filter,
MatchResultListener* listener) const override {
if (filter.is_null() && to_match_.is_null()) {
return true;
}
if (filter.is_null() != to_match_.is_null()) {
return false;
}
const GURL urls_to_test_[] = {
GURL("http://host1.com:1"), GURL("http://host2.com:1"),
GURL("http://host3.com:1"), GURL("invalid spec")};
for (GURL url : urls_to_test_) {
if (filter.Run(url) != to_match_.Run(url)) {
if (listener) {
*listener << "The filters differ on the URL " << url;
}
return false;
}
}
return true;
}
void DescribeTo(::std::ostream* os) const override {
*os << "is probably the same url filter as " << &to_match_;
}
void DescribeNegationTo(::std::ostream* os) const override {
*os << "is definitely NOT the same url filter as " << &to_match_;
}
private:
const base::RepeatingCallback<bool(const GURL&)> to_match_;
};
inline Matcher<const base::RepeatingCallback<bool(const GURL&)>&>
ProbablySameFilter(const base::RepeatingCallback<bool(const GURL&)>& filter) {
return MakeMatcher(new ProbablySameFilterMatcher(filter));
}
bool ProbablySameFilters(
const base::RepeatingCallback<bool(const GURL&)>& filter1,
const base::RepeatingCallback<bool(const GURL&)>& filter2) {
return ProbablySameFilter(filter1).MatchAndExplain(filter2, nullptr);
}
base::Time AnHourAgo() {
return base::Time::Now() - base::Hours(1);
}
class RemoveDownloadsTester {
public:
explicit RemoveDownloadsTester(TestingProfile* testing_profile)
: download_manager_(new testing::NiceMock<content::MockDownloadManager>) {
testing_profile->SetDownloadManagerForTesting(
base::WrapUnique(download_manager_.get()));
std::unique_ptr<ChromeDownloadManagerDelegate> delegate =
std::make_unique<ChromeDownloadManagerDelegate>(testing_profile);
chrome_download_manager_delegate_ = delegate.get();
service_ =
DownloadCoreServiceFactory::GetForBrowserContext(testing_profile);
service_->SetDownloadManagerDelegateForTesting(std::move(delegate));
EXPECT_CALL(*download_manager_, GetBrowserContext())
.WillRepeatedly(Return(testing_profile));
EXPECT_CALL(*download_manager_, Shutdown());
}
RemoveDownloadsTester(const RemoveDownloadsTester&) = delete;
RemoveDownloadsTester& operator=(const RemoveDownloadsTester&) = delete;
~RemoveDownloadsTester() {
// Drop unowned reference before service destroys it.
chrome_download_manager_delegate_ = nullptr;
service_->SetDownloadManagerDelegateForTesting(nullptr);
}
content::MockDownloadManager* download_manager() { return download_manager_; }
private:
raw_ptr<DownloadCoreService> service_;
raw_ptr<content::MockDownloadManager>
download_manager_; // Owned by testing profile.
raw_ptr<ChromeDownloadManagerDelegate> chrome_download_manager_delegate_;
};
base::RepeatingCallback<bool(const GURL&)> CreateUrlFilterFromOriginFilter(
const base::RepeatingCallback<bool(const url::Origin&)>& origin_filter) {
if (origin_filter.is_null()) {
return base::RepeatingCallback<bool(const GURL&)>();
}
return base::BindLambdaForTesting([origin_filter](const GURL& url) {
return origin_filter.Run(url::Origin::Create(url));
});
}
class RemoveAutofillTester {
public:
explicit RemoveAutofillTester(TestingProfile* profile)
: personal_data_manager_(
autofill::PersonalDataManagerFactory::GetForBrowserContext(
profile)) {}
RemoveAutofillTester(const RemoveAutofillTester&) = delete;
RemoveAutofillTester& operator=(const RemoveAutofillTester&) = delete;
// Returns true if there is at least one address and one card.
bool HasProfileAndCard() const {
return !personal_data_manager_->address_data_manager()
.GetProfiles()
.empty() &&
!personal_data_manager_->payments_data_manager()
.GetCreditCards()
.empty();
}
// Add one profile and one credit cards to the database.
void AddProfileAndCard() {
personal_data_manager_->address_data_manager().AddProfile(
autofill::test::GetFullProfile());
personal_data_manager_->payments_data_manager().AddCreditCard(
autofill::test::GetCreditCard());
autofill::PersonalDataChangedWaiter(*personal_data_manager_).Wait();
}
private:
raw_ptr<autofill::PersonalDataManager> personal_data_manager_;
};
std::unique_ptr<KeyedService> BuildSyncService(
content::BrowserContext* context) {
// Build with sync disabled by default.
auto service = std::make_unique<syncer::TestSyncService>();
service->SetSignedOut();
return service;
}
} // namespace
#if BUILDFLAG(ENABLE_REPORTING)
class MockReportingService : public net::ReportingService {
public:
MockReportingService() = default;
MockReportingService(const MockReportingService&) = delete;
MockReportingService& operator=(const MockReportingService&) = delete;
~MockReportingService() override = default;
// net::ReportingService implementation:
void SetDocumentReportingEndpoints(
const base::UnguessableToken& reporting_source,
const url::Origin& origin,
const net::IsolationInfo& isolation_info,
const base::flat_map<std::string, std::string>& endpoints) override {
NOTREACHED();
}
void SetEnterpriseReportingEndpoints(
const base::flat_map<std::string, GURL>& endpoints) override {
NOTREACHED();
}
void SendReportsAndRemoveSource(
const base::UnguessableToken& reporting_source) override {
NOTREACHED();
}
void QueueReport(
const GURL& url,
const std::optional<base::UnguessableToken>& reporting_source,
const net::NetworkAnonymizationKey& network_anonymization_key,
const std::string& user_agent,
const std::string& group,
const std::string& type,
base::Value::Dict body,
int depth,
net::ReportingTargetType target_type) override {
NOTREACHED();
}
void ProcessReportToHeader(
const url::Origin& origin,
const net::NetworkAnonymizationKey& network_anonymization_key,
const std::string& header_value) override {
NOTREACHED();
}
void RemoveBrowsingData(
uint64_t data_type_mask,
const base::RepeatingCallback<bool(const url::Origin&)>& origin_filter)
override {
++remove_calls_;
last_data_type_mask_ = data_type_mask;
last_origin_filter_ = origin_filter;
}
void RemoveAllBrowsingData(uint64_t data_type_mask) override {
++remove_all_calls_;
last_data_type_mask_ = data_type_mask;
last_origin_filter_ = base::RepeatingCallback<bool(const url::Origin&)>();
}
void OnShutdown() override {}
const net::ReportingPolicy& GetPolicy() const override {
static net::ReportingPolicy dummy_policy_;
NOTREACHED();
}
net::ReportingContext* GetContextForTesting() const override { NOTREACHED(); }
std::vector<raw_ptr<const net::ReportingReport, VectorExperimental>>
GetReports() const override {
NOTREACHED();
}
base::flat_map<url::Origin, std::vector<net::ReportingEndpoint>>
GetV1ReportingEndpointsByOrigin() const override {
NOTREACHED();
}
void AddReportingCacheObserver(
net::ReportingCacheObserver* observer) override {}
void RemoveReportingCacheObserver(
net::ReportingCacheObserver* observer) override {}
int remove_calls() const { return remove_calls_; }
int remove_all_calls() const { return remove_all_calls_; }
uint64_t last_data_type_mask() const { return last_data_type_mask_; }
const base::RepeatingCallback<bool(const url::Origin&)>& last_origin_filter()
const {
return last_origin_filter_;
}
private:
int remove_calls_ = 0;
int remove_all_calls_ = 0;
uint64_t last_data_type_mask_ = 0;
base::RepeatingCallback<bool(const url::Origin&)> last_origin_filter_;
};
class MockNetworkErrorLoggingService : public net::NetworkErrorLoggingService {
public:
MockNetworkErrorLoggingService() = default;
MockNetworkErrorLoggingService(const MockNetworkErrorLoggingService&) =
delete;
MockNetworkErrorLoggingService& operator=(
const MockNetworkErrorLoggingService&) = delete;
~MockNetworkErrorLoggingService() override = default;
// net::NetworkErrorLoggingService implementation:
void OnHeader(const net::NetworkAnonymizationKey& network_anonymization_key,
const url::Origin& origin,
const net::IPAddress& received_ip_address,
const std::string& value) override {
NOTREACHED();
}
void OnRequest(RequestDetails details) override {}
void QueueSignedExchangeReport(SignedExchangeReportDetails details) override {
NOTREACHED();
}
void RemoveBrowsingData(
const base::RepeatingCallback<bool(const url::Origin&)>& origin_filter)
override {
++remove_calls_;
last_origin_filter_ = origin_filter;
}
void RemoveAllBrowsingData() override {
++remove_all_calls_;
last_origin_filter_ = base::RepeatingCallback<bool(const url::Origin&)>();
}
int remove_calls() const { return remove_calls_; }
int remove_all_calls() const { return remove_all_calls_; }
const base::RepeatingCallback<bool(const url::Origin&)>& last_origin_filter()
const {
return last_origin_filter_;
}
private:
int remove_calls_ = 0;
int remove_all_calls_ = 0;
base::RepeatingCallback<bool(const url::Origin&)> last_origin_filter_;
};
#endif // BUILDFLAG(ENABLE_REPORTING)
namespace autofill {
// StrikeDatabaseTester is in the autofill namespace since
// StrikeDatabase declares it as a friend in the autofill namespace.
class StrikeDatabaseTester {
public:
explicit StrikeDatabaseTester(Profile* profile)
: strike_database_(
autofill::StrikeDatabaseFactory::GetForProfile(profile)) {}
bool IsEmpty() {
int num_keys;
base::RunLoop run_loop;
strike_database_->LoadKeys(base::BindLambdaForTesting(
[&](bool success, std::unique_ptr<std::vector<std::string>> keys) {
num_keys = keys.get()->size();
run_loop.Quit();
}));
run_loop.Run();
return (num_keys == 0);
}
private:
raw_ptr<autofill::StrikeDatabase> strike_database_;
};
} // namespace autofill
#if BUILDFLAG(ENABLE_NACL)
class ScopedNaClBrowserDelegate {
public:
~ScopedNaClBrowserDelegate() { nacl::NaClBrowser::ClearAndDeleteDelegate(); }
void Init(ProfileManager* profile_manager) {
nacl::NaClBrowser::SetDelegate(
std::make_unique<NaClBrowserDelegateImpl>(profile_manager));
}
};
#endif // BUILDFLAG(ENABLE_NACL)
// Test Class -----------------------------------------------------------------
class ChromeBrowsingDataRemoverDelegateTest : public testing::Test {
public:
ChromeBrowsingDataRemoverDelegateTest() = default;
ChromeBrowsingDataRemoverDelegateTest(
const ChromeBrowsingDataRemoverDelegateTest&) = delete;
ChromeBrowsingDataRemoverDelegateTest& operator=(
const ChromeBrowsingDataRemoverDelegateTest&) = delete;
~ChromeBrowsingDataRemoverDelegateTest() override = default;
void SetUp() override {
// Make sure the Network Service is started before making a NetworkContext.
content::GetNetworkService();
task_environment_.RunUntilIdle();
background_tracing_manager_ =
content::BackgroundTracingManager::CreateInstance(&tracing_delegate_);
// This needs to be done after the test constructor, so that subclasses
// that initialize a ScopedFeatureList in their constructors can do so
// before the code below potentially kicks off tasks on other threads that
// check if a feature is enabled, to avoid tsan data races.
CHECK(temp_dir_.CreateUniqueTempDir());
profile_manager_ = std::make_unique<TestingProfileManager>(
TestingBrowserProcess::GetGlobal());
CHECK(profile_manager_->SetUp(temp_dir_.GetPath()));
profile_ = profile_manager_->CreateTestingProfile("test_profile",
GetTestingFactories());
#if BUILDFLAG(ENABLE_NACL)
// Clearing Cache will clear PNACL cache, which needs this delegate set.
nacl_browser_delegate_.Init(profile_manager_->profile_manager());
#endif // BUILDFLAG(ENABLE_NACL)
#if !BUILDFLAG(IS_ANDROID)
web_app::test::AwaitStartWebAppProviderAndSubsystems(profile_.get());
#endif // !BUILDFLAG(IS_ANDROID)
remover_ = profile_->GetBrowsingDataRemover();
auto network_context_params = network::mojom::NetworkContextParams::New();
network_context_params->cert_verifier_params =
content::GetCertVerifierParams(
cert_verifier::mojom::CertVerifierCreationParams::New());
mojo::PendingRemote<network::mojom::NetworkContext> network_context_remote;
network_context_ = network::NetworkContext::CreateForTesting(
network::NetworkService::GetNetworkServiceForTesting(),
network_context_remote.InitWithNewPipeAndPassReceiver(),
std::move(network_context_params),
base::BindLambdaForTesting(
[this](net::URLRequestContextBuilder* builder) {
this->ConfigureURLRequestContextBuilder(builder);
}));
profile_->GetDefaultStoragePartition()->SetNetworkContextForTesting(
std::move(network_context_remote));
#if BUILDFLAG(IS_ANDROID)
static_cast<ChromeBrowsingDataRemoverDelegate*>(
profile_->GetBrowsingDataRemoverDelegate())
->OverrideWebappRegistryForTesting(
std::make_unique<TestWebappRegistry>());
#endif
#if BUILDFLAG(IS_CHROMEOS)
chromeos::TpmManagerClient::InitializeFake();
#endif // BUILDFLAG(IS_CHROMEOS)
}
void TearDown() override {
// Destroying the profile triggers a call to leveldb_proto::
// ProtoDatabaseProvider::SetSharedDBDeleteObsoleteDelayForTesting, which
// can race with leveldb_proto::SharedProtoDatabase::OnDatabaseInit
// on another thread. Allowing those tasks to complete before we destroy
// the profile should fix the race.
content::RunAllTasksUntilIdle();
// Drop unowned references before ProfileManager destroys owned references.
remover_ = nullptr;
profile_ = nullptr;
// TestingProfile contains a DOMStorageContext. BrowserContext's destructor
// posts a message to the WEBKIT thread to delete some of its member
// variables. We need to ensure that the profile is destroyed, and that
// the message loop is cleared out, before destroying the threads and loop.
// Otherwise we leak memory.
profile_manager_.reset();
background_tracing_manager_.reset();
base::RunLoop().RunUntilIdle();
}
virtual TestingProfile::TestingFactories GetTestingFactories() {
return {
TestingProfile::TestingFactory{
StatefulSSLHostStateDelegateFactory::GetInstance(),
StatefulSSLHostStateDelegateFactory::GetDefaultFactoryForTesting()},
TestingProfile::TestingFactory{
BookmarkModelFactory::GetInstance(),
BookmarkModelFactory::GetDefaultFactory()},
TestingProfile::TestingFactory{
HistoryServiceFactory::GetInstance(),
HistoryServiceFactory::GetDefaultFactory()},
TestingProfile::TestingFactory{
FaviconServiceFactory::GetInstance(),
FaviconServiceFactory::GetDefaultFactory()},
TestingProfile::TestingFactory{
SpellcheckServiceFactory::GetInstance(),
base::BindRepeating([](content::BrowserContext* profile)
-> std::unique_ptr<KeyedService> {
return std::make_unique<SpellcheckService>(
static_cast<Profile*>(profile));
})},
TestingProfile::TestingFactory{
TrustedVaultServiceFactory::GetInstance(),
TrustedVaultServiceFactory::GetDefaultFactory()},
TestingProfile::TestingFactory{SyncServiceFactory::GetInstance(),
base::BindRepeating(&BuildSyncService)},
TestingProfile::TestingFactory{
ChromeSigninClientFactory::GetInstance(),
base::BindRepeating(&signin::BuildTestSigninClient)},
TestingProfile::TestingFactory{
ProtocolHandlerRegistryFactory::GetInstance(),
base::BindRepeating(&BuildProtocolHandlerRegistry)},
TestingProfile::TestingFactory{
WebDataServiceFactory::GetInstance(),
WebDataServiceFactory::GetDefaultFactory()}};
}
virtual void ConfigureURLRequestContextBuilder(
net::URLRequestContextBuilder* builder) {}
// Returns the set of data types for which the deletion failed.
uint64_t BlockUntilBrowsingDataRemoved(const base::Time& delete_begin,
const base::Time& delete_end,
uint64_t remove_mask,
bool include_protected_origins) {
uint64_t origin_type_mask =
content::BrowsingDataRemover::ORIGIN_TYPE_UNPROTECTED_WEB;
if (include_protected_origins) {
origin_type_mask |=
content::BrowsingDataRemover::ORIGIN_TYPE_PROTECTED_WEB;
}
content::BrowsingDataRemoverCompletionObserver completion_observer(
remover_);
remover_->RemoveAndReply(delete_begin, delete_end, remove_mask,
origin_type_mask, &completion_observer);
base::ThreadPoolInstance::Get()->FlushForTesting();
completion_observer.BlockUntilCompletion();
return completion_observer.failed_data_types();
}
// Prefer using BlockUntilBrowsingDataRemoved() for most cases.
content::BrowsingDataRemover* remover() { return remover_; }
void ExpectRemoveLoginsCreatedBetween(
password_manager::MockPasswordStoreInterface* store,
bool success = true) {
EXPECT_CALL(*store, RemoveLoginsCreatedBetween)
.WillOnce(testing::WithArgs<3, 4>(
[success](base::OnceCallback<void(bool)> complete_callback,
base::OnceCallback<void(bool)> sync_callback) {
if (complete_callback) {
std::move(complete_callback).Run(success);
}
if (sync_callback) {
// In this test, deletions are never uploaded, so sync_callback
// always report false.
std::move(sync_callback).Run(false);
}
}));
}
uint64_t BlockUntilOriginDataRemoved(
const base::Time& delete_begin,
const base::Time& delete_end,
uint64_t remove_mask,
std::unique_ptr<BrowsingDataFilterBuilder> filter_builder) {
content::BrowsingDataRemoverCompletionObserver completion_observer(
remover_);
remover_->RemoveWithFilterAndReply(
delete_begin, delete_end, remove_mask,
content::BrowsingDataRemover::ORIGIN_TYPE_UNPROTECTED_WEB,
std::move(filter_builder), &completion_observer);
base::ThreadPoolInstance::Get()->FlushForTesting();
completion_observer.BlockUntilCompletion();
return completion_observer.failed_data_types();
}
void WaitForReadingListModelLoaded(ReadingListModel* reading_list_model) {
testing::NiceMock<MockReadingListModelObserver> observer_;
base::RunLoop run_loop;
EXPECT_CALL(observer_, ReadingListModelLoaded).WillOnce([&run_loop] {
run_loop.Quit();
});
// If the ReadingListModel is already loaded, it'll call
// ReadingListModelLoaded() immediately.
reading_list_model->AddObserver(&observer_);
run_loop.Run();
reading_list_model->RemoveObserver(&observer_);
}
const base::Time& GetBeginTime() {
return remover_->GetLastUsedBeginTimeForTesting();
}
uint64_t GetRemovalMask() {
return remover_->GetLastUsedRemovalMaskForTesting();
}
uint64_t GetOriginTypeMask() {
return remover_->GetLastUsedOriginTypeMaskForTesting();
}
network::NetworkContext* network_context() { return network_context_.get(); }
TestingProfileManager* GetProfileManager() { return profile_manager_.get(); }
syncer::TestSyncService* sync_service() {
// Overridden in GetTestingFactories().
return static_cast<syncer::TestSyncService*>(
SyncServiceFactory::GetForProfile(profile_));
}
TestingProfile* GetProfile() { return profile_.get(); }
bool Match(const GURL& origin,
uint64_t mask,
storage::SpecialStoragePolicy* policy) {
return remover_->DoesOriginMatchMaskForTesting(
mask, url::Origin::Create(origin), policy);
}
content::BrowserTaskEnvironment* task_environment() {
return &task_environment_;
}
ScopedTestingLocalState& local_state() { return local_state_; }
protected:
// |feature_list_| needs to be destroyed after |task_environment_|, to avoid
// tsan flakes caused by other tasks running while |feature_list_| is
// destroyed.
base::test::ScopedFeatureList feature_list_;
private:
// Cached pointer to BrowsingDataRemover for access to testing methods.
raw_ptr<content::BrowsingDataRemover> remover_;
content::TracingDelegate tracing_delegate_;
std::unique_ptr<content::BackgroundTracingManager>
background_tracing_manager_;
#if BUILDFLAG(ENABLE_NACL)
ScopedNaClBrowserDelegate nacl_browser_delegate_;
#endif // BUILDFLAG(ENABLE_NACL)
content::BrowserTaskEnvironment task_environment_{
base::test::TaskEnvironment::TimeSource::MOCK_TIME};
base::ScopedTempDir temp_dir_;
ScopedTestingLocalState local_state_{TestingBrowserProcess::GetGlobal()};
std::unique_ptr<network::NetworkContext> network_context_;
std::unique_ptr<TestingProfileManager> profile_manager_;
raw_ptr<TestingProfile> profile_; // Owned by `profile_manager_`.
};
#if !BUILDFLAG(IS_ANDROID)
TEST_F(ChromeBrowsingDataRemoverDelegateTest,
ClearUserEducationSessionHistory) {
auto& storage_service = static_cast<BrowserUserEducationStorageService&>(
UserEducationServiceFactory::GetForBrowserContext(GetProfile())
->user_education_storage_service());
RecentSessionData data;
data.enabled_time = base::Time::Now() - base::Days(90);
data.recent_session_start_times = {base::Time::Now(),
base::Time::Now() - base::Days(10),
base::Time::Now() - base::Days(20)};
storage_service.SaveRecentSessionData(data);
data = storage_service.ReadRecentSessionData();
ASSERT_EQ(3U, data.recent_session_start_times.size());
ASSERT_TRUE(data.enabled_time.has_value());
BlockUntilBrowsingDataRemoved(base::Time::Now(), base::Time::Max(),
constants::DATA_TYPE_HISTORY, false);
data = storage_service.ReadRecentSessionData();
ASSERT_EQ(0U, data.recent_session_start_times.size());
ASSERT_FALSE(data.enabled_time.has_value());
}
TEST_F(ChromeBrowsingDataRemoverDelegateTest, RemoveLensOverlayWebUIStorage) {
// Enable the translate languages feature.
base::test::ScopedFeatureList features;
features.InitAndEnableFeature(lens::features::kLensOverlayTranslateLanguages);
// Setup local storage data to the Lens Overlay WebUI origin.
const GURL lens_overlay_url = GURL(chrome::kChromeUILensOverlayUntrustedURL);
storage::mojom::LocalStorageControl* local_storage_control =
GetProfile()->GetDefaultStoragePartition()->GetLocalStorageControl();
blink::StorageKey storage_key =
blink::StorageKey::CreateFromStringForTesting(lens_overlay_url.spec());
mojo::Remote<blink::mojom::StorageArea> area;
local_storage_control->BindStorageArea(storage_key,
area.BindNewPipeAndPassReceiver());
// Add the fake data to the Lens Overlay WebUI origin.
base::test::TestFuture<bool> added_data_future;
area->Put({'k', 'e', 'y'}, {'v', 'a', 'l', 'u', 'e'}, std::nullopt, "source",
added_data_future.GetCallback());
ASSERT_TRUE(added_data_future.Get());
// Next, run the function that is supposed to remove this storage.
BlockUntilBrowsingDataRemoved(base::Time::Now(), base::Time::Max(),
constants::DATA_TYPE_HISTORY, false);
// Check if the local storage was successfully removed. ClearData only
// guarantees that tasks to delete data are scheduled when its callback is
// invoked. It doesn't guarantee data has actually been cleared. So use
// RunUntil to verify data is cleared.
EXPECT_TRUE(base::test::RunUntil([&]() {
std::vector<blink::mojom::KeyValuePtr> data;
base::RunLoop loop;
area->GetAll(
/*new_observer=*/mojo::NullRemote(),
base::BindLambdaForTesting(
[&](std::vector<blink::mojom::KeyValuePtr> data_in) {
data = std::move(data_in);
loop.Quit();
}));
loop.Run();
return data.size() == 0UL;
}));
}
#endif
#if BUILDFLAG(ENABLE_REPORTING)
class ChromeBrowsingDataRemoverDelegateWithReportingServiceTest
: public ChromeBrowsingDataRemoverDelegateTest {
public:
void ConfigureURLRequestContextBuilder(
net::URLRequestContextBuilder* builder) final {
builder->set_reporting_service(std::make_unique<MockReportingService>());
}
MockReportingService& GetMockReportingService() {
// This cast is safe because we set a MockReportingService in
// ConfigureURLRequestContextBuilder.
return *static_cast<MockReportingService*>(
network_context()->url_request_context()->reporting_service());
}
};
class ChromeBrowsingDataRemoverDelegateWithNELServiceTest
: public ChromeBrowsingDataRemoverDelegateTest {
public:
void ConfigureURLRequestContextBuilder(
net::URLRequestContextBuilder* builder) final {
builder->SetNetworkErrorLoggingServiceForTesting(
std::make_unique<MockNetworkErrorLoggingService>());
}
MockNetworkErrorLoggingService& GetMockNetworkErrorLoggingService() {
// This cast is safe because we set a MockNetworkErrorLoggingService in
// ConfigureURLRequestContextBuilder.
return *static_cast<MockNetworkErrorLoggingService*>(
network_context()
->url_request_context()
->network_error_logging_service());
}
};
#endif // BUILDFLAG(ENABLE_REPORTING)
// Tests password deletion functionality by setting up fake PasswordStore(s).
// kEnablePasswordsAccountStorage is in its default enabled/disabled state.
class ChromeBrowsingDataRemoverDelegateWithPasswordsTest
: public ChromeBrowsingDataRemoverDelegateTest {
public:
void SetUp() override {
ChromeBrowsingDataRemoverDelegateTest::SetUp();
OSCryptMocker::SetUp();
}
void TearDown() override {
OSCryptMocker::TearDown();
ChromeBrowsingDataRemoverDelegateTest::TearDown();
}
TestingProfile::TestingFactories GetTestingFactories() override {
TestingProfile::TestingFactories factories =
ChromeBrowsingDataRemoverDelegateTest::GetTestingFactories();
factories.emplace_back(
ProfilePasswordStoreFactory::GetInstance(),
base::BindRepeating(
&password_manager::BuildPasswordStoreInterface<
content::BrowserContext,
testing::NiceMock<
password_manager::MockPasswordStoreInterface>>));
// It's fine to override unconditionally, GetForProfile() will still return
// null if account storage is disabled.
factories.emplace_back(
AccountPasswordStoreFactory::GetInstance(),
base::BindRepeating(
&password_manager::BuildPasswordStoreInterface<
content::BrowserContext,
testing::NiceMock<
password_manager::MockPasswordStoreInterface>>));
return factories;
}
password_manager::MockPasswordStoreInterface* profile_password_store() {
return static_cast<password_manager::MockPasswordStoreInterface*>(
ProfilePasswordStoreFactory::GetForProfile(
GetProfile(), ServiceAccessType::EXPLICIT_ACCESS)
.get());
}
password_manager::MockPasswordStoreInterface* account_password_store() {
return static_cast<password_manager::MockPasswordStoreInterface*>(
AccountPasswordStoreFactory::GetForProfile(
GetProfile(), ServiceAccessType::EXPLICIT_ACCESS)
.get());
}
};
// TODO(crbug.com/41370786): Disabled due to flakiness in cookie store
// initialization.
TEST_F(ChromeBrowsingDataRemoverDelegateTest,
DISABLED_RemoveSafeBrowsingCookieForever) {
RemoveSafeBrowsingCookieTester tester(GetProfile());
tester.AddCookie();
ASSERT_TRUE(tester.ContainsCookie());
BlockUntilBrowsingDataRemoved(base::Time(), base::Time::Max(),
content::BrowsingDataRemover::DATA_TYPE_COOKIES,
false);
EXPECT_EQ(content::BrowsingDataRemover::DATA_TYPE_COOKIES, GetRemovalMask());
EXPECT_EQ(content::BrowsingDataRemover::ORIGIN_TYPE_UNPROTECTED_WEB,
GetOriginTypeMask());
EXPECT_FALSE(tester.ContainsCookie());
}
// TODO(crbug.com/41370786): Disabled due to flakiness in cookie store
// initialization.
TEST_F(ChromeBrowsingDataRemoverDelegateTest,
DISABLED_RemoveSafeBrowsingCookieLastHour) {
RemoveSafeBrowsingCookieTester tester(GetProfile());
tester.AddCookie();
ASSERT_TRUE(tester.ContainsCookie());
BlockUntilBrowsingDataRemoved(AnHourAgo(), base::Time::Max(),
content::BrowsingDataRemover::DATA_TYPE_COOKIES,
false);
EXPECT_EQ(content::BrowsingDataRemover::DATA_TYPE_COOKIES, GetRemovalMask());
EXPECT_EQ(content::BrowsingDataRemover::ORIGIN_TYPE_UNPROTECTED_WEB,
GetOriginTypeMask());
// Removing with time period other than all time should not clear safe
// browsing cookies.
EXPECT_TRUE(tester.ContainsCookie());
}
// TODO(crbug.com/41370786): Disabled due to flakiness in cookie store
// initialization.
TEST_F(ChromeBrowsingDataRemoverDelegateTest,
DISABLED_RemoveSafeBrowsingCookieForeverWithPredicate) {
RemoveSafeBrowsingCookieTester tester(GetProfile());
tester.AddCookie();
ASSERT_TRUE(tester.ContainsCookie());
std::unique_ptr<BrowsingDataFilterBuilder> filter(
BrowsingDataFilterBuilder::Create(
BrowsingDataFilterBuilder::Mode::kPreserve));
filter->AddRegisterableDomain(kTestRegisterableDomain1);
BlockUntilOriginDataRemoved(base::Time(), base::Time::Max(),
content::BrowsingDataRemover::DATA_TYPE_COOKIES,
std::move(filter));
EXPECT_EQ(content::BrowsingDataRemover::DATA_TYPE_COOKIES, GetRemovalMask());
EXPECT_EQ(content::BrowsingDataRemover::ORIGIN_TYPE_UNPROTECTED_WEB,
GetOriginTypeMask());
EXPECT_TRUE(tester.ContainsCookie());
std::unique_ptr<BrowsingDataFilterBuilder> filter2(
BrowsingDataFilterBuilder::Create(
BrowsingDataFilterBuilder::Mode::kDelete));
filter2->AddRegisterableDomain(kTestRegisterableDomain1);
BlockUntilOriginDataRemoved(base::Time(), base::Time::Max(),
content::BrowsingDataRemover::DATA_TYPE_COOKIES,
std::move(filter2));
EXPECT_FALSE(tester.ContainsCookie());
}
#if !BUILDFLAG(IS_ANDROID)
TEST_F(ChromeBrowsingDataRemoverDelegateTest, ClearWebAppData) {
auto* provider = web_app::FakeWebAppProvider::Get(GetProfile());
ASSERT_TRUE(provider);
// Make sure WebAppProvider's subsystems are ready.
base::RunLoop run_loop;
provider->on_registry_ready().Post(FROM_HERE, run_loop.QuitClosure());
run_loop.Run();
// Set-up: add a web app to the registry. Currently, only last_launch_time
// and last_badging_time fields are being cleared by ClearBrowsingDataCommand.
// So, we will check if these fields are cleared as a heuristic to
// ClearBrowsingDataCommand being called.
auto web_app_id = web_app::test::InstallDummyWebApp(GetProfile(), "Web App",
GURL("http://some.url"));
auto last_launch_time = base::Time() + base::Seconds(10);
provider->sync_bridge_unsafe().SetAppLastLaunchTime(web_app_id,
last_launch_time);
EXPECT_EQ(
provider->registrar_unsafe().GetAppById(web_app_id)->last_launch_time(),
last_launch_time);
auto last_badging_time = base::Time() + base::Seconds(20);
provider->sync_bridge_unsafe().SetAppLastBadgingTime(web_app_id,
last_badging_time);
EXPECT_EQ(
provider->registrar_unsafe().GetAppById(web_app_id)->last_badging_time(),
last_badging_time);
// Run RemoveEmbedderData, and wait for it to complete.
BlockUntilBrowsingDataRemoved(base::Time(), base::Time::Max(),
constants::DATA_TYPE_HISTORY, false);
// Verify that web app's last launch time is cleared.
EXPECT_EQ(
provider->registrar_unsafe().GetAppById(web_app_id)->last_launch_time(),
base::Time());
// Verify that web app's last badging time is cleared.
EXPECT_EQ(
provider->registrar_unsafe().GetAppById(web_app_id)->last_badging_time(),
base::Time());
EXPECT_EQ(constants::DATA_TYPE_HISTORY, GetRemovalMask());
}
class IsolatedWebAppChromeBrowsingDataRemoverDelegateTest
: public ChromeBrowsingDataRemoverDelegateTest {
public:
struct RemovalInfo {
uint64_t remove_mask;
std::optional<content::StoragePartitionConfig> storage_partition_config =
std::nullopt;
};
IsolatedWebAppChromeBrowsingDataRemoverDelegateTest() {
feature_list_.InitWithFeatures(
{features::kIsolatedWebApps, features::kIsolatedWebAppDevMode}, {});
}
protected:
content::BrowsingDataRemover::DataType DATA_TYPE_COOKIES =
content::BrowsingDataRemover::DATA_TYPE_COOKIES;
content::BrowsingDataRemover::DataType DATA_TYPE_INDEXED_DB =
content::BrowsingDataRemover::DATA_TYPE_INDEXED_DB;
content::BrowsingDataRemover::DataType DATA_TYPE_ON_STORAGE_PARTITION =
content::BrowsingDataRemover::DATA_TYPE_ON_STORAGE_PARTITION;
content::BrowsingDataRemover::DataType DATA_TYPE_SITE_DATA =
constants::DATA_TYPE_SITE_DATA;
web_app::IsolatedWebAppUrlInfo InstallIsolatedWebApp() {
const std::unique_ptr<web_app::ScopedBundledIsolatedWebApp> bundle =
web_app::IsolatedWebAppBuilder(web_app::ManifestBuilder())
.BuildBundle();
bundle->FakeInstallPageState(GetProfile());
bundle->TrustSigningKey();
return bundle->InstallChecked(GetProfile());
}
content::StoragePartitionConfig CreateControlledFrameStoragePartition(
const web_app::IsolatedWebAppUrlInfo& iwa_url_info,
const std::string& partition_name) {
auto* provider = web_app::FakeWebAppProvider::Get(GetProfile());
CHECK(provider);
base::test::TestFuture<std::optional<content::StoragePartitionConfig>>
future;
provider->scheduler().ScheduleCallbackWithResult(
"GetControlledFramePartition",
web_app::AppLockDescription(iwa_url_info.app_id()),
base::BindOnce(&web_app::GetControlledFramePartitionWithLock,
GetProfile(), iwa_url_info, partition_name,
/*in_memory=*/false),
future.GetCallback(), /*arg_for_shutdown=*/
std::optional<content::StoragePartitionConfig>(std::nullopt));
return future.Get().value();
}
std::vector<RemovalInfo> ClearDataAndWait(
const base::Time& delete_begin,
const base::Time& delete_end,
uint64_t remove_mask,
std::unique_ptr<BrowsingDataFilterBuilder> filter_builder) {
std::vector<RemovalInfo> removal_tasks;
base::RunLoop run_loop;
auto* browsing_data_remover = GetProfile()->GetBrowsingDataRemover();
browsing_data_remover->SetWouldCompleteCallbackForTesting(
base::BindLambdaForTesting([&](base::OnceClosure callback) {
removal_tasks.push_back(
{browsing_data_remover->GetLastUsedRemovalMaskForTesting(),
browsing_data_remover
->GetLastUsedStoragePartitionConfigForTesting()});
if (browsing_data_remover->GetPendingTaskCountForTesting() == 1) {
run_loop.Quit();
}
std::move(callback).Run();
}));
BlockUntilOriginDataRemoved(delete_begin, delete_end, remove_mask,
std::move(filter_builder));
run_loop.Run();
browsing_data_remover->SetWouldCompleteCallbackForTesting(
base::DoNothing());
return removal_tasks;
}
private:
data_decoder::test::InProcessDataDecoder in_process_data_decoder_;
};
bool operator==(
const IsolatedWebAppChromeBrowsingDataRemoverDelegateTest::RemovalInfo& a,
const IsolatedWebAppChromeBrowsingDataRemoverDelegateTest::RemovalInfo& b) {
return a.remove_mask == b.remove_mask &&
a.storage_partition_config == b.storage_partition_config;
}
TEST_F(IsolatedWebAppChromeBrowsingDataRemoverDelegateTest, ClearData) {
web_app::IsolatedWebAppUrlInfo iwa_url_info1 = InstallIsolatedWebApp();
content::StoragePartitionConfig controlled_frame_partition1 =
CreateControlledFrameStoragePartition(iwa_url_info1, "controlled_frame");
web_app::IsolatedWebAppUrlInfo iwa_url_info2 = InstallIsolatedWebApp();
EXPECT_NE(iwa_url_info1.app_id(), iwa_url_info2.app_id());
std::vector<RemovalInfo> removal_tasks =
ClearDataAndWait(base::Time(), base::Time::Max(), DATA_TYPE_SITE_DATA,
BrowsingDataFilterBuilder::Create(
BrowsingDataFilterBuilder::Mode::kPreserve));
EXPECT_THAT(
removal_tasks,
UnorderedElementsAre(
RemovalInfo{DATA_TYPE_SITE_DATA},
RemovalInfo{DATA_TYPE_ON_STORAGE_PARTITION & DATA_TYPE_SITE_DATA,
iwa_url_info1.storage_partition_config(GetProfile())},
RemovalInfo{DATA_TYPE_ON_STORAGE_PARTITION & DATA_TYPE_SITE_DATA,
controlled_frame_partition1},
RemovalInfo{DATA_TYPE_ON_STORAGE_PARTITION & DATA_TYPE_SITE_DATA,
iwa_url_info2.storage_partition_config(GetProfile())}));
}
TEST_F(IsolatedWebAppChromeBrowsingDataRemoverDelegateTest,
ForwardClearDataParameterToControlledFrame) {
web_app::IsolatedWebAppUrlInfo iwa_url_info = InstallIsolatedWebApp();
content::StoragePartitionConfig controlled_frame_partition =
CreateControlledFrameStoragePartition(iwa_url_info, "controlled_frame");
std::vector<RemovalInfo> removal_tasks =
ClearDataAndWait(base::Time(), base::Time::Max(), DATA_TYPE_INDEXED_DB,
BrowsingDataFilterBuilder::Create(
BrowsingDataFilterBuilder::Mode::kPreserve));
EXPECT_THAT(
removal_tasks,
UnorderedElementsAre(
RemovalInfo{DATA_TYPE_INDEXED_DB},
RemovalInfo{DATA_TYPE_INDEXED_DB,
iwa_url_info.storage_partition_config(GetProfile())},
RemovalInfo{DATA_TYPE_INDEXED_DB, controlled_frame_partition}));
}
TEST_F(IsolatedWebAppChromeBrowsingDataRemoverDelegateTest,
FilterOriginRespected) {
web_app::IsolatedWebAppUrlInfo iwa_url_info1 = InstallIsolatedWebApp();
web_app::IsolatedWebAppUrlInfo iwa_url_info2 = InstallIsolatedWebApp();
EXPECT_NE(iwa_url_info1.app_id(), iwa_url_info2.app_id());
auto filter_builder = BrowsingDataFilterBuilder::Create(
BrowsingDataFilterBuilder::Mode::kDelete);
filter_builder->AddOrigin(iwa_url_info1.origin());
std::vector<RemovalInfo> removal_tasks = ClearDataAndWait(
base::Time(), base::Time::Max(), DATA_TYPE_SITE_DATA & ~DATA_TYPE_COOKIES,
std::move(filter_builder));
EXPECT_THAT(
removal_tasks,
UnorderedElementsAre(
RemovalInfo{DATA_TYPE_SITE_DATA & ~DATA_TYPE_COOKIES},
RemovalInfo{DATA_TYPE_SITE_DATA & DATA_TYPE_ON_STORAGE_PARTITION,
iwa_url_info1.storage_partition_config(GetProfile())}));
}
TEST_F(IsolatedWebAppChromeBrowsingDataRemoverDelegateTest, AppCookiesDeleted) {
web_app::IsolatedWebAppUrlInfo iwa_url_info = InstallIsolatedWebApp();
auto filter_builder = BrowsingDataFilterBuilder::Create(
BrowsingDataFilterBuilder::Mode::kDelete);
filter_builder->AddOrigin(iwa_url_info.origin());
std::vector<RemovalInfo> removal_tasks = ClearDataAndWait(
base::Time(), base::Time::Max(),
constants::DATA_TYPE_ISOLATED_WEB_APP_COOKIES, std::move(filter_builder));
EXPECT_THAT(
removal_tasks,
UnorderedElementsAre(
RemovalInfo{constants::DATA_TYPE_ISOLATED_WEB_APP_COOKIES},
RemovalInfo{DATA_TYPE_COOKIES,
iwa_url_info.storage_partition_config(GetProfile())}));
}
TEST_F(IsolatedWebAppChromeBrowsingDataRemoverDelegateTest,
TimeRangeSpecified) {
web_app::IsolatedWebAppUrlInfo iwa_url_info = InstallIsolatedWebApp();
content::StoragePartitionConfig controlled_frame_partition =
CreateControlledFrameStoragePartition(iwa_url_info, "controlled_frame");
std::vector<RemovalInfo> removal_tasks =
ClearDataAndWait(AnHourAgo(), base::Time::Max(), DATA_TYPE_INDEXED_DB,
BrowsingDataFilterBuilder::Create(
BrowsingDataFilterBuilder::Mode::kPreserve));
EXPECT_THAT(
removal_tasks,
UnorderedElementsAre(
RemovalInfo{DATA_TYPE_INDEXED_DB},
RemovalInfo{DATA_TYPE_INDEXED_DB,
iwa_url_info.storage_partition_config(GetProfile())},
RemovalInfo{DATA_TYPE_INDEXED_DB, controlled_frame_partition}));
}
#endif // !BUILDFLAG(IS_ANDROID)
TEST_F(ChromeBrowsingDataRemoverDelegateTest, RemoveHistoryForever) {
RemoveHistoryTester tester;
ASSERT_TRUE(tester.Init(GetProfile()));
const GURL kOrigin1("http://host1.com:1");
tester.AddHistory(kOrigin1, base::Time::Now());
ASSERT_TRUE(tester.HistoryContainsURL(kOrigin1));
BlockUntilBrowsingDataRemoved(base::Time(), base::Time::Max(),
constants::DATA_TYPE_HISTORY, false);
EXPECT_EQ(constants::DATA_TYPE_HISTORY, GetRemovalMask());
EXPECT_EQ(content::BrowsingDataRemover::ORIGIN_TYPE_UNPROTECTED_WEB,
GetOriginTypeMask());
EXPECT_FALSE(tester.HistoryContainsURL(kOrigin1));
}
TEST_F(ChromeBrowsingDataRemoverDelegateTest, RemoveHistoryForLastHour) {
RemoveHistoryTester tester;
ASSERT_TRUE(tester.Init(GetProfile()));
base::Time two_hours_ago = base::Time::Now() - base::Hours(2);
const GURL kOrigin1("http://host1.com:1");
const GURL kOrigin2("http://host2.com:1");
tester.AddHistory(kOrigin1, base::Time::Now());
tester.AddHistory(kOrigin2, two_hours_ago);
ASSERT_TRUE(tester.HistoryContainsURL(kOrigin1));
ASSERT_TRUE(tester.HistoryContainsURL(kOrigin2));
BlockUntilBrowsingDataRemoved(AnHourAgo(), base::Time::Max(),
constants::DATA_TYPE_HISTORY, false);
EXPECT_EQ(constants::DATA_TYPE_HISTORY, GetRemovalMask());
EXPECT_EQ(content::BrowsingDataRemover::ORIGIN_TYPE_UNPROTECTED_WEB,
GetOriginTypeMask());
EXPECT_FALSE(tester.HistoryContainsURL(kOrigin1));
EXPECT_TRUE(tester.HistoryContainsURL(kOrigin2));
}
TEST_F(ChromeBrowsingDataRemoverDelegateTest, RemoveHistoryForOlderThan30Days) {
RemoveHistoryTester tester;
ASSERT_TRUE(tester.Init(GetProfile()));
base::Time older_than_29days = base::Time::Now() - base::Days(29);
base::Time older_than_30days = base::Time::Now() - base::Days(30);
base::Time older_than_31days = base::Time::Now() - base::Days(31);
const GURL kOrigin1("http://host1.com:1");
const GURL kOrigin2("http://host2.com:1");
const GURL kOrigin3("http://host3.com:1");
tester.AddHistory(kOrigin1, base::Time::Now());
tester.AddHistory(kOrigin2, older_than_29days);
tester.AddHistory(kOrigin3, older_than_31days);
ASSERT_TRUE(tester.HistoryContainsURL(kOrigin1));
ASSERT_TRUE(tester.HistoryContainsURL(kOrigin2));
ASSERT_TRUE(tester.HistoryContainsURL(kOrigin3));
BlockUntilBrowsingDataRemoved(base::Time(), older_than_30days,
constants::DATA_TYPE_HISTORY, false);
EXPECT_EQ(constants::DATA_TYPE_HISTORY, GetRemovalMask());
EXPECT_EQ(content::BrowsingDataRemover::ORIGIN_TYPE_UNPROTECTED_WEB,
GetOriginTypeMask());
EXPECT_TRUE(tester.HistoryContainsURL(kOrigin1));
EXPECT_TRUE(tester.HistoryContainsURL(kOrigin2));
EXPECT_FALSE(tester.HistoryContainsURL(kOrigin3));
}
// This should crash (DCHECK) in Debug, but death tests don't work properly
// here.
// TODO(msramek): To make this testable, the refusal to delete history should
// be made a part of interface (e.g. a success value) as opposed to a DCHECK.
#if defined(NDEBUG) && !defined(DCHECK_ALWAYS_ON)
TEST_F(ChromeBrowsingDataRemoverDelegateTest, RemoveHistoryProhibited) {
RemoveHistoryTester tester;
ASSERT_TRUE(tester.Init(GetProfile()));
PrefService* prefs = GetProfile()->GetPrefs();
prefs->SetBoolean(prefs::kAllowDeletingBrowserHistory, false);
base::Time two_hours_ago = base::Time::Now() - base::Hours(2);
const GURL kOrigin1("http://host1.com:1");
const GURL kOrigin2("http://host2.com:1");
tester.AddHistory(kOrigin1, base::Time::Now());
tester.AddHistory(kOrigin2, two_hours_ago);
ASSERT_TRUE(tester.HistoryContainsURL(kOrigin1));
ASSERT_TRUE(tester.HistoryContainsURL(kOrigin2));
BlockUntilBrowsingDataRemoved(AnHourAgo(), base::Time::Max(),
constants::DATA_TYPE_HISTORY, false);
EXPECT_EQ(constants::DATA_TYPE_HISTORY, GetRemovalMask());
EXPECT_EQ(content::BrowsingDataRemover::ORIGIN_TYPE_UNPROTECTED_WEB,
GetOriginTypeMask());
// Nothing should have been deleted.
EXPECT_TRUE(tester.HistoryContainsURL(kOrigin1));
EXPECT_TRUE(tester.HistoryContainsURL(kOrigin2));
}
TEST_F(ChromeBrowsingDataRemoverDelegateWithPasswordsTest,
RemoveMultipleTypesHistoryProhibited) {
PrefService* prefs = GetProfile()->GetPrefs();
prefs->SetBoolean(prefs::kAllowDeletingBrowserHistory, false);
// Add some history.
const GURL kOrigin1("http://host1.com:1");
RemoveHistoryTester history_tester;
ASSERT_TRUE(history_tester.Init(GetProfile()));
history_tester.AddHistory(kOrigin1, base::Time::Now());
ASSERT_TRUE(history_tester.HistoryContainsURL(kOrigin1));
// Expect that passwords will be deleted, as they do not depend
// on |prefs::kAllowDeletingBrowserHistory|.
ExpectRemoveLoginsCreatedBetween(profile_password_store());
uint64_t removal_mask =
constants::DATA_TYPE_HISTORY | constants::DATA_TYPE_PASSWORDS;
BlockUntilBrowsingDataRemoved(AnHourAgo(), base::Time::Max(), removal_mask,
false);
EXPECT_EQ(removal_mask, GetRemovalMask());
EXPECT_EQ(content::BrowsingDataRemover::ORIGIN_TYPE_UNPROTECTED_WEB,
GetOriginTypeMask());
// Verify that history was not deleted.
EXPECT_TRUE(history_tester.HistoryContainsURL(kOrigin1));
}
#endif
TEST_F(ChromeBrowsingDataRemoverDelegateTest, RemoveExternalProtocolData) {
TestingProfile* profile = GetProfile();
url::Origin test_origin = url::Origin::Create(GURL("https://example.test"));
const std::string serialized_test_origin = test_origin.Serialize();
// Add external protocol data on profile.
base::Value::Dict allowed_protocols_for_origin;
allowed_protocols_for_origin.Set("tel", true);
base::Value::Dict prefs;
prefs.Set(serialized_test_origin, std::move(allowed_protocols_for_origin));
profile->GetPrefs()->SetDict(prefs::kProtocolHandlerPerOriginAllowedProtocols,
std::move(prefs));
EXPECT_FALSE(profile->GetPrefs()
->GetDict(prefs::kProtocolHandlerPerOriginAllowedProtocols)
.empty());
auto filter_builder = BrowsingDataFilterBuilder::Create(
BrowsingDataFilterBuilder::Mode::kDelete);
filter_builder->AddOrigin(test_origin);
BlockUntilOriginDataRemoved(AnHourAgo(), base::Time::Max(),
constants::DATA_TYPE_EXTERNAL_PROTOCOL_DATA,
std::move(filter_builder));
// This data type doesn't implement per-origin deletion so just test that
// nothing got removed.
EXPECT_FALSE(profile->GetPrefs()
->GetDict(prefs::kProtocolHandlerPerOriginAllowedProtocols)
.empty());
BlockUntilBrowsingDataRemoved(AnHourAgo(), base::Time::Max(),
constants::DATA_TYPE_EXTERNAL_PROTOCOL_DATA,
false);
EXPECT_TRUE(profile->GetPrefs()
->GetDict(prefs::kProtocolHandlerPerOriginAllowedProtocols)
.empty());
}
// Check that clearing browsing data (either history or cookies with other site
// data) clears any saved isolated origins.
TEST_F(ChromeBrowsingDataRemoverDelegateTest, RemovePersistentIsolatedOrigins) {
PrefService* prefs = GetProfile()->GetPrefs();
// Add foo.com to the list of stored user-triggered isolated origins and
// bar.com to the list of stored web-triggered isolated origins.
base::Value::List list;
list.Append("http://foo.com");
prefs->SetList(site_isolation::prefs::kUserTriggeredIsolatedOrigins,
list.Clone());
EXPECT_FALSE(
prefs->GetList(site_isolation::prefs::kUserTriggeredIsolatedOrigins)
.empty());
base::Value::Dict dict;
dict.Set("https://bar.com", base::TimeToValue(base::Time::Now()));
prefs->SetDict(site_isolation::prefs::kWebTriggeredIsolatedOrigins,
dict.Clone());
EXPECT_FALSE(
prefs->GetDict(site_isolation::prefs::kWebTriggeredIsolatedOrigins)
.empty());
// Clear history and ensure the stored isolated origins are cleared.
BlockUntilBrowsingDataRemoved(base::Time(), base::Time::Max(),
constants::DATA_TYPE_HISTORY, false);
EXPECT_TRUE(
prefs->GetList(site_isolation::prefs::kUserTriggeredIsolatedOrigins)
.empty());
EXPECT_TRUE(
prefs->GetDict(site_isolation::prefs::kWebTriggeredIsolatedOrigins)
.empty());
// Re-add foo.com and bar.com to stored isolated origins.
prefs->SetList(site_isolation::prefs::kUserTriggeredIsolatedOrigins,
list.Clone());
EXPECT_FALSE(
prefs->GetList(site_isolation::prefs::kUserTriggeredIsolatedOrigins)
.empty());
prefs->SetDict(site_isolation::prefs::kWebTriggeredIsolatedOrigins,
dict.Clone());
EXPECT_FALSE(
prefs->GetDict(site_isolation::prefs::kWebTriggeredIsolatedOrigins)
.empty());
// Now clear cookies and other site data, and ensure foo.com is cleared.
// Note that this uses a short time period to document that time ranges are
// currently ignored by stored isolated origins.
BlockUntilBrowsingDataRemoved(AnHourAgo(), base::Time::Max(),
constants::DATA_TYPE_SITE_DATA, false);
EXPECT_TRUE(
prefs->GetList(site_isolation::prefs::kUserTriggeredIsolatedOrigins)
.empty());
EXPECT_TRUE(
prefs->GetDict(site_isolation::prefs::kWebTriggeredIsolatedOrigins)
.empty());
// Re-add foo.com and bar.com.
prefs->SetList(site_isolation::prefs::kUserTriggeredIsolatedOrigins,
list.Clone());
EXPECT_FALSE(
prefs->GetList(site_isolation::prefs::kUserTriggeredIsolatedOrigins)
.empty());
prefs->SetDict(site_isolation::prefs::kWebTriggeredIsolatedOrigins,
dict.Clone());
EXPECT_FALSE(
prefs->GetDict(site_isolation::prefs::kWebTriggeredIsolatedOrigins)
.empty());
// Clear the isolated origins data type.
BlockUntilBrowsingDataRemoved(base::Time(), base::Time::Max(),
constants::DATA_TYPE_ISOLATED_ORIGINS, false);
EXPECT_TRUE(
prefs->GetList(site_isolation::prefs::kUserTriggeredIsolatedOrigins)
.empty());
EXPECT_TRUE(
prefs->GetDict(site_isolation::prefs::kWebTriggeredIsolatedOrigins)
.empty());
// Re-add foo.com and bar.com.
prefs->SetList(site_isolation::prefs::kUserTriggeredIsolatedOrigins,
list.Clone());
EXPECT_FALSE(
prefs->GetList(site_isolation::prefs::kUserTriggeredIsolatedOrigins)
.empty());
prefs->SetDict(site_isolation::prefs::kWebTriggeredIsolatedOrigins,
dict.Clone());
EXPECT_FALSE(
prefs->GetDict(site_isolation::prefs::kWebTriggeredIsolatedOrigins)
.empty());
// Clear both history and site data, and ensure the stored isolated origins
// are cleared.
BlockUntilBrowsingDataRemoved(
base::Time(), base::Time::Max(),
constants::DATA_TYPE_HISTORY | constants::DATA_TYPE_SITE_DATA, false);
EXPECT_TRUE(
prefs->GetList(site_isolation::prefs::kUserTriggeredIsolatedOrigins)
.empty());
EXPECT_TRUE(
prefs->GetDict(site_isolation::prefs::kWebTriggeredIsolatedOrigins)
.empty());
}
// Test that clearing history deletes favicons not associated with bookmarks.
TEST_F(ChromeBrowsingDataRemoverDelegateTest, RemoveFaviconsForever) {
GURL page_url("http://a");
RemoveFaviconTester favicon_tester;
ASSERT_TRUE(favicon_tester.Init(GetProfile()));
favicon_tester.VisitAndAddFavicon(page_url);
ASSERT_TRUE(favicon_tester.HasFaviconForPageURL(page_url));
BlockUntilBrowsingDataRemoved(base::Time(), base::Time::Max(),
constants::DATA_TYPE_HISTORY, false);
EXPECT_EQ(constants::DATA_TYPE_HISTORY, GetRemovalMask());
EXPECT_FALSE(favicon_tester.HasFaviconForPageURL(page_url));
}
// Test that a bookmark's favicon is expired and not deleted when clearing
// history. Expiring the favicon causes the bookmark's favicon to be updated
// when the user next visits the bookmarked page. Expiring the bookmark's
// favicon is useful when the bookmark's favicon becomes incorrect (See
// crbug.com/474421 for a sample bug which causes this).
TEST_F(ChromeBrowsingDataRemoverDelegateTest, ExpireBookmarkFavicons) {
GURL bookmarked_page("http://a");
TestingProfile* profile = GetProfile();
bookmarks::BookmarkModel* bookmark_model =
BookmarkModelFactory::GetForBrowserContext(profile);
bookmarks::test::WaitForBookmarkModelToLoad(bookmark_model);
bookmark_model->AddURL(bookmark_model->bookmark_bar_node(), 0, u"a",
bookmarked_page);
RemoveFaviconTester favicon_tester;
ASSERT_TRUE(favicon_tester.Init(GetProfile()));
favicon_tester.VisitAndAddFavicon(bookmarked_page);
ASSERT_TRUE(favicon_tester.HasFaviconForPageURL(bookmarked_page));
BlockUntilBrowsingDataRemoved(base::Time(), base::Time::Max(),
constants::DATA_TYPE_HISTORY, false);
EXPECT_EQ(constants::DATA_TYPE_HISTORY, GetRemovalMask());
EXPECT_TRUE(favicon_tester.HasExpiredFaviconForPageURL(bookmarked_page));
}
TEST_F(ChromeBrowsingDataRemoverDelegateTest, DeleteBookmarks) {
GURL bookmarked_page("http://a");
TestingProfile* profile = GetProfile();
bookmarks::BookmarkModel* bookmark_model =
BookmarkModelFactory::GetForBrowserContext(profile);
bookmarks::test::WaitForBookmarkModelToLoad(bookmark_model);
bookmark_model->AddURL(bookmark_model->bookmark_bar_node(), 0, u"a",
bookmarked_page);
EXPECT_EQ(1u, bookmark_model->bookmark_bar_node()->children().size());
BlockUntilBrowsingDataRemoved(base::Time(), base::Time::Max(),
constants::DATA_TYPE_BOOKMARKS, false);
EXPECT_EQ(0u, bookmark_model->bookmark_bar_node()->children().size());
}
TEST_F(ChromeBrowsingDataRemoverDelegateTest, ClearReadingList) {
TestingProfile* profile = GetProfile();
auto* reading_list_model =
ReadingListModelFactory::GetForBrowserContext(profile);
WaitForReadingListModelLoaded(reading_list_model);
reading_list_model->AddOrReplaceEntry(
GURL("http://url.com/"), "entry_title",
reading_list::ADDED_VIA_CURRENT_APP,
/*estimated_read_time=*/base::TimeDelta());
EXPECT_EQ(1u, reading_list_model->size());
BlockUntilBrowsingDataRemoved(base::Time(), base::Time::Max(),
constants::DATA_TYPE_READING_LIST, false);
EXPECT_EQ(0u, reading_list_model->size());
}
TEST_F(ChromeBrowsingDataRemoverDelegateTest, DeleteBookmarkHistory) {
GURL bookmarked_page("http://a");
TestingProfile* profile = GetProfile();
bookmarks::BookmarkModel* bookmark_model =
BookmarkModelFactory::GetForBrowserContext(profile);
bookmarks::test::WaitForBookmarkModelToLoad(bookmark_model);
const bookmarks::BookmarkNode* node = bookmark_model->AddURL(
bookmark_model->bookmark_bar_node(), 0, u"a", bookmarked_page);
bookmark_model->UpdateLastUsedTime(node, base::Time::Now(),
/*just_opened=*/true);
BlockUntilBrowsingDataRemoved(base::Time(), base::Time::Max(),
constants::DATA_TYPE_HISTORY, false);
EXPECT_EQ(base::Time(), node->date_last_used());
}
// Verifies deleting does not crash if BookmarkModel has not been loaded.
// Regression test for: https://crbug.com/1207632.
TEST_F(ChromeBrowsingDataRemoverDelegateTest,
DeleteBookmarksDoesNothingWhenModelNotLoaded) {
TestingProfile* profile = GetProfileManager()->CreateTestingProfile(
"bookmark_profile", {TestingProfile::TestingFactory{
BookmarkModelFactory::GetInstance(),
BookmarkModelFactory::GetDefaultFactory()}});
bookmarks::BookmarkModel* bookmark_model =
BookmarkModelFactory::GetForBrowserContext(profile);
// For this test to exercise the code path that lead to the crash the
// model must not be loaded yet.
EXPECT_FALSE(bookmark_model->loaded());
content::BrowsingDataRemover* remover = profile->GetBrowsingDataRemover();
content::BrowsingDataRemoverCompletionObserver completion_observer(remover);
remover->RemoveAndReply(
base::Time(), base::Time::Max(), constants::DATA_TYPE_BOOKMARKS,
content::BrowsingDataRemover::ORIGIN_TYPE_UNPROTECTED_WEB,
&completion_observer);
completion_observer.BlockUntilCompletion();
// No crash means test passes.
}
// TODO(crbug.com/40458377): Disabled, since history is not yet marked as
// a filterable datatype.
TEST_F(ChromeBrowsingDataRemoverDelegateTest,
DISABLED_TimeBasedHistoryRemoval) {
RemoveHistoryTester tester;
ASSERT_TRUE(tester.Init(GetProfile()));
base::Time two_hours_ago = base::Time::Now() - base::Hours(2);
const GURL kOrigin1("http://host1.com:1");
const GURL kOrigin2("http://host2.com:1");
tester.AddHistory(kOrigin1, base::Time::Now());
tester.AddHistory(kOrigin2, two_hours_ago);
ASSERT_TRUE(tester.HistoryContainsURL(kOrigin1));
ASSERT_TRUE(tester.HistoryContainsURL(kOrigin2));
std::unique_ptr<BrowsingDataFilterBuilder> builder(
BrowsingDataFilterBuilder::Create(
BrowsingDataFilterBuilder::Mode::kPreserve));
BlockUntilOriginDataRemoved(AnHourAgo(), base::Time::Max(),
constants::DATA_TYPE_HISTORY, std::move(builder));
EXPECT_EQ(constants::DATA_TYPE_HISTORY, GetRemovalMask());
EXPECT_EQ(content::BrowsingDataRemover::ORIGIN_TYPE_UNPROTECTED_WEB,
GetOriginTypeMask());
EXPECT_FALSE(tester.HistoryContainsURL(kOrigin1));
EXPECT_TRUE(tester.HistoryContainsURL(kOrigin2));
}
#if BUILDFLAG(IS_ANDROID)
TEST_F(ChromeBrowsingDataRemoverDelegateTest, DeleteTabs) {
::testing::NiceMock<MockTabModel> tab_model(GetProfile());
TabModelList::AddTabModel(&tab_model);
ASSERT_EQ(1u, TabModelList::models().size());
base::Time two_hours_ago = base::Time::Now() - base::Hours(2);
EXPECT_CALL(tab_model,
CloseTabsNavigatedInTimeWindow(two_hours_ago, base::Time::Max()))
.Times(1);
BlockUntilBrowsingDataRemoved(two_hours_ago, base::Time::Max(),
chrome_browsing_data_remover::DATA_TYPE_TABS,
false);
EXPECT_EQ(chrome_browsing_data_remover::DATA_TYPE_TABS, GetRemovalMask());
}
TEST_F(ChromeBrowsingDataRemoverDelegateTest,
DeleteTabs_WithArchivedTabModelPresent) {
::testing::NiceMock<MockTabModel> tab_model(GetProfile());
TabModelList::AddTabModel(&tab_model);
::testing::NiceMock<MockTabModel> archived_tab_model(GetProfile());
TabModelList::SetArchivedTabModel(&archived_tab_model);
ASSERT_EQ(1u, TabModelList::models().size());
base::Time two_hours_ago = base::Time::Now() - base::Hours(2);
EXPECT_CALL(tab_model,
CloseTabsNavigatedInTimeWindow(two_hours_ago, base::Time::Max()))
.Times(1);
EXPECT_CALL(archived_tab_model,
CloseTabsNavigatedInTimeWindow(two_hours_ago, base::Time::Max()))
.Times(1);
BlockUntilBrowsingDataRemoved(two_hours_ago, base::Time::Max(),
chrome_browsing_data_remover::DATA_TYPE_TABS,
false);
EXPECT_EQ(chrome_browsing_data_remover::DATA_TYPE_TABS, GetRemovalMask());
}
#endif // BUILDFLAG(IS_ANDROID)
class ChromeBrowsingDataRemoverDelegateEnabledUkmDatabaseTest
: public ChromeBrowsingDataRemoverDelegateTest {
public:
ChromeBrowsingDataRemoverDelegateEnabledUkmDatabaseTest() {
// Enable features that will trigger platform to store URLs in database.
feature_list_.InitWithFeatures(
{segmentation_platform::features::kSegmentationPlatformFeature,
segmentation_platform::features::
kSegmentationPlatformLowEngagementFeature,
segmentation_platform::features::kSegmentationPlatformUkmEngine},
{});
}
void SetUp() override {
tester_ = std::make_unique<RemoveUkmDataTester>();
ChromeBrowsingDataRemoverDelegateTest::SetUp();
}
void TearDown() override {
tester_->TearDown(GetProfile());
ChromeBrowsingDataRemoverDelegateTest::TearDown();
tester_.reset();
}
protected:
std::unique_ptr<RemoveUkmDataTester> tester_;
};
TEST_F(ChromeBrowsingDataRemoverDelegateEnabledUkmDatabaseTest, RemoveUkmUrls) {
ASSERT_TRUE(tester_->Init(GetProfile()));
const base::Time timestamp1 = base::Time::Now();
const base::Time timestamp2 = timestamp1 + base::Hours(2);
const GURL kOrigin1("http://host1.com:1");
tester_->AddURL(kOrigin1, timestamp1);
const GURL kOrigin2("http://host2.com:1");
tester_->AddURL(kOrigin2, timestamp2);
ASSERT_TRUE(tester_->UkmDatabaseContainsURL(kOrigin2));
// Removing history URLs will remove URLs from the platform.
BlockUntilBrowsingDataRemoved(base::Time(), timestamp1 + base::Hours(1),
constants::DATA_TYPE_HISTORY, false);
EXPECT_FALSE(tester_->UkmDatabaseContainsURL(kOrigin1));
EXPECT_TRUE(tester_->UkmDatabaseContainsURL(kOrigin2));
// Removing history URLs will remove URLs from the platform.
BlockUntilBrowsingDataRemoved(base::Time(), base::Time::Max(),
constants::DATA_TYPE_HISTORY, false);
EXPECT_FALSE(tester_->UkmDatabaseContainsURL(kOrigin1));
EXPECT_FALSE(tester_->UkmDatabaseContainsURL(kOrigin2));
}
// Verify that clearing autofill form data works.
TEST_F(ChromeBrowsingDataRemoverDelegateTest, AutofillRemovalLastHour) {
RemoveAutofillTester tester(GetProfile());
// Initialize sync service so that PersonalDatabaseHelper::server_database_
// gets initialized:
SyncServiceFactory::GetForProfile(GetProfile());
ASSERT_FALSE(tester.HasProfileAndCard());
tester.AddProfileAndCard();
ASSERT_TRUE(tester.HasProfileAndCard());
BlockUntilBrowsingDataRemoved(AnHourAgo(), base::Time::Max(),
constants::DATA_TYPE_FORM_DATA, false);
EXPECT_EQ(constants::DATA_TYPE_FORM_DATA, GetRemovalMask());
EXPECT_EQ(content::BrowsingDataRemover::ORIGIN_TYPE_UNPROTECTED_WEB,
GetOriginTypeMask());
ASSERT_FALSE(tester.HasProfileAndCard());
}
// Verify the clearing of autofill profiles added / modified more than 30 days
// ago.
TEST_F(ChromeBrowsingDataRemoverDelegateTest, AutofillRemovalOlderThan30Days) {
RemoveAutofillTester tester(GetProfile());
// Initialize sync service so that PersonalDatabaseHelper::server_database_
// gets initialized:
SyncServiceFactory::GetForProfile(GetProfile());
const base::Time k32DaysOld = base::Time::Now();
task_environment()->AdvanceClock(base::Days(1));
const base::Time k31DaysOld = base::Time::Now();
task_environment()->AdvanceClock(base::Days(1));
const base::Time k30DaysOld = base::Time::Now();
task_environment()->AdvanceClock(base::Days(30));
// Add profiles and cards with modification date as 31 days old from now.
autofill::TestAutofillClock test_clock;
test_clock.SetNow(k31DaysOld);
ASSERT_FALSE(tester.HasProfileAndCard());
tester.AddProfileAndCard();
ASSERT_TRUE(tester.HasProfileAndCard());
BlockUntilBrowsingDataRemoved(base::Time(), k32DaysOld,
constants::DATA_TYPE_FORM_DATA, false);
ASSERT_TRUE(tester.HasProfileAndCard());
BlockUntilBrowsingDataRemoved(k30DaysOld, base::Time::Max(),
constants::DATA_TYPE_FORM_DATA, false);
ASSERT_TRUE(tester.HasProfileAndCard());
BlockUntilBrowsingDataRemoved(base::Time(), k30DaysOld,
constants::DATA_TYPE_FORM_DATA, false);
EXPECT_EQ(constants::DATA_TYPE_FORM_DATA, GetRemovalMask());
EXPECT_EQ(content::BrowsingDataRemover::ORIGIN_TYPE_UNPROTECTED_WEB,
GetOriginTypeMask());
ASSERT_FALSE(tester.HasProfileAndCard());
}
TEST_F(ChromeBrowsingDataRemoverDelegateTest, AutofillRemovalEverything) {
RemoveAutofillTester tester(GetProfile());
// Initialize sync service so that PersonalDatabaseHelper::server_database_
// gets initialized:
SyncServiceFactory::GetForProfile(GetProfile());
ASSERT_FALSE(tester.HasProfileAndCard());
tester.AddProfileAndCard();
ASSERT_TRUE(tester.HasProfileAndCard());
BlockUntilBrowsingDataRemoved(base::Time(), base::Time::Max(),
constants::DATA_TYPE_FORM_DATA, false);
EXPECT_EQ(constants::DATA_TYPE_FORM_DATA, GetRemovalMask());
EXPECT_EQ(content::BrowsingDataRemover::ORIGIN_TYPE_UNPROTECTED_WEB,
GetOriginTypeMask());
ASSERT_FALSE(tester.HasProfileAndCard());
}
TEST_F(ChromeBrowsingDataRemoverDelegateTest,
StrikeDatabaseEmptyOnAutofillRemoveEverything) {
RemoveAutofillTester tester(GetProfile());
// Initialize sync service so that PersonalDatabaseHelper::server_database_
// gets initialized:
SyncServiceFactory::GetForProfile(GetProfile());
ASSERT_FALSE(tester.HasProfileAndCard());
tester.AddProfileAndCard();
ASSERT_TRUE(tester.HasProfileAndCard());
autofill::StrikeDatabaseTester strike_database_tester(GetProfile());
BlockUntilBrowsingDataRemoved(base::Time(), base::Time::Max(),
constants::DATA_TYPE_FORM_DATA, false);
// StrikeDatabase should be empty when DATA_TYPE_FORM_DATA browsing data
// gets deleted.
ASSERT_TRUE(strike_database_tester.IsEmpty());
EXPECT_EQ(constants::DATA_TYPE_FORM_DATA, GetRemovalMask());
EXPECT_EQ(content::BrowsingDataRemover::ORIGIN_TYPE_UNPROTECTED_WEB,
GetOriginTypeMask());
ASSERT_FALSE(tester.HasProfileAndCard());
}
TEST_F(ChromeBrowsingDataRemoverDelegateTest, ZeroSuggestPrefsBasedCacheClear) {
// Disable in-memory ZPS caching.
base::test::ScopedFeatureList features;
features.InitAndDisableFeature(omnibox::kZeroSuggestInMemoryCaching);
const std::string page_url = "https://google.com/search?q=chrome";
const std::string response = R"(["", ["foo", "bar"]])";
ZeroSuggestCacheService* zero_suggest_cache_service =
ZeroSuggestCacheServiceFactory::GetForProfile(GetProfile());
zero_suggest_cache_service->StoreZeroSuggestResponse(page_url, response);
zero_suggest_cache_service->StoreZeroSuggestResponse("", response);
// Verify that the in-memory cache is initially empty.
EXPECT_TRUE(zero_suggest_cache_service->IsInMemoryCacheEmptyForTesting());
// Verify that the pref-based cache is initially non-empty.
PrefService* prefs = GetProfile()->GetPrefs();
EXPECT_FALSE(prefs->GetString(omnibox::kZeroSuggestCachedResults).empty());
EXPECT_FALSE(
prefs->GetDict(omnibox::kZeroSuggestCachedResultsWithURL).empty());
BlockUntilBrowsingDataRemoved(base::Time(), base::Time::Max(),
content::BrowsingDataRemover::DATA_TYPE_COOKIES,
false);
// Expect the in-memory cache to remain empty.
EXPECT_TRUE(zero_suggest_cache_service->IsInMemoryCacheEmptyForTesting());
// Expect the prefs to be cleared when cookies are removed.
EXPECT_TRUE(prefs->GetString(omnibox::kZeroSuggestCachedResults).empty());
EXPECT_TRUE(
prefs->GetDict(omnibox::kZeroSuggestCachedResultsWithURL).empty());
EXPECT_EQ(content::BrowsingDataRemover::DATA_TYPE_COOKIES, GetRemovalMask());
EXPECT_EQ(content::BrowsingDataRemover::ORIGIN_TYPE_UNPROTECTED_WEB,
GetOriginTypeMask());
}
#if !BUILDFLAG(IS_ANDROID)
TEST_F(ChromeBrowsingDataRemoverDelegateTest, ZeroSuggestInMemoryCacheClear) {
// Enable in-memory ZPS caching.
base::test::ScopedFeatureList features;
features.InitAndEnableFeature(omnibox::kZeroSuggestInMemoryCaching);
const std::string page_url = "https://google.com/search?q=chrome";
const std::string response = R"(["", ["foo", "bar"]])";
ZeroSuggestCacheService* zero_suggest_cache_service =
ZeroSuggestCacheServiceFactory::GetForProfile(GetProfile());
zero_suggest_cache_service->StoreZeroSuggestResponse(page_url, response);
zero_suggest_cache_service->StoreZeroSuggestResponse("", response);
// Verify that the in-memory cache is initially non-empty.
EXPECT_FALSE(zero_suggest_cache_service->IsInMemoryCacheEmptyForTesting());
// Verify that the pref-based cache is initially empty.
PrefService* prefs = GetProfile()->GetPrefs();
EXPECT_TRUE(prefs->GetString(omnibox::kZeroSuggestCachedResults).empty());
EXPECT_TRUE(
prefs->GetDict(omnibox::kZeroSuggestCachedResultsWithURL).empty());
BlockUntilBrowsingDataRemoved(base::Time(), base::Time::Max(),
content::BrowsingDataRemover::DATA_TYPE_COOKIES,
false);
// Expect the in-memory cache to be cleared when cookies are removed.
EXPECT_TRUE(zero_suggest_cache_service->IsInMemoryCacheEmptyForTesting());
// Expect the prefs to remain empty.
EXPECT_TRUE(prefs->GetString(omnibox::kZeroSuggestCachedResults).empty());
EXPECT_TRUE(
prefs->GetDict(omnibox::kZeroSuggestCachedResultsWithURL).empty());
EXPECT_EQ(content::BrowsingDataRemover::DATA_TYPE_COOKIES, GetRemovalMask());
EXPECT_EQ(content::BrowsingDataRemover::ORIGIN_TYPE_UNPROTECTED_WEB,
GetOriginTypeMask());
}
#endif // !BUILDFLAG(IS_ANDROID)
#if BUILDFLAG(IS_CHROMEOS)
TEST_F(ChromeBrowsingDataRemoverDelegateTest,
ContentProtectionPlatformKeysRemoval) {
auto user_manager = std::make_unique<ash::FakeChromeUserManager>();
auto* user =
user_manager->AddUser(AccountId::FromUserEmail("test@example.com"));
user_manager->UserLoggedIn(
user->GetAccountId(),
user_manager::TestHelper::GetFakeUsernameHash(user->GetAccountId()));
user_manager::ScopedUserManager user_manager_enabler(std::move(user_manager));
ash::AttestationClient::InitializeFake();
BlockUntilBrowsingDataRemoved(
base::Time(), base::Time::Max(),
content::BrowsingDataRemover::DATA_TYPE_MEDIA_LICENSES, false);
const std::vector<::attestation::DeleteKeysRequest>& history =
ash::AttestationClient::Get()->GetTestInterface()->delete_keys_history();
EXPECT_EQ(history.size(), 1u);
ash::AttestationClient::Shutdown();
}
#endif
TEST_F(ChromeBrowsingDataRemoverDelegateTest, DomainReliability_Null) {
ClearDomainReliabilityTester tester(GetProfile());
EXPECT_EQ(0u, tester.clear_count());
}
TEST_F(ChromeBrowsingDataRemoverDelegateTest, DomainReliability_Beacons) {
ClearDomainReliabilityTester tester(GetProfile());
BlockUntilBrowsingDataRemoved(base::Time(), base::Time::Max(),
constants::DATA_TYPE_HISTORY, false);
EXPECT_EQ(1u, tester.clear_count());
EXPECT_EQ(
network::mojom::NetworkContext::DomainReliabilityClearMode::CLEAR_BEACONS,
tester.last_clear_mode());
EXPECT_TRUE(tester.last_filter().is_null());
}
// TODO(crbug.com/40458377): Disabled, since history is not yet marked as
// a filterable datatype.
TEST_F(ChromeBrowsingDataRemoverDelegateTest,
DISABLED_DomainReliability_Beacons_WithFilter) {
ClearDomainReliabilityTester tester(GetProfile());
std::unique_ptr<BrowsingDataFilterBuilder> builder(
BrowsingDataFilterBuilder::Create(
BrowsingDataFilterBuilder::Mode::kDelete));
builder->AddRegisterableDomain(kTestRegisterableDomain1);
BlockUntilOriginDataRemoved(base::Time(), base::Time::Max(),
constants::DATA_TYPE_HISTORY, builder->Copy());
EXPECT_EQ(1u, tester.clear_count());
EXPECT_EQ(
network::mojom::NetworkContext::DomainReliabilityClearMode::CLEAR_BEACONS,
tester.last_clear_mode());
EXPECT_TRUE(
ProbablySameFilters(builder->BuildUrlFilter(), tester.last_filter()));
}
TEST_F(ChromeBrowsingDataRemoverDelegateTest, DomainReliability_Contexts) {
ClearDomainReliabilityTester tester(GetProfile());
BlockUntilBrowsingDataRemoved(base::Time(), base::Time::Max(),
content::BrowsingDataRemover::DATA_TYPE_COOKIES,
false);
EXPECT_EQ(1u, tester.clear_count());
EXPECT_EQ(network::mojom::NetworkContext::DomainReliabilityClearMode::
CLEAR_CONTEXTS,
tester.last_clear_mode());
EXPECT_TRUE(tester.last_filter().is_null());
}
TEST_F(ChromeBrowsingDataRemoverDelegateTest,
DomainReliability_Contexts_WithFilter) {
ClearDomainReliabilityTester tester(GetProfile());
std::unique_ptr<BrowsingDataFilterBuilder> builder(
BrowsingDataFilterBuilder::Create(
BrowsingDataFilterBuilder::Mode::kDelete));
builder->AddRegisterableDomain(kTestRegisterableDomain1);
BlockUntilOriginDataRemoved(base::Time(), base::Time::Max(),
content::BrowsingDataRemover::DATA_TYPE_COOKIES,
builder->Copy());
EXPECT_EQ(1u, tester.clear_count());
EXPECT_EQ(network::mojom::NetworkContext::DomainReliabilityClearMode::
CLEAR_CONTEXTS,
tester.last_clear_mode());
EXPECT_TRUE(
ProbablySameFilters(builder->BuildUrlFilter(), tester.last_filter()));
}
TEST_F(ChromeBrowsingDataRemoverDelegateTest, DomainReliability_ContextsWin) {
ClearDomainReliabilityTester tester(GetProfile());
BlockUntilBrowsingDataRemoved(
base::Time(), base::Time::Max(),
constants::DATA_TYPE_HISTORY |
content::BrowsingDataRemover::DATA_TYPE_COOKIES,
false);
EXPECT_EQ(1u, tester.clear_count());
EXPECT_EQ(network::mojom::NetworkContext::DomainReliabilityClearMode::
CLEAR_CONTEXTS,
tester.last_clear_mode());
}
TEST_F(ChromeBrowsingDataRemoverDelegateTest,
DomainReliability_ProtectedOrigins) {
ClearDomainReliabilityTester tester(GetProfile());
BlockUntilBrowsingDataRemoved(base::Time(), base::Time::Max(),
content::BrowsingDataRemover::DATA_TYPE_COOKIES,
true);
EXPECT_EQ(1u, tester.clear_count());
EXPECT_EQ(network::mojom::NetworkContext::DomainReliabilityClearMode::
CLEAR_CONTEXTS,
tester.last_clear_mode());
}
// TODO(juliatuttle): This isn't actually testing the no-monitor case, since
// BrowsingDataRemoverTest now creates one unconditionally, since it's needed
// for some unrelated test cases. This should be fixed so it tests the no-
// monitor case again.
TEST_F(ChromeBrowsingDataRemoverDelegateTest,
DISABLED_DomainReliability_NoMonitor) {
BlockUntilBrowsingDataRemoved(
base::Time(), base::Time::Max(),
constants::DATA_TYPE_HISTORY |
content::BrowsingDataRemover::DATA_TYPE_COOKIES,
false);
}
// Tests that the deletion of downloads completes successfully and that
// ChromeDownloadManagerDelegate is correctly created and shut down.
TEST_F(ChromeBrowsingDataRemoverDelegateTest, RemoveDownloads) {
RemoveDownloadsTester tester(GetProfile());
EXPECT_CALL(*tester.download_manager(), RemoveDownloadsByURLAndTime(_, _, _));
BlockUntilBrowsingDataRemoved(
base::Time(), base::Time::Max(),
content::BrowsingDataRemover::DATA_TYPE_DOWNLOADS, false);
}
TEST_F(ChromeBrowsingDataRemoverDelegateWithPasswordsTest,
RemovePasswordStatistics) {
base::RepeatingCallback<bool(const GURL&)> empty_filter;
testing::NiceMock<password_manager::MockSmartBubbleStatsStore>
mock_smart_bubble_stats_store;
ON_CALL(*profile_password_store(), GetSmartBubbleStatsStore)
.WillByDefault(Return(&mock_smart_bubble_stats_store));
EXPECT_CALL(
mock_smart_bubble_stats_store,
RemoveStatisticsByOriginAndTime(ProbablySameFilter(empty_filter),
base::Time(), base::Time::Max(), _))
.WillOnce(testing::WithArg<3>([](base::OnceClosure completion) {
base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
FROM_HERE, std::move(completion));
}));
BlockUntilBrowsingDataRemoved(base::Time(), base::Time::Max(),
constants::DATA_TYPE_HISTORY, false);
}
// TODO(crbug.com/40458377): Disabled, since history is not yet marked as
// a filterable datatype.
TEST_F(ChromeBrowsingDataRemoverDelegateWithPasswordsTest,
DISABLED_RemovePasswordStatisticsByOrigin) {
std::unique_ptr<BrowsingDataFilterBuilder> builder(
BrowsingDataFilterBuilder::Create(
BrowsingDataFilterBuilder::Mode::kDelete));
builder->AddRegisterableDomain(kTestRegisterableDomain1);
base::RepeatingCallback<bool(const GURL&)> filter = builder->BuildUrlFilter();
testing::NiceMock<password_manager::MockSmartBubbleStatsStore>
mock_smart_bubble_stats_store;
ON_CALL(*profile_password_store(), GetSmartBubbleStatsStore)
.WillByDefault(Return(&mock_smart_bubble_stats_store));
EXPECT_CALL(
mock_smart_bubble_stats_store,
RemoveStatisticsByOriginAndTime(ProbablySameFilter(filter), base::Time(),
base::Time::Max(), _))
.WillOnce(testing::WithArg<3>([](base::OnceClosure completion) {
base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
FROM_HERE, std::move(completion));
}));
BlockUntilOriginDataRemoved(base::Time(), base::Time::Max(),
constants::DATA_TYPE_HISTORY, std::move(builder));
}
TEST_F(ChromeBrowsingDataRemoverDelegateWithPasswordsTest,
RemovePasswordsByTimeOnly) {
ExpectRemoveLoginsCreatedBetween(profile_password_store());
BlockUntilBrowsingDataRemoved(base::Time(), base::Time::Max(),
constants::DATA_TYPE_PASSWORDS, false);
}
TEST_F(ChromeBrowsingDataRemoverDelegateWithPasswordsTest,
RemovePasswordsFailed_CallbacksFailedDataTypes) {
ExpectRemoveLoginsCreatedBetween(profile_password_store(),
/* success= */ false);
uint64_t failed_data_types = BlockUntilBrowsingDataRemoved(
base::Time(), base::Time::Max(), constants::DATA_TYPE_PASSWORDS, false);
EXPECT_EQ(failed_data_types, constants::DATA_TYPE_PASSWORDS);
}
TEST_F(ChromeBrowsingDataRemoverDelegateWithPasswordsTest,
CheckFailWhenRemovePasswordsByOrigin) {
std::unique_ptr<BrowsingDataFilterBuilder> builder(
BrowsingDataFilterBuilder::Create(
BrowsingDataFilterBuilder::Mode::kDelete));
builder->AddRegisterableDomain(kTestRegisterableDomain1);
EXPECT_CHECK_DEATH_WITH(
BlockUntilOriginDataRemoved(base::Time(), base::Time::Max(),
constants::DATA_TYPE_PASSWORDS,
std::move(builder)),
"");
}
TEST_F(ChromeBrowsingDataRemoverDelegateWithPasswordsTest,
RemovingProfileStorePasswordsTrackedInAPref) {
ExpectRemoveLoginsCreatedBetween(profile_password_store());
BlockUntilBrowsingDataRemoved(base::Time(), base::Time::Max(),
constants::DATA_TYPE_PASSWORDS, false);
// Verify that password removal reason was tracked.
EXPECT_EQ(
GetProfile()->GetPrefs()->GetInteger(
password_manager::prefs::kPasswordRemovalReasonForProfile),
1 << static_cast<int>(
password_manager::metrics_util::
PasswordManagerCredentialRemovalReason::kClearBrowsingData));
EXPECT_EQ(GetProfile()->GetPrefs()->GetInteger(
password_manager::prefs::kPasswordRemovalReasonForAccount),
0);
}
TEST_F(ChromeBrowsingDataRemoverDelegateWithPasswordsTest, DisableAutoSignIn) {
base::RepeatingCallback<bool(const GURL&)> empty_filter =
BrowsingDataFilterBuilder::BuildNoopFilter();
EXPECT_CALL(*profile_password_store(),
DisableAutoSignInForOrigins(ProbablySameFilter(empty_filter), _))
.WillOnce(testing::WithArg<1>([](base::OnceClosure completion) {
base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
FROM_HERE, std::move(completion));
}));
BlockUntilBrowsingDataRemoved(base::Time(), base::Time::Max(),
content::BrowsingDataRemover::DATA_TYPE_COOKIES,
false);
}
TEST_F(ChromeBrowsingDataRemoverDelegateWithPasswordsTest,
DisableAutoSignInAfterRemovingPasswords) {
base::RepeatingCallback<bool(const GURL&)> empty_filter =
BrowsingDataFilterBuilder::BuildNoopFilter();
ExpectRemoveLoginsCreatedBetween(profile_password_store());
EXPECT_CALL(*profile_password_store(),
DisableAutoSignInForOrigins(ProbablySameFilter(empty_filter), _))
.WillOnce(testing::WithArg<1>([](base::OnceClosure completion) {
base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
FROM_HERE, std::move(completion));
}));
BlockUntilBrowsingDataRemoved(
base::Time(), base::Time::Max(),
content::BrowsingDataRemover::DATA_TYPE_COOKIES |
constants::DATA_TYPE_PASSWORDS,
false);
}
TEST_F(ChromeBrowsingDataRemoverDelegateWithPasswordsTest,
DisableAutoSignInCrossSiteClearSiteData) {
std::unique_ptr<BrowsingDataFilterBuilder> filter(
BrowsingDataFilterBuilder::Create(
BrowsingDataFilterBuilder::Mode::kDelete));
filter->AddRegisterableDomain("cookie.com");
filter->SetCookiePartitionKeyCollection(net::CookiePartitionKeyCollection(
net::CookiePartitionKey::FromURLForTesting(
GURL("https://notcookie.com"))));
filter->SetPartitionedCookiesOnly(true);
EXPECT_CALL(*profile_password_store(), DisableAutoSignInForOrigins).Times(0);
BlockUntilOriginDataRemoved(base::Time(), base::Time::Max(),
content::BrowsingDataRemover::DATA_TYPE_COOKIES,
std::move(filter));
}
TEST_F(ChromeBrowsingDataRemoverDelegateTest,
RemoveContentSettingsWithPreserveFilter) {
// When a SiteEngagementService instance is first constructed, it deletes
// stale values from the settings map in a task posted to the UI thread. If
// that happens to run during BlockUntilOriginDataRemoved(), this test will
// fail. So to prevent that, force the task execution ahead of time.
site_engagement::SiteEngagementService::Get(GetProfile());
// This test relies on async loading to complete. RunUntilIdle() should be
// removed and an explicit wait should be added.
task_environment()->RunUntilIdle();
// Add our settings.
const GURL kOrigin1("http://host1.com:1");
const GURL kOrigin2("http://host2.com:1");
const GURL kOrigin3("http://host3.com:1");
const GURL kOrigin4("https://host3.com:1");
HostContentSettingsMap* host_content_settings_map =
HostContentSettingsMapFactory::GetForProfile(GetProfile());
host_content_settings_map->SetWebsiteSettingDefaultScope(
kOrigin1, GURL(), ContentSettingsType::SITE_ENGAGEMENT,
base::Value(base::Value::Type::DICT));
host_content_settings_map->SetWebsiteSettingDefaultScope(
kOrigin2, GURL(), ContentSettingsType::SITE_ENGAGEMENT,
base::Value(base::Value::Type::DICT));
host_content_settings_map->SetWebsiteSettingDefaultScope(
kOrigin3, GURL(), ContentSettingsType::SITE_ENGAGEMENT,
base::Value(base::Value::Type::DICT));
host_content_settings_map->SetWebsiteSettingDefaultScope(
kOrigin4, GURL(), ContentSettingsType::SITE_ENGAGEMENT,
base::Value(base::Value::Type::DICT));
// Clear all except for origin1 and origin3.
std::unique_ptr<BrowsingDataFilterBuilder> filter(
BrowsingDataFilterBuilder::Create(
BrowsingDataFilterBuilder::Mode::kPreserve));
filter->AddRegisterableDomain(kTestRegisterableDomain1);
filter->AddRegisterableDomain(kTestRegisterableDomain3);
BlockUntilOriginDataRemoved(AnHourAgo(), base::Time::Max(),
constants::DATA_TYPE_SITE_USAGE_DATA,
std::move(filter));
EXPECT_EQ(constants::DATA_TYPE_SITE_USAGE_DATA, GetRemovalMask());
EXPECT_EQ(content::BrowsingDataRemover::ORIGIN_TYPE_UNPROTECTED_WEB,
GetOriginTypeMask());
// Verify we only have true, and they're origin1, origin3, and origin4.
ContentSettingsForOneType host_settings =
host_content_settings_map->GetSettingsForOneType(
ContentSettingsType::SITE_ENGAGEMENT);
EXPECT_EQ(3u, host_settings.size());
EXPECT_EQ(ContentSettingsPattern::FromURLNoWildcard(kOrigin1),
host_settings[0].primary_pattern)
<< host_settings[0].primary_pattern.ToString();
EXPECT_EQ(ContentSettingsPattern::FromURLNoWildcard(kOrigin4),
host_settings[1].primary_pattern)
<< host_settings[1].primary_pattern.ToString();
EXPECT_EQ(ContentSettingsPattern::FromURLNoWildcard(kOrigin3),
host_settings[2].primary_pattern)
<< host_settings[2].primary_pattern.ToString();
}
TEST_F(ChromeBrowsingDataRemoverDelegateTest, RemoveContentSettings) {
// This test relies on async loading to complete. RunUntilIdle() should be
// removed and an explicit wait should be added.
task_environment()->RunUntilIdle();
const GURL kOrigin1("http://host1.com:1");
const GURL kOrigin2("http://host2.com:1");
const GURL kOrigin3("http://host3.com:1");
auto* map = HostContentSettingsMapFactory::GetForProfile(GetProfile());
map->SetContentSettingDefaultScope(kOrigin1, kOrigin1,
ContentSettingsType::GEOLOCATION,
CONTENT_SETTING_ALLOW);
map->SetContentSettingDefaultScope(kOrigin2, kOrigin2,
ContentSettingsType::NOTIFICATIONS,
CONTENT_SETTING_ALLOW);
map->SetContentSettingDefaultScope(
kOrigin3, GURL(), ContentSettingsType::COOKIES, CONTENT_SETTING_BLOCK);
ContentSettingsPattern pattern =
ContentSettingsPattern::FromString("[*.]example.com");
map->SetContentSettingCustomScope(pattern, ContentSettingsPattern::Wildcard(),
ContentSettingsType::COOKIES,
CONTENT_SETTING_BLOCK);
BlockUntilBrowsingDataRemoved(base::Time(), base::Time::Max(),
constants::DATA_TYPE_CONTENT_SETTINGS, false);
ContentSettingsForOneType host_settings =
map->GetSettingsForOneType(ContentSettingsType::GEOLOCATION);
ASSERT_EQ(1u, host_settings.size());
EXPECT_EQ(ContentSettingsPattern::Wildcard(),
host_settings[0].primary_pattern)
<< host_settings[0].primary_pattern.ToString();
EXPECT_EQ(CONTENT_SETTING_ASK, host_settings[0].GetContentSetting());
host_settings =
map->GetSettingsForOneType(ContentSettingsType::NOTIFICATIONS);
ASSERT_EQ(1u, host_settings.size());
EXPECT_EQ(ContentSettingsPattern::Wildcard(),
host_settings[0].primary_pattern)
<< host_settings[0].primary_pattern.ToString();
EXPECT_EQ(CONTENT_SETTING_ASK, host_settings[0].GetContentSetting());
host_settings = map->GetSettingsForOneType(ContentSettingsType::COOKIES);
ASSERT_EQ(1u, host_settings.size());
EXPECT_EQ(ContentSettingsPattern::Wildcard(),
host_settings[0].primary_pattern)
<< host_settings[0].primary_pattern.ToString();
EXPECT_EQ(CONTENT_SETTING_ALLOW, host_settings[0].GetContentSetting());
}
TEST_F(ChromeBrowsingDataRemoverDelegateTest, RemoveProtocolHandler) {
// This test relies on async loading to complete. RunUntilIdle() should be
// removed and an explicit wait should be added.
task_environment()->RunUntilIdle();
auto* registry =
ProtocolHandlerRegistryFactory::GetForBrowserContext(GetProfile());
const GURL kOrigin("https://host3.com:1");
base::Time one_hour_ago = base::Time::Now() - base::Hours(1);
base::Time yesterday = base::Time::Now() - base::Days(1);
registry->OnAcceptRegisterProtocolHandler(
custom_handlers::ProtocolHandler::CreateProtocolHandler("news", kOrigin));
registry->OnAcceptRegisterProtocolHandler(custom_handlers::ProtocolHandler(
"mailto", kOrigin, yesterday,
blink::ProtocolHandlerSecurityLevel::kStrict));
EXPECT_TRUE(registry->IsHandledProtocol("news"));
EXPECT_TRUE(registry->IsHandledProtocol("mailto"));
EXPECT_EQ(
2U,
registry->GetUserDefinedHandlers(base::Time(), base::Time::Max()).size());
// Delete last hour.
BlockUntilBrowsingDataRemoved(one_hour_ago, base::Time::Max(),
constants::DATA_TYPE_CONTENT_SETTINGS, false);
EXPECT_FALSE(registry->IsHandledProtocol("news"));
EXPECT_TRUE(registry->IsHandledProtocol("mailto"));
EXPECT_EQ(
1U,
registry->GetUserDefinedHandlers(base::Time(), base::Time::Max()).size());
// Delete everything.
BlockUntilBrowsingDataRemoved(base::Time(), base::Time::Max(),
constants::DATA_TYPE_CONTENT_SETTINGS, false);
EXPECT_FALSE(registry->IsHandledProtocol("news"));
EXPECT_FALSE(registry->IsHandledProtocol("mailto"));
EXPECT_EQ(
0U,
registry->GetUserDefinedHandlers(base::Time(), base::Time::Max()).size());
}
TEST_F(ChromeBrowsingDataRemoverDelegateTest, RemoveSelectedClientHints) {
// This test relies on async loading to complete. RunUntilIdle() should be
// removed and an explicit wait should be added.
task_environment()->RunUntilIdle();
// Add our settings.
HostContentSettingsMap* host_content_settings_map =
HostContentSettingsMapFactory::GetForProfile(GetProfile());
base::Value::List client_hints_list;
client_hints_list.Append(0);
client_hints_list.Append(2);
base::Value::Dict client_hints_dictionary;
client_hints_dictionary.Set(client_hints::kClientHintsSettingKey,
std::move(client_hints_list));
const GURL kOrigin1("http://host1.com:1");
const GURL kOrigin2("http://host2.com:1");
const GURL kOrigin3("http://host3.com:1");
host_content_settings_map->SetWebsiteSettingDefaultScope(
kOrigin1, GURL(), ContentSettingsType::CLIENT_HINTS,
base::Value(client_hints_dictionary.Clone()));
host_content_settings_map->SetWebsiteSettingDefaultScope(
kOrigin2, GURL(), ContentSettingsType::CLIENT_HINTS,
base::Value(client_hints_dictionary.Clone()));
host_content_settings_map->SetWebsiteSettingDefaultScope(
kOrigin3, GURL(), ContentSettingsType::CLIENT_HINTS,
base::Value(client_hints_dictionary.Clone()));
// Clear all except for origin1 and origin3.
std::unique_ptr<BrowsingDataFilterBuilder> filter(
BrowsingDataFilterBuilder::Create(
BrowsingDataFilterBuilder::Mode::kPreserve));
filter->AddRegisterableDomain(kTestRegisterableDomain1);
filter->AddRegisterableDomain(kTestRegisterableDomain3);
BlockUntilOriginDataRemoved(AnHourAgo(), base::Time::Max(),
content::BrowsingDataRemover::DATA_TYPE_COOKIES,
std::move(filter));
ContentSettingsForOneType host_settings =
host_content_settings_map->GetSettingsForOneType(
ContentSettingsType::CLIENT_HINTS);
ASSERT_EQ(2u, host_settings.size());
EXPECT_EQ(ContentSettingsPattern::FromURLNoWildcard(kOrigin1),
host_settings[0].primary_pattern)
<< host_settings[0].primary_pattern.ToString();
EXPECT_EQ(ContentSettingsPattern::FromURLNoWildcard(kOrigin3),
host_settings[1].primary_pattern)
<< host_settings[1].primary_pattern.ToString();
for (const auto& setting : host_settings) {
EXPECT_EQ(ContentSettingsPattern::Wildcard(), setting.secondary_pattern);
EXPECT_EQ(client_hints_dictionary, setting.setting_value);
}
}
TEST_F(ChromeBrowsingDataRemoverDelegateTest, RemoveAllClientHints) {
// Add our settings.
HostContentSettingsMap* host_content_settings_map =
HostContentSettingsMapFactory::GetForProfile(GetProfile());
base::Value::List client_hints_list;
client_hints_list.Append(0);
client_hints_list.Append(2);
base::Value::Dict client_hints_dictionary;
client_hints_dictionary.Set(client_hints::kClientHintsSettingKey,
std::move(client_hints_list));
host_content_settings_map->SetWebsiteSettingDefaultScope(
GURL("http://host1.com:1"), GURL(), ContentSettingsType::CLIENT_HINTS,
base::Value(client_hints_dictionary.Clone()));
host_content_settings_map->SetWebsiteSettingDefaultScope(
GURL("http://host2.com:1"), GURL(), ContentSettingsType::CLIENT_HINTS,
base::Value(client_hints_dictionary.Clone()));
host_content_settings_map->SetWebsiteSettingDefaultScope(
GURL("http://host3.com:1"), GURL(), ContentSettingsType::CLIENT_HINTS,
base::Value(client_hints_dictionary.Clone()));
// Clear all.
BlockUntilBrowsingDataRemoved(AnHourAgo(), base::Time::Max(),
content::BrowsingDataRemover::DATA_TYPE_COOKIES,
false);
ContentSettingsForOneType host_settings =
host_content_settings_map->GetSettingsForOneType(
ContentSettingsType::CLIENT_HINTS);
ASSERT_EQ(0u, host_settings.size());
}
#if !BUILDFLAG(IS_ANDROID)
TEST_F(ChromeBrowsingDataRemoverDelegateTest, RemoveZoomLevel) {
content::HostZoomMap* zoom_map =
content::HostZoomMap::GetDefaultForBrowserContext(GetProfile());
EXPECT_EQ(0u, zoom_map->GetAllZoomLevels().size());
base::SimpleTestClock test_clock;
zoom_map->SetClockForTesting(&test_clock);
base::Time now = base::Time::Now();
zoom_map->InitializeZoomLevelForHost(kTestRegisterableDomain1, 1.5,
now - base::Hours(5));
test_clock.SetNow(now - base::Hours(2));
zoom_map->SetZoomLevelForHost(kTestRegisterableDomain3, 2.0);
EXPECT_EQ(2u, zoom_map->GetAllZoomLevels().size());
// Remove everything created during the last hour.
BlockUntilBrowsingDataRemoved(now - base::Hours(1), base::Time::Max(),
constants::DATA_TYPE_CONTENT_SETTINGS, false);
// Nothing should be deleted as the zoomlevels were created earlier.
EXPECT_EQ(2u, zoom_map->GetAllZoomLevels().size());
test_clock.SetNow(now);
zoom_map->SetZoomLevelForHost(kTestRegisterableDomain3, 2.0);
// Remove everything changed during the last hour (domain3).
BlockUntilBrowsingDataRemoved(now - base::Hours(1), base::Time::Max(),
constants::DATA_TYPE_CONTENT_SETTINGS, false);
// Verify we still have the zoom_level for domain1.
auto levels = zoom_map->GetAllZoomLevels();
EXPECT_EQ(1u, levels.size());
EXPECT_EQ(kTestRegisterableDomain1, levels[0].host);
zoom_map->SetZoomLevelForHostAndScheme("chrome", "print", 4.0);
// Remove everything.
BlockUntilBrowsingDataRemoved(base::Time(), base::Time::Max(),
constants::DATA_TYPE_CONTENT_SETTINGS, false);
// Host and scheme zoomlevels should not be affected.
levels = zoom_map->GetAllZoomLevels();
EXPECT_EQ(1u, levels.size());
EXPECT_EQ("chrome", levels[0].scheme);
EXPECT_EQ("print", levels[0].host);
zoom_map->SetClockForTesting(base::DefaultClock::GetInstance());
}
#endif
#if !BUILDFLAG(IS_ANDROID)
TEST_F(ChromeBrowsingDataRemoverDelegateTest, RemoveTabDiscardExceptionsList) {
base::Value::Dict exclusion_map;
exclusion_map.Set("a.com", base::TimeToValue(base::Time::Now()));
exclusion_map.Set("b.com",
base::TimeToValue(base::Time::Now() - base::Hours(3)));
exclusion_map.Set("c.com", base::Value(base::Value::Type::NONE));
GetProfile()->GetPrefs()->SetDict(
performance_manager::user_tuning::prefs::kTabDiscardingExceptionsWithTime,
std::move(exclusion_map));
// Remove everything created during the last hour.
BlockUntilBrowsingDataRemoved(base::Time::Now() - base::Hours(1),
base::Time::Max(),
constants::DATA_TYPE_CONTENT_SETTINGS, false);
// Two of the entries should have been deleted: the one with no timestamp and
// the one created now.
EXPECT_EQ(1u, GetProfile()
->GetPrefs()
->GetDict(performance_manager::user_tuning::prefs::
kTabDiscardingExceptionsWithTime)
.size());
// Remove everything created during all time.
BlockUntilBrowsingDataRemoved(base::Time::Min(), base::Time::Max(),
constants::DATA_TYPE_CONTENT_SETTINGS, false);
// All entries should be removed now.
EXPECT_EQ(0u, GetProfile()
->GetPrefs()
->GetDict(performance_manager::user_tuning::prefs::
kTabDiscardingExceptionsWithTime)
.size());
}
#endif
TEST_F(ChromeBrowsingDataRemoverDelegateTest, RemoveTranslateBlocklist) {
auto translate_prefs =
ChromeTranslateClient::CreateTranslatePrefs(GetProfile()->GetPrefs());
translate_prefs->AddSiteToNeverPromptList("google.com");
task_environment()->AdvanceClock(base::Days(1));
base::Time t = base::Time::Now();
translate_prefs->AddSiteToNeverPromptList("maps.google.com");
EXPECT_TRUE(translate_prefs->IsSiteOnNeverPromptList("google.com"));
EXPECT_TRUE(translate_prefs->IsSiteOnNeverPromptList("maps.google.com"));
BlockUntilBrowsingDataRemoved(t, base::Time::Max(),
constants::DATA_TYPE_CONTENT_SETTINGS, false);
EXPECT_TRUE(translate_prefs->IsSiteOnNeverPromptList("google.com"));
EXPECT_FALSE(translate_prefs->IsSiteOnNeverPromptList("maps.google.com"));
BlockUntilBrowsingDataRemoved(base::Time(), base::Time::Max(),
constants::DATA_TYPE_CONTENT_SETTINGS, false);
EXPECT_FALSE(translate_prefs->IsSiteOnNeverPromptList("google.com"));
EXPECT_FALSE(translate_prefs->IsSiteOnNeverPromptList("maps.google.com"));
}
TEST_F(ChromeBrowsingDataRemoverDelegateTest, RemoveDurablePermission) {
// Add our settings.
const GURL kOrigin1("http://host1.com:1");
const GURL kOrigin2("http://host2.com:1");
HostContentSettingsMap* host_content_settings_map =
HostContentSettingsMapFactory::GetForProfile(GetProfile());
DurableStoragePermissionContext durable_permission(GetProfile());
durable_permission.UpdateContentSetting(
permissions::PermissionRequestData(
std::make_unique<permissions::ContentSettingPermissionResolver>(
ContentSettingsType::DURABLE_STORAGE),
/*user_gesture=*/true, kOrigin1, GURL()),
CONTENT_SETTING_ALLOW, /*is_one_time=*/false);
durable_permission.UpdateContentSetting(
permissions::PermissionRequestData(
std::make_unique<permissions::ContentSettingPermissionResolver>(
ContentSettingsType::DURABLE_STORAGE),
/*user_gesture=*/true, kOrigin2, GURL()),
CONTENT_SETTING_ALLOW, /*is_one_time=*/false);
// Clear all except for origin1 and origin3.
std::unique_ptr<BrowsingDataFilterBuilder> filter(
BrowsingDataFilterBuilder::Create(
BrowsingDataFilterBuilder::Mode::kPreserve));
filter->AddRegisterableDomain(kTestRegisterableDomain1);
filter->AddRegisterableDomain(kTestRegisterableDomain3);
BlockUntilOriginDataRemoved(AnHourAgo(), base::Time::Max(),
constants::DATA_TYPE_DURABLE_PERMISSION,
std::move(filter));
EXPECT_EQ(constants::DATA_TYPE_DURABLE_PERMISSION, GetRemovalMask());
EXPECT_EQ(content::BrowsingDataRemover::ORIGIN_TYPE_UNPROTECTED_WEB,
GetOriginTypeMask());
// Verify we only have allow for the first origin.
ContentSettingsForOneType host_settings =
host_content_settings_map->GetSettingsForOneType(
ContentSettingsType::DURABLE_STORAGE);
ASSERT_EQ(2u, host_settings.size());
// Only the first should should have a setting.
EXPECT_EQ(ContentSettingsPattern::FromURLNoWildcard(kOrigin1),
host_settings[0].primary_pattern)
<< host_settings[0].primary_pattern.ToString();
EXPECT_EQ(CONTENT_SETTING_ALLOW, host_settings[0].GetContentSetting());
// And our wildcard.
EXPECT_EQ(ContentSettingsPattern::Wildcard(),
host_settings[1].primary_pattern)
<< host_settings[1].primary_pattern.ToString();
EXPECT_EQ(CONTENT_SETTING_ASK, host_settings[1].GetContentSetting());
}
TEST_F(ChromeBrowsingDataRemoverDelegateTest,
DurablePermissionIsPartOfEmbedderDOMStorage) {
HostContentSettingsMap* host_content_settings_map =
HostContentSettingsMapFactory::GetForProfile(GetProfile());
DurableStoragePermissionContext durable_permission(GetProfile());
durable_permission.UpdateContentSetting(
permissions::PermissionRequestData(
std::make_unique<permissions::ContentSettingPermissionResolver>(
ContentSettingsType::DURABLE_STORAGE),
/*user_gesture=*/true, GURL("http://host1.com:1"), GURL()),
CONTENT_SETTING_ALLOW,
/*is_one_time=*/false);
ContentSettingsForOneType host_settings =
host_content_settings_map->GetSettingsForOneType(
ContentSettingsType::DURABLE_STORAGE);
EXPECT_EQ(2u, host_settings.size());
BlockUntilBrowsingDataRemoved(
base::Time(), base::Time::Max(),
content::BrowsingDataRemover::DATA_TYPE_EMBEDDER_DOM_STORAGE, false);
// After the deletion, only the wildcard should remain.
host_settings = host_content_settings_map->GetSettingsForOneType(
ContentSettingsType::DURABLE_STORAGE);
EXPECT_EQ(1u, host_settings.size());
EXPECT_EQ(ContentSettingsPattern::Wildcard(),
host_settings[0].primary_pattern)
<< host_settings[0].primary_pattern.ToString();
}
TEST_F(ChromeBrowsingDataRemoverDelegateTest, RemoveFederatedContentSettings) {
const GURL rp_url("https://rp.com");
const url::Origin rp_origin = url::Origin::Create(rp_url);
const GURL rp_embedder_url("https://rp-embedder.com");
const url::Origin rp_embedder_origin = url::Origin::Create(rp_embedder_url);
const url::Origin idp_origin = url::Origin::Create(GURL("https://idp.com"));
const std::string account_id("account_id");
HostContentSettingsMap* host_content_settings_map =
HostContentSettingsMapFactory::GetForProfile(GetProfile());
content::BrowsingDataRemover::DataType test_cases[] = {
content::BrowsingDataRemover::DATA_TYPE_COOKIES,
constants::DATA_TYPE_HISTORY, constants::DATA_TYPE_PASSWORDS};
for (content::BrowsingDataRemover::DataType test_data_type : test_cases) {
SCOPED_TRACE(base::StringPrintf("Test data type %d",
static_cast<int>(test_data_type)));
{
FederatedIdentityPermissionContext federated_context(GetProfile());
federated_context.GrantSharingPermission(rp_origin, rp_embedder_origin,
idp_origin, account_id);
ASSERT_TRUE(federated_context.GetLastUsedTimestamp(
rp_origin, rp_embedder_origin, idp_origin, account_id));
host_content_settings_map->SetContentSettingDefaultScope(
rp_url, rp_embedder_url, ContentSettingsType::FEDERATED_IDENTITY_API,
CONTENT_SETTING_BLOCK);
ASSERT_EQ(CONTENT_SETTING_BLOCK,
host_content_settings_map->GetContentSetting(
rp_url, rp_embedder_url,
ContentSettingsType::FEDERATED_IDENTITY_API));
federated_context.Shutdown();
}
BlockUntilBrowsingDataRemoved(AnHourAgo(), base::Time::Max(),
test_data_type,
/*include_protected_origins=*/true);
{
// Re-initialize contexts in order to update in-memory
// ObjectPermissionContextBase cache.
FederatedIdentityPermissionContext federated_context(GetProfile());
EXPECT_FALSE(federated_context.GetLastUsedTimestamp(
rp_origin, rp_embedder_origin, idp_origin, account_id));
// Content setting is on by default.
EXPECT_EQ(CONTENT_SETTING_ALLOW,
host_content_settings_map->GetContentSetting(
rp_url, rp_embedder_url,
ContentSettingsType::FEDERATED_IDENTITY_API));
federated_context.Shutdown();
}
}
}
// Test that removing passwords clears HTTP auth data.
TEST_F(ChromeBrowsingDataRemoverDelegateTest,
ClearHttpAuthCache_RemovePasswords) {
net::HttpNetworkSession* http_session = network_context()
->url_request_context()
->http_transaction_factory()
->GetSession();
DCHECK(http_session);
net::HttpAuthCache* http_auth_cache = http_session->http_auth_cache();
const url::SchemeHostPort kSchemeHostPort(GURL("http://host1.com:1"));
http_auth_cache->Add(kSchemeHostPort, net::HttpAuth::AUTH_SERVER, kTestRealm,
net::HttpAuth::AUTH_SCHEME_BASIC,
net::NetworkAnonymizationKey(), "test challenge",
net::AuthCredentials(u"foo", u"bar"), "/");
CHECK(http_auth_cache->Lookup(kSchemeHostPort, net::HttpAuth::AUTH_SERVER,
kTestRealm, net::HttpAuth::AUTH_SCHEME_BASIC,
net::NetworkAnonymizationKey()));
BlockUntilBrowsingDataRemoved(base::Time(), base::Time::Max(),
constants::DATA_TYPE_PASSWORDS, false);
EXPECT_EQ(nullptr, http_auth_cache->Lookup(
kSchemeHostPort, net::HttpAuth::AUTH_SERVER,
kTestRealm, net::HttpAuth::AUTH_SCHEME_BASIC,
net::NetworkAnonymizationKey()));
}
TEST_F(ChromeBrowsingDataRemoverDelegateTest, RemoveFledgeJoinSettings) {
auto* privacy_sandbox_settings =
PrivacySandboxSettingsFactory::GetForProfile(GetProfile());
privacy_sandbox_settings->SetAllPrivacySandboxAllowedForTesting();
privacy_sandbox::ScopedPrivacySandboxAttestations scoped_attestations(
privacy_sandbox::PrivacySandboxAttestations::CreateForTesting());
// Mark all Privacy Sandbox APIs as attested since the test case is testing
// behaviors not related to attestations.
privacy_sandbox::PrivacySandboxAttestations::GetInstance()
->SetAllPrivacySandboxAttestedForTesting(true);
auto auction_party = url::Origin::Create(GURL("https://auction-party.com"));
const std::string etld_one = "example.com";
base::Time setting_time_one = base::Time::Now();
privacy_sandbox_settings->SetFledgeJoiningAllowed(etld_one, false);
task_environment()->AdvanceClock(base::Days(1));
const std::string etld_two = "another-example.com";
base::Time setting_time_two = base::Time::Now();
privacy_sandbox_settings->SetFledgeJoiningAllowed(etld_two, false);
task_environment()->AdvanceClock(base::Days(1));
const std::string etld_three = "different-example.com";
base::Time setting_time_three = base::Time::Now();
privacy_sandbox_settings->SetFledgeJoiningAllowed(etld_three, false);
EXPECT_FALSE(privacy_sandbox_settings->IsFledgeAllowed(
url::Origin::Create(GURL("https://www.example.com")), auction_party,
content::InterestGroupApiOperation::kJoin));
EXPECT_FALSE(privacy_sandbox_settings->IsFledgeAllowed(
url::Origin::Create(GURL("https://another-example.com")), auction_party,
content::InterestGroupApiOperation::kJoin));
EXPECT_FALSE(privacy_sandbox_settings->IsFledgeAllowed(
url::Origin::Create(GURL("http://different-example.com")), auction_party,
content::InterestGroupApiOperation::kJoin));
// Apply a deletion targeting the second setting.
BlockUntilBrowsingDataRemoved(setting_time_two - base::Seconds(1),
setting_time_two + base::Seconds(1),
constants::DATA_TYPE_CONTENT_SETTINGS, false);
EXPECT_FALSE(privacy_sandbox_settings->IsFledgeAllowed(
url::Origin::Create(GURL("https://www.example.com")), auction_party,
content::InterestGroupApiOperation::kJoin));
EXPECT_TRUE(privacy_sandbox_settings->IsFledgeAllowed(
url::Origin::Create(GURL("https://another-example.com")), auction_party,
content::InterestGroupApiOperation::kJoin));
EXPECT_FALSE(privacy_sandbox_settings->IsFledgeAllowed(
url::Origin::Create(GURL("http://different-example.com")), auction_party,
content::InterestGroupApiOperation::kJoin));
// Apply a deletion targeting the remaining settings.
BlockUntilBrowsingDataRemoved(setting_time_one, setting_time_three,
constants::DATA_TYPE_CONTENT_SETTINGS, false);
EXPECT_TRUE(privacy_sandbox_settings->IsFledgeAllowed(
url::Origin::Create(GURL("https://www.example.com")), auction_party,
content::InterestGroupApiOperation::kJoin));
EXPECT_TRUE(privacy_sandbox_settings->IsFledgeAllowed(
url::Origin::Create(GURL("https://another-example.com")), auction_party,
content::InterestGroupApiOperation::kJoin));
EXPECT_TRUE(privacy_sandbox_settings->IsFledgeAllowed(
url::Origin::Create(GURL("http://different-example.com")), auction_party,
content::InterestGroupApiOperation::kJoin));
}
TEST_F(ChromeBrowsingDataRemoverDelegateTest, RemoveTopicSettings) {
auto* privacy_sandbox_settings =
PrivacySandboxSettingsFactory::GetForProfile(GetProfile());
privacy_sandbox::CanonicalTopic topic_one(browsing_topics::Topic(1),
kTopicsAPITestTaxonomyVersion);
privacy_sandbox::CanonicalTopic topic_two(browsing_topics::Topic(2),
kTopicsAPITestTaxonomyVersion);
EXPECT_TRUE(privacy_sandbox_settings->IsTopicAllowed(topic_one));
EXPECT_TRUE(privacy_sandbox_settings->IsTopicAllowed(topic_two));
// Block topic_one.
privacy_sandbox_settings->SetTopicAllowed(topic_one, false);
EXPECT_FALSE(privacy_sandbox_settings->IsTopicAllowed(topic_one));
task_environment()->AdvanceClock(base::Days(1));
// Block topic_two.
privacy_sandbox_settings->SetTopicAllowed(topic_two, false);
EXPECT_FALSE(privacy_sandbox_settings->IsTopicAllowed(topic_two));
// Apply deletion.
BlockUntilBrowsingDataRemoved(base::Time(), base::Time::Max(),
constants::DATA_TYPE_CONTENT_SETTINGS, false);
// Verify topics are unblocked after deletion.
EXPECT_TRUE(privacy_sandbox_settings->IsTopicAllowed(topic_one));
EXPECT_TRUE(privacy_sandbox_settings->IsTopicAllowed(topic_two));
}
TEST_F(ChromeBrowsingDataRemoverDelegateTest,
ClearPermissionPromptCounts) {
RemovePermissionPromptCountsTest tester(GetProfile());
std::unique_ptr<BrowsingDataFilterBuilder> filter_builder_1(
BrowsingDataFilterBuilder::Create(
BrowsingDataFilterBuilder::Mode::kDelete));
filter_builder_1->AddRegisterableDomain(kTestRegisterableDomain1);
std::unique_ptr<BrowsingDataFilterBuilder> filter_builder_2(
BrowsingDataFilterBuilder::Create(
BrowsingDataFilterBuilder::Mode::kPreserve));
filter_builder_2->AddRegisterableDomain(kTestRegisterableDomain1);
const GURL kOrigin1("http://host1.com:1");
const GURL kOrigin2("http://host2.com:1");
{
// Test REMOVE_HISTORY.
EXPECT_FALSE(tester.RecordIgnoreAndEmbargo(
kOrigin1, ContentSettingsType::GEOLOCATION));
EXPECT_FALSE(tester.RecordIgnoreAndEmbargo(
kOrigin1, ContentSettingsType::GEOLOCATION));
EXPECT_FALSE(tester.RecordIgnoreAndEmbargo(
kOrigin1, ContentSettingsType::NOTIFICATIONS));
EXPECT_FALSE(tester.RecordDismissAndEmbargo(
kOrigin1, ContentSettingsType::MIDI_SYSEX));
EXPECT_FALSE(tester.RecordIgnoreAndEmbargo(
kOrigin2, ContentSettingsType::DURABLE_STORAGE));
EXPECT_FALSE(
tester.IsEmbargoed(kOrigin2, ContentSettingsType::NOTIFICATIONS));
EXPECT_FALSE(tester.RecordDismissAndEmbargo(
kOrigin2, ContentSettingsType::NOTIFICATIONS));
EXPECT_FALSE(tester.RecordDismissAndEmbargo(
kOrigin2, ContentSettingsType::NOTIFICATIONS));
EXPECT_TRUE(tester.RecordDismissAndEmbargo(
kOrigin2, ContentSettingsType::NOTIFICATIONS));
EXPECT_TRUE(
tester.IsEmbargoed(kOrigin2, ContentSettingsType::NOTIFICATIONS));
BlockUntilOriginDataRemoved(AnHourAgo(), base::Time::Max(),
constants::DATA_TYPE_SITE_USAGE_DATA,
std::move(filter_builder_1));
// kOrigin1 should be gone, but kOrigin2 remains.
EXPECT_EQ(
0, tester.GetIgnoreCount(kOrigin1, ContentSettingsType::GEOLOCATION));
EXPECT_EQ(
0, tester.GetIgnoreCount(kOrigin1, ContentSettingsType::NOTIFICATIONS));
EXPECT_EQ(
0, tester.GetDismissCount(kOrigin1, ContentSettingsType::MIDI_SYSEX));
EXPECT_EQ(1, tester.GetIgnoreCount(kOrigin2,
ContentSettingsType::DURABLE_STORAGE));
EXPECT_EQ(3, tester.GetDismissCount(kOrigin2,
ContentSettingsType::NOTIFICATIONS));
EXPECT_TRUE(
tester.IsEmbargoed(kOrigin2, ContentSettingsType::NOTIFICATIONS));
BlockUntilBrowsingDataRemoved(AnHourAgo(), base::Time::Max(),
constants::DATA_TYPE_HISTORY, false);
// Everything should be gone.
EXPECT_EQ(
0, tester.GetIgnoreCount(kOrigin1, ContentSettingsType::GEOLOCATION));
EXPECT_EQ(
0, tester.GetIgnoreCount(kOrigin1, ContentSettingsType::NOTIFICATIONS));
EXPECT_EQ(
0, tester.GetDismissCount(kOrigin1, ContentSettingsType::MIDI_SYSEX));
EXPECT_EQ(0, tester.GetIgnoreCount(kOrigin2,
ContentSettingsType::DURABLE_STORAGE));
EXPECT_EQ(0, tester.GetDismissCount(kOrigin2,
ContentSettingsType::NOTIFICATIONS));
EXPECT_FALSE(
tester.IsEmbargoed(kOrigin2, ContentSettingsType::NOTIFICATIONS));
}
{
// Test REMOVE_SITE_DATA.
EXPECT_FALSE(tester.RecordIgnoreAndEmbargo(
kOrigin1, ContentSettingsType::GEOLOCATION));
EXPECT_FALSE(tester.RecordIgnoreAndEmbargo(
kOrigin1, ContentSettingsType::GEOLOCATION));
EXPECT_FALSE(tester.RecordIgnoreAndEmbargo(
kOrigin1, ContentSettingsType::NOTIFICATIONS));
EXPECT_FALSE(tester.RecordDismissAndEmbargo(
kOrigin1, ContentSettingsType::MIDI_SYSEX));
EXPECT_FALSE(tester.IsEmbargoed(kOrigin1, ContentSettingsType::MIDI_SYSEX));
EXPECT_FALSE(tester.RecordIgnoreAndEmbargo(
kOrigin2, ContentSettingsType::DURABLE_STORAGE));
EXPECT_FALSE(tester.RecordDismissAndEmbargo(
kOrigin2, ContentSettingsType::NOTIFICATIONS));
BlockUntilOriginDataRemoved(AnHourAgo(), base::Time::Max(),
constants::DATA_TYPE_SITE_USAGE_DATA,
std::move(filter_builder_2));
// kOrigin2 should be gone, but kOrigin1 remains.
EXPECT_EQ(
2, tester.GetIgnoreCount(kOrigin1, ContentSettingsType::GEOLOCATION));
EXPECT_EQ(
1, tester.GetIgnoreCount(kOrigin1, ContentSettingsType::NOTIFICATIONS));
EXPECT_EQ(
1, tester.GetDismissCount(kOrigin1, ContentSettingsType::MIDI_SYSEX));
EXPECT_EQ(0, tester.GetIgnoreCount(kOrigin2,
ContentSettingsType::DURABLE_STORAGE));
EXPECT_EQ(0, tester.GetDismissCount(kOrigin2,
ContentSettingsType::NOTIFICATIONS));
EXPECT_FALSE(tester.RecordDismissAndEmbargo(
kOrigin1, ContentSettingsType::MIDI_SYSEX));
EXPECT_TRUE(tester.RecordDismissAndEmbargo(
kOrigin1, ContentSettingsType::MIDI_SYSEX));
EXPECT_EQ(
3, tester.GetDismissCount(kOrigin1, ContentSettingsType::MIDI_SYSEX));
EXPECT_TRUE(tester.IsEmbargoed(kOrigin1, ContentSettingsType::MIDI_SYSEX));
BlockUntilBrowsingDataRemoved(AnHourAgo(), base::Time::Max(),
constants::DATA_TYPE_SITE_USAGE_DATA, false);
// Everything should be gone.
EXPECT_EQ(
0, tester.GetIgnoreCount(kOrigin1, ContentSettingsType::GEOLOCATION));
EXPECT_EQ(
0, tester.GetIgnoreCount(kOrigin1, ContentSettingsType::NOTIFICATIONS));
EXPECT_EQ(
0, tester.GetDismissCount(kOrigin1, ContentSettingsType::MIDI_SYSEX));
EXPECT_EQ(0, tester.GetIgnoreCount(kOrigin2,
ContentSettingsType::DURABLE_STORAGE));
EXPECT_EQ(0, tester.GetDismissCount(kOrigin2,
ContentSettingsType::NOTIFICATIONS));
EXPECT_FALSE(tester.IsEmbargoed(kOrigin1, ContentSettingsType::MIDI_SYSEX));
}
}
// Test that the remover clears language model data (normally added by the
// LanguageDetectionDriver).
TEST_F(ChromeBrowsingDataRemoverDelegateTest,
LanguageHistogramClearedOnClearingCompleteHistory) {
language::UrlLanguageHistogram* language_histogram =
UrlLanguageHistogramFactory::GetForBrowserContext(GetProfile());
// Simulate browsing.
for (int i = 0; i < 100; i++) {
language_histogram->OnPageVisited("en");
language_histogram->OnPageVisited("en");
language_histogram->OnPageVisited("en");
language_histogram->OnPageVisited("es");
}
// Clearing a part of the history has no effect.
BlockUntilBrowsingDataRemoved(AnHourAgo(), base::Time::Max(),
constants::DATA_TYPE_HISTORY, false);
EXPECT_THAT(language_histogram->GetTopLanguages(), SizeIs(2));
EXPECT_THAT(language_histogram->GetLanguageFrequency("en"), FloatEq(0.75));
EXPECT_THAT(language_histogram->GetLanguageFrequency("es"), FloatEq(0.25));
// Clearing the full history does the trick.
BlockUntilBrowsingDataRemoved(base::Time(), base::Time::Max(),
constants::DATA_TYPE_HISTORY, false);
EXPECT_THAT(language_histogram->GetTopLanguages(), SizeIs(0));
EXPECT_THAT(language_histogram->GetLanguageFrequency("en"), FloatEq(0.0));
EXPECT_THAT(language_histogram->GetLanguageFrequency("es"), FloatEq(0.0));
}
// TODO(crbug.com/371426261)): Enable this for ENABLE_EXTENSIONS_CORE, but first
// MockExtensionSpecialStoragePolicy must compile on Android.
#if BUILDFLAG(ENABLE_EXTENSIONS_CORE)
TEST_F(ChromeBrowsingDataRemoverDelegateTest, OriginTypeMasks) {
const GURL kOriginProtected("http://protected.com");
const GURL kOriginUnprotected("http://unprotected.com");
const GURL kOriginExtension("chrome-extension://abcdefghijklmnopqrstuvwxyz");
const GURL kOriginDevTools("devtools://abcdefghijklmnopqrstuvw");
auto mock_policy = base::MakeRefCounted<MockExtensionSpecialStoragePolicy>();
// Protect |kOriginProtected|.
mock_policy->AddProtected(kOriginProtected.DeprecatedGetOriginAsURL());
EXPECT_FALSE(Match(kOriginProtected, kUnprotected, mock_policy.get()));
EXPECT_TRUE(Match(kOriginUnprotected, kUnprotected, mock_policy.get()));
EXPECT_FALSE(Match(kOriginExtension, kUnprotected, mock_policy.get()));
EXPECT_FALSE(Match(kOriginDevTools, kUnprotected, mock_policy.get()));
EXPECT_TRUE(Match(kOriginProtected, kProtected, mock_policy.get()));
EXPECT_FALSE(Match(kOriginUnprotected, kProtected, mock_policy.get()));
EXPECT_FALSE(Match(kOriginExtension, kProtected, mock_policy.get()));
EXPECT_FALSE(Match(kOriginDevTools, kProtected, mock_policy.get()));
EXPECT_FALSE(Match(kOriginProtected, kExtension, mock_policy.get()));
EXPECT_FALSE(Match(kOriginUnprotected, kExtension, mock_policy.get()));
EXPECT_TRUE(Match(kOriginExtension, kExtension, mock_policy.get()));
EXPECT_FALSE(Match(kOriginDevTools, kExtension, mock_policy.get()));
EXPECT_TRUE(
Match(kOriginProtected, kUnprotected | kProtected, mock_policy.get()));
EXPECT_TRUE(
Match(kOriginUnprotected, kUnprotected | kProtected, mock_policy.get()));
EXPECT_FALSE(
Match(kOriginExtension, kUnprotected | kProtected, mock_policy.get()));
EXPECT_FALSE(
Match(kOriginDevTools, kUnprotected | kProtected, mock_policy.get()));
EXPECT_FALSE(
Match(kOriginProtected, kUnprotected | kExtension, mock_policy.get()));
EXPECT_TRUE(
Match(kOriginUnprotected, kUnprotected | kExtension, mock_policy.get()));
EXPECT_TRUE(
Match(kOriginExtension, kUnprotected | kExtension, mock_policy.get()));
EXPECT_FALSE(
Match(kOriginDevTools, kUnprotected | kExtension, mock_policy.get()));
EXPECT_TRUE(
Match(kOriginProtected, kProtected | kExtension, mock_policy.get()));
EXPECT_FALSE(
Match(kOriginUnprotected, kProtected | kExtension, mock_policy.get()));
EXPECT_TRUE(
Match(kOriginExtension, kProtected | kExtension, mock_policy.get()));
EXPECT_FALSE(
Match(kOriginDevTools, kProtected | kExtension, mock_policy.get()));
EXPECT_TRUE(Match(kOriginProtected, kUnprotected | kProtected | kExtension,
mock_policy.get()));
EXPECT_TRUE(Match(kOriginUnprotected, kUnprotected | kProtected | kExtension,
mock_policy.get()));
EXPECT_TRUE(Match(kOriginExtension, kUnprotected | kProtected | kExtension,
mock_policy.get()));
EXPECT_FALSE(Match(kOriginDevTools, kUnprotected | kProtected | kExtension,
mock_policy.get()));
}
#endif
// If extensions are disabled, there is no policy.
TEST_F(ChromeBrowsingDataRemoverDelegateTest, OriginTypeMasksNoPolicy) {
const GURL kOriginStandard("http://test.com");
const GURL kOriginExtension("chrome-extension://abcdefghijklmnopqrstuvwxyz");
const GURL kOriginDevTools("devtools://abcdefghijklmnopqrstuvw");
EXPECT_TRUE(Match(kOriginStandard, kUnprotected, nullptr));
EXPECT_FALSE(Match(kOriginExtension, kUnprotected, nullptr));
EXPECT_FALSE(Match(kOriginDevTools, kUnprotected, nullptr));
EXPECT_FALSE(Match(kOriginStandard, kProtected, nullptr));
EXPECT_FALSE(Match(kOriginExtension, kProtected, nullptr));
EXPECT_FALSE(Match(kOriginDevTools, kProtected, nullptr));
#if BUILDFLAG(ENABLE_EXTENSIONS_CORE)
EXPECT_FALSE(Match(kOriginStandard, kExtension, nullptr));
EXPECT_TRUE(Match(kOriginExtension, kExtension, nullptr));
EXPECT_FALSE(Match(kOriginDevTools, kExtension, nullptr));
#endif
}
#if BUILDFLAG(ENABLE_REPORTING)
TEST_F(ChromeBrowsingDataRemoverDelegateTest, ReportingCache_NoService) {
BlockUntilBrowsingDataRemoved(base::Time(), base::Time::Max(),
constants::DATA_TYPE_HISTORY, true);
// Nothing to check, since there's no mock service; we're just making sure
// nothing crashes without a service.
}
TEST_F(ChromeBrowsingDataRemoverDelegateWithReportingServiceTest,
ReportingCache) {
BlockUntilBrowsingDataRemoved(base::Time(), base::Time::Max(),
constants::DATA_TYPE_HISTORY, true);
EXPECT_EQ(0, GetMockReportingService().remove_calls());
EXPECT_EQ(1, GetMockReportingService().remove_all_calls());
EXPECT_EQ(net::ReportingBrowsingDataRemover::DATA_TYPE_REPORTS,
GetMockReportingService().last_data_type_mask());
EXPECT_TRUE(
ProbablySameFilters(base::RepeatingCallback<bool(const GURL&)>(),
CreateUrlFilterFromOriginFilter(
GetMockReportingService().last_origin_filter())));
}
// TODO(crbug.com/40458377): Disabled, since history is not yet marked as
// a filterable datatype.
TEST_F(ChromeBrowsingDataRemoverDelegateWithReportingServiceTest,
DISABLED_ReportingCache_WithFilter) {
std::unique_ptr<BrowsingDataFilterBuilder> builder(
BrowsingDataFilterBuilder::Create(
BrowsingDataFilterBuilder::Mode::kDelete));
builder->AddRegisterableDomain(kTestRegisterableDomain1);
BlockUntilOriginDataRemoved(base::Time(), base::Time::Max(),
constants::DATA_TYPE_HISTORY, builder->Copy());
EXPECT_EQ(1, GetMockReportingService().remove_calls());
EXPECT_EQ(0, GetMockReportingService().remove_all_calls());
EXPECT_EQ(net::ReportingBrowsingDataRemover::DATA_TYPE_REPORTS,
GetMockReportingService().last_data_type_mask());
EXPECT_TRUE(
ProbablySameFilters(builder->BuildUrlFilter(),
CreateUrlFilterFromOriginFilter(
GetMockReportingService().last_origin_filter())));
}
TEST_F(ChromeBrowsingDataRemoverDelegateTest, NetworkErrorLogging_NoDelegate) {
BlockUntilBrowsingDataRemoved(base::Time(), base::Time::Max(),
constants::DATA_TYPE_HISTORY, true);
// Nothing to check, since there's no mock service; we're just making sure
// nothing crashes without a service.
}
// This would use an origin filter, but history isn't yet filterable.
TEST_F(ChromeBrowsingDataRemoverDelegateWithNELServiceTest,
NetworkErrorLogging_History) {
BlockUntilBrowsingDataRemoved(base::Time(), base::Time::Max(),
constants::DATA_TYPE_HISTORY, true);
EXPECT_EQ(0, GetMockNetworkErrorLoggingService().remove_calls());
EXPECT_EQ(1, GetMockNetworkErrorLoggingService().remove_all_calls());
EXPECT_TRUE(ProbablySameFilters(
base::RepeatingCallback<bool(const GURL&)>(),
CreateUrlFilterFromOriginFilter(
GetMockNetworkErrorLoggingService().last_origin_filter())));
}
#endif // BUILDFLAG(ENABLE_REPORTING)
// Test that all WebsiteSettings are getting deleted by creating a
// value for each of them and removing data.
TEST_F(ChromeBrowsingDataRemoverDelegateTest, AllTypesAreGettingDeleted) {
TestingProfile* profile = GetProfile();
ASSERT_TRUE(SubresourceFilterProfileContextFactory::GetForProfile(profile));
auto* map = HostContentSettingsMapFactory::GetForProfile(profile);
auto* registry = content_settings::WebsiteSettingsRegistry::GetInstance();
auto* content_setting_registry =
content_settings::ContentSettingsRegistry::GetInstance();
auto* history_service =
HistoryServiceFactory::GetForProfileWithoutCreating(profile);
// Create a safe_browsing::VerdictCacheManager that will handle deletion of
// ContentSettingsType::PASSWORD_PROTECTION entries.
safe_browsing::VerdictCacheManager sb_cache_manager(
history_service, map, profile->GetPrefs(), /*sync_observer=*/nullptr);
GURL url("https://example.com");
// List of types that don't have to be deletable.
static const ContentSettingsType non_deletable_types[] = {
// Doesn't allow any values.
ContentSettingsType::PROTOCOL_HANDLERS,
// Doesn't allow any values.
ContentSettingsType::MIXEDSCRIPT,
// Only policy provider sets exceptions for this type.
ContentSettingsType::AUTO_SELECT_CERTIFICATE,
// TODO(crbug.com/41312665): Make sure that these get fixed:
// Not deleted but should be deleted with history?
ContentSettingsType::IMPORTANT_SITE_INFO,
};
// Set a value for every WebsiteSetting.
for (const content_settings::WebsiteSettingsInfo* info : *registry) {
if (base::Contains(non_deletable_types, info->type())) {
continue;
}
base::Value some_value;
auto* content_setting = content_setting_registry->Get(info->type());
if (content_setting) {
// Content Settings only allow integers.
if (content_setting->IsSettingValid(CONTENT_SETTING_ALLOW)) {
some_value = base::Value(CONTENT_SETTING_ALLOW);
} else {
ASSERT_TRUE(content_setting->IsSettingValid(CONTENT_SETTING_ASK));
some_value = base::Value(CONTENT_SETTING_ASK);
}
ASSERT_TRUE(content_setting->IsDefaultSettingValid(CONTENT_SETTING_BLOCK))
<< info->name();
// Set default to BLOCK to be able to differentiate an exception from the
// default.
map->SetDefaultContentSetting(info->type(), CONTENT_SETTING_BLOCK);
} else {
// Other website settings only allow dictionaries.
base::Value::Dict dict;
dict.Set("foo", 42);
some_value = base::Value(std::move(dict));
}
// Create an exception.
map->SetWebsiteSettingDefaultScope(url, url, info->type(),
some_value.Clone());
// Check that the exception was created.
base::Value value = map->GetWebsiteSetting(url, url, info->type());
EXPECT_FALSE(value.is_none()) << "Not created: " << info->name();
EXPECT_EQ(some_value, value) << "Not created: " << info->name();
}
// Delete all data types that trigger website setting deletions.
uint64_t mask = constants::DATA_TYPE_HISTORY |
constants::DATA_TYPE_SITE_DATA |
constants::DATA_TYPE_CONTENT_SETTINGS;
BlockUntilBrowsingDataRemoved(base::Time(), base::Time::Max(), mask, false);
// All settings should be deleted now.
for (const content_settings::WebsiteSettingsInfo* info : *registry) {
if (base::Contains(non_deletable_types, info->type())) {
continue;
}
base::Value value = map->GetWebsiteSetting(url, url, info->type());
if (value.is_int()) {
EXPECT_EQ(CONTENT_SETTING_BLOCK, value.GetInt())
<< "Not deleted: " << info->name() << " value: " << value;
} else {
EXPECT_TRUE(value.is_none())
<< "Not deleted: " << info->name() << " value: " << value;
}
}
}
#if BUILDFLAG(IS_ANDROID)
TEST_F(ChromeBrowsingDataRemoverDelegateTest, WipeOriginVerifierData) {
int before = customtabs::ChromeOriginVerifier::
GetClearBrowsingDataCallCountForTesting();
BlockUntilBrowsingDataRemoved(base::Time(), base::Time::Max(),
constants::DATA_TYPE_HISTORY, false);
EXPECT_EQ(before + 1, customtabs::ChromeOriginVerifier::
GetClearBrowsingDataCallCountForTesting());
}
#endif // BUILDFLAG(IS_ANDROID)
#if BUILDFLAG(IS_CHROMEOS)
TEST_F(ChromeBrowsingDataRemoverDelegateTest, WipeCrashData) {
base::ScopedPathOverride override_crash_dumps(chrome::DIR_CRASH_DUMPS);
base::FilePath crash_dir_path;
base::PathService::Get(chrome::DIR_CRASH_DUMPS, &crash_dir_path);
base::FilePath upload_log_path =
crash_dir_path.AppendASCII(CrashUploadList::kReporterLogFilename);
constexpr char kCrashEntry1[] = "12345,abc\n";
constexpr char kCrashEntry2[] = "67890,def\n";
std::string initial_contents = kCrashEntry1;
initial_contents.append(kCrashEntry2);
ASSERT_TRUE(base::WriteFile(upload_log_path, initial_contents));
BlockUntilBrowsingDataRemoved(base::Time::FromTimeT(67890u),
base::Time::Max(), constants::DATA_TYPE_HISTORY,
false);
std::string contents;
base::ReadFileToString(upload_log_path, &contents);
EXPECT_EQ(kCrashEntry1, contents);
BlockUntilBrowsingDataRemoved(base::Time(), base::Time::Max(),
constants::DATA_TYPE_HISTORY, false);
EXPECT_FALSE(base::PathExists(upload_log_path));
}
#endif
TEST_F(ChromeBrowsingDataRemoverDelegateTest, WipeCustomDictionaryData) {
base::FilePath dict_path =
GetProfile()->GetPath().Append(chrome::kCustomDictionaryFileName);
base::FilePath backup_path = dict_path.AddExtensionASCII("backup");
auto* spellcheck = SpellcheckServiceFactory::GetForContext(GetProfile());
ASSERT_NE(nullptr, spellcheck);
auto* dict = spellcheck->GetCustomDictionary();
ASSERT_NE(nullptr, dict);
auto change1 = std::make_unique<SpellcheckCustomDictionary::Change>();
change1->AddWord("wug");
dict->UpdateDictionaryFile(std::move(change1), dict_path);
auto change2 = std::make_unique<SpellcheckCustomDictionary::Change>();
change2->AddWord("spowing");
dict->UpdateDictionaryFile(std::move(change2), dict_path);
EXPECT_TRUE(base::PathExists(dict_path));
EXPECT_TRUE(base::PathExists(backup_path));
BlockUntilBrowsingDataRemoved(base::Time(), base::Time::Max(),
constants::DATA_TYPE_LOCAL_CUSTOM_DICTIONARY,
false);
std::string contents;
base::ReadFileToString(dict_path, &contents);
EXPECT_EQ(std::string::npos, contents.find("wug"));
EXPECT_EQ(std::string::npos, contents.find("spowing"));
EXPECT_FALSE(base::PathExists(backup_path));
}
TEST_F(ChromeBrowsingDataRemoverDelegateTest,
WipeNotificationPermissionPromptOutcomesData) {
PrefService* prefs = GetProfile()->GetPrefs();
base::Time first_recorded_time = base::Time::Now();
auto* action_history =
PermissionActionsHistoryFactory::GetForProfile(GetProfile());
action_history->RecordAction(
permissions::PermissionAction::DENIED,
permissions::RequestType::kNotifications,
permissions::PermissionPromptDisposition::ANCHORED_BUBBLE);
task_environment()->AdvanceClock(base::Days(1));
action_history->RecordAction(
permissions::PermissionAction::DENIED,
permissions::RequestType::kNotifications,
permissions::PermissionPromptDisposition::ANCHORED_BUBBLE);
task_environment()->AdvanceClock(base::Days(1));
base::Time third_recorded_time = base::Time::Now();
action_history->RecordAction(
permissions::PermissionAction::DENIED,
permissions::RequestType::kNotifications,
permissions::PermissionPromptDisposition::LOCATION_BAR_LEFT_QUIET_CHIP);
constexpr char kPermissionActionsPrefPath[] =
"profile.content_settings.permission_actions";
EXPECT_EQ(3u, prefs->GetDict(kPermissionActionsPrefPath)
.FindList("notifications")
->size());
auto filter_builder = BrowsingDataFilterBuilder::Create(
BrowsingDataFilterBuilder::Mode::kDelete);
filter_builder->AddRegisterableDomain("example.com");
BlockUntilOriginDataRemoved(first_recorded_time, third_recorded_time,
constants::DATA_TYPE_SITE_USAGE_DATA,
std::move(filter_builder));
// This data type doesn't implement per-origin deletion so just test that
// nothing got removed.
EXPECT_EQ(3u, prefs->GetDict(kPermissionActionsPrefPath)
.FindList("notifications")
->size());
// Remove the first and the second element.
BlockUntilBrowsingDataRemoved(first_recorded_time, third_recorded_time,
constants::DATA_TYPE_SITE_USAGE_DATA, false);
// There is only one element left.
EXPECT_EQ(1u, prefs->GetDict(kPermissionActionsPrefPath)
.FindList("notifications")
->size());
EXPECT_EQ((base::ValueToTime(prefs->GetDict(kPermissionActionsPrefPath)
.FindList("notifications")
->front()
.GetDict()
.Find("time")))
.value_or(base::Time()),
third_recorded_time);
// Test we wiped all the elements left.
BlockUntilBrowsingDataRemoved(base::Time(), base::Time::Max(),
constants::DATA_TYPE_SITE_USAGE_DATA, false);
EXPECT_TRUE(prefs->GetDict(kPermissionActionsPrefPath).empty());
}
TEST_F(ChromeBrowsingDataRemoverDelegateTest, WipeSuspiciousNotificationIds) {
// Add setting value.
const GURL kOrigin1("http://host1.com:1");
base::Value::List suspicious_notification_ids;
suspicious_notification_ids.Append("1");
suspicious_notification_ids.Append("2");
base::Value::Dict suspicious_notification_id_dict;
suspicious_notification_id_dict.Set("suspicious-notification-ids",
std::move(suspicious_notification_ids));
HostContentSettingsMap* host_content_settings_map =
HostContentSettingsMapFactory::GetForProfile(GetProfile());
host_content_settings_map->SetWebsiteSettingDefaultScope(
kOrigin1, GURL(), ContentSettingsType::SUSPICIOUS_NOTIFICATION_IDS,
base::Value(suspicious_notification_id_dict.Clone()));
ContentSettingsForOneType host_settings =
host_content_settings_map->GetSettingsForOneType(
ContentSettingsType::SUSPICIOUS_NOTIFICATION_IDS);
ASSERT_EQ(1u, host_settings.size());
// Wipe the setting.
BlockUntilBrowsingDataRemoved(base::Time::Now(), base::Time::Max(),
constants::DATA_TYPE_HISTORY, false);
host_settings = host_content_settings_map->GetSettingsForOneType(
ContentSettingsType::SUSPICIOUS_NOTIFICATION_IDS);
ASSERT_EQ(0u, host_settings.size());
}
// Tests with non-null AccountPasswordStoreFactory::GetForProfile().
class ChromeBrowsingDataRemoverDelegateWithAccountPasswordsTest
: public ChromeBrowsingDataRemoverDelegateWithPasswordsTest {
public:
ChromeBrowsingDataRemoverDelegateWithAccountPasswordsTest() {
#if BUILDFLAG(IS_ANDROID)
// Override the GMS version to be big enough for local UPM support, so these
// tests still pass in bots with an outdated version.
base::android::BuildInfo::GetInstance()->set_gms_version_code_for_test(
base::NumberToString(password_manager::GetLocalUpmMinGmsVersion()));
#endif
}
void EnableAccountStorage() {
sync_service()->SetSignedIn(
#if BUILDFLAG(IS_ANDROID)
signin::ConsentLevel::kSync
#else
signin::ConsentLevel::kSignin
#endif
);
ASSERT_TRUE(password_manager::features_util::IsAccountStorageEnabled(
GetProfile()->GetPrefs(), sync_service()));
}
};
// Regression test for crbug.com/325323180. Wiping cookies updates password
// entries (it sets the auto-signin bit). This test verifies that when wiping
// both passwords and cookies, the updates happen *after* deletions are done, to
// avoid resurrecting passwords.
TEST_F(ChromeBrowsingDataRemoverDelegateWithAccountPasswordsTest,
DisableAutoSignInAfterRemovingPasswords) {
// Set up the necessary futures for account and profile PasswordStores, so the
// the test can wait for them later.
EnableAccountStorage();
TestFuture<base::OnceClosure> profile_auto_signin_cb, account_auto_signin_cb;
TestFuture<base::OnceCallback<void(bool)>> account_remove_cb;
TestFuture<base::OnceCallback<void(bool)>> account_sync_cb;
TestFuture<base::OnceCallback<void(bool)>> profile_remove_cb;
ON_CALL(*profile_password_store(), DisableAutoSignInForOrigins)
.WillByDefault(MoveArgToFuture<1>(&profile_auto_signin_cb));
ON_CALL(*account_password_store(), DisableAutoSignInForOrigins)
.WillByDefault(MoveArgToFuture<1>(&account_auto_signin_cb));
ON_CALL(*profile_password_store(), RemoveLoginsCreatedBetween)
.WillByDefault(MoveArgToFuture<3>(&profile_remove_cb));
ON_CALL(*account_password_store(), RemoveLoginsCreatedBetween)
.WillByDefault(WithArgs<3, 4>([&](auto remove_cb, auto sync_cb) {
account_remove_cb.SetValue(std::move(remove_cb));
account_sync_cb.SetValue(std::move(sync_cb));
}));
// Kick off.
content::BrowsingDataRemoverCompletionObserver completion_observer(remover());
remover()->RemoveAndReply(
base::Time(), base::Time::Max(),
content::BrowsingDataRemover::DATA_TYPE_COOKIES |
chrome_browsing_data_remover::DATA_TYPE_PASSWORDS |
chrome_browsing_data_remover::DATA_TYPE_ACCOUNT_PASSWORDS,
content::BrowsingDataRemover::ORIGIN_TYPE_UNPROTECTED_WEB,
&completion_observer);
// Password removal should be triggered, but not auto-signin disabling nor the
// completion signal.
ASSERT_TRUE(profile_remove_cb.Wait());
ASSERT_TRUE(account_remove_cb.Wait());
#if !BUILDFLAG(IS_ANDROID)
ASSERT_TRUE(account_sync_cb.Wait());
#endif
ASSERT_FALSE(profile_auto_signin_cb.IsReady());
ASSERT_FALSE(account_auto_signin_cb.IsReady());
ASSERT_FALSE(completion_observer.browsing_data_remover_done());
// Report password removal as finished, by invoking the callbacks. Note:
// `account_sync_cb` is null on Android.
profile_remove_cb.Take().Run(true);
account_remove_cb.Take().Run(true);
#if !BUILDFLAG(IS_ANDROID)
account_sync_cb.Take().Run(true);
#endif
// Auto-signin disabling should be triggered, but not the completion signal.
ASSERT_TRUE(profile_auto_signin_cb.Wait());
ASSERT_TRUE(account_auto_signin_cb.Wait());
ASSERT_FALSE(completion_observer.browsing_data_remover_done());
// Report auto-signin disabling as finished, by invoking the callbacks.
profile_auto_signin_cb.Take().Run();
account_auto_signin_cb.Take().Run();
// The completion signal should be triggered.
completion_observer.BlockUntilCompletion();
}
TEST_F(ChromeBrowsingDataRemoverDelegateWithAccountPasswordsTest,
RemovePasswordsByTimeOnly_WithAccountStore) {
ExpectRemoveLoginsCreatedBetween(profile_password_store());
// Only DATA_TYPE_PASSWORDS is cleared. Accounts passwords are not affected.
EXPECT_CALL(*account_password_store(), RemoveLoginsCreatedBetween).Times(0);
BlockUntilBrowsingDataRemoved(base::Time(), base::Time::Max(),
constants::DATA_TYPE_PASSWORDS, false);
}
TEST_F(ChromeBrowsingDataRemoverDelegateWithAccountPasswordsTest,
RemoveAccountPasswordsByTimeSyncFailed_CallbacksFailedDataTypes) {
ExpectRemoveLoginsCreatedBetween(account_password_store());
// Only DATA_TYPE_ACCOUNT_PASSWORDS is cleared. Profile passwords are not
// affected.
EXPECT_CALL(*profile_password_store(), RemoveLoginsCreatedBetween).Times(0);
uint64_t failed_data_types = BlockUntilBrowsingDataRemoved(
base::Time(), base::Time::Max(), constants::DATA_TYPE_ACCOUNT_PASSWORDS,
false);
// Desktop waits for DATA_TYPE_ACCOUNT_PASSWORDS deletions to be uploaded to
// the sync server before deleting any other types (because deleting
// DATA_TYPE_COOKIES first would revoke the account storage opt-in and prevent
// the upload). In this test, deletions are never uploaded, so sync callback
// on DATA_TYPE_ACCOUNT_PASSWORDS is reported as failed.
// On Android, the account storage doesn't depend on cookies, so there's no
// waiting logic on sync callback, the removal reported as successful.
EXPECT_EQ(failed_data_types,
#if BUILDFLAG(IS_ANDROID)
0u
#else
constants::DATA_TYPE_ACCOUNT_PASSWORDS
#endif
);
}
TEST_F(ChromeBrowsingDataRemoverDelegateWithAccountPasswordsTest,
RemovingAccountStorePasswordsTrackedInAPref) {
ExpectRemoveLoginsCreatedBetween(account_password_store());
BlockUntilBrowsingDataRemoved(base::Time(), base::Time::Max(),
constants::DATA_TYPE_ACCOUNT_PASSWORDS, false);
// Verify that password removal reason was tracked.
EXPECT_EQ(
GetProfile()->GetPrefs()->GetInteger(
password_manager::prefs::kPasswordRemovalReasonForAccount),
1 << static_cast<int>(
password_manager::metrics_util::
PasswordManagerCredentialRemovalReason::kClearBrowsingData));
EXPECT_EQ(GetProfile()->GetPrefs()->GetInteger(
password_manager::prefs::kPasswordRemovalReasonForProfile),
0);
}
TEST_F(ChromeBrowsingDataRemoverDelegateWithAccountPasswordsTest,
CheckFailWhenRemovePasswordsByOrigin) {
std::unique_ptr<BrowsingDataFilterBuilder> builder(
BrowsingDataFilterBuilder::Create(
BrowsingDataFilterBuilder::Mode::kDelete));
builder->AddRegisterableDomain(kTestRegisterableDomain1);
EXPECT_CHECK_DEATH_WITH(
BlockUntilOriginDataRemoved(base::Time(), base::Time::Max(),
constants::DATA_TYPE_ACCOUNT_PASSWORDS,
std::move(builder)),
"");
}
TEST_F(ChromeBrowsingDataRemoverDelegateTest,
GetDomainsForDeferredCookieDeletion) {
auto* storage_partition = GetProfile()->GetDefaultStoragePartition();
auto* delegate = GetProfile()->GetBrowsingDataRemoverDelegate();
auto domains = delegate->GetDomainsForDeferredCookieDeletion(
storage_partition, constants::DATA_TYPE_ACCOUNT_PASSWORDS);
#if BUILDFLAG(IS_ANDROID)
EXPECT_THAT(domains, IsEmpty());
#else
EXPECT_THAT(domains, UnorderedElementsAre("google.com"));
#endif
domains = delegate->GetDomainsForDeferredCookieDeletion(
storage_partition, constants::DATA_TYPE_PASSWORDS);
EXPECT_THAT(domains, IsEmpty());
domains = delegate->GetDomainsForDeferredCookieDeletion(
storage_partition, constants::ALL_DATA_TYPES);
EXPECT_THAT(domains, IsEmpty());
content::StoragePartition* non_default_storage_partition =
GetProfile()->GetStoragePartition(content::StoragePartitionConfig::Create(
GetProfile(), "domain", /*partition_name=*/"", /*in_memory=*/false));
domains = delegate->GetDomainsForDeferredCookieDeletion(
non_default_storage_partition, constants::DATA_TYPE_ACCOUNT_PASSWORDS);
EXPECT_THAT(domains, IsEmpty());
}
class
ChromeBrowsingDataRemoverDelegateTest_RemoveSecurePaymentConfirmationCredentials
: public ChromeBrowsingDataRemoverDelegateTest {
public:
using MockWrapper = testing::NiceMock<payments::MockWebDataServiceWrapper>;
using MockService =
testing::NiceMock<payments::MockPaymentManifestWebDataService>;
TestingProfile::TestingFactories GetTestingFactories() override {
TestingProfile::TestingFactories factories =
ChromeBrowsingDataRemoverDelegateTest::GetTestingFactories();
factories.emplace_back(
webdata_services::WebDataServiceWrapperFactory::GetInstance(),
base::BindLambdaForTesting([&](content::BrowserContext* context)
-> std::unique_ptr<KeyedService> {
auto wrapper = std::make_unique<MockWrapper>();
ON_CALL(*wrapper, GetPaymentManifestWebData)
.WillByDefault(Return(service_));
return std::move(wrapper);
}));
return factories;
}
void ExpectCallClearSecurePaymentConfirmationCredentials(int times) {
EXPECT_CALL(*service_.get(), ClearSecurePaymentConfirmationCredentials)
.Times(times)
.WillRepeatedly(testing::WithArg<2>([](base::OnceClosure completion) {
base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
FROM_HERE, std::move(completion));
}));
}
void ExpectNoCallsToClearSecurePaymentConfirmationCredentials() {
EXPECT_CALL(*service_.get(), ClearSecurePaymentConfirmationCredentials)
.Times(0);
}
private:
scoped_refptr<MockService> service_ = base::MakeRefCounted<MockService>();
};
// Verify that clearing secure payment confirmation credentials data works when
// deleting passwords.
TEST_F(
ChromeBrowsingDataRemoverDelegateTest_RemoveSecurePaymentConfirmationCredentials,
RemoveSecurePaymentConfirmationCredentials_DeletePasswords) {
ExpectCallClearSecurePaymentConfirmationCredentials(1);
BlockUntilBrowsingDataRemoved(AnHourAgo(), base::Time::Max(),
constants::DATA_TYPE_PASSWORDS, false);
}
#if !BUILDFLAG(IS_ANDROID)
// Verify that clearing secure payment confirmation credentials data works when
// deleting forms data.
TEST_F(
ChromeBrowsingDataRemoverDelegateTest_RemoveSecurePaymentConfirmationCredentials,
RemoveSecurePaymentConfirmationCredentials_DeleteFormData_DbdRevampEnabled) {
base::test::ScopedFeatureList feature(
browsing_data::features::kDbdRevampDesktop);
ExpectCallClearSecurePaymentConfirmationCredentials(1);
BlockUntilBrowsingDataRemoved(AnHourAgo(), base::Time::Max(),
constants::DATA_TYPE_FORM_DATA, false);
}
// Verify that secure payment confirmation credentials data are not deleted when
// deleting forms data when kDbdRevampDesktop is disabled.
// TODO(crbug.com/397187800): Remove once kDbdRevampDesktop is launched.
TEST_F(
ChromeBrowsingDataRemoverDelegateTest_RemoveSecurePaymentConfirmationCredentials,
SecurePaymentConfirmationCredentialsNotRemoved_DeleteFormData_DbdRevampDisabled) {
base::test::ScopedFeatureList scoped_feature_list;
scoped_feature_list.InitAndDisableFeature(
browsing_data::features::kDbdRevampDesktop);
ExpectNoCallsToClearSecurePaymentConfirmationCredentials();
BlockUntilBrowsingDataRemoved(AnHourAgo(), base::Time::Max(),
constants::DATA_TYPE_FORM_DATA, false);
}
#else // !BUILDFLAG(IS_ANDROID)
// Verify that secure payment confirmation credentials data are not deleted when
// deleting forms data on Android.
TEST_F(
ChromeBrowsingDataRemoverDelegateTest_RemoveSecurePaymentConfirmationCredentials,
SecurePaymentConfirmationCredentialsNotRemoved_DeleteFormData_Android) {
ExpectNoCallsToClearSecurePaymentConfirmationCredentials();
BlockUntilBrowsingDataRemoved(AnHourAgo(), base::Time::Max(),
constants::DATA_TYPE_FORM_DATA, false);
}
#endif // !BUILDFLAG(IS_ANDROID)
// Verify that clearing cookies will also clear page load tokens.
TEST_F(ChromeBrowsingDataRemoverDelegateTest,
PageLoadTokenClearedOnCookieDeleted) {
GURL url("https://www.example.com/path");
safe_browsing::VerdictCacheManager* sb_cache_manager =
safe_browsing::VerdictCacheManagerFactory::GetForProfile(GetProfile());
sb_cache_manager->CreatePageLoadToken(url);
safe_browsing::ChromeUserPopulation::PageLoadToken token =
sb_cache_manager->GetPageLoadToken(url);
ASSERT_TRUE(token.has_token_value());
BlockUntilBrowsingDataRemoved(base::Time(), base::Time::Max(),
content::BrowsingDataRemover::DATA_TYPE_COOKIES,
false);
token = sb_cache_manager->GetPageLoadToken(url);
// Token is not found because cookies are deleted.
ASSERT_FALSE(token.has_token_value());
}
#if !BUILDFLAG(IS_ANDROID)
TEST_F(ChromeBrowsingDataRemoverDelegateTest,
RevokeActiveFileSystemPermission) {
ChromeFileSystemAccessPermissionContext* context =
FileSystemAccessPermissionContextFactory::GetForProfile(GetProfile());
auto kTestOrigin1 = url::Origin::Create(GURL("https://a.com"));
auto kTestOrigin2 = url::Origin::Create(GURL("https://b.com"));
const content::PathInfo kTestPath1(FILE_PATH_LITERAL("/a/b"));
const content::PathInfo kTestPath2(FILE_PATH_LITERAL("/a/c"));
// Populate the `grants` object with permissions.
auto origin1_file_read_grant =
context->GetExtendedReadPermissionGrantForTesting(
kTestOrigin1, kTestPath1,
ChromeFileSystemAccessPermissionContext::HandleType::kFile);
auto origin2_file_read_grant =
context->GetExtendedReadPermissionGrantForTesting(
kTestOrigin2, kTestPath2,
ChromeFileSystemAccessPermissionContext::HandleType::kFile);
EXPECT_EQ(
origin1_file_read_grant->GetStatus(),
content::FileSystemAccessPermissionGrant::PermissionStatus::GRANTED);
EXPECT_EQ(
origin2_file_read_grant->GetStatus(),
content::FileSystemAccessPermissionGrant::PermissionStatus::GRANTED);
BlockUntilBrowsingDataRemoved(base::Time(), base::Time::Max(),
constants::DATA_TYPE_CONTENT_SETTINGS, false);
EXPECT_EQ(origin1_file_read_grant->GetStatus(),
content::FileSystemAccessPermissionGrant::PermissionStatus::ASK);
EXPECT_EQ(origin2_file_read_grant->GetStatus(),
content::FileSystemAccessPermissionGrant::PermissionStatus::ASK);
}
#endif // !BUILDFLAG(IS_ANDROID)
// When most cookies are cleared, PrivacySandboxSettings should call the
// OnTopicsDataAccessibleSinceUpdated() method of its observers.
TEST_F(ChromeBrowsingDataRemoverDelegateTest,
Call_OnTopicsDataAccessibleSinceUpdated_WhenClearingMostCookies) {
privacy_sandbox::PrivacySandboxSettings* settings =
PrivacySandboxSettingsFactory::GetForProfile(GetProfile());
privacy_sandbox_test_util::MockPrivacySandboxObserver observer;
base::ScopedObservation<privacy_sandbox::PrivacySandboxSettings,
privacy_sandbox::PrivacySandboxSettings::Observer>
obs(&observer);
obs.Observe(settings);
EXPECT_CALL(observer, OnTopicsDataAccessibleSinceUpdated()).Times(1);
std::unique_ptr<BrowsingDataFilterBuilder> filter_builder =
BrowsingDataFilterBuilder::Create(
BrowsingDataFilterBuilder::Mode::kPreserve);
filter_builder->AddRegisterableDomain("example.test");
ASSERT_TRUE(filter_builder->MatchesMostOriginsAndDomains());
BlockUntilOriginDataRemoved(base::Time::Min(), base::Time::Max(),
content::BrowsingDataRemover::DATA_TYPE_COOKIES,
std::move(filter_builder));
}
// If only some cookies are cleared, PrivacySandboxSettings should NOT call the
// OnTopicsDataAccessibleSinceUpdated() method of its observers.
TEST_F(
ChromeBrowsingDataRemoverDelegateTest,
DontCall_OnTopicsDataAccessibleSinceUpdated_WhenOnlyClearingPartitionedCookies) {
privacy_sandbox::PrivacySandboxSettings* settings =
PrivacySandboxSettingsFactory::GetForProfile(GetProfile());
privacy_sandbox_test_util::MockPrivacySandboxObserver observer;
base::ScopedObservation<privacy_sandbox::PrivacySandboxSettings,
privacy_sandbox::PrivacySandboxSettings::Observer>
obs(&observer);
obs.Observe(settings);
EXPECT_CALL(observer, OnTopicsDataAccessibleSinceUpdated()).Times(0);
// Create a filter builder that deletes only partitioned cookies.
std::unique_ptr<BrowsingDataFilterBuilder> filter_builder =
BrowsingDataFilterBuilder::Create(
BrowsingDataFilterBuilder::Mode::kPreserve);
filter_builder->SetPartitionedCookiesOnly(true);
ASSERT_FALSE(filter_builder->MatchesMostOriginsAndDomains());
BlockUntilOriginDataRemoved(base::Time::Min(), base::Time::Max(),
content::BrowsingDataRemover::DATA_TYPE_COOKIES,
std::move(filter_builder));
}
#if !BUILDFLAG(IS_ANDROID)
// Ensures New Tab page local storage is clear when Microsoft auth service
// exists.
TEST_F(ChromeBrowsingDataRemoverDelegateTest, ClearNewTabPageLocalStorage) {
// Setup features that allows auth service to be created.
base::test::ScopedFeatureList features;
GetProfile()->GetTestingPrefService()->SetManagedPref(
prefs::kNtpSharepointModuleVisible, base::Value(true));
features.InitWithFeatures(
/*enabled_features=*/{ntp_features::kNtpMicrosoftAuthenticationModule,
ntp_features::kNtpSharepointModule},
/*disabled_features=*/{});
// Set auth service access token.
new_tab_page::mojom::AccessTokenPtr access_token =
new_tab_page::mojom::AccessToken::New();
access_token->token = "1234";
access_token->expiration = base::Time::Now() + base::Minutes(20);
auto* auth_service = MicrosoftAuthServiceFactory::GetForProfile(GetProfile());
ASSERT_TRUE(auth_service);
auth_service->SetAccessToken(std::move(access_token));
// Create local storage with fake data.
auto* local_storage_control =
GetProfile()->GetDefaultStoragePartition()->GetLocalStorageControl();
mojo::Remote<blink::mojom::StorageArea> area;
blink::StorageKey key = blink::StorageKey::CreateFromStringForTesting(
chrome::kChromeUINewTabPageURL);
local_storage_control->BindStorageArea(key,
area.BindNewPipeAndPassReceiver());
base::test::TestFuture<bool> put_future;
area->Put({'k', 'e', 'y'}, {'v', 'a', 'l', 'u', 'e'}, std::nullopt, "source",
put_future.GetCallback());
ASSERT_TRUE(put_future.Get());
// Verify fake data has been persisted into local storage.
base::test::TestFuture<std::vector<storage::mojom::StorageUsageInfoPtr>>
usage_future;
local_storage_control->GetUsage(usage_future.GetCallback());
EXPECT_EQ(usage_future.Get().size(), 1u);
// Clear local storage.
BlockUntilBrowsingDataRemoved(base::Time::Now(), base::Time::Max(),
content::BrowsingDataRemover::DATA_TYPE_COOKIES,
false);
// Verify local storage and auth data has been cleared.
usage_future.Clear();
local_storage_control->GetUsage(usage_future.GetCallback());
EXPECT_EQ(usage_future.Get().size(), 0u);
EXPECT_TRUE(auth_service->GetAccessToken().empty());
}
#endif // !BUILDFLAG(IS_ANDROID)
#if BUILDFLAG(IS_ANDROID)
// Verify that clearing cookies will also trigger removing invalid browser bound
// keys.
TEST_F(ChromeBrowsingDataRemoverDelegateTest,
ClearInvalidBrowserBoundKeysForSecurePaymentConfirmation) {
auto* mock_browser_bound_keys_deleter = static_cast<
payments::MockBrowserBoundKeyDeleter*>(
payments::BrowserBoundKeyDeleterFactory::GetInstance()
->SetTestingFactoryAndUse(
GetProfile(),
base::BindOnce([](content::BrowserContext*)
-> std::unique_ptr<KeyedService> {
return std::make_unique<payments::MockBrowserBoundKeyDeleter>();
})));
EXPECT_CALL(*mock_browser_bound_keys_deleter, RemoveInvalidBBKs());
BlockUntilBrowsingDataRemoved(base::Time(), base::Time::Max(),
content::BrowsingDataRemover::DATA_TYPE_COOKIES,
false);
}
#endif // BUILDFLAG(IS_ANDROID)
class ChromeBrowsingDataRemoverDelegateOriginTrialsTest
: public ChromeBrowsingDataRemoverDelegateTest {
public:
ChromeBrowsingDataRemoverDelegateOriginTrialsTest() = default;
protected:
blink::ScopedTestOriginTrialPolicy origin_trial_policy_;
};
// Test that Persistent Origin Trials are deleted along with other website
// settings.
TEST_F(ChromeBrowsingDataRemoverDelegateOriginTrialsTest,
PersistentOriginTrialsAreDeleted) {
// Generated with:
// tools/origin_trials/generate_token.py https://example.com
// FrobulatePersistent
// --expire-timestamp=2000000000
const char kPersistentOriginTrialToken[] =
"AzZfd1vKZ0SSGRGk/"
"8nIszQSlHYjbuYVE3jwaNZG3X4t11zRhzPWWJwTZ+JJDS3JJsyEZcpz+y20pAP6/"
"6upOQ4AAABdeyJvcmlnaW4iOiAiaHR0cHM6Ly9leGFtcGxlLmNvbTo0NDMiLCAiZmVhdHVyZ"
"SI6ICJGcm9idWxhdGVQZXJzaXN0ZW50IiwgImV4cGlyeSI6IDIwMDAwMDAwMDB9";
base::Time kPersistentOriginTrialValidTime =
base::Time::FromSecondsSinceUnixEpoch(1000000);
url::Origin origin = url::Origin::Create(GURL("https://example.com"));
TestingProfile* profile = GetProfile();
ASSERT_TRUE(SubresourceFilterProfileContextFactory::GetForProfile(profile));
std::vector<std::string> tokens{kPersistentOriginTrialToken};
content::OriginTrialsControllerDelegate* delegate =
profile->GetOriginTrialsControllerDelegate();
delegate->PersistTrialsFromTokens(origin, /*partition_origin=*/origin, tokens,
kPersistentOriginTrialValidTime,
/*source_id=*/std::nullopt);
// Delete all data types that trigger website setting deletions.
uint64_t mask = constants::DATA_TYPE_HISTORY |
constants::DATA_TYPE_SITE_DATA |
constants::DATA_TYPE_CONTENT_SETTINGS;
EXPECT_FALSE(
delegate
->GetPersistedTrialsForOrigin(origin, /*partition_origin=*/origin,
kPersistentOriginTrialValidTime)
.empty());
BlockUntilBrowsingDataRemoved(base::Time(), base::Time::Max(), mask, false);
EXPECT_TRUE(delegate
->GetPersistedTrialsForOrigin(origin,
/*partition_origin=*/origin,
kPersistentOriginTrialValidTime)
.empty());
}
class ChromeBrowsingDataRemoverDelegateMediaDeviceSaltTest
: public ChromeBrowsingDataRemoverDelegateTest {
public:
ChromeBrowsingDataRemoverDelegateMediaDeviceSaltTest() {
feature_list_.InitWithFeatures(
{media_device_salt::kMediaDeviceIdPartitioning}, {});
}
void SetUp() override {
ChromeBrowsingDataRemoverDelegateTest::SetUp();
media_device_salt_service_ =
MediaDeviceSaltServiceFactory::GetInstance()->GetForBrowserContext(
GetProfile());
}
void TearDown() override {
media_device_salt_service_ = nullptr;
ChromeBrowsingDataRemoverDelegateTest::TearDown();
}
protected:
std::string GetSalt(const blink::StorageKey& key) {
base::test::TestFuture<const std::string&> future;
media_device_salt_service_->GetSalt(key, future.GetCallback());
return future.Get();
}
static blink::StorageKey StorageKey1() {
return blink::StorageKey::CreateFromStringForTesting(
"https://example1.com");
}
static blink::StorageKey StorageKey2() {
return blink::StorageKey::CreateFromStringForTesting(
"https://example2.com");
}
static blink::StorageKey StorageKey3() {
return blink::StorageKey::CreateFromStringForTesting(
"https://example3.com");
}
private:
raw_ptr<media_device_salt::MediaDeviceSaltService>
media_device_salt_service_ = nullptr;
};
TEST_F(ChromeBrowsingDataRemoverDelegateMediaDeviceSaltTest, RemoveAllSalts) {
std::string salt1 = GetSalt(StorageKey1());
std::string salt2 = GetSalt(StorageKey2());
std::string salt3 = GetSalt(StorageKey3());
BlockUntilBrowsingDataRemoved(base::Time(), base::Time::Max(),
content::BrowsingDataRemover::DATA_TYPE_COOKIES,
false);
EXPECT_NE(GetSalt(StorageKey1()), salt1);
EXPECT_NE(GetSalt(StorageKey2()), salt2);
EXPECT_NE(GetSalt(StorageKey3()), salt3);
// Salts are different from each other
EXPECT_NE(GetSalt(StorageKey1()), GetSalt(StorageKey2()));
EXPECT_NE(GetSalt(StorageKey2()), GetSalt(StorageKey3()));
EXPECT_NE(GetSalt(StorageKey1()), GetSalt(StorageKey3()));
}
TEST_F(ChromeBrowsingDataRemoverDelegateMediaDeviceSaltTest, PreserveOneSalt) {
std::string salt1 = GetSalt(StorageKey1());
std::string salt2 = GetSalt(StorageKey2());
std::string salt3 = GetSalt(StorageKey3());
std::unique_ptr<BrowsingDataFilterBuilder> filter(
BrowsingDataFilterBuilder::Create(
BrowsingDataFilterBuilder::Mode::kPreserve));
filter->AddRegisterableDomain(StorageKey1().origin().host());
BlockUntilOriginDataRemoved(base::Time(), base::Time::Max(),
content::BrowsingDataRemover::DATA_TYPE_COOKIES,
std::move(filter));
EXPECT_EQ(GetSalt(StorageKey1()), salt1);
EXPECT_NE(GetSalt(StorageKey2()), salt2);
EXPECT_NE(GetSalt(StorageKey3()), salt3);
}
TEST_F(ChromeBrowsingDataRemoverDelegateMediaDeviceSaltTest, RemoveOneSalt) {
std::string salt1 = GetSalt(StorageKey1());
std::string salt2 = GetSalt(StorageKey2());
std::string salt3 = GetSalt(StorageKey3());
std::unique_ptr<BrowsingDataFilterBuilder> filter(
BrowsingDataFilterBuilder::Create(
BrowsingDataFilterBuilder::Mode::kDelete));
filter->AddRegisterableDomain(StorageKey1().origin().host());
BlockUntilOriginDataRemoved(base::Time(), base::Time::Max(),
content::BrowsingDataRemover::DATA_TYPE_COOKIES,
std::move(filter));
EXPECT_NE(GetSalt(StorageKey1()), salt1);
EXPECT_EQ(GetSalt(StorageKey2()), salt2);
EXPECT_EQ(GetSalt(StorageKey3()), salt3);
}
TEST_F(ChromeBrowsingDataRemoverDelegateMediaDeviceSaltTest,
RemoveBasedOnTime) {
base::Time time1 = base::Time::Now();
std::string salt1 = GetSalt(StorageKey1());
task_environment()->FastForwardBy(base::Seconds(1));
std::string salt2 = GetSalt(StorageKey2());
task_environment()->FastForwardBy(base::Seconds(1));
base::Time time3 = base::Time::Now();
std::string salt3 = GetSalt(StorageKey3());
// Remove salt for StorageKey3()
BlockUntilBrowsingDataRemoved(time3, base::Time::Max(),
content::BrowsingDataRemover::DATA_TYPE_COOKIES,
false);
std::string salt1b = GetSalt(StorageKey1());
std::string salt2b = GetSalt(StorageKey2());
std::string salt3b = GetSalt(StorageKey3());
EXPECT_EQ(salt1b, salt1);
EXPECT_EQ(salt2b, salt2);
EXPECT_NE(salt3b, salt3);
// Remove salt for StorageKey1()
BlockUntilBrowsingDataRemoved(base::Time(), time1,
content::BrowsingDataRemover::DATA_TYPE_COOKIES,
false);
std::string salt1c = GetSalt(StorageKey1());
std::string salt2c = GetSalt(StorageKey2());
std::string salt3c = GetSalt(StorageKey3());
EXPECT_NE(salt1c, salt1b);
EXPECT_EQ(salt2c, salt2b);
EXPECT_EQ(salt3c, salt3b);
}
class ChromeBrowsingDataRemoverDelegateTpcdMetadataTest
: public ChromeBrowsingDataRemoverDelegateTest {
public:
ChromeBrowsingDataRemoverDelegateTpcdMetadataTest() {
feature_list_.InitWithFeatures({net::features::kTpcdMetadataStageControl},
{});
}
};
TEST_F(ChromeBrowsingDataRemoverDelegateTpcdMetadataTest, ResetAllCohorts) {
auto tester = RemoveTpcdMetadataCohortsTester(local_state(), GetProfile());
const std::string primary_pattern_spec = "https://example1.com";
const std::string primary_pattern_spec_2 = "https://example2.com";
const std::string secondary_pattern_spec = "https://example3.com";
// dtrp is arbitrary here, selected between (0,100).
const uint32_t dtrp = 10;
tpcd::metadata::Metadata metadata;
tpcd::metadata::helpers::AddEntryToMetadata(
metadata, primary_pattern_spec, secondary_pattern_spec,
tpcd::metadata::Parser::kSource1pDt, dtrp);
tpcd::metadata::helpers::AddEntryToMetadata(
metadata, primary_pattern_spec_2, secondary_pattern_spec,
tpcd::metadata::Parser::kSource1pDt, dtrp);
// Establish grant with deterministic cohorts.
{
// rand is set as-is here to guarantee GRACE_PERIOD_FORCED_ON.
uint32_t rand = dtrp + 1;
tester.GetDetGenerator()->set_rand(rand);
tester.GetParser()->ParseMetadata(metadata.SerializeAsString());
EXPECT_EQ(
tester.GetManager()
->GetGrants()
.front()
.metadata.tpcd_metadata_cohort(),
content_settings::mojom::TpcdMetadataCohort::GRACE_PERIOD_FORCED_ON);
EXPECT_EQ(
tester.GetManager()->GetGrants().back().metadata.tpcd_metadata_cohort(),
content_settings::mojom::TpcdMetadataCohort::GRACE_PERIOD_FORCED_ON);
}
// Make sure the cohorts are persisted.
{
// rand is set as-is here to guarantee GRACE_PERIOD_FORCED_OFF.
uint32_t rand = dtrp;
tester.GetDetGenerator()->set_rand(rand);
tester.GetParser()->ParseMetadata(metadata.SerializeAsString());
EXPECT_EQ(
tester.GetManager()
->GetGrants()
.front()
.metadata.tpcd_metadata_cohort(),
content_settings::mojom::TpcdMetadataCohort::GRACE_PERIOD_FORCED_ON);
EXPECT_EQ(
tester.GetManager()->GetGrants().back().metadata.tpcd_metadata_cohort(),
content_settings::mojom::TpcdMetadataCohort::GRACE_PERIOD_FORCED_ON);
}
// Apply deletion of cookies.
BlockUntilBrowsingDataRemoved(base::Time(), base::Time::Max(),
content::BrowsingDataRemover::DATA_TYPE_COOKIES,
false);
// Make sure the cohorts were reset.
{
EXPECT_EQ(
tester.GetManager()
->GetGrants()
.front()
.metadata.tpcd_metadata_cohort(),
content_settings::mojom::TpcdMetadataCohort::GRACE_PERIOD_FORCED_OFF);
EXPECT_EQ(
tester.GetManager()->GetGrants().back().metadata.tpcd_metadata_cohort(),
content_settings::mojom::TpcdMetadataCohort::GRACE_PERIOD_FORCED_OFF);
}
}
TEST_F(ChromeBrowsingDataRemoverDelegateTpcdMetadataTest,
ResetAllCohort_PreserveSome) {
auto tester = RemoveTpcdMetadataCohortsTester(local_state(), GetProfile());
const std::string primary_pattern_spec = "https://example1.com";
const std::string primary_pattern_spec_2 = "https://example2.com";
const std::string secondary_pattern_spec = "https://example3.com";
// dtrp is arbitrary here, selected between (0,100).
const uint32_t dtrp = 10;
tpcd::metadata::Metadata metadata;
tpcd::metadata::helpers::AddEntryToMetadata(
metadata, primary_pattern_spec, secondary_pattern_spec,
tpcd::metadata::Parser::kSource1pDt, dtrp);
tpcd::metadata::helpers::AddEntryToMetadata(
metadata, primary_pattern_spec_2, secondary_pattern_spec,
tpcd::metadata::Parser::kSource1pDt, dtrp);
// Establish grant with deterministic cohorts.
{
// rand is set as-is here to guarantee GRACE_PERIOD_FORCED_ON.
uint32_t rand = dtrp + 1;
tester.GetDetGenerator()->set_rand(rand);
tester.GetParser()->ParseMetadata(metadata.SerializeAsString());
EXPECT_EQ(
tester.GetManager()
->GetGrants()
.front()
.metadata.tpcd_metadata_cohort(),
content_settings::mojom::TpcdMetadataCohort::GRACE_PERIOD_FORCED_ON);
EXPECT_EQ(
tester.GetManager()->GetGrants().back().metadata.tpcd_metadata_cohort(),
content_settings::mojom::TpcdMetadataCohort::GRACE_PERIOD_FORCED_ON);
}
// Make sure the cohorts are persisted.
{
// rand is set as-is here to guarantee GRACE_PERIOD_FORCED_OFF.
uint32_t rand = dtrp;
tester.GetDetGenerator()->set_rand(rand);
tester.GetParser()->ParseMetadata(metadata.SerializeAsString());
EXPECT_EQ(
tester.GetManager()
->GetGrants()
.front()
.metadata.tpcd_metadata_cohort(),
content_settings::mojom::TpcdMetadataCohort::GRACE_PERIOD_FORCED_ON);
EXPECT_EQ(
tester.GetManager()->GetGrants().back().metadata.tpcd_metadata_cohort(),
content_settings::mojom::TpcdMetadataCohort::GRACE_PERIOD_FORCED_ON);
}
// Apply deletion of all cookies.
std::unique_ptr<BrowsingDataFilterBuilder> filter(
BrowsingDataFilterBuilder::Create(
BrowsingDataFilterBuilder::Mode::kPreserve));
filter->AddRegisterableDomain(GURL(primary_pattern_spec).host());
ASSERT_TRUE(filter->MatchesMostOriginsAndDomains());
BlockUntilOriginDataRemoved(base::Time(), base::Time::Max(),
content::BrowsingDataRemover::DATA_TYPE_COOKIES,
std::move(filter));
// Make sure both cohorts were reset.
{
EXPECT_EQ(
tester.GetManager()
->GetGrants()
.front()
.metadata.tpcd_metadata_cohort(),
content_settings::mojom::TpcdMetadataCohort::GRACE_PERIOD_FORCED_OFF);
EXPECT_EQ(
tester.GetManager()->GetGrants().back().metadata.tpcd_metadata_cohort(),
content_settings::mojom::TpcdMetadataCohort::GRACE_PERIOD_FORCED_OFF);
}
}
// Constants for ChromeBrowsingDataRemoverDelegateRelatedWebsiteSetsTest.
namespace {
constexpr char kPrimaryUrl[] = "https://subdomain.example.com:112";
constexpr char kSecondaryUrl[] = "https://subidubi.testsite.com:55";
constexpr char kUnrelatedPrimaryUrl[] = "https://dontdeleteme.com";
constexpr char kUnrelatedSecondaryUrl[] = "https://keepthis.com";
enum class FilterOrigins {
kByPrimaryUrl,
kBySecondaryUrl,
kByBothUrls,
};
// Expected setting for the default grant.
const ContentSettingPatternSource kExpectedSettingDefault(
ContentSettingsPattern::Wildcard(),
ContentSettingsPattern::Wildcard(),
content_settings::ContentSettingToValue(CONTENT_SETTING_ASK),
content_settings::ProviderType::kDefaultProvider,
/*incognito=*/false);
} // namespace
class ChromeBrowsingDataRemoverDelegateRelatedWebsiteSetsTest
: public ChromeBrowsingDataRemoverDelegateTest,
public testing::WithParamInterface<
std::tuple<bool, // IsDecidedByRelatedWebsiteSets.
ContentSettingsType,
FilterOrigins>> {
public:
bool IsDecidedByRelatedWebsiteSets() const { return std::get<0>(GetParam()); }
ContentSettingsType GetContentSettingsType() const {
return std::get<1>(GetParam());
}
FilterOrigins GetFilterOrigin() const { return std::get<2>(GetParam()); }
content_settings::ContentSettingConstraints GetConstraints() {
content_settings::ContentSettingConstraints constraints;
constraints.set_session_model(
content_settings::mojom::SessionModel::DURABLE);
constraints.set_decided_by_related_website_sets(
IsDecidedByRelatedWebsiteSets());
return constraints;
}
content_settings::RuleMetaData GetMetadata() {
content_settings::RuleMetaData metadata;
metadata.SetFromConstraints(GetConstraints());
metadata.set_last_modified(base::Time::Now());
return metadata;
}
void RemoveRelatedWebsiteSetsPermissionsData() {
std::unique_ptr<BrowsingDataFilterBuilder> filter_builder(
BrowsingDataFilterBuilder::Create(
BrowsingDataFilterBuilder::Mode::kDelete));
switch (GetFilterOrigin()) {
case FilterOrigins::kByPrimaryUrl:
filter_builder->AddOrigin(url::Origin::Create(GURL(kPrimaryUrl)));
break;
case FilterOrigins::kBySecondaryUrl:
filter_builder->AddOrigin(url::Origin::Create(GURL(kSecondaryUrl)));
break;
case FilterOrigins::kByBothUrls:
filter_builder->AddOrigin(url::Origin::Create(GURL(kPrimaryUrl)));
filter_builder->AddOrigin(url::Origin::Create(GURL(kSecondaryUrl)));
break;
}
BlockUntilOriginDataRemoved(base::Time(), base::Time::Max(),
content::BrowsingDataRemover::
DATA_TYPE_RELATED_WEBSITE_SETS_PERMISSIONS,
std::move(filter_builder));
}
ContentSettingPatternSource GetExpectedSetting() {
return GetExpectedSetting(kPrimaryUrl, kSecondaryUrl);
}
ContentSettingPatternSource GetExpectedUnrelatedSetting() {
return GetExpectedSetting(kUnrelatedPrimaryUrl, kUnrelatedSecondaryUrl);
}
private:
ContentSettingPatternSource GetExpectedSetting(
std::string_view primaryUrl,
std::string_view secondaryUrl) {
switch (GetContentSettingsType()) {
case ContentSettingsType::STORAGE_ACCESS:
return ContentSettingPatternSource(
ContentSettingsPattern::FromURLToSchemefulSitePattern(
GURL(primaryUrl)), // e.g. https://[*.]example.com
ContentSettingsPattern::FromURLToSchemefulSitePattern(
GURL(secondaryUrl)), // e.g. https://[*.]testsite.com
content_settings::ContentSettingToValue(CONTENT_SETTING_ALLOW),
content_settings::ProviderType::kPrefProvider, /*incognito=*/false,
GetMetadata());
case ContentSettingsType::TOP_LEVEL_STORAGE_ACCESS:
return ContentSettingPatternSource(
ContentSettingsPattern::FromURLNoWildcard(
GURL(primaryUrl)), // e.g. https://subdomain.example.com:112
ContentSettingsPattern::FromURLToSchemefulSitePattern(
GURL(secondaryUrl)),
content_settings::ContentSettingToValue(CONTENT_SETTING_ALLOW),
content_settings::ProviderType::kPrefProvider, /*incognito=*/false,
GetMetadata());
default:
NOTREACHED();
}
}
};
// Test that the DATA_TYPE_RELATED_WEBSITE_SETS_PERMISSIONS mask removes
// permissions if those permissions were granted to the relevant sites and were
// granted via Related Website Sets.
TEST_P(ChromeBrowsingDataRemoverDelegateRelatedWebsiteSetsTest,
RemoveRelatedWebsiteSetsPermissions) {
HostContentSettingsMap* settings_map =
HostContentSettingsMapFactory::GetForProfile(GetProfile());
// Check that there are only default grants.
ASSERT_THAT(settings_map->GetSettingsForOneType(GetContentSettingsType()),
UnorderedElementsAre(kExpectedSettingDefault));
// Set grants.
settings_map->SetContentSettingDefaultScope(
GURL(kPrimaryUrl), GURL(kSecondaryUrl), GetContentSettingsType(),
CONTENT_SETTING_ALLOW, GetConstraints());
settings_map->SetContentSettingDefaultScope(
GURL(kUnrelatedPrimaryUrl), GURL(kUnrelatedSecondaryUrl),
GetContentSettingsType(), CONTENT_SETTING_ALLOW, GetConstraints());
// Check that the grants were set.
ASSERT_THAT(
settings_map->GetSettingsForOneType(GetContentSettingsType()),
UnorderedElementsAre(kExpectedSettingDefault, GetExpectedSetting(),
GetExpectedUnrelatedSetting()));
RemoveRelatedWebsiteSetsPermissionsData();
if (IsDecidedByRelatedWebsiteSets()) {
// Check that there's only the default and unrelated grants left.
EXPECT_THAT(settings_map->GetSettingsForOneType(GetContentSettingsType()),
UnorderedElementsAre(kExpectedSettingDefault,
GetExpectedUnrelatedSetting()));
} else {
// Check that none of the grants have been deleted.
EXPECT_THAT(
settings_map->GetSettingsForOneType(GetContentSettingsType()),
UnorderedElementsAre(kExpectedSettingDefault, GetExpectedSetting(),
GetExpectedUnrelatedSetting()));
}
}
INSTANTIATE_TEST_SUITE_P(
All,
ChromeBrowsingDataRemoverDelegateRelatedWebsiteSetsTest,
testing::Combine(
testing::Bool(), // IsDecidedByRelatedWebsiteSets.
testing::Values(ContentSettingsType::STORAGE_ACCESS,
ContentSettingsType::TOP_LEVEL_STORAGE_ACCESS),
testing::Values(FilterOrigins::kByPrimaryUrl,
FilterOrigins::kBySecondaryUrl,
FilterOrigins::kByBothUrls)));
|