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
|
// Copyright 2022 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/browser/btm/btm_database.h"
#include <cstdio>
#include <optional>
#include <string>
#include <vector>
#include "base/files/file_path.h"
#include "base/files/file_util.h"
#include "base/files/scoped_temp_dir.h"
#include "base/path_service.h"
#include "base/strings/strcat.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_split.h"
#include "base/strings/stringprintf.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/time/time.h"
#include "content/browser/btm/btm_test_utils.h"
#include "content/browser/btm/btm_utils.h"
#include "content/public/common/btm_utils.h"
#include "content/public/common/content_features.h"
#include "sql/database.h"
#include "sql/sqlite_result_code_values.h"
#include "sql/test/scoped_error_expecter.h"
#include "sql/test/test_helpers.h"
#include "testing/gmock/include/gmock/gmock-matchers.h"
#include "testing/gtest/include/gtest/gtest.h"
using base::Time;
using testing::Optional;
namespace content {
namespace {
class TestDatabase : public BtmDatabase {
public:
explicit TestDatabase(const std::optional<base::FilePath>& db_path)
: BtmDatabase(db_path) {}
void LogDatabaseMetricsForTesting() { LogDatabaseMetrics(); }
};
enum ColumnType {
kSiteStorage,
kUserActivation,
kStatefulBounce,
kBounce,
kWebAuthnAssertion
};
} // namespace
class BtmDatabaseTest : public testing::Test {
public:
explicit BtmDatabaseTest(bool in_memory) : in_memory_(in_memory) {}
// Small delta used to test before/after timestamps made with
// FromSecondsSinceUnixEpoch.
base::TimeDelta tiny_delta = base::Milliseconds(1);
TimestampRange ToRange(base::Time& time) { return {{time, time}}; }
protected:
base::SimpleTestClock clock_;
std::unique_ptr<TestDatabase> db_;
base::ScopedTempDir temp_dir_;
base::FilePath db_path_;
base::test::ScopedFeatureList features_;
// Test setup.
void SetUp() override {
if (in_memory_) {
db_ = std::make_unique<TestDatabase>(std::nullopt);
} else {
ASSERT_TRUE(temp_dir_.CreateUniqueTempDir());
db_path_ = temp_dir_.GetPath().AppendASCII("DIPS.db");
db_ = std::make_unique<TestDatabase>(db_path_);
}
ASSERT_TRUE(db_->CheckDBInit());
db_->SetClockForTesting(clock());
}
void TearDown() override {
db_.reset();
// Deletes temporary directory from on-disk tests
if (!in_memory_) {
ASSERT_TRUE(temp_dir_.Delete());
}
}
base::Time Now() { return clock_.Now(); }
void AdvanceTimeTo(base::Time now) {
ASSERT_GE(now, clock_.Now());
clock_.SetNow(now);
}
void AdvanceTimeBy(base::TimeDelta delta) { clock_.Advance(delta); }
base::Clock* clock() { return &clock_; }
private:
bool in_memory_;
};
class BtmDatabaseErrorHistogramsTest
: public BtmDatabaseTest,
public testing::WithParamInterface<bool> {
public:
BtmDatabaseErrorHistogramsTest() : BtmDatabaseTest(GetParam()) {}
void SetUp() override {
BtmDatabaseTest::SetUp();
// Use inf ttl to prevent interactions (including web authn assertions) from
// expiring unintentionally.
features_.InitAndEnableFeatureWithParameters(features::kBtmTtl,
{{"interaction_ttl", "inf"}});
}
};
TEST_P(BtmDatabaseErrorHistogramsTest,
StatefulBounceTimesNotWithinBounceTimes) {
base::HistogramTester histograms;
// `stateful_bounce` start is outside of `bounce_times`.
ASSERT_TRUE(db_->ExecuteSqlForTesting(
"INSERT INTO "
"bounces(site,first_stateful_bounce_time,last_stateful_bounce_time,"
"first_bounce_time,last_bounce_time) VALUES ('site.test',1,3,2,5)"));
db_->Read("site.test");
histograms.ExpectUniqueSample(
"Privacy.DIPS.DIPSErrorCodes",
BtmErrorCode::kRead_BounceTimesIsntSupersetOfStatefulBounces, 1);
// `stateful_bounce` end is outside of `bounce_times`.
ASSERT_TRUE(db_->ExecuteSqlForTesting(
"INSERT OR REPLACE INTO "
"bounces(site,first_stateful_bounce_time,last_stateful_bounce_time,"
"first_bounce_time,last_bounce_time) VALUES ('site.test',2,5,2,3)"));
db_->Read("site.test");
histograms.ExpectUniqueSample(
"Privacy.DIPS.DIPSErrorCodes",
BtmErrorCode::kRead_BounceTimesIsntSupersetOfStatefulBounces, 2);
// stateful_bounce is set but `bounce_times` is NULL.
ASSERT_TRUE(db_->ExecuteSqlForTesting(
"INSERT OR REPLACE INTO "
"bounces(site,first_stateful_bounce_time,last_stateful_bounce_time,"
"first_bounce_time,last_bounce_time) VALUES "
"('site.test',2,3,NULL,NULL)"));
db_->Read("site.test");
histograms.ExpectUniqueSample(
"Privacy.DIPS.DIPSErrorCodes",
BtmErrorCode::kRead_BounceTimesIsntSupersetOfStatefulBounces, 3);
}
// Verifies the histograms logged for the success case.
TEST_P(BtmDatabaseErrorHistogramsTest, StatefulBounceTimesIsWithinBounceTimes) {
base::HistogramTester histograms;
// Both `stateful_bounce_time` fall within the `bounce_time` range.
ASSERT_TRUE(db_->ExecuteSqlForTesting(
"INSERT INTO "
"bounces(site,first_stateful_bounce_time,last_stateful_bounce_time,"
"first_bounce_time,last_bounce_time) VALUES ('site.test',2,4,1,5)"));
db_->Read("site.test");
histograms.ExpectBucketCount(
"Privacy.DIPS.DIPSErrorCodes",
BtmErrorCode::kRead_BounceTimesIsntSupersetOfStatefulBounces, 0);
histograms.ExpectBucketCount("Privacy.DIPS.DIPSErrorCodes",
BtmErrorCode::kRead_None, 1);
}
TEST_P(BtmDatabaseErrorHistogramsTest, kRead_EmptySite_InDb) {
base::HistogramTester histograms;
// Manually write an entry with an empty string `site`, then try to read it.
ASSERT_TRUE(db_->ExecuteSqlForTesting(
"INSERT INTO "
"bounces(site,first_stateful_bounce_time,last_stateful_bounce_time,"
"first_bounce_time,last_bounce_time) VALUES ('',2,4,1,5)"));
EXPECT_EQ(db_->GetEntryCount(BtmDatabaseTable::kBounces), 1u);
EXPECT_EQ(db_->Read(""), std::nullopt);
histograms.ExpectUniqueSample("Privacy.DIPS.DIPSErrorCodes",
BtmErrorCode::kRead_EmptySite_InDb, 1);
// Verify the entry was deleted during the read attempt.
EXPECT_EQ(db_->GetEntryCount(BtmDatabaseTable::kBounces), 0u);
}
TEST_P(BtmDatabaseErrorHistogramsTest, Read_EmptySite_NotInDb) {
base::HistogramTester histograms;
EXPECT_EQ(db_->Read(""), std::nullopt);
histograms.ExpectUniqueSample("Privacy.DIPS.DIPSErrorCodes",
BtmErrorCode::kRead_EmptySite_NotInDb, 1);
}
TEST_P(BtmDatabaseErrorHistogramsTest, Write_EmptySite) {
base::HistogramTester histograms;
// Attempt to add a bounce for an empty site.
const std::string empty_site = GetSiteForBtm(GURL(""));
TimestampRange bounce(
{Time::FromSecondsSinceUnixEpoch(1), Time::FromSecondsSinceUnixEpoch(1)});
EXPECT_FALSE(db_->Write(empty_site, TimestampRange(), TimestampRange(),
TimestampRange(), bounce, TimestampRange()));
histograms.ExpectUniqueSample("Privacy.DIPS.DIPSErrorCodes",
BtmErrorCode::kWrite_EmptySite, 1);
}
// Verifies the histograms logged for the success case (i.e., writing an entry
// with a non-empty site).
TEST_P(BtmDatabaseErrorHistogramsTest, Write_None) {
base::HistogramTester histograms;
// Add a bounce for a non-empty site.
const std::string site = GetSiteForBtm(GURL("https://example.test"));
TimestampRange bounce(
{Time::FromSecondsSinceUnixEpoch(1), Time::FromSecondsSinceUnixEpoch(1)});
EXPECT_TRUE(db_->Write(site, TimestampRange(), TimestampRange(),
TimestampRange(), bounce, TimestampRange()));
histograms.ExpectUniqueSample("Privacy.DIPS.DIPSErrorCodes",
BtmErrorCode::kWrite_None, 1);
}
INSTANTIATE_TEST_SUITE_P(All,
BtmDatabaseErrorHistogramsTest,
::testing::Bool());
// A test class that lets us ensure that we can add, read, update, and delete
// bounces for all columns in the BtmDatabase. Parameterized over whether the
// db is in memory, and what column we're testing.
class BtmDatabaseAllColumnTest
: public BtmDatabaseTest,
public testing::WithParamInterface<std::tuple<bool, ColumnType>> {
public:
BtmDatabaseAllColumnTest()
: BtmDatabaseTest(std::get<0>(GetParam())),
column_(std::get<1>(GetParam())) {}
void SetUp() override {
BtmDatabaseTest::SetUp();
// Use inf ttl to prevent interactions (including webauthn assertions) from
// expiring unintentionally.
features_.InitAndEnableFeatureWithParameters(features::kBtmTtl,
{{"interaction_ttl", "inf"}});
}
protected:
bool IsBounce(ColumnType column) {
return column == kBounce || column == kStatefulBounce;
}
// Uses `times` to write to the first and last columns for `column_` in the
// `site` row in `db`. This also writes the empty time stamps to all other
// columns in `db` that are unrelated.
bool WriteToVariableColumn(const std::string& site,
const TimestampRange& times) {
return db_->Write(site, column_ == kSiteStorage ? times : TimestampRange(),
column_ == kUserActivation ? times : TimestampRange(),
column_ == kStatefulBounce ? times : TimestampRange(),
IsBounce(column_) ? times : TimestampRange(),
column_ == kWebAuthnAssertion ? times : TimestampRange());
}
TimestampRange ReadValueForVariableColumn(std::optional<StateValue> value) {
switch (column_) {
case ColumnType::kSiteStorage:
return value->site_storage_times;
case ColumnType::kUserActivation:
return value->user_activation_times;
case ColumnType::kStatefulBounce:
return value->stateful_bounce_times;
case ColumnType::kBounce:
return value->bounce_times;
case ColumnType::kWebAuthnAssertion:
return value->web_authn_assertion_times;
}
}
std::pair<std::string, std::string> GetVariableColumnNames() {
switch (column_) {
case ColumnType::kSiteStorage:
return {"first_site_storage_time", "last_site_storage_time"};
case ColumnType::kUserActivation:
return {"first_user_activation_time", "last_user_activation_time"};
case ColumnType::kStatefulBounce:
return {"first_stateful_bounce_time", "last_stateful_bounce_time"};
case ColumnType::kBounce:
return {"first_bounce_time", "last_bounce_time"};
case ColumnType::kWebAuthnAssertion:
return {"first_web_authn_assertion_time",
"last_web_authn_assertion_time"};
}
}
private:
ColumnType column_;
};
// Test adding entries in the `bounces` table of the BtmDatabase.
TEST_P(BtmDatabaseAllColumnTest, AddBounce) {
// Add a bounce for site.
const std::string site = GetSiteForBtm(GURL("http://www.youtube.com/"));
TimestampRange bounce_1(
{Time::FromSecondsSinceUnixEpoch(1), Time::FromSecondsSinceUnixEpoch(1)});
EXPECT_TRUE(WriteToVariableColumn(site, bounce_1));
// Verify that site is in `bounces` using Read().
EXPECT_TRUE(db_->Read(site).has_value());
}
// Test updating entries in the `bounces` table of the BtmDatabase.
TEST_P(BtmDatabaseAllColumnTest, UpdateBounce) {
// Add a bounce for site.
const std::string site = GetSiteForBtm(GURL("http://www.youtube.com/"));
TimestampRange bounce_1(
{Time::FromSecondsSinceUnixEpoch(1), Time::FromSecondsSinceUnixEpoch(1)});
EXPECT_TRUE(WriteToVariableColumn(site, bounce_1));
// Verify that site's entry in `bounces` is now at t = 1
EXPECT_EQ(ReadValueForVariableColumn(db_->Read(site)), bounce_1);
// Update site's entry with a bounce at t = 2
TimestampRange bounce_2(
{Time::FromSecondsSinceUnixEpoch(2), Time::FromSecondsSinceUnixEpoch(3)});
EXPECT_TRUE(WriteToVariableColumn(site, bounce_2));
// Verify that site's entry in `bounces` is now at t = 2
EXPECT_EQ(ReadValueForVariableColumn(db_->Read(site)), bounce_2);
}
// Test deleting an entry from the `bounces` table of the BtmDatabase.
TEST_P(BtmDatabaseAllColumnTest, DeleteBounce) {
// Add a bounce for site.
const std::string site = GetSiteForBtm(GURL("http://www.youtube.com/"));
TimestampRange bounce(
{Time::FromSecondsSinceUnixEpoch(1), Time::FromSecondsSinceUnixEpoch(1)});
EXPECT_TRUE(WriteToVariableColumn(site, bounce));
// Verify that site has state tracked in bounces.
EXPECT_TRUE(db_->Read(site).has_value());
// Delete site's entry in bounces.
EXPECT_TRUE(db_->RemoveRow(BtmDatabaseTable::kBounces, site));
// Query the bounces for site, making sure there is no state now.
EXPECT_FALSE(db_->Read(site).has_value());
}
// Test deleting many entries from the `bounces` table of the BtmDatabase.
TEST_P(BtmDatabaseAllColumnTest, DeleteSeveralBounces) {
// Add a bounce for site.
const std::string site1 = GetSiteForBtm(GURL("http://www.youtube.com/"));
const std::string site2 = GetSiteForBtm(GURL("http://www.picasa.com/"));
TimestampRange bounce(
{Time::FromSecondsSinceUnixEpoch(1), Time::FromSecondsSinceUnixEpoch(1)});
EXPECT_TRUE(WriteToVariableColumn(site1, bounce));
EXPECT_TRUE(WriteToVariableColumn(site2, bounce));
// Verify that both sites are in the bounces table.
EXPECT_TRUE(db_->Read(site1).has_value());
EXPECT_TRUE(db_->Read(site2).has_value());
// Delete site's entry in bounces.
EXPECT_TRUE(db_->RemoveRows(BtmDatabaseTable::kBounces, {site1, site2}));
// Query the bounces for site, making sure there is no state now.
EXPECT_FALSE(db_->Read(site1).has_value());
EXPECT_FALSE(db_->Read(site2).has_value());
}
// Test reading the `bounces` table of the BtmDatabase.
TEST_P(BtmDatabaseAllColumnTest, ReadBounce) {
// Add a bounce for site.
const std::string site = GetSiteForBtm(GURL("https://example.test"));
TimestampRange bounce(
{Time::FromSecondsSinceUnixEpoch(1), Time::FromSecondsSinceUnixEpoch(1)});
EXPECT_TRUE(WriteToVariableColumn(site, bounce));
EXPECT_EQ(ReadValueForVariableColumn(db_->Read(site)), bounce);
// Query a site that never had DIPS State, verifying that is has no entry.
EXPECT_FALSE(
db_->Read(GetSiteForBtm(GURL("https://www.not-in-db.com/"))).has_value());
}
// Verifies actions on the `popups` table of the DIPS database.
class BtmDatabasePopupsTest : public BtmDatabaseTest,
public testing::WithParamInterface<bool> {
public:
BtmDatabasePopupsTest() : BtmDatabaseTest(GetParam()) {}
};
// Test adding entries in the `popups` table of the BtmDatabase.
TEST_P(BtmDatabasePopupsTest, AddPopup) {
const std::string opener_site =
GetSiteForBtm(GURL("http://www.youtube.com/"));
const std::string popup_site =
GetSiteForBtm(GURL("http://www.doubleclick.net/"));
uint64_t access_id = 123;
base::Time popup_time = Time::FromSecondsSinceUnixEpoch(1);
bool is_current_interaction = true;
bool is_authentication_interaction = true;
EXPECT_TRUE(db_->WritePopup(opener_site, popup_site, access_id, popup_time,
is_current_interaction,
is_authentication_interaction));
auto popups_state_value = db_->ReadPopup(opener_site, popup_site);
ASSERT_TRUE(popups_state_value.has_value());
EXPECT_EQ(popups_state_value.value().access_id, access_id);
EXPECT_EQ(popups_state_value.value().last_popup_time, popup_time);
EXPECT_EQ(popups_state_value.value().is_current_interaction,
is_current_interaction);
EXPECT_EQ(popups_state_value.value().is_authentication_interaction,
is_authentication_interaction);
}
// Test updating entries in the `popups` table of the BtmDatabase.
TEST_P(BtmDatabasePopupsTest, UpdatePopup) {
const std::string opener_site =
GetSiteForBtm(GURL("http://www.youtube.com/"));
const std::string popup_site =
GetSiteForBtm(GURL("http://www.doubleclick.net/"));
uint64_t first_access_id = 123;
uint64_t second_access_id = 456;
base::Time first_popup_time = Time::FromSecondsSinceUnixEpoch(1);
base::Time second_popup_time = Time::FromSecondsSinceUnixEpoch(2);
// Write the initial entry and verify it was added to the db.
EXPECT_TRUE(db_->WritePopup(
opener_site, popup_site, first_access_id, first_popup_time,
/*is_current_interaction=*/true, /*is_authentication_interaction=*/true));
auto popups_state_value = db_->ReadPopup(opener_site, popup_site);
EXPECT_EQ(popups_state_value.value_or(PopupsStateValue()).last_popup_time,
first_popup_time);
EXPECT_EQ(popups_state_value.value().is_authentication_interaction, true);
// Update the entry with a new popup time of t = 2, is_current_interaction =
// false, and is_authentication_interaction = false.
EXPECT_TRUE(db_->WritePopup(opener_site, popup_site, second_access_id,
second_popup_time,
/*is_current_interaction=*/false,
/*is_authentication_interaction=*/false));
// Verify the new entry.
popups_state_value = db_->ReadPopup(opener_site, popup_site);
ASSERT_TRUE(popups_state_value.has_value());
EXPECT_EQ(popups_state_value.value().access_id, second_access_id);
EXPECT_EQ(popups_state_value.value().last_popup_time, second_popup_time);
EXPECT_EQ(popups_state_value.value().is_current_interaction, false);
EXPECT_EQ(popups_state_value.value().is_authentication_interaction, false);
}
// Test deleting an entry from the `popups` table of the BtmDatabase. An entry
// should be deleted if the input site matches either opener_site or
// popup_site.
TEST_P(BtmDatabasePopupsTest, DeletePopup) {
const std::string opener_site =
GetSiteForBtm(GURL("http://www.youtube.com/"));
const std::string popup_site =
GetSiteForBtm(GURL("http://www.doubleclick.net/"));
uint64_t access_id = 123;
base::Time popup_time = Time::FromSecondsSinceUnixEpoch(1);
// Write the popup to db, and verify.
EXPECT_TRUE(db_->WritePopup(opener_site, popup_site, access_id, popup_time,
/*is_current_interaction=*/true,
/*is_authentication_interaction=*/false));
EXPECT_TRUE(db_->ReadPopup(opener_site, popup_site).has_value());
// Delete the entry in db by opener_site, and verify.
EXPECT_TRUE(db_->RemoveRow(BtmDatabaseTable::kPopups, opener_site));
EXPECT_FALSE(db_->ReadPopup(opener_site, popup_site).has_value());
// Write the popup to db, and verify.
EXPECT_TRUE(db_->WritePopup(opener_site, popup_site, access_id, popup_time,
/*is_current_interaction=*/true,
/*is_authentication_interaction=*/false));
EXPECT_TRUE(db_->ReadPopup(opener_site, popup_site).has_value());
// Delete the entry in db by popup_site, and verify.
EXPECT_TRUE(db_->RemoveRow(BtmDatabaseTable::kPopups, popup_site));
EXPECT_FALSE(db_->ReadPopup(opener_site, popup_site).has_value());
}
// Test deleting many entries from the `popups` table of the BtmDatabase.
TEST_P(BtmDatabasePopupsTest, DeleteSeveralPopups) {
// Add popups to db.
const std::string opener_site_1 =
GetSiteForBtm(GURL("http://www.youtube.com/"));
const std::string opener_site_2 =
GetSiteForBtm(GURL("http://www.picasa.com/"));
const std::string popup_site =
GetSiteForBtm(GURL("http://www.doubleclick.net/"));
EXPECT_TRUE(db_->WritePopup(
opener_site_1, popup_site,
/*access_id=*/123, Time::FromSecondsSinceUnixEpoch(1),
/*is_current_interaction=*/true, /*is_authentication_interaction=*/true));
EXPECT_TRUE(db_->WritePopup(opener_site_2, popup_site,
/*access_id=*/456,
Time::FromSecondsSinceUnixEpoch(2),
/*is_current_interaction=*/true,
/*is_authentication_interaction=*/false));
// Verify that both sites are in the `popups` table.
EXPECT_TRUE(db_->ReadPopup(opener_site_1, popup_site).has_value());
EXPECT_TRUE(db_->ReadPopup(opener_site_2, popup_site).has_value());
// Delete site's entry in `popups`.
EXPECT_TRUE(db_->RemoveRows(BtmDatabaseTable::kBounces,
{opener_site_1, opener_site_2}));
// Verify that both sites are deleted from the `popups` table.
EXPECT_FALSE(db_->Read(opener_site_1).has_value());
EXPECT_FALSE(db_->Read(opener_site_2).has_value());
}
// Test the `ReadRecentPopupsWithInteraction` function which retrieves a list of
// `popups` table entries with recent popup timestamps.
TEST_P(BtmDatabasePopupsTest, ReadRecentPopupsWithInteraction) {
base::Time now = Now();
// Add popups to db.
const std::string opener_site_1 =
GetSiteForBtm(GURL("http://www.youtube.com/"));
const std::string opener_site_2 =
GetSiteForBtm(GURL("http://www.picasa.com/"));
const std::string opener_site_3 =
GetSiteForBtm(GURL("http://www.google.com/"));
const std::string popup_site =
GetSiteForBtm(GURL("http://www.doubleclick.net/"));
EXPECT_TRUE(db_->WritePopup(opener_site_1, popup_site,
/*access_id=*/123, now - base::Seconds(10),
/*is_current_interaction=*/true,
/*is_authentication_interaction=*/false));
EXPECT_TRUE(db_->WritePopup(opener_site_2, popup_site,
/*access_id=*/456, now - base::Seconds(10),
/*is_current_interaction=*/false,
/*is_authentication_interaction=*/false));
EXPECT_TRUE(db_->WritePopup(opener_site_3, popup_site,
/*access_id=*/789, now - base::Seconds(30),
/*is_current_interaction=*/true,
/*is_authentication_interaction=*/false));
// Verify that all three sites are in the `popups` table.
EXPECT_TRUE(db_->ReadPopup(opener_site_1, popup_site).has_value());
EXPECT_TRUE(db_->ReadPopup(opener_site_2, popup_site).has_value());
EXPECT_TRUE(db_->ReadPopup(opener_site_3, popup_site).has_value());
// Expect no popups recorded in the last 5 seconds.
std::vector<PopupWithTime> very_recent_popups =
db_->ReadRecentPopupsWithInteraction(base::Seconds(5));
EXPECT_TRUE(very_recent_popups.empty());
// Expect one popup in the last 20 seconds with a current interaction.
std::vector<PopupWithTime> recent_popups =
db_->ReadRecentPopupsWithInteraction(base::Seconds(20));
ASSERT_EQ(recent_popups.size(), 1u);
EXPECT_EQ(recent_popups.at(0).opener_site, opener_site_1);
EXPECT_EQ(recent_popups.at(0).popup_site, popup_site);
EXPECT_EQ(recent_popups.at(0).last_popup_time, now - base::Seconds(10));
}
INSTANTIATE_TEST_SUITE_P(All, BtmDatabasePopupsTest, ::testing::Bool());
TEST_P(BtmDatabaseAllColumnTest, ErrorHistograms_OpenEndedRange_NullStart) {
base::HistogramTester histograms;
ASSERT_TRUE(db_->ExecuteSqlForTesting(base::StringPrintf(
"INSERT INTO bounces(site,%s,%s) VALUES ('site.test',NULL,0)",
GetVariableColumnNames().first.c_str(),
GetVariableColumnNames().second.c_str())));
db_->Read("site.test");
histograms.ExpectUniqueSample("Privacy.DIPS.DIPSErrorCodes",
BtmErrorCode::kRead_OpenEndedRange_NullStart,
1);
}
TEST_P(BtmDatabaseAllColumnTest, ErrorHistograms_OpenEndedRange_NullEnd) {
base::HistogramTester histograms;
ASSERT_TRUE(db_->ExecuteSqlForTesting(base::StringPrintf(
"INSERT INTO bounces(site,%s,%s) VALUES ('site.test',0,NULL)",
GetVariableColumnNames().first.c_str(),
GetVariableColumnNames().second.c_str())));
db_->Read("site.test");
histograms.ExpectUniqueSample("Privacy.DIPS.DIPSErrorCodes",
BtmErrorCode::kRead_OpenEndedRange_NullEnd, 1);
}
// Verifies the histograms logged for the success case.
TEST_P(BtmDatabaseAllColumnTest, ErrorHistograms_EmptyRangeExcluded) {
base::HistogramTester histograms;
ASSERT_TRUE(db_->ExecuteSqlForTesting(
base::StringPrintf("INSERT INTO bounces(site,%s,%s) VALUES "
"('empty-site.test',NULL,NULL)",
GetVariableColumnNames().first.c_str(),
GetVariableColumnNames().second.c_str())));
db_->Read("empty-site.test");
histograms.ExpectUniqueSample("Privacy.DIPS.DIPSErrorCodes",
BtmErrorCode::kRead_None, 1);
}
INSTANTIATE_TEST_SUITE_P(
All,
BtmDatabaseAllColumnTest,
::testing::Combine(::testing::Bool(),
::testing::Values(ColumnType::kSiteStorage,
ColumnType::kUserActivation,
ColumnType::kStatefulBounce,
ColumnType::kBounce,
ColumnType::kWebAuthnAssertion)));
// A test class that verifies the behavior of the BtmDatabase with respect to
// interactions and Web Authn Assertions (WAA).
//
// Parameterized over whether the db is in memory.
class BtmDatabaseInteractionTest : public BtmDatabaseTest,
public testing::WithParamInterface<bool> {
public:
BtmDatabaseInteractionTest() : BtmDatabaseTest(GetParam()) {
features_.InitWithFeatures({features::kBtmTtl, features::kBtm}, {});
}
// This test only focuses on user activation and WAA times, that's the
// reason why the other times like bounce times not being tested here are left
// NULL throughout.
void LoadDatabase() {
DCHECK(db_);
// Case1: last_web_authn_assertion_time == last_user_activation_time.
EXPECT_TRUE(db_->Write("case1.test", {}, {{dummy_time, dummy_time}}, {}, {},
{{dummy_time, dummy_time}}));
// Case2: last_web_authn_assertion_time > last_user_activation_time.
EXPECT_TRUE(db_->Write("case2.test", {}, {{dummy_time, dummy_time}}, {}, {},
{{dummy_time, dummy_time + tiny_delta}}));
// Case3: last_web_authn_assertion_time < last_user_activation_time.
EXPECT_TRUE(
db_->Write("case3.test", {}, {{dummy_time, dummy_time}}, {}, {},
{{dummy_time - tiny_delta, dummy_time - tiny_delta}}));
// Case4: last_web_authn_assertion_time is NULL.
EXPECT_TRUE(
db_->Write("case4.test", {}, {{dummy_time, dummy_time}}, {}, {}, {}));
// Case5: last_user_activation_time is NULL.
EXPECT_TRUE(
db_->Write("case5.test", {}, {}, {}, {}, {{dummy_time, dummy_time}}));
// Case6: last_web_authn_assertion_time and last_user_activation_time are
// NULL.
EXPECT_TRUE(db_->Write("case6.test", {}, {}, {}, {}, {}));
}
protected:
base::Time dummy_time = Time::FromSecondsSinceUnixEpoch(100);
};
TEST_P(BtmDatabaseInteractionTest, ClearExpiredRowsFromBouncesTable) {
LoadDatabase();
EXPECT_THAT(
db_->GetAllSitesForTesting(BtmDatabaseTable::kBounces),
testing::UnorderedElementsAre("case1.test", "case2.test", "case3.test",
"case4.test", "case5.test", "case6.test"));
AdvanceTimeTo(dummy_time + features::kBtmInteractionTtl.Get());
EXPECT_EQ(db_->ClearExpiredRows(), 0u);
EXPECT_THAT(
db_->GetAllSitesForTesting(BtmDatabaseTable::kBounces),
testing::UnorderedElementsAre("case1.test", "case2.test", "case3.test",
"case4.test", "case5.test", "case6.test"));
AdvanceTimeTo(dummy_time + features::kBtmInteractionTtl.Get() + tiny_delta);
EXPECT_EQ(db_->ClearExpiredRows(), 4u);
EXPECT_THAT(db_->GetAllSitesForTesting(BtmDatabaseTable::kBounces),
testing::UnorderedElementsAre("case2.test", "case6.test"));
// Time travel to a point by which all interactions and WAAs should've
// expired.
AdvanceTimeTo(dummy_time + features::kBtmInteractionTtl.Get() +
tiny_delta * 2);
EXPECT_EQ(db_->ClearExpiredRows(), 1u);
EXPECT_THAT(db_->GetAllSitesForTesting(BtmDatabaseTable::kBounces),
testing::ElementsAre("case6.test"));
}
TEST_P(BtmDatabaseInteractionTest, ReadWithExpiredRows) {
LoadDatabase();
EXPECT_TRUE(db_->Read("case1.test").has_value());
EXPECT_TRUE(db_->Read("case2.test").has_value());
EXPECT_TRUE(db_->Read("case3.test").has_value());
EXPECT_TRUE(db_->Read("case4.test").has_value());
EXPECT_TRUE(db_->Read("case5.test").has_value());
EXPECT_TRUE(db_->Read("case6.test").has_value());
AdvanceTimeTo(dummy_time + features::kBtmInteractionTtl.Get());
EXPECT_TRUE(db_->Read("case1.test").has_value());
EXPECT_TRUE(db_->Read("case2.test").has_value());
EXPECT_TRUE(db_->Read("case3.test").has_value());
EXPECT_TRUE(db_->Read("case4.test").has_value());
EXPECT_TRUE(db_->Read("case5.test").has_value());
EXPECT_TRUE(db_->Read("case6.test").has_value());
AdvanceTimeTo(dummy_time + features::kBtmInteractionTtl.Get() + tiny_delta);
EXPECT_EQ(db_->Read("case1.test"), std::nullopt);
EXPECT_TRUE(db_->Read("case2.test").has_value());
EXPECT_EQ(db_->Read("case3.test"), std::nullopt);
EXPECT_EQ(db_->Read("case4.test"), std::nullopt);
EXPECT_EQ(db_->Read("case5.test"), std::nullopt);
EXPECT_TRUE(db_->Read("case6.test").has_value());
// Time travel to a point by which all interactions and WAAs should've
// expired.
AdvanceTimeTo(dummy_time + features::kBtmInteractionTtl.Get() +
tiny_delta * 2);
EXPECT_EQ(db_->Read("case1.test"), std::nullopt);
EXPECT_EQ(db_->Read("case2.test"), std::nullopt);
EXPECT_EQ(db_->Read("case3.test"), std::nullopt);
EXPECT_EQ(db_->Read("case4.test"), std::nullopt);
EXPECT_EQ(db_->Read("case5.test"), std::nullopt);
EXPECT_TRUE(db_->Read("case6.test").has_value());
}
TEST_P(BtmDatabaseInteractionTest, ClearExpiredRowsFromPopupsTable) {
// Add popups to db.
const std::string opener_site_1 =
GetSiteForBtm(GURL("http://www.youtube.com/"));
const std::string opener_site_2 =
GetSiteForBtm(GURL("http://www.picasa.com/"));
const std::string popup_site =
GetSiteForBtm(GURL("http://www.doubleclick.net/"));
const base::Time first_popup_time = Time::FromSecondsSinceUnixEpoch(1);
const base::Time second_popup_time = Time::FromSecondsSinceUnixEpoch(2);
EXPECT_TRUE(db_->WritePopup(opener_site_1, popup_site,
/*access_id=*/123, first_popup_time,
/*is_current_interaction=*/true,
/*is_authentication_interaction=*/false));
EXPECT_TRUE(db_->WritePopup(opener_site_2, popup_site,
/*access_id=*/456, second_popup_time,
/*is_current_interaction=*/true,
/*is_authentication_interaction=*/false));
// Advance to just before the first popup expires.
AdvanceTimeTo(first_popup_time + BtmDatabase::kPopupTtl - tiny_delta);
// Verify that both sites are present.
EXPECT_EQ(db_->ClearExpiredRows(), 0u);
EXPECT_THAT(db_->GetAllSitesForTesting(BtmDatabaseTable::kPopups),
testing::UnorderedElementsAre("youtube.com", "doubleclick.net",
"picasa.com", "doubleclick.net"));
// Advance to after the first popup expires.
AdvanceTimeTo(first_popup_time + BtmDatabase::kPopupTtl + tiny_delta);
// Verify that only the first popup was removed from the db.
EXPECT_EQ(db_->ClearExpiredRows(), 1u);
EXPECT_THAT(db_->GetAllSitesForTesting(BtmDatabaseTable::kPopups),
testing::UnorderedElementsAre("picasa.com", "doubleclick.net"));
// Advance to after the second popup expires.
AdvanceTimeTo(second_popup_time + BtmDatabase::kPopupTtl + tiny_delta);
// Verify that both popups were removed from the db.
EXPECT_EQ(db_->ClearExpiredRows(), 1u);
EXPECT_THAT(db_->GetAllSitesForTesting(BtmDatabaseTable::kPopups),
testing::IsEmpty());
}
INSTANTIATE_TEST_SUITE_P(All, BtmDatabaseInteractionTest, ::testing::Bool());
// A test class that verifies the behavior of the methods used to query the
// BtmDatabase to find all sites which should have their state cleared by DIPS.
class BtmDatabaseQueryTest : public BtmDatabaseTest,
public testing::WithParamInterface<
std::tuple<bool, BtmTriggeringAction>> {
public:
using QueryMethod = base::RepeatingCallback<std::vector<std::string>(void)>;
BtmDatabaseQueryTest() : BtmDatabaseTest(std::get<0>(GetParam())) {
// Test with the prod feature's parameter to ensure the tested scenarios are
// also valid/respected within prod env.
features_.InitWithFeatures({features::kBtmTtl, features::kBtm}, {});
}
void SetUp() override {
BtmDatabaseTest::SetUp();
grace_period = features::kBtmGracePeriod.Get();
interaction_ttl = features::kBtmInteractionTtl.Get();
}
// Returns the DIPS-triggering action we're testing.
BtmTriggeringAction CurrentAction() { return std::get<1>(GetParam()); }
// Returns a callback for the respective querying method we want to test,
// based on `features::kBtmTriggeringAction`. This is equivalent to that
// used by `BtmStorage::GetSitesToClear` when the DIPS Timer fires.
QueryMethod GetQueryMethodUnderTest() {
switch (CurrentAction()) {
case BtmTriggeringAction::kNone:
return base::BindLambdaForTesting(
[&]() { return std::vector<std::string>{}; });
case BtmTriggeringAction::kBounce:
return base::BindLambdaForTesting(
[&]() { return db_->GetSitesThatBounced(grace_period); });
case BtmTriggeringAction::kStorage:
return base::BindLambdaForTesting(
[&]() { return db_->GetSitesThatUsedStorage(grace_period); });
case BtmTriggeringAction::kStatefulBounce:
return base::BindLambdaForTesting(
[&]() { return db_->GetSitesThatBouncedWithState(grace_period); });
}
}
void WriteForCurrentAction(const std::string& site,
TimestampRange event_times,
TimestampRange interaction_times,
TimestampRange waa_times) {
switch (CurrentAction()) {
case BtmTriggeringAction::kNone:
break;
case BtmTriggeringAction::kBounce:
db_->Write(site, /*storage_times=*/{}, interaction_times,
/*stateful_bounce_times=*/{},
/*bounce_times=*/event_times, waa_times);
break;
case BtmTriggeringAction::kStorage:
db_->Write(site, /*storage_times=*/event_times, interaction_times,
/*stateful_bounce_times=*/{}, /*bounce_times=*/{},
waa_times);
break;
case BtmTriggeringAction::kStatefulBounce:
db_->Write(site, /*storage_times=*/{}, interaction_times,
/*stateful_bounce_times=*/event_times,
/*bounce_times=*/event_times, waa_times);
break;
}
}
protected:
base::TimeDelta grace_period;
base::TimeDelta interaction_ttl;
};
TEST_P(BtmDatabaseQueryTest, ProtectedDuringGracePeriod) {
// The result of running `query` shouldn't include sites which are currently
// in their grace period after first performing a DIPS-triggering event.
QueryMethod query = GetQueryMethodUnderTest();
base::Time event = Time::FromSecondsSinceUnixEpoch(1);
TimestampRange event_times = {{event, event}};
WriteForCurrentAction("site.test", event_times, {}, {});
// Time-travel to the start of the grace period of the triggering event.
AdvanceTimeTo(event);
EXPECT_THAT(query.Run(), testing::IsEmpty());
// Time-travel to within the grace period of the triggering event.
AdvanceTimeTo(event + (grace_period / 2));
EXPECT_THAT(query.Run(), testing::IsEmpty());
// Time-travel to the end of the grace period of the triggering event.
AdvanceTimeTo(event + grace_period);
EXPECT_THAT(query.Run(), testing::IsEmpty());
// Site is no longer protected right after the grace period ends.
AdvanceTimeTo(event + grace_period + tiny_delta);
EXPECT_THAT(query.Run(), testing::ElementsAre("site.test"));
}
TEST_P(BtmDatabaseQueryTest, ProtectedByInteractionBeforeGracePeriod) {
// The result of running `query` shouldn't include sites who've received
// interactions from the user before performing a DIPS-triggering event.
QueryMethod query = GetQueryMethodUnderTest();
base::Time interaction = Time::FromSecondsSinceUnixEpoch(1);
TimestampRange interaction_times = {{interaction, interaction}};
base::Time event = Time::FromSecondsSinceUnixEpoch(2);
TimestampRange event_times = {{event, event}};
WriteForCurrentAction("site.test", event_times, interaction_times, {});
// 'site.test' shouldn't be returned when querying after the grace period
// as the early interaction protects it from being cleared.
AdvanceTimeTo(event + grace_period + tiny_delta);
EXPECT_THAT(query.Run(), testing::IsEmpty());
// "site.test" should still be protected up until the interaction expires.
AdvanceTimeTo(interaction + interaction_ttl - tiny_delta);
EXPECT_THAT(query.Run(), testing::IsEmpty());
// Once `interaction` expires, "site.test" restarts the DIPS-procedure and
// `interaction` no longer protects it from DIPS clearing.
AdvanceTimeTo(interaction + interaction_ttl + tiny_delta);
EXPECT_THAT(query.Run(), testing::IsEmpty());
base::Time after_interaction_expiry = Now();
WriteForCurrentAction("site.test",
{{after_interaction_expiry, after_interaction_expiry}},
{}, {});
EXPECT_THAT(query.Run(), testing::IsEmpty());
// "site.test" is no longer protected by `interaction` and is cleared right
// after its grace period ends.
AdvanceTimeTo(after_interaction_expiry + grace_period + tiny_delta);
EXPECT_THAT(query.Run(), testing::ElementsAre("site.test"));
}
// The results of running `query` shouldn't include `site` with existing
// (expired or unexpired) WAAs (performed by the user before a DIPS-triggering
// event occurred).
TEST_P(BtmDatabaseQueryTest, ProtectedByWaaBeforeGracePeriod) {
const QueryMethod query = GetQueryMethodUnderTest();
const std::string site = "site.test";
// Set up an event that happens after the WAA.
{
auto waa_time = Time::FromSecondsSinceUnixEpoch(100);
base::Time event_time = waa_time + tiny_delta;
WriteForCurrentAction(site, {{event_time, event_time}}, {},
{{waa_time, waa_time}});
EXPECT_THAT(query.Run(), testing::IsEmpty());
EXPECT_TRUE(db_->Read(site).has_value());
// The `site` should remain protected by the existing WAA even after the
// `grace_period`:
EXPECT_GE(interaction_ttl, grace_period + tiny_delta);
AdvanceTimeTo(event_time + grace_period + tiny_delta);
EXPECT_THAT(query.Run(), testing::IsEmpty());
EXPECT_TRUE(db_->Read(site).has_value());
// The `site` should still be protected before WAA expiry:
AdvanceTimeTo(waa_time + interaction_ttl);
EXPECT_THAT(query.Run(), testing::IsEmpty());
EXPECT_TRUE(db_->Read(site).has_value());
// The `site`'s entry should be cleared by
// `BtmDatabase::ClearExpiredRows()` from the DB (hence implicitly
// protected) after WAA expiry:
AdvanceTimeTo(waa_time + interaction_ttl + tiny_delta);
EXPECT_THAT(query.Run(), testing::IsEmpty());
EXPECT_EQ(db_->Read(site), std::nullopt);
}
// Set up an event that happens after WAA expired and the old entry cleared.
{
base::Time event_time = Now() + interaction_ttl + tiny_delta;
WriteForCurrentAction(site, {{event_time, event_time}}, {}, {});
EXPECT_THAT(query.Run(), testing::IsEmpty());
// The `site`'s new entry is no longer protected by WAAs after the
// `grace_period` and will be acted-upon by DIPS:
AdvanceTimeTo(event_time + grace_period + tiny_delta);
EXPECT_THAT(query.Run(), testing::ElementsAre(site));
EXPECT_TRUE(db_->Read(site).has_value());
}
}
TEST_P(BtmDatabaseQueryTest, ProtectedByInteractionDuringGracePeriod) {
// The result of running `query` shouldn't include sites who've received
// interactions during the grace period following a DIPS-triggering event.
QueryMethod query = GetQueryMethodUnderTest();
// Set up an interaction that happens during the event's grace period.
base::Time event = Time::FromSecondsSinceUnixEpoch(1);
TimestampRange event_times = {{event, event}};
base::Time interaction = Time::FromSecondsSinceUnixEpoch(4);
TimestampRange interaction_times = {{interaction, interaction}};
ASSERT_TRUE(interaction < event + grace_period);
WriteForCurrentAction("site.test", event_times, interaction_times, {});
// 'site.test' shouldn't be returned as the interaction protects
// it from being cleared.
AdvanceTimeTo(event + grace_period + tiny_delta);
EXPECT_THAT(query.Run(), testing::IsEmpty());
// "site.test" should still be protected up until the interaction expires.
AdvanceTimeTo(interaction + interaction_ttl - tiny_delta);
EXPECT_THAT(query.Run(), testing::IsEmpty());
// Once `interaction` expires, "site.test" restarts the DIPS-procedure and
// `interaction` no longer protects it from DIPS clearing.
AdvanceTimeTo(interaction + interaction_ttl + tiny_delta);
EXPECT_THAT(query.Run(), testing::IsEmpty());
base::Time after_interaction_expiry = Now();
WriteForCurrentAction("site.test",
{{after_interaction_expiry, after_interaction_expiry}},
{}, {});
EXPECT_THAT(query.Run(), testing::IsEmpty());
// "site.test" is no longer protected by `interaction` and is cleared right
// after its grace period ends.
AdvanceTimeTo(after_interaction_expiry + grace_period + tiny_delta);
EXPECT_THAT(query.Run(), testing::ElementsAre("site.test"));
}
// The results of running `query` shouldn't include `site` with existing
// (expired or unexpired) WAAs (performed by the user after a DIPS-triggering
// event occurred).
TEST_P(BtmDatabaseQueryTest, ProtectedByWaaDuringGracePeriod) {
const QueryMethod query = GetQueryMethodUnderTest();
const std::string site = "site.test";
// Set up an event with a WAA happening before the end of the event's
// `grace_period`.
{
auto event_time = Time::FromSecondsSinceUnixEpoch(100);
base::Time waa_time = event_time + grace_period;
WriteForCurrentAction(site, {{event_time, event_time}}, {},
{{waa_time, waa_time}});
EXPECT_THAT(query.Run(), testing::IsEmpty());
EXPECT_TRUE(db_->Read(site).has_value());
// The `site` should remain protected by the existing WAA even after the
// `grace_period`:
EXPECT_GE(interaction_ttl, grace_period + tiny_delta);
AdvanceTimeTo(event_time + grace_period + tiny_delta);
EXPECT_THAT(query.Run(), testing::IsEmpty());
EXPECT_TRUE(db_->Read(site).has_value());
// The `site` should still be protected before WAA expiry:
AdvanceTimeTo(waa_time + interaction_ttl);
EXPECT_THAT(query.Run(), testing::IsEmpty());
EXPECT_TRUE(db_->Read(site).has_value());
// The `site`'s entry should be cleared by
// `BtmDatabase::ClearExpiredRows()` from the DB (hence implicitly
// protected) after WAA expiry:
AdvanceTimeTo(waa_time + interaction_ttl + tiny_delta);
EXPECT_THAT(query.Run(), testing::IsEmpty());
EXPECT_EQ(db_->Read(site), std::nullopt);
}
// Set up an event that happens after WAA expired and the old entry cleared.
{
base::Time event_time = Now() + interaction_ttl + tiny_delta;
WriteForCurrentAction(site, {{event_time, event_time}}, {}, {});
EXPECT_THAT(query.Run(), testing::IsEmpty());
// The `site`'s new entry is no longer protected by WAAs after the
// `grace_period` and will be acted-upon by DIPS.
AdvanceTimeTo(event_time + grace_period + tiny_delta);
EXPECT_THAT(query.Run(), testing::ElementsAre(site));
EXPECT_TRUE(db_->Read(site).has_value());
}
}
TEST_P(BtmDatabaseQueryTest, SiteWithoutInteractionsAreUnprotected) {
// The result of running `query` should include sites who've never received
// interaction from the user before, or during the grace period after,
// performing a DIPS-triggering event.
base::RepeatingCallback<std::vector<std::string>(void)> query =
GetQueryMethodUnderTest();
// Set up an event with no corresponding interaction.
base::Time event = Time::FromSecondsSinceUnixEpoch(2);
TimestampRange event_times = {{event, event}};
WriteForCurrentAction("site.test", event_times, {}, {});
// 'site.test' is returned since there is no interaction protecting it.
AdvanceTimeTo(event + grace_period + tiny_delta);
EXPECT_THAT(query.Run(), testing::ElementsAre("site.test"));
}
// This is an edge-case and the current accepted behavior is as expressed by
// this test coverage.
TEST_P(BtmDatabaseQueryTest, ProtectedByWaaAfterGracePeriod) {
const QueryMethod query = GetQueryMethodUnderTest();
const std::string site = "site.test";
// Sets up an event with a WAA happening after the end of the event's
// `grace_period` but before the subsequent DIPS-trigger:
auto event_time = Time::FromSecondsSinceUnixEpoch(100);
auto waa_time = event_time + grace_period + tiny_delta;
WriteForCurrentAction(site, {{event_time, event_time}}, {},
{{waa_time, waa_time}});
EXPECT_THAT(query.Run(), testing::IsEmpty());
EXPECT_TRUE(db_->Read(site).has_value());
// The `site` should still be protected before WAA expiry:
EXPECT_GT(interaction_ttl, grace_period);
AdvanceTimeTo(waa_time + interaction_ttl);
EXPECT_THAT(query.Run(), testing::IsEmpty());
EXPECT_TRUE(db_->Read(site).has_value());
// The `site`'s entry should be cleared by
// `BtmDatabase::ClearExpiredRows()` from the DB (hence implicitly protected)
// after WAA expiry:
AdvanceTimeTo(waa_time + interaction_ttl + tiny_delta);
EXPECT_THAT(query.Run(), testing::IsEmpty());
EXPECT_EQ(db_->Read(site), std::nullopt);
}
TEST_P(BtmDatabaseQueryTest, ProtectedByInteractionThenWaa) {
const QueryMethod query = GetQueryMethodUnderTest();
const std::string site = "site.test";
// Sets up an event with a interaction happening before the end of the event's
// `grace_period` and an WAA some moments later:
auto event_time = Time::FromSecondsSinceUnixEpoch(100);
auto interaction_time = event_time + grace_period;
auto waa_time = interaction_time + tiny_delta;
WriteForCurrentAction(site, {{event_time, event_time}},
{{interaction_time, interaction_time}},
{{waa_time, waa_time}});
EXPECT_THAT(query.Run(), testing::IsEmpty());
EXPECT_TRUE(db_->Read(site).has_value());
// The `site` should still be protected after interaction expiry:
EXPECT_GT(interaction_ttl, grace_period);
AdvanceTimeTo(interaction_time + interaction_ttl + tiny_delta);
EXPECT_THAT(query.Run(), testing::IsEmpty());
EXPECT_TRUE(db_->Read(site).has_value());
// The `site`'s entry should be cleared by
// `BtmDatabase::ClearExpiredRows()` from the DB (hence implicitly protected)
// after WAA expiry:
AdvanceTimeTo(waa_time + interaction_ttl + tiny_delta);
EXPECT_THAT(query.Run(), testing::IsEmpty());
EXPECT_EQ(db_->Read(site), std::nullopt);
}
TEST_P(BtmDatabaseQueryTest, ProtectedByWaaThenInteraction) {
const QueryMethod query = GetQueryMethodUnderTest();
const std::string site = "site.test";
// Sets up an event with a WAA happening before the end of the event's
// `grace_period` and an interaction some moments later:
auto event_time = Time::FromSecondsSinceUnixEpoch(100);
auto waa_time = event_time + tiny_delta;
auto interaction_time = waa_time + grace_period;
WriteForCurrentAction(site, {{event_time, event_time}},
{{interaction_time, interaction_time}},
{{waa_time, waa_time}});
EXPECT_THAT(query.Run(), testing::IsEmpty());
EXPECT_TRUE(db_->Read(site).has_value());
// The `site` should still be protected after WAA expiry:
EXPECT_GT(interaction_ttl, grace_period);
AdvanceTimeTo(waa_time + interaction_ttl + tiny_delta);
EXPECT_THAT(query.Run(), testing::IsEmpty());
EXPECT_TRUE(db_->Read(site).has_value());
// The `site`'s entry should be cleared by
// `BtmDatabase::ClearExpiredRows()` from the DB (hence implicitly protected)
// after interaction expiry:
AdvanceTimeTo(interaction_time + interaction_ttl + tiny_delta);
EXPECT_THAT(query.Run(), testing::IsEmpty());
EXPECT_EQ(db_->Read(site), std::nullopt);
}
INSTANTIATE_TEST_SUITE_P(
All,
BtmDatabaseQueryTest,
::testing::Combine(
::testing::Bool(),
::testing::Values(BtmTriggeringAction::kBounce,
BtmTriggeringAction::kStorage,
BtmTriggeringAction::kStatefulBounce)));
// A test class that verifies BtmDatabase garbage collection behavior for both
// tables.
class BtmDatabaseGarbageCollectionTest
: public BtmDatabaseTest,
public testing::WithParamInterface<BtmDatabaseTable> {
public:
BtmDatabaseGarbageCollectionTest() : BtmDatabaseTest(true) {
table_ = GetParam();
}
explicit BtmDatabaseGarbageCollectionTest(BtmDatabaseTable table)
: BtmDatabaseTest(true) {
table_ = table;
}
void SetUp() override {
BtmDatabaseTest::SetUp();
features_.InitAndEnableFeatureWithParameters(
features::kBtmTtl,
{{"interaction_ttl",
base::StringPrintf("%dh", base::Days(90).InHours())}});
DCHECK(db_);
db_->SetMaxEntriesForTesting(200);
db_->SetPurgeEntriesForTesting(20);
recent_interaction = Now();
old_interaction = Now() - base::Days(180);
}
void AddEntry(const std::string& site,
TimestampRange storage_times,
TimestampRange interaction_times,
TimestampRange waa_times) {
if (table_ == BtmDatabaseTable::kBounces) {
ASSERT_TRUE(db_->Write(site, storage_times, interaction_times, {}, {},
waa_times));
} else {
ASSERT_TRUE(db_->WritePopup(site, "doubleclick.net", /*access_id=*/123,
interaction_times->second,
/*is_current_interaction=*/true,
/*is_authentication_interaction=*/false));
}
}
void BloatBouncesForGC(int num_recent_entries, int num_old_entries) {
DCHECK(db_);
for (int i = 0; i < num_recent_entries; i++) {
AddEntry(
base::StrCat({"recent_interaction.test", base::NumberToString(i)}),
ToRange(storage), ToRange(recent_interaction), {});
}
for (int i = 0; i < num_old_entries; i++) {
AddEntry(base::StrCat({"old_interaction.test", base::NumberToString(i)}),
ToRange(storage), ToRange(old_interaction), {});
}
}
void LoadDatabase() {
clock_.SetNow(Time::FromSecondsSinceUnixEpoch(100));
std::vector<base::Time> times{Now(), Now() + tiny_delta,
Now() + tiny_delta * 2};
for (int i = 1; i <= 3; i++) {
if (table_ == BtmDatabaseTable::kBounces) {
ASSERT_TRUE(db_->Write(
base::StringPrintf("entry%d.test", 7 - i), ToRange(times[i % 3]),
ToRange(times[(i + 1) % 3]), {}, {}, ToRange(times[(i + 2) % 3])));
} else {
ASSERT_TRUE(db_->WritePopup(base::StringPrintf("entry%d.test", 7 - i),
"doubleclick.net", /*access_id=*/123,
times[(i + 1) % 3],
/*is_current_interaction=*/true,
/*is_authentication_interaction=*/false));
}
for (auto& time : times) {
time += tiny_delta * 3;
}
}
for (int i = 3; i <= 6; i++) {
if (table_ == BtmDatabaseTable::kBounces) {
ASSERT_TRUE(db_->Write(base::StringPrintf("entry%d.test", 7 - i),
ToRange(times[(i + 2) % 3]),
ToRange(times[(i + 1) % 3]), {}, {},
ToRange(times[i % 3])));
} else {
ASSERT_TRUE(db_->WritePopup(base::StringPrintf("entry%d.test", 7 - i),
"doubleclick.net", /*access_id=*/123,
times[(i + 1) % 3],
/*is_current_interaction=*/true,
/*is_authentication_interaction=*/false));
}
for (auto& time : times) {
time += tiny_delta * 3;
}
}
if (table_ == BtmDatabaseTable::kBounces) {
EXPECT_THAT(
db_->GetAllSitesForTesting(BtmDatabaseTable::kBounces),
testing::ElementsAre("entry1.test", "entry2.test", "entry3.test",
"entry4.test", "entry5.test", "entry6.test"));
} else {
EXPECT_THAT(
db_->GetAllSitesForTesting(BtmDatabaseTable::kPopups),
testing::IsSupersetOf({"entry1.test", "entry2.test", "entry3.test",
"entry4.test", "entry5.test", "entry6.test"}));
}
}
protected:
BtmDatabaseTable table_;
base::Time recent_interaction;
base::Time old_interaction;
base::Time storage = Time::FromSecondsSinceUnixEpoch(2);
};
// More than |max_entries_| entries with recent user interaction; garbage
// collection should purge down to |max_entries_| - |purge_entries_| entries.
TEST_P(BtmDatabaseGarbageCollectionTest, RemovesRecentOverMax) {
BloatBouncesForGC(/*num_recent_entries=*/db_->GetMaxEntries() * 2,
/*num_old_entries=*/0);
EXPECT_EQ(db_->GarbageCollect(),
db_->GetMaxEntries() + db_->GetPurgeEntries());
EXPECT_EQ(db_->GetEntryCount(GetParam()),
db_->GetMaxEntries() - db_->GetPurgeEntries());
}
TEST_P(BtmDatabaseGarbageCollectionTest, RemovesExpired_RemovesRecent_GT_Max) {
BloatBouncesForGC(/*num_recent_entries=*/db_->GetMaxEntries() * 2,
/*num_old_entries=*/db_->GetMaxEntries());
EXPECT_EQ(db_->GarbageCollect(),
db_->GetMaxEntries() * 2 + db_->GetPurgeEntries());
EXPECT_EQ(db_->GetEntryCount(GetParam()),
db_->GetMaxEntries() - db_->GetPurgeEntries());
}
// Less than |max_entries_| entries, none of which are expired;
// no entries should be garbage collected.
TEST_P(BtmDatabaseGarbageCollectionTest, PreservesUnderMax) {
BloatBouncesForGC(
/*num_recent_entries=*/(db_->GetMaxEntries() - db_->GetPurgeEntries()) /
2,
/*num_old_entries=*/0);
EXPECT_EQ(db_->GarbageCollect(), static_cast<size_t>(0));
EXPECT_EQ(db_->GetEntryCount(GetParam()),
(db_->GetMaxEntries() - db_->GetPurgeEntries()) / 2);
}
// Exactly |max_entries_| entries, none of which are expired;
// no entries should be garbage collected.
TEST_P(BtmDatabaseGarbageCollectionTest, PreservesMax) {
BloatBouncesForGC(/*num_recent_entries=*/db_->GetMaxEntries(),
/*num_old_entries=*/0);
EXPECT_EQ(db_->GarbageCollect(), static_cast<size_t>(0));
EXPECT_EQ(db_->GetEntryCount(GetParam()), db_->GetMaxEntries());
}
TEST_P(BtmDatabaseGarbageCollectionTest, RemovesExpired_PreserveRecent_LE_Max) {
BloatBouncesForGC(/*num_recent_entries=*/db_->GetMaxEntries(),
/*num_old_entries=*/db_->GetMaxEntries());
EXPECT_EQ(db_->GarbageCollect(), db_->GetMaxEntries());
EXPECT_EQ(db_->GetEntryCount(GetParam()), db_->GetMaxEntries());
}
TEST_P(BtmDatabaseGarbageCollectionTest, GarbageCollectOldest) {
LoadDatabase();
EXPECT_THAT(
db_->GetGarbageCollectOldestSitesForTesting(GetParam()),
testing::ElementsAre("entry6.test", "entry5.test", "entry4.test",
"entry3.test", "entry2.test", "entry1.test"));
EXPECT_EQ(db_->GarbageCollectOldest(GetParam(), 3), static_cast<size_t>(3));
if (GetParam() == BtmDatabaseTable::kBounces) {
EXPECT_THAT(
db_->GetAllSitesForTesting(BtmDatabaseTable::kBounces),
testing::ElementsAre("entry1.test", "entry2.test", "entry3.test"));
} else {
EXPECT_THAT(db_->GetAllSitesForTesting(BtmDatabaseTable::kPopups),
testing::ElementsAre("entry1.test", "doubleclick.net",
"entry2.test", "doubleclick.net",
"entry3.test", "doubleclick.net"));
}
}
INSTANTIATE_TEST_SUITE_P(All,
BtmDatabaseGarbageCollectionTest,
::testing::Values(BtmDatabaseTable::kBounces,
BtmDatabaseTable::kPopups));
// These tests only apply to the `bounces` table.
class BtmDatabaseBounceTableGarbageCollectionTest
: public BtmDatabaseGarbageCollectionTest {
public:
BtmDatabaseBounceTableGarbageCollectionTest()
: BtmDatabaseGarbageCollectionTest(BtmDatabaseTable::kBounces) {}
};
TEST_F(BtmDatabaseBounceTableGarbageCollectionTest,
GarbageCollectOldest_NullStorageTimes) {
LoadDatabase();
for (int i = 1; i <= 6; i++) {
auto state = db_->Read(base::StringPrintf("entry%d.test", i));
AddEntry(base::StringPrintf("entry%d.test", i), {},
state->user_activation_times, state->web_authn_assertion_times);
}
EXPECT_THAT(
db_->GetGarbageCollectOldestSitesForTesting(BtmDatabaseTable::kBounces),
testing::ElementsAre("entry6.test", "entry5.test", "entry4.test",
"entry3.test", "entry2.test", "entry1.test"));
}
TEST_F(BtmDatabaseBounceTableGarbageCollectionTest,
GarbageCollectOldest_NullInteractionTimes) {
LoadDatabase();
for (int i = 1; i <= 6; i++) {
auto state = db_->Read(base::StringPrintf("entry%d.test", i));
AddEntry(base::StringPrintf("entry%d.test", i), state->site_storage_times,
{}, state->web_authn_assertion_times);
}
EXPECT_THAT(
db_->GetGarbageCollectOldestSitesForTesting(BtmDatabaseTable::kBounces),
testing::ElementsAre("entry6.test", "entry5.test", "entry4.test",
"entry3.test", "entry2.test", "entry1.test"));
}
TEST_F(BtmDatabaseBounceTableGarbageCollectionTest,
GarbageCollectOldest_NullWaaTimes) {
LoadDatabase();
for (int i = 1; i <= 6; i++) {
auto state = db_->Read(base::StringPrintf("entry%d.test", i));
AddEntry(base::StringPrintf("entry%d.test", i), state->site_storage_times,
state->user_activation_times, {});
}
EXPECT_THAT(
db_->GetGarbageCollectOldestSitesForTesting(BtmDatabaseTable::kBounces),
testing::ElementsAre("entry6.test", "entry5.test", "entry4.test",
"entry3.test", "entry2.test", "entry1.test"));
}
// Making sure having only one of storage, user interaction or WAA times
// shouldn't alter the oldest site ordering of the garbage collection. In this
// explicit case we only have user interaction times; we should expect the same
// behavior for the other times.
TEST_F(BtmDatabaseBounceTableGarbageCollectionTest,
GarbageCollectOldest_SingleNonNull) {
LoadDatabase();
for (int i = 1; i <= 6; i++) {
auto state = db_->Read(base::StringPrintf("entry%d.test", i));
AddEntry(base::StringPrintf("entry%d.test", i), {},
state->user_activation_times, {});
}
EXPECT_THAT(
db_->GetGarbageCollectOldestSitesForTesting(BtmDatabaseTable::kBounces),
testing::ElementsAre("entry6.test", "entry5.test", "entry4.test",
"entry3.test", "entry2.test", "entry1.test"));
}
// A test class that verifies BtmDatabase database health metrics collection
// behavior. Created on-disk so opening a corrupt database file can be tested.
class BtmDatabaseHistogramTest : public BtmDatabaseTest {
public:
BtmDatabaseHistogramTest() : BtmDatabaseTest(false) {}
void SetUp() override {
BtmDatabaseTest::SetUp();
features_.InitAndEnableFeatureWithParameters(features::kBtmTtl,
{{"interaction_ttl", "inf"}});
}
const base::HistogramTester& histograms() const { return histogram_tester_; }
protected:
base::HistogramTester histogram_tester_;
};
TEST_F(BtmDatabaseHistogramTest, HealthMetrics) {
// The database was initialized successfully.
histograms().ExpectTotalCount("Privacy.DIPS.DatabaseErrors", 0);
histograms().ExpectTotalCount("Privacy.DIPS.DatabaseInit", 1);
histograms().ExpectUniqueSample("Privacy.DIPS.DatabaseInit", 1, 1);
// These should each have one sample after database initialization.
histograms().ExpectTotalCount("Privacy.DIPS.DatabaseHealthMetricsTime", 1);
histograms().ExpectTotalCount("Privacy.DIPS.DatabaseSize", 1);
// The database should be empty.
histograms().ExpectTotalCount("Privacy.DIPS.DatabaseEntryCount", 1);
histograms().ExpectUniqueSample("Privacy.DIPS.DatabaseEntryCount", 0, 1);
// Write an entry to the db.
db_->Write("url1.test", {},
/*interaction_times=*/
{{Time::FromSecondsSinceUnixEpoch(1),
Time::FromSecondsSinceUnixEpoch(1)}},
{}, {}, {});
db_->LogDatabaseMetricsForTesting();
// These should be unchanged.
histograms().ExpectTotalCount("Privacy.DIPS.DatabaseErrors", 0);
histograms().ExpectTotalCount("Privacy.DIPS.DatabaseInit", 1);
histograms().ExpectUniqueSample("Privacy.DIPS.DatabaseInit", 1, 1);
// These should each have two samples now.
histograms().ExpectTotalCount("Privacy.DIPS.DatabaseHealthMetricsTime", 2);
histograms().ExpectTotalCount("Privacy.DIPS.DatabaseSize", 2);
// The database should now have one entry.
histograms().ExpectTotalCount("Privacy.DIPS.DatabaseEntryCount", 2);
histograms().ExpectBucketCount("Privacy.DIPS.DatabaseEntryCount", 1, 1);
}
TEST_F(BtmDatabaseHistogramTest, ErrorMetrics) {
// The database was initialized successfully.
histograms().ExpectTotalCount("Privacy.DIPS.DatabaseErrors", 0);
histograms().ExpectTotalCount("Privacy.DIPS.DatabaseInit", 1);
histograms().ExpectUniqueSample("Privacy.DIPS.DatabaseInit", 1, 1);
// Write an entry to the db.
db_->Write("url1.test", {},
/*interaction_times=*/
{{Time::FromSecondsSinceUnixEpoch(1),
Time::FromSecondsSinceUnixEpoch(1)}},
{}, {}, {});
EXPECT_EQ(db_->GetEntryCount(BtmDatabaseTable::kBounces),
static_cast<size_t>(1));
// Corrupt the database.
db_.reset();
EXPECT_TRUE(sql::test::CorruptSizeInHeader(db_path_));
sql::test::ScopedErrorExpecter expecter;
expecter.ExpectError(SQLITE_CORRUPT);
// Open that database and ensure that it does not fail.
EXPECT_NO_FATAL_FAILURE(db_ = std::make_unique<TestDatabase>(db_path_));
histograms().ExpectTotalCount("Privacy.DIPS.DatabaseInit", 2);
histograms().ExpectUniqueSample("Privacy.DIPS.DatabaseInit", 1, 2);
// No data should be present as the database should have been razed.
EXPECT_EQ(db_->GetEntryCount(BtmDatabaseTable::kBounces),
static_cast<size_t>(0));
// Verify that the corruption error was reported.
EXPECT_TRUE(expecter.SawExpectedErrors());
histograms().ExpectTotalCount("Privacy.DIPS.DatabaseErrors", 1);
histograms().ExpectUniqueSample("Privacy.DIPS.DatabaseErrors",
sql::SqliteLoggedResultCode::kCorrupt, 1);
}
TEST_F(BtmDatabaseHistogramTest, PerformanceMetrics) {
histograms().ExpectTotalCount("Privacy.DIPS.Database.Operation.WriteTime", 0);
histograms().ExpectTotalCount("Privacy.DIPS.Database.Operation.ReadTime", 0);
// Write an entry to the db.
db_->Write("url.test", {},
/*interaction_times=*/
{{Time::FromSecondsSinceUnixEpoch(1),
Time::FromSecondsSinceUnixEpoch(1)}},
{}, {}, {});
histograms().ExpectTotalCount("Privacy.DIPS.Database.Operation.ReadTime", 0);
histograms().ExpectTotalCount("Privacy.DIPS.Database.Operation.WriteTime", 1);
// Read back the entry from the db.
db_->Read("site.test");
histograms().ExpectTotalCount("Privacy.DIPS.Database.Operation.ReadTime", 1);
histograms().ExpectTotalCount("Privacy.DIPS.Database.Operation.WriteTime", 1);
}
class BtmDatabaseInitializationTest : public testing::Test {
public:
BtmDatabaseInitializationTest() {
features_.InitAndEnableFeatureWithParameters(features::kBtmTtl,
{{"interaction_ttl", "inf"}});
}
protected:
void InitializeDatabase() { TestDatabase db(db_path_); }
void ValidateSchemaAndMetadataMatchLatestVersion(sql::Database* db) {
ValidateMetadataMatchesLatestVersion(db);
ValidateBouncesTableMatchesLatestSchemaVersion(db);
ValidatePopupsTableMatchesLatestSchemaVersion(db);
ValidateConfigTableMatchesLatestSchemaVersion(db);
}
int GetDatabaseVersion(sql::Database* db) {
sql::Statement kGetVersionSql(
db->GetUniqueStatement("SELECT value FROM meta WHERE key='version'"));
if (!kGetVersionSql.Step()) {
return 0;
}
return kGetVersionSql.ColumnInt(0);
}
int GetDatabaseLastCompatibleVersion(sql::Database* db) {
sql::Statement kGetLastCompatibleVersionSql(db->GetUniqueStatement(
"SELECT value FROM meta WHERE key='last_compatible_version'"));
if (!kGetLastCompatibleVersionSql.Step()) {
return 0;
}
return kGetLastCompatibleVersionSql.ColumnInt(0);
}
std::optional<int> GetPrepopulatedFromMetaTable(sql::Database* db) {
sql::Statement kGetPrepopulatedSql(db->GetUniqueStatement(
"SELECT value FROM meta WHERE key='prepopulated'"));
if (!kGetPrepopulatedSql.Step()) {
return std::nullopt;
}
return kGetPrepopulatedSql.ColumnInt(0);
}
std::optional<int64_t> GetPrepopulatedFromConfigTable(sql::Database* db) {
sql::Statement kGetPrepopulatedSql(db->GetUniqueStatement(
"SELECT int_value FROM config WHERE key='prepopulated'"));
if (!kGetPrepopulatedSql.Step()) {
return std::nullopt;
}
return kGetPrepopulatedSql.ColumnInt64(0);
}
base::FilePath db_path() { return db_path_; }
void LoadDatabase(const char* file_name) {
base::FilePath root;
ASSERT_TRUE(base::PathService::Get(base::DIR_SRC_TEST_DATA_ROOT, &root));
base::FilePath file_path = root.AppendASCII("content")
.AppendASCII("test")
.AppendASCII("data")
.AppendASCII("btm")
.AppendASCII(file_name);
EXPECT_TRUE(base::PathExists(file_path));
ASSERT_TRUE(sql::test::CreateDatabaseFromSQL(db_path(), file_path));
}
std::string RowCount(sql::Database* db, const char* table) {
return sql::test::ExecuteWithResult(
db, base::StringPrintf("SELECT COUNT(*) FROM %s", table));
}
private:
base::test::ScopedFeatureList features_;
std::unique_ptr<TestDatabase> db_;
base::ScopedTempDir temp_dir_;
base::FilePath db_path_;
// Test setup.
void SetUp() override {
ASSERT_TRUE(temp_dir_.CreateUniqueTempDir());
db_path_ = temp_dir_.GetPath().AppendASCII("DIPS.db");
}
void TearDown() override {
db_.reset();
ASSERT_TRUE(temp_dir_.Delete());
}
void ValidateMetadataMatchesLatestVersion(sql::Database* db) {
EXPECT_EQ(GetDatabaseVersion(db), BtmDatabase::kLatestSchemaVersion);
EXPECT_EQ(GetDatabaseLastCompatibleVersion(db),
BtmDatabase::kMinCompatibleSchemaVersion);
// We no longer mark prepopulation in the meta table.
EXPECT_EQ(GetPrepopulatedFromMetaTable(db), std::nullopt);
}
void ValidateBouncesTableMatchesLatestSchemaVersion(sql::Database* db) {
EXPECT_TRUE(db->DoesTableExist("bounces"));
EXPECT_TRUE(db->DoesColumnExist("bounces", "site"));
EXPECT_TRUE(db->DoesColumnExist("bounces", "first_bounce_time"));
EXPECT_TRUE(db->DoesColumnExist("bounces", "last_bounce_time"));
EXPECT_TRUE(db->DoesColumnExist("bounces", "first_stateful_bounce_time"));
EXPECT_TRUE(db->DoesColumnExist("bounces", "last_stateful_bounce_time"));
EXPECT_TRUE(db->DoesColumnExist("bounces", "first_site_storage_time"));
EXPECT_TRUE(db->DoesColumnExist("bounces", "last_site_storage_time"));
EXPECT_TRUE(db->DoesColumnExist("bounces", "first_user_activation_time"));
EXPECT_TRUE(db->DoesColumnExist("bounces", "last_user_activation_time"));
EXPECT_TRUE(db->DoesColumnExist("bounces", "first_stateful_bounce_time"));
EXPECT_TRUE(db->DoesColumnExist("bounces", "last_stateful_bounce_time"));
EXPECT_TRUE(
db->DoesColumnExist("bounces", "first_web_authn_assertion_time"));
EXPECT_TRUE(
db->DoesColumnExist("bounces", "last_web_authn_assertion_time"));
// Expect obsolete and temporary columns to have been removed.
EXPECT_FALSE(db->DoesColumnExist("bounces", "first_stateless_bounce_time"));
EXPECT_FALSE(db->DoesColumnExist("bounces", "last_stateless_bounce_time"));
}
void ValidatePopupsTableMatchesLatestSchemaVersion(sql::Database* db) {
EXPECT_TRUE(db->DoesTableExist("popups"));
EXPECT_TRUE(db->DoesColumnExist("popups", "opener_site"));
EXPECT_TRUE(db->DoesColumnExist("popups", "popup_site"));
EXPECT_TRUE(db->DoesColumnExist("popups", "access_id"));
EXPECT_TRUE(db->DoesColumnExist("popups", "last_popup_time"));
EXPECT_TRUE(db->DoesColumnExist("popups", "is_current_interaction"));
}
void ValidateConfigTableMatchesLatestSchemaVersion(sql::Database* db) {
EXPECT_TRUE(db->DoesTableExist("config"));
EXPECT_TRUE(db->DoesColumnExist("config", "key"));
EXPECT_TRUE(db->DoesColumnExist("config", "int_value"));
}
};
TEST_F(BtmDatabaseInitializationTest, InitializeEmptyDBWithLatestSchema) {
// Initialize with an empty DB.
InitializeDatabase();
// Validate aspects of current schema.
{
sql::Database db(sql::test::kTestTag);
ASSERT_TRUE(db.Open(db_path()));
ValidateSchemaAndMetadataMatchLatestVersion(&db);
}
}
TEST_F(BtmDatabaseInitializationTest, RazeIfIncompatible_TooNew) {
ASSERT_NO_FATAL_FAILURE(LoadDatabase("v2.sql"));
// Manipulations on the database version number are not necessary, but
// performed for consistency.
//
// Verify pre migration conditions.
{
sql::Database db(sql::test::kTestTag);
ASSERT_TRUE(db.Open(db_path()));
// Matches what is in "v2.sql" file:
const auto v2sql_version_num = 2;
const auto v2sql_compatible_version_num = 2;
const auto v2sql_prepopulated = 1;
EXPECT_EQ(GetDatabaseVersion(&db), v2sql_version_num);
EXPECT_EQ(GetDatabaseLastCompatibleVersion(&db),
v2sql_compatible_version_num);
EXPECT_EQ(GetPrepopulatedFromMetaTable(&db), v2sql_prepopulated);
sql::MetaTable meta_table;
ASSERT_TRUE(
meta_table.Init(&db, v2sql_version_num, v2sql_compatible_version_num));
// Prepare simulation of raze if incompatible. by making this DB
// incompatible.
const int tiny_increment = 1;
ASSERT_TRUE(meta_table.SetVersionNumber(BtmDatabase::kLatestSchemaVersion +
tiny_increment));
ASSERT_TRUE(meta_table.SetCompatibleVersionNumber(
BtmDatabase::kLatestSchemaVersion + tiny_increment));
EXPECT_EQ(GetDatabaseVersion(&db),
BtmDatabase::kLatestSchemaVersion + tiny_increment);
EXPECT_EQ(GetDatabaseLastCompatibleVersion(&db),
BtmDatabase::kLatestSchemaVersion + tiny_increment);
ASSERT_EQ(RowCount(&db, "bounces"), "4");
}
InitializeDatabase();
// Verify post migration conditions.
{
sql::Database db(sql::test::kTestTag);
ASSERT_TRUE(db.Open(db_path()));
// We should be on the latest schema version after razing.
ValidateSchemaAndMetadataMatchLatestVersion(&db);
// The DB was razed, so it shouldn't be marked as prepopulated, even though
// it was marked as prepopulated before the raze.
EXPECT_EQ(GetPrepopulatedFromConfigTable(&db), std::nullopt);
// The raze should have deleted all existing data.
EXPECT_EQ(RowCount(&db, "bounces"), "0");
}
}
TEST_F(BtmDatabaseInitializationTest, MigrateOldSchemaToLatestVersion) {
ASSERT_NO_FATAL_FAILURE(LoadDatabase("v2.sql"));
{
sql::Database db(sql::test::kTestTag);
ASSERT_TRUE(db.Open(db_path()));
EXPECT_EQ(GetDatabaseVersion(&db), 2);
EXPECT_EQ(GetDatabaseLastCompatibleVersion(&db), 2);
}
InitializeDatabase();
{
sql::Database db(sql::test::kTestTag);
ASSERT_TRUE(db.Open(db_path()));
ValidateSchemaAndMetadataMatchLatestVersion(&db);
}
}
// Verifies actions on the `config` table of the DIPS database.
class BtmDatabaseConfigTest : public BtmDatabaseTest {
public:
BtmDatabaseConfigTest() : BtmDatabaseTest(/*in_memory=*/true) {}
};
TEST_F(BtmDatabaseConfigTest, GetUnknownKeyReturnsNullopt) {
EXPECT_EQ(db_->GetConfigValueForTesting("test"), std::nullopt);
}
TEST_F(BtmDatabaseConfigTest, WriteAndRead) {
ASSERT_TRUE(db_->SetConfigValueForTesting("test", 42));
EXPECT_THAT(db_->GetConfigValueForTesting("test"), Optional(42));
}
TEST_F(BtmDatabaseConfigTest, Overwrite) {
ASSERT_TRUE(db_->SetConfigValueForTesting("test", 42));
ASSERT_TRUE(db_->SetConfigValueForTesting("test", 99));
EXPECT_THAT(db_->GetConfigValueForTesting("test"), Optional(99));
}
TEST_F(BtmDatabaseConfigTest, MultipleKeys) {
ASSERT_TRUE(db_->SetConfigValueForTesting("foo", 42));
ASSERT_TRUE(db_->SetConfigValueForTesting("bar", 99));
EXPECT_THAT(db_->GetConfigValueForTesting("foo"), Optional(42));
EXPECT_THAT(db_->GetConfigValueForTesting("bar"), Optional(99));
}
TEST_F(BtmDatabaseConfigTest, TimerLastFired) {
const base::Time time = Time::FromSecondsSinceUnixEpoch(1);
ASSERT_EQ(db_->GetTimerLastFired(), std::nullopt);
ASSERT_TRUE(db_->SetTimerLastFired(time));
ASSERT_EQ(db_->GetTimerLastFired(), time);
}
} // namespace content
|