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
|
// Copyright 2012 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <stddef.h>
#include <array>
#include <memory>
#include <string>
#include "base/feature_list.h"
#include "base/functional/bind.h"
#include "base/functional/callback.h"
#include "base/metrics/histogram_samples.h"
#include "base/path_service.h"
#include "base/run_loop.h"
#include "base/strings/stringprintf.h"
#include "base/task/sequenced_task_runner.h"
#include "base/test/bind.h"
#include "base/test/metrics/histogram_tester.h"
#include "base/test/scoped_feature_list.h"
#include "base/test/simple_test_clock.h"
#include "base/test/test_future.h"
#include "base/time/time.h"
#include "build/build_config.h"
#include "chrome/browser/browsing_data/browsing_data_remover_browsertest_base.h"
#include "chrome/browser/browsing_data/chrome_browsing_data_remover_constants.h"
#include "chrome/browser/browsing_data/counters/cache_counter.h"
#include "chrome/browser/browsing_data/counters/site_data_counting_helper.h"
#include "chrome/browser/content_settings/host_content_settings_map_factory.h"
#include "chrome/browser/external_protocol/external_protocol_handler.h"
#include "chrome/browser/media/clear_key_cdm_test_helper.h"
#include "chrome/browser/prefs/session_startup_pref.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/signin/account_reconcilor_factory.h"
#include "chrome/browser/signin/identity_manager_factory.h"
#include "chrome/browser/sync/sync_service_factory.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/common/pref_names.h"
#include "chrome/test/base/in_process_browser_test.h"
#include "chrome/test/base/ui_test_utils.h"
#include "components/browsing_data/content/browsing_data_model.h"
#include "components/browsing_data/core/features.h"
#include "components/content_settings/core/browser/host_content_settings_map.h"
#include "components/content_settings/core/common/content_settings_utils.h"
#include "components/history/core/common/pref_names.h"
#include "components/metrics/content/subprocess_metrics_provider.h"
#include "components/nacl/common/buildflags.h"
#include "components/password_manager/core/browser/features/password_features.h"
#include "components/password_manager/core/browser/features/password_manager_features_util.h"
#include "components/prefs/pref_service.h"
#include "components/signin/core/browser/account_reconcilor.h"
#include "components/signin/public/base/signin_switches.h"
#include "components/signin/public/identity_manager/identity_manager.h"
#include "components/signin/public/identity_manager/identity_test_utils.h"
#include "components/sync/base/user_selectable_type.h"
#include "components/sync/service/sync_user_settings.h"
#include "components/sync/test/test_sync_service.h"
#include "content/public/browser/browsing_data_filter_builder.h"
#include "content/public/browser/clear_site_data_utils.h"
#include "content/public/browser/network_service_util.h"
#include "content/public/browser/storage_partition.h"
#include "content/public/browser/storage_usage_info.h"
#include "content/public/common/content_client.h"
#include "content/public/common/content_features.h"
#include "content/public/common/content_paths.h"
#include "content/public/common/content_switches.h"
#include "content/public/test/browser_test.h"
#include "content/public/test/browser_test_utils.h"
#include "content/public/test/browsing_data_remover_test_util.h"
#include "google_apis/gaia/google_service_auth_error.h"
#include "media/base/media_switches.h"
#include "media/mojo/mojom/media_types.mojom.h"
#include "media/mojo/services/video_decode_perf_history.h"
#include "media/mojo/services/webrtc_video_perf_history.h"
#include "net/base/features.h"
#include "net/cookies/cookie_partition_key.h"
#include "net/dns/mock_host_resolver.h"
#include "net/test/embedded_test_server/embedded_test_server.h"
#include "net/traffic_annotation/network_traffic_annotation_test_helper.h"
#include "storage/browser/quota/quota_manager.h"
#include "storage/browser/quota/quota_manager_proxy.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/blink/public/common/features.h"
#include "third_party/blink/public/common/features_generated.h"
#include "url/gurl.h"
#include "url/origin.h"
#if BUILDFLAG(ENABLE_LIBRARY_CDMS)
#if BUILDFLAG(IS_MAC)
#include "base/threading/platform_thread.h"
#endif
#include "base/memory/scoped_refptr.h"
#endif // BUILDFLAG(ENABLE_LIBRARY_CDMS)
#if BUILDFLAG(IS_CHROMEOS)
#include "chrome/browser/ash/net/system_proxy_manager.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/browser_process_platform_part.h"
#include "chromeos/ash/components/dbus/system_proxy/system_proxy_client.h"
#endif // BUILDFLAG(IS_CHROMEOS)
using content::BrowserThread;
using content::BrowsingDataFilterBuilder;
using testing::UnorderedElementsAre;
using testing::UnorderedElementsAreArray;
namespace {
static const char* kExampleHost = "example.com";
static const char* kLocalHost = "localhost";
static const base::Time kStartTime = base::Time::Now();
static const base::Time kLastHourTime = kStartTime - base::Hours(1);
// This enum is used in the place of base::Time because using base::Time
// as a test param causes problems on Fuchsia. See https://crbug.com/1308948 for
// details.
enum TimeEnum {
kDefault,
kStart,
kLastHour,
kMax,
};
base::Time TimeEnumToTime(TimeEnum time) {
switch (time) {
case TimeEnum::kStart:
return kStartTime;
case TimeEnum::kLastHour:
return kLastHourTime;
case TimeEnum::kMax:
return base::Time::Max();
default:
return base::Time();
}
}
std::vector<std::string> GetHistogramSuffixes(
const base::HistogramTester& tester,
const std::string& prefix) {
std::vector<std::string> types;
for (const auto& entry : tester.GetTotalCountsForPrefix(prefix)) {
types.push_back(entry.first.substr(prefix.length()));
}
return types;
}
void AppendRange(std::vector<std::string>& target,
const std::vector<std::string_view>& append) {
// Use std append_range() when c++23 is available.
target.insert(target.end(), append.begin(), append.end());
}
} // namespace
class BrowsingDataRemoverBrowserTest
: public BrowsingDataRemoverBrowserTestBase {
public:
BrowsingDataRemoverBrowserTest() {
std::vector<base::test::FeatureRef> enabled_features = {};
std::vector<base::test::FeatureRef> disabled_features = {};
#if BUILDFLAG(ENABLE_LIBRARY_CDMS)
enabled_features.push_back(media::kExternalClearKeyForTesting);
#endif
#if !BUILDFLAG(IS_ANDROID)
enabled_features.push_back(browsing_data::features::kDbdRevampDesktop);
#endif // !BUILDFLAG(IS_ANDROID)
InitFeatureLists(std::move(enabled_features), std::move(disabled_features));
}
void SetUpOnMainThread() override {
BrowsingDataRemoverBrowserTestBase::SetUpOnMainThread();
host_resolver()->AddRule(kExampleHost, "127.0.0.1");
// Explicitly disable session restore. Otherwise tests that restart the
// browser can get tab data persisted across sessions when we thought we
// deleted it.
SessionStartupPref::SetStartupPref(
GetProfile()->GetPrefs(),
SessionStartupPref(SessionStartupPref::DEFAULT));
}
void RemoveAndWait(uint64_t remove_mask) {
RemoveAndWait(remove_mask, TimeEnum::kDefault, TimeEnum::kMax);
}
void RemoveAndWait(uint64_t remove_mask, TimeEnum delete_begin) {
RemoveAndWait(remove_mask, delete_begin, TimeEnum::kMax);
}
void RemoveAndWait(uint64_t remove_mask,
TimeEnum delete_begin,
TimeEnum delete_end) {
content::BrowsingDataRemover* remover =
GetBrowser()->profile()->GetBrowsingDataRemover();
content::BrowsingDataRemoverCompletionObserver completion_observer(remover);
remover->RemoveAndReply(
TimeEnumToTime(delete_begin), TimeEnumToTime(delete_end), remove_mask,
content::BrowsingDataRemover::ORIGIN_TYPE_UNPROTECTED_WEB,
&completion_observer);
completion_observer.BlockUntilCompletion();
}
void RemoveWithFilterAndWait(
uint64_t remove_mask,
std::unique_ptr<BrowsingDataFilterBuilder> filter_builder) {
content::BrowsingDataRemover* remover =
GetBrowser()->profile()->GetBrowsingDataRemover();
content::BrowsingDataRemoverCompletionObserver completion_observer(remover);
remover->RemoveWithFilterAndReply(
base::Time(), base::Time::Max(), remove_mask,
content::BrowsingDataRemover::ORIGIN_TYPE_UNPROTECTED_WEB,
std::move(filter_builder), &completion_observer);
completion_observer.BlockUntilCompletion();
}
// Test a data type by creating a value and checking it is counted by the
// cookie counter. Then it deletes the value and checks that it has been
// deleted and the cookie counter is back to zero.
void TestSiteData(const std::string& type, TimeEnum delete_begin) {
EXPECT_EQ(0, GetSiteDataCount());
GURL url = embedded_test_server()->GetURL("/browsing_data/site_data.html");
ASSERT_TRUE(ui_test_utils::NavigateToURL(GetBrowser(), url));
EXPECT_EQ(0, GetSiteDataCount());
ExpectTotalModelCount(0);
EXPECT_FALSE(HasDataForType(type));
SetDataForType(type);
EXPECT_EQ(1, GetSiteDataCount());
// TODO(crbug.com/40218898): Use a different approach to determine presence
// of data that does not depend on UI code and has a better resolution when
// 3PSP is fully enabled. ExpectTotalModelCount(1) is not always true
// here.
EXPECT_TRUE(HasDataForType(type));
RemoveAndWait(chrome_browsing_data_remover::DATA_TYPE_SITE_DATA,
delete_begin);
EXPECT_EQ(0, GetSiteDataCount());
ExpectTotalModelCount(0);
EXPECT_FALSE(HasDataForType(type));
}
// Test that storage systems like filesystem, where just an access
// creates an empty store, are counted and deleted correctly.
void TestEmptySiteData(const std::string& type, TimeEnum delete_begin) {
EXPECT_EQ(0, GetSiteDataCount());
ExpectTotalModelCount(0);
GURL url = embedded_test_server()->GetURL("/browsing_data/site_data.html");
ASSERT_TRUE(ui_test_utils::NavigateToURL(GetBrowser(), url));
EXPECT_EQ(0, GetSiteDataCount());
ExpectTotalModelCount(0);
// Opening a store of this type creates a site data entry.
EXPECT_FALSE(HasDataForType(type));
EXPECT_EQ(1, GetSiteDataCount());
// TODO(crbug.com/40218898): Use a different approach to determine presence
// of data that does not depend on UI code and has a better resolution when
// 3PSP is fully enabled. ExpectTotalModelCount(1) is not always true
// here.
RemoveAndWait(chrome_browsing_data_remover::DATA_TYPE_SITE_DATA,
delete_begin);
EXPECT_EQ(0, GetSiteDataCount());
ExpectTotalModelCount(0);
}
inline void ExpectTotalModelCount(size_t expected) {
std::unique_ptr<BrowsingDataModel> browsing_data_model =
GetBrowsingDataModel(GetProfile());
EXPECT_EQ(expected, browsing_data_model->size());
}
void OnVideoDecodePerfInfo(base::RunLoop* run_loop,
bool* out_is_smooth,
bool* out_is_power_efficient,
bool is_smooth,
bool is_power_efficient) {
*out_is_smooth = is_smooth;
*out_is_power_efficient = is_power_efficient;
run_loop->QuitWhenIdle();
}
network::mojom::NetworkContext* network_context() const {
return GetBrowser()
->profile()
->GetDefaultStoragePartition()
->GetNetworkContext();
}
void ClearSiteDataAndWait(
const url::Origin& origin,
const std::optional<net::CookiePartitionKey>& cookie_partition_key,
const std::optional<blink::StorageKey>& storage_key,
const std::set<std::string>& storage_buckets_to_remove) {
bool partitioned_state_allowed_only =
cookie_partition_key.has_value() &&
!origin.DomainIs(cookie_partition_key->site()
.registrable_domain_or_host_for_testing());
base::RunLoop loop;
content::ClearSiteData(
GetBrowser()->profile()->GetWeakPtr(),
/*storage_partition_config=*/std::nullopt,
/*origin=*/origin, content::ClearSiteDataTypeSet::All(),
/*storage_buckets_to_remove=*/storage_buckets_to_remove,
/*avoid_closing_connections=*/true,
/*cookie_partition_key=*/cookie_partition_key,
/*storage_key=*/storage_key,
/*partitioned_state_allowed_only=*/partitioned_state_allowed_only,
/*callback=*/loop.QuitClosure());
loop.Run();
}
private:
void OnCacheSizeResult(
base::RunLoop* run_loop,
browsing_data::BrowsingDataCounter::ResultInt* out_size,
std::unique_ptr<browsing_data::BrowsingDataCounter::Result> result) {
if (!result->Finished())
return;
*out_size =
static_cast<browsing_data::BrowsingDataCounter::FinishedResult*>(
result.get())
->Value();
run_loop->Quit();
}
void SetUpCommandLine(base::CommandLine* command_line) override {
#if BUILDFLAG(ENABLE_LIBRARY_CDMS)
// Testing MediaLicenses requires additional command line parameters as
// it uses the External Clear Key CDM.
RegisterClearKeyCdm(command_line);
#endif
}
};
#if BUILDFLAG(ENABLE_DICE_SUPPORT)
// Same as BrowsingDataRemoverBrowserTest, but forces Dice to be enabled.
class DiceBrowsingDataRemoverBrowserTest
: public BrowsingDataRemoverBrowserTest {
public:
AccountInfo AddAccountToProfile(const std::string& account_id,
Profile* profile,
bool is_primary) {
auto* identity_manager = IdentityManagerFactory::GetForProfile(profile);
if (is_primary) {
DCHECK(!identity_manager->HasPrimaryAccount(signin::ConsentLevel::kSync));
return signin::MakePrimaryAccountAvailable(identity_manager,
account_id + "@gmail.com",
signin::ConsentLevel::kSync);
}
auto account_info =
signin::MakeAccountAvailable(identity_manager, account_id);
DCHECK(
identity_manager->HasAccountWithRefreshToken(account_info.account_id));
return account_info;
}
};
#endif
// Test BrowsingDataRemover for downloads.
IN_PROC_BROWSER_TEST_F(BrowsingDataRemoverBrowserTest, Download) {
DownloadAnItem();
RemoveAndWait(content::BrowsingDataRemover::DATA_TYPE_DOWNLOADS);
VerifyDownloadCount(0u);
}
// Test that the salt for media device IDs is reset when cookies are cleared.
IN_PROC_BROWSER_TEST_F(BrowsingDataRemoverBrowserTest, MediaDeviceIdSalt) {
content::RenderFrameHost* frame_host = GetBrowser()
->tab_strip_model()
->GetActiveWebContents()
->GetPrimaryMainFrame();
url::Origin origin = frame_host->GetLastCommittedOrigin();
net::SiteForCookies site_for_cookies =
net::SiteForCookies::FromOrigin(origin);
blink::StorageKey storage_key = blink::StorageKey::CreateFirstParty(origin);
base::test::TestFuture<bool, const std::string&> future;
content::GetContentClientForTesting()->browser()->GetMediaDeviceIDSalt(
frame_host, site_for_cookies, storage_key, future.GetCallback());
std::string original_salt = future.Get<1>();
RemoveAndWait(content::BrowsingDataRemover::DATA_TYPE_COOKIES);
future.Clear();
content::GetContentClientForTesting()->browser()->GetMediaDeviceIDSalt(
frame_host, site_for_cookies, storage_key, future.GetCallback());
std::string new_salt = future.Get<1>();
EXPECT_NE(original_salt, new_salt);
}
#if BUILDFLAG(ENABLE_DICE_SUPPORT)
// Test that Sync is not paused when cookies are cleared.
IN_PROC_BROWSER_TEST_F(DiceBrowsingDataRemoverBrowserTest, SyncToken) {
Profile* profile = browser()->profile();
// Set a Gaia cookie.
ASSERT_TRUE(SetGaiaCookieForProfile(profile));
// Set a Sync account and a secondary account.
const char kPrimaryAccountId[] = "primary_account_id";
AccountInfo primary_account =
AddAccountToProfile(kPrimaryAccountId, profile, /*is_primary=*/true);
const char kSecondaryAccountId[] = "secondary_account_id";
AccountInfo secondary_account =
AddAccountToProfile(kSecondaryAccountId, profile, /*is_primary=*/false);
// Clear cookies.
RemoveAndWait(content::BrowsingDataRemover::DATA_TYPE_COOKIES);
// Check that the primary account was not removed and has valid auth.
signin::IdentityManager* identity_manager =
IdentityManagerFactory::GetForProfile(profile);
EXPECT_TRUE(
identity_manager->HasAccountWithRefreshToken(primary_account.account_id));
EXPECT_FALSE(
identity_manager->HasAccountWithRefreshTokenInPersistentErrorState(
primary_account.account_id));
// Check that the secondary token was revoked.
EXPECT_FALSE(identity_manager->HasAccountWithRefreshToken(
secondary_account.account_id));
}
// Test that Sync is not paused when cookies are cleared.
IN_PROC_BROWSER_TEST_F(DiceBrowsingDataRemoverBrowserTest,
SyncTokenScopedDeletion) {
Profile* profile = browser()->profile();
// Set a Gaia cookie.
ASSERT_TRUE(SetGaiaCookieForProfile(profile));
// Set a Sync account and a secondary account.
const char kPrimaryAccountId[] = "primary_account_id";
AccountInfo primary_account =
AddAccountToProfile(kPrimaryAccountId, profile, /*is_primary=*/true);
const char kSecondaryAccountId[] = "secondary_account_id";
AccountInfo secondary_account =
AddAccountToProfile(kSecondaryAccountId, profile, /*is_primary=*/false);
// Clear cookies.
RemoveAndWait(content::BrowsingDataRemover::DATA_TYPE_COOKIES);
// Check that the Sync token was not revoked.
auto* identity_manager = IdentityManagerFactory::GetForProfile(profile);
EXPECT_TRUE(
identity_manager->HasAccountWithRefreshToken(primary_account.account_id));
EXPECT_FALSE(
identity_manager->HasAccountWithRefreshTokenInPersistentErrorState(
primary_account.account_id));
// Check that the secondary token was revoked.
EXPECT_FALSE(identity_manager->HasAccountWithRefreshToken(
secondary_account.account_id));
}
// Test that Sync is left in error when cookies are cleared.
IN_PROC_BROWSER_TEST_F(DiceBrowsingDataRemoverBrowserTest, SyncTokenError) {
Profile* profile = browser()->profile();
// Set a Gaia cookie.
ASSERT_TRUE(SetGaiaCookieForProfile(profile));
// Set a Sync account with authentication error.
const char kAccountId[] = "account_id";
AccountInfo primary_account =
AddAccountToProfile(kAccountId, profile, /*is_primary=*/true);
auto* identity_manager = IdentityManagerFactory::GetForProfile(profile);
signin::UpdatePersistentErrorOfRefreshTokenForAccount(
identity_manager, primary_account.account_id,
GoogleServiceAuthError::FromInvalidGaiaCredentialsReason(
GoogleServiceAuthError::InvalidGaiaCredentialsReason::
CREDENTIALS_REJECTED_BY_SERVER));
// Clear cookies.
RemoveAndWait(content::BrowsingDataRemover::DATA_TYPE_COOKIES);
// Check that the account was not removed and Sync was paused.
EXPECT_TRUE(
identity_manager->HasAccountWithRefreshToken(primary_account.account_id));
EXPECT_EQ(
GoogleServiceAuthError::InvalidGaiaCredentialsReason::
CREDENTIALS_REJECTED_BY_SERVER,
identity_manager
->GetErrorStateOfRefreshTokenForAccount(primary_account.account_id)
.GetInvalidGaiaCredentialsReason());
}
// Test that the tokens are revoked when cookies are cleared when there is no
// primary account.
IN_PROC_BROWSER_TEST_F(DiceBrowsingDataRemoverBrowserTest, NoSync) {
Profile* profile = browser()->profile();
// Set a Gaia cookie.
ASSERT_TRUE(SetGaiaCookieForProfile(profile));
// Set a non-Sync account.
const char kAccountId[] = "account_id";
AccountInfo secondary_account =
AddAccountToProfile(kAccountId, profile, /*is_primary=*/false);
// Clear cookies.
RemoveAndWait(content::BrowsingDataRemover::DATA_TYPE_COOKIES);
// Check that the account was removed.
auto* identity_manager = IdentityManagerFactory::GetForProfile(profile);
EXPECT_FALSE(identity_manager->HasAccountWithRefreshToken(
secondary_account.account_id));
}
#endif
// The call to Remove() should crash in debug (DCHECK), but the browser-test
// process model prevents using a death test.
#if defined(NDEBUG) && !defined(DCHECK_ALWAYS_ON)
// Test BrowsingDataRemover for prohibited downloads. Note that this only
// really exercises the code in a Release build.
IN_PROC_BROWSER_TEST_F(BrowsingDataRemoverBrowserTest, DownloadProhibited) {
PrefService* prefs = GetBrowser()->profile()->GetPrefs();
prefs->SetBoolean(prefs::kAllowDeletingBrowserHistory, false);
DownloadAnItem();
RemoveAndWait(content::BrowsingDataRemover::DATA_TYPE_DOWNLOADS);
VerifyDownloadCount(1u);
}
#endif
// Verify VideoDecodePerfHistory is cleared when deleting all history from
// beginning of time.
IN_PROC_BROWSER_TEST_F(BrowsingDataRemoverBrowserTest, VideoDecodePerfHistory) {
media::VideoDecodePerfHistory* video_decode_perf_history =
GetBrowser()->profile()->GetVideoDecodePerfHistory();
// Save a video decode record. Note: we avoid using a web page to generate the
// stats as this takes at least 5 seconds and even then is not a guarantee
// depending on scheduler. Manual injection is quick and non-flaky.
const media::VideoCodecProfile kProfile = media::VP9PROFILE_PROFILE0;
const gfx::Size kSize(100, 200);
const int kFrameRate = 30;
const int kFramesDecoded = 1000;
const int kFramesDropped = .9 * kFramesDecoded;
const int kFramesPowerEfficient = 0;
const url::Origin kOrigin = url::Origin::Create(GURL("http://example.com"));
const bool kIsTopFrame = true;
const uint64_t kPlayerId = 1234u;
media::mojom::PredictionFeatures prediction_features;
prediction_features.profile = kProfile;
prediction_features.video_size = kSize;
prediction_features.frames_per_sec = kFrameRate;
media::mojom::PredictionTargets prediction_targets;
prediction_targets.frames_decoded = kFramesDecoded;
prediction_targets.frames_dropped = kFramesDropped;
prediction_targets.frames_power_efficient = kFramesPowerEfficient;
{
base::RunLoop run_loop;
video_decode_perf_history->GetSaveCallback().Run(
ukm::kInvalidSourceId, media::learning::FeatureValue(0), kIsTopFrame,
prediction_features, prediction_targets, kPlayerId,
run_loop.QuitWhenIdleClosure());
run_loop.Run();
}
// Verify history exists.
// Expect |is_smooth| = false and |is_power_efficient| = false given that 90%
// of recorded frames were dropped and 0 were power efficient.
bool is_smooth = true;
bool is_power_efficient = true;
{
base::RunLoop run_loop;
video_decode_perf_history->GetPerfInfo(
media::mojom::PredictionFeatures::New(prediction_features),
base::BindOnce(&BrowsingDataRemoverBrowserTest::OnVideoDecodePerfInfo,
base::Unretained(this), &run_loop, &is_smooth,
&is_power_efficient));
run_loop.Run();
}
EXPECT_FALSE(is_smooth);
EXPECT_FALSE(is_power_efficient);
// Clear history.
RemoveAndWait(chrome_browsing_data_remover::DATA_TYPE_HISTORY);
// Verify history no longer exists. Both |is_smooth| and |is_power_efficient|
// should now report true because the VideoDecodePerfHistory optimistically
// returns true when it has no data.
{
base::RunLoop run_loop;
video_decode_perf_history->GetPerfInfo(
media::mojom::PredictionFeatures::New(prediction_features),
base::BindOnce(&BrowsingDataRemoverBrowserTest::OnVideoDecodePerfInfo,
base::Unretained(this), &run_loop, &is_smooth,
&is_power_efficient));
run_loop.Run();
}
EXPECT_TRUE(is_smooth);
EXPECT_TRUE(is_power_efficient);
}
// Verify WebrtcVideoPerfHistory is cleared when deleting all history from
// beginning of time.
IN_PROC_BROWSER_TEST_F(BrowsingDataRemoverBrowserTest, WebrtcVideoPerfHistory) {
media::WebrtcVideoPerfHistory* webrtc_video_perf_history =
GetBrowser()->profile()->GetWebrtcVideoPerfHistory();
// Save a video decode record. Note: we avoid using a web page to generate the
// stats as this takes at least 5 seconds and even then is not a guarantee
// depending on scheduler. Manual injection is quick and non-flaky.
const media::VideoCodecProfile kProfile = media::VP9PROFILE_PROFILE0;
const int kVideoPixels = 1920 * 1080;
const int kFrameRate = 30;
const int kFramesProcessed = 1000;
const int kKeyFramesProcessed = 11;
const float kP99ProcessingTimeMs = 100.0;
media::mojom::WebrtcPredictionFeatures features;
features.is_decode_stats = true;
features.profile = kProfile;
features.video_pixels = kVideoPixels;
features.hardware_accelerated = false;
media::mojom::WebrtcVideoStats video_stats;
video_stats.frames_processed = kFramesProcessed;
video_stats.key_frames_processed = kKeyFramesProcessed;
video_stats.p99_processing_time_ms = kP99ProcessingTimeMs;
{
base::RunLoop run_loop;
webrtc_video_perf_history->GetSaveCallback().Run(features, video_stats,
run_loop.QuitClosure());
run_loop.Run();
}
// Verify history exists.
// Expect |is_smooth| = false given that the 99th percentile processing time
// is 100 ms.
{
base::RunLoop run_loop;
webrtc_video_perf_history->GetPerfInfo(
media::mojom::WebrtcPredictionFeatures::New(features), kFrameRate,
base::BindLambdaForTesting([&](bool smooth) {
EXPECT_FALSE(smooth);
run_loop.Quit();
}));
run_loop.Run();
}
auto filter_builder = BrowsingDataFilterBuilder::Create(
BrowsingDataFilterBuilder::Mode::kDelete);
filter_builder->AddRegisterableDomain("example.com");
RemoveWithFilterAndWait(chrome_browsing_data_remover::FILTERABLE_DATA_TYPES,
std::move(filter_builder));
// This data type doesn't implement per-origin deletion so just test that
// nothing got removed.
{
base::RunLoop run_loop;
webrtc_video_perf_history->GetPerfInfo(
media::mojom::WebrtcPredictionFeatures::New(features), kFrameRate,
base::BindLambdaForTesting([&](bool smooth) {
EXPECT_FALSE(smooth);
run_loop.Quit();
}));
run_loop.Run();
}
// Clear history.
RemoveAndWait(chrome_browsing_data_remover::DATA_TYPE_HISTORY);
// Verify history no longer exists. |is_smooth| should now report true because
// the WebrtcVideoPerfHistory optimistically returns true when it has no data.
{
base::RunLoop run_loop;
webrtc_video_perf_history->GetPerfInfo(
media::mojom::WebrtcPredictionFeatures::New(features), kFrameRate,
base::BindLambdaForTesting([&](bool smooth) {
EXPECT_TRUE(smooth);
run_loop.Quit();
}));
run_loop.Run();
}
}
// Verifies that cache deletion finishes successfully. Completes deletion of
// cache should leave it empty, and partial deletion should leave nonzero
// amount of data. Note that this tests the integration of BrowsingDataRemover
// with ConditionalCacheDeletionHelper. Whether ConditionalCacheDeletionHelper
// actually deletes the correct entries is tested
// in ConditionalCacheDeletionHelperBrowsertest.
// TODO(crbug.com/41373874): check the cache size instead of stopping the server
// and loading the request again.
IN_PROC_BROWSER_TEST_F(BrowsingDataRemoverBrowserTest, Cache) {
// Load several resources.
GURL url1 = embedded_test_server()->GetURL("/cachetime");
GURL url2 = embedded_test_server()->GetURL(kExampleHost, "/cachetime");
ASSERT_FALSE(url::IsSameOriginWith(url1, url2));
EXPECT_EQ(net::OK, content::LoadBasicRequest(network_context(), url1));
EXPECT_EQ(net::OK, content::LoadBasicRequest(network_context(), url2));
// Check that the cache has been populated by revisiting these pages with the
// server stopped.
ASSERT_TRUE(embedded_test_server()->ShutdownAndWaitUntilComplete());
EXPECT_EQ(net::OK, content::LoadBasicRequest(network_context(), url1));
EXPECT_EQ(net::OK, content::LoadBasicRequest(network_context(), url2));
// Partially delete cache data. Delete data for localhost, which is the origin
// of |url1|, but not for |kExampleHost|, which is the origin of |url2|.
std::unique_ptr<BrowsingDataFilterBuilder> filter_builder =
BrowsingDataFilterBuilder::Create(
BrowsingDataFilterBuilder::Mode::kDelete);
filter_builder->AddOrigin(url::Origin::Create(url1));
RemoveWithFilterAndWait(content::BrowsingDataRemover::DATA_TYPE_CACHE,
std::move(filter_builder));
// After the partial deletion, the cache should be smaller but still nonempty.
EXPECT_NE(net::OK, content::LoadBasicRequest(network_context(), url1));
EXPECT_EQ(net::OK, content::LoadBasicRequest(network_context(), url2));
// Another partial deletion with the same filter should have no effect.
filter_builder = BrowsingDataFilterBuilder::Create(
BrowsingDataFilterBuilder::Mode::kDelete);
filter_builder->AddOrigin(url::Origin::Create(url1));
RemoveWithFilterAndWait(content::BrowsingDataRemover::DATA_TYPE_CACHE,
std::move(filter_builder));
EXPECT_NE(net::OK, content::LoadBasicRequest(network_context(), url1));
EXPECT_EQ(net::OK, content::LoadBasicRequest(network_context(), url2));
// Delete the remaining data.
RemoveAndWait(content::BrowsingDataRemover::DATA_TYPE_CACHE);
// The cache should be empty.
EXPECT_NE(net::OK, content::LoadBasicRequest(network_context(), url1));
EXPECT_NE(net::OK, content::LoadBasicRequest(network_context(), url2));
}
// Crashes the network service while clearing the HTTP cache to make sure the
// clear operation does complete.
// Note that there is a race between crashing the network service and clearing
// the cache, so the test might flakily fail if the tested behavior does not
// work.
// TODO(crbug.com/40563720): test retry behavior by validating the cache is
// empty after the crash.
IN_PROC_BROWSER_TEST_F(BrowsingDataRemoverBrowserTest,
ClearCacheAndNetworkServiceCrashes) {
if (!content::IsOutOfProcessNetworkService())
return;
// Clear the cached data with a task posted to crash the network service.
// The task should be run while waiting for the cache clearing operation to
// complete, hopefully it happens before the cache has been cleared.
base::SequencedTaskRunner::GetCurrentDefault()->PostTask(
FROM_HERE,
base::BindOnce(&content::BrowserTestBase::SimulateNetworkServiceCrash,
base::Unretained(this)));
RemoveAndWait(content::BrowsingDataRemover::DATA_TYPE_CACHE);
}
// Verifies that the network quality prefs are cleared.
IN_PROC_BROWSER_TEST_F(BrowsingDataRemoverBrowserTest, VerifyNQECacheCleared) {
base::HistogramTester histogram_tester;
RemoveAndWait(content::BrowsingDataRemover::DATA_TYPE_CACHE);
// Wait until there is at least one sample in NQE.PrefsSizeOnClearing.
bool histogram_populated = false;
for (size_t attempt = 0; attempt < 3; ++attempt) {
const std::vector<base::Bucket> buckets =
histogram_tester.GetAllSamples("NQE.PrefsSizeOnClearing");
for (const auto& bucket : buckets) {
if (bucket.count > 0) {
histogram_populated = true;
break;
}
}
if (histogram_populated)
break;
// Retry fetching the histogram since it's not populated yet.
content::FetchHistogramsFromChildProcesses();
metrics::SubprocessMetricsProvider::MergeHistogramDeltasForTesting();
base::RunLoop().RunUntilIdle();
}
histogram_tester.ExpectTotalCount("NQE.PrefsSizeOnClearing", 1);
}
IN_PROC_BROWSER_TEST_F(BrowsingDataRemoverBrowserTest,
ExternalProtocolHandlerPerOriginPrefs) {
Profile* profile = GetBrowser()->profile();
url::Origin test_origin = url::Origin::Create(GURL("https://example.test/"));
const std::string serialized_test_origin = test_origin.Serialize();
base::Value::Dict allowed_protocols_for_origin;
allowed_protocols_for_origin.Set("tel", true);
base::Value::Dict origin_pref;
origin_pref.Set(serialized_test_origin,
std::move(allowed_protocols_for_origin));
profile->GetPrefs()->SetDict(prefs::kProtocolHandlerPerOriginAllowedProtocols,
std::move(origin_pref));
ExternalProtocolHandler::BlockState block_state =
ExternalProtocolHandler::GetBlockState("tel", &test_origin, profile);
ASSERT_EQ(ExternalProtocolHandler::DONT_BLOCK, block_state);
RemoveAndWait(chrome_browsing_data_remover::DATA_TYPE_SITE_DATA);
block_state =
ExternalProtocolHandler::GetBlockState("tel", &test_origin, profile);
ASSERT_EQ(ExternalProtocolHandler::UNKNOWN, block_state);
}
IN_PROC_BROWSER_TEST_F(BrowsingDataRemoverBrowserTest, HistoryDeletion) {
const std::string kType = "History";
GURL url = embedded_test_server()->GetURL("/browsing_data/site_data.html");
// Create a new tab to avoid confusion from having a NTP navigation entry.
ui_test_utils::NavigateToURLWithDisposition(
GetBrowser(), url, WindowOpenDisposition::NEW_FOREGROUND_TAB,
ui_test_utils::BROWSER_TEST_WAIT_FOR_LOAD_STOP);
EXPECT_FALSE(HasDataForType(kType));
SetDataForType(kType);
EXPECT_TRUE(HasDataForType(kType));
// Remove history from navigation to site_data.html.
RemoveAndWait(chrome_browsing_data_remover::DATA_TYPE_HISTORY);
EXPECT_FALSE(HasDataForType(kType));
SetDataForType(kType);
EXPECT_TRUE(HasDataForType(kType));
// Remove history from previous pushState() call in setHistory().
RemoveAndWait(chrome_browsing_data_remover::DATA_TYPE_HISTORY);
EXPECT_FALSE(HasDataForType(kType));
}
// ChromeOS users cannot sign out, their account preferences can never be
// cleared.
#if !BUILDFLAG(IS_CHROMEOS)
IN_PROC_BROWSER_TEST_F(BrowsingDataRemoverBrowserTest,
ClearingCookiesAlsoClearsPasswordAccountStorageOptIn) {
const char kTestEmail[] = "foo@gmail.com";
PrefService* prefs = GetProfile()->GetPrefs();
syncer::SyncService* sync_service =
SyncServiceFactory::GetForProfile(GetProfile());
signin::IdentityManager* identity_manager =
IdentityManagerFactory::GetForProfile(GetProfile());
signin::MakePrimaryAccountAvailable(identity_manager, kTestEmail,
signin::ConsentLevel::kSignin);
// TODO(crbug.com/375024026): Revisit.
sync_service->GetUserSettings()->SetSelectedType(
syncer::UserSelectableType::kPasswords, false);
ASSERT_FALSE(password_manager::features_util::IsAccountStorageEnabled(
prefs, sync_service));
signin::ClearPrimaryAccount(identity_manager);
RemoveAndWait(chrome_browsing_data_remover::DATA_TYPE_SITE_DATA);
signin::MakePrimaryAccountAvailable(identity_manager, kTestEmail,
signin::ConsentLevel::kSignin);
EXPECT_TRUE(password_manager::features_util::IsAccountStorageEnabled(
prefs, sync_service));
}
IN_PROC_BROWSER_TEST_F(
BrowsingDataRemoverBrowserTest,
ClearingCookiesWithFilterAlsoClearsPasswordAccountStorageSetting) {
const char kTestEmail[] = "foo@gmail.com";
PrefService* prefs = GetProfile()->GetPrefs();
syncer::SyncService* sync_service =
SyncServiceFactory::GetForProfile(GetProfile());
signin::IdentityManager* identity_manager =
IdentityManagerFactory::GetForProfile(GetProfile());
signin::MakePrimaryAccountAvailable(identity_manager, kTestEmail,
signin::ConsentLevel::kSignin);
sync_service->GetUserSettings()->SetSelectedType(
syncer::UserSelectableType::kPasswords, false);
ASSERT_FALSE(password_manager::features_util::IsAccountStorageEnabled(
prefs, sync_service));
// Clearing cookies for some random domain should have no effect on the
// setting.
signin::ClearPrimaryAccount(identity_manager);
{
std::unique_ptr<BrowsingDataFilterBuilder> filter_builder =
BrowsingDataFilterBuilder::Create(
BrowsingDataFilterBuilder::Mode::kDelete);
filter_builder->AddRegisterableDomain("example.com");
RemoveWithFilterAndWait(chrome_browsing_data_remover::DATA_TYPE_SITE_DATA,
std::move(filter_builder));
}
signin::MakePrimaryAccountAvailable(identity_manager, kTestEmail,
signin::ConsentLevel::kSignin);
EXPECT_FALSE(password_manager::features_util::IsAccountStorageEnabled(
prefs, sync_service));
// Clearing cookies for google.com should clear the setting.
signin::ClearPrimaryAccount(identity_manager);
{
std::unique_ptr<BrowsingDataFilterBuilder> filter_builder =
BrowsingDataFilterBuilder::Create(
BrowsingDataFilterBuilder::Mode::kDelete);
filter_builder->AddRegisterableDomain("google.com");
RemoveWithFilterAndWait(chrome_browsing_data_remover::DATA_TYPE_SITE_DATA,
std::move(filter_builder));
}
signin::MakePrimaryAccountAvailable(identity_manager, kTestEmail,
signin::ConsentLevel::kSignin);
EXPECT_TRUE(password_manager::features_util::IsAccountStorageEnabled(
prefs, sync_service));
}
IN_PROC_BROWSER_TEST_F(BrowsingDataRemoverBrowserTest, ClearSiteData) {
const char kTestEmail[] = "foo@gmail.com";
PrefService* prefs = GetProfile()->GetPrefs();
syncer::SyncService* sync_service =
SyncServiceFactory::GetForProfile(GetProfile());
signin::IdentityManager* identity_manager =
IdentityManagerFactory::GetForProfile(GetProfile());
signin::MakePrimaryAccountAvailable(identity_manager, kTestEmail,
signin::ConsentLevel::kSignin);
const GURL kFirstPartyURL("https://google.com");
const GURL kCrossSiteURL("https://example.com");
struct TestCases {
const url::Origin origin;
const std::optional<net::CookiePartitionKey> cookie_partition_key;
const std::optional<blink::StorageKey> storage_key;
bool expects_keep_optin_pref;
};
const auto test_cases = std::to_array<TestCases>({
{
url::Origin::Create(kFirstPartyURL),
std::nullopt,
std::nullopt,
false,
},
{
url::Origin::Create(kCrossSiteURL),
std::nullopt,
std::nullopt,
true,
},
{
url::Origin::Create(kFirstPartyURL),
net::CookiePartitionKey::FromURLForTesting(kFirstPartyURL),
std::nullopt,
false,
},
{
url::Origin::Create(kFirstPartyURL),
net::CookiePartitionKey::FromURLForTesting(kFirstPartyURL),
blink::StorageKey::CreateFirstParty(
url::Origin::Create(kFirstPartyURL)),
false,
},
{
url::Origin::Create(kFirstPartyURL),
net::CookiePartitionKey::FromURLForTesting(kCrossSiteURL),
std::nullopt,
true,
},
{
url::Origin::Create(kFirstPartyURL),
net::CookiePartitionKey::FromURLForTesting(kCrossSiteURL),
blink::StorageKey::Create(
url::Origin::Create(kCrossSiteURL),
net::SchemefulSite(url::Origin::Create(kFirstPartyURL)),
blink::mojom::AncestorChainBit::kCrossSite),
true,
},
});
for (size_t i = 0; i < std::size(test_cases); i++) {
SCOPED_TRACE(base::StringPrintf("Test case %zu", i));
const auto& test_case = test_cases[i];
sync_service->GetUserSettings()->SetSelectedType(
syncer::UserSelectableType::kPasswords, false);
ASSERT_FALSE(password_manager::features_util::IsAccountStorageEnabled(
prefs, sync_service));
signin::ClearPrimaryAccount(identity_manager);
ClearSiteDataAndWait(test_case.origin, test_case.cookie_partition_key,
test_case.storage_key, {});
signin::MakePrimaryAccountAvailable(identity_manager, kTestEmail,
signin::ConsentLevel::kSignin);
if (test_case.expects_keep_optin_pref) {
EXPECT_FALSE(password_manager::features_util::IsAccountStorageEnabled(
prefs, sync_service));
} else {
EXPECT_TRUE(password_manager::features_util::IsAccountStorageEnabled(
prefs, sync_service));
}
}
}
#endif // !BUILDFLAG(IS_CHROMEOS)
// Storage Buckets
class BrowsingDataRemoverStorageBucketsBrowserTest
: public BrowsingDataRemoverBrowserTest {
public:
BrowsingDataRemoverStorageBucketsBrowserTest() {
features_.InitWithFeatures({blink::features::kStorageBuckets,
net::features::kThirdPartyStoragePartitioning},
{});
}
void ClearSiteDataAndWait(
const url::Origin& origin,
const std::optional<blink::StorageKey>& storage_key,
const std::set<std::string>& storage_buckets_to_remove) {
base::RunLoop loop;
content::ClearSiteDataTypeSet clear_site_data_types =
content::ClearSiteDataTypeSet::All();
// We're clearing some storage buckets and not all of them.
clear_site_data_types.Remove(content::ClearSiteDataType::kStorage);
content::ClearSiteData(
GetBrowser()->profile()->GetWeakPtr(),
/*storage_partition_config=*/std::nullopt,
/*origin=*/origin, clear_site_data_types,
/*storage_buckets_to_remove=*/storage_buckets_to_remove,
/*avoid_closing_connections=*/true,
/*cookie_partition_key=*/std::nullopt,
/*storage_key=*/storage_key,
/*partitioned_state_allowed_only=*/false,
/*callback=*/loop.QuitClosure());
loop.Run();
}
private:
base::test::ScopedFeatureList features_;
};
IN_PROC_BROWSER_TEST_F(BrowsingDataRemoverStorageBucketsBrowserTest,
ClearSiteDataStorageBuckets) {
GURL url("https://example.com");
url::Origin origin = url::Origin::Create(url);
const auto storage_key = blink::StorageKey::CreateFirstParty(origin);
storage::QuotaManager* quota_manager =
GetBrowser()->profile()->GetDefaultStoragePartition()->GetQuotaManager();
auto* quota_manager_proxy = quota_manager->proxy();
quota_manager_proxy->CreateBucketForTesting(
storage_key, "drafts", base::SequencedTaskRunner::GetCurrentDefault(),
base::BindOnce(
[](storage::QuotaErrorOr<storage::BucketInfo> error_or_bucket_info) {
}));
quota_manager_proxy->CreateBucketForTesting(
storage_key, "inbox", base::SequencedTaskRunner::GetCurrentDefault(),
base::BindOnce(
[](storage::QuotaErrorOr<storage::BucketInfo> error_or_bucket_info) {
}));
quota_manager_proxy->CreateBucketForTesting(
storage_key, "attachments",
base::SequencedTaskRunner::GetCurrentDefault(),
base::BindOnce(
[](storage::QuotaErrorOr<storage::BucketInfo> error_or_bucket_info) {
}));
ClearSiteDataAndWait(origin, storage_key, {"drafts", "attachments"});
quota_manager_proxy->GetBucketsForStorageKey(
storage_key,
/*delete_expired*/ false, base::SequencedTaskRunner::GetCurrentDefault(),
base::BindOnce([](storage::QuotaErrorOr<std::set<storage::BucketInfo>>
error_or_buckets) {
EXPECT_EQ(1u, error_or_buckets.value().size());
}));
}
const char kDelegateHistogramPrefix[] =
"History.ClearBrowsingData.Duration.ChromeTask.";
const char kImplHistogramPrefix[] = "History.ClearBrowsingData.Duration.Task.";
// Add data types here that support filtering and only delete data that matches
// the BrowsingDataFilterBuilder.
const std::vector<std::string_view> kSupportsOriginFilteringImpl{
"AuthCache", "EmbedderData", "HttpCache",
"NetworkErrorLogging", "PrefetchCache", "PreflightCache",
"PrerenderCache", "ReportingCache", "SharedDictionary",
"StoragePartition", "Synchronous", "TrustTokens",
};
const std::vector<std::string_view> kSupportsOriginFilteringDelegate{
#if BUILDFLAG(IS_ANDROID) || BUILDFLAG(IS_WIN)
"CdmLicenses",
#endif
"Cookies", "DisableAutoSigninForProfilePasswords",
"DomainReliability", "MediaDeviceSalts",
"Synchronous",
};
// This test ensures that all deletions that are part of FILTERABLE_DATA_TYPES
// fully support the BrowsingDataFilterBuilder if they are running for
// origin-specific deletions. Ideally, every web-visible data type should
// support filtering. If you implemented filtering already, just add your type
// to kSupportsOriginFiltering above.
//
// If it is not important that your data is cleared with per-origin deletions,
// you can add your type to kDoesNotSupportOriginFiltering and ensure that
// deletions are only performed when the filter builder
// MatchesMostOriginsAndDomains().
IN_PROC_BROWSER_TEST_F(BrowsingDataRemoverBrowserTest, FullyFilteredDataTypes) {
base::HistogramTester tester;
auto filter_builder = BrowsingDataFilterBuilder::Create(
BrowsingDataFilterBuilder::Mode::kDelete);
filter_builder->AddRegisterableDomain("example.com");
RemoveWithFilterAndWait(chrome_browsing_data_remover::FILTERABLE_DATA_TYPES,
std::move(filter_builder));
EXPECT_THAT(GetHistogramSuffixes(tester, kImplHistogramPrefix),
UnorderedElementsAreArray(kSupportsOriginFilteringImpl));
EXPECT_THAT(GetHistogramSuffixes(tester, kDelegateHistogramPrefix),
UnorderedElementsAreArray(kSupportsOriginFilteringDelegate));
}
// Add data types here that do not support the BrowsingDataFilterBuilder.
// These deletions should only run when the mode of the filter builder is
// "kPreserve" and MatchesMostOriginsAndDomains() is true. Otherwise data for
// these types will be cleared when per-origin deletions like those from the
// Clear-Site-Data header are performed.
const std::vector<std::string_view> kDoesNotSupportOriginFilteringImpl{
"CodeCaches",
"NetworkHistory",
};
const std::vector<std::string_view> kDoesNotSupportOriginFilteringDelegate{
"FaviconCacheExpiration",
#if BUILDFLAG(ENABLE_DOWNGRADE_PROCESSING)
"UserDataSnapshot",
#endif
"WebrtcEventLogs",
#if BUILDFLAG(IS_CHROMEOS)
"TpmAttestationKeys",
#endif
#if BUILDFLAG(ENABLE_NACL)
"NaclCache",
"PnaclCache",
#endif
};
// See comment on FullyFilteredDataTypes test for advice when this test fails.
IN_PROC_BROWSER_TEST_F(BrowsingDataRemoverBrowserTest, AllFilterableDataTypes) {
base::HistogramTester tester;
auto filter_builder = BrowsingDataFilterBuilder::Create(
BrowsingDataFilterBuilder::Mode::kPreserve);
filter_builder->AddRegisterableDomain("example.com");
RemoveWithFilterAndWait(chrome_browsing_data_remover::FILTERABLE_DATA_TYPES,
std::move(filter_builder));
std::vector<std::string> all_impl_types;
AppendRange(all_impl_types, kSupportsOriginFilteringImpl);
AppendRange(all_impl_types, kDoesNotSupportOriginFilteringImpl);
EXPECT_THAT(GetHistogramSuffixes(tester, kImplHistogramPrefix),
UnorderedElementsAreArray(all_impl_types));
std::vector<std::string> all_delegate_types;
AppendRange(all_delegate_types, kSupportsOriginFilteringDelegate);
AppendRange(all_delegate_types, kDoesNotSupportOriginFilteringDelegate);
EXPECT_THAT(GetHistogramSuffixes(tester, kDelegateHistogramPrefix),
UnorderedElementsAreArray(all_delegate_types));
}
// Parameterized to run tests for different deletion time ranges.
class BrowsingDataRemoverBrowserTestP
: public BrowsingDataRemoverBrowserTest,
public testing::WithParamInterface<TimeEnum> {};
IN_PROC_BROWSER_TEST_P(BrowsingDataRemoverBrowserTestP, CookieDeletion) {
TestSiteData("Cookie", GetParam());
}
IN_PROC_BROWSER_TEST_P(BrowsingDataRemoverBrowserTestP,
CookieIncognitoDeletion) {
UseIncognitoBrowser();
TestSiteData("Cookie", GetParam());
}
// Regression test for https://crbug.com/1216406.
IN_PROC_BROWSER_TEST_P(BrowsingDataRemoverBrowserTestP,
BrowserContextDestructionVsCookieRemoval) {
// Open an incognito browser.
UseIncognitoBrowser();
// Set a cookie.
const char kDataType[] = "Cookie";
GURL url = embedded_test_server()->GetURL("/browsing_data/site_data.html");
ASSERT_TRUE(ui_test_utils::NavigateToURL(GetBrowser(), url));
SetDataForType(kDataType);
EXPECT_EQ(1, GetSiteDataCount());
ExpectTotalModelCount(1);
EXPECT_TRUE(HasDataForType(kDataType));
// Start data removal. This will CreateTaskCompletionClosureForMojo and
// register it as a completion callback for mojo calls to NetworkContext
// and other StorageParition-owned mojo::Remote(s).
//
// kRemoveMask contains:
// - DATA_TYPE_SITE_DATA - cargo-culted default from other tests
// - DEFERRED_COOKIE_DELETION_DATA_TYPES - to get non-empty result from
// ChromeBrowsingDataRemoverDelegate::GetDomainsForDeferredCookieDeletion
// (which is needed to touch StoragePartition in
// BrowsingDataRemoverImpl::OnTaskComplete when it is called later,
// after starting destruction of the BrowserContext - see the description
// of the next test step below).
constexpr uint64_t kRemoveMask =
chrome_browsing_data_remover::DATA_TYPE_SITE_DATA |
chrome_browsing_data_remover::DEFERRED_COOKIE_DELETION_DATA_TYPES;
content::BrowserContext* browser_context = GetBrowser()->profile();
content::BrowsingDataRemover* remover =
browser_context->GetBrowsingDataRemover();
content::BrowsingDataRemoverCompletionObserver completion_observer(remover);
remover->RemoveAndReply(
base::Time(), // delete_begin
base::Time::Max(), // delete_end
kRemoveMask, content::BrowsingDataRemover::ORIGIN_TYPE_UNPROTECTED_WEB,
&completion_observer);
// Close the incognito browser. This will tear down its
// Profile/BrowserContext, which will tear down the StoragePartition, which
// will tear down some mojo::Remote(s), which will end up running the closures
// returned from CreateTaskCompletionClosureForMojo (see the previous test
// step), which will run BrowsingDataRemoverImpl::OnTaskComplete. In
// https://crbug.com/1216406 OnTaskComplete would attempt to use its
// `browser_context_` (half-way destructed at this point) to get a
// StoragePartition and this would lead to DumpWithoutCrashing initially (and
// potentially crashes down the line).
CloseBrowserSynchronously(GetBrowser());
// Verify that the completion observer will get notified, even if there might
// have been a failure with the removal.
completion_observer.BlockUntilCompletion();
// Expect that removing the cookies failed, because the StoragePartition has
// been already gone by the time BrowsingDataRemoverImpl::OnTaskComplete run.
EXPECT_TRUE(content::StoragePartition::REMOVE_DATA_MASK_COOKIES &
completion_observer.failed_data_types());
}
IN_PROC_BROWSER_TEST_P(BrowsingDataRemoverBrowserTestP, SessionCookieDeletion) {
TestSiteData("SessionCookie", GetParam());
}
IN_PROC_BROWSER_TEST_P(BrowsingDataRemoverBrowserTestP, LocalStorageDeletion) {
TestSiteData("LocalStorage", GetParam());
}
IN_PROC_BROWSER_TEST_P(BrowsingDataRemoverBrowserTestP,
LocalStorageIncognitoDeletion) {
UseIncognitoBrowser();
TestSiteData("LocalStorage", GetParam());
}
// TODO(crbug.com/41348517): DISABLED until session storage is working
// correctly. Add Incognito variant when this is re-enabled.
IN_PROC_BROWSER_TEST_P(BrowsingDataRemoverBrowserTestP,
DISABLED_SessionStorageDeletion) {
TestSiteData("SessionStorage", GetParam());
}
// SessionStorage is not supported by site data counting and the cookie tree
// model but we can test the web visible behavior.
IN_PROC_BROWSER_TEST_P(BrowsingDataRemoverBrowserTestP,
SessionStorageDeletionWebOnly) {
GURL url = embedded_test_server()->GetURL("/browsing_data/site_data.html");
ASSERT_TRUE(ui_test_utils::NavigateToURL(GetBrowser(), url));
const std::string type = "SessionStorage";
EXPECT_FALSE(HasDataForType(type));
SetDataForType(type);
EXPECT_TRUE(HasDataForType(type));
RemoveAndWait(chrome_browsing_data_remover::DATA_TYPE_SITE_DATA, GetParam());
EXPECT_FALSE(HasDataForType(type));
}
// Test that session storage is not counted until crbug.com/772337 is fixed.
IN_PROC_BROWSER_TEST_F(BrowsingDataRemoverBrowserTest, SessionStorageCounting) {
EXPECT_EQ(0, GetSiteDataCount());
ExpectTotalModelCount(0);
GURL url = embedded_test_server()->GetURL("/browsing_data/site_data.html");
ASSERT_TRUE(ui_test_utils::NavigateToURL(GetBrowser(), url));
EXPECT_EQ(0, GetSiteDataCount());
ExpectTotalModelCount(0);
SetDataForType("SessionStorage");
EXPECT_EQ(0, GetSiteDataCount());
ExpectTotalModelCount(0);
EXPECT_TRUE(HasDataForType("SessionStorage"));
}
IN_PROC_BROWSER_TEST_P(BrowsingDataRemoverBrowserTestP, ServiceWorkerDeletion) {
TestSiteData("ServiceWorker", GetParam());
}
IN_PROC_BROWSER_TEST_P(BrowsingDataRemoverBrowserTestP,
ServiceWorkerIncognitoDeletion) {
UseIncognitoBrowser();
TestSiteData("ServiceWorker", GetParam());
}
IN_PROC_BROWSER_TEST_P(BrowsingDataRemoverBrowserTestP, CacheStorageDeletion) {
TestSiteData("CacheStorage", GetParam());
}
IN_PROC_BROWSER_TEST_P(BrowsingDataRemoverBrowserTestP,
CacheStorageIncognitoDeletion) {
UseIncognitoBrowser();
TestSiteData("CacheStorage", GetParam());
}
IN_PROC_BROWSER_TEST_P(BrowsingDataRemoverBrowserTestP, FileSystemDeletion) {
TestSiteData("FileSystem", GetParam());
}
IN_PROC_BROWSER_TEST_P(BrowsingDataRemoverBrowserTestP,
FileSystemIncognitoDeletion) {
UseIncognitoBrowser();
TestSiteData("FileSystem", GetParam());
}
// Test that empty filesystems are deleted correctly.
IN_PROC_BROWSER_TEST_P(BrowsingDataRemoverBrowserTestP,
EmptyFileSystemDeletion) {
TestEmptySiteData("FileSystem", GetParam());
}
// Test that empty filesystems are deleted correctly in incognito mode.
IN_PROC_BROWSER_TEST_P(BrowsingDataRemoverBrowserTestP,
EmptyFileSystemIncognitoDeletion) {
UseIncognitoBrowser();
TestEmptySiteData("FileSystem", GetParam());
}
IN_PROC_BROWSER_TEST_P(BrowsingDataRemoverBrowserTestP, IndexedDbDeletion) {
TestSiteData("IndexedDb", GetParam());
}
IN_PROC_BROWSER_TEST_P(BrowsingDataRemoverBrowserTestP,
IndexedDbIncognitoDeletion) {
UseIncognitoBrowser();
TestSiteData("IndexedDb", GetParam());
}
// Test that empty indexed dbs are deleted correctly.
IN_PROC_BROWSER_TEST_P(BrowsingDataRemoverBrowserTestP, EmptyIndexedDb) {
TestEmptySiteData("IndexedDb", GetParam());
}
#if BUILDFLAG(ENABLE_LIBRARY_CDMS)
// Test Media Licenses by creating one and checking it is counted by the
// cookie counter. Then delete it and check that the cookie counter is back
// to zero.
IN_PROC_BROWSER_TEST_P(BrowsingDataRemoverBrowserTestP, MediaLicenseDeletion) {
const std::string kMediaLicenseType = "MediaLicense";
const TimeEnum delete_begin = GetParam();
EXPECT_EQ(0, GetSiteDataCount());
GURL url =
embedded_test_server()->GetURL("/browsing_data/media_license.html");
ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), url));
EXPECT_EQ(0, GetSiteDataCount());
ExpectTotalModelCount(0);
EXPECT_FALSE(HasDataForType(kMediaLicenseType));
SetDataForType(kMediaLicenseType);
EXPECT_EQ(1, GetSiteDataCount());
ExpectTotalModelCount(1);
EXPECT_TRUE(HasDataForType(kMediaLicenseType));
// Try to remove the Media Licenses using a time frame up until an hour ago,
// which should not remove the recently created Media License.
RemoveAndWait(chrome_browsing_data_remover::DATA_TYPE_SITE_DATA, delete_begin,
TimeEnum::kLastHour);
EXPECT_EQ(1, GetSiteDataCount());
ExpectTotalModelCount(1);
EXPECT_TRUE(HasDataForType(kMediaLicenseType));
// Now try with a time range that includes the current time, which should
// clear the Media License created for this test.
RemoveAndWait(chrome_browsing_data_remover::DATA_TYPE_SITE_DATA, delete_begin,
TimeEnum::kMax);
EXPECT_EQ(0, GetSiteDataCount());
ExpectTotalModelCount(0);
EXPECT_FALSE(HasDataForType(kMediaLicenseType));
}
// Create and save a media license (which will be deleted in the following
// test).
IN_PROC_BROWSER_TEST_F(BrowsingDataRemoverBrowserTest,
PRE_MediaLicenseTimedDeletion) {
const std::string kMediaLicenseType = "MediaLicense";
EXPECT_EQ(0, GetSiteDataCount());
GURL url =
embedded_test_server()->GetURL("/browsing_data/media_license.html");
ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), url));
EXPECT_EQ(0, GetSiteDataCount());
ExpectTotalModelCount(0);
EXPECT_FALSE(HasDataForType(kMediaLicenseType));
SetDataForType(kMediaLicenseType);
EXPECT_EQ(1, GetSiteDataCount());
ExpectTotalModelCount(1);
EXPECT_TRUE(HasDataForType(kMediaLicenseType));
}
// Create and save a second media license, and then verify that timed deletion
// selects the correct license to delete.
IN_PROC_BROWSER_TEST_F(BrowsingDataRemoverBrowserTest,
MediaLicenseTimedDeletion) {
const std::string kMediaLicenseType = "MediaLicense";
// As the PRE_ test should run first, there should be one media license
// still stored. The time of it's creation should be sometime before
// this test starts. This license will be for a different origin, and so wont
// affect HasDataForType, but it still exists.
LOG(INFO) << "MediaLicenseTimedDeletion starting @ " << kStartTime;
EXPECT_EQ(1, GetSiteDataCount());
GURL url =
embedded_test_server()->GetURL("/browsing_data/media_license.html");
ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), url));
#if BUILDFLAG(IS_MAC)
// On some Macs the file system uses second granularity. So before
// creating the second license, delay for 1 second so that the new
// license's time is not the same second as |kStartTime|.
base::PlatformThread::Sleep(base::Seconds(1));
#endif
// This test should use a different domain than the PRE_ test, so there
// should be no existing media license for it.
// Note that checking HasDataForType() may result in an empty file being
// created. Deleting licenses checks for any file within the time range
// specified in order to delete all the files for the domain, so this may
// cause problems (especially with Macs that use second granularity).
// http://crbug.com/909829.
EXPECT_FALSE(HasDataForType(kMediaLicenseType));
SetDataForType(kMediaLicenseType);
ExpectTotalModelCount(1);
EXPECT_TRUE(HasDataForType(kMediaLicenseType));
// As Clear Browsing Data typically deletes recent data (e.g. last hour,
// last day, etc.), try to remove the Media Licenses created since the
// the start of this test, which should only delete the just created
// media license, and leave the one created by the PRE_ test.
RemoveAndWait(chrome_browsing_data_remover::DATA_TYPE_SITE_DATA,
TimeEnum::kStart);
EXPECT_EQ(1, GetSiteDataCount());
ExpectTotalModelCount(1);
EXPECT_FALSE(HasDataForType(kMediaLicenseType));
// Now try with a time range that includes all time, which should
// clear the media license created by the PRE_ test.
RemoveAndWait(chrome_browsing_data_remover::DATA_TYPE_SITE_DATA);
EXPECT_EQ(0, GetSiteDataCount());
ExpectTotalModelCount(0);
}
IN_PROC_BROWSER_TEST_F(BrowsingDataRemoverBrowserTest,
MediaLicenseDeletionWithFilter) {
const std::string kMediaLicenseType = "MediaLicense";
GURL url =
embedded_test_server()->GetURL("/browsing_data/media_license.html");
ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), url));
ExpectTotalModelCount(0);
EXPECT_FALSE(HasDataForType(kMediaLicenseType));
SetDataForType(kMediaLicenseType);
ExpectTotalModelCount(1);
EXPECT_TRUE(HasDataForType(kMediaLicenseType));
// Try to remove the Media Licenses using a deletelist that doesn't include
// the current URL. Media License should not be deleted.
std::unique_ptr<BrowsingDataFilterBuilder> filter_builder =
BrowsingDataFilterBuilder::Create(
BrowsingDataFilterBuilder::Mode::kDelete);
filter_builder->AddOrigin(
url::Origin::CreateFromNormalizedTuple("https", "test-origin", 443));
RemoveWithFilterAndWait(
content::BrowsingDataRemover::DATA_TYPE_MEDIA_LICENSES,
std::move(filter_builder));
ExpectTotalModelCount(1);
// Now try with a preservelist that includes the current URL. Media License
// should not be deleted.
filter_builder = BrowsingDataFilterBuilder::Create(
BrowsingDataFilterBuilder::Mode::kPreserve);
filter_builder->AddOrigin(url::Origin::Create(url));
RemoveWithFilterAndWait(
content::BrowsingDataRemover::DATA_TYPE_MEDIA_LICENSES,
std::move(filter_builder));
ExpectTotalModelCount(1);
// Now try with a deletelist that includes the current URL. Media License
// should be deleted this time.
filter_builder = BrowsingDataFilterBuilder::Create(
BrowsingDataFilterBuilder::Mode::kDelete);
filter_builder->AddOrigin(url::Origin::Create(url));
RemoveWithFilterAndWait(
content::BrowsingDataRemover::DATA_TYPE_MEDIA_LICENSES,
std::move(filter_builder));
ExpectTotalModelCount(0);
}
#endif // BUILDFLAG(ENABLE_LIBRARY_CDMS)
const std::vector<std::string> kStorageTypes{
"Cookie", "LocalStorage", "FileSystem", "SessionStorage",
"IndexedDb", "ServiceWorker", "CacheStorage", "MediaLicense",
};
// Test that storage doesn't leave any traces on disk.
IN_PROC_BROWSER_TEST_F(BrowsingDataRemoverBrowserTest,
PRE_PRE_StorageRemovedFromDisk) {
// Checking leveldb content fails in most cases. See
// https://crbug.com/1238325.
ASSERT_EQ(0, CheckUserDirectoryForString(kLocalHost, {},
/*check_leveldb_content=*/false));
ASSERT_EQ(0, GetSiteDataCount());
ExpectTotalModelCount(0);
// To use secure-only features on a host name, we need an https server.
net::EmbeddedTestServer https_server(net::EmbeddedTestServer::TYPE_HTTPS);
https_server.SetSSLConfig(
net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
base::FilePath path;
base::PathService::Get(content::DIR_TEST_DATA, &path);
https_server.ServeFilesFromDirectory(path);
ASSERT_TRUE(https_server.Start());
GURL url = https_server.GetURL(kLocalHost, "/browsing_data/site_data.html");
ASSERT_TRUE(ui_test_utils::NavigateToURL(GetBrowser(), url));
for (const std::string& type : kStorageTypes) {
SetDataForType(type);
EXPECT_TRUE(HasDataForType(type));
}
// TODO(crbug.com/40577815): Add more datatypes for testing. E.g.
// notifications, payment handler, content settings, autofill, ...?
}
// Restart after creating the data to ensure that everything was written to
// disk.
//
// This depends on session restore being explicitly disabled by the test harness
// above. Otherwise, we'll restore the tabs, delete the data on disk, and the
// still-open tabs can get re-persisted.
IN_PROC_BROWSER_TEST_F(BrowsingDataRemoverBrowserTest,
PRE_StorageRemovedFromDisk) {
EXPECT_EQ(1, GetSiteDataCount());
ExpectTotalModelCount(1);
RemoveAndWait(chrome_browsing_data_remover::DATA_TYPE_SITE_DATA |
content::BrowsingDataRemover::DATA_TYPE_CACHE |
chrome_browsing_data_remover::DATA_TYPE_HISTORY |
chrome_browsing_data_remover::DATA_TYPE_CONTENT_SETTINGS);
EXPECT_EQ(0, GetSiteDataCount());
ExpectTotalModelCount(0);
}
// Check if any data remains after a deletion and a Chrome restart to force
// all writes to be finished.
IN_PROC_BROWSER_TEST_F(BrowsingDataRemoverBrowserTest, StorageRemovedFromDisk) {
// Deletions should remove all traces of browsing data from disk
// but there are a few bugs that need to be fixed.
// Any addition to this list must have an associated TODO.
static const std::vector<std::string> ignore_file_patterns = {
#if BUILDFLAG(IS_CHROMEOS)
// TODO(crbug.com/40577815): Many leveldb files remain on ChromeOS. I
// couldn't reproduce this in manual testing, so it might be a timing
// issue when Chrome is closed after the second test?
"[0-9]{6}",
#endif
};
int found = CheckUserDirectoryForString(kLocalHost, ignore_file_patterns,
/*check_leveldb_content=*/false);
EXPECT_EQ(0, found) << "A non-ignored file contains the hostname.";
}
const std::vector<std::string> kSessionOnlyStorageTestTypes{
"Cookie", "LocalStorage", "FileSystem", "SessionStorage",
"IndexedDb", "ServiceWorker", "CacheStorage", "MediaLicense",
};
// Test that storage gets deleted if marked as SessionOnly.
IN_PROC_BROWSER_TEST_F(BrowsingDataRemoverBrowserTest,
PRE_SessionOnlyStorageRemoved) {
ExpectTotalModelCount(0);
GURL url = embedded_test_server()->GetURL("/browsing_data/site_data.html");
ASSERT_TRUE(ui_test_utils::NavigateToURL(GetBrowser(), url));
for (const std::string& type : kSessionOnlyStorageTestTypes) {
SetDataForType(type);
EXPECT_TRUE(HasDataForType(type));
}
ExpectTotalModelCount(1);
HostContentSettingsMapFactory::GetForProfile(GetBrowser()->profile())
->SetDefaultContentSetting(ContentSettingsType::COOKIES,
CONTENT_SETTING_SESSION_ONLY);
}
// TODO(crbug.com/40925336): Test is flaky on Mac.
#if BUILDFLAG(IS_MAC)
#define MAYBE_SessionOnlyStorageRemoved DISABLED_SessionOnlyStorageRemoved
#else
#define MAYBE_SessionOnlyStorageRemoved SessionOnlyStorageRemoved
#endif
// Restart to delete session only storage.
IN_PROC_BROWSER_TEST_F(BrowsingDataRemoverBrowserTest,
MAYBE_SessionOnlyStorageRemoved) {
// All cookies should have been deleted.
ExpectTotalModelCount(0);
GURL url = embedded_test_server()->GetURL("/browsing_data/site_data.html");
ASSERT_TRUE(ui_test_utils::NavigateToURL(GetBrowser(), url));
for (const std::string& type : kSessionOnlyStorageTestTypes) {
EXPECT_FALSE(HasDataForType(type));
}
}
#if BUILDFLAG(IS_CHROMEOS)
// Test that removing passwords, when System-proxy is enabled on Chrome OS,
// sends a request to System-proxy to clear the cached user credentials.
IN_PROC_BROWSER_TEST_F(BrowsingDataRemoverBrowserTest,
SystemProxyClearsUserCredentials_RemovePasswords) {
ash::SystemProxyManager::Get()->SetSystemProxyEnabledForTest(true);
EXPECT_EQ(0, ash::SystemProxyClient::Get()
->GetTestInterface()
->GetClearUserCredentialsCount());
RemoveAndWait(chrome_browsing_data_remover::DATA_TYPE_PASSWORDS);
EXPECT_EQ(1, ash::SystemProxyClient::Get()
->GetTestInterface()
->GetClearUserCredentialsCount());
}
// Test that removing cookies, when System-proxy is enabled on Chrome OS and
// kDbdRevampDesktop is enabled, sends a request to System-proxy to clear the
// cached user credentials.
IN_PROC_BROWSER_TEST_F(BrowsingDataRemoverBrowserTest,
SystemProxyClearsUserCredentials_RemoveCookies) {
ash::SystemProxyManager::Get()->SetSystemProxyEnabledForTest(true);
EXPECT_EQ(0, ash::SystemProxyClient::Get()
->GetTestInterface()
->GetClearUserCredentialsCount());
RemoveAndWait(content::BrowsingDataRemover::DATA_TYPE_COOKIES);
EXPECT_EQ(1, ash::SystemProxyClient::Get()
->GetTestInterface()
->GetClearUserCredentialsCount());
}
#endif // BUILDFLAG(IS_CHROMEOS)
IN_PROC_BROWSER_TEST_F(BrowsingDataRemoverBrowserTest,
RelatedWebsiteSetsDeletion) {
const GURL kPrimaryUrl("https://subdomain.example.com:112");
const GURL kSecondaryUrl("https://subidubi.testsite.com:55");
HostContentSettingsMap* settings_map =
HostContentSettingsMapFactory::GetForProfile(GetProfile());
// Setting the HostContentSettingsMap's clock to test last_modified of
// RuleMetaData below.
base::SimpleTestClock test_clock;
settings_map->SetClockForTesting(&test_clock);
test_clock.SetNow(base::Time::Now());
// Expected setting for the default grant.
const ContentSettingPatternSource kExpectedSettingDefault(
ContentSettingsPattern::Wildcard(), ContentSettingsPattern::Wildcard(),
content_settings::ContentSettingToValue(CONTENT_SETTING_ASK),
content_settings::ProviderType::kDefaultProvider,
/*incognito=*/false);
// Check that there are only default grants.
ASSERT_THAT(
settings_map->GetSettingsForOneType(ContentSettingsType::STORAGE_ACCESS),
UnorderedElementsAre(kExpectedSettingDefault));
ASSERT_THAT(settings_map->GetSettingsForOneType(
ContentSettingsType::TOP_LEVEL_STORAGE_ACCESS),
UnorderedElementsAre(kExpectedSettingDefault));
// Set RWS grants.
content_settings::ContentSettingConstraints constraints;
constraints.set_session_model(content_settings::mojom::SessionModel::DURABLE);
constraints.set_decided_by_related_website_sets(true);
settings_map->SetContentSettingDefaultScope(
kPrimaryUrl, kSecondaryUrl, ContentSettingsType::STORAGE_ACCESS,
CONTENT_SETTING_ALLOW, constraints);
settings_map->SetContentSettingDefaultScope(
kPrimaryUrl, kSecondaryUrl, ContentSettingsType::TOP_LEVEL_STORAGE_ACCESS,
CONTENT_SETTING_ALLOW, constraints);
// Check that the grants were set.
content_settings::RuleMetaData expected_metadata;
expected_metadata.SetFromConstraints(constraints);
expected_metadata.set_last_modified(test_clock.Now());
EXPECT_THAT(
settings_map->GetSettingsForOneType(ContentSettingsType::STORAGE_ACCESS),
UnorderedElementsAre(
kExpectedSettingDefault,
ContentSettingPatternSource(
ContentSettingsPattern::FromURLToSchemefulSitePattern(
GURL(kPrimaryUrl)), // https://[*.]example.com
ContentSettingsPattern::FromURLToSchemefulSitePattern(
GURL(kSecondaryUrl)), // https://[*.]testsite.com
content_settings::ContentSettingToValue(CONTENT_SETTING_ALLOW),
content_settings::ProviderType::kPrefProvider,
/*incognito=*/false, expected_metadata.Clone())));
EXPECT_THAT(
settings_map->GetSettingsForOneType(
ContentSettingsType::TOP_LEVEL_STORAGE_ACCESS),
UnorderedElementsAre(
kExpectedSettingDefault,
ContentSettingPatternSource(
ContentSettingsPattern::FromURLNoWildcard(
GURL(kPrimaryUrl)), // https://subdomain.example.com:112
ContentSettingsPattern::FromURLToSchemefulSitePattern(
GURL(kSecondaryUrl)),
content_settings::ContentSettingToValue(CONTENT_SETTING_ALLOW),
content_settings::ProviderType::kPrefProvider,
/*incognito=*/false, expected_metadata.Clone())));
// Remove Related Website Sets storage grants.
std::unique_ptr<BrowsingDataFilterBuilder> filter_builder =
BrowsingDataFilterBuilder::Create(
BrowsingDataFilterBuilder::Mode::kDelete);
filter_builder->AddOrigin(url::Origin::Create(kPrimaryUrl));
RemoveWithFilterAndWait(
content::BrowsingDataRemover::DATA_TYPE_RELATED_WEBSITE_SETS_PERMISSIONS,
std::move(filter_builder));
// Check that there's only the default grant left.
EXPECT_THAT(
settings_map->GetSettingsForOneType(ContentSettingsType::STORAGE_ACCESS),
UnorderedElementsAre(kExpectedSettingDefault));
EXPECT_THAT(settings_map->GetSettingsForOneType(
ContentSettingsType::TOP_LEVEL_STORAGE_ACCESS),
UnorderedElementsAre(kExpectedSettingDefault));
}
// Some storage backend use a different code path for full deletions and
// partial deletions, so we need to test both.
INSTANTIATE_TEST_SUITE_P(
All,
BrowsingDataRemoverBrowserTestP,
::testing::Values(TimeEnum::kDefault, TimeEnum::kLastHour),
[](const ::testing::TestParamInfo<
BrowsingDataRemoverBrowserTestP::ParamType>& info) {
switch (info.param) {
case TimeEnum::kDefault:
return "kDefault";
case TimeEnum::kLastHour:
return "kLastHour";
case TimeEnum::kStart:
return "kStart";
case TimeEnum::kMax:
return "kMax";
}
});
|