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
|
// Copyright 2023 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_test_utils.h"
#include <string_view>
#include "base/strings/stringprintf.h"
#include "base/test/bind.h"
#include "components/content_settings/core/common/content_settings.h"
#include "components/content_settings/core/common/content_settings_pattern.h"
#include "components/content_settings/core/common/content_settings_utils.h"
#include "content/browser/btm/btm_service_impl.h"
#include "content/browser/renderer_host/navigation_request.h"
#include "content/public/browser/browsing_data_remover.h"
#include "content/public/browser/btm_service.h"
#include "content/public/browser/web_contents.h"
#include "content/public/common/content_features.h"
#include "content/public/test/browser_test_utils.h"
#include "content/public/test/hit_test_region_observer.h"
#include "content/public/test/test_frame_navigation_observer.h"
#include "content/public/test/test_utils.h"
#include "net/base/schemeful_site.h"
#include "net/cookies/cookie_setting_override.h"
#include "net/cookies/site_for_cookies.h"
#include "net/test/embedded_test_server/embedded_test_server.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "third_party/blink/public/mojom/frame/frame.mojom-shared.h"
namespace content {
void CloseTab(WebContents* web_contents) {
WebContentsDestroyedWatcher destruction_watcher(web_contents);
web_contents->Close();
destruction_watcher.Wait();
}
base::expected<WebContents*, std::string> OpenInNewTab(
WebContents* original_tab,
const GURL& url) {
OpenedWindowObserver tab_observer(original_tab,
WindowOpenDisposition::NEW_FOREGROUND_TAB);
if (!ExecJs(original_tab, JsReplace("window.open($1, '_blank');", url))) {
return base::unexpected("window.open failed");
}
tab_observer.Wait();
// Wait for the new tab to finish navigating.
WaitForLoadStop(tab_observer.window());
return tab_observer.window();
}
[[nodiscard]] testing::AssertionResult AccessStorage(
RenderFrameHost* frame,
blink::mojom::StorageTypeAccessed type) {
// We drop the first character of ToString(type) because it's just the
// constant-indicating 'k'.
return ExecJs(frame,
base::StringPrintf(kStorageAccessScript,
base::ToString(type).substr(1).c_str()),
EXECUTE_SCRIPT_NO_USER_GESTURE,
/*world_id=*/1);
}
void AccessCookieViaJSIn(WebContents* web_contents, RenderFrameHost* frame) {
FrameCookieAccessObserver observer(web_contents, frame,
CookieOperation::kChange);
ASSERT_TRUE(ExecJs(frame, "document.cookie = 'foo=bar';",
EXECUTE_SCRIPT_NO_USER_GESTURE));
observer.Wait();
}
[[nodiscard]] testing::AssertionResult ClientSideRedirectViaMetaTag(
WebContents* web_contents,
RenderFrameHost* frame,
const GURL& target_url,
const std::optional<const GURL>& expected_commit_url) {
TestFrameNavigationObserver nav_observer(frame);
bool js_succeeded = ExecJs(frame,
JsReplace(
R"(
function redirectViaMetaTag() {
var element = document.createElement('meta');
element.setAttribute('http-equiv', 'refresh');
element.setAttribute('content', '0; url=$1');
document.getElementsByTagName('head')[0].appendChild(element);
}
if (document.readyState === "loading") {
document.addEventListener("DOMContentLoaded", redirectViaMetaTag);
} else {
redirectViaMetaTag();
}
)",
target_url),
EXECUTE_SCRIPT_NO_USER_GESTURE);
if (!js_succeeded) {
return testing::AssertionFailure()
<< "Failed to execute script to client-side redirect to URL "
<< target_url;
}
nav_observer.Wait();
if (nav_observer.last_committed_url() ==
expected_commit_url.value_or(target_url)) {
return testing::AssertionSuccess();
} else {
return testing::AssertionFailure()
<< "Expected to arrive at "
<< expected_commit_url.value_or(target_url)
<< " but URL was actually " << nav_observer.last_committed_url();
}
}
[[nodiscard]] testing::AssertionResult ClientSideRedirectViaJS(
WebContents* web_contents,
RenderFrameHost* frame,
const GURL& target_url,
const std::optional<const GURL>& expected_commit_url) {
TestFrameNavigationObserver nav_observer(frame);
bool js_succeeded =
ExecJs(frame, JsReplace(R"(window.location.replace($1);)", target_url),
EXECUTE_SCRIPT_NO_USER_GESTURE);
if (!js_succeeded) {
return testing::AssertionFailure()
<< "Failed to execute script to client-side redirect to URL "
<< target_url;
}
nav_observer.Wait();
if (nav_observer.last_committed_url() ==
expected_commit_url.value_or(target_url)) {
return testing::AssertionSuccess();
} else {
return testing::AssertionFailure()
<< "Expected to arrive at "
<< expected_commit_url.value_or(target_url)
<< " but URL was actually " << nav_observer.last_committed_url();
}
}
std::string StringifyBtmClientRedirectMethod(
BtmClientRedirectMethod client_redirect_method) {
switch (client_redirect_method) {
case BtmClientRedirectMethod::kMetaTag:
return "MetaTag";
case BtmClientRedirectMethod::kJsWindowLocationReplace:
return "JsWindowLocationReplace";
case BtmClientRedirectMethod::kRedirectLikeNavigation:
return "RedirectLikeNavigation";
}
}
[[nodiscard]] testing::AssertionResult PerformClientRedirect(
BtmClientRedirectMethod redirect_method,
WebContents* web_contents,
const GURL& redirect_url,
const std::optional<const GURL>& expected_commit_url) {
const GURL& commit_url = expected_commit_url.value_or(redirect_url);
switch (redirect_method) {
case BtmClientRedirectMethod::kMetaTag:
return ClientSideRedirectViaMetaTag(web_contents,
web_contents->GetPrimaryMainFrame(),
redirect_url, commit_url);
case BtmClientRedirectMethod::kJsWindowLocationReplace:
return ClientSideRedirectViaJS(web_contents,
web_contents->GetPrimaryMainFrame(),
redirect_url, commit_url);
case BtmClientRedirectMethod::kRedirectLikeNavigation:
return testing::AssertionResult(
NavigateToURLFromRendererWithoutUserGesture(
web_contents, redirect_url, commit_url));
}
}
bool NavigateToSetCookie(WebContents* web_contents,
const net::EmbeddedTestServer* server,
std::string_view host,
bool is_secure_cookie_set,
bool is_ad_tagged) {
std::string relative_url = "/set-cookie?name=value";
if (is_secure_cookie_set) {
relative_url += ";Secure;SameSite=None";
}
if (is_ad_tagged) {
relative_url += "&isad=1";
}
const auto url = server->GetURL(host, relative_url);
URLCookieAccessObserver observer(web_contents, url, CookieOperation::kChange);
bool success = NavigateToURL(web_contents, url);
if (success) {
observer.Wait();
}
return success;
}
void CreateImageAndWaitForCookieAccess(WebContents* web_contents,
const GURL& image_url) {
URLCookieAccessObserver observer(web_contents, image_url,
CookieOperation::kRead);
ASSERT_TRUE(ExecJs(web_contents,
JsReplace(
R"(
let img = document.createElement('img');
img.src = $1;
document.body.appendChild(img);)",
image_url),
EXECUTE_SCRIPT_NO_USER_GESTURE));
// The image must cause a cookie access, or else this will hang.
observer.Wait();
}
std::optional<StateValue> GetBtmState(BtmServiceImpl* btm_service,
const GURL& url) {
std::optional<StateValue> state;
auto* storage = btm_service->storage();
DCHECK(storage);
storage->AsyncCall(&BtmStorage::Read)
.WithArgs(url)
.Then(base::BindLambdaForTesting([&](const BtmState& loaded_state) {
if (loaded_state.was_loaded()) {
state = loaded_state.ToStateValue();
}
}));
WaitOnStorage(btm_service);
return state;
}
URLCookieAccessObserver::URLCookieAccessObserver(WebContents* web_contents,
const GURL& url,
CookieOperation access_type)
: WebContentsObserver(web_contents), url_(url), access_type_(access_type) {}
void URLCookieAccessObserver::Wait() {
run_loop_.Run();
}
void URLCookieAccessObserver::OnCookiesAccessed(
RenderFrameHost* render_frame_host,
const CookieAccessDetails& details) {
cookie_accessed_in_primary_page_ = IsInPrimaryPage(*render_frame_host);
if (details.type == access_type_ && details.url == url_) {
run_loop_.Quit();
}
}
void URLCookieAccessObserver::OnCookiesAccessed(
NavigationHandle* navigation_handle,
const CookieAccessDetails& details) {
cookie_accessed_in_primary_page_ = IsInPrimaryPage(*navigation_handle);
if (details.type == access_type_ && details.url == url_) {
run_loop_.Quit();
}
}
bool URLCookieAccessObserver::CookieAccessedInPrimaryPage() const {
return cookie_accessed_in_primary_page_;
}
FrameCookieAccessObserver::FrameCookieAccessObserver(
WebContents* web_contents,
RenderFrameHost* render_frame_host,
CookieOperation access_type)
: WebContentsObserver(web_contents),
render_frame_host_(render_frame_host),
access_type_(access_type) {}
void FrameCookieAccessObserver::Wait() {
run_loop_.Run();
}
void FrameCookieAccessObserver::OnCookiesAccessed(
RenderFrameHost* render_frame_host,
const CookieAccessDetails& details) {
if (details.type == access_type_ && render_frame_host_ == render_frame_host) {
run_loop_.Quit();
}
}
UserActivationObserver::UserActivationObserver(
WebContents* web_contents,
RenderFrameHost* render_frame_host)
: WebContentsObserver(web_contents),
render_frame_host_(render_frame_host) {}
void UserActivationObserver::Wait() {
run_loop_.Run();
}
void UserActivationObserver::FrameReceivedUserActivation(
RenderFrameHost* render_frame_host) {
if (render_frame_host_ == render_frame_host) {
run_loop_.Quit();
}
}
EntryUrlsAre::EntryUrlsAre(std::string entry_name,
std::vector<std::string> urls)
: entry_name_(std::move(entry_name)), expected_urls_(std::move(urls)) {
// Sort the URLs before comparing, so order doesn't matter. (BtmDatabase
// currently sorts its results, but that could change and these tests
// shouldn't care.)
std::sort(expected_urls_.begin(), expected_urls_.end());
}
EntryUrlsAre::EntryUrlsAre(const EntryUrlsAre&) = default;
EntryUrlsAre::EntryUrlsAre(EntryUrlsAre&&) = default;
EntryUrlsAre::~EntryUrlsAre() = default;
bool EntryUrlsAre::MatchAndExplain(
const ukm::TestUkmRecorder& ukm_recorder,
testing::MatchResultListener* result_listener) const {
std::vector<std::string> actual_urls;
for (const ukm::mojom::UkmEntry* entry :
ukm_recorder.GetEntriesByName(entry_name_)) {
GURL url = ukm_recorder.GetSourceForSourceId(entry->source_id)->url();
actual_urls.push_back(url.spec());
}
std::sort(actual_urls.begin(), actual_urls.end());
// ExplainMatchResult() won't print out the full contents of `actual_urls`,
// so for more helpful error messages, we do it ourselves.
*result_listener << "whose entries for '" << entry_name_
<< "' contain the URLs "
<< testing::PrintToString(actual_urls) << ", ";
// Use ContainerEq() instead of e.g. ElementsAreArray() because the error
// messages are much more useful.
return ExplainMatchResult(testing::ContainerEq(expected_urls_), actual_urls,
result_listener);
}
void EntryUrlsAre::DescribeTo(std::ostream* os) const {
*os << "has entries for '" << entry_name_ << "' whose URLs are "
<< testing::PrintToString(expected_urls_);
}
void EntryUrlsAre::DescribeNegationTo(std::ostream* os) const {
*os << "does not have entries for '" << entry_name_ << "' whose URLs are "
<< testing::PrintToString(expected_urls_);
}
ScopedInitFeature::ScopedInitFeature(const base::Feature& feature,
bool enable,
const base::FieldTrialParams& params) {
if (enable) {
feature_list_.InitAndEnableFeatureWithParameters(feature, params);
} else {
feature_list_.InitAndDisableFeature(feature);
}
}
ScopedInitBtmFeature::ScopedInitBtmFeature(bool enable,
const base::FieldTrialParams& params)
: init_feature_(features::kBtm, enable, params) {}
OpenedWindowObserver::OpenedWindowObserver(
WebContents* web_contents,
WindowOpenDisposition open_disposition)
: WebContentsObserver(web_contents), open_disposition_(open_disposition) {}
void OpenedWindowObserver::DidOpenRequestedURL(
WebContents* new_contents,
RenderFrameHost* source_render_frame_host,
const GURL& url,
const Referrer& referrer,
WindowOpenDisposition disposition,
ui::PageTransition transition,
bool started_from_context_menu,
bool renderer_initiated) {
if (!window_ && disposition == open_disposition_) {
window_ = new_contents;
run_loop_.Quit();
}
}
// TODO - crbug.com/40247129: Remove this method in favor of directly using
// SimulateMouseClickAndWait() once mouse clicks / taps reliably trigger user
// activation on Android
void SimulateUserActivation(WebContents* web_contents) {
#if BUILDFLAG(IS_ANDROID)
ASSERT_TRUE(ExecJs(web_contents, ""));
#else
SimulateMouseClickAndWait(web_contents);
#endif
}
void SimulateMouseClickAndWait(WebContents* web_contents) {
WaitForHitTestData(web_contents->GetPrimaryMainFrame());
UserActivationObserver observer(web_contents,
web_contents->GetPrimaryMainFrame());
SimulateMouseClick(web_contents, 0, blink::WebMouseEvent::Button::kLeft);
observer.Wait();
}
UrlAndSourceId MakeUrlAndId(std::string_view url) {
return UrlAndSourceId(GURL(url), ukm::AssignNewSourceId());
}
TpcBlockingBrowserClient::TpcBlockingBrowserClient() = default;
TpcBlockingBrowserClient::~TpcBlockingBrowserClient() = default;
bool TpcBlockingBrowserClient::IsFullCookieAccessAllowed(
BrowserContext* browser_context,
WebContents* web_contents,
const GURL& url,
const blink::StorageKey& storage_key,
net::CookieSettingOverrides overrides) {
return IsFullCookieAccessAllowed(url, storage_key.ToNetSiteForCookies(),
storage_key.origin(), overrides,
storage_key.ToCookiePartitionKey());
}
void TpcBlockingBrowserClient::GrantCookieAccessDueToHeuristic(
BrowserContext* browser_context,
const net::SchemefulSite& top_frame_site,
const net::SchemefulSite& accessing_site,
base::TimeDelta ttl,
bool ignore_schemes) {
ContentSettingsPattern primary_pattern =
ContentSettingsPattern::FromURLToSchemefulSitePattern(
accessing_site.GetURL());
ContentSettingsPattern secondary_pattern =
ContentSettingsPattern::FromURLToSchemefulSitePattern(
top_frame_site.GetURL());
if (ignore_schemes) {
primary_pattern =
ContentSettingsPattern::ToHostOnlyPattern(primary_pattern);
secondary_pattern =
ContentSettingsPattern::ToHostOnlyPattern(secondary_pattern);
}
tpc_content_settings_.SetValue(primary_pattern, secondary_pattern,
base::Value(CONTENT_SETTING_ALLOW),
/*metadata=*/{});
}
bool TpcBlockingBrowserClient::AreThirdPartyCookiesGenerallyAllowed(
BrowserContext* browser_context,
WebContents* web_contents) {
return !block_3pcs_;
}
bool TpcBlockingBrowserClient::ShouldBtmDeleteInteractionRecords(
uint64_t remove_mask) {
return remove_mask & TpcBlockingBrowserClient::DATA_TYPE_HISTORY;
}
void TpcBlockingBrowserClient::AllowThirdPartyCookiesOnSite(const GURL& url) {
tpc_content_settings_.SetValue(
ContentSettingsPattern::Wildcard(),
ContentSettingsPattern::FromURLToSchemefulSitePattern(url),
base::Value(CONTENT_SETTING_ALLOW), /*metadata=*/{});
}
void TpcBlockingBrowserClient::GrantCookieAccessTo3pSite(const GURL& url) {
tpc_content_settings_.SetValue(
ContentSettingsPattern::FromURLToSchemefulSitePattern(url),
ContentSettingsPattern::Wildcard(), base::Value(CONTENT_SETTING_ALLOW),
/*metadata=*/{});
}
void TpcBlockingBrowserClient::BlockThirdPartyCookiesOnSite(const GURL& url) {
tpc_content_settings_.SetValue(
ContentSettingsPattern::Wildcard(),
ContentSettingsPattern::FromURLToSchemefulSitePattern(url),
base::Value(CONTENT_SETTING_BLOCK), /*metadata=*/{});
}
void TpcBlockingBrowserClient::BlockThirdPartyCookies(
const GURL& url,
const GURL& first_party_url) {
tpc_content_settings_.SetValue(
ContentSettingsPattern::FromURLToSchemefulSitePattern(url),
ContentSettingsPattern::FromURLToSchemefulSitePattern(first_party_url),
base::Value(CONTENT_SETTING_BLOCK), /*metadata=*/{});
}
// Overrides for content_settings::CookieSettingsBase
bool TpcBlockingBrowserClient::ShouldIgnoreSameSiteRestrictions(
const GURL& url,
const net::SiteForCookies& site_for_cookies) const {
return false;
}
ContentSetting TpcBlockingBrowserClient::GetContentSetting(
const GURL& primary_url,
const GURL& secondary_url,
ContentSettingsType content_type,
content_settings::SettingInfo* info) const {
if (content_type != ContentSettingsType::COOKIES) {
return CONTENT_SETTING_DEFAULT;
}
const content_settings::RuleEntry* rule_entry =
tpc_content_settings_.Find(primary_url, secondary_url);
if (rule_entry == nullptr) {
if (info) {
info->primary_pattern = ContentSettingsPattern::Wildcard();
info->secondary_pattern = ContentSettingsPattern::Wildcard();
}
// By default we'll allow cookies. Blocking by default will override any 3PC
// exemption settings.
return CONTENT_SETTING_ALLOW;
}
if (info) {
info->primary_pattern = rule_entry->first.primary_pattern;
info->secondary_pattern = rule_entry->first.secondary_pattern;
}
return content_settings::ValueToContentSetting(rule_entry->second.value);
}
bool TpcBlockingBrowserClient::ShouldAlwaysAllowCookies(
const GURL& url,
const GURL& first_party_url) const {
return false;
}
bool TpcBlockingBrowserClient::ShouldBlockThirdPartyCookies(
base::optional_ref<const url::Origin> top_frame_origin,
net::CookieSettingOverrides overrides) const {
return block_3pcs_;
}
bool TpcBlockingBrowserClient::MitigationsEnabledFor3pcd() const {
return false;
}
bool TpcBlockingBrowserClient::IsThirdPartyCookiesAllowedScheme(
const std::string& scheme) const {
return false;
}
PausedCookieAccessObservers::PausedCookieAccessObservers(
NotifyCookiesAccessedCallback callback,
PendingObserversWithContext observers)
: CookieAccessObservers(std::move(callback)),
pending_receivers_(std::move(observers)) {}
PausedCookieAccessObservers::~PausedCookieAccessObservers() = default;
void PausedCookieAccessObservers::Add(
mojo::PendingReceiver<network::mojom::CookieAccessObserver> receiver,
CookieAccessDetails::Source source) {
pending_receivers_.emplace_back(std::move(receiver), source);
}
PausedCookieAccessObservers::PendingObserversWithContext
PausedCookieAccessObservers::TakeReceiversWithContext() {
return std::exchange(pending_receivers_, {});
}
CookieAccessInterceptor::CookieAccessInterceptor(WebContents& web_contents)
: WebContentsObserver(&web_contents) {}
CookieAccessInterceptor::~CookieAccessInterceptor() = default;
void CookieAccessInterceptor::DidStartNavigation(
NavigationHandle* navigation_handle) {
auto& request = *NavigationRequest::From(navigation_handle);
auto observers = std::make_unique<PausedCookieAccessObservers>(
base::BindRepeating(&NavigationRequest::NotifyCookiesAccessed,
// Unretained is safe here because ownership of the
// observers is passed to the request below.
base::Unretained(&request)),
request.TakeCookieObservers());
request.SetCookieAccessObserversForTesting(std::move(observers));
}
} // namespace content
|