code stringlengths 1 1.05M | repo_name stringlengths 6 83 | path stringlengths 3 242 | language stringclasses 222
values | license stringclasses 20
values | size int64 1 1.05M |
|---|---|---|---|---|---|
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef WEBLAYER_BROWSER_NO_STATE_PREFETCH_PRERENDER_CONTROLLER_IMPL_H_
#define WEBLAYER_BROWSER_NO_STATE_PREFETCH_PRERENDER_CONTROLLER_IMPL_H_
#include "base/memory/raw_ptr.h"
#include "build/build_config.h"
#include "weblayer/public/prerender_controller.h"
#if BUILDFLAG(IS_ANDROID)
#include "base/android/scoped_java_ref.h"
#endif
class GURL;
namespace content {
class BrowserContext;
}
namespace weblayer {
// Enables creation of a non-web initiated prerender request.
class PrerenderControllerImpl : public PrerenderController {
public:
explicit PrerenderControllerImpl(content::BrowserContext* browser_context);
~PrerenderControllerImpl() override;
PrerenderControllerImpl(const PrerenderControllerImpl&) = delete;
PrerenderControllerImpl& operator=(const PrerenderControllerImpl&) = delete;
#if BUILDFLAG(IS_ANDROID)
void Prerender(JNIEnv* env, const base::android::JavaParamRef<jstring>& url);
#endif
// PrerenderController
void Prerender(const GURL& url) override;
void DestroyAllContents() override;
private:
raw_ptr<content::BrowserContext> browser_context_;
};
} // namespace weblayer
#endif // WEBLAYER_BROWSER_NO_STATE_PREFETCH_PRERENDER_CONTROLLER_IMPL_H_
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/no_state_prefetch/prerender_controller_impl.h | C++ | unknown | 1,348 |
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "weblayer/browser/no_state_prefetch/prerender_tab_helper.h"
#include "components/no_state_prefetch/browser/no_state_prefetch_manager.h"
#include "content/public/browser/navigation_handle.h"
#include "content/public/browser/web_contents.h"
#include "weblayer/browser/no_state_prefetch/no_state_prefetch_manager_factory.h"
namespace weblayer {
PrerenderTabHelper::PrerenderTabHelper(content::WebContents* web_contents)
: content::WebContentsObserver(web_contents),
content::WebContentsUserData<PrerenderTabHelper>(*web_contents) {}
PrerenderTabHelper::~PrerenderTabHelper() = default;
void PrerenderTabHelper::PrimaryPageChanged(content::Page& page) {
if (page.GetMainDocument().IsErrorDocument())
return;
prerender::NoStatePrefetchManager* no_state_prefetch_manager =
NoStatePrefetchManagerFactory::GetForBrowserContext(
web_contents()->GetBrowserContext());
if (no_state_prefetch_manager &&
!no_state_prefetch_manager->IsWebContentsPrefetching(web_contents()))
no_state_prefetch_manager->RecordNavigation(
page.GetMainDocument().GetLastCommittedURL());
}
WEB_CONTENTS_USER_DATA_KEY_IMPL(PrerenderTabHelper);
} // namespace weblayer
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/no_state_prefetch/prerender_tab_helper.cc | C++ | unknown | 1,349 |
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef WEBLAYER_BROWSER_NO_STATE_PREFETCH_PRERENDER_TAB_HELPER_H_
#define WEBLAYER_BROWSER_NO_STATE_PREFETCH_PRERENDER_TAB_HELPER_H_
#include "content/public/browser/web_contents_observer.h"
#include "content/public/browser/web_contents_user_data.h"
namespace content {
class WebContents;
}
namespace prerender {
class NoStatePrefetchManager;
}
namespace weblayer {
// Notifies the prerender::NoStatePrefetchManager with the events happening in
// the prerendered WebContents.
class PrerenderTabHelper
: public content::WebContentsObserver,
public content::WebContentsUserData<PrerenderTabHelper> {
public:
~PrerenderTabHelper() override;
PrerenderTabHelper(const PrerenderTabHelper&) = delete;
PrerenderTabHelper& operator=(const PrerenderTabHelper&) = delete;
// content::WebContentsObserver implementation.
void PrimaryPageChanged(content::Page& page) override;
private:
explicit PrerenderTabHelper(content::WebContents* web_contents);
friend class content::WebContentsUserData<PrerenderTabHelper>;
WEB_CONTENTS_USER_DATA_KEY_DECL();
};
} // namespace weblayer
#endif // WEBLAYER_BROWSER_NO_STATE_PREFETCH_PRERENDER_TAB_HELPER_H_ | Zhao-PengFei35/chromium_src_4 | weblayer/browser/no_state_prefetch/prerender_tab_helper.h | C++ | unknown | 1,317 |
// Copyright 2022 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <string>
#include "base/containers/flat_set.h"
#include "base/functional/bind.h"
#include "base/strings/strcat.h"
#include "base/test/scoped_feature_list.h"
#include "components/browsing_data/content/browsing_data_helper.h"
#include "components/origin_trials/browser/origin_trials.h"
#include "components/user_prefs/user_prefs.h"
#include "content/public/browser/origin_trials_controller_delegate.h"
#include "content/public/common/content_features.h"
#include "content/public/test/url_loader_interceptor.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "url/gurl.h"
#include "url/origin.h"
#include "weblayer/browser/browser_context_impl.h"
#include "weblayer/shell/browser/shell.h"
#include "weblayer/test/weblayer_browser_test.h"
#include "weblayer/test/weblayer_browser_test_utils.h"
namespace weblayer {
namespace {
// See
// https://chromium.googlesource.com/chromium/src/+/main/docs/origin_trials_integration.md
const char kTestTokenPublicKey[] =
"dRCs+TocuKkocNKa0AtZ4awrt9XKH2SQCI6o4FY6BNA=";
const char kTrialEnabledDomain[] = "example.com";
const char kTrialEnabledPath[] = "/origin-trial";
const char kFrobulatePersistentTrialName[] = "FrobulatePersistent";
// Generated with
// tools/origin_trials/generate_token.py https://example.com \
// FrobulatePersistent --expire-timestamp=2000000000
const char kFrobulatePersistentToken[] =
"AzZfd1vKZ0SSGRGk/"
"8nIszQSlHYjbuYVE3jwaNZG3X4t11zRhzPWWJwTZ+JJDS3JJsyEZcpz+y20pAP6/"
"6upOQ4AAABdeyJvcmlnaW4iOiAiaHR0cHM6Ly9leGFtcGxlLmNvbTo0NDMiLCAiZmVhdHVyZSI"
"6ICJGcm9idWxhdGVQZXJzaXN0ZW50IiwgImV4cGlyeSI6IDIwMDAwMDAwMDB9";
} // namespace
class OriginTrialsBrowserTest : public WebLayerBrowserTest {
public:
OriginTrialsBrowserTest() {
scoped_feature_list_.InitAndEnableFeature(
::features::kPersistentOriginTrials);
}
~OriginTrialsBrowserTest() override = default;
void SetUpOnMainThread() override {
WebLayerBrowserTest::SetUpOnMainThread();
url_loader_interceptor_ = std::make_unique<content::URLLoaderInterceptor>(
base::BindRepeating(&OriginTrialsBrowserTest::InterceptRequest));
}
void TearDownOnMainThread() override {
// Clean up any saved settings after test run
GetBrowserContext()
->GetOriginTrialsControllerDelegate()
->ClearPersistedTokens();
url_loader_interceptor_.reset();
WebLayerBrowserTest::TearDownOnMainThread();
}
base::flat_set<std::string> GetPersistedTrials() {
url::Origin origin = url::Origin::CreateFromNormalizedTuple(
"https", kTrialEnabledDomain, 443);
return GetBrowserContext()
->GetOriginTrialsControllerDelegate()
->GetPersistedTrialsForOrigin(origin, /*partition_origin*/ origin,
base::Time::Now());
}
void SetUpCommandLine(base::CommandLine* command_line) override {
command_line->AppendSwitchASCII("origin-trial-public-key",
kTestTokenPublicKey);
}
// Navigate to an insecure domain
void RequestToHttpDomain() {
NavigateAndWaitForCompletion(GURL("http://127.0.0.1/"), shell());
}
// Navigate to our enabled origin without any Origin-Trial response headers
void RequestWithoutHeaders() {
GURL url(base::StrCat({"https://", kTrialEnabledDomain, "/"}));
NavigateAndWaitForCompletion(url, shell());
}
// Navigate to our enabled origin with a response containing |token|
// in the Origin-Trial header
void RequestForOriginTrial() {
GURL url(
base::StrCat({"https://", kTrialEnabledDomain, kTrialEnabledPath}));
NavigateAndWaitForCompletion(url, shell());
}
static bool InterceptRequest(
content::URLLoaderInterceptor::RequestParams* params) {
std::string headers =
"HTTP/1.1 200 OK\nContent-Type: text/html; charset=utf-8\n";
// Find the appropriate origin trial token.
if (params->url_request.url.DomainIs(kTrialEnabledDomain) &&
params->url_request.url.path() == kTrialEnabledPath) {
// Construct and send the response.
base::StrAppend(&headers,
{"Origin-Trial: ", kFrobulatePersistentToken, "\n"});
}
headers += '\n';
std::string body = "<!DOCTYPE html><body>Hello world!</body>";
content::URLLoaderInterceptor::WriteResponse(headers, body,
params->client.get());
return true;
}
protected:
base::test::ScopedFeatureList scoped_feature_list_;
std::unique_ptr<content::URLLoaderInterceptor> url_loader_interceptor_;
};
IN_PROC_BROWSER_TEST_F(OriginTrialsBrowserTest, NoHeaderDoesNotEnableResponse) {
RequestWithoutHeaders();
base::flat_set<std::string> trials = GetPersistedTrials();
EXPECT_TRUE(trials.empty());
}
IN_PROC_BROWSER_TEST_F(OriginTrialsBrowserTest, ResponseEnablesOriginTrial) {
RequestForOriginTrial();
base::flat_set<std::string> trials = GetPersistedTrials();
ASSERT_FALSE(trials.empty());
EXPECT_EQ(kFrobulatePersistentTrialName, *(trials.begin()));
}
IN_PROC_BROWSER_TEST_F(OriginTrialsBrowserTest,
TrialEnabledAfterNavigationToOtherDomain) {
// Navigate to a page that enables a persistent origin trial
RequestForOriginTrial();
EXPECT_FALSE(GetPersistedTrials().empty());
// Navigate to a different domain
RequestToHttpDomain();
// The trial should still be enabled
base::flat_set<std::string> trials = GetPersistedTrials();
ASSERT_FALSE(trials.empty());
EXPECT_EQ(kFrobulatePersistentTrialName, *(trials.begin()));
}
IN_PROC_BROWSER_TEST_F(OriginTrialsBrowserTest,
TrialDisabledAfterNavigationToSameDomain) {
// Navigate to a page that enables a persistent origin trial
RequestForOriginTrial();
EXPECT_FALSE(GetPersistedTrials().empty());
// Navigate to same domain without the Origin-Trial header set
RequestWithoutHeaders();
// The trial should no longer be enabled
EXPECT_TRUE(GetPersistedTrials().empty());
}
} // namespace weblayer
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/origin_trials_browsertest.cc | C++ | unknown | 6,159 |
// Copyright 2022 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "weblayer/browser/origin_trials_factory.h"
#include "components/keyed_service/content/browser_context_dependency_manager.h"
#include "components/origin_trials/browser/leveldb_persistence_provider.h"
#include "components/origin_trials/browser/origin_trials.h"
#include "components/origin_trials/common/features.h"
#include "content/public/browser/browser_context.h"
#include "content/public/browser/storage_partition.h"
#include "third_party/blink/public/common/origin_trials/trial_token_validator.h"
namespace weblayer {
// static
origin_trials::OriginTrials* OriginTrialsFactory::GetForBrowserContext(
content::BrowserContext* browser_context) {
if (origin_trials::features::IsPersistentOriginTrialsEnabled()) {
return static_cast<origin_trials::OriginTrials*>(
GetInstance()->GetServiceForBrowserContext(browser_context, true));
}
return nullptr;
}
// static
OriginTrialsFactory* OriginTrialsFactory::GetInstance() {
static base::NoDestructor<OriginTrialsFactory> factory;
return factory.get();
}
OriginTrialsFactory::OriginTrialsFactory()
: BrowserContextKeyedServiceFactory(
"OriginTrials",
BrowserContextDependencyManager::GetInstance()) {}
OriginTrialsFactory::~OriginTrialsFactory() noexcept = default;
KeyedService* OriginTrialsFactory::BuildServiceInstanceFor(
content::BrowserContext* context) const {
return new origin_trials::OriginTrials(
std::make_unique<origin_trials::LevelDbPersistenceProvider>(
context->GetPath(),
context->GetDefaultStoragePartition()->GetProtoDatabaseProvider()),
std::make_unique<blink::TrialTokenValidator>());
}
content::BrowserContext* OriginTrialsFactory::GetBrowserContextToUse(
content::BrowserContext* context) const {
return context;
}
} // namespace weblayer
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/origin_trials_factory.cc | C++ | unknown | 1,985 |
// Copyright 2022 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef WEBLAYER_BROWSER_ORIGIN_TRIALS_FACTORY_H_
#define WEBLAYER_BROWSER_ORIGIN_TRIALS_FACTORY_H_
#include "base/no_destructor.h"
#include "components/keyed_service/content/browser_context_keyed_service_factory.h"
namespace origin_trials {
class OriginTrials;
} // namespace origin_trials
namespace weblayer {
class OriginTrialsFactory : public BrowserContextKeyedServiceFactory {
public:
OriginTrialsFactory(const OriginTrialsFactory&) = delete;
OriginTrialsFactory& operator=(const OriginTrialsFactory&) = delete;
static origin_trials::OriginTrials* GetForBrowserContext(
content::BrowserContext* browser_context);
static OriginTrialsFactory* GetInstance();
private:
friend class base::NoDestructor<OriginTrialsFactory>;
OriginTrialsFactory();
~OriginTrialsFactory() override;
// BrowserContextKeyedServiceFactory methods:
KeyedService* BuildServiceInstanceFor(
content::BrowserContext* profile) const override;
content::BrowserContext* GetBrowserContextToUse(
content::BrowserContext* context) const override;
};
} // namespace weblayer
#endif // WEBLAYER_BROWSER_ORIGIN_TRIALS_FACTORY_H_
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/origin_trials_factory.h | C++ | unknown | 1,313 |
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <memory>
#include "base/test/scoped_feature_list.h"
#include "build/build_config.h"
#include "components/page_load_metrics/browser/observers/ad_metrics/ad_intervention_browser_test_utils.h"
#include "components/page_load_metrics/browser/page_load_metrics_test_waiter.h"
#include "components/subresource_filter/content/browser/content_subresource_filter_throttle_manager.h"
#include "components/subresource_filter/core/browser/subresource_filter_features.h"
#include "components/subresource_filter/core/common/common_features.h"
#include "components/subresource_filter/core/common/test_ruleset_utils.h"
#include "components/subresource_filter/core/mojom/subresource_filter.mojom.h"
#include "components/ukm/test_ukm_recorder.h"
#include "content/public/test/browser_test.h"
#include "content/public/test/browser_test_utils.h"
#include "content/public/test/test_navigation_observer.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/blink/public/common/features.h"
#include "url/gurl.h"
#include "weblayer/test/subresource_filter_browser_test_harness.h"
namespace weblayer {
namespace {
const char kAdsInterventionRecordedHistogram[] =
"SubresourceFilter.PageLoad.AdsInterventionTriggered";
} // namespace
class WebLayerOverlayPopupAdViolationBrowserTest
: public SubresourceFilterBrowserTest {
public:
WebLayerOverlayPopupAdViolationBrowserTest() = default;
void SetUp() override {
std::vector<base::test::FeatureRef> enabled = {
subresource_filter::kAdTagging,
subresource_filter::kAdsInterventionsEnforced};
std::vector<base::test::FeatureRef> disabled = {
blink::features::kFrequencyCappingForOverlayPopupDetection};
feature_list_.InitWithFeatures(enabled, disabled);
SubresourceFilterBrowserTest::SetUp();
}
void SetUpOnMainThread() override {
SubresourceFilterBrowserTest::SetUpOnMainThread();
SetRulesetWithRules(
{subresource_filter::testing::CreateSuffixRule("ad_iframe_writer.js")});
}
private:
base::test::ScopedFeatureList feature_list_;
};
// TODO(https://crbug.com/1199860): Fails on Linux MSan.
#if BUILDFLAG(IS_LINUX) && defined(MEMORY_SANITIZER)
#define MAYBE_NoOverlayPopupAd_AdInterventionNotTriggered_WL \
DISABLED_NoOverlayPopupAd_AdInterventionNotTriggered_WL
#else
#define MAYBE_NoOverlayPopupAd_AdInterventionNotTriggered_WL \
NoOverlayPopupAd_AdInterventionNotTriggered_WL
#endif
IN_PROC_BROWSER_TEST_F(WebLayerOverlayPopupAdViolationBrowserTest,
MAYBE_NoOverlayPopupAd_AdInterventionNotTriggered_WL) {
base::HistogramTester histogram_tester;
GURL url = embedded_test_server()->GetURL(
"a.com", "/ads_observer/large_scrollable_page_with_adiframe_writer.html");
page_load_metrics::NavigateAndWaitForFirstMeaningfulPaint(web_contents(),
url);
// Reload the page. Since we haven't seen any ad violations, expect that the
// ad script is loaded and that the subresource filter UI doesn't show up.
EXPECT_TRUE(content::NavigateToURL(web_contents(), url));
EXPECT_TRUE(
WasParsedScriptElementLoaded(web_contents()->GetPrimaryMainFrame()));
histogram_tester.ExpectBucketCount(
"SubresourceFilter.Actions2",
subresource_filter::SubresourceFilterAction::kUIShown, 0);
histogram_tester.ExpectBucketCount(
kAdsInterventionRecordedHistogram,
subresource_filter::mojom::AdsViolation::kOverlayPopupAd, 0);
}
// TODO(https://crbug.com/1287783): Fails on linux, android and chromeos.
#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_ANDROID) || BUILDFLAG(IS_CHROMEOS)
#define MAYBE_OverlayPopupAd_AdInterventionTriggered_WL \
DISABLED_OverlayPopupAd_AdInterventionTriggered_WL
#else
#define MAYBE_OverlayPopupAd_AdInterventionTriggered_WL \
OverlayPopupAd_AdInterventionTriggered_WL
#endif
IN_PROC_BROWSER_TEST_F(WebLayerOverlayPopupAdViolationBrowserTest,
MAYBE_OverlayPopupAd_AdInterventionTriggered_WL) {
base::HistogramTester histogram_tester;
GURL url = embedded_test_server()->GetURL(
"a.com", "/ads_observer/large_scrollable_page_with_adiframe_writer.html");
page_load_metrics::NavigateAndWaitForFirstMeaningfulPaint(web_contents(),
url);
page_load_metrics::TriggerAndDetectOverlayPopupAd(web_contents());
// Reload the page. Since we are enforcing ad blocking on ads violations,
// expect that the ad script is not loaded and that the subresource filter UI
// shows up.
EXPECT_TRUE(content::NavigateToURL(web_contents(), url));
EXPECT_FALSE(
WasParsedScriptElementLoaded(web_contents()->GetPrimaryMainFrame()));
histogram_tester.ExpectBucketCount(
"SubresourceFilter.Actions2",
subresource_filter::SubresourceFilterAction::kUIShown, 1);
histogram_tester.ExpectBucketCount(
kAdsInterventionRecordedHistogram,
subresource_filter::mojom::AdsViolation::kOverlayPopupAd, 1);
}
class WebLayerOverlayPopupAdViolationBrowserTestWithoutEnforcement
: public WebLayerOverlayPopupAdViolationBrowserTest {
public:
WebLayerOverlayPopupAdViolationBrowserTestWithoutEnforcement() = default;
void SetUp() override {
std::vector<base::test::FeatureRef> enabled = {
subresource_filter::kAdTagging};
std::vector<base::test::FeatureRef> disabled = {
subresource_filter::kAdsInterventionsEnforced,
blink::features::kFrequencyCappingForOverlayPopupDetection};
feature_list_.InitWithFeatures(enabled, disabled);
SubresourceFilterBrowserTest::SetUp();
}
private:
base::test::ScopedFeatureList feature_list_;
};
// TODO(https://crbug.com/1344280): Test is flaky.
IN_PROC_BROWSER_TEST_F(
WebLayerOverlayPopupAdViolationBrowserTestWithoutEnforcement,
DISABLED_OverlayPopupAd_NoAdInterventionTriggered_WL) {
base::HistogramTester histogram_tester;
GURL url = embedded_test_server()->GetURL(
"a.com", "/ads_observer/large_scrollable_page_with_adiframe_writer.html");
page_load_metrics::NavigateAndWaitForFirstMeaningfulPaint(web_contents(),
url);
page_load_metrics::TriggerAndDetectOverlayPopupAd(web_contents());
// Reload the page. Since we are not enforcing ad blocking on ads violations,
// expect that the ad script is loaded and that the subresource filter UI
// doesn't show up. Expect a histogram recording as the intervention is
// running in dry run mode.
EXPECT_TRUE(content::NavigateToURL(web_contents(), url));
EXPECT_TRUE(
WasParsedScriptElementLoaded(web_contents()->GetPrimaryMainFrame()));
histogram_tester.ExpectBucketCount(
"SubresourceFilter.Actions2",
subresource_filter::SubresourceFilterAction::kUIShown, 0);
histogram_tester.ExpectBucketCount(
kAdsInterventionRecordedHistogram,
subresource_filter::mojom::AdsViolation::kOverlayPopupAd, 1);
}
} // namespace weblayer
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/overlay_popup_ad_intervention_browsertest.cc | C++ | unknown | 7,121 |
// Copyright 2021 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "weblayer/browser/page_impl.h"
#include "build/build_config.h"
#include "content/public/browser/page.h"
#include "content/public/browser/web_contents.h"
#include "weblayer/browser/navigation_controller_impl.h"
#include "weblayer/browser/tab_impl.h"
#if BUILDFLAG(IS_ANDROID)
#include "weblayer/browser/java/jni/PageImpl_jni.h"
#endif
#if BUILDFLAG(IS_ANDROID)
using base::android::AttachCurrentThread;
using base::android::ScopedJavaLocalRef;
#endif
namespace weblayer {
PAGE_USER_DATA_KEY_IMPL(PageImpl);
PageImpl::PageImpl(content::Page& page)
: content::PageUserData<PageImpl>(page) {}
PageImpl::~PageImpl() {
auto* rfh = &(page().GetMainDocument());
auto* web_contents = content::WebContents::FromRenderFrameHost(rfh);
auto* tab = TabImpl::FromWebContents(web_contents);
if (tab) {
auto* navigation_controller =
static_cast<NavigationControllerImpl*>(tab->GetNavigationController());
navigation_controller->OnPageDestroyed(this);
}
#if BUILDFLAG(IS_ANDROID)
if (java_page_) {
Java_PageImpl_onNativeDestroyed(AttachCurrentThread(), java_page_);
}
#endif
}
#if BUILDFLAG(IS_ANDROID)
void PageImpl::SetJavaPage(
JNIEnv* env,
const base::android::JavaParamRef<jobject>& java_page) {
java_page_ = java_page;
}
#endif
} // namespace weblayer
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/page_impl.cc | C++ | unknown | 1,451 |
// Copyright 2021 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef WEBLAYER_BROWSER_PAGE_IMPL_H_
#define WEBLAYER_BROWSER_PAGE_IMPL_H_
#include "build/build_config.h"
#include "content/public/browser/page_user_data.h"
#include "weblayer/public/page.h"
#if BUILDFLAG(IS_ANDROID)
#include "base/android/scoped_java_ref.h"
#endif
namespace weblayer {
class PageImpl : public Page, public content::PageUserData<PageImpl> {
public:
PageImpl(const PageImpl&) = delete;
PageImpl& operator=(const PageImpl&) = delete;
~PageImpl() override;
#if BUILDFLAG(IS_ANDROID)
void SetJavaPage(JNIEnv* env,
const base::android::JavaParamRef<jobject>& java_page);
base::android::ScopedJavaGlobalRef<jobject> java_page() { return java_page_; }
#endif
private:
explicit PageImpl(content::Page& page);
friend class content::PageUserData<PageImpl>;
PAGE_USER_DATA_KEY_DECL();
#if BUILDFLAG(IS_ANDROID)
base::android::ScopedJavaGlobalRef<jobject> java_page_;
#endif
};
} // namespace weblayer
#endif // WEBLAYER_BROWSER_PAGE_IMPL_H_
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/page_impl.h | C++ | unknown | 1,145 |
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/test/bind.h"
#include "base/test/metrics/histogram_tester.h"
#include "build/build_config.h"
#include "components/page_load_metrics/browser/page_load_metrics_observer.h"
#include "components/page_load_metrics/browser/page_load_tracker.h"
#include "net/test/embedded_test_server/embedded_test_server.h"
#include "weblayer/browser/page_load_metrics_initialize.h"
#include "weblayer/browser/profile_impl.h"
#include "weblayer/test/weblayer_browser_test.h"
#include "weblayer/test/weblayer_browser_test_utils.h"
namespace weblayer {
using PageLoadMetricsBrowserTest = WebLayerBrowserTest;
class PageLoadMetricsObserver
: public page_load_metrics::PageLoadMetricsObserver {
public:
explicit PageLoadMetricsObserver(base::RepeatingClosure quit_closure)
: quit_closure_(quit_closure) {}
~PageLoadMetricsObserver() override = default;
// page_load_metrics::PageLoadMetricsObserver implementation:
ObservePolicy OnFencedFramesStart(
content::NavigationHandle* navigation_handle,
const GURL& currently_committed_url) override {
// This class is only interested in events for outer-most frame that are
// forwarded by PageLoadTracker. So, this class doesn't need observer-level
// forwarding.
return STOP_OBSERVING;
}
PageLoadMetricsObserver::ObservePolicy OnPrerenderStart(
content::NavigationHandle* navigation_handle,
const GURL& currently_committed_url) override {
// Currently, prerendering is not enabled for WebLayer.
//
// TODO(https://crbug.com/1267224): If support prerendering, add callbacks
// and tests.
return STOP_OBSERVING;
}
void OnFirstPaintInPage(
const page_load_metrics::mojom::PageLoadTiming& timing) override {
on_first_paint_seen_ = true;
QuitRunLoopIfReady();
}
void OnFirstContentfulPaintInPage(
const page_load_metrics::mojom::PageLoadTiming& timing) override {
on_first_contentful_paint_seen_ = true;
QuitRunLoopIfReady();
}
private:
void QuitRunLoopIfReady() {
if (on_first_paint_seen_ && on_first_contentful_paint_seen_)
quit_closure_.Run();
}
bool on_first_paint_seen_ = false;
bool on_first_contentful_paint_seen_ = false;
base::RepeatingClosure quit_closure_;
};
IN_PROC_BROWSER_TEST_F(PageLoadMetricsBrowserTest, Heartbeat) {
base::HistogramTester histogram_tester;
ASSERT_TRUE(embedded_test_server()->Start());
base::RunLoop run_loop;
auto callback = base::BindLambdaForTesting(
[&](page_load_metrics::PageLoadTracker* tracker) {
tracker->AddObserver(
std::make_unique<PageLoadMetricsObserver>(run_loop.QuitClosure()));
// Don't need this anymore
SetRegisterEmbedderObserversForTesting(nullptr);
});
SetRegisterEmbedderObserversForTesting(&callback);
NavigateAndWaitForCompletion(
embedded_test_server()->GetURL("/simple_page.html"), shell());
run_loop.Run();
// Look for prefix because on Android the name would be different if the tab
// is not in foreground initially. This seems to happen on a slow test bot.
EXPECT_GE(histogram_tester
.GetTotalCountsForPrefix(
"PageLoad.PaintTiming.NavigationToFirstPaint")
.size(),
1u);
EXPECT_GE(histogram_tester
.GetTotalCountsForPrefix(
"PageLoad.PaintTiming.NavigationToFirstContentfulPaint")
.size(),
1u);
}
IN_PROC_BROWSER_TEST_F(PageLoadMetricsBrowserTest, UserCounter) {
base::HistogramTester histogram_tester;
ASSERT_TRUE(embedded_test_server()->Start());
NavigateAndWaitForCompletion(embedded_test_server()->GetURL("/form.html"),
shell());
NavigateAndWaitForCompletion(GURL("about:blank"), shell()); // Flush.
histogram_tester.ExpectBucketCount("Blink.UseCounter.MainFrame.Features",
blink::mojom::WebFeature::kPageVisits, 1);
histogram_tester.ExpectBucketCount("Blink.UseCounter.Features",
blink::mojom::WebFeature::kFormElement, 1);
}
} // namespace weblayer
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/page_load_metrics_browsertest.cc | C++ | unknown | 4,280 |
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "weblayer/browser/page_load_metrics_initialize.h"
#include <memory>
#include <utility>
#include "base/functional/bind.h"
#include "components/page_load_metrics/browser/metrics_web_contents_observer.h"
#include "components/page_load_metrics/browser/observers/ad_metrics/ads_page_load_metrics_observer.h"
#include "components/page_load_metrics/browser/page_load_metrics_embedder_base.h"
#include "components/page_load_metrics/browser/page_load_metrics_memory_tracker.h"
#include "components/page_load_metrics/browser/page_load_metrics_observer.h"
#include "components/page_load_metrics/browser/page_load_tracker.h"
#include "weblayer/browser/heavy_ad_service_factory.h"
#include "weblayer/browser/i18n_util.h"
#include "weblayer/browser/no_state_prefetch/no_state_prefetch_utils.h"
#include "weblayer/browser/page_load_metrics_observer_impl.h"
#include "weblayer/browser/weblayer_page_load_metrics_memory_tracker_factory.h"
namespace content {
class BrowserContext;
} // namespace content
namespace page_load_metrics {
class PageLoadMetricsMemoryTracker;
} // namespace page_load_metrics
namespace weblayer {
namespace {
base::RepeatingCallback<void(page_load_metrics::PageLoadTracker*)>*
g_callback_for_testing;
class PageLoadMetricsEmbedder
: public page_load_metrics::PageLoadMetricsEmbedderBase {
public:
PageLoadMetricsEmbedder(const PageLoadMetricsEmbedder&) = delete;
PageLoadMetricsEmbedder& operator=(const PageLoadMetricsEmbedder&) = delete;
explicit PageLoadMetricsEmbedder(content::WebContents* web_contents)
: PageLoadMetricsEmbedderBase(web_contents) {}
~PageLoadMetricsEmbedder() override = default;
// page_load_metrics::PageLoadMetricsEmbedderBase:
bool IsNewTabPageUrl(const GURL& url) override { return false; }
bool IsNoStatePrefetch(content::WebContents* web_contents) override {
return NoStatePrefetchContentsFromWebContents(web_contents);
}
bool IsExtensionUrl(const GURL& url) override { return false; }
bool IsSidePanel(content::WebContents* web_contents) override {
// The side panel is not supported in WebLayer so this always returns false.
return false;
}
page_load_metrics::PageLoadMetricsMemoryTracker*
GetMemoryTrackerForBrowserContext(
content::BrowserContext* browser_context) override {
if (!base::FeatureList::IsEnabled(features::kV8PerFrameMemoryMonitoring))
return nullptr;
return WeblayerPageLoadMetricsMemoryTrackerFactory::GetForBrowserContext(
browser_context);
}
protected:
// page_load_metrics::PageLoadMetricsEmbedderBase:
void RegisterEmbedderObservers(
page_load_metrics::PageLoadTracker* tracker) override {
tracker->AddObserver(std::make_unique<PageLoadMetricsObserverImpl>());
if (!IsNoStatePrefetch(web_contents())) {
std::unique_ptr<page_load_metrics::AdsPageLoadMetricsObserver>
ads_observer =
page_load_metrics::AdsPageLoadMetricsObserver::CreateIfNeeded(
tracker->GetWebContents(),
HeavyAdServiceFactory::GetForBrowserContext(
tracker->GetWebContents()->GetBrowserContext()),
base::BindRepeating(&i18n::GetApplicationLocale));
if (ads_observer)
tracker->AddObserver(std::move(ads_observer));
}
if (g_callback_for_testing)
(*g_callback_for_testing).Run(tracker);
}
};
} // namespace
void InitializePageLoadMetricsForWebContents(
content::WebContents* web_contents) {
// Change this method? consider to modify the peer in
// android_webview/browser/page_load_metrics/page_load_metrics_initialize.cc
// chrome/browser/page_load_metrics/page_load_metrics_initialize.cc
// as well.
page_load_metrics::MetricsWebContentsObserver::CreateForWebContents(
web_contents, std::make_unique<PageLoadMetricsEmbedder>(web_contents));
}
void SetRegisterEmbedderObserversForTesting(
base::RepeatingCallback<void(page_load_metrics::PageLoadTracker*)>*
callback) {
g_callback_for_testing = callback;
}
} // namespace weblayer
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/page_load_metrics_initialize.cc | C++ | unknown | 4,205 |
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef WEBLAYER_BROWSER_PAGE_LOAD_METRICS_INITIALIZE_H_
#define WEBLAYER_BROWSER_PAGE_LOAD_METRICS_INITIALIZE_H_
#include "base/functional/callback_forward.h"
namespace content {
class WebContents;
}
namespace page_load_metrics {
class PageLoadTracker;
}
namespace weblayer {
void InitializePageLoadMetricsForWebContents(
content::WebContents* web_contents);
// Sets a callback which is called by
// page_load_metrics::PageLoadMetricsEmbedderBase::RegisterEmbedderObservers.
void SetRegisterEmbedderObserversForTesting(
base::RepeatingCallback<void(page_load_metrics::PageLoadTracker*)>*
callback);
} // namespace weblayer
#endif // WEBLAYER_BROWSER_PAGE_LOAD_METRICS_INITIALIZE_H_
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/page_load_metrics_initialize.h | C++ | unknown | 853 |
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "weblayer/browser/page_load_metrics_observer_impl.h"
#include "base/time/time.h"
#include "build/build_config.h"
#include "components/no_state_prefetch/browser/no_state_prefetch_manager.h"
#include "components/no_state_prefetch/browser/no_state_prefetch_utils.h"
#include "components/page_load_metrics/browser/observers/core/largest_contentful_paint_handler.h"
#include "content/public/browser/navigation_handle.h"
#include "content/public/browser/web_contents.h"
#include "services/metrics/public/cpp/ukm_recorder.h"
#include "weblayer/browser/navigation_controller_impl.h"
#include "weblayer/browser/no_state_prefetch/no_state_prefetch_manager_factory.h"
#include "weblayer/browser/tab_impl.h"
namespace weblayer {
page_load_metrics::PageLoadMetricsObserver::ObservePolicy
PageLoadMetricsObserverImpl::OnFencedFramesStart(
content::NavigationHandle* navigation_handle,
const GURL& currently_committed_url) {
// This class is only interested in events for outer-most frame that are
// forwarded by PageLoadTracker. So, this class doesn't need observer-level
// forwarding.
return STOP_OBSERVING;
}
page_load_metrics::PageLoadMetricsObserver::ObservePolicy
PageLoadMetricsObserverImpl::OnPrerenderStart(
content::NavigationHandle* navigation_handle,
const GURL& currently_committed_url) {
// Currently, prerendering is not enabled for WebLayer.
//
// TODO(https://crbug.com/1267224): If support prerendering, add callbacks,
// e.g. notification of activation_start.
return STOP_OBSERVING;
}
PageLoadMetricsObserverImpl::ObservePolicy
PageLoadMetricsObserverImpl::OnCommit(
content::NavigationHandle* navigation_handle) {
#if BUILDFLAG(IS_ANDROID)
if (!ukm::UkmRecorder::Get())
return CONTINUE_OBSERVING;
// If URL-Keyed-Metrics (UKM) is enabled in the system, this is used to
// populate it with top-level page-load metrics.
prerender::NoStatePrefetchManager* const no_state_prefetch_manager =
NoStatePrefetchManagerFactory::GetForBrowserContext(
navigation_handle->GetWebContents()->GetBrowserContext());
if (!no_state_prefetch_manager)
return CONTINUE_OBSERVING;
prerender::RecordNoStatePrefetchMetrics(navigation_handle,
GetDelegate().GetPageUkmSourceId(),
no_state_prefetch_manager);
#endif
return CONTINUE_OBSERVING;
}
page_load_metrics::PageLoadMetricsObserver::ObservePolicy
PageLoadMetricsObserverImpl::FlushMetricsOnAppEnterBackground(
const page_load_metrics::mojom::PageLoadTiming& timing) {
// FlushMetricsOnAppEnterBackground is invoked on Android in cases where the
// app is about to be backgrounded, as part of the Activity.onPause()
// flow. After this method is invoked, WebLayer may be killed without further
// notification, so we record final metrics collected up to this point.
ReportBufferedMetrics(timing);
// We continue observing after being backgrounded, in case we are foregrounded
// again without being killed. In those cases we may still report non-buffered
// metrics such as FCP after being re-foregrounded.
return CONTINUE_OBSERVING;
}
PageLoadMetricsObserverImpl::ObservePolicy
PageLoadMetricsObserverImpl::OnHidden(
const page_load_metrics::mojom::PageLoadTiming& timing) {
ReportBufferedMetrics(timing);
return CONTINUE_OBSERVING;
}
void PageLoadMetricsObserverImpl::OnComplete(
const page_load_metrics::mojom::PageLoadTiming& timing) {
ReportBufferedMetrics(timing);
}
void PageLoadMetricsObserverImpl::OnFirstContentfulPaintInPage(
const page_load_metrics::mojom::PageLoadTiming& timing) {
auto* tab = TabImpl::FromWebContents(GetDelegate().GetWebContents());
if (!tab)
return;
auto* nav_controller =
static_cast<NavigationControllerImpl*>(tab->GetNavigationController());
nav_controller->OnFirstContentfulPaint(
GetDelegate().GetNavigationStart(),
*timing.paint_timing->first_contentful_paint);
}
void PageLoadMetricsObserverImpl::ReportBufferedMetrics(
const page_load_metrics::mojom::PageLoadTiming& timing) {
// This method may be invoked multiple times. Make sure that if we already
// reported, we do not report again.
if (reported_buffered_metrics_)
return;
reported_buffered_metrics_ = true;
// Buffered metrics aren't available until after the navigation commits.
if (!GetDelegate().DidCommit())
return;
auto* tab = TabImpl::FromWebContents(GetDelegate().GetWebContents());
if (!tab)
return;
const page_load_metrics::ContentfulPaintTimingInfo& largest_contentful_paint =
GetDelegate()
.GetLargestContentfulPaintHandler()
.MergeMainFrameAndSubframes();
if (!largest_contentful_paint.ContainsValidTime())
return;
auto* nav_controller =
static_cast<NavigationControllerImpl*>(tab->GetNavigationController());
nav_controller->OnLargestContentfulPaint(GetDelegate().GetNavigationStart(),
*largest_contentful_paint.Time());
}
} // namespace weblayer
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/page_load_metrics_observer_impl.cc | C++ | unknown | 5,213 |
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef WEBLAYER_BROWSER_PAGE_LOAD_METRICS_OBSERVER_IMPL_H_
#define WEBLAYER_BROWSER_PAGE_LOAD_METRICS_OBSERVER_IMPL_H_
#include "components/page_load_metrics/browser/page_load_metrics_observer.h"
namespace weblayer {
class PageLoadMetricsObserverImpl
: public page_load_metrics::PageLoadMetricsObserver {
public:
PageLoadMetricsObserverImpl() = default;
~PageLoadMetricsObserverImpl() override = default;
// page_load_metrics::PageLoadMetricsObserver implementation:
ObservePolicy OnFencedFramesStart(
content::NavigationHandle* navigation_handle,
const GURL& currently_committed_url) override;
ObservePolicy OnPrerenderStart(content::NavigationHandle* navigation_handle,
const GURL& currently_committed_url) override;
ObservePolicy FlushMetricsOnAppEnterBackground(
const page_load_metrics::mojom::PageLoadTiming& timing) override;
ObservePolicy OnHidden(
const page_load_metrics::mojom::PageLoadTiming& timing) override;
void OnComplete(
const page_load_metrics::mojom::PageLoadTiming& timing) override;
ObservePolicy OnCommit(content::NavigationHandle* navigation_handle) override;
void OnFirstContentfulPaintInPage(
const page_load_metrics::mojom::PageLoadTiming& timing) override;
void ReportBufferedMetrics(
const page_load_metrics::mojom::PageLoadTiming& timing);
private:
bool reported_buffered_metrics_ = false;
};
} // namespace weblayer
#endif // WEBLAYER_BROWSER_PAGE_LOAD_METRICS_OBSERVER_IMPL_H_
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/page_load_metrics_observer_impl.h | C++ | unknown | 1,670 |
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "weblayer/browser/page_specific_content_settings_delegate.h"
#include "base/feature_list.h"
#include "base/functional/callback_helpers.h"
#include "components/content_settings/core/common/content_settings.h"
#include "components/permissions/permission_decision_auto_blocker.h"
#include "content/public/browser/render_process_host.h"
#include "content/public/common/content_features.h"
#include "ipc/ipc_channel_proxy.h"
#include "mojo/public/cpp/bindings/associated_remote.h"
#include "weblayer/browser/browser_context_impl.h"
#include "weblayer/browser/content_settings_manager_delegate.h"
#include "weblayer/browser/host_content_settings_map_factory.h"
#include "weblayer/browser/permissions/permission_decision_auto_blocker_factory.h"
#include "weblayer/common/renderer_configuration.mojom.h"
namespace weblayer {
PageSpecificContentSettingsDelegate::PageSpecificContentSettingsDelegate(
content::WebContents* web_contents)
: web_contents_(web_contents) {}
PageSpecificContentSettingsDelegate::~PageSpecificContentSettingsDelegate() =
default;
// static
void PageSpecificContentSettingsDelegate::InitializeRenderer(
content::RenderProcessHost* process) {
mojo::AssociatedRemote<mojom::RendererConfiguration> rc_interface;
process->GetChannel()->GetRemoteAssociatedInterface(&rc_interface);
mojo::PendingRemote<content_settings::mojom::ContentSettingsManager>
content_settings_manager;
content_settings::ContentSettingsManagerImpl::Create(
process, content_settings_manager.InitWithNewPipeAndPassReceiver(),
std::make_unique<ContentSettingsManagerDelegate>());
rc_interface->SetInitialConfiguration(std::move(content_settings_manager));
}
void PageSpecificContentSettingsDelegate::UpdateLocationBar() {}
PrefService* PageSpecificContentSettingsDelegate::GetPrefs() {
return static_cast<BrowserContextImpl*>(web_contents_->GetBrowserContext())
->pref_service();
}
HostContentSettingsMap* PageSpecificContentSettingsDelegate::GetSettingsMap() {
return HostContentSettingsMapFactory::GetForBrowserContext(
web_contents_->GetBrowserContext());
}
std::unique_ptr<BrowsingDataModel::Delegate>
PageSpecificContentSettingsDelegate::CreateBrowsingDataModelDelegate() {
return nullptr;
}
void PageSpecificContentSettingsDelegate::SetDefaultRendererContentSettingRules(
content::RenderFrameHost* rfh,
RendererContentSettingRules* rules) {}
std::vector<storage::FileSystemType>
PageSpecificContentSettingsDelegate::GetAdditionalFileSystemTypes() {
return {};
}
browsing_data::CookieHelper::IsDeletionDisabledCallback
PageSpecificContentSettingsDelegate::GetIsDeletionDisabledCallback() {
return base::NullCallback();
}
bool PageSpecificContentSettingsDelegate::IsMicrophoneCameraStateChanged(
content_settings::PageSpecificContentSettings::MicrophoneCameraState
microphone_camera_state,
const std::string& media_stream_selected_audio_device,
const std::string& media_stream_selected_video_device) {
return false;
}
content_settings::PageSpecificContentSettings::MicrophoneCameraState
PageSpecificContentSettingsDelegate::GetMicrophoneCameraState() {
return content_settings::PageSpecificContentSettings::
MICROPHONE_CAMERA_NOT_ACCESSED;
}
content::WebContents* PageSpecificContentSettingsDelegate::
MaybeGetSyncedWebContentsForPictureInPicture(
content::WebContents* web_contents) {
return nullptr;
}
void PageSpecificContentSettingsDelegate::OnContentAllowed(
ContentSettingsType type) {}
void PageSpecificContentSettingsDelegate::OnContentBlocked(
ContentSettingsType type) {}
void PageSpecificContentSettingsDelegate::OnStorageAccessAllowed(
content_settings::mojom::ContentSettingsManager::StorageType storage_type,
const url::Origin& origin,
content::Page& page) {}
void PageSpecificContentSettingsDelegate::OnCookieAccessAllowed(
const net::CookieList& accessed_cookies,
content::Page& page) {}
void PageSpecificContentSettingsDelegate::OnServiceWorkerAccessAllowed(
const url::Origin& origin,
content::Page& page) {}
} // namespace weblayer
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/page_specific_content_settings_delegate.cc | C++ | unknown | 4,267 |
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef WEBLAYER_BROWSER_PAGE_SPECIFIC_CONTENT_SETTINGS_DELEGATE_H_
#define WEBLAYER_BROWSER_PAGE_SPECIFIC_CONTENT_SETTINGS_DELEGATE_H_
#include "base/memory/raw_ptr.h"
#include "components/content_settings/browser/page_specific_content_settings.h"
namespace weblayer {
// Called by PageSpecificContentSettings to handle WebLayer specific logic.
class PageSpecificContentSettingsDelegate
: public content_settings::PageSpecificContentSettings::Delegate {
public:
explicit PageSpecificContentSettingsDelegate(
content::WebContents* web_contents);
~PageSpecificContentSettingsDelegate() override;
PageSpecificContentSettingsDelegate(
const PageSpecificContentSettingsDelegate&) = delete;
PageSpecificContentSettingsDelegate& operator=(
const PageSpecificContentSettingsDelegate&) = delete;
static void InitializeRenderer(content::RenderProcessHost* process);
private:
// PageSpecificContentSettings::Delegate:
void UpdateLocationBar() override;
PrefService* GetPrefs() override;
HostContentSettingsMap* GetSettingsMap() override;
std::unique_ptr<BrowsingDataModel::Delegate> CreateBrowsingDataModelDelegate()
override;
void SetDefaultRendererContentSettingRules(
content::RenderFrameHost* rfh,
RendererContentSettingRules* rules) override;
std::vector<storage::FileSystemType> GetAdditionalFileSystemTypes() override;
browsing_data::CookieHelper::IsDeletionDisabledCallback
GetIsDeletionDisabledCallback() override;
bool IsMicrophoneCameraStateChanged(
content_settings::PageSpecificContentSettings::MicrophoneCameraState
microphone_camera_state,
const std::string& media_stream_selected_audio_device,
const std::string& media_stream_selected_video_device) override;
content_settings::PageSpecificContentSettings::MicrophoneCameraState
GetMicrophoneCameraState() override;
content::WebContents* MaybeGetSyncedWebContentsForPictureInPicture(
content::WebContents* web_contents) override;
void OnContentAllowed(ContentSettingsType type) override;
void OnContentBlocked(ContentSettingsType type) override;
void OnStorageAccessAllowed(
content_settings::mojom::ContentSettingsManager::StorageType storage_type,
const url::Origin& origin,
content::Page& page) override;
void OnCookieAccessAllowed(const net::CookieList& accessed_cookies,
content::Page& page) override;
void OnServiceWorkerAccessAllowed(const url::Origin& origin,
content::Page& page) override;
raw_ptr<content::WebContents> web_contents_;
};
} // namespace weblayer
#endif // WEBLAYER_BROWSER_PAGE_SPECIFIC_CONTENT_SETTINGS_DELEGATE_H_
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/page_specific_content_settings_delegate.h | C++ | unknown | 2,857 |
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "weblayer/browser/password_manager_driver_factory.h"
#include "base/memory/raw_ptr.h"
#include "components/password_manager/content/browser/bad_message.h"
#include "components/password_manager/content/browser/form_meta_data.h"
#include "components/site_isolation/site_isolation_policy.h"
#include "content/public/browser/browser_context.h"
#include "content/public/browser/render_frame_host.h"
#include "content/public/browser/web_contents.h"
#include "mojo/public/cpp/bindings/associated_receiver.h"
namespace weblayer {
// A minimal implementation of autofill::mojom::PasswordManagerDriver which just
// listens for the user to type into a password field.
class PasswordManagerDriverFactory::PasswordManagerDriver
: public autofill::mojom::PasswordManagerDriver {
public:
explicit PasswordManagerDriver(content::RenderFrameHost* render_frame_host)
: render_frame_host_(render_frame_host) {}
void BindPendingReceiver(
mojo::PendingAssociatedReceiver<autofill::mojom::PasswordManagerDriver>
pending_receiver) {
password_manager_receiver_.Bind(std::move(pending_receiver));
}
private:
// autofill::mojom::PasswordManagerDriver:
// Note that these messages received from a potentially compromised renderer.
// For that reason, any access to form data should be validated via
// bad_message::CheckChildProcessSecurityPolicy.
void PasswordFormsParsed(
const std::vector<autofill::FormData>& raw_forms_data) override {}
void PasswordFormsRendered(
const std::vector<autofill::FormData>& raw_visible_forms_data) override {}
void PasswordFormSubmitted(const autofill::FormData& raw_form_data) override {
}
void InformAboutUserInput(const autofill::FormData& raw_form_data) override {
autofill::FormData form_data =
password_manager::GetFormWithFrameAndFormMetaData(render_frame_host_,
raw_form_data);
if (FormHasNonEmptyPasswordField(form_data) &&
site_isolation::SiteIsolationPolicy::
IsIsolationForPasswordSitesEnabled()) {
// This function signals that a password field has been filled (whether by
// the user, JS, autofill, or some other means) or a password form has
// been submitted. Use this as a heuristic to start site-isolating the
// form's site. This is intended to be used primarily when full site
// isolation is not used, such as on Android.
content::SiteInstance::StartIsolatingSite(
render_frame_host_->GetSiteInstance()->GetBrowserContext(),
form_data.url,
content::ChildProcessSecurityPolicy::IsolatedOriginSource::
USER_TRIGGERED);
}
}
void DynamicFormSubmission(autofill::mojom::SubmissionIndicatorEvent
submission_indication_event) override {}
void PasswordFormCleared(const autofill::FormData& raw_form_data) override {}
void RecordSavePasswordProgress(const std::string& log) override {}
void UserModifiedPasswordField() override {}
void UserModifiedNonPasswordField(
autofill::FieldRendererId renderer_id,
const std::u16string& field_name,
const std::u16string& value,
bool autocomplete_attribute_has_username) override {}
void ShowPasswordSuggestions(base::i18n::TextDirection text_direction,
const std::u16string& typed_username,
int options,
const gfx::RectF& bounds) override {}
#if BUILDFLAG(IS_ANDROID)
void ShowTouchToFill(
autofill::mojom::SubmissionReadinessState submission_readiness) override {
}
#endif
void CheckSafeBrowsingReputation(const GURL& form_action,
const GURL& frame_url) override {}
void FocusedInputChanged(
autofill::FieldRendererId focused_field_id,
autofill::mojom::FocusedFieldType focused_field_type) override {}
void LogFirstFillingResult(autofill::FormRendererId form_renderer_id,
int32_t result) override {}
mojo::AssociatedReceiver<autofill::mojom::PasswordManagerDriver>
password_manager_receiver_{this};
raw_ptr<content::RenderFrameHost> render_frame_host_;
};
PasswordManagerDriverFactory::PasswordManagerDriverFactory(
content::WebContents* web_contents)
: content::WebContentsObserver(web_contents),
content::WebContentsUserData<PasswordManagerDriverFactory>(
*web_contents) {}
PasswordManagerDriverFactory::~PasswordManagerDriverFactory() = default;
// static
void PasswordManagerDriverFactory::BindPasswordManagerDriver(
mojo::PendingAssociatedReceiver<autofill::mojom::PasswordManagerDriver>
pending_receiver,
content::RenderFrameHost* render_frame_host) {
// TODO(https://crbug.com/1233858): Similarly to the
// ContentPasswordManagerDriver implementation. Do not bind the interface when
// the RenderFrameHost is in an anonymous iframe.
content::WebContents* web_contents =
content::WebContents::FromRenderFrameHost(render_frame_host);
if (!web_contents)
return;
PasswordManagerDriverFactory* factory =
PasswordManagerDriverFactory::FromWebContents(web_contents);
if (!factory)
return;
factory->GetDriverForFrame(render_frame_host)
->BindPendingReceiver(std::move(pending_receiver));
}
PasswordManagerDriverFactory::PasswordManagerDriver*
PasswordManagerDriverFactory::GetDriverForFrame(
content::RenderFrameHost* render_frame_host) {
DCHECK_EQ(web_contents(),
content::WebContents::FromRenderFrameHost(render_frame_host));
DCHECK(render_frame_host->IsRenderFrameLive());
auto [it, inserted] =
frame_driver_map_.try_emplace(render_frame_host, render_frame_host);
return &it->second;
}
void PasswordManagerDriverFactory::RenderFrameDeleted(
content::RenderFrameHost* render_frame_host) {
frame_driver_map_.erase(render_frame_host);
}
WEB_CONTENTS_USER_DATA_KEY_IMPL(PasswordManagerDriverFactory);
} // namespace weblayer
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/password_manager_driver_factory.cc | C++ | unknown | 6,186 |
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef WEBLAYER_BROWSER_PASSWORD_MANAGER_DRIVER_FACTORY_H_
#define WEBLAYER_BROWSER_PASSWORD_MANAGER_DRIVER_FACTORY_H_
#include <map>
#include "components/autofill/content/common/mojom/autofill_driver.mojom.h"
#include "content/public/browser/web_contents_observer.h"
#include "content/public/browser/web_contents_user_data.h"
#include "mojo/public/cpp/bindings/pending_associated_receiver.h"
namespace content {
class WebContents;
}
namespace weblayer {
// WebLayer uses the system autofill and not the autofill used by Chrome. This
// factory and the corresponding driver are only used to listen for the
// notification that a password was typed into a form, since this is used as a
// signal to start isolating that site.
// TODO(crbug.com/1088446): Find a way to easily share this with Chrome.
class PasswordManagerDriverFactory
: public content::WebContentsObserver,
public content::WebContentsUserData<PasswordManagerDriverFactory> {
public:
~PasswordManagerDriverFactory() override;
PasswordManagerDriverFactory(const PasswordManagerDriverFactory&) = delete;
PasswordManagerDriverFactory& operator=(const PasswordManagerDriverFactory&) =
delete;
static void BindPasswordManagerDriver(
mojo::PendingAssociatedReceiver<autofill::mojom::PasswordManagerDriver>
pending_receiver,
content::RenderFrameHost* render_frame_host);
private:
class PasswordManagerDriver;
friend class content::WebContentsUserData<PasswordManagerDriverFactory>;
explicit PasswordManagerDriverFactory(content::WebContents* web_contents);
// content::WebContentsObserver:
void RenderFrameDeleted(content::RenderFrameHost* render_frame_host) override;
PasswordManagerDriver* GetDriverForFrame(
content::RenderFrameHost* render_frame_host);
std::map<content::RenderFrameHost*, PasswordManagerDriver> frame_driver_map_;
WEB_CONTENTS_USER_DATA_KEY_DECL();
};
} // namespace weblayer
#endif // WEBLAYER_BROWSER_PASSWORD_MANAGER_DRIVER_FACTORY_H_
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/password_manager_driver_factory.h | C++ | unknown | 2,148 |
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "weblayer/browser/permissions/geolocation_permission_context_delegate.h"
#include "build/build_config.h"
#if BUILDFLAG(IS_ANDROID)
#include "weblayer/browser/android/permission_request_utils.h"
#include "weblayer/browser/browser_context_impl.h"
#include "weblayer/browser/tab_impl.h"
#endif
namespace weblayer {
bool GeolocationPermissionContextDelegate::DecidePermission(
const permissions::PermissionRequestID& id,
const GURL& requesting_origin,
bool user_gesture,
permissions::BrowserPermissionCallback* callback,
permissions::GeolocationPermissionContext* context) {
return false;
}
#if BUILDFLAG(IS_ANDROID)
bool GeolocationPermissionContextDelegate::IsInteractable(
content::WebContents* web_contents) {
auto* tab = TabImpl::FromWebContents(web_contents);
return tab && tab->IsActive();
}
PrefService* GeolocationPermissionContextDelegate::GetPrefs(
content::BrowserContext* browser_context) {
return static_cast<BrowserContextImpl*>(browser_context)->pref_service();
}
bool GeolocationPermissionContextDelegate::IsRequestingOriginDSE(
content::BrowserContext* browser_context,
const GURL& requesting_origin) {
return false;
}
#endif
} // namespace weblayer
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/permissions/geolocation_permission_context_delegate.cc | C++ | unknown | 1,372 |
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef WEBLAYER_BROWSER_PERMISSIONS_GEOLOCATION_PERMISSION_CONTEXT_DELEGATE_H_
#define WEBLAYER_BROWSER_PERMISSIONS_GEOLOCATION_PERMISSION_CONTEXT_DELEGATE_H_
#include "build/build_config.h"
#include "components/permissions/contexts/geolocation_permission_context.h"
namespace weblayer {
class GeolocationPermissionContextDelegate
: public permissions::GeolocationPermissionContext::Delegate {
public:
GeolocationPermissionContextDelegate() = default;
GeolocationPermissionContextDelegate(
const GeolocationPermissionContextDelegate&) = delete;
GeolocationPermissionContextDelegate& operator=(
const GeolocationPermissionContextDelegate&) = delete;
// GeolocationPermissionContext::Delegate:
bool DecidePermission(
const permissions::PermissionRequestID& id,
const GURL& requesting_origin,
bool user_gesture,
permissions::BrowserPermissionCallback* callback,
permissions::GeolocationPermissionContext* context) override;
#if BUILDFLAG(IS_ANDROID)
bool IsInteractable(content::WebContents* web_contents) override;
PrefService* GetPrefs(content::BrowserContext* browser_context) override;
bool IsRequestingOriginDSE(content::BrowserContext* browser_context,
const GURL& requesting_origin) override;
#endif
};
} // namespace weblayer
#endif // WEBLAYER_BROWSER_PERMISSIONS_GEOLOCATION_PERMISSION_CONTEXT_DELEGATE_H_
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/permissions/geolocation_permission_context_delegate.h | C++ | unknown | 1,559 |
// 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 "weblayer/browser/permissions/origin_keyed_permission_action_service_factory.h"
#include "components/keyed_service/content/browser_context_dependency_manager.h"
#include "components/permissions/origin_keyed_permission_action_service.h"
namespace weblayer {
// static
permissions::OriginKeyedPermissionActionService*
OriginKeyedPermissionActionServiceFactory::GetForBrowserContext(
content::BrowserContext* context) {
return static_cast<permissions::OriginKeyedPermissionActionService*>(
GetInstance()->GetServiceForBrowserContext(context, true));
}
// static
OriginKeyedPermissionActionServiceFactory*
OriginKeyedPermissionActionServiceFactory::GetInstance() {
static base::NoDestructor<OriginKeyedPermissionActionServiceFactory> factory;
return factory.get();
}
OriginKeyedPermissionActionServiceFactory::
OriginKeyedPermissionActionServiceFactory()
: BrowserContextKeyedServiceFactory(
"OriginKeyedPermissionActionService",
BrowserContextDependencyManager::GetInstance()) {}
OriginKeyedPermissionActionServiceFactory::
~OriginKeyedPermissionActionServiceFactory() = default;
KeyedService*
OriginKeyedPermissionActionServiceFactory::BuildServiceInstanceFor(
content::BrowserContext* context) const {
return new permissions::OriginKeyedPermissionActionService();
}
} // namespace weblayer
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/permissions/origin_keyed_permission_action_service_factory.cc | C++ | unknown | 1,505 |
// 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.
#ifndef WEBLAYER_BROWSER_PERMISSIONS_ORIGIN_KEYED_PERMISSION_ACTION_SERVICE_FACTORY_H_
#define WEBLAYER_BROWSER_PERMISSIONS_ORIGIN_KEYED_PERMISSION_ACTION_SERVICE_FACTORY_H_
#include "base/no_destructor.h"
#include "components/keyed_service/content/browser_context_keyed_service_factory.h"
namespace permissions {
class OriginKeyedPermissionActionService;
} // namespace permissions
namespace weblayer {
// Factory to create a service to keep track of permission actions of the
// current browser session for metrics evaluation.
class OriginKeyedPermissionActionServiceFactory
: public BrowserContextKeyedServiceFactory {
public:
OriginKeyedPermissionActionServiceFactory(
const OriginKeyedPermissionActionServiceFactory&) = delete;
OriginKeyedPermissionActionServiceFactory& operator=(
const OriginKeyedPermissionActionServiceFactory&) = delete;
static permissions::OriginKeyedPermissionActionService* GetForBrowserContext(
content::BrowserContext* browser_context);
static OriginKeyedPermissionActionServiceFactory* GetInstance();
private:
friend class base::NoDestructor<OriginKeyedPermissionActionServiceFactory>;
OriginKeyedPermissionActionServiceFactory();
~OriginKeyedPermissionActionServiceFactory() override;
// BrowserContextKeyedServiceFactory:
KeyedService* BuildServiceInstanceFor(
content::BrowserContext* context) const override;
};
} // namespace weblayer
#endif // WEBLAYER_BROWSER_PERMISSIONS_ORIGIN_KEYED_PERMISSION_ACTION_SERVICE_FACTORY_H_
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/permissions/origin_keyed_permission_action_service_factory.h | C++ | unknown | 1,667 |
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "weblayer/browser/permissions/permission_decision_auto_blocker_factory.h"
#include "base/no_destructor.h"
#include "components/keyed_service/content/browser_context_dependency_manager.h"
#include "components/permissions/permission_decision_auto_blocker.h"
#include "weblayer/browser/host_content_settings_map_factory.h"
namespace weblayer {
// static
permissions::PermissionDecisionAutoBlocker*
PermissionDecisionAutoBlockerFactory::GetForBrowserContext(
content::BrowserContext* browser_context) {
return static_cast<permissions::PermissionDecisionAutoBlocker*>(
GetInstance()->GetServiceForBrowserContext(browser_context, true));
}
// static
PermissionDecisionAutoBlockerFactory*
PermissionDecisionAutoBlockerFactory::GetInstance() {
static base::NoDestructor<PermissionDecisionAutoBlockerFactory> factory;
return factory.get();
}
PermissionDecisionAutoBlockerFactory::PermissionDecisionAutoBlockerFactory()
: BrowserContextKeyedServiceFactory(
"PermissionDecisionAutoBlocker",
BrowserContextDependencyManager::GetInstance()) {
DependsOn(HostContentSettingsMapFactory::GetInstance());
}
PermissionDecisionAutoBlockerFactory::~PermissionDecisionAutoBlockerFactory() =
default;
KeyedService* PermissionDecisionAutoBlockerFactory::BuildServiceInstanceFor(
content::BrowserContext* context) const {
return new permissions::PermissionDecisionAutoBlocker(
HostContentSettingsMapFactory::GetForBrowserContext(context));
}
content::BrowserContext*
PermissionDecisionAutoBlockerFactory::GetBrowserContextToUse(
content::BrowserContext* context) const {
return context;
}
} // namespace weblayer
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/permissions/permission_decision_auto_blocker_factory.cc | C++ | unknown | 1,815 |
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef WEBLAYER_BROWSER_PERMISSIONS_PERMISSION_DECISION_AUTO_BLOCKER_FACTORY_H_
#define WEBLAYER_BROWSER_PERMISSIONS_PERMISSION_DECISION_AUTO_BLOCKER_FACTORY_H_
#include "base/no_destructor.h"
#include "components/keyed_service/content/browser_context_keyed_service_factory.h"
namespace permissions {
class PermissionDecisionAutoBlocker;
}
namespace weblayer {
class PermissionDecisionAutoBlockerFactory
: public BrowserContextKeyedServiceFactory {
public:
PermissionDecisionAutoBlockerFactory(
const PermissionDecisionAutoBlockerFactory&) = delete;
PermissionDecisionAutoBlockerFactory& operator=(
const PermissionDecisionAutoBlockerFactory&) = delete;
static permissions::PermissionDecisionAutoBlocker* GetForBrowserContext(
content::BrowserContext* browser_context);
static PermissionDecisionAutoBlockerFactory* GetInstance();
private:
friend class base::NoDestructor<PermissionDecisionAutoBlockerFactory>;
PermissionDecisionAutoBlockerFactory();
~PermissionDecisionAutoBlockerFactory() override;
// BrowserContextKeyedServiceFactory
KeyedService* BuildServiceInstanceFor(
content::BrowserContext* context) const override;
content::BrowserContext* GetBrowserContextToUse(
content::BrowserContext* context) const override;
};
} // namespace weblayer
#endif // WEBLAYER_BROWSER_PERMISSIONS_PERMISSION_DECISION_AUTO_BLOCKER_FACTORY_H_
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/permissions/permission_decision_auto_blocker_factory.h | C++ | unknown | 1,549 |
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "weblayer/browser/permissions/permission_manager_factory.h"
#include "base/no_destructor.h"
#include "build/build_config.h"
#include "components/background_sync/background_sync_permission_context.h"
#include "components/content_settings/core/common/content_settings_types.h"
#include "components/embedder_support/permission_context_utils.h"
#include "components/keyed_service/content/browser_context_dependency_manager.h"
#include "components/permissions/permission_context_base.h"
#include "components/permissions/permission_manager.h"
#include "components/permissions/permission_util.h"
#include "components/webrtc/media_stream_device_enumerator_impl.h"
#include "third_party/blink/public/common/permissions/permission_utils.h"
#include "third_party/blink/public/mojom/permissions_policy/permissions_policy_feature.mojom-shared.h"
#include "weblayer/browser/background_fetch/background_fetch_permission_context.h"
#include "weblayer/browser/host_content_settings_map_factory.h"
#include "weblayer/browser/permissions/geolocation_permission_context_delegate.h"
#include "weblayer/browser/permissions/weblayer_camera_pan_tilt_zoom_permission_context_delegate.h"
#include "weblayer/browser/permissions/weblayer_nfc_permission_context_delegate.h"
namespace weblayer {
namespace {
// Permission context which denies all requests.
class DeniedPermissionContext : public permissions::PermissionContextBase {
public:
using PermissionContextBase::PermissionContextBase;
protected:
ContentSetting GetPermissionStatusInternal(
content::RenderFrameHost* render_frame_host,
const GURL& requesting_origin,
const GURL& embedding_origin) const override {
return CONTENT_SETTING_BLOCK;
}
};
// A permission context with default behavior, which is restricted to secure
// origins.
class SafePermissionContext : public permissions::PermissionContextBase {
public:
using PermissionContextBase::PermissionContextBase;
SafePermissionContext(const SafePermissionContext&) = delete;
SafePermissionContext& operator=(const SafePermissionContext&) = delete;
};
// Used by the CameraPanTiltZoomPermissionContext to query which devices support
// that API.
// TODO(crbug.com/1219486): Move this elsewhere once we're using a custom
// implementation of MediaStreamDeviceEnumerator to expose this information to
// WebLayer embedders via an API.
webrtc::MediaStreamDeviceEnumerator* GetMediaStreamDeviceEnumerator() {
static base::NoDestructor<webrtc::MediaStreamDeviceEnumeratorImpl> instance;
return instance.get();
}
permissions::PermissionManager::PermissionContextMap CreatePermissionContexts(
content::BrowserContext* browser_context) {
embedder_support::PermissionContextDelegates delegates;
delegates.camera_pan_tilt_zoom_permission_context_delegate =
std::make_unique<WebLayerCameraPanTiltZoomPermissionContextDelegate>();
delegates.geolocation_permission_context_delegate =
std::make_unique<GeolocationPermissionContextDelegate>();
#if BUILDFLAG(IS_MAC) || BUILDFLAG(IS_CHROMEOS)
// TODO(crbug.com/1200933): macOS and ChromeOS uses
// GeolocationPermissionContextSystem which requires a GeolocationManager for
// construction. In Chrome this object is owned by the BrowserProcess. An
// equivalent object will need to be created in WebLayer and passed into the
// PermissionContextDelegates here before it supports macOS.
NOTREACHED();
#endif // BUILDFLAG(IS_MAC)
delegates.media_stream_device_enumerator = GetMediaStreamDeviceEnumerator();
delegates.nfc_permission_context_delegate =
std::make_unique<WebLayerNfcPermissionContextDelegate>();
// Create default permission contexts initially.
permissions::PermissionManager::PermissionContextMap permission_contexts =
embedder_support::CreateDefaultPermissionContexts(browser_context,
std::move(delegates));
// Add additional WebLayer specific permission contexts. Please add a comment
// when adding new contexts here explaining why it can't be shared with other
// Content embedders by adding it to CreateDefaultPermissionContexts().
// Similar to the Chrome implementation except we don't have access to the
// DownloadRequestLimiter in WebLayer.
permission_contexts[ContentSettingsType::BACKGROUND_FETCH] =
std::make_unique<BackgroundFetchPermissionContext>(browser_context);
// The Chrome implementation only checks for policies which we don't have in
// WebLayer.
permission_contexts[ContentSettingsType::MEDIASTREAM_CAMERA] =
std::make_unique<SafePermissionContext>(
browser_context, ContentSettingsType::MEDIASTREAM_CAMERA,
blink::mojom::PermissionsPolicyFeature::kCamera);
permission_contexts[ContentSettingsType::MEDIASTREAM_MIC] =
std::make_unique<SafePermissionContext>(
browser_context, ContentSettingsType::MEDIASTREAM_MIC,
blink::mojom::PermissionsPolicyFeature::kMicrophone);
#if BUILDFLAG(IS_ANDROID)
// The Chrome implementation has special cases for Chrome OS and Windows which
// we don't support yet. On Android this will match Chrome's behaviour.
permission_contexts[ContentSettingsType::PROTECTED_MEDIA_IDENTIFIER] =
std::make_unique<SafePermissionContext>(
browser_context, ContentSettingsType::PROTECTED_MEDIA_IDENTIFIER,
blink::mojom::PermissionsPolicyFeature::kEncryptedMedia);
#endif
// For now, all requests are denied. As features are added, their permission
// contexts can be added here instead of DeniedPermissionContext.
for (blink::PermissionType type : blink::GetAllPermissionTypes()) {
#if !BUILDFLAG(IS_ANDROID)
// PROTECTED_MEDIA_IDENTIFIER is only supported on Android.
if (type == blink::PermissionType::PROTECTED_MEDIA_IDENTIFIER)
continue;
#endif
ContentSettingsType content_settings_type =
permissions::PermissionUtil::PermissionTypeToContentSettingType(type);
if (permission_contexts.find(content_settings_type) ==
permission_contexts.end()) {
permission_contexts[content_settings_type] =
std::make_unique<DeniedPermissionContext>(
browser_context, content_settings_type,
blink::mojom::PermissionsPolicyFeature::kNotFound);
}
}
return permission_contexts;
}
} // namespace
// static
permissions::PermissionManager* PermissionManagerFactory::GetForBrowserContext(
content::BrowserContext* browser_context) {
return static_cast<permissions::PermissionManager*>(
GetInstance()->GetServiceForBrowserContext(browser_context, true));
}
// static
PermissionManagerFactory* PermissionManagerFactory::GetInstance() {
static base::NoDestructor<PermissionManagerFactory> factory;
return factory.get();
}
PermissionManagerFactory::PermissionManagerFactory()
: BrowserContextKeyedServiceFactory(
"PermissionManagerFactory",
BrowserContextDependencyManager::GetInstance()) {
DependsOn(HostContentSettingsMapFactory::GetInstance());
}
PermissionManagerFactory::~PermissionManagerFactory() = default;
KeyedService* PermissionManagerFactory::BuildServiceInstanceFor(
content::BrowserContext* context) const {
return new permissions::PermissionManager(context,
CreatePermissionContexts(context));
}
content::BrowserContext* PermissionManagerFactory::GetBrowserContextToUse(
content::BrowserContext* context) const {
return context;
}
} // namespace weblayer
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/permissions/permission_manager_factory.cc | C++ | unknown | 7,650 |
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef WEBLAYER_BROWSER_PERMISSIONS_PERMISSION_MANAGER_FACTORY_H_
#define WEBLAYER_BROWSER_PERMISSIONS_PERMISSION_MANAGER_FACTORY_H_
#include "base/no_destructor.h"
#include "components/keyed_service/content/browser_context_keyed_service_factory.h"
namespace permissions {
class PermissionManager;
}
namespace weblayer {
class PermissionManagerFactory : public BrowserContextKeyedServiceFactory {
public:
PermissionManagerFactory(const PermissionManagerFactory&) = delete;
PermissionManagerFactory& operator=(const PermissionManagerFactory&) = delete;
static permissions::PermissionManager* GetForBrowserContext(
content::BrowserContext* browser_context);
static PermissionManagerFactory* GetInstance();
private:
friend class base::NoDestructor<PermissionManagerFactory>;
PermissionManagerFactory();
~PermissionManagerFactory() override;
// BrowserContextKeyedServiceFactory methods:
KeyedService* BuildServiceInstanceFor(
content::BrowserContext* profile) const override;
content::BrowserContext* GetBrowserContextToUse(
content::BrowserContext* context) const override;
};
} // namespace weblayer
#endif // WEBLAYER_BROWSER_PERMISSIONS_PERMISSION_MANAGER_FACTORY_H_
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/permissions/permission_manager_factory.h | C++ | unknown | 1,365 |
// Copyright 2021 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "components/permissions/permissions_client.h"
#include "weblayer/browser/tab_impl.h"
#include "weblayer/public/navigation_controller.h"
#include "weblayer/public/tab.h"
#include "weblayer/shell/browser/shell.h"
#include "weblayer/test/weblayer_browser_test.h"
#include "weblayer/test/weblayer_browser_test_utils.h"
namespace weblayer {
class PermissionsBrowserTest : public WebLayerBrowserTest {
public:
void SetUpOnMainThread() override {
ASSERT_TRUE(embedded_test_server()->Start());
}
protected:
content::WebContents* GetWebContents() {
Tab* tab = shell()->tab();
TabImpl* tab_impl = static_cast<TabImpl*>(tab);
return tab_impl->web_contents();
}
GURL GetCurrentDisplayURL() {
auto* navigation_controller = shell()->tab()->GetNavigationController();
return navigation_controller->GetNavigationEntryDisplayURL(
navigation_controller->GetNavigationListCurrentIndex());
}
};
IN_PROC_BROWSER_TEST_F(PermissionsBrowserTest, SubresourceFilterActivation) {
NavigateAndWaitForCompletion(GURL("about:blank"), shell());
EXPECT_FALSE(
permissions::PermissionsClient::Get()->IsSubresourceFilterActivated(
GetWebContents()->GetBrowserContext(), GetCurrentDisplayURL()));
GURL test_url(embedded_test_server()->GetURL("/simple_page.html"));
ActivateSubresourceFilterInWebContentsForURL(GetWebContents(), test_url);
NavigateAndWaitForCompletion(test_url, shell());
EXPECT_TRUE(
permissions::PermissionsClient::Get()->IsSubresourceFilterActivated(
GetWebContents()->GetBrowserContext(), GetCurrentDisplayURL()));
}
} // namespace weblayer
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/permissions/permissions_browsertest.cc | C++ | unknown | 1,777 |
// Copyright 2021 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "weblayer/browser/permissions/weblayer_camera_pan_tilt_zoom_permission_context_delegate.h"
#include "build/build_config.h"
namespace weblayer {
WebLayerCameraPanTiltZoomPermissionContextDelegate::
WebLayerCameraPanTiltZoomPermissionContextDelegate() = default;
WebLayerCameraPanTiltZoomPermissionContextDelegate::
~WebLayerCameraPanTiltZoomPermissionContextDelegate() = default;
bool WebLayerCameraPanTiltZoomPermissionContextDelegate::
GetPermissionStatusInternal(const GURL& requesting_origin,
const GURL& embedding_origin,
ContentSetting* content_setting_result) {
#if BUILDFLAG(IS_ANDROID)
// The PTZ permission is automatically granted on Android. It is safe to do so
// because pan and tilt are not supported on Android.
*content_setting_result = CONTENT_SETTING_ALLOW;
return true;
#else
return false;
#endif
}
} // namespace weblayer
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/permissions/weblayer_camera_pan_tilt_zoom_permission_context_delegate.cc | C++ | unknown | 1,088 |
// Copyright 2021 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef WEBLAYER_BROWSER_PERMISSIONS_WEBLAYER_CAMERA_PAN_TILT_ZOOM_PERMISSION_CONTEXT_DELEGATE_H_
#define WEBLAYER_BROWSER_PERMISSIONS_WEBLAYER_CAMERA_PAN_TILT_ZOOM_PERMISSION_CONTEXT_DELEGATE_H_
#include "components/permissions/contexts/camera_pan_tilt_zoom_permission_context.h"
namespace weblayer {
class WebLayerCameraPanTiltZoomPermissionContextDelegate
: public permissions::CameraPanTiltZoomPermissionContext::Delegate {
public:
WebLayerCameraPanTiltZoomPermissionContextDelegate();
WebLayerCameraPanTiltZoomPermissionContextDelegate(
const WebLayerCameraPanTiltZoomPermissionContextDelegate&) = delete;
WebLayerCameraPanTiltZoomPermissionContextDelegate& operator=(
const WebLayerCameraPanTiltZoomPermissionContextDelegate&) = delete;
~WebLayerCameraPanTiltZoomPermissionContextDelegate() override;
// CameraPanTiltZoomPermissionContext::Delegate:
bool GetPermissionStatusInternal(
const GURL& requesting_origin,
const GURL& embedding_origin,
ContentSetting* content_setting_result) override;
};
} // namespace weblayer
#endif // WEBLAYER_BROWSER_PERMISSIONS_WEBLAYER_CAMERA_PAN_TILT_ZOOM_PERMISSION_CONTEXT_DELEGATE_H_ | Zhao-PengFei35/chromium_src_4 | weblayer/browser/permissions/weblayer_camera_pan_tilt_zoom_permission_context_delegate.h | C++ | unknown | 1,328 |
// Copyright 2021 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "weblayer/browser/permissions/weblayer_nfc_permission_context_delegate.h"
#include "build/build_config.h"
#if BUILDFLAG(IS_ANDROID)
#include "weblayer/browser/tab_impl.h"
#endif
namespace weblayer {
WebLayerNfcPermissionContextDelegate::WebLayerNfcPermissionContextDelegate() =
default;
WebLayerNfcPermissionContextDelegate::~WebLayerNfcPermissionContextDelegate() =
default;
#if BUILDFLAG(IS_ANDROID)
bool WebLayerNfcPermissionContextDelegate::IsInteractable(
content::WebContents* web_contents) {
auto* tab = TabImpl::FromWebContents(web_contents);
return tab && tab->IsActive();
}
#endif
} // namespace weblayer
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/permissions/weblayer_nfc_permission_context_delegate.cc | C++ | unknown | 792 |
// Copyright 2021 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef WEBLAYER_BROWSER_PERMISSIONS_WEBLAYER_NFC_PERMISSION_CONTEXT_DELEGATE_H_
#define WEBLAYER_BROWSER_PERMISSIONS_WEBLAYER_NFC_PERMISSION_CONTEXT_DELEGATE_H_
#include "build/build_config.h"
#include "components/permissions/contexts/nfc_permission_context.h"
namespace weblayer {
class WebLayerNfcPermissionContextDelegate
: public permissions::NfcPermissionContext::Delegate {
public:
WebLayerNfcPermissionContextDelegate();
WebLayerNfcPermissionContextDelegate(
const WebLayerNfcPermissionContextDelegate&) = delete;
WebLayerNfcPermissionContextDelegate& operator=(
const WebLayerNfcPermissionContextDelegate&) = delete;
~WebLayerNfcPermissionContextDelegate() override;
// NfcPermissionContext::Delegate:
#if BUILDFLAG(IS_ANDROID)
bool IsInteractable(content::WebContents* web_contents) override;
#endif
};
} // namespace weblayer
#endif // WEBLAYER_BROWSER_PERMISSIONS_WEBLAYER_NFC_PERMISSION_CONTEXT_DELEGATE_H_ | Zhao-PengFei35/chromium_src_4 | weblayer/browser/permissions/weblayer_nfc_permission_context_delegate.h | C++ | unknown | 1,102 |
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "weblayer/browser/permissions/weblayer_permissions_client.h"
#include "base/no_destructor.h"
#include "build/build_config.h"
#include "components/content_settings/core/browser/cookie_settings.h"
#include "components/subresource_filter/content/browser/subresource_filter_content_settings_manager.h"
#include "components/subresource_filter/content/browser/subresource_filter_profile_context.h"
#include "weblayer/browser/cookie_settings_factory.h"
#include "weblayer/browser/host_content_settings_map_factory.h"
#include "weblayer/browser/permissions/origin_keyed_permission_action_service_factory.h"
#include "weblayer/browser/permissions/permission_decision_auto_blocker_factory.h"
#include "weblayer/browser/subresource_filter_profile_context_factory.h"
#if BUILDFLAG(IS_ANDROID)
#include "weblayer/browser/android/permission_request_utils.h"
#include "weblayer/browser/android/resource_mapper.h"
#endif
namespace weblayer {
// static
WebLayerPermissionsClient* WebLayerPermissionsClient::GetInstance() {
static base::NoDestructor<WebLayerPermissionsClient> instance;
return instance.get();
}
HostContentSettingsMap* WebLayerPermissionsClient::GetSettingsMap(
content::BrowserContext* browser_context) {
return HostContentSettingsMapFactory::GetForBrowserContext(browser_context);
}
scoped_refptr<content_settings::CookieSettings>
WebLayerPermissionsClient::GetCookieSettings(
content::BrowserContext* browser_context) {
return CookieSettingsFactory::GetForBrowserContext(browser_context);
}
bool WebLayerPermissionsClient::IsSubresourceFilterActivated(
content::BrowserContext* browser_context,
const GURL& url) {
return SubresourceFilterProfileContextFactory::GetForBrowserContext(
browser_context)
->settings_manager()
->GetSiteActivationFromMetadata(url);
}
permissions::OriginKeyedPermissionActionService*
WebLayerPermissionsClient::GetOriginKeyedPermissionActionService(
content::BrowserContext* browser_context) {
return OriginKeyedPermissionActionServiceFactory::GetForBrowserContext(
browser_context);
}
permissions::PermissionDecisionAutoBlocker*
WebLayerPermissionsClient::GetPermissionDecisionAutoBlocker(
content::BrowserContext* browser_context) {
return PermissionDecisionAutoBlockerFactory::GetForBrowserContext(
browser_context);
}
// PermissionActionsHistory would never be read in WebLayer, so it seems logical
// not to have the service at all.
permissions::PermissionActionsHistory*
WebLayerPermissionsClient::GetPermissionActionsHistory(
content::BrowserContext* browser_context) {
return nullptr;
}
permissions::ObjectPermissionContextBase*
WebLayerPermissionsClient::GetChooserContext(
content::BrowserContext* browser_context,
ContentSettingsType type) {
return nullptr;
}
#if BUILDFLAG(IS_ANDROID)
void WebLayerPermissionsClient::RepromptForAndroidPermissions(
content::WebContents* web_contents,
const std::vector<ContentSettingsType>& content_settings_types,
const std::vector<ContentSettingsType>& filtered_content_settings_types,
const std::vector<std::string>& required_permissions,
const std::vector<std::string>& optional_permissions,
PermissionsUpdatedCallback callback) {
RequestAndroidPermissions(web_contents, content_settings_types,
std::move(callback));
}
int WebLayerPermissionsClient::MapToJavaDrawableId(int resource_id) {
return weblayer::MapToJavaDrawableId(resource_id);
}
#endif
} // namespace weblayer
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/permissions/weblayer_permissions_client.cc | C++ | unknown | 3,665 |
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef WEBLAYER_BROWSER_PERMISSIONS_WEBLAYER_PERMISSIONS_CLIENT_H_
#define WEBLAYER_BROWSER_PERMISSIONS_WEBLAYER_PERMISSIONS_CLIENT_H_
#include "base/no_destructor.h"
#include "build/build_config.h"
#include "components/permissions/permissions_client.h"
namespace weblayer {
class WebLayerPermissionsClient : public permissions::PermissionsClient {
public:
WebLayerPermissionsClient(const WebLayerPermissionsClient&) = delete;
WebLayerPermissionsClient& operator=(const WebLayerPermissionsClient&) =
delete;
static WebLayerPermissionsClient* GetInstance();
// PermissionsClient:
HostContentSettingsMap* GetSettingsMap(
content::BrowserContext* browser_context) override;
scoped_refptr<content_settings::CookieSettings> GetCookieSettings(
content::BrowserContext* browser_context) override;
bool IsSubresourceFilterActivated(content::BrowserContext* browser_context,
const GURL& url) override;
permissions::OriginKeyedPermissionActionService*
GetOriginKeyedPermissionActionService(
content::BrowserContext* browser_context) override;
permissions::PermissionActionsHistory* GetPermissionActionsHistory(
content::BrowserContext* browser_context) override;
permissions::PermissionDecisionAutoBlocker* GetPermissionDecisionAutoBlocker(
content::BrowserContext* browser_context) override;
permissions::ObjectPermissionContextBase* GetChooserContext(
content::BrowserContext* browser_context,
ContentSettingsType type) override;
#if BUILDFLAG(IS_ANDROID)
void RepromptForAndroidPermissions(
content::WebContents* web_contents,
const std::vector<ContentSettingsType>& content_settings_types,
const std::vector<ContentSettingsType>& filtered_content_settings_types,
const std::vector<std::string>& required_permissions,
const std::vector<std::string>& optional_permissions,
PermissionsUpdatedCallback callback) override;
int MapToJavaDrawableId(int resource_id) override;
#endif
private:
friend base::NoDestructor<WebLayerPermissionsClient>;
WebLayerPermissionsClient() = default;
};
} // namespace weblayer
#endif // WEBLAYER_BROWSER_PERMISSIONS_WEBLAYER_PERMISSIONS_CLIENT_H_
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/permissions/weblayer_permissions_client.h | C++ | unknown | 2,379 |
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "weblayer/browser/persistence/browser_persistence_common.h"
#include "components/sessions/content/content_serialized_navigation_builder.h"
#include "components/sessions/content/session_tab_helper.h"
#include "components/sessions/core/session_command.h"
#include "components/sessions/core/session_service_commands.h"
#include "components/sessions/core/session_types.h"
#include "content/public/browser/browser_url_handler.h"
#include "content/public/browser/dom_storage_context.h"
#include "content/public/browser/navigation_entry.h"
#include "content/public/browser/storage_partition.h"
#include "weblayer/browser/browser_context_impl.h"
#include "weblayer/browser/browser_impl.h"
#include "weblayer/browser/profile_impl.h"
#include "weblayer/browser/tab_impl.h"
namespace weblayer {
namespace {
void ProcessRestoreCommands(
BrowserImpl* browser,
const std::vector<std::unique_ptr<sessions::SessionWindow>>& windows) {
if (windows.empty() || windows[0]->tabs.empty())
return;
const bool had_tabs = !browser->GetTabs().empty();
content::BrowserContext* browser_context =
browser->profile()->GetBrowserContext();
for (int i = 0; i < static_cast<int>(windows[0]->tabs.size()); ++i) {
const sessions::SessionTab& session_tab = *(windows[0]->tabs[i]);
if (session_tab.navigations.empty())
continue;
// Associate sessionStorage (if any) to the restored tab.
scoped_refptr<content::SessionStorageNamespace> session_storage_namespace;
if (!session_tab.session_storage_persistent_id.empty()) {
session_storage_namespace =
browser_context->GetDefaultStoragePartition()
->GetDOMStorageContext()
->RecreateSessionStorage(
session_tab.session_storage_persistent_id);
}
const int selected_navigation_index =
session_tab.normalized_navigation_index();
GURL restore_url =
session_tab.navigations[selected_navigation_index].virtual_url();
content::SessionStorageNamespaceMap session_storage_namespace_map =
content::CreateMapWithDefaultSessionStorageNamespace(
browser_context, session_storage_namespace);
content::BrowserURLHandler::GetInstance()->RewriteURLIfNecessary(
&restore_url, browser_context);
content::WebContents::CreateParams create_params(
browser_context,
content::SiteInstance::ShouldAssignSiteForURL(restore_url)
? content::SiteInstance::CreateForURL(browser_context, restore_url)
: nullptr);
create_params.initially_hidden = true;
create_params.desired_renderer_state =
content::WebContents::CreateParams::kNoRendererProcess;
create_params.last_active_time = session_tab.last_active_time;
std::unique_ptr<content::WebContents> web_contents =
content::WebContents::CreateWithSessionStorage(
create_params, session_storage_namespace_map);
std::vector<std::unique_ptr<content::NavigationEntry>> entries =
sessions::ContentSerializedNavigationBuilder::ToNavigationEntries(
session_tab.navigations, browser_context);
blink::UserAgentOverride ua_override;
ua_override.ua_string_override =
session_tab.user_agent_override.ua_string_override;
ua_override.ua_metadata_override = blink::UserAgentMetadata::Demarshal(
session_tab.user_agent_override.opaque_ua_metadata_override);
web_contents->SetUserAgentOverride(ua_override, false);
web_contents->GetController().Restore(
selected_navigation_index, content::RestoreType::kRestored, &entries);
DCHECK(entries.empty());
TabImpl* tab = browser->CreateTabForSessionRestore(std::move(web_contents),
session_tab.guid);
tab->SetData(session_tab.data);
if (!had_tabs && i == (windows[0])->selected_tab_index)
browser->SetActiveTab(tab);
}
if (!had_tabs && !browser->GetTabs().empty() && !browser->GetActiveTab())
browser->SetActiveTab(browser->GetTabs().back());
}
} // namespace
void RestoreBrowserState(
BrowserImpl* browser,
std::vector<std::unique_ptr<sessions::SessionCommand>> commands) {
std::vector<std::unique_ptr<sessions::SessionWindow>> windows;
SessionID active_window_id = SessionID::InvalidValue();
sessions::RestoreSessionFromCommands(commands, &windows, &active_window_id);
ProcessRestoreCommands(browser, windows);
if (browser->GetTabs().empty()) {
// Nothing to restore, or restore failed. Create a default tab.
browser->SetActiveTab(
browser->CreateTabForSessionRestore(nullptr, std::string()));
}
}
std::vector<std::unique_ptr<sessions::SessionCommand>>
BuildCommandsForTabConfiguration(SessionID browser_session_id,
TabImpl* tab,
int index_in_browser) {
DCHECK(tab);
std::vector<std::unique_ptr<sessions::SessionCommand>> result;
const SessionID tab_id = GetSessionIDForTab(tab);
result.push_back(
sessions::CreateSetTabWindowCommand(browser_session_id, tab_id));
result.push_back(sessions::CreateLastActiveTimeCommand(
tab_id, tab->web_contents()->GetLastActiveTime()));
const blink::UserAgentOverride& ua_override =
tab->web_contents()->GetUserAgentOverride();
if (!ua_override.ua_string_override.empty()) {
sessions::SerializedUserAgentOverride serialized_override;
serialized_override.ua_string_override = ua_override.ua_string_override;
serialized_override.opaque_ua_metadata_override =
blink::UserAgentMetadata::Marshal(ua_override.ua_metadata_override);
result.push_back(sessions::CreateSetTabUserAgentOverrideCommand(
tab_id, serialized_override));
}
if (index_in_browser != -1) {
result.push_back(
sessions::CreateSetTabIndexInWindowCommand(tab_id, index_in_browser));
}
result.push_back(sessions::CreateSetSelectedNavigationIndexCommand(
tab_id, tab->web_contents()->GetController().GetCurrentEntryIndex()));
result.push_back(sessions::CreateSetTabGuidCommand(tab_id, tab->GetGuid()));
result.push_back(sessions::CreateSetTabDataCommand(tab_id, tab->GetData()));
return result;
}
SessionID GetSessionIDForTab(Tab* tab) {
sessions::SessionTabHelper* session_tab_helper =
sessions::SessionTabHelper::FromWebContents(
static_cast<TabImpl*>(tab)->web_contents());
DCHECK(session_tab_helper);
return session_tab_helper->session_id();
}
} // namespace weblayer
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/persistence/browser_persistence_common.cc | C++ | unknown | 6,637 |
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef WEBLAYER_BROWSER_PERSISTENCE_BROWSER_PERSISTENCE_COMMON_H_
#define WEBLAYER_BROWSER_PERSISTENCE_BROWSER_PERSISTENCE_COMMON_H_
#include <memory>
#include <vector>
class SessionID;
namespace sessions {
class SessionCommand;
}
// Common functions used in persisting/restoring the state (tabs, navigations)
// of a Browser.
namespace weblayer {
class BrowserImpl;
class Tab;
class TabImpl;
// Restores browser state from |commands|. This ensures |browser| contains at
// least one tab when done.
void RestoreBrowserState(
BrowserImpl* browser,
std::vector<std::unique_ptr<sessions::SessionCommand>> commands);
// Creates and returns the minimal set of SessionCommands to configure a tab.
// This does not include any navigations.
std::vector<std::unique_ptr<sessions::SessionCommand>>
BuildCommandsForTabConfiguration(SessionID browser_session_id,
TabImpl* tab,
int index_in_browser);
// Convenience to return the SessionID for a Tab.
SessionID GetSessionIDForTab(Tab* tab);
} // namespace weblayer
#endif // WEBLAYER_BROWSER_PERSISTENCE_BROWSER_PERSISTENCE_COMMON_H_
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/persistence/browser_persistence_common.h | C++ | unknown | 1,302 |
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "weblayer/browser/persistence/browser_persister.h"
#include <stddef.h>
#include <utility>
#include <vector>
#include "base/functional/bind.h"
#include "base/ranges/algorithm.h"
#include "components/sessions/content/content_serialized_navigation_builder.h"
#include "components/sessions/content/session_tab_helper.h"
#include "components/sessions/core/command_storage_manager.h"
#include "components/sessions/core/session_command.h"
#include "components/sessions/core/session_constants.h"
#include "components/sessions/core/session_id.h"
#include "components/sessions/core/session_types.h"
#include "content/public/browser/navigation_details.h"
#include "content/public/browser/navigation_entry.h"
#include "content/public/browser/restore_type.h"
#include "content/public/browser/session_storage_namespace.h"
#include "content/public/browser/storage_partition.h"
#include "content/public/browser/web_contents.h"
#include "weblayer/browser/browser_context_impl.h"
#include "weblayer/browser/browser_impl.h"
#include "weblayer/browser/persistence/browser_persistence_common.h"
#include "weblayer/browser/profile_impl.h"
#include "weblayer/browser/tab_impl.h"
using sessions::ContentSerializedNavigationBuilder;
using sessions::SerializedNavigationEntry;
namespace weblayer {
namespace {
int GetIndexOfTab(BrowserImpl* browser, Tab* tab) {
const std::vector<Tab*>& tabs = browser->GetTabs();
auto iter = base::ranges::find(tabs, tab);
DCHECK(iter != tabs.end());
return static_cast<int>(iter - tabs.begin());
}
} // namespace
// Every kWritesPerReset commands triggers recreating the file.
constexpr int kWritesPerReset = 250;
// BrowserPersister
// -------------------------------------------------------------
BrowserPersister::BrowserPersister(const base::FilePath& path,
BrowserImpl* browser)
: browser_(browser),
browser_session_id_(SessionID::NewUnique()),
command_storage_manager_(
std::make_unique<sessions::CommandStorageManager>(
sessions::CommandStorageManager::kOther,
path,
this,
browser->profile()->GetBrowserContext()->IsOffTheRecord(),
std::vector<uint8_t>(0))),
rebuild_on_next_save_(false) {
browser_->AddObserver(this);
command_storage_manager_->GetLastSessionCommands(base::BindOnce(
&BrowserPersister::OnGotLastSessionCommands, weak_factory_.GetWeakPtr()));
}
BrowserPersister::~BrowserPersister() {
SaveIfNecessary();
browser_->RemoveObserver(this);
}
void BrowserPersister::SaveIfNecessary() {
if (command_storage_manager_->HasPendingSave())
command_storage_manager_->Save();
}
bool BrowserPersister::ShouldUseDelayedSave() {
return true;
}
void BrowserPersister::OnWillSaveCommands() {
if (!rebuild_on_next_save_)
return;
rebuild_on_next_save_ = false;
command_storage_manager_->set_pending_reset(true);
command_storage_manager_->ClearPendingCommands();
tab_to_available_range_.clear();
BuildCommandsForBrowser();
}
void BrowserPersister::OnErrorWritingSessionCommands() {
rebuild_on_next_save_ = true;
command_storage_manager_->StartSaveTimer();
}
void BrowserPersister::OnTabAdded(Tab* tab) {
auto* tab_impl = static_cast<TabImpl*>(tab);
data_observations_.AddObservation(tab_impl);
content::WebContents* web_contents = tab_impl->web_contents();
auto* tab_helper = sessions::SessionTabHelper::FromWebContents(web_contents);
DCHECK(tab_helper);
tab_helper->SetWindowID(browser_session_id_);
// Record the association between the SessionStorageNamespace and the
// tab.
content::SessionStorageNamespace* session_storage_namespace =
web_contents->GetController().GetDefaultSessionStorageNamespace();
session_storage_namespace->SetShouldPersist(true);
if (rebuild_on_next_save_)
return;
int index = GetIndexOfTab(browser_, tab);
BuildCommandsForTab(static_cast<TabImpl*>(tab), index);
const std::vector<Tab*>& tabs = browser_->GetTabs();
for (int i = index + 1; i < static_cast<int>(tabs.size()); ++i) {
ScheduleCommand(sessions::CreateSetTabIndexInWindowCommand(
GetSessionIDForTab(tabs[i]), i));
}
}
void BrowserPersister::OnTabRemoved(Tab* tab, bool active_tab_changed) {
auto* tab_impl = static_cast<TabImpl*>(tab);
data_observations_.RemoveObservation(tab_impl);
// Allow the associated sessionStorage to get deleted; it won't be needed
// in the session restore.
content::WebContents* web_contents = tab_impl->web_contents();
content::SessionStorageNamespace* session_storage_namespace =
web_contents->GetController().GetDefaultSessionStorageNamespace();
session_storage_namespace->SetShouldPersist(false);
if (rebuild_on_next_save_)
return;
ScheduleCommand(sessions::CreateTabClosedCommand(GetSessionIDForTab(tab)));
const std::vector<Tab*>& tabs = browser_->GetTabs();
for (size_t i = 0; i < tabs.size(); ++i) {
ScheduleCommand(sessions::CreateSetTabIndexInWindowCommand(
GetSessionIDForTab(tabs[i]), i));
}
auto i = tab_to_available_range_.find(GetSessionIDForTab(tab));
if (i != tab_to_available_range_.end())
tab_to_available_range_.erase(i);
}
void BrowserPersister::OnActiveTabChanged(Tab* tab) {
if (rebuild_on_next_save_)
return;
const int index = tab == nullptr ? -1 : GetIndexOfTab(browser_, tab);
ScheduleCommand(sessions::CreateSetSelectedTabInWindowCommand(
browser_session_id_, index));
}
void BrowserPersister::OnDataChanged(
TabImpl* tab,
const std::map<std::string, std::string>& data) {
if (rebuild_on_next_save_)
return;
ScheduleCommand(
sessions::CreateSetTabDataCommand(GetSessionIDForTab(tab), data));
}
void BrowserPersister::SetTabUserAgentOverride(
SessionID window_id,
SessionID tab_id,
const sessions::SerializedUserAgentOverride& user_agent_override) {
if (rebuild_on_next_save_)
return;
ScheduleCommand(sessions::CreateSetTabUserAgentOverrideCommand(
tab_id, user_agent_override));
}
void BrowserPersister::SetSelectedNavigationIndex(SessionID window_id,
SessionID tab_id,
int index) {
if (rebuild_on_next_save_)
return;
if (tab_to_available_range_.find(tab_id) != tab_to_available_range_.end()) {
if (index < tab_to_available_range_[tab_id].first ||
index > tab_to_available_range_[tab_id].second) {
// The new index is outside the range of what we've archived, schedule
// a reset.
ScheduleRebuildOnNextSave();
return;
}
}
ScheduleCommand(
sessions::CreateSetSelectedNavigationIndexCommand(tab_id, index));
}
void BrowserPersister::UpdateTabNavigation(
SessionID window_id,
SessionID tab_id,
const SerializedNavigationEntry& navigation) {
if (rebuild_on_next_save_)
return;
if (tab_to_available_range_.find(tab_id) != tab_to_available_range_.end()) {
std::pair<int, int>& range = tab_to_available_range_[tab_id];
range.first = std::min(navigation.index(), range.first);
range.second = std::max(navigation.index(), range.second);
}
ScheduleCommand(CreateUpdateTabNavigationCommand(tab_id, navigation));
}
void BrowserPersister::TabNavigationPathPruned(SessionID window_id,
SessionID tab_id,
int index,
int count) {
if (rebuild_on_next_save_)
return;
DCHECK_GE(index, 0);
DCHECK_GT(count, 0);
// Update the range of available indices.
if (tab_to_available_range_.find(tab_id) != tab_to_available_range_.end()) {
std::pair<int, int>& range = tab_to_available_range_[tab_id];
// if both range.first and range.second are also deleted.
if (range.second >= index && range.second < index + count &&
range.first >= index && range.first < index + count) {
range.first = range.second = 0;
} else {
// Update range.first
if (range.first >= index + count)
range.first = range.first - count;
else if (range.first >= index && range.first < index + count)
range.first = index;
// Update range.second
if (range.second >= index + count)
range.second = std::max(range.first, range.second - count);
else if (range.second >= index && range.second < index + count)
range.second = std::max(range.first, index - 1);
}
}
return ScheduleCommand(
sessions::CreateTabNavigationPathPrunedCommand(tab_id, index, count));
}
void BrowserPersister::TabNavigationPathEntriesDeleted(SessionID window_id,
SessionID tab_id) {
if (rebuild_on_next_save_)
return;
// Multiple tabs might be affected by this deletion, so the rebuild is
// delayed until next save.
rebuild_on_next_save_ = true;
command_storage_manager_->StartSaveTimer();
}
void BrowserPersister::ScheduleRebuildOnNextSave() {
rebuild_on_next_save_ = true;
command_storage_manager_->StartSaveTimer();
}
void BrowserPersister::OnGotLastSessionCommands(
std::vector<std::unique_ptr<sessions::SessionCommand>> commands,
bool read_error) {
ScheduleRebuildOnNextSave();
RestoreBrowserState(browser_, std::move(commands));
is_restore_in_progress_ = false;
browser_->OnRestoreCompleted();
}
void BrowserPersister::BuildCommandsForTab(TabImpl* tab, int index_in_browser) {
command_storage_manager_->AppendRebuildCommands(
BuildCommandsForTabConfiguration(browser_session_id_, tab,
index_in_browser));
const SessionID session_id = GetSessionIDForTab(tab);
content::NavigationController& controller =
tab->web_contents()->GetController();
// Ensure that we don't try to persist initial NavigationEntry, as it is
// not actually associated with any navigation and will just result in
// about:blank on session restore.
bool is_on_initial_entry = (tab->web_contents()
->GetController()
.GetLastCommittedEntry()
->IsInitialEntry());
const int current_index =
is_on_initial_entry ? -1 : controller.GetCurrentEntryIndex();
const int min_index =
std::max(current_index - sessions::gMaxPersistNavigationCount, 0);
const int max_index =
std::min(current_index + sessions::gMaxPersistNavigationCount,
controller.GetEntryCount());
const int pending_index = controller.GetPendingEntryIndex();
tab_to_available_range_[session_id] =
std::pair<int, int>(min_index, max_index);
for (int i = min_index; i < max_index; ++i) {
content::NavigationEntry* entry = (i == pending_index)
? controller.GetPendingEntry()
: controller.GetEntryAtIndex(i);
DCHECK(entry);
if (entry->IsInitialEntry())
continue;
const SerializedNavigationEntry navigation =
ContentSerializedNavigationBuilder::FromNavigationEntry(i, entry);
command_storage_manager_->AppendRebuildCommand(
CreateUpdateTabNavigationCommand(session_id, navigation));
}
command_storage_manager_->AppendRebuildCommand(
sessions::CreateSetSelectedNavigationIndexCommand(session_id,
current_index));
// Record the association between the sessionStorage namespace and the tab.
content::SessionStorageNamespace* session_storage_namespace =
controller.GetDefaultSessionStorageNamespace();
ScheduleCommand(sessions::CreateSessionStorageAssociatedCommand(
session_id, session_storage_namespace->id()));
}
void BrowserPersister::BuildCommandsForBrowser() {
// This is necessary for BrowserPersister to restore the browser. The type is
// effectively ignored.
command_storage_manager_->AppendRebuildCommand(
sessions::CreateSetWindowTypeCommand(
browser_session_id_,
sessions::SessionWindow::WindowType::TYPE_NORMAL));
int active_index = -1;
int tab_index = 0;
for (Tab* tab : browser_->GetTabs()) {
BuildCommandsForTab(static_cast<TabImpl*>(tab), tab_index);
if (tab == browser_->GetActiveTab())
active_index = tab_index;
++tab_index;
}
command_storage_manager_->AppendRebuildCommand(
sessions::CreateSetSelectedTabInWindowCommand(browser_session_id_,
active_index));
}
void BrowserPersister::ScheduleCommand(
std::unique_ptr<sessions::SessionCommand> command) {
DCHECK(command);
if (ReplacePendingCommand(command_storage_manager_.get(), &command))
return;
command_storage_manager_->ScheduleCommand(std::move(command));
if (command_storage_manager_->commands_since_reset() >= kWritesPerReset)
ScheduleRebuildOnNextSave();
}
} // namespace weblayer
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/persistence/browser_persister.cc | C++ | unknown | 13,127 |
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef WEBLAYER_BROWSER_PERSISTENCE_BROWSER_PERSISTER_H_
#define WEBLAYER_BROWSER_PERSISTENCE_BROWSER_PERSISTER_H_
#include <stddef.h>
#include <map>
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include "base/memory/raw_ptr.h"
#include "base/memory/weak_ptr.h"
#include "base/scoped_multi_source_observation.h"
#include "components/sessions/content/session_tab_helper_delegate.h"
#include "components/sessions/core/command_storage_manager_delegate.h"
#include "components/sessions/core/session_service_commands.h"
#include "weblayer/browser/tab_impl.h"
#include "weblayer/public/browser_observer.h"
class SessionID;
namespace sessions {
class SessionCommand;
}
namespace weblayer {
class BrowserImpl;
// BrowserPersister is responsible for maintaining the state of tabs in a
// single Browser so that they can be restored at a later date. The state is
// written to a file. To avoid having to write the complete state anytime
// something changes interesting events (represented as SessionCommands) are
// written to disk. To restore, the events are read back and the state
// recreated. At certain times the file is truncated and rebuilt from the
// current state.
class BrowserPersister : public sessions::CommandStorageManagerDelegate,
public sessions::SessionTabHelperDelegate,
public BrowserObserver,
public TabImpl::DataObserver {
public:
BrowserPersister(const base::FilePath& path, BrowserImpl* browser);
BrowserPersister(const BrowserPersister&) = delete;
BrowserPersister& operator=(const BrowserPersister&) = delete;
~BrowserPersister() override;
bool is_restore_in_progress() const { return is_restore_in_progress_; }
void SaveIfNecessary();
private:
friend class BrowserPersisterTestHelper;
using IdToRange = std::map<SessionID, std::pair<int, int>>;
// CommandStorageManagerDelegate:
bool ShouldUseDelayedSave() override;
void OnWillSaveCommands() override;
void OnErrorWritingSessionCommands() override;
// BrowserObserver;
void OnTabAdded(Tab* tab) override;
void OnTabRemoved(Tab* tab, bool active_tab_changed) override;
void OnActiveTabChanged(Tab* tab) override;
// TabImpl::DataObserver:
void OnDataChanged(TabImpl* tab,
const std::map<std::string, std::string>& data) override;
// sessions::SessionTabHelperDelegate:
void SetTabUserAgentOverride(SessionID window_id,
SessionID tab_id,
const sessions::SerializedUserAgentOverride&
user_agent_override) override;
void SetSelectedNavigationIndex(SessionID window_id,
SessionID tab_id,
int index) override;
void UpdateTabNavigation(
SessionID window_id,
SessionID tab_id,
const sessions::SerializedNavigationEntry& navigation) override;
void TabNavigationPathPruned(SessionID window_id,
SessionID tab_id,
int index,
int count) override;
void TabNavigationPathEntriesDeleted(SessionID window_id,
SessionID tab_id) override;
// Schedules recreating the file on the next save.
void ScheduleRebuildOnNextSave();
// Called with the contents of the previous session.
void OnGotLastSessionCommands(
std::vector<std::unique_ptr<sessions::SessionCommand>> commands,
bool read_error);
// Schedules commands to recreate the state of the specified tab.
void BuildCommandsForTab(TabImpl* tab, int index_in_window);
// Schedules commands to recreate the state of |browser_|.
void BuildCommandsForBrowser();
// Schedules the specified command.
void ScheduleCommand(std::unique_ptr<sessions::SessionCommand> command);
void ProcessRestoreCommands(
const std::vector<std::unique_ptr<sessions::SessionWindow>>& windows);
raw_ptr<BrowserImpl> browser_;
// ID used for the browser. The sessions code requires each tab to be
// associated with a browser.
const SessionID browser_session_id_;
std::unique_ptr<sessions::CommandStorageManager> command_storage_manager_;
// Maps from session tab id to the range of navigation entries that has
// been written to disk.
IdToRange tab_to_available_range_;
// Force session commands to be rebuild before next save event.
bool rebuild_on_next_save_;
base::ScopedMultiSourceObservation<TabImpl, TabImpl::DataObserver>
data_observations_{this};
// True while asynchronously reading the state to restore.
bool is_restore_in_progress_ = true;
base::WeakPtrFactory<BrowserPersister> weak_factory_{this};
};
} // namespace weblayer
#endif // WEBLAYER_BROWSER_PERSISTENCE_BROWSER_PERSISTER_H_
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/persistence/browser_persister.h | C++ | unknown | 5,017 |
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "weblayer/browser/persistence/browser_persister.h"
#include "base/files/file_path.h"
#include "base/files/file_util.h"
#include "base/functional/callback_helpers.h"
#include "base/guid.h"
#include "base/memory/raw_ptr.h"
#include "base/memory/raw_ref.h"
#include "base/path_service.h"
#include "base/run_loop.h"
#include "base/test/bind.h"
#include "base/threading/thread_restrictions.h"
#include "build/build_config.h"
#include "components/sessions/core/command_storage_backend.h"
#include "components/sessions/core/command_storage_manager_test_helper.h"
#include "components/sessions/core/session_constants.h"
#include "content/public/test/browser_test_utils.h"
#include "content/public/test/url_loader_interceptor.h"
#include "net/base/filename_util.h"
#include "net/test/embedded_test_server/embedded_test_server.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "weblayer/browser/browser_impl.h"
#include "weblayer/browser/persistence/browser_persister_file_utils.h"
#include "weblayer/browser/profile_impl.h"
#include "weblayer/browser/tab_impl.h"
#include "weblayer/common/weblayer_paths.h"
#include "weblayer/public/browser_restore_observer.h"
#include "weblayer/public/navigation.h"
#include "weblayer/public/navigation_controller.h"
#include "weblayer/public/navigation_observer.h"
#include "weblayer/public/tab.h"
#include "weblayer/shell/browser/shell.h"
#include "weblayer/test/interstitial_utils.h"
#include "weblayer/test/test_navigation_observer.h"
#include "weblayer/test/weblayer_browser_test.h"
#include "weblayer/test/weblayer_browser_test_utils.h"
namespace weblayer {
class BrowserPersisterTestHelper {
public:
static sessions::CommandStorageManager* GetCommandStorageManager(
BrowserPersister* persister) {
return persister->command_storage_manager_.get();
}
};
namespace {
using testing::UnorderedElementsAre;
class BrowserNavigationObserverImpl : public BrowserRestoreObserver,
public NavigationObserver {
public:
static void WaitForNewTabToCompleteNavigation(Browser* browser,
const GURL& url,
size_t tab_to_wait_for = 0) {
BrowserNavigationObserverImpl observer(browser, url, tab_to_wait_for);
observer.Wait();
}
private:
BrowserNavigationObserverImpl(Browser* browser,
const GURL& url,
size_t tab_to_wait_for)
: browser_(browser), url_(url), tab_to_wait_for_(tab_to_wait_for) {
browser_->AddBrowserRestoreObserver(this);
}
~BrowserNavigationObserverImpl() override {
tab_->GetNavigationController()->RemoveObserver(this);
}
void Wait() { run_loop_.Run(); }
// NavigationObserver;
void NavigationCompleted(Navigation* navigation) override {
if (navigation->GetURL() == *url_)
run_loop_.Quit();
}
// BrowserRestoreObserver:
void OnRestoreCompleted() override {
browser_->RemoveBrowserRestoreObserver(this);
ASSERT_LT(tab_to_wait_for_, browser_->GetTabs().size());
ASSERT_EQ(nullptr, tab_.get());
tab_ = browser_->GetTabs()[tab_to_wait_for_];
tab_->GetNavigationController()->AddObserver(this);
}
raw_ptr<Browser> browser_;
const raw_ref<const GURL> url_;
raw_ptr<Tab> tab_ = nullptr;
const size_t tab_to_wait_for_;
std::unique_ptr<TestNavigationObserver> navigation_observer_;
base::RunLoop run_loop_;
};
void ShutdownBrowserPersisterAndWait(BrowserImpl* browser) {
auto task_runner = sessions::CommandStorageManagerTestHelper(
BrowserPersisterTestHelper::GetCommandStorageManager(
browser->browser_persister()))
.GetBackendTaskRunner();
browser->PrepareForShutdown();
base::RunLoop run_loop;
task_runner->PostTaskAndReply(FROM_HERE, base::DoNothing(),
run_loop.QuitClosure());
run_loop.Run();
}
std::unique_ptr<BrowserImpl> CreateBrowser(ProfileImpl* profile,
const std::string& persistence_id) {
Browser::PersistenceInfo info;
info.id = persistence_id;
auto browser = Browser::Create(profile, &info);
return std::unique_ptr<BrowserImpl>(
static_cast<BrowserImpl*>(browser.release()));
}
} // namespace
using BrowserPersisterTest = WebLayerBrowserTest;
IN_PROC_BROWSER_TEST_F(BrowserPersisterTest, SingleTab) {
ASSERT_TRUE(embedded_test_server()->Start());
std::unique_ptr<BrowserImpl> browser = CreateBrowser(GetProfile(), "x");
Tab* tab = browser->CreateTab();
EXPECT_TRUE(browser->IsRestoringPreviousState());
const GURL url = embedded_test_server()->GetURL("/simple_page.html");
NavigateAndWaitForCompletion(url, tab);
ShutdownBrowserPersisterAndWait(browser.get());
tab = nullptr;
browser.reset();
browser = CreateBrowser(GetProfile(), "x");
// Should be no tabs while waiting for restore.
EXPECT_TRUE(browser->GetTabs().empty());
EXPECT_TRUE(browser->IsRestoringPreviousState());
// Wait for the restore and navigation to complete.
BrowserNavigationObserverImpl::WaitForNewTabToCompleteNavigation(
browser.get(), url);
ASSERT_EQ(1u, browser->GetTabs().size());
EXPECT_EQ(browser->GetTabs()[0], browser->GetActiveTab());
EXPECT_EQ(1, browser->GetTabs()[0]
->GetNavigationController()
->GetNavigationListSize());
EXPECT_FALSE(browser->IsRestoringPreviousState());
}
IN_PROC_BROWSER_TEST_F(BrowserPersisterTest, RestoresGuid) {
ASSERT_TRUE(embedded_test_server()->Start());
std::unique_ptr<BrowserImpl> browser = CreateBrowser(GetProfile(), "x");
Tab* tab = browser->CreateTab();
const std::string original_guid = tab->GetGuid();
EXPECT_FALSE(original_guid.empty());
EXPECT_TRUE(base::IsValidGUID(original_guid));
const GURL url = embedded_test_server()->GetURL("/simple_page.html");
NavigateAndWaitForCompletion(url, tab);
ShutdownBrowserPersisterAndWait(browser.get());
tab = nullptr;
browser.reset();
browser = CreateBrowser(GetProfile(), "x");
// Should be no tabs while waiting for restore.
EXPECT_TRUE(browser->GetTabs().empty());
// Wait for the restore and navigation to complete.
BrowserNavigationObserverImpl::WaitForNewTabToCompleteNavigation(
browser.get(), url);
ASSERT_EQ(1u, browser->GetTabs().size());
EXPECT_EQ(browser->GetTabs()[0], browser->GetActiveTab());
EXPECT_EQ(original_guid, browser->GetTabs()[0]->GetGuid());
}
IN_PROC_BROWSER_TEST_F(BrowserPersisterTest, RestoresData) {
ASSERT_TRUE(embedded_test_server()->Start());
std::unique_ptr<BrowserImpl> browser = CreateBrowser(GetProfile(), "x");
Tab* tab = browser->CreateTab();
tab->SetData({{"abc", "efg"}});
const GURL url = embedded_test_server()->GetURL("/simple_page.html");
NavigateAndWaitForCompletion(url, tab);
ShutdownBrowserPersisterAndWait(browser.get());
tab = nullptr;
browser.reset();
browser = CreateBrowser(GetProfile(), "x");
// Should be no tabs while waiting for restore.
EXPECT_TRUE(browser->GetTabs().empty());
// Wait for the restore and navigation to complete.
BrowserNavigationObserverImpl::WaitForNewTabToCompleteNavigation(
browser.get(), url);
ASSERT_EQ(1u, browser->GetTabs().size());
EXPECT_EQ(browser->GetTabs()[0], browser->GetActiveTab());
EXPECT_THAT(browser->GetTabs()[0]->GetData(),
UnorderedElementsAre(std::make_pair("abc", "efg")));
}
IN_PROC_BROWSER_TEST_F(BrowserPersisterTest, RestoresMostRecentData) {
ASSERT_TRUE(embedded_test_server()->Start());
std::unique_ptr<BrowserImpl> browser = CreateBrowser(GetProfile(), "x");
Tab* tab = browser->CreateTab();
tab->SetData({{"xxx", "xxx"}});
const GURL url = embedded_test_server()->GetURL("/simple_page.html");
NavigateAndWaitForCompletion(url, tab);
// Make sure the data has been saved, then set different data on the tab.
BrowserPersisterTestHelper::GetCommandStorageManager(
browser->browser_persister())
->Save();
tab->SetData({{"abc", "efg"}});
ShutdownBrowserPersisterAndWait(browser.get());
tab = nullptr;
browser.reset();
browser = CreateBrowser(GetProfile(), "x");
// Should be no tabs while waiting for restore.
EXPECT_TRUE(browser->GetTabs().empty());
// Wait for the restore and navigation to complete.
BrowserNavigationObserverImpl::WaitForNewTabToCompleteNavigation(
browser.get(), url);
ASSERT_EQ(1u, browser->GetTabs().size());
EXPECT_EQ(browser->GetTabs()[0], browser->GetActiveTab());
EXPECT_THAT(browser->GetTabs()[0]->GetData(),
UnorderedElementsAre(std::make_pair("abc", "efg")));
}
IN_PROC_BROWSER_TEST_F(BrowserPersisterTest, TwoTabs) {
ASSERT_TRUE(embedded_test_server()->Start());
std::unique_ptr<BrowserImpl> browser = CreateBrowser(GetProfile(), "x");
Tab* tab1 = browser->CreateTab();
const GURL url1 = embedded_test_server()->GetURL("/simple_page.html");
NavigateAndWaitForCompletion(url1, tab1);
Tab* tab2 = browser->CreateTab();
const GURL url2 = embedded_test_server()->GetURL("/simple_page2.html");
NavigateAndWaitForCompletion(url2, tab2);
browser->SetActiveTab(tab2);
// Shut down the service.
ShutdownBrowserPersisterAndWait(browser.get());
tab1 = tab2 = nullptr;
browser.reset();
// Recreate the browser and run the assertions twice to ensure we handle
// correctly storing state of tabs that need to be reloaded.
for (int i = 0; i < 2; ++i) {
browser = CreateBrowser(GetProfile(), "x");
// Should be no tabs while waiting for restore.
EXPECT_TRUE(browser->GetTabs().empty()) << "iteration " << i;
// Wait for the restore and navigation to complete. This waits for the
// second tab as that was the active one.
BrowserNavigationObserverImpl::WaitForNewTabToCompleteNavigation(
browser.get(), url2, 1);
ASSERT_EQ(2u, browser->GetTabs().size()) << "iteration " << i;
// The first tab shouldn't have loaded yet, as it's not active.
EXPECT_TRUE(static_cast<TabImpl*>(browser->GetTabs()[0])
->web_contents()
->GetController()
.NeedsReload())
<< "iteration " << i;
EXPECT_EQ(browser->GetTabs()[1], browser->GetActiveTab())
<< "iteration " << i;
EXPECT_EQ(1, browser->GetTabs()[1]
->GetNavigationController()
->GetNavigationListSize())
<< "iteration " << i;
ShutdownBrowserPersisterAndWait(browser.get());
}
}
IN_PROC_BROWSER_TEST_F(BrowserPersisterTest, MoveBetweenBrowsers) {
ASSERT_TRUE(embedded_test_server()->Start());
// Create a browser with two tabs.
std::unique_ptr<BrowserImpl> browser1 = CreateBrowser(GetProfile(), "x");
Tab* tab1 = browser1->CreateTab();
const GURL url1 = embedded_test_server()->GetURL("/simple_page.html");
NavigateAndWaitForCompletion(url1, tab1);
Tab* tab2 = browser1->CreateTab();
const GURL url2 = embedded_test_server()->GetURL("/simple_page2.html");
NavigateAndWaitForCompletion(url2, tab2);
browser1->SetActiveTab(tab2);
// Create another browser with a single tab.
std::unique_ptr<BrowserImpl> browser2 = CreateBrowser(GetProfile(), "y");
Tab* tab3 = browser2->CreateTab();
const GURL url3 = embedded_test_server()->GetURL("/simple_page3.html");
NavigateAndWaitForCompletion(url3, tab3);
// Move |tab2| to |browser2|.
browser2->AddTab(tab2);
browser2->SetActiveTab(tab2);
ShutdownBrowserPersisterAndWait(browser1.get());
ShutdownBrowserPersisterAndWait(browser2.get());
tab1 = nullptr;
browser1.reset();
tab2 = tab3 = nullptr;
browser2.reset();
// Restore the browsers.
browser1 = CreateBrowser(GetProfile(), "x");
BrowserNavigationObserverImpl::WaitForNewTabToCompleteNavigation(
browser1.get(), url1);
ASSERT_EQ(1u, browser1->GetTabs().size());
EXPECT_EQ(1, browser1->GetTabs()[0]
->GetNavigationController()
->GetNavigationListSize());
browser2 = CreateBrowser(GetProfile(), "y");
BrowserNavigationObserverImpl::WaitForNewTabToCompleteNavigation(
browser2.get(), url2, 1);
ASSERT_EQ(2u, browser2->GetTabs().size());
EXPECT_EQ(1, browser2->GetTabs()[1]
->GetNavigationController()
->GetNavigationListSize());
// As |tab3| isn't active it needs to be loaded. Force that now.
TabImpl* restored_tab_3 = static_cast<TabImpl*>(browser2->GetTabs()[0]);
EXPECT_TRUE(restored_tab_3->web_contents()->GetController().NeedsReload());
restored_tab_3->web_contents()->GetController().LoadIfNecessary();
EXPECT_TRUE(content::WaitForLoadStop(restored_tab_3->web_contents()));
}
class BrowserPersisterTestWithTwoPersistedIds : public WebLayerBrowserTest {
public:
// WebLayerBrowserTest:
void SetUpOnMainThread() override {
WebLayerBrowserTest::SetUpOnMainThread();
// Configure two browsers with ids 'x' and 'y'.
ASSERT_TRUE(embedded_test_server()->Start());
std::unique_ptr<BrowserImpl> browser1 = CreateBrowser(GetProfile(), "x");
const GURL url1 = embedded_test_server()->GetURL("/simple_page.html");
NavigateAndWaitForCompletion(url1, browser1->CreateTab());
std::unique_ptr<BrowserImpl> browser2 = CreateBrowser(GetProfile(), "y");
const GURL url2 = embedded_test_server()->GetURL("/simple_page3.html");
NavigateAndWaitForCompletion(url2, browser2->CreateTab());
// Shut down the browsers.
ShutdownBrowserPersisterAndWait(browser1.get());
browser1.reset();
ShutdownBrowserPersisterAndWait(browser2.get());
browser2.reset();
}
};
IN_PROC_BROWSER_TEST_F(BrowserPersisterTestWithTwoPersistedIds,
GetBrowserPersistenceIds) {
{
// Create a file that has the name of a valid persistence file, but has
// invalid contents.
base::ScopedAllowBlockingForTesting allow_blocking;
base::WriteFile(BuildBasePathForBrowserPersister(
GetProfile()->GetBrowserPersisterDataBaseDir(), "z"),
"a bogus persistence file");
}
base::RunLoop run_loop;
base::flat_set<std::string> persistence_ids;
GetProfile()->GetBrowserPersistenceIds(
base::BindLambdaForTesting([&](base::flat_set<std::string> ids) {
persistence_ids = std::move(ids);
run_loop.Quit();
}));
run_loop.Run();
ASSERT_EQ(2u, persistence_ids.size());
EXPECT_TRUE(persistence_ids.contains("x"));
EXPECT_TRUE(persistence_ids.contains("y"));
}
bool HasSessionFileStartingWith(const base::FilePath& path) {
auto paths = sessions::CommandStorageBackend::GetSessionFilePaths(
path, sessions::CommandStorageManager::kOther);
return paths.size() == 1;
}
IN_PROC_BROWSER_TEST_F(BrowserPersisterTestWithTwoPersistedIds,
RemoveBrowserPersistenceStorage) {
base::FilePath file_path1 = BuildBasePathForBrowserPersister(
GetProfile()->GetBrowserPersisterDataBaseDir(), "x");
base::FilePath file_path2 = BuildBasePathForBrowserPersister(
GetProfile()->GetBrowserPersisterDataBaseDir(), "y");
{
base::ScopedAllowBlockingForTesting allow_blocking;
ASSERT_TRUE(HasSessionFileStartingWith(file_path1));
ASSERT_TRUE(HasSessionFileStartingWith(file_path2));
}
base::RunLoop run_loop;
base::flat_set<std::string> persistence_ids;
persistence_ids.insert("x");
persistence_ids.insert("y");
GetProfile()->RemoveBrowserPersistenceStorage(
base::BindLambdaForTesting([&](bool result) {
EXPECT_TRUE(result);
run_loop.Quit();
}),
std::move(persistence_ids));
run_loop.Run();
{
base::ScopedAllowBlockingForTesting allow_blocking;
EXPECT_FALSE(base::PathExists(file_path1));
EXPECT_FALSE(base::PathExists(file_path2));
}
}
IN_PROC_BROWSER_TEST_F(BrowserPersisterTest, OnErrorWritingSessionCommands) {
ASSERT_TRUE(embedded_test_server()->Start());
std::unique_ptr<BrowserImpl> browser = CreateBrowser(GetProfile(), "x");
Tab* tab = browser->CreateTab();
EXPECT_TRUE(browser->IsRestoringPreviousState());
const GURL url = embedded_test_server()->GetURL("/simple_page.html");
NavigateAndWaitForCompletion(url, tab);
static_cast<sessions::CommandStorageManagerDelegate*>(
browser->browser_persister())
->OnErrorWritingSessionCommands();
ShutdownBrowserPersisterAndWait(browser.get());
tab = nullptr;
browser.reset();
browser = CreateBrowser(GetProfile(), "x");
// Should be no tabs while waiting for restore.
EXPECT_TRUE(browser->GetTabs().empty());
EXPECT_TRUE(browser->IsRestoringPreviousState());
// Wait for the restore and navigation to complete.
BrowserNavigationObserverImpl::WaitForNewTabToCompleteNavigation(
browser.get(), url);
ASSERT_EQ(1u, browser->GetTabs().size());
EXPECT_EQ(browser->GetTabs()[0], browser->GetActiveTab());
EXPECT_EQ(1, browser->GetTabs()[0]
->GetNavigationController()
->GetNavigationListSize());
EXPECT_FALSE(browser->IsRestoringPreviousState());
}
} // namespace weblayer
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/persistence/browser_persister_browsertest.cc | C++ | unknown | 17,222 |
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "weblayer/browser/persistence/browser_persister_file_utils.h"
#include "base/files/file_enumerator.h"
#include "base/files/file_path.h"
#include "base/files/file_util.h"
#include "base/task/task_traits.h"
#include "base/task/thread_pool.h"
#include "components/base32/base32.h"
#include "components/sessions/core/command_storage_backend.h"
#include "components/sessions/core/session_constants.h"
#include "content/public/browser/browser_thread.h"
#include "weblayer/browser/browser_impl.h"
#include "weblayer/browser/browser_list.h"
#include "weblayer/browser/profile_impl.h"
namespace weblayer {
namespace {
bool RemoveBrowserPersistenceStorageOnBackgroundThread(
const base::FilePath& database_dir,
base::flat_set<std::string> ids) {
DCHECK(!content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
bool all_succeeded = true;
for (const std::string& id : ids) {
DCHECK(!id.empty());
// Original persistence path.
const base::FilePath persistence_path =
BuildBasePathForBrowserPersister(database_dir, id);
if (!base::DeleteFile(persistence_path))
all_succeeded = false;
// Remove persistence paths with timestamps.
auto paths = sessions::CommandStorageBackend::GetSessionFilePaths(
persistence_path, sessions::CommandStorageManager::kOther);
for (const auto& path : paths) {
if (!base::DeleteFile(path))
all_succeeded = false;
}
}
return all_succeeded;
}
} // namespace
base::flat_set<std::string> GetBrowserPersistenceIdsOnBackgroundThread(
const base::FilePath& path) {
DCHECK(!content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
base::flat_set<std::string> ids;
base::FilePath matching_path = base::FilePath().AppendASCII(
std::string(BrowserImpl::kPersistenceFilePrefix) + std::string("*"));
base::FileEnumerator iter(path, /* recursive */ false,
base::FileEnumerator::FILES, matching_path.value());
for (base::FilePath name = iter.Next(); !name.empty(); name = iter.Next()) {
// The name is base32 encoded, which is ascii.
const std::string base_name = iter.GetInfo().GetName().MaybeAsASCII();
if (base_name.size() <= std::size(BrowserImpl::kPersistenceFilePrefix))
continue;
const std::string encoded_id_and_timestamp =
base_name.substr(std::size(BrowserImpl::kPersistenceFilePrefix) - 1);
const size_t separator_index = encoded_id_and_timestamp.find(
base::FilePath(sessions::kTimestampSeparator).MaybeAsASCII());
const std::string encoded_id =
separator_index == std::string::npos
? encoded_id_and_timestamp
: encoded_id_and_timestamp.substr(0, separator_index);
const std::string decoded_id = base32::Base32Decode(encoded_id);
if (!decoded_id.empty() && ids.count(decoded_id) == 0 &&
sessions::CommandStorageBackend::IsValidFile(name)) {
ids.insert(decoded_id);
}
}
return ids;
}
base::FilePath BuildBasePathForBrowserPersister(
const base::FilePath& profile_path,
const std::string& browser_id) {
DCHECK(!browser_id.empty());
const std::string encoded_name = base32::Base32Encode(browser_id);
return profile_path.AppendASCII(BrowserImpl::kPersistenceFilePrefix +
encoded_name);
}
void RemoveBrowserPersistenceStorageImpl(
ProfileImpl* profile,
base::OnceCallback<void(bool)> done_callback,
base::flat_set<std::string> ids) {
// Remove any ids that are actively in use.
for (BrowserImpl* browser : BrowserList::GetInstance()->browsers()) {
if (browser->profile() == profile)
ids.erase(browser->GetPersistenceId());
}
base::ThreadPool::PostTaskAndReplyWithResult(
FROM_HERE,
{base::MayBlock(), base::TaskPriority::BEST_EFFORT,
base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN},
base::BindOnce(&RemoveBrowserPersistenceStorageOnBackgroundThread,
profile->GetBrowserPersisterDataBaseDir(), std::move(ids)),
std::move(done_callback));
}
} // namespace weblayer
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/persistence/browser_persister_file_utils.cc | C++ | unknown | 4,224 |
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef WEBLAYER_BROWSER_PERSISTENCE_BROWSER_PERSISTER_FILE_UTILS_H_
#define WEBLAYER_BROWSER_PERSISTENCE_BROWSER_PERSISTER_FILE_UTILS_H_
#include <string>
#include "base/containers/flat_set.h"
#include "base/functional/callback_forward.h"
namespace base {
class FilePath;
}
namespace weblayer {
class ProfileImpl;
// Returns the set of known persistence ids for the profile at |path|.
base::flat_set<std::string> GetBrowserPersistenceIdsOnBackgroundThread(
const base::FilePath& path);
// Returns the base path to save persistence information. `profile_path` is the
// path of the profile, and `browser_id` the persistence id.
//
// WARNING: persistence code writes more than one file. Historically it wrote
// to the value returned by this. Now it writes to the value returned by this
// with the suffix"_TIMESTAMP", where TIMESTAMP is the time stamp.
base::FilePath BuildBasePathForBrowserPersister(
const base::FilePath& profile_path,
const std::string& browser_id);
// Implementation of RemoveBrowserPersistenceStorage(). Tries to remove all
// the persistence files for the set of browser persistence ids.
void RemoveBrowserPersistenceStorageImpl(
ProfileImpl* profile,
base::OnceCallback<void(bool)> done_callback,
base::flat_set<std::string> ids);
} // namespace weblayer
#endif // WEBLAYER_BROWSER_PERSISTENCE_BROWSER_PERSISTER_FILE_UTILS_H_
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/persistence/browser_persister_file_utils.h | C++ | unknown | 1,531 |
// Copyright 2021 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "weblayer/browser/persistent_download.h"
#include "base/files/file_path.h"
#include "base/functional/bind.h"
#include "base/memory/ptr_util.h"
#include "base/task/sequenced_task_runner.h"
#include "components/download/public/common/download_item.h"
namespace weblayer {
namespace {
const char kPersistentDownloadKeyName[] = "weblayer_download_impl";
}
PersistentDownload::~PersistentDownload() = default;
void PersistentDownload::Create(download::DownloadItem* item) {
item->SetUserData(kPersistentDownloadKeyName,
base::WrapUnique(new PersistentDownload(item)));
}
PersistentDownload* PersistentDownload::Get(download::DownloadItem* item) {
return static_cast<PersistentDownload*>(
item->GetUserData(kPersistentDownloadKeyName));
}
DownloadState PersistentDownload::GetState() {
if (item_->GetState() == download::DownloadItem::COMPLETE)
return DownloadState::kComplete;
if (cancel_pending_ || item_->GetState() == download::DownloadItem::CANCELLED)
return DownloadState::kCancelled;
if (pause_pending_ || (item_->IsPaused() && !resume_pending_))
return DownloadState::kPaused;
if (resume_pending_ ||
item_->GetState() == download::DownloadItem::IN_PROGRESS) {
return DownloadState::kInProgress;
}
return DownloadState::kFailed;
}
int64_t PersistentDownload::GetTotalBytes() {
return item_->GetTotalBytes();
}
int64_t PersistentDownload::GetReceivedBytes() {
return item_->GetReceivedBytes();
}
void PersistentDownload::Pause() {
// The Pause/Resume/Cancel methods need to be called in a PostTask because we
// may be in a callback from the download subsystem and it doesn't handle
// nested calls.
resume_pending_ = false;
pause_pending_ = true;
base::SequencedTaskRunner::GetCurrentDefault()->PostTask(
FROM_HERE, base::BindOnce(&PersistentDownload::PauseInternal,
weak_ptr_factory_.GetWeakPtr()));
}
void PersistentDownload::Resume() {
pause_pending_ = false;
resume_pending_ = true;
base::SequencedTaskRunner::GetCurrentDefault()->PostTask(
FROM_HERE, base::BindOnce(&PersistentDownload::ResumeInternal,
weak_ptr_factory_.GetWeakPtr()));
}
void PersistentDownload::Cancel() {
cancel_pending_ = true;
base::SequencedTaskRunner::GetCurrentDefault()->PostTask(
FROM_HERE, base::BindOnce(&PersistentDownload::CancelInternal,
weak_ptr_factory_.GetWeakPtr()));
}
base::FilePath PersistentDownload::GetLocation() {
return item_->GetTargetFilePath();
}
std::u16string PersistentDownload::GetFileNameToReportToUser() {
return item_->GetFileNameToReportUser().LossyDisplayName();
}
std::string PersistentDownload::GetMimeType() {
return item_->GetMimeType();
}
DownloadError PersistentDownload::GetError() {
auto reason = item_->GetLastReason();
if (reason == download::DOWNLOAD_INTERRUPT_REASON_NONE)
return DownloadError::kNoError;
if (reason == download::DOWNLOAD_INTERRUPT_REASON_SERVER_CERT_PROBLEM)
return DownloadError::kSSLError;
if (reason >= download::DOWNLOAD_INTERRUPT_REASON_SERVER_FAILED &&
reason <=
download::DOWNLOAD_INTERRUPT_REASON_SERVER_CROSS_ORIGIN_REDIRECT)
return DownloadError::kServerError;
if (reason >= download::DOWNLOAD_INTERRUPT_REASON_NETWORK_FAILED &&
reason <= download::DOWNLOAD_INTERRUPT_REASON_NETWORK_INVALID_REQUEST)
return DownloadError::kConnectivityError;
if (reason == download::DOWNLOAD_INTERRUPT_REASON_FILE_NO_SPACE)
return DownloadError::kNoSpace;
if (reason >= download::DOWNLOAD_INTERRUPT_REASON_FILE_FAILED &&
reason <= download::DOWNLOAD_INTERRUPT_REASON_FILE_SAME_AS_SOURCE)
return DownloadError::kFileError;
if (reason == download::DOWNLOAD_INTERRUPT_REASON_USER_CANCELED)
return DownloadError::kCancelled;
return DownloadError::kOtherError;
}
PersistentDownload::PersistentDownload(download::DownloadItem* item)
: item_(item) {}
void PersistentDownload::PauseInternal() {
if (pause_pending_) {
pause_pending_ = false;
item_->Pause();
}
}
int PersistentDownload::GetNotificationId() {
return item_->GetId();
}
bool PersistentDownload::IsTransient() {
return false;
}
GURL PersistentDownload::GetSourceUrl() {
return {};
}
const SkBitmap* PersistentDownload::GetLargeIcon() {
return nullptr;
}
void PersistentDownload::OnFinished(bool activated) {
// For this type of download, activation is handled purely in Java.
}
void PersistentDownload::ResumeInternal() {
if (resume_pending_) {
resume_pending_ = false;
item_->Resume(true);
}
}
void PersistentDownload::CancelInternal() {
cancel_pending_ = false;
item_->Cancel(true);
}
} // namespace weblayer
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/persistent_download.cc | C++ | unknown | 4,915 |
// Copyright 2021 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef WEBLAYER_BROWSER_PERSISTENT_DOWNLOAD_H_
#define WEBLAYER_BROWSER_PERSISTENT_DOWNLOAD_H_
#include "base/memory/raw_ptr.h"
#include "weblayer/browser/download_impl.h"
namespace download {
class DownloadItem;
}
namespace weblayer {
// A DownloadImpl that is persisted to disk. It will be backed by a
// download::DownloadItem for which IsTransient returns false. This is used when
// a user downloads a file from the web.
class PersistentDownload : public DownloadImpl {
public:
PersistentDownload(const PersistentDownload& other) = delete;
PersistentDownload& operator=(const PersistentDownload& other) = delete;
~PersistentDownload() override;
static void Create(download::DownloadItem* item);
static PersistentDownload* Get(download::DownloadItem* item);
// Download:
DownloadState GetState() override;
int64_t GetTotalBytes() override;
int64_t GetReceivedBytes() override;
void Pause() override;
void Resume() override;
void Cancel() override;
base::FilePath GetLocation() override;
std::u16string GetFileNameToReportToUser() override;
std::string GetMimeType() override;
DownloadError GetError() override;
// DownloadImpl:
int GetNotificationId() override;
bool IsTransient() override;
GURL GetSourceUrl() override;
const SkBitmap* GetLargeIcon() override;
void OnFinished(bool activated) override;
private:
explicit PersistentDownload(download::DownloadItem* item);
void PauseInternal();
void ResumeInternal();
void CancelInternal();
raw_ptr<download::DownloadItem> item_;
bool pause_pending_ = false;
bool resume_pending_ = false;
bool cancel_pending_ = false;
base::WeakPtrFactory<PersistentDownload> weak_ptr_factory_{this};
};
} // namespace weblayer
#endif // WEBLAYER_BROWSER_PERSISTENT_DOWNLOAD_H_
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/persistent_download.h | C++ | unknown | 1,940 |
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/memory/raw_ptr.h"
#include "base/strings/stringprintf.h"
#include "build/build_config.h"
#include "components/blocked_content/popup_blocker_tab_helper.h"
#include "third_party/blink/public/common/switches.h"
#include "ui/base/page_transition_types.h"
#include "ui/base/window_open_disposition.h"
#include "weblayer/browser/browser_impl.h"
#include "weblayer/browser/host_content_settings_map_factory.h"
#include "weblayer/browser/profile_impl.h"
#include "weblayer/browser/tab_impl.h"
#include "weblayer/public/browser.h"
#include "weblayer/public/browser_observer.h"
#include "weblayer/public/navigation_controller.h"
#include "weblayer/public/new_tab_delegate.h"
#include "weblayer/shell/browser/shell.h"
#include "weblayer/test/test_navigation_observer.h"
#include "weblayer/test/weblayer_browser_test.h"
#include "weblayer/test/weblayer_browser_test_utils.h"
namespace weblayer {
class PopupBlockerBrowserTest : public WebLayerBrowserTest,
public NewTabDelegate,
public BrowserObserver {
public:
// WebLayerBrowserTest:
void SetUpOnMainThread() override {
ASSERT_TRUE(embedded_test_server()->Start());
original_tab_ = shell()->tab();
original_tab_->SetNewTabDelegate(this);
shell()->browser()->AddObserver(this);
NavigateAndWaitForCompletion(embedded_test_server()->GetURL("/echo"),
original_tab_);
}
void TearDownOnMainThread() override {
shell()->browser()->RemoveObserver(this);
}
void SetUpCommandLine(base::CommandLine* command_line) override {
WebLayerBrowserTest::SetUpCommandLine(command_line);
// Some bots are flaky due to slower loading interacting with
// deferred commits.
command_line->AppendSwitch(blink::switches::kAllowPreCommitInput);
}
// NewTabDelegate:
void OnNewTab(Tab* new_tab, NewTabType type) override {}
// BrowserObserver:
void OnTabAdded(Tab* tab) override {
new_tab_ = tab;
if (new_tab_run_loop_)
new_tab_run_loop_->Quit();
}
void OnTabRemoved(Tab* tab, bool active_tab_changed) override {
ASSERT_EQ(tab, new_tab_);
new_tab_ = nullptr;
if (close_tab_run_loop_)
close_tab_run_loop_->Quit();
}
size_t GetBlockedPopupCount() {
return blocked_content::PopupBlockerTabHelper::FromWebContents(
GetWebContents(original_tab_))
->GetBlockedPopupsCount();
}
content::WebContents* GetWebContents(Tab* tab) {
return static_cast<TabImpl*>(tab)->web_contents();
}
Tab* WaitForNewTab() {
if (!new_tab_) {
new_tab_run_loop_ = std::make_unique<base::RunLoop>();
new_tab_run_loop_->Run();
new_tab_run_loop_ = nullptr;
}
return new_tab_;
}
void WaitForCloseTab() {
if (new_tab_) {
close_tab_run_loop_ = std::make_unique<base::RunLoop>();
close_tab_run_loop_->Run();
close_tab_run_loop_ = nullptr;
}
ASSERT_FALSE(new_tab_);
}
void ExpectTabURL(Tab* tab, const GURL& url) {
if (tab->GetNavigationController()->GetNavigationListSize() > 0) {
EXPECT_EQ(tab->GetNavigationController()->GetNavigationEntryDisplayURL(0),
url);
} else {
TestNavigationObserver(
url, TestNavigationObserver::NavigationEvent::kCompletion, tab)
.Wait();
}
}
Tab* ShowPopup(const GURL& url) {
auto* popup_blocker =
blocked_content::PopupBlockerTabHelper::FromWebContents(
GetWebContents(original_tab_));
popup_blocker->ShowBlockedPopup(
popup_blocker->GetBlockedPopupRequests().begin()->first,
WindowOpenDisposition::NEW_FOREGROUND_TAB);
Tab* new_tab = WaitForNewTab();
ExpectTabURL(new_tab, url);
EXPECT_EQ(GetBlockedPopupCount(), 0u);
return new_tab;
}
Tab* original_tab() { return original_tab_; }
private:
std::unique_ptr<base::RunLoop> new_tab_run_loop_;
std::unique_ptr<base::RunLoop> close_tab_run_loop_;
raw_ptr<Tab> original_tab_ = nullptr;
raw_ptr<Tab> new_tab_ = nullptr;
};
IN_PROC_BROWSER_TEST_F(PopupBlockerBrowserTest, BlocksPopup) {
ExecuteScript(original_tab(), "window.open('https://google.com')", true);
EXPECT_EQ(GetBlockedPopupCount(), 1u);
}
IN_PROC_BROWSER_TEST_F(PopupBlockerBrowserTest, BlocksMultiplePopups) {
ExecuteScript(original_tab(), "window.open('https://google.com')", true);
ExecuteScript(original_tab(), "window.open('https://google.com')", true);
EXPECT_EQ(GetBlockedPopupCount(), 2u);
}
IN_PROC_BROWSER_TEST_F(PopupBlockerBrowserTest, DoesNotBlockUserGesture) {
GURL popup_url = embedded_test_server()->GetURL("/echo?popup");
ExecuteScriptWithUserGesture(
original_tab(),
base::StringPrintf("window.open('%s')", popup_url.spec().c_str()));
Tab* new_tab = WaitForNewTab();
ExpectTabURL(new_tab, popup_url);
EXPECT_EQ(GetBlockedPopupCount(), 0u);
}
IN_PROC_BROWSER_TEST_F(PopupBlockerBrowserTest, OpensBlockedPopup) {
GURL popup_url = embedded_test_server()->GetURL("/echo?popup");
ExecuteScript(
original_tab(),
base::StringPrintf("window.open('%s')", popup_url.spec().c_str()), true);
EXPECT_EQ(GetBlockedPopupCount(), 1u);
Tab* new_tab = ShowPopup(popup_url);
// Blocked popups should no longer have the opener set to match Chrome
// behavior.
EXPECT_FALSE(GetWebContents(new_tab)->HasOpener());
// Make sure we can cleanly close the popup, and there's no crash.
ExecuteScriptWithUserGesture(new_tab, "window.close()");
WaitForCloseTab();
}
IN_PROC_BROWSER_TEST_F(PopupBlockerBrowserTest,
AllowsPopupThroughContentSettingException) {
GURL popup_url = embedded_test_server()->GetURL("/echo?popup");
HostContentSettingsMapFactory::GetForBrowserContext(
GetWebContents(original_tab())->GetBrowserContext())
->SetContentSettingDefaultScope(popup_url, GURL(),
ContentSettingsType::POPUPS,
CONTENT_SETTING_ALLOW);
ExecuteScript(
original_tab(),
base::StringPrintf("window.open('%s')", popup_url.spec().c_str()), true);
Tab* new_tab = WaitForNewTab();
ExpectTabURL(new_tab, popup_url);
EXPECT_EQ(GetBlockedPopupCount(), 0u);
}
IN_PROC_BROWSER_TEST_F(PopupBlockerBrowserTest,
AllowsPopupThroughContentSettingDefaultValue) {
GURL popup_url = embedded_test_server()->GetURL("/echo?popup");
HostContentSettingsMapFactory::GetForBrowserContext(
GetWebContents(original_tab())->GetBrowserContext())
->SetDefaultContentSetting(ContentSettingsType::POPUPS,
CONTENT_SETTING_ALLOW);
ExecuteScript(
original_tab(),
base::StringPrintf("window.open('%s')", popup_url.spec().c_str()), true);
Tab* new_tab = WaitForNewTab();
ExpectTabURL(new_tab, popup_url);
EXPECT_EQ(GetBlockedPopupCount(), 0u);
}
IN_PROC_BROWSER_TEST_F(PopupBlockerBrowserTest,
BlockPopupThroughContentSettingException) {
GURL popup_url = embedded_test_server()->GetURL("/echo?popup");
HostContentSettingsMapFactory::GetForBrowserContext(
GetWebContents(original_tab())->GetBrowserContext())
->SetDefaultContentSetting(ContentSettingsType::POPUPS,
CONTENT_SETTING_ALLOW);
HostContentSettingsMapFactory::GetForBrowserContext(
GetWebContents(original_tab())->GetBrowserContext())
->SetContentSettingDefaultScope(popup_url, GURL(),
ContentSettingsType::POPUPS,
CONTENT_SETTING_BLOCK);
ExecuteScript(
original_tab(),
base::StringPrintf("window.open('%s')", popup_url.spec().c_str()), true);
EXPECT_EQ(GetBlockedPopupCount(), 1u);
}
IN_PROC_BROWSER_TEST_F(PopupBlockerBrowserTest,
BlocksAndOpensPopupFromOpenURL) {
GURL popup_url = embedded_test_server()->GetURL("/echo?popup");
content::OpenURLParams params(popup_url, content::Referrer(),
WindowOpenDisposition::NEW_FOREGROUND_TAB,
ui::PAGE_TRANSITION_LINK, true);
params.initiator_origin = url::Origin::Create(popup_url);
GetWebContents(original_tab())->OpenURL(params);
EXPECT_EQ(GetBlockedPopupCount(), 1u);
ShowPopup(popup_url);
}
IN_PROC_BROWSER_TEST_F(PopupBlockerBrowserTest,
DoesNotOpenPopupWithoutNewTabDelegate) {
NewTabDelegate* old_delegate =
static_cast<TabImpl*>(original_tab())->new_tab_delegate();
original_tab()->SetNewTabDelegate(nullptr);
GURL popup_url = embedded_test_server()->GetURL("/echo?popup");
ExecuteScriptWithUserGesture(
original_tab(),
base::StringPrintf("window.open('%s')", popup_url.spec().c_str()));
EXPECT_EQ(GetBlockedPopupCount(), 0u);
// Navigate the original tab, then make sure we still only have a single tab.
NavigateAndWaitForCompletion(embedded_test_server()->GetURL("/echo"),
original_tab());
EXPECT_EQ(shell()->browser()->GetTabs().size(), 1u);
// Restore the old delegate to make sure it is cleaned up on Android.
original_tab()->SetNewTabDelegate(old_delegate);
}
IN_PROC_BROWSER_TEST_F(PopupBlockerBrowserTest,
DoesNotOpenBlockedPopupWithoutNewTabDelegate) {
NewTabDelegate* old_delegate =
static_cast<TabImpl*>(original_tab())->new_tab_delegate();
original_tab()->SetNewTabDelegate(nullptr);
GURL popup_url = embedded_test_server()->GetURL("/echo?popup");
ExecuteScript(
original_tab(),
base::StringPrintf("window.open('%s')", popup_url.spec().c_str()), true);
EXPECT_EQ(GetBlockedPopupCount(), 0u);
// Navigate the original tab, then make sure we still only have a single tab.
NavigateAndWaitForCompletion(embedded_test_server()->GetURL("/echo"),
original_tab());
EXPECT_EQ(shell()->browser()->GetTabs().size(), 1u);
// Restore the old delegate to make sure it is cleaned up on Android.
original_tab()->SetNewTabDelegate(old_delegate);
}
} // namespace weblayer
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/popup_blocker_browsertest.cc | C++ | unknown | 10,225 |
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "weblayer/browser/popup_navigation_delegate_impl.h"
#include "base/functional/callback_helpers.h"
#include "build/build_config.h"
#include "components/infobars/content/content_infobar_manager.h"
#include "content/public/browser/web_contents.h"
#include "weblayer/browser/host_content_settings_map_factory.h"
#if BUILDFLAG(IS_ANDROID)
#include "components/blocked_content/android/popup_blocked_infobar_delegate.h"
#endif
namespace weblayer {
PopupNavigationDelegateImpl::PopupNavigationDelegateImpl(
const content::OpenURLParams& params,
content::WebContents* source_contents,
content::RenderFrameHost* opener)
: params_(params),
source_contents_(source_contents),
opener_(opener),
original_user_gesture_(params_.user_gesture) {}
content::RenderFrameHost* PopupNavigationDelegateImpl::GetOpener() {
return opener_;
}
bool PopupNavigationDelegateImpl::GetOriginalUserGesture() {
return original_user_gesture_;
}
GURL PopupNavigationDelegateImpl::GetURL() {
return params_.url;
}
blocked_content::PopupNavigationDelegate::NavigateResult
PopupNavigationDelegateImpl::NavigateWithGesture(
const blink::mojom::WindowFeatures& window_features,
absl::optional<WindowOpenDisposition> updated_disposition) {
// It's safe to mutate |params_| here because NavigateWithGesture() will only
// be called once, and the user gesture value has already been saved in
// |original_user_gesture_|.
params_.user_gesture = true;
if (updated_disposition)
params_.disposition = updated_disposition.value();
content::WebContents* new_contents = source_contents_->OpenURL(params_);
return NavigateResult{
new_contents,
params_.disposition,
};
}
void PopupNavigationDelegateImpl::OnPopupBlocked(
content::WebContents* web_contents,
int total_popups_blocked_on_page) {
#if BUILDFLAG(IS_ANDROID)
blocked_content::PopupBlockedInfoBarDelegate::Create(
infobars::ContentInfoBarManager::FromWebContents(web_contents),
total_popups_blocked_on_page,
HostContentSettingsMapFactory::GetForBrowserContext(
web_contents->GetBrowserContext()),
base::NullCallback());
#endif
}
} // namespace weblayer
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/popup_navigation_delegate_impl.cc | C++ | unknown | 2,347 |
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef WEBLAYER_BROWSER_POPUP_NAVIGATION_DELEGATE_IMPL_H_
#define WEBLAYER_BROWSER_POPUP_NAVIGATION_DELEGATE_IMPL_H_
#include "base/memory/raw_ptr.h"
#include "components/blocked_content/popup_navigation_delegate.h"
#include "content/public/browser/page_navigator.h"
#include "content/public/browser/render_frame_host.h"
namespace weblayer {
class PopupNavigationDelegateImpl
: public blocked_content::PopupNavigationDelegate {
public:
PopupNavigationDelegateImpl(const content::OpenURLParams& params,
content::WebContents* source_contents,
content::RenderFrameHost* opener);
// blocked_content::PopupNavigationDelegate:
content::RenderFrameHost* GetOpener() override;
bool GetOriginalUserGesture() override;
GURL GetURL() override;
NavigateResult NavigateWithGesture(
const blink::mojom::WindowFeatures& window_features,
absl::optional<WindowOpenDisposition> updated_disposition) override;
void OnPopupBlocked(content::WebContents* web_contents,
int total_popups_blocked_on_page) override;
const content::OpenURLParams& params() const { return params_; }
private:
content::OpenURLParams params_;
raw_ptr<content::WebContents> source_contents_;
raw_ptr<content::RenderFrameHost> opener_;
const bool original_user_gesture_;
};
} // namespace weblayer
#endif // WEBLAYER_BROWSER_POPUP_NAVIGATION_DELEGATE_IMPL_H_
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/popup_navigation_delegate_impl.h | C++ | unknown | 1,590 |
// Copyright 2019 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/files/file_path.h"
#include "base/strings/stringprintf.h"
#include "base/strings/utf_string_conversions.h"
#include "base/synchronization/lock.h"
#include "base/test/bind.h"
#include "base/thread_annotations.h"
#include "build/build_config.h"
#include "components/network_session_configurator/common/network_switches.h"
#include "content/public/browser/web_contents.h"
#include "content/public/test/browser_test_utils.h"
#include "net/base/network_change_notifier.h"
#include "net/dns/mock_host_resolver.h"
#include "net/test/embedded_test_server/embedded_test_server.h"
#include "net/test/embedded_test_server/http_request.h"
#include "net/test/embedded_test_server/http_response.h"
#include "weblayer/browser/tab_impl.h"
#include "weblayer/shell/browser/shell.h"
#include "weblayer/test/weblayer_browser_test.h"
#include "weblayer/test/weblayer_browser_test_utils.h"
namespace weblayer {
namespace {
const char kPrefetchPage[] = "/simple_prefetch.html";
const char kRedirectPrefetchPage[] = "/redirect_prefetch.html";
const char kRedirectPrefetchUrl[] = "/redirect";
const char kRedirectedPrefetchUrl[] = "/redirected";
const char kPrefetchTarget[] = "/prefetch_target.lnk";
} // namespace
class PrefetchBrowserTest : public WebLayerBrowserTest {
public:
void SetUpOnMainThread() override {
// The test makes requests to google.com which we want to redirect to the
// test server.
host_resolver()->AddRule("*", "127.0.0.1");
embedded_test_server()->RegisterRequestMonitor(base::BindRepeating(
&PrefetchBrowserTest::MonitorRequest, base::Unretained(this)));
ASSERT_TRUE(embedded_test_server()->Start());
}
void SetUpCommandLine(base::CommandLine* command_line) override {
// Set a dummy variation ID to send X-Client-Data header to Google hosts
// in RedirectedPrefetch test.
command_line->AppendSwitchASCII("force-variation-ids", "42");
// Need to ignore cert errors to use a HTTPS server for the test domains.
command_line->AppendSwitch(switches::kIgnoreCertificateErrors);
}
bool RunPrefetchExperiment(GURL url, const std::u16string expected_title) {
content::TitleWatcher title_watcher(
static_cast<TabImpl*>(shell()->tab())->web_contents(), expected_title);
NavigateAndWaitForCompletion(url, shell());
return expected_title == title_watcher.WaitAndGetTitle();
}
protected:
bool prefetch_target_request_seen_ = false;
base::Lock lock_;
// |requests_| is accessed on the UI thread by the test body and on the IO
// thread by the test server's request handler, so must be guarded by a lock
// to avoid data races.
std::vector<net::test_server::HttpRequest> requests_ GUARDED_BY(lock_);
private:
void MonitorRequest(const net::test_server::HttpRequest& request) {
if (request.relative_url == std::string(kPrefetchTarget)) {
prefetch_target_request_seen_ = true;
}
}
};
IN_PROC_BROWSER_TEST_F(PrefetchBrowserTest, PrefetchWorks) {
// Set real NetworkChangeNotifier singleton aside.
std::unique_ptr<net::NetworkChangeNotifier::DisableForTest> disable_for_test(
new net::NetworkChangeNotifier::DisableForTest);
ASSERT_FALSE(prefetch_target_request_seen_);
EXPECT_TRUE(RunPrefetchExperiment(
embedded_test_server()->GetURL(kPrefetchPage), u"link onload"));
EXPECT_TRUE(prefetch_target_request_seen_);
}
// https://crbug.com/922362: When the prefetched request is redirected, DCHECKs
// in PrefetchURLLoader::FollowRedirect() failed due to "X-Client-Data" in
// removed_headers. Verify that it no longer does.
IN_PROC_BROWSER_TEST_F(PrefetchBrowserTest, RedirectedPrefetch) {
net::EmbeddedTestServer https_server(net::EmbeddedTestServer::TYPE_HTTPS);
https_server.RegisterRequestHandler(base::BindLambdaForTesting(
[this](const net::test_server::HttpRequest& request)
-> std::unique_ptr<net::test_server::HttpResponse> {
auto response = std::make_unique<net::test_server::BasicHttpResponse>();
base::AutoLock auto_lock(lock_);
if (request.relative_url == std::string(kRedirectPrefetchPage)) {
requests_.push_back(request);
response->set_content_type("text/html");
response->set_content(
base::StringPrintf("<link rel=\"prefetch\" href=\"%s\" "
"onload=\"document.title='done'\">",
kRedirectPrefetchUrl));
return response;
} else if (request.relative_url == std::string(kRedirectPrefetchUrl)) {
requests_.push_back(request);
response->set_code(net::HTTP_MOVED_PERMANENTLY);
response->AddCustomHeader(
"Location", base::StringPrintf("https://example.com:%s%s",
request.GetURL().port().c_str(),
kRedirectedPrefetchUrl));
return response;
} else if (request.relative_url ==
std::string(kRedirectedPrefetchUrl)) {
requests_.push_back(request);
return response;
}
return nullptr;
}));
https_server.ServeFilesFromSourceDirectory(
base::FilePath(FILE_PATH_LITERAL("weblayer/test/data")));
{
base::AutoLock auto_lock(lock_);
requests_.clear();
}
ASSERT_TRUE(https_server.Start());
GURL url = https_server.GetURL("www.google.com", kRedirectPrefetchPage);
EXPECT_TRUE(RunPrefetchExperiment(url, u"done"));
{
base::AutoLock auto_lock(lock_);
ASSERT_EQ(3U, requests_.size());
EXPECT_EQ(base::StringPrintf("www.google.com:%u", https_server.port()),
requests_[0].headers["Host"]);
EXPECT_EQ(kRedirectPrefetchPage, requests_[0].relative_url);
}
}
} // namespace weblayer
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/prefetch_browsertest.cc | C++ | unknown | 5,906 |
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/test/bind.h"
#include "build/build_config.h"
#include "components/content_settings/core/browser/host_content_settings_map.h"
#include "ui/gfx/image/image_unittest_util.h"
#include "weblayer/browser/browser_list.h"
#include "weblayer/browser/browser_list_observer.h"
#include "weblayer/browser/favicon/favicon_fetcher_impl.h"
#include "weblayer/browser/favicon/test_favicon_fetcher_delegate.h"
#include "weblayer/browser/host_content_settings_map_factory.h"
#include "weblayer/browser/profile_impl.h"
#include "weblayer/browser/tab_impl.h"
#include "weblayer/public/browser.h"
#include "weblayer/shell/browser/shell.h"
#include "weblayer/test/weblayer_browser_test.h"
#include "weblayer/test/weblayer_browser_test_utils.h"
namespace weblayer {
using ProfileBrowserTest = WebLayerBrowserTest;
// TODO(crbug.com/654704): Android does not support PRE_ tests.
#if !BUILDFLAG(IS_ANDROID)
// UKM enabling via Profile persists across restarts.
IN_PROC_BROWSER_TEST_F(ProfileBrowserTest, PRE_PersistUKM) {
GetProfile()->SetBooleanSetting(SettingType::UKM_ENABLED, true);
}
IN_PROC_BROWSER_TEST_F(ProfileBrowserTest, PersistUKM) {
ASSERT_TRUE(GetProfile()->GetBooleanSetting(SettingType::UKM_ENABLED));
}
// Enabling Network Prediction via Profile persists across restarts.
IN_PROC_BROWSER_TEST_F(ProfileBrowserTest, PRE_PersistNetworkPrediction) {
GetProfile()->SetBooleanSetting(SettingType::NETWORK_PREDICTION_ENABLED,
false);
}
IN_PROC_BROWSER_TEST_F(ProfileBrowserTest, PersistNetworkPrediction) {
ASSERT_FALSE(
GetProfile()->GetBooleanSetting(SettingType::NETWORK_PREDICTION_ENABLED));
}
#endif // !BUILDFLAG(IS_ANDROID)
IN_PROC_BROWSER_TEST_F(ProfileBrowserTest, GetCachedFaviconForPageUrl) {
// Navigation to a page with a favicon.
ASSERT_TRUE(embedded_test_server()->Start());
TestFaviconFetcherDelegate fetcher_delegate;
auto fetcher = shell()->tab()->CreateFaviconFetcher(&fetcher_delegate);
const GURL url =
embedded_test_server()->GetURL("/simple_page_with_favicon.html");
NavigateAndWaitForCompletion(url, shell());
fetcher_delegate.WaitForFavicon();
EXPECT_FALSE(fetcher_delegate.last_image().IsEmpty());
EXPECT_EQ(1, fetcher_delegate.on_favicon_changed_call_count());
// Request the favicon.
base::RunLoop run_loop;
static_cast<TabImpl*>(shell()->tab())
->profile()
->GetCachedFaviconForPageUrl(
url, base::BindLambdaForTesting([&](gfx::Image image) {
// The last parameter is the max difference allowed for each color
// component. As the image is encoded before saving to disk some
// variance is expected.
EXPECT_TRUE(gfx::test::AreImagesClose(
image, fetcher_delegate.last_image(), 10));
run_loop.Quit();
}));
run_loop.Run();
}
IN_PROC_BROWSER_TEST_F(ProfileBrowserTest, ClearBrowsingDataDeletesFavicons) {
// Navigate to a page with a favicon.
ASSERT_TRUE(embedded_test_server()->Start());
TestFaviconFetcherDelegate fetcher_delegate;
auto fetcher = shell()->tab()->CreateFaviconFetcher(&fetcher_delegate);
const GURL url =
embedded_test_server()->GetURL("/simple_page_with_favicon.html");
NavigateAndWaitForCompletion(url, shell());
fetcher_delegate.WaitForNonemptyFavicon();
EXPECT_FALSE(fetcher_delegate.last_image().IsEmpty());
EXPECT_EQ(1, fetcher_delegate.on_favicon_changed_call_count());
// Delete the favicons.
base::RunLoop run_loop;
base::Time now = base::Time::Now();
ProfileImpl* profile = static_cast<TabImpl*>(shell()->tab())->profile();
profile->ClearBrowsingData({BrowsingDataType::COOKIES_AND_SITE_DATA},
now - base::Minutes(5), now,
run_loop.QuitClosure());
run_loop.Run();
// Ask for the cached favicon, there shouldn't be one.
base::RunLoop run_loop2;
profile->GetCachedFaviconForPageUrl(
url, base::BindLambdaForTesting([&](gfx::Image image) {
EXPECT_TRUE(image.IsEmpty());
run_loop2.Quit();
}));
run_loop2.Run();
// Navigate to another page, and verify favicon is downloaded.
fetcher_delegate.ClearLastImage();
const GURL url2 =
embedded_test_server()->GetURL("/simple_page_with_favicon2.html");
NavigateAndWaitForCompletion(url2, shell());
fetcher_delegate.WaitForNonemptyFavicon();
EXPECT_FALSE(fetcher_delegate.last_image().IsEmpty());
EXPECT_EQ(2, fetcher_delegate.on_favicon_changed_call_count());
// And fetch the favicon one more time.
base::RunLoop run_loop3;
profile->GetCachedFaviconForPageUrl(
url2, base::BindLambdaForTesting([&](gfx::Image image) {
EXPECT_FALSE(image.IsEmpty());
// The last parameter is the max difference allowed for each color
// component. As the image is encoded before saving to disk some
// variance is expected.
EXPECT_TRUE(gfx::test::AreImagesClose(
image, fetcher_delegate.last_image(), 10));
run_loop3.Quit();
}));
run_loop3.Run();
}
// Test default value.
IN_PROC_BROWSER_TEST_F(ProfileBrowserTest, DefaultNetworkPredictionState) {
ASSERT_TRUE(
GetProfile()->GetBooleanSetting(SettingType::NETWORK_PREDICTION_ENABLED));
}
IN_PROC_BROWSER_TEST_F(ProfileBrowserTest, ClearSiteSettings) {
auto foo_origin = GURL("http://www.foo.com");
auto* settings_map = HostContentSettingsMapFactory::GetForBrowserContext(
static_cast<TabImpl*>(shell()->tab())
->web_contents()
->GetBrowserContext());
EXPECT_EQ(settings_map->GetContentSetting(foo_origin, foo_origin,
ContentSettingsType::GEOLOCATION),
CONTENT_SETTING_ASK);
settings_map->SetContentSettingDefaultScope(foo_origin, foo_origin,
ContentSettingsType::GEOLOCATION,
CONTENT_SETTING_ALLOW);
// Ensure clearing things other than site data doesn't change it
base::RunLoop run_loop;
base::Time now = base::Time::Now();
ProfileImpl* profile = static_cast<TabImpl*>(shell()->tab())->profile();
profile->ClearBrowsingData(
{BrowsingDataType::COOKIES_AND_SITE_DATA, BrowsingDataType::CACHE},
base::Time(), now, run_loop.QuitClosure());
run_loop.Run();
EXPECT_EQ(settings_map->GetContentSetting(foo_origin, foo_origin,
ContentSettingsType::GEOLOCATION),
CONTENT_SETTING_ALLOW);
// Now clear site data.
base::RunLoop run_loop2;
profile->ClearBrowsingData({BrowsingDataType::SITE_SETTINGS}, base::Time(),
now, run_loop2.QuitClosure());
run_loop2.Run();
EXPECT_EQ(settings_map->GetContentSetting(foo_origin, foo_origin,
ContentSettingsType::GEOLOCATION),
CONTENT_SETTING_ASK);
}
// This test creates a Browser and Tab, which doesn't work well with Java when
// driven from native code.
#if !BUILDFLAG(IS_ANDROID)
class BrowserListObserverImpl : public BrowserListObserver {
public:
BrowserListObserverImpl(std::unique_ptr<Profile> profile,
base::OnceClosure done_closure)
: profile_(std::move(profile)), done_closure_(std::move(done_closure)) {
BrowserList::GetInstance()->AddObserver(this);
}
~BrowserListObserverImpl() override {
BrowserList::GetInstance()->RemoveObserver(this);
}
// BrowserListObserver:
void OnBrowserDestroyed(Browser* browser) override {
Profile::DestroyAndDeleteDataFromDisk(std::move(profile_),
std::move(done_closure_));
}
private:
std::unique_ptr<Profile> profile_;
base::OnceClosure done_closure_;
};
// This is a crash test to verify no memory related problems calling
// DestroyAndDeleteDataFromDisk() from OnBrowserDestroyed().
IN_PROC_BROWSER_TEST_F(ProfileBrowserTest, DestroyFromOnBrowserRemoved) {
auto profile = Profile::Create("2", true);
auto browser = Browser::Create(profile.get(), nullptr);
// MarkAsDeleted() may be called multiple times.
static_cast<ProfileImpl*>(profile.get())->MarkAsDeleted();
static_cast<ProfileImpl*>(profile.get())->MarkAsDeleted();
base::RunLoop run_loop;
BrowserListObserverImpl observer(std::move(profile), run_loop.QuitClosure());
browser.reset();
run_loop.Run();
// No crashes should happen.
}
#endif
} // namespace weblayer
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/profile_browsertest.cc | C++ | unknown | 8,608 |
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "weblayer/browser/profile_disk_operations.h"
#include "base/files/file_enumerator.h"
#include "base/files/file_util.h"
#include "base/logging.h"
#include "base/path_service.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_split.h"
#include "base/strings/string_util.h"
#include "build/build_config.h"
#include "components/base32/base32.h"
#include "weblayer/common/weblayer_paths.h"
namespace weblayer {
// Variables named |name| is a string passed in from the embedder to identify a
// profile. It can only contain alphanumeric and underscore.
//
// Variables named |dir_name| generally refers to the directory name of the
// profile. It may be the |name| exactly, or it may be <name>.<number>, if a
// profile is created with a name matching a profile marked for deletion.
// |dir_name| is an implementation detail of this file and should not be exposed
// as a concept out of this file.
namespace {
// Cannot be part of a valid name. This prevents the client ever specifying a
// name that collides a different one with a suffix.
constexpr char kSuffixDelimiter = '.';
bool IsValidProfileNameChar(char c) {
return base::IsAsciiDigit(c) || base::IsAsciiAlpha(c) || c == '_';
}
// Return the data path directory to profiles.
base::FilePath GetProfileRootDataDir() {
base::FilePath path;
CHECK(base::PathService::Get(DIR_USER_DATA, &path));
return path.AppendASCII("profiles");
}
base::FilePath GetProfileMarkerRootDataDir() {
base::FilePath path;
CHECK(base::PathService::Get(DIR_USER_DATA, &path));
path = path.AppendASCII("profiles_to_delete");
base::CreateDirectory(path);
return path;
}
base::FilePath GetDataPathFromDirName(const std::string& dir_name) {
return GetProfileRootDataDir().AppendASCII(dir_name.c_str());
}
#if BUILDFLAG(IS_POSIX)
base::FilePath GetCachePathFromDirName(const std::string& dir_name) {
base::FilePath cache_path;
CHECK(base::PathService::Get(base::DIR_CACHE, &cache_path));
cache_path = cache_path.AppendASCII("profiles").AppendASCII(dir_name.c_str());
return cache_path;
}
#endif // BUILDFLAG(IS_POSIX)
} // namespace
ProfileInfo::ProfileInfo(bool is_incognito,
const std::string& name,
const base::FilePath& data_path,
const base::FilePath& cache_path)
: is_incognito(is_incognito),
name(name),
data_path(data_path),
cache_path(cache_path) {}
ProfileInfo::ProfileInfo() = default;
ProfileInfo::ProfileInfo(const ProfileInfo&) = default;
ProfileInfo& ProfileInfo::operator=(const ProfileInfo&) = default;
ProfileInfo::~ProfileInfo() = default;
ProfileInfo CreateProfileInfo(const std::string& name, bool is_incognito) {
if (is_incognito)
return {is_incognito, name, base::FilePath(), base::FilePath()};
CHECK(internal::IsValidNameForNonIncognitoProfile(name));
std::string dir_name = name;
int suffix = 0;
while (internal::IsProfileMarkedForDeletion(dir_name)) {
suffix++;
dir_name = name;
dir_name.append(1, kSuffixDelimiter).append(base::NumberToString(suffix));
}
base::FilePath data_path = GetDataPathFromDirName(dir_name);
base::CreateDirectory(data_path);
base::FilePath cache_path = data_path;
#if BUILDFLAG(IS_POSIX)
cache_path = GetCachePathFromDirName(dir_name);
base::CreateDirectory(cache_path);
#endif
return {is_incognito, name, data_path, cache_path};
}
base::FilePath ComputeBrowserPersisterDataBaseDir(const ProfileInfo& info) {
base::FilePath base_path;
if (info.is_incognito) {
CHECK(base::PathService::Get(DIR_USER_DATA, &base_path));
if (info.name.empty()) {
// Originally the Android side of WebLayer only supported a single
// incognito file with an empty name.
std::string file_name = "Incognito Restore Data";
base_path = base_path.AppendASCII(file_name);
} else {
std::string file_name = "Named Profile Incognito Restore Data";
base_path = base_path.AppendASCII(file_name).AppendASCII(
base32::Base32Encode(info.name));
}
} else {
base_path = info.data_path.AppendASCII("Restore Data");
}
return base_path;
}
void MarkProfileAsDeleted(const ProfileInfo& info) {
if (info.is_incognito)
return;
base::FilePath data_root_path = GetProfileRootDataDir();
base::FilePath marker_path = GetProfileMarkerRootDataDir();
CHECK(data_root_path.AppendRelativePath(info.data_path, &marker_path));
base::File file(marker_path,
base::File::FLAG_CREATE | base::File::FLAG_WRITE);
if (!base::PathExists(marker_path)) {
LOG(WARNING) << "Failure in deleting profile data. Profile:" << info.name
<< " error:" << static_cast<int>(file.error_details());
}
}
void TryNukeProfileFromDisk(const ProfileInfo& info) {
if (info.is_incognito) {
// Incognito. Just delete session data.
base::DeletePathRecursively(ComputeBrowserPersisterDataBaseDir(info));
return;
}
// This may fail, but that is ok since the marker is not deleted.
base::DeletePathRecursively(info.data_path);
#if BUILDFLAG(IS_POSIX)
base::DeletePathRecursively(info.cache_path);
#endif
}
std::vector<std::string> ListProfileNames() {
base::FilePath root_dir = GetProfileRootDataDir();
std::vector<std::string> profile_names;
base::FileEnumerator enumerator(root_dir, /*recursive=*/false,
base::FileEnumerator::DIRECTORIES);
for (base::FilePath path = enumerator.Next(); !path.empty();
path = enumerator.Next()) {
std::string dir_name = enumerator.GetInfo().GetName().MaybeAsASCII();
std::string name = internal::CheckDirNameAndExtractName(dir_name);
if (!name.empty() && !internal::IsProfileMarkedForDeletion(dir_name))
profile_names.push_back(name);
}
return profile_names;
}
void NukeProfilesMarkedForDeletion() {
base::FilePath marker_root_dir = GetProfileMarkerRootDataDir();
base::FileEnumerator enumerator(marker_root_dir, /*recursive=*/false,
base::FileEnumerator::FILES);
for (base::FilePath marker_path = enumerator.Next(); !marker_path.empty();
marker_path = enumerator.Next()) {
std::string dir_name = enumerator.GetInfo().GetName().MaybeAsASCII();
if (!internal::CheckDirNameAndExtractName(dir_name).empty()) {
// Delete cache and data directory first before deleting marker.
bool delete_success = true;
#if BUILDFLAG(IS_POSIX)
delete_success |=
base::DeletePathRecursively(GetCachePathFromDirName(dir_name));
#endif // BUILDFLAG(IS_POSIX)
delete_success |=
base::DeletePathRecursively(GetDataPathFromDirName(dir_name));
// Only delete the marker if deletion is successful.
if (delete_success) {
base::DeleteFile(marker_path);
}
}
}
}
namespace internal {
bool IsValidNameForNonIncognitoProfile(const std::string& name) {
for (char c : name) {
if (!IsValidProfileNameChar(c))
return false;
}
return !name.empty();
}
// If |dir_name| is valid, then return the |name|. Otherwise return the empty
// string.
std::string CheckDirNameAndExtractName(const std::string& dir_name) {
std::vector<std::string> parts =
base::SplitString(dir_name, std::string(1, kSuffixDelimiter),
base::KEEP_WHITESPACE, base::SPLIT_WANT_ALL);
if (parts.size() == 0 || parts.size() > 2)
return std::string();
if (!IsValidNameForNonIncognitoProfile(parts[0]))
return std::string();
if (parts.size() > 1) {
if (parts[1].empty())
return std::string();
for (char c : parts[1]) {
if (!base::IsAsciiDigit(c))
return std::string();
}
}
return parts[0];
}
bool IsProfileMarkedForDeletion(const std::string& dir_name) {
base::FilePath marker =
GetProfileMarkerRootDataDir().AppendASCII(dir_name.c_str());
return base::PathExists(marker);
}
} // namespace internal
} // namespace weblayer
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/profile_disk_operations.cc | C++ | unknown | 8,117 |
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef WEBLAYER_BROWSER_PROFILE_DISK_OPERATIONS_H_
#define WEBLAYER_BROWSER_PROFILE_DISK_OPERATIONS_H_
#include <string>
#include <vector>
#include "base/files/file_path.h"
namespace weblayer {
struct ProfileInfo {
ProfileInfo(bool is_incognito,
const std::string& name,
const base::FilePath& data_path,
const base::FilePath& cache_path);
ProfileInfo();
ProfileInfo(const ProfileInfo&);
ProfileInfo& operator=(const ProfileInfo&);
~ProfileInfo();
bool is_incognito = false;
// The profile name supplied by client code. For non-incognito profiles name
// can only contain alphanumeric and underscore to be valid.
std::string name;
// Path where persistent profile data is stored. This will be empty if
// icognito.
base::FilePath data_path;
// Path where cache profile data is stored. Depending on the OS, this may
// be the same as |data_path|; the OS may delete data in this directory.
base::FilePath cache_path;
};
// |name| must be a valid profile name. Ensures that both data and cache path
// directories are created. The paths returned may be different from the name
// to avoid reusing directories that are marked as deleted.
ProfileInfo CreateProfileInfo(const std::string& name, bool is_incognito);
base::FilePath ComputeBrowserPersisterDataBaseDir(const ProfileInfo& info);
void MarkProfileAsDeleted(const ProfileInfo& info);
void TryNukeProfileFromDisk(const ProfileInfo& info);
// Return names of profiles on disk. Invalid profile names are ignored.
// Profiles marked as deleted are ignored.
std::vector<std::string> ListProfileNames();
// This should be called before any |MarkProfileAsDeleted| for a single process
// to avoid races.
void NukeProfilesMarkedForDeletion();
// Functions exposed for testing.
namespace internal {
bool IsValidNameForNonIncognitoProfile(const std::string& name);
std::string CheckDirNameAndExtractName(const std::string& dir_name);
bool IsProfileMarkedForDeletion(const std::string& dir_name);
} // namespace internal
} // namespace weblayer
#endif // WEBLAYER_BROWSER_PROFILE_DISK_OPERATIONS_H_
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/profile_disk_operations.h | C++ | unknown | 2,274 |
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <string>
#include <vector>
#include "base/base_paths.h"
#include "base/check.h"
#include "base/containers/contains.h"
#include "base/files/file_util.h"
#include "base/strings/string_number_conversions.h"
#include "base/test/scoped_path_override.h"
#include "build/build_config.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "weblayer/browser/profile_disk_operations.h"
#include "weblayer/common/weblayer_paths.h"
namespace weblayer {
class ProfileDiskOperationsTest : public testing::Test {
protected:
base::ScopedPathOverride data_dir_override_{DIR_USER_DATA};
#if BUILDFLAG(IS_POSIX)
base::ScopedPathOverride cache_dir_override_{base::DIR_CACHE};
#endif
};
TEST_F(ProfileDiskOperationsTest, IsValidNameForNonIncognitoProfile) {
EXPECT_TRUE(internal::IsValidNameForNonIncognitoProfile("foo"));
EXPECT_TRUE(internal::IsValidNameForNonIncognitoProfile("123"));
EXPECT_FALSE(internal::IsValidNameForNonIncognitoProfile(std::string()));
EXPECT_FALSE(internal::IsValidNameForNonIncognitoProfile("foo.bar"));
EXPECT_FALSE(internal::IsValidNameForNonIncognitoProfile("foo~"));
EXPECT_FALSE(internal::IsValidNameForNonIncognitoProfile("foo-"));
}
TEST_F(ProfileDiskOperationsTest, CheckDirnameAndExtractName) {
EXPECT_EQ(std::string("foo123"),
internal::CheckDirNameAndExtractName("foo123"));
EXPECT_EQ(std::string("foo"), internal::CheckDirNameAndExtractName("foo.1"));
EXPECT_EQ(std::string("foo"), internal::CheckDirNameAndExtractName("foo.2"));
EXPECT_EQ(std::string("foo"),
internal::CheckDirNameAndExtractName("foo.123"));
EXPECT_EQ(std::string(), internal::CheckDirNameAndExtractName("foo."));
EXPECT_EQ(std::string(), internal::CheckDirNameAndExtractName("foo~"));
EXPECT_EQ(std::string(), internal::CheckDirNameAndExtractName("foo~.1"));
EXPECT_EQ(std::string(), internal::CheckDirNameAndExtractName("foo.bar"));
EXPECT_EQ(std::string(), internal::CheckDirNameAndExtractName("foo.1.2"));
EXPECT_EQ(std::string(), internal::CheckDirNameAndExtractName(std::string()));
EXPECT_EQ(std::string(), internal::CheckDirNameAndExtractName(".1"));
}
TEST_F(ProfileDiskOperationsTest, BasicListProfileNames) {
std::vector<std::string> names{"foo", "bar", "baz"};
for (const auto& name : names) {
ProfileInfo info = CreateProfileInfo(name, false);
EXPECT_FALSE(info.data_path.empty());
EXPECT_FALSE(info.cache_path.empty());
}
std::vector<std::string> listed_names = ListProfileNames();
EXPECT_EQ(names.size(), listed_names.size());
for (const auto& name : names) {
EXPECT_TRUE(base::Contains(listed_names, name));
}
}
TEST_F(ProfileDiskOperationsTest, MarkProfileAsDeleted) {
std::vector<std::string> names{"foo", "bar", "baz"};
std::vector<ProfileInfo> infos;
for (const auto& name : names) {
ProfileInfo info = CreateProfileInfo(name, false);
infos.push_back(info);
EXPECT_FALSE(info.data_path.empty());
EXPECT_FALSE(info.cache_path.empty());
}
for (const auto& info : infos) {
MarkProfileAsDeleted(info);
EXPECT_TRUE(internal::IsProfileMarkedForDeletion(
info.data_path.BaseName().MaybeAsASCII()));
}
std::vector<std::string> listed_names = ListProfileNames();
EXPECT_TRUE(listed_names.empty());
}
TEST_F(ProfileDiskOperationsTest, ReuseProfileName) {
constexpr int kRepeat = 3;
for (int i = 0; i < kRepeat; ++i) {
ProfileInfo info = CreateProfileInfo("foo", false);
MarkProfileAsDeleted(info);
EXPECT_TRUE(internal::IsProfileMarkedForDeletion(
info.data_path.BaseName().MaybeAsASCII()));
std::string expected_base_name("foo");
if (i != 0) {
expected_base_name += ".";
expected_base_name += base::NumberToString(i);
}
EXPECT_EQ(expected_base_name, info.data_path.BaseName().MaybeAsASCII());
EXPECT_EQ(expected_base_name, info.cache_path.BaseName().MaybeAsASCII());
std::vector<std::string> listed_names = ListProfileNames();
EXPECT_TRUE(listed_names.empty());
}
}
TEST_F(ProfileDiskOperationsTest, NukeProfile) {
std::vector<ProfileInfo> deleted_infos;
constexpr int kRepeat = 3;
for (int i = 0; i < kRepeat; ++i) {
ProfileInfo info = CreateProfileInfo("foo", false);
MarkProfileAsDeleted(info);
deleted_infos.push_back(info);
}
{
ProfileInfo info = CreateProfileInfo("bar", false);
MarkProfileAsDeleted(info);
deleted_infos.push_back(info);
}
{
ProfileInfo info = CreateProfileInfo("baz", false);
MarkProfileAsDeleted(info);
deleted_infos.push_back(info);
}
ProfileInfo kept_info = CreateProfileInfo("kept", false);
for (auto& info : deleted_infos) {
EXPECT_TRUE(base::PathExists(info.data_path));
EXPECT_TRUE(base::PathExists(info.cache_path));
}
EXPECT_TRUE(base::PathExists(kept_info.data_path));
EXPECT_TRUE(base::PathExists(kept_info.cache_path));
NukeProfilesMarkedForDeletion();
for (auto& info : deleted_infos) {
EXPECT_FALSE(base::PathExists(info.data_path));
EXPECT_FALSE(base::PathExists(info.cache_path));
}
EXPECT_TRUE(base::PathExists(kept_info.data_path));
EXPECT_TRUE(base::PathExists(kept_info.cache_path));
ProfileInfo info = CreateProfileInfo("bar", false);
EXPECT_EQ(std::string("bar"), info.data_path.BaseName().MaybeAsASCII());
EXPECT_EQ(std::string("bar"), info.cache_path.BaseName().MaybeAsASCII());
}
} // namespace weblayer
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/profile_disk_operations_unittests.cc | C++ | unknown | 5,532 |
// Copyright 2019 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "weblayer/browser/profile_impl.h"
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include "base/functional/bind.h"
#include "base/memory/raw_ptr.h"
#include "base/no_destructor.h"
#include "base/observer_list.h"
#include "base/ranges/algorithm.h"
#include "base/task/sequenced_task_runner.h"
#include "base/task/task_traits.h"
#include "base/task/thread_pool.h"
#include "base/threading/thread_restrictions.h"
#include "build/build_config.h"
#include "components/keyed_service/content/browser_context_dependency_manager.h"
#include "components/prefs/pref_service.h"
#include "components/profile_metrics/browser_profile_type.h"
#include "components/web_cache/browser/web_cache_manager.h"
#include "content/public/browser/browser_task_traits.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/browsing_data_remover.h"
#include "content/public/browser/device_service.h"
#include "content/public/browser/download_manager.h"
#include "content/public/browser/page_navigator.h"
#include "content/public/browser/render_process_host.h"
#include "content/public/browser/storage_partition.h"
#include "content/public/browser/web_contents.h"
#include "services/network/public/mojom/network_context.mojom.h"
#include "ui/gfx/image/image.h"
#include "ui/gfx/image/image_skia.h"
#include "ui/gfx/image/image_skia_rep.h"
#include "weblayer/browser/browser_context_impl.h"
#include "weblayer/browser/browser_impl.h"
#include "weblayer/browser/browser_list.h"
#include "weblayer/browser/browsing_data_remover_delegate.h"
#include "weblayer/browser/cookie_manager_impl.h"
#include "weblayer/browser/favicon/favicon_service_impl.h"
#include "weblayer/browser/favicon/favicon_service_impl_factory.h"
#include "weblayer/browser/no_state_prefetch/prerender_controller_impl.h"
#include "weblayer/browser/persistence/browser_persister_file_utils.h"
#include "weblayer/browser/tab_impl.h"
#if BUILDFLAG(IS_ANDROID)
#include "base/android/callback_android.h"
#include "base/android/jni_array.h"
#include "base/android/jni_string.h"
#include "base/android/scoped_java_ref.h"
#include "components/safe_browsing/core/common/safe_browsing_prefs.h"
#include "components/unified_consent/pref_names.h"
#include "ui/gfx/android/java_bitmap.h"
#include "weblayer/browser/android/metrics/weblayer_metrics_service_client.h"
#include "weblayer/browser/browser_process.h"
#include "weblayer/browser/java/jni/ProfileImpl_jni.h"
#include "weblayer/browser/safe_browsing/safe_browsing_service.h"
#endif
#if BUILDFLAG(IS_POSIX)
#include "base/base_paths_posix.h"
#endif
#if BUILDFLAG(IS_ANDROID)
using base::android::AttachCurrentThread;
#endif
namespace weblayer {
namespace {
bool g_first_profile_created = false;
// TaskRunner used by MarkProfileAsDeleted and NukeProfilesMarkedForDeletion to
// esnure that Nuke happens before any Mark in this process.
base::SequencedTaskRunner* GetBackgroundDiskOperationTaskRunner() {
static const base::NoDestructor<scoped_refptr<base::SequencedTaskRunner>>
task_runner(base::ThreadPool::CreateSingleThreadTaskRunner(
{base::MayBlock(), base::TaskPriority::BEST_EFFORT}));
return task_runner.get()->get();
}
std::set<ProfileImpl*>& GetProfiles() {
static base::NoDestructor<std::set<ProfileImpl*>> s_all_profiles;
return *s_all_profiles;
}
base::ObserverList<ProfileImpl::ProfileObserver>::Unchecked& GetObservers() {
static base::NoDestructor<
base::ObserverList<ProfileImpl::ProfileObserver>::Unchecked>
s_observers;
return *s_observers;
}
#if BUILDFLAG(IS_ANDROID)
void PassFilePathsToJavaCallback(
const base::android::ScopedJavaGlobalRef<jobject>& callback,
const std::vector<std::string>& file_paths) {
base::android::RunObjectCallbackAndroid(
callback, base::android::ToJavaArrayOfStrings(
base::android::AttachCurrentThread(), file_paths));
}
void OnGotBrowserPersistenceIds(
const base::android::ScopedJavaGlobalRef<jobject>& callback,
base::flat_set<std::string> ids) {
std::vector<std::string> as_vector;
for (const std::string& id : ids)
as_vector.push_back(id);
base::android::RunObjectCallbackAndroid(
callback,
base::android::ToJavaArrayOfStrings(AttachCurrentThread(), as_vector));
}
void OnDidRemoveBrowserPersistenceStorage(
const base::android::ScopedJavaGlobalRef<jobject>& callback,
bool result) {
base::android::RunBooleanCallbackAndroid(callback, result);
}
void OnDidGetCachedFaviconForPageUrl(
const base::android::ScopedJavaGlobalRef<jobject>& callback,
gfx::Image image) {
SkBitmap favicon = image.AsImageSkia().GetRepresentation(1.0f).GetBitmap();
base::android::RunObjectCallbackAndroid(
callback, favicon.empty() ? nullptr : gfx::ConvertToJavaBitmap(favicon));
}
#endif // BUILDFLAG(IS_ANDROID)
} // namespace
class ProfileImpl::DataClearer : public content::BrowsingDataRemover::Observer {
public:
DataClearer(content::BrowserContext* browser_context,
base::OnceCallback<void()> callback)
: remover_(browser_context->GetBrowsingDataRemover()),
callback_(std::move(callback)) {
remover_->AddObserver(this);
}
void ClearData(ProfileImpl* profile,
uint64_t mask,
base::Time from_time,
base::Time to_time) {
uint64_t origin_types =
content::BrowsingDataRemover::ORIGIN_TYPE_UNPROTECTED_WEB |
content::BrowsingDataRemover::ORIGIN_TYPE_PROTECTED_WEB;
remover_->RemoveAndReply(from_time, to_time, mask, origin_types, this);
}
// content::BrowsingDataRemover::Observer:
void OnBrowsingDataRemoverDone(uint64_t failed_data_types) override {
// Remove the observer now as after this returns the BrowserContext may
// be destroyed, which owns |remover_|.
remover_->RemoveObserver(this);
std::move(callback_).Run();
delete this;
}
private:
// DataClearer deletes itself when removal is done.
~DataClearer() override = default;
raw_ptr<content::BrowsingDataRemover> remover_;
base::OnceCallback<void()> callback_;
};
// static
base::FilePath ProfileImpl::GetCachePath(content::BrowserContext* context) {
DCHECK(context);
ProfileImpl* profile = FromBrowserContext(context);
return profile->info_.cache_path;
}
ProfileImpl::ProfileImpl(const std::string& name, bool is_incognito)
: download_directory_(BrowserContextImpl::GetDefaultDownloadDirectory()) {
{
base::ScopedAllowBlocking allow_blocking;
info_ = CreateProfileInfo(name, is_incognito);
}
GetProfiles().insert(this);
profile_metrics::SetBrowserProfileType(
GetBrowserContext(), is_incognito
? profile_metrics::BrowserProfileType::kIncognito
: profile_metrics::BrowserProfileType::kRegular);
for (auto& observer : GetObservers())
observer.ProfileCreated(this);
if (!g_first_profile_created) {
g_first_profile_created = true;
GetBackgroundDiskOperationTaskRunner()->PostTask(
FROM_HERE, base::BindOnce(&NukeProfilesMarkedForDeletion));
}
// Ensure WebCacheManager is created so that it starts observing
// OnRenderProcessHostCreated events.
web_cache::WebCacheManager::GetInstance();
#if BUILDFLAG(IS_ANDROID)
WebLayerMetricsServiceClient::GetInstance()->UpdateUkm(false);
#endif
}
ProfileImpl::~ProfileImpl() {
// Destroy any scheduled WebContents. These implicitly refer to the
// BrowserContext and must be destroyed before the BrowserContext.
web_contents_to_delete_.clear();
if (browser_context_) {
// Needs to be called before ShutdownStoragePartitions().
browser_context_->NotifyWillBeDestroyed();
BrowserContextDependencyManager::GetInstance()
->DestroyBrowserContextServices(browser_context_.get());
browser_context_->ShutdownStoragePartitions();
}
GetProfiles().erase(this);
for (auto& observer : GetObservers())
observer.ProfileDestroyed(this);
}
ProfileImpl* ProfileImpl::FromBrowserContext(
content::BrowserContext* browser_context) {
return static_cast<BrowserContextImpl*>(browser_context)->profile_impl();
}
std::set<ProfileImpl*> ProfileImpl::GetAllProfiles() {
return GetProfiles();
}
void ProfileImpl::AddProfileObserver(ProfileObserver* observer) {
GetObservers().AddObserver(observer);
}
void ProfileImpl::RemoveProfileObserver(ProfileObserver* observer) {
GetObservers().RemoveObserver(observer);
}
void ProfileImpl::DeleteWebContentsSoon(
std::unique_ptr<content::WebContents> web_contents) {
if (web_contents_to_delete_.empty()) {
base::SequencedTaskRunner::GetCurrentDefault()->PostTask(
FROM_HERE, base::BindOnce(&ProfileImpl::DeleteScheduleWebContents,
weak_ptr_factory_.GetWeakPtr()));
}
web_contents_to_delete_.push_back(std::move(web_contents));
}
BrowserContextImpl* ProfileImpl::GetBrowserContext() {
if (browser_context_)
return browser_context_.get();
browser_context_ =
std::make_unique<BrowserContextImpl>(this, info_.data_path);
locale_change_subscription_ =
i18n::RegisterLocaleChangeCallback(base::BindRepeating(
&ProfileImpl::OnLocaleChanged, base::Unretained(this)));
return browser_context_.get();
}
void ProfileImpl::DownloadsInitialized() {
#if BUILDFLAG(IS_ANDROID)
return Java_ProfileImpl_downloadsInitialized(
base::android::AttachCurrentThread(), java_profile_);
#endif
}
void ProfileImpl::MarkAsDeleted() {
GetBackgroundDiskOperationTaskRunner()->PostTask(
FROM_HERE, base::BindOnce(&MarkProfileAsDeleted, info_));
}
void ProfileImpl::ClearBrowsingData(
const std::vector<BrowsingDataType>& data_types,
base::Time from_time,
base::Time to_time,
base::OnceClosure callback) {
auto* clearer = new DataClearer(GetBrowserContext(), std::move(callback));
// DataClearer will delete itself in OnBrowsingDataRemoverDone().
// If Profile is destroyed during clearing, it would lead to destroying
// browser_context_ and then BrowsingDataRemover, which in turn would call
// OnBrowsingDataRemoverDone(), even though the clearing hasn't been finished.
uint64_t remove_mask = 0;
// This follows what Chrome does: see browsing_data_bridge.cc.
for (auto data_type : data_types) {
switch (data_type) {
case BrowsingDataType::COOKIES_AND_SITE_DATA:
remove_mask |= content::BrowsingDataRemover::DATA_TYPE_COOKIES;
remove_mask |= content::BrowsingDataRemover::DATA_TYPE_DOM_STORAGE;
remove_mask |= content::BrowsingDataRemover::DATA_TYPE_MEDIA_LICENSES;
remove_mask |= BrowsingDataRemoverDelegate::DATA_TYPE_ISOLATED_ORIGINS;
remove_mask |= BrowsingDataRemoverDelegate::DATA_TYPE_FAVICONS;
remove_mask |= BrowsingDataRemoverDelegate::DATA_TYPE_AD_INTERVENTIONS;
remove_mask |= content::BrowsingDataRemover::DATA_TYPE_PRIVACY_SANDBOX;
break;
case BrowsingDataType::CACHE:
remove_mask |= content::BrowsingDataRemover::DATA_TYPE_CACHE;
ClearRendererCache();
break;
case BrowsingDataType::SITE_SETTINGS:
remove_mask |= BrowsingDataRemoverDelegate::DATA_TYPE_SITE_SETTINGS;
break;
default:
NOTREACHED();
}
}
clearer->ClearData(this, remove_mask, from_time, to_time);
}
void ProfileImpl::SetDownloadDirectory(const base::FilePath& directory) {
download_directory_ = directory;
}
void ProfileImpl::SetDownloadDelegate(DownloadDelegate* delegate) {
download_delegate_ = delegate;
}
void ProfileImpl::SetGoogleAccountAccessTokenFetchDelegate(
GoogleAccountAccessTokenFetchDelegate* delegate) {
access_token_fetch_delegate_ = delegate;
}
CookieManager* ProfileImpl::GetCookieManager() {
if (!cookie_manager_)
cookie_manager_ = std::make_unique<CookieManagerImpl>(GetBrowserContext());
return cookie_manager_.get();
}
PrerenderController* ProfileImpl::GetPrerenderController() {
if (!prerender_controller_)
prerender_controller_ =
std::make_unique<PrerenderControllerImpl>(GetBrowserContext());
return prerender_controller_.get();
}
void ProfileImpl::GetBrowserPersistenceIds(
base::OnceCallback<void(base::flat_set<std::string>)> callback) {
DCHECK(!browser_context_->IsOffTheRecord());
base::ThreadPool::PostTaskAndReplyWithResult(
FROM_HERE,
{base::MayBlock(), base::TaskPriority::BEST_EFFORT,
base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN},
base::BindOnce(&GetBrowserPersistenceIdsOnBackgroundThread,
GetBrowserPersisterDataBaseDir()),
std::move(callback));
}
void ProfileImpl::RemoveBrowserPersistenceStorage(
base::OnceCallback<void(bool)> done_callback,
base::flat_set<std::string> ids) {
DCHECK(!browser_context_->IsOffTheRecord());
RemoveBrowserPersistenceStorageImpl(this, std::move(done_callback),
std::move(ids));
}
// static
void ProfileImpl::NukeDataAfterRemovingData(
std::unique_ptr<ProfileImpl> profile,
base::OnceClosure done_callback) {
// Need PostTask to avoid reentrancy for deleting |browser_context_|.
content::GetUIThreadTaskRunner({})->PostTask(
FROM_HERE, base::BindOnce(&ProfileImpl::DoNukeData, std::move(profile),
std::move(done_callback)));
}
// static
void ProfileImpl::DoNukeData(std::unique_ptr<ProfileImpl> profile,
base::OnceClosure done_callback) {
ProfileInfo info = profile->info_;
profile.reset();
GetBackgroundDiskOperationTaskRunner()->PostTaskAndReply(
FROM_HERE, base::BindOnce(&TryNukeProfileFromDisk, info),
std::move(done_callback));
}
void ProfileImpl::ClearRendererCache() {
for (content::RenderProcessHost::iterator iter =
content::RenderProcessHost::AllHostsIterator();
!iter.IsAtEnd(); iter.Advance()) {
content::RenderProcessHost* render_process_host = iter.GetCurrentValue();
if (render_process_host->GetBrowserContext() == GetBrowserContext() &&
render_process_host->IsInitializedAndNotDead()) {
web_cache::WebCacheManager::GetInstance()->ClearCacheForProcess(
render_process_host->GetID());
}
}
}
void ProfileImpl::OnLocaleChanged() {
GetBrowserContext()->ForEachLoadedStoragePartition(base::BindRepeating(
[](const std::string& accept_language,
content::StoragePartition* storage_partition) {
storage_partition->GetNetworkContext()->SetAcceptLanguage(
accept_language);
},
i18n::GetAcceptLangs()));
}
// static
std::unique_ptr<Profile> Profile::Create(const std::string& name,
bool is_incognito) {
return std::make_unique<ProfileImpl>(name, is_incognito);
}
// static
std::unique_ptr<Profile> Profile::DestroyAndDeleteDataFromDisk(
std::unique_ptr<Profile> profile,
base::OnceClosure done_callback) {
std::unique_ptr<ProfileImpl> impl(
static_cast<ProfileImpl*>(profile.release()));
return ProfileImpl::DestroyAndDeleteDataFromDisk(std::move(impl),
std::move(done_callback));
}
// static
std::unique_ptr<ProfileImpl> ProfileImpl::DestroyAndDeleteDataFromDisk(
std::unique_ptr<ProfileImpl> profile,
base::OnceClosure done_callback) {
if (profile->GetNumberOfBrowsers() > 0)
return profile;
ProfileInfo profile_info = profile->info_;
GetBackgroundDiskOperationTaskRunner()->PostTaskAndReply(
FROM_HERE, base::BindOnce(&MarkProfileAsDeleted, profile_info),
base::BindOnce(&ProfileImpl::OnProfileMarked, std::move(profile),
std::move(done_callback)));
return nullptr;
}
// static
void ProfileImpl::OnProfileMarked(std::unique_ptr<ProfileImpl> profile,
base::OnceClosure done_callback) {
// Try to finish all writes and remove all data before nuking the profile.
profile->GetBrowserContext()->pref_service()->CommitPendingWrite();
ProfileImpl* raw_profile = profile.get();
auto* clearer = new DataClearer(
raw_profile->GetBrowserContext(),
base::BindOnce(&ProfileImpl::NukeDataAfterRemovingData,
std::move(profile), std::move(done_callback)));
uint64_t remove_all_mask = 0xffffffffffffffffull;
clearer->ClearData(raw_profile, remove_all_mask, base::Time::Min(),
base::Time::Max());
}
#if BUILDFLAG(IS_ANDROID)
ProfileImpl::ProfileImpl(
JNIEnv* env,
const base::android::JavaParamRef<jstring>& name,
const base::android::JavaParamRef<jobject>& java_profile,
bool is_incognito)
: ProfileImpl(ConvertJavaStringToUTF8(env, name), is_incognito) {
java_profile_ = java_profile;
}
static jlong JNI_ProfileImpl_CreateProfile(
JNIEnv* env,
const base::android::JavaParamRef<jstring>& name,
const base::android::JavaParamRef<jobject>& java_profile,
jboolean is_incognito) {
return reinterpret_cast<jlong>(
new ProfileImpl(env, name, java_profile, is_incognito));
}
static void JNI_ProfileImpl_DeleteProfile(JNIEnv* env, jlong profile) {
delete reinterpret_cast<ProfileImpl*>(profile);
}
static void JNI_ProfileImpl_EnumerateAllProfileNames(
JNIEnv* env,
const base::android::JavaParamRef<jobject>& callback) {
base::ThreadPool::PostTaskAndReplyWithResult(
FROM_HERE,
{base::MayBlock(), base::TaskPriority::BEST_EFFORT,
base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN},
base::BindOnce(&ListProfileNames),
base::BindOnce(&PassFilePathsToJavaCallback,
base::android::ScopedJavaGlobalRef<jobject>(callback)));
}
jint ProfileImpl::GetNumBrowserImpl(JNIEnv* env) {
return GetNumberOfBrowsers();
}
jlong ProfileImpl::GetBrowserContext(JNIEnv* env) {
return reinterpret_cast<intptr_t>(GetBrowserContext());
}
void ProfileImpl::DestroyAndDeleteDataFromDisk(
JNIEnv* env,
const base::android::JavaRef<jobject>& j_completion_callback) {
std::unique_ptr<ProfileImpl> ptr(this);
std::unique_ptr<ProfileImpl> result =
ProfileImpl::DestroyAndDeleteDataFromDisk(
std::move(ptr),
base::BindOnce(&base::android::RunRunnableAndroid,
base::android::ScopedJavaGlobalRef<jobject>(
j_completion_callback)));
CHECK(!result);
}
void ProfileImpl::ClearBrowsingData(
JNIEnv* env,
const base::android::JavaParamRef<jintArray>& j_data_types,
const jlong j_from_time_millis,
const jlong j_to_time_millis,
const base::android::JavaRef<jobject>& j_callback) {
std::vector<int> data_type_ints;
base::android::JavaIntArrayToIntVector(env, j_data_types, &data_type_ints);
std::vector<BrowsingDataType> data_types;
data_types.reserve(data_type_ints.size());
for (int type : data_type_ints)
data_types.push_back(static_cast<BrowsingDataType>(type));
ClearBrowsingData(
data_types,
base::Time::FromJavaTime(static_cast<int64_t>(j_from_time_millis)),
base::Time::FromJavaTime(static_cast<int64_t>(j_to_time_millis)),
base::BindOnce(base::android::RunRunnableAndroid,
base::android::ScopedJavaGlobalRef<jobject>(j_callback)));
}
void ProfileImpl::SetDownloadDirectory(
JNIEnv* env,
const base::android::JavaParamRef<jstring>& directory) {
base::FilePath directory_path(
base::android::ConvertJavaStringToUTF8(directory));
SetDownloadDirectory(directory_path);
}
jlong ProfileImpl::GetCookieManager(JNIEnv* env) {
return reinterpret_cast<jlong>(GetCookieManager());
}
jlong ProfileImpl::GetPrerenderController(JNIEnv* env) {
return reinterpret_cast<jlong>(GetPrerenderController());
}
void ProfileImpl::EnsureBrowserContextInitialized(JNIEnv* env) {
GetBrowserContext()->GetDownloadManager();
}
void ProfileImpl::SetBooleanSetting(JNIEnv* env,
jint j_type,
jboolean j_value) {
SetBooleanSetting(static_cast<SettingType>(j_type), j_value);
}
jboolean ProfileImpl::GetBooleanSetting(JNIEnv* env, jint j_type) {
return GetBooleanSetting(static_cast<SettingType>(j_type));
}
void ProfileImpl::GetBrowserPersistenceIds(
JNIEnv* env,
const base::android::JavaRef<jobject>& j_callback) {
GetBrowserPersistenceIds(
base::BindOnce(&OnGotBrowserPersistenceIds,
base::android::ScopedJavaGlobalRef<jobject>(j_callback)));
}
void ProfileImpl::RemoveBrowserPersistenceStorage(
JNIEnv* env,
const base::android::JavaRef<jobjectArray>& j_ids,
const base::android::JavaRef<jobject>& j_callback) {
std::vector<std::string> ids;
base::android::AppendJavaStringArrayToStringVector(env, j_ids, &ids);
RemoveBrowserPersistenceStorage(
base::BindOnce(&OnDidRemoveBrowserPersistenceStorage,
base::android::ScopedJavaGlobalRef<jobject>(j_callback)),
base::flat_set<std::string>(ids.begin(), ids.end()));
}
void ProfileImpl::PrepareForPossibleCrossOriginNavigation(JNIEnv* env) {
PrepareForPossibleCrossOriginNavigation();
}
void ProfileImpl::GetCachedFaviconForPageUrl(
JNIEnv* env,
const base::android::JavaRef<jstring>& j_page_url,
const base::android::JavaRef<jobject>& j_callback) {
GetCachedFaviconForPageUrl(
GURL(base::android::ConvertJavaStringToUTF8(j_page_url)),
base::BindOnce(&OnDidGetCachedFaviconForPageUrl,
base::android::ScopedJavaGlobalRef<jobject>(j_callback)));
}
#endif // BUILDFLAG(IS_ANDROID)
base::FilePath ProfileImpl::GetBrowserPersisterDataBaseDir() const {
return ComputeBrowserPersisterDataBaseDir(info_);
}
content::WebContents* ProfileImpl::OpenUrl(
const content::OpenURLParams& params) {
#if !BUILDFLAG(IS_ANDROID)
return nullptr;
#else
// We expect only NEW_FOREGROUND_TAB. The NEW_POPUP disposition is only used
// for payment handler windows, but WebLayer (and Android Chrome) do not
// support that. See ContentBrowserClient::ShowPaymentHandlerWindow().
DCHECK_EQ(params.disposition, WindowOpenDisposition::NEW_FOREGROUND_TAB);
JNIEnv* env = base::android::AttachCurrentThread();
BrowserImpl* browser = reinterpret_cast<BrowserImpl*>(
Java_ProfileImpl_getBrowserForNewTab(env, java_profile_));
if (!browser)
return nullptr;
std::unique_ptr<content::WebContents> new_tab_contents =
content::WebContents::Create(
content::WebContents::CreateParams(GetBrowserContext()));
base::WeakPtr<content::WebContents> new_tab_contents_weak_ptr(
new_tab_contents->GetWeakPtr());
Tab* tab = browser->CreateTab(std::move(new_tab_contents));
if (!new_tab_contents_weak_ptr)
return nullptr;
Java_ProfileImpl_onTabAdded(env, java_profile_,
static_cast<TabImpl*>(tab)->GetJavaTab());
new_tab_contents_weak_ptr->GetController().LoadURLWithParams(
content::NavigationController::LoadURLParams(params));
return new_tab_contents_weak_ptr.get();
#endif // !BUILDFLAG(IS_ANDROID)
}
void ProfileImpl::SetBooleanSetting(SettingType type, bool value) {
auto* pref_service = GetBrowserContext()->pref_service();
switch (type) {
case SettingType::BASIC_SAFE_BROWSING_ENABLED:
#if BUILDFLAG(IS_ANDROID)
safe_browsing::SetSafeBrowsingState(
pref_service,
value ? safe_browsing::SafeBrowsingState::STANDARD_PROTECTION
: safe_browsing::SafeBrowsingState::NO_SAFE_BROWSING,
/*is_esb_enabled_in_sync=*/false);
#endif
break;
case SettingType::UKM_ENABLED: {
#if BUILDFLAG(IS_ANDROID)
bool old_value = pref_service->GetBoolean(prefs::kUkmEnabled);
#endif
pref_service->SetBoolean(prefs::kUkmEnabled, value);
#if BUILDFLAG(IS_ANDROID)
// Trigger a purge if the current state no longer allows UKM.
bool must_purge = old_value && !value;
WebLayerMetricsServiceClient::GetInstance()->UpdateUkm(must_purge);
#endif
break;
}
case SettingType::EXTENDED_REPORTING_SAFE_BROWSING_ENABLED:
#if BUILDFLAG(IS_ANDROID)
pref_service->SetBoolean(::prefs::kSafeBrowsingScoutReportingEnabled,
value);
#endif
break;
case SettingType::REAL_TIME_SAFE_BROWSING_ENABLED:
#if BUILDFLAG(IS_ANDROID)
pref_service->SetBoolean(
unified_consent::prefs::kUrlKeyedAnonymizedDataCollectionEnabled,
value);
#endif
break;
case SettingType::NETWORK_PREDICTION_ENABLED:
pref_service->SetBoolean(prefs::kNoStatePrefetchEnabled, value);
}
}
bool ProfileImpl::GetBooleanSetting(SettingType type) {
auto* pref_service = GetBrowserContext()->pref_service();
switch (type) {
case SettingType::BASIC_SAFE_BROWSING_ENABLED:
#if BUILDFLAG(IS_ANDROID)
return safe_browsing::IsSafeBrowsingEnabled(*pref_service);
#else
return false;
#endif
case SettingType::UKM_ENABLED:
return pref_service->GetBoolean(prefs::kUkmEnabled);
case SettingType::EXTENDED_REPORTING_SAFE_BROWSING_ENABLED:
#if BUILDFLAG(IS_ANDROID)
return pref_service->GetBoolean(
::prefs::kSafeBrowsingScoutReportingEnabled);
#else
return false;
#endif
case SettingType::REAL_TIME_SAFE_BROWSING_ENABLED:
#if BUILDFLAG(IS_ANDROID)
return pref_service->GetBoolean(
unified_consent::prefs::kUrlKeyedAnonymizedDataCollectionEnabled);
#else
return false;
#endif
case SettingType::NETWORK_PREDICTION_ENABLED:
return pref_service->GetBoolean(prefs::kNoStatePrefetchEnabled);
}
NOTREACHED();
}
void ProfileImpl::GetCachedFaviconForPageUrl(
const GURL& page_url,
base::OnceCallback<void(gfx::Image)> callback) {
auto* service =
FaviconServiceImplFactory::GetForBrowserContext(GetBrowserContext());
if (!service) {
std::move(callback).Run({});
return;
}
service->GetFaviconForPageUrl(page_url, std::move(callback),
&cancelable_task_tracker_);
}
void ProfileImpl::PrepareForPossibleCrossOriginNavigation() {
content::RenderProcessHost::WarmupSpareRenderProcessHost(GetBrowserContext());
}
int ProfileImpl::GetNumberOfBrowsers() {
const auto& browsers = BrowserList::GetInstance()->browsers();
return base::ranges::count(browsers, this, &BrowserImpl::profile);
}
void ProfileImpl::DeleteScheduleWebContents() {
web_contents_to_delete_.clear();
}
} // namespace weblayer
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/profile_impl.cc | C++ | unknown | 26,520 |
// Copyright 2019 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef WEBLAYER_BROWSER_PROFILE_IMPL_H_
#define WEBLAYER_BROWSER_PROFILE_IMPL_H_
#include <set>
#include <vector>
#include "base/files/file_path.h"
#include "base/memory/raw_ptr.h"
#include "base/memory/weak_ptr.h"
#include "base/task/cancelable_task_tracker.h"
#include "build/build_config.h"
#include "weblayer/browser/browser_list_observer.h"
#include "weblayer/browser/i18n_util.h"
#include "weblayer/browser/profile_disk_operations.h"
#include "weblayer/public/profile.h"
#if BUILDFLAG(IS_ANDROID)
#include <jni.h>
#include "base/android/scoped_java_ref.h"
#endif
namespace content {
class BrowserContext;
class WebContents;
struct OpenURLParams;
} // namespace content
namespace weblayer {
class BrowserContextImpl;
class CookieManagerImpl;
class PrerenderControllerImpl;
class ProfileImpl : public Profile {
public:
// Return the cache directory path for this BrowserContext. On some
// platforms, file in cache directory may be deleted by the operating
// system. So it is suitable for storing data that can be recreated such
// as caches.
// |context| must not be null.
static base::FilePath GetCachePath(content::BrowserContext* context);
static std::unique_ptr<ProfileImpl> DestroyAndDeleteDataFromDisk(
std::unique_ptr<ProfileImpl> profile,
base::OnceClosure done_callback);
ProfileImpl(const std::string& name, bool is_incognito);
ProfileImpl(const ProfileImpl&) = delete;
ProfileImpl& operator=(const ProfileImpl&) = delete;
~ProfileImpl() override;
// Returns the ProfileImpl from the specified BrowserContext.
static ProfileImpl* FromBrowserContext(
content::BrowserContext* browser_context);
static std::set<ProfileImpl*> GetAllProfiles();
// Allows getting notified when profiles are created or destroyed.
class ProfileObserver {
public:
virtual void ProfileCreated(ProfileImpl* profile) {}
virtual void ProfileDestroyed(ProfileImpl* profile) {}
protected:
virtual ~ProfileObserver() = default;
};
static void AddProfileObserver(ProfileObserver* observer);
static void RemoveProfileObserver(ProfileObserver* observer);
// Deletes |web_contents| after a delay. This is used if the owning Tab is
// deleted and it's not safe to delete the WebContents.
void DeleteWebContentsSoon(
std::unique_ptr<content::WebContents> web_contents);
BrowserContextImpl* GetBrowserContext();
// Called when the download subsystem has finished initializing. By this point
// information about downloads that were interrupted by a previous crash would
// be available.
void DownloadsInitialized();
// Path data is stored at, empty if off-the-record.
const base::FilePath& data_path() const { return info_.data_path; }
const std::string& name() const { return info_.name; }
DownloadDelegate* download_delegate() { return download_delegate_; }
GoogleAccountAccessTokenFetchDelegate* access_token_fetch_delegate() {
return access_token_fetch_delegate_;
}
void MarkAsDeleted();
// Profile implementation:
void ClearBrowsingData(const std::vector<BrowsingDataType>& data_types,
base::Time from_time,
base::Time to_time,
base::OnceClosure callback) override;
void SetDownloadDirectory(const base::FilePath& directory) override;
void SetDownloadDelegate(DownloadDelegate* delegate) override;
void SetGoogleAccountAccessTokenFetchDelegate(
GoogleAccountAccessTokenFetchDelegate* delegate) override;
CookieManager* GetCookieManager() override;
PrerenderController* GetPrerenderController() override;
void GetBrowserPersistenceIds(
base::OnceCallback<void(base::flat_set<std::string>)> callback) override;
void RemoveBrowserPersistenceStorage(
base::OnceCallback<void(bool)> done_callback,
base::flat_set<std::string> ids) override;
void SetBooleanSetting(SettingType type, bool value) override;
bool GetBooleanSetting(SettingType type) override;
void GetCachedFaviconForPageUrl(
const GURL& page_url,
base::OnceCallback<void(gfx::Image)> callback) override;
void PrepareForPossibleCrossOriginNavigation() override;
#if BUILDFLAG(IS_ANDROID)
ProfileImpl(JNIEnv* env,
const base::android::JavaParamRef<jstring>& path,
const base::android::JavaParamRef<jobject>& java_profile,
bool is_incognito);
jint GetNumBrowserImpl(JNIEnv* env);
jlong GetBrowserContext(JNIEnv* env);
void DestroyAndDeleteDataFromDisk(
JNIEnv* env,
const base::android::JavaRef<jobject>& j_completion_callback);
void ClearBrowsingData(
JNIEnv* env,
const base::android::JavaParamRef<jintArray>& j_data_types,
const jlong j_from_time_millis,
const jlong j_to_time_millis,
const base::android::JavaRef<jobject>& j_callback);
void SetDownloadDirectory(
JNIEnv* env,
const base::android::JavaParamRef<jstring>& directory);
jlong GetCookieManager(JNIEnv* env);
jlong GetPrerenderController(JNIEnv* env);
void EnsureBrowserContextInitialized(JNIEnv* env);
void SetBooleanSetting(JNIEnv* env, jint j_type, jboolean j_value);
jboolean GetBooleanSetting(JNIEnv* env, jint j_type);
void GetBrowserPersistenceIds(
JNIEnv* env,
const base::android::JavaRef<jobject>& j_callback);
void RemoveBrowserPersistenceStorage(
JNIEnv* env,
const base::android::JavaRef<jobjectArray>& j_ids,
const base::android::JavaRef<jobject>& j_callback);
void PrepareForPossibleCrossOriginNavigation(JNIEnv* env);
void GetCachedFaviconForPageUrl(
JNIEnv* env,
const base::android::JavaRef<jstring>& j_page_url,
const base::android::JavaRef<jobject>& j_callback);
void MarkAsDeleted(JNIEnv* env) { MarkAsDeleted(); }
base::android::ScopedJavaGlobalRef<jobject> GetJavaProfile() {
return java_profile_;
}
#endif
const base::FilePath& download_directory() { return download_directory_; }
// Get the directory where BrowserPersister stores tab state data. This will
// be a real file path even for the off-the-record profile.
base::FilePath GetBrowserPersisterDataBaseDir() const;
// Creates a new web contents and navigates it according to `params`, but only
// if an OpenUrlCallback has been set by the embedder. This is used for
// navigations originating from service workers, which don't necessarily have
// an associated tab. It may return null if the operation fails.
content::WebContents* OpenUrl(const content::OpenURLParams& params);
private:
class DataClearer;
static void OnProfileMarked(std::unique_ptr<ProfileImpl> profile,
base::OnceClosure done_callback);
static void NukeDataAfterRemovingData(std::unique_ptr<ProfileImpl> profile,
base::OnceClosure done_callback);
static void DoNukeData(std::unique_ptr<ProfileImpl> profile,
base::OnceClosure done_callback);
void ClearRendererCache();
// Callback when the system locale has been updated.
void OnLocaleChanged();
// Returns the number of Browsers with this profile.
int GetNumberOfBrowsers();
void DeleteScheduleWebContents();
ProfileInfo info_;
std::unique_ptr<BrowserContextImpl> browser_context_;
base::FilePath download_directory_;
raw_ptr<DownloadDelegate> download_delegate_ = nullptr;
raw_ptr<GoogleAccountAccessTokenFetchDelegate> access_token_fetch_delegate_ =
nullptr;
base::CallbackListSubscription locale_change_subscription_;
std::unique_ptr<CookieManagerImpl> cookie_manager_;
std::unique_ptr<PrerenderControllerImpl> prerender_controller_;
#if BUILDFLAG(IS_ANDROID)
base::android::ScopedJavaGlobalRef<jobject> java_profile_;
#endif
// The typical pattern for CancelableTaskTrackers is to have the caller
// supply one. This code is predominantly called from the Java side, where
// CancelableTaskTracker isn't applicable. Because of this, the
// CancelableTaskTracker is owned by Profile.
base::CancelableTaskTracker cancelable_task_tracker_;
std::vector<std::unique_ptr<content::WebContents>> web_contents_to_delete_;
base::WeakPtrFactory<ProfileImpl> weak_ptr_factory_{this};
};
} // namespace weblayer
#endif // WEBLAYER_BROWSER_PROFILE_IMPL_H_
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/profile_impl.h | C++ | unknown | 8,448 |
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "weblayer/browser/proxying_url_loader_factory_impl.h"
#include "base/time/time.h"
#include "components/embedder_support/android/util/android_stream_reader_url_loader.h"
#include "components/embedder_support/android/util/response_delegate_impl.h"
#include "components/embedder_support/android/util/web_resource_response.h"
#include "content/public/browser/navigation_controller.h"
#include "content/public/browser/navigation_entry.h"
#include "content/public/browser/web_contents.h"
#include "mojo/public/cpp/system/data_pipe_producer.h"
#include "mojo/public/cpp/system/string_data_source.h"
#include "weblayer/browser/navigation_entry_data.h"
namespace weblayer {
namespace {
struct WriteData {
mojo::Remote<network::mojom::URLLoaderClient> client;
std::string data;
std::unique_ptr<mojo::DataPipeProducer> producer;
};
void OnWrite(std::unique_ptr<WriteData> write_data, MojoResult result) {
if (result != MOJO_RESULT_OK) {
write_data->client->OnComplete(
network::URLLoaderCompletionStatus(net::ERR_FAILED));
return;
}
network::URLLoaderCompletionStatus status(net::OK);
status.encoded_data_length = write_data->data.size();
status.encoded_body_length = write_data->data.size();
status.decoded_body_length = write_data->data.size();
write_data->client->OnComplete(status);
}
void StartCachedLoad(
mojo::PendingRemote<network::mojom::URLLoaderClient> pending_client,
network::mojom::URLResponseHeadPtr response_head,
const std::string& data) {
mojo::Remote<network::mojom::URLLoaderClient> client(
std::move(pending_client));
mojo::ScopedDataPipeProducerHandle producer;
mojo::ScopedDataPipeConsumerHandle consumer;
if (CreateDataPipe(nullptr, producer, consumer) != MOJO_RESULT_OK) {
client->OnComplete(
network::URLLoaderCompletionStatus(net::ERR_INSUFFICIENT_RESOURCES));
return;
}
client->OnReceiveResponse(std::move(response_head), std::move(consumer),
absl::nullopt);
auto write_data = std::make_unique<WriteData>();
write_data->client = std::move(client);
write_data->data = std::move(data);
write_data->producer =
std::make_unique<mojo::DataPipeProducer>(std::move(producer));
mojo::DataPipeProducer* producer_ptr = write_data->producer.get();
base::StringPiece string_piece(write_data->data);
producer_ptr->Write(
std::make_unique<mojo::StringDataSource>(
string_piece, mojo::StringDataSource::AsyncWritingMode::
STRING_STAYS_VALID_UNTIL_COMPLETION),
base::BindOnce(OnWrite, std::move(write_data)));
}
// Returns a NavigationEntry (pending or committed) for the given id if it
// exists.
content::NavigationEntry* GetNavigationEntryFromUniqueId(
int frame_tree_node_id,
int navigation_entry_unique_id) {
auto* web_contents =
content::WebContents::FromFrameTreeNodeId(frame_tree_node_id);
if (!web_contents)
return nullptr;
auto& controller = web_contents->GetController();
auto* pending_entry = controller.GetPendingEntry();
if (pending_entry &&
pending_entry->GetUniqueID() == navigation_entry_unique_id) {
return pending_entry;
}
// Entry might have committed.
for (int i = 0; i < controller.GetEntryCount(); ++i) {
if (controller.GetEntryAtIndex(i)->GetUniqueID() ==
navigation_entry_unique_id)
return controller.GetEntryAtIndex(i);
}
return nullptr;
}
// Returns true if the response headers indicate that the response is still
// valid without going over the network.
bool IsCachedResponseValid(net::HttpResponseHeaders* headers,
base::Time request_time,
base::Time response_time) {
return headers->RequiresValidation(request_time, response_time,
base::Time::Now()) == net::VALIDATION_NONE;
}
// A ResponseDelegate for AndroidStreamReaderURLLoader which will cache the
// response if it's successful. This allows back-forward navigations to reuse an
// InputStream.
class CachingResponseDelegate : public embedder_support::ResponseDelegateImpl {
public:
CachingResponseDelegate(
std::unique_ptr<embedder_support::WebResourceResponse> response,
int frame_tree_node_id,
int navigation_entry_unique_id)
: ResponseDelegateImpl(std::move(response)),
frame_tree_node_id_(frame_tree_node_id),
navigation_entry_unique_id_(navigation_entry_unique_id),
request_time_(base::Time::Now()) {}
~CachingResponseDelegate() override = default;
// embedder_support::ResponseDelegateImpl implementation:
bool ShouldCacheResponse(network::mojom::URLResponseHead* response) override {
response_time_ = base::Time::Now();
// If at this point the response isn't cacheable it'll never be.
if (!IsCachedResponseValid(response->headers.get(), request_time_,
response_time_)) {
return false;
}
response_head_ = response->Clone();
return true;
}
void OnResponseCache(const std::string& data) override {
content::NavigationEntry* entry = GetNavigationEntryFromUniqueId(
frame_tree_node_id_, navigation_entry_unique_id_);
if (!entry)
return;
auto* entry_data = NavigationEntryData::Get(entry);
auto response_data = std::make_unique<NavigationEntryData::ResponseData>();
response_data->response_head = std::move(response_head_);
response_data->data = data;
response_data->request_time = request_time_;
response_data->response_time = response_time_;
entry_data->set_response_data(std::move(response_data));
}
private:
int frame_tree_node_id_;
int navigation_entry_unique_id_;
// The time that this object was created.
base::Time request_time_;
// The time that we sent the response headers.
base::Time response_time_;
network::mojom::URLResponseHeadPtr response_head_;
};
} // namespace
ProxyingURLLoaderFactoryImpl::ProxyingURLLoaderFactoryImpl(
mojo::PendingReceiver<network::mojom::URLLoaderFactory> loader_receiver,
mojo::PendingRemote<network::mojom::URLLoaderFactory> target_factory_remote,
const GURL& url_for_response,
std::unique_ptr<embedder_support::WebResourceResponse> response,
int frame_tree_node_id,
int navigation_entry_unique_id)
: url_for_response_(url_for_response),
response_(std::move(response)),
frame_tree_node_id_(frame_tree_node_id),
navigation_entry_unique_id_(navigation_entry_unique_id) {
DCHECK(response_ ||
HasCachedInputStream(frame_tree_node_id, navigation_entry_unique_id));
target_factory_.Bind(std::move(target_factory_remote));
target_factory_.set_disconnect_handler(
base::BindOnce(&ProxyingURLLoaderFactoryImpl::OnTargetFactoryError,
base::Unretained(this)));
proxy_receivers_.Add(this, std::move(loader_receiver));
proxy_receivers_.set_disconnect_handler(
base::BindRepeating(&ProxyingURLLoaderFactoryImpl::OnProxyBindingError,
base::Unretained(this)));
}
ProxyingURLLoaderFactoryImpl::~ProxyingURLLoaderFactoryImpl() = default;
bool ProxyingURLLoaderFactoryImpl::HasCachedInputStream(
int frame_tree_node_id,
int navigation_entry_unique_id) {
auto* entry = GetNavigationEntryFromUniqueId(frame_tree_node_id,
navigation_entry_unique_id);
if (!entry)
return false;
auto* entry_data = NavigationEntryData::Get(entry);
if (!entry_data)
return false;
auto* response_data = entry_data->response_data();
if (!response_data)
return false;
if (!IsCachedResponseValid(response_data->response_head->headers.get(),
response_data->request_time,
response_data->response_time)) {
// Cache expired so remove it.
entry_data->reset_response_data();
return false;
}
return true;
}
void ProxyingURLLoaderFactoryImpl::CreateLoaderAndStart(
mojo::PendingReceiver<network::mojom::URLLoader> loader,
int32_t request_id,
uint32_t options,
const network::ResourceRequest& request,
mojo::PendingRemote<network::mojom::URLLoaderClient> client,
const net::MutableNetworkTrafficAnnotationTag& traffic_annotation) {
if (url_for_response_ == request.url) {
if (response_) {
auto* stream_loader = new embedder_support::AndroidStreamReaderURLLoader(
request, std::move(client), traffic_annotation,
std::make_unique<CachingResponseDelegate>(
std::move(response_), frame_tree_node_id_,
navigation_entry_unique_id_),
absl::nullopt);
stream_loader->Start();
return;
}
if (HasCachedInputStream(frame_tree_node_id_,
navigation_entry_unique_id_)) {
auto* entry = GetNavigationEntryFromUniqueId(frame_tree_node_id_,
navigation_entry_unique_id_);
auto* entry_data = NavigationEntryData::Get(entry);
auto* response_data = entry_data->response_data();
StartCachedLoad(std::move(client), response_data->response_head->Clone(),
response_data->data);
return;
}
}
target_factory_->CreateLoaderAndStart(std::move(loader), request_id, options,
request, std::move(client),
traffic_annotation);
}
void ProxyingURLLoaderFactoryImpl::Clone(
mojo::PendingReceiver<network::mojom::URLLoaderFactory> loader_receiver) {
proxy_receivers_.Add(this, std::move(loader_receiver));
}
void ProxyingURLLoaderFactoryImpl::OnTargetFactoryError() {
delete this;
}
void ProxyingURLLoaderFactoryImpl::OnProxyBindingError() {
if (proxy_receivers_.empty())
delete this;
}
} // namespace weblayer
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/proxying_url_loader_factory_impl.cc | C++ | unknown | 9,998 |
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef WEBLAYER_BROWSER_PROXYING_URL_LOADER_FACTORY_IMPL_H_
#define WEBLAYER_BROWSER_PROXYING_URL_LOADER_FACTORY_IMPL_H_
#include "mojo/public/cpp/bindings/receiver_set.h"
#include "mojo/public/cpp/bindings/remote.h"
#include "services/network/public/mojom/url_loader_factory.mojom.h"
#include "url/gurl.h"
namespace embedder_support {
class WebResourceResponse;
}
namespace weblayer {
// Used to service navigations when the WebResourceResponse was specified.
// Otherwise it will forward the request to the original URLLoaderFactory.
class ProxyingURLLoaderFactoryImpl : public network::mojom::URLLoaderFactory {
public:
ProxyingURLLoaderFactoryImpl(
mojo::PendingReceiver<network::mojom::URLLoaderFactory> loader_receiver,
mojo::PendingRemote<network::mojom::URLLoaderFactory>
target_factory_remote,
const GURL& url_for_response,
std::unique_ptr<embedder_support::WebResourceResponse> response,
int frame_tree_node_id,
int navigation_entry_unique_id);
ProxyingURLLoaderFactoryImpl(const ProxyingURLLoaderFactoryImpl&) = delete;
ProxyingURLLoaderFactoryImpl& operator=(const ProxyingURLLoaderFactoryImpl&) =
delete;
static bool HasCachedInputStream(int frame_tree_node_id,
int navigation_entry_unique_id);
void CreateLoaderAndStart(
mojo::PendingReceiver<network::mojom::URLLoader> loader,
int32_t request_id,
uint32_t options,
const network::ResourceRequest& request,
mojo::PendingRemote<network::mojom::URLLoaderClient> client,
const net::MutableNetworkTrafficAnnotationTag& traffic_annotation)
override;
void Clone(mojo::PendingReceiver<network::mojom::URLLoaderFactory>
loader_receiver) override;
private:
~ProxyingURLLoaderFactoryImpl() override;
void OnTargetFactoryError();
void OnProxyBindingError();
mojo::ReceiverSet<network::mojom::URLLoaderFactory> proxy_receivers_;
mojo::Remote<network::mojom::URLLoaderFactory> target_factory_;
GURL url_for_response_;
std::unique_ptr<embedder_support::WebResourceResponse> response_;
const int frame_tree_node_id_;
const int navigation_entry_unique_id_;
};
} // namespace weblayer
#endif // WEBLAYER_BROWSER_PROXYING_URL_LOADER_FACTORY_IMPL_H_
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/proxying_url_loader_factory_impl.h | C++ | unknown | 2,431 |
// Copyright 2022 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "weblayer/browser/reduce_accept_language_factory.h"
#include "components/keyed_service/content/browser_context_dependency_manager.h"
#include "components/reduce_accept_language/browser/reduce_accept_language_service.h"
#include "weblayer/browser/browser_context_impl.h"
#include "weblayer/browser/host_content_settings_map_factory.h"
namespace weblayer {
// static
reduce_accept_language::ReduceAcceptLanguageService*
ReduceAcceptLanguageFactory::GetForBrowserContext(
content::BrowserContext* context) {
return static_cast<reduce_accept_language::ReduceAcceptLanguageService*>(
GetInstance()->GetServiceForBrowserContext(context, true));
}
// static
ReduceAcceptLanguageFactory* ReduceAcceptLanguageFactory::GetInstance() {
static base::NoDestructor<ReduceAcceptLanguageFactory> instance;
return instance.get();
}
ReduceAcceptLanguageFactory::ReduceAcceptLanguageFactory()
: BrowserContextKeyedServiceFactory(
"ReduceAcceptLanguage",
BrowserContextDependencyManager::GetInstance()) {
DependsOn(HostContentSettingsMapFactory::GetInstance());
}
ReduceAcceptLanguageFactory::~ReduceAcceptLanguageFactory() = default;
KeyedService* ReduceAcceptLanguageFactory::BuildServiceInstanceFor(
content::BrowserContext* context) const {
return new reduce_accept_language::ReduceAcceptLanguageService(
HostContentSettingsMapFactory::GetForBrowserContext(context),
static_cast<BrowserContextImpl*>(context)->pref_service(),
context->IsOffTheRecord());
}
content::BrowserContext* ReduceAcceptLanguageFactory::GetBrowserContextToUse(
content::BrowserContext* context) const {
return context;
}
} // namespace weblayer | Zhao-PengFei35/chromium_src_4 | weblayer/browser/reduce_accept_language_factory.cc | C++ | unknown | 1,836 |
// Copyright 2022 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef WEBLAYER_BROWSER_REDUCE_ACCEPT_LANGUAGE_FACTORY_H_
#define WEBLAYER_BROWSER_REDUCE_ACCEPT_LANGUAGE_FACTORY_H_
#include "base/no_destructor.h"
#include "components/keyed_service/content/browser_context_keyed_service_factory.h"
#include "components/reduce_accept_language/browser/reduce_accept_language_service.h"
#include "content/public/browser/reduce_accept_language_controller_delegate.h"
namespace weblayer {
class ReduceAcceptLanguageFactory : public BrowserContextKeyedServiceFactory {
public:
static reduce_accept_language::ReduceAcceptLanguageService*
GetForBrowserContext(content::BrowserContext* context);
static ReduceAcceptLanguageFactory* GetInstance();
// Non-copyable, non-moveable.
ReduceAcceptLanguageFactory(const ReduceAcceptLanguageFactory&) = delete;
ReduceAcceptLanguageFactory& operator=(const ReduceAcceptLanguageFactory&) =
delete;
private:
friend base::NoDestructor<ReduceAcceptLanguageFactory>;
ReduceAcceptLanguageFactory();
~ReduceAcceptLanguageFactory() override;
// BrowserContextKeyedServiceFactory methods:
KeyedService* BuildServiceInstanceFor(
content::BrowserContext* context) const override;
content::BrowserContext* GetBrowserContextToUse(
content::BrowserContext* context) const override;
};
} // namespace weblayer
#endif // WEBLAYER_BROWSER_REDUCE_ACCEPT_LANGUAGE_FACTORY_H_
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/reduce_accept_language_factory.h | C++ | unknown | 1,523 |
// Copyright 2022 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "components/content_settings/core/browser/host_content_settings_map.h"
#include "components/language/core/browser/language_prefs.h"
#include "components/language/core/browser/pref_names.h"
#include "components/prefs/pref_service.h"
#include "components/reduce_accept_language/browser/reduce_accept_language_service.h"
#include "components/reduce_accept_language/browser/reduce_accept_language_service_test_util.h"
#include "url/gurl.h"
#include "url/origin.h"
#include "weblayer/browser/browser_context_impl.h"
#include "weblayer/browser/host_content_settings_map_factory.h"
#include "weblayer/browser/reduce_accept_language_factory.h"
#include "weblayer/browser/tab_impl.h"
#include "weblayer/shell/browser/shell.h"
#include "weblayer/test/weblayer_browser_test.h"
#include "weblayer/test/weblayer_browser_test_utils.h"
using reduce_accept_language::test::ReduceAcceptLanguageServiceTester;
namespace weblayer {
class ReduceAcceptLanguageServiceTest : public WebLayerBrowserTest {
public:
void SetUpOnMainThread() override {
WebLayerBrowserTest::SetUpOnMainThread();
service_tester_ = std::make_unique<ReduceAcceptLanguageServiceTester>(
settings_map(), service(), prefs());
language::LanguagePrefs(prefs()).SetUserSelectedLanguagesList(
{"en", "ja", "it"});
}
content::WebContents* web_contents() {
return static_cast<TabImpl*>(shell()->tab())->web_contents();
}
HostContentSettingsMap* settings_map() {
return HostContentSettingsMapFactory::GetForBrowserContext(
web_contents()->GetBrowserContext());
}
PrefService* prefs() {
return static_cast<BrowserContextImpl*>(web_contents()->GetBrowserContext())
->pref_service();
}
reduce_accept_language::ReduceAcceptLanguageService* service() {
return ReduceAcceptLanguageFactory::GetForBrowserContext(
web_contents()->GetBrowserContext());
}
ReduceAcceptLanguageServiceTester* tester() { return service_tester_.get(); }
private:
std::unique_ptr<ReduceAcceptLanguageServiceTester> service_tester_;
};
IN_PROC_BROWSER_TEST_F(ReduceAcceptLanguageServiceTest, GetAcceptLanguageList) {
tester()->VerifyFetchAcceptLanguageList({"en", "ja", "it"});
reduce_accept_language::ReduceAcceptLanguageService incognito_service(
settings_map(), prefs(), true);
// Verify incognito mode only has first accept language.
EXPECT_EQ(std::vector<std::string>{"en"},
incognito_service.GetUserAcceptLanguages());
}
IN_PROC_BROWSER_TEST_F(ReduceAcceptLanguageServiceTest, PersistLanguageFail) {
tester()->VerifyPersistFail(GURL("ws://example.com/"), "Zh-CN");
}
IN_PROC_BROWSER_TEST_F(ReduceAcceptLanguageServiceTest,
PersistLanguageSuccessJavaScriptNotEnabled) {
tester()->VerifyPersistSuccessOnJavaScriptDisable(
GURL("https://example.com/"), "Zh-CN");
}
IN_PROC_BROWSER_TEST_F(ReduceAcceptLanguageServiceTest,
PersistLanguageSuccess) {
tester()->VerifyPersistSuccess(GURL("https://example.com/"), "Zh-CN");
}
IN_PROC_BROWSER_TEST_F(ReduceAcceptLanguageServiceTest,
PersistLanguageMultipleHosts) {
tester()->VerifyPersistMultipleHostsSuccess(
{GURL("https://example1.com/"), GURL("https://example2.com/"),
GURL("http://example.com/")},
{"en-US", "es-MX", "zh-CN"});
}
} // namespace weblayer
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/reduce_accept_language_service_browsertest.cc | C++ | unknown | 3,507 |
<!doctype html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>WebLayer Internals</title>
<link rel="stylesheet" href="chrome://resources/css/text_defaults.css">
<script type="module" src="weblayer_internals.js"></script>
</head>
<body>
<h1>WebLayer Internals</h1>
<div>
<label id="remote-debug-label" hidden>
<input type="checkbox" id="remote-debug">
Enable remote debugging
</label>
</div>
</body>
</html>
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/resources/weblayer_internals/weblayer_internals.html | HTML | unknown | 489 |
// Copyright 2019 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
/* Javascript module for chrome://weblayer. */
import {isAndroid} from 'chrome://resources/js/platform.js';
import {$} from 'chrome://resources/js/util_ts.js';
import {PageHandler} from './weblayer_internals.mojom-webui.js';
/* Main entry point. */
window.document.addEventListener('DOMContentLoaded', async function() {
// Setup backend mojo.
const pageHandler = PageHandler.getRemote();
if (isAndroid) {
const {enabled} = await pageHandler.getRemoteDebuggingEnabled();
const checkbox = $('remote-debug');
checkbox.checked = enabled;
checkbox.addEventListener('click', (event) => {
pageHandler.setRemoteDebuggingEnabled(event.target.checked);
});
$('remote-debug-label').removeAttribute('hidden');
}
});
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/resources/weblayer_internals/weblayer_internals.js | JavaScript | unknown | 891 |
include_rules = [
"+components/safe_browsing/content/browser",
"+components/safe_browsing/content/common",
"+services/network/test",
]
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/safe_browsing/DEPS | Python | unknown | 141 |
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "weblayer/browser/safe_browsing/client_side_detection_service_factory.h"
#include "base/test/bind.h"
#include "base/test/scoped_feature_list.h"
#include "components/prefs/pref_service.h"
#include "components/safe_browsing/content/browser/client_side_detection_service.h"
#include "components/safe_browsing/content/browser/client_side_phishing_model.h"
#include "components/safe_browsing/content/common/safe_browsing.mojom.h"
#include "components/safe_browsing/core/common/proto/client_model.pb.h"
#include "components/safe_browsing/core/common/safe_browsing_prefs.h"
#include "content/public/test/browser_test.h"
#include "mojo/public/cpp/bindings/remote.h"
#include "services/service_manager/public/cpp/interface_provider.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "weblayer/browser/browser_context_impl.h"
#include "weblayer/browser/profile_impl.h"
#include "weblayer/browser/tab_impl.h"
#include "weblayer/common/features.h"
#include "weblayer/shell/browser/shell.h"
#include "weblayer/test/weblayer_browser_test.h"
#include "weblayer/test/weblayer_browser_test_utils.h"
namespace weblayer {
using safe_browsing::ClientSideDetectionService;
using safe_browsing::ClientSideModel;
using safe_browsing::ClientSidePhishingModel;
using ::testing::_;
using ::testing::ReturnRef;
using ::testing::StrictMock;
class ClientSideDetectionServiceBrowserTest : public WebLayerBrowserTest {
public:
ClientSideDetectionServiceBrowserTest() {
feature_list_.InitAndEnableFeature(
features::kWebLayerClientSidePhishingDetection);
}
content::WebContents* GetWebContents() {
return static_cast<TabImpl*>(shell()->tab())->web_contents();
}
private:
void SetUpOnMainThread() override {
NavigateAndWaitForCompletion(GURL("about:blank"), shell());
}
base::test::ScopedFeatureList feature_list_;
};
// TODO(crbug.com/1217128): Re-enable this test, once we have a more reliable
// method of ensuring the SetPhishingModel IPC comes before the
// StartPhishingDetection IPC.
IN_PROC_BROWSER_TEST_F(ClientSideDetectionServiceBrowserTest,
DISABLED_NewHostGetsModel) {
PrefService* prefs = GetProfile()->GetBrowserContext()->pref_service();
prefs->SetBoolean(::prefs::kSafeBrowsingEnabled, false);
ClientSideModel model;
model.set_max_words_per_term(0);
std::string model_str;
model.SerializeToString(&model_str);
ClientSidePhishingModel::GetInstance()->SetModelStrForTesting(model_str);
// Enable Safe Browsing and the CSD service.
prefs->SetBoolean(::prefs::kSafeBrowsingEnabled, true);
base::RunLoop run_loop;
content::RenderFrameHost* rfh = GetWebContents()->GetPrimaryMainFrame();
mojo::Remote<safe_browsing::mojom::PhishingDetector> phishing_detector;
rfh->GetRemoteInterfaces()->GetInterface(
phishing_detector.BindNewPipeAndPassReceiver());
safe_browsing::mojom::PhishingDetectorResult result;
std::string verdict;
phishing_detector->StartPhishingDetection(
GURL("about:blank"),
base::BindOnce(
[](base::RepeatingClosure quit_closure,
safe_browsing::mojom::PhishingDetectorResult* out_result,
std::string* out_verdict,
safe_browsing::mojom::PhishingDetectorResult result,
const std::string& verdict) {
*out_result = result;
*out_verdict = verdict;
quit_closure.Run();
},
run_loop.QuitClosure(), &result, &verdict));
run_loop.Run();
// The model classification will run, but will return an invalid score.
EXPECT_EQ(result,
safe_browsing::mojom::PhishingDetectorResult::INVALID_SCORE);
}
} // namespace weblayer
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/safe_browsing/client_side_detection_service_browsertest.cc | C++ | unknown | 3,820 |
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "weblayer/browser/safe_browsing/client_side_detection_service_factory.h"
#include "base/no_destructor.h"
#include "components/keyed_service/content/browser_context_dependency_manager.h"
#include "components/safe_browsing/content/browser/client_side_detection_service.h"
#include "content/public/browser/browser_context.h"
#include "weblayer/browser/browser_context_impl.h"
#include "weblayer/browser/browser_process.h"
#include "weblayer/browser/feature_list_creator.h"
#include "weblayer/browser/safe_browsing/weblayer_client_side_detection_service_delegate.h"
#include "weblayer/common/features.h"
namespace weblayer {
// static
safe_browsing::ClientSideDetectionService*
ClientSideDetectionServiceFactory::GetForBrowserContext(
content::BrowserContext* browser_context) {
if (base::FeatureList::IsEnabled(
features::kWebLayerClientSidePhishingDetection)) {
return static_cast<safe_browsing::ClientSideDetectionService*>(
GetInstance()->GetServiceForBrowserContext(browser_context,
/* create= */ true));
}
return nullptr;
}
// static
ClientSideDetectionServiceFactory*
ClientSideDetectionServiceFactory::GetInstance() {
static base::NoDestructor<ClientSideDetectionServiceFactory> factory;
return factory.get();
}
ClientSideDetectionServiceFactory::ClientSideDetectionServiceFactory()
: BrowserContextKeyedServiceFactory(
"ClientSideDetectionService",
BrowserContextDependencyManager::GetInstance()) {}
ClientSideDetectionServiceFactory::~ClientSideDetectionServiceFactory() =
default;
KeyedService* ClientSideDetectionServiceFactory::BuildServiceInstanceFor(
content::BrowserContext* context) const {
return new safe_browsing::ClientSideDetectionService(
std::make_unique<WebLayerClientSideDetectionServiceDelegate>(
static_cast<BrowserContextImpl*>(context)),
/*opt_guide=*/nullptr,
/*background_task_runner=*/nullptr);
}
content::BrowserContext*
ClientSideDetectionServiceFactory::GetBrowserContextToUse(
content::BrowserContext* context) const {
return context;
}
} // namespace weblayer
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/safe_browsing/client_side_detection_service_factory.cc | C++ | unknown | 2,312 |
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef WEBLAYER_BROWSER_SAFE_BROWSING_CLIENT_SIDE_DETECTION_SERVICE_FACTORY_H_
#define WEBLAYER_BROWSER_SAFE_BROWSING_CLIENT_SIDE_DETECTION_SERVICE_FACTORY_H_
#include "base/no_destructor.h"
#include "components/keyed_service/content/browser_context_keyed_service_factory.h"
class KeyedService;
namespace content {
class BrowserContext;
}
namespace safe_browsing {
class ClientSideDetectionService;
}
namespace weblayer {
// Singleton that owns ClientSideDetectionServiceFactory objects and associates
// them them with BrowserContextImpl instances.
class ClientSideDetectionServiceFactory
: public BrowserContextKeyedServiceFactory {
public:
ClientSideDetectionServiceFactory(const ClientSideDetectionServiceFactory&) =
delete;
ClientSideDetectionServiceFactory& operator=(
const ClientSideDetectionServiceFactory&) = delete;
// Creates the service if it doesn't exist already for the given
// |browser_context|. If the service already exists, return its pointer.
static safe_browsing::ClientSideDetectionService* GetForBrowserContext(
content::BrowserContext* browser_context);
// Get the singleton instance.
static ClientSideDetectionServiceFactory* GetInstance();
private:
friend class base::NoDestructor<ClientSideDetectionServiceFactory>;
ClientSideDetectionServiceFactory();
~ClientSideDetectionServiceFactory() override;
// BrowserContextKeyedServiceFactory:
KeyedService* BuildServiceInstanceFor(
content::BrowserContext* context) const override;
content::BrowserContext* GetBrowserContextToUse(
content::BrowserContext* context) const override;
};
} // namespace weblayer
#endif // WEBLAYER_BROWSER_SAFE_BROWSING_CLIENT_SIDE_DETECTION_SERVICE_FACTORY_H_
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/safe_browsing/client_side_detection_service_factory.h | C++ | unknown | 1,886 |
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "weblayer/browser/safe_browsing/client_side_detection_service_factory.h"
#include "base/test/scoped_feature_list.h"
#include "weblayer/browser/browser_context_impl.h"
#include "weblayer/browser/profile_impl.h"
#include "weblayer/common/features.h"
#include "weblayer/test/weblayer_browser_test.h"
namespace weblayer {
class ClientSideDetectionServiceFactoryBrowserTest
: public WebLayerBrowserTest {
public:
ClientSideDetectionServiceFactoryBrowserTest() {
feature_list_.InitAndDisableFeature(
features::kWebLayerClientSidePhishingDetection);
}
private:
void SetUpOnMainThread() override {}
base::test::ScopedFeatureList feature_list_;
};
IN_PROC_BROWSER_TEST_F(ClientSideDetectionServiceFactoryBrowserTest,
ClientDetectionServiceNullWhenDisabled) {
EXPECT_EQ(nullptr, ClientSideDetectionServiceFactory::GetForBrowserContext(
GetProfile()->GetBrowserContext()));
}
} // namespace weblayer
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/safe_browsing/client_side_detection_service_factory_browsertest.cc | C++ | unknown | 1,125 |
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "weblayer/browser/safe_browsing/real_time_url_lookup_service_factory.h"
#include "base/functional/bind.h"
#include "components/keyed_service/content/browser_context_dependency_manager.h"
#include "components/safe_browsing/core/browser/realtime/url_lookup_service.h"
#include "components/safe_browsing/core/browser/safe_browsing_token_fetcher.h"
#include "components/safe_browsing/core/common/utils.h"
#include "content/public/browser/browser_context.h"
#include "services/network/public/cpp/cross_thread_pending_shared_url_loader_factory.h"
#include "weblayer/browser/browser_context_impl.h"
#include "weblayer/browser/browser_process.h"
#include "weblayer/browser/feature_list_creator.h"
#include "weblayer/browser/profile_impl.h"
#include "weblayer/browser/safe_browsing/safe_browsing_service.h"
#include "weblayer/browser/safe_browsing/safe_browsing_token_fetcher_impl.h"
#include "weblayer/browser/safe_browsing/weblayer_user_population_helper.h"
#include "weblayer/browser/verdict_cache_manager_factory.h"
namespace weblayer {
// static
safe_browsing::RealTimeUrlLookupService*
RealTimeUrlLookupServiceFactory::GetForBrowserContext(
content::BrowserContext* browser_context) {
return static_cast<safe_browsing::RealTimeUrlLookupService*>(
GetInstance()->GetServiceForBrowserContext(browser_context,
/* create= */ true));
}
// static
RealTimeUrlLookupServiceFactory*
RealTimeUrlLookupServiceFactory::GetInstance() {
return base::Singleton<RealTimeUrlLookupServiceFactory>::get();
}
RealTimeUrlLookupServiceFactory::RealTimeUrlLookupServiceFactory()
: BrowserContextKeyedServiceFactory(
"RealTimeUrlLookupService",
BrowserContextDependencyManager::GetInstance()) {}
KeyedService* RealTimeUrlLookupServiceFactory::BuildServiceInstanceFor(
content::BrowserContext* context) const {
auto url_loader_factory =
std::make_unique<network::CrossThreadPendingSharedURLLoaderFactory>(
BrowserProcess::GetInstance()
->GetSafeBrowsingService()
->GetURLLoaderFactory());
return new safe_browsing::RealTimeUrlLookupService(
network::SharedURLLoaderFactory::Create(std::move(url_loader_factory)),
VerdictCacheManagerFactory::GetForBrowserContext(context),
base::BindRepeating(&GetUserPopulationForBrowserContext, context),
static_cast<BrowserContextImpl*>(context)->pref_service(),
std::make_unique<SafeBrowsingTokenFetcherImpl>(base::BindRepeating(
&ProfileImpl::access_token_fetch_delegate,
base::Unretained(ProfileImpl::FromBrowserContext(context)))),
// TODO(crbug.com/1171215): Change this to production mechanism for
// enabling Gaia-keyed URL lookups once that mechanism is determined.
base::BindRepeating(&RealTimeUrlLookupServiceFactory::
access_token_fetches_enabled_for_testing,
base::Unretained(this)),
static_cast<BrowserContextImpl*>(context)->IsOffTheRecord(),
FeatureListCreator::GetInstance()->variations_service(),
// Referrer chain provider is currently not available on WebLayer. Once it
// is implemented, inject it to enable referrer chain in real time
// requests.
/*referrer_chain_provider=*/nullptr);
}
} // namespace weblayer
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/safe_browsing/real_time_url_lookup_service_factory.cc | C++ | unknown | 3,501 |
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef WEBLAYER_BROWSER_SAFE_BROWSING_REAL_TIME_URL_LOOKUP_SERVICE_FACTORY_H_
#define WEBLAYER_BROWSER_SAFE_BROWSING_REAL_TIME_URL_LOOKUP_SERVICE_FACTORY_H_
#include "base/memory/singleton.h"
#include "components/keyed_service/content/browser_context_keyed_service_factory.h"
class KeyedService;
namespace content {
class BrowserContext;
}
namespace safe_browsing {
class RealTimeUrlLookupService;
} // namespace safe_browsing
namespace weblayer {
// Singleton that owns RealTimeUrlLookupService objects and associates them
// them with BrowserContextImpl instances.
class RealTimeUrlLookupServiceFactory
: public BrowserContextKeyedServiceFactory {
public:
// Creates the service if it doesn't exist already for the given
// |browser_context|. If the service already exists, return its pointer.
static safe_browsing::RealTimeUrlLookupService* GetForBrowserContext(
content::BrowserContext* browser_context);
// Get the singleton instance.
static RealTimeUrlLookupServiceFactory* GetInstance();
// TODO(crbug.com/1171215): Remove this once browsertests can enable this
// functionality via the production mechanism for doing so.
void set_access_token_fetches_enabled_for_testing() {
access_token_fetches_enabled_for_testing_ = true;
}
private:
friend struct base::DefaultSingletonTraits<RealTimeUrlLookupServiceFactory>;
RealTimeUrlLookupServiceFactory();
~RealTimeUrlLookupServiceFactory() override = default;
RealTimeUrlLookupServiceFactory(const RealTimeUrlLookupServiceFactory&) =
delete;
RealTimeUrlLookupServiceFactory& operator=(
const RealTimeUrlLookupServiceFactory&) = delete;
// BrowserContextKeyedServiceFactory:
KeyedService* BuildServiceInstanceFor(
content::BrowserContext* context) const override;
// TODO(crbug.com/1171215): Remove this once browsertests can enable this
// functionality via the production mechanism for doing so.
bool access_token_fetches_enabled_for_testing(
bool user_has_enabled_enhanced_protection) const {
return access_token_fetches_enabled_for_testing_;
}
// TODO(crbug.com/1171215): Remove this once browsertests can enable this
// functionality via the production mechanism for doing so.
bool access_token_fetches_enabled_for_testing_ = false;
};
} // namespace weblayer
#endif // WEBLAYER_BROWSER_SAFE_BROWSING_REAL_TIME_URL_LOOKUP_SERVICE_FACTORY_H_
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/safe_browsing/real_time_url_lookup_service_factory.h | C++ | unknown | 2,549 |
// Copyright 2019 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <map>
#include "base/memory/raw_ptr.h"
#include "components/prefs/pref_service.h"
#include "components/safe_browsing/android/safe_browsing_api_handler_bridge.h"
#include "components/safe_browsing/content/browser/base_blocking_page.h"
#include "components/safe_browsing/content/browser/safe_browsing_blocking_page.h"
#include "components/safe_browsing/core/browser/db/v4_protocol_manager_util.h"
#include "components/safe_browsing/core/browser/safe_browsing_token_fetcher.h"
#include "components/security_interstitials/content/security_interstitial_page.h"
#include "components/security_interstitials/content/security_interstitial_tab_helper.h"
#include "components/user_prefs/user_prefs.h"
#include "content/public/browser/browser_context.h"
#include "content/public/browser/browser_task_traits.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/render_process_host.h"
#include "content/public/browser/web_contents.h"
#include "content/public/test/test_utils.h"
#include "google_apis/gaia/gaia_constants.h"
#include "net/dns/mock_host_resolver.h"
#include "net/test/embedded_test_server/embedded_test_server.h"
#include "weblayer/browser/browser_context_impl.h"
#include "weblayer/browser/browser_impl.h"
#include "weblayer/browser/profile_impl.h"
#include "weblayer/browser/safe_browsing/real_time_url_lookup_service_factory.h"
#include "weblayer/browser/tab_impl.h"
#include "weblayer/public/google_account_access_token_fetch_delegate.h"
#include "weblayer/public/navigation.h"
#include "weblayer/public/navigation_controller.h"
#include "weblayer/public/navigation_observer.h"
#include "weblayer/public/profile.h"
#include "weblayer/public/tab.h"
#include "weblayer/shell/browser/shell.h"
#include "weblayer/test/load_completion_observer.h"
#include "weblayer/test/weblayer_browser_test.h"
#include "weblayer/test/weblayer_browser_test_utils.h"
namespace weblayer {
namespace {
// Implementation of GoogleAccountAccessTokenFetchDelegate used to exercise safe
// browsing access token fetches.
class TestAccessTokenFetchDelegate
: public GoogleAccountAccessTokenFetchDelegate {
public:
TestAccessTokenFetchDelegate() = default;
~TestAccessTokenFetchDelegate() override = default;
// GoogleAccountAccessTokenFetchDelegate:
void FetchAccessToken(const std::set<std::string>& scopes,
OnTokenFetchedCallback callback) override {
has_received_request_ = true;
scopes_from_most_recent_request_ = scopes;
if (should_respond_to_request_) {
std::move(callback).Run("token");
} else {
outstanding_request_ = std::move(callback);
}
}
void OnAccessTokenIdentifiedAsInvalid(const std::set<std::string>& scopes,
const std::string& token) override {
NOTREACHED();
}
void set_should_respond_to_request(bool should_respond) {
should_respond_to_request_ = should_respond;
}
bool has_received_request() { return has_received_request_; }
const std::set<std::string>& scopes_from_most_recent_request() {
return scopes_from_most_recent_request_;
}
private:
bool should_respond_to_request_ = false;
bool has_received_request_ = false;
std::set<std::string> scopes_from_most_recent_request_;
OnTokenFetchedCallback outstanding_request_;
};
// Observer customized for safe browsing navigation failures.
class SafeBrowsingErrorNavigationObserver : public NavigationObserver {
public:
SafeBrowsingErrorNavigationObserver(const GURL& url, Shell* shell)
: url_(url), tab_(shell->tab()) {
tab_->GetNavigationController()->AddObserver(this);
}
~SafeBrowsingErrorNavigationObserver() override {
tab_->GetNavigationController()->RemoveObserver(this);
}
void NavigationFailed(Navigation* navigation) override {
if (navigation->GetURL() != url_)
return;
EXPECT_EQ(navigation->GetLoadError(),
Navigation::LoadError::kSafeBrowsingError);
run_loop_.Quit();
}
// Begins waiting for a Navigation within |shell_| and to |url_| to fail. In
// the failure callback verifies that the navigation failed with a safe
// browsing error.
void WaitForNavigationFailureWithSafeBrowsingError() { run_loop_.Run(); }
private:
const GURL url_;
raw_ptr<Tab> tab_;
base::RunLoop run_loop_;
};
using SbBridge = safe_browsing::SafeBrowsingApiHandlerBridge;
void RunCallbackOnIOThread(std::unique_ptr<SbBridge::ResponseCallback> callback,
safe_browsing::SBThreatType threat_type,
const safe_browsing::ThreatMetadata& metadata) {
content::GetIOThreadTaskRunner({})->PostTask(
FROM_HERE, base::BindOnce(std::move(*callback), threat_type, metadata));
}
} // namespace
class TestUrlCheckInterceptor : public safe_browsing::UrlCheckInterceptor {
public:
void Add(const GURL& url, safe_browsing::SBThreatType threat_type) {
map_[url] = threat_type;
}
void Clear() { map_.clear(); }
// safe_browsing::UrlCheckInterceptor
void Check(std::unique_ptr<SbBridge::ResponseCallback> callback,
const GURL& url) const override {
RunCallbackOnIOThread(std::move(callback), Find(url),
safe_browsing::ThreatMetadata());
}
~TestUrlCheckInterceptor() override {}
private:
safe_browsing::SBThreatType Find(const GURL& url) const {
auto it = map_.find(url);
if (it != map_.end())
return it->second;
// If the url is not in the map assume it is safe.
return safe_browsing::SB_THREAT_TYPE_SAFE;
}
std::map<GURL, safe_browsing::SBThreatType> map_;
};
class SafeBrowsingBrowserTest : public WebLayerBrowserTest {
public:
SafeBrowsingBrowserTest()
: url_check_interceptor_(std::make_unique<TestUrlCheckInterceptor>()) {}
SafeBrowsingBrowserTest(const SafeBrowsingBrowserTest&) = delete;
SafeBrowsingBrowserTest& operator=(const SafeBrowsingBrowserTest&) = delete;
~SafeBrowsingBrowserTest() override = default;
void SetUpOnMainThread() override {
InitializeOnMainThread();
// Safe Browsing is enabled by default
ASSERT_TRUE(GetSafeBrowsingEnabled());
profile()->SetGoogleAccountAccessTokenFetchDelegate(
&access_token_fetch_delegate_);
}
void TearDown() override {
profile()->SetGoogleAccountAccessTokenFetchDelegate(nullptr);
SbBridge::GetInstance().SetInterceptorForTesting(nullptr);
}
void InitializeOnMainThread() {
NavigateAndWaitForCompletion(GURL("about:blank"), shell());
SbBridge::GetInstance().SetInterceptorForTesting(
url_check_interceptor_.get());
// Some tests need to be able to navigate to URLs on domains that are not
// explicitly localhost (e.g., so that realtime URL lookups occur on these
// navigations).
host_resolver()->AddRule("*", "127.0.0.1");
ASSERT_TRUE(embedded_test_server()->Start());
url_ = embedded_test_server()->GetURL("/simple_page.html");
}
void SetSafeBrowsingEnabled(bool value) {
GetProfile()->SetBooleanSetting(SettingType::BASIC_SAFE_BROWSING_ENABLED,
value);
}
void SetRealTimeURLLookupsEnabled(bool value) {
GetProfile()->SetBooleanSetting(
SettingType::REAL_TIME_SAFE_BROWSING_ENABLED, value);
}
void EnableSafeBrowsingAccessTokenFetches() {
RealTimeUrlLookupServiceFactory::GetInstance()
->set_access_token_fetches_enabled_for_testing();
}
bool GetSafeBrowsingEnabled() {
return GetProfile()->GetBooleanSetting(
SettingType::BASIC_SAFE_BROWSING_ENABLED);
}
void NavigateWithThreatType(const safe_browsing::SBThreatType& threatType,
bool expect_interstitial) {
url_check_interceptor_->Add(url_, threatType);
Navigate(url_, expect_interstitial);
}
void Navigate(const GURL& url, bool expect_interstitial) {
LoadCompletionObserver load_observer(shell());
shell()->tab()->GetNavigationController()->Navigate(url);
load_observer.Wait();
EXPECT_EQ(expect_interstitial, HasInterstitial());
if (expect_interstitial) {
ASSERT_EQ(safe_browsing::SafeBrowsingBlockingPage::kTypeForTesting,
GetSecurityInterstitialPage()->GetTypeForTesting());
EXPECT_TRUE(GetSecurityInterstitialPage()->GetHTMLContents().length() >
0);
}
}
void NavigateWithSubResourceAndThreatType(
const safe_browsing::SBThreatType& threat_type,
bool expect_interstitial) {
GURL page_with_script_url =
embedded_test_server()->GetURL("/simple_page_with_script.html");
GURL script_url = embedded_test_server()->GetURL("/script.js");
url_check_interceptor_->Add(script_url, threat_type);
Navigate(page_with_script_url, expect_interstitial);
}
protected:
content::WebContents* GetWebContents() {
Tab* tab = shell()->tab();
TabImpl* tab_impl = static_cast<TabImpl*>(tab);
return tab_impl->web_contents();
}
security_interstitials::SecurityInterstitialPage*
GetSecurityInterstitialPage() {
security_interstitials::SecurityInterstitialTabHelper* helper =
security_interstitials::SecurityInterstitialTabHelper::FromWebContents(
GetWebContents());
return helper
? helper
->GetBlockingPageForCurrentlyCommittedNavigationForTesting()
: nullptr;
}
bool HasInterstitial() { return GetSecurityInterstitialPage() != nullptr; }
void KillRenderer() {
content::RenderProcessHost* child_process =
static_cast<TabImpl*>(shell()->tab())
->web_contents()
->GetPrimaryMainFrame()
->GetProcess();
content::RenderProcessHostWatcher crash_observer(
child_process,
content::RenderProcessHostWatcher::WATCH_FOR_PROCESS_EXIT);
child_process->Shutdown(0);
crash_observer.Wait();
}
std::unique_ptr<TestUrlCheckInterceptor> url_check_interceptor_;
GURL url_;
ProfileImpl* profile() {
auto* tab_impl = static_cast<TabImpl*>(shell()->tab());
return tab_impl->profile();
}
TestAccessTokenFetchDelegate* access_token_fetch_delegate() {
return &access_token_fetch_delegate_;
}
private:
TestAccessTokenFetchDelegate access_token_fetch_delegate_;
};
class SafeBrowsingDisabledBrowserTest : public SafeBrowsingBrowserTest {
public:
SafeBrowsingDisabledBrowserTest() {}
SafeBrowsingDisabledBrowserTest(const SafeBrowsingDisabledBrowserTest&) =
delete;
SafeBrowsingDisabledBrowserTest& operator=(
const SafeBrowsingDisabledBrowserTest&) = delete;
~SafeBrowsingDisabledBrowserTest() override = default;
void SetUpOnMainThread() override {
SetSafeBrowsingEnabled(false);
SafeBrowsingBrowserTest::InitializeOnMainThread();
ASSERT_FALSE(GetSafeBrowsingEnabled());
}
};
IN_PROC_BROWSER_TEST_F(SafeBrowsingBrowserTest,
DoesNotShowInterstitial_NoRestriction) {
Navigate(url_, false);
}
IN_PROC_BROWSER_TEST_F(SafeBrowsingBrowserTest, DoesNotShowInterstitial_Safe) {
NavigateWithThreatType(safe_browsing::SB_THREAT_TYPE_SAFE, false);
}
IN_PROC_BROWSER_TEST_F(SafeBrowsingBrowserTest, ShowsInterstitial_Malware) {
NavigateWithThreatType(safe_browsing::SB_THREAT_TYPE_URL_MALWARE, true);
}
IN_PROC_BROWSER_TEST_F(SafeBrowsingBrowserTest, ShowsInterstitial_Phishing) {
NavigateWithThreatType(safe_browsing::SB_THREAT_TYPE_URL_PHISHING, true);
}
IN_PROC_BROWSER_TEST_F(SafeBrowsingBrowserTest, CheckNavigationErrorType) {
auto threat_types = {
safe_browsing::SB_THREAT_TYPE_URL_PHISHING,
safe_browsing::SB_THREAT_TYPE_URL_MALWARE,
safe_browsing::SB_THREAT_TYPE_URL_UNWANTED,
safe_browsing::SB_THREAT_TYPE_BILLING,
};
for (auto threat_type : threat_types) {
SafeBrowsingErrorNavigationObserver observer(url_, shell());
url_check_interceptor_->Clear();
url_check_interceptor_->Add(url_, threat_type);
shell()->tab()->GetNavigationController()->Navigate(url_);
observer.WaitForNavigationFailureWithSafeBrowsingError();
}
}
// Tests below are disabled due to failures on Android.
// See crbug.com/1340200.
IN_PROC_BROWSER_TEST_F(SafeBrowsingBrowserTest, ShowsInterstitial_Unwanted) {
NavigateWithThreatType(safe_browsing::SB_THREAT_TYPE_URL_UNWANTED, true);
}
IN_PROC_BROWSER_TEST_F(SafeBrowsingBrowserTest, ShowsInterstitial_Billing) {
NavigateWithThreatType(safe_browsing::SB_THREAT_TYPE_BILLING, true);
}
IN_PROC_BROWSER_TEST_F(SafeBrowsingBrowserTest,
ShowsInterstitial_Malware_Subresource) {
NavigateWithSubResourceAndThreatType(
safe_browsing::SB_THREAT_TYPE_URL_MALWARE, true);
}
IN_PROC_BROWSER_TEST_F(SafeBrowsingBrowserTest,
DoesNotShowInterstitial_Phishing_disableSB) {
// Test that the browser checks the safe browsing setting for new navigations.
SetSafeBrowsingEnabled(false);
NavigateWithThreatType(safe_browsing::SB_THREAT_TYPE_URL_PHISHING, false);
}
IN_PROC_BROWSER_TEST_F(SafeBrowsingBrowserTest,
DoesNotShowInterstitial_Malware_Subresource_disableSB) {
// Test that new renderer checks the safe browsing setting.
SetSafeBrowsingEnabled(false);
KillRenderer();
NavigateWithSubResourceAndThreatType(
safe_browsing::SB_THREAT_TYPE_URL_MALWARE, false);
}
IN_PROC_BROWSER_TEST_F(SafeBrowsingBrowserTest, CheckSetsPrefs) {
// Check that changing safe browsing setting sets corresponding pref,
// which is persistent.
PrefService* prefs = GetProfile()->GetBrowserContext()->pref_service();
SetSafeBrowsingEnabled(true);
EXPECT_TRUE(prefs->GetBoolean(::prefs::kSafeBrowsingEnabled));
SetSafeBrowsingEnabled(false);
EXPECT_FALSE(prefs->GetBoolean(::prefs::kSafeBrowsingEnabled));
}
IN_PROC_BROWSER_TEST_F(SafeBrowsingDisabledBrowserTest,
DoesNotShowInterstitial_NoRestriction) {
Navigate(url_, false);
}
IN_PROC_BROWSER_TEST_F(SafeBrowsingDisabledBrowserTest,
DoesNotShowInterstitial_Safe) {
NavigateWithThreatType(safe_browsing::SB_THREAT_TYPE_SAFE, false);
}
IN_PROC_BROWSER_TEST_F(SafeBrowsingDisabledBrowserTest,
DoesNotShowInterstitial_Malware) {
NavigateWithThreatType(safe_browsing::SB_THREAT_TYPE_URL_MALWARE, false);
}
IN_PROC_BROWSER_TEST_F(SafeBrowsingDisabledBrowserTest,
DoesNotShowInterstitial_Phishing) {
NavigateWithThreatType(safe_browsing::SB_THREAT_TYPE_URL_PHISHING, false);
}
IN_PROC_BROWSER_TEST_F(SafeBrowsingDisabledBrowserTest,
DoesNotShowInterstitial_Unwanted) {
NavigateWithThreatType(safe_browsing::SB_THREAT_TYPE_URL_UNWANTED, false);
}
IN_PROC_BROWSER_TEST_F(SafeBrowsingDisabledBrowserTest,
DoesNotShowInterstitial_Billing) {
NavigateWithThreatType(safe_browsing::SB_THREAT_TYPE_BILLING, false);
}
IN_PROC_BROWSER_TEST_F(SafeBrowsingDisabledBrowserTest,
DoesNotShowInterstitial_Malware_Subresource) {
NavigateWithSubResourceAndThreatType(
safe_browsing::SB_THREAT_TYPE_URL_MALWARE, false);
}
IN_PROC_BROWSER_TEST_F(SafeBrowsingBrowserTest,
NoAccessTokenFetchWhenSafeBrowsingNotEnabled) {
GURL a_url(embedded_test_server()->GetURL("a.com", "/simple_page.html"));
NavigateAndWaitForCompletion(a_url, shell()->tab());
EXPECT_FALSE(access_token_fetch_delegate()->has_received_request());
}
IN_PROC_BROWSER_TEST_F(SafeBrowsingBrowserTest,
NoAccessTokenFetchInBasicSafeBrowsing) {
SetSafeBrowsingEnabled(true);
GURL a_url(embedded_test_server()->GetURL("a.com", "/simple_page.html"));
NavigateAndWaitForCompletion(a_url, shell()->tab());
EXPECT_FALSE(access_token_fetch_delegate()->has_received_request());
}
IN_PROC_BROWSER_TEST_F(SafeBrowsingBrowserTest,
NoAccessTokenFetchInRealTimeUrlLookupsUnlessEnabled) {
SetRealTimeURLLookupsEnabled(true);
GURL a_url(embedded_test_server()->GetURL("a.com", "/simple_page.html"));
NavigateAndWaitForCompletion(a_url, shell()->tab());
EXPECT_FALSE(access_token_fetch_delegate()->has_received_request());
EnableSafeBrowsingAccessTokenFetches();
access_token_fetch_delegate()->set_should_respond_to_request(true);
GURL b_url(embedded_test_server()->GetURL("a.com", "/simple_page.html"));
NavigateAndWaitForCompletion(a_url, shell()->tab());
std::set<std::string> safe_browsing_scopes = {
GaiaConstants::kChromeSafeBrowsingOAuth2Scope};
EXPECT_TRUE(access_token_fetch_delegate()->has_received_request());
EXPECT_EQ(safe_browsing_scopes,
access_token_fetch_delegate()->scopes_from_most_recent_request());
}
// Tests that even if the embedder does not respond to an access token fetch
// that is made by safe browsing as part of a navigation, the navigation
// completes due to Safe Browsing's timing out the access token fetch.
IN_PROC_BROWSER_TEST_F(
SafeBrowsingBrowserTest,
UnfulfilledAccessTokenFetchTimesOutAndNavigationCompletes) {
SetRealTimeURLLookupsEnabled(true);
EnableSafeBrowsingAccessTokenFetches();
access_token_fetch_delegate()->set_should_respond_to_request(false);
GURL a_url(embedded_test_server()->GetURL("a.com", "/simple_page.html"));
NavigateAndWaitForCompletion(a_url, shell()->tab());
std::set<std::string> safe_browsing_scopes = {
GaiaConstants::kChromeSafeBrowsingOAuth2Scope};
EXPECT_TRUE(access_token_fetch_delegate()->has_received_request());
EXPECT_EQ(safe_browsing_scopes,
access_token_fetch_delegate()->scopes_from_most_recent_request());
}
} // namespace weblayer
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/safe_browsing/safe_browsing_browsertest.cc | C++ | unknown | 17,721 |
// Copyright 2021 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "weblayer/browser/safe_browsing/safe_browsing_metrics_collector_factory.h"
#include "base/no_destructor.h"
#include "components/keyed_service/content/browser_context_dependency_manager.h"
#include "components/safe_browsing/core/browser/safe_browsing_metrics_collector.h"
#include "weblayer/browser/browser_context_impl.h"
namespace weblayer {
// static
safe_browsing::SafeBrowsingMetricsCollector*
SafeBrowsingMetricsCollectorFactory::GetForBrowserContext(
content::BrowserContext* browser_context) {
return static_cast<safe_browsing::SafeBrowsingMetricsCollector*>(
GetInstance()->GetServiceForBrowserContext(browser_context,
/* create= */ true));
}
// static
SafeBrowsingMetricsCollectorFactory*
SafeBrowsingMetricsCollectorFactory::GetInstance() {
static base::NoDestructor<SafeBrowsingMetricsCollectorFactory> factory;
return factory.get();
}
// static
SafeBrowsingMetricsCollectorFactory::SafeBrowsingMetricsCollectorFactory()
: BrowserContextKeyedServiceFactory(
"SafeBrowsingMetricsCollector",
BrowserContextDependencyManager::GetInstance()) {}
KeyedService* SafeBrowsingMetricsCollectorFactory::BuildServiceInstanceFor(
content::BrowserContext* context) const {
BrowserContextImpl* context_impl = static_cast<BrowserContextImpl*>(context);
return new safe_browsing::SafeBrowsingMetricsCollector(
context_impl->pref_service());
}
} // namespace weblayer
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/safe_browsing/safe_browsing_metrics_collector_factory.cc | C++ | unknown | 1,625 |
// Copyright 2021 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef WEBLAYER_BROWSER_SAFE_BROWSING_SAFE_BROWSING_METRICS_COLLECTOR_FACTORY_H_
#define WEBLAYER_BROWSER_SAFE_BROWSING_SAFE_BROWSING_METRICS_COLLECTOR_FACTORY_H_
#include "base/no_destructor.h"
#include "components/keyed_service/content/browser_context_keyed_service_factory.h"
class KeyedService;
namespace content {
class BrowserContext;
}
namespace safe_browsing {
class SafeBrowsingMetricsCollector;
}
namespace weblayer {
// Singleton that owns SafeBrowsingMetricsCollector objects, one for each active
// BrowserContext. It returns nullptr in incognito mode.
class SafeBrowsingMetricsCollectorFactory
: public BrowserContextKeyedServiceFactory {
public:
SafeBrowsingMetricsCollectorFactory(
const SafeBrowsingMetricsCollectorFactory&) = delete;
SafeBrowsingMetricsCollectorFactory& operator=(
const SafeBrowsingMetricsCollectorFactory&) = delete;
// Creates the object if it doesn't exist already for the given
// |browser_context|. If the object already exists, returns its pointer.
static safe_browsing::SafeBrowsingMetricsCollector* GetForBrowserContext(
content::BrowserContext* browser_context);
// Get the singleton instance.
static SafeBrowsingMetricsCollectorFactory* GetInstance();
private:
friend class base::NoDestructor<SafeBrowsingMetricsCollectorFactory>;
SafeBrowsingMetricsCollectorFactory();
~SafeBrowsingMetricsCollectorFactory() override = default;
// BrowserContextKeyedServiceFactory:
KeyedService* BuildServiceInstanceFor(
content::BrowserContext* context) const override;
};
} // namespace weblayer
#endif // WEBLAYER_BROWSER_SAFE_BROWSING_SAFE_BROWSING_METRICS_COLLECTOR_FACTORY_H_
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/safe_browsing/safe_browsing_metrics_collector_factory.h | C++ | unknown | 1,827 |
// Copyright 2021 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "weblayer/browser/safe_browsing/safe_browsing_navigation_observer_manager_factory.h"
#include "base/no_destructor.h"
#include "components/keyed_service/content/browser_context_dependency_manager.h"
#include "components/safe_browsing/content/browser/safe_browsing_navigation_observer_manager.h"
#include "weblayer/browser/browser_context_impl.h"
namespace weblayer {
// static
safe_browsing::SafeBrowsingNavigationObserverManager*
SafeBrowsingNavigationObserverManagerFactory::GetForBrowserContext(
content::BrowserContext* browser_context) {
return static_cast<safe_browsing::SafeBrowsingNavigationObserverManager*>(
GetInstance()->GetServiceForBrowserContext(browser_context,
/*create=*/true));
}
// static
SafeBrowsingNavigationObserverManagerFactory*
SafeBrowsingNavigationObserverManagerFactory::GetInstance() {
static base::NoDestructor<SafeBrowsingNavigationObserverManagerFactory>
factory;
return factory.get();
}
SafeBrowsingNavigationObserverManagerFactory::
SafeBrowsingNavigationObserverManagerFactory()
: BrowserContextKeyedServiceFactory(
"SafeBrowsingNavigationObserverManager",
BrowserContextDependencyManager::GetInstance()) {}
KeyedService*
SafeBrowsingNavigationObserverManagerFactory::BuildServiceInstanceFor(
content::BrowserContext* context) const {
BrowserContextImpl* context_impl = static_cast<BrowserContextImpl*>(context);
return new safe_browsing::SafeBrowsingNavigationObserverManager(
context_impl->pref_service());
}
content::BrowserContext*
SafeBrowsingNavigationObserverManagerFactory::GetBrowserContextToUse(
content::BrowserContext* context) const {
return context;
}
} // namespace weblayer
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/safe_browsing/safe_browsing_navigation_observer_manager_factory.cc | C++ | unknown | 1,907 |
// Copyright 2021 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef WEBLAYER_BROWSER_SAFE_BROWSING_SAFE_BROWSING_NAVIGATION_OBSERVER_MANAGER_FACTORY_H_
#define WEBLAYER_BROWSER_SAFE_BROWSING_SAFE_BROWSING_NAVIGATION_OBSERVER_MANAGER_FACTORY_H_
#include "base/no_destructor.h"
#include "components/keyed_service/content/browser_context_keyed_service_factory.h"
class KeyedService;
namespace content {
class BrowserContext;
}
namespace safe_browsing {
class SafeBrowsingNavigationObserverManager;
}
namespace weblayer {
// Singleton that owns SafeBrowsingNavigationObserverManager objects, one for
// each active BrowserContext. It returns a separate instance if the
// BrowserContext is in incognito mode.
class SafeBrowsingNavigationObserverManagerFactory
: public BrowserContextKeyedServiceFactory {
public:
SafeBrowsingNavigationObserverManagerFactory(
const SafeBrowsingNavigationObserverManagerFactory&) = delete;
SafeBrowsingNavigationObserverManagerFactory& operator=(
const SafeBrowsingNavigationObserverManagerFactory&) = delete;
// Creates the service if it doesn't exist already for the given
// |browser_context|. If the service already exists, returns its pointer.
static safe_browsing::SafeBrowsingNavigationObserverManager*
GetForBrowserContext(content::BrowserContext* browser_context);
// Get the singleton instance.
static SafeBrowsingNavigationObserverManagerFactory* GetInstance();
private:
friend class base::NoDestructor<SafeBrowsingNavigationObserverManagerFactory>;
SafeBrowsingNavigationObserverManagerFactory();
~SafeBrowsingNavigationObserverManagerFactory() override = default;
// BrowserContextKeyedServiceFactory:
KeyedService* BuildServiceInstanceFor(
content::BrowserContext* context) const override;
content::BrowserContext* GetBrowserContextToUse(
content::BrowserContext* context) const override;
};
} // namespace weblayer
#endif // WEBLAYER_BROWSER_SAFE_BROWSING_SAFE_BROWSING_NAVIGATION_OBSERVER_MANAGER_FACTORY_H_
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/safe_browsing/safe_browsing_navigation_observer_manager_factory.h | C++ | unknown | 2,108 |
// Copyright 2019 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "weblayer/browser/safe_browsing/safe_browsing_service.h"
#include <memory>
#include "base/functional/bind.h"
#include "base/path_service.h"
#include "components/prefs/pref_service.h"
#include "components/safe_browsing/android/remote_database_manager.h"
#include "components/safe_browsing/android/safe_browsing_api_handler_bridge.h"
#include "components/safe_browsing/content/browser/browser_url_loader_throttle.h"
#include "components/safe_browsing/content/browser/mojo_safe_browsing_impl.h"
#include "components/safe_browsing/content/browser/safe_browsing_navigation_throttle.h"
#include "components/safe_browsing/content/browser/safe_browsing_network_context.h"
#include "components/safe_browsing/content/browser/triggers/trigger_manager.h"
#include "components/safe_browsing/core/browser/realtime/url_lookup_service.h"
#include "components/safe_browsing/core/common/features.h"
#include "components/safe_browsing/core/common/safe_browsing_prefs.h"
#include "content/public/browser/browser_context.h"
#include "content/public/browser/browser_task_traits.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/network_service_instance.h"
#include "content/public/browser/render_process_host.h"
#include "content/public/browser/resource_context.h"
#include "services/cert_verifier/public/mojom/cert_verifier_service_factory.mojom.h"
#include "services/network/public/mojom/network_context.mojom.h"
#include "services/network/public/mojom/network_service.mojom.h"
#include "third_party/blink/public/common/loader/url_loader_throttle.h"
#include "weblayer/browser/browser_context_impl.h"
#include "weblayer/browser/browser_process.h"
#include "weblayer/browser/safe_browsing/url_checker_delegate_impl.h"
#include "weblayer/browser/safe_browsing/weblayer_safe_browsing_blocking_page_factory.h"
#include "weblayer/browser/safe_browsing/weblayer_ui_manager_delegate.h"
#include "weblayer/browser/system_network_context_manager.h"
#include "weblayer/common/features.h"
namespace weblayer {
namespace {
network::mojom::NetworkContextParamsPtr CreateDefaultNetworkContextParams(
const std::string& user_agent) {
network::mojom::NetworkContextParamsPtr network_context_params =
network::mojom::NetworkContextParams::New();
network_context_params->cert_verifier_params = content::GetCertVerifierParams(
cert_verifier::mojom::CertVerifierCreationParams::New());
network_context_params->user_agent = user_agent;
return network_context_params;
}
// Helper method that checks the RenderProcessHost is still alive and checks the
// latest Safe Browsing pref value on the UI thread before hopping over to the
// IO thread.
void MaybeCreateSafeBrowsing(
int rph_id,
base::WeakPtr<content::ResourceContext> resource_context,
base::RepeatingCallback<scoped_refptr<safe_browsing::UrlCheckerDelegate>()>
get_checker_delegate,
mojo::PendingReceiver<safe_browsing::mojom::SafeBrowsing> receiver) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
content::RenderProcessHost* render_process_host =
content::RenderProcessHost::FromID(rph_id);
if (!render_process_host) {
return;
}
bool is_safe_browsing_enabled = safe_browsing::IsSafeBrowsingEnabled(
*static_cast<BrowserContextImpl*>(
render_process_host->GetBrowserContext())
->pref_service());
if (!is_safe_browsing_enabled) {
return;
}
if (base::FeatureList::IsEnabled(safe_browsing::kSafeBrowsingOnUIThread)) {
safe_browsing::MojoSafeBrowsingImpl::MaybeCreate(
rph_id, std::move(resource_context), std::move(get_checker_delegate),
std::move(receiver));
} else {
content::GetIOThreadTaskRunner({})->PostTask(
FROM_HERE,
base::BindOnce(&safe_browsing::MojoSafeBrowsingImpl::MaybeCreate,
rph_id, std::move(resource_context),
std::move(get_checker_delegate), std::move(receiver)));
}
}
} // namespace
SafeBrowsingService::SafeBrowsingService(const std::string& user_agent)
: user_agent_(user_agent) {}
SafeBrowsingService::~SafeBrowsingService() = default;
void SafeBrowsingService::Initialize() {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
if (network_context_) {
// already initialized
return;
}
base::FilePath user_data_dir;
bool result =
base::PathService::Get(base::DIR_ANDROID_APP_DATA, &user_data_dir);
DCHECK(result);
// safebrowsing network context needs to be created on the UI thread.
network_context_ =
std::make_unique<safe_browsing::SafeBrowsingNetworkContext>(
user_data_dir, /*trigger_migration=*/false,
base::BindRepeating(CreateDefaultNetworkContextParams, user_agent_));
CreateSafeBrowsingUIManager();
// Needs to happen after |ui_manager_| is created.
CreateTriggerManager();
}
std::unique_ptr<blink::URLLoaderThrottle>
SafeBrowsingService::CreateURLLoaderThrottle(
const base::RepeatingCallback<content::WebContents*()>& wc_getter,
int frame_tree_node_id,
safe_browsing::RealTimeUrlLookupServiceBase* url_lookup_service) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
return safe_browsing::BrowserURLLoaderThrottle::Create(
base::BindOnce(
[](SafeBrowsingService* sb_service) {
return sb_service->GetSafeBrowsingUrlCheckerDelegate();
},
base::Unretained(this)),
wc_getter, frame_tree_node_id,
url_lookup_service ? url_lookup_service->GetWeakPtr() : nullptr,
/*hash_realtime_service=*/nullptr,
/*ping_manager=*/nullptr);
}
std::unique_ptr<content::NavigationThrottle>
SafeBrowsingService::MaybeCreateSafeBrowsingNavigationThrottleFor(
content::NavigationHandle* handle) {
if (!base::FeatureList::IsEnabled(features::kWebLayerSafeBrowsing)) {
return nullptr;
}
return safe_browsing::SafeBrowsingNavigationThrottle::MaybeCreateThrottleFor(
handle, GetSafeBrowsingUIManager().get());
}
scoped_refptr<safe_browsing::UrlCheckerDelegate>
SafeBrowsingService::GetSafeBrowsingUrlCheckerDelegate() {
DCHECK_CURRENTLY_ON(
base::FeatureList::IsEnabled(safe_browsing::kSafeBrowsingOnUIThread)
? content::BrowserThread::UI
: content::BrowserThread::IO);
if (!safe_browsing_url_checker_delegate_) {
safe_browsing_url_checker_delegate_ = new UrlCheckerDelegateImpl(
GetSafeBrowsingDBManager(), GetSafeBrowsingUIManager());
}
return safe_browsing_url_checker_delegate_;
}
scoped_refptr<safe_browsing::RemoteSafeBrowsingDatabaseManager>
SafeBrowsingService::GetSafeBrowsingDBManager() {
if (!safe_browsing_db_manager_) {
CreateAndStartSafeBrowsingDBManager();
}
return safe_browsing_db_manager_;
}
scoped_refptr<safe_browsing::SafeBrowsingUIManager>
SafeBrowsingService::GetSafeBrowsingUIManager() {
return ui_manager_;
}
safe_browsing::TriggerManager* SafeBrowsingService::GetTriggerManager() {
return trigger_manager_.get();
}
void SafeBrowsingService::CreateSafeBrowsingUIManager() {
DCHECK(!ui_manager_);
ui_manager_ = new safe_browsing::SafeBrowsingUIManager(
std::make_unique<WebLayerSafeBrowsingUIManagerDelegate>(),
std::make_unique<WebLayerSafeBrowsingBlockingPageFactory>(),
GURL(url::kAboutBlankURL));
}
void SafeBrowsingService::CreateTriggerManager() {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
trigger_manager_ = std::make_unique<safe_browsing::TriggerManager>(
ui_manager_.get(), BrowserProcess::GetInstance()->GetLocalState());
}
void SafeBrowsingService::CreateAndStartSafeBrowsingDBManager() {
DCHECK(!safe_browsing_db_manager_);
safe_browsing_db_manager_ =
new safe_browsing::RemoteSafeBrowsingDatabaseManager();
auto task_runner =
base::FeatureList::IsEnabled(safe_browsing::kSafeBrowsingOnUIThread)
? content::GetUIThreadTaskRunner({})
: content::GetIOThreadTaskRunner({});
if (!task_runner->BelongsToCurrentThread()) {
// Posting a task to start the DB here ensures that it will be started by
// the time that a consumer uses it on the IO thread, as such a consumer
// would need to make it available for usage on the IO thread via a
// PostTask() that will be ordered after this one.
task_runner->PostTask(
FROM_HERE,
base::BindOnce(
&SafeBrowsingService::StartSafeBrowsingDBManagerOnSBThread,
base::Unretained(this)));
} else {
StartSafeBrowsingDBManagerOnSBThread();
}
}
void SafeBrowsingService::StartSafeBrowsingDBManagerOnSBThread() {
DCHECK_CURRENTLY_ON(
base::FeatureList::IsEnabled(safe_browsing::kSafeBrowsingOnUIThread)
? content::BrowserThread::UI
: content::BrowserThread::IO);
DCHECK(safe_browsing_db_manager_);
if (started_db_manager_) {
return;
}
started_db_manager_ = true;
// V4ProtocolConfig is not used. Just create one with empty values.
safe_browsing::V4ProtocolConfig config("", false, "", "");
scoped_refptr<network::SharedURLLoaderFactory> factory;
if (base::FeatureList::IsEnabled(safe_browsing::kSafeBrowsingOnUIThread)) {
factory =
SystemNetworkContextManager::GetInstance()->GetSharedURLLoaderFactory();
} else {
factory = GetURLLoaderFactoryOnIOThread();
}
safe_browsing_db_manager_->StartOnSBThread(factory, config);
}
scoped_refptr<network::SharedURLLoaderFactory>
SafeBrowsingService::GetURLLoaderFactoryOnIOThread() {
DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
if (!shared_url_loader_factory_on_io_) {
content::GetUIThreadTaskRunner({})->PostTask(
FROM_HERE,
base::BindOnce(&SafeBrowsingService::CreateURLLoaderFactoryForIO,
base::Unretained(this),
url_loader_factory_on_io_.BindNewPipeAndPassReceiver()));
shared_url_loader_factory_on_io_ =
base::MakeRefCounted<network::WeakWrapperSharedURLLoaderFactory>(
url_loader_factory_on_io_.get());
}
return shared_url_loader_factory_on_io_;
}
void SafeBrowsingService::CreateURLLoaderFactoryForIO(
mojo::PendingReceiver<network::mojom::URLLoaderFactory> receiver) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
auto url_loader_factory_params =
network::mojom::URLLoaderFactoryParams::New();
url_loader_factory_params->process_id = network::mojom::kBrowserProcessId;
url_loader_factory_params->is_corb_enabled = false;
network_context_->GetNetworkContext()->CreateURLLoaderFactory(
std::move(receiver), std::move(url_loader_factory_params));
}
void SafeBrowsingService::AddInterface(
service_manager::BinderRegistry* registry,
content::RenderProcessHost* render_process_host) {
content::ResourceContext* resource_context =
render_process_host->GetBrowserContext()->GetResourceContext();
registry->AddInterface(
base::BindRepeating(
&MaybeCreateSafeBrowsing, render_process_host->GetID(),
resource_context->GetWeakPtr(),
base::BindRepeating(
&SafeBrowsingService::GetSafeBrowsingUrlCheckerDelegate,
base::Unretained(this))),
content::GetUIThreadTaskRunner({}));
}
void SafeBrowsingService::StopDBManager() {
if (base::FeatureList::IsEnabled(safe_browsing::kSafeBrowsingOnUIThread)) {
StopDBManagerOnSBThread();
} else {
content::GetIOThreadTaskRunner({})->PostTask(
FROM_HERE, base::BindOnce(&SafeBrowsingService::StopDBManagerOnSBThread,
base::Unretained(this)));
}
}
void SafeBrowsingService::StopDBManagerOnSBThread() {
DCHECK_CURRENTLY_ON(
base::FeatureList::IsEnabled(safe_browsing::kSafeBrowsingOnUIThread)
? content::BrowserThread::UI
: content::BrowserThread::IO);
if (safe_browsing_db_manager_) {
safe_browsing_db_manager_->StopOnSBThread(true /*shutdown*/);
safe_browsing_db_manager_.reset();
started_db_manager_ = false;
}
}
network::mojom::NetworkContext* SafeBrowsingService::GetNetworkContext() {
if (!network_context_) {
return nullptr;
}
return network_context_->GetNetworkContext();
}
scoped_refptr<network::SharedURLLoaderFactory>
SafeBrowsingService::GetURLLoaderFactory() {
if (!network_context_) {
return nullptr;
}
return network_context_->GetURLLoaderFactory();
}
} // namespace weblayer
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/safe_browsing/safe_browsing_service.cc | C++ | unknown | 12,471 |
// Copyright 2019 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef WEBLAYER_BROWSER_SAFE_BROWSING_SAFE_BROWSING_SERVICE_H_
#define WEBLAYER_BROWSER_SAFE_BROWSING_SAFE_BROWSING_SERVICE_H_
#include "components/safe_browsing/content/browser/base_ui_manager.h"
#include "components/safe_browsing/content/browser/ui_manager.h"
#include "mojo/public/cpp/bindings/pending_receiver.h"
#include "mojo/public/cpp/bindings/remote.h"
#include "services/network/public/cpp/weak_wrapper_shared_url_loader_factory.h"
#include "services/service_manager/public/cpp/binder_registry.h"
namespace content {
class NavigationHandle;
class NavigationThrottle;
class RenderProcessHost;
} // namespace content
namespace blink {
class URLLoaderThrottle;
}
namespace network {
namespace mojom {
class NetworkContext;
}
class SharedURLLoaderFactory;
} // namespace network
namespace safe_browsing {
class UrlCheckerDelegate;
class RealTimeUrlLookupServiceBase;
class RemoteSafeBrowsingDatabaseManager;
class SafeBrowsingApiHandlerBridge;
class SafeBrowsingNetworkContext;
class TriggerManager;
} // namespace safe_browsing
namespace weblayer {
class UrlCheckerDelegateImpl;
// Class for managing safebrowsing related functionality. In particular this
// class owns both the safebrowsing database and UI managers and provides
// support for initialization and construction of these objects.
class SafeBrowsingService {
public:
explicit SafeBrowsingService(const std::string& user_agent);
SafeBrowsingService(const SafeBrowsingService&) = delete;
SafeBrowsingService& operator=(const SafeBrowsingService&) = delete;
~SafeBrowsingService();
// Executed on UI thread
void Initialize();
std::unique_ptr<blink::URLLoaderThrottle> CreateURLLoaderThrottle(
const base::RepeatingCallback<content::WebContents*()>& wc_getter,
int frame_tree_node_id,
safe_browsing::RealTimeUrlLookupServiceBase* url_lookup_service);
std::unique_ptr<content::NavigationThrottle>
MaybeCreateSafeBrowsingNavigationThrottleFor(
content::NavigationHandle* handle);
void AddInterface(service_manager::BinderRegistry* registry,
content::RenderProcessHost* render_process_host);
void StopDBManager();
network::mojom::NetworkContext* GetNetworkContext();
scoped_refptr<network::SharedURLLoaderFactory> GetURLLoaderFactory();
// May be called on the UI or IO thread. The instance returned should be
// *accessed* only on the IO thread.
scoped_refptr<safe_browsing::RemoteSafeBrowsingDatabaseManager>
GetSafeBrowsingDBManager();
scoped_refptr<safe_browsing::SafeBrowsingUIManager>
GetSafeBrowsingUIManager();
safe_browsing::TriggerManager* GetTriggerManager();
private:
// Executed on IO thread
scoped_refptr<safe_browsing::UrlCheckerDelegate>
GetSafeBrowsingUrlCheckerDelegate();
// Safe to call multiple times; invocations after the first will be no-ops.
void StartSafeBrowsingDBManagerOnSBThread();
void CreateSafeBrowsingUIManager();
void CreateTriggerManager();
void CreateAndStartSafeBrowsingDBManager();
scoped_refptr<network::SharedURLLoaderFactory>
GetURLLoaderFactoryOnIOThread();
void CreateURLLoaderFactoryForIO(
mojo::PendingReceiver<network::mojom::URLLoaderFactory> receiver);
void StopDBManagerOnSBThread();
// The UI manager handles showing interstitials. Accessed on both UI and IO
// thread.
scoped_refptr<safe_browsing::SafeBrowsingUIManager> ui_manager_;
// This is what owns the URLRequestContext inside the network service. This
// is used by SimpleURLLoader for Safe Browsing requests.
std::unique_ptr<safe_browsing::SafeBrowsingNetworkContext> network_context_;
// May be created on UI thread and have references obtained to it on that
// thread for later passing to the IO thread, but should be *accessed* only
// on the IO thread.
scoped_refptr<safe_browsing::RemoteSafeBrowsingDatabaseManager>
safe_browsing_db_manager_;
// A SharedURLLoaderFactory and its remote used on the IO thread.
mojo::Remote<network::mojom::URLLoaderFactory> url_loader_factory_on_io_;
scoped_refptr<network::WeakWrapperSharedURLLoaderFactory>
shared_url_loader_factory_on_io_;
scoped_refptr<UrlCheckerDelegateImpl> safe_browsing_url_checker_delegate_;
std::unique_ptr<safe_browsing::SafeBrowsingApiHandlerBridge>
safe_browsing_api_handler_;
std::string user_agent_;
// Whether |safe_browsing_db_manager_| has been started. Accessed only on the
// IO thread.
bool started_db_manager_ = false;
// Collects data and sends reports to Safe Browsing. Accessed on UI thread.
std::unique_ptr<safe_browsing::TriggerManager> trigger_manager_;
};
} // namespace weblayer
#endif // WEBLAYER_BROWSER_SAFE_BROWSING_SAFE_BROWSING_SERVICE_H_
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/safe_browsing/safe_browsing_service.h | C++ | unknown | 4,859 |
// Copyright 2021 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "weblayer/browser/safe_browsing/safe_browsing_token_fetcher_impl.h"
#include "base/functional/bind.h"
#include "base/memory/weak_ptr.h"
#include "google_apis/gaia/gaia_constants.h"
#include "weblayer/public/google_account_access_token_fetch_delegate.h"
namespace weblayer {
SafeBrowsingTokenFetcherImpl::SafeBrowsingTokenFetcherImpl(
const AccessTokenFetchDelegateGetter& delegate_getter)
: delegate_getter_(delegate_getter) {}
SafeBrowsingTokenFetcherImpl::~SafeBrowsingTokenFetcherImpl() = default;
void SafeBrowsingTokenFetcherImpl::Start(Callback callback) {
auto* delegate = delegate_getter_.Run();
if (!delegate) {
std::move(callback).Run("");
return;
}
// NOTE: When a token fetch timeout occurs |token_fetch_tracker_| will invoke
// the client callback, which may end up synchronously destroying this object
// before this object's own callback is invoked. Hence we bind our own
// callback via a WeakPtr.
const int request_id = token_fetch_tracker_.StartTrackingTokenFetch(
std::move(callback),
base::BindOnce(&SafeBrowsingTokenFetcherImpl::OnTokenTimeout,
weak_ptr_factory_.GetWeakPtr()));
request_ids_.insert(request_id);
// In contrast, this object does *not* have a determined lifetime relationship
// with |delegate|.
delegate->FetchAccessToken(
{GaiaConstants::kChromeSafeBrowsingOAuth2Scope},
base::BindOnce(&SafeBrowsingTokenFetcherImpl::OnTokenFetched,
weak_ptr_factory_.GetWeakPtr(), request_id));
}
void SafeBrowsingTokenFetcherImpl::OnInvalidAccessToken(
const std::string& invalid_access_token) {
auto* delegate = delegate_getter_.Run();
if (!delegate)
return;
delegate->OnAccessTokenIdentifiedAsInvalid(
{GaiaConstants::kChromeSafeBrowsingOAuth2Scope}, invalid_access_token);
}
void SafeBrowsingTokenFetcherImpl::OnTokenFetched(
int request_id,
const std::string& access_token) {
if (!request_ids_.count(request_id)) {
// The request timed out before the delegate responded; nothing to do.
return;
}
request_ids_.erase(request_id);
token_fetch_tracker_.OnTokenFetchComplete(request_id, access_token);
// NOTE: Calling SafeBrowsingTokenFetchTracker::OnTokenFetchComplete might
// have resulted in the synchronous destruction of this object, so there is
// nothing safe to do here but return.
}
void SafeBrowsingTokenFetcherImpl::OnTokenTimeout(int request_id) {
DCHECK(request_ids_.count(request_id));
request_ids_.erase(request_id);
}
} // namespace weblayer
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/safe_browsing/safe_browsing_token_fetcher_impl.cc | C++ | unknown | 2,713 |
// Copyright 2021 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef WEBLAYER_BROWSER_SAFE_BROWSING_SAFE_BROWSING_TOKEN_FETCHER_IMPL_H_
#define WEBLAYER_BROWSER_SAFE_BROWSING_SAFE_BROWSING_TOKEN_FETCHER_IMPL_H_
#include <memory>
#include <set>
#include "base/memory/weak_ptr.h"
#include "components/safe_browsing/core/browser/safe_browsing_token_fetch_tracker.h"
#include "components/safe_browsing/core/browser/safe_browsing_token_fetcher.h"
namespace weblayer {
class GoogleAccountAccessTokenFetchDelegate;
// This class fetches access tokens for Safe Browsing via a
// GoogleAccountAccessTokenFetcherDelegate.
class SafeBrowsingTokenFetcherImpl
: public safe_browsing::SafeBrowsingTokenFetcher {
public:
using AccessTokenFetchDelegateGetter =
base::RepeatingCallback<GoogleAccountAccessTokenFetchDelegate*()>;
// Create a SafeBrowsingTokenFetcherImpl that makes access token requests via
// the object returned by |delegate_getter|. |delegate_getter| may return
// null, in which case this object will return the empty string for access
// token requests. This object will not cache the pointer returned by
// |delegate_getter| but will instead invoke it on every access token request,
// as that object might change over time.
// NOTE: In production the getter is
// ProfileImpl::access_token_fetcher_delegate(); this level of indirection is
// present to support unittests.
explicit SafeBrowsingTokenFetcherImpl(
const AccessTokenFetchDelegateGetter& delegate_getter);
~SafeBrowsingTokenFetcherImpl() override;
// SafeBrowsingTokenFetcher:
void Start(Callback callback) override;
void OnInvalidAccessToken(const std::string& invalid_access_token) override;
private:
void OnTokenFetched(int request_id, const std::string& access_token);
void OnTokenTimeout(int request_id);
AccessTokenFetchDelegateGetter delegate_getter_;
safe_browsing::SafeBrowsingTokenFetchTracker token_fetch_tracker_;
// IDs of outstanding client access token requests being tracked by
// |token_fetch_tracker_|.
std::set<int> request_ids_;
base::WeakPtrFactory<SafeBrowsingTokenFetcherImpl> weak_ptr_factory_{this};
};
} // namespace weblayer
#endif // WEBLAYER_BROWSER_SAFE_BROWSING_SAFE_BROWSING_TOKEN_FETCHER_IMPL_H_
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/safe_browsing/safe_browsing_token_fetcher_impl.h | C++ | unknown | 2,359 |
// Copyright 2021 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "weblayer/browser/safe_browsing/safe_browsing_token_fetcher_impl.h"
#include "content/public/test/browser_task_environment.h"
#include "google_apis/gaia/gaia_constants.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "weblayer/public/google_account_access_token_fetch_delegate.h"
namespace weblayer {
namespace {
// Callback passed to SafeBrowsingTokenFetcherImpl to be invoked on
// access token fetch completion.
void OnAccessTokenFetched(base::OnceClosure quit_closure,
std::string* target_token,
const std::string& received_token) {
*target_token = received_token;
std::move(quit_closure).Run();
}
// Test implementation of GoogleAccountAccessTokenFetchDelegate.
class TestAccessTokenFetchDelegate
: public GoogleAccountAccessTokenFetchDelegate {
public:
TestAccessTokenFetchDelegate() {}
~TestAccessTokenFetchDelegate() override {}
TestAccessTokenFetchDelegate(const TestAccessTokenFetchDelegate&) = delete;
TestAccessTokenFetchDelegate& operator=(const TestAccessTokenFetchDelegate&) =
delete;
// GoogleAccountAccessTokenFetchDelegate:
void FetchAccessToken(const std::set<std::string>& scopes,
OnTokenFetchedCallback callback) override {
most_recent_request_id_++;
// All access token requests made by SafeBrowsingTokenFetcherImpl should be
// for the safe browsing scope.
std::set<std::string> expected_scopes = {
GaiaConstants::kChromeSafeBrowsingOAuth2Scope};
EXPECT_EQ(expected_scopes, scopes);
outstanding_callbacks_[most_recent_request_id_] = std::move(callback);
}
void OnAccessTokenIdentifiedAsInvalid(const std::set<std::string>& scopes,
const std::string& token) override {
// All invalid token notifications originating from
// SafeBrowsingTokenFetcherImpl should be for the safe browsing scope.
std::set<std::string> expected_scopes = {
GaiaConstants::kChromeSafeBrowsingOAuth2Scope};
EXPECT_EQ(expected_scopes, scopes);
invalid_token_ = token;
}
int get_num_outstanding_requests() { return outstanding_callbacks_.size(); }
int get_most_recent_request_id() { return most_recent_request_id_; }
const std::string& get_most_recent_invalid_token() { return invalid_token_; }
void RespondWithTokenForRequest(int request_id, const std::string& token) {
ASSERT_TRUE(outstanding_callbacks_.count(request_id));
auto callback = std::move(outstanding_callbacks_[request_id]);
outstanding_callbacks_.erase(request_id);
std::move(callback).Run(token);
}
private:
int most_recent_request_id_ = 0;
std::map<int, OnTokenFetchedCallback> outstanding_callbacks_;
std::string invalid_token_;
};
} // namespace
class SafeBrowsingTokenFetcherImplTest : public testing::Test {
public:
SafeBrowsingTokenFetcherImplTest() = default;
SafeBrowsingTokenFetcherImplTest(const SafeBrowsingTokenFetcherImplTest&) =
delete;
SafeBrowsingTokenFetcherImplTest& operator=(
const SafeBrowsingTokenFetcherImplTest&) = delete;
protected:
content::BrowserTaskEnvironment* task_environment() {
return &task_environment_;
}
private:
content::BrowserTaskEnvironment task_environment_{
content::BrowserTaskEnvironment::TimeSource::MOCK_TIME};
};
// Tests that SafeBrowsingTokenFetcherImpl responds with an empty token when
// there is no delegate available to fetch tokens from.
TEST_F(SafeBrowsingTokenFetcherImplTest, NoDelegate) {
base::RunLoop run_loop;
std::string access_token = "dummy";
SafeBrowsingTokenFetcherImpl fetcher(base::BindRepeating(
[]() -> GoogleAccountAccessTokenFetchDelegate* { return nullptr; }));
fetcher.Start(base::BindOnce(&OnAccessTokenFetched, run_loop.QuitClosure(),
&access_token));
run_loop.Run();
EXPECT_EQ("", access_token);
}
TEST_F(SafeBrowsingTokenFetcherImplTest, SuccessfulTokenFetch) {
TestAccessTokenFetchDelegate delegate;
base::RunLoop run_loop;
std::string access_token = "";
std::string kTokenFromResponse = "token";
SafeBrowsingTokenFetcherImpl fetcher(base::BindRepeating(
[](TestAccessTokenFetchDelegate* delegate)
-> GoogleAccountAccessTokenFetchDelegate* { return delegate; },
&delegate));
fetcher.Start(base::BindOnce(&OnAccessTokenFetched, run_loop.QuitClosure(),
&access_token));
EXPECT_EQ(1, delegate.get_num_outstanding_requests());
EXPECT_EQ("", access_token);
delegate.RespondWithTokenForRequest(delegate.get_most_recent_request_id(),
kTokenFromResponse);
run_loop.Run();
EXPECT_EQ(kTokenFromResponse, access_token);
}
// Verifies that destruction of a SafeBrowsingTokenFetcherImpl instance from
// within the client callback that the token was fetched doesn't cause a crash.
TEST_F(SafeBrowsingTokenFetcherImplTest,
FetcherDestroyedFromWithinOnTokenFetchedCallback) {
TestAccessTokenFetchDelegate delegate;
base::RunLoop run_loop;
std::string access_token = "";
std::string kTokenFromResponse = "token";
// Destroyed in the token fetch callback.
auto* fetcher = new SafeBrowsingTokenFetcherImpl(base::BindRepeating(
[](TestAccessTokenFetchDelegate* delegate)
-> GoogleAccountAccessTokenFetchDelegate* { return delegate; },
&delegate));
fetcher->Start(base::BindOnce(
[](base::OnceClosure quit_closure, std::string* target_token,
SafeBrowsingTokenFetcherImpl* fetcher, const std::string& token) {
*target_token = token;
delete fetcher;
std::move(quit_closure).Run();
},
run_loop.QuitClosure(), &access_token, fetcher));
EXPECT_EQ(1, delegate.get_num_outstanding_requests());
EXPECT_EQ("", access_token);
delegate.RespondWithTokenForRequest(delegate.get_most_recent_request_id(),
kTokenFromResponse);
run_loop.Run();
EXPECT_EQ(kTokenFromResponse, access_token);
}
// Tests correct operation in the case of concurrent requests to
// SafeBrowsingTokenFetcherImpl.
TEST_F(SafeBrowsingTokenFetcherImplTest, ConcurrentRequests) {
TestAccessTokenFetchDelegate delegate;
base::RunLoop run_loop1;
base::RunLoop run_loop2;
std::string access_token1 = "";
std::string access_token2 = "";
std::string kTokenFromResponse1 = "token1";
std::string kTokenFromResponse2 = "token2";
SafeBrowsingTokenFetcherImpl fetcher(base::BindRepeating(
[](TestAccessTokenFetchDelegate* delegate)
-> GoogleAccountAccessTokenFetchDelegate* { return delegate; },
&delegate));
fetcher.Start(base::BindOnce(&OnAccessTokenFetched, run_loop1.QuitClosure(),
&access_token1));
EXPECT_EQ(1, delegate.get_num_outstanding_requests());
int request_id1 = delegate.get_most_recent_request_id();
EXPECT_EQ("", access_token1);
EXPECT_EQ("", access_token2);
fetcher.Start(base::BindOnce(&OnAccessTokenFetched, run_loop2.QuitClosure(),
&access_token2));
EXPECT_EQ(2, delegate.get_num_outstanding_requests());
int request_id2 = delegate.get_most_recent_request_id();
EXPECT_EQ("", access_token1);
EXPECT_EQ("", access_token2);
delegate.RespondWithTokenForRequest(request_id2, kTokenFromResponse2);
run_loop2.Run();
EXPECT_EQ("", access_token1);
EXPECT_EQ(kTokenFromResponse2, access_token2);
delegate.RespondWithTokenForRequest(request_id1, kTokenFromResponse1);
run_loop1.Run();
EXPECT_EQ(kTokenFromResponse1, access_token1);
EXPECT_EQ(kTokenFromResponse2, access_token2);
}
TEST_F(SafeBrowsingTokenFetcherImplTest, TokenFetchTimeout) {
TestAccessTokenFetchDelegate delegate;
base::RunLoop run_loop;
std::string access_token = "dummy";
std::string kTokenFromResponse = "token";
SafeBrowsingTokenFetcherImpl fetcher(base::BindRepeating(
[](TestAccessTokenFetchDelegate* delegate)
-> GoogleAccountAccessTokenFetchDelegate* { return delegate; },
&delegate));
fetcher.Start(base::BindOnce(&OnAccessTokenFetched, run_loop.QuitClosure(),
&access_token));
EXPECT_EQ(1, delegate.get_num_outstanding_requests());
EXPECT_EQ("dummy", access_token);
// Fast-forward to trigger the token fetch timeout.
task_environment()->FastForwardBy(base::Milliseconds(
safe_browsing::kTokenFetchTimeoutDelayFromMilliseconds));
// Even though the delegate has not yet responded,
// SafeBrowsingTokenFetcherImpl should have responded to its request with the
// empty token.
EXPECT_EQ(1, delegate.get_num_outstanding_requests());
EXPECT_EQ("", access_token);
// Check that the delegate responding at this point has no adverse effect.
delegate.RespondWithTokenForRequest(delegate.get_most_recent_request_id(),
kTokenFromResponse);
base::RunLoop().RunUntilIdle();
EXPECT_EQ("", access_token);
}
// Verifies that destruction of a SafeBrowsingTokenFetcherImpl instance from
// within the client callback that the token was fetched doesn't cause a crash
// when invoked due to the token fetch timing out.
TEST_F(SafeBrowsingTokenFetcherImplTest,
FetcherDestroyedFromWithinOnTokenFetchedCallbackInvokedOnTimeout) {
TestAccessTokenFetchDelegate delegate;
std::string access_token;
bool callback_invoked = false;
// Destroyed in the token fetch callback, which is invoked on timeout.
auto* fetcher = new SafeBrowsingTokenFetcherImpl(base::BindRepeating(
[](TestAccessTokenFetchDelegate* delegate)
-> GoogleAccountAccessTokenFetchDelegate* { return delegate; },
&delegate));
fetcher->Start(base::BindOnce(
[](bool* on_invoked_flag, std::string* target_token,
SafeBrowsingTokenFetcherImpl* fetcher, const std::string& token) {
*on_invoked_flag = true;
*target_token = token;
delete fetcher;
},
&callback_invoked, &access_token, fetcher));
// Trigger a timeout of the fetch, which will invoke the client callback
// passed to the fetcher.
task_environment()->FastForwardBy(base::Milliseconds(
safe_browsing::kTokenFetchTimeoutDelayFromMilliseconds));
ASSERT_TRUE(callback_invoked);
ASSERT_TRUE(access_token.empty());
}
TEST_F(SafeBrowsingTokenFetcherImplTest, FetcherDestroyedBeforeFetchReturns) {
TestAccessTokenFetchDelegate delegate;
base::RunLoop run_loop;
std::string access_token = "dummy";
std::string kTokenFromResponse = "token";
auto fetcher =
std::make_unique<SafeBrowsingTokenFetcherImpl>(base::BindRepeating(
[](TestAccessTokenFetchDelegate* delegate)
-> GoogleAccountAccessTokenFetchDelegate* { return delegate; },
&delegate));
fetcher->Start(base::BindOnce(&OnAccessTokenFetched, run_loop.QuitClosure(),
&access_token));
EXPECT_EQ(1, delegate.get_num_outstanding_requests());
EXPECT_EQ("dummy", access_token);
fetcher.reset();
// The fetcher should have responded to the outstanding request with the empty
// token on its destruction.
EXPECT_EQ(1, delegate.get_num_outstanding_requests());
EXPECT_EQ("", access_token);
// Check that the delegate responding at this point has no adverse effect.
delegate.RespondWithTokenForRequest(delegate.get_most_recent_request_id(),
kTokenFromResponse);
base::RunLoop().RunUntilIdle();
EXPECT_EQ("", access_token);
}
// Tests correct operation in the case of concurrent requests to
// SafeBrowsingTokenFetcherImpl made at different times, with an earlier one
// timing out and a later one being fulfilled.
TEST_F(SafeBrowsingTokenFetcherImplTest, ConcurrentRequestsAtDifferentTimes) {
TestAccessTokenFetchDelegate delegate;
base::RunLoop run_loop1;
base::RunLoop run_loop2;
std::string access_token1 = "dummy";
std::string access_token2 = "dummy";
std::string kTokenFromResponse1 = "token1";
std::string kTokenFromResponse2 = "token2";
int delay_before_second_request_from_ms =
safe_browsing::kTokenFetchTimeoutDelayFromMilliseconds / 2;
SafeBrowsingTokenFetcherImpl fetcher(base::BindRepeating(
[](TestAccessTokenFetchDelegate* delegate)
-> GoogleAccountAccessTokenFetchDelegate* { return delegate; },
&delegate));
fetcher.Start(base::BindOnce(&OnAccessTokenFetched, run_loop1.QuitClosure(),
&access_token1));
EXPECT_EQ(1, delegate.get_num_outstanding_requests());
int request_id1 = delegate.get_most_recent_request_id();
EXPECT_EQ("dummy", access_token1);
EXPECT_EQ("dummy", access_token2);
task_environment()->FastForwardBy(
base::Milliseconds(delay_before_second_request_from_ms));
fetcher.Start(base::BindOnce(&OnAccessTokenFetched, run_loop2.QuitClosure(),
&access_token2));
EXPECT_EQ(2, delegate.get_num_outstanding_requests());
int request_id2 = delegate.get_most_recent_request_id();
EXPECT_EQ("dummy", access_token1);
EXPECT_EQ("dummy", access_token2);
// Fast-forward to trigger the first request's timeout threshold, but not the
// second.
int time_to_trigger_first_timeout_from_ms =
safe_browsing::kTokenFetchTimeoutDelayFromMilliseconds -
delay_before_second_request_from_ms;
task_environment()->FastForwardBy(
base::Milliseconds(time_to_trigger_first_timeout_from_ms));
// Verify that the first request's timeout was handled by
// SafeBrowsingTokenFetcherImpl.
EXPECT_EQ(2, delegate.get_num_outstanding_requests());
EXPECT_EQ("", access_token1);
EXPECT_EQ("dummy", access_token2);
// Verify that the second request can still be fulfilled and that there is no
// adverse effect from the delegate now responding to the first request.
delegate.RespondWithTokenForRequest(request_id1, kTokenFromResponse1);
delegate.RespondWithTokenForRequest(request_id2, kTokenFromResponse2);
run_loop2.Run();
EXPECT_EQ("", access_token1);
EXPECT_EQ(kTokenFromResponse2, access_token2);
}
// Tests that the fetcher calls through to GoogleAccountAccessTokenFetchDelegate
// on being notified of an invalid token.
TEST_F(SafeBrowsingTokenFetcherImplTest, OnInvalidAccessToken) {
TestAccessTokenFetchDelegate delegate;
const std::string kInvalidToken = "dummy";
SafeBrowsingTokenFetcherImpl fetcher(base::BindRepeating(
[](TestAccessTokenFetchDelegate* delegate)
-> GoogleAccountAccessTokenFetchDelegate* { return delegate; },
&delegate));
EXPECT_EQ("", delegate.get_most_recent_invalid_token());
fetcher.OnInvalidAccessToken(kInvalidToken);
EXPECT_EQ(kInvalidToken, delegate.get_most_recent_invalid_token());
}
} // namespace weblayer
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/safe_browsing/safe_browsing_token_fetcher_impl_unittest.cc | C++ | unknown | 14,902 |
// Copyright 2019 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "weblayer/browser/safe_browsing/url_checker_delegate_impl.h"
#include "base/functional/bind.h"
#include "components/no_state_prefetch/browser/no_state_prefetch_manager.h"
#include "components/safe_browsing/content/browser/ui_manager.h"
#include "components/safe_browsing/core/browser/db/database_manager.h"
#include "components/security_interstitials/content/unsafe_resource_util.h"
#include "components/security_interstitials/core/unsafe_resource.h"
#include "content/public/browser/browser_task_traits.h"
#include "content/public/browser/browser_thread.h"
#include "weblayer/browser/no_state_prefetch/no_state_prefetch_manager_factory.h"
#include "weblayer/browser/no_state_prefetch/no_state_prefetch_utils.h"
namespace weblayer {
namespace {
// Destroys the NoStatePrefetch contents associated with the web_contents, if
// any.
void DestroyNoStatePrefetchContents(
content::WebContents::OnceGetter web_contents_getter) {
content::WebContents* web_contents = std::move(web_contents_getter).Run();
auto* no_state_prefetch_contents =
NoStatePrefetchContentsFromWebContents(web_contents);
if (no_state_prefetch_contents)
no_state_prefetch_contents->Destroy(prerender::FINAL_STATUS_SAFE_BROWSING);
}
} // namespace
UrlCheckerDelegateImpl::UrlCheckerDelegateImpl(
scoped_refptr<safe_browsing::SafeBrowsingDatabaseManager> database_manager,
scoped_refptr<safe_browsing::SafeBrowsingUIManager> ui_manager)
: database_manager_(std::move(database_manager)),
ui_manager_(std::move(ui_manager)),
threat_types_(safe_browsing::CreateSBThreatTypeSet(
{safe_browsing::SB_THREAT_TYPE_URL_MALWARE,
safe_browsing::SB_THREAT_TYPE_URL_PHISHING,
safe_browsing::SB_THREAT_TYPE_URL_UNWANTED,
safe_browsing::SB_THREAT_TYPE_BILLING})) {}
UrlCheckerDelegateImpl::~UrlCheckerDelegateImpl() = default;
void UrlCheckerDelegateImpl::MaybeDestroyNoStatePrefetchContents(
content::WebContents::OnceGetter web_contents_getter) {
// Destroy the prefetch with FINAL_STATUS_SAFE_BROWSING.
content::GetUIThreadTaskRunner({})->PostTask(
FROM_HERE, base::BindOnce(&DestroyNoStatePrefetchContents,
std::move(web_contents_getter)));
}
void UrlCheckerDelegateImpl::StartDisplayingBlockingPageHelper(
const security_interstitials::UnsafeResource& resource,
const std::string& method,
const net::HttpRequestHeaders& headers,
bool is_main_frame,
bool has_user_gesture) {
content::GetUIThreadTaskRunner({})->PostTask(
FROM_HERE,
base::BindOnce(
&UrlCheckerDelegateImpl::StartDisplayingDefaultBlockingPage,
base::Unretained(this), resource));
}
void UrlCheckerDelegateImpl::
StartObservingInteractionsForDelayedBlockingPageHelper(
const security_interstitials::UnsafeResource& resource,
bool is_main_frame) {
NOTREACHED() << "Delayed warnings aren't implemented for WebLayer";
}
void UrlCheckerDelegateImpl::StartDisplayingDefaultBlockingPage(
const security_interstitials::UnsafeResource& resource) {
content::WebContents* web_contents =
security_interstitials::GetWebContentsForResource(resource);
if (web_contents) {
GetUIManager()->DisplayBlockingPage(resource);
return;
}
// Report back that it is not ok to proceed with loading the URL.
content::GetIOThreadTaskRunner({})->PostTask(
FROM_HERE, base::BindOnce(resource.callback, false /* proceed */,
false /* showed_interstitial */));
}
bool UrlCheckerDelegateImpl::IsUrlAllowlisted(const GURL& url) {
// TODO(timvolodine): false for now, we may want allowlisting support later.
return false;
}
void UrlCheckerDelegateImpl::SetPolicyAllowlistDomains(
const std::vector<std::string>& allowlist_domains) {
// The SafeBrowsingAllowlistDomains policy is not supported on WebLayer.
return;
}
bool UrlCheckerDelegateImpl::ShouldSkipRequestCheck(
const GURL& original_url,
int frame_tree_node_id,
int render_process_id,
int render_frame_id,
bool originated_from_service_worker) {
return false;
}
void UrlCheckerDelegateImpl::NotifySuspiciousSiteDetected(
const base::RepeatingCallback<content::WebContents*()>&
web_contents_getter) {}
const safe_browsing::SBThreatTypeSet& UrlCheckerDelegateImpl::GetThreatTypes() {
return threat_types_;
}
safe_browsing::SafeBrowsingDatabaseManager*
UrlCheckerDelegateImpl::GetDatabaseManager() {
return database_manager_.get();
}
safe_browsing::BaseUIManager* UrlCheckerDelegateImpl::GetUIManager() {
return ui_manager_.get();
}
void UrlCheckerDelegateImpl::CheckLookupMechanismExperimentEligibility(
const security_interstitials::UnsafeResource& resource,
base::OnceCallback<void(bool)> callback,
scoped_refptr<base::SequencedTaskRunner> callback_task_runner) {
// Amongst other constraints, this function is only eligible to be called if
// BrowserUrlLoaderThrottle's CheckerOnIO has is_mechanism_experiment_allowed
// = true, which is only the case for Desktop.
NOTREACHED();
}
void UrlCheckerDelegateImpl::CheckExperimentEligibilityAndStartBlockingPage(
const security_interstitials::UnsafeResource& resource,
base::OnceCallback<void(bool)> callback,
scoped_refptr<base::SequencedTaskRunner> callback_task_runner) {
// Amongst other constraints, this function is only eligible to be called if
// BrowserUrlLoaderThrottle's CheckerOnIO has is_mechanism_experiment_allowed
// = true, which is only the case for Desktop.
NOTREACHED();
}
} // namespace weblayer
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/safe_browsing/url_checker_delegate_impl.cc | C++ | unknown | 5,744 |
// Copyright 2019 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef WEBLAYER_BROWSER_SAFE_BROWSING_URL_CHECKER_DELEGATE_IMPL_H_
#define WEBLAYER_BROWSER_SAFE_BROWSING_URL_CHECKER_DELEGATE_IMPL_H_
#include "base/memory/ref_counted.h"
#include "components/safe_browsing/core/browser/url_checker_delegate.h"
#include "content/public/browser/web_contents.h"
namespace security_interstitials {
struct UnsafeResource;
}
namespace safe_browsing {
class SafeBrowsingUIManager;
}
namespace weblayer {
class UrlCheckerDelegateImpl : public safe_browsing::UrlCheckerDelegate {
public:
UrlCheckerDelegateImpl(
scoped_refptr<safe_browsing::SafeBrowsingDatabaseManager>
database_manager,
scoped_refptr<safe_browsing::SafeBrowsingUIManager> ui_manager);
UrlCheckerDelegateImpl(const UrlCheckerDelegateImpl&) = delete;
UrlCheckerDelegateImpl& operator=(const UrlCheckerDelegateImpl&) = delete;
void SetSafeBrowsingDisabled(bool disabled);
private:
~UrlCheckerDelegateImpl() override;
// Implementation of UrlCheckerDelegate:
void MaybeDestroyNoStatePrefetchContents(
content::WebContents::OnceGetter web_contents_getter) override;
void StartDisplayingBlockingPageHelper(
const security_interstitials::UnsafeResource& resource,
const std::string& method,
const net::HttpRequestHeaders& headers,
bool is_main_frame,
bool has_user_gesture) override;
void StartObservingInteractionsForDelayedBlockingPageHelper(
const security_interstitials::UnsafeResource& resource,
bool is_main_frame) override;
void CheckLookupMechanismExperimentEligibility(
const security_interstitials::UnsafeResource& resource,
base::OnceCallback<void(bool)> callback,
scoped_refptr<base::SequencedTaskRunner> callback_task_runner) override;
void CheckExperimentEligibilityAndStartBlockingPage(
const security_interstitials::UnsafeResource& resource,
base::OnceCallback<void(bool)> callback,
scoped_refptr<base::SequencedTaskRunner> callback_task_runner) override;
bool IsUrlAllowlisted(const GURL& url) override;
void SetPolicyAllowlistDomains(
const std::vector<std::string>& allowlist_domains) override;
bool ShouldSkipRequestCheck(const GURL& original_url,
int frame_tree_node_id,
int render_process_id,
int render_frame_id,
bool originated_from_service_worker) override;
void NotifySuspiciousSiteDetected(
const base::RepeatingCallback<content::WebContents*()>&
web_contents_getter) override;
const safe_browsing::SBThreatTypeSet& GetThreatTypes() override;
safe_browsing::SafeBrowsingDatabaseManager* GetDatabaseManager() override;
safe_browsing::BaseUIManager* GetUIManager() override;
void StartDisplayingDefaultBlockingPage(
const security_interstitials::UnsafeResource& resource);
scoped_refptr<safe_browsing::SafeBrowsingDatabaseManager> database_manager_;
scoped_refptr<safe_browsing::SafeBrowsingUIManager> ui_manager_;
safe_browsing::SBThreatTypeSet threat_types_;
};
} // namespace weblayer
#endif // WEBLAYER_BROWSER_SAFE_BROWSING_URL_CHECKER_DELEGATE_IMPL_H_
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/safe_browsing/url_checker_delegate_impl.h | C++ | unknown | 3,329 |
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "weblayer/browser/safe_browsing/weblayer_client_side_detection_host_delegate.h"
#include "components/prefs/pref_service.h"
#include "components/safe_browsing/android/remote_database_manager.h"
#include "components/safe_browsing/content/browser/client_side_detection_service.h"
#include "content/public/browser/global_routing_id.h"
#include "weblayer/browser/browser_context_impl.h"
#include "weblayer/browser/browser_process.h"
#include "weblayer/browser/safe_browsing/client_side_detection_service_factory.h"
#include "weblayer/browser/safe_browsing/safe_browsing_service.h"
#include "weblayer/browser/safe_browsing/weblayer_user_population_helper.h"
#include "weblayer/browser/verdict_cache_manager_factory.h"
namespace weblayer {
WebLayerClientSideDetectionHostDelegate::
WebLayerClientSideDetectionHostDelegate(content::WebContents* web_contents)
: web_contents_(web_contents) {}
WebLayerClientSideDetectionHostDelegate::
~WebLayerClientSideDetectionHostDelegate() = default;
bool WebLayerClientSideDetectionHostDelegate::
HasSafeBrowsingUserInteractionObserver() {
return false;
}
PrefService* WebLayerClientSideDetectionHostDelegate::GetPrefs() {
BrowserContextImpl* browser_context_impl =
static_cast<BrowserContextImpl*>(web_contents_->GetBrowserContext());
DCHECK(browser_context_impl);
return browser_context_impl->pref_service();
}
scoped_refptr<safe_browsing::SafeBrowsingDatabaseManager>
WebLayerClientSideDetectionHostDelegate::GetSafeBrowsingDBManager() {
SafeBrowsingService* sb_service =
BrowserProcess::GetInstance()->GetSafeBrowsingService();
return sb_service->GetSafeBrowsingDBManager();
}
scoped_refptr<safe_browsing::BaseUIManager>
WebLayerClientSideDetectionHostDelegate::GetSafeBrowsingUIManager() {
SafeBrowsingService* sb_service =
BrowserProcess::GetInstance()->GetSafeBrowsingService();
return sb_service->GetSafeBrowsingUIManager();
}
base::WeakPtr<safe_browsing::ClientSideDetectionService>
WebLayerClientSideDetectionHostDelegate::GetClientSideDetectionService() {
return ClientSideDetectionServiceFactory::GetForBrowserContext(
web_contents_->GetBrowserContext())
->GetWeakPtr();
}
void WebLayerClientSideDetectionHostDelegate::AddReferrerChain(
safe_browsing::ClientPhishingRequest* verdict,
GURL current_url,
const content::GlobalRenderFrameHostId& current_outermost_main_frame_id) {}
safe_browsing::VerdictCacheManager*
WebLayerClientSideDetectionHostDelegate::GetCacheManager() {
return VerdictCacheManagerFactory::GetForBrowserContext(
web_contents_->GetBrowserContext());
}
safe_browsing::ChromeUserPopulation
WebLayerClientSideDetectionHostDelegate::GetUserPopulation() {
return GetUserPopulationForBrowserContext(web_contents_->GetBrowserContext());
}
} // namespace weblayer
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/safe_browsing/weblayer_client_side_detection_host_delegate.cc | C++ | unknown | 2,977 |
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef WEBLAYER_BROWSER_SAFE_BROWSING_WEBLAYER_CLIENT_SIDE_DETECTION_HOST_DELEGATE_H_
#define WEBLAYER_BROWSER_SAFE_BROWSING_WEBLAYER_CLIENT_SIDE_DETECTION_HOST_DELEGATE_H_
#include "base/memory/raw_ptr.h"
#include "components/safe_browsing/content/browser/client_side_detection_host.h"
#include "components/safe_browsing/core/common/proto/csd.pb.h"
#include "url/gurl.h"
namespace content {
struct GlobalRenderFrameHostId;
} // namespace content
namespace weblayer {
class WebLayerClientSideDetectionHostDelegate
: public safe_browsing::ClientSideDetectionHost::Delegate {
public:
explicit WebLayerClientSideDetectionHostDelegate(
content::WebContents* web_contents);
WebLayerClientSideDetectionHostDelegate(
const WebLayerClientSideDetectionHostDelegate&) = delete;
WebLayerClientSideDetectionHostDelegate& operator=(
const WebLayerClientSideDetectionHostDelegate&) = delete;
~WebLayerClientSideDetectionHostDelegate() override;
// ClientSideDetectionHost::Delegate implementation.
bool HasSafeBrowsingUserInteractionObserver() override;
PrefService* GetPrefs() override;
scoped_refptr<safe_browsing::SafeBrowsingDatabaseManager>
GetSafeBrowsingDBManager() override;
scoped_refptr<safe_browsing::BaseUIManager> GetSafeBrowsingUIManager()
override;
base::WeakPtr<safe_browsing::ClientSideDetectionService>
GetClientSideDetectionService() override;
void AddReferrerChain(safe_browsing::ClientPhishingRequest* verdict,
GURL current_url,
const content::GlobalRenderFrameHostId&
current_outermost_main_frame_id) override;
safe_browsing::VerdictCacheManager* GetCacheManager() override;
safe_browsing::ChromeUserPopulation GetUserPopulation() override;
private:
raw_ptr<content::WebContents> web_contents_;
};
} // namespace weblayer
#endif // WEBLAYER_BROWSER_SAFE_BROWSING_WEBLAYER_CLIENT_SIDE_DETECTION_HOST_DELEGATE_H_
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/safe_browsing/weblayer_client_side_detection_host_delegate.h | C++ | unknown | 2,115 |
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "weblayer/browser/safe_browsing/weblayer_client_side_detection_service_delegate.h"
#include "components/prefs/pref_service.h"
#include "components/safe_browsing/core/common/proto/csd.pb.h"
#include "components/safe_browsing/core/common/utils.h"
#include "components/unified_consent/pref_names.h"
#include "content/public/browser/storage_partition.h"
#include "weblayer/browser/browser_context_impl.h"
#include "weblayer/browser/browser_process.h"
#include "weblayer/browser/safe_browsing/safe_browsing_service.h"
namespace weblayer {
WebLayerClientSideDetectionServiceDelegate::
WebLayerClientSideDetectionServiceDelegate(
BrowserContextImpl* browser_context)
: browser_context_(browser_context) {}
WebLayerClientSideDetectionServiceDelegate::
~WebLayerClientSideDetectionServiceDelegate() = default;
PrefService* WebLayerClientSideDetectionServiceDelegate::GetPrefs() {
DCHECK(browser_context_);
return browser_context_->pref_service();
}
scoped_refptr<network::SharedURLLoaderFactory>
WebLayerClientSideDetectionServiceDelegate::GetURLLoaderFactory() {
return browser_context_->GetDefaultStoragePartition()
->GetURLLoaderFactoryForBrowserProcess();
}
scoped_refptr<network::SharedURLLoaderFactory>
WebLayerClientSideDetectionServiceDelegate::GetSafeBrowsingURLLoaderFactory() {
SafeBrowsingService* sb_service =
BrowserProcess::GetInstance()->GetSafeBrowsingService();
return sb_service->GetURLLoaderFactory();
}
} // namespace weblayer
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/safe_browsing/weblayer_client_side_detection_service_delegate.cc | C++ | unknown | 1,643 |
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef WEBLAYER_BROWSER_SAFE_BROWSING_WEBLAYER_CLIENT_SIDE_DETECTION_SERVICE_DELEGATE_H_
#define WEBLAYER_BROWSER_SAFE_BROWSING_WEBLAYER_CLIENT_SIDE_DETECTION_SERVICE_DELEGATE_H_
#include "base/memory/raw_ptr.h"
#include "components/safe_browsing/content/browser/client_side_detection_service.h"
#include "weblayer/browser/browser_context_impl.h"
namespace weblayer {
class WebLayerClientSideDetectionServiceDelegate
: public safe_browsing::ClientSideDetectionService::Delegate {
public:
explicit WebLayerClientSideDetectionServiceDelegate(
BrowserContextImpl* browser_context);
WebLayerClientSideDetectionServiceDelegate(
const WebLayerClientSideDetectionServiceDelegate&) = delete;
WebLayerClientSideDetectionServiceDelegate& operator=(
const WebLayerClientSideDetectionServiceDelegate&) = delete;
~WebLayerClientSideDetectionServiceDelegate() override;
// ClientSideDetectionService::Delegate implementation.
PrefService* GetPrefs() override;
scoped_refptr<network::SharedURLLoaderFactory> GetURLLoaderFactory() override;
scoped_refptr<network::SharedURLLoaderFactory>
GetSafeBrowsingURLLoaderFactory() override;
private:
raw_ptr<BrowserContextImpl> browser_context_;
};
} // namespace weblayer
#endif // WEBLAYER_BROWSER_SAFE_BROWSING_WEBLAYER_CLIENT_SIDE_DETECTION_SERVICE_DELEGATE_H_
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/safe_browsing/weblayer_client_side_detection_service_delegate.h | C++ | unknown | 1,490 |
// Copyright 2022 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "weblayer/browser/safe_browsing/weblayer_ping_manager_factory.h"
#include "base/no_destructor.h"
#include "components/keyed_service/content/browser_context_dependency_manager.h"
#include "components/safe_browsing/content/browser/web_ui/safe_browsing_ui.h"
#include "components/safe_browsing/core/browser/ping_manager.h"
#include "components/safe_browsing/core/common/features.h"
#include "content/public/browser/browser_thread.h"
#include "weblayer/browser/browser_context_impl.h"
#include "weblayer/browser/browser_process.h"
#include "weblayer/browser/profile_impl.h"
#include "weblayer/browser/safe_browsing/safe_browsing_service.h"
#include "weblayer/browser/safe_browsing/safe_browsing_token_fetcher_impl.h"
#include "weblayer/browser/safe_browsing/weblayer_user_population_helper.h"
namespace weblayer {
// static
WebLayerPingManagerFactory* WebLayerPingManagerFactory::GetInstance() {
static base::NoDestructor<WebLayerPingManagerFactory> instance;
return instance.get();
}
// static
safe_browsing::PingManager* WebLayerPingManagerFactory::GetForBrowserContext(
content::BrowserContext* context) {
return static_cast<safe_browsing::PingManager*>(
GetInstance()->GetServiceForBrowserContext(context, /*create=*/true));
}
WebLayerPingManagerFactory::WebLayerPingManagerFactory()
: BrowserContextKeyedServiceFactory(
"WeblayerSafeBrowsingPingManager",
BrowserContextDependencyManager::GetInstance()) {}
WebLayerPingManagerFactory::~WebLayerPingManagerFactory() = default;
KeyedService* WebLayerPingManagerFactory::BuildServiceInstanceFor(
content::BrowserContext* context) const {
return safe_browsing::PingManager::Create(
safe_browsing::GetV4ProtocolConfig(GetProtocolConfigClientName(),
/*disable_auto_update=*/false),
// TODO(crbug.com/1233532): Should WebLayer support the
// kSafeBrowsingSeparateNetworkContexts feature?
BrowserProcess::GetInstance()
->GetSafeBrowsingService()
->GetURLLoaderFactory(),
std::make_unique<SafeBrowsingTokenFetcherImpl>(base::BindRepeating(
&ProfileImpl::access_token_fetch_delegate,
base::Unretained(ProfileImpl::FromBrowserContext(context)))),
base::BindRepeating(
&WebLayerPingManagerFactory::ShouldFetchAccessTokenForReport,
base::Unretained(this), context),
safe_browsing::WebUIInfoSingleton::GetInstance(),
content::GetUIThreadTaskRunner({}),
base::BindRepeating(&GetUserPopulationForBrowserContext, context),
base::FeatureList::IsEnabled(
safe_browsing::kAddPageLoadTokenToClientSafeBrowsingReport)
? base::BindRepeating(&GetPageLoadTokenForURL, context)
: base::NullCallback());
}
bool WebLayerPingManagerFactory::ShouldFetchAccessTokenForReport(
content::BrowserContext* context) const {
PrefService* pref_service =
static_cast<BrowserContextImpl*>(context)->pref_service();
return safe_browsing::IsEnhancedProtectionEnabled(*pref_service) &&
// TODO(crbug.com/1171215): Change this to production mechanism for
// enabling Gaia-keyed client reports once that mechanism is
// determined.
is_account_signed_in_for_testing_;
}
std::string WebLayerPingManagerFactory::GetProtocolConfigClientName() const {
// Return a weblayer specific client name.
return "weblayer";
}
// TODO(crbug.com/1171215): Remove this once browsertests can enable this
// functionality via the production mechanism for doing so.
void WebLayerPingManagerFactory::SignInAccountForTesting() {
is_account_signed_in_for_testing_ = true;
}
} // namespace weblayer
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/safe_browsing/weblayer_ping_manager_factory.cc | C++ | unknown | 3,836 |
// Copyright 2022 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef WEBLAYER_BROWSER_SAFE_BROWSING_WEBLAYER_PING_MANAGER_FACTORY_H_
#define WEBLAYER_BROWSER_SAFE_BROWSING_WEBLAYER_PING_MANAGER_FACTORY_H_
#include "base/no_destructor.h"
#include "components/keyed_service/content/browser_context_keyed_service_factory.h"
#include "components/safe_browsing/core/browser/ping_manager.h"
namespace weblayer {
// Factory for creating the KeyedService PingManager for WebLayer. It returns
// null for incognito mode.
class WebLayerPingManagerFactory : public BrowserContextKeyedServiceFactory {
public:
static WebLayerPingManagerFactory* GetInstance();
static safe_browsing::PingManager* GetForBrowserContext(
content::BrowserContext* context);
// TODO(crbug.com/1171215): Remove this once browsertests can enable this
// functionality via the production mechanism for doing so.
void SignInAccountForTesting();
private:
friend class base::NoDestructor<WebLayerPingManagerFactory>;
friend class WeblayerPingManagerFactoryTest;
WebLayerPingManagerFactory();
~WebLayerPingManagerFactory() override;
// BrowserContextKeyedServiceFactory override:
KeyedService* BuildServiceInstanceFor(
content::BrowserContext* context) const override;
bool ShouldFetchAccessTokenForReport(content::BrowserContext* context) const;
std::string GetProtocolConfigClientName() const;
// TODO(crbug.com/1171215): Remove this once browsertests can enable this
// functionality via the production mechanism for doing so.
bool is_account_signed_in_for_testing_ = false;
};
} // namespace weblayer
#endif // WEBLAYER_BROWSER_SAFE_BROWSING_WEBLAYER_PING_MANAGER_FACTORY_H_
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/safe_browsing/weblayer_ping_manager_factory.h | C++ | unknown | 1,779 |
// 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 "base/functional/bind.h"
#include "base/functional/callback.h"
#include "base/test/bind.h"
#include "base/time/time.h"
#include "components/safe_browsing/core/common/safe_browsing_prefs.h"
#include "services/network/public/cpp/weak_wrapper_shared_url_loader_factory.h"
#include "services/network/test/test_url_loader_factory.h"
#include "services/network/test/test_utils.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "weblayer/browser/browser_context_impl.h"
#include "weblayer/browser/profile_impl.h"
#include "weblayer/browser/safe_browsing/weblayer_ping_manager_factory.h"
#include "weblayer/browser/safe_browsing/weblayer_user_population_helper.h"
#include "weblayer/test/weblayer_browser_test.h"
using safe_browsing::ClientSafeBrowsingReportRequest;
using ReportThreatDetailsResult =
safe_browsing::PingManager::ReportThreatDetailsResult;
namespace weblayer {
class WeblayerPingManagerFactoryTest : public WebLayerBrowserTest {
protected:
void RunShouldFetchAccessTokenForReportTest(bool is_enhanced_protection,
bool is_signed_in,
bool expect_should_fetch);
};
class IncognitoModeWeblayerPingManagerFactoryTest
: public WeblayerPingManagerFactoryTest {
public:
IncognitoModeWeblayerPingManagerFactoryTest() {
SetShellStartsInIncognitoMode();
}
};
void WeblayerPingManagerFactoryTest::RunShouldFetchAccessTokenForReportTest(
bool is_enhanced_protection,
bool is_signed_in,
bool expect_should_fetch) {
SetSafeBrowsingState(
GetProfile()->GetBrowserContext()->pref_service(),
is_enhanced_protection
? safe_browsing::SafeBrowsingState::ENHANCED_PROTECTION
: safe_browsing::SafeBrowsingState::STANDARD_PROTECTION);
if (is_signed_in) {
WebLayerPingManagerFactory::GetInstance()->SignInAccountForTesting();
}
EXPECT_EQ(
WebLayerPingManagerFactory::GetInstance()
->ShouldFetchAccessTokenForReport(GetProfile()->GetBrowserContext()),
expect_should_fetch);
}
IN_PROC_BROWSER_TEST_F(WeblayerPingManagerFactoryTest, ReportThreatDetails) {
auto* ping_manager = WebLayerPingManagerFactory::GetForBrowserContext(
GetProfile()->GetBrowserContext());
std::string input_report_content;
std::unique_ptr<ClientSafeBrowsingReportRequest> report =
std::make_unique<ClientSafeBrowsingReportRequest>();
// The report must be non-empty. The selected property to set is arbitrary.
report->set_type(ClientSafeBrowsingReportRequest::URL_PHISHING);
EXPECT_TRUE(report->SerializeToString(&input_report_content));
ClientSafeBrowsingReportRequest expected_report;
expected_report.ParseFromString(input_report_content);
*expected_report.mutable_population() =
GetUserPopulationForBrowserContext(GetProfile()->GetBrowserContext());
std::string expected_report_content;
EXPECT_TRUE(expected_report.SerializeToString(&expected_report_content));
network::TestURLLoaderFactory test_url_loader_factory;
test_url_loader_factory.SetInterceptor(
base::BindLambdaForTesting([&](const network::ResourceRequest& request) {
EXPECT_EQ(GetUploadData(request), expected_report_content);
}));
ping_manager->SetURLLoaderFactoryForTesting(
base::MakeRefCounted<network::WeakWrapperSharedURLLoaderFactory>(
&test_url_loader_factory));
EXPECT_EQ(ping_manager->ReportThreatDetails(std::move(report)),
ReportThreatDetailsResult::SUCCESS);
}
IN_PROC_BROWSER_TEST_F(IncognitoModeWeblayerPingManagerFactoryTest,
DISABLED_NoPingManagerForIncognito) {
EXPECT_EQ(WebLayerPingManagerFactory::GetForBrowserContext(
GetProfile()->GetBrowserContext()),
nullptr);
}
IN_PROC_BROWSER_TEST_F(WeblayerPingManagerFactoryTest,
ShouldFetchAccessTokenForReport_Yes) {
RunShouldFetchAccessTokenForReportTest(/*is_enhanced_protection=*/true,
/*is_signed_in=*/true,
/*expect_should_fetch=*/true);
}
IN_PROC_BROWSER_TEST_F(WeblayerPingManagerFactoryTest,
ShouldFetchAccessTokenForReport_NotEnhancedProtection) {
RunShouldFetchAccessTokenForReportTest(/*is_enhanced_protection=*/false,
/*is_signed_in=*/true,
/*expect_should_fetch=*/false);
}
IN_PROC_BROWSER_TEST_F(WeblayerPingManagerFactoryTest,
ShouldFetchAccessTokenForReport_NotSignedIn) {
RunShouldFetchAccessTokenForReportTest(/*is_enhanced_protection=*/true,
/*is_signed_in=*/false,
/*expect_should_fetch=*/false);
}
} // namespace weblayer
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/safe_browsing/weblayer_ping_manager_factory_browsertest.cc | C++ | unknown | 5,007 |
// Copyright 2021 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "weblayer/browser/safe_browsing/weblayer_safe_browsing_blocking_page_factory.h"
#include "components/security_interstitials/content/security_interstitial_controller_client.h"
#include "components/security_interstitials/content/settings_page_helper.h"
#include "components/security_interstitials/core/base_safe_browsing_error_ui.h"
#include "content/public/browser/navigation_entry.h"
#include "weblayer/browser/browser_context_impl.h"
#include "weblayer/browser/browser_process.h"
#include "weblayer/browser/safe_browsing/safe_browsing_metrics_collector_factory.h"
#include "weblayer/browser/safe_browsing/safe_browsing_navigation_observer_manager_factory.h"
#include "weblayer/browser/safe_browsing/safe_browsing_service.h"
namespace weblayer {
safe_browsing::SafeBrowsingBlockingPage*
WebLayerSafeBrowsingBlockingPageFactory::CreateSafeBrowsingPage(
safe_browsing::BaseUIManager* ui_manager,
content::WebContents* web_contents,
const GURL& main_frame_url,
const safe_browsing::SafeBrowsingBlockingPage::UnsafeResourceList&
unsafe_resources,
bool should_trigger_reporting) {
BrowserContextImpl* browser_context =
static_cast<BrowserContextImpl*>(web_contents->GetBrowserContext());
security_interstitials::BaseSafeBrowsingErrorUI::SBErrorDisplayOptions
display_options =
safe_browsing::BaseBlockingPage::CreateDefaultDisplayOptions(
unsafe_resources);
display_options.is_extended_reporting_opt_in_allowed =
safe_browsing::IsExtendedReportingOptInAllowed(
*(browser_context->pref_service()));
display_options.is_extended_reporting_enabled =
safe_browsing::IsExtendedReportingEnabled(
*(browser_context->pref_service()));
// TODO(crbug.com/1080748): Set settings_page_helper once enhanced protection
// is supported on weblayer.
return new safe_browsing::SafeBrowsingBlockingPage(
ui_manager, web_contents, main_frame_url, unsafe_resources,
safe_browsing::BaseBlockingPage::CreateControllerClient(
web_contents, unsafe_resources, ui_manager,
browser_context->pref_service(),
/*settings_page_helper*/ nullptr),
display_options, should_trigger_reporting,
// WebLayer doesn't integrate //components/history.
/*history_service=*/nullptr,
SafeBrowsingNavigationObserverManagerFactory::GetForBrowserContext(
browser_context),
SafeBrowsingMetricsCollectorFactory::GetForBrowserContext(
browser_context),
BrowserProcess::GetInstance()
->GetSafeBrowsingService()
->GetTriggerManager());
}
} // namespace weblayer
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/safe_browsing/weblayer_safe_browsing_blocking_page_factory.cc | C++ | unknown | 2,790 |
// Copyright 2021 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef WEBLAYER_BROWSER_SAFE_BROWSING_WEBLAYER_SAFE_BROWSING_BLOCKING_PAGE_FACTORY_H_
#define WEBLAYER_BROWSER_SAFE_BROWSING_WEBLAYER_SAFE_BROWSING_BLOCKING_PAGE_FACTORY_H_
#include "components/safe_browsing/content/browser/safe_browsing_blocking_page_factory.h"
namespace weblayer {
// Factory for creating SafeBrowsingBlockingPage.
class WebLayerSafeBrowsingBlockingPageFactory
: public safe_browsing::SafeBrowsingBlockingPageFactory {
public:
WebLayerSafeBrowsingBlockingPageFactory() = default;
~WebLayerSafeBrowsingBlockingPageFactory() override = default;
// safe_browsing::SafeBrowsingBlockingPageFactory:
safe_browsing::SafeBrowsingBlockingPage* CreateSafeBrowsingPage(
safe_browsing::BaseUIManager* ui_manager,
content::WebContents* web_contents,
const GURL& main_frame_url,
const safe_browsing::SafeBrowsingBlockingPage::UnsafeResourceList&
unsafe_resources,
bool should_trigger_reporting) override;
};
} // namespace weblayer
#endif // WEBLAYER_BROWSER_SAFE_BROWSING_WEBLAYER_SAFE_BROWSING_BLOCKING_PAGE_FACTORY_H_
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/safe_browsing/weblayer_safe_browsing_blocking_page_factory.h | C++ | unknown | 1,232 |
// Copyright 2021 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "weblayer/browser/safe_browsing/weblayer_safe_browsing_tab_observer_delegate.h"
#include "base/functional/bind.h"
#include "components/prefs/pref_service.h"
#include "components/safe_browsing/content/browser/client_side_detection_host.h"
#include "components/safe_browsing/content/browser/client_side_detection_service.h"
#include "content/public/browser/web_contents.h"
#include "weblayer/browser/browser_context_impl.h"
#include "weblayer/browser/browser_process.h"
#include "weblayer/browser/profile_impl.h"
#include "weblayer/browser/safe_browsing/client_side_detection_service_factory.h"
#include "weblayer/browser/safe_browsing/safe_browsing_service.h"
#include "weblayer/browser/safe_browsing/safe_browsing_token_fetcher_impl.h"
#include "weblayer/browser/safe_browsing/weblayer_client_side_detection_host_delegate.h"
namespace weblayer {
namespace {
std::unique_ptr<safe_browsing::ClientSideDetectionHost>
CreateClientSideDetectionHost(content::WebContents* web_contents,
PrefService* prefs,
BrowserContextImpl* browser_context) {
return safe_browsing::ClientSideDetectionHost::Create(
web_contents,
std::make_unique<WebLayerClientSideDetectionHostDelegate>(web_contents),
prefs,
std::make_unique<SafeBrowsingTokenFetcherImpl>(base::BindRepeating(
&ProfileImpl::access_token_fetch_delegate,
base::Unretained(ProfileImpl::FromBrowserContext(browser_context)))),
static_cast<BrowserContextImpl*>(browser_context)->IsOffTheRecord(),
// TODO(crbug.com/1171215): Change this to production mechanism for
// enabling Gaia-keyed CSD once that mechanism is determined. See also
// crbug.com/1190615.
/* account_signed_in_callback= */ base::BindRepeating([]() {
return false;
}));
}
} // namespace
WebLayerSafeBrowsingTabObserverDelegate::
WebLayerSafeBrowsingTabObserverDelegate() = default;
WebLayerSafeBrowsingTabObserverDelegate::
~WebLayerSafeBrowsingTabObserverDelegate() = default;
PrefService* WebLayerSafeBrowsingTabObserverDelegate::GetPrefs(
content::BrowserContext* browser_context) {
return static_cast<BrowserContextImpl*>(browser_context)->pref_service();
}
safe_browsing::ClientSideDetectionService*
WebLayerSafeBrowsingTabObserverDelegate::GetClientSideDetectionServiceIfExists(
content::BrowserContext* browser_context) {
return ClientSideDetectionServiceFactory::GetForBrowserContext(
browser_context);
}
bool WebLayerSafeBrowsingTabObserverDelegate::DoesSafeBrowsingServiceExist() {
return BrowserProcess::GetInstance()->GetSafeBrowsingService();
}
std::unique_ptr<safe_browsing::ClientSideDetectionHost>
WebLayerSafeBrowsingTabObserverDelegate::CreateClientSideDetectionHost(
content::WebContents* web_contents) {
BrowserContextImpl* browser_context =
static_cast<BrowserContextImpl*>(web_contents->GetBrowserContext());
return ::weblayer::CreateClientSideDetectionHost(
web_contents, GetPrefs(browser_context), browser_context);
}
} // namespace weblayer
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/safe_browsing/weblayer_safe_browsing_tab_observer_delegate.cc | C++ | unknown | 3,238 |
// Copyright 2021 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef WEBLAYER_BROWSER_SAFE_BROWSING_WEBLAYER_SAFE_BROWSING_TAB_OBSERVER_DELEGATE_H_
#define WEBLAYER_BROWSER_SAFE_BROWSING_WEBLAYER_SAFE_BROWSING_TAB_OBSERVER_DELEGATE_H_
#include "components/safe_browsing/content/browser/safe_browsing_tab_observer.h"
namespace weblayer {
// Provides embedder-specific logic for SafeBrowsingTabObserver.
class WebLayerSafeBrowsingTabObserverDelegate
: public safe_browsing::SafeBrowsingTabObserver::Delegate {
public:
WebLayerSafeBrowsingTabObserverDelegate();
~WebLayerSafeBrowsingTabObserverDelegate() override;
WebLayerSafeBrowsingTabObserverDelegate(
const WebLayerSafeBrowsingTabObserverDelegate&) = delete;
WebLayerSafeBrowsingTabObserverDelegate& operator=(
const WebLayerSafeBrowsingTabObserverDelegate&) = delete;
// SafeBrowsingTabObserver::Delegate:
PrefService* GetPrefs(content::BrowserContext* browser_context) override;
safe_browsing::ClientSideDetectionService*
GetClientSideDetectionServiceIfExists(
content::BrowserContext* browser_context) override;
bool DoesSafeBrowsingServiceExist() override;
std::unique_ptr<safe_browsing::ClientSideDetectionHost>
CreateClientSideDetectionHost(content::WebContents* web_contents) override;
};
} // namespace weblayer
#endif // WEBLAYER_BROWSER_SAFE_BROWSING_WEBLAYER_SAFE_BROWSING_TAB_OBSERVER_DELEGATE_H_
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/safe_browsing/weblayer_safe_browsing_tab_observer_delegate.h | C++ | unknown | 1,498 |
// Copyright 2021 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "weblayer/browser/safe_browsing/weblayer_ui_manager_delegate.h"
#include "components/safe_browsing/core/browser/ping_manager.h"
#include "content/public/browser/web_contents.h"
#include "services/network/public/cpp/cross_thread_pending_shared_url_loader_factory.h"
#include "weblayer/browser/browser_context_impl.h"
#include "weblayer/browser/browser_process.h"
#include "weblayer/browser/i18n_util.h"
#include "weblayer/browser/no_state_prefetch/no_state_prefetch_utils.h"
#include "weblayer/browser/safe_browsing/weblayer_ping_manager_factory.h"
#include "weblayer/browser/weblayer_metrics_service_accessor.h"
namespace weblayer {
WebLayerSafeBrowsingUIManagerDelegate::WebLayerSafeBrowsingUIManagerDelegate() =
default;
WebLayerSafeBrowsingUIManagerDelegate::
~WebLayerSafeBrowsingUIManagerDelegate() = default;
std::string WebLayerSafeBrowsingUIManagerDelegate::GetApplicationLocale() {
return i18n::GetApplicationLocale();
}
void WebLayerSafeBrowsingUIManagerDelegate::
TriggerSecurityInterstitialShownExtensionEventIfDesired(
content::WebContents* web_contents,
const GURL& page_url,
const std::string& reason,
int net_error_code) {}
void WebLayerSafeBrowsingUIManagerDelegate::
TriggerSecurityInterstitialProceededExtensionEventIfDesired(
content::WebContents* web_contents,
const GURL& page_url,
const std::string& reason,
int net_error_code) {}
prerender::NoStatePrefetchContents*
WebLayerSafeBrowsingUIManagerDelegate::GetNoStatePrefetchContentsIfExists(
content::WebContents* web_contents) {
return NoStatePrefetchContentsFromWebContents(web_contents);
}
bool WebLayerSafeBrowsingUIManagerDelegate::IsHostingExtension(
content::WebContents* web_contents) {
return false;
}
PrefService* WebLayerSafeBrowsingUIManagerDelegate::GetPrefs(
content::BrowserContext* browser_context) {
return static_cast<BrowserContextImpl*>(browser_context)->pref_service();
}
history::HistoryService*
WebLayerSafeBrowsingUIManagerDelegate::GetHistoryService(
content::BrowserContext* browser_context) {
return nullptr;
}
safe_browsing::PingManager*
WebLayerSafeBrowsingUIManagerDelegate::GetPingManager(
content::BrowserContext* browser_context) {
return WebLayerPingManagerFactory::GetForBrowserContext(browser_context);
}
bool WebLayerSafeBrowsingUIManagerDelegate::
IsMetricsAndCrashReportingEnabled() {
return WebLayerMetricsServiceAccessor::IsMetricsReportingEnabled(
BrowserProcess::GetInstance()->GetLocalState());
}
bool WebLayerSafeBrowsingUIManagerDelegate::IsSendingOfHitReportsEnabled() {
// TODO(crbug.com/1232315): Determine whether to enable sending of hit reports
// in WebLayer.
return false;
}
} // namespace weblayer
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/safe_browsing/weblayer_ui_manager_delegate.cc | C++ | unknown | 2,924 |
// Copyright 2021 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef WEBLAYER_BROWSER_SAFE_BROWSING_WEBLAYER_UI_MANAGER_DELEGATE_H_
#define WEBLAYER_BROWSER_SAFE_BROWSING_WEBLAYER_UI_MANAGER_DELEGATE_H_
#include "components/safe_browsing/content/browser/ui_manager.h"
namespace weblayer {
// Provides embedder-specific logic for SafeBrowsingUIManager.
class WebLayerSafeBrowsingUIManagerDelegate
: public safe_browsing::SafeBrowsingUIManager::Delegate {
public:
WebLayerSafeBrowsingUIManagerDelegate();
~WebLayerSafeBrowsingUIManagerDelegate() override;
WebLayerSafeBrowsingUIManagerDelegate(
const WebLayerSafeBrowsingUIManagerDelegate&) = delete;
WebLayerSafeBrowsingUIManagerDelegate& operator=(
const WebLayerSafeBrowsingUIManagerDelegate&) = delete;
// safe_browsing::SafeBrowsingUIManager::Delegate:
std::string GetApplicationLocale() override;
void TriggerSecurityInterstitialShownExtensionEventIfDesired(
content::WebContents* web_contents,
const GURL& page_url,
const std::string& reason,
int net_error_code) override;
void TriggerSecurityInterstitialProceededExtensionEventIfDesired(
content::WebContents* web_contents,
const GURL& page_url,
const std::string& reason,
int net_error_code) override;
prerender::NoStatePrefetchContents* GetNoStatePrefetchContentsIfExists(
content::WebContents* web_contents) override;
bool IsHostingExtension(content::WebContents* web_contents) override;
PrefService* GetPrefs(content::BrowserContext* browser_context) override;
history::HistoryService* GetHistoryService(
content::BrowserContext* browser_context) override;
safe_browsing::PingManager* GetPingManager(
content::BrowserContext* browser_context) override;
bool IsMetricsAndCrashReportingEnabled() override;
bool IsSendingOfHitReportsEnabled() override;
};
} // namespace weblayer
#endif // WEBLAYER_BROWSER_SAFE_BROWSING_WEBLAYER_UI_MANAGER_DELEGATE_H_
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/safe_browsing/weblayer_ui_manager_delegate.h | C++ | unknown | 2,065 |
// Copyright 2021 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "weblayer/browser/safe_browsing/weblayer_user_population_helper.h"
#include "components/safe_browsing/core/browser/user_population.h"
#include "components/safe_browsing/core/browser/verdict_cache_manager.h"
#include "weblayer/browser/browser_context_impl.h"
#include "weblayer/browser/verdict_cache_manager_factory.h"
namespace weblayer {
safe_browsing::ChromeUserPopulation GetUserPopulationForBrowserContext(
content::BrowserContext* browser_context) {
auto* browser_context_impl =
static_cast<BrowserContextImpl*>(browser_context);
return safe_browsing::GetUserPopulation(
browser_context_impl->pref_service(),
browser_context_impl->IsOffTheRecord(),
/*is_history_sync_enabled=*/false,
/*is_signed_in=*/false,
/*is_under_advanced_protection=*/false,
/*browser_policy_connector=*/nullptr,
/*num_profiles=*/absl::optional<size_t>(),
/*num_loaded_profiles=*/absl::optional<size_t>(),
/*num_open_profiles=*/absl::optional<size_t>());
}
safe_browsing::ChromeUserPopulation::PageLoadToken GetPageLoadTokenForURL(
content::BrowserContext* browser_context,
GURL url) {
safe_browsing::VerdictCacheManager* cache_manager =
VerdictCacheManagerFactory::GetForBrowserContext(browser_context);
if (!cache_manager) {
return safe_browsing::ChromeUserPopulation::PageLoadToken();
}
return cache_manager->GetPageLoadToken(url);
}
} // namespace weblayer
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/safe_browsing/weblayer_user_population_helper.cc | C++ | unknown | 1,593 |
// Copyright 2021 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef WEBLAYER_BROWSER_SAFE_BROWSING_WEBLAYER_USER_POPULATION_HELPER_H_
#define WEBLAYER_BROWSER_SAFE_BROWSING_WEBLAYER_USER_POPULATION_HELPER_H_
#include "components/safe_browsing/core/common/proto/csd.pb.h"
#include "url/gurl.h"
namespace content {
class BrowserContext;
}
namespace weblayer {
// A convenience function that creates a ChromeUserPopulation proto for the
// given |browser_context| and populates it appropriately for WebLayer.
safe_browsing::ChromeUserPopulation GetUserPopulationForBrowserContext(
content::BrowserContext* browser_context);
// A function that returns tha page load token for the provided URL
safe_browsing::ChromeUserPopulation::PageLoadToken GetPageLoadTokenForURL(
content::BrowserContext* browser_context,
GURL url);
} // namespace weblayer
#endif // WEBLAYER_BROWSER_SAFE_BROWSING_WEBLAYER_USER_POPULATION_HELPER_H_
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/safe_browsing/weblayer_user_population_helper.h | C++ | unknown | 1,022 |
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "weblayer/browser/signin_url_loader_throttle.h"
#include "components/content_settings/core/browser/cookie_settings.h"
#include "components/signin/core/browser/signin_header_helper.h"
#include "components/signin/public/base/account_consistency_method.h"
#include "components/signin/public/identity_manager/tribool.h"
#include "content/public/browser/browser_context.h"
#include "content/public/browser/browser_task_traits.h"
#include "content/public/browser/browser_thread.h"
#include "google_apis/gaia/gaia_auth_util.h"
#include "net/base/url_util.h"
#include "services/network/public/cpp/resource_request.h"
#include "services/network/public/mojom/url_response_head.mojom.h"
#include "third_party/blink/public/mojom/loader/resource_load_info.mojom.h"
#include "weblayer/browser/cookie_settings_factory.h"
#include "weblayer/browser/tab_impl.h"
#include "weblayer/public/google_accounts_delegate.h"
namespace weblayer {
const char kSignOutPath[] = "/SignOutOptions";
namespace {
constexpr char kWebLayerMirrorHeaderSource[] = "WebLayer";
GoogleAccountsDelegate* GetDelegate(
const content::WebContents::Getter& web_contents_getter) {
auto* web_contents = web_contents_getter.Run();
if (!web_contents)
return nullptr;
auto* tab = TabImpl::FromWebContents(web_contents);
if (!tab)
return nullptr;
return tab->google_accounts_delegate();
}
void ProcessMirrorHeader(content::WebContents::Getter web_contents_getter,
const signin::ManageAccountsParams& params) {
auto* delegate = GetDelegate(web_contents_getter);
if (delegate)
delegate->OnGoogleAccountsRequest(params);
}
void MaybeAddQueryParams(GURL* url) {
// Add manage=true to query parameters for sign out URLs to make sure we
// receive the Mirror response headers instead of the normal sign out page.
if (gaia::HasGaiaSchemeHostPort(*url) && url->path_piece() == kSignOutPath) {
*url = net::AppendOrReplaceQueryParameter(*url, "manage", "true");
}
}
} // namespace
SigninURLLoaderThrottle::~SigninURLLoaderThrottle() = default;
// static
std::unique_ptr<SigninURLLoaderThrottle> SigninURLLoaderThrottle::Create(
content::BrowserContext* browser_context,
content::WebContents::Getter web_contents_getter) {
if (!GetDelegate(web_contents_getter))
return nullptr;
// Use base::WrapUnique + new because of the constructor is private.
return base::WrapUnique(new SigninURLLoaderThrottle(
browser_context, std::move(web_contents_getter)));
}
void SigninURLLoaderThrottle::WillStartRequest(
network::ResourceRequest* request,
bool* defer) {
GoogleAccountsDelegate* delegate = GetDelegate(web_contents_getter_);
if (!delegate)
return;
MaybeAddQueryParams(&request->url);
request_url_ = request->url;
is_main_frame_ =
static_cast<blink::mojom::ResourceType>(request->resource_type) ==
blink::mojom::ResourceType::kMainFrame;
net::HttpRequestHeaders modified_request_headers;
std::vector<std::string> to_be_removed_request_headers;
ProcessRequest(GURL(), &request->headers, &to_be_removed_request_headers,
&modified_request_headers);
signin::RequestAdapter adapter(request_url_, request->headers,
&modified_request_headers,
&to_be_removed_request_headers);
request_headers_.CopyFrom(request->headers);
}
void SigninURLLoaderThrottle::WillRedirectRequest(
net::RedirectInfo* redirect_info,
const network::mojom::URLResponseHead& response_head,
bool* defer,
std::vector<std::string>* headers_to_remove,
net::HttpRequestHeaders* modified_headers,
net::HttpRequestHeaders* modified_cors_exempt_request_headers) {
if (!GetDelegate(web_contents_getter_))
return;
MaybeAddQueryParams(&redirect_info->new_url);
ProcessRequest(redirect_info->new_url, &request_headers_, headers_to_remove,
modified_headers);
ProcessResponse(response_head.headers.get());
request_url_ = redirect_info->new_url;
}
void SigninURLLoaderThrottle::WillProcessResponse(
const GURL& response_url,
network::mojom::URLResponseHead* response_head,
bool* defer) {
if (!GetDelegate(web_contents_getter_))
return;
ProcessResponse(response_head->headers.get());
}
SigninURLLoaderThrottle::SigninURLLoaderThrottle(
content::BrowserContext* browser_context,
content::WebContents::Getter web_contents_getter)
: browser_context_(browser_context),
web_contents_getter_(std::move(web_contents_getter)) {}
void SigninURLLoaderThrottle::ProcessRequest(
const GURL& new_url,
net::HttpRequestHeaders* original_headers,
std::vector<std::string>* headers_to_remove,
net::HttpRequestHeaders* modified_headers) {
GoogleAccountsDelegate* delegate = GetDelegate(web_contents_getter_);
if (!delegate)
return;
signin::RequestAdapter request_adapter(request_url_, *original_headers,
modified_headers, headers_to_remove);
// Disable incognito and adding accounts for now. This shouldn't matter in
// practice though since we are skipping the /SignOutOptions page completely
// with the manage=true param.
//
// TODO(crbug.com/1134042): Check whether the child account status should also
// be sent in the Mirror request header from WebLayer.
signin::AppendOrRemoveMirrorRequestHeader(
&request_adapter, new_url, delegate->GetGaiaId(),
/*is_child_account=*/signin::Tribool::kUnknown,
signin::AccountConsistencyMethod::kMirror,
CookieSettingsFactory::GetForBrowserContext(browser_context_).get(),
signin::PROFILE_MODE_INCOGNITO_DISABLED |
signin::PROFILE_MODE_ADD_ACCOUNT_DISABLED,
kWebLayerMirrorHeaderSource, /*force_account_consistency=*/true);
original_headers->MergeFrom(*modified_headers);
for (const std::string& name : *headers_to_remove)
original_headers->RemoveHeader(name);
}
void SigninURLLoaderThrottle::ProcessResponse(
const net::HttpResponseHeaders* headers) {
if (!gaia::HasGaiaSchemeHostPort(request_url_) || !is_main_frame_ ||
!headers) {
return;
}
std::string header_value;
if (!headers->GetNormalizedHeader(signin::kChromeManageAccountsHeader,
&header_value)) {
return;
}
signin::ManageAccountsParams params =
signin::BuildManageAccountsParams(header_value);
if (params.service_type == signin::GAIA_SERVICE_TYPE_NONE)
return;
// Only process one mirror header per request (multiple headers on the same
// redirect chain are ignored).
if (response_header_processed_) {
LOG(ERROR) << "Multiple X-Chrome-Manage-Accounts headers on a redirect "
<< "chain, ignoring";
return;
}
response_header_processed_ = true;
// Post a task even if we are already on the UI thread to avoid making any
// requests while processing a throttle event.
content::GetUIThreadTaskRunner({})->PostTask(
FROM_HERE,
base::BindOnce(&ProcessMirrorHeader, web_contents_getter_, params));
}
} // namespace weblayer
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/signin_url_loader_throttle.cc | C++ | unknown | 7,247 |
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef WEBLAYER_BROWSER_SIGNIN_URL_LOADER_THROTTLE_H_
#define WEBLAYER_BROWSER_SIGNIN_URL_LOADER_THROTTLE_H_
#include "base/memory/raw_ptr.h"
#include "components/signin/core/browser/signin_header_helper.h"
#include "content/public/browser/browser_context.h"
#include "content/public/browser/web_contents.h"
#include "net/http/http_request_headers.h"
#include "third_party/blink/public/common/loader/url_loader_throttle.h"
namespace net {
class HttpResponseHeaders;
}
namespace weblayer {
// Exposed for testing.
extern const char kSignOutPath[];
class SigninURLLoaderThrottle : public blink::URLLoaderThrottle {
public:
~SigninURLLoaderThrottle() override;
static std::unique_ptr<SigninURLLoaderThrottle> Create(
content::BrowserContext* browser_context,
content::WebContents::Getter web_contents_getter);
// blink::URLLoaderThrottle
void WillStartRequest(network::ResourceRequest* request,
bool* defer) override;
void WillRedirectRequest(
net::RedirectInfo* redirect_info,
const network::mojom::URLResponseHead& response_head,
bool* defer,
std::vector<std::string>* headers_to_remove,
net::HttpRequestHeaders* modified_headers,
net::HttpRequestHeaders* modified_cors_exempt_request_headers) override;
void WillProcessResponse(const GURL& response_url,
network::mojom::URLResponseHead* response_head,
bool* defer) override;
private:
SigninURLLoaderThrottle(content::BrowserContext* browser_context,
content::WebContents::Getter web_contents_getter);
void ProcessRequest(const GURL& url,
net::HttpRequestHeaders* original_headers,
std::vector<std::string>* headers_to_remove,
net::HttpRequestHeaders* modified_headers);
void ProcessResponse(const net::HttpResponseHeaders* headers);
raw_ptr<content::BrowserContext> browser_context_;
content::WebContents::Getter web_contents_getter_;
net::HttpRequestHeaders request_headers_;
GURL request_url_;
bool is_main_frame_ = false;
bool response_header_processed_ = false;
};
} // namespace weblayer
#endif // WEBLAYER_BROWSER_SIGNIN_URL_LOADER_THROTTLE_H_
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/signin_url_loader_throttle.h | C++ | unknown | 2,409 |
// Copyright 2021 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "weblayer/browser/site_engagement/site_engagement_service_factory.h"
#include "base/no_destructor.h"
#include "components/keyed_service/content/browser_context_dependency_manager.h"
using site_engagement::SiteEngagementService;
namespace weblayer {
// static
SiteEngagementService* SiteEngagementServiceFactory::GetForBrowserContext(
content::BrowserContext* browser_context) {
return static_cast<SiteEngagementService*>(
GetInstance()->GetServiceForBrowserContext(browser_context,
/*create=*/true));
}
// static
SiteEngagementServiceFactory* SiteEngagementServiceFactory::GetInstance() {
static base::NoDestructor<SiteEngagementServiceFactory> factory;
return factory.get();
}
SiteEngagementServiceFactory::SiteEngagementServiceFactory()
: BrowserContextKeyedServiceFactory(
"SiteEngagementService",
BrowserContextDependencyManager::GetInstance()) {
SiteEngagementService::SetServiceProvider(this);
}
SiteEngagementServiceFactory::~SiteEngagementServiceFactory() {
SiteEngagementService::ClearServiceProvider(this);
}
KeyedService* SiteEngagementServiceFactory::BuildServiceInstanceFor(
content::BrowserContext* browser_context) const {
return new SiteEngagementService(browser_context);
}
content::BrowserContext* SiteEngagementServiceFactory::GetBrowserContextToUse(
content::BrowserContext* context) const {
return context;
}
SiteEngagementService* SiteEngagementServiceFactory::GetSiteEngagementService(
content::BrowserContext* browser_context) {
return GetForBrowserContext(browser_context);
}
} // namespace weblayer
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/site_engagement/site_engagement_service_factory.cc | C++ | unknown | 1,801 |
// Copyright 2021 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef WEBLAYER_BROWSER_SITE_ENGAGEMENT_SITE_ENGAGEMENT_SERVICE_FACTORY_H_
#define WEBLAYER_BROWSER_SITE_ENGAGEMENT_SITE_ENGAGEMENT_SERVICE_FACTORY_H_
#include "base/no_destructor.h"
#include "components/keyed_service/content/browser_context_keyed_service_factory.h"
#include "components/site_engagement/content/site_engagement_service.h"
namespace weblayer {
// Singleton that owns all SiteEngagementServices and associates them with
// BrowserContexts.
class SiteEngagementServiceFactory
: public BrowserContextKeyedServiceFactory,
public site_engagement::SiteEngagementService::ServiceProvider {
public:
SiteEngagementServiceFactory(const SiteEngagementServiceFactory&) = delete;
SiteEngagementServiceFactory& operator=(const SiteEngagementServiceFactory&) =
delete;
// Creates the service if it doesn't already exist for the given
// |browser_context|. If the service already exists, return it.
static site_engagement::SiteEngagementService* GetForBrowserContext(
content::BrowserContext* browser_context);
static SiteEngagementServiceFactory* GetInstance();
// SiteEngagementService::ServiceProvider:
site_engagement::SiteEngagementService* GetSiteEngagementService(
content::BrowserContext* browser_context) override;
private:
friend class base::NoDestructor<SiteEngagementServiceFactory>;
SiteEngagementServiceFactory();
~SiteEngagementServiceFactory() override;
// BrowserContextKeyedServiceFactory:
KeyedService* BuildServiceInstanceFor(
content::BrowserContext* browser_context) const override;
content::BrowserContext* GetBrowserContextToUse(
content::BrowserContext* context) const override;
};
} // namespace weblayer
#endif // WEBLAYER_BROWSER_SITE_ENGAGEMENT_SITE_ENGAGEMENT_SERVICE_FACTORY_H_
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/site_engagement/site_engagement_service_factory.h | C++ | unknown | 1,937 |
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/base_switches.h"
#include "base/command_line.h"
#include "base/files/file_path.h"
#include "base/memory/raw_ptr.h"
#include "base/system/sys_info.h"
#include "base/test/scoped_feature_list.h"
#include "build/build_config.h"
#include "components/prefs/pref_service.h"
#include "components/site_isolation/features.h"
#include "components/site_isolation/pref_names.h"
#include "components/user_prefs/user_prefs.h"
#include "content/public/browser/site_isolation_policy.h"
#include "content/public/common/content_client.h"
#include "content/public/test/browser_test_utils.h"
#include "content/public/test/test_navigation_observer.h"
#include "net/dns/mock_host_resolver.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "weblayer/browser/browser_context_impl.h"
#include "weblayer/browser/browser_impl.h"
#include "weblayer/browser/content_browser_client_impl.h"
#include "weblayer/browser/profile_impl.h"
#include "weblayer/browser/tab_impl.h"
#include "weblayer/shell/browser/shell.h"
#include "weblayer/test/weblayer_browser_test.h"
#include "weblayer/test/weblayer_browser_test_utils.h"
namespace weblayer {
using testing::IsEmpty;
using testing::UnorderedElementsAre;
class SiteIsolationBrowserTest : public WebLayerBrowserTest {
public:
SiteIsolationBrowserTest() {
feature_list_.InitWithFeaturesAndParameters(
{{site_isolation::features::kSiteIsolationMemoryThresholds,
{{site_isolation::features::
kPartialSiteIsolationMemoryThresholdParamName,
"128"}}},
{site_isolation::features::kSiteIsolationForPasswordSites, {}}},
{});
}
std::vector<std::string> GetSavedIsolatedSites() {
PrefService* prefs =
user_prefs::UserPrefs::Get(GetProfile()->GetBrowserContext());
const auto& list =
prefs->GetList(site_isolation::prefs::kUserTriggeredIsolatedOrigins);
std::vector<std::string> sites;
for (const base::Value& value : list)
sites.push_back(value.GetString());
return sites;
}
// WebLayerBrowserTest:
void SetUpOnMainThread() override {
original_client_ = content::SetBrowserClientForTesting(&browser_client_);
host_resolver()->AddRule("*", "127.0.0.1");
embedded_test_server()->ServeFilesFromSourceDirectory("weblayer/test/data");
ASSERT_TRUE(embedded_test_server()->Start());
ASSERT_FALSE(
content::SiteIsolationPolicy::UseDedicatedProcessesForAllSites());
ASSERT_TRUE(
content::SiteIsolationPolicy::AreDynamicIsolatedOriginsEnabled());
}
void TearDownOnMainThread() override {
content::SetBrowserClientForTesting(original_client_);
}
void SetUpCommandLine(base::CommandLine* command_line) override {
command_line->AppendSwitch("ignore-certificate-errors");
// This way the test always sees the same amount of physical memory
// (kLowMemoryDeviceThresholdMB = 512MB), regardless of how much memory is
// available in the testing environment.
base::CommandLine::ForCurrentProcess()->AppendSwitch(
switches::kEnableLowEndDeviceMode);
EXPECT_EQ(512, base::SysInfo::AmountOfPhysicalMemoryMB());
}
content::WebContents* GetWebContents() {
return static_cast<TabImpl*>(shell()->tab())->web_contents();
}
void StartIsolatingSite(const GURL& url) {
content::SiteInstance::StartIsolatingSite(
GetProfile()->GetBrowserContext(), url,
content::ChildProcessSecurityPolicy::IsolatedOriginSource::
USER_TRIGGERED);
}
private:
// A browser client which forces off strict site isolation, so the test can
// assume password isolation is enabled.
class SiteIsolationContentBrowserClient : public ContentBrowserClientImpl {
public:
SiteIsolationContentBrowserClient() : ContentBrowserClientImpl(nullptr) {}
bool ShouldEnableStrictSiteIsolation() override { return false; }
};
SiteIsolationContentBrowserClient browser_client_;
raw_ptr<content::ContentBrowserClient> original_client_ = nullptr;
base::test::ScopedFeatureList feature_list_;
};
IN_PROC_BROWSER_TEST_F(SiteIsolationBrowserTest,
SiteIsIsolatedAfterEnteringPassword) {
GURL url = embedded_test_server()->GetURL("sub.foo.com",
"/simple_password_form.html");
NavigateAndWaitForCompletion(url, shell());
content::WebContents* contents = GetWebContents();
// foo.com should not be isolated to start with. Verify that a cross-site
// iframe does not become an OOPIF.
EXPECT_FALSE(contents->GetPrimaryMainFrame()
->GetSiteInstance()
->RequiresDedicatedProcess());
std::string kAppendIframe = R"(
var i = document.createElement('iframe');
i.id = 'child';
document.body.appendChild(i);)";
EXPECT_TRUE(content::ExecJs(contents, kAppendIframe));
GURL bar_url(embedded_test_server()->GetURL("bar.com", "/simple_page.html"));
EXPECT_TRUE(NavigateIframeToURL(contents, "child", bar_url));
content::RenderFrameHost* child =
ChildFrameAt(contents->GetPrimaryMainFrame(), 0);
EXPECT_FALSE(child->IsCrossProcessSubframe());
// Fill a form and submit through a <input type="submit"> button.
content::TestNavigationObserver observer(contents);
std::string kFillAndSubmit =
"document.getElementById('username_field').value = 'temp';"
"document.getElementById('password_field').value = 'random';"
"document.getElementById('input_submit_button').click()";
EXPECT_TRUE(content::ExecJs(contents, kFillAndSubmit));
observer.Wait();
// Since there were no script references from other windows, we should've
// swapped BrowsingInstances and put the result of the form submission into a
// dedicated process, locked to foo.com. Check that a cross-site iframe now
// becomes an OOPIF.
EXPECT_TRUE(contents->GetPrimaryMainFrame()
->GetSiteInstance()
->RequiresDedicatedProcess());
EXPECT_TRUE(ExecJs(contents, kAppendIframe));
EXPECT_TRUE(NavigateIframeToURL(contents, "child", bar_url));
child = ChildFrameAt(contents->GetPrimaryMainFrame(), 0);
EXPECT_TRUE(child->IsCrossProcessSubframe());
}
// TODO(crbug.com/654704): Android does not support PRE_ tests.
#if !BUILDFLAG(IS_ANDROID)
IN_PROC_BROWSER_TEST_F(SiteIsolationBrowserTest,
PRE_IsolatedSitesPersistAcrossRestarts) {
// There shouldn't be any saved isolated origins to start with.
EXPECT_THAT(GetSavedIsolatedSites(), IsEmpty());
// Isolate saved.com and saved2.com persistently.
GURL saved_url =
embedded_test_server()->GetURL("saved.com", "/simple_page.html");
StartIsolatingSite(saved_url);
GURL saved2_url =
embedded_test_server()->GetURL("saved2.com", "/simple_page.html");
StartIsolatingSite(saved2_url);
NavigateAndWaitForCompletion(saved_url, shell());
EXPECT_TRUE(GetWebContents()
->GetPrimaryMainFrame()
->GetSiteInstance()
->RequiresDedicatedProcess());
// Check that saved.com and saved2.com were saved to disk.
EXPECT_THAT(GetSavedIsolatedSites(),
UnorderedElementsAre("http://saved.com", "http://saved2.com"));
}
IN_PROC_BROWSER_TEST_F(SiteIsolationBrowserTest,
IsolatedSitesPersistAcrossRestarts) {
// Check that saved.com and saved2.com are still saved to disk.
EXPECT_THAT(GetSavedIsolatedSites(),
UnorderedElementsAre("http://saved.com", "http://saved2.com"));
// Check that these sites utilize a dedicated process after restarting, but a
// non-isolated foo.com URL does not.
GURL saved_url =
embedded_test_server()->GetURL("saved.com", "/simple_page.html");
GURL saved2_url =
embedded_test_server()->GetURL("saved2.com", "/simple_page2.html");
GURL foo_url =
embedded_test_server()->GetURL("foo.com", "/simple_page3.html");
NavigateAndWaitForCompletion(saved_url, shell());
content::WebContents* contents = GetWebContents();
EXPECT_TRUE(contents->GetPrimaryMainFrame()
->GetSiteInstance()
->RequiresDedicatedProcess());
NavigateAndWaitForCompletion(saved2_url, shell());
EXPECT_TRUE(contents->GetPrimaryMainFrame()
->GetSiteInstance()
->RequiresDedicatedProcess());
NavigateAndWaitForCompletion(foo_url, shell());
EXPECT_FALSE(contents->GetPrimaryMainFrame()
->GetSiteInstance()
->RequiresDedicatedProcess());
}
#endif
IN_PROC_BROWSER_TEST_F(SiteIsolationBrowserTest, IsolatedSiteIsSavedOnlyOnce) {
GURL saved_url =
embedded_test_server()->GetURL("saved.com", "/simple_page.html");
StartIsolatingSite(saved_url);
StartIsolatingSite(saved_url);
StartIsolatingSite(saved_url);
EXPECT_THAT(GetSavedIsolatedSites(),
UnorderedElementsAre("http://saved.com"));
}
// Failing on Android, see https://crbug.com/1254509.
#if defined(ANDROID)
#define MAYBE_ClearSiteDataHeaderDoesNotClearSavedIsolatedSites \
ClearSiteDataHeaderDoesNotClearSavedIsolatedSites
#else
#define MAYBE_ClearSiteDataHeaderDoesNotClearSavedIsolatedSites \
ClearSiteDataHeaderDoesNotClearSavedIsolatedSites
#endif
// Verify that serving a Clear-Site-Data header does not clear saved isolated
// sites. Saved isolated sites should only be cleared by user-initiated actions.
IN_PROC_BROWSER_TEST_F(
SiteIsolationBrowserTest,
MAYBE_ClearSiteDataHeaderDoesNotClearSavedIsolatedSites) {
// Start an HTTPS server, as Clear-Site-Data is only available on HTTPS URLs.
net::EmbeddedTestServer https_server(net::EmbeddedTestServer::TYPE_HTTPS);
https_server.AddDefaultHandlers(
base::FilePath(FILE_PATH_LITERAL("weblayer/test/data")));
ASSERT_TRUE(https_server.Start());
// Isolate saved.com and verify it's been saved to disk.
GURL saved_url = https_server.GetURL("saved.com", "/clear_site_data.html");
StartIsolatingSite(saved_url);
EXPECT_THAT(GetSavedIsolatedSites(),
UnorderedElementsAre("https://saved.com"));
// Navigate to a URL that serves a Clear-Site-Data header for cache, cookies,
// and DOM storage. This is the most that a Clear-Site-Data header could
// clear, and this should not clear saved isolated sites.
NavigateAndWaitForCompletion(saved_url, shell());
EXPECT_THAT(GetSavedIsolatedSites(),
UnorderedElementsAre("https://saved.com"));
}
IN_PROC_BROWSER_TEST_F(SiteIsolationBrowserTest,
ExplicitClearBrowsingDataClearsSavedIsolatedSites) {
GURL saved_url =
embedded_test_server()->GetURL("saved.com", "/simple_page.html");
StartIsolatingSite(saved_url);
EXPECT_THAT(GetSavedIsolatedSites(),
UnorderedElementsAre("http://saved.com"));
base::RunLoop run_loop;
base::Time now = base::Time::Now();
GetProfile()->ClearBrowsingData({BrowsingDataType::COOKIES_AND_SITE_DATA},
now - base::Days(1), now,
run_loop.QuitClosure());
run_loop.Run();
EXPECT_THAT(GetSavedIsolatedSites(), IsEmpty());
}
} // namespace weblayer
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/site_isolation_browsertest.cc | C++ | unknown | 11,239 |
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "components/site_isolation/site_isolation_policy.h"
#include "base/base_switches.h"
#include "base/command_line.h"
#include "base/system/sys_info.h"
#include "base/test/scoped_feature_list.h"
#include "build/build_config.h"
#include "components/site_isolation/features.h"
#include "components/site_isolation/preloaded_isolated_origins.h"
#include "content/public/browser/child_process_security_policy.h"
#include "content/public/browser/site_isolation_policy.h"
#include "content/public/common/content_features.h"
#include "content/public/common/content_switches.h"
#include "content/public/test/browser_task_environment.h"
#include "content/public/test/test_utils.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace weblayer {
namespace {
using testing::UnorderedElementsAreArray;
// Some command-line switches override field trials - the tests need to be
// skipped in this case.
bool ShouldSkipBecauseOfConflictingCommandLineSwitches() {
if (base::CommandLine::ForCurrentProcess()->HasSwitch(
switches::kSitePerProcess))
return true;
if (base::CommandLine::ForCurrentProcess()->HasSwitch(
switches::kDisableSiteIsolation))
return true;
return false;
}
} // namespace
class SiteIsolationPolicyTest : public testing::Test {
public:
SiteIsolationPolicyTest() = default;
SiteIsolationPolicyTest(const SiteIsolationPolicyTest&) = delete;
SiteIsolationPolicyTest& operator=(const SiteIsolationPolicyTest&) = delete;
void SetUp() override {
// This way the test always sees the same amount of physical memory
// (kLowMemoryDeviceThresholdMB = 512MB), regardless of how much memory is
// available in the testing environment.
base::CommandLine::ForCurrentProcess()->AppendSwitch(
switches::kEnableLowEndDeviceMode);
EXPECT_EQ(512, base::SysInfo::AmountOfPhysicalMemoryMB());
}
// Sets the same memory threshold for both strict site isolation and partial
// site isolation modes, since these tests care about both. For example,
// UseDedicatedProcessesForAllSites() depends on the former, while preloaded
// isolated origins use the latter.
void SetMemoryThreshold(const std::string& threshold) {
threshold_feature_.InitAndEnableFeatureWithParameters(
site_isolation::features::kSiteIsolationMemoryThresholds,
{{site_isolation::features::
kStrictSiteIsolationMemoryThresholdParamName,
threshold},
{site_isolation::features::
kPartialSiteIsolationMemoryThresholdParamName,
threshold}});
}
private:
content::BrowserTaskEnvironment task_environment_;
base::test::ScopedFeatureList threshold_feature_;
};
TEST_F(SiteIsolationPolicyTest, NoIsolationBelowMemoryThreshold) {
if (ShouldSkipBecauseOfConflictingCommandLineSwitches())
return;
SetMemoryThreshold("768");
EXPECT_FALSE(
content::SiteIsolationPolicy::UseDedicatedProcessesForAllSites());
EXPECT_FALSE(
content::SiteIsolationPolicy::ArePreloadedIsolatedOriginsEnabled());
}
TEST_F(SiteIsolationPolicyTest, IsolationAboveMemoryThreshold) {
if (ShouldSkipBecauseOfConflictingCommandLineSwitches())
return;
SetMemoryThreshold("128");
// Android should only use the preloaded origin list, while desktop should
// isolate all sites.
#if BUILDFLAG(IS_ANDROID)
EXPECT_FALSE(
content::SiteIsolationPolicy::UseDedicatedProcessesForAllSites());
EXPECT_TRUE(
content::SiteIsolationPolicy::ArePreloadedIsolatedOriginsEnabled());
#else
EXPECT_TRUE(content::SiteIsolationPolicy::UseDedicatedProcessesForAllSites());
EXPECT_FALSE(
content::SiteIsolationPolicy::ArePreloadedIsolatedOriginsEnabled());
#endif
}
TEST_F(SiteIsolationPolicyTest, IsolatedOriginsContainPreloadedOrigins) {
if (ShouldSkipBecauseOfConflictingCommandLineSwitches())
return;
content::SiteIsolationPolicy::ApplyGlobalIsolatedOrigins();
std::vector<url::Origin> expected_embedder_origins =
site_isolation::GetBrowserSpecificBuiltInIsolatedOrigins();
auto* cpsp = content::ChildProcessSecurityPolicy::GetInstance();
std::vector<url::Origin> isolated_origins = cpsp->GetIsolatedOrigins();
EXPECT_THAT(expected_embedder_origins,
UnorderedElementsAreArray(isolated_origins));
}
} // namespace weblayer
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/site_isolation_policy_unittest.cc | C++ | unknown | 4,493 |
// Copyright 2019 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "weblayer/test/weblayer_browser_test.h"
#include "base/files/file_path.h"
#include "base/scoped_observation.h"
#include "base/test/scoped_feature_list.h"
#include "build/build_config.h"
#include "components/network_time/network_time_tracker.h"
#include "components/security_interstitials/content/insecure_form_blocking_page.h"
#include "components/security_interstitials/content/ssl_error_assistant.h"
#include "components/security_interstitials/content/ssl_error_handler.h"
#include "net/ssl/ssl_info.h"
#include "net/test/embedded_test_server/embedded_test_server.h"
#include "third_party/abseil-cpp/absl/types/optional.h"
#include "weblayer/browser/browser_process.h"
#include "weblayer/browser/weblayer_security_blocking_page_factory.h"
#include "weblayer/public/browser.h"
#include "weblayer/public/browser_observer.h"
#include "weblayer/public/error_page.h"
#include "weblayer/public/error_page_delegate.h"
#include "weblayer/public/new_tab_delegate.h"
#include "weblayer/public/tab.h"
#include "weblayer/shell/browser/shell.h"
#include "weblayer/test/interstitial_utils.h"
#include "weblayer/test/load_completion_observer.h"
#include "weblayer/test/test_navigation_observer.h"
#include "weblayer/test/weblayer_browser_test_utils.h"
namespace weblayer {
namespace {
#if BUILDFLAG(IS_ANDROID)
// Waits for a new tab to be created, and then load |url|.
class NewTabWaiter : public NewTabDelegate {
public:
explicit NewTabWaiter(const GURL& url) : url_(url) {}
void OnNewTab(Tab* new_tab, NewTabType type) override {
navigation_observer_ = std::make_unique<TestNavigationObserver>(
url_, TestNavigationObserver::NavigationEvent::kStart, new_tab);
run_loop_.Quit();
}
void Wait() {
if (!navigation_observer_)
run_loop_.Run();
navigation_observer_->Wait();
}
private:
GURL url_;
std::unique_ptr<TestNavigationObserver> navigation_observer_;
base::RunLoop run_loop_;
};
#endif
class TestErrorPageDelegate : public ErrorPageDelegate {
public:
bool was_get_error_page_content_called() const {
return was_get_error_page_content_called_;
}
// ErrorPageDelegate:
bool OnBackToSafety() override { return false; }
std::unique_ptr<ErrorPage> GetErrorPageContent(
Navigation* navigation) override {
was_get_error_page_content_called_ = true;
return std::make_unique<ErrorPage>();
}
private:
bool was_get_error_page_content_called_ = false;
};
} // namespace
class SSLBrowserTest : public WebLayerBrowserTest {
public:
SSLBrowserTest() = default;
SSLBrowserTest(const SSLBrowserTest&) = delete;
SSLBrowserTest& operator=(const SSLBrowserTest&) = delete;
~SSLBrowserTest() override = default;
// WebLayerBrowserTest:
void SetUpOnMainThread() override {
https_server_ = std::make_unique<net::EmbeddedTestServer>(
net::EmbeddedTestServer::TYPE_HTTPS);
https_server_->AddDefaultHandlers(
base::FilePath(FILE_PATH_LITERAL("weblayer/test/data")));
https_server_mismatched_ = std::make_unique<net::EmbeddedTestServer>(
net::EmbeddedTestServer::TYPE_HTTPS);
https_server_mismatched_->SetSSLConfig(
net::EmbeddedTestServer::CERT_MISMATCHED_NAME);
https_server_mismatched_->AddDefaultHandlers(
base::FilePath(FILE_PATH_LITERAL("weblayer/test/data")));
https_server_expired_ = std::make_unique<net::EmbeddedTestServer>(
net::EmbeddedTestServer::TYPE_HTTPS);
https_server_expired_->SetSSLConfig(net::EmbeddedTestServer::CERT_EXPIRED);
https_server_expired_->AddDefaultHandlers(
base::FilePath(FILE_PATH_LITERAL("weblayer/test/data")));
ASSERT_TRUE(https_server_->Start());
ASSERT_TRUE(https_server_mismatched_->Start());
ASSERT_TRUE(https_server_expired_->Start());
}
void PostRunTestOnMainThread() override {
https_server_.reset();
https_server_mismatched_.reset();
WebLayerBrowserTest::PostRunTestOnMainThread();
}
void NavigateToOkPage() {
ASSERT_EQ("127.0.0.1", ok_url().host());
NavigateAndWaitForCompletion(ok_url(), shell());
EXPECT_FALSE(IsShowingSecurityInterstitial(shell()->tab()));
}
void NavigateToPageWithMismatchedCertExpectSSLInterstitial() {
// Do a navigation that should result in an SSL error.
NavigateAndWaitForFailure(mismatched_cert_url(), shell());
// First check that there *is* an interstitial.
ASSERT_TRUE(IsShowingSecurityInterstitial(shell()->tab()));
// Now verify that the interstitial is in fact an SSL interstitial.
EXPECT_TRUE(IsShowingSSLInterstitial(shell()->tab()));
// TODO(blundell): Check the security state once security state is available
// via the public WebLayer API, following the example of //chrome's
// ssl_browsertest.cc's CheckAuthenticationBrokenState() function.
}
void NavigateToPageWithMismatchedCertExpectCaptivePortalInterstitial() {
// Do a navigation that should result in an SSL error.
NavigateAndWaitForFailure(mismatched_cert_url(), shell());
// First check that there *is* an interstitial.
ASSERT_TRUE(IsShowingSecurityInterstitial(shell()->tab()));
// Now verify that the interstitial is in fact a captive portal
// interstitial.
EXPECT_TRUE(IsShowingCaptivePortalInterstitial(shell()->tab()));
// TODO(blundell): Check the security state once security state is available
// via the public WebLayer API, following the example of //chrome's
// ssl_browsertest.cc's CheckAuthenticationBrokenState() function.
}
void NavigateToPageWithExpiredCertExpectSSLInterstitial() {
// Do a navigation that should result in an SSL error.
NavigateAndWaitForFailure(expired_cert_url(), shell());
// First check that there *is* an interstitial.
ASSERT_TRUE(IsShowingSecurityInterstitial(shell()->tab()));
// Now verify that the interstitial is in fact an SSL interstitial.
EXPECT_TRUE(IsShowingSSLInterstitial(shell()->tab()));
// TODO(blundell): Check the security state once security state is available
// via the public WebLayer API, following the example of //chrome's
// ssl_browsertest.cc's CheckAuthenticationBrokenState() function.
}
void NavigateToPageWithExpiredCertExpectBadClockInterstitial() {
// Do a navigation that should result in an SSL error.
NavigateAndWaitForFailure(expired_cert_url(), shell());
// First check that there *is* an interstitial.
ASSERT_TRUE(IsShowingSecurityInterstitial(shell()->tab()));
// Now verify that the interstitial is in fact a bad clock interstitial.
EXPECT_TRUE(IsShowingBadClockInterstitial(shell()->tab()));
// TODO(blundell): Check the security state once security state is available
// via the public WebLayer API, following the example of //chrome's
// ssl_browsertest.cc's CheckAuthenticationBrokenState() function.
}
void NavigateToPageWithMismatchedCertExpectNotBlocked() {
NavigateAndWaitForCompletion(mismatched_cert_url(), shell());
EXPECT_FALSE(IsShowingSecurityInterstitial(shell()->tab()));
// TODO(blundell): Check the security state once security state is available
// via the public WebLayer API, following the example of //chrome's
// ssl_browsertest.cc's CheckAuthenticationBrokenState() function.
}
void SendInterstitialNavigationCommandAndWait(
bool proceed,
absl::optional<GURL> previous_url = absl::nullopt) {
GURL expected_url =
proceed ? mismatched_cert_url() : previous_url.value_or(ok_url());
ASSERT_TRUE(IsShowingSSLInterstitial(shell()->tab()));
TestNavigationObserver navigation_observer(
expected_url, TestNavigationObserver::NavigationEvent::kCompletion,
shell());
ExecuteScript(shell(),
"window.certificateErrorPageController." +
std::string(proceed ? "proceed" : "dontProceed") + "();",
false /*use_separate_isolate*/);
navigation_observer.Wait();
EXPECT_FALSE(IsShowingSSLInterstitial(shell()->tab()));
}
void SendInterstitialReloadCommandAndWait() {
ASSERT_TRUE(IsShowingSSLInterstitial(shell()->tab()));
LoadCompletionObserver load_observer(shell());
ExecuteScript(shell(), "window.certificateErrorPageController.reload();",
false /*use_separate_isolate*/);
load_observer.Wait();
// Should still be showing the SSL interstitial after the reload command is
// processed.
EXPECT_TRUE(IsShowingSSLInterstitial(shell()->tab()));
}
#if BUILDFLAG(IS_ANDROID)
void SendInterstitialOpenLoginCommandAndWait() {
ASSERT_TRUE(IsShowingCaptivePortalInterstitial(shell()->tab()));
// Note: The embedded test server cannot actually load the captive portal
// login URL, so simply detect the start of the navigation to the page.
NewTabWaiter waiter(WebLayerSecurityBlockingPageFactory::
GetCaptivePortalLoginPageUrlForTesting());
shell()->tab()->SetNewTabDelegate(&waiter);
ExecuteScript(shell(), "window.certificateErrorPageController.openLogin();",
false /*use_separate_isolate*/);
waiter.Wait();
}
#endif
void NavigateToOtherOkPage() {
NavigateAndWaitForCompletion(https_server_->GetURL("/simple_page2.html"),
shell());
EXPECT_FALSE(IsShowingSecurityInterstitial(shell()->tab()));
}
GURL ok_url() { return https_server_->GetURL("/simple_page.html"); }
GURL mismatched_cert_url() {
return https_server_mismatched_->GetURL("/simple_page.html");
}
GURL expired_cert_url() {
return https_server_expired_->GetURL("/simple_page.html");
}
protected:
std::unique_ptr<net::EmbeddedTestServer> https_server_;
std::unique_ptr<net::EmbeddedTestServer> https_server_mismatched_;
std::unique_ptr<net::EmbeddedTestServer> https_server_expired_;
};
// Tests clicking "take me back" on the interstitial page.
IN_PROC_BROWSER_TEST_F(SSLBrowserTest, TakeMeBack) {
NavigateToOkPage();
NavigateToPageWithMismatchedCertExpectSSLInterstitial();
// Click "Take me back".
SendInterstitialNavigationCommandAndWait(false /*proceed*/);
// Check that it's possible to navigate to a new page.
NavigateToOtherOkPage();
// Navigate to the bad SSL page again, an interstitial shows again (in
// contrast to what would happen had the user chosen to proceed).
NavigateToPageWithMismatchedCertExpectSSLInterstitial();
}
// Tests clicking "take me back" on the interstitial page when there's no
// navigation history. The user should be taken to a safe page (about:blank).
IN_PROC_BROWSER_TEST_F(SSLBrowserTest, TakeMeBackEmptyNavigationHistory) {
NavigateToPageWithMismatchedCertExpectSSLInterstitial();
// Click "Take me back".
SendInterstitialNavigationCommandAndWait(false /*proceed*/,
GURL("about:blank"));
}
IN_PROC_BROWSER_TEST_F(SSLBrowserTest, Reload) {
NavigateToOkPage();
NavigateToPageWithMismatchedCertExpectSSLInterstitial();
SendInterstitialReloadCommandAndWait();
// TODO(blundell): Ideally we would fix the SSL error, reload, and verify
// that the SSL interstitial isn't showing. However, currently this doesn't
// work: Calling ResetSSLConfig() on |http_server_mismatched_| passing
// CERT_OK does not cause future reloads or navigations to
// mismatched_cert_url() to succeed; they still fail and pop an interstitial.
// I verified that the LoadCompletionObserver is in fact waiting for a new
// load, i.e., there is actually a *new* SSL interstitial popped up. From
// looking at the ResetSSLConfig() impl there shouldn't be any waiting or
// anything needed within the client.
}
// Tests clicking proceed link on the interstitial page. This is a PRE_ test
// because it also acts as setup for the test below which verifies the behavior
// across restarts.
// TODO(crbug.com/654704): Android does not support PRE_ tests. For Android just
// run only the PRE_ version of this test.
#if BUILDFLAG(IS_ANDROID)
#define PRE_Proceed Proceed
#endif
IN_PROC_BROWSER_TEST_F(SSLBrowserTest, PRE_Proceed) {
NavigateToOkPage();
NavigateToPageWithMismatchedCertExpectSSLInterstitial();
SendInterstitialNavigationCommandAndWait(true /*proceed*/);
// Go back to an OK page, then try to navigate again. The "Proceed" decision
// should be saved, so no interstitial is shown this time.
NavigateToOkPage();
NavigateToPageWithMismatchedCertExpectNotBlocked();
}
#if !BUILDFLAG(IS_ANDROID)
// The proceed decision is perpetuated across WebLayer sessions, i.e. WebLayer
// will not block again when navigating to the same bad page that was previously
// proceeded through.
IN_PROC_BROWSER_TEST_F(SSLBrowserTest, Proceed) {
NavigateToPageWithMismatchedCertExpectNotBlocked();
}
#endif
// Tests navigating away from the interstitial page.
IN_PROC_BROWSER_TEST_F(SSLBrowserTest, NavigateAway) {
NavigateToOkPage();
NavigateToPageWithMismatchedCertExpectSSLInterstitial();
NavigateToOtherOkPage();
}
// Tests the scenario where the OS reports that an SSL error is due to a
// captive portal. A captive portal interstitial should be displayed. The test
// then switches OS captive portal status to false and reloads the page. This
// time, a normal SSL interstitial should be displayed.
IN_PROC_BROWSER_TEST_F(SSLBrowserTest, OSReportsCaptivePortal) {
SSLErrorHandler::SetOSReportsCaptivePortalForTesting(true);
NavigateToPageWithMismatchedCertExpectCaptivePortalInterstitial();
// Check that clearing the test setting causes behavior to revert to normal.
SSLErrorHandler::SetOSReportsCaptivePortalForTesting(false);
NavigateToPageWithMismatchedCertExpectSSLInterstitial();
}
#if BUILDFLAG(IS_ANDROID)
// Tests that after reaching a captive portal interstitial, clicking on the
// connect link will cause a navigation to the login page.
IN_PROC_BROWSER_TEST_F(SSLBrowserTest, CaptivePortalConnectToLoginPage) {
SSLErrorHandler::SetOSReportsCaptivePortalForTesting(true);
NavigateToPageWithMismatchedCertExpectCaptivePortalInterstitial();
SendInterstitialOpenLoginCommandAndWait();
}
#endif
IN_PROC_BROWSER_TEST_F(SSLBrowserTest, BadClockInterstitial) {
// Without the NetworkTimeTracker reporting that the clock is ahead or
// behind, navigating to a page with an expired cert should result in the
// default SSL interstitial appearing.
NavigateToPageWithExpiredCertExpectSSLInterstitial();
// Set network time back ten minutes.
BrowserProcess::GetInstance()->GetNetworkTimeTracker()->UpdateNetworkTime(
base::Time::Now() - base::Minutes(10),
base::Milliseconds(1), /* resolution */
base::Milliseconds(500), /* latency */
base::TimeTicks::Now() /* posting time of this update */);
// Now navigating to a page with an expired cert should cause the bad clock
// interstitial to appear.
NavigateToPageWithExpiredCertExpectBadClockInterstitial();
}
// This test verifies that a certificate in the list of known captive portal
// certificates in ssl_error_assistant.asciipb is detected as such. This serves
// to verify that the ssl_error_assistant proto was correctly loaded.
IN_PROC_BROWSER_TEST_F(SSLBrowserTest,
CertificateInKnownCaptivePortalsListDetected) {
net::SSLInfo ssl_info_with_known_captive_portal_cert;
net::HashValue captive_portal_public_key;
// Set up the SSSLInfo with the certificate of captive-portal.badssl.com
// (taken from ssl_error_assistant.asciipb).
ASSERT_TRUE(captive_portal_public_key.FromString(
"sha256/fjZPHewEHTrMDX3I1ecEIeoy3WFxHyGplOLv28kIbtI="));
net::HashValueVector public_keys;
public_keys.push_back(captive_portal_public_key);
ssl_info_with_known_captive_portal_cert.public_key_hashes = public_keys;
EXPECT_TRUE(SSLErrorAssistant().IsKnownCaptivePortalCertificate(
ssl_info_with_known_captive_portal_cert));
}
// Verifies an error page is not requested for an ssl error.
IN_PROC_BROWSER_TEST_F(SSLBrowserTest, ErrorPageNotCalledForMismatch) {
TestErrorPageDelegate error_page_delegate;
shell()->tab()->SetErrorPageDelegate(&error_page_delegate);
NavigateToOkPage();
EXPECT_FALSE(error_page_delegate.was_get_error_page_content_called());
NavigateToPageWithMismatchedCertExpectSSLInterstitial();
EXPECT_FALSE(error_page_delegate.was_get_error_page_content_called());
}
// Visits a page that displays an insecure form, submits the form, and checks an
// interstitial is shown.
IN_PROC_BROWSER_TEST_F(SSLBrowserTest,
TestDisplaysInsecureFormSubmissionWarning) {
GURL insecure_form_url = https_server_->GetURL("/insecure_form.html");
GURL form_target_url = GURL("http://does-not-exist.test/form_target.html?");
NavigateAndWaitForCompletion(insecure_form_url, shell());
// Submit the form and wait for the interstitial to load.
TestNavigationObserver navigation_observer(
form_target_url, TestNavigationObserver::NavigationEvent::kFailure,
shell());
ExecuteScript(shell(), "submitForm();", false /*use_separate_isolate*/);
navigation_observer.Wait();
// Check the correct interstitial loaded.
EXPECT_TRUE(IsShowingInsecureFormInterstitial(shell()->tab()));
}
} // namespace weblayer
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/ssl_browsertest.cc | C++ | unknown | 17,328 |