1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561
|
// Copyright 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "components/sync/engine_impl/sync_manager_impl.h"
#include <cstddef>
#include <memory>
#include <utility>
#include "base/callback.h"
#include "base/compiler_specific.h"
#include "base/files/scoped_temp_dir.h"
#include "base/format_macros.h"
#include "base/location.h"
#include "base/metrics/field_trial.h"
#include "base/run_loop.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/stringprintf.h"
#include "base/strings/utf_string_conversions.h"
#include "base/test/scoped_feature_list.h"
#include "base/test/values_test_util.h"
#include "base/values.h"
#include "components/sync/base/attachment_id_proto.h"
#include "components/sync/base/cancelation_signal.h"
#include "components/sync/base/extensions_activity.h"
#include "components/sync/base/fake_encryptor.h"
#include "components/sync/base/hash_util.h"
#include "components/sync/base/mock_unrecoverable_error_handler.h"
#include "components/sync/base/model_type_test_util.h"
#include "components/sync/base/sync_features.h"
#include "components/sync/engine/engine_util.h"
#include "components/sync/engine/events/protocol_event.h"
#include "components/sync/engine/model_safe_worker.h"
#include "components/sync/engine/net/http_post_provider_factory.h"
#include "components/sync/engine/net/http_post_provider_interface.h"
#include "components/sync/engine/polling_constants.h"
#include "components/sync/engine/test_engine_components_factory.h"
#include "components/sync/engine_impl/cycle/sync_cycle.h"
#include "components/sync/engine_impl/sync_scheduler.h"
#include "components/sync/engine_impl/test_entry_factory.h"
#include "components/sync/js/js_event_handler.h"
#include "components/sync/js/js_test_util.h"
#include "components/sync/protocol/bookmark_specifics.pb.h"
#include "components/sync/protocol/encryption.pb.h"
#include "components/sync/protocol/extension_specifics.pb.h"
#include "components/sync/protocol/password_specifics.pb.h"
#include "components/sync/protocol/preference_specifics.pb.h"
#include "components/sync/protocol/proto_value_conversions.h"
#include "components/sync/protocol/sync.pb.h"
#include "components/sync/syncable/change_record.h"
#include "components/sync/syncable/directory.h"
#include "components/sync/syncable/entry.h"
#include "components/sync/syncable/mutable_entry.h"
#include "components/sync/syncable/nigori_util.h"
#include "components/sync/syncable/read_node.h"
#include "components/sync/syncable/read_transaction.h"
#include "components/sync/syncable/syncable_id.h"
#include "components/sync/syncable/syncable_read_transaction.h"
#include "components/sync/syncable/syncable_write_transaction.h"
#include "components/sync/syncable/test_user_share.h"
#include "components/sync/syncable/write_node.h"
#include "components/sync/syncable/write_transaction.h"
#include "components/sync/test/callback_counter.h"
#include "components/sync/test/engine/fake_model_worker.h"
#include "components/sync/test/engine/fake_sync_scheduler.h"
#include "components/sync/test/engine/test_id_factory.h"
#include "google_apis/gaia/gaia_constants.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/protobuf/src/google/protobuf/io/coded_stream.h"
#include "third_party/protobuf/src/google/protobuf/io/zero_copy_stream_impl_lite.h"
#include "url/gurl.h"
using base::ExpectDictStringValue;
using testing::_;
using testing::DoAll;
using testing::InSequence;
using testing::Return;
using testing::SaveArg;
using testing::StrictMock;
namespace syncer {
using syncable::GET_BY_HANDLE;
using syncable::IS_DEL;
using syncable::IS_UNSYNCED;
using syncable::NON_UNIQUE_NAME;
using syncable::SPECIFICS;
using syncable::kEncryptedString;
namespace {
// Makes a child node under the type root folder. Returns the id of the
// newly-created node.
int64_t MakeNode(UserShare* share,
ModelType model_type,
const std::string& client_tag) {
WriteTransaction trans(FROM_HERE, share);
WriteNode node(&trans);
WriteNode::InitUniqueByCreationResult result =
node.InitUniqueByCreation(model_type, client_tag);
EXPECT_EQ(WriteNode::INIT_SUCCESS, result);
node.SetIsFolder(false);
return node.GetId();
}
// Makes a non-folder child of the root node. Returns the id of the
// newly-created node.
int64_t MakeNodeWithRoot(UserShare* share,
ModelType model_type,
const std::string& client_tag) {
WriteTransaction trans(FROM_HERE, share);
ReadNode root_node(&trans);
root_node.InitByRootLookup();
WriteNode node(&trans);
WriteNode::InitUniqueByCreationResult result =
node.InitUniqueByCreation(model_type, root_node, client_tag);
EXPECT_EQ(WriteNode::INIT_SUCCESS, result);
node.SetIsFolder(false);
return node.GetId();
}
// Makes a folder child of a non-root node. Returns the id of the
// newly-created node.
int64_t MakeFolderWithParent(UserShare* share,
ModelType model_type,
int64_t parent_id,
BaseNode* predecessor) {
WriteTransaction trans(FROM_HERE, share);
ReadNode parent_node(&trans);
EXPECT_EQ(BaseNode::INIT_OK, parent_node.InitByIdLookup(parent_id));
WriteNode node(&trans);
EXPECT_TRUE(node.InitBookmarkByCreation(parent_node, predecessor));
node.SetIsFolder(true);
return node.GetId();
}
int64_t MakeBookmarkWithParent(UserShare* share,
int64_t parent_id,
BaseNode* predecessor) {
WriteTransaction trans(FROM_HERE, share);
ReadNode parent_node(&trans);
EXPECT_EQ(BaseNode::INIT_OK, parent_node.InitByIdLookup(parent_id));
WriteNode node(&trans);
EXPECT_TRUE(node.InitBookmarkByCreation(parent_node, predecessor));
return node.GetId();
}
// Creates the "synced" root node for a particular datatype. We use the syncable
// methods here so that the syncer treats these nodes as if they were already
// received from the server.
int64_t MakeTypeRoot(UserShare* share, ModelType model_type) {
sync_pb::EntitySpecifics specifics;
AddDefaultFieldValue(model_type, &specifics);
syncable::WriteTransaction trans(FROM_HERE, syncable::UNITTEST,
share->directory.get());
// Attempt to lookup by nigori tag.
std::string type_tag = ModelTypeToRootTag(model_type);
syncable::Id node_id = syncable::Id::CreateFromServerId(type_tag);
syncable::MutableEntry entry(&trans, syncable::CREATE_NEW_UPDATE_ITEM,
node_id);
EXPECT_TRUE(entry.good());
entry.PutBaseVersion(1);
entry.PutServerVersion(1);
entry.PutIsUnappliedUpdate(false);
entry.PutParentId(syncable::Id::GetRoot());
entry.PutServerParentId(syncable::Id::GetRoot());
entry.PutServerIsDir(true);
entry.PutIsDir(true);
entry.PutServerSpecifics(specifics);
entry.PutSpecifics(specifics);
entry.PutUniqueServerTag(type_tag);
entry.PutNonUniqueName(type_tag);
entry.PutIsDel(false);
return entry.GetMetahandle();
}
// Simulates creating a "synced" node as a child of the root datatype node.
int64_t MakeServerNode(UserShare* share,
ModelType model_type,
const std::string& client_tag,
const std::string& hashed_tag,
const sync_pb::EntitySpecifics& specifics) {
syncable::WriteTransaction trans(FROM_HERE, syncable::UNITTEST,
share->directory.get());
syncable::Entry root_entry(&trans, syncable::GET_TYPE_ROOT, model_type);
EXPECT_TRUE(root_entry.good());
syncable::Id root_id = root_entry.GetId();
syncable::Id node_id = syncable::Id::CreateFromServerId(client_tag);
syncable::MutableEntry entry(&trans, syncable::CREATE_NEW_UPDATE_ITEM,
node_id);
EXPECT_TRUE(entry.good());
entry.PutBaseVersion(1);
entry.PutServerVersion(1);
entry.PutIsUnappliedUpdate(false);
entry.PutServerParentId(root_id);
entry.PutParentId(root_id);
entry.PutServerIsDir(false);
entry.PutIsDir(false);
entry.PutServerSpecifics(specifics);
entry.PutSpecifics(specifics);
entry.PutNonUniqueName(client_tag);
entry.PutUniqueClientTag(hashed_tag);
entry.PutIsDel(false);
return entry.GetMetahandle();
}
int GetTotalNodeCount(UserShare* share, int64_t root) {
ReadTransaction trans(FROM_HERE, share);
ReadNode node(&trans);
EXPECT_EQ(BaseNode::INIT_OK, node.InitByIdLookup(root));
return node.GetTotalNodeCount();
}
const char kUrl[] = "example.com";
const char kPasswordValue[] = "secret";
const char kClientTag[] = "tag";
} // namespace
// Unit tests for the SyncApi. Note that a lot of the underlying
// functionality is provided by the Syncable layer, which has its own
// unit tests. We'll test SyncApi specific things in this harness.
class SyncApiTest : public testing::Test {
public:
void SetUp() override { test_user_share_.SetUp(); }
void TearDown() override { test_user_share_.TearDown(); }
protected:
// Create an entry with the given |model_type|, |client_tag| and
// |attachment_metadata|.
void CreateEntryWithAttachmentMetadata(
const ModelType& model_type,
const std::string& client_tag,
const sync_pb::AttachmentMetadata& attachment_metadata);
// Attempts to load the entry specified by |model_type| and |client_tag| and
// returns the lookup result code.
BaseNode::InitByLookupResult LookupEntryByClientTag(
const ModelType& model_type,
const std::string& client_tag);
// Replace the entry specified by |model_type| and |client_tag| with a
// tombstone.
void ReplaceWithTombstone(const ModelType& model_type,
const std::string& client_tag);
// Save changes to the Directory, destroy it then reload it.
bool ReloadDir();
UserShare* user_share();
syncable::Directory* dir();
SyncEncryptionHandler* encryption_handler();
PassphraseType GetPassphraseType(BaseTransaction* trans);
private:
base::MessageLoop message_loop_;
TestUserShare test_user_share_;
};
UserShare* SyncApiTest::user_share() {
return test_user_share_.user_share();
}
syncable::Directory* SyncApiTest::dir() {
return test_user_share_.user_share()->directory.get();
}
SyncEncryptionHandler* SyncApiTest::encryption_handler() {
return test_user_share_.encryption_handler();
}
PassphraseType SyncApiTest::GetPassphraseType(BaseTransaction* trans) {
return dir()->GetNigoriHandler()->GetPassphraseType(trans->GetWrappedTrans());
}
bool SyncApiTest::ReloadDir() {
return test_user_share_.Reload();
}
void SyncApiTest::CreateEntryWithAttachmentMetadata(
const ModelType& model_type,
const std::string& client_tag,
const sync_pb::AttachmentMetadata& attachment_metadata) {
WriteTransaction trans(FROM_HERE, user_share());
ReadNode root_node(&trans);
root_node.InitByRootLookup();
WriteNode node(&trans);
ASSERT_EQ(node.InitUniqueByCreation(model_type, root_node, client_tag),
WriteNode::INIT_SUCCESS);
node.SetAttachmentMetadata(attachment_metadata);
}
BaseNode::InitByLookupResult SyncApiTest::LookupEntryByClientTag(
const ModelType& model_type,
const std::string& client_tag) {
ReadTransaction trans(FROM_HERE, user_share());
ReadNode node(&trans);
return node.InitByClientTagLookup(model_type, client_tag);
}
void SyncApiTest::ReplaceWithTombstone(const ModelType& model_type,
const std::string& client_tag) {
WriteTransaction trans(FROM_HERE, user_share());
WriteNode node(&trans);
ASSERT_EQ(node.InitByClientTagLookup(model_type, client_tag),
WriteNode::INIT_OK);
node.Tombstone();
}
TEST_F(SyncApiTest, SanityCheckTest) {
{
ReadTransaction trans(FROM_HERE, user_share());
EXPECT_TRUE(trans.GetWrappedTrans());
}
{
WriteTransaction trans(FROM_HERE, user_share());
EXPECT_TRUE(trans.GetWrappedTrans());
}
{
// No entries but root should exist
ReadTransaction trans(FROM_HERE, user_share());
ReadNode node(&trans);
// Metahandle 1 can be root, sanity check 2
EXPECT_EQ(BaseNode::INIT_FAILED_ENTRY_NOT_GOOD, node.InitByIdLookup(2));
}
}
TEST_F(SyncApiTest, BasicTagWrite) {
{
ReadTransaction trans(FROM_HERE, user_share());
ReadNode root_node(&trans);
root_node.InitByRootLookup();
EXPECT_EQ(kInvalidId, root_node.GetFirstChildId());
}
ignore_result(MakeNodeWithRoot(user_share(), BOOKMARKS, "testtag"));
{
ReadTransaction trans(FROM_HERE, user_share());
ReadNode node(&trans);
EXPECT_EQ(BaseNode::INIT_OK,
node.InitByClientTagLookup(BOOKMARKS, "testtag"));
EXPECT_NE(0, node.GetId());
ReadNode root_node(&trans);
root_node.InitByRootLookup();
EXPECT_EQ(node.GetId(), root_node.GetFirstChildId());
}
}
TEST_F(SyncApiTest, BasicTagWriteWithImplicitParent) {
int64_t type_root = MakeTypeRoot(user_share(), PREFERENCES);
{
ReadTransaction trans(FROM_HERE, user_share());
ReadNode type_root_node(&trans);
EXPECT_EQ(BaseNode::INIT_OK, type_root_node.InitByIdLookup(type_root));
EXPECT_EQ(kInvalidId, type_root_node.GetFirstChildId());
}
ignore_result(MakeNode(user_share(), PREFERENCES, "testtag"));
{
ReadTransaction trans(FROM_HERE, user_share());
ReadNode node(&trans);
EXPECT_EQ(BaseNode::INIT_OK,
node.InitByClientTagLookup(PREFERENCES, "testtag"));
EXPECT_EQ(kInvalidId, node.GetParentId());
ReadNode type_root_node(&trans);
EXPECT_EQ(BaseNode::INIT_OK, type_root_node.InitByIdLookup(type_root));
EXPECT_EQ(node.GetId(), type_root_node.GetFirstChildId());
}
}
TEST_F(SyncApiTest, ModelTypesSiloed) {
{
WriteTransaction trans(FROM_HERE, user_share());
ReadNode root_node(&trans);
root_node.InitByRootLookup();
EXPECT_EQ(root_node.GetFirstChildId(), 0);
}
ignore_result(MakeNodeWithRoot(user_share(), BOOKMARKS, "collideme"));
ignore_result(MakeNodeWithRoot(user_share(), PREFERENCES, "collideme"));
ignore_result(MakeNodeWithRoot(user_share(), AUTOFILL, "collideme"));
{
ReadTransaction trans(FROM_HERE, user_share());
ReadNode bookmarknode(&trans);
EXPECT_EQ(BaseNode::INIT_OK,
bookmarknode.InitByClientTagLookup(BOOKMARKS, "collideme"));
ReadNode prefnode(&trans);
EXPECT_EQ(BaseNode::INIT_OK,
prefnode.InitByClientTagLookup(PREFERENCES, "collideme"));
ReadNode autofillnode(&trans);
EXPECT_EQ(BaseNode::INIT_OK,
autofillnode.InitByClientTagLookup(AUTOFILL, "collideme"));
EXPECT_NE(bookmarknode.GetId(), prefnode.GetId());
EXPECT_NE(autofillnode.GetId(), prefnode.GetId());
EXPECT_NE(bookmarknode.GetId(), autofillnode.GetId());
}
}
TEST_F(SyncApiTest, ReadMissingTagsFails) {
{
ReadTransaction trans(FROM_HERE, user_share());
ReadNode node(&trans);
EXPECT_EQ(BaseNode::INIT_FAILED_ENTRY_NOT_GOOD,
node.InitByClientTagLookup(BOOKMARKS, "testtag"));
}
{
WriteTransaction trans(FROM_HERE, user_share());
WriteNode node(&trans);
EXPECT_EQ(BaseNode::INIT_FAILED_ENTRY_NOT_GOOD,
node.InitByClientTagLookup(BOOKMARKS, "testtag"));
}
}
// TODO(chron): Hook this all up to the server and write full integration tests
// for update->undelete behavior.
TEST_F(SyncApiTest, TestDeleteBehavior) {
int64_t node_id;
int64_t folder_id;
std::string test_title("test1");
{
WriteTransaction trans(FROM_HERE, user_share());
ReadNode root_node(&trans);
root_node.InitByRootLookup();
// we'll use this spare folder later
WriteNode folder_node(&trans);
EXPECT_TRUE(folder_node.InitBookmarkByCreation(root_node, nullptr));
folder_id = folder_node.GetId();
WriteNode wnode(&trans);
WriteNode::InitUniqueByCreationResult result =
wnode.InitUniqueByCreation(BOOKMARKS, root_node, "testtag");
EXPECT_EQ(WriteNode::INIT_SUCCESS, result);
wnode.SetIsFolder(false);
wnode.SetTitle(test_title);
node_id = wnode.GetId();
}
// Ensure we can delete something with a tag.
{
WriteTransaction trans(FROM_HERE, user_share());
WriteNode wnode(&trans);
EXPECT_EQ(BaseNode::INIT_OK,
wnode.InitByClientTagLookup(BOOKMARKS, "testtag"));
EXPECT_FALSE(wnode.GetIsFolder());
EXPECT_EQ(wnode.GetTitle(), test_title);
wnode.Tombstone();
}
// Lookup of a node which was deleted should return failure,
// but have found some data about the node.
{
ReadTransaction trans(FROM_HERE, user_share());
ReadNode node(&trans);
EXPECT_EQ(BaseNode::INIT_FAILED_ENTRY_IS_DEL,
node.InitByClientTagLookup(BOOKMARKS, "testtag"));
// Note that for proper function of this API this doesn't need to be
// filled, we're checking just to make sure the DB worked in this test.
EXPECT_EQ(node.GetTitle(), test_title);
}
{
WriteTransaction trans(FROM_HERE, user_share());
ReadNode folder_node(&trans);
EXPECT_EQ(BaseNode::INIT_OK, folder_node.InitByIdLookup(folder_id));
WriteNode wnode(&trans);
// This will undelete the tag.
WriteNode::InitUniqueByCreationResult result =
wnode.InitUniqueByCreation(BOOKMARKS, folder_node, "testtag");
EXPECT_EQ(WriteNode::INIT_SUCCESS, result);
EXPECT_EQ(wnode.GetIsFolder(), false);
EXPECT_EQ(wnode.GetParentId(), folder_node.GetId());
EXPECT_EQ(wnode.GetId(), node_id);
EXPECT_NE(wnode.GetTitle(), test_title); // Title should be cleared
wnode.SetTitle(test_title);
}
// Now look up should work.
{
ReadTransaction trans(FROM_HERE, user_share());
ReadNode node(&trans);
EXPECT_EQ(BaseNode::INIT_OK,
node.InitByClientTagLookup(BOOKMARKS, "testtag"));
EXPECT_EQ(node.GetTitle(), test_title);
EXPECT_EQ(node.GetModelType(), BOOKMARKS);
}
}
TEST_F(SyncApiTest, WriteAndReadPassword) {
KeyParams params = {"localhost", "username", "passphrase"};
EXPECT_FALSE(base::FeatureList::IsEnabled(kFillPasswordMetadata));
{
ReadTransaction trans(FROM_HERE, user_share());
trans.GetCryptographer()->AddKey(params);
}
{
WriteTransaction trans(FROM_HERE, user_share());
ReadNode root_node(&trans);
root_node.InitByRootLookup();
WriteNode password_node(&trans);
WriteNode::InitUniqueByCreationResult result =
password_node.InitUniqueByCreation(PASSWORDS, root_node, kClientTag);
EXPECT_EQ(WriteNode::INIT_SUCCESS, result);
sync_pb::PasswordSpecificsData data;
data.set_password_value(kPasswordValue);
password_node.SetPasswordSpecifics(data);
}
{
ReadTransaction trans(FROM_HERE, user_share());
ReadNode password_node(&trans);
EXPECT_EQ(BaseNode::INIT_OK,
password_node.InitByClientTagLookup(PASSWORDS, kClientTag));
const sync_pb::PasswordSpecificsData& data =
password_node.GetPasswordSpecifics();
EXPECT_EQ(kPasswordValue, data.password_value());
// Check that when feature is disabled nothing appears in the unencrypted
// field.
EXPECT_FALSE(password_node.GetEntitySpecifics()
.password()
.has_unencrypted_metadata());
}
}
TEST_F(SyncApiTest, WritePasswordAndCheckMetadata) {
KeyParams params = {"localhost", "username", "passphrase"};
{
ReadTransaction trans(FROM_HERE, user_share());
trans.GetCryptographer()->AddKey(params);
}
base::FieldTrialList field_trial_list(nullptr);
base::test::ScopedFeatureList scoped_feature_list;
scoped_feature_list.InitAndEnableFeature(kFillPasswordMetadata);
EXPECT_TRUE(base::FeatureList::IsEnabled(kFillPasswordMetadata));
{
WriteTransaction trans(FROM_HERE, user_share());
ReadNode root_node(&trans);
root_node.InitByRootLookup();
WriteNode password_node(&trans);
WriteNode::InitUniqueByCreationResult result =
password_node.InitUniqueByCreation(PASSWORDS, root_node, kClientTag);
EXPECT_EQ(WriteNode::INIT_SUCCESS, result);
sync_pb::PasswordSpecificsData data;
data.set_password_value(kPasswordValue);
data.set_signon_realm(kUrl);
password_node.SetPasswordSpecifics(data);
}
{
ReadTransaction trans(FROM_HERE, user_share());
ReadNode password_node(&trans);
EXPECT_EQ(BaseNode::INIT_OK,
password_node.InitByClientTagLookup(PASSWORDS, kClientTag));
const sync_pb::PasswordSpecificsData& data =
password_node.GetPasswordSpecifics();
EXPECT_EQ(kPasswordValue, data.password_value());
EXPECT_EQ(kUrl, password_node.GetEntitySpecifics()
.password()
.unencrypted_metadata()
.url());
}
}
TEST_F(SyncApiTest, WriteEncryptedTitle) {
KeyParams params = {"localhost", "username", "passphrase"};
{
ReadTransaction trans(FROM_HERE, user_share());
trans.GetCryptographer()->AddKey(params);
}
encryption_handler()->EnableEncryptEverything();
int bookmark_id;
{
WriteTransaction trans(FROM_HERE, user_share());
ReadNode root_node(&trans);
root_node.InitByRootLookup();
WriteNode bookmark_node(&trans);
ASSERT_TRUE(bookmark_node.InitBookmarkByCreation(root_node, nullptr));
bookmark_id = bookmark_node.GetId();
bookmark_node.SetTitle("foo");
WriteNode pref_node(&trans);
WriteNode::InitUniqueByCreationResult result =
pref_node.InitUniqueByCreation(PREFERENCES, root_node, "bar");
ASSERT_EQ(WriteNode::INIT_SUCCESS, result);
pref_node.SetTitle("bar");
}
{
ReadTransaction trans(FROM_HERE, user_share());
ReadNode bookmark_node(&trans);
ASSERT_EQ(BaseNode::INIT_OK, bookmark_node.InitByIdLookup(bookmark_id));
EXPECT_EQ("foo", bookmark_node.GetTitle());
EXPECT_EQ(kEncryptedString, bookmark_node.GetEntry()->GetNonUniqueName());
ReadNode pref_node(&trans);
ASSERT_EQ(BaseNode::INIT_OK,
pref_node.InitByClientTagLookup(PREFERENCES, "bar"));
EXPECT_EQ(kEncryptedString, pref_node.GetTitle());
}
}
// Non-unique name should not be empty. For bookmarks non-unique name is copied
// from bookmark title. This test verifies that setting bookmark title to ""
// results in single space title and non-unique name in internal representation.
// GetTitle should still return empty string.
TEST_F(SyncApiTest, WriteEmptyBookmarkTitle) {
int bookmark_id;
{
WriteTransaction trans(FROM_HERE, user_share());
ReadNode root_node(&trans);
root_node.InitByRootLookup();
WriteNode bookmark_node(&trans);
ASSERT_TRUE(bookmark_node.InitBookmarkByCreation(root_node, nullptr));
bookmark_id = bookmark_node.GetId();
bookmark_node.SetTitle("");
}
{
ReadTransaction trans(FROM_HERE, user_share());
ReadNode bookmark_node(&trans);
ASSERT_EQ(BaseNode::INIT_OK, bookmark_node.InitByIdLookup(bookmark_id));
EXPECT_EQ("", bookmark_node.GetTitle());
EXPECT_EQ(" ", bookmark_node.GetEntitySpecifics().bookmark().title());
EXPECT_EQ(" ", bookmark_node.GetEntry()->GetNonUniqueName());
}
}
TEST_F(SyncApiTest, BaseNodeSetSpecifics) {
int64_t child_id = MakeNodeWithRoot(user_share(), BOOKMARKS, "testtag");
WriteTransaction trans(FROM_HERE, user_share());
WriteNode node(&trans);
EXPECT_EQ(BaseNode::INIT_OK, node.InitByIdLookup(child_id));
sync_pb::EntitySpecifics entity_specifics;
entity_specifics.mutable_bookmark()->set_url("http://www.google.com");
EXPECT_NE(entity_specifics.SerializeAsString(),
node.GetEntitySpecifics().SerializeAsString());
node.SetEntitySpecifics(entity_specifics);
EXPECT_EQ(entity_specifics.SerializeAsString(),
node.GetEntitySpecifics().SerializeAsString());
}
TEST_F(SyncApiTest, BaseNodeSetSpecificsPreservesUnknownFields) {
int64_t child_id = MakeNodeWithRoot(user_share(), BOOKMARKS, "testtag");
WriteTransaction trans(FROM_HERE, user_share());
WriteNode node(&trans);
EXPECT_EQ(BaseNode::INIT_OK, node.InitByIdLookup(child_id));
EXPECT_TRUE(node.GetEntitySpecifics().unknown_fields().empty());
sync_pb::EntitySpecifics entity_specifics;
entity_specifics.mutable_bookmark()->set_url("http://www.google.com");
std::string unknown_fields;
{
::google::protobuf::io::StringOutputStream unknown_fields_stream(
&unknown_fields);
::google::protobuf::io::CodedOutputStream output(&unknown_fields_stream);
const int tag = 5;
const int value = 100;
output.WriteTag(tag);
output.WriteLittleEndian32(value);
}
*entity_specifics.mutable_unknown_fields() = unknown_fields;
node.SetEntitySpecifics(entity_specifics);
EXPECT_FALSE(node.GetEntitySpecifics().unknown_fields().empty());
EXPECT_EQ(unknown_fields, node.GetEntitySpecifics().unknown_fields());
entity_specifics.mutable_unknown_fields()->clear();
node.SetEntitySpecifics(entity_specifics);
EXPECT_FALSE(node.GetEntitySpecifics().unknown_fields().empty());
EXPECT_EQ(unknown_fields, node.GetEntitySpecifics().unknown_fields());
}
TEST_F(SyncApiTest, EmptyTags) {
WriteTransaction trans(FROM_HERE, user_share());
ReadNode root_node(&trans);
root_node.InitByRootLookup();
WriteNode node(&trans);
std::string empty_tag;
WriteNode::InitUniqueByCreationResult result =
node.InitUniqueByCreation(TYPED_URLS, root_node, empty_tag);
EXPECT_NE(WriteNode::INIT_SUCCESS, result);
EXPECT_EQ(BaseNode::INIT_FAILED_PRECONDITION,
node.InitByClientTagLookup(TYPED_URLS, empty_tag));
}
// Test counting nodes when the type's root node has no children.
TEST_F(SyncApiTest, GetTotalNodeCountEmpty) {
int64_t type_root = MakeTypeRoot(user_share(), BOOKMARKS);
EXPECT_EQ(1, GetTotalNodeCount(user_share(), type_root));
}
// Test counting nodes when there is one child beneath the type's root.
TEST_F(SyncApiTest, GetTotalNodeCountOneChild) {
int64_t type_root = MakeTypeRoot(user_share(), BOOKMARKS);
int64_t parent =
MakeFolderWithParent(user_share(), BOOKMARKS, type_root, nullptr);
EXPECT_EQ(2, GetTotalNodeCount(user_share(), type_root));
EXPECT_EQ(1, GetTotalNodeCount(user_share(), parent));
}
// Test counting nodes when there are multiple children beneath the type root,
// and one of those children has children of its own.
TEST_F(SyncApiTest, GetTotalNodeCountMultipleChildren) {
int64_t type_root = MakeTypeRoot(user_share(), BOOKMARKS);
int64_t parent =
MakeFolderWithParent(user_share(), BOOKMARKS, type_root, nullptr);
ignore_result(
MakeFolderWithParent(user_share(), BOOKMARKS, type_root, nullptr));
int64_t child1 =
MakeFolderWithParent(user_share(), BOOKMARKS, parent, nullptr);
ignore_result(MakeBookmarkWithParent(user_share(), parent, nullptr));
ignore_result(MakeBookmarkWithParent(user_share(), child1, nullptr));
EXPECT_EQ(6, GetTotalNodeCount(user_share(), type_root));
EXPECT_EQ(4, GetTotalNodeCount(user_share(), parent));
}
// Verify that Directory keeps track of which attachments are referenced by
// which entries.
TEST_F(SyncApiTest, AttachmentLinking) {
// Add an entry with an attachment.
std::string tag1("some tag");
AttachmentId attachment_id(AttachmentId::Create(0, 0));
sync_pb::AttachmentMetadata attachment_metadata;
sync_pb::AttachmentMetadataRecord* record = attachment_metadata.add_record();
*record->mutable_id() = attachment_id.GetProto();
ASSERT_FALSE(dir()->IsAttachmentLinked(attachment_id.GetProto()));
CreateEntryWithAttachmentMetadata(PREFERENCES, tag1, attachment_metadata);
// See that the directory knows it's linked.
ASSERT_TRUE(dir()->IsAttachmentLinked(attachment_id.GetProto()));
// Add a second entry referencing the same attachment.
std::string tag2("some other tag");
CreateEntryWithAttachmentMetadata(PREFERENCES, tag2, attachment_metadata);
// See that the directory knows it's still linked.
ASSERT_TRUE(dir()->IsAttachmentLinked(attachment_id.GetProto()));
// Tombstone the first entry.
ReplaceWithTombstone(PREFERENCES, tag1);
// See that the attachment is still considered linked because the entry hasn't
// been purged from the Directory.
ASSERT_TRUE(dir()->IsAttachmentLinked(attachment_id.GetProto()));
// Save changes and see that the entry is truly gone.
ASSERT_TRUE(dir()->SaveChanges());
ASSERT_EQ(LookupEntryByClientTag(PREFERENCES, tag1),
WriteNode::INIT_FAILED_ENTRY_NOT_GOOD);
// However, the attachment is still linked.
ASSERT_TRUE(dir()->IsAttachmentLinked(attachment_id.GetProto()));
// Save, destroy, and recreate the directory. See that it's still linked.
ASSERT_TRUE(ReloadDir());
ASSERT_TRUE(dir()->IsAttachmentLinked(attachment_id.GetProto()));
// Tombstone the second entry, save changes, see that it's truly gone.
ReplaceWithTombstone(PREFERENCES, tag2);
ASSERT_TRUE(dir()->SaveChanges());
ASSERT_EQ(LookupEntryByClientTag(PREFERENCES, tag2),
WriteNode::INIT_FAILED_ENTRY_NOT_GOOD);
// Finally, the attachment is no longer linked.
ASSERT_FALSE(dir()->IsAttachmentLinked(attachment_id.GetProto()));
}
// This tests directory integrity in the case of creating a new unique node
// with client tag matching that of an existing unapplied node with server only
// data. See crbug.com/505761.
TEST_F(SyncApiTest, WriteNode_UniqueByCreation_UndeleteCase) {
int64_t preferences_root = MakeTypeRoot(user_share(), PREFERENCES);
// Create a node with server only data.
int64_t item1 = 0;
{
syncable::WriteTransaction trans(FROM_HERE, syncable::UNITTEST,
user_share()->directory.get());
syncable::MutableEntry entry(&trans, syncable::CREATE_NEW_UPDATE_ITEM,
syncable::Id::CreateFromServerId("foo1"));
DCHECK(entry.good());
entry.PutServerVersion(10);
entry.PutIsUnappliedUpdate(true);
sync_pb::EntitySpecifics specifics;
AddDefaultFieldValue(PREFERENCES, &specifics);
entry.PutServerSpecifics(specifics);
const std::string hash = GenerateSyncableHash(PREFERENCES, "foo");
entry.PutUniqueClientTag(hash);
item1 = entry.GetMetahandle();
}
// Verify that the server-only item is invisible as a child of
// of |preferences_root| because at this point it should have the
// "deleted" flag set.
EXPECT_EQ(1, GetTotalNodeCount(user_share(), preferences_root));
// Create a client node with the same tag as the node above.
int64_t item2 = MakeNode(user_share(), PREFERENCES, "foo");
// Expect this to be the same directory entry as |item1|.
EXPECT_EQ(item1, item2);
// Expect it to be visible as a child of |preferences_root|.
EXPECT_EQ(2, GetTotalNodeCount(user_share(), preferences_root));
// Tombstone the new item
{
WriteTransaction trans(FROM_HERE, user_share());
WriteNode node(&trans);
EXPECT_EQ(BaseNode::INIT_OK, node.InitByIdLookup(item1));
node.Tombstone();
}
// Verify that it is gone from the index.
EXPECT_EQ(1, GetTotalNodeCount(user_share(), preferences_root));
}
// Tests that InitUniqueByCreation called for existing encrypted entry properly
// decrypts specifics and pust them in BaseNode::unencrypted_data_.
TEST_F(SyncApiTest, WriteNode_UniqueByCreation_EncryptedExistingEntry) {
KeyParams params = {"localhost", "username", "passphrase"};
{
ReadTransaction trans(FROM_HERE, user_share());
trans.GetCryptographer()->AddKey(params);
}
encryption_handler()->EnableEncryptEverything();
WriteTransaction trans(FROM_HERE, user_share());
ReadNode root_node(&trans);
root_node.InitByRootLookup();
{
WriteNode pref_node(&trans);
WriteNode::InitUniqueByCreationResult result =
pref_node.InitUniqueByCreation(PREFERENCES, root_node, "bar");
ASSERT_EQ(WriteNode::INIT_SUCCESS, result);
pref_node.SetTitle("bar");
sync_pb::EntitySpecifics entity_specifics;
entity_specifics.mutable_preference();
pref_node.SetEntitySpecifics(entity_specifics);
}
{
WriteNode pref_node(&trans);
WriteNode::InitUniqueByCreationResult result =
pref_node.InitUniqueByCreation(PREFERENCES, root_node, "bar");
ASSERT_EQ(WriteNode::INIT_SUCCESS, result);
// Call GetEntitySpecifics, ensure it doesn't DCHECK.
pref_node.GetEntitySpecifics();
}
}
// Tests that undeleting deleted password doesn't trigger any issues.
// See crbug/440430.
TEST_F(SyncApiTest, WriteNode_PasswordUniqueByCreationAfterDelete) {
KeyParams params = {"localhost", "username", "passphrase"};
{
ReadTransaction trans(FROM_HERE, user_share());
trans.GetCryptographer()->AddKey(params);
}
WriteTransaction trans(FROM_HERE, user_share());
ReadNode root_node(&trans);
root_node.InitByRootLookup();
// Create new password.
{
WriteNode password_node(&trans);
WriteNode::InitUniqueByCreationResult result =
password_node.InitUniqueByCreation(PASSWORDS, root_node, "foo");
ASSERT_EQ(WriteNode::INIT_SUCCESS, result);
sync_pb::PasswordSpecificsData password_specifics;
password_specifics.set_password_value("secret");
password_node.SetPasswordSpecifics(password_specifics);
}
// Delete password.
{
WriteNode password_node(&trans);
BaseNode::InitByLookupResult result =
password_node.InitByClientTagLookup(PASSWORDS, "foo");
ASSERT_EQ(BaseNode::INIT_OK, result);
password_node.Tombstone();
}
// Create password again triggering undeletion.
{
WriteNode password_node(&trans);
WriteNode::InitUniqueByCreationResult result =
password_node.InitUniqueByCreation(PASSWORDS, root_node, "foo");
ASSERT_EQ(WriteNode::INIT_SUCCESS, result);
}
}
namespace {
class TestHttpPostProviderInterface : public HttpPostProviderInterface {
public:
~TestHttpPostProviderInterface() override {}
void SetExtraRequestHeaders(const char* headers) override {}
void SetURL(const char* url, int port) override {}
void SetPostPayload(const char* content_type,
int content_length,
const char* content) override {}
bool MakeSynchronousPost(int* error_code, int* response_code) override {
return false;
}
int GetResponseContentLength() const override { return 0; }
const char* GetResponseContent() const override { return ""; }
const std::string GetResponseHeaderValue(
const std::string& name) const override {
return std::string();
}
void Abort() override {}
};
class TestHttpPostProviderFactory : public HttpPostProviderFactory {
public:
~TestHttpPostProviderFactory() override {}
void Init(const std::string& user_agent,
const BindToTrackerCallback& bind_to_tracker_callback) override {}
HttpPostProviderInterface* Create() override {
return new TestHttpPostProviderInterface();
}
void Destroy(HttpPostProviderInterface* http) override {
delete static_cast<TestHttpPostProviderInterface*>(http);
}
};
class SyncManagerObserverMock : public SyncManager::Observer {
public:
MOCK_METHOD1(OnSyncCycleCompleted, void(const SyncCycleSnapshot&)); // NOLINT
MOCK_METHOD4(OnInitializationComplete,
void(const WeakHandle<JsBackend>&,
const WeakHandle<DataTypeDebugInfoListener>&,
bool,
ModelTypeSet)); // NOLINT
MOCK_METHOD1(OnConnectionStatusChange, void(ConnectionStatus)); // NOLINT
MOCK_METHOD1(OnUpdatedToken, void(const std::string&)); // NOLINT
MOCK_METHOD1(OnActionableError, void(const SyncProtocolError&)); // NOLINT
MOCK_METHOD1(OnMigrationRequested, void(ModelTypeSet)); // NOLINT
MOCK_METHOD1(OnProtocolEvent, void(const ProtocolEvent&)); // NOLINT
};
class SyncEncryptionHandlerObserverMock
: public SyncEncryptionHandler::Observer {
public:
MOCK_METHOD2(OnPassphraseRequired,
void(PassphraseRequiredReason,
const sync_pb::EncryptedData&)); // NOLINT
MOCK_METHOD0(OnPassphraseAccepted, void()); // NOLINT
MOCK_METHOD2(OnBootstrapTokenUpdated,
void(const std::string&, BootstrapTokenType type)); // NOLINT
MOCK_METHOD2(OnEncryptedTypesChanged, void(ModelTypeSet, bool)); // NOLINT
MOCK_METHOD0(OnEncryptionComplete, void()); // NOLINT
MOCK_METHOD1(OnCryptographerStateChanged, void(Cryptographer*)); // NOLINT
MOCK_METHOD2(OnPassphraseTypeChanged,
void(PassphraseType,
base::Time)); // NOLINT
MOCK_METHOD1(OnLocalSetPassphraseEncryption,
void(const SyncEncryptionHandler::NigoriState&)); // NOLINT
};
} // namespace
class SyncManagerTest : public testing::Test,
public SyncManager::ChangeDelegate {
protected:
enum NigoriStatus { DONT_WRITE_NIGORI, WRITE_TO_NIGORI };
enum EncryptionStatus { UNINITIALIZED, DEFAULT_ENCRYPTION, FULL_ENCRYPTION };
SyncManagerTest() : sync_manager_("Test sync manager") {
switches_.encryption_method = EngineComponentsFactory::ENCRYPTION_KEYSTORE;
}
virtual ~SyncManagerTest() {}
virtual void DoSetUp(bool enable_local_sync_backend) {
ASSERT_TRUE(temp_dir_.CreateUniqueTempDir());
extensions_activity_ = new ExtensionsActivity();
SyncCredentials credentials;
credentials.account_id = "foo@bar.com";
credentials.email = "foo@bar.com";
credentials.sync_token = "sometoken";
OAuth2TokenService::ScopeSet scope_set;
scope_set.insert(GaiaConstants::kChromeSyncOAuth2Scope);
credentials.scope_set = scope_set;
sync_manager_.AddObserver(&manager_observer_);
EXPECT_CALL(manager_observer_, OnInitializationComplete(_, _, _, _))
.WillOnce(DoAll(SaveArg<0>(&js_backend_),
SaveArg<2>(&initialization_succeeded_)));
EXPECT_FALSE(js_backend_.IsInitialized());
std::vector<scoped_refptr<ModelSafeWorker>> workers;
ModelSafeRoutingInfo routing_info;
GetModelSafeRoutingInfo(&routing_info);
// This works only because all routing info types are GROUP_PASSIVE.
// If we had types in other groups, we would need additional workers
// to support them.
scoped_refptr<ModelSafeWorker> worker = new FakeModelWorker(GROUP_PASSIVE);
workers.push_back(worker);
SyncManager::InitArgs args;
args.database_location = temp_dir_.GetPath();
args.service_url = GURL("https://example.com/");
args.post_factory = std::unique_ptr<HttpPostProviderFactory>(
new TestHttpPostProviderFactory());
args.workers = workers;
args.extensions_activity = extensions_activity_.get(),
args.change_delegate = this;
if (!enable_local_sync_backend)
args.credentials = credentials;
args.invalidator_client_id = "fake_invalidator_client_id";
args.enable_local_sync_backend = enable_local_sync_backend;
args.local_sync_backend_folder = temp_dir_.GetPath();
args.engine_components_factory.reset(GetFactory());
args.encryptor = &encryptor_;
args.unrecoverable_error_handler =
MakeWeakHandle(mock_unrecoverable_error_handler_.GetWeakPtr());
args.cancelation_signal = &cancelation_signal_;
sync_manager_.Init(&args);
sync_manager_.GetEncryptionHandler()->AddObserver(&encryption_observer_);
EXPECT_TRUE(js_backend_.IsInitialized());
EXPECT_EQ(EngineComponentsFactory::STORAGE_ON_DISK, storage_used_);
if (initialization_succeeded_) {
for (ModelSafeRoutingInfo::iterator i = routing_info.begin();
i != routing_info.end(); ++i) {
type_roots_[i->first] =
MakeTypeRoot(sync_manager_.GetUserShare(), i->first);
}
}
PumpLoop();
}
// Test implementation.
void SetUp() { DoSetUp(false); }
void TearDown() {
sync_manager_.RemoveObserver(&manager_observer_);
sync_manager_.ShutdownOnSyncThread(STOP_SYNC);
PumpLoop();
}
void GetModelSafeRoutingInfo(ModelSafeRoutingInfo* out) {
(*out)[NIGORI] = GROUP_PASSIVE;
(*out)[DEVICE_INFO] = GROUP_PASSIVE;
(*out)[EXPERIMENTS] = GROUP_PASSIVE;
(*out)[BOOKMARKS] = GROUP_PASSIVE;
(*out)[THEMES] = GROUP_PASSIVE;
(*out)[SESSIONS] = GROUP_PASSIVE;
(*out)[PASSWORDS] = GROUP_PASSIVE;
(*out)[PREFERENCES] = GROUP_PASSIVE;
(*out)[PRIORITY_PREFERENCES] = GROUP_PASSIVE;
(*out)[ARTICLES] = GROUP_PASSIVE;
}
ModelTypeSet GetEnabledTypes() {
ModelSafeRoutingInfo routing_info;
GetModelSafeRoutingInfo(&routing_info);
return GetRoutingInfoTypes(routing_info);
}
void OnChangesApplied(ModelType model_type,
int64_t model_version,
const BaseTransaction* trans,
const ImmutableChangeRecordList& changes) override {}
void OnChangesComplete(ModelType model_type) override {}
// Helper methods.
bool SetUpEncryption(NigoriStatus nigori_status,
EncryptionStatus encryption_status) {
UserShare* share = sync_manager_.GetUserShare();
// We need to create the nigori node as if it were an applied server update.
int64_t nigori_id = GetIdForDataType(NIGORI);
if (nigori_id == kInvalidId)
return false;
// Set the nigori cryptographer information.
if (encryption_status == FULL_ENCRYPTION)
sync_manager_.GetEncryptionHandler()->EnableEncryptEverything();
WriteTransaction trans(FROM_HERE, share);
Cryptographer* cryptographer = trans.GetCryptographer();
if (!cryptographer)
return false;
if (encryption_status != UNINITIALIZED) {
KeyParams params = {"localhost", "dummy", "foobar"};
cryptographer->AddKey(params);
} else {
DCHECK_NE(nigori_status, WRITE_TO_NIGORI);
}
if (nigori_status == WRITE_TO_NIGORI) {
sync_pb::NigoriSpecifics nigori;
cryptographer->GetKeys(nigori.mutable_encryption_keybag());
share->directory->GetNigoriHandler()->UpdateNigoriFromEncryptedTypes(
&nigori, trans.GetWrappedTrans());
WriteNode node(&trans);
EXPECT_EQ(BaseNode::INIT_OK, node.InitByIdLookup(nigori_id));
node.SetNigoriSpecifics(nigori);
}
return cryptographer->is_ready();
}
int64_t GetIdForDataType(ModelType type) {
if (type_roots_.count(type) == 0)
return 0;
return type_roots_[type];
}
void PumpLoop() { base::RunLoop().RunUntilIdle(); }
void SetJsEventHandler(const WeakHandle<JsEventHandler>& event_handler) {
js_backend_.Call(FROM_HERE, &JsBackend::SetJsEventHandler, event_handler);
PumpLoop();
}
// Looks up an entry by client tag and resets IS_UNSYNCED value to false.
// Returns true if entry was previously unsynced, false if IS_UNSYNCED was
// already false.
bool ResetUnsyncedEntry(ModelType type, const std::string& client_tag) {
UserShare* share = sync_manager_.GetUserShare();
syncable::WriteTransaction trans(FROM_HERE, syncable::UNITTEST,
share->directory.get());
const std::string hash = GenerateSyncableHash(type, client_tag);
syncable::MutableEntry entry(&trans, syncable::GET_BY_CLIENT_TAG, hash);
EXPECT_TRUE(entry.good());
if (!entry.GetIsUnsynced())
return false;
entry.PutIsUnsynced(false);
return true;
}
virtual EngineComponentsFactory* GetFactory() {
return new TestEngineComponentsFactory(
GetSwitches(), EngineComponentsFactory::STORAGE_IN_MEMORY,
&storage_used_);
}
// Returns true if we are currently encrypting all sync data. May
// be called on any thread.
bool IsEncryptEverythingEnabledForTest() {
return sync_manager_.GetEncryptionHandler()->IsEncryptEverythingEnabled();
}
// Gets the set of encrypted types from the cryptographer
// Note: opens a transaction. May be called from any thread.
ModelTypeSet GetEncryptedTypes() {
ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
return GetEncryptedTypesWithTrans(&trans);
}
ModelTypeSet GetEncryptedTypesWithTrans(BaseTransaction* trans) {
return trans->GetDirectory()->GetNigoriHandler()->GetEncryptedTypes(
trans->GetWrappedTrans());
}
PassphraseType GetPassphraseType() {
ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
return GetPassphraseTypeWithTrans(&trans);
}
PassphraseType GetPassphraseTypeWithTrans(BaseTransaction* trans) {
return trans->GetDirectory()->GetNigoriHandler()->GetPassphraseType(
trans->GetWrappedTrans());
}
void SimulateInvalidatorEnabledForTest(bool is_enabled) {
DCHECK(sync_manager_.thread_checker_.CalledOnValidThread());
sync_manager_.SetInvalidatorEnabled(is_enabled);
}
void SetProgressMarkerForType(ModelType type, bool set) {
if (set) {
sync_pb::DataTypeProgressMarker marker;
marker.set_token("token");
marker.set_data_type_id(GetSpecificsFieldNumberFromModelType(type));
sync_manager_.directory()->SetDownloadProgress(type, marker);
} else {
sync_pb::DataTypeProgressMarker marker;
sync_manager_.directory()->SetDownloadProgress(type, marker);
}
}
EngineComponentsFactory::Switches GetSwitches() const { return switches_; }
void ExpectPassphraseAcceptance() {
EXPECT_CALL(encryption_observer_, OnPassphraseAccepted());
EXPECT_CALL(encryption_observer_, OnEncryptionComplete());
EXPECT_CALL(encryption_observer_, OnCryptographerStateChanged(_));
}
void SetImplicitPassphraseAndCheck(const std::string& passphrase) {
sync_manager_.GetEncryptionHandler()->SetEncryptionPassphrase(passphrase,
false);
EXPECT_EQ(PassphraseType::IMPLICIT_PASSPHRASE, GetPassphraseType());
}
void SetCustomPassphraseAndCheck(const std::string& passphrase) {
EXPECT_CALL(encryption_observer_,
OnPassphraseTypeChanged(PassphraseType::CUSTOM_PASSPHRASE, _));
sync_manager_.GetEncryptionHandler()->SetEncryptionPassphrase(passphrase,
true);
EXPECT_EQ(PassphraseType::CUSTOM_PASSPHRASE, GetPassphraseType());
}
bool HasUnrecoverableError() {
return mock_unrecoverable_error_handler_.invocation_count() > 0;
}
private:
// Needed by |sync_manager_|.
base::MessageLoop message_loop_;
// Needed by |sync_manager_|.
base::ScopedTempDir temp_dir_;
// Sync Id's for the roots of the enabled datatypes.
std::map<ModelType, int64_t> type_roots_;
scoped_refptr<ExtensionsActivity> extensions_activity_;
protected:
FakeEncryptor encryptor_;
SyncManagerImpl sync_manager_;
CancelationSignal cancelation_signal_;
WeakHandle<JsBackend> js_backend_;
bool initialization_succeeded_;
StrictMock<SyncManagerObserverMock> manager_observer_;
StrictMock<SyncEncryptionHandlerObserverMock> encryption_observer_;
EngineComponentsFactory::Switches switches_;
EngineComponentsFactory::StorageOption storage_used_;
MockUnrecoverableErrorHandler mock_unrecoverable_error_handler_;
};
TEST_F(SyncManagerTest, RefreshEncryptionReady) {
EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI, DEFAULT_ENCRYPTION));
EXPECT_CALL(encryption_observer_, OnEncryptionComplete());
EXPECT_CALL(encryption_observer_, OnCryptographerStateChanged(_));
EXPECT_CALL(encryption_observer_, OnEncryptedTypesChanged(_, false));
sync_manager_.GetEncryptionHandler()->Init();
PumpLoop();
const ModelTypeSet encrypted_types = GetEncryptedTypes();
EXPECT_TRUE(encrypted_types.Has(PASSWORDS));
EXPECT_FALSE(IsEncryptEverythingEnabledForTest());
{
ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
ReadNode node(&trans);
EXPECT_EQ(BaseNode::INIT_OK, node.InitByIdLookup(GetIdForDataType(NIGORI)));
sync_pb::NigoriSpecifics nigori = node.GetNigoriSpecifics();
EXPECT_TRUE(nigori.has_encryption_keybag());
Cryptographer* cryptographer = trans.GetCryptographer();
EXPECT_TRUE(cryptographer->is_ready());
EXPECT_TRUE(cryptographer->CanDecrypt(nigori.encryption_keybag()));
}
}
// Attempt to refresh encryption when nigori not downloaded.
TEST_F(SyncManagerTest, RefreshEncryptionNotReady) {
// Don't set up encryption (no nigori node created).
// Should fail. Triggers an OnPassphraseRequired because the cryptographer
// is not ready.
EXPECT_CALL(encryption_observer_, OnPassphraseRequired(_, _)).Times(1);
EXPECT_CALL(encryption_observer_, OnCryptographerStateChanged(_));
EXPECT_CALL(encryption_observer_, OnEncryptedTypesChanged(_, false));
sync_manager_.GetEncryptionHandler()->Init();
PumpLoop();
const ModelTypeSet encrypted_types = GetEncryptedTypes();
EXPECT_TRUE(encrypted_types.Has(PASSWORDS)); // Hardcoded.
EXPECT_FALSE(IsEncryptEverythingEnabledForTest());
}
// Attempt to refresh encryption when nigori is empty.
TEST_F(SyncManagerTest, RefreshEncryptionEmptyNigori) {
EXPECT_TRUE(SetUpEncryption(DONT_WRITE_NIGORI, DEFAULT_ENCRYPTION));
EXPECT_CALL(encryption_observer_, OnEncryptionComplete()).Times(1);
EXPECT_CALL(encryption_observer_, OnCryptographerStateChanged(_));
EXPECT_CALL(encryption_observer_, OnEncryptedTypesChanged(_, false));
// Should write to nigori.
sync_manager_.GetEncryptionHandler()->Init();
PumpLoop();
const ModelTypeSet encrypted_types = GetEncryptedTypes();
EXPECT_TRUE(encrypted_types.Has(PASSWORDS)); // Hardcoded.
EXPECT_FALSE(IsEncryptEverythingEnabledForTest());
{
ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
ReadNode node(&trans);
EXPECT_EQ(BaseNode::INIT_OK, node.InitByIdLookup(GetIdForDataType(NIGORI)));
sync_pb::NigoriSpecifics nigori = node.GetNigoriSpecifics();
EXPECT_TRUE(nigori.has_encryption_keybag());
Cryptographer* cryptographer = trans.GetCryptographer();
EXPECT_TRUE(cryptographer->is_ready());
EXPECT_TRUE(cryptographer->CanDecrypt(nigori.encryption_keybag()));
}
}
TEST_F(SyncManagerTest, EncryptDataTypesWithNoData) {
EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI, DEFAULT_ENCRYPTION));
EXPECT_CALL(
encryption_observer_,
OnEncryptedTypesChanged(HasModelTypes(EncryptableUserTypes()), true));
EXPECT_CALL(encryption_observer_, OnEncryptionComplete());
sync_manager_.GetEncryptionHandler()->EnableEncryptEverything();
EXPECT_TRUE(IsEncryptEverythingEnabledForTest());
}
TEST_F(SyncManagerTest, EncryptDataTypesWithData) {
size_t batch_size = 5;
EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI, DEFAULT_ENCRYPTION));
// Create some unencrypted unsynced data.
int64_t folder = MakeFolderWithParent(sync_manager_.GetUserShare(), BOOKMARKS,
GetIdForDataType(BOOKMARKS), nullptr);
// First batch_size nodes are children of folder.
size_t i;
for (i = 0; i < batch_size; ++i) {
MakeBookmarkWithParent(sync_manager_.GetUserShare(), folder, nullptr);
}
// Next batch_size nodes are a different type and on their own.
for (; i < 2 * batch_size; ++i) {
MakeNodeWithRoot(sync_manager_.GetUserShare(), SESSIONS,
base::StringPrintf("%" PRIuS "", i));
}
// Last batch_size nodes are a third type that will not need encryption.
for (; i < 3 * batch_size; ++i) {
MakeNodeWithRoot(sync_manager_.GetUserShare(), THEMES,
base::StringPrintf("%" PRIuS "", i));
}
{
ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
EXPECT_EQ(SyncEncryptionHandler::SensitiveTypes(),
GetEncryptedTypesWithTrans(&trans));
EXPECT_TRUE(syncable::VerifyDataTypeEncryptionForTest(
trans.GetWrappedTrans(), BOOKMARKS, false /* not encrypted */));
EXPECT_TRUE(syncable::VerifyDataTypeEncryptionForTest(
trans.GetWrappedTrans(), SESSIONS, false /* not encrypted */));
EXPECT_TRUE(syncable::VerifyDataTypeEncryptionForTest(
trans.GetWrappedTrans(), THEMES, false /* not encrypted */));
}
EXPECT_CALL(
encryption_observer_,
OnEncryptedTypesChanged(HasModelTypes(EncryptableUserTypes()), true));
EXPECT_CALL(encryption_observer_, OnEncryptionComplete());
sync_manager_.GetEncryptionHandler()->EnableEncryptEverything();
EXPECT_TRUE(IsEncryptEverythingEnabledForTest());
{
ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
EXPECT_EQ(EncryptableUserTypes(), GetEncryptedTypesWithTrans(&trans));
EXPECT_TRUE(syncable::VerifyDataTypeEncryptionForTest(
trans.GetWrappedTrans(), BOOKMARKS, true /* is encrypted */));
EXPECT_TRUE(syncable::VerifyDataTypeEncryptionForTest(
trans.GetWrappedTrans(), SESSIONS, true /* is encrypted */));
EXPECT_TRUE(syncable::VerifyDataTypeEncryptionForTest(
trans.GetWrappedTrans(), THEMES, true /* is encrypted */));
}
// Trigger's a ReEncryptEverything with new passphrase.
testing::Mock::VerifyAndClearExpectations(&encryption_observer_);
EXPECT_CALL(encryption_observer_,
OnBootstrapTokenUpdated(_, PASSPHRASE_BOOTSTRAP_TOKEN));
ExpectPassphraseAcceptance();
SetCustomPassphraseAndCheck("new_passphrase");
EXPECT_TRUE(IsEncryptEverythingEnabledForTest());
{
ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
EXPECT_EQ(EncryptableUserTypes(), GetEncryptedTypesWithTrans(&trans));
EXPECT_TRUE(syncable::VerifyDataTypeEncryptionForTest(
trans.GetWrappedTrans(), BOOKMARKS, true /* is encrypted */));
EXPECT_TRUE(syncable::VerifyDataTypeEncryptionForTest(
trans.GetWrappedTrans(), SESSIONS, true /* is encrypted */));
EXPECT_TRUE(syncable::VerifyDataTypeEncryptionForTest(
trans.GetWrappedTrans(), THEMES, true /* is encrypted */));
}
// Calling EncryptDataTypes with an empty encrypted types should not trigger
// a reencryption and should just notify immediately.
testing::Mock::VerifyAndClearExpectations(&encryption_observer_);
EXPECT_CALL(encryption_observer_,
OnBootstrapTokenUpdated(_, PASSPHRASE_BOOTSTRAP_TOKEN))
.Times(0);
EXPECT_CALL(encryption_observer_, OnPassphraseAccepted()).Times(0);
EXPECT_CALL(encryption_observer_, OnEncryptionComplete()).Times(0);
sync_manager_.GetEncryptionHandler()->EnableEncryptEverything();
}
// Test that when there are no pending keys and the cryptographer is not
// initialized, we add a key based on the current GAIA password.
// (case 1 in SyncManager::SyncInternal::SetEncryptionPassphrase)
TEST_F(SyncManagerTest, SetInitialGaiaPass) {
EXPECT_FALSE(SetUpEncryption(DONT_WRITE_NIGORI, UNINITIALIZED));
EXPECT_CALL(encryption_observer_,
OnBootstrapTokenUpdated(_, PASSPHRASE_BOOTSTRAP_TOKEN));
ExpectPassphraseAcceptance();
SetImplicitPassphraseAndCheck("new_passphrase");
EXPECT_FALSE(IsEncryptEverythingEnabledForTest());
{
ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
ReadNode node(&trans);
EXPECT_EQ(BaseNode::INIT_OK, node.InitTypeRoot(NIGORI));
sync_pb::NigoriSpecifics nigori = node.GetNigoriSpecifics();
Cryptographer* cryptographer = trans.GetCryptographer();
EXPECT_TRUE(cryptographer->is_ready());
EXPECT_TRUE(cryptographer->CanDecrypt(nigori.encryption_keybag()));
}
}
// Test that when there are no pending keys and we have on the old GAIA
// password, we update and re-encrypt everything with the new GAIA password.
// (case 1 in SyncManager::SyncInternal::SetEncryptionPassphrase)
TEST_F(SyncManagerTest, UpdateGaiaPass) {
EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI, DEFAULT_ENCRYPTION));
Cryptographer verifier(&encryptor_);
{
ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
Cryptographer* cryptographer = trans.GetCryptographer();
std::string bootstrap_token;
cryptographer->GetBootstrapToken(&bootstrap_token);
verifier.Bootstrap(bootstrap_token);
}
EXPECT_CALL(encryption_observer_,
OnBootstrapTokenUpdated(_, PASSPHRASE_BOOTSTRAP_TOKEN));
ExpectPassphraseAcceptance();
SetImplicitPassphraseAndCheck("new_passphrase");
EXPECT_FALSE(IsEncryptEverythingEnabledForTest());
{
ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
Cryptographer* cryptographer = trans.GetCryptographer();
EXPECT_TRUE(cryptographer->is_ready());
// Verify the default key has changed.
sync_pb::EncryptedData encrypted;
cryptographer->GetKeys(&encrypted);
EXPECT_FALSE(verifier.CanDecrypt(encrypted));
}
}
// Sets a new explicit passphrase. This should update the bootstrap token
// and re-encrypt everything.
// (case 2 in SyncManager::SyncInternal::SetEncryptionPassphrase)
TEST_F(SyncManagerTest, SetPassphraseWithPassword) {
Cryptographer verifier(&encryptor_);
EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI, DEFAULT_ENCRYPTION));
{
WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
// Store the default (soon to be old) key.
Cryptographer* cryptographer = trans.GetCryptographer();
std::string bootstrap_token;
cryptographer->GetBootstrapToken(&bootstrap_token);
verifier.Bootstrap(bootstrap_token);
ReadNode root_node(&trans);
root_node.InitByRootLookup();
WriteNode password_node(&trans);
WriteNode::InitUniqueByCreationResult result =
password_node.InitUniqueByCreation(PASSWORDS, root_node, "foo");
EXPECT_EQ(WriteNode::INIT_SUCCESS, result);
sync_pb::PasswordSpecificsData data;
data.set_password_value("secret");
password_node.SetPasswordSpecifics(data);
}
EXPECT_CALL(encryption_observer_,
OnBootstrapTokenUpdated(_, PASSPHRASE_BOOTSTRAP_TOKEN));
ExpectPassphraseAcceptance();
SetCustomPassphraseAndCheck("new_passphrase");
EXPECT_FALSE(IsEncryptEverythingEnabledForTest());
{
ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
Cryptographer* cryptographer = trans.GetCryptographer();
EXPECT_TRUE(cryptographer->is_ready());
// Verify the default key has changed.
sync_pb::EncryptedData encrypted;
cryptographer->GetKeys(&encrypted);
EXPECT_FALSE(verifier.CanDecrypt(encrypted));
ReadNode password_node(&trans);
EXPECT_EQ(BaseNode::INIT_OK,
password_node.InitByClientTagLookup(PASSWORDS, "foo"));
const sync_pb::PasswordSpecificsData& data =
password_node.GetPasswordSpecifics();
EXPECT_EQ("secret", data.password_value());
}
}
// Manually set the pending keys in the cryptographer/nigori to reflect the data
// being encrypted with a new (unprovided) GAIA password, then supply the
// password.
// (case 7 in SyncManager::SyncInternal::SetDecryptionPassphrase)
TEST_F(SyncManagerTest, SupplyPendingGAIAPass) {
EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI, DEFAULT_ENCRYPTION));
Cryptographer other_cryptographer(&encryptor_);
{
WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
Cryptographer* cryptographer = trans.GetCryptographer();
std::string bootstrap_token;
cryptographer->GetBootstrapToken(&bootstrap_token);
other_cryptographer.Bootstrap(bootstrap_token);
// Now update the nigori to reflect the new keys, and update the
// cryptographer to have pending keys.
KeyParams params = {"localhost", "dummy", "passphrase2"};
other_cryptographer.AddKey(params);
WriteNode node(&trans);
EXPECT_EQ(BaseNode::INIT_OK, node.InitTypeRoot(NIGORI));
sync_pb::NigoriSpecifics nigori;
other_cryptographer.GetKeys(nigori.mutable_encryption_keybag());
cryptographer->SetPendingKeys(nigori.encryption_keybag());
EXPECT_TRUE(cryptographer->has_pending_keys());
node.SetNigoriSpecifics(nigori);
}
EXPECT_CALL(encryption_observer_,
OnBootstrapTokenUpdated(_, PASSPHRASE_BOOTSTRAP_TOKEN));
ExpectPassphraseAcceptance();
sync_manager_.GetEncryptionHandler()->SetDecryptionPassphrase("passphrase2");
EXPECT_EQ(PassphraseType::IMPLICIT_PASSPHRASE, GetPassphraseType());
EXPECT_FALSE(IsEncryptEverythingEnabledForTest());
{
ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
Cryptographer* cryptographer = trans.GetCryptographer();
EXPECT_TRUE(cryptographer->is_ready());
// Verify we're encrypting with the new key.
sync_pb::EncryptedData encrypted;
cryptographer->GetKeys(&encrypted);
EXPECT_TRUE(other_cryptographer.CanDecrypt(encrypted));
}
}
// Manually set the pending keys in the cryptographer/nigori to reflect the data
// being encrypted with an old (unprovided) GAIA password. Attempt to supply
// the current GAIA password and verify the bootstrap token is updated. Then
// supply the old GAIA password, and verify we re-encrypt all data with the
// new GAIA password.
// (cases 4 and 5 in SyncManager::SyncInternal::SetEncryptionPassphrase)
TEST_F(SyncManagerTest, SupplyPendingOldGAIAPass) {
EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI, DEFAULT_ENCRYPTION));
Cryptographer other_cryptographer(&encryptor_);
{
WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
Cryptographer* cryptographer = trans.GetCryptographer();
std::string bootstrap_token;
cryptographer->GetBootstrapToken(&bootstrap_token);
other_cryptographer.Bootstrap(bootstrap_token);
// Now update the nigori to reflect the new keys, and update the
// cryptographer to have pending keys.
KeyParams params = {"localhost", "dummy", "old_gaia"};
other_cryptographer.AddKey(params);
WriteNode node(&trans);
EXPECT_EQ(BaseNode::INIT_OK, node.InitTypeRoot(NIGORI));
sync_pb::NigoriSpecifics nigori;
other_cryptographer.GetKeys(nigori.mutable_encryption_keybag());
node.SetNigoriSpecifics(nigori);
cryptographer->SetPendingKeys(nigori.encryption_keybag());
// other_cryptographer now contains all encryption keys, and is encrypting
// with the newest gaia.
KeyParams new_params = {"localhost", "dummy", "new_gaia"};
other_cryptographer.AddKey(new_params);
}
// The bootstrap token should have been updated. Save it to ensure it's based
// on the new GAIA password.
std::string bootstrap_token;
EXPECT_CALL(encryption_observer_,
OnBootstrapTokenUpdated(_, PASSPHRASE_BOOTSTRAP_TOKEN))
.WillOnce(SaveArg<0>(&bootstrap_token));
EXPECT_CALL(encryption_observer_, OnPassphraseRequired(_, _));
EXPECT_CALL(encryption_observer_, OnCryptographerStateChanged(_));
SetImplicitPassphraseAndCheck("new_gaia");
EXPECT_FALSE(IsEncryptEverythingEnabledForTest());
testing::Mock::VerifyAndClearExpectations(&encryption_observer_);
{
ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
Cryptographer* cryptographer = trans.GetCryptographer();
EXPECT_TRUE(cryptographer->is_initialized());
EXPECT_FALSE(cryptographer->is_ready());
// Verify we're encrypting with the new key, even though we have pending
// keys.
sync_pb::EncryptedData encrypted;
other_cryptographer.GetKeys(&encrypted);
EXPECT_TRUE(cryptographer->CanDecrypt(encrypted));
}
EXPECT_CALL(encryption_observer_,
OnBootstrapTokenUpdated(_, PASSPHRASE_BOOTSTRAP_TOKEN));
ExpectPassphraseAcceptance();
SetImplicitPassphraseAndCheck("old_gaia");
{
ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
Cryptographer* cryptographer = trans.GetCryptographer();
EXPECT_TRUE(cryptographer->is_ready());
// Verify we're encrypting with the new key.
sync_pb::EncryptedData encrypted;
other_cryptographer.GetKeys(&encrypted);
EXPECT_TRUE(cryptographer->CanDecrypt(encrypted));
// Verify the saved bootstrap token is based on the new gaia password.
Cryptographer temp_cryptographer(&encryptor_);
temp_cryptographer.Bootstrap(bootstrap_token);
EXPECT_TRUE(temp_cryptographer.CanDecrypt(encrypted));
}
}
// Manually set the pending keys in the cryptographer/nigori to reflect the data
// being encrypted with an explicit (unprovided) passphrase, then supply the
// passphrase.
// (case 9 in SyncManager::SyncInternal::SetDecryptionPassphrase)
TEST_F(SyncManagerTest, SupplyPendingExplicitPass) {
EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI, DEFAULT_ENCRYPTION));
Cryptographer other_cryptographer(&encryptor_);
{
WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
Cryptographer* cryptographer = trans.GetCryptographer();
std::string bootstrap_token;
cryptographer->GetBootstrapToken(&bootstrap_token);
other_cryptographer.Bootstrap(bootstrap_token);
// Now update the nigori to reflect the new keys, and update the
// cryptographer to have pending keys.
KeyParams params = {"localhost", "dummy", "explicit"};
other_cryptographer.AddKey(params);
WriteNode node(&trans);
EXPECT_EQ(BaseNode::INIT_OK, node.InitTypeRoot(NIGORI));
sync_pb::NigoriSpecifics nigori;
other_cryptographer.GetKeys(nigori.mutable_encryption_keybag());
cryptographer->SetPendingKeys(nigori.encryption_keybag());
EXPECT_TRUE(cryptographer->has_pending_keys());
nigori.set_keybag_is_frozen(true);
node.SetNigoriSpecifics(nigori);
}
EXPECT_CALL(encryption_observer_, OnCryptographerStateChanged(_));
EXPECT_CALL(encryption_observer_,
OnPassphraseTypeChanged(PassphraseType::CUSTOM_PASSPHRASE, _));
EXPECT_CALL(encryption_observer_, OnPassphraseRequired(_, _));
EXPECT_CALL(encryption_observer_, OnEncryptedTypesChanged(_, false));
sync_manager_.GetEncryptionHandler()->Init();
EXPECT_CALL(encryption_observer_,
OnBootstrapTokenUpdated(_, PASSPHRASE_BOOTSTRAP_TOKEN));
ExpectPassphraseAcceptance();
sync_manager_.GetEncryptionHandler()->SetDecryptionPassphrase("explicit");
EXPECT_EQ(PassphraseType::CUSTOM_PASSPHRASE, GetPassphraseType());
EXPECT_FALSE(IsEncryptEverythingEnabledForTest());
{
ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
Cryptographer* cryptographer = trans.GetCryptographer();
EXPECT_TRUE(cryptographer->is_ready());
// Verify we're encrypting with the new key.
sync_pb::EncryptedData encrypted;
cryptographer->GetKeys(&encrypted);
EXPECT_TRUE(other_cryptographer.CanDecrypt(encrypted));
}
}
// Manually set the pending keys in the cryptographer/nigori to reflect the data
// being encrypted with a new (unprovided) GAIA password, then supply the
// password as a user-provided password.
// This is the android case 7/8.
TEST_F(SyncManagerTest, SupplyPendingGAIAPassUserProvided) {
EXPECT_FALSE(SetUpEncryption(DONT_WRITE_NIGORI, UNINITIALIZED));
Cryptographer other_cryptographer(&encryptor_);
{
WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
Cryptographer* cryptographer = trans.GetCryptographer();
// Now update the nigori to reflect the new keys, and update the
// cryptographer to have pending keys.
KeyParams params = {"localhost", "dummy", "passphrase"};
other_cryptographer.AddKey(params);
WriteNode node(&trans);
EXPECT_EQ(BaseNode::INIT_OK, node.InitTypeRoot(NIGORI));
sync_pb::NigoriSpecifics nigori;
other_cryptographer.GetKeys(nigori.mutable_encryption_keybag());
node.SetNigoriSpecifics(nigori);
cryptographer->SetPendingKeys(nigori.encryption_keybag());
EXPECT_FALSE(cryptographer->is_ready());
}
EXPECT_CALL(encryption_observer_,
OnBootstrapTokenUpdated(_, PASSPHRASE_BOOTSTRAP_TOKEN));
ExpectPassphraseAcceptance();
SetImplicitPassphraseAndCheck("passphrase");
EXPECT_FALSE(IsEncryptEverythingEnabledForTest());
{
ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
Cryptographer* cryptographer = trans.GetCryptographer();
EXPECT_TRUE(cryptographer->is_ready());
}
}
TEST_F(SyncManagerTest, SetPassphraseWithEmptyPasswordNode) {
EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI, DEFAULT_ENCRYPTION));
int64_t node_id = 0;
std::string tag = "foo";
{
WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
ReadNode root_node(&trans);
root_node.InitByRootLookup();
WriteNode password_node(&trans);
WriteNode::InitUniqueByCreationResult result =
password_node.InitUniqueByCreation(PASSWORDS, root_node, tag);
EXPECT_EQ(WriteNode::INIT_SUCCESS, result);
node_id = password_node.GetId();
}
EXPECT_CALL(encryption_observer_,
OnBootstrapTokenUpdated(_, PASSPHRASE_BOOTSTRAP_TOKEN));
ExpectPassphraseAcceptance();
SetCustomPassphraseAndCheck("new_passphrase");
EXPECT_FALSE(IsEncryptEverythingEnabledForTest());
{
ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
ReadNode password_node(&trans);
EXPECT_EQ(BaseNode::INIT_FAILED_DECRYPT_IF_NECESSARY,
password_node.InitByClientTagLookup(PASSWORDS, tag));
}
{
ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
ReadNode password_node(&trans);
EXPECT_EQ(BaseNode::INIT_FAILED_DECRYPT_IF_NECESSARY,
password_node.InitByIdLookup(node_id));
}
}
// Friended by WriteNode, so can't be in an anonymouse namespace.
TEST_F(SyncManagerTest, EncryptBookmarksWithLegacyData) {
EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI, DEFAULT_ENCRYPTION));
std::string title;
SyncAPINameToServerName("Google", &title);
std::string url = "http://www.google.com";
std::string raw_title2 = ".."; // An invalid cosmo title.
std::string title2;
SyncAPINameToServerName(raw_title2, &title2);
std::string url2 = "http://www.bla.com";
// Create a bookmark using the legacy format.
int64_t node_id1 =
MakeNodeWithRoot(sync_manager_.GetUserShare(), BOOKMARKS, "testtag");
int64_t node_id2 =
MakeNodeWithRoot(sync_manager_.GetUserShare(), BOOKMARKS, "testtag2");
{
WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
WriteNode node(&trans);
EXPECT_EQ(BaseNode::INIT_OK, node.InitByIdLookup(node_id1));
sync_pb::EntitySpecifics entity_specifics;
entity_specifics.mutable_bookmark()->set_url(url);
node.SetEntitySpecifics(entity_specifics);
// Set the old style title.
syncable::MutableEntry* node_entry = node.entry_;
node_entry->PutNonUniqueName(title);
WriteNode node2(&trans);
EXPECT_EQ(BaseNode::INIT_OK, node2.InitByIdLookup(node_id2));
sync_pb::EntitySpecifics entity_specifics2;
entity_specifics2.mutable_bookmark()->set_url(url2);
node2.SetEntitySpecifics(entity_specifics2);
// Set the old style title.
syncable::MutableEntry* node_entry2 = node2.entry_;
node_entry2->PutNonUniqueName(title2);
}
{
ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
ReadNode node(&trans);
EXPECT_EQ(BaseNode::INIT_OK, node.InitByIdLookup(node_id1));
EXPECT_EQ(BOOKMARKS, node.GetModelType());
EXPECT_EQ(title, node.GetTitle());
EXPECT_EQ(title, node.GetBookmarkSpecifics().title());
EXPECT_EQ(url, node.GetBookmarkSpecifics().url());
ReadNode node2(&trans);
EXPECT_EQ(BaseNode::INIT_OK, node2.InitByIdLookup(node_id2));
EXPECT_EQ(BOOKMARKS, node2.GetModelType());
// We should de-canonicalize the title in GetTitle(), but the title in the
// specifics should be stored in the server legal form.
EXPECT_EQ(raw_title2, node2.GetTitle());
EXPECT_EQ(title2, node2.GetBookmarkSpecifics().title());
EXPECT_EQ(url2, node2.GetBookmarkSpecifics().url());
}
{
ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
EXPECT_TRUE(syncable::VerifyDataTypeEncryptionForTest(
trans.GetWrappedTrans(), BOOKMARKS, false /* not encrypted */));
}
EXPECT_CALL(
encryption_observer_,
OnEncryptedTypesChanged(HasModelTypes(EncryptableUserTypes()), true));
EXPECT_CALL(encryption_observer_, OnEncryptionComplete());
sync_manager_.GetEncryptionHandler()->EnableEncryptEverything();
EXPECT_TRUE(IsEncryptEverythingEnabledForTest());
{
ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
EXPECT_EQ(EncryptableUserTypes(), GetEncryptedTypesWithTrans(&trans));
EXPECT_TRUE(syncable::VerifyDataTypeEncryptionForTest(
trans.GetWrappedTrans(), BOOKMARKS, true /* is encrypted */));
ReadNode node(&trans);
EXPECT_EQ(BaseNode::INIT_OK, node.InitByIdLookup(node_id1));
EXPECT_EQ(BOOKMARKS, node.GetModelType());
EXPECT_EQ(title, node.GetTitle());
EXPECT_EQ(title, node.GetBookmarkSpecifics().title());
EXPECT_EQ(url, node.GetBookmarkSpecifics().url());
ReadNode node2(&trans);
EXPECT_EQ(BaseNode::INIT_OK, node2.InitByIdLookup(node_id2));
EXPECT_EQ(BOOKMARKS, node2.GetModelType());
// We should de-canonicalize the title in GetTitle(), but the title in the
// specifics should be stored in the server legal form.
EXPECT_EQ(raw_title2, node2.GetTitle());
EXPECT_EQ(title2, node2.GetBookmarkSpecifics().title());
EXPECT_EQ(url2, node2.GetBookmarkSpecifics().url());
}
}
// Create a bookmark and set the title/url, then verify the data was properly
// set. This replicates the unique way bookmarks have of creating sync nodes.
// See BookmarkChangeProcessor::PlaceSyncNode(..).
TEST_F(SyncManagerTest, CreateLocalBookmark) {
std::string title = "title";
std::string url = "url";
{
WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
ReadNode bookmark_root(&trans);
ASSERT_EQ(BaseNode::INIT_OK, bookmark_root.InitTypeRoot(BOOKMARKS));
WriteNode node(&trans);
ASSERT_TRUE(node.InitBookmarkByCreation(bookmark_root, nullptr));
node.SetIsFolder(false);
node.SetTitle(title);
sync_pb::BookmarkSpecifics bookmark_specifics(node.GetBookmarkSpecifics());
bookmark_specifics.set_url(url);
node.SetBookmarkSpecifics(bookmark_specifics);
}
{
ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
ReadNode bookmark_root(&trans);
ASSERT_EQ(BaseNode::INIT_OK, bookmark_root.InitTypeRoot(BOOKMARKS));
int64_t child_id = bookmark_root.GetFirstChildId();
ReadNode node(&trans);
ASSERT_EQ(BaseNode::INIT_OK, node.InitByIdLookup(child_id));
EXPECT_FALSE(node.GetIsFolder());
EXPECT_EQ(title, node.GetTitle());
EXPECT_EQ(url, node.GetBookmarkSpecifics().url());
}
}
// Verifies WriteNode::UpdateEntryWithEncryption does not make unnecessary
// changes.
TEST_F(SyncManagerTest, UpdateEntryWithEncryption) {
std::string client_tag = "title";
sync_pb::EntitySpecifics entity_specifics;
entity_specifics.mutable_bookmark()->set_url("url");
entity_specifics.mutable_bookmark()->set_title("title");
MakeServerNode(sync_manager_.GetUserShare(), BOOKMARKS, client_tag,
GenerateSyncableHash(BOOKMARKS, client_tag), entity_specifics);
// New node shouldn't start off unsynced.
EXPECT_FALSE(ResetUnsyncedEntry(BOOKMARKS, client_tag));
// Manually change to the same data. Should not set is_unsynced.
{
WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
WriteNode node(&trans);
EXPECT_EQ(BaseNode::INIT_OK,
node.InitByClientTagLookup(BOOKMARKS, client_tag));
node.SetEntitySpecifics(entity_specifics);
}
EXPECT_FALSE(ResetUnsyncedEntry(BOOKMARKS, client_tag));
// Encrypt the datatatype, should set is_unsynced.
EXPECT_CALL(
encryption_observer_,
OnEncryptedTypesChanged(HasModelTypes(EncryptableUserTypes()), true));
EXPECT_CALL(encryption_observer_, OnEncryptionComplete());
EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI, FULL_ENCRYPTION));
EXPECT_CALL(encryption_observer_, OnCryptographerStateChanged(_));
EXPECT_CALL(encryption_observer_, OnEncryptedTypesChanged(_, true));
sync_manager_.GetEncryptionHandler()->Init();
PumpLoop();
{
ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
ReadNode node(&trans);
EXPECT_EQ(BaseNode::INIT_OK,
node.InitByClientTagLookup(BOOKMARKS, client_tag));
const syncable::Entry* node_entry = node.GetEntry();
const sync_pb::EntitySpecifics& specifics = node_entry->GetSpecifics();
EXPECT_TRUE(specifics.has_encrypted());
EXPECT_EQ(kEncryptedString, node_entry->GetNonUniqueName());
Cryptographer* cryptographer = trans.GetCryptographer();
EXPECT_TRUE(cryptographer->is_ready());
EXPECT_TRUE(
cryptographer->CanDecryptUsingDefaultKey(specifics.encrypted()));
}
EXPECT_TRUE(ResetUnsyncedEntry(BOOKMARKS, client_tag));
// Set a new passphrase. Should set is_unsynced.
testing::Mock::VerifyAndClearExpectations(&encryption_observer_);
EXPECT_CALL(encryption_observer_,
OnBootstrapTokenUpdated(_, PASSPHRASE_BOOTSTRAP_TOKEN));
ExpectPassphraseAcceptance();
SetCustomPassphraseAndCheck("new_passphrase");
{
ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
ReadNode node(&trans);
EXPECT_EQ(BaseNode::INIT_OK,
node.InitByClientTagLookup(BOOKMARKS, client_tag));
const syncable::Entry* node_entry = node.GetEntry();
const sync_pb::EntitySpecifics& specifics = node_entry->GetSpecifics();
EXPECT_TRUE(specifics.has_encrypted());
EXPECT_EQ(kEncryptedString, node_entry->GetNonUniqueName());
Cryptographer* cryptographer = trans.GetCryptographer();
EXPECT_TRUE(cryptographer->is_ready());
EXPECT_TRUE(
cryptographer->CanDecryptUsingDefaultKey(specifics.encrypted()));
}
EXPECT_TRUE(ResetUnsyncedEntry(BOOKMARKS, client_tag));
// Force a re-encrypt everything. Should not set is_unsynced.
testing::Mock::VerifyAndClearExpectations(&encryption_observer_);
EXPECT_CALL(encryption_observer_, OnEncryptionComplete());
EXPECT_CALL(encryption_observer_, OnCryptographerStateChanged(_));
EXPECT_CALL(encryption_observer_, OnEncryptedTypesChanged(_, true));
sync_manager_.GetEncryptionHandler()->Init();
PumpLoop();
{
ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
ReadNode node(&trans);
EXPECT_EQ(BaseNode::INIT_OK,
node.InitByClientTagLookup(BOOKMARKS, client_tag));
const syncable::Entry* node_entry = node.GetEntry();
const sync_pb::EntitySpecifics& specifics = node_entry->GetSpecifics();
EXPECT_TRUE(specifics.has_encrypted());
EXPECT_EQ(kEncryptedString, node_entry->GetNonUniqueName());
Cryptographer* cryptographer = trans.GetCryptographer();
EXPECT_TRUE(
cryptographer->CanDecryptUsingDefaultKey(specifics.encrypted()));
}
EXPECT_FALSE(ResetUnsyncedEntry(BOOKMARKS, client_tag));
// Manually change to the same data. Should not set is_unsynced.
{
WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
WriteNode node(&trans);
EXPECT_EQ(BaseNode::INIT_OK,
node.InitByClientTagLookup(BOOKMARKS, client_tag));
node.SetEntitySpecifics(entity_specifics);
const syncable::Entry* node_entry = node.GetEntry();
const sync_pb::EntitySpecifics& specifics = node_entry->GetSpecifics();
EXPECT_TRUE(specifics.has_encrypted());
EXPECT_FALSE(node_entry->GetIsUnsynced());
EXPECT_EQ(kEncryptedString, node_entry->GetNonUniqueName());
Cryptographer* cryptographer = trans.GetCryptographer();
EXPECT_TRUE(
cryptographer->CanDecryptUsingDefaultKey(specifics.encrypted()));
}
EXPECT_FALSE(ResetUnsyncedEntry(BOOKMARKS, client_tag));
// Manually change to different data. Should set is_unsynced.
{
entity_specifics.mutable_bookmark()->set_url("url2");
entity_specifics.mutable_bookmark()->set_title("title2");
WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
WriteNode node(&trans);
EXPECT_EQ(BaseNode::INIT_OK,
node.InitByClientTagLookup(BOOKMARKS, client_tag));
node.SetEntitySpecifics(entity_specifics);
const syncable::Entry* node_entry = node.GetEntry();
const sync_pb::EntitySpecifics& specifics = node_entry->GetSpecifics();
EXPECT_TRUE(specifics.has_encrypted());
EXPECT_TRUE(node_entry->GetIsUnsynced());
EXPECT_EQ(kEncryptedString, node_entry->GetNonUniqueName());
Cryptographer* cryptographer = trans.GetCryptographer();
EXPECT_TRUE(
cryptographer->CanDecryptUsingDefaultKey(specifics.encrypted()));
}
}
// Passwords have their own handling for encryption. Verify it does not result
// in unnecessary writes via SetEntitySpecifics.
TEST_F(SyncManagerTest, UpdatePasswordSetEntitySpecificsNoChange) {
std::string client_tag = "title";
EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI, DEFAULT_ENCRYPTION));
sync_pb::EntitySpecifics entity_specifics;
{
ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
Cryptographer* cryptographer = trans.GetCryptographer();
sync_pb::PasswordSpecificsData data;
data.set_password_value("secret");
cryptographer->Encrypt(
data, entity_specifics.mutable_password()->mutable_encrypted());
}
MakeServerNode(sync_manager_.GetUserShare(), PASSWORDS, client_tag,
GenerateSyncableHash(PASSWORDS, client_tag), entity_specifics);
// New node shouldn't start off unsynced.
EXPECT_FALSE(ResetUnsyncedEntry(PASSWORDS, client_tag));
// Manually change to the same data via SetEntitySpecifics. Should not set
// is_unsynced.
{
WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
WriteNode node(&trans);
EXPECT_EQ(BaseNode::INIT_OK,
node.InitByClientTagLookup(PASSWORDS, client_tag));
node.SetEntitySpecifics(entity_specifics);
}
EXPECT_FALSE(ResetUnsyncedEntry(PASSWORDS, client_tag));
}
// Passwords have their own handling for encryption. Verify it does not result
// in unnecessary writes via SetPasswordSpecifics.
TEST_F(SyncManagerTest, UpdatePasswordSetPasswordSpecifics) {
std::string client_tag = "title";
EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI, DEFAULT_ENCRYPTION));
sync_pb::EntitySpecifics entity_specifics;
{
ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
Cryptographer* cryptographer = trans.GetCryptographer();
sync_pb::PasswordSpecificsData data;
data.set_password_value("secret");
cryptographer->Encrypt(
data, entity_specifics.mutable_password()->mutable_encrypted());
}
MakeServerNode(sync_manager_.GetUserShare(), PASSWORDS, client_tag,
GenerateSyncableHash(PASSWORDS, client_tag), entity_specifics);
// New node shouldn't start off unsynced.
EXPECT_FALSE(ResetUnsyncedEntry(PASSWORDS, client_tag));
// Manually change to the same data via SetPasswordSpecifics. Should not set
// is_unsynced.
{
WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
WriteNode node(&trans);
EXPECT_EQ(BaseNode::INIT_OK,
node.InitByClientTagLookup(PASSWORDS, client_tag));
node.SetPasswordSpecifics(node.GetPasswordSpecifics());
}
EXPECT_FALSE(ResetUnsyncedEntry(PASSWORDS, client_tag));
// Manually change to different data. Should set is_unsynced.
{
WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
WriteNode node(&trans);
EXPECT_EQ(BaseNode::INIT_OK,
node.InitByClientTagLookup(PASSWORDS, client_tag));
Cryptographer* cryptographer = trans.GetCryptographer();
sync_pb::PasswordSpecificsData data;
data.set_password_value("secret2");
cryptographer->Encrypt(
data, entity_specifics.mutable_password()->mutable_encrypted());
node.SetPasswordSpecifics(data);
const syncable::Entry* node_entry = node.GetEntry();
EXPECT_TRUE(node_entry->GetIsUnsynced());
}
}
// Passwords have their own handling for encryption. Verify setting a new
// passphrase updates the data and clears the unencrypted metadta for passwords.
TEST_F(SyncManagerTest, UpdatePasswordNewPassphrase) {
EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI, DEFAULT_ENCRYPTION));
sync_pb::EntitySpecifics entity_specifics;
base::FieldTrialList field_trial_list(nullptr);
base::test::ScopedFeatureList scoped_feature_list;
scoped_feature_list.InitAndEnableFeature(kFillPasswordMetadata);
{
ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
Cryptographer* cryptographer = trans.GetCryptographer();
sync_pb::PasswordSpecificsData data;
data.set_password_value(kPasswordValue);
entity_specifics.mutable_password()
->mutable_unencrypted_metadata()
->set_url(kUrl);
cryptographer->Encrypt(
data, entity_specifics.mutable_password()->mutable_encrypted());
}
EXPECT_TRUE(entity_specifics.password().has_unencrypted_metadata());
MakeServerNode(sync_manager_.GetUserShare(), PASSWORDS, kClientTag,
GenerateSyncableHash(PASSWORDS, kClientTag), entity_specifics);
// New node shouldn't start off unsynced.
EXPECT_FALSE(ResetUnsyncedEntry(PASSWORDS, kClientTag));
// Set a new passphrase. Should set is_unsynced.
testing::Mock::VerifyAndClearExpectations(&encryption_observer_);
EXPECT_CALL(encryption_observer_,
OnBootstrapTokenUpdated(_, PASSPHRASE_BOOTSTRAP_TOKEN));
ExpectPassphraseAcceptance();
SetCustomPassphraseAndCheck("new_passphrase");
{
ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
Cryptographer* cryptographer = trans.GetCryptographer();
EXPECT_TRUE(cryptographer->is_ready());
ReadNode password_node(&trans);
EXPECT_EQ(BaseNode::INIT_OK,
password_node.InitByClientTagLookup(PASSWORDS, kClientTag));
const sync_pb::PasswordSpecificsData& data =
password_node.GetPasswordSpecifics();
EXPECT_EQ(kPasswordValue, data.password_value());
EXPECT_FALSE(password_node.GetEntitySpecifics()
.password()
.has_unencrypted_metadata());
}
EXPECT_TRUE(ResetUnsyncedEntry(PASSWORDS, kClientTag));
// Check that writing new password doesn't set the metadata.
const std::string tag = "newpassentity";
{
WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
ReadNode root_node(&trans);
root_node.InitByRootLookup();
WriteNode password_node(&trans);
WriteNode::InitUniqueByCreationResult result =
password_node.InitUniqueByCreation(PASSWORDS, root_node, tag);
EXPECT_EQ(WriteNode::INIT_SUCCESS, result);
sync_pb::PasswordSpecificsData data;
data.set_password_value(kPasswordValue);
data.set_signon_realm(kUrl);
password_node.SetPasswordSpecifics(data);
}
{
ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
Cryptographer* cryptographer = trans.GetCryptographer();
EXPECT_TRUE(cryptographer->is_ready());
ReadNode password_node(&trans);
EXPECT_EQ(BaseNode::INIT_OK,
password_node.InitByClientTagLookup(PASSWORDS, tag));
const sync_pb::PasswordSpecificsData& data =
password_node.GetPasswordSpecifics();
EXPECT_EQ(kPasswordValue, data.password_value());
EXPECT_FALSE(password_node.GetEntitySpecifics()
.password()
.has_unencrypted_metadata());
}
}
// Passwords have their own handling for encryption. Verify it does not result
// in unnecessary writes via ReencryptEverything.
TEST_F(SyncManagerTest, UpdatePasswordReencryptEverything) {
EXPECT_FALSE(base::FeatureList::IsEnabled(kFillPasswordMetadata));
EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI, DEFAULT_ENCRYPTION));
sync_pb::EntitySpecifics entity_specifics;
{
ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
Cryptographer* cryptographer = trans.GetCryptographer();
sync_pb::PasswordSpecificsData data;
data.set_password_value("secret");
cryptographer->Encrypt(
data, entity_specifics.mutable_password()->mutable_encrypted());
}
MakeServerNode(sync_manager_.GetUserShare(), PASSWORDS, kClientTag,
GenerateSyncableHash(PASSWORDS, kClientTag), entity_specifics);
// New node shouldn't start off unsynced.
EXPECT_FALSE(ResetUnsyncedEntry(PASSWORDS, kClientTag));
// Force a re-encrypt everything. Should not set is_unsynced.
testing::Mock::VerifyAndClearExpectations(&encryption_observer_);
EXPECT_CALL(encryption_observer_, OnEncryptionComplete());
EXPECT_CALL(encryption_observer_, OnCryptographerStateChanged(_));
EXPECT_CALL(encryption_observer_, OnEncryptedTypesChanged(_, false));
sync_manager_.GetEncryptionHandler()->Init();
PumpLoop();
EXPECT_FALSE(ResetUnsyncedEntry(PASSWORDS, kClientTag));
}
// Metadata filling can happen during ReencryptEverything, check that data is
// written when it's applicable, namely that password specifics entity is marked
// unsynced, when data was written to the unencrypted metadata field.
TEST_F(SyncManagerTest, UpdatePasswordReencryptEverythingFillMetadata) {
base::FieldTrialList field_trial_list(nullptr);
base::test::ScopedFeatureList scoped_feature_list;
scoped_feature_list.InitAndEnableFeature(kFillPasswordMetadata);
EXPECT_TRUE(base::FeatureList::IsEnabled(kFillPasswordMetadata));
EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI, DEFAULT_ENCRYPTION));
sync_pb::EntitySpecifics entity_specifics;
{
ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
Cryptographer* cryptographer = trans.GetCryptographer();
sync_pb::PasswordSpecificsData data;
data.set_password_value("secret");
data.set_signon_realm(kUrl);
cryptographer->Encrypt(
data, entity_specifics.mutable_password()->mutable_encrypted());
}
MakeServerNode(sync_manager_.GetUserShare(), PASSWORDS, kClientTag,
GenerateSyncableHash(PASSWORDS, kClientTag), entity_specifics);
// New node shouldn't start off unsynced.
EXPECT_FALSE(ResetUnsyncedEntry(PASSWORDS, kClientTag));
// Force a re-encrypt everything. Should set is_unsynced.
testing::Mock::VerifyAndClearExpectations(&encryption_observer_);
EXPECT_CALL(encryption_observer_, OnEncryptionComplete());
EXPECT_CALL(encryption_observer_, OnCryptographerStateChanged(_));
EXPECT_CALL(encryption_observer_, OnEncryptedTypesChanged(_, false));
sync_manager_.GetEncryptionHandler()->Init();
PumpLoop();
// Check that unencrypted metadata field was set.
{
ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
Cryptographer* cryptographer = trans.GetCryptographer();
EXPECT_TRUE(cryptographer->is_ready());
ReadNode password_node(&trans);
EXPECT_EQ(BaseNode::INIT_OK,
password_node.InitByClientTagLookup(PASSWORDS, kClientTag));
EXPECT_EQ(kUrl, password_node.GetEntitySpecifics()
.password()
.unencrypted_metadata()
.url());
}
EXPECT_TRUE(ResetUnsyncedEntry(PASSWORDS, kClientTag));
}
// Check that when the data in PasswordSpecifics hasn't changed during
// ReEncryption, entity is not marked as unsynced.
TEST_F(SyncManagerTest,
UpdatePasswordReencryptEverythingDontMarkUnsyncWhenNotNeeded) {
base::FieldTrialList field_trial_list(nullptr);
base::test::ScopedFeatureList scoped_feature_list;
scoped_feature_list.InitAndEnableFeature(kFillPasswordMetadata);
EXPECT_TRUE(base::FeatureList::IsEnabled(kFillPasswordMetadata));
EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI, DEFAULT_ENCRYPTION));
sync_pb::EntitySpecifics entity_specifics;
{
ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
Cryptographer* cryptographer = trans.GetCryptographer();
sync_pb::PasswordSpecificsData data;
data.set_password_value("secret");
data.set_signon_realm(kUrl);
cryptographer->Encrypt(
data, entity_specifics.mutable_password()->mutable_encrypted());
}
entity_specifics.mutable_password()->mutable_unencrypted_metadata()->set_url(
kUrl);
MakeServerNode(sync_manager_.GetUserShare(), PASSWORDS, kClientTag,
GenerateSyncableHash(PASSWORDS, kClientTag), entity_specifics);
// New node shouldn't start off unsynced.
EXPECT_FALSE(ResetUnsyncedEntry(PASSWORDS, kClientTag));
// Force a re-encrypt everything. Should not set is_unsynced.
testing::Mock::VerifyAndClearExpectations(&encryption_observer_);
EXPECT_CALL(encryption_observer_, OnEncryptionComplete());
EXPECT_CALL(encryption_observer_, OnCryptographerStateChanged(_));
EXPECT_CALL(encryption_observer_, OnEncryptedTypesChanged(_, false));
sync_manager_.GetEncryptionHandler()->Init();
PumpLoop();
EXPECT_FALSE(ResetUnsyncedEntry(PASSWORDS, kClientTag));
}
// Test that attempting to start up with corrupted password data triggers
// an unrecoverable error (rather than crashing).
TEST_F(SyncManagerTest, ReencryptEverythingWithUnrecoverableErrorPasswords) {
const char kClientTag[] = "client_tag";
EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI, DEFAULT_ENCRYPTION));
sync_pb::EntitySpecifics entity_specifics;
{
// Create a synced bookmark with undecryptable data.
ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
Cryptographer other_cryptographer(&encryptor_);
KeyParams fake_params = {"localhost", "dummy", "fake_key"};
other_cryptographer.AddKey(fake_params);
sync_pb::PasswordSpecificsData data;
data.set_password_value("secret");
other_cryptographer.Encrypt(
data, entity_specifics.mutable_password()->mutable_encrypted());
// Set up the real cryptographer with a different key.
KeyParams real_params = {"localhost", "username", "real_key"};
trans.GetCryptographer()->AddKey(real_params);
}
MakeServerNode(sync_manager_.GetUserShare(), PASSWORDS, kClientTag,
GenerateSyncableHash(PASSWORDS, kClientTag), entity_specifics);
EXPECT_FALSE(ResetUnsyncedEntry(PASSWORDS, kClientTag));
// Force a re-encrypt everything. Should trigger an unrecoverable error due
// to being unable to decrypt the data that was previously applied.
testing::Mock::VerifyAndClearExpectations(&encryption_observer_);
EXPECT_CALL(encryption_observer_, OnEncryptionComplete());
EXPECT_CALL(encryption_observer_, OnCryptographerStateChanged(_));
EXPECT_CALL(encryption_observer_, OnEncryptedTypesChanged(_, false));
EXPECT_FALSE(HasUnrecoverableError());
sync_manager_.GetEncryptionHandler()->Init();
PumpLoop();
EXPECT_TRUE(HasUnrecoverableError());
}
// Test that attempting to start up with corrupted bookmark data triggers
// an unrecoverable error (rather than crashing).
TEST_F(SyncManagerTest, ReencryptEverythingWithUnrecoverableErrorBookmarks) {
const char kClientTag[] = "client_tag";
EXPECT_CALL(
encryption_observer_,
OnEncryptedTypesChanged(HasModelTypes(EncryptableUserTypes()), true));
EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI, FULL_ENCRYPTION));
sync_pb::EntitySpecifics entity_specifics;
{
// Create a synced bookmark with undecryptable data.
ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
Cryptographer other_cryptographer(&encryptor_);
KeyParams fake_params = {"localhost", "dummy", "fake_key"};
other_cryptographer.AddKey(fake_params);
sync_pb::EntitySpecifics bm_specifics;
bm_specifics.mutable_bookmark()->set_title("title");
bm_specifics.mutable_bookmark()->set_url("url");
sync_pb::EncryptedData encrypted;
other_cryptographer.Encrypt(bm_specifics, &encrypted);
entity_specifics.mutable_encrypted()->CopyFrom(encrypted);
// Set up the real cryptographer with a different key.
KeyParams real_params = {"localhost", "username", "real_key"};
trans.GetCryptographer()->AddKey(real_params);
}
MakeServerNode(sync_manager_.GetUserShare(), BOOKMARKS, kClientTag,
GenerateSyncableHash(BOOKMARKS, kClientTag), entity_specifics);
EXPECT_FALSE(ResetUnsyncedEntry(BOOKMARKS, kClientTag));
// Force a re-encrypt everything. Should trigger an unrecoverable error due
// to being unable to decrypt the data that was previously applied.
testing::Mock::VerifyAndClearExpectations(&encryption_observer_);
EXPECT_CALL(encryption_observer_, OnEncryptionComplete());
EXPECT_CALL(encryption_observer_, OnCryptographerStateChanged(_));
EXPECT_CALL(encryption_observer_, OnEncryptedTypesChanged(_, true));
EXPECT_FALSE(HasUnrecoverableError());
sync_manager_.GetEncryptionHandler()->Init();
PumpLoop();
EXPECT_TRUE(HasUnrecoverableError());
}
// Verify SetTitle(..) doesn't unnecessarily set IS_UNSYNCED for bookmarks
// when we write the same data, but does set it when we write new data.
TEST_F(SyncManagerTest, SetBookmarkTitle) {
std::string client_tag = "title";
sync_pb::EntitySpecifics entity_specifics;
entity_specifics.mutable_bookmark()->set_url("url");
entity_specifics.mutable_bookmark()->set_title("title");
MakeServerNode(sync_manager_.GetUserShare(), BOOKMARKS, client_tag,
GenerateSyncableHash(BOOKMARKS, client_tag), entity_specifics);
// New node shouldn't start off unsynced.
EXPECT_FALSE(ResetUnsyncedEntry(BOOKMARKS, client_tag));
// Manually change to the same title. Should not set is_unsynced.
{
WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
WriteNode node(&trans);
EXPECT_EQ(BaseNode::INIT_OK,
node.InitByClientTagLookup(BOOKMARKS, client_tag));
node.SetTitle(client_tag);
}
EXPECT_FALSE(ResetUnsyncedEntry(BOOKMARKS, client_tag));
// Manually change to new title. Should set is_unsynced.
{
WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
WriteNode node(&trans);
EXPECT_EQ(BaseNode::INIT_OK,
node.InitByClientTagLookup(BOOKMARKS, client_tag));
node.SetTitle("title2");
}
EXPECT_TRUE(ResetUnsyncedEntry(BOOKMARKS, client_tag));
}
// Verify SetTitle(..) doesn't unnecessarily set IS_UNSYNCED for encrypted
// bookmarks when we write the same data, but does set it when we write new
// data.
TEST_F(SyncManagerTest, SetBookmarkTitleWithEncryption) {
std::string client_tag = "title";
sync_pb::EntitySpecifics entity_specifics;
entity_specifics.mutable_bookmark()->set_url("url");
entity_specifics.mutable_bookmark()->set_title("title");
MakeServerNode(sync_manager_.GetUserShare(), BOOKMARKS, client_tag,
GenerateSyncableHash(BOOKMARKS, client_tag), entity_specifics);
// New node shouldn't start off unsynced.
EXPECT_FALSE(ResetUnsyncedEntry(BOOKMARKS, client_tag));
// Encrypt the datatatype, should set is_unsynced.
EXPECT_CALL(
encryption_observer_,
OnEncryptedTypesChanged(HasModelTypes(EncryptableUserTypes()), true));
EXPECT_CALL(encryption_observer_, OnEncryptionComplete());
EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI, FULL_ENCRYPTION));
EXPECT_CALL(encryption_observer_, OnCryptographerStateChanged(_));
EXPECT_CALL(encryption_observer_, OnEncryptedTypesChanged(_, true));
sync_manager_.GetEncryptionHandler()->Init();
PumpLoop();
EXPECT_TRUE(ResetUnsyncedEntry(BOOKMARKS, client_tag));
// Manually change to the same title. Should not set is_unsynced.
// NON_UNIQUE_NAME should be kEncryptedString.
{
WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
WriteNode node(&trans);
EXPECT_EQ(BaseNode::INIT_OK,
node.InitByClientTagLookup(BOOKMARKS, client_tag));
node.SetTitle(client_tag);
const syncable::Entry* node_entry = node.GetEntry();
const sync_pb::EntitySpecifics& specifics = node_entry->GetSpecifics();
EXPECT_TRUE(specifics.has_encrypted());
EXPECT_EQ(kEncryptedString, node_entry->GetNonUniqueName());
}
EXPECT_FALSE(ResetUnsyncedEntry(BOOKMARKS, client_tag));
// Manually change to new title. Should set is_unsynced. NON_UNIQUE_NAME
// should still be kEncryptedString.
{
WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
WriteNode node(&trans);
EXPECT_EQ(BaseNode::INIT_OK,
node.InitByClientTagLookup(BOOKMARKS, client_tag));
node.SetTitle("title2");
const syncable::Entry* node_entry = node.GetEntry();
const sync_pb::EntitySpecifics& specifics = node_entry->GetSpecifics();
EXPECT_TRUE(specifics.has_encrypted());
EXPECT_EQ(kEncryptedString, node_entry->GetNonUniqueName());
}
EXPECT_TRUE(ResetUnsyncedEntry(BOOKMARKS, client_tag));
}
// Verify SetTitle(..) doesn't unnecessarily set IS_UNSYNCED for non-bookmarks
// when we write the same data, but does set it when we write new data.
TEST_F(SyncManagerTest, SetNonBookmarkTitle) {
std::string client_tag = "title";
sync_pb::EntitySpecifics entity_specifics;
entity_specifics.mutable_preference()->set_name("name");
entity_specifics.mutable_preference()->set_value("value");
MakeServerNode(sync_manager_.GetUserShare(), PREFERENCES, client_tag,
GenerateSyncableHash(PREFERENCES, client_tag),
entity_specifics);
// New node shouldn't start off unsynced.
EXPECT_FALSE(ResetUnsyncedEntry(PREFERENCES, client_tag));
// Manually change to the same title. Should not set is_unsynced.
{
WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
WriteNode node(&trans);
EXPECT_EQ(BaseNode::INIT_OK,
node.InitByClientTagLookup(PREFERENCES, client_tag));
node.SetTitle(client_tag);
}
EXPECT_FALSE(ResetUnsyncedEntry(PREFERENCES, client_tag));
// Manually change to new title. Should set is_unsynced.
{
WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
WriteNode node(&trans);
EXPECT_EQ(BaseNode::INIT_OK,
node.InitByClientTagLookup(PREFERENCES, client_tag));
node.SetTitle("title2");
}
EXPECT_TRUE(ResetUnsyncedEntry(PREFERENCES, client_tag));
}
// Verify SetTitle(..) doesn't unnecessarily set IS_UNSYNCED for encrypted
// non-bookmarks when we write the same data or when we write new data
// data (should remained kEncryptedString).
TEST_F(SyncManagerTest, SetNonBookmarkTitleWithEncryption) {
std::string client_tag = "title";
sync_pb::EntitySpecifics entity_specifics;
entity_specifics.mutable_preference()->set_name("name");
entity_specifics.mutable_preference()->set_value("value");
MakeServerNode(sync_manager_.GetUserShare(), PREFERENCES, client_tag,
GenerateSyncableHash(PREFERENCES, client_tag),
entity_specifics);
// New node shouldn't start off unsynced.
EXPECT_FALSE(ResetUnsyncedEntry(PREFERENCES, client_tag));
// Encrypt the datatatype, should set is_unsynced.
EXPECT_CALL(
encryption_observer_,
OnEncryptedTypesChanged(HasModelTypes(EncryptableUserTypes()), true));
EXPECT_CALL(encryption_observer_, OnEncryptionComplete());
EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI, FULL_ENCRYPTION));
EXPECT_CALL(encryption_observer_, OnCryptographerStateChanged(_));
EXPECT_CALL(encryption_observer_, OnEncryptedTypesChanged(_, true));
sync_manager_.GetEncryptionHandler()->Init();
PumpLoop();
EXPECT_TRUE(ResetUnsyncedEntry(PREFERENCES, client_tag));
// Manually change to the same title. Should not set is_unsynced.
// NON_UNIQUE_NAME should be kEncryptedString.
{
WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
WriteNode node(&trans);
EXPECT_EQ(BaseNode::INIT_OK,
node.InitByClientTagLookup(PREFERENCES, client_tag));
node.SetTitle(client_tag);
const syncable::Entry* node_entry = node.GetEntry();
const sync_pb::EntitySpecifics& specifics = node_entry->GetSpecifics();
EXPECT_TRUE(specifics.has_encrypted());
EXPECT_EQ(kEncryptedString, node_entry->GetNonUniqueName());
}
EXPECT_FALSE(ResetUnsyncedEntry(PREFERENCES, client_tag));
// Manually change to new title. Should not set is_unsynced because the
// NON_UNIQUE_NAME should still be kEncryptedString.
{
WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
WriteNode node(&trans);
EXPECT_EQ(BaseNode::INIT_OK,
node.InitByClientTagLookup(PREFERENCES, client_tag));
node.SetTitle("title2");
const syncable::Entry* node_entry = node.GetEntry();
const sync_pb::EntitySpecifics& specifics = node_entry->GetSpecifics();
EXPECT_TRUE(specifics.has_encrypted());
EXPECT_EQ(kEncryptedString, node_entry->GetNonUniqueName());
EXPECT_FALSE(node_entry->GetIsUnsynced());
}
}
// Ensure that titles are truncated to 255 bytes, and attempting to reset
// them to their longer version does not set IS_UNSYNCED.
TEST_F(SyncManagerTest, SetLongTitle) {
const int kNumChars = 512;
const std::string kClientTag = "tag";
std::string title(kNumChars, '0');
sync_pb::EntitySpecifics entity_specifics;
entity_specifics.mutable_preference()->set_name("name");
entity_specifics.mutable_preference()->set_value("value");
MakeServerNode(sync_manager_.GetUserShare(), PREFERENCES, "short_title",
GenerateSyncableHash(PREFERENCES, kClientTag),
entity_specifics);
// New node shouldn't start off unsynced.
EXPECT_FALSE(ResetUnsyncedEntry(PREFERENCES, kClientTag));
// Manually change to the long title. Should set is_unsynced.
{
WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
WriteNode node(&trans);
EXPECT_EQ(BaseNode::INIT_OK,
node.InitByClientTagLookup(PREFERENCES, kClientTag));
node.SetTitle(title);
EXPECT_EQ(node.GetTitle(), title.substr(0, 255));
}
EXPECT_TRUE(ResetUnsyncedEntry(PREFERENCES, kClientTag));
// Manually change to the same title. Should not set is_unsynced.
{
WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
WriteNode node(&trans);
EXPECT_EQ(BaseNode::INIT_OK,
node.InitByClientTagLookup(PREFERENCES, kClientTag));
node.SetTitle(title);
EXPECT_EQ(node.GetTitle(), title.substr(0, 255));
}
EXPECT_FALSE(ResetUnsyncedEntry(PREFERENCES, kClientTag));
// Manually change to new title. Should set is_unsynced.
{
WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
WriteNode node(&trans);
EXPECT_EQ(BaseNode::INIT_OK,
node.InitByClientTagLookup(PREFERENCES, kClientTag));
node.SetTitle("title2");
}
EXPECT_TRUE(ResetUnsyncedEntry(PREFERENCES, kClientTag));
}
// Create an encrypted entry when the cryptographer doesn't think the type is
// marked for encryption. Ensure reads/writes don't break and don't unencrypt
// the data.
TEST_F(SyncManagerTest, SetPreviouslyEncryptedSpecifics) {
std::string client_tag = "tag";
std::string url = "url";
std::string url2 = "new_url";
std::string title = "title";
sync_pb::EntitySpecifics entity_specifics;
EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI, DEFAULT_ENCRYPTION));
{
ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
Cryptographer* crypto = trans.GetCryptographer();
sync_pb::EntitySpecifics bm_specifics;
bm_specifics.mutable_bookmark()->set_title("title");
bm_specifics.mutable_bookmark()->set_url("url");
sync_pb::EncryptedData encrypted;
crypto->Encrypt(bm_specifics, &encrypted);
entity_specifics.mutable_encrypted()->CopyFrom(encrypted);
AddDefaultFieldValue(BOOKMARKS, &entity_specifics);
}
MakeServerNode(sync_manager_.GetUserShare(), BOOKMARKS, client_tag,
GenerateSyncableHash(BOOKMARKS, client_tag), entity_specifics);
{
// Verify the data.
ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
ReadNode node(&trans);
EXPECT_EQ(BaseNode::INIT_OK,
node.InitByClientTagLookup(BOOKMARKS, client_tag));
EXPECT_EQ(title, node.GetTitle());
EXPECT_EQ(url, node.GetBookmarkSpecifics().url());
}
{
// Overwrite the url (which overwrites the specifics).
WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
WriteNode node(&trans);
EXPECT_EQ(BaseNode::INIT_OK,
node.InitByClientTagLookup(BOOKMARKS, client_tag));
sync_pb::BookmarkSpecifics bookmark_specifics(node.GetBookmarkSpecifics());
bookmark_specifics.set_url(url2);
node.SetBookmarkSpecifics(bookmark_specifics);
}
{
// Verify it's still encrypted and it has the most recent url.
ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
ReadNode node(&trans);
EXPECT_EQ(BaseNode::INIT_OK,
node.InitByClientTagLookup(BOOKMARKS, client_tag));
EXPECT_EQ(title, node.GetTitle());
EXPECT_EQ(url2, node.GetBookmarkSpecifics().url());
const syncable::Entry* node_entry = node.GetEntry();
EXPECT_EQ(kEncryptedString, node_entry->GetNonUniqueName());
const sync_pb::EntitySpecifics& specifics = node_entry->GetSpecifics();
EXPECT_TRUE(specifics.has_encrypted());
}
}
// Verify transaction version of a model type is incremented when node of
// that type is updated.
TEST_F(SyncManagerTest, IncrementTransactionVersion) {
ModelSafeRoutingInfo routing_info;
GetModelSafeRoutingInfo(&routing_info);
{
ReadTransaction read_trans(FROM_HERE, sync_manager_.GetUserShare());
for (ModelSafeRoutingInfo::iterator i = routing_info.begin();
i != routing_info.end(); ++i) {
// Transaction version is incremented when SyncManagerTest::SetUp()
// creates a node of each type.
EXPECT_EQ(1,
sync_manager_.GetUserShare()->directory->GetTransactionVersion(
i->first));
}
}
// Create bookmark node to increment transaction version of bookmark model.
std::string client_tag = "title";
sync_pb::EntitySpecifics entity_specifics;
entity_specifics.mutable_bookmark()->set_url("url");
entity_specifics.mutable_bookmark()->set_title("title");
MakeServerNode(sync_manager_.GetUserShare(), BOOKMARKS, client_tag,
GenerateSyncableHash(BOOKMARKS, client_tag), entity_specifics);
{
ReadTransaction read_trans(FROM_HERE, sync_manager_.GetUserShare());
for (ModelSafeRoutingInfo::iterator i = routing_info.begin();
i != routing_info.end(); ++i) {
EXPECT_EQ(i->first == BOOKMARKS ? 2 : 1,
sync_manager_.GetUserShare()->directory->GetTransactionVersion(
i->first));
}
}
}
class SyncManagerWithLocalBackendTest : public SyncManagerTest {
protected:
void SetUp() override { DoSetUp(true); }
};
// This test checks that we can successfully initialize without credentials in
// the local backend case.
TEST_F(SyncManagerWithLocalBackendTest, StartSyncInLocalMode) {
EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI, DEFAULT_ENCRYPTION));
EXPECT_CALL(encryption_observer_, OnEncryptionComplete());
EXPECT_CALL(encryption_observer_, OnCryptographerStateChanged(_));
EXPECT_CALL(encryption_observer_, OnEncryptedTypesChanged(_, false));
sync_manager_.GetEncryptionHandler()->Init();
PumpLoop();
const ModelTypeSet encrypted_types = GetEncryptedTypes();
EXPECT_TRUE(encrypted_types.Has(PASSWORDS));
EXPECT_FALSE(IsEncryptEverythingEnabledForTest());
{
ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
ReadNode node(&trans);
EXPECT_EQ(BaseNode::INIT_OK, node.InitByIdLookup(GetIdForDataType(NIGORI)));
sync_pb::NigoriSpecifics nigori = node.GetNigoriSpecifics();
EXPECT_TRUE(nigori.has_encryption_keybag());
Cryptographer* cryptographer = trans.GetCryptographer();
EXPECT_TRUE(cryptographer->is_ready());
EXPECT_TRUE(cryptographer->CanDecrypt(nigori.encryption_keybag()));
}
}
class MockSyncScheduler : public FakeSyncScheduler {
public:
MockSyncScheduler() : FakeSyncScheduler() {}
virtual ~MockSyncScheduler() {}
MOCK_METHOD2(Start, void(SyncScheduler::Mode, base::Time));
MOCK_METHOD1(ScheduleConfiguration, void(const ConfigurationParams&));
};
class ComponentsFactory : public TestEngineComponentsFactory {
public:
ComponentsFactory(const Switches& switches,
SyncScheduler* scheduler_to_use,
SyncCycleContext** cycle_context,
EngineComponentsFactory::StorageOption* storage_used)
: TestEngineComponentsFactory(switches,
EngineComponentsFactory::STORAGE_IN_MEMORY,
storage_used),
scheduler_to_use_(scheduler_to_use),
cycle_context_(cycle_context) {}
~ComponentsFactory() override {}
std::unique_ptr<SyncScheduler> BuildScheduler(
const std::string& name,
SyncCycleContext* context,
CancelationSignal* stop_handle,
bool local_sync_backend_enabled) override {
*cycle_context_ = context;
return std::move(scheduler_to_use_);
}
private:
std::unique_ptr<SyncScheduler> scheduler_to_use_;
SyncCycleContext** cycle_context_;
};
class SyncManagerTestWithMockScheduler : public SyncManagerTest {
public:
SyncManagerTestWithMockScheduler() : scheduler_(nullptr) {}
EngineComponentsFactory* GetFactory() override {
scheduler_ = new MockSyncScheduler();
return new ComponentsFactory(GetSwitches(), scheduler_, &cycle_context_,
&storage_used_);
}
MockSyncScheduler* scheduler() { return scheduler_; }
SyncCycleContext* cycle_context() { return cycle_context_; }
private:
MockSyncScheduler* scheduler_;
SyncCycleContext* cycle_context_;
};
// Test that the configuration params are properly created and sent to
// ScheduleConfigure. No callback should be invoked. Any disabled datatypes
// should be purged.
TEST_F(SyncManagerTestWithMockScheduler, BasicConfiguration) {
ConfigureReason reason = CONFIGURE_REASON_RECONFIGURATION;
ModelTypeSet types_to_download(BOOKMARKS, PREFERENCES);
ModelSafeRoutingInfo new_routing_info;
GetModelSafeRoutingInfo(&new_routing_info);
ModelTypeSet enabled_types = GetRoutingInfoTypes(new_routing_info);
ModelTypeSet disabled_types = Difference(ModelTypeSet::All(), enabled_types);
ConfigurationParams params;
EXPECT_CALL(*scheduler(), Start(SyncScheduler::CONFIGURATION_MODE, _));
EXPECT_CALL(*scheduler(), ScheduleConfiguration(_))
.WillOnce(SaveArg<0>(¶ms));
// Set data for all types.
ModelTypeSet protocol_types = ProtocolTypes();
for (ModelTypeSet::Iterator iter = protocol_types.First(); iter.Good();
iter.Inc()) {
SetProgressMarkerForType(iter.Get(), true);
}
sync_manager_.PurgeDisabledTypes(disabled_types, ModelTypeSet(),
ModelTypeSet());
CallbackCounter ready_task_counter, retry_task_counter;
sync_manager_.ConfigureSyncer(
reason, types_to_download, new_routing_info,
base::Bind(&CallbackCounter::Callback,
base::Unretained(&ready_task_counter)),
base::Bind(&CallbackCounter::Callback,
base::Unretained(&retry_task_counter)));
EXPECT_EQ(0, ready_task_counter.times_called());
EXPECT_EQ(0, retry_task_counter.times_called());
EXPECT_EQ(sync_pb::GetUpdatesCallerInfo::RECONFIGURATION, params.source);
EXPECT_EQ(types_to_download, params.types_to_download);
EXPECT_EQ(new_routing_info, params.routing_info);
// Verify all the disabled types were purged.
EXPECT_EQ(enabled_types,
sync_manager_.GetUserShare()->directory->InitialSyncEndedTypes());
EXPECT_EQ(disabled_types, sync_manager_.GetTypesWithEmptyProgressMarkerToken(
ModelTypeSet::All()));
}
// Test that on a reconfiguration (configuration where the session context
// already has routing info), only those recently disabled types are purged.
TEST_F(SyncManagerTestWithMockScheduler, ReConfiguration) {
ConfigureReason reason = CONFIGURE_REASON_RECONFIGURATION;
ModelTypeSet types_to_download(BOOKMARKS, PREFERENCES);
ModelTypeSet disabled_types = ModelTypeSet(THEMES, SESSIONS);
ModelSafeRoutingInfo old_routing_info;
ModelSafeRoutingInfo new_routing_info;
GetModelSafeRoutingInfo(&old_routing_info);
new_routing_info = old_routing_info;
new_routing_info.erase(THEMES);
new_routing_info.erase(SESSIONS);
ModelTypeSet enabled_types = GetRoutingInfoTypes(new_routing_info);
ConfigurationParams params;
EXPECT_CALL(*scheduler(), Start(SyncScheduler::CONFIGURATION_MODE, _));
EXPECT_CALL(*scheduler(), ScheduleConfiguration(_))
.WillOnce(SaveArg<0>(¶ms));
// Set data for all types except those recently disabled (so we can verify
// only those recently disabled are purged) .
ModelTypeSet protocol_types = ProtocolTypes();
for (ModelTypeSet::Iterator iter = protocol_types.First(); iter.Good();
iter.Inc()) {
if (!disabled_types.Has(iter.Get())) {
SetProgressMarkerForType(iter.Get(), true);
} else {
SetProgressMarkerForType(iter.Get(), false);
}
}
// Set the context to have the old routing info.
cycle_context()->SetRoutingInfo(old_routing_info);
CallbackCounter ready_task_counter, retry_task_counter;
sync_manager_.PurgeDisabledTypes(ModelTypeSet(), ModelTypeSet(),
ModelTypeSet());
sync_manager_.ConfigureSyncer(
reason, types_to_download, new_routing_info,
base::Bind(&CallbackCounter::Callback,
base::Unretained(&ready_task_counter)),
base::Bind(&CallbackCounter::Callback,
base::Unretained(&retry_task_counter)));
EXPECT_EQ(0, ready_task_counter.times_called());
EXPECT_EQ(0, retry_task_counter.times_called());
EXPECT_EQ(sync_pb::GetUpdatesCallerInfo::RECONFIGURATION, params.source);
EXPECT_EQ(types_to_download, params.types_to_download);
EXPECT_EQ(new_routing_info, params.routing_info);
// Verify only the recently disabled types were purged.
EXPECT_EQ(disabled_types, sync_manager_.GetTypesWithEmptyProgressMarkerToken(
ProtocolTypes()));
}
// Test that SyncManager::ClearServerData invokes the scheduler.
TEST_F(SyncManagerTestWithMockScheduler, ClearServerData) {
EXPECT_CALL(*scheduler(), Start(SyncScheduler::CLEAR_SERVER_DATA_MODE, _));
CallbackCounter callback_counter;
sync_manager_.ClearServerData(base::Bind(
&CallbackCounter::Callback, base::Unretained(&callback_counter)));
PumpLoop();
EXPECT_EQ(1, callback_counter.times_called());
}
// Test that PurgePartiallySyncedTypes purges only those types that have not
// fully completed their initial download and apply.
TEST_F(SyncManagerTest, PurgePartiallySyncedTypes) {
ModelSafeRoutingInfo routing_info;
GetModelSafeRoutingInfo(&routing_info);
ModelTypeSet enabled_types = GetRoutingInfoTypes(routing_info);
UserShare* share = sync_manager_.GetUserShare();
// The test harness automatically initializes all types in the routing info.
// Check that autofill is not among them.
ASSERT_FALSE(enabled_types.Has(AUTOFILL));
// Further ensure that the test harness did not create its root node.
{
syncable::ReadTransaction trans(FROM_HERE, share->directory.get());
syncable::Entry autofill_root_node(&trans, syncable::GET_TYPE_ROOT,
AUTOFILL);
ASSERT_FALSE(autofill_root_node.good());
}
// One more redundant check.
ASSERT_FALSE(
sync_manager_.GetUserShare()->directory->InitialSyncEndedTypes().Has(
AUTOFILL));
// Give autofill a progress marker.
sync_pb::DataTypeProgressMarker autofill_marker;
autofill_marker.set_data_type_id(
GetSpecificsFieldNumberFromModelType(AUTOFILL));
autofill_marker.set_token("token");
share->directory->SetDownloadProgress(AUTOFILL, autofill_marker);
// Also add a pending autofill root node update from the server.
TestEntryFactory factory_(share->directory.get());
int autofill_meta = factory_.CreateUnappliedRootNode(AUTOFILL);
// Preferences is an enabled type. Check that the harness initialized it.
ASSERT_TRUE(enabled_types.Has(PREFERENCES));
ASSERT_TRUE(
sync_manager_.GetUserShare()->directory->InitialSyncEndedTypes().Has(
PREFERENCES));
// Give preferencse a progress marker.
sync_pb::DataTypeProgressMarker prefs_marker;
prefs_marker.set_data_type_id(
GetSpecificsFieldNumberFromModelType(PREFERENCES));
prefs_marker.set_token("token");
share->directory->SetDownloadProgress(PREFERENCES, prefs_marker);
// Add a fully synced preferences node under the root.
std::string pref_client_tag = "prefABC";
std::string pref_hashed_tag = "hashXYZ";
sync_pb::EntitySpecifics pref_specifics;
AddDefaultFieldValue(PREFERENCES, &pref_specifics);
int pref_meta = MakeServerNode(share, PREFERENCES, pref_client_tag,
pref_hashed_tag, pref_specifics);
// And now, the purge.
sync_manager_.PurgePartiallySyncedTypes();
// Ensure that autofill lost its progress marker, but preferences did not.
ModelTypeSet empty_tokens =
sync_manager_.GetTypesWithEmptyProgressMarkerToken(ModelTypeSet::All());
EXPECT_TRUE(empty_tokens.Has(AUTOFILL));
EXPECT_FALSE(empty_tokens.Has(PREFERENCES));
// Ensure that autofill lost its node, but preferences did not.
{
syncable::ReadTransaction trans(FROM_HERE, share->directory.get());
syncable::Entry autofill_node(&trans, GET_BY_HANDLE, autofill_meta);
syncable::Entry pref_node(&trans, GET_BY_HANDLE, pref_meta);
EXPECT_FALSE(autofill_node.good());
EXPECT_TRUE(pref_node.good());
}
}
// Test CleanupDisabledTypes properly purges all disabled types as specified
// by the previous and current enabled params.
TEST_F(SyncManagerTest, PurgeDisabledTypes) {
ModelSafeRoutingInfo routing_info;
GetModelSafeRoutingInfo(&routing_info);
ModelTypeSet enabled_types = GetRoutingInfoTypes(routing_info);
ModelTypeSet disabled_types = Difference(ModelTypeSet::All(), enabled_types);
// The harness should have initialized the enabled_types for us.
EXPECT_EQ(enabled_types,
sync_manager_.GetUserShare()->directory->InitialSyncEndedTypes());
// Set progress markers for all types.
ModelTypeSet protocol_types = ProtocolTypes();
for (ModelTypeSet::Iterator iter = protocol_types.First(); iter.Good();
iter.Inc()) {
SetProgressMarkerForType(iter.Get(), true);
}
// Verify all the enabled types remain after cleanup, and all the disabled
// types were purged.
sync_manager_.PurgeDisabledTypes(disabled_types, ModelTypeSet(),
ModelTypeSet());
EXPECT_EQ(enabled_types,
sync_manager_.GetUserShare()->directory->InitialSyncEndedTypes());
EXPECT_EQ(disabled_types, sync_manager_.GetTypesWithEmptyProgressMarkerToken(
ModelTypeSet::All()));
// Disable some more types.
disabled_types.Put(BOOKMARKS);
disabled_types.Put(PREFERENCES);
ModelTypeSet new_enabled_types =
Difference(ModelTypeSet::All(), disabled_types);
// Verify only the non-disabled types remain after cleanup.
sync_manager_.PurgeDisabledTypes(disabled_types, ModelTypeSet(),
ModelTypeSet());
EXPECT_EQ(new_enabled_types,
sync_manager_.GetUserShare()->directory->InitialSyncEndedTypes());
EXPECT_EQ(disabled_types, sync_manager_.GetTypesWithEmptyProgressMarkerToken(
ModelTypeSet::All()));
}
// Test PurgeDisabledTypes properly unapplies types by deleting their local data
// and preserving their server data and progress marker.
TEST_F(SyncManagerTest, PurgeUnappliedTypes) {
ModelSafeRoutingInfo routing_info;
GetModelSafeRoutingInfo(&routing_info);
ModelTypeSet unapplied_types = ModelTypeSet(BOOKMARKS, PREFERENCES);
ModelTypeSet enabled_types = GetRoutingInfoTypes(routing_info);
ModelTypeSet disabled_types = Difference(ModelTypeSet::All(), enabled_types);
// The harness should have initialized the enabled_types for us.
EXPECT_EQ(enabled_types,
sync_manager_.GetUserShare()->directory->InitialSyncEndedTypes());
// Set progress markers for all types.
ModelTypeSet protocol_types = ProtocolTypes();
for (ModelTypeSet::Iterator iter = protocol_types.First(); iter.Good();
iter.Inc()) {
SetProgressMarkerForType(iter.Get(), true);
}
// Add the following kinds of items:
// 1. Fully synced preference.
// 2. Locally created preference, server unknown, unsynced
// 3. Locally deleted preference, server known, unsynced
// 4. Server deleted preference, locally known.
// 5. Server created preference, locally unknown, unapplied.
// 6. A fully synced bookmark (no unique_client_tag).
UserShare* share = sync_manager_.GetUserShare();
sync_pb::EntitySpecifics pref_specifics;
AddDefaultFieldValue(PREFERENCES, &pref_specifics);
sync_pb::EntitySpecifics bm_specifics;
AddDefaultFieldValue(BOOKMARKS, &bm_specifics);
int pref1_meta =
MakeServerNode(share, PREFERENCES, "pref1", "hash1", pref_specifics);
int64_t pref2_meta = MakeNodeWithRoot(share, PREFERENCES, "pref2");
int pref3_meta =
MakeServerNode(share, PREFERENCES, "pref3", "hash3", pref_specifics);
int pref4_meta =
MakeServerNode(share, PREFERENCES, "pref4", "hash4", pref_specifics);
int pref5_meta =
MakeServerNode(share, PREFERENCES, "pref5", "hash5", pref_specifics);
int bookmark_meta =
MakeServerNode(share, BOOKMARKS, "bookmark", "", bm_specifics);
{
syncable::WriteTransaction trans(FROM_HERE, syncable::SYNCER,
share->directory.get());
// Pref's 1 and 2 are already set up properly.
// Locally delete pref 3.
syncable::MutableEntry pref3(&trans, GET_BY_HANDLE, pref3_meta);
pref3.PutIsDel(true);
pref3.PutIsUnsynced(true);
// Delete pref 4 at the server.
syncable::MutableEntry pref4(&trans, GET_BY_HANDLE, pref4_meta);
pref4.PutServerIsDel(true);
pref4.PutIsUnappliedUpdate(true);
pref4.PutServerVersion(2);
// Pref 5 is an new unapplied update.
syncable::MutableEntry pref5(&trans, GET_BY_HANDLE, pref5_meta);
pref5.PutIsUnappliedUpdate(true);
pref5.PutIsDel(true);
pref5.PutBaseVersion(-1);
// Bookmark is already set up properly
}
// Take a snapshot to clear all the dirty bits.
share->directory.get()->SaveChanges();
// Now request a purge for the unapplied types.
disabled_types.PutAll(unapplied_types);
sync_manager_.PurgeDisabledTypes(disabled_types, ModelTypeSet(),
unapplied_types);
// Verify the unapplied types still have progress markers and initial sync
// ended after cleanup.
EXPECT_TRUE(
sync_manager_.GetUserShare()->directory->InitialSyncEndedTypes().HasAll(
unapplied_types));
EXPECT_TRUE(
sync_manager_.GetTypesWithEmptyProgressMarkerToken(unapplied_types)
.Empty());
// Ensure the items were unapplied as necessary.
{
syncable::ReadTransaction trans(FROM_HERE, share->directory.get());
syncable::Entry pref_node(&trans, GET_BY_HANDLE, pref1_meta);
ASSERT_TRUE(pref_node.good());
EXPECT_TRUE(pref_node.GetKernelCopy().is_dirty());
EXPECT_FALSE(pref_node.GetIsUnsynced());
EXPECT_TRUE(pref_node.GetIsUnappliedUpdate());
EXPECT_TRUE(pref_node.GetIsDel());
EXPECT_GT(pref_node.GetServerVersion(), 0);
EXPECT_EQ(pref_node.GetBaseVersion(), -1);
// Pref 2 should just be locally deleted.
syncable::Entry pref2_node(&trans, GET_BY_HANDLE, pref2_meta);
ASSERT_TRUE(pref2_node.good());
EXPECT_TRUE(pref2_node.GetKernelCopy().is_dirty());
EXPECT_FALSE(pref2_node.GetIsUnsynced());
EXPECT_TRUE(pref2_node.GetIsDel());
EXPECT_FALSE(pref2_node.GetIsUnappliedUpdate());
EXPECT_TRUE(pref2_node.GetIsDel());
EXPECT_EQ(pref2_node.GetServerVersion(), 0);
EXPECT_EQ(pref2_node.GetBaseVersion(), -1);
syncable::Entry pref3_node(&trans, GET_BY_HANDLE, pref3_meta);
ASSERT_TRUE(pref3_node.good());
EXPECT_TRUE(pref3_node.GetKernelCopy().is_dirty());
EXPECT_FALSE(pref3_node.GetIsUnsynced());
EXPECT_TRUE(pref3_node.GetIsUnappliedUpdate());
EXPECT_TRUE(pref3_node.GetIsDel());
EXPECT_GT(pref3_node.GetServerVersion(), 0);
EXPECT_EQ(pref3_node.GetBaseVersion(), -1);
syncable::Entry pref4_node(&trans, GET_BY_HANDLE, pref4_meta);
ASSERT_TRUE(pref4_node.good());
EXPECT_TRUE(pref4_node.GetKernelCopy().is_dirty());
EXPECT_FALSE(pref4_node.GetIsUnsynced());
EXPECT_TRUE(pref4_node.GetIsUnappliedUpdate());
EXPECT_TRUE(pref4_node.GetIsDel());
EXPECT_GT(pref4_node.GetServerVersion(), 0);
EXPECT_EQ(pref4_node.GetBaseVersion(), -1);
// Pref 5 should remain untouched.
syncable::Entry pref5_node(&trans, GET_BY_HANDLE, pref5_meta);
ASSERT_TRUE(pref5_node.good());
EXPECT_FALSE(pref5_node.GetKernelCopy().is_dirty());
EXPECT_FALSE(pref5_node.GetIsUnsynced());
EXPECT_TRUE(pref5_node.GetIsUnappliedUpdate());
EXPECT_TRUE(pref5_node.GetIsDel());
EXPECT_GT(pref5_node.GetServerVersion(), 0);
EXPECT_EQ(pref5_node.GetBaseVersion(), -1);
syncable::Entry bookmark_node(&trans, GET_BY_HANDLE, bookmark_meta);
ASSERT_TRUE(bookmark_node.good());
EXPECT_TRUE(bookmark_node.GetKernelCopy().is_dirty());
EXPECT_FALSE(bookmark_node.GetIsUnsynced());
EXPECT_TRUE(bookmark_node.GetIsUnappliedUpdate());
EXPECT_TRUE(bookmark_node.GetIsDel());
EXPECT_GT(bookmark_node.GetServerVersion(), 0);
EXPECT_EQ(bookmark_node.GetBaseVersion(), -1);
}
}
// A test harness to exercise the code that processes and passes changes from
// the "SYNCER"-WriteTransaction destructor, through the SyncManager, to the
// ChangeProcessor.
class SyncManagerChangeProcessingTest : public SyncManagerTest {
public:
void OnChangesApplied(ModelType model_type,
int64_t model_version,
const BaseTransaction* trans,
const ImmutableChangeRecordList& changes) override {
last_changes_ = changes;
}
void OnChangesComplete(ModelType model_type) override {}
const ImmutableChangeRecordList& GetRecentChangeList() {
return last_changes_;
}
UserShare* share() { return sync_manager_.GetUserShare(); }
// Set some flags so our nodes reasonably approximate the real world scenario
// and can get past CheckTreeInvariants.
//
// It's never going to be truly accurate, since we're squashing update
// receipt, processing and application into a single transaction.
void SetNodeProperties(syncable::MutableEntry* entry) {
entry->PutId(id_factory_.NewServerId());
entry->PutBaseVersion(10);
entry->PutServerVersion(10);
}
// Looks for the given change in the list. Returns the index at which it was
// found. Returns -1 on lookup failure.
size_t FindChangeInList(int64_t id, ChangeRecord::Action action) {
SCOPED_TRACE(id);
for (size_t i = 0; i < last_changes_.Get().size(); ++i) {
if (last_changes_.Get()[i].id == id &&
last_changes_.Get()[i].action == action) {
return i;
}
}
ADD_FAILURE() << "Failed to find specified change";
return static_cast<size_t>(-1);
}
// Returns the current size of the change list.
//
// Note that spurious changes do not necessarily indicate a problem.
// Assertions on change list size can help detect problems, but it may be
// necessary to reduce their strictness if the implementation changes.
size_t GetChangeListSize() { return last_changes_.Get().size(); }
void ClearChangeList() { last_changes_ = ImmutableChangeRecordList(); }
protected:
ImmutableChangeRecordList last_changes_;
TestIdFactory id_factory_;
};
// Test creation of a folder and a bookmark.
TEST_F(SyncManagerChangeProcessingTest, AddBookmarks) {
int64_t type_root = GetIdForDataType(BOOKMARKS);
int64_t folder_id = kInvalidId;
int64_t child_id = kInvalidId;
// Create a folder and a bookmark under it.
{
syncable::WriteTransaction trans(FROM_HERE, syncable::SYNCER,
share()->directory.get());
syncable::Entry root(&trans, syncable::GET_BY_HANDLE, type_root);
ASSERT_TRUE(root.good());
syncable::MutableEntry folder(&trans, syncable::CREATE, BOOKMARKS,
root.GetId(), "folder");
ASSERT_TRUE(folder.good());
SetNodeProperties(&folder);
folder.PutIsDir(true);
folder_id = folder.GetMetahandle();
syncable::MutableEntry child(&trans, syncable::CREATE, BOOKMARKS,
folder.GetId(), "child");
ASSERT_TRUE(child.good());
SetNodeProperties(&child);
child_id = child.GetMetahandle();
}
// The closing of the above scope will delete the transaction. Its processed
// changes should be waiting for us in a member of the test harness.
EXPECT_EQ(2UL, GetChangeListSize());
// We don't need to check these return values here. The function will add a
// non-fatal failure if these changes are not found.
size_t folder_change_pos =
FindChangeInList(folder_id, ChangeRecord::ACTION_ADD);
size_t child_change_pos =
FindChangeInList(child_id, ChangeRecord::ACTION_ADD);
// Parents are delivered before children.
EXPECT_LT(folder_change_pos, child_change_pos);
}
// Test creation of a preferences (with implicit parent Id)
TEST_F(SyncManagerChangeProcessingTest, AddPreferences) {
int64_t item1_id = kInvalidId;
int64_t item2_id = kInvalidId;
// Create two preferences.
{
syncable::WriteTransaction trans(FROM_HERE, syncable::SYNCER,
share()->directory.get());
syncable::MutableEntry item1(&trans, syncable::CREATE, PREFERENCES,
"test_item_1");
ASSERT_TRUE(item1.good());
SetNodeProperties(&item1);
item1_id = item1.GetMetahandle();
// Need at least two items to ensure hitting all possible codepaths in
// ChangeReorderBuffer::Traversal::ExpandToInclude.
syncable::MutableEntry item2(&trans, syncable::CREATE, PREFERENCES,
"test_item_2");
ASSERT_TRUE(item2.good());
SetNodeProperties(&item2);
item2_id = item2.GetMetahandle();
}
// The closing of the above scope will delete the transaction. Its processed
// changes should be waiting for us in a member of the test harness.
EXPECT_EQ(2UL, GetChangeListSize());
FindChangeInList(item1_id, ChangeRecord::ACTION_ADD);
FindChangeInList(item2_id, ChangeRecord::ACTION_ADD);
}
// Test moving a bookmark into an empty folder.
TEST_F(SyncManagerChangeProcessingTest, MoveBookmarkIntoEmptyFolder) {
int64_t type_root = GetIdForDataType(BOOKMARKS);
int64_t folder_b_id = kInvalidId;
int64_t child_id = kInvalidId;
// Create two folders. Place a child under folder A.
{
syncable::WriteTransaction trans(FROM_HERE, syncable::SYNCER,
share()->directory.get());
syncable::Entry root(&trans, syncable::GET_BY_HANDLE, type_root);
ASSERT_TRUE(root.good());
syncable::MutableEntry folder_a(&trans, syncable::CREATE, BOOKMARKS,
root.GetId(), "folderA");
ASSERT_TRUE(folder_a.good());
SetNodeProperties(&folder_a);
folder_a.PutIsDir(true);
syncable::MutableEntry folder_b(&trans, syncable::CREATE, BOOKMARKS,
root.GetId(), "folderB");
ASSERT_TRUE(folder_b.good());
SetNodeProperties(&folder_b);
folder_b.PutIsDir(true);
folder_b_id = folder_b.GetMetahandle();
syncable::MutableEntry child(&trans, syncable::CREATE, BOOKMARKS,
folder_a.GetId(), "child");
ASSERT_TRUE(child.good());
SetNodeProperties(&child);
child_id = child.GetMetahandle();
}
// Close that transaction. The above was to setup the initial scenario. The
// real test starts now.
// Move the child from folder A to folder B.
{
syncable::WriteTransaction trans(FROM_HERE, syncable::SYNCER,
share()->directory.get());
syncable::Entry folder_b(&trans, syncable::GET_BY_HANDLE, folder_b_id);
syncable::MutableEntry child(&trans, syncable::GET_BY_HANDLE, child_id);
child.PutParentId(folder_b.GetId());
}
EXPECT_EQ(1UL, GetChangeListSize());
// Verify that this was detected as a real change. An early version of the
// UniquePosition code had a bug where moves from one folder to another were
// ignored unless the moved node's UniquePosition value was also changed in
// some way.
FindChangeInList(child_id, ChangeRecord::ACTION_UPDATE);
}
// Test moving a bookmark into a non-empty folder.
TEST_F(SyncManagerChangeProcessingTest, MoveIntoPopulatedFolder) {
int64_t type_root = GetIdForDataType(BOOKMARKS);
int64_t child_a_id = kInvalidId;
int64_t child_b_id = kInvalidId;
// Create two folders. Place one child each under folder A and folder B.
{
syncable::WriteTransaction trans(FROM_HERE, syncable::SYNCER,
share()->directory.get());
syncable::Entry root(&trans, syncable::GET_BY_HANDLE, type_root);
ASSERT_TRUE(root.good());
syncable::MutableEntry folder_a(&trans, syncable::CREATE, BOOKMARKS,
root.GetId(), "folderA");
ASSERT_TRUE(folder_a.good());
SetNodeProperties(&folder_a);
folder_a.PutIsDir(true);
syncable::MutableEntry folder_b(&trans, syncable::CREATE, BOOKMARKS,
root.GetId(), "folderB");
ASSERT_TRUE(folder_b.good());
SetNodeProperties(&folder_b);
folder_b.PutIsDir(true);
syncable::MutableEntry child_a(&trans, syncable::CREATE, BOOKMARKS,
folder_a.GetId(), "childA");
ASSERT_TRUE(child_a.good());
SetNodeProperties(&child_a);
child_a_id = child_a.GetMetahandle();
syncable::MutableEntry child_b(&trans, syncable::CREATE, BOOKMARKS,
folder_b.GetId(), "childB");
SetNodeProperties(&child_b);
child_b_id = child_b.GetMetahandle();
}
// Close that transaction. The above was to setup the initial scenario. The
// real test starts now.
{
syncable::WriteTransaction trans(FROM_HERE, syncable::SYNCER,
share()->directory.get());
syncable::MutableEntry child_a(&trans, syncable::GET_BY_HANDLE, child_a_id);
syncable::MutableEntry child_b(&trans, syncable::GET_BY_HANDLE, child_b_id);
// Move child A from folder A to folder B and update its position.
child_a.PutParentId(child_b.GetParentId());
child_a.PutPredecessor(child_b.GetId());
}
EXPECT_EQ(1UL, GetChangeListSize());
// Verify that only child a is in the change list.
// (This function will add a failure if the lookup fails.)
FindChangeInList(child_a_id, ChangeRecord::ACTION_UPDATE);
}
// Tests the ordering of deletion changes.
TEST_F(SyncManagerChangeProcessingTest, DeletionsAndChanges) {
int64_t type_root = GetIdForDataType(BOOKMARKS);
int64_t folder_a_id = kInvalidId;
int64_t folder_b_id = kInvalidId;
int64_t child_id = kInvalidId;
// Create two folders. Place a child under folder A.
{
syncable::WriteTransaction trans(FROM_HERE, syncable::SYNCER,
share()->directory.get());
syncable::Entry root(&trans, syncable::GET_BY_HANDLE, type_root);
ASSERT_TRUE(root.good());
syncable::MutableEntry folder_a(&trans, syncable::CREATE, BOOKMARKS,
root.GetId(), "folderA");
ASSERT_TRUE(folder_a.good());
SetNodeProperties(&folder_a);
folder_a.PutIsDir(true);
folder_a_id = folder_a.GetMetahandle();
syncable::MutableEntry folder_b(&trans, syncable::CREATE, BOOKMARKS,
root.GetId(), "folderB");
ASSERT_TRUE(folder_b.good());
SetNodeProperties(&folder_b);
folder_b.PutIsDir(true);
folder_b_id = folder_b.GetMetahandle();
syncable::MutableEntry child(&trans, syncable::CREATE, BOOKMARKS,
folder_a.GetId(), "child");
ASSERT_TRUE(child.good());
SetNodeProperties(&child);
child_id = child.GetMetahandle();
}
// Close that transaction. The above was to setup the initial scenario. The
// real test starts now.
{
syncable::WriteTransaction trans(FROM_HERE, syncable::SYNCER,
share()->directory.get());
syncable::MutableEntry folder_a(&trans, syncable::GET_BY_HANDLE,
folder_a_id);
syncable::MutableEntry folder_b(&trans, syncable::GET_BY_HANDLE,
folder_b_id);
syncable::MutableEntry child(&trans, syncable::GET_BY_HANDLE, child_id);
// Delete folder B and its child.
child.PutIsDel(true);
folder_b.PutIsDel(true);
// Make an unrelated change to folder A.
folder_a.PutNonUniqueName("NewNameA");
}
EXPECT_EQ(3UL, GetChangeListSize());
size_t folder_a_pos =
FindChangeInList(folder_a_id, ChangeRecord::ACTION_UPDATE);
size_t folder_b_pos =
FindChangeInList(folder_b_id, ChangeRecord::ACTION_DELETE);
size_t child_pos = FindChangeInList(child_id, ChangeRecord::ACTION_DELETE);
// Deletes should appear before updates.
EXPECT_LT(child_pos, folder_a_pos);
EXPECT_LT(folder_b_pos, folder_a_pos);
}
// See that attachment metadata changes are not filtered out by
// SyncManagerImpl::VisiblePropertiesDiffer.
TEST_F(SyncManagerChangeProcessingTest, AttachmentMetadataOnlyChanges) {
// Create an article with no attachments. See that a change is generated.
int64_t article_id = kInvalidId;
{
syncable::WriteTransaction trans(FROM_HERE, syncable::SYNCER,
share()->directory.get());
int64_t type_root = GetIdForDataType(ARTICLES);
syncable::Entry root(&trans, syncable::GET_BY_HANDLE, type_root);
ASSERT_TRUE(root.good());
syncable::MutableEntry article(&trans, syncable::CREATE, ARTICLES,
root.GetId(), "article");
ASSERT_TRUE(article.good());
SetNodeProperties(&article);
article_id = article.GetMetahandle();
}
ASSERT_EQ(1UL, GetChangeListSize());
FindChangeInList(article_id, ChangeRecord::ACTION_ADD);
ClearChangeList();
// Modify the article by adding one attachment. Don't touch anything else.
// See that a change is generated.
{
syncable::WriteTransaction trans(FROM_HERE, syncable::SYNCER,
share()->directory.get());
syncable::MutableEntry article(&trans, syncable::GET_BY_HANDLE, article_id);
sync_pb::AttachmentMetadata metadata;
*metadata.add_record()->mutable_id() = CreateAttachmentIdProto(0, 0);
article.PutAttachmentMetadata(metadata);
}
ASSERT_EQ(1UL, GetChangeListSize());
FindChangeInList(article_id, ChangeRecord::ACTION_UPDATE);
ClearChangeList();
// Modify the article by replacing its attachment with a different one. See
// that a change is generated.
{
syncable::WriteTransaction trans(FROM_HERE, syncable::SYNCER,
share()->directory.get());
syncable::MutableEntry article(&trans, syncable::GET_BY_HANDLE, article_id);
sync_pb::AttachmentMetadata metadata = article.GetAttachmentMetadata();
*metadata.add_record()->mutable_id() = CreateAttachmentIdProto(0, 0);
article.PutAttachmentMetadata(metadata);
}
ASSERT_EQ(1UL, GetChangeListSize());
FindChangeInList(article_id, ChangeRecord::ACTION_UPDATE);
ClearChangeList();
// Modify the article by replacing its attachment metadata with the same
// attachment metadata. No change should be generated.
{
syncable::WriteTransaction trans(FROM_HERE, syncable::SYNCER,
share()->directory.get());
syncable::MutableEntry article(&trans, syncable::GET_BY_HANDLE, article_id);
article.PutAttachmentMetadata(article.GetAttachmentMetadata());
}
ASSERT_EQ(0UL, GetChangeListSize());
}
// During initialization SyncManagerImpl loads sqlite database. If it fails to
// do so it should fail initialization. This test verifies this behavior.
// Test reuses SyncManagerImpl initialization from SyncManagerTest but overrides
// EngineComponentsFactory to return DirectoryBackingStore that always fails
// to load.
class SyncManagerInitInvalidStorageTest : public SyncManagerTest {
public:
SyncManagerInitInvalidStorageTest() {}
EngineComponentsFactory* GetFactory() override {
return new TestEngineComponentsFactory(
GetSwitches(), EngineComponentsFactory::STORAGE_INVALID,
&storage_used_);
}
};
// SyncManagerInitInvalidStorageTest::GetFactory will return
// DirectoryBackingStore that ensures that SyncManagerImpl::OpenDirectory fails.
// SyncManagerImpl initialization is done in SyncManagerTest::SetUp. This test's
// task is to ensure that SyncManagerImpl reported initialization failure in
// OnInitializationComplete callback.
TEST_F(SyncManagerInitInvalidStorageTest, FailToOpenDatabase) {
EXPECT_FALSE(initialization_succeeded_);
}
} // namespace syncer
|