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
|
// Copyright 2012 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "net/extras/sqlite/sqlite_persistent_cookie_store.h"
#include <stdint.h>
#include <map>
#include <memory>
#include <optional>
#include <set>
#include <utility>
#include <vector>
#include "base/containers/span.h"
#include "base/files/file.h"
#include "base/files/file_util.h"
#include "base/files/scoped_temp_dir.h"
#include "base/functional/bind.h"
#include "base/functional/callback.h"
#include "base/location.h"
#include "base/memory/ref_counted.h"
#include "base/memory/weak_ptr.h"
#include "base/run_loop.h"
#include "base/sequence_checker.h"
#include "base/strings/stringprintf.h"
#include "base/synchronization/waitable_event.h"
#include "base/task/sequenced_task_runner.h"
#include "base/task/single_thread_task_runner.h"
#include "base/task/thread_pool.h"
#include "base/test/bind.h"
#include "base/test/metrics/histogram_tester.h"
#include "base/test/scoped_feature_list.h"
#include "base/threading/thread_restrictions.h"
#include "base/time/time.h"
#include "crypto/aes_cbc.h"
#include "net/base/features.h"
#include "net/base/test_completion_callback.h"
#include "net/cookies/canonical_cookie.h"
#include "net/cookies/cookie_constants.h"
#include "net/cookies/cookie_inclusion_status.h"
#include "net/cookies/cookie_store_test_callbacks.h"
#include "net/extras/sqlite/cookie_crypto_delegate.h"
#include "net/log/net_log_capture_mode.h"
#include "net/log/test_net_log.h"
#include "net/log/test_net_log_util.h"
#include "net/test/test_with_task_environment.h"
#include "sql/database.h"
#include "sql/meta_table.h"
#include "sql/statement.h"
#include "sql/test/test_helpers.h"
#include "sql/transaction.h"
#include "testing/gmock/include/gmock/gmock-matchers.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "url/gurl.h"
#include "url/third_party/mozilla/url_parse.h"
namespace net {
namespace {
const base::FilePath::CharType kCookieFilename[] = FILE_PATH_LITERAL("Cookies");
class CookieCryptor : public CookieCryptoDelegate {
public:
CookieCryptor();
// net::CookieCryptoDelegate implementation.
void Init(base::OnceClosure callback) override;
bool EncryptString(const std::string& plaintext,
std::string* ciphertext) override;
bool DecryptString(const std::string& ciphertext,
std::string* plaintext) override;
// Obtain a closure that can be called to trigger an initialize. If this
// instance has already been destructed then the returned base::OnceClosure
// does nothing. This allows tests to pass ownership to the CookieCryptor
// while still retaining a weak reference to the Init function.
base::OnceClosure GetInitClosure(base::OnceClosure callback);
private:
void InitComplete();
bool init_ GUARDED_BY_CONTEXT(sequence_checker_) = false;
bool initing_ GUARDED_BY_CONTEXT(sequence_checker_) = false;
base::OnceClosureList callbacks_ GUARDED_BY_CONTEXT(sequence_checker_);
SEQUENCE_CHECKER(sequence_checker_);
base::WeakPtrFactory<CookieCryptor> weak_ptr_factory_{this};
};
constexpr std::array<uint8_t, 32> kFixedKey{
'c', 'o', 'o', 'k', 'i', 'e', 'c', 'r', 'y', 'p', 't',
'o', 'r', 'i', 's', 'a', 'u', 's', 'e', 'f', 'u', 'l',
't', 'e', 's', 't', 'c', 'l', 'a', 's', 's', '!',
};
constexpr std::array<uint8_t, 16> kFixedIv{
't', 'h', 'e', ' ', 'i', 'v', ':', ' ',
'1', '6', ' ', 'b', 'y', 't', 'e', 's',
};
CookieCryptor::CookieCryptor() {
DETACH_FROM_SEQUENCE(sequence_checker_);
}
base::OnceClosure CookieCryptor::GetInitClosure(base::OnceClosure callback) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
return base::BindOnce(&CookieCryptor::Init, weak_ptr_factory_.GetWeakPtr(),
std::move(callback));
}
void CookieCryptor::Init(base::OnceClosure callback) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
if (init_) {
std::move(callback).Run();
return;
}
// Callbacks here are owned by test fixtures that outlive the CookieCryptor.
callbacks_.AddUnsafe(std::move(callback));
if (initing_) {
return;
}
initing_ = true;
base::SingleThreadTaskRunner::GetCurrentDefault()->PostDelayedTask(
FROM_HERE,
base::BindOnce(&CookieCryptor::InitComplete,
weak_ptr_factory_.GetWeakPtr()),
base::Milliseconds(100));
}
bool CookieCryptor::EncryptString(const std::string& plaintext,
std::string* ciphertext) {
// SQLite crypto uses OSCrypt Async Encryptor and the behavior for empty
// plaintext is to return empty ciphertext. See
// os_crypt_async::Encryptor::EncryptString. This matches this behavior,
// without adding a dependency from net into components.
if (plaintext.empty()) {
ciphertext->clear();
return true;
}
auto result = crypto::aes_cbc::Encrypt(kFixedKey, kFixedIv,
base::as_byte_span(plaintext));
ciphertext->assign(result.begin(), result.end());
return true;
}
bool CookieCryptor::DecryptString(const std::string& ciphertext,
std::string* plaintext) {
// SQLite crypto uses OSCrypt Async Encryptor and the behavior for empty
// ciphertext is to return empty plaintext. See
// os_crypt_async::Encryptor::DecryptString. This matches this behavior,
// without adding a dependency from net into components.
if (ciphertext.empty()) {
plaintext->clear();
return true;
}
auto result = crypto::aes_cbc::Decrypt(kFixedKey, kFixedIv,
base::as_byte_span(ciphertext));
if (result.has_value()) {
plaintext->assign(result->begin(), result->end());
return true;
}
return false;
}
void CookieCryptor::InitComplete() {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
init_ = true;
callbacks_.Notify();
}
// Matches the CanonicalCookie's strictly_unique_key and last_access_date
// against a unique_ptr<CanonicalCookie>.
MATCHER_P2(MatchesCookieKeyAndLastAccessDate,
StrictlyUniqueKey,
last_access_date,
"") {
if (!arg) {
return false;
}
const CanonicalCookie& list_cookie = *arg;
return testing::ExplainMatchResult(StrictlyUniqueKey,
list_cookie.StrictlyUniqueKey(),
result_listener) &&
testing::ExplainMatchResult(
last_access_date, list_cookie.LastAccessDate(), result_listener);
}
// Matches every field of a CanonicalCookie against a
// unique_ptr<CanonicalCookie>.
MATCHER_P(MatchesEveryCookieField, cookie, "") {
if (!arg) {
return false;
}
const CanonicalCookie& list_cookie = *arg;
return cookie.HasEquivalentDataMembers(list_cookie);
}
} // namespace
typedef std::vector<std::unique_ptr<CanonicalCookie>> CanonicalCookieVector;
class SQLitePersistentCookieStoreTest : public TestWithTaskEnvironment {
public:
SQLitePersistentCookieStoreTest()
: loaded_event_(base::WaitableEvent::ResetPolicy::AUTOMATIC,
base::WaitableEvent::InitialState::NOT_SIGNALED),
db_thread_event_(base::WaitableEvent::ResetPolicy::AUTOMATIC,
base::WaitableEvent::InitialState::NOT_SIGNALED) {}
void SignalLoadedEvent() { loaded_event_.Signal(); }
void OnLoaded(base::OnceClosure closure, CanonicalCookieVector cookies) {
cookies_.swap(cookies);
std::move(closure).Run();
}
CanonicalCookieVector Load() {
base::RunLoop run_loop;
CanonicalCookieVector cookies;
store_->Load(
base::BindLambdaForTesting([&](CanonicalCookieVector obtained_cookies) {
cookies.swap(obtained_cookies);
run_loop.Quit();
}),
NetLogWithSource::Make(NetLogSourceType::NONE));
run_loop.Run();
return cookies;
}
void LoadAsyncAndSignalEvent() {
store_->Load(
base::BindOnce(
&SQLitePersistentCookieStoreTest::OnLoaded, base::Unretained(this),
base::BindOnce(&SQLitePersistentCookieStoreTest::SignalLoadedEvent,
base::Unretained(this))),
NetLogWithSource::Make(NetLogSourceType::NONE));
}
void Flush() {
base::RunLoop run_loop;
store_->Flush(run_loop.QuitClosure());
run_loop.Run();
}
void DestroyStore() {
store_ = nullptr;
// Make sure we wait until the destructor has run by running all
// TaskEnvironment tasks.
RunUntilIdle();
}
void Create(bool crypt_cookies,
bool restore_old_session_cookies,
bool use_current_thread,
bool enable_exclusive_access) {
store_ = base::MakeRefCounted<SQLitePersistentCookieStore>(
temp_dir_.GetPath().Append(kCookieFilename),
use_current_thread ? base::SingleThreadTaskRunner::GetCurrentDefault()
: client_task_runner_,
background_task_runner_, restore_old_session_cookies,
crypt_cookies ? std::make_unique<CookieCryptor>() : nullptr,
enable_exclusive_access);
}
CanonicalCookieVector CreateAndLoad(bool crypt_cookies,
bool restore_old_session_cookies) {
Create(crypt_cookies, restore_old_session_cookies,
/*use_current_thread=*/false, /*enable_exclusive_access=*/false);
return Load();
}
void InitializeStore(bool crypt, bool restore_old_session_cookies) {
EXPECT_EQ(0U, CreateAndLoad(crypt, restore_old_session_cookies).size());
}
void WaitOnDBEvent() {
base::ScopedAllowBaseSyncPrimitivesForTesting allow_base_sync_primitives;
db_thread_event_.Wait();
}
// Adds a persistent cookie to store_.
void AddCookie(const std::string& name,
const std::string& value,
const std::string& domain,
const std::string& path,
const base::Time& creation) {
store_->AddCookie(*CanonicalCookie::CreateUnsafeCookieForTesting(
name, value, domain, path, creation, /*expiration=*/creation,
/*last_access=*/base::Time(), /*last_update=*/base::Time(),
/*secure=*/false,
/*httponly=*/false, CookieSameSite::NO_RESTRICTION,
COOKIE_PRIORITY_DEFAULT));
}
void AddCookieWithExpiration(const std::string& name,
const std::string& value,
const std::string& domain,
const std::string& path,
const base::Time& creation,
const base::Time& expiration) {
store_->AddCookie(*CanonicalCookie::CreateUnsafeCookieForTesting(
name, value, domain, path, creation, expiration,
/*last_access=*/base::Time(), /*last_update=*/base::Time(),
/*secure=*/false,
/*httponly=*/false, CookieSameSite::NO_RESTRICTION,
COOKIE_PRIORITY_DEFAULT));
}
std::string ReadRawDBContents() {
std::string contents;
if (!base::ReadFileToString(temp_dir_.GetPath().Append(kCookieFilename),
&contents)) {
return std::string();
}
return contents;
}
void SetUp() override { ASSERT_TRUE(temp_dir_.CreateUniqueTempDir()); }
void TearDown() override {
if (!expect_init_errors_) {
EXPECT_THAT(histograms_.GetAllSamples("Cookie.ErrorInitializeDB"),
::testing::IsEmpty());
}
DestroyStore();
}
protected:
const scoped_refptr<base::SequencedTaskRunner> background_task_runner_ =
base::ThreadPool::CreateSequencedTaskRunner({base::MayBlock()});
const scoped_refptr<base::SequencedTaskRunner> client_task_runner_ =
base::ThreadPool::CreateSequencedTaskRunner({base::MayBlock()});
base::WaitableEvent loaded_event_;
base::WaitableEvent db_thread_event_;
CanonicalCookieVector cookies_;
base::ScopedTempDir temp_dir_;
scoped_refptr<SQLitePersistentCookieStore> store_;
std::unique_ptr<CookieCryptor> cookie_crypto_delegate_;
base::HistogramTester histograms_;
bool expect_init_errors_ = false;
};
TEST_F(SQLitePersistentCookieStoreTest, TestInvalidVersionRecovery) {
InitializeStore(/*crypt=*/false, /*restore_old_session_cookies=*/false);
AddCookie("A", "B", "foo.bar", "/", base::Time::Now());
DestroyStore();
// Load up the store and verify that it has good data in it.
CanonicalCookieVector cookies = CreateAndLoad(
/*crypt_cookies=*/false, /*restore_old_session_cookies=*/false);
ASSERT_EQ(1U, cookies.size());
ASSERT_STREQ("foo.bar", cookies[0]->Domain().c_str());
ASSERT_STREQ("A", cookies[0]->Name().c_str());
ASSERT_STREQ("B", cookies[0]->Value().c_str());
DestroyStore();
cookies.clear();
// Now make the version too old to initialize from.
{
sql::Database db(sql::test::kTestTag);
ASSERT_TRUE(db.Open(temp_dir_.GetPath().Append(kCookieFilename)));
sql::MetaTable meta_table;
ASSERT_TRUE(meta_table.Init(&db, 1, 1));
// Keep in sync with latest unsupported version from:
// net/extras/sqlite/sqlite_persistent_cookie_store.cc
ASSERT_TRUE(meta_table.SetVersionNumber(17));
}
// Upon loading, the database should be reset to a good, blank state.
cookies = CreateAndLoad(/*crypt_cookies=*/false,
/*restore_old_session_cookies=*/false);
ASSERT_EQ(0U, cookies.size());
// Verify that, after, recovery, the database persists properly.
AddCookie("X", "Y", "foo.bar", "/", base::Time::Now());
DestroyStore();
cookies = CreateAndLoad(/*crypt_cookies=*/false,
/*restore_old_session_cookies=*/false);
ASSERT_EQ(1U, cookies.size());
ASSERT_STREQ("foo.bar", cookies[0]->Domain().c_str());
ASSERT_STREQ("X", cookies[0]->Name().c_str());
ASSERT_STREQ("Y", cookies[0]->Value().c_str());
}
TEST_F(SQLitePersistentCookieStoreTest, TestInvalidMetaTableRecovery) {
InitializeStore(/*crypt=*/false, /*restore_old_session_cookies=*/false);
AddCookie("A", "B", "foo.bar", "/", base::Time::Now());
DestroyStore();
// Load up the store and verify that it has good data in it.
CanonicalCookieVector cookies = CreateAndLoad(
/*crypt_cookies=*/false, /*restore_old_session_cookies=*/false);
ASSERT_EQ(1U, cookies.size());
ASSERT_STREQ("foo.bar", cookies[0]->Domain().c_str());
ASSERT_STREQ("A", cookies[0]->Name().c_str());
ASSERT_STREQ("B", cookies[0]->Value().c_str());
DestroyStore();
cookies.clear();
// Now corrupt the meta table.
{
sql::Database db(sql::test::kTestTag);
ASSERT_TRUE(db.Open(temp_dir_.GetPath().Append(kCookieFilename)));
sql::MetaTable meta_table;
ASSERT_TRUE(meta_table.Init(&db, 1, 1));
ASSERT_TRUE(db.Execute("DELETE FROM meta"));
}
// Upon loading, the database should be reset to a good, blank state.
cookies = CreateAndLoad(/*crypt_cookies=*/false,
/*restore_old_session_cookies=*/false);
ASSERT_EQ(0U, cookies.size());
// Verify that, after, recovery, the database persists properly.
AddCookie("X", "Y", "foo.bar", "/", base::Time::Now());
DestroyStore();
cookies = CreateAndLoad(/*crypt_cookies=*/false,
/*restore_old_session_cookies=*/false);
ASSERT_EQ(1U, cookies.size());
ASSERT_STREQ("foo.bar", cookies[0]->Domain().c_str());
ASSERT_STREQ("X", cookies[0]->Name().c_str());
ASSERT_STREQ("Y", cookies[0]->Value().c_str());
}
// Test if data is stored as expected in the SQLite database.
TEST_F(SQLitePersistentCookieStoreTest, TestPersistance) {
InitializeStore(/*crypt=*/false, /*restore_old_session_cookies=*/false);
AddCookie("A", "B", "foo.bar", "/", base::Time::Now());
// Replace the store effectively destroying the current one and forcing it
// to write its data to disk. Then we can see if after loading it again it
// is still there.
DestroyStore();
// Reload and test for persistence
CanonicalCookieVector cookies = CreateAndLoad(
/*crypt_cookies=*/false, /*restore_old_session_cookies=*/false);
ASSERT_EQ(1U, cookies.size());
ASSERT_STREQ("foo.bar", cookies[0]->Domain().c_str());
ASSERT_STREQ("A", cookies[0]->Name().c_str());
ASSERT_STREQ("B", cookies[0]->Value().c_str());
// Now delete the cookie and check persistence again.
store_->DeleteCookie(*cookies[0]);
DestroyStore();
cookies.clear();
// Reload and check if the cookie has been removed.
cookies = CreateAndLoad(/*crypt_cookies=*/false,
/*restore_old_session_cookies=*/false);
ASSERT_EQ(0U, cookies.size());
}
TEST_F(SQLitePersistentCookieStoreTest, TestSessionCookiesDeletedOnStartup) {
// Initialize the cookie store with 3 persistent cookies, 5 transient
// cookies.
InitializeStore(/*crypt=*/false, /*restore_old_session_cookies=*/false);
// Add persistent cookies.
base::Time t = base::Time::Now();
AddCookie("A", "B", "a1.com", "/", t);
t += base::Microseconds(10);
AddCookie("A", "B", "a2.com", "/", t);
t += base::Microseconds(10);
AddCookie("A", "B", "a3.com", "/", t);
// Add transient cookies.
t += base::Microseconds(10);
AddCookieWithExpiration("A", "B", "b1.com", "/", t, base::Time());
t += base::Microseconds(10);
AddCookieWithExpiration("A", "B", "b2.com", "/", t, base::Time());
t += base::Microseconds(10);
AddCookieWithExpiration("A", "B", "b3.com", "/", t, base::Time());
t += base::Microseconds(10);
AddCookieWithExpiration("A", "B", "b4.com", "/", t, base::Time());
t += base::Microseconds(10);
AddCookieWithExpiration("A", "B", "b5.com", "/", t, base::Time());
DestroyStore();
// Load the store a second time. Before the store finishes loading, add a
// transient cookie and flush it to disk.
store_ = base::MakeRefCounted<SQLitePersistentCookieStore>(
temp_dir_.GetPath().Append(kCookieFilename), client_task_runner_,
background_task_runner_, false, nullptr, false);
// Posting a blocking task to db_thread_ makes sure that the DB thread waits
// until both Load and Flush have been posted to its task queue.
background_task_runner_->PostTask(
FROM_HERE, base::BindOnce(&SQLitePersistentCookieStoreTest::WaitOnDBEvent,
base::Unretained(this)));
LoadAsyncAndSignalEvent();
t += base::Microseconds(10);
AddCookieWithExpiration("A", "B", "c.com", "/", t, base::Time());
base::WaitableEvent event(base::WaitableEvent::ResetPolicy::AUTOMATIC,
base::WaitableEvent::InitialState::NOT_SIGNALED);
store_->Flush(
base::BindOnce(&base::WaitableEvent::Signal, base::Unretained(&event)));
// Now the DB-thread queue contains:
// (active:)
// 1. Wait (on db_event)
// (pending:)
// 2. "Init And Chain-Load First Domain"
// 3. Add Cookie (c.com)
// 4. Flush Cookie (c.com)
db_thread_event_.Signal();
event.Wait();
loaded_event_.Wait();
cookies_.clear();
DestroyStore();
// Load the store a third time, this time restoring session cookies. The
// store should contain exactly 4 cookies: the 3 persistent, and "c.com",
// which was added during the second cookie store load.
store_ = base::MakeRefCounted<SQLitePersistentCookieStore>(
temp_dir_.GetPath().Append(kCookieFilename), client_task_runner_,
background_task_runner_, true, nullptr, false);
LoadAsyncAndSignalEvent();
loaded_event_.Wait();
ASSERT_EQ(4u, cookies_.size());
}
// Test that priority load of cookies for a specific domain key could be
// completed before the entire store is loaded.
TEST_F(SQLitePersistentCookieStoreTest, TestLoadCookiesForKey) {
InitializeStore(/*crypt=*/true, /*restore_old_session_cookies=*/false);
base::Time t = base::Time::Now();
AddCookie("A", "B", "foo.bar", "/", t);
t += base::Microseconds(10);
AddCookie("A", "B", "www.aaa.com", "/", t);
t += base::Microseconds(10);
AddCookie("A", "B", "travel.aaa.com", "/", t);
t += base::Microseconds(10);
AddCookie("A", "B", "www.bbb.com", "/", t);
DestroyStore();
auto cookie_crypto_delegate = std::make_unique<CookieCryptor>();
base::RunLoop cookie_crypto_loop;
auto init_closure =
cookie_crypto_delegate->GetInitClosure(cookie_crypto_loop.QuitClosure());
// base::test::TaskEnvironment runs |background_task_runner_| and
// |client_task_runner_| on the same thread. Therefore, when a
// |background_task_runner_| task is blocked, |client_task_runner_| tasks
// can't run. To allow precise control of |background_task_runner_| without
// preventing client tasks to run, use
// base::SingleThreadTaskRunner::GetCurrentDefault() instead of
// |client_task_runner_| for this test.
store_ = base::MakeRefCounted<SQLitePersistentCookieStore>(
temp_dir_.GetPath().Append(kCookieFilename),
base::SingleThreadTaskRunner::GetCurrentDefault(),
background_task_runner_,
/*restore_old_session_cookies=*/false, std::move(cookie_crypto_delegate),
/*enable_exclusive_access=*/false);
// Posting a blocking task to db_thread_ makes sure that the DB thread waits
// until both Load and LoadCookiesForKey have been posted to its task queue.
background_task_runner_->PostTask(
FROM_HERE, base::BindOnce(&SQLitePersistentCookieStoreTest::WaitOnDBEvent,
base::Unretained(this)));
RecordingNetLogObserver net_log_observer;
LoadAsyncAndSignalEvent();
base::RunLoop run_loop;
net_log_observer.SetObserverCaptureMode(NetLogCaptureMode::kDefault);
store_->LoadCookiesForKey(
"aaa.com",
base::BindOnce(&SQLitePersistentCookieStoreTest::OnLoaded,
base::Unretained(this), run_loop.QuitClosure()));
// Complete the initialization of the cookie crypto delegate. This ensures
// that any background tasks from the Load or the LoadCookiesForKey are posted
// to the background_task_runner_.
std::move(init_closure).Run();
cookie_crypto_loop.Run();
// Post a final blocking task to the background_task_runner_ to ensure no
// other cookie loads take place during the test.
background_task_runner_->PostTask(
FROM_HERE, base::BindOnce(&SQLitePersistentCookieStoreTest::WaitOnDBEvent,
base::Unretained(this)));
// Now the DB-thread queue contains:
// (active:)
// 1. Wait (on db_event)
// (pending:)
// 2. "Init And Chain-Load First Domain"
// 3. Priority Load (aaa.com)
// 4. Wait (on db_event)
db_thread_event_.Signal();
// Wait until the OnKeyLoaded callback has run.
run_loop.Run();
EXPECT_FALSE(loaded_event_.IsSignaled());
std::set<std::string> cookies_loaded;
for (CanonicalCookieVector::const_iterator it = cookies_.begin();
it != cookies_.end(); ++it) {
cookies_loaded.insert((*it)->Domain().c_str());
}
cookies_.clear();
ASSERT_GT(4U, cookies_loaded.size());
ASSERT_EQ(true, cookies_loaded.find("www.aaa.com") != cookies_loaded.end());
ASSERT_EQ(true,
cookies_loaded.find("travel.aaa.com") != cookies_loaded.end());
db_thread_event_.Signal();
RunUntilIdle();
EXPECT_TRUE(loaded_event_.IsSignaled());
for (CanonicalCookieVector::const_iterator it = cookies_.begin();
it != cookies_.end(); ++it) {
cookies_loaded.insert((*it)->Domain().c_str());
}
ASSERT_EQ(4U, cookies_loaded.size());
ASSERT_EQ(cookies_loaded.find("foo.bar") != cookies_loaded.end(), true);
ASSERT_EQ(cookies_loaded.find("www.bbb.com") != cookies_loaded.end(), true);
cookies_.clear();
store_ = nullptr;
auto entries = net_log_observer.GetEntries();
size_t pos = ExpectLogContainsSomewhere(
entries, 0, NetLogEventType::COOKIE_PERSISTENT_STORE_LOAD,
NetLogEventPhase::BEGIN);
pos = ExpectLogContainsSomewhere(
entries, pos, NetLogEventType::COOKIE_PERSISTENT_STORE_LOAD,
NetLogEventPhase::END);
pos = ExpectLogContainsSomewhere(
entries, 0, NetLogEventType::COOKIE_PERSISTENT_STORE_LOAD,
NetLogEventPhase::BEGIN);
pos = ExpectLogContainsSomewhere(
entries, pos, NetLogEventType::COOKIE_PERSISTENT_STORE_KEY_LOAD_STARTED,
NetLogEventPhase::NONE);
EXPECT_FALSE(GetOptionalStringValueFromParams(entries[pos], "key"));
pos = ExpectLogContainsSomewhere(
entries, pos, NetLogEventType::COOKIE_PERSISTENT_STORE_KEY_LOAD_COMPLETED,
NetLogEventPhase::NONE);
pos = ExpectLogContainsSomewhere(
entries, pos, NetLogEventType::COOKIE_PERSISTENT_STORE_LOAD,
NetLogEventPhase::END);
ExpectLogContainsSomewhere(entries, pos,
NetLogEventType::COOKIE_PERSISTENT_STORE_CLOSED,
NetLogEventPhase::NONE);
}
TEST_F(SQLitePersistentCookieStoreTest, TestBeforeCommitCallback) {
InitializeStore(/*crypt=*/false, /*restore_old_session_cookies=*/false);
struct Counter {
int count = 0;
void increment() { count++; }
};
Counter counter;
store_->SetBeforeCommitCallback(
base::BindRepeating(&Counter::increment, base::Unretained(&counter)));
// The implementation of SQLitePersistentCookieStore::Backend flushes changes
// after 30s or 512 pending operations. Add 512 cookies to the store to test
// that the callback gets called when SQLitePersistentCookieStore internally
// flushes its store.
for (int i = 0; i < 512; i++) {
// Each cookie needs a unique timestamp for creation_utc (see DB schema).
base::Time t = base::Time::Now() + base::Microseconds(i);
AddCookie(base::StringPrintf("%d", i), "foo", "example.com", "/", t);
}
RunUntilIdle();
EXPECT_GT(counter.count, 0);
DestroyStore();
}
// Test that we can force the database to be written by calling Flush().
TEST_F(SQLitePersistentCookieStoreTest, TestFlush) {
InitializeStore(/*crypt=*/false, /*restore_old_session_cookies=*/false);
// File timestamps don't work well on all platforms, so we'll determine
// whether the DB file has been modified by checking its size.
base::FilePath path = temp_dir_.GetPath().Append(kCookieFilename);
base::File::Info info;
ASSERT_TRUE(base::GetFileInfo(path, &info));
int64_t base_size = info.size;
// Write some large cookies, so the DB will have to expand by several KB.
for (char c = 'a'; c < 'z'; ++c) {
// Each cookie needs a unique timestamp for creation_utc (see DB schema).
base::Time t = base::Time::Now() + base::Microseconds(c);
std::string name(1, c);
std::string value(1000, c);
AddCookie(name, value, "foo.bar", "/", t);
}
Flush();
// We forced a write, so now the file will be bigger.
ASSERT_TRUE(base::GetFileInfo(path, &info));
ASSERT_GT(info.size, base_size);
}
// Test loading old session cookies from the disk.
TEST_F(SQLitePersistentCookieStoreTest, TestLoadOldSessionCookies) {
InitializeStore(/*crypt=*/false, /*restore_old_session_cookies=*/true);
// Add a session cookie.
store_->AddCookie(*CanonicalCookie::CreateUnsafeCookieForTesting(
"C", "D", "sessioncookie.com", "/", /*creation=*/base::Time::Now(),
/*expiration=*/base::Time(),
/*last_access=*/base::Time(), /*last_update=*/base::Time(),
/*secure=*/false, /*httponly=*/false, CookieSameSite::NO_RESTRICTION,
COOKIE_PRIORITY_DEFAULT));
// Force the store to write its data to the disk.
DestroyStore();
// Create a store that loads session cookies and test that the session cookie
// was loaded.
CanonicalCookieVector cookies = CreateAndLoad(
/*crypt_cookies=*/false, /*restore_old_session_cookies=*/true);
ASSERT_EQ(1U, cookies.size());
ASSERT_STREQ("sessioncookie.com", cookies[0]->Domain().c_str());
ASSERT_STREQ("C", cookies[0]->Name().c_str());
ASSERT_STREQ("D", cookies[0]->Value().c_str());
ASSERT_EQ(COOKIE_PRIORITY_DEFAULT, cookies[0]->Priority());
}
// Test refusing to load old session cookies from the disk.
TEST_F(SQLitePersistentCookieStoreTest, TestDontLoadOldSessionCookies) {
InitializeStore(/*crypt=*/false, /*restore_old_session_cookies=*/true);
// Add a session cookie.
store_->AddCookie(*CanonicalCookie::CreateUnsafeCookieForTesting(
"C", "D", "sessioncookie.com", "/", /*creation=*/base::Time::Now(),
/*expiration=*/base::Time(),
/*last_access=*/base::Time(), /*last_update=*/base::Time(),
/*secure=*/false, /*httponly=*/false, CookieSameSite::NO_RESTRICTION,
COOKIE_PRIORITY_DEFAULT));
// Force the store to write its data to the disk.
DestroyStore();
// Create a store that doesn't load old session cookies and test that the
// session cookie was not loaded.
CanonicalCookieVector cookies = CreateAndLoad(
/*crypt_cookies=*/false, /*restore_old_session_cookies=*/false);
ASSERT_EQ(0U, cookies.size());
// The store should also delete the session cookie. Wait until that has been
// done.
DestroyStore();
// Create a store that loads old session cookies and test that the session
// cookie is gone.
cookies = CreateAndLoad(/*crypt_cookies=*/false,
/*restore_old_session_cookies=*/true);
ASSERT_EQ(0U, cookies.size());
}
// Confirm bad cookies on disk don't get looaded, and that we also remove them
// from the database.
TEST_F(SQLitePersistentCookieStoreTest, FilterBadCookiesAndFixupDb) {
// Create an on-disk store.
InitializeStore(/*crypt=*/false, /*restore_old_session_cookies=*/true);
DestroyStore();
// Add some cookies in by hand.
base::FilePath store_name(temp_dir_.GetPath().Append(kCookieFilename));
std::unique_ptr<sql::Database> db(
std::make_unique<sql::Database>(sql::test::kTestTag));
ASSERT_TRUE(db->Open(store_name));
sql::Statement stmt(db->GetUniqueStatement(
"INSERT INTO cookies (creation_utc, host_key, top_frame_site_key, name, "
"value, encrypted_value, path, expires_utc, is_secure, is_httponly, "
"samesite, last_access_utc, has_expires, is_persistent, priority, "
"source_scheme, source_port, last_update_utc, source_type, "
"has_cross_site_ancestor) "
"VALUES (?,?,?,?,?,'',?,0,0,0,0,0,1,1,0,?,?,?,0,0)"));
ASSERT_TRUE(stmt.is_valid());
struct CookieInfo {
const char* domain;
const char* name;
const char* value;
const char* path;
} cookies_info[] = {// A couple non-canonical cookies.
{"google.izzle", "A=", "B", "/path"},
{"google.izzle", "C ", "D", "/path"},
// A canonical cookie for same eTLD+1. This one will get
// dropped out of precaution to avoid confusing the site,
// even though there is nothing wrong with it.
{"sub.google.izzle", "E", "F", "/path"},
// A canonical cookie for another eTLD+1
{"chromium.org", "G", "H", "/dir"}};
int64_t creation_time = 1;
base::Time last_update(base::Time::Now());
for (auto& cookie_info : cookies_info) {
stmt.Reset(true);
stmt.BindInt64(0, creation_time++);
stmt.BindString(1, cookie_info.domain);
// TODO(crbug.com/40188414) Test some non-empty values when CanonicalCookie
// supports partition key.
stmt.BindString(2, net::kEmptyCookiePartitionKey);
stmt.BindString(3, cookie_info.name);
stmt.BindString(4, cookie_info.value);
stmt.BindString(5, cookie_info.path);
stmt.BindInt(6, static_cast<int>(CookieSourceScheme::kUnset));
stmt.BindInt(7, SQLitePersistentCookieStore::kDefaultUnknownPort);
stmt.BindTime(8, last_update);
ASSERT_TRUE(stmt.Run());
}
stmt.Clear();
db.reset();
// Reopen the store and confirm that the only cookie loaded is the
// canonical one on an unrelated domain.
CanonicalCookieVector cookies = CreateAndLoad(
/*crypt_cookies=*/false, /*restore_old_session_cookies=*/false);
ASSERT_EQ(1U, cookies.size());
EXPECT_STREQ("chromium.org", cookies[0]->Domain().c_str());
EXPECT_STREQ("G", cookies[0]->Name().c_str());
EXPECT_STREQ("H", cookies[0]->Value().c_str());
EXPECT_STREQ("/dir", cookies[0]->Path().c_str());
EXPECT_EQ(last_update, cookies[0]->LastUpdateDate());
DestroyStore();
// Make sure that we only have one row left.
db = std::make_unique<sql::Database>(sql::test::kTestTag);
ASSERT_TRUE(db->Open(store_name));
sql::Statement verify_stmt(db->GetUniqueStatement("SELECT * FROM COOKIES"));
ASSERT_TRUE(verify_stmt.is_valid());
EXPECT_TRUE(verify_stmt.Step());
EXPECT_TRUE(verify_stmt.Succeeded());
// Confirm only one match.
EXPECT_FALSE(verify_stmt.Step());
}
TEST_F(SQLitePersistentCookieStoreTest, PersistIsPersistent) {
InitializeStore(/*crypt=*/false, /*restore_old_session_cookies=*/true);
static const char kSessionName[] = "session";
static const char kPersistentName[] = "persistent";
// Add a session cookie.
store_->AddCookie(*CanonicalCookie::CreateUnsafeCookieForTesting(
kSessionName, "val", "sessioncookie.com", "/",
/*creation=*/base::Time::Now(),
/*expiration=*/base::Time(), /*last_access=*/base::Time(),
/*last_update=*/base::Time(), /*secure=*/false, /*httponly=*/false,
CookieSameSite::NO_RESTRICTION, COOKIE_PRIORITY_DEFAULT));
// Add a persistent cookie.
store_->AddCookie(*CanonicalCookie::CreateUnsafeCookieForTesting(
kPersistentName, "val", "sessioncookie.com", "/",
/*creation=*/base::Time::Now() - base::Days(1),
/*expiration=*/base::Time::Now() + base::Days(1),
/*last_access=*/base::Time(), /*last_update=*/base::Time(),
/*secure=*/false, /*httponly=*/false, CookieSameSite::NO_RESTRICTION,
COOKIE_PRIORITY_DEFAULT));
// Force the store to write its data to the disk.
DestroyStore();
// Create a store that loads session cookie and test that the IsPersistent
// attribute is restored.
CanonicalCookieVector cookies = CreateAndLoad(
/*crypt_cookies=*/false, /*restore_old_session_cookies=*/true);
ASSERT_EQ(2U, cookies.size());
std::map<std::string, CanonicalCookie*> cookie_map;
for (const auto& cookie : cookies) {
cookie_map[cookie->Name()] = cookie.get();
}
auto it = cookie_map.find(kSessionName);
ASSERT_TRUE(it != cookie_map.end());
EXPECT_FALSE(cookie_map[kSessionName]->IsPersistent());
it = cookie_map.find(kPersistentName);
ASSERT_TRUE(it != cookie_map.end());
EXPECT_TRUE(cookie_map[kPersistentName]->IsPersistent());
}
TEST_F(SQLitePersistentCookieStoreTest, PriorityIsPersistent) {
static const char kDomain[] = "sessioncookie.com";
static const char kLowName[] = "low";
static const char kMediumName[] = "medium";
static const char kHighName[] = "high";
static const char kCookieValue[] = "value";
static const char kCookiePath[] = "/";
InitializeStore(/*crypt=*/false, /*restore_old_session_cookies=*/true);
// Add a low-priority persistent cookie.
store_->AddCookie(*CanonicalCookie::CreateUnsafeCookieForTesting(
kLowName, kCookieValue, kDomain, kCookiePath,
/*creation=*/base::Time::Now() - base::Minutes(1),
/*expiration=*/base::Time::Now() + base::Days(1),
/*last_access=*/base::Time(), /*last_update=*/base::Time(),
/*secure=*/false, /*httponly=*/false, CookieSameSite::NO_RESTRICTION,
COOKIE_PRIORITY_LOW));
// Add a medium-priority persistent cookie.
store_->AddCookie(*CanonicalCookie::CreateUnsafeCookieForTesting(
kMediumName, kCookieValue, kDomain, kCookiePath,
/*creation=*/base::Time::Now() - base::Minutes(2),
/*expiration=*/base::Time::Now() + base::Days(1),
/*last_access=*/base::Time(), /*last_update=*/base::Time(),
/*secure=*/false, /*httponly=*/false, CookieSameSite::NO_RESTRICTION,
COOKIE_PRIORITY_MEDIUM));
// Add a high-priority persistent cookie.
store_->AddCookie(*CanonicalCookie::CreateUnsafeCookieForTesting(
kHighName, kCookieValue, kDomain, kCookiePath,
/*creation=*/base::Time::Now() - base::Minutes(3),
/*expiration=*/base::Time::Now() + base::Days(1),
/*last_access=*/base::Time(), /*last_update=*/base::Time(),
/*secure=*/false, /*httponly=*/false, CookieSameSite::NO_RESTRICTION,
COOKIE_PRIORITY_HIGH));
// Force the store to write its data to the disk.
DestroyStore();
// Create a store that loads session cookie and test that the priority
// attribute values are restored.
CanonicalCookieVector cookies = CreateAndLoad(
/*crypt_cookies=*/false, /*restore_old_session_cookies=*/true);
ASSERT_EQ(3U, cookies.size());
// Put the cookies into a map, by name, so we can easily find them.
std::map<std::string, CanonicalCookie*> cookie_map;
for (const auto& cookie : cookies) {
cookie_map[cookie->Name()] = cookie.get();
}
// Validate that each cookie has the correct priority.
auto it = cookie_map.find(kLowName);
ASSERT_TRUE(it != cookie_map.end());
EXPECT_EQ(COOKIE_PRIORITY_LOW, cookie_map[kLowName]->Priority());
it = cookie_map.find(kMediumName);
ASSERT_TRUE(it != cookie_map.end());
EXPECT_EQ(COOKIE_PRIORITY_MEDIUM, cookie_map[kMediumName]->Priority());
it = cookie_map.find(kHighName);
ASSERT_TRUE(it != cookie_map.end());
EXPECT_EQ(COOKIE_PRIORITY_HIGH, cookie_map[kHighName]->Priority());
}
TEST_F(SQLitePersistentCookieStoreTest, SameSiteIsPersistent) {
const char kDomain[] = "sessioncookie.com";
const char kNoneName[] = "none";
const char kLaxName[] = "lax";
const char kStrictName[] = "strict";
const char kCookieValue[] = "value";
const char kCookiePath[] = "/";
InitializeStore(/*crypt=*/false, /*restore_old_session_cookies=*/true);
// Add a non-samesite persistent cookie.
store_->AddCookie(*CanonicalCookie::CreateUnsafeCookieForTesting(
kNoneName, kCookieValue, kDomain, kCookiePath,
/*creation=*/base::Time::Now() - base::Minutes(1),
/*expiration=*/base::Time::Now() + base::Days(1),
/*last_access=*/base::Time(), /*last_update=*/base::Time(),
/*secure=*/false, /*httponly=*/false, CookieSameSite::NO_RESTRICTION,
COOKIE_PRIORITY_DEFAULT));
// Add a lax-samesite persistent cookie.
store_->AddCookie(*CanonicalCookie::CreateUnsafeCookieForTesting(
kLaxName, kCookieValue, kDomain, kCookiePath,
/*creation=*/base::Time::Now() - base::Minutes(2),
/*expiration=*/base::Time::Now() + base::Days(1),
/*last_access=*/base::Time(), /*last_update=*/base::Time(),
/*secure=*/false, /*httponly=*/false, CookieSameSite::LAX_MODE,
COOKIE_PRIORITY_DEFAULT));
// Add a strict-samesite persistent cookie.
store_->AddCookie(*CanonicalCookie::CreateUnsafeCookieForTesting(
kStrictName, kCookieValue, kDomain, kCookiePath,
/*creation=*/base::Time::Now() - base::Minutes(3),
/*expiration=*/base::Time::Now() + base::Days(1),
/*last_access=*/base::Time(), /*last_update=*/base::Time(),
/*secure=*/false, /*httponly=*/false, CookieSameSite::STRICT_MODE,
COOKIE_PRIORITY_DEFAULT));
// Force the store to write its data to the disk.
DestroyStore();
// Create a store that loads session cookie and test that the SameSite
// attribute values are restored.
CanonicalCookieVector cookies = CreateAndLoad(
/*crypt_cookies=*/false, /*restore_old_session_cookies=*/true);
ASSERT_EQ(3U, cookies.size());
// Put the cookies into a map, by name, for comparison below.
std::map<std::string, CanonicalCookie*> cookie_map;
for (const auto& cookie : cookies) {
cookie_map[cookie->Name()] = cookie.get();
}
// Validate that each cookie has the correct SameSite.
ASSERT_EQ(1u, cookie_map.count(kNoneName));
EXPECT_EQ(CookieSameSite::NO_RESTRICTION, cookie_map[kNoneName]->SameSite());
ASSERT_EQ(1u, cookie_map.count(kLaxName));
EXPECT_EQ(CookieSameSite::LAX_MODE, cookie_map[kLaxName]->SameSite());
ASSERT_EQ(1u, cookie_map.count(kStrictName));
EXPECT_EQ(CookieSameSite::STRICT_MODE, cookie_map[kStrictName]->SameSite());
}
TEST_F(SQLitePersistentCookieStoreTest, SameSiteExtendedTreatedAsUnspecified) {
constexpr char kDomain[] = "sessioncookie.com";
constexpr char kExtendedName[] = "extended";
constexpr char kCookieValue[] = "value";
constexpr char kCookiePath[] = "/";
InitializeStore(/*crypt=*/false, /*restore_old_session_cookies=*/true);
// Add an extended-samesite persistent cookie by first adding a strict-same
// site cookie, then turning that into the legacy extended-samesite state with
// direct SQL DB access.
store_->AddCookie(*CanonicalCookie::CreateUnsafeCookieForTesting(
kExtendedName, kCookieValue, kDomain, kCookiePath,
/*creation=*/base::Time::Now() - base::Minutes(1),
/*expiration=*/base::Time::Now() + base::Days(1),
/*last_access=*/base::Time(), /*last_update=*/base::Time(),
/*secure=*/false, /*httponly=*/false, CookieSameSite::STRICT_MODE,
COOKIE_PRIORITY_DEFAULT));
// Force the store to write its data to the disk.
DestroyStore();
// Open db.
sql::Database connection(sql::test::kTestTag);
ASSERT_TRUE(connection.Open(temp_dir_.GetPath().Append(kCookieFilename)));
std::string update_stmt(
"UPDATE cookies SET samesite=3" // 3 is Extended.
" WHERE samesite=2" // 2 is Strict.
);
ASSERT_TRUE(connection.Execute(update_stmt));
connection.Close();
// Create a store that loads session cookie and test that the
// SameSite=Extended attribute values is ignored.
CanonicalCookieVector cookies = CreateAndLoad(
/*crypt_cookies=*/false, /*restore_old_session_cookies=*/true);
ASSERT_EQ(1U, cookies.size());
// Validate that the cookie has the correct SameSite.
EXPECT_EQ(kExtendedName, cookies[0]->Name());
EXPECT_EQ(CookieSameSite::UNSPECIFIED, cookies[0]->SameSite());
}
TEST_F(SQLitePersistentCookieStoreTest, SourcePortIsPersistent) {
const char kDomain[] = "sessioncookie.com";
const char kCookieValue[] = "value";
const char kCookiePath[] = "/";
struct CookieTestValues {
std::string name;
int port;
};
const std::vector<CookieTestValues> kTestCookies = {
{"1", 80},
{"2", 443},
{"3", 1234},
{"4", url::PORT_UNSPECIFIED},
{"5", url::PORT_INVALID}};
InitializeStore(/*crypt=*/false, /*restore_old_session_cookies=*/true);
for (const auto& input : kTestCookies) {
// Add some persistent cookies.
store_->AddCookie(*CanonicalCookie::CreateUnsafeCookieForTesting(
input.name, kCookieValue, kDomain, kCookiePath,
/*creation=*/base::Time::Now() - base::Minutes(1),
/*expiration=*/base::Time::Now() + base::Days(1),
/*last_access=*/base::Time(), /*last_update=*/base::Time(),
/*secure=*/true, /*httponly=*/false, CookieSameSite::LAX_MODE,
COOKIE_PRIORITY_DEFAULT,
/*partition_key=*/std::nullopt,
CookieSourceScheme::kUnset /* Doesn't matter for this test. */,
input.port));
}
// Force the store to write its data to the disk.
DestroyStore();
// Create a store that loads session cookie and test that the source_port
// attribute values are restored.
CanonicalCookieVector cookies = CreateAndLoad(
/*crypt_cookies=*/false, /*restore_old_session_cookies=*/true);
ASSERT_EQ(kTestCookies.size(), cookies.size());
// Put the cookies into a map, by name, for comparison below.
std::map<std::string, CanonicalCookie*> cookie_map;
for (const auto& cookie : cookies) {
cookie_map[cookie->Name()] = cookie.get();
}
for (const auto& expected : kTestCookies) {
ASSERT_EQ(1u, cookie_map.count(expected.name));
ASSERT_EQ(expected.port, cookie_map[expected.name]->SourcePort());
}
}
TEST_F(SQLitePersistentCookieStoreTest, UpdateToEncryption) {
// Create unencrypted cookie store and write something to it.
InitializeStore(/*crypt=*/false, /*restore_old_session_cookies=*/false);
AddCookie("name", "value123XYZ", "foo.bar", "/", base::Time::Now());
DestroyStore();
// Verify that "value" is visible in the file. This is necessary in order to
// have confidence in a later test that "encrypted_value" is not visible.
std::string contents = ReadRawDBContents();
EXPECT_NE(0U, contents.length());
EXPECT_NE(contents.find("value123XYZ"), std::string::npos);
// Create encrypted cookie store and ensure old cookie still reads.
CanonicalCookieVector cookies = CreateAndLoad(
/*crypt_cookies=*/true, /*restore_old_session_cookies=*/false);
EXPECT_EQ(1U, cookies.size());
EXPECT_EQ("name", cookies[0]->Name());
EXPECT_EQ("value123XYZ", cookies[0]->Value());
// Make sure we can update existing cookie and add new cookie as encrypted.
store_->DeleteCookie(*(cookies[0]));
AddCookie("name", "encrypted_value123XYZ", "foo.bar", "/", base::Time::Now());
AddCookie("other", "something456ABC", "foo.bar", "/",
base::Time::Now() + base::Microseconds(10));
DestroyStore();
cookies = CreateAndLoad(/*crypt_cookies=*/true,
/*restore_old_session_cookies=*/false);
EXPECT_EQ(2U, cookies.size());
CanonicalCookie* cookie_name = nullptr;
CanonicalCookie* cookie_other = nullptr;
if (cookies[0]->Name() == "name") {
cookie_name = cookies[0].get();
cookie_other = cookies[1].get();
} else {
cookie_name = cookies[1].get();
cookie_other = cookies[0].get();
}
EXPECT_EQ("encrypted_value123XYZ", cookie_name->Value());
EXPECT_EQ("something456ABC", cookie_other->Value());
DestroyStore();
// Examine the real record to make sure plaintext version doesn't exist.
sql::Database db(sql::test::kTestTag);
sql::Statement smt;
ASSERT_TRUE(db.Open(temp_dir_.GetPath().Append(kCookieFilename)));
smt.Assign(db.GetCachedStatement(SQL_FROM_HERE,
"SELECT * "
"FROM cookies "
"WHERE host_key = 'foo.bar'"));
int resultcount = 0;
for (; smt.Step(); ++resultcount) {
for (int i = 0; i < smt.ColumnCount(); i++) {
EXPECT_EQ(smt.ColumnString(i).find("value"), std::string::npos);
EXPECT_EQ(smt.ColumnString(i).find("something"), std::string::npos);
}
}
EXPECT_EQ(2, resultcount);
// Verify that "encrypted_value" is NOT visible in the file.
contents = ReadRawDBContents();
EXPECT_NE(0U, contents.length());
EXPECT_EQ(contents.find("encrypted_value123XYZ"), std::string::npos);
EXPECT_EQ(contents.find("something456ABC"), std::string::npos);
}
bool CompareCookies(const std::unique_ptr<CanonicalCookie>& a,
const std::unique_ptr<CanonicalCookie>& b) {
CHECK(a);
CHECK(b);
return *a < *b;
}
// Confirm the store can handle having cookies with identical creation
// times stored in it.
TEST_F(SQLitePersistentCookieStoreTest, IdenticalCreationTimes) {
InitializeStore(/*crypt=*/false, /*restore_old_session_cookies=*/false);
base::Time cookie_time(base::Time::Now());
base::Time cookie_expiry(cookie_time + base::Days(1));
AddCookieWithExpiration("A", "B", "example.com", "/", cookie_time,
cookie_expiry);
AddCookieWithExpiration("C", "B", "example.com", "/", cookie_time,
cookie_expiry);
AddCookieWithExpiration("A", "B", "example2.com", "/", cookie_time,
cookie_expiry);
AddCookieWithExpiration("C", "B", "example2.com", "/", cookie_time,
cookie_expiry);
AddCookieWithExpiration("A", "B", "example.com", "/path", cookie_time,
cookie_expiry);
AddCookieWithExpiration("C", "B", "example.com", "/path", cookie_time,
cookie_expiry);
Flush();
DestroyStore();
CanonicalCookieVector read_in_cookies = CreateAndLoad(
/*crypt_cookies=*/false, /*restore_old_session_cookies=*/false);
ASSERT_EQ(6u, read_in_cookies.size());
std::sort(read_in_cookies.begin(), read_in_cookies.end(), &CompareCookies);
int i = 0;
EXPECT_EQ("A", read_in_cookies[i]->Name());
EXPECT_EQ("example.com", read_in_cookies[i]->Domain());
EXPECT_EQ("/", read_in_cookies[i]->Path());
i++;
EXPECT_EQ("A", read_in_cookies[i]->Name());
EXPECT_EQ("example.com", read_in_cookies[i]->Domain());
EXPECT_EQ("/path", read_in_cookies[i]->Path());
i++;
EXPECT_EQ("A", read_in_cookies[i]->Name());
EXPECT_EQ("example2.com", read_in_cookies[i]->Domain());
EXPECT_EQ("/", read_in_cookies[i]->Path());
i++;
EXPECT_EQ("C", read_in_cookies[i]->Name());
EXPECT_EQ("example.com", read_in_cookies[i]->Domain());
EXPECT_EQ("/", read_in_cookies[i]->Path());
i++;
EXPECT_EQ("C", read_in_cookies[i]->Name());
EXPECT_EQ("example.com", read_in_cookies[i]->Domain());
EXPECT_EQ("/path", read_in_cookies[i]->Path());
i++;
EXPECT_EQ("C", read_in_cookies[i]->Name());
EXPECT_EQ("example2.com", read_in_cookies[i]->Domain());
EXPECT_EQ("/", read_in_cookies[i]->Path());
}
TEST_F(SQLitePersistentCookieStoreTest, KeyInconsistency) {
// Regression testcase for previous disagreement between CookieMonster
// and SQLitePersistentCookieStoreTest as to what keys to LoadCookiesForKey
// mean. The particular example doesn't, of course, represent an actual in-use
// scenario, but while the inconstancy could happen with chrome-extension
// URLs in real life, it was irrelevant for them in practice since their
// rows would get key = "" which would get sorted before actual domains,
// and therefore get loaded first by CookieMonster::FetchAllCookiesIfNecessary
// with the task runners involved ensuring that would finish before the
// incorrect LoadCookiesForKey got the chance to run.
//
// This test uses a URL that used to be treated differently by the two
// layers that also sorts after other rows to avoid this scenario.
// SQLitePersistentCookieStore will run its callbacks on what's passed to it
// as |client_task_runner|, and CookieMonster expects to get callbacks from
// its PersistentCookieStore on the same thread as its methods are invoked on;
// so to avoid needing to post every CookieMonster API call, this uses the
// current thread for SQLitePersistentCookieStore's |client_task_runner|.
// Note: Cookie encryption is explicitly enabled here to verify threading
// model with async initialization functions correctly.
Create(/*crypt_cookies=*/true, /*restore_old_session_cookies=*/false,
/*use_current_thread=*/true, /*enable_exclusive_access=*/false);
// Create a cookie on a scheme that doesn't handle cookies by default,
// and save it.
std::unique_ptr<CookieMonster> cookie_monster =
std::make_unique<CookieMonster>(store_.get(), /*net_log=*/nullptr);
ResultSavingCookieCallback<bool> cookie_scheme_callback1;
cookie_monster->SetCookieableSchemes({"ftp", "http"},
cookie_scheme_callback1.MakeCallback());
cookie_scheme_callback1.WaitUntilDone();
EXPECT_TRUE(cookie_scheme_callback1.result());
ResultSavingCookieCallback<CookieAccessResult> set_cookie_callback;
GURL ftp_url("ftp://subdomain.ftperiffic.com/page/");
auto cookie = CanonicalCookie::CreateForTesting(ftp_url, "A=B; max-age=3600",
base::Time::Now());
cookie_monster->SetCanonicalCookieAsync(std::move(cookie), ftp_url,
CookieOptions::MakeAllInclusive(),
set_cookie_callback.MakeCallback());
set_cookie_callback.WaitUntilDone();
EXPECT_TRUE(set_cookie_callback.result().status.IsInclude());
// Also insert a whole bunch of cookies to slow down the background loading of
// all the cookies.
for (int i = 0; i < 50; ++i) {
ResultSavingCookieCallback<CookieAccessResult> set_cookie_callback2;
GURL url(base::StringPrintf("http://example%d.com/", i));
auto canonical_cookie = CanonicalCookie::CreateForTesting(
url, "A=B; max-age=3600", base::Time::Now());
cookie_monster->SetCanonicalCookieAsync(
std::move(canonical_cookie), url, CookieOptions::MakeAllInclusive(),
set_cookie_callback2.MakeCallback());
set_cookie_callback2.WaitUntilDone();
EXPECT_TRUE(set_cookie_callback2.result().status.IsInclude());
}
net::TestClosure flush_closure;
cookie_monster->FlushStore(flush_closure.closure());
flush_closure.WaitForResult();
cookie_monster = nullptr;
// Re-create the PersistentCookieStore & CookieMonster. Note that the
// destroyed store's ops will happen on same runners as the previous
// instances, so they should complete before the new PersistentCookieStore
// starts looking at the state on disk.
Create(/*crypt_cookies=*/true, /*restore_old_session_cookies=*/false,
/*use_current_thread=*/true, /*enable_exclusive_access=*/false);
cookie_monster =
std::make_unique<CookieMonster>(store_.get(), /*net_log=*/nullptr);
ResultSavingCookieCallback<bool> cookie_scheme_callback2;
cookie_monster->SetCookieableSchemes({"ftp", "http"},
cookie_scheme_callback2.MakeCallback());
cookie_scheme_callback2.WaitUntilDone();
EXPECT_TRUE(cookie_scheme_callback2.result());
// Now try to get the cookie back.
GetCookieListCallback get_callback;
cookie_monster->GetCookieListWithOptionsAsync(
GURL("ftp://subdomain.ftperiffic.com/page"),
CookieOptions::MakeAllInclusive(), CookiePartitionKeyCollection(),
base::BindOnce(&GetCookieListCallback::Run,
base::Unretained(&get_callback)));
get_callback.WaitUntilDone();
ASSERT_EQ(1u, get_callback.cookies().size());
EXPECT_EQ("A", get_callback.cookies()[0].Name());
EXPECT_EQ("B", get_callback.cookies()[0].Value());
EXPECT_EQ("subdomain.ftperiffic.com", get_callback.cookies()[0].Domain());
}
TEST_F(SQLitePersistentCookieStoreTest, OpsIfInitFailed) {
// Test to make sure we don't leak pending operations when initialization
// fails really hard. To inject the failure, we put a directory where the
// database file ought to be. This test relies on an external leak checker
// (e.g. lsan) to actual catch thing.
ASSERT_TRUE(
base::CreateDirectory(temp_dir_.GetPath().Append(kCookieFilename)));
Create(/*crypt_cookies=*/false, /*restore_old_session_cookies=*/false,
/*use_current_thread=*/true,
/*enable_exclusive_access=*/false);
std::unique_ptr<CookieMonster> cookie_monster =
std::make_unique<CookieMonster>(store_.get(), /*net_log=*/nullptr);
ResultSavingCookieCallback<CookieAccessResult> set_cookie_callback;
GURL url("http://www.example.com/");
auto cookie = CanonicalCookie::CreateForTesting(url, "A=B; max-age=3600",
base::Time::Now());
cookie_monster->SetCanonicalCookieAsync(std::move(cookie), url,
CookieOptions::MakeAllInclusive(),
set_cookie_callback.MakeCallback());
set_cookie_callback.WaitUntilDone();
EXPECT_TRUE(set_cookie_callback.result().status.IsInclude());
// Things should commit once going out of scope.
expect_init_errors_ = true;
}
TEST_F(SQLitePersistentCookieStoreTest, Coalescing) {
enum class Op { kAdd, kDelete, kUpdate };
struct TestCase {
std::vector<Op> operations;
size_t expected_queue_length;
};
std::vector<TestCase> testcases = {
{{Op::kAdd, Op::kDelete}, 1u},
{{Op::kUpdate, Op::kDelete}, 1u},
{{Op::kAdd, Op::kUpdate, Op::kDelete}, 1u},
{{Op::kUpdate, Op::kUpdate}, 1u},
{{Op::kAdd, Op::kUpdate, Op::kUpdate}, 2u},
{{Op::kDelete, Op::kAdd}, 2u},
{{Op::kDelete, Op::kAdd, Op::kUpdate}, 3u},
{{Op::kDelete, Op::kAdd, Op::kUpdate, Op::kUpdate}, 3u},
{{Op::kDelete, Op::kDelete}, 1u},
{{Op::kDelete, Op::kAdd, Op::kDelete}, 1u},
{{Op::kDelete, Op::kAdd, Op::kUpdate, Op::kDelete}, 1u}};
std::unique_ptr<CanonicalCookie> cookie = CanonicalCookie::CreateForTesting(
GURL("http://www.example.com/path"), "Tasty=Yes", base::Time::Now());
for (const TestCase& testcase : testcases) {
Create(/*crypt_cookies=*/false, /*restore_old_session_cookies=*/false,
/*use_current_thread=*/true,
/*enable_exclusive_access=*/false);
base::RunLoop run_loop;
store_->Load(base::BindLambdaForTesting(
[&](CanonicalCookieVector cookies) { run_loop.Quit(); }),
NetLogWithSource());
run_loop.Run();
// Wedge the background thread to make sure that it doesn't start consuming
// the queue.
background_task_runner_->PostTask(
FROM_HERE,
base::BindOnce(&SQLitePersistentCookieStoreTest::WaitOnDBEvent,
base::Unretained(this)));
// Now run the ops, and check how much gets queued.
for (const Op op : testcase.operations) {
switch (op) {
case Op::kAdd:
store_->AddCookie(*cookie);
break;
case Op::kDelete:
store_->DeleteCookie(*cookie);
break;
case Op::kUpdate:
store_->UpdateCookieAccessTime(*cookie);
break;
}
}
EXPECT_EQ(testcase.expected_queue_length,
store_->GetQueueLengthForTesting());
db_thread_event_.Signal();
DestroyStore();
}
}
TEST_F(SQLitePersistentCookieStoreTest, NoCoalesceUnrelated) {
Create(/*crypt_cookies=*/false, /*restore_old_session_cookies=*/false,
/*use_current_thread=*/true,
/*enable_exclusive_access=*/false);
base::RunLoop run_loop;
store_->Load(base::BindLambdaForTesting(
[&](CanonicalCookieVector cookies) { run_loop.Quit(); }),
NetLogWithSource());
run_loop.Run();
std::unique_ptr<CanonicalCookie> cookie1 = CanonicalCookie::CreateForTesting(
GURL("http://www.example.com/path"), "Tasty=Yes", base::Time::Now());
std::unique_ptr<CanonicalCookie> cookie2 = CanonicalCookie::CreateForTesting(
GURL("http://not.example.com/path"), "Tasty=No", base::Time::Now());
// Wedge the background thread to make sure that it doesn't start consuming
// the queue.
background_task_runner_->PostTask(
FROM_HERE, base::BindOnce(&SQLitePersistentCookieStoreTest::WaitOnDBEvent,
base::Unretained(this)));
store_->AddCookie(*cookie1);
store_->DeleteCookie(*cookie2);
// delete on cookie2 shouldn't cancel op on unrelated cookie1.
EXPECT_EQ(2u, store_->GetQueueLengthForTesting());
db_thread_event_.Signal();
}
// Locking is only supported on Windows.
#if BUILDFLAG(IS_WIN)
class SQLitePersistentCookieStoreExclusiveAccessTest
: public SQLitePersistentCookieStoreTest,
public ::testing::WithParamInterface<bool> {
protected:
const bool& ShouldBeExclusive() { return GetParam(); }
};
TEST_P(SQLitePersistentCookieStoreExclusiveAccessTest, LockedStore) {
Create(/*crypt_cookies=*/false, /*restore_old_session_cookies=*/false,
/*use_current_thread=*/true,
/*enable_exclusive_access=*/ShouldBeExclusive());
base::RunLoop run_loop;
store_->Load(base::BindLambdaForTesting(
[&](CanonicalCookieVector cookies) { run_loop.Quit(); }),
NetLogWithSource());
run_loop.Run();
std::unique_ptr<CanonicalCookie> cookie = CanonicalCookie::CreateForTesting(
GURL("http://www.example.com/path"), "Tasty=Yes", base::Time::Now());
// Wedge the background thread to make sure that it doesn't start consuming
// the queue.
background_task_runner_->PostTask(
FROM_HERE, base::BindOnce(&SQLitePersistentCookieStoreTest::WaitOnDBEvent,
base::Unretained(this)));
store_->AddCookie(*cookie);
{
base::File file(
temp_dir_.GetPath().Append(kCookieFilename),
base::File::Flags::FLAG_OPEN_ALWAYS | base::File::Flags::FLAG_READ);
// If locked, should not be able to open file even for read.
EXPECT_EQ(ShouldBeExclusive(), !file.IsValid());
}
db_thread_event_.Signal();
}
TEST_P(SQLitePersistentCookieStoreExclusiveAccessTest, LockedStoreAlreadyOpen) {
base::HistogramTester histograms;
base::File file(
temp_dir_.GetPath().Append(kCookieFilename),
base::File::Flags::FLAG_CREATE | base::File::Flags::FLAG_READ);
ASSERT_TRUE(file.IsValid());
Create(/*crypt_cookies=*/false, /*restore_old_session_cookies=*/false,
/*use_current_thread=*/true,
/*enable_exclusive_access=*/ShouldBeExclusive());
base::RunLoop run_loop;
store_->Load(base::BindLambdaForTesting(
[&](CanonicalCookieVector cookies) { run_loop.Quit(); }),
NetLogWithSource());
run_loop.Run();
// Note: The non-exclusive path is verified in the TearDown for the fixture.
if (ShouldBeExclusive()) {
expect_init_errors_ = true;
histograms.ExpectUniqueSample("Cookie.ErrorInitializeDB",
sql::SqliteLoggedResultCode::kCantOpen, 1);
histograms.ExpectUniqueSample("Cookie.WinGetLastErrorInitializeDB",
ERROR_SHARING_VIOLATION, 1);
}
}
INSTANTIATE_TEST_SUITE_P(All,
SQLitePersistentCookieStoreExclusiveAccessTest,
::testing::Bool(),
[](const auto& info) {
return info.param ? "Exclusive" : "NotExclusive";
});
#endif // BUILDFLAG(IS_WIN)
TEST_F(SQLitePersistentCookieStoreTest, CorruptStore) {
base::HistogramTester histograms;
base::WriteFile(temp_dir_.GetPath().Append(kCookieFilename),
"SQLite format 3 foobarfoobarfoobar");
Create(/*crypt_cookies=*/false, /*restore_old_session_cookies=*/false,
/*use_current_thread=*/true,
/*enable_exclusive_access=*/false);
base::RunLoop run_loop;
store_->Load(base::BindLambdaForTesting(
[&](CanonicalCookieVector cookies) { run_loop.Quit(); }),
NetLogWithSource());
run_loop.Run();
expect_init_errors_ = true;
histograms.ExpectUniqueSample("Cookie.ErrorInitializeDB",
sql::SqliteLoggedResultCode::kNotADatabase, 1);
}
bool CreateV18Schema(sql::Database* db) {
sql::MetaTable meta_table;
if (!meta_table.Init(db, 18, 18)) {
return false;
}
// Version 18 schema
static constexpr char kCreateSql[] =
"CREATE TABLE cookies("
"creation_utc INTEGER NOT NULL,"
"host_key TEXT NOT NULL,"
"top_frame_site_key TEXT NOT NULL,"
"name TEXT NOT NULL,"
"value TEXT NOT NULL,"
"encrypted_value BLOB NOT NULL,"
"path TEXT NOT NULL,"
"expires_utc INTEGER NOT NULL,"
"is_secure INTEGER NOT NULL,"
"is_httponly INTEGER NOT NULL,"
"last_access_utc INTEGER NOT NULL,"
"has_expires INTEGER NOT NULL,"
"is_persistent INTEGER NOT NULL,"
"priority INTEGER NOT NULL,"
"samesite INTEGER NOT NULL,"
"source_scheme INTEGER NOT NULL,"
"source_port INTEGER NOT NULL,"
"is_same_party INTEGER NOT NULL,"
"last_update_utc INTEGER NOT NULL,"
"UNIQUE (host_key, top_frame_site_key, name, path))";
static constexpr char kCreateIndexSql[] =
"CREATE UNIQUE INDEX cookies_unique_index "
"ON cookies(host_key, top_frame_site_key, name, path)";
return db->Execute(kCreateSql) && db->Execute(kCreateIndexSql);
}
bool CreateV20Schema(sql::Database* db) {
sql::MetaTable meta_table;
if (!meta_table.Init(db, 20, 20)) {
return false;
}
// Version 20 schema
static constexpr char kCreateSql[] =
"CREATE TABLE cookies("
"creation_utc INTEGER NOT NULL,"
"host_key TEXT NOT NULL,"
"top_frame_site_key TEXT NOT NULL,"
"name TEXT NOT NULL,"
"value TEXT NOT NULL,"
"encrypted_value BLOB NOT NULL,"
"path TEXT NOT NULL,"
"expires_utc INTEGER NOT NULL,"
"is_secure INTEGER NOT NULL,"
"is_httponly INTEGER NOT NULL,"
"last_access_utc INTEGER NOT NULL,"
"has_expires INTEGER NOT NULL,"
"is_persistent INTEGER NOT NULL,"
"priority INTEGER NOT NULL,"
"samesite INTEGER NOT NULL,"
"source_scheme INTEGER NOT NULL,"
"source_port INTEGER NOT NULL,"
"is_same_party INTEGER NOT NULL,"
"last_update_utc INTEGER NOT NULL,"
"UNIQUE (host_key, top_frame_site_key, name, path, source_scheme, "
"source_port))";
static constexpr char kCreateIndexSql[] =
"CREATE UNIQUE INDEX cookies_unique_index "
"ON cookies(host_key, top_frame_site_key, name, path, source_scheme, "
"source_port)";
return db->Execute(kCreateSql) && db->Execute(kCreateIndexSql);
}
bool CreateV21Schema(sql::Database* db) {
sql::MetaTable meta_table;
if (!meta_table.Init(db, 21, 21)) {
return false;
}
// Version 21 schema
static constexpr char kCreateSql[] =
"CREATE TABLE cookies("
"creation_utc INTEGER NOT NULL,"
"host_key TEXT NOT NULL,"
"top_frame_site_key TEXT NOT NULL,"
"name TEXT NOT NULL,"
"value TEXT NOT NULL,"
"encrypted_value BLOB NOT NULL,"
"path TEXT NOT NULL,"
"expires_utc INTEGER NOT NULL,"
"is_secure INTEGER NOT NULL,"
"is_httponly INTEGER NOT NULL,"
"last_access_utc INTEGER NOT NULL,"
"has_expires INTEGER NOT NULL,"
"is_persistent INTEGER NOT NULL,"
"priority INTEGER NOT NULL,"
"samesite INTEGER NOT NULL,"
"source_scheme INTEGER NOT NULL,"
"source_port INTEGER NOT NULL,"
"last_update_utc INTEGER NOT NULL,"
"UNIQUE (host_key, top_frame_site_key, name, path, source_scheme, "
"source_port))";
static constexpr char kCreateIndexSql[] =
"CREATE UNIQUE INDEX cookies_unique_index "
"ON cookies(host_key, top_frame_site_key, name, path, source_scheme, "
"source_port)";
return db->Execute(kCreateSql) && db->Execute(kCreateIndexSql);
}
bool CreateV22Schema(sql::Database* db) {
sql::MetaTable meta_table;
if (!meta_table.Init(db, 22, 22)) {
return false;
}
// Version 22 schema
static constexpr char kCreateSql[] =
"CREATE TABLE cookies("
"creation_utc INTEGER NOT NULL,"
"host_key TEXT NOT NULL,"
"top_frame_site_key TEXT NOT NULL,"
"name TEXT NOT NULL,"
"value TEXT NOT NULL,"
"encrypted_value BLOB NOT NULL,"
"path TEXT NOT NULL,"
"expires_utc INTEGER NOT NULL,"
"is_secure INTEGER NOT NULL,"
"is_httponly INTEGER NOT NULL,"
"last_access_utc INTEGER NOT NULL,"
"has_expires INTEGER NOT NULL,"
"is_persistent INTEGER NOT NULL,"
"priority INTEGER NOT NULL,"
"samesite INTEGER NOT NULL,"
"source_scheme INTEGER NOT NULL,"
"source_port INTEGER NOT NULL,"
"last_update_utc INTEGER NOT NULL,"
"source_type INTEGER NOT NULL,"
"UNIQUE (host_key, top_frame_site_key, name, path, source_scheme, "
"source_port))";
static constexpr char kCreateIndexSql[] =
"CREATE UNIQUE INDEX cookies_unique_index "
"ON cookies(host_key, top_frame_site_key, name, path, source_scheme, "
"source_port)";
return db->Execute(kCreateSql) && db->Execute(kCreateIndexSql);
}
bool CreateV23Schema(sql::Database* db) {
sql::MetaTable meta_table;
if (!meta_table.Init(db, 23, 23)) {
return false;
}
// Version 23 schema
static constexpr char kCreateSql[] =
"CREATE TABLE cookies("
"creation_utc INTEGER NOT NULL,"
"host_key TEXT NOT NULL,"
"top_frame_site_key TEXT NOT NULL,"
"name TEXT NOT NULL,"
"value TEXT NOT NULL,"
"encrypted_value BLOB NOT NULL,"
"path TEXT NOT NULL,"
"expires_utc INTEGER NOT NULL,"
"is_secure INTEGER NOT NULL,"
"is_httponly INTEGER NOT NULL,"
"last_access_utc INTEGER NOT NULL,"
"has_expires INTEGER NOT NULL,"
"is_persistent INTEGER NOT NULL,"
"priority INTEGER NOT NULL,"
"samesite INTEGER NOT NULL,"
"source_scheme INTEGER NOT NULL,"
"source_port INTEGER NOT NULL,"
"last_update_utc INTEGER NOT NULL,"
"source_type INTEGER NOT NULL,"
"has_cross_site_ancestor INTEGER NOT NULL);";
static constexpr char kCreateIndexSql[] =
"CREATE UNIQUE INDEX cookies_unique_index "
"ON cookies(host_key, top_frame_site_key, has_cross_site_ancestor, "
"name, path, source_scheme, source_port)";
return db->Execute(kCreateSql) && db->Execute(kCreateIndexSql);
}
int GetDBCurrentVersionNumber(sql::Database* db) {
static constexpr char kGetDBCurrentVersionQuery[] =
"SELECT value FROM meta WHERE key='version'";
sql::Statement statement(db->GetUniqueStatement(kGetDBCurrentVersionQuery));
statement.Step();
return statement.ColumnInt(0);
}
std::vector<CanonicalCookie> CookiesForMigrationTest() {
const base::Time now = base::Time::Now();
std::vector<CanonicalCookie> cookies;
cookies.push_back(*CanonicalCookie::CreateUnsafeCookieForTesting(
"A", "B", "example.com", "/", /*creation=*/now, /*expiration=*/now,
/*last_access=*/now, /*last_update=*/now, /*secure=*/true,
/*httponly=*/false, CookieSameSite::UNSPECIFIED,
COOKIE_PRIORITY_DEFAULT));
cookies.push_back(*CanonicalCookie::CreateUnsafeCookieForTesting(
"C", "B", "example.com", "/", /*creation=*/now, /*expiration=*/now,
/*last_access=*/now, /*last_update=*/now, /*secure=*/true,
/*httponly=*/false, CookieSameSite::UNSPECIFIED,
COOKIE_PRIORITY_DEFAULT));
cookies.push_back(*CanonicalCookie::CreateUnsafeCookieForTesting(
"A", "B", "example2.com", "/", /*creation=*/now, /*expiration=*/now,
/*last_access=*/now, /*last_update=*/now, /*secure=*/true,
/*httponly=*/false, CookieSameSite::UNSPECIFIED,
COOKIE_PRIORITY_DEFAULT));
cookies.push_back(*CanonicalCookie::CreateUnsafeCookieForTesting(
"C", "B", "example2.com", "/", /*creation=*/now,
/*expiration=*/now + base::Days(399), /*last_access=*/now,
/*last_update=*/now,
/*secure=*/false, /*httponly=*/false, CookieSameSite::UNSPECIFIED,
COOKIE_PRIORITY_DEFAULT));
cookies.push_back(*CanonicalCookie::CreateUnsafeCookieForTesting(
"A", "B", "example.com", "/path", /*creation=*/now,
/*expiration=*/now + base::Days(400), /*last_access=*/now,
/*last_update=*/now,
/*secure=*/false, /*httponly=*/false, CookieSameSite::UNSPECIFIED,
COOKIE_PRIORITY_DEFAULT));
cookies.push_back(*CanonicalCookie::CreateUnsafeCookieForTesting(
"C", "B", "example.com", "/path", /*creation=*/now,
/*expiration=*/now + base::Days(401), /*last_access=*/now,
/*last_update=*/now,
/*secure=*/false, /*httponly=*/false, CookieSameSite::UNSPECIFIED,
COOKIE_PRIORITY_DEFAULT));
cookies.push_back(*CanonicalCookie::CreateUnsafeCookieForTesting(
"D", "", "empty.com", "/", /*creation=*/now, /*expiration=*/now,
/*last_access=*/now, /*last_update=*/now, /*secure=*/true,
/*httponly=*/false, CookieSameSite::UNSPECIFIED,
COOKIE_PRIORITY_DEFAULT));
return cookies;
}
// Versions 18, 19, and 20 use the same schema so they can reuse this function.
// AddV20CookiesToDB (and future versions) need to set max_expiration_delta to
// base::Days(400) to simulate expiration limits introduced in version 19.
bool AddV18CookiesToDB(sql::Database* db,
base::TimeDelta max_expiration_delta) {
std::vector<CanonicalCookie> cookies = CookiesForMigrationTest();
sql::Statement statement(db->GetCachedStatement(
SQL_FROM_HERE,
"INSERT INTO cookies (creation_utc, top_frame_site_key, host_key, name, "
"value, encrypted_value, path, expires_utc, is_secure, is_httponly, "
"samesite, last_access_utc, has_expires, is_persistent, priority, "
"source_scheme, source_port, is_same_party, last_update_utc) "
"VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"));
if (!statement.is_valid()) {
return false;
}
sql::Transaction transaction(db);
if (!transaction.Begin()) {
return false;
}
for (const CanonicalCookie& cookie : cookies) {
base::Time max_expiration(cookie.CreationDate() + max_expiration_delta);
statement.Reset(true);
statement.BindTime(0, cookie.CreationDate());
base::expected<CookiePartitionKey::SerializedCookiePartitionKey,
std::string>
serialized_partition_key =
CookiePartitionKey::Serialize(cookie.PartitionKey());
EXPECT_TRUE(serialized_partition_key.has_value());
statement.BindString(1, serialized_partition_key->TopLevelSite());
statement.BindString(2, cookie.Domain());
statement.BindString(3, cookie.Name());
statement.BindString(4, cookie.Value());
statement.BindBlob(5, base::span<uint8_t>()); // encrypted_value
statement.BindString(6, cookie.Path());
statement.BindTime(7, std::min(cookie.ExpiryDate(), max_expiration));
statement.BindInt(8, cookie.SecureAttribute());
statement.BindInt(9, cookie.IsHttpOnly());
// Note that this, Priority(), and SourceScheme() below nominally rely on
// the enums in sqlite_persistent_cookie_store.cc having the same values as
// the ones in ../../cookies/cookie_constants.h. But nothing in this test
// relies on that equivalence, so it's not worth the hassle to guarantee
// that.
statement.BindInt(10, static_cast<int>(cookie.SameSite()));
statement.BindTime(11, cookie.LastAccessDate());
statement.BindInt(12, cookie.IsPersistent());
statement.BindInt(13, cookie.IsPersistent());
statement.BindInt(14, static_cast<int>(cookie.Priority()));
statement.BindInt(15, static_cast<int>(cookie.SourceScheme()));
statement.BindInt(16, cookie.SourcePort());
statement.BindInt(17, /*is_same_party=*/false);
statement.BindTime(18, cookie.LastUpdateDate());
if (!statement.Run()) {
return false;
}
}
return transaction.Commit();
}
bool AddV20CookiesToDB(sql::Database* db) {
return AddV18CookiesToDB(db, base::Days(400));
}
bool AddV21CookiesToDB(sql::Database* db) {
std::vector<CanonicalCookie> cookies = CookiesForMigrationTest();
sql::Statement statement(db->GetCachedStatement(
SQL_FROM_HERE,
"INSERT INTO cookies (creation_utc, top_frame_site_key, host_key, name, "
"value, encrypted_value, path, expires_utc, is_secure, is_httponly, "
"samesite, last_access_utc, has_expires, is_persistent, priority, "
"source_scheme, source_port, last_update_utc) "
"VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"));
if (!statement.is_valid()) {
return false;
}
sql::Transaction transaction(db);
if (!transaction.Begin()) {
return false;
}
for (const CanonicalCookie& cookie : cookies) {
base::Time max_expiration(cookie.CreationDate() + base::Days(400));
statement.Reset(true);
statement.BindTime(0, cookie.CreationDate());
base::expected<CookiePartitionKey::SerializedCookiePartitionKey,
std::string>
serialized_partition_key =
CookiePartitionKey::Serialize(cookie.PartitionKey());
EXPECT_TRUE(serialized_partition_key.has_value());
statement.BindString(1, serialized_partition_key->TopLevelSite());
statement.BindString(2, cookie.Domain());
statement.BindString(3, cookie.Name());
statement.BindString(4, cookie.Value());
statement.BindBlob(5, base::span<uint8_t>()); // encrypted_value
statement.BindString(6, cookie.Path());
statement.BindTime(7, std::min(cookie.ExpiryDate(), max_expiration));
statement.BindInt(8, cookie.SecureAttribute());
statement.BindInt(9, cookie.IsHttpOnly());
// Note that this, Priority(), and SourceScheme() below nominally rely on
// the enums in sqlite_persistent_cookie_store.cc having the same values as
// the ones in ../../cookies/cookie_constants.h. But nothing in this test
// relies on that equivalence, so it's not worth the hassle to guarantee
// that.
statement.BindInt(10, static_cast<int>(cookie.SameSite()));
statement.BindTime(11, cookie.LastAccessDate());
statement.BindInt(12, cookie.IsPersistent());
statement.BindInt(13, cookie.IsPersistent());
statement.BindInt(14, static_cast<int>(cookie.Priority()));
statement.BindInt(15, static_cast<int>(cookie.SourceScheme()));
statement.BindInt(16, cookie.SourcePort());
statement.BindTime(17, cookie.LastUpdateDate());
if (!statement.Run()) {
return false;
}
}
return transaction.Commit();
}
bool AddV22CookiesToDB(sql::Database* db,
const std::vector<CanonicalCookie>& cookies) {
sql::Statement statement(db->GetCachedStatement(
SQL_FROM_HERE,
"INSERT INTO cookies (creation_utc, top_frame_site_key, host_key, name, "
"value, encrypted_value, path, expires_utc, is_secure, is_httponly, "
"samesite, last_access_utc, has_expires, is_persistent, priority, "
"source_scheme, source_port, last_update_utc, source_type) "
"VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"));
if (!statement.is_valid()) {
return false;
}
sql::Transaction transaction(db);
if (!transaction.Begin()) {
return false;
}
for (const CanonicalCookie& cookie : cookies) {
base::Time max_expiration(cookie.CreationDate() + base::Days(400));
statement.Reset(true);
statement.BindTime(0, cookie.CreationDate());
base::expected<CookiePartitionKey::SerializedCookiePartitionKey,
std::string>
serialized_partition_key =
CookiePartitionKey::Serialize(cookie.PartitionKey());
EXPECT_TRUE(serialized_partition_key.has_value());
statement.BindString(1, serialized_partition_key->TopLevelSite());
statement.BindString(2, cookie.Domain());
statement.BindString(3, cookie.Name());
statement.BindString(4, cookie.Value());
statement.BindBlob(5, base::span<uint8_t>()); // encrypted_value
statement.BindString(6, cookie.Path());
statement.BindTime(7, std::min(cookie.ExpiryDate(), max_expiration));
statement.BindInt(8, cookie.SecureAttribute());
statement.BindInt(9, cookie.IsHttpOnly());
// Note that this, Priority(), and SourceScheme() below nominally rely on
// the enums in sqlite_persistent_cookie_store.cc having the same values as
// the ones in ../../cookies/cookie_constants.h. But nothing in this test
// relies on that equivalence, so it's not worth the hassle to guarantee
// that.
statement.BindInt(10, static_cast<int>(cookie.SameSite()));
statement.BindTime(11, cookie.LastAccessDate());
statement.BindInt(12, cookie.IsPersistent());
statement.BindInt(13, cookie.IsPersistent());
statement.BindInt(14, static_cast<int>(cookie.Priority()));
statement.BindInt(15, static_cast<int>(cookie.SourceScheme()));
statement.BindInt(16, cookie.SourcePort());
statement.BindTime(17, cookie.LastUpdateDate());
statement.BindInt(18, static_cast<int>(cookie.SourceType()));
if (!statement.Run()) {
return false;
}
}
return transaction.Commit();
}
bool AddV23CookiesToDB(sql::Database* db,
const std::vector<CanonicalCookie>& cookies,
CookieCryptoDelegate* crypto,
bool place_unencrypted_too) {
sql::Statement statement(db->GetCachedStatement(
SQL_FROM_HERE,
"INSERT INTO cookies (creation_utc, host_key, top_frame_site_key, name, "
"value, encrypted_value, path, expires_utc, is_secure, is_httponly, "
"samesite, last_access_utc, has_expires, is_persistent, priority, "
"source_scheme, source_port, last_update_utc, source_type, "
"has_cross_site_ancestor) "
"VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"));
if (!statement.is_valid()) {
return false;
}
sql::Transaction transaction(db);
if (!transaction.Begin()) {
return false;
}
for (const CanonicalCookie& cookie : cookies) {
base::Time max_expiration(cookie.CreationDate() + base::Days(400));
statement.Reset(true);
statement.BindTime(0, cookie.CreationDate());
base::expected<CookiePartitionKey::SerializedCookiePartitionKey,
std::string>
serialized_partition_key =
CookiePartitionKey::Serialize(cookie.PartitionKey());
EXPECT_TRUE(serialized_partition_key.has_value());
statement.BindString(1, cookie.Domain());
statement.BindString(2, serialized_partition_key->TopLevelSite());
statement.BindString(3, cookie.Name());
if (crypto) {
statement.BindString(
4, place_unencrypted_too
? cookie.Value()
: ""); // value is encrypted. If `place_unencrypted_too` is
// set then place it here too, to test bad databases.
std::string encrypted_value;
// v23 and below simply encrypted the cookie and stored it in this value.
EXPECT_TRUE(crypto->EncryptString(cookie.Value(), &encrypted_value));
statement.BindBlob(5, encrypted_value); // encrypted_value.
} else {
statement.BindString(4, cookie.Value());
statement.BindBlob(5, base::span<uint8_t>()); // encrypted_value empty.
}
statement.BindString(6, cookie.Path());
statement.BindTime(7, std::min(cookie.ExpiryDate(), max_expiration));
statement.BindInt(8, cookie.SecureAttribute());
statement.BindInt(9, cookie.IsHttpOnly());
// Note that this, Priority(), and SourceScheme() below nominally rely on
// the enums in sqlite_persistent_cookie_store.cc having the same values as
// the ones in ../../cookies/cookie_constants.h. But nothing in this test
// relies on that equivalence, so it's not worth the hassle to guarantee
// that.
statement.BindInt(10, static_cast<int>(cookie.SameSite()));
statement.BindTime(11, cookie.LastAccessDate());
statement.BindInt(12, cookie.IsPersistent());
statement.BindInt(13, cookie.IsPersistent());
statement.BindInt(14, static_cast<int>(cookie.Priority()));
// Version 23 updated any preexisting cookies with a source_scheme value of
// kUnset and a is_secure of true to have a source_scheme value of kSecure.
// This situation can occur with the test cookies, so update the data to
// reflect a v23 cookie store.
auto source_scheme = cookie.SourceScheme();
if (cookie.SourceScheme() == CookieSourceScheme::kUnset &&
cookie.IsSecure()) {
source_scheme = CookieSourceScheme::kSecure;
}
statement.BindInt(15, static_cast<int>(source_scheme));
statement.BindInt(16, cookie.SourcePort());
statement.BindTime(17, cookie.LastUpdateDate());
statement.BindInt(18, static_cast<int>(cookie.SourceType()));
statement.BindBool(19, serialized_partition_key->has_cross_site_ancestor());
if (!statement.Run()) {
return false;
}
}
return transaction.Commit();
}
// Confirm the cookie list passed in has the above cookies in it.
void ConfirmCookiesAfterMigrationTest(
std::vector<std::unique_ptr<CanonicalCookie>> read_in_cookies,
bool expect_last_update_date = false) {
ASSERT_EQ(read_in_cookies.size(), 7u);
std::sort(read_in_cookies.begin(), read_in_cookies.end(), &CompareCookies);
int i = 0;
EXPECT_EQ("A", read_in_cookies[i]->Name());
EXPECT_EQ("B", read_in_cookies[i]->Value());
EXPECT_EQ("example.com", read_in_cookies[i]->Domain());
EXPECT_EQ("/", read_in_cookies[i]->Path());
EXPECT_TRUE(read_in_cookies[i]->SecureAttribute());
EXPECT_EQ(CookieSourceScheme::kSecure, read_in_cookies[i]->SourceScheme());
EXPECT_EQ(read_in_cookies[i]->LastUpdateDate(),
expect_last_update_date ? read_in_cookies[i]->CreationDate()
: base::Time());
EXPECT_EQ(read_in_cookies[i]->ExpiryDate(),
read_in_cookies[i]->CreationDate());
EXPECT_EQ(read_in_cookies[i]->SourceType(), CookieSourceType::kUnknown);
i++;
EXPECT_EQ("A", read_in_cookies[i]->Name());
EXPECT_EQ("B", read_in_cookies[i]->Value());
EXPECT_EQ("example.com", read_in_cookies[i]->Domain());
EXPECT_EQ("/path", read_in_cookies[i]->Path());
EXPECT_FALSE(read_in_cookies[i]->SecureAttribute());
EXPECT_EQ(CookieSourceScheme::kUnset, read_in_cookies[i]->SourceScheme());
EXPECT_EQ(read_in_cookies[i]->LastUpdateDate(),
expect_last_update_date ? read_in_cookies[i]->CreationDate()
: base::Time());
EXPECT_EQ(read_in_cookies[i]->ExpiryDate(),
read_in_cookies[i]->CreationDate() + base::Days(400));
EXPECT_EQ(read_in_cookies[i]->SourceType(), CookieSourceType::kUnknown);
i++;
EXPECT_EQ("A", read_in_cookies[i]->Name());
EXPECT_EQ("B", read_in_cookies[i]->Value());
EXPECT_EQ("example2.com", read_in_cookies[i]->Domain());
EXPECT_EQ("/", read_in_cookies[i]->Path());
EXPECT_TRUE(read_in_cookies[i]->SecureAttribute());
EXPECT_EQ(CookieSourceScheme::kSecure, read_in_cookies[i]->SourceScheme());
EXPECT_EQ(read_in_cookies[i]->LastUpdateDate(),
expect_last_update_date ? read_in_cookies[i]->CreationDate()
: base::Time());
EXPECT_EQ(read_in_cookies[i]->ExpiryDate(),
read_in_cookies[i]->CreationDate());
EXPECT_EQ(read_in_cookies[i]->SourceType(), CookieSourceType::kUnknown);
i++;
EXPECT_EQ("C", read_in_cookies[i]->Name());
EXPECT_EQ("B", read_in_cookies[i]->Value());
EXPECT_EQ("example.com", read_in_cookies[i]->Domain());
EXPECT_EQ("/", read_in_cookies[i]->Path());
EXPECT_TRUE(read_in_cookies[i]->SecureAttribute());
EXPECT_EQ(CookieSourceScheme::kSecure, read_in_cookies[i]->SourceScheme());
EXPECT_EQ(read_in_cookies[i]->LastUpdateDate(),
expect_last_update_date ? read_in_cookies[i]->CreationDate()
: base::Time());
EXPECT_EQ(read_in_cookies[i]->ExpiryDate(),
read_in_cookies[i]->CreationDate());
EXPECT_EQ(read_in_cookies[i]->SourceType(), CookieSourceType::kUnknown);
i++;
EXPECT_EQ("C", read_in_cookies[i]->Name());
EXPECT_EQ("B", read_in_cookies[i]->Value());
EXPECT_EQ("example.com", read_in_cookies[i]->Domain());
EXPECT_EQ("/path", read_in_cookies[i]->Path());
EXPECT_FALSE(read_in_cookies[i]->SecureAttribute());
EXPECT_EQ(CookieSourceScheme::kUnset, read_in_cookies[i]->SourceScheme());
EXPECT_EQ(read_in_cookies[i]->LastUpdateDate(),
expect_last_update_date ? read_in_cookies[i]->CreationDate()
: base::Time());
// The exact time will be within the last minute due to the cap.
EXPECT_LE(read_in_cookies[i]->ExpiryDate(),
base::Time::Now() + base::Days(400));
EXPECT_GE(read_in_cookies[i]->ExpiryDate(),
base::Time::Now() + base::Days(400) - base::Minutes(1));
EXPECT_EQ(read_in_cookies[i]->SourceType(), CookieSourceType::kUnknown);
i++;
EXPECT_EQ("C", read_in_cookies[i]->Name());
EXPECT_EQ("B", read_in_cookies[i]->Value());
EXPECT_EQ("example2.com", read_in_cookies[i]->Domain());
EXPECT_EQ("/", read_in_cookies[i]->Path());
EXPECT_FALSE(read_in_cookies[i]->SecureAttribute());
EXPECT_EQ(CookieSourceScheme::kUnset, read_in_cookies[i]->SourceScheme());
EXPECT_EQ(read_in_cookies[i]->LastUpdateDate(),
expect_last_update_date ? read_in_cookies[i]->CreationDate()
: base::Time());
EXPECT_EQ(read_in_cookies[i]->ExpiryDate(),
read_in_cookies[i]->CreationDate() + base::Days(399));
EXPECT_EQ(read_in_cookies[i]->SourceType(), CookieSourceType::kUnknown);
i++;
EXPECT_EQ("D", read_in_cookies[i]->Name());
EXPECT_EQ("", read_in_cookies[i]->Value());
EXPECT_EQ("empty.com", read_in_cookies[i]->Domain());
EXPECT_EQ("/", read_in_cookies[i]->Path());
EXPECT_TRUE(read_in_cookies[i]->SecureAttribute());
EXPECT_EQ(CookieSourceScheme::kSecure, read_in_cookies[i]->SourceScheme());
EXPECT_EQ(read_in_cookies[i]->LastUpdateDate(),
expect_last_update_date ? read_in_cookies[i]->CreationDate()
: base::Time());
EXPECT_EQ(read_in_cookies[i]->ExpiryDate(),
read_in_cookies[i]->CreationDate());
EXPECT_EQ(read_in_cookies[i]->SourceType(), CookieSourceType::kUnknown);
}
void ConfirmDatabaseVersionAfterMigration(const base::FilePath path,
int version) {
sql::Database connection(sql::test::kTestTag);
ASSERT_TRUE(connection.Open(path));
ASSERT_GE(GetDBCurrentVersionNumber(&connection), version);
}
TEST_F(SQLitePersistentCookieStoreTest, UpgradeToSchemaVersion19) {
// Open db.
const base::FilePath database_path =
temp_dir_.GetPath().Append(kCookieFilename);
{
sql::Database connection(sql::test::kTestTag);
ASSERT_TRUE(connection.Open(database_path));
ASSERT_TRUE(CreateV18Schema(&connection));
ASSERT_EQ(GetDBCurrentVersionNumber(&connection), 18);
ASSERT_TRUE(AddV18CookiesToDB(&connection, base::TimeDelta::Max()));
}
CanonicalCookieVector read_in_cookies = CreateAndLoad(
/*crypt_cookies=*/false, /*restore_old_session_cookies=*/false);
ASSERT_NO_FATAL_FAILURE(
ConfirmCookiesAfterMigrationTest(std::move(read_in_cookies),
/*expect_last_update_date=*/true));
DestroyStore();
ASSERT_NO_FATAL_FAILURE(
ConfirmDatabaseVersionAfterMigration(database_path, 19));
}
TEST_F(SQLitePersistentCookieStoreTest, UpgradeToSchemaVersion20) {
// Open db.
const base::FilePath database_path =
temp_dir_.GetPath().Append(kCookieFilename);
{
sql::Database connection(sql::test::kTestTag);
ASSERT_TRUE(connection.Open(database_path));
// V19's schema is the same as V18, so we can reuse the creation function.
ASSERT_TRUE(CreateV18Schema(&connection));
ASSERT_EQ(GetDBCurrentVersionNumber(&connection), 18);
ASSERT_TRUE(AddV18CookiesToDB(&connection, base::TimeDelta::Max()));
}
CanonicalCookieVector read_in_cookies = CreateAndLoad(
/*crypt_cookies=*/false, /*restore_old_session_cookies=*/false);
ASSERT_NO_FATAL_FAILURE(
ConfirmCookiesAfterMigrationTest(std::move(read_in_cookies),
/*expect_last_update_date=*/true));
DestroyStore();
ASSERT_NO_FATAL_FAILURE(
ConfirmDatabaseVersionAfterMigration(database_path, 20));
}
TEST_F(SQLitePersistentCookieStoreTest, UpgradeToSchemaVersion21) {
// Open db.
const base::FilePath database_path =
temp_dir_.GetPath().Append(kCookieFilename);
{
sql::Database connection(sql::test::kTestTag);
ASSERT_TRUE(connection.Open(database_path));
ASSERT_TRUE(CreateV20Schema(&connection));
ASSERT_EQ(GetDBCurrentVersionNumber(&connection), 20);
ASSERT_TRUE(AddV20CookiesToDB(&connection));
}
CanonicalCookieVector read_in_cookies = CreateAndLoad(
/*crypt_cookies=*/false, /*restore_old_session_cookies=*/false);
ASSERT_NO_FATAL_FAILURE(
ConfirmCookiesAfterMigrationTest(std::move(read_in_cookies),
/*expect_last_update_date=*/true));
DestroyStore();
ASSERT_NO_FATAL_FAILURE(
ConfirmDatabaseVersionAfterMigration(database_path, 21));
}
TEST_F(SQLitePersistentCookieStoreTest, UpgradeToSchemaVersion22) {
// Open db.
const base::FilePath database_path =
temp_dir_.GetPath().Append(kCookieFilename);
{
sql::Database connection(sql::test::kTestTag);
ASSERT_TRUE(connection.Open(database_path));
ASSERT_TRUE(CreateV21Schema(&connection));
ASSERT_EQ(GetDBCurrentVersionNumber(&connection), 21);
ASSERT_TRUE(AddV21CookiesToDB(&connection));
}
CanonicalCookieVector read_in_cookies = CreateAndLoad(
/*crypt_cookies=*/false, /*restore_old_session_cookies=*/false);
ASSERT_NO_FATAL_FAILURE(
ConfirmCookiesAfterMigrationTest(std::move(read_in_cookies),
/*expect_last_update_date=*/true));
DestroyStore();
ASSERT_NO_FATAL_FAILURE(
ConfirmDatabaseVersionAfterMigration(database_path, 22));
}
TEST_F(SQLitePersistentCookieStoreTest, UpgradeToSchemaVersion23) {
// Open db.
const base::FilePath database_path =
temp_dir_.GetPath().Append(kCookieFilename);
{
sql::Database connection(sql::test::kTestTag);
ASSERT_TRUE(connection.Open(database_path));
ASSERT_TRUE(CreateV22Schema(&connection));
ASSERT_EQ(GetDBCurrentVersionNumber(&connection), 22);
ASSERT_TRUE(AddV22CookiesToDB(&connection, CookiesForMigrationTest()));
}
CanonicalCookieVector read_in_cookies = CreateAndLoad(
/*crypt_cookies=*/false, /*restore_old_session_cookies=*/false);
ASSERT_NO_FATAL_FAILURE(
ConfirmCookiesAfterMigrationTest(std::move(read_in_cookies),
/*expect_last_update_date=*/true));
DestroyStore();
ASSERT_NO_FATAL_FAILURE(
ConfirmDatabaseVersionAfterMigration(database_path, 23));
}
class SQLitePersistentCookieStorev24UpgradeTest
: public SQLitePersistentCookieStoreTest,
public ::testing::WithParamInterface<
std::tuple</*crypto_for_encrypt*/ bool,
/*crypto_for_decrypt*/ bool,
/*place_unencrypted_too*/ bool,
/*kEncryptedAndPlaintextValuesAreInvalid*/ bool>> {
protected:
void SetUp() override {
features_.InitWithFeatureState(
features::kEncryptedAndPlaintextValuesAreInvalid,
std::get<3>(GetParam()));
SQLitePersistentCookieStoreTest::SetUp();
}
private:
base::test::ScopedFeatureList features_;
};
TEST_P(SQLitePersistentCookieStorev24UpgradeTest, UpgradeToSchemaVersion24) {
const bool crypto_for_encrypt = std::get<0>(GetParam());
const bool crypto_for_decrypt = std::get<1>(GetParam());
const bool place_unencrypted_too = std::get<2>(GetParam());
const bool drop_dup_values = std::get<3>(GetParam());
const base::FilePath database_path =
temp_dir_.GetPath().Append(kCookieFilename);
{
sql::Database connection(sql::test::kTestTag);
ASSERT_TRUE(connection.Open(database_path));
ASSERT_TRUE(CreateV23Schema(&connection));
ASSERT_EQ(GetDBCurrentVersionNumber(&connection), 23);
auto cryptor = std::make_unique<CookieCryptor>();
ASSERT_TRUE(AddV23CookiesToDB(&connection, CookiesForMigrationTest(),
crypto_for_encrypt ? cryptor.get() : nullptr,
place_unencrypted_too));
}
{
base::HistogramTester histogram_tester;
CanonicalCookieVector read_in_cookies = CreateAndLoad(
/*crypt_cookies=*/crypto_for_decrypt,
/*restore_old_session_cookies=*/false);
// If encryption is enabled for encrypt and not available for decrypt, then
// most cookies will be gone, as the data is encrypted with no way to
// decrypt.
if (crypto_for_encrypt && !crypto_for_decrypt) {
// Subtle: The empty cookie for empty.com will not trigger a cookie load
// failure. This is because during the migration there is no crypto so no
// migration occurs for any cookie, including the empty one. Then when
// attempting to load a v24 store the cookie with an empty value and empty
// encrypted value will simply load empty.
EXPECT_EQ(read_in_cookies.size(), 1u);
// The case of plaintext and encrypted values is always checked when
// loading a cookie before the availability of crypto. This means the
// error code here depends on whether migration from v23 to v24 was done
// with crypto available or not. In this case, crypto was not available
// during migration so the values were left alone - meaning that if there
// are both plaintext and encrypted values the
// kValuesExistInBothEncryptedAndPlaintext error is returned. However, if
// this cookie does not have both plaintext and encrypted values, then the
// second check is hit which reports encrypted data that cannot be
// decrypted - kNoCrypto. Functionality for an already-migrated store (v24
// and above) with both plaintext and encrypted values is tested in the
// `OverridePlaintextValue` test below.
const base::Histogram::Sample32 expected_bucket =
drop_dup_values && place_unencrypted_too
? /*CookieLoadProblem::kValuesExistInBothEncryptedAndPlaintext*/ 8
: /*CookieLoadProblem::kNoCrypto*/ 7;
histogram_tester.ExpectBucketCount("Cookie.LoadProblem", expected_bucket,
CookiesForMigrationTest().size() - 1);
} else {
histogram_tester.ExpectTotalCount("Cookie.LoadProblem", 0);
ASSERT_NO_FATAL_FAILURE(
ConfirmCookiesAfterMigrationTest(std::move(read_in_cookies),
/*expect_last_update_date=*/true));
}
DestroyStore();
}
ASSERT_NO_FATAL_FAILURE(
ConfirmDatabaseVersionAfterMigration(database_path, 24));
}
INSTANTIATE_TEST_SUITE_P(,
SQLitePersistentCookieStorev24UpgradeTest,
::testing::Combine(::testing::Bool(),
::testing::Bool(),
::testing::Bool(),
::testing::Bool()));
TEST_F(SQLitePersistentCookieStoreTest, CannotModifyHostName) {
{
CreateAndLoad(/*crypt_cookies=*/true,
/*restore_old_session_cookies=*/false);
AddCookie("A", "B", "sensitive.com", "/", base::Time::Now());
AddCookie("A", "B", "example.com", "/", base::Time::Now());
DestroyStore();
}
{
const base::FilePath database_path =
temp_dir_.GetPath().Append(kCookieFilename);
// Simulate an attacker modifying hostname to attacker controlled, to
// perform a cookie replay attack.
sql::Database connection(sql::test::kTestTag);
ASSERT_TRUE(connection.Open(database_path));
sql::Transaction transaction(&connection);
ASSERT_TRUE(transaction.Begin());
ASSERT_TRUE(
connection.Execute("UPDATE cookies SET host_key='attacker.com' WHERE "
"host_key='sensitive.com'"));
ASSERT_TRUE(transaction.Commit());
}
{
base::HistogramTester histogram_tester;
auto cookies = CreateAndLoad(/*crypt_cookies=*/true,
/*restore_old_session_cookies=*/false);
// Modified cookie should not load.
ASSERT_EQ(cookies.size(), 1u);
ASSERT_EQ(cookies[0]->Domain(), "example.com");
ASSERT_EQ(cookies[0]->Name(), "A");
ASSERT_EQ(cookies[0]->Value(), "B");
DestroyStore();
histogram_tester.ExpectBucketCount("Cookie.LoadProblem",
/*CookieLoadProblem::kHashFailed*/ 6, 1);
}
{
base::HistogramTester histogram_tester;
auto cookies = CreateAndLoad(/*crypt_cookies=*/true,
/*restore_old_session_cookies=*/false);
// Modified cookie should not load.
ASSERT_EQ(cookies.size(), 1u);
ASSERT_EQ(cookies[0]->Domain(), "example.com");
ASSERT_EQ(cookies[0]->Name(), "A");
ASSERT_EQ(cookies[0]->Value(), "B");
DestroyStore();
// The hash failure should only appear once, during the first read, as the
// invalid cookie gets deleted afterwards.
histogram_tester.ExpectTotalCount("Cookie.LoadProblem", 0);
}
}
TEST_F(SQLitePersistentCookieStoreTest, ShortHash) {
{
CreateAndLoad(/*crypt_cookies=*/true,
/*restore_old_session_cookies=*/false);
AddCookie("A", "B", "sensitive.com", "/", base::Time::Now());
AddCookie("A", "B", "example.com", "/", base::Time::Now());
DestroyStore();
}
{
const base::FilePath database_path =
temp_dir_.GetPath().Append(kCookieFilename);
// Simulate an attacker modifying hostname to attacker controlled, to
// perform a cookie replay attack.
sql::Database connection(sql::test::kTestTag);
ASSERT_TRUE(connection.Open(database_path));
sql::Transaction transaction(&connection);
sql::Statement set_encrypted_value(connection.GetUniqueStatement(
"UPDATE cookies SET encrypted_value=? WHERE host_key='sensitive.com'"));
CookieCryptor crypto;
// Short string, without a hash, but valid encryption. This verifies that
// the decryption code handles short-length encrypted data fine.
std::string encrypted_data;
crypto.EncryptString("a", &encrypted_data);
set_encrypted_value.BindBlob(0, encrypted_data);
ASSERT_TRUE(transaction.Begin());
ASSERT_TRUE(set_encrypted_value.Run());
ASSERT_TRUE(transaction.Commit());
}
{
base::HistogramTester histogram_tester;
auto cookies = CreateAndLoad(/*crypt_cookies=*/true,
/*restore_old_session_cookies=*/false);
// Modified cookie should not load.
ASSERT_EQ(cookies.size(), 1u);
ASSERT_EQ(cookies[0]->Domain(), "example.com");
ASSERT_EQ(cookies[0]->Name(), "A");
ASSERT_EQ(cookies[0]->Value(), "B");
DestroyStore();
histogram_tester.ExpectBucketCount("Cookie.LoadProblem",
/*CookieLoadProblem::kHashFailed*/ 6, 1);
}
{
base::HistogramTester histogram_tester;
auto cookies = CreateAndLoad(/*crypt_cookies=*/true,
/*restore_old_session_cookies=*/false);
// Modified cookie should not load.
ASSERT_EQ(cookies.size(), 1u);
ASSERT_EQ(cookies[0]->Domain(), "example.com");
ASSERT_EQ(cookies[0]->Name(), "A");
ASSERT_EQ(cookies[0]->Value(), "B");
DestroyStore();
// The hash failure should only appear once, during the first read, as the
// invalid cookie gets deleted afterwards.
histogram_tester.ExpectTotalCount("Cookie.LoadProblem", 0);
}
}
TEST_F(SQLitePersistentCookieStoreTest,
UpgradeToSchemaVersion23_ConfirmSourceSchemeRecalculation) {
const base::FilePath database_path =
temp_dir_.GetPath().Append(kCookieFilename);
const base::Time now = base::Time::Now();
std::vector<CanonicalCookie> cookies;
cookies.push_back(*CanonicalCookie::CreateUnsafeCookieForTesting(
"secure_true", "A", "example.com", "/", now, now, now, now,
/*secure=*/true, /*httponly=*/false, CookieSameSite::UNSPECIFIED,
COOKIE_PRIORITY_DEFAULT, std::optional<CookiePartitionKey>(),
CookieSourceScheme::kUnset));
cookies.push_back(*CanonicalCookie::CreateUnsafeCookieForTesting(
"secure_false", "B", "example.com", "/", now, now, now, now,
/*secure=*/false, /*httponly=*/false, CookieSameSite::UNSPECIFIED,
COOKIE_PRIORITY_DEFAULT, std::optional<CookiePartitionKey>(),
CookieSourceScheme::kUnset));
// Open database, populate and close db.
{
sql::Database db(sql::test::kTestTag);
ASSERT_TRUE(db.Open(database_path));
ASSERT_TRUE(CreateV22Schema(&db));
ASSERT_EQ(GetDBCurrentVersionNumber(&db), 22);
ASSERT_TRUE(AddV22CookiesToDB(&db, cookies));
}
CanonicalCookieVector read_in_cookies = CreateAndLoad(
/*crypt_cookies=*/false, /*restore_old_session_cookies=*/true);
EXPECT_EQ(read_in_cookies.size(), cookies.size());
// Reopen database for testing.
sql::Database connection(sql::test::kTestTag);
ASSERT_TRUE(connection.Open(database_path));
ASSERT_GE(GetDBCurrentVersionNumber(&connection), 23);
for (const auto& cookie : cookies) {
sql::Statement verify_stmt(connection.GetUniqueStatement(
"SELECT source_scheme FROM cookies WHERE is_secure=?"));
verify_stmt.BindBool(0, cookie.SecureAttribute());
ASSERT_TRUE(verify_stmt.is_valid());
EXPECT_TRUE(verify_stmt.Step());
EXPECT_EQ(
static_cast<int>(cookie.SecureAttribute() ? CookieSourceScheme::kSecure
: CookieSourceScheme::kUnset),
verify_stmt.ColumnInt(0));
// Confirm that exactly one cookie matches the SQL query
EXPECT_FALSE(verify_stmt.Step());
}
}
class SQLitePersistentCookieStoreTest_OriginBoundCookies
: public SQLitePersistentCookieStoreTest {
public:
// Creates and stores 4 cookies that differ only by scheme and/or port. When
// this function returns, the store will be created and all the cookies loaded
// into cookies_.
void InitializeTest() {
InitializeStore(/*crypt=*/false, /*restore_old_session_cookies=*/false);
basic_cookie_ = CanonicalCookie::CreateForTesting(
basic_url_, "a=b; max-age=100000", /*creation_time=*/base::Time::Now());
http_cookie_ = std::make_unique<CanonicalCookie>(*basic_cookie_);
http_cookie_->SetSourceScheme(CookieSourceScheme::kNonSecure);
port_444_cookie_ = std::make_unique<CanonicalCookie>(*basic_cookie_);
port_444_cookie_->SetSourcePort(444);
http_444_cookie_ = std::make_unique<CanonicalCookie>(*basic_cookie_);
http_444_cookie_->SetSourceScheme(CookieSourceScheme::kNonSecure);
http_444_cookie_->SetSourcePort(444);
store_->AddCookie(*basic_cookie_);
store_->AddCookie(*http_cookie_);
store_->AddCookie(*port_444_cookie_);
store_->AddCookie(*http_444_cookie_);
// Force the store to write its data to the disk.
DestroyStore();
cookies_ = CreateAndLoad(/*crypt_cookies=*/false,
/*restore_old_session_cookies=*/false);
EXPECT_EQ(cookies_.size(), 4UL);
}
GURL basic_url_ = GURL("https://example.com");
std::unique_ptr<net::CanonicalCookie> basic_cookie_;
std::unique_ptr<net::CanonicalCookie> http_cookie_;
std::unique_ptr<net::CanonicalCookie> port_444_cookie_;
std::unique_ptr<net::CanonicalCookie> http_444_cookie_;
CanonicalCookieVector cookies_;
};
// Tests that cookies which differ only in their scheme and port are considered
// distinct.
TEST_F(SQLitePersistentCookieStoreTest_OriginBoundCookies,
UniquenessConstraint) {
InitializeTest();
// Try to add another cookie that is the same as basic_cookie_ except that its
// value is different. Value isn't considered as part of the unique constraint
// and so this cookie won't be considered unique and should fail to be added.
auto basic_cookie2 =
CanonicalCookie::CreateForTesting(basic_url_, "a=b2; max-age=100000",
/*creation_time=*/base::Time::Now());
store_->AddCookie(*basic_cookie2);
// Force the store to write its data to the disk.
DestroyStore();
cookies_.clear();
cookies_ = CreateAndLoad(/*crypt_cookies=*/false,
/*restore_old_session_cookies=*/false);
// Confirm that basic_cookie2 failed to be added.
EXPECT_THAT(cookies_, testing::UnorderedElementsAre(
MatchesEveryCookieField(*basic_cookie_),
MatchesEveryCookieField(*http_cookie_),
MatchesEveryCookieField(*port_444_cookie_),
MatchesEveryCookieField(*http_444_cookie_)));
}
// Tests that deleting a cookie correctly takes the scheme and port into
// account.
TEST_F(SQLitePersistentCookieStoreTest_OriginBoundCookies, DeleteCookie) {
InitializeTest();
// Try to delete just one of the cookies.
store_->DeleteCookie(*http_444_cookie_);
DestroyStore();
cookies_.clear();
cookies_ = CreateAndLoad(/*crypt_cookies=*/false,
/*restore_old_session_cookies=*/false);
// Only the single cookie should be deleted.
EXPECT_THAT(cookies_, testing::UnorderedElementsAre(
MatchesEveryCookieField(*basic_cookie_),
MatchesEveryCookieField(*http_cookie_),
MatchesEveryCookieField(*port_444_cookie_)));
}
// Tests that updating a cookie correctly takes the scheme and port into
// account.
TEST_F(SQLitePersistentCookieStoreTest_OriginBoundCookies,
UpdateCookieAccessTime) {
InitializeTest();
base::Time basic_last_access = basic_cookie_->LastAccessDate();
base::Time http_last_access = http_cookie_->LastAccessDate();
base::Time port_444_last_access = port_444_cookie_->LastAccessDate();
base::Time http_444_last_access = http_444_cookie_->LastAccessDate();
base::Time new_last_access = http_444_last_access + base::Hours(1);
http_444_cookie_->SetLastAccessDate(new_last_access);
store_->UpdateCookieAccessTime(*http_444_cookie_);
DestroyStore();
cookies_.clear();
cookies_ = CreateAndLoad(/*crypt_cookies=*/false,
/*restore_old_session_cookies=*/false);
// All loaded cookies' should have their original LastAccessDate() except for
// the one updated to new_last_access.
EXPECT_THAT(
cookies_,
testing::UnorderedElementsAre(
MatchesCookieKeyAndLastAccessDate(basic_cookie_->StrictlyUniqueKey(),
basic_last_access),
MatchesCookieKeyAndLastAccessDate(http_cookie_->StrictlyUniqueKey(),
http_last_access),
MatchesCookieKeyAndLastAccessDate(
port_444_cookie_->StrictlyUniqueKey(), port_444_last_access),
MatchesCookieKeyAndLastAccessDate(
http_444_cookie_->StrictlyUniqueKey(), new_last_access)));
}
TEST_F(SQLitePersistentCookieStoreTest, SavingPartitionedCookies) {
InitializeStore(/*crypt=*/false, /*restore_old_session_cookies=*/false);
store_->AddCookie(*CanonicalCookie::CreateUnsafeCookieForTesting(
"__Host-foo", "bar", GURL("https://example.com/").host(), "/",
/*creation=*/base::Time::Now(),
/*expiration=*/base::Time::Now() + base::Days(1),
/*last_access=*/base::Time::Now(),
/*last_update=*/base::Time::Now(), /*secure=*/true, /*httponly=*/false,
CookieSameSite::UNSPECIFIED, COOKIE_PRIORITY_DEFAULT,
CookiePartitionKey::FromURLForTesting(GURL("https://toplevelsite.com"))));
Flush();
std::string got_db_content(ReadRawDBContents());
EXPECT_NE(got_db_content.find("__Host-foo"), std::string::npos);
DestroyStore();
}
TEST_F(SQLitePersistentCookieStoreTest, LoadingPartitionedCookies) {
InitializeStore(/*crypt=*/false, /*restore_old_session_cookies=*/false);
DestroyStore();
// Insert a partitioned cookie into the database manually.
base::FilePath store_name(temp_dir_.GetPath().Append(kCookieFilename));
std::unique_ptr<sql::Database> db(
std::make_unique<sql::Database>(sql::test::kTestTag));
ASSERT_TRUE(db->Open(store_name));
sql::Statement stmt(db->GetUniqueStatement(
"INSERT INTO cookies (creation_utc, host_key, top_frame_site_key, name, "
"value, encrypted_value, path, expires_utc, is_secure, is_httponly, "
"samesite, last_access_utc, has_expires, is_persistent, priority, "
"source_scheme, source_port, last_update_utc, source_type, "
"has_cross_site_ancestor) "
"VALUES (?,?,?,?,?,'',?,?,1,0,0,?,1,1,0,?,?,?,0, 1)"));
ASSERT_TRUE(stmt.is_valid());
base::Time creation(base::Time::Now());
base::Time expiration(creation + base::Days(1));
base::Time last_access(base::Time::Now());
base::Time last_update(base::Time::Now());
stmt.BindTime(0, creation);
stmt.BindString(1, GURL("https://www.example.com/").host());
stmt.BindString(2, "https://toplevelsite.com");
stmt.BindString(3, "__Host-foo");
stmt.BindString(4, "bar");
stmt.BindString(5, "/");
stmt.BindTime(6, expiration);
stmt.BindTime(7, last_access);
stmt.BindInt(8, static_cast<int>(CookieSourceScheme::kUnset));
stmt.BindInt(9, SQLitePersistentCookieStore::kDefaultUnknownPort);
stmt.BindTime(10, last_update);
ASSERT_TRUE(stmt.Run());
stmt.Clear();
db.reset();
CanonicalCookieVector cookies = CreateAndLoad(
/*crypt_cookies=*/false, /*restore_old_session_cookies=*/false);
EXPECT_EQ(1u, cookies.size());
auto cc = std::move(cookies[0]);
EXPECT_EQ("__Host-foo", cc->Name());
EXPECT_EQ("bar", cc->Value());
EXPECT_EQ(GURL("https://www.example.com/").host(), cc->Domain());
EXPECT_TRUE(cc->IsPartitioned());
EXPECT_EQ(
CookiePartitionKey::FromURLForTesting(GURL("https://toplevelsite.com")),
cc->PartitionKey());
EXPECT_EQ(last_update, cc->LastUpdateDate());
}
std::unique_ptr<CanonicalCookie> CreatePartitionedCookie(
const std::string& name,
const std::string& domain,
const std::string& top_frame_site_key,
CookiePartitionKey::AncestorChainBit ancestor_chain_bit,
CookieSourceScheme scheme = CookieSourceScheme::kUnset,
bool partitioned_cookies_enabled = true) {
const base::Time now = base::Time::Now();
return CanonicalCookie::CreateUnsafeCookieForTesting(
name, "B", domain, "/", now, now, now, now, /*secure=*/true,
/*httponly=*/false, CookieSameSite::UNSPECIFIED, COOKIE_PRIORITY_DEFAULT,
partitioned_cookies_enabled
? CookiePartitionKey::FromURLForTesting(GURL(top_frame_site_key),
ancestor_chain_bit)
:
/* std::nullopt can't be used because of the ternary evaluation might
result in different types */
std::optional<CookiePartitionKey>(),
scheme);
}
// During migration we have no way of knowing if a cross site ancestor was
// present. When the existing domain and the top_level_site of the partition key
// are the same. The default behavior is to set the cross site value to
// kSameSite, so ignore the kCrossSite cookie when testing migration.
std::vector<CanonicalCookie> GenerateCookiesForCrossSiteAncestorTest(
bool migrating = false) {
std::vector<CanonicalCookie> results;
const std::string default_domain = "example.com";
// Key and domain are the same site
results.emplace_back(*CreatePartitionedCookie(
"A", default_domain, "https://www.example.com",
CookiePartitionKey::AncestorChainBit::kSameSite));
if (!migrating) {
// Key and domain are the same site but with kCrossSite
results.emplace_back(*CreatePartitionedCookie(
"B", default_domain, "https://www.example.com",
CookiePartitionKey::AncestorChainBit::kCrossSite));
}
// Key and domain are different
results.emplace_back(*CreatePartitionedCookie(
"C", default_domain, "https://www.toplevelsite.com",
CookiePartitionKey::AncestorChainBit::kCrossSite));
// Domain is a substring
results.emplace_back(*CreatePartitionedCookie(
"D", "ample.com", "https://www.example.com",
CookiePartitionKey::AncestorChainBit::kCrossSite));
// http check kNonSecure scheme match.
results.emplace_back(*CreatePartitionedCookie(
"E", default_domain, "http://www.example.com",
CookiePartitionKey::AncestorChainBit::kSameSite));
return results;
}
TEST_F(SQLitePersistentCookieStoreTest,
UpgradeToSchemaVersion23_AddingHasCrossSiteAncestor) {
const base::FilePath database_path =
temp_dir_.GetPath().Append(kCookieFilename);
std::vector<CanonicalCookie> exected_cookies =
GenerateCookiesForCrossSiteAncestorTest(/*migrating=*/true);
std::vector<CanonicalCookie> cookies;
for (auto cookie : exected_cookies) {
cookies.push_back(cookie);
}
// Open database, populate and close db.
{
sql::Database db(sql::test::kTestTag);
ASSERT_TRUE(db.Open(database_path));
ASSERT_TRUE(CreateV22Schema(&db));
ASSERT_EQ(GetDBCurrentVersionNumber(&db), 22);
ASSERT_TRUE(AddV22CookiesToDB(&db, cookies));
}
CanonicalCookieVector read_in_cookies = CreateAndLoad(
/*crypt_cookies=*/false, /*restore_old_session_cookies=*/true);
EXPECT_EQ(read_in_cookies.size(), cookies.size());
// Reopen database for testing.
sql::Database connection(sql::test::kTestTag);
ASSERT_TRUE(connection.Open(database_path));
ASSERT_GE(GetDBCurrentVersionNumber(&connection), 23);
for (const auto& cookie : exected_cookies) {
base::expected<CookiePartitionKey::SerializedCookiePartitionKey,
std::string>
serialized_partition_key =
CookiePartitionKey::Serialize(cookie.PartitionKey());
ASSERT_TRUE(serialized_partition_key.has_value());
sql::Statement verify_stmt(connection.GetUniqueStatement(
"SELECT name FROM cookies WHERE host_key=?"
" AND top_frame_site_key=?"
" AND has_cross_site_ancestor=?"));
verify_stmt.BindString(0, cookie.Domain());
verify_stmt.BindString(1, serialized_partition_key->TopLevelSite());
verify_stmt.BindBool(2,
serialized_partition_key->has_cross_site_ancestor());
ASSERT_TRUE(verify_stmt.is_valid());
EXPECT_TRUE(verify_stmt.Step());
EXPECT_EQ(cookie.Name(), verify_stmt.ColumnString(0));
// Confirm that exactly one cookie matches the SQL query
EXPECT_FALSE(verify_stmt.Step());
}
}
TEST_F(SQLitePersistentCookieStoreTest,
TestValueOfHasCrossSiteAncestorOnDoCommit) {
InitializeStore(/*crypt=*/false, /*restore_old_session_cookies=*/false);
std::vector<CanonicalCookie> exected_cookies =
GenerateCookiesForCrossSiteAncestorTest();
for (const auto& cookie : exected_cookies) {
store_->AddCookie(cookie);
}
// Force the store to write its data to the disk.
DestroyStore();
cookies_ = CreateAndLoad(/*crypt_cookies=*/false,
/*restore_old_session_cookies=*/false);
EXPECT_EQ(cookies_.size(), exected_cookies.size());
sql::Database connection(sql::test::kTestTag);
ASSERT_TRUE(connection.Open(temp_dir_.GetPath().Append(kCookieFilename)));
ASSERT_GT(GetDBCurrentVersionNumber(&connection), 23);
for (const auto& cookie : exected_cookies) {
base::expected<CookiePartitionKey::SerializedCookiePartitionKey,
std::string>
serialized_partition_key =
CookiePartitionKey::Serialize(cookie.PartitionKey());
ASSERT_TRUE(serialized_partition_key.has_value());
sql::Statement verify_stmt(connection.GetUniqueStatement(
"SELECT name FROM cookies WHERE host_key=?"
" AND top_frame_site_key=?"
" AND has_cross_site_ancestor=?"));
verify_stmt.BindString(0, cookie.Domain());
verify_stmt.BindString(1, serialized_partition_key->TopLevelSite());
verify_stmt.BindBool(2,
serialized_partition_key->has_cross_site_ancestor());
ASSERT_TRUE(verify_stmt.is_valid());
EXPECT_TRUE(verify_stmt.Step());
EXPECT_EQ(cookie.Name(), verify_stmt.ColumnString(0));
// Confirm that exactly one cookie matches the SQL query
EXPECT_FALSE(verify_stmt.Step());
}
}
TEST_F(SQLitePersistentCookieStoreTest, NoCryptoForDecryption) {
InitializeStore(/*crypt=*/true, /*restore_old_session_cookies=*/false);
AddCookie("X", "Y", "foo.bar", "/", base::Time::Now());
DestroyStore();
{
base::HistogramTester histogram_tester;
const auto cookies =
CreateAndLoad(/*crypt=*/false, /*restore_old_session_cookies=*/false);
ASSERT_TRUE(cookies.empty());
histogram_tester.ExpectBucketCount("Cookie.LoadProblem",
/*CookieLoadProblem::kNoCrypto*/ 7, 1);
}
}
class SQLitePersistentCookieStoreTestWithDropDupDataFeature
: public ::testing::WithParamInterface<
/*features::kEncryptedAndPlaintextValuesAreInvalid*/ bool>,
public SQLitePersistentCookieStoreTest {
public:
void SetUp() override {
features_.InitWithFeatureState(
features::kEncryptedAndPlaintextValuesAreInvalid,
IsDroppingCookiesEnabled());
SQLitePersistentCookieStoreTest::SetUp();
}
protected:
bool IsDroppingCookiesEnabled() const { return GetParam(); }
private:
base::test::ScopedFeatureList features_;
};
// This test verifies that if a plaintext value is in the store (e.g. written in
// manually, or crypto was at some point not available in the past) and crypto
// is now available, it can still be read fine, including if the value is empty.
// It also tests the case where both a plaintext and encrypted value exist,
// where the encrypted value should always take precedence except if
// kEncryptedAndPlaintextValuesAreInvalid is enabled, in which case the cookie
// is dropped.
TEST_P(SQLitePersistentCookieStoreTestWithDropDupDataFeature,
OverridePlaintextValue) {
{
CreateAndLoad(/*crypt_cookies=*/true,
/*restore_old_session_cookies=*/false);
AddCookie("A", "B", "example.com", "/", base::Time::Now());
AddCookie("C", "D", "example2.com", "/", base::Time::Now());
AddCookie("E", "F", "example3.com", "/", base::Time::Now());
DestroyStore();
}
{
base::HistogramTester histogram_tester;
auto cookies = CreateAndLoad(/*crypt_cookies=*/true,
/*restore_old_session_cookies=*/false);
ASSERT_EQ(cookies.size(), 3u);
EXPECT_EQ(cookies[0]->Domain(), "example.com");
EXPECT_EQ(cookies[0]->Name(), "A");
EXPECT_EQ(cookies[0]->Value(), "B");
EXPECT_EQ(cookies[1]->Domain(), "example2.com");
EXPECT_EQ(cookies[1]->Name(), "C");
EXPECT_EQ(cookies[1]->Value(), "D");
EXPECT_EQ(cookies[2]->Domain(), "example3.com");
EXPECT_EQ(cookies[2]->Name(), "E");
EXPECT_EQ(cookies[2]->Value(), "F");
DestroyStore();
}
{
const base::FilePath database_path =
temp_dir_.GetPath().Append(kCookieFilename);
sql::Database connection(sql::test::kTestTag);
ASSERT_TRUE(connection.Open(database_path));
sql::Transaction transaction(&connection);
ASSERT_TRUE(transaction.Begin());
// Clear the encrypted value and set the plaintext value to something else.
ASSERT_TRUE(
connection.Execute("UPDATE cookies SET encrypted_value=x'', "
"value='Val' WHERE host_key='example.com'"));
// Verify also that an empty value can be injected.
ASSERT_TRUE(
connection.Execute("UPDATE cookies SET encrypted_value=x'', "
"value='' WHERE host_key='example2.com'"));
// Verify if both are present, it's dealt with correctly (encrypted data
// takes priority), and a histogram is recorded.
ASSERT_TRUE(connection.Execute(
"UPDATE cookies SET value='not-F' WHERE host_key='example3.com'"));
ASSERT_TRUE(transaction.Commit());
}
{
base::HistogramTester histogram_tester;
auto cookies = CreateAndLoad(/*crypt_cookies=*/true,
/*restore_old_session_cookies=*/false);
histogram_tester.ExpectBucketCount("Cookie.EncryptedAndPlaintextValues",
true, 1);
// Third cookie (example3.com) should be dropped if
// kEncryptedAndPlaintextValuesAreInvalid is enabled.
ASSERT_EQ(cookies.size(), IsDroppingCookiesEnabled() ? 2u : 3u);
// Cookie should load fine since it's been modified by writing plaintext and
// clearing ciphertext.
EXPECT_EQ(cookies[0]->Domain(), "example.com");
EXPECT_EQ(cookies[0]->Name(), "A");
EXPECT_EQ(cookies[0]->Value(), "Val");
EXPECT_EQ(cookies[1]->Domain(), "example2.com");
EXPECT_EQ(cookies[1]->Name(), "C");
EXPECT_TRUE(cookies[1]->Value().empty());
if (IsDroppingCookiesEnabled()) {
// Cookie should be dropped and a metric recorded.
histogram_tester.ExpectBucketCount(
"Cookie.LoadProblem",
/*CookieLoadProblem::kValuesExistInBothEncryptedAndPlaintext*/ 8, 1u);
} else {
// If the kEncryptedAndPlaintextValuesAreInvalid feature is disabled (and
// the cookie was not dropped) then the final cookie should always use the
// encrypted value and not the plaintext value.
EXPECT_EQ(cookies[2]->Domain(), "example3.com");
EXPECT_EQ(cookies[2]->Name(), "E");
EXPECT_EQ(cookies[2]->Value(), "F");
histogram_tester.ExpectTotalCount("Cookie.LoadProblem", 0);
}
DestroyStore();
}
}
INSTANTIATE_TEST_SUITE_P(,
SQLitePersistentCookieStoreTestWithDropDupDataFeature,
::testing::Bool(),
[](auto& info) {
return info.param ? "Enabled" : "Disabled";
});
} // namespace net
|