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
|
// Copyright 2012 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Portions of this code based on Mozilla:
// (netwerk/cookie/src/nsCookieService.cpp)
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is mozilla.org code.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 2003
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Daniel Witte (dwitte@stanford.edu)
* Michiel van Leeuwen (mvl@exedo.nl)
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#include "net/cookies/cookie_monster.h"
#include <algorithm>
#include <array>
#include <functional>
#include <list>
#include <map>
#include <memory>
#include <numeric>
#include <optional>
#include <set>
#include <string_view>
#include <tuple>
#include <utility>
#include <vector>
#include "base/check.h"
#include "base/check_is_test.h"
#include "base/compiler_specific.h"
#include "base/containers/flat_map.h"
#include "base/dcheck_is_on.h"
#include "base/feature_list.h"
#include "base/functional/bind.h"
#include "base/functional/callback.h"
#include "base/location.h"
#include "base/logging.h"
#include "base/metrics/field_trial.h"
#include "base/metrics/histogram_functions.h"
#include "base/metrics/histogram_macros.h"
#include "base/rand_util.h"
#include "base/strings/strcat.h"
#include "base/strings/string_util.h"
#include "base/strings/stringprintf.h"
#include "base/task/single_thread_task_runner.h"
#include "base/threading/thread_checker.h"
#include "base/time/time.h"
#include "base/timer/elapsed_timer.h"
#include "net/base/isolation_info.h"
#include "net/base/registry_controlled_domains/registry_controlled_domain.h"
#include "net/base/schemeful_site.h"
#include "net/base/url_util.h"
#include "net/cookies/canonical_cookie.h"
#include "net/cookies/cookie_access_params.h"
#include "net/cookies/cookie_base.h"
#include "net/cookies/cookie_constants.h"
#include "net/cookies/cookie_monster_change_dispatcher.h"
#include "net/cookies/cookie_monster_netlog_params.h"
#include "net/cookies/cookie_partition_key.h"
#include "net/cookies/cookie_partition_key_collection.h"
#include "net/cookies/cookie_util.h"
#include "net/cookies/parsed_cookie.h"
#include "net/cookies/unique_cookie_key.h"
#include "net/http/http_util.h"
#include "net/log/net_log.h"
#include "net/log/net_log_values.h"
#include "url/origin.h"
#include "url/third_party/mozilla/url_parse.h"
#include "url/url_canon.h"
#include "url/url_constants.h"
using base::Time;
using base::TimeTicks;
using TimeRange = net::CookieDeletionInfo::TimeRange;
// In steady state, most cookie requests can be satisfied by the in memory
// cookie monster store. If the cookie request cannot be satisfied by the in
// memory store, the relevant cookies must be fetched from the persistent
// store. The task is queued in CookieMonster::tasks_pending_ if it requires
// all cookies to be loaded from the backend, or tasks_pending_for_key_ if it
// only requires all cookies associated with an eTLD+1.
//
// On the browser critical paths (e.g. for loading initial web pages in a
// session restore) it may take too long to wait for the full load. If a cookie
// request is for a specific URL, DoCookieCallbackForURL is called, which
// triggers a priority load if the key is not loaded yet by calling
// PersistentCookieStore::LoadCookiesForKey. The request is queued in
// CookieMonster::tasks_pending_for_key_ and executed upon receiving
// notification of key load completion via CookieMonster::OnKeyLoaded(). If
// multiple requests for the same eTLD+1 are received before key load
// completion, only the first request calls
// PersistentCookieStore::LoadCookiesForKey, all subsequent requests are queued
// in CookieMonster::tasks_pending_for_key_ and executed upon receiving
// notification of key load completion triggered by the first request for the
// same eTLD+1.
static const int kMinutesIn400Days = 60 * 24 * 400;
namespace {
// This enum is used to generate a histogramed bitmask measureing the types
// of stored cookies. Please do not reorder the list when adding new entries.
// New items MUST be added at the end of the list, just before
// COOKIE_TYPE_LAST_ENTRY;
// There will be 2^COOKIE_TYPE_LAST_ENTRY buckets in the linear histogram.
enum CookieType {
COOKIE_TYPE_SAME_SITE = 0,
COOKIE_TYPE_HTTPONLY,
COOKIE_TYPE_SECURE,
COOKIE_TYPE_PERSISTENT,
COOKIE_TYPE_LAST_ENTRY
};
void MaybeRunDeleteCallback(base::WeakPtr<net::CookieMonster> cookie_monster,
base::OnceClosure callback) {
if (cookie_monster && callback)
std::move(callback).Run();
}
template <typename CB, typename... R>
void MaybeRunCookieCallback(base::OnceCallback<CB> callback, R&&... result) {
if (callback) {
std::move(callback).Run(std::forward<R>(result)...);
}
}
// Anonymous and Fenced Frame uses a CookiePartitionKey with a nonce. In these
// contexts, access to unpartitioned cookie is not granted.
//
// This returns true if the |list| of key should include unpartitioned cookie in
// GetCookie...().
bool IncludeUnpartitionedCookies(
const net::CookiePartitionKeyCollection& list) {
if (list.IsEmpty() || list.ContainsAllKeys())
return true;
return !std::ranges::all_of(
list.PartitionKeys(),
&net::CookiePartitionKey::ForbidsUnpartitionedCookieAccess);
}
size_t NameValueSizeBytes(const net::CanonicalCookie& cc) {
base::CheckedNumeric<size_t> name_value_pair_size = cc.Name().size();
name_value_pair_size += cc.Value().size();
DCHECK(name_value_pair_size.IsValid());
return name_value_pair_size.ValueOrDie();
}
size_t NumBytesInCookieMapForKey(
const net::CookieMonster::CookieMap& cookie_map,
const std::string& key) {
size_t result = 0;
auto range = cookie_map.equal_range(key);
for (auto it = range.first; it != range.second; ++it) {
result += NameValueSizeBytes(*it->second);
}
return result;
}
size_t NumBytesInCookieItVector(
const net::CookieMonster::CookieItVector& cookie_its) {
size_t result = 0;
for (const auto& it : cookie_its) {
result += NameValueSizeBytes(*it->second);
}
return result;
}
void LogStoredCookieToUMA(const net::CanonicalCookie& cc,
const net::CookieAccessResult& access_result) {
// Cookie.Type2 collects a bitvector of important cookie attributes.
int32_t type_sample =
!cc.IsEffectivelySameSiteNone(access_result.access_semantics)
? 1 << COOKIE_TYPE_SAME_SITE
: 0;
type_sample |= cc.IsHttpOnly() ? 1 << COOKIE_TYPE_HTTPONLY : 0;
type_sample |= cc.SecureAttribute() ? 1 << COOKIE_TYPE_SECURE : 0;
type_sample |= cc.IsPersistent() ? 1 << COOKIE_TYPE_PERSISTENT : 0;
base::UmaHistogramExactLinear("Cookie.Type2.Subsampled", type_sample,
(1 << COOKIE_TYPE_LAST_ENTRY));
// Cookie.SourceType collects the CookieSourceType of the stored cookie.
base::UmaHistogramEnumeration("Cookie.SourceType.Subsampled",
cc.SourceType());
}
} // namespace
namespace net {
// See comments at declaration of these variables in cookie_monster.h
// for details.
const size_t CookieMonster::kDomainMaxCookies = 180;
const size_t CookieMonster::kDomainPurgeCookies = 30;
const size_t CookieMonster::kMaxCookies = 3300;
const size_t CookieMonster::kPurgeCookies = 300;
const size_t CookieMonster::kMaxDomainPurgedKeys = 100;
const size_t CookieMonster::kPerPartitionDomainMaxCookieBytes = 10240;
const size_t CookieMonster::kPerPartitionDomainMaxCookies = 180;
const size_t CookieMonster::kDomainCookiesQuotaLow = 30;
const size_t CookieMonster::kDomainCookiesQuotaMedium = 50;
const size_t CookieMonster::kDomainCookiesQuotaHigh =
kDomainMaxCookies - kDomainPurgeCookies - kDomainCookiesQuotaLow -
kDomainCookiesQuotaMedium;
const int CookieMonster::kSafeFromGlobalPurgeDays = 30;
namespace {
bool ContainsControlCharacter(const std::string& s) {
return std::ranges::any_of(s, &HttpUtil::IsControlChar);
}
typedef std::vector<CanonicalCookie*> CanonicalCookieVector;
// Default minimum delay after updating a cookie's LastAccessDate before we
// will update it again.
const int kDefaultAccessUpdateThresholdSeconds = 60;
// Comparator to sort cookies from highest creation date to lowest
// creation date.
struct OrderByCreationTimeDesc {
bool operator()(const CookieMonster::CookieMap::iterator& a,
const CookieMonster::CookieMap::iterator& b) const {
return a->second->CreationDate() > b->second->CreationDate();
}
};
bool LRACookieSorter(const CookieMonster::CookieMap::iterator& it1,
const CookieMonster::CookieMap::iterator& it2) {
if (it1->second->LastAccessDate() != it2->second->LastAccessDate())
return it1->second->LastAccessDate() < it2->second->LastAccessDate();
// Ensure stability for == last access times by falling back to creation.
return it1->second->CreationDate() < it2->second->CreationDate();
}
// For a CookieItVector iterator range [|it_begin|, |it_end|),
// sorts the first |num_sort| elements by LastAccessDate().
void SortLeastRecentlyAccessed(CookieMonster::CookieItVector::iterator it_begin,
CookieMonster::CookieItVector::iterator it_end,
size_t num_sort) {
DCHECK_LE(static_cast<int>(num_sort), it_end - it_begin);
std::partial_sort(it_begin, it_begin + num_sort, it_end, LRACookieSorter);
}
// Given a single cookie vector |cookie_its|, pushs all of the secure cookies in
// |cookie_its| into |secure_cookie_its| and all of the non-secure cookies into
// |non_secure_cookie_its|. Both |secure_cookie_its| and |non_secure_cookie_its|
// must be non-NULL.
void SplitCookieVectorIntoSecureAndNonSecure(
const CookieMonster::CookieItVector& cookie_its,
CookieMonster::CookieItVector* secure_cookie_its,
CookieMonster::CookieItVector* non_secure_cookie_its) {
DCHECK(secure_cookie_its && non_secure_cookie_its);
for (const auto& curit : cookie_its) {
if (curit->second->SecureAttribute()) {
secure_cookie_its->push_back(curit);
} else {
non_secure_cookie_its->push_back(curit);
}
}
}
bool LowerBoundAccessDateComparator(const CookieMonster::CookieMap::iterator it,
const Time& access_date) {
return it->second->LastAccessDate() < access_date;
}
// For a CookieItVector iterator range [|it_begin|, |it_end|)
// from a CookieItVector sorted by LastAccessDate(), returns the
// first iterator with access date >= |access_date|, or cookie_its_end if this
// holds for all.
CookieMonster::CookieItVector::iterator LowerBoundAccessDate(
const CookieMonster::CookieItVector::iterator its_begin,
const CookieMonster::CookieItVector::iterator its_end,
const Time& access_date) {
return std::lower_bound(its_begin, its_end, access_date,
LowerBoundAccessDateComparator);
}
// Mapping between DeletionCause and CookieChangeCause; the
// mapping also provides a boolean that specifies whether or not an
// OnCookieChange notification ought to be generated.
typedef struct ChangeCausePair_struct {
CookieChangeCause cause;
bool notify;
} ChangeCausePair;
constexpr auto kChangeCauseMapping = std::to_array<ChangeCausePair>({
// DELETE_COOKIE_EXPLICIT
{CookieChangeCause::EXPLICIT, true},
// DELETE_COOKIE_OVERWRITE
{CookieChangeCause::OVERWRITE, true},
// DELETE_COOKIE_EXPIRED
{CookieChangeCause::EXPIRED, true},
// DELETE_COOKIE_EVICTED
{CookieChangeCause::EVICTED, true},
// DELETE_COOKIE_DUPLICATE_IN_BACKING_STORE
{CookieChangeCause::EXPLICIT, false},
// DELETE_COOKIE_DONT_RECORD
{CookieChangeCause::EXPLICIT, false},
// DELETE_COOKIE_EVICTED_DOMAIN
{CookieChangeCause::EVICTED, true},
// DELETE_COOKIE_EVICTED_GLOBAL
{CookieChangeCause::EVICTED, true},
// DELETE_COOKIE_EVICTED_DOMAIN_PRE_SAFE
{CookieChangeCause::EVICTED, true},
// DELETE_COOKIE_EVICTED_DOMAIN_POST_SAFE
{CookieChangeCause::EVICTED, true},
// DELETE_COOKIE_EXPIRED_OVERWRITE
{CookieChangeCause::EXPIRED_OVERWRITE, true},
// DELETE_COOKIE_CONTROL_CHAR
{CookieChangeCause::EVICTED, true},
// DELETE_COOKIE_NON_SECURE
{CookieChangeCause::EVICTED, true},
// DELETE_COOKIE_EVICTED_PER_PARTITION_DOMAIN
{CookieChangeCause::EVICTED, true},
// DELETE_COOKIE_ALIAS
{CookieChangeCause::EVICTED, false},
// DELETE_COOKIE_LAST_ENTRY
{CookieChangeCause::EXPLICIT, false},
});
bool IsCookieEligibleForEviction(CookiePriority current_priority_level,
bool protect_secure_cookies,
const CanonicalCookie* cookie) {
if (cookie->Priority() == current_priority_level && protect_secure_cookies)
return !cookie->SecureAttribute();
return cookie->Priority() == current_priority_level;
}
size_t CountCookiesForPossibleDeletion(
CookiePriority priority,
const CookieMonster::CookieItVector& cookies,
bool protect_secure_cookies) {
size_t cookies_count = 0U;
for (const auto& cookie : cookies) {
if (cookie->second->Priority() == priority) {
if (!protect_secure_cookies || cookie->second->SecureAttribute()) {
cookies_count++;
}
}
}
return cookies_count;
}
struct DeletionCookieLists {
std::list<CookieMonster::CookieItList::const_iterator> host_cookies;
std::list<CookieMonster::CookieItList::const_iterator> domain_cookies;
};
// Performs 2 tasks
// * Counts every cookie at the given `priority` in `cookies`. This is the
// return value.
// * Fills in the host & domain lists for `could_be_deleted` with every cookie
// of the given {secureness, priority} in `cookies`.
size_t CountCookiesAndGenerateListsForPossibleDeletion(
CookiePriority priority,
DeletionCookieLists& could_be_deleted,
const CookieMonster::CookieItList& cookies,
bool generate_for_secure) {
size_t total_cookies_at_priority = 0;
for (auto list_it = cookies.begin(); list_it != cookies.end(); list_it++) {
const auto cookiemap_it = *list_it;
const auto& cookie = cookiemap_it->second;
if (cookie->Priority() != priority) {
continue;
}
// Because we want to keep a specific number of cookies per priority level,
// independent of securness of the cookies, we need to count all the cookies
// at the level even if we'll skip adding them to the deletion lists.
total_cookies_at_priority++;
if (cookie->IsSecure() != generate_for_secure) {
continue;
}
if (cookie->IsHostCookie()) {
could_be_deleted.host_cookies.push_back(list_it);
} else { // Is a domain cookie.
could_be_deleted.domain_cookies.push_back(list_it);
}
}
return total_cookies_at_priority;
}
// Fills in the host & domain lists for `could_be_deleted` with every cookie
// in `cookies`.
DeletionCookieLists
CountCookiesAndGenerateListsForPossibleDeletionPartitionedCookies(
const CookieMonster::CookieItList& cookies) {
DeletionCookieLists could_be_deleted;
for (auto list_it = cookies.begin(); list_it != cookies.end(); list_it++) {
const auto cookiemap_it = *list_it;
const auto& cookie = cookiemap_it->second;
if (cookie->IsHostCookie()) {
could_be_deleted.host_cookies.push_back(list_it);
} else { // Is a domain cookie.
could_be_deleted.domain_cookies.push_back(list_it);
}
}
return could_be_deleted;
}
// Records whether the cookie being set is persistent. If so, this also records
// minutes until the expiration date of a cookie to the appropriate histogram.
void RecordPersistanceHistograms(const CanonicalCookie& cookie,
base::Time creation_time) {
base::UmaHistogramBoolean("Cookie.IsPersistentWhenSet.Subsampled",
cookie.IsPersistent());
if (!cookie.IsPersistent())
return;
int expiration_duration_minutes =
(cookie.ExpiryDate() - creation_time).InMinutes();
if (cookie.SecureAttribute()) {
base::UmaHistogramCustomCounts(
"Cookie.ExpirationDurationMinutesSecure.Subsampled2",
expiration_duration_minutes, 1, kMinutesIn400Days, 100);
} else {
base::UmaHistogramCustomCounts(
"Cookie.ExpirationDurationMinutesNonSecure.Subsampled2",
expiration_duration_minutes, 1, kMinutesIn400Days, 100);
}
}
} // namespace
CookieMonster::CookieMonster(scoped_refptr<PersistentCookieStore> store,
NetLog* net_log,
std::unique_ptr<PrefDelegate> pref_delegate)
: CookieMonster(std::move(store),
base::Seconds(kDefaultAccessUpdateThresholdSeconds),
net_log,
std::move(pref_delegate)) {}
CookieMonster::CookieMonster(scoped_refptr<PersistentCookieStore> store,
base::TimeDelta last_access_threshold,
NetLog* net_log,
std::unique_ptr<PrefDelegate> pref_delegate)
: change_dispatcher_(this),
net_log_(NetLogWithSource::Make(net_log, NetLogSourceType::COOKIE_STORE)),
pref_delegate_(std::move(pref_delegate)),
store_(std::move(store)),
last_access_threshold_(last_access_threshold),
last_statistic_record_time_(base::Time::Now()) {
cookieable_schemes_ = GetDefaultCookieableSchemes();
net_log_.BeginEvent(NetLogEventType::COOKIE_STORE_ALIVE, [&] {
return NetLogCookieMonsterConstructorParams(store_ != nullptr);
});
}
// Asynchronous CookieMonster API
void CookieMonster::FlushStore(base::OnceClosure callback) {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
if (initialized_ && store_.get()) {
store_->Flush(std::move(callback));
} else if (callback) {
base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
FROM_HERE, std::move(callback));
}
}
void CookieMonster::SetForceKeepSessionState() {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
if (store_)
store_->SetForceKeepSessionState();
}
void CookieMonster::SetAllCookiesAsync(const CookieList& list,
SetCookiesCallback callback) {
DoCookieCallback(base::BindOnce(
// base::Unretained is safe as DoCookieCallback stores
// the callback on |*this|, so the callback will not outlive
// the object.
&CookieMonster::SetAllCookies, base::Unretained(this), list,
std::move(callback)));
}
void CookieMonster::SetCanonicalCookieAsync(
std::unique_ptr<CanonicalCookie> cookie,
const GURL& source_url,
const CookieOptions& options,
SetCookiesCallback callback,
std::optional<CookieAccessResult> cookie_access_result) {
if constexpr (DCHECK_IS_ON()) {
CanonicalCookie::CanonicalizationResult result = cookie->IsCanonical();
DCHECK(result) << result;
}
std::string domain = cookie->Domain();
DoCookieCallbackForHostOrDomain(
base::BindOnce(
// base::Unretained is safe as DoCookieCallbackForHostOrDomain stores
// the callback on |*this|, so the callback will not outlive
// the object.
&CookieMonster::SetCanonicalCookie, base::Unretained(this),
std::move(cookie), source_url, options, std::move(callback),
std::move(cookie_access_result)),
domain);
}
void CookieMonster::SetUnsafeCanonicalCookieForTestAsync(
std::unique_ptr<CanonicalCookie> cookie,
SetCookiesCallback callback) {
CanonicalCookie::CanonicalizationResult result = cookie->IsCanonical();
CHECK(result) << result;
std::string domain = cookie->Domain();
DoCookieCallbackForHostOrDomain(
base::BindOnce(
// base::Unretained is safe as DoCookieCallbackForHostOrDomain stores
// the callback on |*this|, so the callback will not outlive
// the object.
&CookieMonster::SetUnsafeCanonicalCookieForTest,
base::Unretained(this), std::move(cookie), std::move(callback)),
domain);
}
void CookieMonster::GetCookieListWithOptionsAsync(
const GURL& url,
const CookieOptions& options,
const CookiePartitionKeyCollection& cookie_partition_key_collection,
GetCookieListCallback callback) {
DoCookieCallbackForURL(
base::BindOnce(
// base::Unretained is safe as DoCookieCallbackForURL stores
// the callback on |*this|, so the callback will not outlive
// the object.
&CookieMonster::GetCookieListWithOptions, base::Unretained(this), url,
options, cookie_partition_key_collection, std::move(callback)),
url);
}
void CookieMonster::GetAllCookiesAsync(GetAllCookiesCallback callback) {
DoCookieCallback(base::BindOnce(
// base::Unretained is safe as DoCookieCallback stores
// the callback on |*this|, so the callback will not outlive
// the object.
&CookieMonster::GetAllCookies, base::Unretained(this),
std::move(callback)));
}
void CookieMonster::GetAllCookiesWithAccessSemanticsAsync(
GetAllCookiesWithAccessSemanticsCallback callback) {
DoCookieCallback(base::BindOnce(
// base::Unretained is safe as DoCookieCallback stores
// the callback on |*this|, so the callback will not outlive
// the object.
&CookieMonster::GetAllCookies, base::Unretained(this),
base::BindOnce(&CookieMonster::AttachAccessSemanticsListForCookieList,
base::Unretained(this), std::move(callback))));
}
void CookieMonster::DeleteCanonicalCookieAsync(const CanonicalCookie& cookie,
DeleteCallback callback) {
DoCookieCallback(base::BindOnce(
// base::Unretained is safe as DoCookieCallback stores
// the callback on |*this|, so the callback will not outlive
// the object.
&CookieMonster::DeleteCanonicalCookie, base::Unretained(this), cookie,
std::move(callback)));
}
void CookieMonster::DeleteAllCreatedInTimeRangeAsync(
const TimeRange& creation_range,
DeleteCallback callback) {
DoCookieCallback(base::BindOnce(
// base::Unretained is safe as DoCookieCallback stores
// the callback on |*this|, so the callback will not outlive
// the object.
&CookieMonster::DeleteAllCreatedInTimeRange, base::Unretained(this),
creation_range, std::move(callback)));
}
void CookieMonster::DeleteAllMatchingInfoAsync(CookieDeletionInfo delete_info,
DeleteCallback callback) {
auto cookie_matcher =
base::BindRepeating(&CookieMonster::MatchCookieDeletionInfo,
base::Unretained(this), std::move(delete_info));
DoCookieCallback(base::BindOnce(
// base::Unretained is safe as DoCookieCallback stores
// the callback on |*this|, so the callback will not outlive
// the object.
&CookieMonster::DeleteMatchingCookies, base::Unretained(this),
std::move(cookie_matcher), DELETE_COOKIE_EXPLICIT, std::move(callback)));
}
void CookieMonster::DeleteSessionCookiesAsync(
CookieStore::DeleteCallback callback) {
auto session_cookie_matcher =
base::BindRepeating([](const net::CanonicalCookie& cookie) {
return !cookie.IsPersistent();
});
DoCookieCallback(base::BindOnce(
// base::Unretained is safe as DoCookieCallback stores
// the callback on |*this|, so the callback will not outlive
// the object.
&CookieMonster::DeleteMatchingCookies, base::Unretained(this),
std::move(session_cookie_matcher), DELETE_COOKIE_EXPIRED,
std::move(callback)));
}
void CookieMonster::DeleteMatchingCookiesAsync(
CookieStore::DeletePredicate predicate,
CookieStore::DeleteCallback callback) {
DoCookieCallback(base::BindOnce(
// base::Unretained is safe as DoCookieCallback stores
// the callback on |*this|, so the callback will not outlive
// the object.
&CookieMonster::DeleteMatchingCookies, base::Unretained(this),
std::move(predicate), DELETE_COOKIE_EXPLICIT, std::move(callback)));
}
void CookieMonster::SetCookieableSchemes(
std::vector<std::string> schemes,
SetCookieableSchemesCallback callback) {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
// Calls to this method will have no effect if made after a WebView or
// CookieManager instance has been created.
if (initialized_) {
MaybeRunCookieCallback(std::move(callback), false);
return;
}
cookieable_schemes_ = std::move(schemes);
MaybeRunCookieCallback(std::move(callback), true);
}
// This function must be called before the CookieMonster is used.
void CookieMonster::SetPersistSessionCookies(bool persist_session_cookies) {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
DCHECK(!initialized_);
net_log_.AddEntryWithBoolParams(
NetLogEventType::COOKIE_STORE_SESSION_PERSISTENCE, NetLogEventPhase::NONE,
"persistence", persist_session_cookies);
persist_session_cookies_ = persist_session_cookies;
}
// static
std::vector<std::string> CookieMonster::GetDefaultCookieableSchemes() {
return std::vector<std::string>{"http", "https", "ws", "wss"};
}
CookieChangeDispatcher& CookieMonster::GetChangeDispatcher() {
return change_dispatcher_;
}
CookieMonster::~CookieMonster() {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
net_log_.EndEvent(NetLogEventType::COOKIE_STORE_ALIVE);
}
// static
bool CookieMonster::CookieSorter(const CanonicalCookie* cc1,
const CanonicalCookie* cc2) {
// Mozilla sorts on the path length (longest first), and then it sorts by
// creation time (oldest first). The RFC says the sort order for the domain
// attribute is undefined.
if (cc1->Path().length() == cc2->Path().length())
return cc1->CreationDate() < cc2->CreationDate();
return cc1->Path().length() > cc2->Path().length();
}
void CookieMonster::GetAllCookies(GetAllCookiesCallback callback) {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
// This function is being called to scrape the cookie list for management UI
// or similar. We shouldn't show expired cookies in this list since it will
// just be confusing to users, and this function is called rarely enough (and
// is already slow enough) that it's OK to take the time to garbage collect
// the expired cookies now.
//
// Note that this does not prune cookies to be below our limits (if we've
// exceeded them) the way that calling GarbageCollect() would.
GarbageCollectExpired(
Time::Now(), CookieMapItPair(cookies_.begin(), cookies_.end()), nullptr);
GarbageCollectAllExpiredPartitionedCookies(Time::Now());
// Copy the CanonicalCookie pointers from the map so that we can use the same
// sorter as elsewhere, then copy the result out.
std::vector<CanonicalCookie*> cookie_ptrs;
cookie_ptrs.reserve(cookies_.size());
for (const auto& cookie : cookies_)
cookie_ptrs.push_back(cookie.second.get());
for (const auto& cookie_partition : partitioned_cookies_) {
for (const auto& cookie : *cookie_partition.second.get())
cookie_ptrs.push_back(cookie.second.get());
}
std::sort(cookie_ptrs.begin(), cookie_ptrs.end(), CookieSorter);
CookieList cookie_list;
cookie_list.reserve(cookie_ptrs.size());
for (auto* cookie_ptr : cookie_ptrs)
cookie_list.push_back(*cookie_ptr);
MaybeRunCookieCallback(std::move(callback), cookie_list);
}
void CookieMonster::AttachAccessSemanticsListForCookieList(
GetAllCookiesWithAccessSemanticsCallback callback,
const CookieList& cookie_list) {
std::vector<CookieAccessSemantics> access_semantics_list;
for (const CanonicalCookie& cookie : cookie_list) {
access_semantics_list.push_back(GetAccessSemanticsForCookie(cookie));
}
MaybeRunCookieCallback(std::move(callback), cookie_list,
access_semantics_list);
}
void CookieMonster::GetCookieListWithOptions(
const GURL& url,
const CookieOptions& options,
const CookiePartitionKeyCollection& cookie_partition_key_collection,
GetCookieListCallback callback) {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
std::optional<base::ElapsedTimer> timer;
if (metrics_subsampler_.ShouldSample(kHistogramSampleProbability)) {
timer.emplace();
}
CookieAccessResultList included_cookies;
CookieAccessResultList excluded_cookies;
if (HasCookieableScheme(url)) {
// Retrieve the domain, check this domain to see if this is the first
// time it is entering legacy mode, if it is delete all aliasing cookies
// within this domain.
CheckAndActivateLegacyScopeBehavior(url.host_piece());
std::vector<CanonicalCookie*> cookie_ptrs =
FindCookiesForRegistryControlledHost(url);
if (!cookie_partition_key_collection.IsEmpty()) {
if (cookie_partition_key_collection.ContainsAllKeys()) {
for (PartitionedCookieMap::iterator partition_it =
partitioned_cookies_.begin();
partition_it != partitioned_cookies_.end();) {
// InternalDeletePartitionedCookie may invalidate |partition_it| if
// that cookie partition only has one cookie and it expires.
auto cur_partition_it = partition_it;
++partition_it;
std::vector<CanonicalCookie*> partitioned_cookie_ptrs =
FindPartitionedCookiesForRegistryControlledHost(
cur_partition_it->first, url);
cookie_ptrs.insert(cookie_ptrs.end(), partitioned_cookie_ptrs.begin(),
partitioned_cookie_ptrs.end());
}
} else {
for (const CookiePartitionKey& key :
cookie_partition_key_collection.PartitionKeys()) {
std::vector<CanonicalCookie*> partitioned_cookie_ptrs =
FindPartitionedCookiesForRegistryControlledHost(key, url);
cookie_ptrs.insert(cookie_ptrs.end(), partitioned_cookie_ptrs.begin(),
partitioned_cookie_ptrs.end());
}
}
}
std::sort(cookie_ptrs.begin(), cookie_ptrs.end(), CookieSorter);
included_cookies.reserve(cookie_ptrs.size());
FilterCookiesWithOptions(url, options, cookie_partition_key_collection,
cookie_ptrs, included_cookies, excluded_cookies);
}
MaybeRunCookieCallback(std::move(callback), std::move(included_cookies),
std::move(excluded_cookies));
if (timer) {
base::UmaHistogramCustomMicrosecondsTimes(
"Cookie.GetCookieListWithOptions.Duration.Subsampled", timer->Elapsed(),
base::Microseconds(1), base::Milliseconds(128), 100);
}
}
void CookieMonster::DeleteAllCreatedInTimeRange(const TimeRange& creation_range,
DeleteCallback callback) {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
uint32_t num_deleted = 0;
for (auto it = cookies_.begin(); it != cookies_.end();) {
auto curit = it;
CanonicalCookie* cc = curit->second.get();
++it;
if (creation_range.Contains(cc->CreationDate())) {
InternalDeleteCookie(curit, true, /*sync_to_store*/
DELETE_COOKIE_EXPLICIT);
++num_deleted;
}
}
for (PartitionedCookieMap::iterator partition_it =
partitioned_cookies_.begin();
partition_it != partitioned_cookies_.end();) {
auto cur_partition_it = partition_it;
CookieMap::iterator cookie_it = cur_partition_it->second->begin();
CookieMap::iterator cookie_end = cur_partition_it->second->end();
// InternalDeletePartitionedCookie may delete this cookie partition if it
// only has one cookie, so we need to increment the iterator beforehand.
++partition_it;
while (cookie_it != cookie_end) {
auto cur_cookie_it = cookie_it;
CanonicalCookie* cc = cur_cookie_it->second.get();
++cookie_it;
if (creation_range.Contains(cc->CreationDate())) {
InternalDeletePartitionedCookie(cur_partition_it, cur_cookie_it,
true /*sync_to_store*/,
DELETE_COOKIE_EXPLICIT);
++num_deleted;
}
}
}
FlushStore(
base::BindOnce(&MaybeRunDeleteCallback, weak_ptr_factory_.GetWeakPtr(),
callback ? base::BindOnce(std::move(callback), num_deleted)
: base::OnceClosure()));
}
bool CookieMonster::MatchCookieDeletionInfo(
const CookieDeletionInfo& delete_info,
const net::CanonicalCookie& cookie) {
bool delegate_treats_url_as_trustworthy = false; // irrelevant if no URL.
if (delete_info.url.has_value()) {
delegate_treats_url_as_trustworthy =
cookie_access_delegate() &&
cookie_access_delegate()->ShouldTreatUrlAsTrustworthy(
delete_info.url.value());
}
return delete_info.Matches(
cookie,
CookieAccessParams{GetAccessSemanticsForCookie(cookie),
GetScopeSemanticsForCookieDomain(cookie.Domain()),
delegate_treats_url_as_trustworthy});
}
void CookieMonster::DeleteCanonicalCookie(const CanonicalCookie& cookie,
DeleteCallback callback) {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
uint32_t result = 0u;
CookieMap* cookie_map = nullptr;
PartitionedCookieMap::iterator cookie_partition_it;
if (cookie.IsPartitioned()) {
cookie_partition_it =
partitioned_cookies_.find(cookie.PartitionKey().value());
if (cookie_partition_it != partitioned_cookies_.end())
cookie_map = cookie_partition_it->second.get();
} else {
cookie_map = &cookies_;
}
if (cookie_map) {
for (CookieMapItPair its = cookie_map->equal_range(GetKey(cookie.Domain()));
its.first != its.second; ++its.first) {
const std::unique_ptr<CanonicalCookie>& candidate = its.first->second;
// Historically, this has refused modification if the cookie has changed
// value in between the CanonicalCookie object was returned by a getter
// and when this ran. The later parts of the conditional (everything but
// the equivalence check) attempt to preserve this behavior.
if (candidate->IsEquivalent(cookie) &&
candidate->Value() == cookie.Value()) {
if (cookie.IsPartitioned()) {
InternalDeletePartitionedCookie(cookie_partition_it, its.first, true,
DELETE_COOKIE_EXPLICIT);
} else {
InternalDeleteCookie(its.first, true, DELETE_COOKIE_EXPLICIT);
}
result = 1u;
break;
}
}
}
FlushStore(
base::BindOnce(&MaybeRunDeleteCallback, weak_ptr_factory_.GetWeakPtr(),
callback ? base::BindOnce(std::move(callback), result)
: base::OnceClosure()));
}
void CookieMonster::DeleteMatchingCookies(DeletePredicate predicate,
DeletionCause cause,
DeleteCallback callback) {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
DCHECK(predicate);
uint32_t num_deleted = 0;
for (auto it = cookies_.begin(); it != cookies_.end();) {
auto curit = it;
CanonicalCookie* cc = curit->second.get();
++it;
if (predicate.Run(*cc)) {
InternalDeleteCookie(curit, true /*sync_to_store*/, cause);
++num_deleted;
}
}
for (auto partition_it = partitioned_cookies_.begin();
partition_it != partitioned_cookies_.end();) {
// InternalDeletePartitionedCookie may invalidate |partition_it| if that
// cookie partition only has one cookie.
auto cur_partition_it = partition_it;
CookieMap::iterator cookie_it = cur_partition_it->second->begin();
CookieMap::iterator cookie_end = cur_partition_it->second->end();
++partition_it;
while (cookie_it != cookie_end) {
auto cur_cookie_it = cookie_it;
CanonicalCookie* cc = cur_cookie_it->second.get();
++cookie_it;
if (predicate.Run(*cc)) {
InternalDeletePartitionedCookie(cur_partition_it, cur_cookie_it, true,
cause);
++num_deleted;
}
}
}
FlushStore(
base::BindOnce(&MaybeRunDeleteCallback, weak_ptr_factory_.GetWeakPtr(),
callback ? base::BindOnce(std::move(callback), num_deleted)
: base::OnceClosure()));
}
void CookieMonster::MarkCookieStoreAsInitialized() {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
initialized_ = true;
}
void CookieMonster::FetchAllCookiesIfNecessary() {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
if (store_.get() && !started_fetching_all_cookies_) {
started_fetching_all_cookies_ = true;
FetchAllCookies();
}
}
void CookieMonster::FetchAllCookies() {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
DCHECK(store_.get()) << "Store must exist to initialize";
DCHECK(!finished_fetching_all_cookies_)
<< "All cookies have already been fetched.";
// We bind in the current time so that we can report the wall-clock time for
// loading cookies.
store_->Load(base::BindOnce(&CookieMonster::OnLoaded,
weak_ptr_factory_.GetWeakPtr(), TimeTicks::Now()),
net_log_);
}
void CookieMonster::OnLoaded(
TimeTicks beginning_time,
std::vector<std::unique_ptr<CanonicalCookie>> cookies) {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
StoreLoadedCookies(std::move(cookies));
base::TimeTicks now = base::TimeTicks::Now();
base::UmaHistogramCustomTimes("Cookie.TimeBlockedOnLoad",
now - beginning_time, base::Milliseconds(1),
base::Minutes(1), 50);
base::TimeDelta blocked_due_to_global_op = base::Milliseconds(0);
if (time_start_block_load_all_.has_value()) {
blocked_due_to_global_op = now - *time_start_block_load_all_;
}
base::UmaHistogramCustomTimes("Cookie.TimeOpsBlockedDueToGlobalOp",
blocked_due_to_global_op, base::Milliseconds(1),
base::Minutes(1), 50);
// Invoke the task queue of cookie request.
InvokeQueue();
}
void CookieMonster::OnKeyLoaded(
const std::string& key,
std::vector<std::unique_ptr<CanonicalCookie>> cookies) {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
StoreLoadedCookies(std::move(cookies));
auto tasks_pending_for_key = tasks_pending_for_key_.find(key);
// TODO(mmenke): Can this be turned into a DCHECK?
if (tasks_pending_for_key == tasks_pending_for_key_.end())
return;
// Run all tasks for the key. Note that running a task can result in multiple
// tasks being added to the back of the deque.
while (!tasks_pending_for_key->second.empty()) {
base::OnceClosure task = std::move(tasks_pending_for_key->second.front());
tasks_pending_for_key->second.pop_front();
std::move(task).Run();
}
tasks_pending_for_key_.erase(tasks_pending_for_key);
// This has to be done last, in case running a task queues a new task for the
// key, to ensure tasks are run in the correct order.
keys_loaded_.insert(key);
}
void CookieMonster::StoreLoadedCookies(
std::vector<std::unique_ptr<CanonicalCookie>> cookies) {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
// Even if a key is expired, insert it so it can be garbage collected,
// removed, and sync'd.
CookieItVector cookies_with_control_chars;
std::vector<PartitionedCookieMapIterators>
partitioned_cookies_with_control_chars;
for (auto& cookie : cookies) {
CanonicalCookie* cookie_ptr = cookie.get();
CookieAccessResult access_result;
access_result.access_semantics = CookieAccessSemantics::UNKNOWN;
if (cookie_ptr->IsPartitioned()) {
auto inserted = InternalInsertPartitionedCookie(
GetKey(cookie_ptr->Domain()), std::move(cookie),
/*sync_to_store=*/false, access_result, /*dispatch_change=*/false);
if (ContainsControlCharacter(cookie_ptr->Name()) ||
ContainsControlCharacter(cookie_ptr->Value())) {
partitioned_cookies_with_control_chars.push_back(inserted);
}
} else {
auto inserted = InternalInsertCookie(
GetKey(cookie_ptr->Domain()), std::move(cookie),
/*sync_to_store=*/false, access_result, /*dispatch_change=*/false);
if (ContainsControlCharacter(cookie_ptr->Name()) ||
ContainsControlCharacter(cookie_ptr->Value())) {
cookies_with_control_chars.push_back(inserted);
}
}
const Time cookie_access_time(cookie_ptr->LastAccessDate());
if (earliest_access_time_.is_null() ||
cookie_access_time < earliest_access_time_) {
earliest_access_time_ = cookie_access_time;
}
}
// Any cookies that contain control characters that we have loaded from the
// persistent store should be deleted. See http://crbug.com/238041.
for (auto it = cookies_with_control_chars.begin();
it != cookies_with_control_chars.end();) {
auto curit = it;
++it;
InternalDeleteCookie(*curit, true, DELETE_COOKIE_CONTROL_CHAR);
}
for (auto it = partitioned_cookies_with_control_chars.begin();
it != partitioned_cookies_with_control_chars.end();) {
// InternalDeletePartitionedCookie may invalidate the current iterator, so
// we increment the iterator in the loop before calling the function.
auto curit = it;
++it;
InternalDeletePartitionedCookie(curit->first, curit->second, true,
DELETE_COOKIE_CONTROL_CHAR);
}
// After importing cookies from the PersistentCookieStore, verify that
// none of our other constraints are violated.
// In particular, the backing store might have given us duplicate cookies.
// This method could be called multiple times due to priority loading, thus
// cookies loaded in previous runs will be validated again, but this is OK
// since they are expected to be much fewer than total DB.
EnsureCookiesMapIsValid();
}
void CookieMonster::InvokeQueue() {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
// Move all per-key tasks into the global queue, if there are any. This is
// protection about a race where the store learns about all cookies loading
// before it learned about the cookies for a key loading.
// Needed to prevent any recursively queued tasks from going back into the
// per-key queues.
seen_global_task_ = true;
for (auto& tasks_for_key : tasks_pending_for_key_) {
tasks_pending_.insert(tasks_pending_.begin(),
std::make_move_iterator(tasks_for_key.second.begin()),
std::make_move_iterator(tasks_for_key.second.end()));
}
tasks_pending_for_key_.clear();
while (!tasks_pending_.empty()) {
base::OnceClosure request_task = std::move(tasks_pending_.front());
tasks_pending_.pop_front();
std::move(request_task).Run();
}
DCHECK(tasks_pending_for_key_.empty());
finished_fetching_all_cookies_ = true;
keys_loaded_.clear();
}
void CookieMonster::EnsureCookiesMapIsValid() {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
// Iterate through all the of the cookies, grouped by host.
for (auto next = cookies_.begin(); next != cookies_.end();) {
auto cur_range_begin = next;
const std::string key = cur_range_begin->first; // Keep a copy.
auto cur_range_end = cookies_.upper_bound(key);
next = cur_range_end;
// Ensure no equivalent cookies for this host.
TrimDuplicateCookiesForKey(key, cur_range_begin, cur_range_end,
std::nullopt);
}
for (auto cookie_partition_it = partitioned_cookies_.begin();
cookie_partition_it != partitioned_cookies_.end();) {
auto cur_cookie_partition_it = cookie_partition_it;
++cookie_partition_it;
// Iterate through the cookies in this partition, grouped by host.
CookieMap* cookie_partition = cur_cookie_partition_it->second.get();
auto prev_range_end = cookie_partition->begin();
while (prev_range_end != cookie_partition->end()) {
auto cur_range_begin = prev_range_end;
const std::string key = cur_range_begin->first; // Keep a copy.
auto cur_range_end = cookie_partition->upper_bound(key);
prev_range_end = cur_range_end;
// Ensure no equivalent cookies for this host and cookie partition key.
TrimDuplicateCookiesForKey(key, cur_range_begin, cur_range_end,
std::make_optional(cur_cookie_partition_it));
}
}
}
// Our strategy to find duplicates is:
// (1) Build a map from cookie unique key to
// {list of cookies with this signature, sorted by creation time}.
// (2) For each list with more than 1 entry, keep the cookie having the
// most recent creation time, and delete the others.
//
void CookieMonster::TrimDuplicateCookiesForKey(
const std::string& key,
CookieMap::iterator begin,
CookieMap::iterator end,
std::optional<PartitionedCookieMap::iterator> cookie_partition_it) {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
// Set of cookies ordered by creation time.
typedef std::multiset<CookieMap::iterator, OrderByCreationTimeDesc> CookieSet;
// Helper map we populate to find the duplicates.
std::map<UniqueCookieKey, CookieSet> equivalent_cookies;
// The number of duplicate cookies that have been found.
int num_duplicates = 0;
// Iterate through all of the cookies in our range, and insert them into
// the equivalence map.
for (auto it = begin; it != end; ++it) {
DCHECK_EQ(key, it->first);
CanonicalCookie* cookie = it->second.get();
UniqueCookieKey signature(cookie->UniqueKey());
CookieSet& set = equivalent_cookies[signature];
// We found a duplicate!
if (!set.empty()) {
num_duplicates++;
}
// We save the iterator into |cookies_| rather than the actual cookie
// pointer, since we may need to delete it later.
set.insert(it);
}
// If there were no duplicates, we are done!
if (num_duplicates == 0) {
return;
}
// Make sure we find everything below that we did above.
int num_duplicates_found = 0;
// Otherwise, delete all the duplicate cookies, both from our in-memory
// store and from the backing store.
for (auto& equivalent_cookie : equivalent_cookies) {
const UniqueCookieKey& signature = equivalent_cookie.first;
CookieSet& dupes = equivalent_cookie.second;
if (dupes.size() <= 1) {
continue; // This cookiename/path has no duplicates.
}
num_duplicates_found += dupes.size() - 1;
// Since |dupes| is sorted by creation time (descending), the first cookie
// is the most recent one (or tied for it), so we will keep it. The rest are
// duplicates.
dupes.erase(dupes.begin());
// TODO(crbug.com/40188414) Include cookie partition key in this log
// statement as well if needed.
// TODO(crbug.com/40165805): Include source scheme and source port.
LOG(ERROR) << base::StringPrintf(
"Found %d duplicate cookies for key='%s', "
"with {name='%s', domain='%s', path='%s'}",
static_cast<int>(dupes.size()), key.c_str(), signature.name().c_str(),
signature.domain().c_str(), signature.path().c_str());
// Remove all the cookies identified by |dupes|. It is valid to delete our
// list of iterators one at a time, since |cookies_| is a multimap (they
// don't invalidate existing iterators following deletion).
for (const CookieMap::iterator& dupe : dupes) {
if (cookie_partition_it) {
InternalDeletePartitionedCookie(
cookie_partition_it.value(), dupe, true,
DELETE_COOKIE_DUPLICATE_IN_BACKING_STORE);
} else {
InternalDeleteCookie(dupe, true,
DELETE_COOKIE_DUPLICATE_IN_BACKING_STORE);
}
}
}
CHECK_EQ(num_duplicates, num_duplicates_found);
}
std::vector<CanonicalCookie*>
CookieMonster::FindCookiesForRegistryControlledHost(
const GURL& url,
CookieMap* cookie_map,
CookieMonster::PartitionedCookieMap::iterator* partition_it) {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
if (!cookie_map)
cookie_map = &cookies_;
Time current_time = Time::Now();
// Retrieve all cookies for a given key
const std::string key(GetKey(url.host_piece()));
std::vector<CanonicalCookie*> cookies;
for (CookieMapItPair its = cookie_map->equal_range(key);
its.first != its.second;) {
auto curit = its.first;
CanonicalCookie* cc = curit->second.get();
++its.first;
// If the cookie is expired, delete it.
if (cc->IsExpired(current_time)) {
if (cc->IsPartitioned()) {
DCHECK(partition_it);
DCHECK_EQ((*partition_it)->second.get(), cookie_map);
InternalDeletePartitionedCookie(*partition_it, curit, true,
DELETE_COOKIE_EXPIRED);
} else {
InternalDeleteCookie(curit, true, DELETE_COOKIE_EXPIRED);
}
continue;
}
cookies.push_back(cc);
}
return cookies;
}
std::vector<CanonicalCookie*>
CookieMonster::FindPartitionedCookiesForRegistryControlledHost(
const CookiePartitionKey& cookie_partition_key,
const GURL& url) {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
PartitionedCookieMap::iterator it =
partitioned_cookies_.find(cookie_partition_key);
if (it == partitioned_cookies_.end())
return std::vector<CanonicalCookie*>();
return FindCookiesForRegistryControlledHost(url, it->second.get(), &it);
}
void CookieMonster::FilterCookiesWithOptions(
const GURL& url,
const CookieOptions& options,
const CookiePartitionKeyCollection& cookie_partition_key_collection,
std::vector<CanonicalCookie*>& cookie_ptrs,
CookieAccessResultList& included_cookies,
CookieAccessResultList& excluded_cookies) {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
// Probe to save statistics relatively frequently. We do it here rather
// than in the set path as many websites won't set cookies, and we
// want to collect statistics whenever the browser's being used.
Time current_time = Time::Now();
RecordPeriodicStats(current_time);
bool delegate_treats_url_as_trustworthy =
cookie_access_delegate() &&
cookie_access_delegate()->ShouldTreatUrlAsTrustworthy(url);
std::vector<std::pair<CanonicalCookie*, CookieAccessResult>>
cookies_and_access_results;
cookies_and_access_results.reserve(cookie_ptrs.size());
std::set<std::string> origin_cookie_names;
const bool include_unpartitioned_cookies =
IncludeUnpartitionedCookies(cookie_partition_key_collection);
for (CanonicalCookie* cookie_ptr : cookie_ptrs) {
// Filter out cookies that should not be included for a request to the
// given |url|. HTTP only cookies are filtered depending on the passed
// cookie |options|.
CookieAccessResult access_result = cookie_ptr->IncludeForRequestURL(
url, options,
CookieAccessParams{
GetAccessSemanticsForCookie(*cookie_ptr),
GetScopeSemanticsForCookieDomain(cookie_ptr->Domain()),
delegate_treats_url_as_trustworthy});
if (!include_unpartitioned_cookies && !cookie_ptr->IsPartitioned()) {
access_result.status.AddExclusionReason(
CookieInclusionStatus::ExclusionReason::EXCLUDE_ANONYMOUS_CONTEXT);
}
cookies_and_access_results.emplace_back(cookie_ptr, access_result);
// Record the names of all origin cookies that would be included if both
// kEnablePortBoundCookies and kEnableSchemeBoundCookies are enabled.
//
// We DO want to record origin cookies that are being excluded for path
// reasons, so we'll remove any potential path exclusions.
CookieInclusionStatus status_copy = access_result.status;
status_copy.RemoveExclusionReason(
CookieInclusionStatus::ExclusionReason::EXCLUDE_NOT_ON_PATH);
bool exclusion_or_warning =
!status_copy.IsInclude() ||
status_copy.HasWarningReason(
CookieInclusionStatus::WarningReason::WARN_SCHEME_MISMATCH) ||
status_copy.HasWarningReason(
CookieInclusionStatus::WarningReason::WARN_PORT_MISMATCH);
if (!exclusion_or_warning && cookie_ptr->IsHostCookie()) {
origin_cookie_names.insert(cookie_ptr->Name());
}
}
for (auto& cookie_result : cookies_and_access_results) {
CanonicalCookie* cookie_ptr = cookie_result.first;
DCHECK(cookie_ptr);
CookieAccessResult& access_result = cookie_result.second;
// We want to collect these metrics for cookies that would be included
// without considering shadowing domain cookies. Recording them on every
// resource sequest results in unnecessarily large amounts of samples
// and has a non-zero runtime cost, so only collect 1/1000 times.
if (metrics_subsampler_.ShouldSample(kHistogramSampleProbability) &&
access_result.status.IsInclude()) {
int destination_port = url.EffectiveIntPort();
if (IsLocalhost(url)) {
UMA_HISTOGRAM_ENUMERATION(
"Cookie.Port.Read.Localhost.Subsampled",
ReducePortRangeForCookieHistogram(destination_port));
UMA_HISTOGRAM_ENUMERATION(
"Cookie.Port.ReadDiffersFromSet.Localhost.Subsampled",
IsCookieSentToSamePortThatSetIt(url, cookie_ptr->SourcePort(),
cookie_ptr->SourceScheme()));
} else {
UMA_HISTOGRAM_ENUMERATION(
"Cookie.Port.Read.RemoteHost.Subsampled",
ReducePortRangeForCookieHistogram(destination_port));
UMA_HISTOGRAM_ENUMERATION(
"Cookie.Port.ReadDiffersFromSet.RemoteHost.Subsampled",
IsCookieSentToSamePortThatSetIt(url, cookie_ptr->SourcePort(),
cookie_ptr->SourceScheme()));
}
if (cookie_ptr->IsDomainCookie()) {
UMA_HISTOGRAM_ENUMERATION(
"Cookie.Port.ReadDiffersFromSet.DomainSet.Subsampled",
IsCookieSentToSamePortThatSetIt(url, cookie_ptr->SourcePort(),
cookie_ptr->SourceScheme()));
}
}
// Filter out any domain `cookie_ptr` which are shadowing origin cookies.
// Don't apply domain shadowing exclusion/warning reason if `cookie_ptr` is
// already being excluded/warned for scheme matching reasons (Note, domain
// cookies match every port so they'll never get excluded/warned for port
// reasons).
bool scheme_mismatch =
access_result.status.HasExclusionReason(
CookieInclusionStatus::ExclusionReason::EXCLUDE_SCHEME_MISMATCH) ||
access_result.status.HasWarningReason(
CookieInclusionStatus::WarningReason::WARN_SCHEME_MISMATCH);
if (cookie_ptr->IsDomainCookie() && !scheme_mismatch &&
origin_cookie_names.count(cookie_ptr->Name())) {
if (cookie_util::IsSchemeBoundCookiesEnabled()) {
access_result.status.AddExclusionReason(
CookieInclusionStatus::ExclusionReason::EXCLUDE_SHADOWING_DOMAIN);
} else {
access_result.status.AddWarningReason(
CookieInclusionStatus::WarningReason::WARN_SHADOWING_DOMAIN);
}
}
if (!access_result.status.IsInclude()) {
if (options.return_excluded_cookies()) {
excluded_cookies.push_back({*cookie_ptr, access_result});
}
continue;
}
if (options.update_access_time()) {
InternalUpdateCookieAccessTime(*cookie_ptr, current_time);
}
included_cookies.push_back({*cookie_ptr, access_result});
}
}
bool CookieMonster::MaybeDeleteEquivalentCookieAndUpdateStatus(
const std::string& key,
const CanonicalCookie& cookie_being_set,
bool allowed_to_set_secure_cookie,
bool skip_httponly,
bool already_expired,
base::Time& creation_date_to_inherit,
CookieInclusionStatus& status,
std::optional<PartitionedCookieMap::iterator> cookie_partition_it) {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
DCHECK(!status.HasExclusionReason(
CookieInclusionStatus::ExclusionReason::EXCLUDE_OVERWRITE_SECURE));
DCHECK(!status.HasExclusionReason(
CookieInclusionStatus::ExclusionReason::EXCLUDE_OVERWRITE_HTTP_ONLY));
CookieMap* cookie_map = &cookies_;
if (cookie_partition_it) {
cookie_map = cookie_partition_it.value()->second.get();
}
bool found_equivalent_cookie = false;
CookieMap::iterator deletion_candidate_it = cookie_map->end();
CanonicalCookie* skipped_secure_cookie = nullptr;
// Check every cookie matching this domain key for equivalence.
CookieMapItPair range_its = cookie_map->equal_range(key);
const auto cookie_being_set_key = cookie_being_set.RefUniqueKey();
const auto cookie_being_set_scope_semantics =
GetScopeSemanticsForCookieDomain(cookie_being_set.Domain());
for (auto cur_it = range_its.first; cur_it != range_its.second; ++cur_it) {
CanonicalCookie* cur_existing_cookie = cur_it->second.get();
// Evaluate "Leave Secure Cookies Alone":
// If the cookie is being set from an insecure source, then if an
// "equivalent" Secure cookie already exists, then the cookie should *not*
// be updated.
//
// "Equivalent" means they are the same by
// IsEquivalentForSecureCookieMatching(). See the comment there for
// details. (Note this is not a symmetric comparison.) This notion of
// equivalence is slightly more inclusive than the usual IsEquivalent() one.
//
// See: https://tools.ietf.org/html/draft-ietf-httpbis-cookie-alone
if (cur_existing_cookie->SecureAttribute() &&
!allowed_to_set_secure_cookie &&
cookie_being_set.IsEquivalentForSecureCookieMatching(
*cur_existing_cookie)) {
// Hold onto this for additional Netlogging later if we end up preserving
// a would-have-been-deleted cookie because of this.
skipped_secure_cookie = cur_existing_cookie;
net_log_.AddEvent(NetLogEventType::COOKIE_STORE_COOKIE_REJECTED_SECURE,
[&](NetLogCaptureMode capture_mode) {
return NetLogCookieMonsterCookieRejectedSecure(
skipped_secure_cookie, &cookie_being_set,
capture_mode);
});
status.AddExclusionReason(
CookieInclusionStatus::ExclusionReason::EXCLUDE_OVERWRITE_SECURE);
}
// If cookie's domain is in legacy mode, check to make sure we are not
// setting an aliasing cookie.
if (cookie_being_set_key == cur_existing_cookie->RefUniqueKey() ||
(cookie_being_set_scope_semantics == CookieScopeSemantics::LEGACY &&
cookie_being_set.LegacyUniqueKey() ==
cur_existing_cookie->LegacyUniqueKey())) {
// We should never have more than one equivalent cookie, since they should
// overwrite each other.
CHECK(!found_equivalent_cookie)
<< "Duplicate equivalent cookies found, cookie store is corrupted.";
DCHECK(deletion_candidate_it == cookie_map->end());
found_equivalent_cookie = true;
// The |cookie_being_set| is rejected for trying to overwrite an httponly
// cookie when it should not be able to.
if (skip_httponly && cur_existing_cookie->IsHttpOnly()) {
net_log_.AddEvent(
NetLogEventType::COOKIE_STORE_COOKIE_REJECTED_HTTPONLY,
[&](NetLogCaptureMode capture_mode) {
return NetLogCookieMonsterCookieRejectedHttponly(
cur_existing_cookie, &cookie_being_set, capture_mode);
});
status.AddExclusionReason(CookieInclusionStatus::ExclusionReason::
EXCLUDE_OVERWRITE_HTTP_ONLY);
} else {
deletion_candidate_it = cur_it;
}
}
}
bool is_web_observable_change = true;
if (deletion_candidate_it != cookie_map->end()) {
CanonicalCookie* deletion_candidate = deletion_candidate_it->second.get();
if (deletion_candidate->Value() == cookie_being_set.Value()) {
creation_date_to_inherit = deletion_candidate->CreationDate();
}
is_web_observable_change =
!deletion_candidate->IsWebEquivalentTo(cookie_being_set);
if (status.IsInclude()) {
if (cookie_being_set.IsPartitioned()) {
InternalDeletePartitionedCookie(
cookie_partition_it.value(), deletion_candidate_it,
true /* sync_to_store */,
already_expired ? DELETE_COOKIE_EXPIRED_OVERWRITE
: DELETE_COOKIE_OVERWRITE);
} else {
InternalDeleteCookie(deletion_candidate_it, true /* sync_to_store */,
already_expired ? DELETE_COOKIE_EXPIRED_OVERWRITE
: DELETE_COOKIE_OVERWRITE);
}
} else if (status.HasExclusionReason(
CookieInclusionStatus::ExclusionReason::
EXCLUDE_OVERWRITE_SECURE)) {
// Log that we preserved a cookie that would have been deleted due to
// Leave Secure Cookies Alone. This arbitrarily only logs the last
// |skipped_secure_cookie| that we were left with after the for loop, even
// if there were multiple matching Secure cookies that were left alone.
DCHECK(skipped_secure_cookie);
net_log_.AddEvent(
NetLogEventType::COOKIE_STORE_COOKIE_PRESERVED_SKIPPED_SECURE,
[&](NetLogCaptureMode capture_mode) {
return NetLogCookieMonsterCookiePreservedSkippedSecure(
skipped_secure_cookie, deletion_candidate, &cookie_being_set,
capture_mode);
});
}
}
return is_web_observable_change;
}
CookieMonster::CookieMap::iterator CookieMonster::InternalInsertCookie(
const std::string& key,
std::unique_ptr<CanonicalCookie> cc,
bool sync_to_store,
const CookieAccessResult& access_result,
bool dispatch_change,
bool is_web_observable_change) {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
DCHECK(cc);
CanonicalCookie* cc_ptr = cc.get();
net_log_.AddEvent(NetLogEventType::COOKIE_STORE_COOKIE_ADDED,
[&](NetLogCaptureMode capture_mode) {
return NetLogCookieMonsterCookieAdded(
cc.get(), sync_to_store, capture_mode);
});
if (ShouldUpdatePersistentStore(*cc_ptr) && sync_to_store) {
store_->AddCookie(*cc_ptr);
}
auto inserted = cookies_.insert(CookieMap::value_type(key, std::move(cc)));
if (metrics_subsampler_.ShouldSample(kHistogramSampleProbability)) {
LogStoredCookieToUMA(*cc_ptr, access_result);
}
DCHECK(access_result.status.IsInclude());
if (dispatch_change) {
change_dispatcher_.DispatchChange(
CookieChangeInfo(*cc_ptr, access_result,
is_web_observable_change
? CookieChangeCause::INSERTED
: CookieChangeCause::INSERTED_NO_CHANGE_OVERWRITE),
true);
}
// If this is the first cookie in |cookies_| with this key, increment the
// |num_keys_| counter.
bool different_prev =
inserted == cookies_.begin() || std::prev(inserted)->first != key;
// According to std::multiqueue documentation:
// "If the container has elements with equivalent key, inserts at the upper
// bound of that range. (since C++11)"
// This means that "inserted" iterator either points to the last element in
// the map, or the element succeeding it has to have different key.
DCHECK(std::next(inserted) == cookies_.end() ||
std::next(inserted)->first != key);
if (different_prev)
++num_keys_;
return inserted;
}
bool CookieMonster::ShouldUpdatePersistentStore(CanonicalCookie& cc) {
return (cc.IsPersistent() || persist_session_cookies_) && store_.get();
}
CookieMonster::PartitionedCookieMapIterators
CookieMonster::InternalInsertPartitionedCookie(
std::string key,
std::unique_ptr<CanonicalCookie> cc,
bool sync_to_store,
const CookieAccessResult& access_result,
bool dispatch_change,
bool is_web_observable_change) {
DCHECK(cc);
DCHECK(cc->IsPartitioned());
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
CanonicalCookie* cc_ptr = cc.get();
net_log_.AddEvent(NetLogEventType::COOKIE_STORE_COOKIE_ADDED,
[&](NetLogCaptureMode capture_mode) {
return NetLogCookieMonsterCookieAdded(
cc.get(), sync_to_store, capture_mode);
});
if (ShouldUpdatePersistentStore(*cc_ptr) && sync_to_store) {
store_->AddCookie(*cc_ptr);
}
CookiePartitionKey partition_key(cc->PartitionKey().value());
size_t n_bytes = NameValueSizeBytes(*cc);
num_partitioned_cookies_bytes_ += n_bytes;
bytes_per_cookie_partition_[partition_key] += n_bytes;
if (partition_key.nonce()) {
num_nonced_partitioned_cookie_bytes_ += n_bytes;
}
PartitionedCookieMap::iterator partition_it =
partitioned_cookies_.find(partition_key);
if (partition_it == partitioned_cookies_.end()) {
partition_it =
partitioned_cookies_
.insert(PartitionedCookieMap::value_type(
std::move(partition_key), std::make_unique<CookieMap>()))
.first;
}
CookieMap::iterator cookie_it = partition_it->second->insert(
CookieMap::value_type(std::move(key), std::move(cc)));
++num_partitioned_cookies_;
if (partition_it->first.nonce()) {
++num_nonced_partitioned_cookies_;
}
CHECK_GE(num_partitioned_cookies_, num_nonced_partitioned_cookies_);
if (metrics_subsampler_.ShouldSample(kHistogramSampleProbability)) {
LogStoredCookieToUMA(*cc_ptr, access_result);
}
DCHECK(access_result.status.IsInclude());
if (dispatch_change) {
change_dispatcher_.DispatchChange(
CookieChangeInfo(*cc_ptr, access_result,
is_web_observable_change
? CookieChangeCause::INSERTED
: CookieChangeCause::INSERTED_NO_CHANGE_OVERWRITE),
true);
}
return std::pair(partition_it, cookie_it);
}
void CookieMonster::SetCanonicalCookie(
std::unique_ptr<CanonicalCookie> cc,
const GURL& source_url,
const CookieOptions& options,
SetCookiesCallback callback,
std::optional<CookieAccessResult> cookie_access_result) {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
bool collect_metrics =
metrics_subsampler_.ShouldSample(kHistogramSampleProbability);
// TODO(crbug.com/40281870): Fix macos specific issue with CHECK_IS_TEST
// crashing network service process.
#if !BUILDFLAG(IS_MAC)
// Only tests should be adding new cookies with source type kUnknown. If this
// line causes a fatal track down the callsite and have it correctly set the
// source type to kOther (or kHTTP/kScript where applicable). See
// CookieSourceType in net/cookies/cookie_constants.h for more.
if (cc->SourceType() == CookieSourceType::kUnknown) {
CHECK_IS_TEST();
}
#endif
bool delegate_treats_url_as_trustworthy =
cookie_access_delegate() &&
cookie_access_delegate()->ShouldTreatUrlAsTrustworthy(source_url);
CheckAndActivateLegacyScopeBehavior(cc->Domain());
CookieAccessResult access_result = cc->IsSetPermittedInContext(
source_url, options,
CookieAccessParams(GetAccessSemanticsForCookie(*cc),
GetScopeSemanticsForCookieDomain(cc->Domain()),
delegate_treats_url_as_trustworthy),
cookieable_schemes_, cookie_access_result);
const std::string key(GetKey(cc->Domain()));
base::Time creation_date = cc->CreationDate();
if (creation_date.is_null()) {
creation_date = Time::Now();
cc->SetCreationDate(creation_date);
}
bool already_expired = cc->IsExpired(creation_date);
base::Time creation_date_to_inherit;
std::optional<PartitionedCookieMap::iterator> cookie_partition_it;
bool should_try_to_delete_duplicates = true;
if (cc->IsPartitioned()) {
auto it = partitioned_cookies_.find(cc->PartitionKey().value());
if (it == partitioned_cookies_.end()) {
// This is the first cookie in its partition, so it won't have any
// duplicates.
should_try_to_delete_duplicates = false;
} else {
cookie_partition_it = std::make_optional(it);
}
}
bool is_web_observable_change = true;
// Iterates through existing cookies for the same eTLD+1, and potentially
// deletes an existing cookie, so any ExclusionReasons in |status| that would
// prevent such deletion should be finalized beforehand.
if (should_try_to_delete_duplicates) {
is_web_observable_change = MaybeDeleteEquivalentCookieAndUpdateStatus(
key, *cc, access_result.is_allowed_to_access_secure_cookies,
options.exclude_httponly(), already_expired, creation_date_to_inherit,
access_result.status, cookie_partition_it);
}
if (access_result.status.HasExclusionReason(
CookieInclusionStatus::ExclusionReason::EXCLUDE_OVERWRITE_SECURE) ||
access_result.status.HasExclusionReason(
CookieInclusionStatus::ExclusionReason::
EXCLUDE_OVERWRITE_HTTP_ONLY)) {
DVLOG(net::cookie_util::kVlogSetCookies)
<< "SetCookie() not clobbering httponly cookie or secure cookie for "
"insecure scheme";
}
if (access_result.status.IsInclude()) {
DVLOG(net::cookie_util::kVlogSetCookies)
<< "SetCookie() key: " << key << " cc: " << cc->DebugString();
if (cc->IsEffectivelySameSiteNone() && collect_metrics) {
size_t cookie_size = NameValueSizeBytes(*cc);
base::UmaHistogramCounts10000("Cookie.SameSiteNoneSizeBytes.Subsampled",
cookie_size);
if (cc->IsPartitioned()) {
base::UmaHistogramCounts10000(
"Cookie.SameSiteNoneSizeBytes.Partitioned.Subsampled", cookie_size);
} else {
base::UmaHistogramCounts10000(
"Cookie.SameSiteNoneSizeBytes.Unpartitioned.Subsampled",
cookie_size);
}
}
std::optional<CookiePartitionKey> cookie_partition_key = cc->PartitionKey();
CHECK_EQ(cc->IsPartitioned(), cookie_partition_key.has_value());
// Realize that we might be setting an expired cookie, and the only point
// was to delete the cookie which we've already done.
if (!already_expired) {
if (collect_metrics) {
RecordPersistanceHistograms(*cc, creation_date);
base::UmaHistogramBoolean("Cookie.DomainSet.Subsampled",
cc->IsDomainCookie());
}
if (!creation_date_to_inherit.is_null()) {
cc->SetCreationDate(creation_date_to_inherit);
}
if (cookie_partition_key.has_value()) {
InternalInsertPartitionedCookie(key, std::move(cc), true, access_result,
/*dispatch_change=*/true,
is_web_observable_change);
} else {
InternalInsertCookie(key, std::move(cc), true, access_result,
/*dispatch_change=*/true,
is_web_observable_change);
}
} else {
DVLOG(net::cookie_util::kVlogSetCookies)
<< "SetCookie() not storing already expired cookie.";
}
// We assume that hopefully setting a cookie will be less common than
// querying a cookie. Since setting a cookie can put us over our limits,
// make sure that we garbage collect... We can also make the assumption
// that if a cookie was set, in the common case it will be used soon after,
// and we will purge the expired cookies in GetCookies().
if (cookie_partition_key.has_value()) {
GarbageCollectPartitionedCookies(creation_date,
cookie_partition_key.value(), key);
} else {
GarbageCollect(creation_date, key);
}
if (collect_metrics) {
if (IsLocalhost(source_url)) {
base::UmaHistogramEnumeration(
"Cookie.Port.Set.Localhost.Subsampled",
ReducePortRangeForCookieHistogram(source_url.EffectiveIntPort()));
} else {
base::UmaHistogramEnumeration(
"Cookie.Port.Set.RemoteHost.Subsampled",
ReducePortRangeForCookieHistogram(source_url.EffectiveIntPort()));
}
base::UmaHistogramEnumeration("Cookie.CookieSourceSchemeName.Subsampled",
GetSchemeNameEnum(source_url));
}
} else {
// If the cookie would be excluded, don't bother warning about the 3p cookie
// phaseout.
access_result.status.RemoveWarningReason(
net::CookieInclusionStatus::WarningReason::WARN_THIRD_PARTY_PHASEOUT);
}
// TODO(chlily): Log metrics.
MaybeRunCookieCallback(std::move(callback), access_result);
}
void CookieMonster::SetAllCookies(CookieList list,
SetCookiesCallback callback) {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
// Nuke the existing store.
while (!cookies_.empty()) {
// TODO(rdsmith): The CANONICAL is a lie.
InternalDeleteCookie(cookies_.begin(), true, DELETE_COOKIE_EXPLICIT);
}
// Set all passed in cookies.
for (const auto& cookie : list) {
const std::string key(GetKey(cookie.Domain()));
Time creation_time = cookie.CreationDate();
if (cookie.IsExpired(creation_time))
continue;
if (metrics_subsampler_.ShouldSample(kHistogramSampleProbability)) {
RecordPersistanceHistograms(cookie, creation_time);
}
CookieAccessResult access_result;
access_result.access_semantics = GetAccessSemanticsForCookie(cookie);
if (cookie.IsPartitioned()) {
InternalInsertPartitionedCookie(
key, std::make_unique<CanonicalCookie>(cookie), true, access_result);
GarbageCollectPartitionedCookies(creation_time,
cookie.PartitionKey().value(), key);
} else {
InternalInsertCookie(key, std::make_unique<CanonicalCookie>(cookie), true,
access_result);
GarbageCollect(creation_time, key);
}
}
// TODO(rdsmith): If this function always returns the same value, it
// shouldn't have a return value. But it should also be deleted (see
// https://codereview.chromium.org/2882063002/#msg64), which would
// solve the return value problem.
MaybeRunCookieCallback(std::move(callback), CookieAccessResult());
}
void CookieMonster::SetUnsafeCanonicalCookieForTest(
std::unique_ptr<CanonicalCookie> cc,
SetCookiesCallback callback) {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
CookieAccessResult access_result;
const std::string key(GetKey(cc->Domain()));
base::Time creation_date = cc->CreationDate();
if (creation_date.is_null()) {
creation_date = Time::Now();
cc->SetCreationDate(creation_date);
}
std::optional<CookiePartitionKey> cookie_partition_key = cc->PartitionKey();
CHECK_EQ(cc->IsPartitioned(), cookie_partition_key.has_value());
// Set cookie based on if its partitioned or not.
if (cookie_partition_key.has_value()) {
InternalInsertPartitionedCookie(key, std::move(cc), true, access_result);
} else {
InternalInsertCookie(key, std::move(cc), true, access_result);
}
MaybeRunCookieCallback(std::move(callback), access_result);
}
void CookieMonster::InternalUpdateCookieAccessTime(CanonicalCookie& cc,
const Time& current) {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
// Based off the Mozilla code. When a cookie has been accessed recently,
// don't bother updating its access time again. This reduces the number of
// updates we do during pageload, which in turn reduces the chance our storage
// backend will hit its batch thresholds and be forced to update.
if ((current - cc.LastAccessDate()) < last_access_threshold_) {
return;
}
cc.SetLastAccessDate(current);
if (ShouldUpdatePersistentStore(cc))
store_->UpdateCookieAccessTime(cc);
}
// InternalDeleteCookies must not invalidate iterators other than the one being
// deleted.
void CookieMonster::InternalDeleteCookie(CookieMap::iterator it,
bool sync_to_store,
DeletionCause deletion_cause) {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
// Ideally, this would be asserted up where we define kChangeCauseMapping,
// but DeletionCause's visibility (or lack thereof) forces us to make
// this check here.
static_assert(std::size(kChangeCauseMapping) == DELETE_COOKIE_LAST_ENTRY + 1,
"kChangeCauseMapping size should match DeletionCause size");
CanonicalCookie* cc = it->second.get();
DCHECK(cc);
DVLOG(net::cookie_util::kVlogSetCookies)
<< "InternalDeleteCookie()"
<< ", cause:" << deletion_cause << ", cc: " << cc->DebugString();
ChangeCausePair mapping = kChangeCauseMapping[deletion_cause];
if (deletion_cause != DELETE_COOKIE_DONT_RECORD) {
net_log_.AddEvent(NetLogEventType::COOKIE_STORE_COOKIE_DELETED,
[&](NetLogCaptureMode capture_mode) {
return NetLogCookieMonsterCookieDeleted(
cc, mapping.cause, sync_to_store, capture_mode);
});
}
if (ShouldUpdatePersistentStore(*cc) && sync_to_store) {
store_->DeleteCookie(*cc);
}
change_dispatcher_.DispatchChange(
CookieChangeInfo(
*cc,
CookieAccessResult(CookieEffectiveSameSite::UNDEFINED,
CookieInclusionStatus(),
GetAccessSemanticsForCookie(*cc),
GetScopeSemanticsForCookieDomain(cc->Domain()),
true /* is_allowed_to_access_secure_cookies */),
mapping.cause),
mapping.notify);
// If this is the last cookie in |cookies_| with this key, decrement the
// |num_keys_| counter.
bool different_prev =
it == cookies_.begin() || std::prev(it)->first != it->first;
bool different_next =
std::next(it) == cookies_.end() || std::next(it)->first != it->first;
if (different_prev && different_next)
--num_keys_;
DCHECK(cookies_.find(it->first) != cookies_.end())
<< "Called erase with an iterator not in the cookie map";
cookies_.erase(it);
}
void CookieMonster::InternalDeletePartitionedCookie(
PartitionedCookieMap::iterator partition_it,
CookieMap::iterator cookie_it,
bool sync_to_store,
DeletionCause deletion_cause) {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
// Ideally, this would be asserted up where we define kChangeCauseMapping,
// but DeletionCause's visibility (or lack thereof) forces us to make
// this check here.
static_assert(std::size(kChangeCauseMapping) == DELETE_COOKIE_LAST_ENTRY + 1,
"kChangeCauseMapping size should match DeletionCause size");
CanonicalCookie* cc = cookie_it->second.get();
DCHECK(cc);
DCHECK(cc->IsPartitioned());
DVLOG(net::cookie_util::kVlogSetCookies)
<< "InternalDeletePartitionedCookie()"
<< ", cause:" << deletion_cause << ", cc: " << cc->DebugString();
ChangeCausePair mapping = kChangeCauseMapping[deletion_cause];
if (deletion_cause != DELETE_COOKIE_DONT_RECORD) {
net_log_.AddEvent(NetLogEventType::COOKIE_STORE_COOKIE_DELETED,
[&](NetLogCaptureMode capture_mode) {
return NetLogCookieMonsterCookieDeleted(
cc, mapping.cause, sync_to_store, capture_mode);
});
}
if (ShouldUpdatePersistentStore(*cc) && sync_to_store) {
store_->DeleteCookie(*cc);
}
change_dispatcher_.DispatchChange(
CookieChangeInfo(
*cc,
CookieAccessResult(CookieEffectiveSameSite::UNDEFINED,
CookieInclusionStatus(),
GetAccessSemanticsForCookie(*cc),
GetScopeSemanticsForCookieDomain(cc->Domain()),
true /* is_allowed_to_access_secure_cookies */),
mapping.cause),
mapping.notify);
size_t n_bytes = NameValueSizeBytes(*cc);
num_partitioned_cookies_bytes_ -= n_bytes;
bytes_per_cookie_partition_[*cc->PartitionKey()] -= n_bytes;
if (CookiePartitionKey::HasNonce(cc->PartitionKey())) {
num_nonced_partitioned_cookie_bytes_ -= n_bytes;
}
DCHECK(partition_it->second->find(cookie_it->first) !=
partition_it->second->end())
<< "Called erase with an iterator not in this partitioned cookie map";
partition_it->second->erase(cookie_it);
--num_partitioned_cookies_;
if (partition_it->first.nonce()) {
--num_nonced_partitioned_cookies_;
}
CHECK_GE(num_partitioned_cookies_, num_nonced_partitioned_cookies_);
if (partition_it->second->empty())
partitioned_cookies_.erase(partition_it);
}
// Domain expiry behavior is unchanged by key/expiry scheme (the
// meaning of the key is different, but that's not visible to this routine).
size_t CookieMonster::GarbageCollect(const Time& current,
const std::string& key) {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
size_t num_deleted = 0;
const Time safe_date(Time::Now() - base::Days(kSafeFromGlobalPurgeDays));
// For the domain check if legacy mode is active or not.
const bool obc_behavior_enabled =
cookie_util::IsOriginBoundCookiesPartiallyEnabled() &&
CheckAndActivateLegacyScopeBehavior(key) != CookieScopeSemantics::LEGACY;
// Collect garbage for this key, minding cookie priorities.
if (cookies_.count(key) > kDomainMaxCookies) {
DVLOG(net::cookie_util::kVlogGarbageCollection)
<< "GarbageCollect() key: " << key;
CookieItVector* cookie_its;
CookieItVector non_expired_cookie_its;
cookie_its = &non_expired_cookie_its;
num_deleted +=
GarbageCollectExpired(current, cookies_.equal_range(key), cookie_its);
if (cookie_its->size() > kDomainMaxCookies) {
DVLOG(net::cookie_util::kVlogGarbageCollection)
<< "Deep Garbage Collect domain.";
if (domain_purged_keys_.size() < kMaxDomainPurgedKeys)
domain_purged_keys_.insert(key);
size_t purge_goal =
cookie_its->size() - (kDomainMaxCookies - kDomainPurgeCookies);
DCHECK(purge_goal > kDomainPurgeCookies);
// Sort the cookies by access date, from least-recent to most-recent.
std::sort(cookie_its->begin(), cookie_its->end(), LRACookieSorter);
CookieItList cookie_it_list;
if (obc_behavior_enabled) {
cookie_it_list = CookieItList(cookie_its->begin(), cookie_its->end());
}
// Remove all but the kDomainCookiesQuotaLow most-recently accessed
// cookies with low-priority. Then, if cookies still need to be removed,
// bump the quota and remove low- and medium-priority. Then, if cookies
// _still_ need to be removed, bump the quota and remove cookies with
// any priority.
//
// 1. Low-priority non-secure cookies.
// 2. Low-priority secure cookies.
// 3. Medium-priority non-secure cookies.
// 4. High-priority non-secure cookies.
// 5. Medium-priority secure cookies.
// 6. High-priority secure cookies.
constexpr struct {
CookiePriority priority;
bool protect_secure_cookies;
} kPurgeRounds[] = {
// 1. Low-priority non-secure cookies.
{COOKIE_PRIORITY_LOW, true},
// 2. Low-priority secure cookies.
{COOKIE_PRIORITY_LOW, false},
// 3. Medium-priority non-secure cookies.
{COOKIE_PRIORITY_MEDIUM, true},
// 4. High-priority non-secure cookies.
{COOKIE_PRIORITY_HIGH, true},
// 5. Medium-priority secure cookies.
{COOKIE_PRIORITY_MEDIUM, false},
// 6. High-priority secure cookies.
{COOKIE_PRIORITY_HIGH, false},
};
size_t quota = 0;
for (const auto& purge_round : kPurgeRounds) {
// Adjust quota according to the priority of cookies. Each round should
// protect certain number of cookies in order to avoid starvation.
// For example, when each round starts to remove cookies, the number of
// cookies of that priority are counted and a decision whether they
// should be deleted or not is made. If yes, some number of cookies of
// that priority are deleted considering the quota.
switch (purge_round.priority) {
case COOKIE_PRIORITY_LOW:
quota = kDomainCookiesQuotaLow;
break;
case COOKIE_PRIORITY_MEDIUM:
quota = kDomainCookiesQuotaMedium;
break;
case COOKIE_PRIORITY_HIGH:
quota = kDomainCookiesQuotaHigh;
break;
}
size_t just_deleted = 0u;
// Purge up to |purge_goal| for all cookies at the given priority. This
// path will be taken only if the initial non-secure purge did not evict
// enough cookies.
if (purge_goal > 0) {
if (obc_behavior_enabled) {
just_deleted = PurgeLeastRecentMatchesForOBC(
cookie_it_list, purge_round.priority, quota, purge_goal,
!purge_round.protect_secure_cookies);
} else {
just_deleted = PurgeLeastRecentMatches(
*cookie_its, purge_round.priority, quota, purge_goal,
purge_round.protect_secure_cookies);
}
DCHECK_LE(just_deleted, purge_goal);
purge_goal -= just_deleted;
num_deleted += just_deleted;
}
}
DCHECK_EQ(0u, purge_goal);
}
}
// Collect garbage for everything. With firefox style we want to preserve
// cookies accessed in kSafeFromGlobalPurgeDays, otherwise evict.
if (cookies_.size() > kMaxCookies && earliest_access_time_ < safe_date) {
DVLOG(net::cookie_util::kVlogGarbageCollection)
<< "GarbageCollect() everything";
CookieItVector cookie_its;
num_deleted += GarbageCollectExpired(
current, CookieMapItPair(cookies_.begin(), cookies_.end()),
&cookie_its);
if (cookie_its.size() > kMaxCookies) {
DVLOG(net::cookie_util::kVlogGarbageCollection)
<< "Deep Garbage Collect everything.";
size_t purge_goal = cookie_its.size() - (kMaxCookies - kPurgeCookies);
DCHECK(purge_goal > kPurgeCookies);
CookieItVector secure_cookie_its;
CookieItVector non_secure_cookie_its;
SplitCookieVectorIntoSecureAndNonSecure(cookie_its, &secure_cookie_its,
&non_secure_cookie_its);
size_t non_secure_purge_goal =
std::min<size_t>(purge_goal, non_secure_cookie_its.size());
base::Time earliest_non_secure_access_time;
size_t just_deleted = GarbageCollectLeastRecentlyAccessed(
current, safe_date, non_secure_purge_goal,
std::move(non_secure_cookie_its), earliest_non_secure_access_time);
num_deleted += just_deleted;
if (secure_cookie_its.size() == 0) {
// This case is unlikely, but should still update
// |earliest_access_time_| if only have non-secure cookies.
earliest_access_time_ = earliest_non_secure_access_time;
// Garbage collection can't delete all cookies.
DCHECK(!earliest_access_time_.is_null());
} else if (just_deleted < purge_goal) {
size_t secure_purge_goal = std::min<size_t>(purge_goal - just_deleted,
secure_cookie_its.size());
base::Time earliest_secure_access_time;
num_deleted += GarbageCollectLeastRecentlyAccessed(
current, safe_date, secure_purge_goal, std::move(secure_cookie_its),
earliest_secure_access_time);
if (!earliest_non_secure_access_time.is_null() &&
earliest_non_secure_access_time < earliest_secure_access_time) {
earliest_access_time_ = earliest_non_secure_access_time;
} else {
earliest_access_time_ = earliest_secure_access_time;
}
// Garbage collection can't delete all cookies.
DCHECK(!earliest_access_time_.is_null());
}
// If there are secure cookies, but deleting non-secure cookies was enough
// to meet the purge goal, secure cookies are never examined, so
// |earliest_access_time_| can't be determined. Leaving it alone will mean
// it's no later than the real earliest last access time, so this won't
// lead to any problems.
}
}
return num_deleted;
}
size_t CookieMonster::GarbageCollectPartitionedCookies(
const base::Time& current,
const CookiePartitionKey& cookie_partition_key,
const std::string& key) {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
size_t num_deleted = 0;
PartitionedCookieMap::iterator cookie_partition_it =
partitioned_cookies_.find(cookie_partition_key);
if (cookie_partition_it == partitioned_cookies_.end())
return num_deleted;
if (NumBytesInCookieMapForKey(*cookie_partition_it->second.get(), key) >
kPerPartitionDomainMaxCookieBytes ||
cookie_partition_it->second->count(key) > kPerPartitionDomainMaxCookies) {
// TODO(crbug.com/40188414): Log garbage collection for partitioned cookies.
CookieItVector non_expired_cookie_its;
num_deleted += GarbageCollectExpiredPartitionedCookies(
current, cookie_partition_it,
cookie_partition_it->second->equal_range(key), &non_expired_cookie_its);
size_t bytes_used = NumBytesInCookieItVector(non_expired_cookie_its);
if (bytes_used > kPerPartitionDomainMaxCookieBytes ||
non_expired_cookie_its.size() > kPerPartitionDomainMaxCookies) {
// For the domain check if legacy mode is active or not.
const bool obc_behavior_enabled =
cookie_util::IsOriginBoundCookiesPartiallyEnabled() &&
GetScopeSemanticsForCookieDomain(key) != CookieScopeSemantics::LEGACY;
// TODO(crbug.com/40188414): Log deep garbage collection for partitioned
// cookies.
std::sort(non_expired_cookie_its.begin(), non_expired_cookie_its.end(),
LRACookieSorter);
// When OBC behavior is enabled, we need to consider the partitioned
// cookies that are domain cookies first and delete those, and then we
// want to delete host cookies.
if (obc_behavior_enabled) {
CookieItList cookie_it_list = CookieItList(
non_expired_cookie_its.begin(), non_expired_cookie_its.end());
DeletionCookieLists could_be_deleted =
CountCookiesAndGenerateListsForPossibleDeletionPartitionedCookies(
cookie_it_list);
// Delete domain cookies first.
// We have 3 layers of iterators to consider:
// The `could_be_deleted` list's iterator, which points to...
// The `cookies` list's iterator, which points to...
// The CookieMap's iterator which is used to delete the actual cookie
// from the backend. For each cookie deleted all three of these will
// need to erased, in a bottom up approach.
size_t num_cookies_deleted = 0;
for (auto domain_list_it = could_be_deleted.domain_cookies.begin();
domain_list_it != could_be_deleted.domain_cookies.end() &&
(bytes_used > kPerPartitionDomainMaxCookieBytes ||
non_expired_cookie_its.size() - num_cookies_deleted >
kPerPartitionDomainMaxCookies);
++num_cookies_deleted) {
auto cookies_list_it = *domain_list_it;
auto cookie_map_it = *cookies_list_it;
bytes_used -= NameValueSizeBytes(*cookie_map_it->second);
// Delete from the cookie store.
InternalDeletePartitionedCookie(
cookie_partition_it, cookie_map_it, /*sync_to_store=*/true,
DELETE_COOKIE_EVICTED_PER_PARTITION_DOMAIN);
// Delete from `cookie_it_list`.
cookie_it_list.erase(cookies_list_it);
// Delete from `could_be_deleted`.
domain_list_it =
could_be_deleted.domain_cookies.erase(domain_list_it);
++num_deleted;
}
// Now do the same for host cookies.
for (auto host_list_it = could_be_deleted.host_cookies.begin();
host_list_it != could_be_deleted.host_cookies.end() &&
(bytes_used > kPerPartitionDomainMaxCookieBytes ||
non_expired_cookie_its.size() - num_cookies_deleted >
kPerPartitionDomainMaxCookies);
++num_cookies_deleted) {
auto cookies_list_it = *host_list_it;
auto cookie_map_it = *cookies_list_it;
bytes_used -= NameValueSizeBytes(*cookie_map_it->second);
// Delete from the cookie store.
InternalDeletePartitionedCookie(
cookie_partition_it, cookie_map_it, /*sync_to_store=*/true,
DELETE_COOKIE_EVICTED_PER_PARTITION_DOMAIN);
// Delete from `cookie_it_list`.
cookie_it_list.erase(cookies_list_it);
// Delete from `could_be_deleted`.
host_list_it = could_be_deleted.host_cookies.erase(host_list_it);
++num_deleted;
}
} else {
for (size_t i = 0;
bytes_used > kPerPartitionDomainMaxCookieBytes ||
non_expired_cookie_its.size() - i > kPerPartitionDomainMaxCookies;
++i) {
bytes_used -= NameValueSizeBytes(*non_expired_cookie_its[i]->second);
InternalDeletePartitionedCookie(
cookie_partition_it, non_expired_cookie_its[i], true,
DELETE_COOKIE_EVICTED_PER_PARTITION_DOMAIN);
++num_deleted;
}
}
}
}
// TODO(crbug.com/40188414): Enforce global limit on partitioned cookies.
return num_deleted;
}
size_t CookieMonster::PurgeLeastRecentMatches(CookieItVector& cookies,
CookiePriority priority,
size_t to_protect,
size_t purge_goal,
bool protect_secure_cookies) {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
// 1. Count number of the cookies at |priority|
size_t cookies_count_possibly_to_be_deleted = CountCookiesForPossibleDeletion(
priority, cookies, false /* count all cookies */);
// 2. If |cookies_count_possibly_to_be_deleted| at |priority| is less than or
// equal |to_protect|, skip round in order to preserve the quota. This
// involves secure and non-secure cookies at |priority|.
if (cookies_count_possibly_to_be_deleted <= to_protect)
return 0u;
// 3. Calculate number of secure cookies at |priority|
// and number of cookies at |priority| that can possibly be deleted.
// It is guaranteed we do not delete more than |purge_goal| even if
// |cookies_count_possibly_to_be_deleted| is higher.
size_t secure_cookies = 0u;
if (protect_secure_cookies) {
secure_cookies = CountCookiesForPossibleDeletion(
priority, cookies, protect_secure_cookies /* count secure cookies */);
cookies_count_possibly_to_be_deleted -=
std::max(secure_cookies, to_protect);
} else {
cookies_count_possibly_to_be_deleted -= to_protect;
}
size_t removed = 0u;
size_t current = 0u;
while ((removed < purge_goal && current < cookies.size()) &&
cookies_count_possibly_to_be_deleted > 0) {
const CanonicalCookie* current_cookie = cookies.at(current)->second.get();
// Only delete the current cookie if the priority is equal to
// the current level.
if (IsCookieEligibleForEviction(priority, protect_secure_cookies,
current_cookie)) {
InternalDeleteCookie(cookies.at(current), true,
DELETE_COOKIE_EVICTED_DOMAIN);
cookies.erase(cookies.begin() + current);
removed++;
cookies_count_possibly_to_be_deleted--;
} else {
current++;
}
}
return removed;
}
size_t CookieMonster::PurgeLeastRecentMatchesForOBC(
CookieItList& cookies,
CookiePriority priority,
size_t to_protect,
size_t purge_goal,
bool delete_secure_cookies) {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
// 1. Count number of the cookies at `priority`. Includes both secure and
// non-secure cookies.
DeletionCookieLists could_be_deleted;
size_t total_could_be_deleted_for_priority =
CountCookiesAndGenerateListsForPossibleDeletion(
priority, could_be_deleted, cookies, delete_secure_cookies);
// 2. If we have fewer cookies at this priority than we intend to keep/protect
// then just skip this round entirely.
if (total_could_be_deleted_for_priority <= to_protect) {
return 0u;
}
// 3. Calculate the number of cookies that could be deleted for this round.
// This number is the lesser of either: The number of cookies that exist at
// this {priority, secureness} tuple, or the number of cookies at this
// priority less the number to protect. We won't exceed the `purge_goal` even
// if this resulting value is larger.
size_t total_deletable = could_be_deleted.host_cookies.size() +
could_be_deleted.domain_cookies.size();
size_t max_cookies_to_delete_this_round = std::min(
total_deletable, total_could_be_deleted_for_priority - to_protect);
// 4. Remove domain cookies. As per "Origin-Bound Cookies" behavior, domain
// cookies should always be deleted before host cookies.
size_t removed = 0u;
// At this point we have 3 layers of iterators to consider:
// * The `could_be_deleted` list's iterator, which points to...
// * The `cookies` list's iterator, which points to...
// * The CookieMap's iterator which is used to delete the actual cookie from
// the backend.
// For each cookie deleted all three of these will need to erased, in a bottom
// up approach.
for (auto domain_list_it = could_be_deleted.domain_cookies.begin();
domain_list_it != could_be_deleted.domain_cookies.end() &&
removed < purge_goal && max_cookies_to_delete_this_round > 0;) {
auto cookies_list_it = *domain_list_it;
auto cookie_map_it = *cookies_list_it;
// Delete from the cookie store.
InternalDeleteCookie(cookie_map_it, /*sync_to_store=*/true,
DELETE_COOKIE_EVICTED_DOMAIN);
// Delete from `cookies`.
cookies.erase(cookies_list_it);
// Delete from `could_be_deleted`.
domain_list_it = could_be_deleted.domain_cookies.erase(domain_list_it);
max_cookies_to_delete_this_round--;
removed++;
}
// 5. Remove host cookies
for (auto host_list_it = could_be_deleted.host_cookies.begin();
host_list_it != could_be_deleted.host_cookies.end() &&
removed < purge_goal && max_cookies_to_delete_this_round > 0;) {
auto cookies_list_it = *host_list_it;
auto cookie_map_it = *cookies_list_it;
// Delete from the cookie store.
InternalDeleteCookie(cookie_map_it, /*sync_to_store=*/true,
DELETE_COOKIE_EVICTED_DOMAIN);
// Delete from `cookies`.
cookies.erase(cookies_list_it);
// Delete from `could_be_deleted`.
host_list_it = could_be_deleted.host_cookies.erase(host_list_it);
max_cookies_to_delete_this_round--;
removed++;
}
return removed;
}
size_t CookieMonster::GarbageCollectExpired(const Time& current,
const CookieMapItPair& itpair,
CookieItVector* cookie_its) {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
int num_deleted = 0;
for (CookieMap::iterator it = itpair.first, end = itpair.second; it != end;) {
auto curit = it;
++it;
if (curit->second->IsExpired(current)) {
InternalDeleteCookie(curit, true, DELETE_COOKIE_EXPIRED);
++num_deleted;
} else if (cookie_its) {
cookie_its->push_back(curit);
}
}
return num_deleted;
}
size_t CookieMonster::GarbageCollectExpiredPartitionedCookies(
const Time& current,
const PartitionedCookieMap::iterator& cookie_partition_it,
const CookieMapItPair& itpair,
CookieItVector* cookie_its) {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
int num_deleted = 0;
for (CookieMap::iterator it = itpair.first, end = itpair.second; it != end;) {
auto curit = it;
++it;
if (curit->second->IsExpired(current)) {
InternalDeletePartitionedCookie(cookie_partition_it, curit, true,
DELETE_COOKIE_EXPIRED);
++num_deleted;
} else if (cookie_its) {
cookie_its->push_back(curit);
}
}
return num_deleted;
}
void CookieMonster::GarbageCollectAllExpiredPartitionedCookies(
const Time& current) {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
for (auto it = partitioned_cookies_.begin();
it != partitioned_cookies_.end();) {
// GarbageCollectExpiredPartitionedCookies calls
// InternalDeletePartitionedCookie which may invalidate
// |cur_cookie_partition_it|.
auto cur_cookie_partition_it = it;
++it;
GarbageCollectExpiredPartitionedCookies(
current, cur_cookie_partition_it,
CookieMapItPair(cur_cookie_partition_it->second->begin(),
cur_cookie_partition_it->second->end()),
nullptr /*cookie_its*/);
}
}
size_t CookieMonster::GarbageCollectDeleteRange(
const Time& current,
DeletionCause cause,
CookieItVector::iterator it_begin,
CookieItVector::iterator it_end) {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
for (auto it = it_begin; it != it_end; it++) {
InternalDeleteCookie((*it), true, cause);
}
return it_end - it_begin;
}
size_t CookieMonster::GarbageCollectLeastRecentlyAccessed(
const base::Time& current,
const base::Time& safe_date,
size_t purge_goal,
CookieItVector cookie_its,
base::Time& earliest_time) {
DCHECK_LE(purge_goal, cookie_its.size());
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
// Sorts up to *and including* |cookie_its[purge_goal]| (if it exists), so
// |earliest_time| will be properly assigned even if
// |global_purge_it| == |cookie_its.begin() + purge_goal|.
SortLeastRecentlyAccessed(
cookie_its.begin(), cookie_its.end(),
cookie_its.size() < purge_goal ? purge_goal + 1 : purge_goal);
// Find boundary to cookies older than safe_date.
auto global_purge_it = LowerBoundAccessDate(
cookie_its.begin(), cookie_its.begin() + purge_goal, safe_date);
// Only delete the old cookies and delete non-secure ones first.
size_t num_deleted =
GarbageCollectDeleteRange(current, DELETE_COOKIE_EVICTED_GLOBAL,
cookie_its.begin(), global_purge_it);
if (global_purge_it != cookie_its.end())
earliest_time = (*global_purge_it)->second->LastAccessDate();
return num_deleted;
}
// A wrapper around registry_controlled_domains::GetDomainAndRegistry
// to make clear we're creating a key for our local map or for the persistent
// store's use. Here and in FindCookiesForRegistryControlledHost() are the only
// two places where we need to conditionalize based on key type.
//
// Note that this key algorithm explicitly ignores the scheme. This is
// because when we're entering cookies into the map from the backing store,
// we in general won't have the scheme at that point.
// In practical terms, this means that file cookies will be stored
// in the map either by an empty string or by UNC name (and will be
// limited by kMaxCookiesPerHost), and extension cookies will be stored
// based on the single extension id, as the extension id won't have the
// form of a DNS host and hence GetKey() will return it unchanged.
//
// Arguably the right thing to do here is to make the key
// algorithm dependent on the scheme, and make sure that the scheme is
// available everywhere the key must be obtained (specfically at backing
// store load time). This would require either changing the backing store
// database schema to include the scheme (far more trouble than it's worth), or
// separating out file cookies into their own CookieMonster instance and
// thus restricting each scheme to a single cookie monster (which might
// be worth it, but is still too much trouble to solve what is currently a
// non-problem).
//
// static
std::string CookieMonster::GetKey(std::string_view domain) {
std::string effective_domain(
registry_controlled_domains::GetDomainAndRegistry(
domain, registry_controlled_domains::INCLUDE_PRIVATE_REGISTRIES));
if (effective_domain.empty())
effective_domain = std::string(domain);
return cookie_util::CookieDomainAsHost(effective_domain);
}
bool CookieMonster::HasCookieableScheme(const GURL& url) {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
// Make sure the request is on a cookie-able url scheme.
bool is_cookieable = std::ranges::any_of(
cookieable_schemes_, [&url](const std::string& cookieable_scheme) {
return url.SchemeIs(cookieable_scheme.c_str());
});
if (!is_cookieable) {
// The scheme didn't match any in our allowed list.
DVLOG(net::cookie_util::kVlogPerCookieMonster)
<< "WARNING: Unsupported cookie scheme: " << url.scheme();
}
return is_cookieable;
}
CookieAccessSemantics CookieMonster::GetAccessSemanticsForCookie(
const CanonicalCookie& cookie) const {
if (cookie_access_delegate())
return cookie_access_delegate()->GetAccessSemantics(cookie);
return CookieAccessSemantics::UNKNOWN;
}
CookieScopeSemantics CookieMonster::GetScopeSemanticsForCookieDomain(
const std::string_view domain) const {
if (cookie_access_delegate()) {
return cookie_access_delegate()->GetScopeSemantics(domain);
}
return CookieScopeSemantics::UNKNOWN;
}
CookieScopeSemantics CookieMonster::CheckAndActivateLegacyScopeBehavior(
const std::string_view domain) {
const std::string cookie_key = GetKey(domain);
CookieScopeSemantics cookie_scope_semantic =
GetScopeSemanticsForCookieDomain(domain);
if (!pref_delegate_dict_) {
// TODO(crbug.com/378827534) Add CHECK once callbacks are supported.
if (pref_delegate_ && pref_delegate_->IsPrefReady()) {
pref_delegate_dict_ = std::make_unique<base::Value::Dict>(
pref_delegate_->GetLegacyDomains().Clone());
} else {
pref_delegate_dict_ = std::make_unique<base::Value::Dict>();
}
}
bool is_in_pref = pref_delegate_dict_->Find(cookie_key);
if (!is_in_pref && cookie_scope_semantic == CookieScopeSemantics::LEGACY) {
// Delete all aliasing cookies for this domain.
DeleteAllAliasingCookies(cookie_key);
// This is the first time this domain is entering legacy mode so add it to
// pref.
pref_delegate_dict_->Set(cookie_key, base::Value(true));
// Only set to pref_delegate if it is valid.
if (pref_delegate_) {
pref_delegate_->SetLegacyDomains(pref_delegate_dict_->Clone());
}
} else if (is_in_pref &&
cookie_scope_semantic != CookieScopeSemantics::LEGACY) {
pref_delegate_dict_->Remove(cookie_key);
// Only set pref if it is valid.
if (pref_delegate_) {
pref_delegate_->SetLegacyDomains(pref_delegate_dict_->Clone());
}
}
return cookie_scope_semantic;
}
void CookieMonster::DeleteAllAliasingCookies(const std::string& domain) {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
std::map<UniqueCookieKey, std::pair<base::Time, UniqueCookieKey>>
most_recent_cookies;
CookieMapItPair cookie_map_its = cookies_.equal_range(domain);
UpdateMostRecentCookie(cookie_map_its, most_recent_cookies);
// Delete all non-partitioned cookie aliases from cookie map.
for (auto it = cookie_map_its.first; it != cookie_map_its.second;) {
auto curit = it;
CanonicalCookie* cc = curit->second.get();
++it;
// Cookie is not most recently created of its alias so delete it.
if (cc->StrictlyUniqueKey() !=
most_recent_cookies.find(cc->LegacyUniqueKey())->second.second) {
InternalDeleteCookie(curit, true, DELETE_COOKIE_ALIAS);
}
}
// Delete all partitioned cookie aliases for this domain as well.
for (auto it = partitioned_cookies_.begin();
it != partitioned_cookies_.end();) {
CookieMapItPair itpair = it->second->equal_range(domain);
auto cookie_partition_it = it;
it++;
// most_recent_cookie map is only scoped to the current
// cookie_partition_key.
std::map<UniqueCookieKey, std::pair<base::Time, UniqueCookieKey>>
most_recent_partitioned_cookies;
UpdateMostRecentCookie(itpair, most_recent_partitioned_cookies);
for (auto inner_it = itpair.first; inner_it != itpair.second;) {
auto curit = inner_it;
CanonicalCookie* cc = curit->second.get();
++inner_it;
if (cc->StrictlyUniqueKey() !=
most_recent_partitioned_cookies.find(cc->LegacyUniqueKey())
->second.second) {
// Cookie is not most recently created for its alias so delete.
InternalDeletePartitionedCookie(cookie_partition_it, curit, true,
DELETE_COOKIE_ALIAS);
}
}
}
}
void CookieMonster::UpdateMostRecentCookie(
const CookieMapItPair& itpair,
std::map<UniqueCookieKey, std::pair<base::Time, UniqueCookieKey>>&
most_recent_cookies) {
for (CookieMap::iterator it = itpair.first, end = itpair.second; it != end;
++it) {
CanonicalCookie* cc = it->second.get();
// Find the iterator for the LegacyUniqueKey in the most recent cookies
// map.
auto most_recent_it = most_recent_cookies.find(cc->LegacyUniqueKey());
// Update the most recent cookie if it is not found or if the current
// cookie is more recent.
if (most_recent_it == most_recent_cookies.end() ||
cc->CreationDate() > most_recent_it->second.first) {
most_recent_cookies.insert_or_assign(
most_recent_it, cc->LegacyUniqueKey(),
std::make_pair(cc->CreationDate(), cc->StrictlyUniqueKey()));
}
}
}
// Test to see if stats should be recorded, and record them if so.
// The goal here is to get sampling for the average browser-hour of
// activity. We won't take samples when the web isn't being surfed,
// and when the web is being surfed, we'll take samples about every
// kRecordStatisticsIntervalSeconds.
// last_statistic_record_time_ is initialized to Now() rather than null
// in the constructor so that we won't take statistics right after
// startup, to avoid bias from browsers that are started but not used.
void CookieMonster::RecordPeriodicStats(const base::Time& current_time) {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
const base::TimeDelta kRecordStatisticsIntervalTime(
base::Seconds(kRecordStatisticsIntervalSeconds));
// If we've taken statistics recently, return.
if (current_time - last_statistic_record_time_ <=
kRecordStatisticsIntervalTime) {
return;
}
if (DoRecordPeriodicStats())
last_statistic_record_time_ = current_time;
}
bool CookieMonster::DoRecordPeriodicStats() {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
SCOPED_UMA_HISTOGRAM_TIMER("Cookie.TimeToRecordPeriodicStats");
// These values are all bogus if we have only partially loaded the cookies.
if (started_fetching_all_cookies_ && !finished_fetching_all_cookies_)
return false;
base::UmaHistogramCounts100000("Cookie.Count2", cookies_.size());
if (cookie_access_delegate()) {
std::vector<SchemefulSite> sites;
for (const auto& entry : cookies_) {
sites.emplace_back(
GURL(base::StrCat({url::kHttpsScheme, "://", entry.first})));
}
for (const auto& [partition_key, cookie_map] : partitioned_cookies_) {
for (const auto& [domain, unused_cookie] : *cookie_map) {
sites.emplace_back(
GURL(base::StrCat({url::kHttpsScheme, "://", domain})));
}
}
std::optional<base::flat_map<SchemefulSite, FirstPartySetEntry>>
maybe_sets = cookie_access_delegate()->FindFirstPartySetEntries(
sites,
base::BindOnce(&CookieMonster::RecordPeriodicFirstPartySetsStats,
weak_ptr_factory_.GetWeakPtr()));
if (maybe_sets.has_value())
RecordPeriodicFirstPartySetsStats(maybe_sets.value());
}
// Can be up to kMaxCookies.
UMA_HISTOGRAM_COUNTS_10000("Cookie.NumKeys", num_keys_);
std::map<std::string, size_t> n_same_site_none_cookies;
size_t n_bytes = 0;
std::map<std::string, size_t> n_bytes_per_key;
for (const auto& [host_key, host_cookie] : cookies_) {
size_t cookie_n_bytes = NameValueSizeBytes(*host_cookie);
n_bytes += cookie_n_bytes;
n_bytes_per_key[host_key] += cookie_n_bytes;
if (!host_cookie || !host_cookie->IsEffectivelySameSiteNone())
continue;
n_same_site_none_cookies[host_key]++;
}
size_t max_n_cookies = 0;
for (const auto& entry : n_same_site_none_cookies) {
max_n_cookies = std::max(max_n_cookies, entry.second);
}
size_t max_n_bytes = 0;
for (const auto& entry : n_bytes_per_key) {
max_n_bytes = std::max(max_n_bytes, entry.second);
}
// Can be up to 180 cookies, the max per-domain.
base::UmaHistogramCounts1000("Cookie.MaxSameSiteNoneCookiesPerKey",
max_n_cookies);
base::UmaHistogramCounts100000("Cookie.CookieJarSize", n_bytes >> 10);
base::UmaHistogramCounts100000(
"Cookie.AvgCookieJarSizePerKey2",
n_bytes / std::max(num_keys_, static_cast<size_t>(1)));
base::UmaHistogramCounts100000("Cookie.MaxCookieJarSizePerKey",
max_n_bytes >> 10);
// Collect stats for partitioned cookies.
base::UmaHistogramCounts1000("Cookie.PartitionCount",
partitioned_cookies_.size());
base::UmaHistogramCounts100000("Cookie.PartitionedCookieCount",
num_partitioned_cookies_);
base::UmaHistogramCounts100000("Cookie.PartitionedCookieCount.Nonced",
num_nonced_partitioned_cookies_);
base::UmaHistogramCounts100000(
"Cookie.PartitionedCookieCount.Unnonced",
num_partitioned_cookies_ - num_nonced_partitioned_cookies_);
base::UmaHistogramCounts100000("Cookie.PartitionedCookieJarSizeKibibytes",
num_partitioned_cookies_bytes_ >> 10);
base::UmaHistogramCounts100000(
"Cookie.PartitionedCookieJarSizeKibibytes.Nonced",
num_nonced_partitioned_cookie_bytes_ >> 10);
base::UmaHistogramCounts100000(
"Cookie.PartitionedCookieJarSizeKibibytes.Unnonced",
(num_partitioned_cookies_bytes_ - num_nonced_partitioned_cookie_bytes_) >>
10);
for (const auto& it : bytes_per_cookie_partition_) {
base::UmaHistogramCounts100000("Cookie.CookiePartitionSizeKibibytes",
it.second >> 10);
}
return true;
}
void CookieMonster::RecordPeriodicFirstPartySetsStats(
base::flat_map<SchemefulSite, FirstPartySetEntry> sets) const {
base::flat_map<SchemefulSite, std::set<SchemefulSite>> grouped_by_owner;
for (const auto& [site, entry] : sets) {
grouped_by_owner[entry.primary()].insert(site);
}
for (const auto& set : grouped_by_owner) {
int sample = std::accumulate(
set.second.begin(), set.second.end(), 0,
[this](int acc, const net::SchemefulSite& site) -> int {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
if (!site.has_registrable_domain_or_host())
return acc;
return acc + cookies_.count(GetKey(site.GetURL().host()));
});
base::UmaHistogramCustomCounts("Cookie.PerFirstPartySetCount", sample, 0,
4000, 50);
}
}
void CookieMonster::DoCookieCallback(base::OnceClosure callback) {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
MarkCookieStoreAsInitialized();
FetchAllCookiesIfNecessary();
seen_global_task_ = true;
if (!finished_fetching_all_cookies_ && store_.get()) {
if (tasks_pending_.empty()) {
time_start_block_load_all_ = base::TimeTicks::Now();
}
tasks_pending_.push_back(std::move(callback));
return;
}
std::move(callback).Run();
}
void CookieMonster::DoCookieCallbackForURL(base::OnceClosure callback,
const GURL& url) {
DoCookieCallbackForHostOrDomain(std::move(callback), url.host_piece());
}
void CookieMonster::DoCookieCallbackForHostOrDomain(
base::OnceClosure callback,
std::string_view host_or_domain) {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
MarkCookieStoreAsInitialized();
FetchAllCookiesIfNecessary();
// If cookies for the requested domain key (eTLD+1) have been loaded from DB
// then run the task, otherwise load from DB.
if (!finished_fetching_all_cookies_ && store_.get()) {
// If a global task has been previously seen, queue the task as a global
// task. Note that the CookieMonster may be in the middle of executing
// the global queue, |tasks_pending_| may be empty, which is why another
// bool is needed.
if (seen_global_task_) {
tasks_pending_.push_back(std::move(callback));
return;
}
// Checks if the domain key has been loaded.
std::string key = GetKey(host_or_domain);
if (keys_loaded_.find(key) == keys_loaded_.end()) {
auto it = tasks_pending_for_key_.find(key);
if (it == tasks_pending_for_key_.end()) {
store_->LoadCookiesForKey(
key, base::BindOnce(&CookieMonster::OnKeyLoaded,
weak_ptr_factory_.GetWeakPtr(), key));
it = tasks_pending_for_key_
.emplace(key, base::circular_deque<base::OnceClosure>())
.first;
}
it->second.push_back(std::move(callback));
return;
}
}
std::move(callback).Run();
}
CookieMonster::CookieSentToSamePort
CookieMonster::IsCookieSentToSamePortThatSetIt(
const GURL& destination,
int source_port,
CookieSourceScheme source_scheme) {
if (source_port == url::PORT_UNSPECIFIED)
return CookieSentToSamePort::kSourcePortUnspecified;
if (source_port == url::PORT_INVALID)
return CookieSentToSamePort::kInvalid;
int destination_port = destination.EffectiveIntPort();
if (source_port == destination_port)
return CookieSentToSamePort::kYes;
const std::string& destination_scheme = destination.scheme();
bool destination_port_is_default =
url::DefaultPortForScheme(destination_scheme) == destination_port;
// Since the source port has to be specified if we got to this point, that
// means this is a newer cookie that therefore has its scheme set as well.
DCHECK(source_scheme != CookieSourceScheme::kUnset);
std::string source_scheme_string =
source_scheme == CookieSourceScheme::kSecure
? url::kHttpsScheme
: url::kHttpScheme; // wss/ws have the same default port values as
// https/http, so it's ok that we use these.
bool source_port_is_default =
url::DefaultPortForScheme(source_scheme_string) == source_port;
if (destination_port_is_default && source_port_is_default)
return CookieSentToSamePort::kNoButDefault;
return CookieSentToSamePort::kNo;
}
std::optional<bool> CookieMonster::SiteHasCookieInOtherPartition(
const net::SchemefulSite& site,
const CookiePartitionKey& partition_key) const {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
std::string domain = site.GetURL().host();
if (store_ && !finished_fetching_all_cookies_ &&
!keys_loaded_.count(domain)) {
return std::nullopt;
}
return std::ranges::any_of(partitioned_cookies_, [&](const auto& pair) {
const auto& [other_key, cookie_map] = pair;
return other_key != partition_key &&
!CookiePartitionKey::HasNonce(other_key) &&
cookie_map->contains(domain);
});
}
} // namespace net
|