1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894
|
// Copyright 2018 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/lookalikes/lookalike_url_navigation_throttle.h"
#include "base/containers/contains.h"
#include "base/functional/bind.h"
#include "base/path_service.h"
#include "base/strings/pattern.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/stringprintf.h"
#include "base/strings/utf_string_conversions.h"
#include "base/test/metrics/histogram_tester.h"
#include "base/test/simple_test_clock.h"
#include "build/build_config.h"
#include "chrome/browser/history/history_service_factory.h"
#include "chrome/browser/history/history_test_utils.h"
#include "chrome/browser/lookalikes/lookalike_test_helper.h"
#include "chrome/browser/lookalikes/lookalike_url_blocking_page.h"
#include "chrome/browser/lookalikes/lookalike_url_service.h"
#include "chrome/browser/lookalikes/lookalike_url_service_factory.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_commands.h"
#include "chrome/browser/ui/browser_window/public/browser_window_features.h"
#include "chrome/common/webui_url_constants.h"
#include "chrome/test/base/in_process_browser_test.h"
#include "chrome/test/base/ui_test_utils.h"
#include "components/lookalikes/core/lookalike_url_util.h"
#include "components/lookalikes/core/safety_tip_test_utils.h"
#include "components/lookalikes/core/safety_tips_config.h"
#include "components/network_session_configurator/common/network_switches.h"
#include "components/omnibox/browser/location_bar_model.h"
#include "components/security_interstitials/content/security_interstitial_page.h"
#include "components/security_interstitials/content/security_interstitial_tab_helper.h"
#include "components/security_interstitials/core/metrics_helper.h"
#include "components/site_engagement/content/site_engagement_score.h"
#include "components/site_engagement/content/site_engagement_service.h"
#include "components/ukm/test_ukm_recorder.h"
#include "components/url_formatter/spoof_checks/top_domains/test_top_bucket_domains.h"
#include "content/public/browser/web_contents.h"
#include "content/public/common/content_paths.h"
#include "content/public/test/browser_test.h"
#include "content/public/test/content_mock_cert_verifier.h"
#include "content/public/test/prerender_test_util.h"
#include "content/public/test/signed_exchange_browser_test_helper.h"
#include "content/public/test/test_navigation_observer.h"
#include "content/public/test/url_loader_interceptor.h"
#include "net/cert/mock_cert_verifier.h"
#include "net/cert/test_root_certs.h"
#include "net/dns/mock_host_resolver.h"
#include "net/test/cert_test_util.h"
#include "net/test/embedded_test_server/http_request.h"
#include "net/test/embedded_test_server/http_response.h"
#include "services/metrics/public/cpp/ukm_builders.h"
#include "services/metrics/public/cpp/ukm_source.h"
#include "services/network/public/cpp/network_switches.h"
#include "services/network/public/cpp/simple_url_loader.h"
#include "ui/base/window_open_disposition.h"
namespace {
using lookalikes::LookalikeUrlMatchType;
using lookalikes::NavigationSuggestionEvent;
using security_interstitials::MetricsHelper;
using security_interstitials::SecurityInterstitialCommand;
using UkmEntry = ukm::builders::LookalikeUrl_NavigationSuggestion;
using lookalikes::GetDomainInfo;
using lookalikes::kIncognitoInterstitialHistogramName;
using lookalikes::kInterstitialHistogramName;
using lookalikes::LookalikeUrlBlockingPageUserAction;
// An engagement score above MEDIUM.
const int kHighEngagement = 20;
// An engagement score below MEDIUM.
const int kLowEngagement = 1;
// The UMA metric names registered by metrics_helper.
const char kInterstitialDecisionMetric[] = "interstitial.lookalike.decision";
const char kInterstitialInteractionMetric[] =
"interstitial.lookalike.interaction";
const char kConsoleMessage[] =
"Chrome has determined that * could be fake or fraudulent*";
static std::unique_ptr<net::test_server::HttpResponse>
NetworkErrorResponseHandler(const net::test_server::HttpRequest& request) {
return std::unique_ptr<net::test_server::HttpResponse>(
new net::test_server::RawHttpResponse("", ""));
}
security_interstitials::SecurityInterstitialPage* GetCurrentInterstitial(
content::WebContents* web_contents) {
security_interstitials::SecurityInterstitialTabHelper* helper =
security_interstitials::SecurityInterstitialTabHelper::FromWebContents(
web_contents);
if (!helper) {
return nullptr;
}
return helper->GetBlockingPageForCurrentlyCommittedNavigationForTesting();
}
security_interstitials::SecurityInterstitialPage::TypeID GetInterstitialType(
content::WebContents* web_contents) {
security_interstitials::SecurityInterstitialPage* page =
GetCurrentInterstitial(web_contents);
if (!page) {
return nullptr;
}
return page->GetTypeForTesting();
}
// Sets the absolute Site Engagement |score| for the testing origin.
void SetEngagementScore(Browser* browser, const GURL& url, double score) {
site_engagement::SiteEngagementService::Get(browser->profile())
->ResetBaseScoreForURL(url, score);
}
bool IsUrlShowing(Browser* browser) {
return !browser->GetFeatures()
.location_bar_model()
->GetFormattedFullURL()
.empty();
}
// Navigate to |url| and wait for the load to complete before returning.
// Simulates a link click navigation. We don't use
// ui_test_utils::NavigateToURL(const GURL&) because it simulates the user
// typing the URL, causing the site to have a site engagement score of at
// least LOW.
void NavigateToURLSync(Browser* browser, const GURL& url) {
content::TestNavigationObserver navigation_observer(
browser->tab_strip_model()->GetActiveWebContents(), 1);
NavigateParams params(browser, url, ui::PAGE_TRANSITION_LINK);
params.initiator_origin = url::Origin::Create(GURL("about:blank"));
params.disposition = WindowOpenDisposition::CURRENT_TAB;
params.is_renderer_initiated = true;
ui_test_utils::NavigateToURL(¶ms);
navigation_observer.Wait();
}
// Load given URL and verify that it loaded an interstitial and hid the URL.
void LoadAndCheckInterstitialAt(Browser* browser, const GURL& url) {
content::WebContents* web_contents =
browser->tab_strip_model()->GetActiveWebContents();
content::WebContentsConsoleObserver console_observer(web_contents);
console_observer.SetPattern(kConsoleMessage);
EXPECT_EQ(nullptr, GetCurrentInterstitial(web_contents));
NavigateToURLSync(browser, url);
EXPECT_EQ(LookalikeUrlBlockingPage::kTypeForTesting,
GetInterstitialType(web_contents));
EXPECT_FALSE(IsUrlShowing(browser));
ASSERT_TRUE(console_observer.Wait());
EXPECT_TRUE(
base::MatchPattern(console_observer.GetMessageAt(0u), kConsoleMessage));
}
void SendInterstitialCommand(content::WebContents* web_contents,
SecurityInterstitialCommand command) {
GetCurrentInterstitial(web_contents)
->CommandReceived(base::NumberToString(command));
}
void SendInterstitialCommandSync(Browser* browser,
SecurityInterstitialCommand command,
bool punycode_interstitial = false) {
content::WebContents* web_contents =
browser->tab_strip_model()->GetActiveWebContents();
EXPECT_EQ(LookalikeUrlBlockingPage::kTypeForTesting,
GetInterstitialType(web_contents));
content::TestNavigationObserver navigation_observer(web_contents, 1);
SendInterstitialCommand(web_contents, command);
navigation_observer.Wait();
EXPECT_EQ(nullptr, GetCurrentInterstitial(web_contents));
if (punycode_interstitial) {
// "Back to safety" button on the punycode interstitial goes to the New
// Tab Page which doesn't show the URL.
EXPECT_FALSE(IsUrlShowing(browser));
} else {
EXPECT_TRUE(IsUrlShowing(browser));
}
}
// Verify that no interstitial is shown, regardless of feature state.
void TestInterstitialNotShown(Browser* browser, const GURL& navigated_url) {
content::WebContents* web_contents =
browser->tab_strip_model()->GetActiveWebContents();
NavigateToURLSync(browser, navigated_url);
EXPECT_EQ(nullptr, GetCurrentInterstitial(web_contents));
// Navigate to an empty page. This will happen after any
// LookalikeUrlService tasks, so will effectively wait for those tasks to
// finish.
NavigateToURLSync(browser, GURL("about:blank"));
EXPECT_EQ(nullptr, GetCurrentInterstitial(web_contents));
}
// Add an allowlist with entries that aren't allowlisted for all domains.
void ConfigureAllowlistWithScopes() {
auto config_proto = lookalikes::GetOrCreateSafetyTipsConfig();
config_proto->clear_allowed_pattern();
config_proto->clear_canonical_pattern();
config_proto->clear_cohort();
// Note: allowed_pattern must be sorted, so "Allowed*" comes before "May*".
// may-spoof-anyone.com has no cohort.
auto* patternWildcard = config_proto->add_allowed_pattern();
patternWildcard->set_pattern("may-spoof-anyone.com/");
// may-spoof-google.com is only allowed to spoof google.com.
config_proto->add_canonical_pattern()->set_pattern("google.com/");
auto* pattern = config_proto->add_allowed_pattern();
pattern->set_pattern("may-spoof-google.com/");
auto* cohort = config_proto->add_cohort();
cohort->add_canonical_index(0); // google.com
pattern->add_cohort_index(0);
// example·com.com is xn--examplecom-rra.com in punycode & fails spoof checks.
auto* idn_pattern = config_proto->add_allowed_pattern(); // Index 2
idn_pattern->set_pattern("xn--examplecom-rra.com/");
auto* idn_cohort = config_proto->add_cohort(); // Index 1
idn_cohort->add_allowed_index(2);
idn_pattern->add_cohort_index(1);
lookalikes::SetSafetyTipsRemoteConfigProto(std::move(config_proto));
}
} // namespace
class LookalikeUrlNavigationThrottleBrowserTest : public InProcessBrowserTest {
protected:
LookalikeUrlNavigationThrottleBrowserTest()
: https_server_(std::make_unique<net::EmbeddedTestServer>(
net::EmbeddedTestServer::TYPE_HTTPS)) {}
void SetUpOnMainThread() override {
host_resolver()->AddRule("*", "127.0.0.1");
test_ukm_recorder_ = std::make_unique<ukm::TestAutoSetUkmRecorder>();
test_helper_ =
std::make_unique<LookalikeTestHelper>(test_ukm_recorder_.get());
const base::Time kNow = base::Time::FromSecondsSinceUnixEpoch(1000);
test_clock_.SetNow(kNow);
LookalikeUrlService* lookalike_service =
LookalikeUrlServiceFactory::GetForProfile(browser()->profile());
lookalike_service->SetClockForTesting(&test_clock_);
// Use HTTPS URLs in tests.
mock_cert_verifier_.mock_cert_verifier()->set_default_result(net::OK);
https_server_->AddDefaultHandlers(GetChromeTestDataDir());
ASSERT_TRUE(https_server_->Start());
LookalikeTestHelper::SetUpLookalikeTestParams();
InProcessBrowserTest::SetUpOnMainThread();
}
void TearDownOnMainThread() override {
InProcessBrowserTest::TearDownOnMainThread();
LookalikeTestHelper::TearDownLookalikeTestParams();
}
void SetUpCommandLine(base::CommandLine* command_line) override {
mock_cert_verifier_.SetUpCommandLine(command_line);
}
void SetUpInProcessBrowserTestFixture() override {
mock_cert_verifier_.SetUpInProcessBrowserTestFixture();
}
void TearDownInProcessBrowserTestFixture() override {
mock_cert_verifier_.TearDownInProcessBrowserTestFixture();
}
GURL GetURL(const char* hostname) const {
return https_server()->GetURL(hostname, "/title1.html");
}
GURL GetURLWithoutPath(const char* hostname) const {
return GetURL(hostname).GetWithEmptyPath();
}
GURL GetLongRedirect(const char* via_hostname1,
const char* via_hostname2,
const char* dest_hostname) const {
GURL dest = GetURL(dest_hostname);
GURL mid = https_server()->GetURL(via_hostname2,
"/server-redirect?" + dest.spec());
return https_server()->GetURL(via_hostname1,
"/server-redirect?" + mid.spec());
}
// Checks that UKM recorded an event for each URL in |navigated_urls| with the
// given metric value.
template <typename T>
void CheckInterstitialUkm(const std::vector<GURL>& navigated_urls,
const std::string& metric_name,
T metric_value) {
auto entries = test_ukm_recorder()->GetEntriesByName(UkmEntry::kEntryName);
ASSERT_EQ(navigated_urls.size(), entries.size());
int entry_count = 0;
for (const ukm::mojom::UkmEntry* const entry : entries) {
test_ukm_recorder()->ExpectEntrySourceHasUrl(entry,
navigated_urls[entry_count]);
test_ukm_recorder()->ExpectEntryMetric(entry, metric_name,
static_cast<int>(metric_value));
entry_count++;
}
}
// Tests that the histogram event |expected_event| is recorded, the
// interstitial is displayed and clicking the link on the interstitial works.
void TestMetricsRecordedAndInterstitialShown(
Browser* browser,
const base::HistogramTester& histograms,
const GURL& navigated_url,
const GURL& expected_suggested_url,
NavigationSuggestionEvent expected_event,
bool expect_signed_exchange = false) {
history::HistoryService* const history_service =
HistoryServiceFactory::GetForProfile(
browser->profile(), ServiceAccessType::EXPLICIT_ACCESS);
ui_test_utils::WaitForHistoryToLoad(history_service);
LoadAndCheckInterstitialAt(browser, navigated_url);
if (expect_signed_exchange) {
LookalikeUrlBlockingPage* interstitial =
static_cast<LookalikeUrlBlockingPage*>(GetCurrentInterstitial(
browser->tab_strip_model()->GetActiveWebContents()));
EXPECT_TRUE(interstitial->is_signed_exchange_for_testing());
}
bool punycode_interstitial =
expected_event == NavigationSuggestionEvent::kFailedSpoofChecks;
SendInterstitialCommandSync(browser,
SecurityInterstitialCommand::CMD_DONT_PROCEED,
punycode_interstitial);
EXPECT_EQ(
expected_suggested_url,
browser->tab_strip_model()->GetActiveWebContents()->GetVisibleURL());
// Clicking the link in the interstitial should also remove the original
// URL from history.
ui_test_utils::HistoryEnumerator enumerator(browser->profile());
EXPECT_FALSE(base::Contains(enumerator.urls(), navigated_url));
bool is_incognito = browser->profile()->IsIncognitoProfile();
histograms.ExpectUniqueSample(kInterstitialHistogramName, expected_event,
is_incognito ? 0 : 1);
histograms.ExpectUniqueSample(kIncognitoInterstitialHistogramName,
expected_event, is_incognito ? 1 : 0);
histograms.ExpectTotalCount(kInterstitialDecisionMetric, 2);
histograms.ExpectBucketCount(kInterstitialDecisionMetric,
MetricsHelper::SHOW, 1);
histograms.ExpectBucketCount(kInterstitialDecisionMetric,
MetricsHelper::DONT_PROCEED, 1);
histograms.ExpectTotalCount(kInterstitialInteractionMetric, 1);
histograms.ExpectBucketCount(kInterstitialInteractionMetric,
MetricsHelper::TOTAL_VISITS, 1);
}
// Tests that the histogram event |expected_event| is recorded, the
// interstitial is displayed and clicking "Back to safety" on the interstitial
// works.
void TestPunycodeInterstitialShown(Browser* browser,
const GURL& navigated_url,
NavigationSuggestionEvent expected_event) {
base::HistogramTester histograms;
history::HistoryService* const history_service =
HistoryServiceFactory::GetForProfile(
browser->profile(), ServiceAccessType::EXPLICIT_ACCESS);
ui_test_utils::WaitForHistoryToLoad(history_service);
LoadAndCheckInterstitialAt(browser, navigated_url);
// Clicking "Back to safety" should go to the new tab page.
SendInterstitialCommandSync(browser,
SecurityInterstitialCommand::CMD_DONT_PROCEED,
/*punycode_interstitial=*/true);
EXPECT_EQ(
GURL(chrome::kChromeUINewTabURL),
browser->tab_strip_model()->GetActiveWebContents()->GetVisibleURL());
histograms.ExpectTotalCount(kInterstitialHistogramName, 1);
histograms.ExpectBucketCount(kInterstitialHistogramName, expected_event, 1);
histograms.ExpectTotalCount(kInterstitialDecisionMetric, 2);
histograms.ExpectBucketCount(kInterstitialDecisionMetric,
MetricsHelper::SHOW, 1);
histograms.ExpectBucketCount(kInterstitialDecisionMetric,
MetricsHelper::DONT_PROCEED, 1);
histograms.ExpectTotalCount(kInterstitialInteractionMetric, 1);
histograms.ExpectBucketCount(kInterstitialInteractionMetric,
MetricsHelper::TOTAL_VISITS, 1);
}
// Tests that the histogram event |expected_event| is recorded, the
// interstitial is displayed and clicking through the interstitial works.
void TestHistogramEventsRecordedWhenInterstitialIgnored(
Browser* browser,
base::HistogramTester* histograms,
const GURL& navigated_url,
NavigationSuggestionEvent expected_event) {
history::HistoryService* const history_service =
HistoryServiceFactory::GetForProfile(
browser->profile(), ServiceAccessType::EXPLICIT_ACCESS);
ui_test_utils::WaitForHistoryToLoad(history_service);
LoadAndCheckInterstitialAt(browser, navigated_url);
// Clicking the ignore button in the interstitial should remove the
// interstitial and navigate to the original URL.
SendInterstitialCommandSync(browser,
SecurityInterstitialCommand::CMD_PROCEED);
EXPECT_EQ(
navigated_url,
browser->tab_strip_model()->GetActiveWebContents()->GetVisibleURL());
// Clicking the link should cause the original URL to appear in history.
ui_test_utils::HistoryEnumerator enumerator(browser->profile());
EXPECT_TRUE(base::Contains(enumerator.urls(), navigated_url));
histograms->ExpectTotalCount(kInterstitialHistogramName, 1);
histograms->ExpectBucketCount(kInterstitialHistogramName, expected_event,
1);
histograms->ExpectTotalCount(kInterstitialDecisionMetric, 2);
histograms->ExpectBucketCount(kInterstitialDecisionMetric,
MetricsHelper::SHOW, 1);
histograms->ExpectBucketCount(kInterstitialDecisionMetric,
MetricsHelper::PROCEED, 1);
histograms->ExpectTotalCount(kInterstitialInteractionMetric, 1);
histograms->ExpectBucketCount(kInterstitialInteractionMetric,
MetricsHelper::TOTAL_VISITS, 1);
TestInterstitialNotShown(browser, navigated_url);
}
LookalikeTestHelper* test_helper() { return test_helper_.get(); }
ukm::TestUkmRecorder* test_ukm_recorder() { return test_ukm_recorder_.get(); }
base::SimpleTestClock* test_clock() { return &test_clock_; }
net::EmbeddedTestServer* https_server() const { return https_server_.get(); }
private:
std::unique_ptr<ukm::TestAutoSetUkmRecorder> test_ukm_recorder_;
std::unique_ptr<LookalikeTestHelper> test_helper_;
std::unique_ptr<net::EmbeddedTestServer> https_server_;
content::ContentMockCertVerifier mock_cert_verifier_;
base::SimpleTestClock test_clock_;
};
// Navigating to a non-IDN shouldn't show an interstitial or record metrics.
// TODO(https://crbug.com1207573): re-enable when flakiness is fixed.
#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_WIN) || BUILDFLAG(IS_MAC)
#define MAYBE_NonIdn_NoMatch DISABLED_NonIdn_NoMatch
#else
#define MAYBE_NonIdn_NoMatch NonIdn_NoMatch
#endif
IN_PROC_BROWSER_TEST_F(LookalikeUrlNavigationThrottleBrowserTest,
MAYBE_NonIdn_NoMatch) {
TestInterstitialNotShown(browser(), GetURL("google.com"));
test_helper()->CheckNoLookalikeUkm();
}
// Navigating to a domain whose visual representation does not look like a
// top domain shouldn't show an interstitial or record metrics.
IN_PROC_BROWSER_TEST_F(LookalikeUrlNavigationThrottleBrowserTest,
NonTopDomainIdn_NoInterstitial) {
TestInterstitialNotShown(browser(), GetURL("éxample.com"));
test_helper()->CheckNoLookalikeUkm();
}
// If the user has engaged with the domain before, metrics shouldn't be recorded
// and the interstitial shouldn't be shown, even if the domain is visually
// similar to a top domain.
IN_PROC_BROWSER_TEST_F(LookalikeUrlNavigationThrottleBrowserTest,
Idn_TopDomain_EngagedSite_NoMatch) {
const GURL url = GetURL("googlé.com");
SetEngagementScore(browser(), url, kHighEngagement);
TestInterstitialNotShown(browser(), url);
test_helper()->CheckNoLookalikeUkm();
}
// Navigate to a domain whose visual representation looks like a top domain.
// This should record metrics. It should also show a lookalike warning
// interstitial.
IN_PROC_BROWSER_TEST_F(LookalikeUrlNavigationThrottleBrowserTest,
Idn_TopDomain_Match) {
const GURL kNavigatedUrl = GetURL("googlé.com");
const GURL kExpectedSuggestedUrl = GetURLWithoutPath("google.com");
// Even if the navigated site has a low engagement score, it should be
// considered for lookalike suggestions.
SetEngagementScore(browser(), kNavigatedUrl, kLowEngagement);
base::HistogramTester histograms;
TestMetricsRecordedAndInterstitialShown(
browser(), histograms, kNavigatedUrl, kExpectedSuggestedUrl,
NavigationSuggestionEvent::kMatchSkeletonTop500);
CheckInterstitialUkm({kNavigatedUrl}, "MatchType",
LookalikeUrlMatchType::kSkeletonMatchTop500);
CheckInterstitialUkm({kNavigatedUrl}, "TriggeredByInitialUrl", false);
test_helper()->CheckSafetyTipUkmCount(0);
}
// Navigate to a domain that contains an unsafe ligature.
IN_PROC_BROWSER_TEST_F(LookalikeUrlNavigationThrottleBrowserTest,
UnsafeLigature) {
const GURL kNavigatedUrl = GetURL("GOOGLELOGOLIGATURE.com");
// Ligature checks show the punycode interstitial which doesn't have a
// suggested URL. Its "Don't proceed" button goes back, which is the new tab
// page here.
const GURL kSuggestedURL("chrome://newtab");
base::HistogramTester histograms;
TestMetricsRecordedAndInterstitialShown(
browser(), histograms, kNavigatedUrl, kSuggestedURL,
NavigationSuggestionEvent::kFailedSpoofChecks);
CheckInterstitialUkm({kNavigatedUrl}, "MatchType",
LookalikeUrlMatchType::kFailedSpoofChecks);
CheckInterstitialUkm({kNavigatedUrl}, "TriggeredByInitialUrl", false);
test_helper()->CheckSafetyTipUkmCount(0);
}
// Navigate to a domain that would trigger the warning, but doesn't because it
// fails-safe when the allowlist isn't available.
IN_PROC_BROWSER_TEST_F(LookalikeUrlNavigationThrottleBrowserTest,
NoMatchOnAllowlistMissing) {
const GURL kNavigatedUrl = GetURL("googlé.com");
// Clear out any existing proto.
lookalikes::SetSafetyTipsRemoteConfigProto(nullptr);
SetEngagementScore(browser(), kNavigatedUrl, kLowEngagement);
TestInterstitialNotShown(browser(), kNavigatedUrl);
test_helper()->CheckNoLookalikeUkm();
}
// Embedding a top domain should show an interstitial when enabled.
IN_PROC_BROWSER_TEST_F(LookalikeUrlNavigationThrottleBrowserTest,
TargetEmbedding_TopDomain_Match) {
const GURL kNavigatedUrl = GetURL("google.com-test.com");
const GURL kExpectedSuggestedUrl = GetURLWithoutPath("google.com");
SetEngagementScore(browser(), kNavigatedUrl, kLowEngagement);
base::HistogramTester histograms;
TestMetricsRecordedAndInterstitialShown(
browser(), histograms, kNavigatedUrl, kExpectedSuggestedUrl,
NavigationSuggestionEvent::kMatchTargetEmbedding);
CheckInterstitialUkm({kNavigatedUrl}, "MatchType",
LookalikeUrlMatchType::kTargetEmbedding);
CheckInterstitialUkm({kNavigatedUrl}, "TriggeredByInitialUrl", false);
test_helper()->CheckSafetyTipUkmCount(0);
}
// Embedding a top domain would normally show an interstitial, but shouldn't
// here because it's narrowly allowlisted.
IN_PROC_BROWSER_TEST_F(LookalikeUrlNavigationThrottleBrowserTest,
TargetEmbedding_ScopedAllowlistMatch) {
ConfigureAllowlistWithScopes();
const GURL kNavigatedUrl = GetURL("google.com.may-spoof-google.com");
SetEngagementScore(browser(), kNavigatedUrl, kLowEngagement);
TestInterstitialNotShown(browser(), kNavigatedUrl);
test_helper()->CheckNoLookalikeUkm();
}
// Same as TargetEmbedding_ScopedAllowlistMatch, but the attacker-controlled
// domain is spoofing an unauthorized victim. This should show a warning.
IN_PROC_BROWSER_TEST_F(LookalikeUrlNavigationThrottleBrowserTest,
TargetEmbedding_ScopedAllowlistMatchWrongDomain) {
ConfigureAllowlistWithScopes();
const GURL kNavigatedUrl = GetURL("blogspot.com.may-spoof-google.com");
const GURL kExpectedSuggestedUrl = GetURLWithoutPath("blogspot.com");
SetEngagementScore(browser(), kNavigatedUrl, kLowEngagement);
base::HistogramTester histograms;
TestMetricsRecordedAndInterstitialShown(
browser(), histograms, kNavigatedUrl, kExpectedSuggestedUrl,
NavigationSuggestionEvent::kMatchTargetEmbedding);
CheckInterstitialUkm({kNavigatedUrl}, "MatchType",
LookalikeUrlMatchType::kTargetEmbedding);
CheckInterstitialUkm({kNavigatedUrl}, "TriggeredByInitialUrl", false);
test_helper()->CheckSafetyTipUkmCount(0);
}
// Same as TargetEmbedding_TopDomain_Match, but has a redirect where the first
// and last URLs are both target embedding matches. Should only record
// metrics for the first URL. Regression test for crbug.com/1136296.
IN_PROC_BROWSER_TEST_F(LookalikeUrlNavigationThrottleBrowserTest,
TargetEmbedding_TopDomain_Redirect_Match) {
const GURL kNavigatedUrl = GetLongRedirect("google.com-test.com", "site.test",
"youtube.com-test.com");
// UKM will record the final URL of the redirect:
const GURL kLastUrl = GetURL("youtube.com-test.com");
const GURL kExpectedSuggestedUrl = GetURLWithoutPath("google.com");
SetEngagementScore(browser(), kNavigatedUrl, kLowEngagement);
base::HistogramTester histograms;
TestMetricsRecordedAndInterstitialShown(
browser(), histograms, kNavigatedUrl, kExpectedSuggestedUrl,
NavigationSuggestionEvent::kMatchTargetEmbedding);
CheckInterstitialUkm({kLastUrl}, "MatchType",
LookalikeUrlMatchType::kTargetEmbedding);
CheckInterstitialUkm({kLastUrl}, "TriggeredByInitialUrl", true);
test_helper()->CheckSafetyTipUkmCount(0);
}
// Target embedding should not trigger on allowlisted embedder domains.
IN_PROC_BROWSER_TEST_F(LookalikeUrlNavigationThrottleBrowserTest,
TargetEmbedding_EmbedderAllowlist) {
const GURL kNavigatedUrl = GetURL("google.com.allowlisted.com");
SetEngagementScore(browser(), kNavigatedUrl, kLowEngagement);
lookalikes::SetSafetyTipAllowlistPatterns({"allowlisted.com/"}, {}, {});
TestInterstitialNotShown(browser(), kNavigatedUrl);
test_helper()->CheckNoLookalikeUkm();
}
// Target embedding should not trigger on allowlisted target domains.
IN_PROC_BROWSER_TEST_F(LookalikeUrlNavigationThrottleBrowserTest,
TargetEmbedding_TargetAllowlist) {
const GURL kNavigatedUrl = GetURL("foo.scholar.google.com.com");
SetEngagementScore(browser(), kNavigatedUrl, kLowEngagement);
lookalikes::SetSafetyTipAllowlistPatterns({}, {"scholar\\.google\\.com"}, {});
TestInterstitialNotShown(browser(), kNavigatedUrl);
test_helper()->CheckNoLookalikeUkm();
}
// Target embedding shouldn't trigger on component-delivered common words.
IN_PROC_BROWSER_TEST_F(LookalikeUrlNavigationThrottleBrowserTest,
TargetEmbedding_ComponentCommonWords) {
const GURL kNavigatedUrl = GetURL("google.com.example.com");
SetEngagementScore(browser(), kNavigatedUrl, kLowEngagement);
lookalikes::SetSafetyTipAllowlistPatterns({}, {}, {"google"});
TestInterstitialNotShown(browser(), kNavigatedUrl);
test_helper()->CheckNoLookalikeUkm();
}
// Navigate to a domain target embedding a domain with no separators, but that
// matches the target allowlist. Regression test for crbug.com/1127450.
IN_PROC_BROWSER_TEST_F(LookalikeUrlNavigationThrottleBrowserTest,
TargetEmbedding_TargetAllowlistWithNoSeparators) {
const GURL kNavigatedUrl = GetURL("googlecom.example.com");
SetEngagementScore(browser(), kNavigatedUrl, kLowEngagement);
lookalikes::SetSafetyTipAllowlistPatterns({}, {"google\\.com"}, {});
TestInterstitialNotShown(browser(), kNavigatedUrl);
test_helper()->CheckNoLookalikeUkm();
}
// Similar to Idn_TopDomain_Match but the domain is not in top 500. Should not
// show an interstitial, but should still record metrics.
IN_PROC_BROWSER_TEST_F(LookalikeUrlNavigationThrottleBrowserTest,
Idn_TopDomain_Match_Not500) {
const GURL kNavigatedUrl = GetURL("googlé.sk");
// Even if the navigated site has a low engagement score, it should be
// considered for lookalike suggestions.
SetEngagementScore(browser(), kNavigatedUrl, kLowEngagement);
base::HistogramTester histograms;
TestInterstitialNotShown(browser(), kNavigatedUrl);
histograms.ExpectTotalCount(kInterstitialHistogramName, 1);
histograms.ExpectBucketCount(kInterstitialHistogramName,
NavigationSuggestionEvent::kMatchSkeletonTop5k,
1);
// Navigate away so that safety tip metrics are recorded.
ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), GURL("about:blank")));
// This heuristic shows a safety tip, so no interstitial UKM should be
// recorded.
test_helper()->CheckInterstitialUkmCount(0);
test_helper()->CheckSafetyTipUkmCount(1);
}
// Same as Idn_TopDomain_Match, but this time the domain contains characters
// from different scripts, failing the checks in IDN spoof checker before
// reaching the top domain check. In this case, the end result is the same, but
// the reason we fall back to punycode is different.
IN_PROC_BROWSER_TEST_F(LookalikeUrlNavigationThrottleBrowserTest,
Idn_TopDomainMixedScript_Match) {
const GURL kNavigatedUrl = GetURL("аррӏе.com");
const GURL kExpectedSuggestedUrl = GetURLWithoutPath("apple.com");
// Even if the navigated site has a low engagement score, it should be
// considered for lookalike suggestions.
SetEngagementScore(browser(), kNavigatedUrl, kLowEngagement);
base::HistogramTester histograms;
TestMetricsRecordedAndInterstitialShown(
browser(), histograms, kNavigatedUrl, kExpectedSuggestedUrl,
NavigationSuggestionEvent::kMatchSkeletonTop500);
CheckInterstitialUkm({kNavigatedUrl}, "MatchType",
LookalikeUrlMatchType::kSkeletonMatchTop500);
test_helper()->CheckSafetyTipUkmCount(0);
}
// The navigated domain will fall back to punycode because it fails standard
// ICU spoof checks in the IDN spoof checker. However, no interstitial will be
// shown as the domain name is single character.
IN_PROC_BROWSER_TEST_F(LookalikeUrlNavigationThrottleBrowserTest,
Punycode_ShortHostname_NoInterstitial) {
const GURL kNavigatedUrl = GetURL("τ.com");
TestInterstitialNotShown(browser(), kNavigatedUrl);
test_helper()->CheckNoLookalikeUkm();
}
// Same as Punycode_ShortHostname_NoInterstitial but also has target embedding.
// Should show an interstitial this time.
IN_PROC_BROWSER_TEST_F(LookalikeUrlNavigationThrottleBrowserTest,
Punycode_ShortHostname_TargetEmbedding_Interstitial) {
const GURL kNavigatedUrl = GetURL("google-com.τ.com");
const GURL kExpectedSuggestedUrl = GetURLWithoutPath("google.com");
base::HistogramTester histograms;
TestMetricsRecordedAndInterstitialShown(
browser(), histograms, kNavigatedUrl, kExpectedSuggestedUrl,
NavigationSuggestionEvent::kMatchTargetEmbedding);
CheckInterstitialUkm({kNavigatedUrl}, "MatchType",
LookalikeUrlMatchType::kTargetEmbedding);
test_helper()->CheckSafetyTipUkmCount(0);
}
// The navigated domain will fall back to punycode because it fails spoof checks
// in IDN spoof checker. The heuristic that changes this domain to punycode
// (latin middle dot) is configured to show a punycode interstitial.
IN_PROC_BROWSER_TEST_F(LookalikeUrlNavigationThrottleBrowserTest,
Punycode_NoSuggestedUrl_Interstitial) {
const GURL kNavigatedUrl = GetURL("example·com.com");
TestPunycodeInterstitialShown(browser(), kNavigatedUrl,
NavigationSuggestionEvent::kFailedSpoofChecks);
CheckInterstitialUkm({kNavigatedUrl}, "MatchType",
LookalikeUrlMatchType::kFailedSpoofChecks);
test_helper()->CheckSafetyTipUkmCount(0);
}
// The navigated domain will fall back to punycode because it fails spoof checks
// in IDN spoof checker. The heuristic that changes this domain to punycode
// (latin middle dot) is configured to show a punycode interstitial, but the
// domain is allowlisted.
IN_PROC_BROWSER_TEST_F(LookalikeUrlNavigationThrottleBrowserTest,
Punycode_NoSuggestedUrl_Allowlisted) {
ConfigureAllowlistWithScopes();
const GURL kNavigatedUrl = GetURL("example·com.com");
TestInterstitialNotShown(browser(), kNavigatedUrl);
test_helper()->CheckNoLookalikeUkm();
}
// The navigated domain will fall back to punycode because it fails spoof checks
// in IDN spoof checker. The heuristic that changes this domain to punycode
// (latin middle dot) is configured to show a punycode interstitial. The domain
// is also caught by the target embedding heuristic. Target embedding should
// take priority.
IN_PROC_BROWSER_TEST_F(LookalikeUrlNavigationThrottleBrowserTest,
PunycodeAndTargetEmbedding_NoSuggestedUrl_Interstitial) {
// Navigate to a domain that triggers target embedding:
const GURL kNavigatedUrl = GetURL("google·com.com");
const GURL kExpectedSuggestedUrl = GetURLWithoutPath("google.com");
base::HistogramTester histograms;
TestMetricsRecordedAndInterstitialShown(
browser(), histograms, kNavigatedUrl, kExpectedSuggestedUrl,
NavigationSuggestionEvent::kMatchTargetEmbedding);
CheckInterstitialUkm({kNavigatedUrl}, "MatchType",
LookalikeUrlMatchType::kTargetEmbedding);
test_helper()->CheckSafetyTipUkmCount(0);
}
// The navigated domain itself is a top domain or a subdomain of a top domain.
// Should not record metrics. The top domain list doesn't contain any IDN, so
// this only tests the case where the subdomains are IDNs.
IN_PROC_BROWSER_TEST_F(LookalikeUrlNavigationThrottleBrowserTest,
TopDomainIdnSubdomain_NoMatch) {
TestInterstitialNotShown(browser(), GetURL("tést.google.com"));
test_helper()->CheckNoLookalikeUkm();
// blogspot.com is a private registry, so the eTLD+1 of "tést.blogspot.com" is
// itself, instead of just "blogspot.com". This is different than
// tést.google.com whose eTLD+1 is google.com, and it should be handled
// correctly.
TestInterstitialNotShown(browser(), GetURL("tést.blogspot.com"));
test_helper()->CheckNoLookalikeUkm();
}
// Schemes other than HTTP and HTTPS should be ignored.
IN_PROC_BROWSER_TEST_F(LookalikeUrlNavigationThrottleBrowserTest,
TopDomainChromeUrl_NoMatch) {
TestInterstitialNotShown(browser(), GURL("chrome://googlé.com"));
test_helper()->CheckNoLookalikeUkm();
}
// Navigate to a domain within an edit distance of 1 to an engaged domain.
// This should record metrics, but should not show a lookalike warning
// interstitial yet.
IN_PROC_BROWSER_TEST_F(LookalikeUrlNavigationThrottleBrowserTest,
EditDistance_EngagedDomain_Match) {
base::HistogramTester histograms;
SetEngagementScore(browser(), GURL("https://test-site.com"), kHighEngagement);
// The skeleton of this domain is one 1 edit away from the skeleton of
// test-site.com.
const GURL kNavigatedUrl = GetURL("best-sité.com");
// Even if the navigated site has a low engagement score, it should be
// considered for lookalike suggestions.
SetEngagementScore(browser(), kNavigatedUrl, kLowEngagement);
// Advance clock to force a fetch of new engaged sites list.
test_clock()->Advance(base::Hours(1));
TestInterstitialNotShown(browser(), kNavigatedUrl);
histograms.ExpectTotalCount(kInterstitialHistogramName, 1);
histograms.ExpectBucketCount(
kInterstitialHistogramName,
NavigationSuggestionEvent::kMatchEditDistanceSiteEngagement, 1);
// Navigate away so that safety tip metrics are recorded.
ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), GURL("about:blank")));
test_helper()->CheckInterstitialUkmCount(0);
test_helper()->CheckSafetyTipUkmCount(1);
}
// Navigate to a domain within a character swap of 1 to a top domain.
// This should not record interstitial metrics as it'll display a safety tip.
IN_PROC_BROWSER_TEST_F(LookalikeUrlNavigationThrottleBrowserTest,
CharacterSwap_TopDomain_Match_ShouldNotRecordMetrics) {
base::HistogramTester histograms;
const GURL kNavigatedUrl = GetURL("goolge.com");
// Even if the navigated site has a low engagement score, it should be
// considered for lookalike suggestions.
SetEngagementScore(browser(), kNavigatedUrl, kLowEngagement);
TestInterstitialNotShown(browser(), kNavigatedUrl);
histograms.ExpectTotalCount(kInterstitialHistogramName, 1);
histograms.ExpectBucketCount(
kInterstitialHistogramName,
NavigationSuggestionEvent::kMatchCharacterSwapTop500, 1);
// Navigate away so that safety tip metrics are recorded.
ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), GURL("about:blank")));
test_helper()->CheckInterstitialUkmCount(0);
test_helper()->CheckSafetyTipUkmCount(1);
}
// Tests that a hostname on a safe TLD can spoof another hostname without a
// lookalike warning.
IN_PROC_BROWSER_TEST_F(LookalikeUrlNavigationThrottleBrowserTest,
Idn_SafeTLD_CanSpoof) {
base::HistogramTester histograms;
SetEngagementScore(browser(), GURL("https://digital.gov"), kHighEngagement);
const GURL kNavigatedUrl = GetURL("digitál.gov");
// Even if the navigated site has a low engagement score, it should be
// considered for lookalike suggestions.
SetEngagementScore(browser(), kNavigatedUrl, kLowEngagement);
// Advance clock to force a fetch of new engaged sites list.
test_clock()->Advance(base::Hours(1));
TestInterstitialNotShown(browser(), kNavigatedUrl);
histograms.ExpectTotalCount(kInterstitialHistogramName, 0);
test_helper()->CheckNoLookalikeUkm();
}
// Navigate to a domain within an edit distance of 1 to a top domain.
// This should record metrics, but should not show a lookalike warning
// interstitial yet.
IN_PROC_BROWSER_TEST_F(LookalikeUrlNavigationThrottleBrowserTest,
EditDistance_TopDomain_Match) {
base::HistogramTester histograms;
// The skeleton of this domain, gooogle.corn, is one 1 edit away from
// google.corn, the skeleton of google.com.
const GURL kNavigatedUrl = GetURL("goooglé.com");
// Even if the navigated site has a low engagement score, it should be
// considered for lookalike suggestions.
SetEngagementScore(browser(), kNavigatedUrl, kLowEngagement);
TestInterstitialNotShown(browser(), kNavigatedUrl);
histograms.ExpectTotalCount(kInterstitialHistogramName, 1);
histograms.ExpectBucketCount(kInterstitialHistogramName,
NavigationSuggestionEvent::kMatchEditDistance,
1);
CheckInterstitialUkm({kNavigatedUrl}, "MatchType",
LookalikeUrlMatchType::kEditDistance);
test_helper()->CheckSafetyTipUkmCount(0);
}
// Navigate to a domain within an edit distance of 1 to a top domain, but that
// matches the allowlist. This should neither record metrics nor show an
// interstitial.
IN_PROC_BROWSER_TEST_F(LookalikeUrlNavigationThrottleBrowserTest,
EditDistance_TopDomain_Target_Allowlist) {
base::HistogramTester histograms;
lookalikes::SetSafetyTipAllowlistPatterns({}, {"google\\.com"}, {});
// The skeleton of this domain, gooogle.corn, is one 1 edit away from
// google.corn, the skeleton of google.com.
const GURL kNavigatedUrl = GetURL("goooglé.com");
// Even if the navigated site has a low engagement score, it should be
// considered for lookalike suggestions.
SetEngagementScore(browser(), kNavigatedUrl, kLowEngagement);
TestInterstitialNotShown(browser(), kNavigatedUrl);
histograms.ExpectTotalCount(kInterstitialHistogramName, 0);
test_helper()->CheckNoLookalikeUkm();
}
// Navigate to a domain within an edit distance of 1 to an engaged domain, but
// that matches the allowlist. This should neither record metrics nor show an
// interstitial.
IN_PROC_BROWSER_TEST_F(LookalikeUrlNavigationThrottleBrowserTest,
EditDistance_EngagedDomain_Target_Allowlist) {
base::HistogramTester histograms;
SetEngagementScore(browser(), GURL("https://test-site.com"), kHighEngagement);
lookalikes::SetSafetyTipAllowlistPatterns({}, {"test-site\\.com"}, {});
// The skeleton of this domain is one 1 edit away from the skeleton of
// test-site.com.
const GURL kNavigatedUrl = GetURL("best-sité.com");
// Even if the navigated site has a low engagement score, it should be
// considered for lookalike suggestions.
SetEngagementScore(browser(), kNavigatedUrl, kLowEngagement);
// Advance clock to force a fetch of new engaged sites list.
test_clock()->Advance(base::Hours(1));
TestInterstitialNotShown(browser(), kNavigatedUrl);
histograms.ExpectTotalCount(kInterstitialHistogramName, 0);
test_helper()->CheckNoLookalikeUkm();
}
// Tests negative examples for the edit distance.
IN_PROC_BROWSER_TEST_F(LookalikeUrlNavigationThrottleBrowserTest,
EditDistance_TopDomain_NoMatch) {
// Matches google.com.tr but only differs in registry.
ASSERT_TRUE(IsTopDomain(GetDomainInfo("google.com.tr")));
TestInterstitialNotShown(browser(), GetURL("google.com.tw"));
// Matches academia.edu but is a top domain itself.
ASSERT_TRUE(IsTopDomain(GetDomainInfo("academia.edu")));
ASSERT_TRUE(IsTopDomain(GetDomainInfo("academic.ru")));
TestInterstitialNotShown(browser(), GetURL("academic.ru"));
// Matches ask.com but is too short.
ASSERT_TRUE(IsTopDomain(GetDomainInfo("ask.com")));
TestInterstitialNotShown(browser(), GetURL("bsk.com"));
test_helper()->CheckNoLookalikeUkm();
}
// Tests negative examples for the edit distance with engaged sites.
IN_PROC_BROWSER_TEST_F(LookalikeUrlNavigationThrottleBrowserTest,
EditDistance_SiteEngagement_NoMatch) {
SetEngagementScore(browser(), GURL("https://test-site.com.tr"),
kHighEngagement);
SetEngagementScore(browser(), GURL("https://1234.com"), kHighEngagement);
SetEngagementScore(browser(), GURL("https://gooogle.com"), kHighEngagement);
// Advance clock to force a fetch of new engaged sites list.
test_clock()->Advance(base::Hours(1));
// Matches test-site.com.tr but only differs in registry.
TestInterstitialNotShown(browser(), GetURL("test-site.com.tw"));
// Matches gooogle.com but is a top domain itself.
TestInterstitialNotShown(browser(), GetURL("google.com"));
// Matches 1234.com but is too short.
TestInterstitialNotShown(browser(), GetURL("123.com"));
test_helper()->CheckNoLookalikeUkm();
}
// Test that the heuristics are not triggered with net errors.
IN_PROC_BROWSER_TEST_F(LookalikeUrlNavigationThrottleBrowserTest,
NetError_SiteEngagement_Interstitial) {
// Create a test server that returns invalid responses.
net::EmbeddedTestServer custom_test_server;
custom_test_server.RegisterRequestHandler(
base::BindRepeating(&NetworkErrorResponseHandler));
ASSERT_TRUE(custom_test_server.Start());
SetEngagementScore(browser(), GURL("http://site1.com"), kHighEngagement);
// Advance clock to force a fetch of new engaged sites list.
test_clock()->Advance(base::Hours(1));
TestInterstitialNotShown(
browser(), custom_test_server.GetURL("sité1.com", "/title1.html"));
test_helper()->CheckNoLookalikeUkm();
}
// Same as NetError_SiteEngagement_Interstitial, but triggered by a top domain.
IN_PROC_BROWSER_TEST_F(LookalikeUrlNavigationThrottleBrowserTest,
NetError_TopDomain_Interstitial) {
// Create a test server that returns invalid responses.
net::EmbeddedTestServer custom_test_server;
custom_test_server.RegisterRequestHandler(
base::BindRepeating(&NetworkErrorResponseHandler));
ASSERT_TRUE(custom_test_server.Start());
TestInterstitialNotShown(browser(),
custom_test_server.GetURL("googlé.com", "/"));
test_helper()->CheckNoLookalikeUkm();
}
// TODO(crbug.com/40146482): Enable test when MacOS flake is fixed.
// TODO(crbug.com/40706320): Enable test when Win/Linux flake is fixed.
#if BUILDFLAG(IS_MAC) || BUILDFLAG(IS_WIN) || BUILDFLAG(IS_LINUX)
#define MAYBE_Idn_SiteEngagement_Match DISABLED_Idn_SiteEngagement_Match
#else
#define MAYBE_Idn_SiteEngagement_Match Idn_SiteEngagement_Match
#endif
// Navigate to a domain whose visual representation looks like a domain with a
// site engagement score above a certain threshold. This should record metrics.
// It should also show lookalike warning interstitial.
IN_PROC_BROWSER_TEST_F(LookalikeUrlNavigationThrottleBrowserTest,
MAYBE_Idn_SiteEngagement_Match) {
const char* const kEngagedSites[] = {
"http://site1.com", "http://www.site2.com", "http://sité3.com",
"http://www.sité4.com"};
for (const char* const kSite : kEngagedSites) {
SetEngagementScore(browser(), GURL(kSite), kHighEngagement);
}
// The domains here should not be private domains (e.g. site.test), otherwise
// they might test the wrong thing. Also note that site5.com is in the top
// domain list, so it shouldn't be used here.
const struct SiteEngagementTestCase {
const char* const navigated;
const char* const suggested;
} kSiteEngagementTestCases[] = {
{"sité1.com", "site1.com"},
{"mail.www.sité1.com", "site1.com"},
// Same as above two but ending with dots.
{"sité1.com.", "site1.com"},
{"mail.www.sité1.com.", "site1.com"},
// These should match since the comparison uses eTLD+1s.
{"sité2.com", "site2.com"},
{"mail.sité2.com", "site2.com"},
{"síté3.com", "sité3.com"},
{"mail.síté3.com", "sité3.com"},
{"síté4.com", "sité4.com"},
{"mail.síté4.com", "sité4.com"},
};
std::vector<GURL> ukm_urls;
for (const auto& test_case : kSiteEngagementTestCases) {
const GURL kNavigatedUrl = GetURL(test_case.navigated);
const GURL kExpectedSuggestedUrl = GetURLWithoutPath(test_case.suggested);
// Even if the navigated site has a low engagement score, it should be
// considered for lookalike suggestions.
SetEngagementScore(browser(), kNavigatedUrl, kLowEngagement);
// Advance the clock to force LookalikeUrlService to fetch a new engaged
// site list.
test_clock()->Advance(base::Hours(1));
base::HistogramTester histograms;
TestMetricsRecordedAndInterstitialShown(
browser(), histograms, kNavigatedUrl, kExpectedSuggestedUrl,
NavigationSuggestionEvent::kMatchSiteEngagement);
ukm_urls.push_back(kNavigatedUrl);
CheckInterstitialUkm(ukm_urls, "MatchType",
LookalikeUrlMatchType::kSkeletonMatchSiteEngagement);
}
test_helper()->CheckSafetyTipUkmCount(0);
}
// The site redirects to the matched site, this should not show
// an interstitial.
IN_PROC_BROWSER_TEST_F(LookalikeUrlNavigationThrottleBrowserTest,
Idn_SiteEngagement_SafeRedirect) {
const GURL kExpectedSuggestedUrl = GetURLWithoutPath("site1.com");
const GURL kNavigatedUrl = https_server()->GetURL(
"sité1.com", "/server-redirect?" + kExpectedSuggestedUrl.spec());
SetEngagementScore(browser(), kNavigatedUrl, kLowEngagement);
SetEngagementScore(browser(), kExpectedSuggestedUrl, kHighEngagement);
TestInterstitialNotShown(browser(), kNavigatedUrl);
test_helper()->CheckNoLookalikeUkm();
}
// The site redirects to the matched site, but the redirect chain has more than
// two redirects.
IN_PROC_BROWSER_TEST_F(LookalikeUrlNavigationThrottleBrowserTest,
Idn_SiteEngagement_MidRedirectSpoofsIgnored) {
const GURL kFinalUrl = GetURLWithoutPath("site1.com");
const GURL kMidUrl = https_server()->GetURL(
"sité1.com", "/server-redirect?" + kFinalUrl.spec());
const GURL kNavigatedUrl = https_server()->GetURL(
"other-site.test", "/server-redirect?" + kMidUrl.spec());
SetEngagementScore(browser(), kNavigatedUrl, kLowEngagement);
SetEngagementScore(browser(), kFinalUrl, kHighEngagement);
TestInterstitialNotShown(browser(), kNavigatedUrl);
test_helper()->CheckNoLookalikeUkm();
}
// The site is allowed by the component updater.
IN_PROC_BROWSER_TEST_F(LookalikeUrlNavigationThrottleBrowserTest,
AllowedByComponentUpdater) {
lookalikes::SetSafetyTipAllowlistPatterns(
{"xn--googl-fsa.com/", // googlé.com in punycode
"site.test/", "another-site.test/"},
{}, {});
TestInterstitialNotShown(browser(), GetURL("googlé.com"));
// Try a non-HTTP URL. Shouldn't crash.
TestInterstitialNotShown(browser(), GURL("data:text/html, test"));
test_helper()->CheckNoLookalikeUkm();
}
// The site is allowed by enterprise policy.
IN_PROC_BROWSER_TEST_F(LookalikeUrlNavigationThrottleBrowserTest,
AllowedByPolicy) {
const GURL kNavigatedUrl = GetURL("xn--googl-fsa.com");
lookalikes::SetEnterpriseAllowlistForTesting(browser()->profile()->GetPrefs(),
{"xn--googl-fsa.com"});
SetEngagementScore(browser(), kNavigatedUrl, kLowEngagement);
TestInterstitialNotShown(browser(), kNavigatedUrl);
test_helper()->CheckNoLookalikeUkm();
}
// Tests negative examples for all heuristics.
IN_PROC_BROWSER_TEST_F(LookalikeUrlNavigationThrottleBrowserTest,
NonUniqueDomains_NoMatch) {
// Unknown registry.
TestInterstitialNotShown(browser(), GetURL("google.cóm"));
test_helper()->CheckNoLookalikeUkm();
// Engaged site is localhost, navigated site has unknown registry. This
// is intended to test that nonunique domains in the engaged site list is
// filtered out. However, it doesn't quite test that: We'll bail out early
// because the navigated site has unknown registry (and not because there is
// no engaged nonunique site).
SetEngagementScore(browser(), GURL("http://localhost6.localhost"),
kHighEngagement);
test_clock()->Advance(base::Hours(1));
// The skeleton of this URL is localhost6.localpost which is at one edit
// distance from localhost6.localhost. We use localpost here to prevent an
// early return in LookalikeUrlNavigationThrottle::HandleThrottleRequest().
TestInterstitialNotShown(browser(), GURL("http://localhóst6.localpost"));
test_helper()->CheckNoLookalikeUkm();
}
// Navigate to a domain whose visual representation looks both like a domain
// with a site engagement score and also a top domain. This should record
// metrics for a site engagement match because of the order of checks. It should
// also show lookalike warning interstitial.
IN_PROC_BROWSER_TEST_F(LookalikeUrlNavigationThrottleBrowserTest,
Idn_SiteEngagementAndTopDomain_Match) {
const GURL kNavigatedUrl = GetURL("googlé.com");
const GURL kExpectedSuggestedUrl = GetURLWithoutPath("google.com");
SetEngagementScore(browser(), kNavigatedUrl, kLowEngagement);
SetEngagementScore(browser(), kExpectedSuggestedUrl, kHighEngagement);
// Advance the clock to force LookalikeUrlService to fetch a new engaged
// site list.
test_clock()->Advance(base::Hours(1));
base::HistogramTester histograms;
TestMetricsRecordedAndInterstitialShown(
browser(), histograms, kNavigatedUrl, kExpectedSuggestedUrl,
NavigationSuggestionEvent::kMatchSiteEngagement);
CheckInterstitialUkm({kNavigatedUrl}, "MatchType",
LookalikeUrlMatchType::kSkeletonMatchSiteEngagement);
test_helper()->CheckSafetyTipUkmCount(0);
}
// Similar to Idn_SiteEngagement_Match, but tests a single domain. Also checks
// that the list of engaged sites in incognito and the main profile don't affect
// each other.
IN_PROC_BROWSER_TEST_F(LookalikeUrlNavigationThrottleBrowserTest,
Idn_SiteEngagement_Match_Incognito) {
const GURL kNavigatedUrl = GetURL("sité1.com");
const GURL kEngagedUrl = GetURLWithoutPath("site1.com");
// Set high engagement scores in the main profile and low engagement scores
// in incognito. Main profile should record metrics, incognito shouldn't.
Browser* incognito = CreateIncognitoBrowser();
LookalikeUrlServiceFactory::GetForProfile(incognito->profile())
->SetClockForTesting(test_clock());
SetEngagementScore(browser(), kEngagedUrl, kHighEngagement);
SetEngagementScore(incognito, kEngagedUrl, kLowEngagement);
std::vector<GURL> ukm_urls;
// Main profile should record metrics because there are engaged sites.
{
// Advance the clock to force LookalikeUrlService to fetch a new engaged
// site list.
test_clock()->Advance(base::Hours(1));
base::HistogramTester histograms;
TestMetricsRecordedAndInterstitialShown(
browser(), histograms, kNavigatedUrl, kEngagedUrl,
NavigationSuggestionEvent::kMatchSiteEngagement);
ukm_urls.push_back(kNavigatedUrl);
CheckInterstitialUkm(ukm_urls, "MatchType",
LookalikeUrlMatchType::kSkeletonMatchSiteEngagement);
}
// Incognito shouldn't record metrics because there are no engaged sites.
{
base::HistogramTester histograms;
test_clock()->Advance(base::Hours(1));
TestInterstitialNotShown(incognito, kNavigatedUrl);
histograms.ExpectTotalCount(kIncognitoInterstitialHistogramName, 0);
}
// Now reverse the scores: Set low engagement in the main profile and high
// engagement in incognito.
SetEngagementScore(browser(), kEngagedUrl, kLowEngagement);
SetEngagementScore(incognito, kEngagedUrl, kHighEngagement);
// Incognito should start recording metrics and main profile should stop.
{
test_clock()->Advance(base::Hours(1));
base::HistogramTester histograms;
TestMetricsRecordedAndInterstitialShown(
incognito, histograms, kNavigatedUrl, kEngagedUrl,
NavigationSuggestionEvent::kMatchSiteEngagement);
ukm_urls.push_back(kNavigatedUrl);
CheckInterstitialUkm(ukm_urls, "MatchType",
LookalikeUrlMatchType::kSkeletonMatchSiteEngagement);
}
// Main profile shouldn't record metrics because there are no engaged sites.
{
base::HistogramTester histograms;
test_clock()->Advance(base::Hours(1));
TestInterstitialNotShown(browser(), kNavigatedUrl);
histograms.ExpectTotalCount(kInterstitialHistogramName, 0);
}
test_helper()->CheckSafetyTipUkmCount(0);
}
// Test that navigations to a site with a high engagement score shouldn't
// record metrics or show interstitial.
IN_PROC_BROWSER_TEST_F(LookalikeUrlNavigationThrottleBrowserTest,
Idn_SiteEngagement_Match_IgnoreHighlyEngagedSite) {
base::HistogramTester histograms;
SetEngagementScore(browser(), GURL("http://site-not-in-top-domain-list.com"),
kHighEngagement);
const GURL high_engagement_url = GetURL("síte-not-ín-top-domaín-líst.com");
SetEngagementScore(browser(), high_engagement_url, kHighEngagement);
TestInterstitialNotShown(browser(), high_engagement_url);
histograms.ExpectTotalCount(kInterstitialHistogramName, 0);
test_helper()->CheckNoLookalikeUkm();
}
// Test that an engaged site with a scheme other than HTTP or HTTPS should be
// ignored.
IN_PROC_BROWSER_TEST_F(LookalikeUrlNavigationThrottleBrowserTest,
Idn_SiteEngagement_IgnoreChromeUrl) {
base::HistogramTester histograms;
SetEngagementScore(browser(),
GURL("chrome://site-not-in-top-domain-list.com"),
kHighEngagement);
const GURL low_engagement_url("https://síte-not-ín-top-domaín-líst.com");
SetEngagementScore(browser(), low_engagement_url, kLowEngagement);
TestInterstitialNotShown(browser(), low_engagement_url);
histograms.ExpectTotalCount(kInterstitialHistogramName, 0);
test_helper()->CheckNoLookalikeUkm();
}
// IDNs with a single label should be properly handled. There are two cases
// where this might occur:
// 1. The navigated URL is an IDN with a single label.
// 2. One of the engaged sites is an IDN with a single label.
// Neither of these should cause a crash.
IN_PROC_BROWSER_TEST_F(LookalikeUrlNavigationThrottleBrowserTest,
IdnWithSingleLabelShouldNotCauseACrash) {
base::HistogramTester histograms;
// Case 1: Navigating to an IDN with a single label shouldn't cause a crash.
TestInterstitialNotShown(browser(), GetURL("é"));
// Case 2: An IDN with a single label with a site engagement score shouldn't
// cause a crash.
SetEngagementScore(browser(), GURL("http://tést"), kHighEngagement);
TestInterstitialNotShown(browser(), GetURL("tést.com"));
histograms.ExpectTotalCount(kInterstitialHistogramName, 0);
test_helper()->CheckNoLookalikeUkm();
}
// Ensure that dismissing the interstitial works, and the result is remembered
// in the current tab. This should record metrics on the first visit, but not
// the second.
IN_PROC_BROWSER_TEST_F(LookalikeUrlNavigationThrottleBrowserTest,
Interstitial_Dismiss) {
base::HistogramTester histograms;
const GURL kNavigatedUrl = GetURL("sité1.com");
const GURL kEngagedUrl = GetURL("site1.com");
SetEngagementScore(browser(), kNavigatedUrl, kLowEngagement);
SetEngagementScore(browser(), kEngagedUrl, kHighEngagement);
TestHistogramEventsRecordedWhenInterstitialIgnored(
browser(), &histograms, kNavigatedUrl,
NavigationSuggestionEvent::kMatchSiteEngagement);
CheckInterstitialUkm({kNavigatedUrl}, "MatchType",
LookalikeUrlMatchType::kSkeletonMatchSiteEngagement);
test_helper()->CheckSafetyTipUkmCount(0);
}
// Navigate to lookalike domains that redirect to benign domains and ensure that
// we display an interstitial along the way.
IN_PROC_BROWSER_TEST_F(LookalikeUrlNavigationThrottleBrowserTest,
Interstitial_CapturesRedirects) {
{
// Verify it works when the lookalike domain is the first in the chain
const GURL kNavigatedUrl =
GetLongRedirect("googlé.com", "example.net", "example.com");
SetEngagementScore(browser(), kNavigatedUrl, kLowEngagement);
LoadAndCheckInterstitialAt(browser(), kNavigatedUrl);
}
// LoadAndCheckInterstitialAt assumes there's not an interstitial already
// showing (since otherwise it can't be sure that the navigation caused it).
NavigateToURLSync(browser(), GetURL("example.com"));
{
// ...but not when it's in the middle of the chain
const GURL kNavigatedUrl =
GetLongRedirect("example.net", "googlé.com", "example.com");
SetEngagementScore(browser(), kNavigatedUrl, kLowEngagement);
TestInterstitialNotShown(browser(), kNavigatedUrl);
}
NavigateToURLSync(browser(), GetURL("example.com"));
{
// ...but definitely when it's last in the chain.
const GURL kNavigatedUrl =
GetLongRedirect("example.net", "example.com", "googlé.com");
SetEngagementScore(browser(), kNavigatedUrl, kLowEngagement);
LoadAndCheckInterstitialAt(browser(), kNavigatedUrl);
}
test_helper()->CheckSafetyTipUkmCount(0);
}
// Verify that a warning, when ignored, applies to the entire eTLD+1, not just
// the navigated origin.
IN_PROC_BROWSER_TEST_F(LookalikeUrlNavigationThrottleBrowserTest,
AllowlistAppliesToETLDPlusOne) {
{
const GURL kNavigatedUrl = GetURL("sub1.googlé.com");
SetEngagementScore(browser(), kNavigatedUrl, kLowEngagement);
LoadAndCheckInterstitialAt(browser(), kNavigatedUrl);
SendInterstitialCommandSync(browser(),
SecurityInterstitialCommand::CMD_PROCEED);
test_helper()->CheckInterstitialUkmCount(1);
test_helper()->CheckSafetyTipUkmCount(0);
}
// TestInterstitialNotShown assumes there's not an interstitial already
// showing (since otherwise it can't be sure that the navigation caused it).
NavigateToURLSync(browser(), GetURL("example.com"));
{
const GURL kNavigatedUrl = GetURL("sub2.googlé.com");
SetEngagementScore(browser(), kNavigatedUrl, kLowEngagement);
TestInterstitialNotShown(browser(), kNavigatedUrl);
test_helper()->CheckInterstitialUkmCount(1);
test_helper()->CheckSafetyTipUkmCount(0);
}
// We respect private registries for this manual allowlisting so that
// different (independent) subdomains each show their own warning.
NavigateToURLSync(browser(), GetURL("example.com"));
{
// We must use a private registry that isn't a top domain, since top domains
// don't show warnings.
const GURL kNavigatedUrl = GetURL("google-com.bluebite.io");
SetEngagementScore(browser(), kNavigatedUrl, kLowEngagement);
LoadAndCheckInterstitialAt(browser(), kNavigatedUrl);
SendInterstitialCommandSync(browser(),
SecurityInterstitialCommand::CMD_PROCEED);
test_helper()->CheckInterstitialUkmCount(2);
test_helper()->CheckSafetyTipUkmCount(0);
}
NavigateToURLSync(browser(), GetURL("example.com"));
{
const GURL kNavigatedUrl = GetURL("google-com-unrelated.bluebite.io");
SetEngagementScore(browser(), kNavigatedUrl, kLowEngagement);
LoadAndCheckInterstitialAt(browser(), kNavigatedUrl);
SendInterstitialCommandSync(browser(),
SecurityInterstitialCommand::CMD_PROCEED);
test_helper()->CheckInterstitialUkmCount(3);
test_helper()->CheckSafetyTipUkmCount(0);
}
}
// Verify that the user action in UKM is recorded even when we navigate away
// from the interstitial without interacting with it.
IN_PROC_BROWSER_TEST_F(LookalikeUrlNavigationThrottleBrowserTest,
UkmRecordedAfterNavigateAway) {
const GURL navigated_url = GetURL("googlé.com");
const GURL subsequent_url = GetURL("example.com");
LoadAndCheckInterstitialAt(browser(), navigated_url);
NavigateToURLSync(browser(), subsequent_url);
CheckInterstitialUkm({navigated_url}, "UserAction",
LookalikeUrlBlockingPageUserAction::kCloseOrBack);
test_helper()->CheckSafetyTipUkmCount(0);
}
// Verify that the user action in UKM is recorded properly when the user accepts
// the navigation suggestion.
IN_PROC_BROWSER_TEST_F(LookalikeUrlNavigationThrottleBrowserTest,
UkmRecordedAfterSuggestionAccepted) {
const GURL navigated_url = GetURL("googlé.com");
LoadAndCheckInterstitialAt(browser(), navigated_url);
SendInterstitialCommandSync(browser(),
SecurityInterstitialCommand::CMD_DONT_PROCEED);
CheckInterstitialUkm({navigated_url}, "UserAction",
LookalikeUrlBlockingPageUserAction::kAcceptSuggestion);
test_helper()->CheckSafetyTipUkmCount(0);
}
// Verify that the user action in UKM is recorded properly when the user ignores
// the navigation suggestion.
IN_PROC_BROWSER_TEST_F(LookalikeUrlNavigationThrottleBrowserTest,
UkmRecordedAfterSuggestionIgnored) {
const GURL navigated_url = GetURL("googlé.com");
LoadAndCheckInterstitialAt(browser(), navigated_url);
SendInterstitialCommandSync(browser(),
SecurityInterstitialCommand::CMD_PROCEED);
CheckInterstitialUkm({navigated_url}, "UserAction",
LookalikeUrlBlockingPageUserAction::kClickThrough);
test_helper()->CheckSafetyTipUkmCount(0);
}
// Verify that the URL shows normally on pages after a lookalike interstitial.
IN_PROC_BROWSER_TEST_F(LookalikeUrlNavigationThrottleBrowserTest,
UrlShownAfterInterstitial) {
LoadAndCheckInterstitialAt(browser(), GetURL("googlé.com"));
// URL should be showing again when we navigate to a normal URL
NavigateToURLSync(browser(), GetURL("example.com"));
EXPECT_TRUE(IsUrlShowing(browser()));
}
// Verify that bypassing warnings in the main profile does not affect incognito.
IN_PROC_BROWSER_TEST_F(LookalikeUrlNavigationThrottleBrowserTest,
MainProfileDoesNotAffectIncognito) {
const GURL kNavigatedUrl = GetURL("googlé.com");
// Set low engagement scores in the main profile and in incognito.
Browser* incognito = CreateIncognitoBrowser();
SetEngagementScore(browser(), kNavigatedUrl, kLowEngagement);
SetEngagementScore(incognito, kNavigatedUrl, kLowEngagement);
LoadAndCheckInterstitialAt(browser(), kNavigatedUrl);
// PROCEEDing will disable the interstitial on subsequent navigations
SendInterstitialCommandSync(browser(),
SecurityInterstitialCommand::CMD_PROCEED);
LoadAndCheckInterstitialAt(incognito, kNavigatedUrl);
}
// Verify that bypassing warnings in incognito does not affect the main profile.
IN_PROC_BROWSER_TEST_F(LookalikeUrlNavigationThrottleBrowserTest,
IncognitoDoesNotAffectMainProfile) {
const GURL kNavigatedUrl = GetURL("sité1.com");
const GURL kEngagedUrl = GetURL("site1.com");
// Set engagement scores in the main profile and in incognito.
Browser* incognito = CreateIncognitoBrowser();
SetEngagementScore(browser(), kNavigatedUrl, kLowEngagement);
SetEngagementScore(incognito, kNavigatedUrl, kLowEngagement);
SetEngagementScore(browser(), kEngagedUrl, kHighEngagement);
SetEngagementScore(incognito, kEngagedUrl, kHighEngagement);
LoadAndCheckInterstitialAt(incognito, kNavigatedUrl);
// PROCEEDing will disable the interstitial on subsequent navigations
SendInterstitialCommandSync(incognito,
SecurityInterstitialCommand::CMD_PROCEED);
LoadAndCheckInterstitialAt(browser(), kNavigatedUrl);
}
// Verify reloading the page does not result in dismissing an interstitial.
// Regression test for crbug/941886.
IN_PROC_BROWSER_TEST_F(LookalikeUrlNavigationThrottleBrowserTest,
RefreshDoesntDismiss) {
// Verify it works when the lookalike domain is the first in the chain.
const GURL kNavigatedUrl =
GetLongRedirect("googlé.com", "example.net", "example.com");
SetEngagementScore(browser(), kNavigatedUrl, kLowEngagement);
LoadAndCheckInterstitialAt(browser(), kNavigatedUrl);
content::WebContents* web_contents =
browser()->tab_strip_model()->GetActiveWebContents();
// Reload the interstitial twice. Should still work.
for (size_t i = 0; i < 2; i++) {
content::TestNavigationObserver navigation_observer(web_contents);
chrome::Reload(browser(), WindowOpenDisposition::CURRENT_TAB);
navigation_observer.Wait();
EXPECT_EQ(LookalikeUrlBlockingPage::kTypeForTesting,
GetInterstitialType(web_contents));
EXPECT_FALSE(IsUrlShowing(browser()));
}
// Go to the affected site directly. This should not result in an
// interstitial.
TestInterstitialNotShown(browser(),
https_server()->GetURL("example.net", "/"));
}
// Navigate to a URL that triggers combo squatting heuristic via the
// hard coded brand name list. This should record metrics but shouldn't show
// an interstitial.
IN_PROC_BROWSER_TEST_F(LookalikeUrlNavigationThrottleBrowserTest,
ComboSquatting_ShouldRecordMetricsWithoutUI) {
base::HistogramTester histograms;
const GURL kNavigatedUrl = GetURL("google-login.com");
SetEngagementScore(browser(), kNavigatedUrl, kLowEngagement);
TestInterstitialNotShown(browser(), kNavigatedUrl);
histograms.ExpectTotalCount(kInterstitialHistogramName, 1);
histograms.ExpectBucketCount(kInterstitialHistogramName,
NavigationSuggestionEvent::kComboSquatting, 1);
CheckInterstitialUkm({kNavigatedUrl}, "MatchType",
LookalikeUrlMatchType::kComboSquatting);
CheckInterstitialUkm({kNavigatedUrl}, "TriggeredByInitialUrl", false);
test_helper()->CheckSafetyTipUkmCount(0);
}
// Navigate to a URL that triggers combo squatting heuristic via a
// brand name from engaged sites. This should record metrics but shouldn't show
// an interstitial.
IN_PROC_BROWSER_TEST_F(
LookalikeUrlNavigationThrottleBrowserTest,
ComboSquatting_EngagedSites_ShouldRecordMetricsWithoutUI) {
base::HistogramTester histograms;
SetEngagementScore(browser(), GURL("https://example.com"), kHighEngagement);
const GURL kNavigatedUrl = GetURL("example-login.com");
SetEngagementScore(browser(), kNavigatedUrl, kLowEngagement);
TestInterstitialNotShown(browser(), kNavigatedUrl);
histograms.ExpectTotalCount(kInterstitialHistogramName, 1);
histograms.ExpectBucketCount(
kInterstitialHistogramName,
NavigationSuggestionEvent::kComboSquattingSiteEngagement, 1);
CheckInterstitialUkm({kNavigatedUrl}, "MatchType",
LookalikeUrlMatchType::kComboSquattingSiteEngagement);
CheckInterstitialUkm({kNavigatedUrl}, "TriggeredByInitialUrl", false);
test_helper()->CheckSafetyTipUkmCount(0);
}
// Combo Squatting shouldn't trigger on allowlisted sites and no
// UKM should be recorded.
IN_PROC_BROWSER_TEST_F(LookalikeUrlNavigationThrottleBrowserTest,
ComboSquatting_ShouldNotTriggeredForAllowlist) {
const GURL kNavigatedUrl = GetURL("google-login.com");
SetEngagementScore(browser(), kNavigatedUrl, kLowEngagement);
lookalikes::SetSafetyTipAllowlistPatterns({"google-login.com/"}, {}, {});
TestInterstitialNotShown(browser(), kNavigatedUrl);
test_helper()->CheckNoLookalikeUkm();
}
scoped_refptr<net::X509Certificate> LoadCertificate() {
constexpr char kCertFileName[] = "prime256v1-sha256-google-com.public.pem";
base::ScopedAllowBlockingForTesting allow_io;
base::FilePath dir_path;
base::PathService::Get(content::DIR_TEST_DATA, &dir_path);
dir_path = dir_path.Append(FILE_PATH_LITERAL("sxg"));
return net::CreateCertificateChainFromFile(
dir_path, kCertFileName, net::X509Certificate::FORMAT_PEM_CERT_SEQUENCE);
}
// Tests for Signed Exchanges.
class LookalikeUrlNavigationThrottleSignedExchangeBrowserTest
: public LookalikeUrlNavigationThrottleBrowserTest {
public:
LookalikeUrlNavigationThrottleSignedExchangeBrowserTest() {
scoped_test_root_ = net::EmbeddedTestServer::RegisterTestCerts();
}
void SetUpCommandLine(base::CommandLine* command_line) override {
// HTTPS server only serves a valid cert for localhost, so this is needed
// to load pages from other hosts without an error.
command_line->AppendSwitch(switches::kIgnoreCertificateErrors);
mock_cert_verifier_.SetUpCommandLine(command_line);
}
void SetUpInProcessBrowserTestFixture() override {
mock_cert_verifier_.SetUpInProcessBrowserTestFixture();
}
void TearDownInProcessBrowserTestFixture() override {
mock_cert_verifier_.TearDownInProcessBrowserTestFixture();
}
void SetUp() override {
sxg_test_helper_.SetUp();
LookalikeUrlNavigationThrottleBrowserTest::SetUp();
}
void SetUpOnMainThread() override {
https_server_.AddDefaultHandlers(
base::FilePath(FILE_PATH_LITERAL("content/test/data")));
https_server_.ServeFilesFromSourceDirectory("content/test/data");
https_server_.RegisterRequestMonitor(base::BindRepeating(
&LookalikeUrlNavigationThrottleSignedExchangeBrowserTest::
MonitorRequest,
base::Unretained(this)));
ASSERT_TRUE(https_server_.Start());
LookalikeUrlNavigationThrottleBrowserTest::SetUpOnMainThread();
}
void TearDownOnMainThread() override {
sxg_test_helper_.TearDownOnMainThread();
}
bool HadSignedExchangeInAcceptHeader(const GURL& url) const {
const auto it = url_accept_header_map_.find(url);
if (it == url_accept_header_map_.end())
return false;
return it->second.find("application/signed-exchange") != std::string::npos;
}
void InstallMockCert() {
sxg_test_helper_.InstallMockCert(mock_cert_verifier_.mock_cert_verifier());
// Make the MockCertVerifier treat the certificate
// "prime256v1-sha256-google-com.public.pem" as valid for
// "google-com.example.org".
scoped_refptr<net::X509Certificate> original_cert = LoadCertificate();
net::CertVerifyResult dummy_result;
dummy_result.verified_cert = original_cert;
dummy_result.cert_status = net::OK;
dummy_result.ocsp_result.response_status = bssl::OCSPVerifyResult::PROVIDED;
dummy_result.ocsp_result.revocation_status =
bssl::OCSPRevocationStatus::GOOD;
mock_cert_verifier_.mock_cert_verifier()->AddResultForCertAndHost(
original_cert, "google-com.example.org", dummy_result, net::OK);
}
void InstallMockCertChainInterceptor() {
sxg_test_helper_.InstallMockCertChainInterceptor();
sxg_test_helper_.InstallUrlInterceptor(
GURL("https://google-com.example.org/cert.msg"),
"content/test/data/sxg/google-com.example.org.public.pem.cbor");
}
protected:
net::EmbeddedTestServer https_server_{net::EmbeddedTestServer::TYPE_HTTPS};
content::SignedExchangeBrowserTestHelper sxg_test_helper_;
content::ContentMockCertVerifier mock_cert_verifier_;
private:
void MonitorRequest(const net::test_server::HttpRequest& request) {
const auto it = request.headers.find("Accept");
if (it == request.headers.end())
return;
url_accept_header_map_[request.base_url.Resolve(request.relative_url)] =
it->second;
}
net::ScopedTestRoot scoped_test_root_;
std::map<GURL, std::string> url_accept_header_map_;
};
// Navigates to a 127.0.0.1 URL that serves a signed exchange for
// google-com.example.org. This navigation should be blocked by the target
// embedding interstitial. We only test target embedding here because we can
// test it with a subdomain of example.org (which is the domain used by SGX test
// code). Testing an ETLD+1 such as googlé.com would require generating a custom
// cert.
IN_PROC_BROWSER_TEST_F(LookalikeUrlNavigationThrottleSignedExchangeBrowserTest,
InnerUrlIsLookalike_ShouldBlock) {
InstallMockCert();
InstallMockCertChainInterceptor();
sxg_test_helper_.InstallUrlInterceptor(
GURL("https://google-com.example.org/test/"),
"content/test/data/sxg/fallback.html");
const GURL kNavigatedUrl =
https_server_.GetURL("/sxg/google-com.example.org_test.sxg");
const GURL kExpectedSuggestedUrl("https://google.com");
base::HistogramTester histograms;
TestMetricsRecordedAndInterstitialShown(
browser(), histograms, kNavigatedUrl, kExpectedSuggestedUrl,
NavigationSuggestionEvent::kMatchTargetEmbedding,
true /* expect_signed_exchange */);
// Check that the SXG file was handled as a Signed Exchange.
ASSERT_TRUE(HadSignedExchangeInAcceptHeader(kNavigatedUrl));
}
// Navigates to a lookalike URL (google-com.test.com) that serves a signed
// exchange for test.example.org. This should not be blocked.
IN_PROC_BROWSER_TEST_F(LookalikeUrlNavigationThrottleSignedExchangeBrowserTest,
OuterUrlIsLookalike_ShouldNotBlock) {
InstallMockCert();
InstallMockCertChainInterceptor();
const GURL kSgxTargetUrl("https://test.example.org/test/");
sxg_test_helper_.InstallUrlInterceptor(kSgxTargetUrl,
"content/test/data/sxg/fallback.html");
const GURL kNavigatedUrl = https_server_.GetURL(
"google-com.test.com", "/sxg/test.example.org_test.sxg");
TestInterstitialNotShown(browser(), kNavigatedUrl);
// Check that the SXG file was handled as a Signed Exchange.
// MonitorRequest() sees kNavigatedUrl with an IP address instead of
// domain name, so check it instead.
const GURL kResolvedNavigatedUrl =
https_server_.GetURL("/sxg/test.example.org_test.sxg");
ASSERT_TRUE(HadSignedExchangeInAcceptHeader(kResolvedNavigatedUrl));
}
// Navigates to a lookalike URL (google-com.test.com) that serves a signed
// exchange for test.example.org. This should not be blocked.
IN_PROC_BROWSER_TEST_F(LookalikeUrlNavigationThrottleSignedExchangeBrowserTest,
OuterUrlIsLookalikeButNotSignedExchange_ShouldNotBlock) {
InstallMockCert();
InstallMockCertChainInterceptor();
const GURL kSgxTargetUrl("https://test.example.org/test/");
sxg_test_helper_.InstallUrlInterceptor(kSgxTargetUrl,
"content/test/data/sxg/fallback.html");
const GURL kSgxCacheUrl = https_server_.GetURL(
"google-com.test.com", "/sxg/test.example.org_test.sxg");
const GURL kNavigatedUrl = https_server()->GetURL(
"apple-com.site.test", "/server-redirect?" + kSgxCacheUrl.spec());
TestInterstitialNotShown(browser(), kNavigatedUrl);
// Check that the SXG file was handled as a Signed Exchange.
// MonitorRequest() sees kNavigatedUrl with an IP address instead of
// domain name, so check it instead.
const GURL kResolvedNavigatedUrl =
https_server_.GetURL("/sxg/test.example.org_test.sxg");
ASSERT_TRUE(HadSignedExchangeInAcceptHeader(kResolvedNavigatedUrl));
}
// Navigates to a lookalike URL (google-com.test.com) that serves a signed
// exchange for google-com.example.org.
// Both the outer URL (i.e. cache) and the inner URL are lookalikes so this
// should be blocked.
IN_PROC_BROWSER_TEST_F(LookalikeUrlNavigationThrottleSignedExchangeBrowserTest,
InnerAndOuterUrlsAreLookalikes_ShouldBlock) {
InstallMockCert();
InstallMockCertChainInterceptor();
sxg_test_helper_.InstallUrlInterceptor(
GURL("https://google-com.example.org/test/"),
"content/test/data/sxg/fallback.html");
const GURL kNavigatedUrl = https_server_.GetURL(
"google-com.test.com", "/sxg/google-com.example.org_test.sxg");
const GURL kExpectedSuggestedUrl("https://google.com");
base::HistogramTester histograms;
TestMetricsRecordedAndInterstitialShown(
browser(), histograms, kNavigatedUrl, kExpectedSuggestedUrl,
NavigationSuggestionEvent::kMatchTargetEmbedding,
true /* expect_signed_exchange */);
// Check that the SXG file was handled as a Signed Exchange.
// MonitorRequest() sees kNavigatedUrl with an IP address instead of
// domain name, so check it instead.
const GURL kResolvedNavigatedUrl =
https_server_.GetURL("/sxg/google-com.example.org_test.sxg");
ASSERT_TRUE(HadSignedExchangeInAcceptHeader(kResolvedNavigatedUrl));
}
// TODO(meacer): Add a test for a failed SGX response. It should be treated
// as a normal redirect. In fact, InnerAndOuterUrlsLookalikes_ShouldBlock
// is actually testing this right now, fix it.
class LookalikeUrlNavigationThrottlePrerenderBrowserTest
: public LookalikeUrlNavigationThrottleBrowserTest {
public:
LookalikeUrlNavigationThrottlePrerenderBrowserTest() = default;
~LookalikeUrlNavigationThrottlePrerenderBrowserTest() override = default;
void SetUpCommandLine(base::CommandLine* command_line) override {
LookalikeUrlNavigationThrottleBrowserTest::SetUpCommandLine(command_line);
prerender_helper_ = std::make_unique<content::test::PrerenderTestHelper>(
base::BindRepeating(
&LookalikeUrlNavigationThrottlePrerenderBrowserTest::web_contents,
base::Unretained(this)));
}
void SetUpOnMainThread() override {
prerender_helper_->RegisterServerRequestMonitor(https_server());
LookalikeUrlNavigationThrottleBrowserTest::SetUpOnMainThread();
}
content::WebContents* web_contents() {
return browser()->tab_strip_model()->GetActiveWebContents();
}
protected:
std::unique_ptr<content::test::PrerenderTestHelper> prerender_helper_;
};
IN_PROC_BROWSER_TEST_F(LookalikeUrlNavigationThrottlePrerenderBrowserTest,
ShowInterstitialAfterActivation) {
// TODO(crbug.com/40168192): Cross-origin prerender isn't yet supported, so we
// trigger prerendering a page that needs to show an interstitial like this.
// Once cross-origin prerender is supported, this should be updated to more
// realistic use-case. i.e. navigate to an primary page with a normal URL and
// prerender/activate with a lookalike URL.
const GURL kNavigateUrl = GetURL("googlé.com");
LoadAndCheckInterstitialAt(browser(), kNavigateUrl);
SendInterstitialCommandSync(browser(),
SecurityInterstitialCommand::CMD_PROCEED);
LookalikeUrlServiceFactory::GetForProfile(browser()->profile())
->ResetWarningDismissedETLDPlusOnesForTesting();
// Start a prerender.
const GURL kPrerenderUrl =
https_server()->GetURL("googlé.com", "/title1.html?prerender");
content::test::PrerenderHostObserver host_observer(*web_contents(),
kPrerenderUrl);
prerender_helper_->AddPrerenderAsync(kPrerenderUrl);
// Wait until the prerender destroyed.
host_observer.WaitForDestroyed();
EXPECT_EQ(nullptr, GetCurrentInterstitial(web_contents()));
// Activate the prerendered page.
prerender_helper_->NavigatePrimaryPage(kPrerenderUrl);
EXPECT_EQ(LookalikeUrlBlockingPage::kTypeForTesting,
GetInterstitialType(web_contents()));
EXPECT_FALSE(IsUrlShowing(browser()));
}
|