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
|
// Copyright 2015 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ui/webui/settings/people_handler.h"
#include <memory>
#include <string>
#include <vector>
#include "base/command_line.h"
#include "base/functional/bind.h"
#include "base/functional/callback_helpers.h"
#include "base/i18n/time_formatting.h"
#include "base/json/json_writer.h"
#include "base/memory/raw_ptr.h"
#include "base/strings/utf_string_conversions.h"
#include "base/test/metrics/histogram_tester.h"
#include "base/test/mock_callback.h"
#include "base/test/scoped_feature_list.h"
#include "base/values.h"
#include "build/build_config.h"
#include "chrome/browser/defaults.h"
#include "chrome/browser/first_run/first_run.h"
#include "chrome/browser/signin/account_consistency_mode_manager.h"
#include "chrome/browser/signin/chrome_signin_client_factory.h"
#include "chrome/browser/signin/chrome_signin_client_test_util.h"
#include "chrome/browser/signin/dice_web_signin_interceptor.h"
#include "chrome/browser/signin/identity_test_environment_profile_adaptor.h"
#include "chrome/browser/signin/signin_error_controller_factory.h"
#include "chrome/browser/signin/signin_ui_delegate.h"
#include "chrome/browser/signin/signin_ui_util.h"
#include "chrome/browser/signin/signin_util.h"
#include "chrome/browser/sync/sync_service_factory.h"
#include "chrome/browser/ui/browser_finder.h"
#include "chrome/browser/ui/browser_window/public/browser_window_features.h"
#include "chrome/browser/ui/chrome_pages.h"
#include "chrome/browser/ui/signin/signin_view_controller.h"
#include "chrome/browser/ui/webui/signin/login_ui_service.h"
#include "chrome/browser/ui/webui/signin/login_ui_service_factory.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/pref_names.h"
#include "chrome/common/url_constants.h"
#include "chrome/test/base/browser_with_test_window_test.h"
#include "chrome/test/base/scoped_testing_local_state.h"
#include "chrome/test/base/test_chrome_web_ui_controller_factory.h"
#include "chrome/test/base/testing_browser_process.h"
#include "chrome/test/base/testing_profile.h"
#include "components/prefs/pref_service.h"
#include "components/signin/public/base/account_consistency_method.h"
#include "components/signin/public/base/consent_level.h"
#include "components/signin/public/base/signin_pref_names.h"
#include "components/signin/public/base/signin_prefs.h"
#include "components/signin/public/identity_manager/account_capabilities_test_mutator.h"
#include "components/signin/public/identity_manager/accounts_mutator.h"
#include "components/signin/public/identity_manager/identity_manager.h"
#include "components/signin/public/identity_manager/identity_test_environment.h"
#include "components/signin/public/identity_manager/identity_test_utils.h"
#include "components/signin/public/identity_manager/primary_account_mutator.h"
#include "components/sync/base/passphrase_enums.h"
#include "components/sync/base/user_selectable_type.h"
#include "components/sync/service/sync_user_settings_impl.h"
#include "components/sync/test/test_sync_service.h"
#include "content/public/browser/web_contents.h"
#include "content/public/browser/web_ui.h"
#include "content/public/browser/web_ui_controller.h"
#include "content/public/test/browser_task_environment.h"
#include "content/public/test/navigation_simulator.h"
#include "content/public/test/scoped_web_ui_controller_factory_registration.h"
#include "content/public/test/test_web_contents_factory.h"
#include "content/public/test/test_web_ui.h"
#include "content/public/test/web_contents_tester.h"
#include "google_apis/gaia/gaia_urls.h"
#include "services/network/test/test_url_loader_factory.h"
#include "testing/gtest/include/gtest/gtest.h"
#if BUILDFLAG(IS_CHROMEOS)
#include "ash/constants/ash_features.h"
#include "chrome/test/base/chrome_render_view_host_test_harness.h"
#endif // BUILDFLAG(IS_CHROMEOS)
namespace {
using signin::ConsentLevel;
using signin_util::SignedInState;
using ::testing::_;
using ::testing::ByMove;
using ::testing::Const;
using ::testing::Invoke;
using ::testing::IsEmpty;
using ::testing::Mock;
using ::testing::Return;
using ::testing::Values;
constexpr char kTestUser[] = "chrome_p13n_test@gmail.com";
constexpr char kTestCallbackId[] = "test-callback-id";
#if BUILDFLAG(ENABLE_DICE_SUPPORT)
// Event fired when calling
// `PeopleHandler::UpdateChromeSigninUserChoiceInfo()`.
constexpr char kChromeSigninUserChoiceInfoChangeEventName[] =
"chrome-signin-user-choice-info-change";
// Event fired when calling `PeopleHandler::UpdateSyncStatus()`.
constexpr char kSyncStatusChangeEventName[] = "sync-status-changed";
class MockSigninUiDelegate : public signin_ui_util::SigninUiDelegate {
public:
MOCK_METHOD(void,
ShowTurnSyncOnUI,
(Profile*,
signin_metrics::AccessPoint,
signin_metrics::PromoAction,
const CoreAccountId&,
TurnSyncOnHelper::SigninAbortedMode,
bool,
bool),
(override));
MOCK_METHOD(void,
ShowSigninUI,
(Profile*,
bool,
signin_metrics::AccessPoint,
signin_metrics::PromoAction),
(override));
MOCK_METHOD(void,
ShowReauthUI,
(Profile*,
const std::string&,
bool,
signin_metrics::AccessPoint,
signin_metrics::PromoAction),
(override));
};
#endif
// Returns a UserSelectableTypeSet with all types set.
syncer::UserSelectableTypeSet GetAllTypes() {
return syncer::UserSelectableTypeSet::All();
}
enum SyncAllDataConfig { SYNC_ALL_DATA, CHOOSE_WHAT_TO_SYNC };
// Create a json-format string with the key/value pairs appropriate for a call
// to HandleSetDatatypes().
std::string GetConfiguration(SyncAllDataConfig sync_all,
syncer::UserSelectableTypeSet types) {
base::Value::Dict result;
result.Set("syncAllDataTypes", sync_all == SYNC_ALL_DATA);
// Add all of our data types.
result.Set("appsSynced", types.Has(syncer::UserSelectableType::kApps));
result.Set("autofillSynced",
types.Has(syncer::UserSelectableType::kAutofill));
result.Set("bookmarksSynced",
types.Has(syncer::UserSelectableType::kBookmarks));
result.Set("cookiesSynced", types.Has(syncer::UserSelectableType::kCookies));
result.Set("extensionsSynced",
types.Has(syncer::UserSelectableType::kExtensions));
result.Set("passwordsSynced",
types.Has(syncer::UserSelectableType::kPasswords));
result.Set("paymentsSynced",
types.Has(syncer::UserSelectableType::kPayments));
result.Set("preferencesSynced",
types.Has(syncer::UserSelectableType::kPreferences));
result.Set("productComparisonSynced",
types.Has(syncer::UserSelectableType::kProductComparison));
result.Set("readingListSynced",
types.Has(syncer::UserSelectableType::kReadingList));
result.Set("savedTabGroupsSynced",
types.Has(syncer::UserSelectableType::kSavedTabGroups));
result.Set("tabsSynced", types.Has(syncer::UserSelectableType::kTabs));
result.Set("themesSynced", types.Has(syncer::UserSelectableType::kThemes));
result.Set("typedUrlsSynced",
types.Has(syncer::UserSelectableType::kHistory));
std::string args;
base::JSONWriter::Write(result, &args);
return args;
}
// Checks whether the passed |dictionary| contains a |key| with the given
// |expected_value|. This will fail if the key isn't present, even if
// |expected_value| is false.
void ExpectHasBoolKey(const base::Value::Dict& dictionary,
const std::string& key,
bool expected_value) {
ASSERT_TRUE(dictionary.contains(key)) << "No value found for " << key;
ASSERT_TRUE(dictionary.FindBool(key).has_value()) << key << " has wrong type";
EXPECT_EQ(expected_value, *dictionary.FindBool(key))
<< "Mismatch found for " << key;
}
// Checks to make sure that the values stored in |dictionary| match the values
// expected by the showSyncSetupPage() JS function for a given set of data
// types.
void CheckConfigDataTypeArguments(const base::Value::Dict& dictionary,
SyncAllDataConfig config,
syncer::UserSelectableTypeSet types) {
ExpectHasBoolKey(dictionary, "syncAllDataTypes", config == SYNC_ALL_DATA);
ExpectHasBoolKey(dictionary, "appsSynced",
types.Has(syncer::UserSelectableType::kApps));
ExpectHasBoolKey(dictionary, "autofillSynced",
types.Has(syncer::UserSelectableType::kAutofill));
ExpectHasBoolKey(dictionary, "bookmarksSynced",
types.Has(syncer::UserSelectableType::kBookmarks));
ExpectHasBoolKey(dictionary, "cookiesSynced",
types.Has(syncer::UserSelectableType::kCookies));
ExpectHasBoolKey(dictionary, "extensionsSynced",
types.Has(syncer::UserSelectableType::kExtensions));
ExpectHasBoolKey(dictionary, "passwordsSynced",
types.Has(syncer::UserSelectableType::kPasswords));
ExpectHasBoolKey(dictionary, "preferencesSynced",
types.Has(syncer::UserSelectableType::kPreferences));
ExpectHasBoolKey(dictionary, "readingListSynced",
types.Has(syncer::UserSelectableType::kReadingList));
ExpectHasBoolKey(dictionary, "savedTabGroupsSynced",
types.Has(syncer::UserSelectableType::kSavedTabGroups));
ExpectHasBoolKey(dictionary, "tabsSynced",
types.Has(syncer::UserSelectableType::kTabs));
ExpectHasBoolKey(dictionary, "themesSynced",
types.Has(syncer::UserSelectableType::kThemes));
ExpectHasBoolKey(dictionary, "typedUrlsSynced",
types.Has(syncer::UserSelectableType::kHistory));
}
std::unique_ptr<KeyedService> BuildTestSyncService(
content::BrowserContext* context) {
return std::make_unique<syncer::TestSyncService>();
}
} // namespace
namespace settings {
class TestingPeopleHandler : public PeopleHandler {
public:
TestingPeopleHandler(content::WebUI* web_ui, Profile* profile)
: PeopleHandler(profile) {
set_web_ui(web_ui);
}
TestingPeopleHandler(const TestingPeopleHandler&) = delete;
TestingPeopleHandler& operator=(const TestingPeopleHandler&) = delete;
using PeopleHandler::is_configuring_sync;
};
class PeopleHandlerTest
#if BUILDFLAG(IS_CHROMEOS)
// ChromeRenderViewHostTestHarness is flaky, but is required on ChromeOS
// because `TestWebContentsFactory` does not work out of the box.
: public ChromeRenderViewHostTestHarness {
#else
: public testing::Test {
#endif
public:
PeopleHandlerTest() = default;
PeopleHandlerTest(const PeopleHandlerTest&) = delete;
PeopleHandlerTest& operator=(const PeopleHandlerTest&) = delete;
~PeopleHandlerTest() override = default;
void SetUp() override {
#if BUILDFLAG(IS_CHROMEOS)
ChromeRenderViewHostTestHarness::SetUp();
#else
profile_ = IdentityTestEnvironmentProfileAdaptor::
CreateProfileForIdentityTestEnvironment();
#endif
identity_test_env_adaptor_ =
std::make_unique<IdentityTestEnvironmentProfileAdaptor>(profile());
sync_service_ = static_cast<syncer::TestSyncService*>(
SyncServiceFactory::GetInstance()->SetTestingFactoryAndUse(
profile(), base::BindRepeating(&BuildTestSyncService)));
sync_service_->SetSignedOut();
}
void TearDown() override {
sync_service_ = nullptr;
DestroyPeopleHandler();
identity_test_env_adaptor_.reset();
#if BUILDFLAG(IS_CHROMEOS)
ChromeRenderViewHostTestHarness::TearDown();
#endif
}
#if BUILDFLAG(IS_CHROMEOS)
TestingProfile::TestingFactories GetTestingFactories() const override {
return IdentityTestEnvironmentProfileAdaptor::
GetIdentityTestEnvironmentFactories();
}
#endif
void SigninUserWithoutSyncFeature() {
const CoreAccountInfo account_info = identity_test_env()->SetPrimaryAccount(
kTestUser, signin::ConsentLevel::kSignin);
sync_service_->SetSignedIn(signin::ConsentLevel::kSignin, account_info);
}
void SigninUserAndTurnSyncFeatureOn() {
const CoreAccountInfo account_info = identity_test_env()->SetPrimaryAccount(
kTestUser, signin::ConsentLevel::kSync);
sync_service_->SetSignedIn(signin::ConsentLevel::kSync, account_info);
}
void CreatePeopleHandler() {
handler_ = std::make_unique<TestingPeopleHandler>(&web_ui_, profile());
handler_->AllowJavascript();
#if !BUILDFLAG(IS_CHROMEOS)
web_contents_ = web_contents_factory_.CreateWebContents(profile());
#endif
web_ui_.set_web_contents(web_contents());
handler_->RegisterMessages();
}
void DestroyPeopleHandler() {
if (handler_) {
handler_->set_web_ui(nullptr);
handler_->DisallowJavascript();
handler_ = nullptr;
#if !BUILDFLAG(IS_CHROMEOS)
web_contents_ = nullptr;
#endif
}
}
void ExpectPageStatusResponse(const std::string& expected_status) {
auto& data = *web_ui_.call_data().back();
EXPECT_EQ("cr.webUIResponse", data.function_name());
ASSERT_TRUE(data.arg1()->is_string());
EXPECT_EQ(kTestCallbackId, data.arg1()->GetString());
ASSERT_TRUE(data.arg2()->is_bool());
EXPECT_TRUE(data.arg2()->GetBool());
ASSERT_TRUE(data.arg3()->is_string());
EXPECT_EQ(expected_status, data.arg3()->GetString());
}
// Expects a call to ResolveJavascriptCallback() with |should_succeed| as its
// argument.
void ExpectSetPassphraseSuccess(bool should_succeed) {
EXPECT_EQ(1u, web_ui_.call_data().size());
const auto& data = *web_ui_.call_data()[0];
EXPECT_EQ("cr.webUIResponse", data.function_name());
EXPECT_TRUE(data.arg2()->is_bool());
EXPECT_TRUE(data.arg2()->GetBool())
<< "Callback should be resolved with a boolean indicating the success, "
"never rejected.";
EXPECT_TRUE(data.arg3()->is_bool());
EXPECT_EQ(should_succeed, data.arg3()->GetBool());
}
std::vector<const base::Value*> GetAllFiredValuesForEventName(
const std::string& event_name) {
std::vector<const base::Value*> arguments;
for (const std::unique_ptr<content::TestWebUI::CallData>& data :
web_ui_.call_data()) {
if (data->function_name() == "cr.webUIListenerCallback" &&
data->arg1()->is_string() &&
data->arg1()->GetString() == event_name) {
arguments.push_back(data->arg2());
}
}
return arguments;
}
// Returns all fired sync-prefs-changed events, without any validation.
std::vector<const base::Value*> GetFiredSyncPrefsChanged() {
return GetAllFiredValuesForEventName("sync-prefs-changed");
}
// Must be called at most once per test to check if a sync-prefs-changed
// event happened. Returns the single fired value.
base::Value::Dict ExpectSyncPrefsChanged() {
std::vector<const base::Value*> args = GetFiredSyncPrefsChanged();
EXPECT_EQ(1U, args.size());
EXPECT_NE(args[0], nullptr);
EXPECT_TRUE(args[0]->is_dict());
return args[0]->GetDict().Clone();
}
// Must be called at most once per test to check if a sync-status-changed
// event happened. Returns the single fired value.
base::Value::Dict ExpectSyncStatusChanged() {
std::vector<const base::Value*> args =
GetAllFiredValuesForEventName("sync-status-changed");
EXPECT_EQ(1U, args.size());
EXPECT_NE(args[0], nullptr);
EXPECT_TRUE(args[0]->is_dict());
return args[0]->GetDict().Clone();
}
signin::IdentityTestEnvironment* identity_test_env() {
return identity_test_env_adaptor_->identity_test_env();
}
signin::IdentityManager* identity_manager() {
return identity_test_env()->identity_manager();
}
syncer::TestSyncUserSettings* sync_user_settings() {
return sync_service_->GetUserSettings();
}
#if BUILDFLAG(ENABLE_DICE_SUPPORT)
// Checks values returned as a response of WebUI called.
void ExpectChromeSigninUserChoiceInfoFromWebUiResponse(
bool should_show_settings,
ChromeSigninUserChoice expected_choice,
const std::string& expected_signed_in_email) {
auto& data = *web_ui_.call_data().back();
EXPECT_EQ("cr.webUIResponse", data.function_name());
ASSERT_TRUE(data.arg1()->is_string());
EXPECT_EQ(kTestCallbackId, data.arg1()->GetString());
ASSERT_TRUE(data.arg2()->is_bool());
EXPECT_TRUE(data.arg2()->GetBool())
<< "Callback should be resolved with a boolean indicating the success, "
"never rejected.";
ASSERT_TRUE(data.arg3()->is_dict());
const base::Value::Dict& dict = data.arg3()->GetDict();
ExpectChromeSigninUserChoiceInfoDict(
dict, should_show_settings, expected_choice, expected_signed_in_email);
}
// Checks values returned from firing the change event.
// Reads the last event. Expecting at least one event.
void ExpectChromeSigninUserChoiceInfoFromLastChangeEvent(
bool should_show_settings,
ChromeSigninUserChoice expected_choice,
const std::string& expected_signed_in_email) {
auto values_list = GetAllFiredValuesForEventName(
kChromeSigninUserChoiceInfoChangeEventName);
ASSERT_GT(values_list.size(), 0U);
size_t last_index = values_list.size() - 1;
ASSERT_TRUE(values_list[last_index]);
ASSERT_TRUE(values_list[last_index]->is_dict());
const base::Value::Dict& values_dict = values_list[last_index]->GetDict();
ExpectChromeSigninUserChoiceInfoDict(values_dict, should_show_settings,
expected_choice,
expected_signed_in_email);
}
// Tests the Dict content returned for the WebUI for
// ChromeSigninUserChoiceInfo.
static void ExpectChromeSigninUserChoiceInfoDict(
const base::Value::Dict& values_dict,
bool expected_should_show_settings,
ChromeSigninUserChoice expected_choice,
const std::string& expected_signed_in_email) {
std::optional<bool> should_show_settings =
values_dict.FindBool("shouldShowSettings");
ASSERT_TRUE(should_show_settings.has_value());
EXPECT_EQ(should_show_settings.value(), expected_should_show_settings);
std::optional<int> choice_int = values_dict.FindInt("choice");
ASSERT_TRUE(choice_int.has_value());
EXPECT_EQ(static_cast<ChromeSigninUserChoice>(choice_int.value()),
expected_choice);
const std::string* signed_in_email =
values_dict.FindString("signedInEmail");
ASSERT_TRUE(signed_in_email);
EXPECT_EQ(*signed_in_email, expected_signed_in_email);
}
bool HasChromeSigninUserChoiceInfoChangeEvent() {
return !GetAllFiredValuesForEventName(
kChromeSigninUserChoiceInfoChangeEventName)
.empty();
}
void SetExplicitSignin(bool value) {
profile()->GetPrefs()->SetBoolean(prefs::kExplicitBrowserSignin, value);
}
void TriggerPrimaryAccountInPersistentError() {
ASSERT_TRUE(identity_manager()->HasPrimaryAccount(ConsentLevel::kSignin));
// Inject the error.
identity_test_env()->SetInvalidRefreshTokenForPrimaryAccount();
}
bool HasSyncStatusUpdateChangedEvent() {
return !GetAllFiredValuesForEventName(kSyncStatusChangeEventName).empty();
}
void SimluateReauth() {
ASSERT_TRUE(
identity_manager()->HasPrimaryAccount(signin::ConsentLevel::kSignin));
// Clear the error.
identity_test_env()->SetRefreshTokenForPrimaryAccount();
}
void SimulateSignout() {
ASSERT_TRUE(
identity_manager()->HasPrimaryAccount(signin::ConsentLevel::kSignin));
identity_test_env()->ClearPrimaryAccount();
}
void SimulateHandleGetChromeSigninUserChoiceInfo() const {
base::Value::List args_get;
args_get.Append(kTestCallbackId);
handler_->HandleGetChromeSigninUserChoiceInfo(args_get);
}
void SimulateHandleSetChromeSigninUserChoiceInfo(
std::string_view email,
ChromeSigninUserChoice user_choice) {
base::Value::List args_set;
args_set.Append(static_cast<int>(user_choice));
args_set.Append(email);
handler_->HandleSetChromeSigninUserChoice(args_set);
}
#endif // BUILDFLAG(ENABLE_DICE_SUPPORT)
#if !BUILDFLAG(IS_CHROMEOS)
Profile* profile() { return profile_.get(); }
content::WebContents* web_contents() { return web_contents_; }
content::BrowserTaskEnvironment task_environment_;
#endif
std::unique_ptr<IdentityTestEnvironmentProfileAdaptor>
identity_test_env_adaptor_;
#if !BUILDFLAG(IS_CHROMEOS)
std::unique_ptr<TestingProfile> profile_;
content::TestWebContentsFactory web_contents_factory_;
raw_ptr<content::WebContents> web_contents_ = nullptr;
#endif
raw_ptr<syncer::TestSyncService> sync_service_;
content::TestWebUI web_ui_;
std::unique_ptr<TestingPeopleHandler> handler_;
base::test::ScopedFeatureList feature_list_;
};
#if !BUILDFLAG(IS_CHROMEOS)
TEST_F(PeopleHandlerTest, DisplayBasicLogin) {
testing::StrictMock<MockSigninUiDelegate> mock_signin_ui_delegate;
base::AutoReset<signin_ui_util::SigninUiDelegate*> delegate_auto_reset =
signin_ui_util::SetSigninUiDelegateForTesting(&mock_signin_ui_delegate);
ASSERT_FALSE(identity_test_env()->identity_manager()->HasPrimaryAccount(
ConsentLevel::kSignin));
CreatePeopleHandler();
// Test that the HandleStartSignin call enables JavaScript.
handler_->DisallowJavascript();
EXPECT_CALL(mock_signin_ui_delegate,
ShowSigninUI(profile(), /*enable_sync=*/true,
signin_metrics::AccessPoint::kSettings,
signin_metrics::PromoAction::
PROMO_ACTION_NEW_ACCOUNT_NO_EXISTING_ACCOUNT));
handler_->HandleStartSignin(base::Value::List());
// Sync setup hands off control to the gaia login tab.
EXPECT_EQ(
nullptr,
LoginUIServiceFactory::GetForProfile(profile())->current_login_ui());
ASSERT_FALSE(handler_->is_configuring_sync());
handler_->CloseSyncSetup();
EXPECT_EQ(
nullptr,
LoginUIServiceFactory::GetForProfile(profile())->current_login_ui());
}
#endif // !BUILDFLAG(IS_CHROMEOS)
TEST_F(PeopleHandlerTest, DisplayConfigureWithEngineDisabledAndCancel) {
SigninUserAndTurnSyncFeatureOn();
sync_user_settings()->ClearInitialSyncFeatureSetupComplete();
CreatePeopleHandler();
ASSERT_THAT(sync_service_->GetDisableReasons(), IsEmpty());
sync_service_->SetMaxTransportState(
syncer::SyncService::TransportState::INITIALIZING);
// We're simulating a user setting up sync, which would cause the engine to
// kick off initialization, but not download user data types. The sync
// engine will try to download control data types (e.g encryption info), but
// that won't finish for this test as we're simulating cancelling while the
// spinner is showing.
handler_->HandleShowSyncSetupUI(base::Value::List());
EXPECT_EQ(
handler_.get(),
LoginUIServiceFactory::GetForProfile(profile())->current_login_ui());
EXPECT_EQ(0U, web_ui_.call_data().size());
handler_->CloseSyncSetup();
EXPECT_EQ(
nullptr,
LoginUIServiceFactory::GetForProfile(profile())->current_login_ui());
}
// Verifies that the handler only sends the sync pref updates once the engine is
// initialized.
TEST_F(PeopleHandlerTest,
DisplayConfigureWithEngineDisabledAndSyncStartupCompleted) {
SigninUserAndTurnSyncFeatureOn();
sync_user_settings()->ClearInitialSyncFeatureSetupComplete();
CreatePeopleHandler();
ASSERT_THAT(sync_service_->GetDisableReasons(), IsEmpty());
// Sync engine is stopped initially, and will start up.
sync_service_->SetMaxTransportState(
syncer::SyncService::TransportState::START_DEFERRED);
handler_->HandleShowSyncSetupUI(base::Value::List());
// Mimic engine initialization.
sync_service_->SetMaxTransportState(
syncer::SyncService::TransportState::INITIALIZING);
sync_service_->FireStateChanged();
// No pref updates sent yet, because the engine is not initialized.
EXPECT_EQ(0U, GetFiredSyncPrefsChanged().size());
web_ui_.ClearTrackedCalls();
// Now, act as if the SyncService has started up.
sync_service_->SetMaxTransportState(
syncer::SyncService::TransportState::ACTIVE);
sync_service_->FireStateChanged();
// Updates for the sync status, sync prefs, trusted vault opt-in and stored
// accounts are sent.
EXPECT_EQ(4U, web_ui_.call_data().size());
base::Value::Dict dictionary = ExpectSyncPrefsChanged();
ExpectHasBoolKey(dictionary, "syncAllDataTypes", true);
ExpectHasBoolKey(dictionary, "customPassphraseAllowed", true);
ExpectHasBoolKey(dictionary, "encryptAllData", false);
ExpectHasBoolKey(dictionary, "passphraseRequired", false);
ExpectHasBoolKey(dictionary, "trustedVaultKeysRequired", false);
}
// Verifies the case where the user cancels after the sync engine has
// initialized. This isn't reachable on Ash because
// IsInitialSyncFeatureSetupComplete() always returns true.
#if !BUILDFLAG(IS_CHROMEOS)
TEST_F(PeopleHandlerTest,
DisplayConfigureWithEngineDisabledAndCancelAfterSigninSuccess) {
SigninUserAndTurnSyncFeatureOn();
sync_user_settings()->ClearInitialSyncFeatureSetupComplete();
CreatePeopleHandler();
handler_->HandleShowSyncSetupUI(base::Value::List());
EXPECT_TRUE(sync_service_->IsSetupInProgress());
// Sync engine becomes active, so |handler_| is notified.
ASSERT_EQ(sync_service_->GetTransportState(),
syncer::SyncService::TransportState::ACTIVE);
handler_->CloseSyncSetup();
EXPECT_EQ(
nullptr,
LoginUIServiceFactory::GetForProfile(profile())->current_login_ui());
EXPECT_FALSE(sync_service_->IsSetupInProgress());
}
#endif // !BUILDFLAG(IS_CHROMEOS)
TEST_F(PeopleHandlerTest, RestartSyncAfterDashboardClear) {
SigninUserAndTurnSyncFeatureOn();
CreatePeopleHandler();
// Mimic a dashboard clear, which should reset the sync engine and restart it
// in transport mode. Defer the second initialization of the engine, to test
// that prefs are not sent yet.
sync_service_->SetMaxTransportState(
syncer::SyncService::TransportState::INITIALIZING);
sync_service_->MimicDashboardClear();
ASSERT_EQ(sync_service_->GetTransportState(),
syncer::SyncService::TransportState::INITIALIZING);
#if BUILDFLAG(IS_CHROMEOS)
ASSERT_TRUE(sync_user_settings()->IsSyncFeatureDisabledViaDashboard());
#else // BUILDFLAG(IS_CHROMEOS)
ASSERT_FALSE(sync_user_settings()->IsInitialSyncFeatureSetupComplete());
#endif // BUILDFLAG(IS_CHROMEOS)
handler_->HandleShowSyncSetupUI(base::Value::List());
#if BUILDFLAG(IS_CHROMEOS)
EXPECT_FALSE(sync_user_settings()->IsSyncFeatureDisabledViaDashboard());
#endif // BUILDFLAG(IS_CHROMEOS)
// Since the engine is not initialized yet, no prefs should be sent.
EXPECT_EQ(0U, GetFiredSyncPrefsChanged().size());
// Now, allow the sync engine to fully start.
sync_service_->SetMaxTransportState(
syncer::SyncService::TransportState::ACTIVE);
sync_service_->FireStateChanged();
// Upon initialization of the engine, the new prefs should be sent.
ExpectSyncPrefsChanged();
}
// Tests that signals not related to user intention to configure sync don't
// trigger sync engine start.
TEST_F(PeopleHandlerTest, OnlyStartEngineWhenConfiguringSync) {
SigninUserAndTurnSyncFeatureOn();
CreatePeopleHandler();
sync_service_->SetMaxTransportState(
syncer::SyncService::TransportState::START_DEFERRED);
sync_service_->FireStateChanged();
EXPECT_EQ(sync_service_->GetTransportState(),
syncer::SyncService::TransportState::START_DEFERRED);
}
TEST_F(PeopleHandlerTest, AcquireSyncBlockerWhenLoadingSyncSettingsSubpage) {
SigninUserAndTurnSyncFeatureOn();
CreatePeopleHandler();
// Remove the WebUIConfig for chrome::kSyncSetupSubPage to prevent a new web
// ui from being created when we navigate to a page that would normally create
// one.
content::ScopedWebUIConfigRegistration registration(
chrome::GetSettingsUrl(chrome::kSyncSetupSubPage));
EXPECT_FALSE(handler_->sync_blocker_);
auto navigation = content::NavigationSimulator::CreateBrowserInitiated(
chrome::GetSettingsUrl(chrome::kSyncSetupSubPage), web_contents());
navigation->Start();
handler_->InitializeSyncBlocker();
EXPECT_TRUE(handler_->sync_blocker_);
}
TEST_F(PeopleHandlerTest, UnrecoverableErrorInitializingSync) {
SigninUserAndTurnSyncFeatureOn();
CreatePeopleHandler();
sync_service_->SetHasUnrecoverableError(true);
sync_user_settings()->ClearInitialSyncFeatureSetupComplete();
// Open the web UI.
handler_->HandleShowSyncSetupUI(base::Value::List());
ASSERT_FALSE(handler_->is_configuring_sync());
}
TEST_F(PeopleHandlerTest, GaiaErrorInitializingSync) {
SigninUserAndTurnSyncFeatureOn();
CreatePeopleHandler();
sync_service_->SetSignedOut();
// Open the web UI.
handler_->HandleShowSyncSetupUI(base::Value::List());
ASSERT_FALSE(handler_->is_configuring_sync());
}
TEST_F(PeopleHandlerTest, TestSyncEverything) {
SigninUserAndTurnSyncFeatureOn();
CreatePeopleHandler();
sync_user_settings()->SetSelectedTypes(/*sync_everything=*/false,
/*types=*/GetAllTypes());
std::string args = GetConfiguration(SYNC_ALL_DATA, GetAllTypes());
base::Value::List list_args;
list_args.Append(kTestCallbackId);
list_args.Append(args);
handler_->HandleSetDatatypes(list_args);
EXPECT_TRUE(sync_user_settings()->IsSyncEverythingEnabled());
ExpectPageStatusResponse(PeopleHandler::kConfigurePageStatus);
}
TEST_F(PeopleHandlerTest, EnterCorrectExistingPassphrase) {
const std::string kCorrectPassphrase = "correct_passphrase";
SigninUserAndTurnSyncFeatureOn();
CreatePeopleHandler();
sync_user_settings()->SetPassphraseRequired(kCorrectPassphrase);
ASSERT_TRUE(sync_user_settings()->IsPassphraseRequired());
base::Value::List list_args;
list_args.Append(kTestCallbackId);
list_args.Append(kCorrectPassphrase);
handler_->HandleSetDecryptionPassphrase(list_args);
ExpectSetPassphraseSuccess(true);
EXPECT_FALSE(sync_user_settings()->IsPassphraseRequired());
}
TEST_F(PeopleHandlerTest, SuccessfullyCreateCustomPassphrase) {
const std::string kPassphrase = "custom_passphrase";
SigninUserAndTurnSyncFeatureOn();
CreatePeopleHandler();
ASSERT_FALSE(sync_user_settings()->IsUsingExplicitPassphrase());
base::Value::List list_args;
list_args.Append(kTestCallbackId);
list_args.Append(kPassphrase);
handler_->HandleSetEncryptionPassphrase(list_args);
ExpectSetPassphraseSuccess(true);
EXPECT_EQ(sync_user_settings()->GetEncryptionPassphrase(), kPassphrase);
}
TEST_F(PeopleHandlerTest, EnterWrongExistingPassphrase) {
SigninUserAndTurnSyncFeatureOn();
CreatePeopleHandler();
sync_user_settings()->SetPassphraseRequired("correct_passphrase");
ASSERT_TRUE(sync_user_settings()->IsPassphraseRequired());
base::Value::List list_args;
list_args.Append(kTestCallbackId);
list_args.Append("invalid_passphrase");
handler_->HandleSetDecryptionPassphrase(list_args);
ExpectSetPassphraseSuccess(false);
ASSERT_TRUE(sync_user_settings()->IsPassphraseRequired());
}
TEST_F(PeopleHandlerTest, CannotCreateBlankPassphrase) {
SigninUserAndTurnSyncFeatureOn();
CreatePeopleHandler();
ASSERT_FALSE(sync_user_settings()->IsUsingExplicitPassphrase());
base::Value::List list_args;
list_args.Append(kTestCallbackId);
list_args.Append("");
handler_->HandleSetEncryptionPassphrase(list_args);
ExpectSetPassphraseSuccess(false);
ASSERT_FALSE(sync_user_settings()->IsUsingExplicitPassphrase());
}
// Walks through each user selectable type, and tries to sync just that single
// data type.
TEST_F(PeopleHandlerTest, TestSyncIndividualTypes) {
SigninUserAndTurnSyncFeatureOn();
CreatePeopleHandler();
for (syncer::UserSelectableType type : GetAllTypes()) {
syncer::UserSelectableTypeSet type_to_set;
type_to_set.Put(type);
std::string args = GetConfiguration(CHOOSE_WHAT_TO_SYNC, type_to_set);
base::Value::List list_args;
list_args.Append(kTestCallbackId);
list_args.Append(args);
handler_->HandleSetDatatypes(list_args);
ExpectPageStatusResponse(PeopleHandler::kConfigurePageStatus);
EXPECT_FALSE(sync_user_settings()->IsSyncEverythingEnabled());
EXPECT_EQ(sync_user_settings()->GetSelectedTypes(), type_to_set);
}
}
TEST_F(PeopleHandlerTest, TestSyncAllManually) {
SigninUserAndTurnSyncFeatureOn();
CreatePeopleHandler();
std::string args = GetConfiguration(CHOOSE_WHAT_TO_SYNC, GetAllTypes());
base::Value::List list_args;
list_args.Append(kTestCallbackId);
list_args.Append(args);
handler_->HandleSetDatatypes(list_args);
ExpectPageStatusResponse(PeopleHandler::kConfigurePageStatus);
EXPECT_FALSE(sync_user_settings()->IsSyncEverythingEnabled());
EXPECT_EQ(sync_user_settings()->GetSelectedTypes(), GetAllTypes());
}
TEST_F(PeopleHandlerTest, NonRegisteredType) {
SigninUserAndTurnSyncFeatureOn();
CreatePeopleHandler();
// Simulate apps not being registered.
syncer::UserSelectableTypeSet registered_types = GetAllTypes();
registered_types.Remove(syncer::UserSelectableType::kApps);
sync_user_settings()->SetRegisteredSelectableTypes(registered_types);
// Simulate "Sync everything" being turned off, but all individual
// toggles left on.
std::string config = GetConfiguration(CHOOSE_WHAT_TO_SYNC, GetAllTypes());
base::Value::List list_args;
list_args.Append(kTestCallbackId);
list_args.Append(config);
// Only the registered types are selected.
handler_->HandleSetDatatypes(list_args);
EXPECT_FALSE(sync_user_settings()->IsSyncEverythingEnabled());
EXPECT_EQ(sync_user_settings()->GetSelectedTypes(), registered_types);
}
TEST_F(PeopleHandlerTest, ShowSyncSetup) {
SigninUserAndTurnSyncFeatureOn();
CreatePeopleHandler();
// This should display the sync setup dialog (not login).
handler_->HandleShowSyncSetupUI(base::Value::List());
ExpectSyncPrefsChanged();
}
TEST_F(PeopleHandlerTest, ShowSetupSyncEverything) {
SigninUserAndTurnSyncFeatureOn();
CreatePeopleHandler();
// This should display the sync setup dialog (not login).
handler_->HandleShowSyncSetupUI(base::Value::List());
base::Value::Dict dictionary = ExpectSyncPrefsChanged();
ExpectHasBoolKey(dictionary, "syncAllDataTypes", true);
ExpectHasBoolKey(dictionary, "appsRegistered", true);
ExpectHasBoolKey(dictionary, "autofillRegistered", true);
ExpectHasBoolKey(dictionary, "bookmarksRegistered", true);
ExpectHasBoolKey(dictionary, "cookiesRegistered", true);
ExpectHasBoolKey(dictionary, "extensionsRegistered", true);
ExpectHasBoolKey(dictionary, "passwordsRegistered", true);
ExpectHasBoolKey(dictionary, "paymentsRegistered", true);
ExpectHasBoolKey(dictionary, "preferencesRegistered", true);
ExpectHasBoolKey(dictionary, "readingListRegistered", true);
ExpectHasBoolKey(dictionary, "tabsRegistered", true);
ExpectHasBoolKey(dictionary, "themesRegistered", true);
ExpectHasBoolKey(dictionary, "typedUrlsRegistered", true);
ExpectHasBoolKey(dictionary, "passphraseRequired", false);
ExpectHasBoolKey(dictionary, "encryptAllData", false);
CheckConfigDataTypeArguments(dictionary, SYNC_ALL_DATA, GetAllTypes());
}
TEST_F(PeopleHandlerTest, ShowSetupManuallySyncAll) {
SigninUserAndTurnSyncFeatureOn();
CreatePeopleHandler();
sync_user_settings()->SetSelectedTypes(/*sync_everything=*/false,
/*types=*/GetAllTypes());
ASSERT_FALSE(sync_user_settings()->IsSyncEverythingEnabled());
// This should display the sync setup dialog (not login).
handler_->HandleShowSyncSetupUI(base::Value::List());
base::Value::Dict dictionary = ExpectSyncPrefsChanged();
CheckConfigDataTypeArguments(dictionary, CHOOSE_WHAT_TO_SYNC, GetAllTypes());
}
TEST_F(PeopleHandlerTest, ShowSetupSyncForAllTypesIndividually) {
SigninUserAndTurnSyncFeatureOn();
CreatePeopleHandler();
for (syncer::UserSelectableType type : GetAllTypes()) {
const syncer::UserSelectableTypeSet types = {type};
sync_user_settings()->SetSelectedTypes(/*sync_everything=*/false, types);
// This should display the sync setup dialog (not login).
handler_->HandleShowSyncSetupUI(base::Value::List());
// Close the config overlay.
LoginUIServiceFactory::GetForProfile(profile())->LoginUIClosed(
handler_.get());
base::Value::Dict dictionary = ExpectSyncPrefsChanged();
CheckConfigDataTypeArguments(dictionary, CHOOSE_WHAT_TO_SYNC, types);
// Clean up so we can loop back to display the dialog again.
web_ui_.ClearTrackedCalls();
}
}
TEST_F(PeopleHandlerTest, ShowSetupOldGaiaPassphraseRequired) {
SigninUserAndTurnSyncFeatureOn();
CreatePeopleHandler();
const auto passphrase_time = base::Time::Now();
sync_user_settings()->SetPassphraseRequired();
sync_user_settings()->SetPassphraseType(
syncer::PassphraseType::kFrozenImplicitPassphrase);
sync_user_settings()->SetExplicitPassphraseTime(passphrase_time);
handler_->HandleShowSyncSetupUI(base::Value::List());
base::Value::Dict dictionary = ExpectSyncPrefsChanged();
ExpectHasBoolKey(dictionary, "passphraseRequired", true);
ASSERT_TRUE(dictionary.contains("explicitPassphraseTime"));
ASSERT_TRUE(dictionary.FindString("explicitPassphraseTime"));
EXPECT_EQ(base::UTF16ToUTF8(base::TimeFormatShortDate(passphrase_time)),
*dictionary.FindString("explicitPassphraseTime"));
}
TEST_F(PeopleHandlerTest, ShowSetupCustomPassphraseRequired) {
SigninUserAndTurnSyncFeatureOn();
CreatePeopleHandler();
const auto passphrase_time = base::Time::Now();
sync_user_settings()->SetPassphraseRequired();
sync_user_settings()->SetPassphraseType(
syncer::PassphraseType::kCustomPassphrase);
sync_user_settings()->SetExplicitPassphraseTime(passphrase_time);
handler_->HandleShowSyncSetupUI(base::Value::List());
base::Value::Dict dictionary = ExpectSyncPrefsChanged();
ExpectHasBoolKey(dictionary, "passphraseRequired", true);
ASSERT_TRUE(dictionary.contains("explicitPassphraseTime"));
ASSERT_TRUE(dictionary.FindString("explicitPassphraseTime"));
EXPECT_EQ(base::UTF16ToUTF8(base::TimeFormatShortDate(passphrase_time)),
*dictionary.FindString("explicitPassphraseTime"));
}
// Verifies that the user is not prompted to enter the custom passphrase while
// sync setup is ongoing. This isn't reachable on Ash because
// IsInitialSyncFeatureSetupComplete() always returns true.
#if !BUILDFLAG(IS_CHROMEOS)
TEST_F(PeopleHandlerTest, OngoingSetupCustomPassphraseRequired) {
SigninUserWithoutSyncFeature();
CreatePeopleHandler();
const auto passphrase_time = base::Time::Now();
sync_user_settings()->SetPassphraseRequired();
sync_user_settings()->SetPassphraseType(
syncer::PassphraseType::kCustomPassphrase);
sync_user_settings()->SetExplicitPassphraseTime(passphrase_time);
handler_->HandleShowSyncSetupUI(base::Value::List());
base::Value::Dict dictionary = ExpectSyncPrefsChanged();
ExpectHasBoolKey(dictionary, "passphraseRequired", false);
}
#endif // !BUILDFLAG(IS_CHROMEOS)
TEST_F(PeopleHandlerTest, ShowSetupTrustedVaultKeysRequired) {
SigninUserAndTurnSyncFeatureOn();
CreatePeopleHandler();
sync_user_settings()->SetPassphraseType(
syncer::PassphraseType::kTrustedVaultPassphrase);
sync_service_->SetTrustedVaultKeyRequired(true);
// This should display the sync setup dialog (not login).
handler_->HandleShowSyncSetupUI(base::Value::List());
base::Value::Dict dictionary = ExpectSyncPrefsChanged();
ExpectHasBoolKey(dictionary, "passphraseRequired", false);
ExpectHasBoolKey(dictionary, "trustedVaultKeysRequired", true);
EXPECT_FALSE(dictionary.contains("explicitPassphraseTime"));
}
TEST_F(PeopleHandlerTest, ShowSetupEncryptAll) {
SigninUserAndTurnSyncFeatureOn();
CreatePeopleHandler();
sync_user_settings()->SetIsUsingExplicitPassphrase(true);
ASSERT_TRUE(sync_user_settings()->IsEncryptEverythingEnabled());
// This should display the sync setup dialog (not login).
handler_->HandleShowSyncSetupUI(base::Value::List());
base::Value::Dict dictionary = ExpectSyncPrefsChanged();
ExpectHasBoolKey(dictionary, "encryptAllData", true);
}
TEST_F(PeopleHandlerTest, ShowSetupEncryptAllDisallowed) {
SigninUserAndTurnSyncFeatureOn();
CreatePeopleHandler();
sync_user_settings()->SetCustomPassphraseAllowed(false);
// This should display the sync setup dialog (not login).
handler_->HandleShowSyncSetupUI(base::Value::List());
base::Value::Dict dictionary = ExpectSyncPrefsChanged();
ExpectHasBoolKey(dictionary, "encryptAllData", false);
ExpectHasBoolKey(dictionary, "customPassphraseAllowed", false);
}
TEST_F(PeopleHandlerTest, CannotCreatePassphraseIfCustomPassphraseDisallowed) {
SigninUserAndTurnSyncFeatureOn();
CreatePeopleHandler();
sync_user_settings()->SetCustomPassphraseAllowed(false);
ASSERT_FALSE(sync_user_settings()->IsUsingExplicitPassphrase());
base::Value::List list_args;
list_args.Append(kTestCallbackId);
list_args.Append("passphrase123");
handler_->HandleSetEncryptionPassphrase(list_args);
ExpectSetPassphraseSuccess(false);
EXPECT_FALSE(sync_user_settings()->IsUsingExplicitPassphrase());
}
TEST_F(PeopleHandlerTest, CannotOverwritePassphraseWithNewOne) {
const std::string kInitialPassphrase = "initial_passphrase";
SigninUserAndTurnSyncFeatureOn();
CreatePeopleHandler();
sync_user_settings()->SetEncryptionPassphrase(kInitialPassphrase);
ASSERT_TRUE(sync_user_settings()->IsUsingExplicitPassphrase());
base::Value::List list_args;
list_args.Append(kTestCallbackId);
list_args.Append("passphrase123");
handler_->HandleSetEncryptionPassphrase(list_args);
ExpectSetPassphraseSuccess(false);
EXPECT_EQ(sync_user_settings()->GetEncryptionPassphrase(),
kInitialPassphrase);
}
TEST_F(PeopleHandlerTest, DashboardClearWhileSettingsOpen_ConfirmSoon) {
SigninUserAndTurnSyncFeatureOn();
CreatePeopleHandler();
ASSERT_TRUE(sync_user_settings()->IsInitialSyncFeatureSetupComplete());
handler_->HandleShowSyncSetupUI(base::Value::List());
sync_service_->MimicDashboardClear();
sync_service_->FireStateChanged();
#if BUILDFLAG(IS_CHROMEOS)
ASSERT_TRUE(sync_user_settings()->IsSyncFeatureDisabledViaDashboard());
#else // BUILDFLAG(IS_CHROMEOS)
ASSERT_FALSE(sync_user_settings()->IsInitialSyncFeatureSetupComplete());
#endif // BUILDFLAG(IS_CHROMEOS)
// Now the user confirms sync again. This should set both the sync-requested
// and the first-setup-complete bits.
base::Value::List did_abort;
did_abort.Append(false);
handler_->OnDidClosePage(did_abort);
EXPECT_TRUE(sync_user_settings()->IsInitialSyncFeatureSetupComplete());
}
TEST_F(PeopleHandlerTest, DashboardClearWhileSettingsOpen_ConfirmLater) {
SigninUserAndTurnSyncFeatureOn();
CreatePeopleHandler();
ASSERT_TRUE(sync_user_settings()->IsInitialSyncFeatureSetupComplete());
handler_->HandleShowSyncSetupUI(base::Value::List());
sync_service_->MimicDashboardClear();
sync_service_->FireStateChanged();
#if BUILDFLAG(IS_CHROMEOS)
ASSERT_TRUE(sync_user_settings()->IsSyncFeatureDisabledViaDashboard());
#else // BUILDFLAG(IS_CHROMEOS)
ASSERT_FALSE(sync_user_settings()->IsInitialSyncFeatureSetupComplete());
#endif // BUILDFLAG(IS_CHROMEOS)
// Sync starts up in transport mode.
ASSERT_EQ(sync_service_->GetTransportState(),
syncer::SyncService::TransportState::ACTIVE);
// Now the user confirms sync again. This should set the sync-requested bit
// and also the first-setup-complete bit (except on ChromeOS Ash where it is
// always true).
base::Value::List did_abort;
did_abort.Append(false);
handler_->OnDidClosePage(did_abort);
EXPECT_EQ(sync_service_->GetTransportState(),
syncer::SyncService::TransportState::ACTIVE);
EXPECT_TRUE(sync_user_settings()->IsInitialSyncFeatureSetupComplete());
}
#if BUILDFLAG(ENABLE_DICE_SUPPORT)
TEST(PeopleHandlerDiceTest, StoredAccountsList) {
ScopedTestingLocalState local_state(TestingBrowserProcess::GetGlobal());
content::BrowserTaskEnvironment task_environment;
network::TestURLLoaderFactory url_loader_factory =
network::TestURLLoaderFactory();
TestingProfile::Builder builder;
builder.AddTestingFactories(
IdentityTestEnvironmentProfileAdaptor::
GetIdentityTestEnvironmentFactoriesWithAppendedFactories(
{TestingProfile::TestingFactory{
ChromeSigninClientFactory::GetInstance(),
base::BindRepeating(&BuildChromeSigninClientWithURLLoader,
&url_loader_factory)}}));
std::unique_ptr<TestingProfile> profile = builder.Build();
ASSERT_EQ(true, AccountConsistencyModeManager::IsDiceEnabledForProfile(
profile.get()));
auto identity_test_env_adaptor =
std::make_unique<IdentityTestEnvironmentProfileAdaptor>(profile.get());
auto* identity_test_env = identity_test_env_adaptor->identity_test_env();
identity_test_env->SetTestURLLoaderFactory(&url_loader_factory);
auto account_1 = identity_test_env->MakeAccountAvailable(
"a@gmail.com", {.set_cookie = true});
auto account_2 = identity_test_env->MakeAccountAvailable(
"b@gmail.com", {.set_cookie = true});
identity_test_env->SetPrimaryAccount(account_1.email,
signin::ConsentLevel::kSignin);
PeopleHandler handler(profile.get());
base::Value::List accounts = handler.GetStoredAccountsList();
ASSERT_EQ(2u, accounts.size());
ASSERT_TRUE(accounts[0].GetDict().FindString("email"));
ASSERT_TRUE(accounts[1].GetDict().FindString("email"));
EXPECT_EQ("a@gmail.com", *accounts[0].GetDict().FindString("email"));
EXPECT_EQ("b@gmail.com", *accounts[1].GetDict().FindString("email"));
}
#endif // BUILDFLAG(ENABLE_DICE_SUPPORT)
#if BUILDFLAG(IS_CHROMEOS)
// Regression test for crash in guest mode. https://crbug.com/1040476
TEST(PeopleHandlerGuestModeTest, GetStoredAccountsList) {
content::BrowserTaskEnvironment task_environment;
TestingProfile::Builder builder;
builder.SetGuestSession();
std::unique_ptr<Profile> profile = builder.Build();
PeopleHandler handler(profile.get());
base::Value::List accounts = handler.GetStoredAccountsList();
EXPECT_TRUE(accounts.empty());
}
TEST_F(PeopleHandlerTest, GetStoredAccountsList) {
// Chrome OS sets an unconsented primary account on login.
identity_test_env()->MakePrimaryAccountAvailable("user@gmail.com",
ConsentLevel::kSignin);
ASSERT_FALSE(identity_manager()->HasPrimaryAccount(ConsentLevel::kSync));
CreatePeopleHandler();
base::Value::List accounts = handler_->GetStoredAccountsList();
ASSERT_EQ(1u, accounts.size());
EXPECT_EQ("user@gmail.com", *accounts[0].GetDict().FindString("email"));
}
TEST_F(PeopleHandlerTest, SyncCookiesDisabled) {
base::test::ScopedFeatureList features;
// Disable Floating SSO feature flag.
features.InitWithFeatures(
/*enabled_features=*/{},
/*disabled_features=*/{ash::features::kFloatingSso});
SigninUserAndTurnSyncFeatureOn();
CreatePeopleHandler();
const base::Value::Dict& sync_status_values =
handler_->GetSyncStatusDictionary();
std::optional<bool> sync_cookies_supported =
sync_status_values.FindBool("syncCookiesSupported");
EXPECT_FALSE(sync_cookies_supported.has_value());
}
#endif // BUILDFLAG(IS_CHROMEOS)
#if BUILDFLAG(ENABLE_DICE_SUPPORT)
TEST_F(PeopleHandlerTest, ChromeSigninUserChoice) {
base::HistogramTester histogram_tester;
CreatePeopleHandler();
SimulateHandleGetChromeSigninUserChoiceInfo();
ExpectChromeSigninUserChoiceInfoFromWebUiResponse(
false, ChromeSigninUserChoice::kNoChoice, "");
std::string email("user@gmail.com");
identity_test_env()->MakePrimaryAccountAvailable(email,
ConsentLevel::kSignin);
SimulateHandleGetChromeSigninUserChoiceInfo();
ExpectChromeSigninUserChoiceInfoFromWebUiResponse(
true, ChromeSigninUserChoice::kNoChoice, email);
ChromeSigninUserChoice user_choice = ChromeSigninUserChoice::kSignin;
SimulateHandleSetChromeSigninUserChoiceInfo(email, user_choice);
SimulateHandleGetChromeSigninUserChoiceInfo();
ExpectChromeSigninUserChoiceInfoFromWebUiResponse(true, user_choice, email);
DestroyPeopleHandler();
histogram_tester.ExpectTotalCount(
"Signin.Settings.ChromeSigninSettingModification", 1);
histogram_tester.ExpectBucketCount(
"Signin.Settings.ChromeSigninSettingModification",
/*`ChromeSigninSettingModification::kToSignin`*/ 2, 1);
}
TEST_F(PeopleHandlerTest,
ChromeSigninUserAvailableOnExplicitChromeSigninSignout) {
const std::string email("user@gmail.com");
identity_test_env()->MakePrimaryAccountAvailable(email,
ConsentLevel::kSignin);
SetExplicitSignin(true);
CreatePeopleHandler();
SimulateHandleGetChromeSigninUserChoiceInfo();
ExpectChromeSigninUserChoiceInfoFromWebUiResponse(
true, ChromeSigninUserChoice::kNoChoice, email);
SimulateSignout();
ASSERT_FALSE(
identity_manager()->HasPrimaryAccount(signin::ConsentLevel::kSignin));
ASSERT_TRUE(identity_manager()->GetAccountsWithRefreshTokens().empty());
SimulateHandleGetChromeSigninUserChoiceInfo();
ExpectChromeSigninUserChoiceInfoFromWebUiResponse(
false, ChromeSigninUserChoice::kNoChoice, "");
}
TEST_F(PeopleHandlerTest, ChromeSigninUserAvailableOnDiceSignin) {
const std::string email("user@gmail.com");
identity_test_env()->MakePrimaryAccountAvailable(email,
ConsentLevel::kSignin);
// Simulates Dice signin.
SetExplicitSignin(false);
CreatePeopleHandler();
SimulateHandleGetChromeSigninUserChoiceInfo();
ExpectChromeSigninUserChoiceInfoFromWebUiResponse(
false, ChromeSigninUserChoice::kNoChoice, email);
}
TEST_F(PeopleHandlerTest, ChromeSigninUserInfoUpdateOnPrefValueChange) {
const std::string email("user@gmail.com");
AccountInfo account_info = identity_test_env()->MakePrimaryAccountAvailable(
email, ConsentLevel::kSignin);
SetExplicitSignin(true);
CreatePeopleHandler();
ASSERT_FALSE(HasChromeSigninUserChoiceInfoChangeEvent());
SigninPrefs signin_prefs(*profile()->GetPrefs());
auto new_choice_value = ChromeSigninUserChoice::kSignin;
ASSERT_NE(
signin_prefs.GetChromeSigninInterceptionUserChoice(account_info.gaia),
new_choice_value);
signin_prefs.SetChromeSigninInterceptionUserChoice(account_info.gaia,
new_choice_value);
ExpectChromeSigninUserChoiceInfoFromLastChangeEvent(true, new_choice_value,
email);
}
TEST_F(PeopleHandlerTest, ChromeSigninUserInfoUpdateOnSignin) {
CreatePeopleHandler();
ASSERT_FALSE(HasChromeSigninUserChoiceInfoChangeEvent());
const std::string email("user@gmail.com");
// Explicit browser signin.
identity_test_env()->MakePrimaryAccountAvailable(email,
ConsentLevel::kSignin);
// By default no choice yet.
ExpectChromeSigninUserChoiceInfoFromLastChangeEvent(
true, ChromeSigninUserChoice::kNoChoice, email);
}
TEST_F(PeopleHandlerTest, ChromeSigninUserInfoUpdateOnSync) {
CreatePeopleHandler();
ASSERT_FALSE(HasChromeSigninUserChoiceInfoChangeEvent());
const std::string email("user@gmail.com");
// Sync is a form of explicit browser signin.
identity_test_env()->MakePrimaryAccountAvailable(email, ConsentLevel::kSync);
// By default no choice yet.
ExpectChromeSigninUserChoiceInfoFromLastChangeEvent(
true, ChromeSigninUserChoice::kNoChoice, email);
}
// This test does not use `PeopleHandlerTest` test suite and needs it's own test
// setup because in order to get the proper web signin, we need to set a cookie
// while signing in, which requires setting up a `TestURLLoaderFactory` with the
// `ChromeSigninClient`.
TEST(PeopleHandlerWebOnlySigninTest, ChromeSigninUserAvailableOnWebSignin) {
// -- Test Setup start
// Needed to enable setting a proper account signed in on the web.
ScopedTestingLocalState local_state(TestingBrowserProcess::GetGlobal());
content::BrowserTaskEnvironment task_environment;
network::TestURLLoaderFactory url_loader_factory =
network::TestURLLoaderFactory();
TestingProfile::Builder builder;
builder.AddTestingFactories(
IdentityTestEnvironmentProfileAdaptor::
GetIdentityTestEnvironmentFactoriesWithAppendedFactories(
{TestingProfile::TestingFactory{
ChromeSigninClientFactory::GetInstance(),
base::BindRepeating(&BuildChromeSigninClientWithURLLoader,
&url_loader_factory)},
TestingProfile::TestingFactory{
SyncServiceFactory::GetInstance(),
base::BindRepeating(&BuildTestSyncService)}}));
std::unique_ptr<TestingProfile> profile = builder.Build();
auto identity_test_env_adaptor =
std::make_unique<IdentityTestEnvironmentProfileAdaptor>(profile.get());
// This test env should be used throughout the test.
auto* identity_test_env = identity_test_env_adaptor->identity_test_env();
identity_test_env->SetTestURLLoaderFactory(&url_loader_factory);
PeopleHandler handler(profile.get());
// -- Test Setup end.
// Test before web signin -- only need to check the `shouldShowSettings` param
{
base::Value::Dict chrome_signin_user_choice_info_dict =
handler.GetChromeSigninUserChoiceInfo();
std::optional<bool> should_show_settings =
chrome_signin_user_choice_info_dict.FindBool("shouldShowSettings");
ASSERT_TRUE(should_show_settings.has_value());
EXPECT_FALSE(should_show_settings.value());
}
const std::string email("user@gmail.com");
// Signs in to the web only.
identity_test_env->MakeAccountAvailable(email, {.set_cookie = true});
ASSERT_FALSE(identity_test_env->identity_manager()->HasPrimaryAccount(
signin::ConsentLevel::kSignin));
// Test after web signin and check all the fields.
{
base::Value::Dict chrome_signin_user_choice_info_dict =
handler.GetChromeSigninUserChoiceInfo();
PeopleHandlerTest::ExpectChromeSigninUserChoiceInfoDict(
chrome_signin_user_choice_info_dict,
/*expected_should_show_settings=*/true,
ChromeSigninUserChoice::kNoChoice, email);
}
// Check that `SignedInState` is properly computed
{
const base::Value::Dict& sync_status_values =
handler.GetSyncStatusDictionary();
std::optional<int> signedInState =
sync_status_values.FindInt("signedInState");
ASSERT_TRUE(signedInState.has_value());
EXPECT_EQ(static_cast<SignedInState>(signedInState.value()),
SignedInState::kWebOnlySignedIn);
}
}
TEST_F(PeopleHandlerTest, SigninPendingThenSignout) {
identity_test_env()->MakePrimaryAccountAvailable(kTestUser,
ConsentLevel::kSignin);
SetExplicitSignin(true);
CreatePeopleHandler();
ASSERT_FALSE(HasSyncStatusUpdateChangedEvent());
TriggerPrimaryAccountInPersistentError();
{
auto values_list =
GetAllFiredValuesForEventName(kSyncStatusChangeEventName);
ASSERT_GT(values_list.size(), 0U);
size_t last_index = values_list.size() - 1;
ASSERT_TRUE(values_list[last_index]->is_dict());
const base::Value::Dict& sync_status_values =
values_list[last_index]->GetDict();
std::optional<int> signedInState =
sync_status_values.FindInt("signedInState");
ASSERT_TRUE(signedInState.has_value());
EXPECT_EQ(static_cast<SignedInState>(signedInState.value()),
SignedInState::kSignInPending);
}
// Simulates pressing on the "Sign out" Button in the Sign in Paused state,
// that redirects to `PeopleHandler::HandleSignout()`. Since the test has no
// browser, clearing the primary account should be equivalent.
SimulateSignout();
{
auto values_list =
GetAllFiredValuesForEventName(kSyncStatusChangeEventName);
ASSERT_GT(values_list.size(), 0U);
size_t last_index = values_list.size() - 1;
ASSERT_TRUE(values_list[last_index]->is_dict());
const base::Value::Dict& sync_status_values =
values_list[last_index]->GetDict();
std::optional<int> signedInState =
sync_status_values.FindInt("signedInState");
ASSERT_TRUE(signedInState.has_value());
EXPECT_EQ(static_cast<SignedInState>(signedInState.value()),
SignedInState::kSignedOut);
}
}
TEST_F(PeopleHandlerTest, SigninPendingThenReauth) {
identity_test_env()->MakePrimaryAccountAvailable(kTestUser,
ConsentLevel::kSignin);
SetExplicitSignin(true);
CreatePeopleHandler();
ASSERT_FALSE(HasSyncStatusUpdateChangedEvent());
TriggerPrimaryAccountInPersistentError();
{
auto values_list =
GetAllFiredValuesForEventName(kSyncStatusChangeEventName);
ASSERT_GT(values_list.size(), 0U);
size_t last_index = values_list.size() - 1;
ASSERT_TRUE(values_list[last_index]->is_dict());
const base::Value::Dict& sync_status_values =
values_list[last_index]->GetDict();
std::optional<int> signedInState =
sync_status_values.FindInt("signedInState");
ASSERT_TRUE(signedInState.has_value());
EXPECT_EQ(static_cast<SignedInState>(signedInState.value()),
SignedInState::kSignInPending);
;
}
// Simulates pressing on the "Verify it's you" button in the Sign in Paused
// state, and reauth.
SimluateReauth();
{
auto values_list =
GetAllFiredValuesForEventName(kSyncStatusChangeEventName);
ASSERT_GT(values_list.size(), 0U);
size_t last_index = values_list.size() - 1;
ASSERT_TRUE(values_list[last_index]->is_dict());
const base::Value::Dict& sync_status_values =
values_list[last_index]->GetDict();
std::optional<int> signedInState =
sync_status_values.FindInt("signedInState");
ASSERT_TRUE(signedInState.has_value());
EXPECT_EQ(static_cast<SignedInState>(signedInState.value()),
SignedInState::kSignedIn);
}
}
// Regression test for https://crbug.com/389031469
TEST_F(PeopleHandlerTest, HandleStartSigninManaged) {
testing::StrictMock<MockSigninUiDelegate> mock_signin_ui_delegate;
base::AutoReset<signin_ui_util::SigninUiDelegate*> delegate_auto_reset =
signin_ui_util::SetSigninUiDelegateForTesting(&mock_signin_ui_delegate);
const char kManagedEmail[] = "user@managedchrome.com";
AccountInfo account = identity_test_env()->MakePrimaryAccountAvailable(
kManagedEmail, ConsentLevel::kSignin);
SetExplicitSignin(true);
// Make the account managed and disallow signout.
account.hosted_domain = "managedchrome.com";
AccountCapabilitiesTestMutator(&account.capabilities)
.set_is_subject_to_enterprise_policies(true);
identity_test_env()->UpdateAccountInfoForAccount(account);
SigninClient* client = ChromeSigninClientFactory::GetForProfile(profile());
client->set_is_clear_primary_account_allowed_for_testing(
SigninClient::SignoutDecision::CLEAR_PRIMARY_ACCOUNT_DISALLOWED);
ASSERT_FALSE(
client->IsClearPrimaryAccountAllowed(/*has_sync_account=*/false));
TriggerPrimaryAccountInPersistentError();
CreatePeopleHandler();
// This should not crash.
EXPECT_CALL(
mock_signin_ui_delegate,
ShowReauthUI(profile(), kManagedEmail, /*enable_sync=*/false,
signin_metrics::AccessPoint::kSettings,
signin_metrics::PromoAction::PROMO_ACTION_NO_SIGNIN_PROMO));
web_ui_.HandleReceivedMessage("SyncSetupStartSignIn", base::Value::List());
}
TEST_F(PeopleHandlerTest, SigninPendingValueWithSync) {
CreatePeopleHandler();
ASSERT_FALSE(HasSyncStatusUpdateChangedEvent());
// User is syncing.
identity_test_env()->MakePrimaryAccountAvailable(kTestUser,
ConsentLevel::kSync);
{
auto values_list =
GetAllFiredValuesForEventName(kSyncStatusChangeEventName);
ASSERT_GT(values_list.size(), 0U);
size_t last_index = values_list.size() - 1;
ASSERT_TRUE(values_list[last_index]->is_dict());
const base::Value::Dict& sync_status_values =
values_list[last_index]->GetDict();
std::optional<int> signedInState =
sync_status_values.FindInt("signedInState");
ASSERT_TRUE(signedInState.has_value());
EXPECT_EQ(static_cast<SignedInState>(signedInState.value()),
SignedInState::kSyncing);
}
// Invalidate the account while it is syncing.
TriggerPrimaryAccountInPersistentError();
// `SigninPending` is still false even when the account is in error.
{
auto values_list =
GetAllFiredValuesForEventName(kSyncStatusChangeEventName);
ASSERT_GT(values_list.size(), 0U);
size_t last_index = values_list.size() - 1;
ASSERT_TRUE(values_list[last_index]->is_dict());
const base::Value::Dict& sync_status_values =
values_list[last_index]->GetDict();
std::optional<int> signedInState =
sync_status_values.FindInt("signedInState");
ASSERT_TRUE(signedInState.has_value());
EXPECT_EQ(static_cast<SignedInState>(signedInState.value()),
SignedInState::kSyncing);
}
}
TEST_F(PeopleHandlerTest, ChromeSigninUserChoiceHistogramsWhenSignedOut) {
base::HistogramTester histogram_tester;
CreatePeopleHandler();
// Simluates settings page loading.
SimulateHandleGetChromeSigninUserChoiceInfo();
// Simulates closing the settings page.
DestroyPeopleHandler();
// No account are signed in, the setting is not expected to be shown, so no
// values related to it should be recorded.
histogram_tester.ExpectTotalCount(
"Signin.Settings.ChromeSigninSettingModification", 0);
}
TEST_F(PeopleHandlerTest,
ChromeSigninUserChoiceHistogramsWhenSignedInWithoutChangingSetting) {
base::HistogramTester histogram_tester;
// Signed in user can see the setting.
identity_test_env()->MakePrimaryAccountAvailable("email@gmail.com",
ConsentLevel::kSignin);
CreatePeopleHandler();
// Simluates settings page loading.
SimulateHandleGetChromeSigninUserChoiceInfo();
// Simulates closing the settings page.
DestroyPeopleHandler();
// Setting is seen but not modiffied.
histogram_tester.ExpectTotalCount(
"Signin.Settings.ChromeSigninSettingModification", 1);
histogram_tester.ExpectBucketCount(
"Signin.Settings.ChromeSigninSettingModification",
/*`ChromeSigninSettingModification::kNoModification`*/ 0, 1);
}
TEST_F(PeopleHandlerTest,
ChromeSigninUserChoiceHistogramsWhenSignedInWithChangingSetting) {
base::HistogramTester histogram_tester;
// Signed in user can see the setting.
AccountInfo account = identity_test_env()->MakePrimaryAccountAvailable(
/*email=*/"email@gmail.com", ConsentLevel::kSignin);
CreatePeopleHandler();
// Simluates settings page loading.
SimulateHandleGetChromeSigninUserChoiceInfo();
SigninPrefs signin_prefs(*profile()->GetPrefs());
ChromeSigninUserChoice current_choice =
signin_prefs.GetChromeSigninInterceptionUserChoice(account.gaia);
// Simulates setting a new value through the UI.
ChromeSigninUserChoice user_choice = ChromeSigninUserChoice::kSignin;
ASSERT_NE(current_choice, user_choice);
SimulateHandleSetChromeSigninUserChoiceInfo(account.email, user_choice);
// Simulate a last bubble decline time as well.
signin_prefs.SetChromeSigninInterceptionLastBubbleDeclineTime(
account.gaia, base::Time::Now());
signin_prefs.IncrementChromeSigninBubbleRepromptCount(account.gaia);
// Simulates a second selection within the same settings session.
ChromeSigninUserChoice user_choice2 = ChromeSigninUserChoice::kDoNotSignin;
ASSERT_NE(current_choice, user_choice2);
SimulateHandleSetChromeSigninUserChoiceInfo(account.email, user_choice2);
// Explicitly setting the do not sign in option should clear bubble declined
// time.
EXPECT_FALSE(
signin_prefs
.GetChromeSigninInterceptionLastBubbleDeclineTime(account.gaia)
.has_value());
EXPECT_EQ(signin_prefs.GetChromeSigninBubbleRepromptCount(account.gaia), 0);
// Enforcing changing the value to the same previous one should not record a
// new modification.
SimulateHandleSetChromeSigninUserChoiceInfo(account.email, user_choice2);
// Simulates closing the settings page.
DestroyPeopleHandler();
// Setting is seen and modified twice.
histogram_tester.ExpectTotalCount(
"Signin.Settings.ChromeSigninSettingModification", 2);
histogram_tester.ExpectBucketCount(
"Signin.Settings.ChromeSigninSettingModification",
/*`ChromeSigninSettingModification::kToSignin`*/ 2, 1);
histogram_tester.ExpectBucketCount(
"Signin.Settings.ChromeSigninSettingModification",
/*`ChromeSigninSettingModification::kToDoNotSignin`*/ 3, 1);
}
TEST_F(
PeopleHandlerTest,
ChromeSigninUserChoiceHistogramsWhenSignedInWithChangingSettingThenSignout) {
base::HistogramTester histogram_tester;
// Signed in user can see the setting.
AccountInfo account = identity_test_env()->MakePrimaryAccountAvailable(
/*email=*/"email@gmail.com", ConsentLevel::kSignin);
CreatePeopleHandler();
// Simluates settings page loading.
SimulateHandleGetChromeSigninUserChoiceInfo();
SigninPrefs signin_prefs(*profile()->GetPrefs());
ChromeSigninUserChoice current_choice =
signin_prefs.GetChromeSigninInterceptionUserChoice(account.gaia);
// Simulates setting a new value through the settings UI.
ChromeSigninUserChoice new_value = ChromeSigninUserChoice::kSignin;
ASSERT_NE(current_choice, new_value);
SimulateHandleSetChromeSigninUserChoiceInfo(account.email, new_value);
SimulateSignout();
SimulateHandleGetChromeSigninUserChoiceInfo();
// The setting should not be seen anymore.
ExpectChromeSigninUserChoiceInfoFromWebUiResponse(
false, ChromeSigninUserChoice::kNoChoice, "");
// Simulates closing the settings page.
DestroyPeopleHandler();
// A modification value is still recorded, even after signing out, since a
// modification occurred during the session.
histogram_tester.ExpectTotalCount(
"Signin.Settings.ChromeSigninSettingModification", 1);
histogram_tester.ExpectBucketCount(
"Signin.Settings.ChromeSigninSettingModification",
/*`ChromeSigninSettingModification::kToSignin`*/ 2, 1);
}
#endif
#if BUILDFLAG(ENABLE_DICE_SUPPORT)
class PeopleHandlerSignoutTest : public BrowserWithTestWindowTest {
public:
PeopleHandlerSignoutTest() = default;
~PeopleHandlerSignoutTest() override = default;
signin::IdentityTestEnvironment* identity_test_env() {
return identity_test_env_profile_adaptor_->identity_test_env();
}
signin::IdentityManager* identity_manager() {
return identity_test_env()->identity_manager();
}
PeopleHandler* handler() { return handler_.get(); }
void CreatePeopleHandler() {
handler_ = std::make_unique<TestingPeopleHandler>(&web_ui_, profile());
}
void SimulateSignout(const base::Value::List& args) {
handler()->HandleSignout(args);
}
content::WebUI* web_ui() { return handler()->web_ui(); }
content::WebContents* web_contents() {
return browser()->tab_strip_model()->GetActiveWebContents();
}
protected:
// testing::Test:
void SetUp() override {
BrowserWithTestWindowTest::SetUp();
identity_test_env_profile_adaptor_ =
std::make_unique<IdentityTestEnvironmentProfileAdaptor>(profile());
// Create the first tab so that web_contents() exists.
AddTab(browser(), GURL(chrome::kChromeUINewTabURL));
web_ui_.set_web_contents(web_contents());
}
SigninClient* GetSigninSlient(Profile* profile) {
return ChromeSigninClientFactory::GetForProfile(profile);
}
private:
TestingProfile::TestingFactories GetTestingFactories() override {
return IdentityTestEnvironmentProfileAdaptor::
GetIdentityTestEnvironmentFactories();
}
void TearDown() override {
handler_->set_web_ui(nullptr);
handler_->DisallowJavascript();
identity_test_env_profile_adaptor_.reset();
BrowserWithTestWindowTest::TearDown();
}
std::unique_ptr<IdentityTestEnvironmentProfileAdaptor>
identity_test_env_profile_adaptor_;
content::TestWebUI web_ui_;
std::unique_ptr<TestingPeopleHandler> handler_;
};
#if DCHECK_IS_ON()
TEST_F(PeopleHandlerSignoutTest, RevokeSyncNotAllowed) {
auto account_1 = identity_test_env()->MakePrimaryAccountAvailable(
"a@gmail.com", ConsentLevel::kSync);
EXPECT_TRUE(identity_manager()->HasPrimaryAccount(ConsentLevel::kSync));
GetSigninSlient(profile())->set_is_clear_primary_account_allowed_for_testing(
SigninClient::SignoutDecision::REVOKE_SYNC_DISALLOWED);
CreatePeopleHandler();
base::Value::List args;
args.Append(/*value=*/false);
EXPECT_DEATH(SimulateSignout(args), ".*");
}
TEST_F(PeopleHandlerSignoutTest, SignoutNotAllowedSyncOff) {
auto account_1 = identity_test_env()->MakePrimaryAccountAvailable(
"a@gmail.com", ConsentLevel::kSignin);
EXPECT_TRUE(identity_manager()->HasPrimaryAccount(ConsentLevel::kSignin));
GetSigninSlient(profile())->set_is_clear_primary_account_allowed_for_testing(
SigninClient::SignoutDecision::CLEAR_PRIMARY_ACCOUNT_DISALLOWED);
CreatePeopleHandler();
base::Value::List args;
args.Append(/*value=*/false);
EXPECT_DEATH(SimulateSignout(args), ".*");
}
#endif // DCHECK_IS_ON()
TEST_F(PeopleHandlerSignoutTest, SignoutNotAllowedSyncOn) {
auto account_1 = identity_test_env()->MakePrimaryAccountAvailable(
"a@gmail.com", ConsentLevel::kSync);
auto account_2 = identity_test_env()->MakeAccountAvailable("b@gmail.com");
EXPECT_TRUE(identity_manager()->HasPrimaryAccount(ConsentLevel::kSync));
EXPECT_EQ(2U, identity_manager()->GetAccountsWithRefreshTokens().size());
GetSigninSlient(profile())->set_is_clear_primary_account_allowed_for_testing(
SigninClient::SignoutDecision::CLEAR_PRIMARY_ACCOUNT_DISALLOWED);
EXPECT_TRUE(ChromeSigninClientFactory::GetForProfile(profile())
->IsRevokeSyncConsentAllowed());
CreatePeopleHandler();
base::Value::List args;
args.Append(/*value=*/false);
SimulateSignout(args);
EXPECT_FALSE(identity_manager()->HasPrimaryAccount(ConsentLevel::kSync));
EXPECT_TRUE(identity_manager()->HasPrimaryAccount(ConsentLevel::kSignin));
EXPECT_EQ(2U, identity_manager()->GetAccountsWithRefreshTokens().size());
// Signout not triggered on dice platforms.
EXPECT_EQ(web_contents()->GetVisibleURL().spec(), chrome::kChromeUINewTabURL);
EXPECT_NE(web_contents()->GetVisibleURL(),
GaiaUrls::GetInstance()->service_logout_url());
}
TEST_F(PeopleHandlerSignoutTest, SignoutWithSyncOn) {
auto account_1 = identity_test_env()->MakePrimaryAccountAvailable(
"a@gmail.com", ConsentLevel::kSync);
auto account_2 = identity_test_env()->MakeAccountAvailable("b@gmail.com");
EXPECT_TRUE(identity_manager()->HasPrimaryAccount(ConsentLevel::kSignin));
EXPECT_EQ(2U, identity_manager()->GetAccountsWithRefreshTokens().size());
CreatePeopleHandler();
EXPECT_NE(web_ui(), nullptr);
EXPECT_NE(nullptr, web_ui()->GetWebContents());
EXPECT_TRUE(chrome::FindBrowserWithTab(web_ui()->GetWebContents()));
base::Value::List args;
args.Append(/*value=*/false);
SimulateSignout(args);
EXPECT_EQ(web_contents()->GetVisibleURL(),
GaiaUrls::GetInstance()->LogOutURLWithContinueURL(GURL()));
EXPECT_FALSE(identity_manager()->HasPrimaryAccount(ConsentLevel::kSync));
}
TEST_F(PeopleHandlerSignoutTest, Signout) {
auto account_1 = identity_test_env()->MakePrimaryAccountAvailable(
"a@gmail.com", ConsentLevel::kSignin);
auto account_2 = identity_test_env()->MakeAccountAvailable("b@gmail.com");
EXPECT_TRUE(identity_manager()->HasPrimaryAccount(ConsentLevel::kSignin));
EXPECT_EQ(2U, identity_manager()->GetAccountsWithRefreshTokens().size());
CreatePeopleHandler();
EXPECT_FALSE(
browser()->GetFeatures().signin_view_controller()->ShowsModalDialog());
base::Value::List args;
args.Append(/*value=*/false);
SimulateSignout(args);
// The signout confirmation dialog is shown.
EXPECT_TRUE(identity_manager()->HasPrimaryAccount(ConsentLevel::kSignin));
EXPECT_TRUE(
browser()->GetFeatures().signin_view_controller()->ShowsModalDialog());
}
#endif // BUILDFLAG(ENABLE_DICE_SUPPORT)
#if BUILDFLAG(IS_CHROMEOS)
class PeopleHandlerWithCookiesSyncTest : public PeopleHandlerTest {
private:
// Enable Floating SSO feature flag.
base::test::ScopedFeatureList features_{ash::features::kFloatingSso};
};
TEST_F(PeopleHandlerWithCookiesSyncTest, SyncCookiesSupported) {
SigninUserAndTurnSyncFeatureOn();
CreatePeopleHandler();
// Feature flag enabled, policy unset.
{
const base::Value::Dict& sync_status_values =
handler_->GetSyncStatusDictionary();
std::optional<bool> sync_cookies_supported =
sync_status_values.FindBool("syncCookiesSupported");
ASSERT_TRUE(sync_cookies_supported.has_value());
EXPECT_FALSE(sync_cookies_supported.value());
}
// Feature flag enabled, policy set to false.
{
profile()->GetPrefs()->SetBoolean(prefs::kFloatingSsoEnabled, false);
const base::Value::Dict& sync_status_values =
handler_->GetSyncStatusDictionary();
std::optional<bool> sync_cookies_supported =
sync_status_values.FindBool("syncCookiesSupported");
ASSERT_TRUE(sync_cookies_supported.has_value());
EXPECT_FALSE(sync_cookies_supported.value());
}
// Feature flag enabled, policy set to true.
{
profile()->GetPrefs()->SetBoolean(prefs::kFloatingSsoEnabled, true);
const base::Value::Dict& sync_status_values =
handler_->GetSyncStatusDictionary();
std::optional<bool> sync_cookies_supported =
sync_status_values.FindBool("syncCookiesSupported");
ASSERT_TRUE(sync_cookies_supported.has_value());
EXPECT_TRUE(sync_cookies_supported.value());
}
}
#endif // BUILDFLAG(IS_CHROMEOS)
} // namespace settings
|