From 78e0ae42932363c468cf59b4f752b42fa335cfa3 Mon Sep 17 00:00:00 2001 From: bridiver Date: Fri, 26 Jul 2019 10:54:00 -0700 Subject: [PATCH 1/6] consolidate shields logic fix https://github.com/brave/brave-browser/issues/5416 --- browser/extensions/api/brave_shields_api.cc | 407 +++--- browser/extensions/api/brave_shields_api.h | 128 +- .../api/brave_shields_api_browsertest.cc | 232 +--- .../default_brave_shields_page.js | 4 +- browser/ui/BUILD.gn | 1 + .../settings/default_brave_shields_handler.cc | 134 +- common/extensions/api/brave_shields.json | 325 +++-- .../extension/brave_extension/background.ts | 6 +- .../background/api/shieldsAPI.ts | 137 +- .../constants/resourceIdentifiers.ts | 11 - .../brave_extension/helpers/urlUtils.ts | 6 - .../types/constants/resourceIdentifiers.ts | 15 - .../browser/brave_shields_util.cc | 273 +++- .../browser/brave_shields_util.h | 34 + .../browser/brave_shields_util_unittest.cc | 1197 +++++++++++++++++ components/definitions/chromel.d.ts | 14 +- .../background/api/shieldsAPI_test.ts | 286 +--- .../brave_extension/helpers/urlUtils_test.ts | 12 - components/test/testData.ts | 52 +- test/BUILD.gn | 1 + 20 files changed, 2236 insertions(+), 1039 deletions(-) delete mode 100644 components/brave_extension/extension/brave_extension/constants/resourceIdentifiers.ts delete mode 100644 components/brave_extension/extension/brave_extension/types/constants/resourceIdentifiers.ts create mode 100644 components/brave_shields/browser/brave_shields_util_unittest.cc diff --git a/browser/extensions/api/brave_shields_api.cc b/browser/extensions/api/brave_shields_api.cc index 91f6345d9d4..4b06be89fa7 100644 --- a/browser/extensions/api/brave_shields_api.cc +++ b/browser/extensions/api/brave_shields_api.cc @@ -12,52 +12,29 @@ #include "base/strings/string_number_conversions.h" #include "brave/common/extensions/api/brave_shields.h" #include "brave/common/extensions/extension_constants.h" +#include "brave/components/brave_shields/browser/brave_shields_util.h" #include "brave/components/brave_shields/browser/brave_shields_web_contents_observer.h" -#include "chrome/browser/content_settings/host_content_settings_map_factory.h" -#include "chrome/browser/extensions/api/content_settings/content_settings_api_constants.h" -#include "chrome/browser/extensions/api/content_settings/content_settings_helpers.h" -#include "chrome/browser/extensions/api/content_settings/content_settings_service.h" -#include "chrome/browser/extensions/api/content_settings/content_settings_store.h" -#include "chrome/browser/extensions/api/preference/preference_api_constants.h" #include "chrome/browser/extensions/api/tabs/tabs_constants.h" #include "chrome/browser/extensions/extension_tab_util.h" #include "chrome/browser/profiles/profile.h" -#include "components/content_settings/core/browser/content_settings_registry.h" -#include "components/content_settings/core/browser/content_settings_utils.h" -#include "components/content_settings/core/browser/host_content_settings_map.h" #include "content/public/browser/web_contents.h" #include "extensions/browser/extension_util.h" using brave_shields::BraveShieldsWebContentsObserver; +using brave_shields::ControlType; +using brave_shields::ControlTypeFromString; +using brave_shields::ControlTypeToString; -namespace Get = extensions::api::brave_shields::ContentSetting::Get; -namespace Set = extensions::api::brave_shields::ContentSetting::Set; -namespace pref_keys = extensions::preference_api_constants; +namespace extensions { +namespace api { namespace { -bool RemoveContentType(base::ListValue* args, - ContentSettingsType* content_type) { - std::string content_type_str; - if (!args->GetString(0, &content_type_str)) - return false; - // We remove the ContentSettingsType parameter since this is added by the - // renderer, and is not part of the JSON schema. - args->Remove(0, nullptr); - *content_type = - extensions::content_settings_helpers::StringToContentSettingsType( - content_type_str); - return *content_type != CONTENT_SETTINGS_TYPE_DEFAULT; -} +const char kInvalidUrlError[] = "Invalid URL."; +const char kInvalidControlTypeError[] = "Invalid ControlType."; } // namespace -namespace extensions { -namespace api { - -BraveShieldsAllowScriptsOnceFunction::~BraveShieldsAllowScriptsOnceFunction() { -} - ExtensionFunction::ResponseAction BraveShieldsAllowScriptsOnceFunction::Run() { std::unique_ptr params( brave_shields::AllowScriptsOnce::Params::Create(*args_)); @@ -66,201 +43,267 @@ ExtensionFunction::ResponseAction BraveShieldsAllowScriptsOnceFunction::Run() { // Get web contents for this tab content::WebContents* contents = nullptr; if (!ExtensionTabUtil::GetTabById( - params->tab_id, - Profile::FromBrowserContext(browser_context()), - include_incognito_information(), - nullptr, - nullptr, - &contents, - nullptr)) { + params->tab_id, Profile::FromBrowserContext(browser_context()), + include_incognito_information(), nullptr, nullptr, &contents, + nullptr)) { return RespondNow(Error(tabs_constants::kTabNotFoundError, base::NumberToString(params->tab_id))); } - BraveShieldsWebContentsObserver::FromWebContents( - contents)->AllowScriptsOnce(params->origins, contents); + BraveShieldsWebContentsObserver::FromWebContents(contents)->AllowScriptsOnce( + params->origins, contents); return RespondNow(NoArguments()); } ExtensionFunction::ResponseAction -BraveShieldsContentSettingGetFunction::Run() { - ContentSettingsType content_type; - EXTENSION_FUNCTION_VALIDATE(RemoveContentType(args_.get(), &content_type)); +BraveShieldsSetBraveShieldsControlTypeFunction::Run() { + std::unique_ptr params( + brave_shields::SetBraveShieldsControlType::Params::Create(*args_)); + EXTENSION_FUNCTION_VALIDATE(params.get()); + + const GURL url(params->url); + // we don't allow setting defaults from the extension + if (url.is_empty() || !url.is_valid()) { + return RespondNow(Error(kInvalidUrlError, params->url)); + } + + auto control_type = ControlTypeFromString(params->control_type); + if (control_type == ControlType::INVALID) { + return RespondNow(Error(kInvalidControlTypeError, params->control_type)); + } + + Profile* profile = Profile::FromBrowserContext(browser_context()); + ::brave_shields::SetBraveShieldsControlType(profile, control_type, url); + + return RespondNow(NoArguments()); +} + +ExtensionFunction::ResponseAction +BraveShieldsGetBraveShieldsControlTypeFunction::Run() { + std::unique_ptr params( + brave_shields::GetBraveShieldsControlType::Params::Create(*args_)); + EXTENSION_FUNCTION_VALIDATE(params.get()); + + const GURL url(params->url); + // we don't allow getting defaults from the extension + if (url.is_empty() || !url.is_valid()) { + return RespondNow(Error(kInvalidUrlError, params->url)); + } + + Profile* profile = Profile::FromBrowserContext(browser_context()); + auto type = ::brave_shields::GetBraveShieldsControlType(profile, url); + auto result = std::make_unique(ControlTypeToString(type)); - std::unique_ptr params(Get::Params::Create(*args_)); + return RespondNow(OneArgument(std::move(result))); +} + +ExtensionFunction::ResponseAction BraveShieldsSetAdControlTypeFunction::Run() { + std::unique_ptr params( + brave_shields::SetAdControlType::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params.get()); - GURL primary_url(params->details.primary_url); - if (!primary_url.is_valid()) { - return RespondNow(Error(content_settings_api_constants::kInvalidUrlError, - params->details.primary_url)); + const GURL url(params->url); + // we don't allow setting defaults from the extension + if (url.is_empty() || !url.is_valid()) { + return RespondNow(Error(kInvalidUrlError, params->url)); } - GURL secondary_url(primary_url); - if (params->details.secondary_url.get()) { - secondary_url = GURL(*params->details.secondary_url); - if (!secondary_url.is_valid()) { - return RespondNow(Error(content_settings_api_constants::kInvalidUrlError, - *params->details.secondary_url)); - } + auto control_type = ControlTypeFromString(params->control_type); + if (control_type == ControlType::INVALID) { + return RespondNow(Error(kInvalidControlTypeError, params->control_type)); } - std::string resource_identifier; - if (params->details.resource_identifier.get()) - resource_identifier = params->details.resource_identifier->id; + Profile* profile = Profile::FromBrowserContext(browser_context()); + ::brave_shields::SetAdControlType(profile, control_type, url); - bool incognito = false; - if (params->details.incognito.get()) - incognito = *params->details.incognito; - if (incognito && !include_incognito_information()) - return RespondNow(Error(pref_keys::kIncognitoErrorMessage)); + return RespondNow(NoArguments()); +} + +ExtensionFunction::ResponseAction BraveShieldsGetAdControlTypeFunction::Run() { + std::unique_ptr params( + brave_shields::GetAdControlType::Params::Create(*args_)); + EXTENSION_FUNCTION_VALIDATE(params.get()); + + const GURL url(params->url); + // we don't allow getting defaults from the extension + if (url.is_empty() || !url.is_valid()) { + return RespondNow(Error(kInvalidUrlError, params->url)); + } - HostContentSettingsMap* map; Profile* profile = Profile::FromBrowserContext(browser_context()); - if (incognito) { - if (!profile->HasOffTheRecordProfile()) { - // TODO(bauerb): Allow reading incognito content settings - // outside of an incognito session. - return RespondNow( - Error(content_settings_api_constants::kIncognitoSessionOnlyError)); - } - map = HostContentSettingsMapFactory::GetForProfile( - profile->GetOffTheRecordProfile()); - } else { - map = HostContentSettingsMapFactory::GetForProfile(profile); + auto type = ::brave_shields::GetAdControlType(profile, url); + auto result = std::make_unique(ControlTypeToString(type)); + + return RespondNow(OneArgument(std::move(result))); +} + +ExtensionFunction::ResponseAction +BraveShieldsSetCookieControlTypeFunction::Run() { + std::unique_ptr params( + brave_shields::SetCookieControlType::Params::Create(*args_)); + EXTENSION_FUNCTION_VALIDATE(params.get()); + + const GURL url(params->url); + // we don't allow setting defaults from the extension + if (url.is_empty() || !url.is_valid()) { + return RespondNow(Error(kInvalidUrlError, params->url)); + } + + auto control_type = ControlTypeFromString(params->control_type); + if (control_type == ControlType::INVALID) { + return RespondNow(Error(kInvalidControlTypeError, params->control_type)); } - ContentSetting setting = map->GetContentSetting( - primary_url, secondary_url, content_type, resource_identifier); + Profile* profile = Profile::FromBrowserContext(browser_context()); + ::brave_shields::SetCookieControlType(profile, control_type, url); + + return RespondNow(NoArguments()); +} + +ExtensionFunction::ResponseAction +BraveShieldsGetCookieControlTypeFunction::Run() { + std::unique_ptr params( + brave_shields::GetCookieControlType::Params::Create(*args_)); + EXTENSION_FUNCTION_VALIDATE(params.get()); + + const GURL url(params->url); + // we don't allow getting defaults from the extension + if (url.is_empty() || !url.is_valid()) { + return RespondNow(Error(kInvalidUrlError, params->url)); + } - std::unique_ptr result(new base::DictionaryValue()); - std::string setting_string = - content_settings::ContentSettingToString(setting); - DCHECK(!setting_string.empty()); - result->SetString(content_settings_api_constants::kContentSettingKey, - setting_string); + Profile* profile = Profile::FromBrowserContext(browser_context()); + auto type = ::brave_shields::GetCookieControlType(profile, url); + auto result = std::make_unique(ControlTypeToString(type)); return RespondNow(OneArgument(std::move(result))); } ExtensionFunction::ResponseAction -BraveShieldsContentSettingSetFunction::Run() { - ContentSettingsType content_type; - EXTENSION_FUNCTION_VALIDATE(RemoveContentType(args_.get(), &content_type)); +BraveShieldsSetFingerprintingControlTypeFunction::Run() { + std::unique_ptr params( + brave_shields::SetFingerprintingControlType::Params::Create(*args_)); + EXTENSION_FUNCTION_VALIDATE(params.get()); + + const GURL url(params->url); + // we don't allow setting defaults from the extension + if (url.is_empty() || !url.is_valid()) { + return RespondNow(Error(kInvalidUrlError, params->url)); + } - std::unique_ptr params(Set::Params::Create(*args_)); + auto control_type = ControlTypeFromString(params->control_type); + if (control_type == ControlType::INVALID) { + return RespondNow(Error(kInvalidControlTypeError, params->control_type)); + } + + Profile* profile = Profile::FromBrowserContext(browser_context()); + ::brave_shields::SetFingerprintingControlType(profile, control_type, url); + + return RespondNow(NoArguments()); +} + +ExtensionFunction::ResponseAction +BraveShieldsGetFingerprintingControlTypeFunction::Run() { + std::unique_ptr params( + brave_shields::GetFingerprintingControlType::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params.get()); - std::string resource_identifier; - if (params->details.resource_identifier.get()) - resource_identifier = params->details.resource_identifier->id; - - std::string setting_str; - EXTENSION_FUNCTION_VALIDATE( - params->details.setting->GetAsString(&setting_str)); - ContentSetting setting; - EXTENSION_FUNCTION_VALIDATE( - content_settings::ContentSettingFromString(setting_str, &setting)); - EXTENSION_FUNCTION_VALIDATE(CONTENT_SETTING_DEFAULT != setting); - EXTENSION_FUNCTION_VALIDATE( - content_settings::ContentSettingsRegistry::GetInstance() - ->Get(content_type) - ->IsSettingValid(setting)); - - std::string primary_error; - ContentSettingsPattern primary_pattern = - content_settings_helpers::ParseExtensionPattern( - params->details.primary_pattern, &primary_error); - if (!primary_pattern.IsValid()) - return RespondNow(Error(primary_error)); - ContentSettingsPattern secondary_pattern = - ContentSettingsPattern::Wildcard(); - if (params->details.secondary_pattern.get()) { - std::string secondary_error; - secondary_pattern = content_settings_helpers::ParseExtensionPattern( - *params->details.secondary_pattern, &secondary_error); - if (!secondary_pattern.IsValid()) - return RespondNow(Error(secondary_error)); + const GURL url(params->url); + // we don't allow getting defaults from the extension + if (url.is_empty() || !url.is_valid()) { + return RespondNow(Error(kInvalidUrlError, params->url)); } - ExtensionPrefsScope scope = kExtensionPrefsScopeRegular; - bool incognito = false; - if (params->details.scope == - brave_shields::SCOPE_INCOGNITO_SESSION_ONLY) { - scope = kExtensionPrefsScopeIncognitoSessionOnly; - incognito = true; + Profile* profile = Profile::FromBrowserContext(browser_context()); + auto type = ::brave_shields::GetFingerprintingControlType(profile, url); + auto result = std::make_unique(ControlTypeToString(type)); + + return RespondNow(OneArgument(std::move(result))); +} + +ExtensionFunction::ResponseAction +BraveShieldsSetHTTPSEverywhereControlTypeFunction::Run() { + std::unique_ptr params( + brave_shields::SetHTTPSEverywhereControlType::Params::Create(*args_)); + EXTENSION_FUNCTION_VALIDATE(params.get()); + + const GURL url(params->url); + // we don't allow setting defaults from the extension + if (url.is_empty() || !url.is_valid()) { + return RespondNow(Error(kInvalidUrlError, params->url)); } - if (incognito) { - // Regular profiles can't access incognito unless the extension is allowed - // to run in incognito contexts. - if (!browser_context()->IsOffTheRecord() && - !extensions::util::IsIncognitoEnabled(brave_extension_id, - browser_context())) { - return RespondNow(Error(pref_keys::kIncognitoErrorMessage)); - } - } else { - // Incognito profiles can't access regular mode ever, they only exist in - // split mode. - if (browser_context()->IsOffTheRecord()) - return RespondNow( - Error(content_settings_api_constants::kIncognitoContextError)); + auto control_type = ControlTypeFromString(params->control_type); + if (control_type == ControlType::INVALID) { + return RespondNow(Error(kInvalidControlTypeError, params->control_type)); } - if (scope == kExtensionPrefsScopeIncognitoSessionOnly && - !Profile::FromBrowserContext(browser_context()) - ->HasOffTheRecordProfile()) { - return RespondNow(Error(pref_keys::kIncognitoSessionOnlyErrorMessage)); + Profile* profile = Profile::FromBrowserContext(browser_context()); + ::brave_shields::SetHTTPSEverywhereControlType(profile, control_type, url); + + return RespondNow(NoArguments()); +} + +ExtensionFunction::ResponseAction +BraveShieldsGetHTTPSEverywhereControlTypeFunction::Run() { + std::unique_ptr params( + brave_shields::GetHTTPSEverywhereControlType::Params::Create(*args_)); + EXTENSION_FUNCTION_VALIDATE(params.get()); + + const GURL url(params->url); + // we don't allow getting defaults from the extension + if (url.is_empty() || !url.is_valid()) { + return RespondNow(Error(kInvalidUrlError, params->url)); } - HostContentSettingsMap* map; Profile* profile = Profile::FromBrowserContext(browser_context()); - if (incognito) { - if (!profile->HasOffTheRecordProfile()) { - // TODO(bauerb): Allow reading incognito content settings - // outside of an incognito session. - return RespondNow( - Error(content_settings_api_constants::kIncognitoSessionOnlyError)); - } - map = HostContentSettingsMapFactory::GetForProfile( - profile->GetOffTheRecordProfile()); - } else { - map = HostContentSettingsMapFactory::GetForProfile(profile); + auto type = ::brave_shields::GetHTTPSEverywhereControlType(profile, url); + auto result = std::make_unique(ControlTypeToString(type)); + + return RespondNow(OneArgument(std::move(result))); +} + +ExtensionFunction::ResponseAction +BraveShieldsSetNoScriptControlTypeFunction::Run() { + std::unique_ptr params( + brave_shields::SetNoScriptControlType::Params::Create(*args_)); + EXTENSION_FUNCTION_VALIDATE(params.get()); + + const GURL url(params->url); + // we don't allow setting defaults from the extension + if (url.is_empty() || !url.is_valid()) { + return RespondNow(Error(kInvalidUrlError, params->url)); } - if (content_type == CONTENT_SETTINGS_TYPE_JAVASCRIPT) { - // TODO(simonhong): Need to check why generating pattern with - // content_settings_helpers::ParseExtensionPattern() causes javascript - // set fail. - // Without this separate handling, shields can't toggle block script setting - // anymore after user changes js permission from page info bubble. - // page info bubble uses SetNarrowestContentSetting() for setting and it - // gets pattern by using GetPatternsForContentSettingsType() same as - // SetContentSettingDefaultScope(). - const GURL primary_url(params->details.primary_pattern); - if (!primary_url.is_valid()) - return RespondNow(Error("Invalid url")); - - map->SetContentSettingDefaultScope( - primary_url, primary_url, content_type, resource_identifier, setting); - } else { - map->SetContentSettingCustomScope( - primary_pattern, secondary_pattern, - content_type, resource_identifier, setting); + auto control_type = ControlTypeFromString(params->control_type); + if (control_type == ControlType::INVALID) { + return RespondNow(Error(kInvalidControlTypeError, params->control_type)); } - // Delete previous settings set by brave extension in extension's - // ContentSettingsStore. Setting default means delete. - scoped_refptr store = - ContentSettingsService::Get(browser_context())->content_settings_store(); - store->SetExtensionContentSetting(brave_extension_id, - primary_pattern, secondary_pattern, - content_type, - resource_identifier, - CONTENT_SETTING_DEFAULT, - scope); + Profile* profile = Profile::FromBrowserContext(browser_context()); + ::brave_shields::SetNoScriptControlType(profile, control_type, url); + return RespondNow(NoArguments()); } +ExtensionFunction::ResponseAction +BraveShieldsGetNoScriptControlTypeFunction::Run() { + std::unique_ptr params( + brave_shields::GetNoScriptControlType::Params::Create(*args_)); + EXTENSION_FUNCTION_VALIDATE(params.get()); + + const GURL url(params->url); + // we don't allow getting defaults from the extension + if (url.is_empty() || !url.is_valid()) { + return RespondNow(Error(kInvalidUrlError, params->url)); + } + + Profile* profile = Profile::FromBrowserContext(browser_context()); + auto type = ::brave_shields::GetNoScriptControlType(profile, url); + auto result = std::make_unique(ControlTypeToString(type)); + + return RespondNow(OneArgument(std::move(result))); +} + } // namespace api } // namespace extensions diff --git a/browser/extensions/api/brave_shields_api.h b/browser/extensions/api/brave_shields_api.h index f758036ee3c..509ca0ac304 100644 --- a/browser/extensions/api/brave_shields_api.h +++ b/browser/extensions/api/brave_shields_api.h @@ -16,32 +16,142 @@ class BraveShieldsAllowScriptsOnceFunction : public UIThreadExtensionFunction { DECLARE_EXTENSION_FUNCTION("braveShields.allowScriptsOnce", UNKNOWN) protected: - ~BraveShieldsAllowScriptsOnceFunction() override; + ~BraveShieldsAllowScriptsOnceFunction() override {} ResponseAction Run() override; }; -class BraveShieldsContentSettingGetFunction +class BraveShieldsSetBraveShieldsControlTypeFunction : public UIThreadExtensionFunction { public: - DECLARE_EXTENSION_FUNCTION("braveShields.get", UNKNOWN) + DECLARE_EXTENSION_FUNCTION("braveShields.setBraveShieldsControlType", UNKNOWN) protected: - ~BraveShieldsContentSettingGetFunction() override {} + ~BraveShieldsSetBraveShieldsControlTypeFunction() override {} - // ExtensionFunction: ResponseAction Run() override; }; -class BraveShieldsContentSettingSetFunction +class BraveShieldsGetBraveShieldsControlTypeFunction : public UIThreadExtensionFunction { public: - DECLARE_EXTENSION_FUNCTION("braveShields.set", UNKNOWN) + DECLARE_EXTENSION_FUNCTION("braveShields.getBraveShieldsControlType", UNKNOWN) protected: - ~BraveShieldsContentSettingSetFunction() override {} + ~BraveShieldsGetBraveShieldsControlTypeFunction() override {} + + ResponseAction Run() override; +}; + +class BraveShieldsSetAdControlTypeFunction : public UIThreadExtensionFunction { + public: + DECLARE_EXTENSION_FUNCTION("braveShields.setAdControlType", UNKNOWN) + + protected: + ~BraveShieldsSetAdControlTypeFunction() override {} + + ResponseAction Run() override; +}; + +class BraveShieldsGetAdControlTypeFunction : public UIThreadExtensionFunction { + public: + DECLARE_EXTENSION_FUNCTION("braveShields.getAdControlType", UNKNOWN) + + protected: + ~BraveShieldsGetAdControlTypeFunction() override {} + + ResponseAction Run() override; +}; + +class BraveShieldsSetCookieControlTypeFunction + : public UIThreadExtensionFunction { + public: + DECLARE_EXTENSION_FUNCTION("braveShields.setCookieControlType", UNKNOWN) + + protected: + ~BraveShieldsSetCookieControlTypeFunction() override {} + + ResponseAction Run() override; +}; + +class BraveShieldsGetCookieControlTypeFunction + : public UIThreadExtensionFunction { + public: + DECLARE_EXTENSION_FUNCTION("braveShields.getCookieControlType", UNKNOWN) + + protected: + ~BraveShieldsGetCookieControlTypeFunction() override {} + + ResponseAction Run() override; +}; + +class BraveShieldsSetFingerprintingControlTypeFunction + : public UIThreadExtensionFunction { + public: + DECLARE_EXTENSION_FUNCTION("braveShields.setFingerprintingControlType", + UNKNOWN) + + protected: + ~BraveShieldsSetFingerprintingControlTypeFunction() override {} + + ResponseAction Run() override; +}; + +class BraveShieldsGetFingerprintingControlTypeFunction + : public UIThreadExtensionFunction { + public: + DECLARE_EXTENSION_FUNCTION("braveShields.getFingerprintingControlType", + UNKNOWN) + + protected: + ~BraveShieldsGetFingerprintingControlTypeFunction() override {} + + ResponseAction Run() override; +}; + +class BraveShieldsSetHTTPSEverywhereControlTypeFunction + : public UIThreadExtensionFunction { + public: + DECLARE_EXTENSION_FUNCTION("braveShields.setHTTPSEverywhereControlType", + UNKNOWN) + + protected: + ~BraveShieldsSetHTTPSEverywhereControlTypeFunction() override {} + + ResponseAction Run() override; +}; + +class BraveShieldsGetHTTPSEverywhereControlTypeFunction + : public UIThreadExtensionFunction { + public: + DECLARE_EXTENSION_FUNCTION("braveShields.getHTTPSEverywhereControlType", + UNKNOWN) + + protected: + ~BraveShieldsGetHTTPSEverywhereControlTypeFunction() override {} + + ResponseAction Run() override; +}; + +class BraveShieldsSetNoScriptControlTypeFunction + : public UIThreadExtensionFunction { + public: + DECLARE_EXTENSION_FUNCTION("braveShields.setNoScriptControlType", UNKNOWN) + + protected: + ~BraveShieldsSetNoScriptControlTypeFunction() override {} + + ResponseAction Run() override; +}; + +class BraveShieldsGetNoScriptControlTypeFunction + : public UIThreadExtensionFunction { + public: + DECLARE_EXTENSION_FUNCTION("braveShields.getNoScriptControlType", UNKNOWN) + + protected: + ~BraveShieldsGetNoScriptControlTypeFunction() override {} - // ExtensionFunction: ResponseAction Run() override; }; diff --git a/browser/extensions/api/brave_shields_api_browsertest.cc b/browser/extensions/api/brave_shields_api_browsertest.cc index 645bc7ffde9..7f56737a5a7 100644 --- a/browser/extensions/api/brave_shields_api_browsertest.cc +++ b/browser/extensions/api/brave_shields_api_browsertest.cc @@ -20,20 +20,18 @@ #include "chrome/browser/ui/browser.h" #include "chrome/test/base/in_process_browser_test.h" #include "chrome/test/base/ui_test_utils.h" -#include "content/public/test/browser_test_utils.h" #include "components/content_settings/core/browser/host_content_settings_map.h" #include "components/content_settings/core/common/content_settings.h" #include "components/content_settings/core/common/content_settings_types.h" +#include "content/public/test/browser_test_utils.h" #include "extensions/common/extension_builder.h" #include "net/dns/mock_host_resolver.h" namespace extensions { -using api::BraveShieldsContentSettingGetFunction; -using api::BraveShieldsContentSettingSetFunction; -using extensions::api::BraveShieldsAllowScriptsOnceFunction; using extension_function_test_utils::RunFunctionAndReturnError; using extension_function_test_utils::RunFunctionAndReturnSingleResult; +using extensions::api::BraveShieldsAllowScriptsOnceFunction; class BraveShieldsAPIBrowserTest : public InProcessBrowserTest { public: @@ -57,13 +55,9 @@ class BraveShieldsAPIBrowserTest : public InProcessBrowserTest { return browser()->tab_strip_model()->GetActiveWebContents(); } - scoped_refptr extension() { - return extension_; - } + scoped_refptr extension() { return extension_; } - HostContentSettingsMap* content_settings() const { - return content_settings_; - } + HostContentSettingsMap* content_settings() const { return content_settings_; } void BlockScripts() { content_settings_->SetContentSettingCustomScope( @@ -71,11 +65,10 @@ class BraveShieldsAPIBrowserTest : public InProcessBrowserTest { CONTENT_SETTINGS_TYPE_JAVASCRIPT, "", CONTENT_SETTING_BLOCK); } - bool NavigateToURLUntilLoadStop( - const std::string& origin, const std::string& path) { - ui_test_utils::NavigateToURL( - browser(), - embedded_test_server()->GetURL(origin, path)); + bool NavigateToURLUntilLoadStop(const std::string& origin, + const std::string& path) { + ui_test_utils::NavigateToURL(browser(), + embedded_test_server()->GetURL(origin, path)); return WaitForLoadStop(active_contents()); } @@ -98,7 +91,7 @@ class BraveShieldsAPIBrowserTest : public InProcessBrowserTest { // reload page with a.com temporarily allowed active_contents()->GetController().Reload(content::ReloadType::NORMAL, - true); + true); } void AllowScriptOriginAndDataURLOnce(const std::string& origin, @@ -133,38 +126,37 @@ IN_PROC_BROWSER_TEST_F(BraveShieldsAPIBrowserTest, AllowScriptsOnce) { EXPECT_TRUE( NavigateToURLUntilLoadStop("a.com", "/load_js_from_origins.html")); - EXPECT_EQ(active_contents()->GetAllFrames().size(), 1u) << - "All script loadings should be blocked."; + EXPECT_EQ(active_contents()->GetAllFrames().size(), 1u) + << "All script loadings should be blocked."; AllowScriptOriginOnce("a.com"); EXPECT_TRUE(WaitForLoadStop(active_contents())); - EXPECT_EQ(active_contents()->GetAllFrames().size(), 2u) << - "Scripts from a.com should be temporarily allowed."; + EXPECT_EQ(active_contents()->GetAllFrames().size(), 2u) + << "Scripts from a.com should be temporarily allowed."; // reload page again - active_contents()->GetController().Reload(content::ReloadType::NORMAL, - true); + active_contents()->GetController().Reload(content::ReloadType::NORMAL, true); EXPECT_TRUE(WaitForLoadStop(active_contents())); - EXPECT_EQ(active_contents()->GetAllFrames().size(), 2u) << - "Scripts from a.com should be temporarily allowed after reload."; + EXPECT_EQ(active_contents()->GetAllFrames().size(), 2u) + << "Scripts from a.com should be temporarily allowed after reload."; // same doc navigation - ui_test_utils::NavigateToURL( - browser(), - embedded_test_server()->GetURL("a.com", - "/load_js_from_origins.html#foo")); + ui_test_utils::NavigateToURL(browser(), + embedded_test_server()->GetURL( + "a.com", "/load_js_from_origins.html#foo")); EXPECT_TRUE(WaitForLoadStop(active_contents())); - EXPECT_EQ(active_contents()->GetAllFrames().size(), 2u) << - "Scripts from a.com should be temporarily allowed for same doc navigation."; + EXPECT_EQ(active_contents()->GetAllFrames().size(), 2u) + << "Scripts from a.com should be temporarily allowed for same doc " + "navigation."; // navigate to a different origin ui_test_utils::NavigateToURL( browser(), embedded_test_server()->GetURL("b.com", "/load_js_from_origins.html")); EXPECT_TRUE(WaitForLoadStop(active_contents())); - EXPECT_EQ(active_contents()->GetAllFrames().size(), 1u) << - "All script loadings should be blocked after navigating away."; + EXPECT_EQ(active_contents()->GetAllFrames().size(), 1u) + << "All script loadings should be blocked after navigating away."; } IN_PROC_BROWSER_TEST_F(BraveShieldsAPIBrowserTest, AllowScriptsOnceDataURL) { @@ -192,178 +184,94 @@ IN_PROC_BROWSER_TEST_F(BraveShieldsAPIBrowserTest, AllowScriptsOnceDataURL) { IN_PROC_BROWSER_TEST_F(BraveShieldsAPIBrowserTest, AllowScriptsOnceIframe) { BlockScripts(); - EXPECT_TRUE( - NavigateToURLUntilLoadStop("a.com", "/remote_iframe.html")); - EXPECT_EQ(active_contents()->GetAllFrames().size(), 2u) << - "All script loadings should be blocked."; + EXPECT_TRUE(NavigateToURLUntilLoadStop("a.com", "/remote_iframe.html")); + EXPECT_EQ(active_contents()->GetAllFrames().size(), 2u) + << "All script loadings should be blocked."; AllowScriptOriginOnce("b.com"); EXPECT_TRUE(WaitForLoadStop(active_contents())); - EXPECT_EQ(active_contents()->GetAllFrames().size(), 3u) << - "Scripts from b.com should be temporarily allowed."; + EXPECT_EQ(active_contents()->GetAllFrames().size(), 3u) + << "Scripts from b.com should be temporarily allowed."; } constexpr char kJavascriptSetParams[] = - "[\"javascript\", {\"primaryPattern\": \"https://www.brave.com/*\"," - "\"setting\": \"block\"}]"; -constexpr char kJavascriptGetParams[] = - "[\"javascript\", {\"primaryUrl\": \"https://www.brave.com/*\"}]"; -constexpr char kBraveURLPattern[] = "https://www.brave.com/*"; + "[\"block\", \"https://www.brave.com/\"]"; +constexpr char kJavascriptGetParams[] = "[\"https://www.brave.com/\"]"; const GURL kBraveURL("https://www.brave.com"); // Test javascript content setting works properly via braveShields api. IN_PROC_BROWSER_TEST_F(BraveShieldsAPIBrowserTest, - ContentSettingJavascriptAPI) { + GetNoScriptControlTypeFunction) { // Default content settings for javascript is allow. - scoped_refptr get_function( - new BraveShieldsContentSettingGetFunction()); + scoped_refptr get_function( + new api::BraveShieldsGetNoScriptControlTypeFunction()); get_function->set_extension(extension().get()); std::unique_ptr value; - value.reset(RunFunctionAndReturnSingleResult(get_function.get(), - kJavascriptGetParams, - browser())); - EXPECT_EQ(value->FindKey( - content_settings_api_constants::kContentSettingKey)->GetString(), - std::string("allow")); - - // Block javascript. - scoped_refptr set_function( - new BraveShieldsContentSettingSetFunction()); - set_function->set_extension(extension().get()); - RunFunctionAndReturnSingleResult(set_function.get(), - kJavascriptSetParams, - browser()); - - // Check Block is set. - get_function = base::MakeRefCounted(); - get_function->set_extension(extension().get()); - value.reset(RunFunctionAndReturnSingleResult(get_function.get(), - kJavascriptGetParams, - browser())); - EXPECT_EQ(value->FindKey( - content_settings_api_constants::kContentSettingKey)->GetString(), - std::string("block")); + value.reset(RunFunctionAndReturnSingleResult( + get_function.get(), kJavascriptGetParams, browser())); + EXPECT_EQ(value->GetString(), std::string("allow")); } -// Test previous settings set by extension is deleted when setting is newly -// modifed. IN_PROC_BROWSER_TEST_F(BraveShieldsAPIBrowserTest, - ContentSettingValueFromExtensionDelete) { - // Set javascript content setting via ContentSettingsStore and check this - // settings comes from extension. chrome.contentSettings.javascript.set() - // sets settings into ContentSettingsStore. - std::string primary_error; - ContentSettingsPattern primary_pattern = - content_settings_helpers::ParseExtensionPattern(kBraveURLPattern, - &primary_error); - scoped_refptr store = - ContentSettingsService::Get(browser()->profile())-> - content_settings_store(); - store->SetExtensionContentSetting(brave_extension_id, - primary_pattern, - ContentSettingsPattern::Wildcard(), - CONTENT_SETTINGS_TYPE_JAVASCRIPT, - std::string(), - CONTENT_SETTING_ALLOW, - kExtensionPrefsScopeRegular); - DCHECK(primary_pattern.IsValid()); - - content_settings::SettingInfo info; - content_settings()->GetWebsiteSetting( - kBraveURL, kBraveURL, - CONTENT_SETTINGS_TYPE_JAVASCRIPT, std::string(), &info); - // Check source is extension. - EXPECT_EQ(info.source, - content_settings::SettingSource::SETTING_SOURCE_EXTENSION); - - // Check this value via braveShields api. - scoped_refptr get_function( - new BraveShieldsContentSettingGetFunction()); - get_function->set_extension(extension().get()); - std::unique_ptr value; - value.reset(RunFunctionAndReturnSingleResult(get_function.get(), - kJavascriptGetParams, - browser())); - EXPECT_EQ(value->FindKey( - content_settings_api_constants::kContentSettingKey)->GetString(), - std::string("allow")); - - // Block via shields api. - scoped_refptr set_function( - new BraveShieldsContentSettingSetFunction()); + SetNoScriptControlTypeFunction) { + // Block javascript. + scoped_refptr set_function( + new api::BraveShieldsSetNoScriptControlTypeFunction()); set_function->set_extension(extension().get()); - RunFunctionAndReturnSingleResult(set_function.get(), - kJavascriptSetParams, + RunFunctionAndReturnSingleResult(set_function.get(), kJavascriptSetParams, browser()); // Check Block is set. - get_function = base::MakeRefCounted(); - get_function->set_extension(extension().get()); - value.reset(RunFunctionAndReturnSingleResult(get_function.get(), - kJavascriptGetParams, - browser())); - EXPECT_EQ(value->FindKey( - content_settings_api_constants::kContentSettingKey)->GetString(), - std::string("block")); - - content_settings()->GetWebsiteSetting( - kBraveURL, kBraveURL, - CONTENT_SETTINGS_TYPE_JAVASCRIPT, std::string(), &info); - // Check source is user. - EXPECT_EQ(info.source, - content_settings::SettingSource::SETTING_SOURCE_USER); + ContentSetting setting = + HostContentSettingsMapFactory::GetForProfile(browser()->profile()) + ->GetContentSetting(kBraveURL, GURL(), + CONTENT_SETTINGS_TYPE_JAVASCRIPT, ""); + EXPECT_EQ(setting, CONTENT_SETTING_BLOCK); } // Checks shields configuration is persisted across the sessions. IN_PROC_BROWSER_TEST_F(BraveShieldsAPIBrowserTest, PRE_ShieldSettingsPersistTest) { - HostContentSettingsMapFactory::GetForProfile(browser()->profile())-> - SetContentSettingDefaultScope( - kBraveURL, kBraveURL, - CONTENT_SETTINGS_TYPE_PLUGINS, - brave_shields::kHTTPUpgradableResources, - CONTENT_SETTING_ALLOW); + HostContentSettingsMapFactory::GetForProfile(browser()->profile()) + ->SetContentSettingDefaultScope( + kBraveURL, GURL(), CONTENT_SETTINGS_TYPE_PLUGINS, + brave_shields::kHTTPUpgradableResources, CONTENT_SETTING_ALLOW); ContentSetting setting = - HostContentSettingsMapFactory::GetForProfile(browser()->profile())-> - GetContentSetting(kBraveURL, kBraveURL, CONTENT_SETTINGS_TYPE_PLUGINS, - brave_shields::kHTTPUpgradableResources); + HostContentSettingsMapFactory::GetForProfile(browser()->profile()) + ->GetContentSetting(kBraveURL, GURL(), CONTENT_SETTINGS_TYPE_PLUGINS, + brave_shields::kHTTPUpgradableResources); EXPECT_EQ(setting, CONTENT_SETTING_ALLOW); } -IN_PROC_BROWSER_TEST_F(BraveShieldsAPIBrowserTest, - ShieldSettingsPersistTest) { +IN_PROC_BROWSER_TEST_F(BraveShieldsAPIBrowserTest, ShieldSettingsPersistTest) { ContentSetting setting = - HostContentSettingsMapFactory::GetForProfile(browser()->profile())-> - GetContentSetting(kBraveURL, kBraveURL, CONTENT_SETTINGS_TYPE_PLUGINS, - brave_shields::kHTTPUpgradableResources); + HostContentSettingsMapFactory::GetForProfile(browser()->profile()) + ->GetContentSetting(kBraveURL, GURL(), CONTENT_SETTINGS_TYPE_PLUGINS, + brave_shields::kHTTPUpgradableResources); EXPECT_EQ(setting, CONTENT_SETTING_ALLOW); } // Checks flash configuration isn't persisted across the sessions. -IN_PROC_BROWSER_TEST_F(BraveShieldsAPIBrowserTest, - PRE_FlashPersistTest) { - HostContentSettingsMapFactory::GetForProfile(browser()->profile())-> - SetContentSettingDefaultScope( - kBraveURL, kBraveURL, - CONTENT_SETTINGS_TYPE_PLUGINS, - std::string(), - CONTENT_SETTING_ALLOW); +IN_PROC_BROWSER_TEST_F(BraveShieldsAPIBrowserTest, PRE_FlashPersistTest) { + HostContentSettingsMapFactory::GetForProfile(browser()->profile()) + ->SetContentSettingDefaultScope(kBraveURL, GURL(), + CONTENT_SETTINGS_TYPE_PLUGINS, + std::string(), CONTENT_SETTING_ALLOW); ContentSetting setting = - HostContentSettingsMapFactory::GetForProfile(browser()->profile())-> - GetContentSetting(kBraveURL, kBraveURL, CONTENT_SETTINGS_TYPE_PLUGINS, - std::string()); + HostContentSettingsMapFactory::GetForProfile(browser()->profile()) + ->GetContentSetting(kBraveURL, GURL(), + CONTENT_SETTINGS_TYPE_PLUGINS, std::string()); EXPECT_EQ(setting, CONTENT_SETTING_ALLOW); } -IN_PROC_BROWSER_TEST_F(BraveShieldsAPIBrowserTest, - FlashPersistTest) { +IN_PROC_BROWSER_TEST_F(BraveShieldsAPIBrowserTest, FlashPersistTest) { ContentSetting setting = - HostContentSettingsMapFactory::GetForProfile(browser()->profile())-> - GetContentSetting(kBraveURL, kBraveURL, CONTENT_SETTINGS_TYPE_PLUGINS, - std::string()); + HostContentSettingsMapFactory::GetForProfile(browser()->profile()) + ->GetContentSetting(kBraveURL, GURL(), + CONTENT_SETTINGS_TYPE_PLUGINS, std::string()); EXPECT_EQ(setting, CONTENT_SETTING_BLOCK); } diff --git a/browser/resources/settings/default_brave_shields_page/default_brave_shields_page.js b/browser/resources/settings/default_brave_shields_page/default_brave_shields_page.js index 5f4262979af..06e8ad9be1c 100644 --- a/browser/resources/settings/default_brave_shields_page/default_brave_shields_page.js +++ b/browser/resources/settings/default_brave_shields_page/default_brave_shields_page.js @@ -18,7 +18,7 @@ Polymer({ type: Array, value: function() { return [ - {value: '3p', name: loadTimeData.getString('block3rdPartyCookies')}, + {value: 'block_third_party', name: loadTimeData.getString('block3rdPartyCookies')}, {value: 'block', name: loadTimeData.getString('blockAllCookies')}, {value: 'allow', name: loadTimeData.getString('allowAllCookies')} ] @@ -30,7 +30,7 @@ Polymer({ type: Array, value: function() { return [ - {value: '3p', name: loadTimeData.getString('block3rdPartyFingerprinting')}, + {value: 'block_third_party', name: loadTimeData.getString('block3rdPartyFingerprinting')}, {value: 'block', name: loadTimeData.getString('blockAllFingerprinting')}, {value: 'allow', name: loadTimeData.getString('allowAllFingerprinting')} ] diff --git a/browser/ui/BUILD.gn b/browser/ui/BUILD.gn index dc48a7416c2..af7454ddc7c 100644 --- a/browser/ui/BUILD.gn +++ b/browser/ui/BUILD.gn @@ -147,6 +147,7 @@ source_set("ui") { "//brave/components/brave_new_tab_ui:generated_resources", "//brave/components/brave_rewards/browser", "//brave/components/brave_rewards/resources", + "//brave/components/brave_shields/browser", "//brave/components/brave_welcome_ui:generated_resources", "//chrome/app:command_ids", "//chrome/common", diff --git a/browser/ui/webui/settings/default_brave_shields_handler.cc b/browser/ui/webui/settings/default_brave_shields_handler.cc index 000fc83c9f1..1d9241c6b59 100644 --- a/browser/ui/webui/settings/default_brave_shields_handler.cc +++ b/browser/ui/webui/settings/default_brave_shields_handler.cc @@ -9,14 +9,14 @@ #include "base/bind.h" #include "base/values.h" -#include "brave/common/pref_names.h" -#include "brave/components/brave_shields/common/brave_shield_constants.h" -#include "chrome/browser/content_settings/host_content_settings_map_factory.h" +#include "brave/components/brave_shields/browser/brave_shields_util.h" #include "chrome/browser/profiles/profile.h" -#include "components/content_settings/core/browser/host_content_settings_map.h" -#include "components/prefs/pref_service.h" #include "content/public/browser/web_ui.h" +using brave_shields::ControlType; +using brave_shields::ControlTypeFromString; +using brave_shields::ControlTypeToString; + void DefaultBraveShieldsHandler::RegisterMessages() { profile_ = Profile::FromWebUI(web_ui()); web_ui()->RegisterMessageCallback( @@ -60,14 +60,12 @@ void DefaultBraveShieldsHandler::GetAdControlType(const base::ListValue* args) { CHECK_EQ(args->GetSize(), 1U); CHECK(profile_); - ContentSetting setting = - HostContentSettingsMapFactory::GetForProfile(profile_)->GetContentSetting( - GURL(), GURL(), CONTENT_SETTINGS_TYPE_PLUGINS, brave_shields::kAds); + ControlType setting = brave_shields::GetAdControlType(profile_, GURL()); AllowJavascript(); ResolveJavascriptCallback( args->GetList()[0].Clone(), - base::Value(setting == CONTENT_SETTING_ALLOW)); + base::Value(setting == ControlType::ALLOW)); } void DefaultBraveShieldsHandler::SetAdControlType(const base::ListValue* args) { @@ -76,20 +74,10 @@ void DefaultBraveShieldsHandler::SetAdControlType(const base::ListValue* args) { bool value; args->GetBoolean(0, &value); - HostContentSettingsMapFactory::GetForProfile(profile_)-> - SetContentSettingCustomScope( - ContentSettingsPattern::Wildcard(), - ContentSettingsPattern::Wildcard(), - CONTENT_SETTINGS_TYPE_PLUGINS, - brave_shields::kAds, - value ? CONTENT_SETTING_BLOCK : CONTENT_SETTING_ALLOW); - HostContentSettingsMapFactory::GetForProfile(profile_)-> - SetContentSettingCustomScope( - ContentSettingsPattern::Wildcard(), - ContentSettingsPattern::Wildcard(), - CONTENT_SETTINGS_TYPE_PLUGINS, - brave_shields::kTrackers, - value ? CONTENT_SETTING_BLOCK : CONTENT_SETTING_ALLOW); + brave_shields::SetAdControlType(profile_, + value ? ControlType::BLOCK + : ControlType::ALLOW, + GURL()); } void DefaultBraveShieldsHandler::GetCookieControlType( @@ -97,26 +85,12 @@ void DefaultBraveShieldsHandler::GetCookieControlType( CHECK_EQ(args->GetSize(), 1U); CHECK(profile_); - ContentSetting setting = - HostContentSettingsMapFactory::GetForProfile(profile_)->GetContentSetting( - GURL(), GURL(), CONTENT_SETTINGS_TYPE_PLUGINS, - brave_shields::kCookies); - ContentSetting fp_setting = - HostContentSettingsMapFactory::GetForProfile(profile_)->GetContentSetting( - GURL(), GURL("https://firstParty/"), CONTENT_SETTINGS_TYPE_PLUGINS, - brave_shields::kCookies); - - std::string value = "block"; - if (setting == CONTENT_SETTING_ALLOW) { - value = "allow"; - } else if (fp_setting != CONTENT_SETTING_BLOCK) { - value = "3p"; - } + ControlType setting = brave_shields::GetCookieControlType(profile_, GURL()); AllowJavascript(); ResolveJavascriptCallback( args->GetList()[0].Clone(), - base::Value(value)); + base::Value(ControlTypeToString(setting))); } void DefaultBraveShieldsHandler::SetCookieControlType( @@ -126,27 +100,9 @@ void DefaultBraveShieldsHandler::SetCookieControlType( std::string value; args->GetString(0, &value); - auto* map = HostContentSettingsMapFactory::GetForProfile(profile_); - map->SetContentSettingCustomScope( - ContentSettingsPattern::Wildcard(), - ContentSettingsPattern::Wildcard(), - CONTENT_SETTINGS_TYPE_PLUGINS, - brave_shields::kReferrers, - value == "allow" ? CONTENT_SETTING_ALLOW : CONTENT_SETTING_BLOCK); - - map->SetContentSettingCustomScope( - ContentSettingsPattern::Wildcard(), - ContentSettingsPattern::Wildcard(), - CONTENT_SETTINGS_TYPE_PLUGINS, - brave_shields::kCookies, - value == "allow" ? CONTENT_SETTING_ALLOW : CONTENT_SETTING_BLOCK); - - map->SetContentSettingCustomScope( - ContentSettingsPattern::Wildcard(), - ContentSettingsPattern::FromString("https://firstParty/*"), - CONTENT_SETTINGS_TYPE_PLUGINS, - brave_shields::kCookies, - value == "block" ? CONTENT_SETTING_BLOCK : CONTENT_SETTING_ALLOW); + brave_shields::SetCookieControlType(profile_, + ControlTypeFromString(value), + GURL()); } void DefaultBraveShieldsHandler::GetFingerprintingControlType( @@ -154,26 +110,13 @@ void DefaultBraveShieldsHandler::GetFingerprintingControlType( CHECK_EQ(args->GetSize(), 1U); CHECK(profile_); - ContentSetting setting = - HostContentSettingsMapFactory::GetForProfile(profile_)->GetContentSetting( - GURL(), GURL(), CONTENT_SETTINGS_TYPE_PLUGINS, - brave_shields::kFingerprinting); - ContentSetting fp_setting = - HostContentSettingsMapFactory::GetForProfile(profile_)->GetContentSetting( - GURL(), GURL("https://firstParty/"), CONTENT_SETTINGS_TYPE_PLUGINS, - brave_shields::kFingerprinting); - - std::string value; - if (setting != fp_setting || setting == CONTENT_SETTING_DEFAULT) { - value = "3p"; - } else { - value = setting == CONTENT_SETTING_ALLOW ? "allow" : "block"; - } + ControlType setting = + brave_shields::GetFingerprintingControlType(profile_, GURL()); AllowJavascript(); ResolveJavascriptCallback( args->GetList()[0].Clone(), - base::Value(value)); + base::Value(ControlTypeToString(setting))); } void DefaultBraveShieldsHandler::SetFingerprintingControlType( @@ -183,20 +126,9 @@ void DefaultBraveShieldsHandler::SetFingerprintingControlType( std::string value; args->GetString(0, &value); - auto* map = HostContentSettingsMapFactory::GetForProfile(profile_); - map->SetContentSettingCustomScope( - ContentSettingsPattern::Wildcard(), - ContentSettingsPattern::Wildcard(), - CONTENT_SETTINGS_TYPE_PLUGINS, - brave_shields::kFingerprinting, - value == "allow" ? CONTENT_SETTING_ALLOW : CONTENT_SETTING_BLOCK); - - map->SetContentSettingCustomScope( - ContentSettingsPattern::Wildcard(), - ContentSettingsPattern::FromString("https://firstParty/*"), - CONTENT_SETTINGS_TYPE_PLUGINS, - brave_shields::kFingerprinting, - value == "block" ? CONTENT_SETTING_BLOCK : CONTENT_SETTING_ALLOW); + brave_shields::SetFingerprintingControlType(profile_, + ControlTypeFromString(value), + GURL()); } void DefaultBraveShieldsHandler::SetHTTPSEverywhereControlType( @@ -206,13 +138,10 @@ void DefaultBraveShieldsHandler::SetHTTPSEverywhereControlType( bool value; args->GetBoolean(0, &value); - HostContentSettingsMapFactory::GetForProfile(profile_)-> - SetContentSettingCustomScope( - ContentSettingsPattern::Wildcard(), - ContentSettingsPattern::Wildcard(), - CONTENT_SETTINGS_TYPE_PLUGINS, - brave_shields::kHTTPUpgradableResources, - value ? CONTENT_SETTING_BLOCK : CONTENT_SETTING_ALLOW); + brave_shields::SetHTTPSEverywhereControlType(profile_, + value ? ControlType::BLOCK + : ControlType::ALLOW, + GURL()); } void DefaultBraveShieldsHandler::SetNoScriptControlType( @@ -222,11 +151,8 @@ void DefaultBraveShieldsHandler::SetNoScriptControlType( bool value; args->GetBoolean(0, &value); - HostContentSettingsMapFactory::GetForProfile(profile_)-> - SetContentSettingCustomScope( - ContentSettingsPattern::Wildcard(), - ContentSettingsPattern::Wildcard(), - CONTENT_SETTINGS_TYPE_JAVASCRIPT, - "", - value ? CONTENT_SETTING_BLOCK : CONTENT_SETTING_ALLOW); + brave_shields::SetNoScriptControlType(profile_, + value ? ControlType::BLOCK + : ControlType::ALLOW, + GURL()); } diff --git a/common/extensions/api/brave_shields.json b/common/extensions/api/brave_shields.json index b2c0a27964c..f60b6008ac4 100644 --- a/common/extensions/api/brave_shields.json +++ b/common/extensions/api/brave_shields.json @@ -29,176 +29,243 @@ ], "functions": [ { - "name": "allowScriptsOnce", + "name": "setBraveShieldsControlType", "type": "function", - "description": "Allow scripts from a list of origins until next reload", + "description": "Set brave shields control type for a url", "parameters": [ { - "name": "origins", - "type": "array", - "items": {"type": "string"} + "name": "controlType", + "type": "string" }, { - "name": "tabID", - "type": "integer" + "name": "url", + "type": "string" + } + ] + }, + { + "name": "getBraveShieldsControlType", + "type": "function", + "description": "Get brave shields control type for a url", + "parameters": [ + { + "name": "url", + "type": "string" }, { "type": "function", "name": "callback", - "optional": true, - "parameters": [] + "parameters": [ + { + "name": "controlType", + "type": "string" + } + ] } ] - } - ], - "types": [ + }, { - "id": "ResourceIdentifier", - "type": "object", - "properties": { - "id": { - "type": "string", - "description": "The resource identifier for the given content type." + "name": "setAdControlType", + "type": "function", + "description": "Set ads control type for a url", + "parameters": [ + { + "name": "controlType", + "type": "string" }, - "description": { - "type": "string", - "optional": true, - "description": "A human readable description of the resource." + { + "name": "url", + "type": "string" } - }, - "description": "The only content type using resource identifiers is $(ref:contentSettings.plugins). For more information, see Resource Identifiers." + ] }, { - "id": "Scope", - "type": "string", - "enum": ["regular", "incognito_session_only"], - "description": "The scope of the ContentSetting. One of
regular: setting for regular profile (which is inherited by the incognito profile if not overridden elsewhere),
incognito_session_only: setting for incognito profile that can only be set during an incognito session and is deleted when the incognito session ends (overrides regular settings)." + "name": "getAdControlType", + "type": "function", + "description": "Get ads control type for a url", + "parameters": [ + { + "name": "url", + "type": "string" + }, + { + "type": "function", + "name": "callback", + "parameters": [ + { + "name": "controlType", + "type": "string" + } + ] + } + ] }, { - "id": "ContentSetting", - "js_module": "ContentSetting", - "type": "object", - "functions": [ + "name": "setCookieControlType", + "type": "function", + "description": "Set cookie control type for a url", + "parameters": [ + { + "name": "controlType", + "type": "string" + }, + { + "name": "url", + "type": "string" + } + ] + }, + { + "name": "getCookieControlType", + "type": "function", + "description": "Get cookie control type for a url", + "parameters": [ + { + "name": "url", + "type": "string" + }, { - "name": "get", "type": "function", - "description": "Gets the current content setting for a given pair of URLs.", + "name": "callback", "parameters": [ { - "name": "details", - "type": "object", - "properties": { - "primaryUrl": { - "type": "string", - "description": "The primary URL for which the content setting should be retrieved. Note that the meaning of a primary URL depends on the content type." - }, - "secondaryUrl": { - "type": "string", - "description": "The secondary URL for which the content setting should be retrieved. Defaults to the primary URL. Note that the meaning of a secondary URL depends on the content type, and not all content types use secondary URLs.", - "optional": true - }, - "resourceIdentifier": { - "$ref": "ResourceIdentifier", - "optional": true, - "description": "A more specific identifier of the type of content for which the settings should be retrieved." - }, - "incognito": { - "type": "boolean", - "optional": true, - "description": "Whether to check the content settings for an incognito session. (default false)" - } - } - }, - { - "type": "function", - "name": "callback", - "parameters": [ - { - "name": "details", - "type": "object", - "properties": { - "setting": { - "type": "any", - "description": "The content setting. See the description of the individual ContentSetting objects for the possible values." - } - } - } - ] + "name": "controlType", + "type": "string" } ] + } + ] + }, + { + "name": "setFingerprintingControlType", + "type": "function", + "description": "Set fingerprinting control type for a url", + "parameters": [ + { + "name": "controlType", + "type": "string" + }, + { + "name": "url", + "type": "string" + } + ] + }, + { + "name": "getFingerprintingControlType", + "type": "function", + "description": "Get fingerprinting control type for a url", + "parameters": [ + { + "name": "url", + "type": "string" }, { - "name": "set", "type": "function", - "description": "Applies a new content setting rule.", + "name": "callback", "parameters": [ { - "name": "details", - "type": "object", - "properties": { - "primaryPattern": { - "type": "string", - "description": "The pattern for the primary URL. For details on the format of a pattern, see Content Setting Patterns." - }, - "secondaryPattern": { - "type": "string", - "description": "The pattern for the secondary URL. Defaults to matching all URLs. For details on the format of a pattern, see Content Setting Patterns.", - "optional": true - }, - "resourceIdentifier": { - "$ref": "ResourceIdentifier", - "optional": true, - "description": "The resource identifier for the content type." - }, - "setting": { - "type": "any", - "description": "The setting applied by this rule. See the description of the individual ContentSetting objects for the possible values." - }, - "scope": { - "$ref": "Scope", - "optional": true, - "description": "Where to set the setting (default: regular)." - } - } - }, + "name": "controlType", + "type": "string" + } + ] + } + ] + }, + { + "name": "setHTTPSEverywhereControlType", + "type": "function", + "description": "Set httpse control type for a url", + "parameters": [ + { + "name": "controlType", + "type": "string" + }, + { + "name": "url", + "type": "string" + } + ] + }, + { + "name": "getHTTPSEverywhereControlType", + "type": "function", + "description": "Get httpse control type for a url", + "parameters": [ + { + "name": "url", + "type": "string" + }, + { + "type": "function", + "name": "callback", + "parameters": [ { - "type": "function", - "name": "callback", - "optional": true, - "parameters": [] + "name": "controlType", + "type": "string" } ] } ] }, { - "id": "JavascriptContentSetting", - "type": "string", - "enum": ["allow", "block"] + "name": "setNoScriptControlType", + "type": "function", + "description": "Set noscript control type for a url", + "parameters": [ + { + "name": "controlType", + "type": "string" + }, + { + "name": "url", + "type": "string" + } + ] }, { - "id": "PluginsContentSetting", - "type": "string", - "enum": ["allow", "block", "detect_important_content"] - } - ], - "properties": { - "javascript": { - "$ref": "ContentSetting", - "description": "Whether to run JavaScript. One of
allow: Run JavaScript,
block: Don't run JavaScript.
Default is allow.
The primary URL is the URL of the top-level frame. The secondary URL is not used.", - "value": [ - "javascript", - {"$ref":"JavascriptContentSetting"} + "name": "getNoScriptControlType", + "type": "function", + "description": "Get noscript control type for a url", + "parameters": [ + { + "name": "url", + "type": "string" + }, + { + "type": "function", + "name": "callback", + "parameters": [ + { + "name": "controlType", + "type": "string" + } + ] + } ] }, - "plugins": { - "$ref": "ContentSetting", - "description": "Whether to run plugins. One of
allow: Run plugins automatically,
block: Don't run plugins automatically,
detect_important_content: Only run automatically those plugins that are detected as the website's main content.
The primary URL is the URL of the top-level frame. The secondary URL is not used.", - "value": [ - "plugins", - {"$ref":"PluginsContentSetting"} + { + "name": "allowScriptsOnce", + "type": "function", + "description": "Allow scripts from a list of origins until next reload", + "parameters": [ + { + "name": "origins", + "type": "array", + "items": {"type": "string"} + }, + { + "name": "tabID", + "type": "integer" + }, + { + "type": "function", + "name": "callback", + "optional": true, + "parameters": [] + } ] } - } + ] } ] diff --git a/components/brave_extension/extension/brave_extension/background.ts b/components/brave_extension/extension/brave_extension/background.ts index e70b64834d2..35ee4f1de77 100644 --- a/components/brave_extension/extension/brave_extension/background.ts +++ b/components/brave_extension/extension/brave_extension/background.ts @@ -26,14 +26,12 @@ promisifyAll(chrome, [ 'tabs', 'windows' ]) + promisifyAll(chrome.storage, [ 'local' ]) -promisifyAll(chrome.braveShields, [ - 'javascript', - 'plugins' -]) +bluebird.promisifyAll(chrome.braveShields, { promisifier }) require('./background/api') require('./background/events') diff --git a/components/brave_extension/extension/brave_extension/background/api/shieldsAPI.ts b/components/brave_extension/extension/brave_extension/background/api/shieldsAPI.ts index 06660df48f8..4f73fec4a32 100644 --- a/components/brave_extension/extension/brave_extension/background/api/shieldsAPI.ts +++ b/components/brave_extension/extension/brave_extension/background/api/shieldsAPI.ts @@ -4,8 +4,6 @@ import { ShieldDetails } from '../../types/actions/shieldsPanelActions' import { BlockOptions } from '../../types/other/blockTypes' -import * as resourceIdentifiers from '../../constants/resourceIdentifiers' -import { isHttpOrHttps, hasPortNumber } from '../../helpers/urlUtils' import actions from '../actions/shieldsPanelActions' import * as SettingsPrivate from '../../../../../common/settingsPrivate' @@ -24,31 +22,25 @@ export const getShieldSettingsForTabData = (tabData?: chrome.tabs.Tab) => { const hostname = url.hostname return Promise.all([ - chrome.braveShields.plugins.getAsync({ primaryUrl: origin, resourceIdentifier: { id: resourceIdentifiers.RESOURCE_IDENTIFIER_BRAVE_SHIELDS } }), - chrome.braveShields.plugins.getAsync({ primaryUrl: origin, resourceIdentifier: { id: resourceIdentifiers.RESOURCE_IDENTIFIER_ADS } }), - chrome.braveShields.plugins.getAsync({ primaryUrl: origin, resourceIdentifier: { id: resourceIdentifiers.RESOURCE_IDENTIFIER_TRACKERS } }), - chrome.braveShields.plugins.getAsync({ primaryUrl: origin, resourceIdentifier: { id: resourceIdentifiers.RESOURCE_IDENTIFIER_HTTP_UPGRADABLE_RESOURCES } }), - chrome.braveShields.javascript.getAsync({ primaryUrl: origin }), - chrome.braveShields.plugins.getAsync({ primaryUrl: origin, resourceIdentifier: { id: resourceIdentifiers.RESOURCE_IDENTIFIER_FINGERPRINTING } }), - chrome.braveShields.plugins.getAsync({ primaryUrl: origin, secondaryUrl: 'https://firstParty/*', resourceIdentifier: { id: resourceIdentifiers.RESOURCE_IDENTIFIER_FINGERPRINTING } }), - chrome.braveShields.plugins.getAsync({ primaryUrl: origin, resourceIdentifier: { id: resourceIdentifiers.RESOURCE_IDENTIFIER_COOKIES } }), - chrome.braveShields.plugins.getAsync({ primaryUrl: origin, secondaryUrl: 'https://firstParty/', resourceIdentifier: { id: resourceIdentifiers.RESOURCE_IDENTIFIER_COOKIES } }) + chrome.braveShields.getBraveShieldsControlTypeAsync(tabData.url), + chrome.braveShields.getAdControlTypeAsync(tabData.url), + chrome.braveShields.getHTTPSEverywhereControlTypeAsync(tabData.url), + chrome.braveShields.getNoScriptControlTypeAsync(tabData.url), + chrome.braveShields.getFingerprintingControlTypeAsync(tabData.url), + chrome.braveShields.getCookieControlTypeAsync(tabData.url) ]).then((details) => { - const fingerprinting = details[5].setting !== details[6].setting ? 'block_third_party' : details[5].setting - const cookies = details[7].setting !== details[8].setting ? 'block_third_party' : details[7].setting - const braveShields = isHttpOrHttps(origin) ? details[0].setting : 'block' return { url: url.href, origin, hostname, id: tabData.id, - braveShields, - ads: details[1].setting, - trackers: details[2].setting, - httpUpgradableResources: details[3].setting, - javascript: details[4].setting, - fingerprinting, - cookies + braveShields: details[0], + ads: details[1], + trackers: details[1], + httpUpgradableResources: details[2], + javascript: details[3], + fingerprinting: details[4], + cookies: details[5] } }).catch(() => { return { @@ -66,9 +58,6 @@ export const getShieldSettingsForTabData = (tabData?: chrome.tabs.Tab) => { }) } -const getScope = () => - chrome.extension.inIncognitoContext ? 'incognito_session_only' : 'regular' - /** * Obtains specified tab data * @return a promise with the active tab data @@ -88,15 +77,6 @@ export const requestShieldPanelData = (tabId: number) => actions.shieldsPanelDataUpdated(details) }) -const getPrimaryPatternForOrigin = (origin: string) => { - // When url includes port w/o scheme, chromium parses it as an invalid port - // number. - if (hasPortNumber(origin) && isHttpOrHttps(origin)) { - return origin + '/*' - } - return origin.replace(/^(http|https):\/\//, '*://') + '/*' -} - /** * Changes the brave shields setting at origin to be allowed or blocked. * @param {string} origin the origin of the site to change the setting for @@ -104,12 +84,7 @@ const getPrimaryPatternForOrigin = (origin: string) => { * @return a promise which resolves when the setting is set */ export const setAllowBraveShields = (origin: string, setting: string) => - chrome.braveShields.plugins.setAsync({ - primaryPattern: getPrimaryPatternForOrigin(origin), - resourceIdentifier: { id: resourceIdentifiers.RESOURCE_IDENTIFIER_BRAVE_SHIELDS }, - setting, - scope: getScope() - }) + chrome.braveShields.setBraveShieldsControlTypeAsync(setting, origin) /** * Changes the ads at origin to be allowed or blocked. @@ -119,12 +94,7 @@ export const setAllowBraveShields = (origin: string, setting: string) => * @return a promise which resolves when the setting is set */ export const setAllowAds = (origin: string, setting: string) => - chrome.braveShields.plugins.setAsync({ - primaryPattern: origin + '/*', - resourceIdentifier: { id: resourceIdentifiers.RESOURCE_IDENTIFIER_ADS }, - setting, - scope: getScope() - }) + chrome.braveShields.setAdControlTypeAsync(setting, origin) /** * Changes the trackers at origin to be allowed or blocked. @@ -134,12 +104,7 @@ export const setAllowAds = (origin: string, setting: string) => * @return a promise which resolves with the setting is set */ export const setAllowTrackers = (origin: string, setting: string) => - chrome.braveShields.plugins.setAsync({ - primaryPattern: origin + '/*', - resourceIdentifier: { id: resourceIdentifiers.RESOURCE_IDENTIFIER_TRACKERS }, - setting, - scope: getScope() - }) + chrome.braveShields.setAdControlTypeAsync(setting, origin) /** * Changes the http upgrdabable resources to be allows as is or blocked. @@ -147,15 +112,8 @@ export const setAllowTrackers = (origin: string, setting: string) => * @param {string} origin the origin of the site to change the setting for * @return a promise which resolves when the setting is set */ -export const setAllowHTTPUpgradableResources = (origin: string, setting: BlockOptions) => { - const primaryPattern = getPrimaryPatternForOrigin(origin) - return chrome.braveShields.plugins.setAsync({ - primaryPattern, - resourceIdentifier: { id: resourceIdentifiers.RESOURCE_IDENTIFIER_HTTP_UPGRADABLE_RESOURCES }, - setting, - scope: getScope() - }) -} +export const setAllowHTTPUpgradableResources = (origin: string, setting: BlockOptions) => + chrome.braveShields.setHTTPSEverywhereControlTypeAsync(setting, origin) /** * Changes the Javascript to be on (allow) or off (block) @@ -164,11 +122,7 @@ export const setAllowHTTPUpgradableResources = (origin: string, setting: BlockOp * @return a promise which resolves when the setting is set */ export const setAllowJavaScript = (origin: string, setting: string) => - chrome.braveShields.javascript.setAsync({ - primaryPattern: origin + '/*', - setting, - scope: getScope() - }) + chrome.braveShields.setNoScriptControlTypeAsync(setting, origin) /** * Changes the fingerprinting at origin to be allowed or blocked. @@ -176,61 +130,16 @@ export const setAllowJavaScript = (origin: string, setting: string) => * @param {string} origin the origin of the site to change the setting for * @return a promise which resolves with the setting is set */ -export const setAllowFingerprinting = (origin: string, setting: string) => { - const originSetting = setting === 'allow' ? 'allow' : 'block' - const firstPartySetting = setting === 'block' ? 'block' : 'allow' - - const p1 = chrome.braveShields.plugins.setAsync({ - primaryPattern: origin + '/*', - resourceIdentifier: { id: resourceIdentifiers.RESOURCE_IDENTIFIER_FINGERPRINTING }, - setting: originSetting, - scope: getScope() - }) - - const p2 = chrome.braveShields.plugins.setAsync({ - primaryPattern: origin + '/*', - secondaryPattern: 'https://firstParty/*', - resourceIdentifier: { id: resourceIdentifiers.RESOURCE_IDENTIFIER_FINGERPRINTING }, - setting: firstPartySetting, - scope: getScope() - }) - - return Promise.all([p1, p2]) -} +export const setAllowFingerprinting = (origin: string, setting: string) => + chrome.braveShields.setFingerprintingControlTypeAsync(setting, origin) /** * Changes the cookie at origin to be allowed or blocked. * @param {string} origin the origin of the site to change the setting for * @return a promise which resolves with the setting is set */ -export const setAllowCookies = (origin: string, setting: string) => { - const originSetting = setting === 'allow' ? 'allow' : 'block' - const firstPartySetting = setting === 'block' ? 'block' : 'allow' - - const p1 = chrome.braveShields.plugins.setAsync({ - primaryPattern: origin + '/*', - resourceIdentifier: { id: resourceIdentifiers.RESOURCE_IDENTIFIER_REFERRERS }, - setting: originSetting, - scope: getScope() - }) - - const p2 = chrome.braveShields.plugins.setAsync({ - primaryPattern: origin + '/*', - resourceIdentifier: { id: resourceIdentifiers.RESOURCE_IDENTIFIER_COOKIES }, - setting: originSetting, - scope: getScope() - }) - - const p3 = chrome.braveShields.plugins.setAsync({ - primaryPattern: origin + '/*', - secondaryPattern: 'https://firstParty/*', - resourceIdentifier: { id: resourceIdentifiers.RESOURCE_IDENTIFIER_COOKIES }, - setting: firstPartySetting, - scope: getScope() - }) - - return Promise.all([p1, p2, p3]) -} +export const setAllowCookies = (origin: string, setting: string) => + chrome.braveShields.setCookieControlTypeAsync(setting, origin) /** * Toggles the input value between allow and block diff --git a/components/brave_extension/extension/brave_extension/constants/resourceIdentifiers.ts b/components/brave_extension/extension/brave_extension/constants/resourceIdentifiers.ts deleted file mode 100644 index a12314b33ac..00000000000 --- a/components/brave_extension/extension/brave_extension/constants/resourceIdentifiers.ts +++ /dev/null @@ -1,11 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public -+ * License, v. 2.0. If a copy of the MPL was not distributed with this file, -+ * You can obtain one at http://mozilla.org/MPL/2.0/. */ - -export const RESOURCE_IDENTIFIER_ADS = 'ads' -export const RESOURCE_IDENTIFIER_TRACKERS = 'trackers' -export const RESOURCE_IDENTIFIER_HTTP_UPGRADABLE_RESOURCES = 'httpUpgradableResources' -export const RESOURCE_IDENTIFIER_BRAVE_SHIELDS = 'braveShields' -export const RESOURCE_IDENTIFIER_FINGERPRINTING = 'fingerprinting' -export const RESOURCE_IDENTIFIER_COOKIES = 'cookies' -export const RESOURCE_IDENTIFIER_REFERRERS = 'referrers' diff --git a/components/brave_extension/extension/brave_extension/helpers/urlUtils.ts b/components/brave_extension/extension/brave_extension/helpers/urlUtils.ts index d0e73bad342..68ca2080e85 100644 --- a/components/brave_extension/extension/brave_extension/helpers/urlUtils.ts +++ b/components/brave_extension/extension/brave_extension/helpers/urlUtils.ts @@ -2,8 +2,6 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this file, * You can obtain one at http://mozilla.org/MPL/2.0/. */ -import * as urlParser from 'url' - export const isHttpOrHttps = (url?: string) => { if (!url) { return false @@ -11,10 +9,6 @@ export const isHttpOrHttps = (url?: string) => { return /^https?:/i.test(url) } -export const hasPortNumber = (url: string) => { - return typeof urlParser.parse(url).port === 'string' -} - /** * Get the URL origin via Web API * @param {string} url - The URL to get the origin from diff --git a/components/brave_extension/extension/brave_extension/types/constants/resourceIdentifiers.ts b/components/brave_extension/extension/brave_extension/types/constants/resourceIdentifiers.ts deleted file mode 100644 index 11a1a9e5925..00000000000 --- a/components/brave_extension/extension/brave_extension/types/constants/resourceIdentifiers.ts +++ /dev/null @@ -1,15 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public -+ * License, v. 2.0. If a copy of the MPL was not distributed with this file, -+ * You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. */ - -import * as types from '../../constants/resourceIdentifiers' - -export type RESOURCE_IDENTIFIER_ADS = typeof types.RESOURCE_IDENTIFIER_ADS -export type RESOURCE_IDENTIFIER_TRACKERS = typeof types.RESOURCE_IDENTIFIER_TRACKERS -export type RESOURCE_IDENTIFIER_HTTP_UPGRADABLE_RESOURCES = typeof types.RESOURCE_IDENTIFIER_HTTP_UPGRADABLE_RESOURCES -export type RESOURCE_IDENTIFIER_FINGERPRINTING = typeof types.RESOURCE_IDENTIFIER_FINGERPRINTING -export type RESOURCE_IDENTIFIER_COOKIES = typeof types.RESOURCE_IDENTIFIER_COOKIES diff --git a/components/brave_shields/browser/brave_shields_util.cc b/components/brave_shields/browser/brave_shields_util.cc index 9f6cc0e3c43..364b7c13884 100644 --- a/components/brave_shields/browser/brave_shields_util.cc +++ b/components/brave_shields/browser/brave_shields_util.cc @@ -12,6 +12,7 @@ #include "brave/common/shield_exceptions.h" #include "brave/components/brave_shields/browser/brave_shields_web_contents_observer.h" #include "brave/components/brave_shields/browser/referrer_whitelist_service.h" +#include "brave/components/brave_shields/common/brave_shield_constants.h" #include "brave/components/content_settings/core/browser/content_settings_util.h" #include "chrome/browser/content_settings/host_content_settings_map_factory.h" #include "chrome/browser/profiles/profile_io_data.h" @@ -34,6 +35,262 @@ using net::URLRequest; namespace brave_shields { +namespace { + +ContentSetting GetDefaultAllowFromControlType(ControlType type) { + if (type == ControlType::DEFAULT) + return CONTENT_SETTING_DEFAULT; + + return type == ControlType::BLOCK ? CONTENT_SETTING_BLOCK + : CONTENT_SETTING_ALLOW; +} + +ContentSetting GetDefaultBlockFromControlType(ControlType type) { + if (type == ControlType::DEFAULT) + return CONTENT_SETTING_DEFAULT; + + return type == ControlType::ALLOW ? CONTENT_SETTING_ALLOW + : CONTENT_SETTING_BLOCK; +} + +} // namespace + +ContentSettingsPattern GetPatternFromURL(const GURL& url, + bool scheme_wildcard) { + DCHECK(url.is_empty() ? url.possibly_invalid_spec() == "" : url.is_valid()); + if (url.is_empty() && url.possibly_invalid_spec() == "") + return ContentSettingsPattern::Wildcard(); + + return scheme_wildcard && !url.has_port() + ? ContentSettingsPattern::FromString("*://" + url.host() + "/*") + : ContentSettingsPattern::FromString(url.GetOrigin().spec() + "/*"); +} + +std::string ControlTypeToString(ControlType type) { + switch (type) { + case ControlType::ALLOW: + return "allow"; + case ControlType::BLOCK: + return "block"; + case ControlType::BLOCK_THIRD_PARTY: + return "block_third_party"; + case ControlType::DEFAULT: + return "default"; + default: + NOTREACHED(); + return "invalid"; + } +} + +ControlType ControlTypeFromString(const std::string& string) { + if (string == "allow") { + return ControlType::ALLOW; + } else if (string == "block") { + return ControlType::BLOCK; + } else if (string == "block_third_party") { + return ControlType::BLOCK_THIRD_PARTY; + } else if (string == "default") { + return ControlType::DEFAULT; + } else { + NOTREACHED(); + return ControlType::INVALID; + } +} + +void SetBraveShieldsControlType(Profile* profile, + ControlType type, + const GURL& url) { + DCHECK(type != ControlType::BLOCK_THIRD_PARTY); + + if (url.is_valid() && !url.SchemeIsHTTPOrHTTPS()) + return; + + auto primary_pattern = GetPatternFromURL(url, true); + + if (!primary_pattern.IsValid()) + return; + + HostContentSettingsMapFactory::GetForProfile(profile) + ->SetContentSettingCustomScope( + primary_pattern, ContentSettingsPattern::Wildcard(), + CONTENT_SETTINGS_TYPE_PLUGINS, kBraveShields, + GetDefaultAllowFromControlType(type)); +} + +ControlType GetBraveShieldsControlType(Profile* profile, const GURL& url) { + if (url.is_valid() && !url.SchemeIsHTTPOrHTTPS()) + return ControlType::BLOCK; + + ContentSetting setting = + HostContentSettingsMapFactory::GetForProfile(profile)->GetContentSetting( + url, GURL(), CONTENT_SETTINGS_TYPE_PLUGINS, kBraveShields); + + return setting == CONTENT_SETTING_BLOCK ? ControlType::BLOCK + : ControlType::ALLOW; +} + +void SetAdControlType(Profile* profile, ControlType type, const GURL& url) { + DCHECK(type != ControlType::BLOCK_THIRD_PARTY); + auto primary_pattern = GetPatternFromURL(url); + + if (!primary_pattern.IsValid()) + return; + + HostContentSettingsMapFactory::GetForProfile(profile) + ->SetContentSettingCustomScope(primary_pattern, + ContentSettingsPattern::Wildcard(), + CONTENT_SETTINGS_TYPE_PLUGINS, kAds, + GetDefaultBlockFromControlType(type)); + + HostContentSettingsMapFactory::GetForProfile(profile) + ->SetContentSettingCustomScope(primary_pattern, + ContentSettingsPattern::Wildcard(), + CONTENT_SETTINGS_TYPE_PLUGINS, kTrackers, + GetDefaultBlockFromControlType(type)); +} + +ControlType GetAdControlType(Profile* profile, const GURL& url) { + ContentSetting setting = + HostContentSettingsMapFactory::GetForProfile(profile)->GetContentSetting( + url, GURL(), CONTENT_SETTINGS_TYPE_PLUGINS, kAds); + + return setting == CONTENT_SETTING_ALLOW ? ControlType::ALLOW + : ControlType::BLOCK; +} + +void SetCookieControlType(Profile* profile, ControlType type, const GURL& url) { + auto primary_pattern = GetPatternFromURL(url); + + if (!primary_pattern.IsValid()) + return; + + auto* map = HostContentSettingsMapFactory::GetForProfile(profile); + map->SetContentSettingCustomScope(primary_pattern, + ContentSettingsPattern::Wildcard(), + CONTENT_SETTINGS_TYPE_PLUGINS, kReferrers, + GetDefaultBlockFromControlType(type)); + + map->SetContentSettingCustomScope(primary_pattern, + ContentSettingsPattern::Wildcard(), + CONTENT_SETTINGS_TYPE_PLUGINS, kCookies, + GetDefaultBlockFromControlType(type)); + + map->SetContentSettingCustomScope( + primary_pattern, + ContentSettingsPattern::FromString("https://firstParty/*"), + CONTENT_SETTINGS_TYPE_PLUGINS, kCookies, + GetDefaultAllowFromControlType(type)); +} + +ControlType GetCookieControlType(Profile* profile, const GURL& url) { + ContentSetting setting = + HostContentSettingsMapFactory::GetForProfile(profile)->GetContentSetting( + url, GURL(), CONTENT_SETTINGS_TYPE_PLUGINS, kCookies); + + ContentSetting fp_setting = + HostContentSettingsMapFactory::GetForProfile(profile)->GetContentSetting( + url, GURL("https://firstParty/"), CONTENT_SETTINGS_TYPE_PLUGINS, + kCookies); + + if (setting == CONTENT_SETTING_ALLOW) { + return ControlType::ALLOW; + } else if (fp_setting != CONTENT_SETTING_BLOCK) { + return ControlType::BLOCK_THIRD_PARTY; + } else { + return ControlType::BLOCK; + } +} + +void SetFingerprintingControlType(Profile* profile, + ControlType type, + const GURL& url) { + auto primary_pattern = GetPatternFromURL(url); + + if (!primary_pattern.IsValid()) + return; + + auto* map = HostContentSettingsMapFactory::GetForProfile(profile); + map->SetContentSettingCustomScope( + primary_pattern, ContentSettingsPattern::Wildcard(), + CONTENT_SETTINGS_TYPE_PLUGINS, kFingerprinting, + GetDefaultBlockFromControlType(type)); + + map->SetContentSettingCustomScope( + primary_pattern, + ContentSettingsPattern::FromString("https://firstParty/*"), + CONTENT_SETTINGS_TYPE_PLUGINS, kFingerprinting, + GetDefaultAllowFromControlType(type)); +} + +ControlType GetFingerprintingControlType(Profile* profile, const GURL& url) { + auto* map = HostContentSettingsMapFactory::GetForProfile(profile); + + ContentSetting setting = map->GetContentSetting( + url, GURL(), CONTENT_SETTINGS_TYPE_PLUGINS, kFingerprinting); + ContentSetting fp_setting = + map->GetContentSetting(url, GURL("https://firstParty/"), + CONTENT_SETTINGS_TYPE_PLUGINS, kFingerprinting); + + if (setting != fp_setting || setting == CONTENT_SETTING_DEFAULT) { + return ControlType::BLOCK_THIRD_PARTY; + } else { + return setting == CONTENT_SETTING_ALLOW ? ControlType::ALLOW + : ControlType::BLOCK; + } +} + +void SetHTTPSEverywhereControlType(Profile* profile, + ControlType type, + const GURL& url) { + DCHECK(type != ControlType::BLOCK_THIRD_PARTY); + auto primary_pattern = GetPatternFromURL(url, true); + + if (!primary_pattern.IsValid()) + return; + + HostContentSettingsMapFactory::GetForProfile(profile) + ->SetContentSettingCustomScope( + primary_pattern, ContentSettingsPattern::Wildcard(), + CONTENT_SETTINGS_TYPE_PLUGINS, kHTTPUpgradableResources, + type == ControlType::ALLOW ? CONTENT_SETTING_ALLOW + : CONTENT_SETTING_BLOCK); +} + +ControlType GetHTTPSEverywhereControlType(Profile* profile, const GURL& url) { + ContentSetting setting = + HostContentSettingsMapFactory::GetForProfile(profile)->GetContentSetting( + url, GURL(), CONTENT_SETTINGS_TYPE_PLUGINS, kHTTPUpgradableResources); + + return setting == CONTENT_SETTING_ALLOW ? ControlType::ALLOW + : ControlType::BLOCK; +} + +void SetNoScriptControlType(Profile* profile, + ControlType type, + const GURL& url) { + DCHECK(type != ControlType::BLOCK_THIRD_PARTY); + auto primary_pattern = GetPatternFromURL(url); + + if (!primary_pattern.IsValid()) + return; + + HostContentSettingsMapFactory::GetForProfile(profile) + ->SetContentSettingCustomScope( + primary_pattern, ContentSettingsPattern::Wildcard(), + CONTENT_SETTINGS_TYPE_JAVASCRIPT, "", + type == ControlType::ALLOW ? CONTENT_SETTING_ALLOW + : CONTENT_SETTING_BLOCK); +} + +ControlType GetNoScriptControlType(Profile* profile, const GURL& url) { + ContentSetting setting = + HostContentSettingsMapFactory::GetForProfile(profile)->GetContentSetting( + url, GURL(), CONTENT_SETTINGS_TYPE_JAVASCRIPT, ""); + + return setting == CONTENT_SETTING_ALLOW ? ControlType::ALLOW + : ControlType::BLOCK; +} + bool IsAllowContentSettingFromIO(const net::URLRequest* request, const GURL& primary_url, const GURL& secondary_url, @@ -61,11 +318,8 @@ bool IsAllowContentSettingsForProfile(Profile* profile, DCHECK_CURRENTLY_ON(BrowserThread::UI); DCHECK(profile); return content_settings::IsAllowContentSetting( - HostContentSettingsMapFactory::GetForProfile(profile), - primary_url, - secondary_url, - setting_type, - resource_identifier); + HostContentSettingsMapFactory::GetForProfile(profile), primary_url, + secondary_url, setting_type, resource_identifier); } bool IsAllowContentSettingWithIOData(ProfileIOData* io_data, @@ -78,11 +332,8 @@ bool IsAllowContentSettingWithIOData(ProfileIOData* io_data, resource_identifier, primary_url, secondary_url); } return content_settings::IsAllowContentSetting( - io_data->GetHostContentSettingsMap(), - primary_url, - secondary_url, - setting_type, - resource_identifier); + io_data->GetHostContentSettingsMap(), primary_url, secondary_url, + setting_type, resource_identifier); } void GetRenderFrameInfo(const URLRequest* request, @@ -140,7 +391,7 @@ bool ShouldSetReferrer(bool allow_referrers, // Whitelisted referrers shoud never set the referrer (g_brave_browser_process && g_brave_browser_process->referrer_whitelist_service()->IsWhitelisted( - tab_origin, target_url.GetOrigin()))) { + tab_origin, target_url.GetOrigin()))) { return false; } *output_referrer = Referrer::SanitizeForRequest( diff --git a/components/brave_shields/browser/brave_shields_util.h b/components/brave_shields/browser/brave_shields_util.h index 3a73f10dae6..eab6be22273 100644 --- a/components/brave_shields/browser/brave_shields_util.h +++ b/components/brave_shields/browser/brave_shields_util.h @@ -9,6 +9,7 @@ #include #include +#include "components/content_settings/core/common/content_settings_pattern.h" #include "components/content_settings/core/common/content_settings_types.h" #include "services/network/public/mojom/referrer_policy.mojom.h" @@ -27,6 +28,39 @@ class ProfileIOData; namespace brave_shields { +enum ControlType { ALLOW = 0, BLOCK, BLOCK_THIRD_PARTY, DEFAULT, INVALID }; + +ContentSettingsPattern GetPatternFromURL(const GURL& url, + bool scheme_wildcard = false); +std::string ControlTypeToString(ControlType type); +ControlType ControlTypeFromString(const std::string& string); + +void SetBraveShieldsControlType(Profile* profile, + ControlType type, + const GURL& url); +ControlType GetBraveShieldsControlType(Profile* profile, const GURL& url); + +void SetAdControlType(Profile* profile, ControlType type, const GURL& url); +ControlType GetAdControlType(Profile* profile, const GURL& url); + +void SetCookieControlType(Profile* profile, ControlType type, const GURL& url); +ControlType GetCookieControlType(Profile* profile, const GURL& url); + +void SetFingerprintingControlType(Profile* profile, + ControlType type, + const GURL& url); +ControlType GetFingerprintingControlType(Profile* profile, const GURL& url); + +void SetHTTPSEverywhereControlType(Profile* profile, + ControlType type, + const GURL& url); +ControlType GetHTTPSEverywhereControlType(Profile* profile, const GURL& url); + +void SetNoScriptControlType(Profile* profile, + ControlType type, + const GURL& url); +ControlType GetNoScriptControlType(Profile* profile, const GURL& url); + bool IsAllowContentSettingWithIOData(ProfileIOData* io_data, const GURL& primary_url, const GURL& secondary_url, diff --git a/components/brave_shields/browser/brave_shields_util_unittest.cc b/components/brave_shields/browser/brave_shields_util_unittest.cc new file mode 100644 index 00000000000..6db17035099 --- /dev/null +++ b/components/brave_shields/browser/brave_shields_util_unittest.cc @@ -0,0 +1,1197 @@ +/* Copyright (c) 2019 The Brave Authors. All rights reserved. + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this file, + * You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#include + +#include "base/macros.h" +#include "brave/components/brave_shields/browser/brave_shields_util.h" +#include "brave/components/brave_shields/common/brave_shield_constants.h" +#include "build/build_config.h" +#include "chrome/browser/content_settings/host_content_settings_map_factory.h" +#include "chrome/test/base/testing_profile.h" +#include "components/content_settings/core/browser/host_content_settings_map.h" +#include "components/content_settings/core/common/content_settings_types.h" +#include "content/public/test/test_browser_thread_bundle.h" +#include "testing/gtest/include/gtest/gtest.h" + +using brave_shields::ControlType; +using brave_shields::ControlTypeFromString; +using brave_shields::ControlTypeToString; +using brave_shields::GetPatternFromURL; + +class BraveShieldsUtilTest : public testing::Test { + public: + BraveShieldsUtilTest() = default; + ~BraveShieldsUtilTest() override = default; + + void SetUp() override { profile_ = std::make_unique(); } + + TestingProfile* profile() { return profile_.get(); } + + private: + content::TestBrowserThreadBundle test_browser_thread_bundle_; + std::unique_ptr profile_; + + DISALLOW_COPY_AND_ASSIGN(BraveShieldsUtilTest); +}; + +TEST_F(BraveShieldsUtilTest, GetPatternFromURL) { + // wildcard + auto pattern = GetPatternFromURL(GURL()); + EXPECT_EQ(ContentSettingsPattern::Wildcard(), pattern); + + // no scheme wildcard + pattern = GetPatternFromURL(GURL("http://brave.com")); + EXPECT_TRUE(pattern.Matches(GURL("http://brave.com"))); + EXPECT_TRUE(pattern.Matches(GURL("http://brave.com/path1"))); + EXPECT_TRUE(pattern.Matches(GURL("http://brave.com/path2"))); + EXPECT_FALSE(pattern.Matches(GURL("https://brave.com"))); + EXPECT_FALSE(pattern.Matches(GURL("http://subdomain.brave.com"))); + EXPECT_FALSE(pattern.Matches(GURL("http://brave2.com"))); + + pattern = GetPatternFromURL(GURL("http://brave.com/path1")); + EXPECT_TRUE(pattern.Matches(GURL("http://brave.com"))); + EXPECT_TRUE(pattern.Matches(GURL("http://brave.com/path1"))); + EXPECT_TRUE(pattern.Matches(GURL("http://brave.com/path2"))); + EXPECT_FALSE(pattern.Matches(GURL("https://brave.com"))); + EXPECT_FALSE(pattern.Matches(GURL("http://subdomain.brave.com"))); + EXPECT_FALSE(pattern.Matches(GURL("http://brave2.com"))); + + // with scheme wildcard + pattern = GetPatternFromURL(GURL("http://brave.com"), true); + EXPECT_TRUE(pattern.Matches(GURL("http://brave.com"))); + EXPECT_TRUE(pattern.Matches(GURL("http://brave.com/path1"))); + EXPECT_TRUE(pattern.Matches(GURL("http://brave.com/path2"))); + EXPECT_TRUE(pattern.Matches(GURL("https://brave.com"))); + EXPECT_FALSE(pattern.Matches(GURL("http://subdomain.brave.com"))); + EXPECT_FALSE(pattern.Matches(GURL("http://brave2.com"))); + + // with port + pattern = GetPatternFromURL(GURL("http://brave.com:8080")); + EXPECT_TRUE(pattern.Matches(GURL("http://brave.com:8080"))); + EXPECT_TRUE(pattern.Matches(GURL("http://brave.com:8080/path1"))); + EXPECT_TRUE(pattern.Matches(GURL("http://brave.com:8080/path2"))); + EXPECT_FALSE(pattern.Matches(GURL("https://brave.com:8080"))); + EXPECT_FALSE(pattern.Matches(GURL("http://brave.com"))); + EXPECT_FALSE(pattern.Matches(GURL("https://brave.com"))); + EXPECT_FALSE(pattern.Matches(GURL("http://subdomain.brave.com"))); + EXPECT_FALSE(pattern.Matches(GURL("http://brave2.com"))); + + // with port and scheme wildcard + // scheme wildcard with explicit port is not a valid pattern so this is + // identical to "with port" + pattern = GetPatternFromURL(GURL("http://brave.com:8080"), true); + EXPECT_TRUE(pattern.Matches(GURL("http://brave.com:8080"))); + EXPECT_TRUE(pattern.Matches(GURL("http://brave.com:8080/path1"))); + EXPECT_TRUE(pattern.Matches(GURL("http://brave.com:8080/path2"))); + EXPECT_FALSE(pattern.Matches(GURL("https://brave.com:8080"))); + EXPECT_FALSE(pattern.Matches(GURL("http://brave.com"))); + EXPECT_FALSE(pattern.Matches(GURL("https://brave.com"))); + EXPECT_FALSE(pattern.Matches(GURL("http://subdomain.brave.com"))); + EXPECT_FALSE(pattern.Matches(GURL("http://brave2.com:8080"))); +} + +TEST_F(BraveShieldsUtilTest, ControlTypeToString) { + EXPECT_EQ("block", ControlTypeToString(ControlType::BLOCK)); + EXPECT_EQ("allow", ControlTypeToString(ControlType::ALLOW)); + EXPECT_EQ("block_third_party", + ControlTypeToString(ControlType::BLOCK_THIRD_PARTY)); +} + +TEST_F(BraveShieldsUtilTest, ControlTypeFromString) { + EXPECT_EQ(ControlType::BLOCK, ControlTypeFromString("block")); + EXPECT_EQ(ControlType::ALLOW, ControlTypeFromString("allow")); + EXPECT_EQ(ControlType::BLOCK_THIRD_PARTY, + ControlTypeFromString("block_third_party")); +} + +/* BRAVE_SHIELDS CONTROL */ +TEST_F(BraveShieldsUtilTest, SetBraveShieldsControlType_Default) { + auto* map = HostContentSettingsMapFactory::GetForProfile(profile()); + // settings should be default + auto setting = + map->GetContentSetting(GURL(), GURL(), CONTENT_SETTINGS_TYPE_PLUGINS, + brave_shields::kBraveShields); + EXPECT_EQ(CONTENT_SETTING_DEFAULT, setting); + setting = map->GetContentSetting(GURL("http://brave.com"), GURL(), + CONTENT_SETTINGS_TYPE_PLUGINS, + brave_shields::kBraveShields); + EXPECT_EQ(CONTENT_SETTING_DEFAULT, setting); + + /* ALLOW */ + brave_shields::SetBraveShieldsControlType(profile(), ControlType::ALLOW, + GURL()); + setting = + map->GetContentSetting(GURL(), GURL(), CONTENT_SETTINGS_TYPE_PLUGINS, + brave_shields::kBraveShields); + EXPECT_EQ(CONTENT_SETTING_ALLOW, setting); + + // override should apply to all origins + setting = map->GetContentSetting(GURL("http://brave.com"), GURL(), + CONTENT_SETTINGS_TYPE_PLUGINS, + brave_shields::kBraveShields); + EXPECT_EQ(CONTENT_SETTING_ALLOW, setting); + + /* BLOCK */ + brave_shields::SetBraveShieldsControlType(profile(), ControlType::BLOCK, + GURL()); + setting = + map->GetContentSetting(GURL(), GURL(), CONTENT_SETTINGS_TYPE_PLUGINS, + brave_shields::kBraveShields); + EXPECT_EQ(CONTENT_SETTING_BLOCK, setting); + + // override should apply to all origins + setting = map->GetContentSetting(GURL("http://brave.com"), GURL(), + CONTENT_SETTINGS_TYPE_PLUGINS, + brave_shields::kBraveShields); + EXPECT_EQ(CONTENT_SETTING_BLOCK, setting); + + /* DEFAULT */ + brave_shields::SetBraveShieldsControlType(profile(), ControlType::DEFAULT, + GURL()); + setting = + map->GetContentSetting(GURL(), GURL(), CONTENT_SETTINGS_TYPE_PLUGINS, + brave_shields::kBraveShields); + EXPECT_EQ(CONTENT_SETTING_DEFAULT, setting); + + // override should apply to all origins + setting = map->GetContentSetting(GURL("http://brave.com"), GURL(), + CONTENT_SETTINGS_TYPE_PLUGINS, + brave_shields::kBraveShields); + EXPECT_EQ(CONTENT_SETTING_DEFAULT, setting); +} + +TEST_F(BraveShieldsUtilTest, SetBraveShieldsControlType_ForOrigin) { + auto* map = HostContentSettingsMapFactory::GetForProfile(profile()); + + brave_shields::SetBraveShieldsControlType(profile(), ControlType::ALLOW, + GURL("http://brave.com")); + // setting should apply to origin + auto setting = map->GetContentSetting(GURL("http://brave.com"), GURL(), + CONTENT_SETTINGS_TYPE_PLUGINS, + brave_shields::kBraveShields); + EXPECT_EQ(CONTENT_SETTING_ALLOW, setting); + + // setting should apply to different scheme + setting = map->GetContentSetting(GURL("https://brave.com"), GURL(), + CONTENT_SETTINGS_TYPE_PLUGINS, + brave_shields::kBraveShields); + EXPECT_EQ(CONTENT_SETTING_ALLOW, setting); + + // setting should not apply to default + setting = + map->GetContentSetting(GURL(), GURL(), CONTENT_SETTINGS_TYPE_PLUGINS, + brave_shields::kBraveShields); + EXPECT_EQ(CONTENT_SETTING_DEFAULT, setting); +} + +TEST_F(BraveShieldsUtilTest, SetBraveShieldsControlType_IsNotHttpHttps) { + auto setting = brave_shields::GetBraveShieldsControlType( + profile(), GURL("chrome://preferences")); + EXPECT_EQ(ControlType::BLOCK, setting); + brave_shields::SetBraveShieldsControlType(profile(), ControlType::ALLOW, + GURL("chrome://preferences")); + setting = brave_shields::GetBraveShieldsControlType( + profile(), GURL("chrome://preferences")); + EXPECT_EQ(ControlType::BLOCK, setting); + + setting = + brave_shields::GetBraveShieldsControlType(profile(), GURL("about:blank")); + EXPECT_EQ(ControlType::BLOCK, setting); + brave_shields::SetBraveShieldsControlType(profile(), ControlType::ALLOW, + GURL("about:blank")); + setting = brave_shields::GetBraveShieldsControlType( + profile(), GURL("about:blank")); + EXPECT_EQ(ControlType::BLOCK, setting); +} + +TEST_F(BraveShieldsUtilTest, GetBraveShieldsControlType_Default) { + auto* map = HostContentSettingsMapFactory::GetForProfile(profile()); + + auto setting = brave_shields::GetBraveShieldsControlType(profile(), GURL()); + EXPECT_EQ(ControlType::ALLOW, setting); + + /* BLOCK */ + map->SetContentSettingCustomScope( + ContentSettingsPattern::Wildcard(), ContentSettingsPattern::Wildcard(), + CONTENT_SETTINGS_TYPE_PLUGINS, brave_shields::kBraveShields, + CONTENT_SETTING_BLOCK); + setting = brave_shields::GetBraveShieldsControlType(profile(), GURL()); + EXPECT_EQ(ControlType::BLOCK, setting); + + /* ALLOW */ + map->SetContentSettingCustomScope( + ContentSettingsPattern::Wildcard(), ContentSettingsPattern::Wildcard(), + CONTENT_SETTINGS_TYPE_PLUGINS, brave_shields::kBraveShields, + CONTENT_SETTING_ALLOW); + setting = brave_shields::GetBraveShieldsControlType(profile(), GURL()); + EXPECT_EQ(ControlType::ALLOW, setting); +} + +TEST_F(BraveShieldsUtilTest, GetBraveShieldsControlType_ForOrigin) { + auto* map = HostContentSettingsMapFactory::GetForProfile(profile()); + + auto setting = brave_shields::GetBraveShieldsControlType(profile(), GURL()); + EXPECT_EQ(ControlType::ALLOW, setting); + setting = brave_shields::GetBraveShieldsControlType(profile(), + GURL("http://brave.com")); + EXPECT_EQ(ControlType::ALLOW, setting); + setting = brave_shields::GetBraveShieldsControlType( + profile(), GURL("https://brave.com")); + EXPECT_EQ(ControlType::ALLOW, setting); + + /* BLOCK */ + map->SetContentSettingCustomScope( + ContentSettingsPattern::FromString("http://brave.com/*"), + ContentSettingsPattern::Wildcard(), CONTENT_SETTINGS_TYPE_PLUGINS, + brave_shields::kBraveShields, CONTENT_SETTING_BLOCK); + setting = brave_shields::GetBraveShieldsControlType( + profile(), GURL("http://brave.com/*")); + EXPECT_EQ(ControlType::BLOCK, setting); + // https in unchanged + setting = brave_shields::GetBraveShieldsControlType( + profile(), GURL("https://brave.com")); + EXPECT_EQ(ControlType::ALLOW, setting); + // default is unchanged + setting = brave_shields::GetBraveShieldsControlType(profile(), GURL()); + EXPECT_EQ(ControlType::ALLOW, setting); + + /* ALLOW */ + // change default to block + map->SetContentSettingCustomScope( + ContentSettingsPattern::Wildcard(), ContentSettingsPattern::Wildcard(), + CONTENT_SETTINGS_TYPE_PLUGINS, brave_shields::kBraveShields, + CONTENT_SETTING_BLOCK); + setting = brave_shields::GetBraveShieldsControlType(profile(), + GURL("http://brave.com")); + EXPECT_EQ(ControlType::BLOCK, setting); + setting = brave_shields::GetBraveShieldsControlType( + profile(), GURL("https://brave.com")); + EXPECT_EQ(ControlType::BLOCK, setting); + setting = brave_shields::GetBraveShieldsControlType(profile(), GURL()); + EXPECT_EQ(ControlType::BLOCK, setting); + + // set override to allow + map->SetContentSettingCustomScope( + ContentSettingsPattern::FromString("http://brave.com/*"), + ContentSettingsPattern::Wildcard(), CONTENT_SETTINGS_TYPE_PLUGINS, + brave_shields::kBraveShields, CONTENT_SETTING_ALLOW); + setting = brave_shields::GetBraveShieldsControlType(profile(), + GURL("http://brave.com")); + EXPECT_EQ(ControlType::ALLOW, setting); + + // https in unchanged + setting = brave_shields::GetBraveShieldsControlType( + profile(), GURL("https://brave.com")); + EXPECT_EQ(ControlType::BLOCK, setting); + // default is unchanged + setting = brave_shields::GetBraveShieldsControlType(profile(), GURL()); + EXPECT_EQ(ControlType::BLOCK, setting); +} + +TEST_F(BraveShieldsUtilTest, GetBraveShieldsControlType_IsNotHttpHttps) { + auto setting = brave_shields::GetBraveShieldsControlType( + profile(), GURL("chrome://preferences")); + EXPECT_EQ(ControlType::BLOCK, setting); + + setting = + brave_shields::GetBraveShieldsControlType(profile(), GURL("about:blank")); + EXPECT_EQ(ControlType::BLOCK, setting); +} + +/* AD CONTROL */ +TEST_F(BraveShieldsUtilTest, SetAdControlType_Default) { + auto* map = HostContentSettingsMapFactory::GetForProfile(profile()); + // settings should be default + auto setting = map->GetContentSetting( + GURL(), GURL(), CONTENT_SETTINGS_TYPE_PLUGINS, brave_shields::kAds); + EXPECT_EQ(CONTENT_SETTING_DEFAULT, setting); + setting = map->GetContentSetting(GURL("http://brave.com"), GURL(), + CONTENT_SETTINGS_TYPE_PLUGINS, + brave_shields::kAds); + EXPECT_EQ(CONTENT_SETTING_DEFAULT, setting); + + /* ALLOW */ + brave_shields::SetAdControlType(profile(), ControlType::ALLOW, GURL()); + setting = map->GetContentSetting( + GURL(), GURL(), CONTENT_SETTINGS_TYPE_PLUGINS, brave_shields::kAds); + EXPECT_EQ(CONTENT_SETTING_ALLOW, setting); + + // override should apply to all origins + setting = map->GetContentSetting(GURL("http://brave.com"), GURL(), + CONTENT_SETTINGS_TYPE_PLUGINS, + brave_shields::kAds); + EXPECT_EQ(CONTENT_SETTING_ALLOW, setting); + + /* BLOCK */ + brave_shields::SetAdControlType(profile(), ControlType::BLOCK, GURL()); + setting = map->GetContentSetting( + GURL(), GURL(), CONTENT_SETTINGS_TYPE_PLUGINS, brave_shields::kAds); + EXPECT_EQ(CONTENT_SETTING_BLOCK, setting); + + // override should apply to all origins + setting = map->GetContentSetting(GURL("http://brave.com"), GURL(), + CONTENT_SETTINGS_TYPE_PLUGINS, + brave_shields::kAds); + EXPECT_EQ(CONTENT_SETTING_BLOCK, setting); +} + +TEST_F(BraveShieldsUtilTest, SetAdControlType_ForOrigin) { + auto* map = HostContentSettingsMapFactory::GetForProfile(profile()); + + brave_shields::SetAdControlType(profile(), ControlType::ALLOW, + GURL("http://brave.com")); + // setting should apply to origin + auto setting = map->GetContentSetting(GURL("http://brave.com"), GURL(), + CONTENT_SETTINGS_TYPE_PLUGINS, + brave_shields::kAds); + EXPECT_EQ(CONTENT_SETTING_ALLOW, setting); + + // setting should not apply to different scheme + setting = map->GetContentSetting(GURL("https://brave.com"), GURL(), + CONTENT_SETTINGS_TYPE_PLUGINS, + brave_shields::kAds); + EXPECT_EQ(CONTENT_SETTING_DEFAULT, setting); + + // setting should not apply to default + setting = map->GetContentSetting( + GURL(), GURL(), CONTENT_SETTINGS_TYPE_PLUGINS, brave_shields::kAds); + EXPECT_EQ(CONTENT_SETTING_DEFAULT, setting); +} + +TEST_F(BraveShieldsUtilTest, GetAdControlType_Default) { + auto* map = HostContentSettingsMapFactory::GetForProfile(profile()); + + auto setting = brave_shields::GetAdControlType(profile(), GURL()); + EXPECT_EQ(ControlType::BLOCK, setting); + + /* ALLOW */ + map->SetContentSettingCustomScope(ContentSettingsPattern::Wildcard(), + ContentSettingsPattern::Wildcard(), + CONTENT_SETTINGS_TYPE_PLUGINS, + brave_shields::kAds, CONTENT_SETTING_ALLOW); + setting = brave_shields::GetAdControlType(profile(), GURL()); + EXPECT_EQ(ControlType::ALLOW, setting); + + /* BLOCK */ + map->SetContentSettingCustomScope(ContentSettingsPattern::Wildcard(), + ContentSettingsPattern::Wildcard(), + CONTENT_SETTINGS_TYPE_PLUGINS, + brave_shields::kAds, CONTENT_SETTING_BLOCK); + setting = brave_shields::GetAdControlType(profile(), GURL()); + EXPECT_EQ(ControlType::BLOCK, setting); +} + +TEST_F(BraveShieldsUtilTest, GetAdControlType_ForOrigin) { + auto* map = HostContentSettingsMapFactory::GetForProfile(profile()); + + auto setting = brave_shields::GetAdControlType(profile(), GURL()); + EXPECT_EQ(ControlType::BLOCK, setting); + setting = + brave_shields::GetAdControlType(profile(), GURL("http://brave.com")); + EXPECT_EQ(ControlType::BLOCK, setting); + setting = + brave_shields::GetAdControlType(profile(), GURL("https://brave.com")); + EXPECT_EQ(ControlType::BLOCK, setting); + + /* ALLOW */ + map->SetContentSettingCustomScope( + ContentSettingsPattern::FromString("http://brave.com/*"), + ContentSettingsPattern::Wildcard(), CONTENT_SETTINGS_TYPE_PLUGINS, + brave_shields::kAds, CONTENT_SETTING_ALLOW); + setting = + brave_shields::GetAdControlType(profile(), GURL("http://brave.com")); + EXPECT_EQ(ControlType::ALLOW, setting); + + // https in unchanged + setting = + brave_shields::GetAdControlType(profile(), GURL("https://brave.com")); + EXPECT_EQ(ControlType::BLOCK, setting); + // default is unchanged + setting = brave_shields::GetAdControlType(profile(), GURL()); + EXPECT_EQ(ControlType::BLOCK, setting); + + /* BLOCK */ + // change default to allow + map->SetContentSettingCustomScope(ContentSettingsPattern::Wildcard(), + ContentSettingsPattern::Wildcard(), + CONTENT_SETTINGS_TYPE_PLUGINS, + brave_shields::kAds, CONTENT_SETTING_ALLOW); + setting = + brave_shields::GetAdControlType(profile(), GURL("http://brave.com")); + EXPECT_EQ(ControlType::ALLOW, setting); + setting = + brave_shields::GetAdControlType(profile(), GURL("https://brave.com")); + EXPECT_EQ(ControlType::ALLOW, setting); + setting = brave_shields::GetAdControlType(profile(), GURL()); + EXPECT_EQ(ControlType::ALLOW, setting); + + // set override to block + map->SetContentSettingCustomScope( + ContentSettingsPattern::FromString("http://brave.com/*"), + ContentSettingsPattern::Wildcard(), CONTENT_SETTINGS_TYPE_PLUGINS, + brave_shields::kAds, CONTENT_SETTING_BLOCK); + setting = + brave_shields::GetAdControlType(profile(), GURL("http://brave.com/*")); + EXPECT_EQ(ControlType::BLOCK, setting); + // https in unchanged + setting = + brave_shields::GetAdControlType(profile(), GURL("https://brave.com")); + EXPECT_EQ(ControlType::ALLOW, setting); + // default is unchanged + setting = brave_shields::GetAdControlType(profile(), GURL()); + EXPECT_EQ(ControlType::ALLOW, setting); +} + +/* COOKIE CONTROL */ +TEST_F(BraveShieldsUtilTest, SetCookieControlType_Default) { + auto* map = HostContentSettingsMapFactory::GetForProfile(profile()); + // setting should be default to start with + auto setting = map->GetContentSetting( + GURL(), GURL(), CONTENT_SETTINGS_TYPE_PLUGINS, brave_shields::kCookies); + EXPECT_EQ(CONTENT_SETTING_DEFAULT, setting); + setting = map->GetContentSetting(GURL(), GURL("https://firstParty"), + CONTENT_SETTINGS_TYPE_PLUGINS, + brave_shields::kCookies); + EXPECT_EQ(CONTENT_SETTING_DEFAULT, setting); + setting = map->GetContentSetting(GURL("http://brave.com"), GURL(), + CONTENT_SETTINGS_TYPE_PLUGINS, + brave_shields::kCookies); + setting = map->GetContentSetting( + GURL("http://brave.com"), GURL("https://firstParty"), + CONTENT_SETTINGS_TYPE_PLUGINS, brave_shields::kCookies); + EXPECT_EQ(CONTENT_SETTING_DEFAULT, setting); + + /* ALLOW */ + brave_shields::SetCookieControlType(profile(), ControlType::ALLOW, GURL()); + setting = map->GetContentSetting( + GURL(), GURL(), CONTENT_SETTINGS_TYPE_PLUGINS, brave_shields::kCookies); + EXPECT_EQ(CONTENT_SETTING_ALLOW, setting); + setting = map->GetContentSetting(GURL(), GURL("https://firstParty"), + CONTENT_SETTINGS_TYPE_PLUGINS, + brave_shields::kCookies); + EXPECT_EQ(CONTENT_SETTING_ALLOW, setting); + // setting should apply to all urls + setting = map->GetContentSetting(GURL("http://brave.com"), GURL(), + CONTENT_SETTINGS_TYPE_PLUGINS, + brave_shields::kCookies); + EXPECT_EQ(CONTENT_SETTING_ALLOW, setting); + setting = map->GetContentSetting( + GURL("http://brave.com"), GURL("https://firstParty"), + CONTENT_SETTINGS_TYPE_PLUGINS, brave_shields::kCookies); + EXPECT_EQ(CONTENT_SETTING_ALLOW, setting); + + /* BLOCK */ + brave_shields::SetCookieControlType(profile(), ControlType::BLOCK, GURL()); + setting = map->GetContentSetting( + GURL(), GURL(), CONTENT_SETTINGS_TYPE_PLUGINS, brave_shields::kCookies); + EXPECT_EQ(CONTENT_SETTING_BLOCK, setting); + setting = map->GetContentSetting(GURL(), GURL("https://firstParty"), + CONTENT_SETTINGS_TYPE_PLUGINS, + brave_shields::kCookies); + EXPECT_EQ(CONTENT_SETTING_BLOCK, setting); + // setting should apply to all urls + setting = map->GetContentSetting(GURL("http://brave.com"), GURL(), + CONTENT_SETTINGS_TYPE_PLUGINS, + brave_shields::kCookies); + EXPECT_EQ(CONTENT_SETTING_BLOCK, setting); + setting = map->GetContentSetting( + GURL("http://brave.com"), GURL("https://firstParty"), + CONTENT_SETTINGS_TYPE_PLUGINS, brave_shields::kCookies); + EXPECT_EQ(CONTENT_SETTING_BLOCK, setting); + + /* BLOCK_THIRD_PARTY */ + brave_shields::SetCookieControlType(profile(), ControlType::BLOCK_THIRD_PARTY, + GURL()); + setting = map->GetContentSetting( + GURL(), GURL(), CONTENT_SETTINGS_TYPE_PLUGINS, brave_shields::kCookies); + EXPECT_EQ(CONTENT_SETTING_BLOCK, setting); + setting = map->GetContentSetting(GURL(), GURL("https://firstParty"), + CONTENT_SETTINGS_TYPE_PLUGINS, + brave_shields::kCookies); + EXPECT_EQ(CONTENT_SETTING_ALLOW, setting); + + // setting should apply to all urls + setting = map->GetContentSetting(GURL("http://brave.com"), GURL(), + CONTENT_SETTINGS_TYPE_PLUGINS, + brave_shields::kCookies); + EXPECT_EQ(CONTENT_SETTING_BLOCK, setting); + setting = map->GetContentSetting( + GURL("http://brave.com"), GURL("https://firstParty"), + CONTENT_SETTINGS_TYPE_PLUGINS, brave_shields::kCookies); + EXPECT_EQ(CONTENT_SETTING_ALLOW, setting); +} + +TEST_F(BraveShieldsUtilTest, SetCookieControlType_ForOrigin) { + auto* map = HostContentSettingsMapFactory::GetForProfile(profile()); + + brave_shields::SetCookieControlType(profile(), ControlType::ALLOW, + GURL("http://brave.com")); + // override should apply to origin + auto setting = map->GetContentSetting(GURL("http://brave.com"), GURL(), + CONTENT_SETTINGS_TYPE_PLUGINS, + brave_shields::kCookies); + setting = map->GetContentSetting( + GURL("http://brave.com"), GURL("https://firstParty"), + CONTENT_SETTINGS_TYPE_PLUGINS, brave_shields::kCookies); + EXPECT_EQ(CONTENT_SETTING_ALLOW, setting); + + // override should not apply to different scheme + setting = map->GetContentSetting(GURL("https://brave.com"), GURL(), + CONTENT_SETTINGS_TYPE_PLUGINS, + brave_shields::kCookies); + EXPECT_EQ(CONTENT_SETTING_DEFAULT, setting); + setting = map->GetContentSetting( + GURL("https://brave.com"), GURL("https://firstParty"), + CONTENT_SETTINGS_TYPE_PLUGINS, brave_shields::kCookies); + EXPECT_EQ(CONTENT_SETTING_DEFAULT, setting); + + // override should not apply to default + setting = map->GetContentSetting( + GURL(), GURL(), CONTENT_SETTINGS_TYPE_PLUGINS, brave_shields::kCookies); + EXPECT_EQ(CONTENT_SETTING_DEFAULT, setting); + // override should not apply to default + setting = map->GetContentSetting(GURL(), GURL("https://firstParty"), + CONTENT_SETTINGS_TYPE_PLUGINS, + brave_shields::kCookies); + EXPECT_EQ(CONTENT_SETTING_DEFAULT, setting); +} + +TEST_F(BraveShieldsUtilTest, GetCookieControlType_Default) { + auto* map = HostContentSettingsMapFactory::GetForProfile(profile()); + + auto setting = brave_shields::GetCookieControlType(profile(), GURL()); + EXPECT_EQ(ControlType::BLOCK_THIRD_PARTY, setting); + setting = + brave_shields::GetCookieControlType(profile(), GURL("http://brave.com")); + EXPECT_EQ(ControlType::BLOCK_THIRD_PARTY, setting); + + /* ALLOW */ + map->SetContentSettingCustomScope( + ContentSettingsPattern::Wildcard(), ContentSettingsPattern::Wildcard(), + CONTENT_SETTINGS_TYPE_PLUGINS, brave_shields::kCookies, + CONTENT_SETTING_ALLOW); + map->SetContentSettingCustomScope( + ContentSettingsPattern::Wildcard(), + ContentSettingsPattern::FromString("https://firstParty/*"), + CONTENT_SETTINGS_TYPE_PLUGINS, brave_shields::kCookies, + CONTENT_SETTING_ALLOW); + setting = brave_shields::GetCookieControlType(profile(), GURL()); + EXPECT_EQ(ControlType::ALLOW, setting); + setting = + brave_shields::GetCookieControlType(profile(), GURL("http://brave.com")); + EXPECT_EQ(ControlType::ALLOW, setting); + + /* BLOCK */ + map->SetContentSettingCustomScope( + ContentSettingsPattern::Wildcard(), ContentSettingsPattern::Wildcard(), + CONTENT_SETTINGS_TYPE_PLUGINS, brave_shields::kCookies, + CONTENT_SETTING_BLOCK); + map->SetContentSettingCustomScope( + ContentSettingsPattern::Wildcard(), + ContentSettingsPattern::FromString("https://firstParty/*"), + CONTENT_SETTINGS_TYPE_PLUGINS, brave_shields::kCookies, + CONTENT_SETTING_BLOCK); + setting = brave_shields::GetCookieControlType(profile(), GURL()); + EXPECT_EQ(ControlType::BLOCK, setting); + setting = + brave_shields::GetCookieControlType(profile(), GURL("http://brave.com")); + EXPECT_EQ(ControlType::BLOCK, setting); + + /* BLOCK_THIRD_PARTY */ + map->SetContentSettingCustomScope( + ContentSettingsPattern::Wildcard(), ContentSettingsPattern::Wildcard(), + CONTENT_SETTINGS_TYPE_PLUGINS, brave_shields::kCookies, + CONTENT_SETTING_BLOCK); + map->SetContentSettingCustomScope( + ContentSettingsPattern::Wildcard(), + ContentSettingsPattern::FromString("https://firstParty/*"), + CONTENT_SETTINGS_TYPE_PLUGINS, brave_shields::kCookies, + CONTENT_SETTING_ALLOW); + setting = brave_shields::GetCookieControlType(profile(), GURL()); + EXPECT_EQ(ControlType::BLOCK_THIRD_PARTY, setting); + setting = + brave_shields::GetCookieControlType(profile(), GURL("http://brave.com")); + EXPECT_EQ(ControlType::BLOCK_THIRD_PARTY, setting); +} + +TEST_F(BraveShieldsUtilTest, GetCookieControlType_ForOrigin) { + auto* map = HostContentSettingsMapFactory::GetForProfile(profile()); + + auto setting = + brave_shields::GetCookieControlType(profile(), GURL("http://brave.com")); + EXPECT_EQ(ControlType::BLOCK_THIRD_PARTY, setting); + + /* ALLOW */ + map->SetContentSettingCustomScope( + ContentSettingsPattern::FromString("http://brave.com/*"), + ContentSettingsPattern::Wildcard(), CONTENT_SETTINGS_TYPE_PLUGINS, + brave_shields::kCookies, CONTENT_SETTING_ALLOW); + map->SetContentSettingCustomScope( + ContentSettingsPattern::FromString("http://brave.com/*"), + ContentSettingsPattern::FromString("https://firstParty/*"), + CONTENT_SETTINGS_TYPE_PLUGINS, brave_shields::kCookies, + CONTENT_SETTING_ALLOW); + setting = + brave_shields::GetCookieControlType(profile(), GURL("http://brave.com")); + EXPECT_EQ(ControlType::ALLOW, setting); + setting = brave_shields::GetCookieControlType(profile(), GURL()); + EXPECT_EQ(ControlType::BLOCK_THIRD_PARTY, setting); + + /* BLOCK */ + map->SetContentSettingCustomScope( + ContentSettingsPattern::FromString("http://brave.com/*"), + ContentSettingsPattern::Wildcard(), CONTENT_SETTINGS_TYPE_PLUGINS, + brave_shields::kCookies, CONTENT_SETTING_BLOCK); + map->SetContentSettingCustomScope( + ContentSettingsPattern::FromString("http://brave.com/*"), + ContentSettingsPattern::FromString("https://firstParty/*"), + CONTENT_SETTINGS_TYPE_PLUGINS, brave_shields::kCookies, + CONTENT_SETTING_BLOCK); + setting = + brave_shields::GetCookieControlType(profile(), GURL("http://brave.com")); + EXPECT_EQ(ControlType::BLOCK, setting); + setting = brave_shields::GetCookieControlType(profile(), GURL()); + EXPECT_EQ(ControlType::BLOCK_THIRD_PARTY, setting); + + /* BLOCK_THIRD_PARTY */ + map->SetContentSettingCustomScope( + ContentSettingsPattern::FromString("http://brave.com/*"), + ContentSettingsPattern::Wildcard(), CONTENT_SETTINGS_TYPE_PLUGINS, + brave_shields::kCookies, CONTENT_SETTING_BLOCK); + map->SetContentSettingCustomScope( + ContentSettingsPattern::FromString("http://brave.com/*"), + ContentSettingsPattern::FromString("https://firstParty/*"), + CONTENT_SETTINGS_TYPE_PLUGINS, brave_shields::kCookies, + CONTENT_SETTING_ALLOW); + setting = + brave_shields::GetCookieControlType(profile(), GURL("http://brave.com")); + EXPECT_EQ(ControlType::BLOCK_THIRD_PARTY, setting); + setting = brave_shields::GetCookieControlType(profile(), GURL()); + EXPECT_EQ(ControlType::BLOCK_THIRD_PARTY, setting); +} + +/* FINGERPRINTING CONTROL */ +TEST_F(BraveShieldsUtilTest, SetFingerprintingControlType_Default) { + auto* map = HostContentSettingsMapFactory::GetForProfile(profile()); + // setting should be default to start with + auto setting = + map->GetContentSetting(GURL(), GURL(), CONTENT_SETTINGS_TYPE_PLUGINS, + brave_shields::kFingerprinting); + EXPECT_EQ(CONTENT_SETTING_DEFAULT, setting); + setting = map->GetContentSetting(GURL(), GURL("https://firstParty"), + CONTENT_SETTINGS_TYPE_PLUGINS, + brave_shields::kFingerprinting); + EXPECT_EQ(CONTENT_SETTING_DEFAULT, setting); + setting = map->GetContentSetting(GURL("http://brave.com"), GURL(), + CONTENT_SETTINGS_TYPE_PLUGINS, + brave_shields::kFingerprinting); + setting = map->GetContentSetting( + GURL("http://brave.com"), GURL("https://firstParty"), + CONTENT_SETTINGS_TYPE_PLUGINS, brave_shields::kFingerprinting); + EXPECT_EQ(CONTENT_SETTING_DEFAULT, setting); + + /* ALLOW */ + brave_shields::SetFingerprintingControlType(profile(), ControlType::ALLOW, + GURL()); + setting = + map->GetContentSetting(GURL(), GURL(), CONTENT_SETTINGS_TYPE_PLUGINS, + brave_shields::kFingerprinting); + EXPECT_EQ(CONTENT_SETTING_ALLOW, setting); + setting = map->GetContentSetting(GURL(), GURL("https://firstParty"), + CONTENT_SETTINGS_TYPE_PLUGINS, + brave_shields::kFingerprinting); + EXPECT_EQ(CONTENT_SETTING_ALLOW, setting); + // setting should apply to all urls + setting = map->GetContentSetting(GURL("http://brave.com"), GURL(), + CONTENT_SETTINGS_TYPE_PLUGINS, + brave_shields::kFingerprinting); + EXPECT_EQ(CONTENT_SETTING_ALLOW, setting); + setting = map->GetContentSetting( + GURL("http://brave.com"), GURL("https://firstParty"), + CONTENT_SETTINGS_TYPE_PLUGINS, brave_shields::kFingerprinting); + EXPECT_EQ(CONTENT_SETTING_ALLOW, setting); + + /* BLOCK */ + brave_shields::SetFingerprintingControlType(profile(), ControlType::BLOCK, + GURL()); + setting = + map->GetContentSetting(GURL(), GURL(), CONTENT_SETTINGS_TYPE_PLUGINS, + brave_shields::kFingerprinting); + EXPECT_EQ(CONTENT_SETTING_BLOCK, setting); + setting = map->GetContentSetting(GURL(), GURL("https://firstParty"), + CONTENT_SETTINGS_TYPE_PLUGINS, + brave_shields::kFingerprinting); + EXPECT_EQ(CONTENT_SETTING_BLOCK, setting); + // setting should apply to all urls + setting = map->GetContentSetting(GURL("http://brave.com"), GURL(), + CONTENT_SETTINGS_TYPE_PLUGINS, + brave_shields::kFingerprinting); + EXPECT_EQ(CONTENT_SETTING_BLOCK, setting); + setting = map->GetContentSetting( + GURL("http://brave.com"), GURL("https://firstParty"), + CONTENT_SETTINGS_TYPE_PLUGINS, brave_shields::kFingerprinting); + EXPECT_EQ(CONTENT_SETTING_BLOCK, setting); + + /* BLOCK_THIRD_PARTY */ + brave_shields::SetFingerprintingControlType( + profile(), ControlType::BLOCK_THIRD_PARTY, GURL()); + setting = + map->GetContentSetting(GURL(), GURL(), CONTENT_SETTINGS_TYPE_PLUGINS, + brave_shields::kFingerprinting); + EXPECT_EQ(CONTENT_SETTING_BLOCK, setting); + setting = map->GetContentSetting(GURL(), GURL("https://firstParty"), + CONTENT_SETTINGS_TYPE_PLUGINS, + brave_shields::kFingerprinting); + EXPECT_EQ(CONTENT_SETTING_ALLOW, setting); + + // setting should apply to all urls + setting = map->GetContentSetting(GURL("http://brave.com"), GURL(), + CONTENT_SETTINGS_TYPE_PLUGINS, + brave_shields::kFingerprinting); + EXPECT_EQ(CONTENT_SETTING_BLOCK, setting); + setting = map->GetContentSetting( + GURL("http://brave.com"), GURL("https://firstParty"), + CONTENT_SETTINGS_TYPE_PLUGINS, brave_shields::kFingerprinting); + EXPECT_EQ(CONTENT_SETTING_ALLOW, setting); +} + +TEST_F(BraveShieldsUtilTest, SetFingerprintingControlType_ForOrigin) { + auto* map = HostContentSettingsMapFactory::GetForProfile(profile()); + + brave_shields::SetFingerprintingControlType(profile(), ControlType::ALLOW, + GURL("http://brave.com")); + // override should apply to origin + auto setting = map->GetContentSetting(GURL("http://brave.com"), GURL(), + CONTENT_SETTINGS_TYPE_PLUGINS, + brave_shields::kFingerprinting); + setting = map->GetContentSetting( + GURL("http://brave.com"), GURL("https://firstParty"), + CONTENT_SETTINGS_TYPE_PLUGINS, brave_shields::kFingerprinting); + EXPECT_EQ(CONTENT_SETTING_ALLOW, setting); + + // override should not apply to different scheme + setting = map->GetContentSetting(GURL("https://brave.com"), GURL(), + CONTENT_SETTINGS_TYPE_PLUGINS, + brave_shields::kFingerprinting); + EXPECT_EQ(CONTENT_SETTING_DEFAULT, setting); + setting = map->GetContentSetting( + GURL("https://brave.com"), GURL("https://firstParty"), + CONTENT_SETTINGS_TYPE_PLUGINS, brave_shields::kFingerprinting); + EXPECT_EQ(CONTENT_SETTING_DEFAULT, setting); + + // override should not apply to default + setting = + map->GetContentSetting(GURL(), GURL(), CONTENT_SETTINGS_TYPE_PLUGINS, + brave_shields::kFingerprinting); + EXPECT_EQ(CONTENT_SETTING_DEFAULT, setting); + // override should not apply to default + setting = map->GetContentSetting(GURL(), GURL("https://firstParty"), + CONTENT_SETTINGS_TYPE_PLUGINS, + brave_shields::kFingerprinting); + EXPECT_EQ(CONTENT_SETTING_DEFAULT, setting); +} + +TEST_F(BraveShieldsUtilTest, GetFingerprintingControlType_Default) { + auto* map = HostContentSettingsMapFactory::GetForProfile(profile()); + + auto setting = brave_shields::GetFingerprintingControlType(profile(), GURL()); + EXPECT_EQ(ControlType::BLOCK_THIRD_PARTY, setting); + setting = brave_shields::GetFingerprintingControlType( + profile(), GURL("http://brave.com")); + EXPECT_EQ(ControlType::BLOCK_THIRD_PARTY, setting); + + /* ALLOW */ + map->SetContentSettingCustomScope( + ContentSettingsPattern::Wildcard(), ContentSettingsPattern::Wildcard(), + CONTENT_SETTINGS_TYPE_PLUGINS, brave_shields::kFingerprinting, + CONTENT_SETTING_ALLOW); + map->SetContentSettingCustomScope( + ContentSettingsPattern::Wildcard(), + ContentSettingsPattern::FromString("https://firstParty/*"), + CONTENT_SETTINGS_TYPE_PLUGINS, brave_shields::kFingerprinting, + CONTENT_SETTING_ALLOW); + setting = brave_shields::GetFingerprintingControlType(profile(), GURL()); + EXPECT_EQ(ControlType::ALLOW, setting); + setting = brave_shields::GetFingerprintingControlType( + profile(), GURL("http://brave.com")); + EXPECT_EQ(ControlType::ALLOW, setting); + + /* BLOCK */ + map->SetContentSettingCustomScope( + ContentSettingsPattern::Wildcard(), ContentSettingsPattern::Wildcard(), + CONTENT_SETTINGS_TYPE_PLUGINS, brave_shields::kFingerprinting, + CONTENT_SETTING_BLOCK); + map->SetContentSettingCustomScope( + ContentSettingsPattern::Wildcard(), + ContentSettingsPattern::FromString("https://firstParty/*"), + CONTENT_SETTINGS_TYPE_PLUGINS, brave_shields::kFingerprinting, + CONTENT_SETTING_BLOCK); + setting = brave_shields::GetFingerprintingControlType(profile(), GURL()); + EXPECT_EQ(ControlType::BLOCK, setting); + setting = brave_shields::GetFingerprintingControlType( + profile(), GURL("http://brave.com")); + EXPECT_EQ(ControlType::BLOCK, setting); + + /* BLOCK_THIRD_PARTY */ + map->SetContentSettingCustomScope( + ContentSettingsPattern::Wildcard(), ContentSettingsPattern::Wildcard(), + CONTENT_SETTINGS_TYPE_PLUGINS, brave_shields::kFingerprinting, + CONTENT_SETTING_BLOCK); + map->SetContentSettingCustomScope( + ContentSettingsPattern::Wildcard(), + ContentSettingsPattern::FromString("https://firstParty/*"), + CONTENT_SETTINGS_TYPE_PLUGINS, brave_shields::kFingerprinting, + CONTENT_SETTING_ALLOW); + setting = brave_shields::GetFingerprintingControlType(profile(), GURL()); + EXPECT_EQ(ControlType::BLOCK_THIRD_PARTY, setting); + setting = brave_shields::GetFingerprintingControlType( + profile(), GURL("http://brave.com")); + EXPECT_EQ(ControlType::BLOCK_THIRD_PARTY, setting); +} + +TEST_F(BraveShieldsUtilTest, GetFingerprintingControlType_ForOrigin) { + auto* map = HostContentSettingsMapFactory::GetForProfile(profile()); + + auto setting = brave_shields::GetFingerprintingControlType( + profile(), GURL("http://brave.com")); + EXPECT_EQ(ControlType::BLOCK_THIRD_PARTY, setting); + + /* ALLOW */ + map->SetContentSettingCustomScope( + ContentSettingsPattern::FromString("http://brave.com/*"), + ContentSettingsPattern::Wildcard(), CONTENT_SETTINGS_TYPE_PLUGINS, + brave_shields::kFingerprinting, CONTENT_SETTING_ALLOW); + map->SetContentSettingCustomScope( + ContentSettingsPattern::FromString("http://brave.com/*"), + ContentSettingsPattern::FromString("https://firstParty/*"), + CONTENT_SETTINGS_TYPE_PLUGINS, brave_shields::kFingerprinting, + CONTENT_SETTING_ALLOW); + setting = brave_shields::GetFingerprintingControlType( + profile(), GURL("http://brave.com")); + EXPECT_EQ(ControlType::ALLOW, setting); + setting = brave_shields::GetFingerprintingControlType(profile(), GURL()); + EXPECT_EQ(ControlType::BLOCK_THIRD_PARTY, setting); + + /* BLOCK */ + map->SetContentSettingCustomScope( + ContentSettingsPattern::FromString("http://brave.com/*"), + ContentSettingsPattern::Wildcard(), CONTENT_SETTINGS_TYPE_PLUGINS, + brave_shields::kFingerprinting, CONTENT_SETTING_BLOCK); + map->SetContentSettingCustomScope( + ContentSettingsPattern::FromString("http://brave.com/*"), + ContentSettingsPattern::FromString("https://firstParty/*"), + CONTENT_SETTINGS_TYPE_PLUGINS, brave_shields::kFingerprinting, + CONTENT_SETTING_BLOCK); + setting = brave_shields::GetFingerprintingControlType( + profile(), GURL("http://brave.com")); + EXPECT_EQ(ControlType::BLOCK, setting); + setting = brave_shields::GetFingerprintingControlType(profile(), GURL()); + EXPECT_EQ(ControlType::BLOCK_THIRD_PARTY, setting); + + /* BLOCK_THIRD_PARTY */ + map->SetContentSettingCustomScope( + ContentSettingsPattern::FromString("http://brave.com/*"), + ContentSettingsPattern::Wildcard(), CONTENT_SETTINGS_TYPE_PLUGINS, + brave_shields::kFingerprinting, CONTENT_SETTING_BLOCK); + map->SetContentSettingCustomScope( + ContentSettingsPattern::FromString("http://brave.com/*"), + ContentSettingsPattern::FromString("https://firstParty/*"), + CONTENT_SETTINGS_TYPE_PLUGINS, brave_shields::kFingerprinting, + CONTENT_SETTING_ALLOW); + setting = brave_shields::GetFingerprintingControlType( + profile(), GURL("http://brave.com")); + EXPECT_EQ(ControlType::BLOCK_THIRD_PARTY, setting); + setting = brave_shields::GetFingerprintingControlType(profile(), GURL()); + EXPECT_EQ(ControlType::BLOCK_THIRD_PARTY, setting); +} + +/* HTTPSEVERYWHERE CONTROL */ +TEST_F(BraveShieldsUtilTest, SetHTTPSEverywhereControlType_Default) { + auto* map = HostContentSettingsMapFactory::GetForProfile(profile()); + // settings should be default + auto setting = + map->GetContentSetting(GURL(), GURL(), CONTENT_SETTINGS_TYPE_PLUGINS, + brave_shields::kHTTPUpgradableResources); + EXPECT_EQ(CONTENT_SETTING_DEFAULT, setting); + setting = map->GetContentSetting(GURL("http://brave.com"), GURL(), + CONTENT_SETTINGS_TYPE_PLUGINS, + brave_shields::kHTTPUpgradableResources); + EXPECT_EQ(CONTENT_SETTING_DEFAULT, setting); + + /* ALLOW */ + brave_shields::SetHTTPSEverywhereControlType(profile(), ControlType::ALLOW, + GURL()); + setting = + map->GetContentSetting(GURL(), GURL(), CONTENT_SETTINGS_TYPE_PLUGINS, + brave_shields::kHTTPUpgradableResources); + EXPECT_EQ(CONTENT_SETTING_ALLOW, setting); + + // override should apply to all origins + setting = map->GetContentSetting(GURL("http://brave.com"), GURL(), + CONTENT_SETTINGS_TYPE_PLUGINS, + brave_shields::kHTTPUpgradableResources); + EXPECT_EQ(CONTENT_SETTING_ALLOW, setting); + + /* BLOCK */ + brave_shields::SetHTTPSEverywhereControlType(profile(), ControlType::BLOCK, + GURL()); + setting = + map->GetContentSetting(GURL(), GURL(), CONTENT_SETTINGS_TYPE_PLUGINS, + brave_shields::kHTTPUpgradableResources); + EXPECT_EQ(CONTENT_SETTING_BLOCK, setting); + + // override should apply to all origins + setting = map->GetContentSetting(GURL("http://brave.com"), GURL(), + CONTENT_SETTINGS_TYPE_PLUGINS, + brave_shields::kHTTPUpgradableResources); + EXPECT_EQ(CONTENT_SETTING_BLOCK, setting); +} + +TEST_F(BraveShieldsUtilTest, SetHTTPSEverywhereControlType_ForOrigin) { + auto* map = HostContentSettingsMapFactory::GetForProfile(profile()); + + brave_shields::SetHTTPSEverywhereControlType(profile(), ControlType::ALLOW, + GURL("http://brave.com")); + // setting should apply to origin + auto setting = map->GetContentSetting( + GURL("http://brave.com"), GURL(), CONTENT_SETTINGS_TYPE_PLUGINS, + brave_shields::kHTTPUpgradableResources); + EXPECT_EQ(CONTENT_SETTING_ALLOW, setting); + + // setting should apply to different scheme + setting = map->GetContentSetting(GURL("https://brave.com"), GURL(), + CONTENT_SETTINGS_TYPE_PLUGINS, + brave_shields::kHTTPUpgradableResources); + EXPECT_EQ(CONTENT_SETTING_ALLOW, setting); + + // setting should not apply to default + setting = + map->GetContentSetting(GURL(), GURL(), CONTENT_SETTINGS_TYPE_PLUGINS, + brave_shields::kHTTPUpgradableResources); + EXPECT_EQ(CONTENT_SETTING_DEFAULT, setting); +} + +TEST_F(BraveShieldsUtilTest, GetHTTPSEverywhereControlType_Default) { + auto* map = HostContentSettingsMapFactory::GetForProfile(profile()); + + auto setting = + brave_shields::GetHTTPSEverywhereControlType(profile(), GURL()); + EXPECT_EQ(ControlType::BLOCK, setting); + + /* ALLOW */ + map->SetContentSettingCustomScope( + ContentSettingsPattern::Wildcard(), ContentSettingsPattern::Wildcard(), + CONTENT_SETTINGS_TYPE_PLUGINS, brave_shields::kHTTPUpgradableResources, + CONTENT_SETTING_ALLOW); + setting = brave_shields::GetHTTPSEverywhereControlType(profile(), GURL()); + EXPECT_EQ(ControlType::ALLOW, setting); + + /* BLOCK */ + map->SetContentSettingCustomScope( + ContentSettingsPattern::Wildcard(), ContentSettingsPattern::Wildcard(), + CONTENT_SETTINGS_TYPE_PLUGINS, brave_shields::kHTTPUpgradableResources, + CONTENT_SETTING_BLOCK); + setting = brave_shields::GetHTTPSEverywhereControlType(profile(), GURL()); + EXPECT_EQ(ControlType::BLOCK, setting); +} + +TEST_F(BraveShieldsUtilTest, GetHTTPSEverywhereControlType_ForOrigin) { + auto* map = HostContentSettingsMapFactory::GetForProfile(profile()); + + auto setting = + brave_shields::GetHTTPSEverywhereControlType(profile(), GURL()); + EXPECT_EQ(ControlType::BLOCK, setting); + setting = brave_shields::GetHTTPSEverywhereControlType( + profile(), GURL("http://brave.com")); + EXPECT_EQ(ControlType::BLOCK, setting); + setting = brave_shields::GetHTTPSEverywhereControlType( + profile(), GURL("https://brave.com")); + EXPECT_EQ(ControlType::BLOCK, setting); + + /* ALLOW */ + map->SetContentSettingCustomScope( + ContentSettingsPattern::FromString("http://brave.com/*"), + ContentSettingsPattern::Wildcard(), CONTENT_SETTINGS_TYPE_PLUGINS, + brave_shields::kHTTPUpgradableResources, CONTENT_SETTING_ALLOW); + setting = brave_shields::GetHTTPSEverywhereControlType( + profile(), GURL("http://brave.com")); + EXPECT_EQ(ControlType::ALLOW, setting); + + // https in unchanged + setting = brave_shields::GetHTTPSEverywhereControlType( + profile(), GURL("https://brave.com")); + EXPECT_EQ(ControlType::BLOCK, setting); + // default is unchanged + setting = brave_shields::GetHTTPSEverywhereControlType(profile(), GURL()); + EXPECT_EQ(ControlType::BLOCK, setting); + + /* BLOCK */ + // change default to allow + map->SetContentSettingCustomScope( + ContentSettingsPattern::Wildcard(), ContentSettingsPattern::Wildcard(), + CONTENT_SETTINGS_TYPE_PLUGINS, brave_shields::kHTTPUpgradableResources, + CONTENT_SETTING_ALLOW); + setting = brave_shields::GetHTTPSEverywhereControlType( + profile(), GURL("http://brave.com")); + EXPECT_EQ(ControlType::ALLOW, setting); + setting = brave_shields::GetHTTPSEverywhereControlType( + profile(), GURL("https://brave.com")); + EXPECT_EQ(ControlType::ALLOW, setting); + setting = brave_shields::GetHTTPSEverywhereControlType(profile(), GURL()); + EXPECT_EQ(ControlType::ALLOW, setting); + + // set override to block + map->SetContentSettingCustomScope( + ContentSettingsPattern::FromString("http://brave.com/*"), + ContentSettingsPattern::Wildcard(), CONTENT_SETTINGS_TYPE_PLUGINS, + brave_shields::kHTTPUpgradableResources, CONTENT_SETTING_BLOCK); + setting = brave_shields::GetHTTPSEverywhereControlType( + profile(), GURL("http://brave.com/*")); + EXPECT_EQ(ControlType::BLOCK, setting); + // https in unchanged + setting = brave_shields::GetHTTPSEverywhereControlType( + profile(), GURL("https://brave.com")); + EXPECT_EQ(ControlType::ALLOW, setting); + // default is unchanged + setting = brave_shields::GetHTTPSEverywhereControlType(profile(), GURL()); + EXPECT_EQ(ControlType::ALLOW, setting); +} + +/* NOSCRIPT CONTROL */ +TEST_F(BraveShieldsUtilTest, SetNoScriptControlType_Default) { + auto* map = HostContentSettingsMapFactory::GetForProfile(profile()); + // settings should be default + auto setting = map->GetContentSetting(GURL(), GURL(), + CONTENT_SETTINGS_TYPE_JAVASCRIPT, ""); + EXPECT_EQ(CONTENT_SETTING_ALLOW, setting); + setting = map->GetContentSetting(GURL("http://brave.com"), GURL(), + CONTENT_SETTINGS_TYPE_JAVASCRIPT, ""); + EXPECT_EQ(CONTENT_SETTING_ALLOW, setting); + + /* BLOCK */ + brave_shields::SetNoScriptControlType(profile(), ControlType::BLOCK, GURL()); + setting = map->GetContentSetting(GURL(), GURL(), + CONTENT_SETTINGS_TYPE_JAVASCRIPT, ""); + EXPECT_EQ(CONTENT_SETTING_BLOCK, setting); + + // override should apply to all origins + setting = map->GetContentSetting(GURL("http://brave.com"), GURL(), + CONTENT_SETTINGS_TYPE_JAVASCRIPT, ""); + EXPECT_EQ(CONTENT_SETTING_BLOCK, setting); + + /* ALLOW */ + brave_shields::SetNoScriptControlType(profile(), ControlType::ALLOW, GURL()); + setting = map->GetContentSetting(GURL(), GURL(), + CONTENT_SETTINGS_TYPE_JAVASCRIPT, ""); + EXPECT_EQ(CONTENT_SETTING_ALLOW, setting); + + // override should apply to all origins + setting = map->GetContentSetting(GURL("http://brave.com"), GURL(), + CONTENT_SETTINGS_TYPE_JAVASCRIPT, ""); + EXPECT_EQ(CONTENT_SETTING_ALLOW, setting); +} + +TEST_F(BraveShieldsUtilTest, SetNoScriptControlType_ForOrigin) { + auto* map = HostContentSettingsMapFactory::GetForProfile(profile()); + + brave_shields::SetNoScriptControlType(profile(), ControlType::BLOCK, + GURL("http://brave.com")); + // setting should apply to origin + auto setting = map->GetContentSetting(GURL("http://brave.com"), GURL(), + CONTENT_SETTINGS_TYPE_JAVASCRIPT, ""); + EXPECT_EQ(CONTENT_SETTING_BLOCK, setting); + + // setting should not apply to different scheme + setting = map->GetContentSetting(GURL("https://brave.com"), GURL(), + CONTENT_SETTINGS_TYPE_JAVASCRIPT, ""); + EXPECT_EQ(CONTENT_SETTING_ALLOW, setting); + + // setting should not apply to default + setting = map->GetContentSetting(GURL(), GURL(), + CONTENT_SETTINGS_TYPE_JAVASCRIPT, ""); + EXPECT_EQ(CONTENT_SETTING_ALLOW, setting); +} + +TEST_F(BraveShieldsUtilTest, GetNoScriptControlType_Default) { + auto* map = HostContentSettingsMapFactory::GetForProfile(profile()); + + auto setting = brave_shields::GetNoScriptControlType(profile(), GURL()); + EXPECT_EQ(ControlType::ALLOW, setting); + + /* BLOCK */ + map->SetContentSettingCustomScope( + ContentSettingsPattern::Wildcard(), ContentSettingsPattern::Wildcard(), + CONTENT_SETTINGS_TYPE_JAVASCRIPT, "", CONTENT_SETTING_BLOCK); + setting = brave_shields::GetNoScriptControlType(profile(), GURL()); + EXPECT_EQ(ControlType::BLOCK, setting); + + /* ALLOW */ + map->SetContentSettingCustomScope( + ContentSettingsPattern::Wildcard(), ContentSettingsPattern::Wildcard(), + CONTENT_SETTINGS_TYPE_JAVASCRIPT, "", CONTENT_SETTING_ALLOW); + setting = brave_shields::GetNoScriptControlType(profile(), GURL()); + EXPECT_EQ(ControlType::ALLOW, setting); +} + +TEST_F(BraveShieldsUtilTest, GetNoScriptControlType_ForOrigin) { + auto* map = HostContentSettingsMapFactory::GetForProfile(profile()); + + auto setting = brave_shields::GetNoScriptControlType(profile(), GURL()); + EXPECT_EQ(ControlType::ALLOW, setting); + setting = brave_shields::GetNoScriptControlType(profile(), + GURL("http://brave.com")); + EXPECT_EQ(ControlType::ALLOW, setting); + setting = brave_shields::GetNoScriptControlType(profile(), + GURL("https://brave.com")); + EXPECT_EQ(ControlType::ALLOW, setting); + + /* BLOCK */ + // set override to block + map->SetContentSettingCustomScope( + ContentSettingsPattern::FromString("http://brave.com/*"), + ContentSettingsPattern::Wildcard(), CONTENT_SETTINGS_TYPE_JAVASCRIPT, "", + CONTENT_SETTING_BLOCK); + setting = brave_shields::GetNoScriptControlType(profile(), + GURL("http://brave.com/*")); + EXPECT_EQ(ControlType::BLOCK, setting); + // https in unchanged + setting = brave_shields::GetNoScriptControlType(profile(), + GURL("https://brave.com")); + EXPECT_EQ(ControlType::ALLOW, setting); + // default is unchanged + setting = brave_shields::GetNoScriptControlType(profile(), GURL()); + EXPECT_EQ(ControlType::ALLOW, setting); + + /* ALLOW */ + // change default to block + map->SetContentSettingCustomScope( + ContentSettingsPattern::Wildcard(), ContentSettingsPattern::Wildcard(), + CONTENT_SETTINGS_TYPE_JAVASCRIPT, "", CONTENT_SETTING_BLOCK); + setting = brave_shields::GetNoScriptControlType(profile(), + GURL("http://brave.com")); + EXPECT_EQ(ControlType::BLOCK, setting); + setting = brave_shields::GetNoScriptControlType(profile(), + GURL("https://brave.com")); + EXPECT_EQ(ControlType::BLOCK, setting); + setting = brave_shields::GetNoScriptControlType(profile(), GURL()); + EXPECT_EQ(ControlType::BLOCK, setting); + + map->SetContentSettingCustomScope( + ContentSettingsPattern::FromString("http://brave.com/*"), + ContentSettingsPattern::Wildcard(), CONTENT_SETTINGS_TYPE_JAVASCRIPT, "", + CONTENT_SETTING_ALLOW); + setting = brave_shields::GetNoScriptControlType(profile(), + GURL("http://brave.com")); + EXPECT_EQ(ControlType::ALLOW, setting); + + // https in unchanged + setting = brave_shields::GetNoScriptControlType(profile(), + GURL("https://brave.com")); + EXPECT_EQ(ControlType::BLOCK, setting); + // default is unchanged + setting = brave_shields::GetNoScriptControlType(profile(), GURL()); + EXPECT_EQ(ControlType::BLOCK, setting); +} diff --git a/components/definitions/chromel.d.ts b/components/definitions/chromel.d.ts index b2f783d74fd..19eed062bb7 100644 --- a/components/definitions/chromel.d.ts +++ b/components/definitions/chromel.d.ts @@ -185,8 +185,18 @@ declare namespace chrome.braveShields { } const allowScriptsOnce: any - const javascript: any - const plugins: any + const setBraveShieldsControlTypeAsync: any + const getBraveShieldsControlTypeAsync: any + const setAdControlTypeAsync: any + const getAdControlTypeAsync: any + const setCookieControlTypeAsync: any + const getCookieControlTypeAsync: any + const setFingerprintingControlTypeAsync: any + const getFingerprintingControlTypeAsync: any + const setHTTPSEverywhereControlTypeAsync: any + const getHTTPSEverywhereControlTypeAsync: any + const setNoScriptControlTypeAsync: any + const getNoScriptControlTypeAsync: any type BraveShieldsViewPreferences = { showAdvancedView: boolean diff --git a/components/test/brave_extension/background/api/shieldsAPI_test.ts b/components/test/brave_extension/background/api/shieldsAPI_test.ts index 72282c2d3b8..178948e72db 100644 --- a/components/test/brave_extension/background/api/shieldsAPI_test.ts +++ b/components/test/brave_extension/background/api/shieldsAPI_test.ts @@ -6,7 +6,6 @@ import actions from '../../../../brave_extension/extension/brave_extension/backg import * as shieldsAPI from '../../../../brave_extension/extension/brave_extension/background/api/shieldsAPI' import { activeTabData } from '../../../testData' // import { Tab as TabType } from '../../../types/state/shieldsPannelState' -import * as resourceIdentifiers from '../../../../brave_extension/extension/brave_extension/constants/resourceIdentifiers' describe('Shields API', () => { describe('getShieldSettingsForTabData', () => { @@ -51,75 +50,6 @@ describe('Shields API', () => { console.error(e.toString()) }) }) - - it('returns `block` by default for braveShields', (cb) => { - const tab: chrome.tabs.Tab = { - url: 'https://www.brave.com/charizard/knows/serg', - index: 1, - pinned: false, - highlighted: false, - windowId: 1, - active: true, - incognito: false, - selected: false, - id: 1337 - } - - expect.assertions(1) - shieldsAPI.getShieldSettingsForTabData(tab).then((data) => { - expect(data.braveShields).toBe('block') - cb() - }) - .catch((e: Error) => { - console.error(e.toString()) - }) - }) - - it('returns `block` by default for braveShields when origin is not http or https', (cb) => { - const tab: chrome.tabs.Tab = { - url: 'ftp://www.brave.com/serg/dont/know/pikachu', - index: 1, - pinned: false, - highlighted: false, - windowId: 1, - active: true, - incognito: false, - selected: false, - id: 1337 - } - - expect.assertions(1) - shieldsAPI.getShieldSettingsForTabData(tab).then((data) => { - expect(data.braveShields).toBe('block') - cb() - }) - .catch((e: Error) => { - console.error(e.toString()) - }) - }) - - it('returns `block` by default for braveShields when origin is an about page', (cb) => { - const tab: chrome.tabs.Tab = { - url: 'chrome://welcome', - index: 1, - pinned: false, - highlighted: false, - windowId: 1, - active: true, - incognito: false, - selected: false, - id: 1337 - } - - expect.assertions(1) - shieldsAPI.getShieldSettingsForTabData(tab).then((data) => { - expect(data.braveShields).toBe('block') - cb() - }) - .catch((e: Error) => { - console.error(e.toString()) - }) - }) }) describe('getTabData', () => { @@ -191,265 +121,105 @@ describe('Shields API', () => { describe('setAllowAds', () => { let spy: jest.SpyInstance beforeEach(() => { - spy = jest.spyOn(chrome.braveShields.plugins, 'setAsync') + spy = jest.spyOn(chrome.braveShields, 'setAdControlTypeAsync') }) afterEach(() => { spy.mockRestore() }) - it('calls chrome.braveShields.plugins with the correct args', () => { + it('calls chrome.braveShields.setAdControlTypeAsync with the correct args', () => { shieldsAPI.setAllowAds('https://www.brave.com', 'block') .catch(() => { expect(true).toBe(false) }) const arg0 = spy.mock.calls[0][0] - expect.assertions(1) - expect(arg0).toEqual({ - primaryPattern: 'https://www.brave.com/*', - resourceIdentifier: { id: resourceIdentifiers.RESOURCE_IDENTIFIER_ADS }, - setting: 'block', - scope: 'incognito_session_only' - }) - }) - it('passes only 1 arg to chrome.braveShields.plugins', () => { - shieldsAPI.setAllowAds('https://www.brave.com', 'block') - .catch(() => { - expect(true).toBe(false) - }) - expect.assertions(1) - expect(spy.mock.calls[0].length).toBe(1) - }) - it('resolves the returned promise', (cb) => { - shieldsAPI.setAllowAds('https://www.brave.com', 'block') - .then(cb) - .catch((e: Error) => { - console.error(e.toString()) - }) - }) - }) - - describe('setAllowTrackers', () => { - let spy: jest.SpyInstance - beforeEach(() => { - spy = jest.spyOn(chrome.braveShields.plugins, 'setAsync') - }) - afterEach(() => { - spy.mockRestore() - }) - it('calls chrome.braveShields.plugins with the correct args', () => { - shieldsAPI.setAllowTrackers('https://www.brave.com', 'block') - .catch(() => { - expect(true).toBe(false) - }) - const arg0 = spy.mock.calls[0][0] - expect.assertions(1) - expect(arg0).toEqual({ - primaryPattern: 'https://www.brave.com/*', - resourceIdentifier: { id: resourceIdentifiers.RESOURCE_IDENTIFIER_TRACKERS }, - setting: 'block', - scope: 'incognito_session_only' - }) - }) - it('passes only 1 arg to chrome.braveShields.plugins', () => { - shieldsAPI.setAllowTrackers('https://www.brave.com', 'block') - .catch(() => { - expect(true).toBe(false) - }) - expect.assertions(1) - expect(spy.mock.calls[0].length).toBe(1) - }) - it('resolves the returned promise', (cb) => { - shieldsAPI.setAllowTrackers('https://www.brave.com', 'block') - .then(cb) - .catch((e: Error) => { - console.error(e.toString()) - }) + const arg1 = spy.mock.calls[0][1] + expect.assertions(2) + expect(arg0).toEqual('block') + expect(arg1).toEqual('https://www.brave.com') }) }) describe('setAllowHTTPUpgradableResource', () => { let spy: jest.SpyInstance beforeEach(() => { - spy = jest.spyOn(chrome.braveShields.plugins, 'setAsync') + spy = jest.spyOn(chrome.braveShields, 'setHTTPSEverywhereControlTypeAsync') }) afterEach(() => { spy.mockRestore() }) - it('calls chrome.braveShields.plugins with the correct args', () => { + it('calls chrome.braveShields.setHTTPSEverywhereControlTypeAsync with the correct args', () => { shieldsAPI.setAllowHTTPUpgradableResources('https://www.brave.com', 'block') .catch(() => { expect(true).toBe(false) }) const arg0 = spy.mock.calls[0][0] - expect.assertions(1) - expect(arg0).toEqual({ - primaryPattern: '*://www.brave.com/*', - resourceIdentifier: { id: resourceIdentifiers.RESOURCE_IDENTIFIER_HTTP_UPGRADABLE_RESOURCES }, - setting: 'block', - scope: 'incognito_session_only' - }) - }) - it('passes only 1 arg to chrome.braveShields.plugins', () => { - shieldsAPI.setAllowHTTPUpgradableResources('https://www.brave.com', 'block') - .catch(() => { - expect(true).toBe(false) - }) - expect.assertions(1) - expect(spy.mock.calls[0].length).toBe(1) - }) - it('resolves the returned promise', (cb) => { - shieldsAPI.setAllowHTTPUpgradableResources('https://www.brave.com', 'block') - .then(cb) - .catch((e: Error) => { - console.error(e.toString()) - }) + const arg1 = spy.mock.calls[0][1] + expect.assertions(2) + expect(arg0).toEqual('block') + expect(arg1).toEqual('https://www.brave.com') }) }) describe('setAllowJavaScript', () => { let spy: jest.SpyInstance beforeEach(() => { - spy = jest.spyOn(chrome.braveShields.javascript, 'setAsync') + spy = jest.spyOn(chrome.braveShields, 'setNoScriptControlTypeAsync') }) afterEach(() => { spy.mockRestore() }) - - it('calls chrome.braveShields.plugins with the correct args', () => { + it('calls chrome.braveShields.setNoScriptControlTypeAsync with the correct args', () => { shieldsAPI.setAllowJavaScript('https://www.brave.com', 'block') .catch(() => { expect(true).toBe(false) }) const arg0 = spy.mock.calls[0][0] - expect.assertions(1) - expect(arg0).toEqual({ - primaryPattern: 'https://www.brave.com/*', - setting: 'block', - scope: 'incognito_session_only' - }) - }) - - it('passes only 1 arg to chrome.braveShields.plugins', () => { - shieldsAPI.setAllowJavaScript('https://www.brave.com', 'block') - .catch(() => { - expect(true).toBe(false) - }) - expect.assertions(1) - expect(spy.mock.calls[0].length).toBe(1) - }) - - it('resolves the returned promise', (cb) => { - shieldsAPI.setAllowJavaScript('https://www.brave.com', 'block') - .then(cb) - .catch((e: Error) => { - console.error(e.toString()) - }) + const arg1 = spy.mock.calls[0][1] + expect.assertions(2) + expect(arg0).toEqual('block') + expect(arg1).toEqual('https://www.brave.com') }) }) describe('setAllowFingerprinting', () => { let spy: jest.SpyInstance beforeEach(() => { - spy = jest.spyOn(chrome.braveShields.plugins, 'setAsync') + spy = jest.spyOn(chrome.braveShields, 'setFingerprintingControlTypeAsync') }) afterEach(() => { spy.mockRestore() }) - it('calls chrome.braveShields.plugins with the correct args', () => { + it('calls chrome.braveShields.setFingerprintingControlTypeAsync with the correct args', () => { shieldsAPI.setAllowFingerprinting('https://www.brave.com', 'block') .catch(() => { expect(true).toBe(false) }) const arg0 = spy.mock.calls[0][0] + const arg1 = spy.mock.calls[0][1] expect.assertions(2) - expect(arg0).toEqual({ - primaryPattern: 'https://www.brave.com/*', - resourceIdentifier: { id: resourceIdentifiers.RESOURCE_IDENTIFIER_FINGERPRINTING }, - setting: 'block', - scope: 'incognito_session_only' - }) - const arg1 = spy.mock.calls[1][0] - expect(arg1).toEqual({ - primaryPattern: 'https://www.brave.com/*', - secondaryPattern: 'https://firstParty/*', - resourceIdentifier: { id: resourceIdentifiers.RESOURCE_IDENTIFIER_FINGERPRINTING }, - setting: 'block', - scope: 'incognito_session_only' - }) - }) - it('passes only 1 arg to chrome.braveShields.plugins', () => { - shieldsAPI.setAllowFingerprinting('https://www.brave.com', 'block') - .catch(() => { - expect(true).toBe(false) - }) - expect.assertions(2) - expect(spy.mock.calls[0].length).toBe(1) - expect(spy.mock.calls[1].length).toBe(1) - }) - it('resolves the returned promise', (cb) => { - shieldsAPI.setAllowFingerprinting('https://www.brave.com', 'block') - .then(function () { - cb() - }) - .catch((e: Error) => { - console.error(e.toString()) - }) + expect(arg0).toEqual('block') + expect(arg1).toEqual('https://www.brave.com') }) }) describe('setAllowCookies', () => { let spy: jest.SpyInstance beforeEach(() => { - spy = jest.spyOn(chrome.braveShields.plugins, 'setAsync') + spy = jest.spyOn(chrome.braveShields, 'setCookieControlTypeAsync') }) afterEach(() => { spy.mockRestore() }) - it('calls chrome.braveShields.plugins with the correct args', () => { + it('calls chrome.braveShields.setCookieControlTypeAsync with the correct args', () => { shieldsAPI.setAllowCookies('https://www.brave.com', 'block') .catch(() => { expect(true).toBe(false) }) const arg0 = spy.mock.calls[0][0] - expect.assertions(3) - expect(arg0).toEqual({ - primaryPattern: 'https://www.brave.com/*', - resourceIdentifier: { id: resourceIdentifiers.RESOURCE_IDENTIFIER_REFERRERS }, - setting: 'block', - scope: 'incognito_session_only' - }) - const arg1 = spy.mock.calls[1][0] - expect(arg1).toEqual({ - primaryPattern: 'https://www.brave.com/*', - resourceIdentifier: { id: resourceIdentifiers.RESOURCE_IDENTIFIER_COOKIES }, - setting: 'block', - scope: 'incognito_session_only' - }) - const arg2 = spy.mock.calls[2][0] - expect(arg2).toEqual({ - primaryPattern: 'https://www.brave.com/*', - secondaryPattern: 'https://firstParty/*', - resourceIdentifier: { id: resourceIdentifiers.RESOURCE_IDENTIFIER_COOKIES }, - setting: 'block', - scope: 'incognito_session_only' - }) - }) - it('passes only 1 arg to chrome.braveShields.plugins', () => { - shieldsAPI.setAllowCookies('https://www.brave.com', 'block') - .catch(() => { - expect(true).toBe(false) - }) + const arg1 = spy.mock.calls[0][1] expect.assertions(2) - expect(spy.mock.calls[0].length).toBe(1) - expect(spy.mock.calls[1].length).toBe(1) - }) - it('resolves the returned promise', (cb) => { - shieldsAPI.setAllowCookies('https://www.brave.com', 'block') - .then(() => { - cb() - }) - .catch((e: Error) => { - console.error(e.toString()) - }) + expect(arg0).toEqual('block') + expect(arg1).toEqual('https://www.brave.com') }) }) diff --git a/components/test/brave_extension/helpers/urlUtils_test.ts b/components/test/brave_extension/helpers/urlUtils_test.ts index 313a4a8102d..68318c12649 100644 --- a/components/test/brave_extension/helpers/urlUtils_test.ts +++ b/components/test/brave_extension/helpers/urlUtils_test.ts @@ -4,7 +4,6 @@ import { isHttpOrHttps, - hasPortNumber, getOrigin, getHostname, stripProtocolFromUrl @@ -45,17 +44,6 @@ describe('urlUtils test', () => { expect(isHttpOrHttps(url)).toBe(true) }) }) - describe('hasPortNumber', () => { - it('not a port number if # is located in front of :XXXX', () => { - const url = 'http://brianbondy.com#:8080' - expect(hasPortNumber(url)).toBe(false) - }) - it('port number if # is not existed in front of :XXXX', () => { - const url = 'http://brianbondy.com:8080' - expect(hasPortNumber(url)).toBe(true) - expect(isHttpOrHttps(url)).toBe(true) - }) - }) describe('getOrigin', () => { it('properly gets the origin from an URL', () => { const url = 'https://pokemons-invading-tests-breaking-stuff.com/you-knew-that.js' diff --git a/components/test/testData.ts b/components/test/testData.ts index 37789cc903d..1164de71874 100644 --- a/components/test/testData.ts +++ b/components/test/testData.ts @@ -209,25 +209,41 @@ export const getMockChrome = () => { allowScriptsOnce: function (origins: Array, tabId: number, cb: () => void) { setImmediate(cb) }, - plugins: { - setAsync: function () { - return Promise.resolve() - }, - getAsync: function () { - return Promise.resolve({ - setting: 'block' - }) - } + getBraveShieldsControlTypeAsync: function (url: string) { + return Promise.resolve('block') }, - javascript: { - setAsync: function () { - return Promise.resolve() - }, - getAsync: function () { - return Promise.resolve({ - setting: 'block' - }) - } + getAdControlTypeAsync: function (url: string) { + return Promise.resolve('block') + }, + getCookieControlTypeAsync: function (url: string) { + return Promise.resolve('block') + }, + getFingerprintingControlTypeAsync: function (url: string) { + return Promise.resolve('block') + }, + getHTTPSEverywhereControlTypeAsync: function (url: string) { + return Promise.resolve('block') + }, + getNoScriptControlTypeAsync: function (url: string) { + return Promise.resolve('block') + }, + setBraveShieldsControlTypeAsync: function (url: string, controlType: string) { + return new Promise(() => []) + }, + setAdControlTypeAsync: function (url: string, controlType: string) { + return new Promise(() => []) + }, + setCookieControlTypeAsync: function (url: string, controlType: string) { + return new Promise(() => []) + }, + setFingerprintingControlTypeAsync: function (url: string, controlType: string) { + return new Promise(() => []) + }, + setHTTPSEverywhereControlTypeAsync: function (url: string, controlType: string) { + return new Promise(() => []) + }, + setNoScriptControlTypeAsync: function (url: string, controlType: string) { + return new Promise(() => []) } }, i18n: { diff --git a/test/BUILD.gn b/test/BUILD.gn index 0e84cc85575..7e769cd957b 100644 --- a/test/BUILD.gn +++ b/test/BUILD.gn @@ -90,6 +90,7 @@ test("brave_unit_tests") { "//brave/common/shield_exceptions_unittest.cc", "//brave/components/assist_ranker/ranker_model_loader_impl_unittest.cc", "//brave/components/brave_shields/browser/ad_block_regional_service_unittest.cc", + "//brave/components/brave_shields/browser/brave_shields_util_unittest.cc", "//brave/components/brave_shields/browser/https_everywhere_recently_used_cache_unittest.cpp", "//brave/components/brave_webtorrent/browser/net/brave_torrent_redirect_network_delegate_helper_unittest.cc", "//brave/components/invalidation/fcm_unittest.cc", From 8eb29bddbfd73df96f894effb437d3e6e5a519ed Mon Sep 17 00:00:00 2001 From: bridiver Date: Tue, 30 Jul 2019 16:00:15 -0700 Subject: [PATCH 2/6] add callbacks for extension set* methods change brave shields method names for clarity fix https://github.com/brave/brave-browser/issues/5470 --- browser/extensions/api/brave_shields_api.cc | 46 ++-- browser/extensions/api/brave_shields_api.h | 24 +- .../default_brave_shields_browser_proxy.js | 6 +- .../default_brave_shields_page.js | 2 +- .../settings/default_brave_shields_handler.cc | 13 +- .../settings/default_brave_shields_handler.h | 7 +- common/extensions/api/brave_shields.json | 60 ++++- .../extension/brave_extension/background.ts | 2 +- .../background/api/shieldsAPI.ts | 17 +- .../components/advancedView/header.tsx | 9 +- .../browser/brave_shields_util.cc | 69 ++++-- .../browser/brave_shields_util.h | 17 +- .../browser/brave_shields_util_unittest.cc | 231 +++++++++--------- components/definitions/chromel.d.ts | 8 +- .../background/api/shieldsAPI_test.ts | 6 +- components/test/testData.ts | 12 +- 16 files changed, 290 insertions(+), 239 deletions(-) diff --git a/browser/extensions/api/brave_shields_api.cc b/browser/extensions/api/brave_shields_api.cc index 4b06be89fa7..b979bcef50e 100644 --- a/browser/extensions/api/brave_shields_api.cc +++ b/browser/extensions/api/brave_shields_api.cc @@ -56,9 +56,9 @@ ExtensionFunction::ResponseAction BraveShieldsAllowScriptsOnceFunction::Run() { } ExtensionFunction::ResponseAction -BraveShieldsSetBraveShieldsControlTypeFunction::Run() { - std::unique_ptr params( - brave_shields::SetBraveShieldsControlType::Params::Create(*args_)); +BraveShieldsSetBraveShieldsEnabledFunction::Run() { + std::unique_ptr params( + brave_shields::SetBraveShieldsEnabled::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params.get()); const GURL url(params->url); @@ -67,21 +67,16 @@ BraveShieldsSetBraveShieldsControlTypeFunction::Run() { return RespondNow(Error(kInvalidUrlError, params->url)); } - auto control_type = ControlTypeFromString(params->control_type); - if (control_type == ControlType::INVALID) { - return RespondNow(Error(kInvalidControlTypeError, params->control_type)); - } - Profile* profile = Profile::FromBrowserContext(browser_context()); - ::brave_shields::SetBraveShieldsControlType(profile, control_type, url); + ::brave_shields::SetBraveShieldsEnabled(profile, params->enabled, url); return RespondNow(NoArguments()); } ExtensionFunction::ResponseAction -BraveShieldsGetBraveShieldsControlTypeFunction::Run() { - std::unique_ptr params( - brave_shields::GetBraveShieldsControlType::Params::Create(*args_)); +BraveShieldsGetBraveShieldsEnabledFunction::Run() { + std::unique_ptr params( + brave_shields::GetBraveShieldsEnabled::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params.get()); const GURL url(params->url); @@ -91,8 +86,8 @@ BraveShieldsGetBraveShieldsControlTypeFunction::Run() { } Profile* profile = Profile::FromBrowserContext(browser_context()); - auto type = ::brave_shields::GetBraveShieldsControlType(profile, url); - auto result = std::make_unique(ControlTypeToString(type)); + auto enabled = ::brave_shields::GetBraveShieldsEnabled(profile, url); + auto result = std::make_unique(enabled); return RespondNow(OneArgument(std::move(result))); } @@ -222,9 +217,9 @@ BraveShieldsGetFingerprintingControlTypeFunction::Run() { } ExtensionFunction::ResponseAction -BraveShieldsSetHTTPSEverywhereControlTypeFunction::Run() { - std::unique_ptr params( - brave_shields::SetHTTPSEverywhereControlType::Params::Create(*args_)); +BraveShieldsSetHTTPSEverywhereEnabledFunction::Run() { + std::unique_ptr params( + brave_shields::SetHTTPSEverywhereEnabled::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params.get()); const GURL url(params->url); @@ -233,21 +228,16 @@ BraveShieldsSetHTTPSEverywhereControlTypeFunction::Run() { return RespondNow(Error(kInvalidUrlError, params->url)); } - auto control_type = ControlTypeFromString(params->control_type); - if (control_type == ControlType::INVALID) { - return RespondNow(Error(kInvalidControlTypeError, params->control_type)); - } - Profile* profile = Profile::FromBrowserContext(browser_context()); - ::brave_shields::SetHTTPSEverywhereControlType(profile, control_type, url); + ::brave_shields::SetHTTPSEverywhereEnabled(profile, params->enabled, url); return RespondNow(NoArguments()); } ExtensionFunction::ResponseAction -BraveShieldsGetHTTPSEverywhereControlTypeFunction::Run() { - std::unique_ptr params( - brave_shields::GetHTTPSEverywhereControlType::Params::Create(*args_)); +BraveShieldsGetHTTPSEverywhereEnabledFunction::Run() { + std::unique_ptr params( + brave_shields::GetHTTPSEverywhereEnabled::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params.get()); const GURL url(params->url); @@ -257,8 +247,8 @@ BraveShieldsGetHTTPSEverywhereControlTypeFunction::Run() { } Profile* profile = Profile::FromBrowserContext(browser_context()); - auto type = ::brave_shields::GetHTTPSEverywhereControlType(profile, url); - auto result = std::make_unique(ControlTypeToString(type)); + auto type = ::brave_shields::GetHTTPSEverywhereEnabled(profile, url); + auto result = std::make_unique(type); return RespondNow(OneArgument(std::move(result))); } diff --git a/browser/extensions/api/brave_shields_api.h b/browser/extensions/api/brave_shields_api.h index 509ca0ac304..59380d2de9e 100644 --- a/browser/extensions/api/brave_shields_api.h +++ b/browser/extensions/api/brave_shields_api.h @@ -21,24 +21,24 @@ class BraveShieldsAllowScriptsOnceFunction : public UIThreadExtensionFunction { ResponseAction Run() override; }; -class BraveShieldsSetBraveShieldsControlTypeFunction +class BraveShieldsSetBraveShieldsEnabledFunction : public UIThreadExtensionFunction { public: - DECLARE_EXTENSION_FUNCTION("braveShields.setBraveShieldsControlType", UNKNOWN) + DECLARE_EXTENSION_FUNCTION("braveShields.setBraveShieldsEnabled", UNKNOWN) protected: - ~BraveShieldsSetBraveShieldsControlTypeFunction() override {} + ~BraveShieldsSetBraveShieldsEnabledFunction() override {} ResponseAction Run() override; }; -class BraveShieldsGetBraveShieldsControlTypeFunction +class BraveShieldsGetBraveShieldsEnabledFunction : public UIThreadExtensionFunction { public: - DECLARE_EXTENSION_FUNCTION("braveShields.getBraveShieldsControlType", UNKNOWN) + DECLARE_EXTENSION_FUNCTION("braveShields.getBraveShieldsEnabled", UNKNOWN) protected: - ~BraveShieldsGetBraveShieldsControlTypeFunction() override {} + ~BraveShieldsGetBraveShieldsEnabledFunction() override {} ResponseAction Run() override; }; @@ -109,26 +109,26 @@ class BraveShieldsGetFingerprintingControlTypeFunction ResponseAction Run() override; }; -class BraveShieldsSetHTTPSEverywhereControlTypeFunction +class BraveShieldsSetHTTPSEverywhereEnabledFunction : public UIThreadExtensionFunction { public: - DECLARE_EXTENSION_FUNCTION("braveShields.setHTTPSEverywhereControlType", + DECLARE_EXTENSION_FUNCTION("braveShields.setHTTPSEverywhereEnabled", UNKNOWN) protected: - ~BraveShieldsSetHTTPSEverywhereControlTypeFunction() override {} + ~BraveShieldsSetHTTPSEverywhereEnabledFunction() override {} ResponseAction Run() override; }; -class BraveShieldsGetHTTPSEverywhereControlTypeFunction +class BraveShieldsGetHTTPSEverywhereEnabledFunction : public UIThreadExtensionFunction { public: - DECLARE_EXTENSION_FUNCTION("braveShields.getHTTPSEverywhereControlType", + DECLARE_EXTENSION_FUNCTION("braveShields.getHTTPSEverywhereEnabled", UNKNOWN) protected: - ~BraveShieldsGetHTTPSEverywhereControlTypeFunction() override {} + ~BraveShieldsGetHTTPSEverywhereEnabledFunction() override {} ResponseAction Run() override; }; diff --git a/browser/resources/settings/default_brave_shields_page/default_brave_shields_browser_proxy.js b/browser/resources/settings/default_brave_shields_page/default_brave_shields_browser_proxy.js index f4635c7bb49..77e1a38027c 100644 --- a/browser/resources/settings/default_brave_shields_page/default_brave_shields_browser_proxy.js +++ b/browser/resources/settings/default_brave_shields_page/default_brave_shields_browser_proxy.js @@ -35,7 +35,7 @@ cr.define('settings', function() { /** * @param {string} value name. */ - setHTTPSEverywhereControlType(value) {} + setHTTPSEverywhereEnabled(value) {} /** * @param {string} value name. @@ -78,8 +78,8 @@ cr.define('settings', function() { } /** @override */ - setHTTPSEverywhereControlType(value) { - chrome.send('setHTTPSEverywhereControlType', [value]); + setHTTPSEverywhereEnabled(value) { + chrome.send('setHTTPSEverywhereEnabled', [value]); } /** @override */ diff --git a/browser/resources/settings/default_brave_shields_page/default_brave_shields_page.js b/browser/resources/settings/default_brave_shields_page/default_brave_shields_page.js index 06e8ad9be1c..dbb3924e689 100644 --- a/browser/resources/settings/default_brave_shields_page/default_brave_shields_page.js +++ b/browser/resources/settings/default_brave_shields_page/default_brave_shields_page.js @@ -85,7 +85,7 @@ Polymer({ this.browserProxy_.setFingerprintingControlType(this.$.fingerprintingControlType.value); }, onHTTPSEverywhereControlChange_: function() { - this.browserProxy_.setHTTPSEverywhereControlType(this.$.httpsEverywhereControlType.checked); + this.browserProxy_.setHTTPSEverywhereEnabled(this.$.httpsEverywhereControlType.checked); }, onNoScriptControlChange_: function() { this.browserProxy_.setNoScriptControlType(this.$.noScriptControlType.checked); diff --git a/browser/ui/webui/settings/default_brave_shields_handler.cc b/browser/ui/webui/settings/default_brave_shields_handler.cc index 1d9241c6b59..22ab715b4b5 100644 --- a/browser/ui/webui/settings/default_brave_shields_handler.cc +++ b/browser/ui/webui/settings/default_brave_shields_handler.cc @@ -46,9 +46,9 @@ void DefaultBraveShieldsHandler::RegisterMessages() { &DefaultBraveShieldsHandler::SetFingerprintingControlType, base::Unretained(this))); web_ui()->RegisterMessageCallback( - "setHTTPSEverywhereControlType", + "setHTTPSEverywhereEnabled", base::BindRepeating( - &DefaultBraveShieldsHandler::SetHTTPSEverywhereControlType, + &DefaultBraveShieldsHandler::SetHTTPSEverywhereEnabled, base::Unretained(this))); web_ui()->RegisterMessageCallback( "setNoScriptControlType", @@ -131,17 +131,16 @@ void DefaultBraveShieldsHandler::SetFingerprintingControlType( GURL()); } -void DefaultBraveShieldsHandler::SetHTTPSEverywhereControlType( +void DefaultBraveShieldsHandler::SetHTTPSEverywhereEnabled( const base::ListValue* args) { CHECK_EQ(args->GetSize(), 1U); CHECK(profile_); bool value; args->GetBoolean(0, &value); - brave_shields::SetHTTPSEverywhereControlType(profile_, - value ? ControlType::BLOCK - : ControlType::ALLOW, - GURL()); + brave_shields::SetHTTPSEverywhereEnabled(profile_, + value, + GURL()); } void DefaultBraveShieldsHandler::SetNoScriptControlType( diff --git a/browser/ui/webui/settings/default_brave_shields_handler.h b/browser/ui/webui/settings/default_brave_shields_handler.h index a2711cc5119..37955d80a24 100644 --- a/browser/ui/webui/settings/default_brave_shields_handler.h +++ b/browser/ui/webui/settings/default_brave_shields_handler.h @@ -1,4 +1,5 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public +/* Copyright (c) 2019 The Brave Authors. All rights reserved. + * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this file, * You can obtain one at http://mozilla.org/MPL/2.0/. */ @@ -26,8 +27,8 @@ class DefaultBraveShieldsHandler : public settings::SettingsPageUIHandler { void GetCookieControlType(const base::ListValue* args); void SetFingerprintingControlType(const base::ListValue* args); void GetFingerprintingControlType(const base::ListValue* args); - void SetHTTPSEverywhereControlType(const base::ListValue* args); - void GetHTTPSEverywhereControlType(const base::ListValue* args); + void SetHTTPSEverywhereEnabled(const base::ListValue* args); + void GetHTTPSEverywhereEnabled(const base::ListValue* args); void SetNoScriptControlType(const base::ListValue* args); void GetNoScriptControlType(const base::ListValue* args); diff --git a/common/extensions/api/brave_shields.json b/common/extensions/api/brave_shields.json index f60b6008ac4..e52b041cfd4 100644 --- a/common/extensions/api/brave_shields.json +++ b/common/extensions/api/brave_shields.json @@ -29,22 +29,28 @@ ], "functions": [ { - "name": "setBraveShieldsControlType", + "name": "setBraveShieldsEnabled", "type": "function", "description": "Set brave shields control type for a url", "parameters": [ { - "name": "controlType", - "type": "string" + "name": "enabled", + "type": "boolean" }, { "name": "url", "type": "string" + }, + { + "type": "function", + "name": "callback", + "optional": true, + "parameters": [] } ] }, { - "name": "getBraveShieldsControlType", + "name": "getBraveShieldsEnabled", "type": "function", "description": "Get brave shields control type for a url", "parameters": [ @@ -57,8 +63,8 @@ "name": "callback", "parameters": [ { - "name": "controlType", - "type": "string" + "name": "enabled", + "type": "boolean" } ] } @@ -76,6 +82,12 @@ { "name": "url", "type": "string" + }, + { + "type": "function", + "name": "callback", + "optional": true, + "parameters": [] } ] }, @@ -112,6 +124,12 @@ { "name": "url", "type": "string" + }, + { + "type": "function", + "name": "callback", + "optional": true, + "parameters": [] } ] }, @@ -148,6 +166,12 @@ { "name": "url", "type": "string" + }, + { + "type": "function", + "name": "callback", + "optional": true, + "parameters": [] } ] }, @@ -173,22 +197,28 @@ ] }, { - "name": "setHTTPSEverywhereControlType", + "name": "setHTTPSEverywhereEnabled", "type": "function", "description": "Set httpse control type for a url", "parameters": [ { - "name": "controlType", - "type": "string" + "name": "enabled", + "type": "boolean" }, { "name": "url", "type": "string" + }, + { + "type": "function", + "name": "callback", + "optional": true, + "parameters": [] } ] }, { - "name": "getHTTPSEverywhereControlType", + "name": "getHTTPSEverywhereEnabled", "type": "function", "description": "Get httpse control type for a url", "parameters": [ @@ -201,8 +231,8 @@ "name": "callback", "parameters": [ { - "name": "controlType", - "type": "string" + "name": "enabled", + "type": "boolean" } ] } @@ -220,6 +250,12 @@ { "name": "url", "type": "string" + }, + { + "type": "function", + "name": "callback", + "optional": true, + "parameters": [] } ] }, diff --git a/components/brave_extension/extension/brave_extension/background.ts b/components/brave_extension/extension/brave_extension/background.ts index 35ee4f1de77..d7cb83657df 100644 --- a/components/brave_extension/extension/brave_extension/background.ts +++ b/components/brave_extension/extension/brave_extension/background.ts @@ -7,7 +7,7 @@ global.Promise = bluebird function promisifier (method: any) { // return a function - return function promisified (...args: string[]) { + return function promisified (...args: any[]) { // which returns a promise return new Promise((resolve: any) => { args.push(resolve) diff --git a/components/brave_extension/extension/brave_extension/background/api/shieldsAPI.ts b/components/brave_extension/extension/brave_extension/background/api/shieldsAPI.ts index 4f73fec4a32..c8b0be4a8fe 100644 --- a/components/brave_extension/extension/brave_extension/background/api/shieldsAPI.ts +++ b/components/brave_extension/extension/brave_extension/background/api/shieldsAPI.ts @@ -22,9 +22,9 @@ export const getShieldSettingsForTabData = (tabData?: chrome.tabs.Tab) => { const hostname = url.hostname return Promise.all([ - chrome.braveShields.getBraveShieldsControlTypeAsync(tabData.url), + chrome.braveShields.getBraveShieldsEnabledAsync(tabData.url), chrome.braveShields.getAdControlTypeAsync(tabData.url), - chrome.braveShields.getHTTPSEverywhereControlTypeAsync(tabData.url), + chrome.braveShields.getHTTPSEverywhereEnabledAsync(tabData.url), chrome.braveShields.getNoScriptControlTypeAsync(tabData.url), chrome.braveShields.getFingerprintingControlTypeAsync(tabData.url), chrome.braveShields.getCookieControlTypeAsync(tabData.url) @@ -34,10 +34,10 @@ export const getShieldSettingsForTabData = (tabData?: chrome.tabs.Tab) => { origin, hostname, id: tabData.id, - braveShields: details[0], + braveShields: details[0] ? 'allow' : 'block', ads: details[1], trackers: details[1], - httpUpgradableResources: details[2], + httpUpgradableResources: details[2] ? 'block' : 'allow', javascript: details[3], fingerprinting: details[4], cookies: details[5] @@ -84,7 +84,7 @@ export const requestShieldPanelData = (tabId: number) => * @return a promise which resolves when the setting is set */ export const setAllowBraveShields = (origin: string, setting: string) => - chrome.braveShields.setBraveShieldsControlTypeAsync(setting, origin) + chrome.braveShields.setBraveShieldsEnabledAsync(setting === 'allow' ? true : false, origin) /** * Changes the ads at origin to be allowed or blocked. @@ -103,8 +103,9 @@ export const setAllowAds = (origin: string, setting: string) => * @param {string} setting 'allow' or 'block' * @return a promise which resolves with the setting is set */ -export const setAllowTrackers = (origin: string, setting: string) => - chrome.braveShields.setAdControlTypeAsync(setting, origin) +export const setAllowTrackers = (origin: string, setting: string) => { + return chrome.braveShields.setAdControlTypeAsync(setting, origin) +} /** * Changes the http upgrdabable resources to be allows as is or blocked. @@ -113,7 +114,7 @@ export const setAllowTrackers = (origin: string, setting: string) => * @return a promise which resolves when the setting is set */ export const setAllowHTTPUpgradableResources = (origin: string, setting: BlockOptions) => - chrome.braveShields.setHTTPSEverywhereControlTypeAsync(setting, origin) + chrome.braveShields.setHTTPSEverywhereEnabledAsync(setting === 'allow' ? false : true, origin) /** * Changes the Javascript to be on (allow) or off (block) diff --git a/components/brave_extension/extension/brave_extension/components/advancedView/header.tsx b/components/brave_extension/extension/brave_extension/components/advancedView/header.tsx index 4c1194278b0..4f0ba5d17fe 100644 --- a/components/brave_extension/extension/brave_extension/components/advancedView/header.tsx +++ b/components/brave_extension/extension/brave_extension/components/advancedView/header.tsx @@ -28,8 +28,7 @@ import { import { getLocale } from '../../background/api/localeAPI' import { blockedResourcesSize, - getTotalBlockedSizeStrings, - getToggleStateViaEventTarget + getTotalBlockedSizeStrings } from '../../helpers/shieldsUtils' // Types @@ -71,8 +70,8 @@ export default class Header extends React.PureComponent { return getTotalBlockedSizeStrings(this.blockedItemsSize, httpsUpgrades) } - onToggleShields = (event: React.ChangeEvent) => { - const shieldsOption: BlockOptions = getToggleStateViaEventTarget(event) + onToggleShieldsMain = (event: React.ChangeEvent) => { + const shieldsOption: BlockOptions = event.target.checked ? 'allow' : 'block' this.props.shieldsToggled(shieldsOption) } @@ -91,7 +90,7 @@ export default class Header extends React.PureComponent { {enabled ? {getLocale('enabledMessage')} : null} - + diff --git a/components/brave_shields/browser/brave_shields_util.cc b/components/brave_shields/browser/brave_shields_util.cc index 364b7c13884..9cc76fec838 100644 --- a/components/brave_shields/browser/brave_shields_util.cc +++ b/components/brave_shields/browser/brave_shields_util.cc @@ -97,11 +97,27 @@ ControlType ControlTypeFromString(const std::string& string) { } } -void SetBraveShieldsControlType(Profile* profile, - ControlType type, - const GURL& url) { - DCHECK(type != ControlType::BLOCK_THIRD_PARTY); +void SetBraveShieldsEnabled(Profile* profile, + bool enable, + const GURL& url) { + if (url.is_valid() && !url.SchemeIsHTTPOrHTTPS()) + return; + + auto primary_pattern = GetPatternFromURL(url, true); + if (!primary_pattern.IsValid()) + return; + + HostContentSettingsMapFactory::GetForProfile(profile) + ->SetContentSettingCustomScope( + primary_pattern, ContentSettingsPattern::Wildcard(), + CONTENT_SETTINGS_TYPE_PLUGINS, kBraveShields, + // this is 'allow_brave_shields' so 'enable' == 'allow' + enable ? CONTENT_SETTING_ALLOW : CONTENT_SETTING_BLOCK); +} + +void ResetBraveShieldsEnabled(Profile* profile, + const GURL& url) { if (url.is_valid() && !url.SchemeIsHTTPOrHTTPS()) return; @@ -114,27 +130,28 @@ void SetBraveShieldsControlType(Profile* profile, ->SetContentSettingCustomScope( primary_pattern, ContentSettingsPattern::Wildcard(), CONTENT_SETTINGS_TYPE_PLUGINS, kBraveShields, - GetDefaultAllowFromControlType(type)); + CONTENT_SETTING_DEFAULT); } -ControlType GetBraveShieldsControlType(Profile* profile, const GURL& url) { +bool GetBraveShieldsEnabled(Profile* profile, const GURL& url) { if (url.is_valid() && !url.SchemeIsHTTPOrHTTPS()) - return ControlType::BLOCK; + return false; ContentSetting setting = HostContentSettingsMapFactory::GetForProfile(profile)->GetContentSetting( url, GURL(), CONTENT_SETTINGS_TYPE_PLUGINS, kBraveShields); - return setting == CONTENT_SETTING_BLOCK ? ControlType::BLOCK - : ControlType::ALLOW; + // see EnableBraveShields - allow and default == true + return setting == CONTENT_SETTING_BLOCK ? false : true; } void SetAdControlType(Profile* profile, ControlType type, const GURL& url) { DCHECK(type != ControlType::BLOCK_THIRD_PARTY); auto primary_pattern = GetPatternFromURL(url); - if (!primary_pattern.IsValid()) + if (!primary_pattern.IsValid()) { return; + } HostContentSettingsMapFactory::GetForProfile(profile) ->SetContentSettingCustomScope(primary_pattern, @@ -239,10 +256,9 @@ ControlType GetFingerprintingControlType(Profile* profile, const GURL& url) { } } -void SetHTTPSEverywhereControlType(Profile* profile, - ControlType type, - const GURL& url) { - DCHECK(type != ControlType::BLOCK_THIRD_PARTY); +void SetHTTPSEverywhereEnabled(Profile* profile, + bool enable, + const GURL& url) { auto primary_pattern = GetPatternFromURL(url, true); if (!primary_pattern.IsValid()) @@ -252,17 +268,32 @@ void SetHTTPSEverywhereControlType(Profile* profile, ->SetContentSettingCustomScope( primary_pattern, ContentSettingsPattern::Wildcard(), CONTENT_SETTINGS_TYPE_PLUGINS, kHTTPUpgradableResources, - type == ControlType::ALLOW ? CONTENT_SETTING_ALLOW - : CONTENT_SETTING_BLOCK); + // this is 'allow_http_upgradeable_resources' so enabling + // httpse will set the value to 'BLOCK' + enable ? CONTENT_SETTING_BLOCK : CONTENT_SETTING_ALLOW); } -ControlType GetHTTPSEverywhereControlType(Profile* profile, const GURL& url) { +void ResetHTTPSEverywhereEnabled(Profile* profile, + bool enable, + const GURL& url) { + auto primary_pattern = GetPatternFromURL(url, true); + + if (!primary_pattern.IsValid()) + return; + + HostContentSettingsMapFactory::GetForProfile(profile) + ->SetContentSettingCustomScope( + primary_pattern, ContentSettingsPattern::Wildcard(), + CONTENT_SETTINGS_TYPE_PLUGINS, kHTTPUpgradableResources, + CONTENT_SETTING_DEFAULT); +} + +bool GetHTTPSEverywhereEnabled(Profile* profile, const GURL& url) { ContentSetting setting = HostContentSettingsMapFactory::GetForProfile(profile)->GetContentSetting( url, GURL(), CONTENT_SETTINGS_TYPE_PLUGINS, kHTTPUpgradableResources); - return setting == CONTENT_SETTING_ALLOW ? ControlType::ALLOW - : ControlType::BLOCK; + return setting == CONTENT_SETTING_ALLOW ? false : true; } void SetNoScriptControlType(Profile* profile, diff --git a/components/brave_shields/browser/brave_shields_util.h b/components/brave_shields/browser/brave_shields_util.h index eab6be22273..ad54c83a463 100644 --- a/components/brave_shields/browser/brave_shields_util.h +++ b/components/brave_shields/browser/brave_shields_util.h @@ -35,10 +35,10 @@ ContentSettingsPattern GetPatternFromURL(const GURL& url, std::string ControlTypeToString(ControlType type); ControlType ControlTypeFromString(const std::string& string); -void SetBraveShieldsControlType(Profile* profile, - ControlType type, - const GURL& url); -ControlType GetBraveShieldsControlType(Profile* profile, const GURL& url); +void SetBraveShieldsEnabled(Profile* profile, bool enable, const GURL& url); +// reset to the default value +void ResetBraveShieldsEnabled(Profile* profile, const GURL& url); +bool GetBraveShieldsEnabled(Profile* profile, const GURL& url); void SetAdControlType(Profile* profile, ControlType type, const GURL& url); ControlType GetAdControlType(Profile* profile, const GURL& url); @@ -51,10 +51,11 @@ void SetFingerprintingControlType(Profile* profile, const GURL& url); ControlType GetFingerprintingControlType(Profile* profile, const GURL& url); -void SetHTTPSEverywhereControlType(Profile* profile, - ControlType type, - const GURL& url); -ControlType GetHTTPSEverywhereControlType(Profile* profile, const GURL& url); +void SetHTTPSEverywhereEnabled(Profile* profile, bool enable, const GURL& url); +// reset to the default value +void SetHTTPSEverywhereEnabled(Profile* profile, bool enable, const GURL& url); +void ResetHTTPSEverywhereEnabled(Profile* profile, const GURL& url); +bool GetHTTPSEverywhereEnabled(Profile* profile, const GURL& url); void SetNoScriptControlType(Profile* profile, ControlType type, diff --git a/components/brave_shields/browser/brave_shields_util_unittest.cc b/components/brave_shields/browser/brave_shields_util_unittest.cc index 6db17035099..c808f54dde8 100644 --- a/components/brave_shields/browser/brave_shields_util_unittest.cc +++ b/components/brave_shields/browser/brave_shields_util_unittest.cc @@ -108,7 +108,7 @@ TEST_F(BraveShieldsUtilTest, ControlTypeFromString) { } /* BRAVE_SHIELDS CONTROL */ -TEST_F(BraveShieldsUtilTest, SetBraveShieldsControlType_Default) { +TEST_F(BraveShieldsUtilTest, SetBraveShieldsEnabled_Default) { auto* map = HostContentSettingsMapFactory::GetForProfile(profile()); // settings should be default auto setting = @@ -120,9 +120,8 @@ TEST_F(BraveShieldsUtilTest, SetBraveShieldsControlType_Default) { brave_shields::kBraveShields); EXPECT_EQ(CONTENT_SETTING_DEFAULT, setting); - /* ALLOW */ - brave_shields::SetBraveShieldsControlType(profile(), ControlType::ALLOW, - GURL()); + /* enabled */ + brave_shields::SetBraveShieldsEnabled(profile(), true, GURL()); setting = map->GetContentSetting(GURL(), GURL(), CONTENT_SETTINGS_TYPE_PLUGINS, brave_shields::kBraveShields); @@ -134,9 +133,8 @@ TEST_F(BraveShieldsUtilTest, SetBraveShieldsControlType_Default) { brave_shields::kBraveShields); EXPECT_EQ(CONTENT_SETTING_ALLOW, setting); - /* BLOCK */ - brave_shields::SetBraveShieldsControlType(profile(), ControlType::BLOCK, - GURL()); + /* disabled */ + brave_shields::SetBraveShieldsEnabled(profile(), false, GURL()); setting = map->GetContentSetting(GURL(), GURL(), CONTENT_SETTINGS_TYPE_PLUGINS, brave_shields::kBraveShields); @@ -149,8 +147,7 @@ TEST_F(BraveShieldsUtilTest, SetBraveShieldsControlType_Default) { EXPECT_EQ(CONTENT_SETTING_BLOCK, setting); /* DEFAULT */ - brave_shields::SetBraveShieldsControlType(profile(), ControlType::DEFAULT, - GURL()); + brave_shields::ResetBraveShieldsEnabled(profile(), GURL()); setting = map->GetContentSetting(GURL(), GURL(), CONTENT_SETTINGS_TYPE_PLUGINS, brave_shields::kBraveShields); @@ -163,11 +160,11 @@ TEST_F(BraveShieldsUtilTest, SetBraveShieldsControlType_Default) { EXPECT_EQ(CONTENT_SETTING_DEFAULT, setting); } -TEST_F(BraveShieldsUtilTest, SetBraveShieldsControlType_ForOrigin) { +TEST_F(BraveShieldsUtilTest, SetBraveShieldsEnabled_ForOrigin) { auto* map = HostContentSettingsMapFactory::GetForProfile(profile()); - brave_shields::SetBraveShieldsControlType(profile(), ControlType::ALLOW, - GURL("http://brave.com")); + brave_shields::SetBraveShieldsEnabled(profile(), true, + GURL("http://brave.com")); // setting should apply to origin auto setting = map->GetContentSetting(GURL("http://brave.com"), GURL(), CONTENT_SETTINGS_TYPE_PLUGINS, @@ -187,76 +184,76 @@ TEST_F(BraveShieldsUtilTest, SetBraveShieldsControlType_ForOrigin) { EXPECT_EQ(CONTENT_SETTING_DEFAULT, setting); } -TEST_F(BraveShieldsUtilTest, SetBraveShieldsControlType_IsNotHttpHttps) { - auto setting = brave_shields::GetBraveShieldsControlType( +TEST_F(BraveShieldsUtilTest, SetBraveShieldsEnabled_IsNotHttpHttps) { + auto setting = brave_shields::GetBraveShieldsEnabled( profile(), GURL("chrome://preferences")); - EXPECT_EQ(ControlType::BLOCK, setting); - brave_shields::SetBraveShieldsControlType(profile(), ControlType::ALLOW, - GURL("chrome://preferences")); - setting = brave_shields::GetBraveShieldsControlType( - profile(), GURL("chrome://preferences")); - EXPECT_EQ(ControlType::BLOCK, setting); + EXPECT_EQ(false, setting); + brave_shields::SetBraveShieldsEnabled(profile(), ControlType::ALLOW, + GURL("chrome://preferences")); + setting = brave_shields::GetBraveShieldsEnabled(profile(), + GURL("chrome://preferences")); + EXPECT_EQ(false, setting); setting = - brave_shields::GetBraveShieldsControlType(profile(), GURL("about:blank")); - EXPECT_EQ(ControlType::BLOCK, setting); - brave_shields::SetBraveShieldsControlType(profile(), ControlType::ALLOW, - GURL("about:blank")); - setting = brave_shields::GetBraveShieldsControlType( - profile(), GURL("about:blank")); - EXPECT_EQ(ControlType::BLOCK, setting); + brave_shields::GetBraveShieldsEnabled(profile(), GURL("about:blank")); + EXPECT_EQ(false, setting); + brave_shields::SetBraveShieldsEnabled(profile(), ControlType::ALLOW, + GURL("about:blank")); + setting = + brave_shields::GetBraveShieldsEnabled(profile(), GURL("about:blank")); + EXPECT_EQ(false, setting); } -TEST_F(BraveShieldsUtilTest, GetBraveShieldsControlType_Default) { +TEST_F(BraveShieldsUtilTest, GetBraveShieldsEnabled_Default) { auto* map = HostContentSettingsMapFactory::GetForProfile(profile()); - auto setting = brave_shields::GetBraveShieldsControlType(profile(), GURL()); - EXPECT_EQ(ControlType::ALLOW, setting); + auto setting = brave_shields::GetBraveShieldsEnabled(profile(), GURL()); + EXPECT_EQ(true, setting); /* BLOCK */ map->SetContentSettingCustomScope( ContentSettingsPattern::Wildcard(), ContentSettingsPattern::Wildcard(), CONTENT_SETTINGS_TYPE_PLUGINS, brave_shields::kBraveShields, CONTENT_SETTING_BLOCK); - setting = brave_shields::GetBraveShieldsControlType(profile(), GURL()); - EXPECT_EQ(ControlType::BLOCK, setting); + setting = brave_shields::GetBraveShieldsEnabled(profile(), GURL()); + EXPECT_EQ(false, setting); /* ALLOW */ map->SetContentSettingCustomScope( ContentSettingsPattern::Wildcard(), ContentSettingsPattern::Wildcard(), CONTENT_SETTINGS_TYPE_PLUGINS, brave_shields::kBraveShields, CONTENT_SETTING_ALLOW); - setting = brave_shields::GetBraveShieldsControlType(profile(), GURL()); - EXPECT_EQ(ControlType::ALLOW, setting); + setting = brave_shields::GetBraveShieldsEnabled(profile(), GURL()); + EXPECT_EQ(true, setting); } -TEST_F(BraveShieldsUtilTest, GetBraveShieldsControlType_ForOrigin) { +TEST_F(BraveShieldsUtilTest, GetBraveShieldsEnabled_ForOrigin) { auto* map = HostContentSettingsMapFactory::GetForProfile(profile()); - auto setting = brave_shields::GetBraveShieldsControlType(profile(), GURL()); - EXPECT_EQ(ControlType::ALLOW, setting); - setting = brave_shields::GetBraveShieldsControlType(profile(), - GURL("http://brave.com")); - EXPECT_EQ(ControlType::ALLOW, setting); - setting = brave_shields::GetBraveShieldsControlType( - profile(), GURL("https://brave.com")); - EXPECT_EQ(ControlType::ALLOW, setting); + auto setting = brave_shields::GetBraveShieldsEnabled(profile(), GURL()); + EXPECT_EQ(true, setting); + setting = brave_shields::GetBraveShieldsEnabled(profile(), + GURL("http://brave.com")); + EXPECT_EQ(true, setting); + setting = brave_shields::GetBraveShieldsEnabled(profile(), + GURL("https://brave.com")); + EXPECT_EQ(true, setting); /* BLOCK */ map->SetContentSettingCustomScope( ContentSettingsPattern::FromString("http://brave.com/*"), ContentSettingsPattern::Wildcard(), CONTENT_SETTINGS_TYPE_PLUGINS, brave_shields::kBraveShields, CONTENT_SETTING_BLOCK); - setting = brave_shields::GetBraveShieldsControlType( - profile(), GURL("http://brave.com/*")); - EXPECT_EQ(ControlType::BLOCK, setting); + setting = brave_shields::GetBraveShieldsEnabled(profile(), + GURL("http://brave.com/*")); + EXPECT_EQ(false, setting); // https in unchanged - setting = brave_shields::GetBraveShieldsControlType( - profile(), GURL("https://brave.com")); - EXPECT_EQ(ControlType::ALLOW, setting); + setting = brave_shields::GetBraveShieldsEnabled(profile(), + GURL("https://brave.com")); + EXPECT_EQ(true, setting); // default is unchanged - setting = brave_shields::GetBraveShieldsControlType(profile(), GURL()); - EXPECT_EQ(ControlType::ALLOW, setting); + setting = brave_shields::GetBraveShieldsEnabled(profile(), GURL()); + EXPECT_EQ(true, setting); /* ALLOW */ // change default to block @@ -264,41 +261,41 @@ TEST_F(BraveShieldsUtilTest, GetBraveShieldsControlType_ForOrigin) { ContentSettingsPattern::Wildcard(), ContentSettingsPattern::Wildcard(), CONTENT_SETTINGS_TYPE_PLUGINS, brave_shields::kBraveShields, CONTENT_SETTING_BLOCK); - setting = brave_shields::GetBraveShieldsControlType(profile(), - GURL("http://brave.com")); - EXPECT_EQ(ControlType::BLOCK, setting); - setting = brave_shields::GetBraveShieldsControlType( - profile(), GURL("https://brave.com")); - EXPECT_EQ(ControlType::BLOCK, setting); - setting = brave_shields::GetBraveShieldsControlType(profile(), GURL()); - EXPECT_EQ(ControlType::BLOCK, setting); + setting = brave_shields::GetBraveShieldsEnabled(profile(), + GURL("http://brave.com")); + EXPECT_EQ(false, setting); + setting = brave_shields::GetBraveShieldsEnabled(profile(), + GURL("https://brave.com")); + EXPECT_EQ(false, setting); + setting = brave_shields::GetBraveShieldsEnabled(profile(), GURL()); + EXPECT_EQ(false, setting); // set override to allow map->SetContentSettingCustomScope( ContentSettingsPattern::FromString("http://brave.com/*"), ContentSettingsPattern::Wildcard(), CONTENT_SETTINGS_TYPE_PLUGINS, brave_shields::kBraveShields, CONTENT_SETTING_ALLOW); - setting = brave_shields::GetBraveShieldsControlType(profile(), - GURL("http://brave.com")); - EXPECT_EQ(ControlType::ALLOW, setting); + setting = brave_shields::GetBraveShieldsEnabled(profile(), + GURL("http://brave.com")); + EXPECT_EQ(true, setting); // https in unchanged - setting = brave_shields::GetBraveShieldsControlType( - profile(), GURL("https://brave.com")); - EXPECT_EQ(ControlType::BLOCK, setting); + setting = brave_shields::GetBraveShieldsEnabled(profile(), + GURL("https://brave.com")); + EXPECT_EQ(false, setting); // default is unchanged - setting = brave_shields::GetBraveShieldsControlType(profile(), GURL()); - EXPECT_EQ(ControlType::BLOCK, setting); + setting = brave_shields::GetBraveShieldsEnabled(profile(), GURL()); + EXPECT_EQ(false, setting); } -TEST_F(BraveShieldsUtilTest, GetBraveShieldsControlType_IsNotHttpHttps) { - auto setting = brave_shields::GetBraveShieldsControlType( +TEST_F(BraveShieldsUtilTest, GetBraveShieldsEnabled_IsNotHttpHttps) { + auto setting = brave_shields::GetBraveShieldsEnabled( profile(), GURL("chrome://preferences")); - EXPECT_EQ(ControlType::BLOCK, setting); + EXPECT_EQ(false, setting); setting = - brave_shields::GetBraveShieldsControlType(profile(), GURL("about:blank")); - EXPECT_EQ(ControlType::BLOCK, setting); + brave_shields::GetBraveShieldsEnabled(profile(), GURL("about:blank")); + EXPECT_EQ(false, setting); } /* AD CONTROL */ @@ -909,7 +906,7 @@ TEST_F(BraveShieldsUtilTest, GetFingerprintingControlType_ForOrigin) { } /* HTTPSEVERYWHERE CONTROL */ -TEST_F(BraveShieldsUtilTest, SetHTTPSEverywhereControlType_Default) { +TEST_F(BraveShieldsUtilTest, SetHTTPSEverywhereEnabled_Default) { auto* map = HostContentSettingsMapFactory::GetForProfile(profile()); // settings should be default auto setting = @@ -921,9 +918,8 @@ TEST_F(BraveShieldsUtilTest, SetHTTPSEverywhereControlType_Default) { brave_shields::kHTTPUpgradableResources); EXPECT_EQ(CONTENT_SETTING_DEFAULT, setting); - /* ALLOW */ - brave_shields::SetHTTPSEverywhereControlType(profile(), ControlType::ALLOW, - GURL()); + /* disabled */ + brave_shields::SetHTTPSEverywhereEnabled(profile(), false, GURL()); setting = map->GetContentSetting(GURL(), GURL(), CONTENT_SETTINGS_TYPE_PLUGINS, brave_shields::kHTTPUpgradableResources); @@ -935,9 +931,8 @@ TEST_F(BraveShieldsUtilTest, SetHTTPSEverywhereControlType_Default) { brave_shields::kHTTPUpgradableResources); EXPECT_EQ(CONTENT_SETTING_ALLOW, setting); - /* BLOCK */ - brave_shields::SetHTTPSEverywhereControlType(profile(), ControlType::BLOCK, - GURL()); + /* enabled */ + brave_shields::SetHTTPSEverywhereEnabled(profile(), true, GURL()); setting = map->GetContentSetting(GURL(), GURL(), CONTENT_SETTINGS_TYPE_PLUGINS, brave_shields::kHTTPUpgradableResources); @@ -950,11 +945,11 @@ TEST_F(BraveShieldsUtilTest, SetHTTPSEverywhereControlType_Default) { EXPECT_EQ(CONTENT_SETTING_BLOCK, setting); } -TEST_F(BraveShieldsUtilTest, SetHTTPSEverywhereControlType_ForOrigin) { +TEST_F(BraveShieldsUtilTest, SetHTTPSEverywhereEnabled_ForOrigin) { auto* map = HostContentSettingsMapFactory::GetForProfile(profile()); - brave_shields::SetHTTPSEverywhereControlType(profile(), ControlType::ALLOW, - GURL("http://brave.com")); + brave_shields::SetHTTPSEverywhereEnabled(profile(), false, + GURL("http://brave.com")); // setting should apply to origin auto setting = map->GetContentSetting( GURL("http://brave.com"), GURL(), CONTENT_SETTINGS_TYPE_PLUGINS, @@ -974,59 +969,57 @@ TEST_F(BraveShieldsUtilTest, SetHTTPSEverywhereControlType_ForOrigin) { EXPECT_EQ(CONTENT_SETTING_DEFAULT, setting); } -TEST_F(BraveShieldsUtilTest, GetHTTPSEverywhereControlType_Default) { +TEST_F(BraveShieldsUtilTest, GetHTTPSEverywhereEnabled_Default) { auto* map = HostContentSettingsMapFactory::GetForProfile(profile()); - auto setting = - brave_shields::GetHTTPSEverywhereControlType(profile(), GURL()); - EXPECT_EQ(ControlType::BLOCK, setting); + auto setting = brave_shields::GetHTTPSEverywhereEnabled(profile(), GURL()); + EXPECT_EQ(true, setting); /* ALLOW */ map->SetContentSettingCustomScope( ContentSettingsPattern::Wildcard(), ContentSettingsPattern::Wildcard(), CONTENT_SETTINGS_TYPE_PLUGINS, brave_shields::kHTTPUpgradableResources, CONTENT_SETTING_ALLOW); - setting = brave_shields::GetHTTPSEverywhereControlType(profile(), GURL()); - EXPECT_EQ(ControlType::ALLOW, setting); + setting = brave_shields::GetHTTPSEverywhereEnabled(profile(), GURL()); + EXPECT_EQ(false, setting); /* BLOCK */ map->SetContentSettingCustomScope( ContentSettingsPattern::Wildcard(), ContentSettingsPattern::Wildcard(), CONTENT_SETTINGS_TYPE_PLUGINS, brave_shields::kHTTPUpgradableResources, CONTENT_SETTING_BLOCK); - setting = brave_shields::GetHTTPSEverywhereControlType(profile(), GURL()); - EXPECT_EQ(ControlType::BLOCK, setting); + setting = brave_shields::GetHTTPSEverywhereEnabled(profile(), GURL()); + EXPECT_EQ(true, setting); } -TEST_F(BraveShieldsUtilTest, GetHTTPSEverywhereControlType_ForOrigin) { +TEST_F(BraveShieldsUtilTest, GetHTTPSEverywhereEnabled_ForOrigin) { auto* map = HostContentSettingsMapFactory::GetForProfile(profile()); - auto setting = - brave_shields::GetHTTPSEverywhereControlType(profile(), GURL()); - EXPECT_EQ(ControlType::BLOCK, setting); - setting = brave_shields::GetHTTPSEverywhereControlType( - profile(), GURL("http://brave.com")); - EXPECT_EQ(ControlType::BLOCK, setting); - setting = brave_shields::GetHTTPSEverywhereControlType( - profile(), GURL("https://brave.com")); - EXPECT_EQ(ControlType::BLOCK, setting); + auto setting = brave_shields::GetHTTPSEverywhereEnabled(profile(), GURL()); + EXPECT_EQ(true, setting); + setting = brave_shields::GetHTTPSEverywhereEnabled(profile(), + GURL("http://brave.com")); + EXPECT_EQ(true, setting); + setting = brave_shields::GetHTTPSEverywhereEnabled(profile(), + GURL("https://brave.com")); + EXPECT_EQ(true, setting); /* ALLOW */ map->SetContentSettingCustomScope( ContentSettingsPattern::FromString("http://brave.com/*"), ContentSettingsPattern::Wildcard(), CONTENT_SETTINGS_TYPE_PLUGINS, brave_shields::kHTTPUpgradableResources, CONTENT_SETTING_ALLOW); - setting = brave_shields::GetHTTPSEverywhereControlType( - profile(), GURL("http://brave.com")); + setting = brave_shields::GetHTTPSEverywhereEnabled(profile(), + GURL("http://brave.com")); EXPECT_EQ(ControlType::ALLOW, setting); // https in unchanged - setting = brave_shields::GetHTTPSEverywhereControlType( - profile(), GURL("https://brave.com")); - EXPECT_EQ(ControlType::BLOCK, setting); + setting = brave_shields::GetHTTPSEverywhereEnabled(profile(), + GURL("https://brave.com")); + EXPECT_EQ(true, setting); // default is unchanged - setting = brave_shields::GetHTTPSEverywhereControlType(profile(), GURL()); - EXPECT_EQ(ControlType::BLOCK, setting); + setting = brave_shields::GetHTTPSEverywhereEnabled(profile(), GURL()); + EXPECT_EQ(true, setting); /* BLOCK */ // change default to allow @@ -1034,13 +1027,13 @@ TEST_F(BraveShieldsUtilTest, GetHTTPSEverywhereControlType_ForOrigin) { ContentSettingsPattern::Wildcard(), ContentSettingsPattern::Wildcard(), CONTENT_SETTINGS_TYPE_PLUGINS, brave_shields::kHTTPUpgradableResources, CONTENT_SETTING_ALLOW); - setting = brave_shields::GetHTTPSEverywhereControlType( - profile(), GURL("http://brave.com")); + setting = brave_shields::GetHTTPSEverywhereEnabled(profile(), + GURL("http://brave.com")); EXPECT_EQ(ControlType::ALLOW, setting); - setting = brave_shields::GetHTTPSEverywhereControlType( - profile(), GURL("https://brave.com")); + setting = brave_shields::GetHTTPSEverywhereEnabled(profile(), + GURL("https://brave.com")); EXPECT_EQ(ControlType::ALLOW, setting); - setting = brave_shields::GetHTTPSEverywhereControlType(profile(), GURL()); + setting = brave_shields::GetHTTPSEverywhereEnabled(profile(), GURL()); EXPECT_EQ(ControlType::ALLOW, setting); // set override to block @@ -1048,16 +1041,16 @@ TEST_F(BraveShieldsUtilTest, GetHTTPSEverywhereControlType_ForOrigin) { ContentSettingsPattern::FromString("http://brave.com/*"), ContentSettingsPattern::Wildcard(), CONTENT_SETTINGS_TYPE_PLUGINS, brave_shields::kHTTPUpgradableResources, CONTENT_SETTING_BLOCK); - setting = brave_shields::GetHTTPSEverywhereControlType( + setting = brave_shields::GetHTTPSEverywhereEnabled( profile(), GURL("http://brave.com/*")); - EXPECT_EQ(ControlType::BLOCK, setting); + EXPECT_EQ(true, setting); // https in unchanged - setting = brave_shields::GetHTTPSEverywhereControlType( - profile(), GURL("https://brave.com")); - EXPECT_EQ(ControlType::ALLOW, setting); + setting = brave_shields::GetHTTPSEverywhereEnabled(profile(), + GURL("https://brave.com")); + EXPECT_EQ(false, setting); // default is unchanged - setting = brave_shields::GetHTTPSEverywhereControlType(profile(), GURL()); - EXPECT_EQ(ControlType::ALLOW, setting); + setting = brave_shields::GetHTTPSEverywhereEnabled(profile(), GURL()); + EXPECT_EQ(false, setting); } /* NOSCRIPT CONTROL */ diff --git a/components/definitions/chromel.d.ts b/components/definitions/chromel.d.ts index 19eed062bb7..35522dcfdd4 100644 --- a/components/definitions/chromel.d.ts +++ b/components/definitions/chromel.d.ts @@ -185,16 +185,16 @@ declare namespace chrome.braveShields { } const allowScriptsOnce: any - const setBraveShieldsControlTypeAsync: any - const getBraveShieldsControlTypeAsync: any + const setBraveShieldsEnabledAsync: any + const getBraveShieldsEnabledAsync: any const setAdControlTypeAsync: any const getAdControlTypeAsync: any const setCookieControlTypeAsync: any const getCookieControlTypeAsync: any const setFingerprintingControlTypeAsync: any const getFingerprintingControlTypeAsync: any - const setHTTPSEverywhereControlTypeAsync: any - const getHTTPSEverywhereControlTypeAsync: any + const setHTTPSEverywhereEnabledAsync: any + const getHTTPSEverywhereEnabledAsync: any const setNoScriptControlTypeAsync: any const getNoScriptControlTypeAsync: any diff --git a/components/test/brave_extension/background/api/shieldsAPI_test.ts b/components/test/brave_extension/background/api/shieldsAPI_test.ts index 178948e72db..0617eac5aa7 100644 --- a/components/test/brave_extension/background/api/shieldsAPI_test.ts +++ b/components/test/brave_extension/background/api/shieldsAPI_test.ts @@ -142,12 +142,12 @@ describe('Shields API', () => { describe('setAllowHTTPUpgradableResource', () => { let spy: jest.SpyInstance beforeEach(() => { - spy = jest.spyOn(chrome.braveShields, 'setHTTPSEverywhereControlTypeAsync') + spy = jest.spyOn(chrome.braveShields, 'setHTTPSEverywhereEnabledAsync') }) afterEach(() => { spy.mockRestore() }) - it('calls chrome.braveShields.setHTTPSEverywhereControlTypeAsync with the correct args', () => { + it('calls chrome.braveShields.setHTTPSEverywhereEnabledAsync with the correct args', () => { shieldsAPI.setAllowHTTPUpgradableResources('https://www.brave.com', 'block') .catch(() => { expect(true).toBe(false) @@ -155,7 +155,7 @@ describe('Shields API', () => { const arg0 = spy.mock.calls[0][0] const arg1 = spy.mock.calls[0][1] expect.assertions(2) - expect(arg0).toEqual('block') + expect(arg0).toEqual(true) expect(arg1).toEqual('https://www.brave.com') }) }) diff --git a/components/test/testData.ts b/components/test/testData.ts index 1164de71874..f22a95cf725 100644 --- a/components/test/testData.ts +++ b/components/test/testData.ts @@ -209,8 +209,8 @@ export const getMockChrome = () => { allowScriptsOnce: function (origins: Array, tabId: number, cb: () => void) { setImmediate(cb) }, - getBraveShieldsControlTypeAsync: function (url: string) { - return Promise.resolve('block') + getBraveShieldsEnabledAsync: function (url: string) { + return Promise.resolve(false) }, getAdControlTypeAsync: function (url: string) { return Promise.resolve('block') @@ -221,13 +221,13 @@ export const getMockChrome = () => { getFingerprintingControlTypeAsync: function (url: string) { return Promise.resolve('block') }, - getHTTPSEverywhereControlTypeAsync: function (url: string) { - return Promise.resolve('block') + getHTTPSEverywhereEnabledAsync: function (url: string) { + return Promise.resolve(true) }, getNoScriptControlTypeAsync: function (url: string) { return Promise.resolve('block') }, - setBraveShieldsControlTypeAsync: function (url: string, controlType: string) { + setBraveShieldsEnabledAsync: function (url: string, enabled: boolean) { return new Promise(() => []) }, setAdControlTypeAsync: function (url: string, controlType: string) { @@ -239,7 +239,7 @@ export const getMockChrome = () => { setFingerprintingControlTypeAsync: function (url: string, controlType: string) { return new Promise(() => []) }, - setHTTPSEverywhereControlTypeAsync: function (url: string, controlType: string) { + setHTTPSEverywhereEnabledAsync: function (url: string, enabled: boolean) { return new Promise(() => []) }, setNoScriptControlTypeAsync: function (url: string, controlType: string) { From 4a046499559c641c86eb24bf29dbc11cde35cde0 Mon Sep 17 00:00:00 2001 From: Brian Johnson Date: Wed, 14 Aug 2019 14:26:19 -0700 Subject: [PATCH 3/6] Merge pull request #2988 from brave/shields_network_service_final Issue 2351: Brave NetworkServicification --- browser/BUILD.gn | 4 + browser/brave_content_browser_client.cc | 27 + browser/brave_content_browser_client.h | 11 + .../ad_block_pref_service_factory.cc | 49 ++ .../ad_block_pref_service_factory.h | 44 + ...browser_context_keyed_service_factories.cc | 2 + browser/net/BUILD.gn | 13 + browser/net/brave_network_delegate_base.cc | 34 +- browser/net/brave_network_delegate_base.h | 10 - .../brave_network_delegate_base_unittest.cc | 4 + .../net/brave_proxying_url_loader_factory.cc | 757 ++++++++++++++++++ .../net/brave_proxying_url_loader_factory.h | 243 ++++++ ...brave_referrals_network_delegate_helper.cc | 1 + browser/net/brave_request_handler.cc | 293 +++++++ browser/net/brave_request_handler.h | 77 ++ ...rave_site_hacks_network_delegate_helper.cc | 19 +- ..._hacks_network_delegate_helper_unittest.cc | 55 -- browser/net/brave_stp_util.cc | 44 + browser/net/brave_stp_util.h | 26 + browser/net/url_context.cc | 67 ++ browser/net/url_context.h | 30 +- common/network_constants.cc | 2 - common/network_constants.h | 2 - components/brave_shields/browser/BUILD.gn | 3 + .../brave_shields/browser/ad_block_service.cc | 72 +- .../brave_shields/browser/ad_block_service.h | 19 + .../browser/adblock_stub_response.cc | 113 +++ .../browser/adblock_stub_response.h | 26 + ...direct_network_delegate_helper_unittest.cc | 12 + 29 files changed, 1925 insertions(+), 134 deletions(-) create mode 100644 browser/brave_shields/ad_block_pref_service_factory.cc create mode 100644 browser/brave_shields/ad_block_pref_service_factory.h create mode 100644 browser/net/brave_proxying_url_loader_factory.cc create mode 100644 browser/net/brave_proxying_url_loader_factory.h create mode 100644 browser/net/brave_request_handler.cc create mode 100644 browser/net/brave_request_handler.h create mode 100644 browser/net/brave_stp_util.cc create mode 100644 browser/net/brave_stp_util.h create mode 100644 components/brave_shields/browser/adblock_stub_response.cc create mode 100644 components/brave_shields/browser/adblock_stub_response.h diff --git a/browser/BUILD.gn b/browser/BUILD.gn index 04b7ed4c8c8..48892acc50f 100644 --- a/browser/BUILD.gn +++ b/browser/BUILD.gn @@ -21,6 +21,8 @@ source_set("browser_process") { "autocomplete/brave_autocomplete_provider_client.h", "autocomplete/brave_autocomplete_scheme_classifier.cc", "autocomplete/brave_autocomplete_scheme_classifier.h", + "brave_shields/ad_block_pref_service_factory.cc", + "brave_shields/ad_block_pref_service_factory.h", "brave_browser_main_extra_parts.cc", "brave_browser_main_extra_parts.h", "brave_browser_main_parts.cc", @@ -108,6 +110,7 @@ source_set("browser_process") { "//brave/components/brave_drm", "//brave/components/brave_referrals/browser", "//brave/components/brave_rewards/browser", + "//brave/components/brave_shields/browser", "//brave/components/brave_sync", "//brave/components/brave_wallet/browser", "//brave/components/brave_webtorrent/browser/buildflags", @@ -120,6 +123,7 @@ source_set("browser_process") { "//components/browsing_data/core", "//components/component_updater", "//components/content_settings/core/common", + "//components/keyed_service/content", "//components/password_manager/core/common", "//components/prefs", "//components/safe_browsing/common:safe_browsing_prefs", diff --git a/browser/brave_content_browser_client.cc b/browser/brave_content_browser_client.cc index 08d3929c16a..1560cd178bf 100644 --- a/browser/brave_content_browser_client.cc +++ b/browser/brave_content_browser_client.cc @@ -15,6 +15,7 @@ #include "brave/browser/brave_browser_main_extra_parts.h" #include "brave/browser/brave_browser_process_impl.h" #include "brave/browser/extensions/brave_tor_client_updater.h" +#include "brave/browser/net/brave_proxying_url_loader_factory.h" #include "brave/browser/tor/buildflags.h" #include "brave/common/webui_url_constants.h" #include "brave/components/brave_ads/browser/buildflags/buildflags.h" @@ -266,6 +267,32 @@ void BraveContentBrowserClient::AdjustUtilityServiceProcessCommandLine( #endif } +bool BraveContentBrowserClient::WillCreateURLLoaderFactory( + content::BrowserContext* browser_context, + content::RenderFrameHost* frame, + int render_process_id, + bool is_navigation, + bool is_download, + const url::Origin& request_initiator, + network::mojom::URLLoaderFactoryRequest* factory_request, + network::mojom::TrustedURLLoaderHeaderClientPtrInfo* header_client, + bool* bypass_redirect_checks) { + bool use_proxy = false; + + use_proxy = ChromeContentBrowserClient::WillCreateURLLoaderFactory( + browser_context, + frame, render_process_id, is_navigation, is_download, request_initiator, + factory_request, header_client, bypass_redirect_checks); + + // TODO(iefremov): Skip proxying for certain requests? + use_proxy |= BraveProxyingURLLoaderFactory::MaybeProxyRequest( + browser_context, + frame, is_navigation ? -1 : render_process_id, + factory_request); + return use_proxy; +} + + void BraveContentBrowserClient::MaybeHideReferrer( content::BrowserContext* browser_context, const GURL& request_url, diff --git a/browser/brave_content_browser_client.h b/browser/brave_content_browser_client.h index 4f5a0ffad21..6fdc0fa8d5f 100644 --- a/browser/brave_content_browser_client.h +++ b/browser/brave_content_browser_client.h @@ -66,6 +66,17 @@ class BraveContentBrowserClient : public ChromeContentBrowserClient { const service_manager::Identity& identity, base::CommandLine* command_line) override; + bool WillCreateURLLoaderFactory( + content::BrowserContext* browser_context, + content::RenderFrameHost* frame, + int render_process_id, + bool is_navigation, + bool is_download, + const url::Origin& request_initiator, + network::mojom::URLLoaderFactoryRequest* factory_request, + network::mojom::TrustedURLLoaderHeaderClientPtrInfo* header_client, + bool* bypass_redirect_checks) override; + void MaybeHideReferrer(content::BrowserContext* browser_context, const GURL& request_url, const GURL& document_url, diff --git a/browser/brave_shields/ad_block_pref_service_factory.cc b/browser/brave_shields/ad_block_pref_service_factory.cc new file mode 100644 index 00000000000..5a942b5c979 --- /dev/null +++ b/browser/brave_shields/ad_block_pref_service_factory.cc @@ -0,0 +1,49 @@ +/* Copyright (c) 2019 The Brave Authors. All rights reserved. + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this file, + * You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#include "brave/browser/brave_shields/ad_block_pref_service_factory.h" +#include "brave/components/brave_shields/browser/ad_block_service.h" +#include "chrome/browser/profiles/incognito_helpers.h" +#include "chrome/browser/profiles/profile.h" +#include "components/keyed_service/content/browser_context_dependency_manager.h" + +namespace brave_shields { + +// static +AdBlockPrefService* AdBlockPrefServiceFactory::GetForBrowserContext( + content::BrowserContext* context) { + return static_cast( + GetInstance()->GetServiceForBrowserContext(context, + /*create_service=*/true)); +} + +// static +AdBlockPrefServiceFactory* AdBlockPrefServiceFactory::GetInstance() { + return base::Singleton::get(); +} + +AdBlockPrefServiceFactory::AdBlockPrefServiceFactory() + : BrowserContextKeyedServiceFactory( + "AdBlockPrefService", + BrowserContextDependencyManager::GetInstance()) {} + +AdBlockPrefServiceFactory::~AdBlockPrefServiceFactory() {} + +KeyedService* AdBlockPrefServiceFactory::BuildServiceInstanceFor( + content::BrowserContext* context) const { + return new AdBlockPrefService( + Profile::FromBrowserContext(context)->GetPrefs()); +} + +content::BrowserContext* AdBlockPrefServiceFactory::GetBrowserContextToUse( + content::BrowserContext* context) const { + return chrome::GetBrowserContextRedirectedInIncognito(context); +} + +bool AdBlockPrefServiceFactory::ServiceIsCreatedWithBrowserContext() const { + return true; +} + +} // namespace brave_shields diff --git a/browser/brave_shields/ad_block_pref_service_factory.h b/browser/brave_shields/ad_block_pref_service_factory.h new file mode 100644 index 00000000000..dc02c13a039 --- /dev/null +++ b/browser/brave_shields/ad_block_pref_service_factory.h @@ -0,0 +1,44 @@ +/* Copyright (c) 2019 The Brave Authors. All rights reserved. + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this file, + * You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#ifndef BRAVE_BROWSER_BRAVE_SHIELDS_AD_BLOCK_PREF_SERVICE_FACTORY_H_ +#define BRAVE_BROWSER_BRAVE_SHIELDS_AD_BLOCK_PREF_SERVICE_FACTORY_H_ + +#include "base/memory/singleton.h" +#include "components/keyed_service/content/browser_context_keyed_service_factory.h" + +namespace brave_shields { + +class AdBlockPrefService; + +class AdBlockPrefServiceFactory : public BrowserContextKeyedServiceFactory { + public: + static AdBlockPrefService* GetForBrowserContext( + content::BrowserContext* context); + + static AdBlockPrefServiceFactory* GetInstance(); + + private: + friend struct base::DefaultSingletonTraits; + + AdBlockPrefServiceFactory(); + ~AdBlockPrefServiceFactory() override; + + // BrowserContextKeyedServiceFactory: + KeyedService* BuildServiceInstanceFor( + content::BrowserContext* profile) const override; + + // We use the same service in both normal and incognito modes. + content::BrowserContext* GetBrowserContextToUse( + content::BrowserContext* context) const override; + + bool ServiceIsCreatedWithBrowserContext() const override; + + DISALLOW_COPY_AND_ASSIGN(AdBlockPrefServiceFactory); +}; + +} // namespace brave_shields + +#endif // BRAVE_BROWSER_BRAVE_SHIELDS_AD_BLOCK_PREF_SERVICE_FACTORY_H_ diff --git a/browser/browser_context_keyed_service_factories.cc b/browser/browser_context_keyed_service_factories.cc index ccfcc3f5e0c..bd30e4581d6 100644 --- a/browser/browser_context_keyed_service_factories.cc +++ b/browser/browser_context_keyed_service_factories.cc @@ -5,6 +5,7 @@ #include "brave/browser/browser_context_keyed_service_factories.h" +#include "brave/browser/brave_shields/ad_block_pref_service_factory.h" #include "brave/browser/greaselion/greaselion_service_factory.h" #include "brave/browser/search_engines/search_engine_provider_service_factory.h" #include "brave/browser/tor/tor_profile_service_factory.h" @@ -20,6 +21,7 @@ namespace brave { void EnsureBrowserContextKeyedServiceFactoriesBuilt() { brave_ads::AdsServiceFactory::GetInstance(); brave_rewards::RewardsServiceFactory::GetInstance(); + brave_shields::AdBlockPrefServiceFactory::GetInstance(); greaselion::GreaselionServiceFactory::GetInstance(); TorProfileServiceFactory::GetInstance(); SearchEngineProviderServiceFactory::GetInstance(); diff --git a/browser/net/BUILD.gn b/browser/net/BUILD.gn index ba8ce6dce3a..14cefeda541 100644 --- a/browser/net/BUILD.gn +++ b/browser/net/BUILD.gn @@ -16,10 +16,16 @@ source_set("net") { "brave_network_delegate_base.h", "brave_profile_network_delegate.cc", "brave_profile_network_delegate.h", + "brave_proxying_url_loader_factory.cc", + "brave_proxying_url_loader_factory.h", + "brave_request_handler.cc", + "brave_request_handler.h", "brave_site_hacks_network_delegate_helper.cc", "brave_site_hacks_network_delegate_helper.h", "brave_static_redirect_network_delegate_helper.cc", "brave_static_redirect_network_delegate_helper.h", + "brave_stp_util.cc", + "brave_stp_util.h", "brave_system_network_delegate.cc", "brave_system_network_delegate.h", "url_context.cc", @@ -30,10 +36,17 @@ source_set("net") { "//base", "//brave/app:brave_generated_resources_grit", "//brave/browser/safebrowsing", + "//brave/components/brave_shields/browser", + "//components/prefs", "//content/public/browser", "//content/public/common", "//extensions/common:common_constants", + "//mojo/public/cpp/bindings", + "//mojo/public/cpp/system", "//net", + "//services/network/public/cpp", + "//services/network/public/mojom", + "//url", ] if (is_android) { diff --git a/browser/net/brave_network_delegate_base.cc b/browser/net/brave_network_delegate_base.cc index 0cd96f028ea..4376a3940ec 100644 --- a/browser/net/brave_network_delegate_base.cc +++ b/browser/net/brave_network_delegate_base.cc @@ -10,6 +10,7 @@ #include "base/task/post_task.h" #include "brave/browser/brave_browser_process_impl.h" +#include "brave/browser/net/brave_stp_util.h" #include "brave/common/pref_names.h" #include "brave/components/brave_shields/browser/brave_shields_util.h" #include "brave/components/brave_shields/browser/brave_shields_web_contents_observer.h" @@ -22,7 +23,6 @@ #include "components/prefs/pref_service.h" #include "content/public/browser/browser_task_traits.h" #include "content/public/browser/browser_thread.h" -#include "net/base/registry_controlled_domains/registry_controlled_domain.h" #include "net/url_request/url_request.h" using content::BrowserThread; @@ -66,36 +66,6 @@ bool OnAllowAccessCookies( } // namespace -base::flat_set* TrackableSecurityHeaders() { - static base::NoDestructor> - kTrackableSecurityHeaders(base::flat_set{ - "Strict-Transport-Security", "Expect-CT", "Public-Key-Pins", - "Public-Key-Pins-Report-Only"}); - return kTrackableSecurityHeaders.get(); -} - -void RemoveTrackableSecurityHeadersForThirdParty( - const GURL& request_url, const url::Origin& top_frame_origin, - const net::HttpResponseHeaders* original_response_headers, - scoped_refptr* override_response_headers) { - if (!original_response_headers && !override_response_headers->get()) { - return; - } - - if (net::registry_controlled_domains::SameDomainOrHost( - request_url, top_frame_origin, - net::registry_controlled_domains::INCLUDE_PRIVATE_REGISTRIES)) { - return; - } - - if (!override_response_headers->get()) { - *override_response_headers = - new net::HttpResponseHeaders(original_response_headers->raw_headers()); - } - for (auto header : *TrackableSecurityHeaders()) { - (*override_response_headers)->RemoveHeader(header.as_string()); - } -} BraveNetworkDelegateBase::BraveNetworkDelegateBase( extensions::EventRouterForwarder* event_router) @@ -190,7 +160,7 @@ int BraveNetworkDelegateBase::OnHeadersReceived( scoped_refptr* override_response_headers, GURL* allowed_unsafe_redirect_url) { if (request->top_frame_origin().has_value()) { - RemoveTrackableSecurityHeadersForThirdParty( + brave::RemoveTrackableSecurityHeadersForThirdParty( request->url(), request->top_frame_origin().value(), original_response_headers, override_response_headers); } diff --git a/browser/net/brave_network_delegate_base.h b/browser/net/brave_network_delegate_base.h index 45bb7929c76..0a3a9db1f38 100644 --- a/browser/net/brave_network_delegate_base.h +++ b/browser/net/brave_network_delegate_base.h @@ -11,9 +11,6 @@ #include #include -#include "base/containers/flat_set.h" -#include "base/files/file_path.h" -#include "base/strings/string_piece.h" #include "brave/browser/net/url_context.h" #include "chrome/browser/net/chrome_network_delegate.h" #include "content/public/browser/browser_thread.h" @@ -29,13 +26,6 @@ namespace net { class URLRequest; } -base::flat_set* TrackableSecurityHeaders(); - -void RemoveTrackableSecurityHeadersForThirdParty( - const GURL& request_url, const url::Origin& top_frame_origin, - const net::HttpResponseHeaders* original_response_headers, - scoped_refptr* override_response_headers); - // BraveNetworkDelegateBase is the central point from within the Brave code to // add hooks into the network stack. class BraveNetworkDelegateBase : public ChromeNetworkDelegate { diff --git a/browser/net/brave_network_delegate_base_unittest.cc b/browser/net/brave_network_delegate_base_unittest.cc index 790ee5a3281..ba7559f34a1 100644 --- a/browser/net/brave_network_delegate_base_unittest.cc +++ b/browser/net/brave_network_delegate_base_unittest.cc @@ -8,13 +8,17 @@ #include #include "brave/browser/net/url_context.h" +#include "brave/browser/net/brave_stp_util.h" #include "chrome/test/base/chrome_render_view_host_test_harness.h" #include "net/traffic_annotation/network_traffic_annotation_test_helper.h" #include "net/url_request/url_request_test_util.h" #include "url/gurl.h" +using brave::RemoveTrackableSecurityHeadersForThirdParty; +using brave::TrackableSecurityHeaders; using net::HttpResponseHeaders; + namespace { const char kFirstPartyDomain[] = "http://firstparty.com/"; diff --git a/browser/net/brave_proxying_url_loader_factory.cc b/browser/net/brave_proxying_url_loader_factory.cc new file mode 100644 index 00000000000..6a1344efb5e --- /dev/null +++ b/browser/net/brave_proxying_url_loader_factory.cc @@ -0,0 +1,757 @@ +/* Copyright 2019 The Brave Authors. All rights reserved. + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this file, + * You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#include "brave/browser/net/brave_proxying_url_loader_factory.h" + +#include + +#include "base/bind.h" +#include "base/feature_list.h" +#include "base/strings/stringprintf.h" +#include "base/task/post_task.h" +#include "brave/browser/net/brave_request_handler.h" +#include "brave/components/brave_shields/browser/adblock_stub_response.h" +#include "content/public/browser/browser_context.h" +#include "content/public/browser/browser_task_traits.h" +#include "content/public/browser/render_frame_host.h" +#include "content/public/browser/resource_context.h" +#include "content/public/common/url_utils.h" +#include "mojo/public/cpp/system/string_data_pipe_producer.h" +#include "net/base/completion_repeating_callback.h" +#include "net/http/http_util.h" +#include "services/network/public/cpp/features.h" +#include "url/origin.h" + +namespace { + +// User data key for ResourceContextData. +const void* const kResourceContextUserDataKey = &kResourceContextUserDataKey; + +class ResourceContextData : public base::SupportsUserData::Data { + public: + ~ResourceContextData() override {} + + static void StartProxying( + content::ResourceContext* resource_context, + int render_process_id, + int frame_tree_node_id, + network::mojom::URLLoaderFactoryRequest request, + network::mojom::URLLoaderFactoryPtrInfo target_factory) { + DCHECK_CURRENTLY_ON(content::BrowserThread::IO); + + auto* self = static_cast( + resource_context->GetUserData(kResourceContextUserDataKey)); + if (!self) { + self = new ResourceContextData(); + resource_context->SetUserData(kResourceContextUserDataKey, + base::WrapUnique(self)); + } + + if (!self->request_handler_) { + self->request_handler_.reset(new BraveRequestHandler); + } + + auto proxy = std::make_unique( + self->request_handler_.get(), resource_context, render_process_id, + frame_tree_node_id, std::move(request), std::move(target_factory), + self->request_id_generator_, + base::BindOnce(&ResourceContextData::RemoveProxy, + self->weak_factory_.GetWeakPtr())); + + self->proxies_.emplace(std::move(proxy)); + } + + void RemoveProxy(BraveProxyingURLLoaderFactory* proxy) { + auto it = proxies_.find(proxy); + DCHECK(it != proxies_.end()); + proxies_.erase(it); + } + + private: + ResourceContextData() + : request_id_generator_(base::MakeRefCounted()), + weak_factory_(this) {} + + std::unique_ptr request_handler_; + scoped_refptr request_id_generator_; + + std::set, + base::UniquePtrComparator> + proxies_; + + base::WeakPtrFactory weak_factory_; + + DISALLOW_COPY_AND_ASSIGN(ResourceContextData); +}; + +// Helper struct for crafting responses. +struct WriteData { + // Wek ref. |client| destroys itself in |OnComplete()|. + network::mojom::URLLoaderClient* client; + std::string data; + std::unique_ptr producer; +}; + +void OnWrite(std::unique_ptr write_data, MojoResult result) { + if (result != MOJO_RESULT_OK) { + network::URLLoaderCompletionStatus status(net::ERR_FAILED); + write_data->client->OnComplete(status); + 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); +} + +} // namespace + +BraveProxyingURLLoaderFactory::InProgressRequest::FollowRedirectParams:: + FollowRedirectParams() = default; +BraveProxyingURLLoaderFactory::InProgressRequest::FollowRedirectParams:: + ~FollowRedirectParams() = default; + +BraveProxyingURLLoaderFactory::InProgressRequest::InProgressRequest( + BraveProxyingURLLoaderFactory* factory, + uint64_t request_id, + int32_t network_service_request_id, + int32_t routing_id, + int render_process_id, + int frame_tree_node_id, + uint32_t options, + const network::ResourceRequest& request, + content::ResourceContext* resource_context, + const net::MutableNetworkTrafficAnnotationTag& traffic_annotation, + network::mojom::URLLoaderRequest loader_request, + network::mojom::URLLoaderClientPtr client) + : factory_(factory), + request_(request), + request_id_(request_id), + network_service_request_id_(network_service_request_id), + render_process_id_(render_process_id), + frame_tree_node_id_(frame_tree_node_id), + routing_id_(routing_id), + options_(options), + resource_context_(resource_context), + traffic_annotation_(traffic_annotation), + proxied_loader_binding_(this, std::move(loader_request)), + target_client_(std::move(client)), + proxied_client_binding_(this), + weak_factory_(this) { + // If there is a client error, clean up the request. + target_client_.set_connection_error_handler(base::BindOnce( + &BraveProxyingURLLoaderFactory::InProgressRequest::OnRequestError, + weak_factory_.GetWeakPtr(), + network::URLLoaderCompletionStatus(net::ERR_ABORTED))); +} + +BraveProxyingURLLoaderFactory::InProgressRequest::~InProgressRequest() { + if (ctx_) { + factory_->request_handler_->OnURLRequestDestroyed(ctx_); + } +} + +void BraveProxyingURLLoaderFactory::InProgressRequest::Restart() { + UpdateRequestInfo(); + RestartInternal(); +} + +void BraveProxyingURLLoaderFactory::InProgressRequest::UpdateRequestInfo() { + // TODO(iefremov): Update |ctx_| here and get rid of multiple spots where + // it is refilled. +} + +void BraveProxyingURLLoaderFactory::InProgressRequest::RestartInternal() { + request_completed_ = false; + + base::RepeatingCallback continuation = + base::BindRepeating(&InProgressRequest::ContinueToBeforeSendHeaders, + weak_factory_.GetWeakPtr()); + redirect_url_ = GURL(); + ctx_ = std::make_shared(); + brave::BraveRequestInfo::FillCTX(request_, render_process_id_, + frame_tree_node_id_, request_id_, + resource_context_, ctx_); + int result = factory_->request_handler_->OnBeforeURLRequest( + ctx_, continuation, &redirect_url_); + + if (result == net::ERR_BLOCKED_BY_CLIENT) { + // The request was cancelled synchronously. Dispatch an error notification + // and terminate the request. + network::URLLoaderCompletionStatus status(result); + OnRequestError(status); + return; + } + + if (result == net::ERR_IO_PENDING) { + // One or more listeners is blocking, so the request must be paused until + // they respond. |continuation| above will be invoked asynchronously to + // continue or cancel the request. + // + // We pause the binding here to prevent further client message processing. + if (proxied_client_binding_.is_bound()) + proxied_client_binding_.PauseIncomingMethodCallProcessing(); + + return; + } + DCHECK_EQ(net::OK, result); + + continuation.Run(net::OK); +} + +void BraveProxyingURLLoaderFactory::InProgressRequest::FollowRedirect( + const std::vector& removed_headers, + const net::HttpRequestHeaders& modified_headers, + const base::Optional& new_url) { + if (new_url) + request_.url = new_url.value(); + + for (const std::string& header : removed_headers) + request_.headers.RemoveHeader(header); + request_.headers.MergeFrom(modified_headers); + + UpdateRequestInfo(); + + if (target_loader_.is_bound()) { + auto params = std::make_unique(); + params->removed_headers = removed_headers; + params->modified_headers = modified_headers; + params->new_url = new_url; + pending_follow_redirect_params_ = std::move(params); + } + + RestartInternal(); +} + +void BraveProxyingURLLoaderFactory::InProgressRequest::ProceedWithResponse() { + if (target_loader_.is_bound()) + target_loader_->ProceedWithResponse(); +} + +void BraveProxyingURLLoaderFactory::InProgressRequest::SetPriority( + net::RequestPriority priority, + int32_t intra_priority_value) { + if (target_loader_.is_bound()) + target_loader_->SetPriority(priority, intra_priority_value); +} + +void BraveProxyingURLLoaderFactory::InProgressRequest:: + PauseReadingBodyFromNet() { + if (target_loader_.is_bound()) + target_loader_->PauseReadingBodyFromNet(); +} + +void BraveProxyingURLLoaderFactory::InProgressRequest:: + ResumeReadingBodyFromNet() { + if (target_loader_.is_bound()) + target_loader_->ResumeReadingBodyFromNet(); +} + +void BraveProxyingURLLoaderFactory::InProgressRequest::OnReceiveResponse( + const network::ResourceResponseHead& head) { + current_response_ = head; + HandleResponseOrRedirectHeaders( + base::BindRepeating(&InProgressRequest::ContinueToResponseStarted, + weak_factory_.GetWeakPtr())); +} + +void BraveProxyingURLLoaderFactory::InProgressRequest::OnReceiveRedirect( + const net::RedirectInfo& redirect_info, + const network::ResourceResponseHead& head) { + current_response_ = head; + HandleResponseOrRedirectHeaders( + base::BindRepeating(&InProgressRequest::ContinueToBeforeRedirect, + weak_factory_.GetWeakPtr(), redirect_info)); +} + +void BraveProxyingURLLoaderFactory::InProgressRequest::OnUploadProgress( + int64_t current_position, + int64_t total_size, + OnUploadProgressCallback callback) { + target_client_->OnUploadProgress(current_position, total_size, + std::move(callback)); +} + +void BraveProxyingURLLoaderFactory::InProgressRequest:: + OnReceiveCachedMetadata(mojo_base::BigBuffer data) { + target_client_->OnReceiveCachedMetadata(std::move(data)); +} + +void BraveProxyingURLLoaderFactory::InProgressRequest::OnTransferSizeUpdated( + int32_t transfer_size_diff) { + target_client_->OnTransferSizeUpdated(transfer_size_diff); +} + +void BraveProxyingURLLoaderFactory::InProgressRequest:: + OnStartLoadingResponseBody(mojo::ScopedDataPipeConsumerHandle body) { + target_client_->OnStartLoadingResponseBody(std::move(body)); +} + +void BraveProxyingURLLoaderFactory::InProgressRequest::OnComplete( + const network::URLLoaderCompletionStatus& status) { + if (status.error_code != net::OK) { + OnRequestError(status); + return; + } + target_client_->OnComplete(status); + + // Deletes |this|. + factory_->RemoveRequest(this); +} + +void BraveProxyingURLLoaderFactory::InProgressRequest:: + HandleBeforeRequestRedirect() { + // The listener requested a redirect. Close the connection with the current + // URLLoader and inform the URLLoaderClient redirect was generated. + // To load |redirect_url_|, a new URLLoader will be recreated + // after receiving FollowRedirect(). + + // Forgetting to close the connection with the current URLLoader caused + // bugs. The latter doesn't know anything about the redirect. Continuing + // the load with it gives unexpected results. See + // https://crbug.com/882661#c72. + proxied_client_binding_.Close(); + target_loader_.reset(); + + constexpr int kInternalRedirectStatusCode = 307; + + net::RedirectInfo redirect_info; + redirect_info.status_code = kInternalRedirectStatusCode; + redirect_info.new_method = request_.method; + redirect_info.new_url = redirect_url_; + redirect_info.new_site_for_cookies = redirect_url_; + + network::ResourceResponseHead head; + std::string headers = base::StringPrintf( + "HTTP/1.1 %i Internal Redirect\n" + "Location: %s\n" + "Non-Authoritative-Reason: WebRequest API\n\n", + kInternalRedirectStatusCode, redirect_url_.spec().c_str()); + + if (base::FeatureList::IsEnabled(network::features::kOutOfBlinkCors)) { + // Cross-origin requests need to modify the Origin header to 'null'. Since + // CorsURLLoader sets |request_initiator| to the Origin request header in + // NetworkService, we need to modify |request_initiator| here to craft the + // Origin header indirectly. + // Following checks implement the step 10 of "4.4. HTTP-redirect fetch", + // https://fetch.spec.whatwg.org/#http-redirect-fetch + if (request_.request_initiator && + (!url::Origin::Create(redirect_url_) + .IsSameOriginWith(url::Origin::Create(request_.url)) && + !request_.request_initiator->IsSameOriginWith( + url::Origin::Create(request_.url)))) { + // Reset the initiator to pretend tainted origin flag of the spec is set. + request_.request_initiator = url::Origin(); + } + } else { + // If this redirect is used in a cross-origin request, add CORS headers to + // make sure that the redirect gets through the Blink CORS. Note that the + // destination URL is still subject to the usual CORS policy, i.e. the + // resource will only be available to web pages if the server serves the + // response with the required CORS response headers. Matches the behavior in + // url_request_redirect_job.cc. + std::string http_origin; + if (request_.headers.GetHeader("Origin", &http_origin)) { + headers += base::StringPrintf( + "\n" + "Access-Control-Allow-Origin: %s\n" + "Access-Control-Allow-Credentials: true", + http_origin.c_str()); + } + } + head.headers = base::MakeRefCounted( + net::HttpUtil::AssembleRawHeaders(headers)); + head.encoded_data_length = 0; + + current_response_ = head; + ContinueToBeforeRedirect(redirect_info, net::OK); +} + +void BraveProxyingURLLoaderFactory::InProgressRequest:: + ContinueToBeforeSendHeaders(int error_code) { + if (error_code != net::OK) { + OnRequestError(network::URLLoaderCompletionStatus(error_code)); + return; + } + + if (!redirect_url_.is_empty()) { + HandleBeforeRequestRedirect(); + return; + } + + DCHECK(ctx_); + if (!ctx_->new_referrer.is_empty()) { + request_.referrer = ctx_->new_referrer; + } + + if (proxied_client_binding_.is_bound()) + proxied_client_binding_.ResumeIncomingMethodCallProcessing(); + + // TODO(iefremov): Shorten + if (ctx_->blocked_by != brave::kNotBlocked) { + if (ctx_->cancel_request_explicitly) { + OnRequestError(network::URLLoaderCompletionStatus(net::ERR_ABORTED)); + return; + } + network::ResourceResponseHead response; + std::string response_data; + brave_shields::MakeStubResponse(request_, &response, &response_data); + + target_client_->OnReceiveResponse(response); + + // Create a data pipe for transmitting the response. + mojo::ScopedDataPipeProducerHandle producer; + mojo::ScopedDataPipeConsumerHandle consumer; + if (CreateDataPipe(nullptr, &producer, &consumer) != MOJO_RESULT_OK) { + OnRequestError( + network::URLLoaderCompletionStatus(net::ERR_INSUFFICIENT_RESOURCES)); + return; + } + + // Craft the response. + target_client_->OnStartLoadingResponseBody(std::move(consumer)); + + auto write_data = std::make_unique(); + write_data->client = this; + write_data->data = response_data; + write_data->producer = + std::make_unique(std::move(producer)); + + base::StringPiece string_piece(write_data->data); + write_data->producer->Write(string_piece, + mojo::StringDataPipeProducer::AsyncWritingMode:: + STRING_STAYS_VALID_UNTIL_COMPLETION, + base::BindOnce(OnWrite, std::move(write_data))); + return; + } + + if (request_.url.SchemeIsHTTPOrHTTPS()) { + auto continuation = base::BindRepeating( + &InProgressRequest::ContinueToSendHeaders, weak_factory_.GetWeakPtr()); + + ctx_ = std::make_shared(); + brave::BraveRequestInfo::FillCTX(request_, render_process_id_, + frame_tree_node_id_, request_id_, + resource_context_, ctx_); + int result = factory_->request_handler_->OnBeforeStartTransaction( + ctx_, continuation, &request_.headers); + + if (result == net::ERR_BLOCKED_BY_CLIENT) { + // The request was cancelled synchronously. Dispatch an error notification + // and terminate the request. + OnRequestError(network::URLLoaderCompletionStatus(result)); + return; + } + + if (result == net::ERR_IO_PENDING) { + // One or more listeners is blocking, so the request must be paused until + // they respond. |continuation| above will be invoked asynchronously to + // continue or cancel the request. + // + // We pause the binding here to prevent further client message processing. + if (proxied_client_binding_.is_bound()) + proxied_client_binding_.PauseIncomingMethodCallProcessing(); + return; + } + DCHECK_EQ(net::OK, result); + } + + ContinueToSendHeaders(net::OK); +} + +void BraveProxyingURLLoaderFactory::InProgressRequest::ContinueToStartRequest( + int error_code) { + if (error_code != net::OK) { + OnRequestError(network::URLLoaderCompletionStatus(error_code)); + return; + } + + if (proxied_client_binding_.is_bound()) + proxied_client_binding_.ResumeIncomingMethodCallProcessing(); + + if (!target_loader_.is_bound() && factory_->target_factory_.is_bound()) { + // Nothing has cancelled us up to this point, so it's now OK to + // initiate the real network request. + network::mojom::URLLoaderClientPtr proxied_client; + proxied_client_binding_.Bind(mojo::MakeRequest(&proxied_client)); + uint32_t options = options_; + factory_->target_factory_->CreateLoaderAndStart( + mojo::MakeRequest(&target_loader_), routing_id_, + network_service_request_id_, options, request_, + std::move(proxied_client), traffic_annotation_); + } + + // From here the lifecycle of this request is driven by subsequent events on + // either |proxy_loader_binding_|, |proxy_client_binding_|. +} + +void BraveProxyingURLLoaderFactory::InProgressRequest::ContinueToSendHeaders( + int error_code) { + if (error_code != net::OK) { + OnRequestError(network::URLLoaderCompletionStatus(error_code)); + return; + } + const std::set& removed_headers = ctx_->removed_headers; + const std::set& set_headers = ctx_->set_headers; + + if (pending_follow_redirect_params_) { + pending_follow_redirect_params_->removed_headers.insert( + pending_follow_redirect_params_->removed_headers.end(), + removed_headers.begin(), removed_headers.end()); + + for (auto& set_header : set_headers) { + std::string header_value; + if (request_.headers.GetHeader(set_header, &header_value)) { + pending_follow_redirect_params_->modified_headers.SetHeader( + set_header, header_value); + } else { + NOTREACHED(); + } + } + + if (target_loader_.is_bound()) { + target_loader_->FollowRedirect( + pending_follow_redirect_params_->removed_headers, + pending_follow_redirect_params_->modified_headers, + pending_follow_redirect_params_->new_url); + } + + pending_follow_redirect_params_.reset(); + } + + if (proxied_client_binding_.is_bound()) + proxied_client_binding_.ResumeIncomingMethodCallProcessing(); + ContinueToStartRequest(net::OK); +} + +void BraveProxyingURLLoaderFactory::InProgressRequest:: + ContinueToResponseStarted(int error_code) { + if (error_code != net::OK) { + OnRequestError(network::URLLoaderCompletionStatus(error_code)); + return; + } + + if (override_headers_) + current_response_.headers = override_headers_; + + std::string redirect_location; + if (override_headers_ && override_headers_->IsRedirect(&redirect_location)) { + // The response headers may have been overridden by an |onHeadersReceived| + // handler and may have been changed to a redirect. We handle that here + // instead of acting like regular request completion. + // + // Note that we can't actually change how the Network Service handles the + // original request at this point, so our "redirect" is really just + // generating an artificial |onBeforeRedirect| event and starting a new + // request to the Network Service. Our client shouldn't know the difference. + GURL new_url(redirect_location); + + net::RedirectInfo redirect_info; + redirect_info.status_code = override_headers_->response_code(); + redirect_info.new_method = request_.method; + redirect_info.new_url = new_url; + redirect_info.new_site_for_cookies = new_url; + + // These will get re-bound if a new request is initiated by + // |FollowRedirect()|. + proxied_client_binding_.Close(); + target_loader_.reset(); + + ContinueToBeforeRedirect(redirect_info, net::OK); + return; + } + + proxied_client_binding_.ResumeIncomingMethodCallProcessing(); + target_client_->OnReceiveResponse(current_response_); +} + +void BraveProxyingURLLoaderFactory::InProgressRequest::ContinueToBeforeRedirect( + const net::RedirectInfo& redirect_info, + int error_code) { + if (error_code != net::OK) { + OnRequestError(network::URLLoaderCompletionStatus(error_code)); + return; + } + + if (proxied_client_binding_.is_bound()) + proxied_client_binding_.ResumeIncomingMethodCallProcessing(); + + target_client_->OnReceiveRedirect(redirect_info, current_response_); + request_.url = redirect_info.new_url; + request_.method = redirect_info.new_method; + request_.site_for_cookies = redirect_info.new_site_for_cookies; + request_.referrer = GURL(redirect_info.new_referrer); + request_.referrer_policy = redirect_info.new_referrer_policy; + + // The request method can be changed to "GET". In this case we need to + // reset the request body manually. + if (request_.method == net::HttpRequestHeaders::kGetMethod) + request_.request_body = nullptr; + + request_completed_ = true; +} + +void BraveProxyingURLLoaderFactory::InProgressRequest:: + HandleResponseOrRedirectHeaders(net::CompletionOnceCallback continuation) { + override_headers_ = nullptr; + redirect_url_ = GURL(); + + net::CompletionRepeatingCallback copyable_callback = + base::AdaptCallbackForRepeating(std::move(continuation)); + if (request_.url.SchemeIsHTTPOrHTTPS()) { + ctx_ = std::make_shared(); + brave::BraveRequestInfo::FillCTX(request_, render_process_id_, + frame_tree_node_id_, request_id_, + resource_context_, ctx_); + int result = factory_->request_handler_->OnHeadersReceived( + ctx_, copyable_callback, current_response_.headers.get(), + &override_headers_, &redirect_url_); + + if (result == net::ERR_BLOCKED_BY_CLIENT) { + OnRequestError(network::URLLoaderCompletionStatus(result)); + return; + } + + if (result == net::ERR_IO_PENDING) { + // One or more listeners is blocking, so the request must be paused until + // they respond. |continuation| above will be invoked asynchronously to + // continue or cancel the request. + // + // We pause the binding here to prevent further client message processing. + proxied_client_binding_.PauseIncomingMethodCallProcessing(); + return; + } + + DCHECK_EQ(net::OK, result); + } + + copyable_callback.Run(net::OK); +} +void BraveProxyingURLLoaderFactory::InProgressRequest::OnRequestError( + const network::URLLoaderCompletionStatus& status) { + if (!request_completed_) { + target_client_->OnComplete(status); + } + + // Deletes |this|. + factory_->RemoveRequest(this); +} + +BraveProxyingURLLoaderFactory::BraveProxyingURLLoaderFactory( + BraveRequestHandler* request_handler, + content::ResourceContext* resource_context, + int render_process_id, + int frame_tree_node_id, + network::mojom::URLLoaderFactoryRequest loader_request, + network::mojom::URLLoaderFactoryPtrInfo target_factory, + scoped_refptr request_id_generator, + DisconnectCallback on_disconnect) + : request_handler_(request_handler), + resource_context_(resource_context), + render_process_id_(render_process_id), + frame_tree_node_id_(frame_tree_node_id), + request_id_generator_(request_id_generator), + disconnect_callback_(std::move(on_disconnect)), + weak_factory_(this) { + DCHECK_CURRENTLY_ON(content::BrowserThread::IO); + DCHECK(proxy_bindings_.empty()); + DCHECK(!target_factory_.is_bound()); + + target_factory_.Bind(std::move(target_factory)); + target_factory_.set_connection_error_handler( + base::BindOnce(&BraveProxyingURLLoaderFactory::OnTargetFactoryError, + base::Unretained(this))); + + proxy_bindings_.AddBinding(this, std::move(loader_request)); + proxy_bindings_.set_connection_error_handler( + base::BindRepeating(&BraveProxyingURLLoaderFactory::OnProxyBindingError, + base::Unretained(this))); +} + +BraveProxyingURLLoaderFactory::~BraveProxyingURLLoaderFactory() = default; + +// static +bool BraveProxyingURLLoaderFactory::MaybeProxyRequest( + content::BrowserContext* browser_context, + content::RenderFrameHost* render_frame_host, + int render_process_id, + network::mojom::URLLoaderFactoryRequest* factory_request) { + DCHECK_CURRENTLY_ON(content::BrowserThread::UI); + auto proxied_request = std::move(*factory_request); + network::mojom::URLLoaderFactoryPtrInfo target_factory_info; + *factory_request = mojo::MakeRequest(&target_factory_info); + + base::PostTaskWithTraits( + FROM_HERE, {content::BrowserThread::IO}, + base::BindOnce( + &ResourceContextData::StartProxying, + browser_context->GetResourceContext(), render_process_id, + render_frame_host ? render_frame_host->GetFrameTreeNodeId() : 0, + std::move(proxied_request), std::move(target_factory_info))); + return true; +} + +void BraveProxyingURLLoaderFactory::CreateLoaderAndStart( + network::mojom::URLLoaderRequest loader_request, + int32_t routing_id, + int32_t request_id, + uint32_t options, + const network::ResourceRequest& request, + network::mojom::URLLoaderClientPtr client, + const net::MutableNetworkTrafficAnnotationTag& traffic_annotation) { + DCHECK_CURRENTLY_ON(content::BrowserThread::IO); + + // The request ID doesn't really matter in the Network Service path. It just + // needs to be unique per-BrowserContext so request handlers can make sense of + // it. Note that |network_service_request_id_| by contrast is not necessarily + // unique, so we don't use it for identity here. + const uint64_t brave_request_id = request_id_generator_->Generate(); + + auto result = requests_.emplace( + std::make_unique( + this, brave_request_id, request_id, routing_id, render_process_id_, + frame_tree_node_id_, options, request, resource_context_, + traffic_annotation, std::move(loader_request), std::move(client))); + (*result.first)->Restart(); +} + +void BraveProxyingURLLoaderFactory::Clone( + network::mojom::URLLoaderFactoryRequest loader_request) { + proxy_bindings_.AddBinding(this, std::move(loader_request)); +} + +void BraveProxyingURLLoaderFactory::OnTargetFactoryError() { + // Stop calls to CreateLoaderAndStart() when |target_factory_| is invalid. + target_factory_.reset(); + proxy_bindings_.CloseAllBindings(); + MaybeRemoveProxy(); +} + +void BraveProxyingURLLoaderFactory::OnProxyBindingError() { + if (proxy_bindings_.empty()) + target_factory_.reset(); + + MaybeRemoveProxy(); +} + +void BraveProxyingURLLoaderFactory::RemoveRequest(InProgressRequest* request) { + auto it = requests_.find(request); + DCHECK(it != requests_.end()); + requests_.erase(it); + + MaybeRemoveProxy(); +} + +void BraveProxyingURLLoaderFactory::MaybeRemoveProxy() { + // Even if all URLLoaderFactory pipes connected to this object have been + // closed it has to stay alive until all active requests have completed. + if (target_factory_.is_bound() || !requests_.empty()) + return; + + // Deletes |this|. + std::move(disconnect_callback_).Run(this); +} diff --git a/browser/net/brave_proxying_url_loader_factory.h b/browser/net/brave_proxying_url_loader_factory.h new file mode 100644 index 00000000000..fd1d3a88b9c --- /dev/null +++ b/browser/net/brave_proxying_url_loader_factory.h @@ -0,0 +1,243 @@ +/* Copyright 2019 The Brave Authors. All rights reserved. + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this file, + * You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#ifndef BRAVE_BROWSER_NET_BRAVE_PROXYING_URL_LOADER_FACTORY_H_ +#define BRAVE_BROWSER_NET_BRAVE_PROXYING_URL_LOADER_FACTORY_H_ + +#include +#include +#include +#include +#include +#include +#include + +#include "base/callback.h" +#include "base/containers/unique_ptr_adapters.h" +#include "base/macros.h" +#include "base/memory/ref_counted.h" +#include "base/memory/ref_counted_delete_on_sequence.h" +#include "base/memory/weak_ptr.h" +#include "base/optional.h" +#include "brave/browser/net/url_context.h" +#include "content/public/browser/browser_thread.h" +#include "mojo/public/cpp/bindings/binding.h" +#include "mojo/public/cpp/bindings/binding_set.h" +#include "net/base/completion_once_callback.h" +#include "net/traffic_annotation/network_traffic_annotation.h" +#include "services/network/public/cpp/resource_request.h" +#include "services/network/public/cpp/resource_response.h" +#include "services/network/public/mojom/network_context.mojom.h" +#include "services/network/public/mojom/url_loader.mojom.h" +#include "services/network/public/mojom/url_loader_factory.mojom.h" +#include "url/gurl.h" + +namespace content { +class BrowserContext; +class RenderFrameHost; +class ResourceContext; +} // namespace content + +class RequestIDGenerator + : public base::RefCountedThreadSafe { + public: + RequestIDGenerator() = default; + int64_t Generate() { + DCHECK_CURRENTLY_ON(content::BrowserThread::IO); + return ++id_; + } + + private: + friend class base::RefCountedThreadSafe; + ~RequestIDGenerator() {} + + // Although this initialization can be done in a thread other than the IO + // thread, we expect at least one memory barrier before actually calling + // Generate in the IO thread, so we don't protect the variable with a lock. + int64_t id_ = 0; + DISALLOW_COPY_AND_ASSIGN(RequestIDGenerator); +}; + +// Cargoculted from WebRequestProxyingURLLoaderFactory and +// signin::ProxyingURLLoaderFactory +class BraveProxyingURLLoaderFactory + : public network::mojom::URLLoaderFactory { + public: + using DisconnectCallback = + base::OnceCallback; + + class InProgressRequest : public network::mojom::URLLoader, + public network::mojom::URLLoaderClient { + public: + InProgressRequest( + BraveProxyingURLLoaderFactory* factory, + uint64_t request_id, + int32_t network_service_request_id, + int render_process_id, + int frame_tree_node_id, + int32_t routing_id, + uint32_t options, + const network::ResourceRequest& request, + content::ResourceContext* resource_context, + const net::MutableNetworkTrafficAnnotationTag& traffic_annotation, + network::mojom::URLLoaderRequest loader_request, + network::mojom::URLLoaderClientPtr client); + ~InProgressRequest() override; + + void Restart(); + + // network::mojom::URLLoader: + void FollowRedirect(const std::vector& removed_headers, + const net::HttpRequestHeaders& modified_headers, + const base::Optional& new_url) override; + void ProceedWithResponse() override; + void SetPriority(net::RequestPriority priority, + int32_t intra_priority_value) override; + void PauseReadingBodyFromNet() override; + void ResumeReadingBodyFromNet() override; + + // network::mojom::URLLoaderClient: + void OnReceiveResponse(const network::ResourceResponseHead& head) override; + void OnReceiveRedirect(const net::RedirectInfo& redirect_info, + const network::ResourceResponseHead& head) override; + void OnUploadProgress(int64_t current_position, + int64_t total_size, + OnUploadProgressCallback callback) override; + void OnReceiveCachedMetadata(mojo_base::BigBuffer data) override; + void OnTransferSizeUpdated(int32_t transfer_size_diff) override; + void OnStartLoadingResponseBody( + mojo::ScopedDataPipeConsumerHandle body) override; + void OnComplete(const network::URLLoaderCompletionStatus& status) override; + + private: + // These two methods combined form the implementation of Restart(). + void UpdateRequestInfo(); + void RestartInternal(); + + void ContinueToBeforeSendHeaders(int error_code); + void ContinueToSendHeaders(int error_code); + void ContinueToStartRequest(int error_code); + void ContinueToResponseStarted(int error_code); + void ContinueToBeforeRedirect(const net::RedirectInfo& redirect_info, + int error_code); + void HandleResponseOrRedirectHeaders( + net::CompletionOnceCallback continuation); + void OnRequestError(const network::URLLoaderCompletionStatus& status); + void HandleBeforeRequestRedirect(); + + // TODO(iefremov): Get rid of shared_ptr, we should clearly own the pointer. + std::shared_ptr ctx_; + BraveProxyingURLLoaderFactory* const factory_; + network::ResourceRequest request_; + const uint64_t request_id_; + const int32_t network_service_request_id_; + + const int render_process_id_; + const int frame_tree_node_id_; + const int32_t routing_id_; + const uint32_t options_; + + content::ResourceContext* resource_context_; + const net::MutableNetworkTrafficAnnotationTag traffic_annotation_; + mojo::Binding proxied_loader_binding_; + network::mojom::URLLoaderClientPtr target_client_; + + mojo::Binding proxied_client_binding_; + network::mojom::URLLoaderPtr target_loader_; + + // NOTE: This is state which ExtensionWebRequestEventRouter needs to have + // persisted across some phases of this request -- namely between + // |OnHeadersReceived()| and request completion or restart. Pointers to + // these fields are stored in a |BlockedRequest| (created and owned by + // ExtensionWebRequestEventRouter) through much of the request's lifetime. + // That code supports both Network Service and non-Network Service behavior, + // which is why this weirdness exists here. + network::ResourceResponseHead current_response_; + scoped_refptr override_headers_; + GURL redirect_url_; + + bool request_completed_ = false; + + // This stores the parameters to FollowRedirect that came from + // the client. That way we can combine it with any other changes that + // extensions made to headers in their callbacks. + struct FollowRedirectParams { + FollowRedirectParams(); + ~FollowRedirectParams(); + std::vector removed_headers; + net::HttpRequestHeaders modified_headers; + base::Optional new_url; + + DISALLOW_COPY_AND_ASSIGN(FollowRedirectParams); + }; + std::unique_ptr pending_follow_redirect_params_; + + base::WeakPtrFactory weak_factory_; + + DISALLOW_COPY_AND_ASSIGN(InProgressRequest); + }; + + // Constructor public for testing purposes. New instances should be created + // by calling MaybeProxyRequest(). + BraveProxyingURLLoaderFactory( + BraveRequestHandler* request_handler, + content::ResourceContext* resource_context, + int render_process_id, + int frame_tree_node_id, + network::mojom::URLLoaderFactoryRequest request, + network::mojom::URLLoaderFactoryPtrInfo target_factory, + scoped_refptr request_id_generator, + DisconnectCallback on_disconnect); + + ~BraveProxyingURLLoaderFactory() override; + + static bool MaybeProxyRequest( + content::BrowserContext* browser_context, + content::RenderFrameHost* render_frame_host, + int render_process_id, + network::mojom::URLLoaderFactoryRequest* factory_request); + + // network::mojom::URLLoaderFactory: + void CreateLoaderAndStart(network::mojom::URLLoaderRequest loader_request, + int32_t routing_id, + int32_t request_id, + uint32_t options, + const network::ResourceRequest& request, + network::mojom::URLLoaderClientPtr client, + const net::MutableNetworkTrafficAnnotationTag& + traffic_annotation) override; + void Clone(network::mojom::URLLoaderFactoryRequest loader_request) override; + + private: + friend class base::DeleteHelper; + friend class base::RefCountedDeleteOnSequence; + + void OnTargetFactoryError(); + void OnProxyBindingError(); + void RemoveRequest(InProgressRequest* request); + + void MaybeRemoveProxy(); + + BraveRequestHandler* request_handler_; + content::ResourceContext* resource_context_; + const int render_process_id_; + const int frame_tree_node_id_; + + mojo::BindingSet proxy_bindings_; + network::mojom::URLLoaderFactoryPtr target_factory_; + + std::set, base::UniquePtrComparator> + requests_; + + scoped_refptr request_id_generator_; + + DisconnectCallback disconnect_callback_; + + base::WeakPtrFactory weak_factory_; + + DISALLOW_COPY_AND_ASSIGN(BraveProxyingURLLoaderFactory); +}; + +#endif // BRAVE_BROWSER_NET_BRAVE_PROXYING_URL_LOADER_FACTORY_H_ diff --git a/browser/net/brave_referrals_network_delegate_helper.cc b/browser/net/brave_referrals_network_delegate_helper.cc index 82f9edae668..5ec7a6e383b 100644 --- a/browser/net/brave_referrals_network_delegate_helper.cc +++ b/browser/net/brave_referrals_network_delegate_helper.cc @@ -30,6 +30,7 @@ int OnBeforeStartTransaction_ReferralsWork( for (const auto& it : request_headers_dict->DictItems()) { if (it.first == kBravePartnerHeader) { headers->SetHeader(it.first, it.second.GetString()); + ctx->set_headers.insert(it.first); } } return net::OK; diff --git a/browser/net/brave_request_handler.cc b/browser/net/brave_request_handler.cc new file mode 100644 index 00000000000..b39e096b512 --- /dev/null +++ b/browser/net/brave_request_handler.cc @@ -0,0 +1,293 @@ +/* Copyright (c) 2019 The Brave Authors. All rights reserved. + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this file, + * You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#include "brave/browser/net/brave_request_handler.h" + +#include +#include + +#include "base/task/post_task.h" +#include "brave/browser/net/brave_ad_block_tp_network_delegate_helper.h" +#include "brave/browser/net/brave_common_static_redirect_network_delegate_helper.h" +#include "brave/browser/net/brave_httpse_network_delegate_helper.h" +#include "brave/browser/net/brave_site_hacks_network_delegate_helper.h" +#include "brave/browser/net/brave_stp_util.h" +#include "brave/browser/translate/buildflags/buildflags.h" +#include "brave/common/pref_names.h" +#include "brave/components/brave_referrals/buildflags/buildflags.h" +#include "brave/components/brave_rewards/browser/buildflags/buildflags.h" +#include "brave/components/brave_webtorrent/browser/buildflags/buildflags.h" +#include "chrome/browser/browser_process.h" +#include "components/prefs/pref_change_registrar.h" +#include "components/prefs/pref_service.h" +#include "content/public/browser/browser_task_traits.h" +#include "content/public/browser/browser_thread.h" + +#if BUILDFLAG(ENABLE_BRAVE_REFERRALS) +#include "brave/browser/net/brave_referrals_network_delegate_helper.h" +#endif + +#if BUILDFLAG(BRAVE_REWARDS_ENABLED) +#include "brave/components/brave_rewards/browser/net/network_delegate_helper.h" +#endif + +#if BUILDFLAG(ENABLE_BRAVE_WEBTORRENT) +#include "brave/components/brave_webtorrent/browser/net/brave_torrent_redirect_network_delegate_helper.h" +#endif + +#if BUILDFLAG(ENABLE_BRAVE_TRANSLATE_GO) +#include "brave/browser/net/brave_translate_redirect_network_delegate_helper.h" +#endif + +BraveRequestHandler::BraveRequestHandler() { + DCHECK_CURRENTLY_ON(content::BrowserThread::IO); + SetupCallbacks(); + // Initialize the preference change registrar. + base::PostTaskWithTraits( + FROM_HERE, {content::BrowserThread::UI}, + base::Bind(&BraveRequestHandler::InitPrefChangeRegistrarOnUI, + base::Unretained(this))); +} + +BraveRequestHandler::~BraveRequestHandler() = default; + +void BraveRequestHandler::SetupCallbacks() { + brave::OnBeforeURLRequestCallback callback = + base::Bind(brave::OnBeforeURLRequest_SiteHacksWork); + before_url_request_callbacks_.push_back(callback); + + callback = base::Bind(brave::OnBeforeURLRequest_AdBlockTPPreWork); + before_url_request_callbacks_.push_back(callback); + + callback = base::Bind(brave::OnBeforeURLRequest_HttpsePreFileWork); + before_url_request_callbacks_.push_back(callback); + + callback = base::Bind(brave::OnBeforeURLRequest_CommonStaticRedirectWork); + before_url_request_callbacks_.push_back(callback); + +#if BUILDFLAG(BRAVE_REWARDS_ENABLED) + callback = base::Bind(brave_rewards::OnBeforeURLRequest); + before_url_request_callbacks_.push_back(callback); +#endif + +#if BUILDFLAG(ENABLE_BRAVE_TRANSLATE_GO) + callback = + base::BindRepeating(brave::OnBeforeURLRequest_TranslateRedirectWork); + before_url_request_callbacks_.push_back(callback); +#endif + + brave::OnBeforeStartTransactionCallback start_transaction_callback = + base::Bind(brave::OnBeforeStartTransaction_SiteHacksWork); + before_start_transaction_callbacks_.push_back(start_transaction_callback); + +#if BUILDFLAG(ENABLE_BRAVE_REFERRALS) + start_transaction_callback = + base::Bind(brave::OnBeforeStartTransaction_ReferralsWork); + before_start_transaction_callbacks_.push_back(start_transaction_callback); +#endif + +#if BUILDFLAG(ENABLE_BRAVE_WEBTORRENT) + brave::OnHeadersReceivedCallback headers_received_callback = + base::Bind(webtorrent::OnHeadersReceived_TorrentRedirectWork); + headers_received_callbacks_.push_back(headers_received_callback); +#endif +} + +void BraveRequestHandler::InitPrefChangeRegistrarOnUI() { + DCHECK_CURRENTLY_ON(content::BrowserThread::UI); +#if BUILDFLAG(ENABLE_BRAVE_REFERRALS) + PrefService* prefs = g_browser_process->local_state(); + pref_change_registrar_.reset(new PrefChangeRegistrar()); + pref_change_registrar_->Init(prefs); + pref_change_registrar_->Add( + kReferralHeaders, + base::Bind(&BraveRequestHandler::OnReferralHeadersChanged, + base::Unretained(this))); + // Retrieve current referral headers, if any. + OnReferralHeadersChanged(); +#endif +} + +void BraveRequestHandler::OnReferralHeadersChanged() { + DCHECK_CURRENTLY_ON(content::BrowserThread::UI); + if (const base::ListValue* referral_headers = + g_browser_process->local_state()->GetList(kReferralHeaders)) { + base::PostTaskWithTraits( + FROM_HERE, {content::BrowserThread::IO}, + base::Bind(&BraveRequestHandler::SetReferralHeaders, + base::Unretained(this), referral_headers->DeepCopy())); + } +} + +void BraveRequestHandler::SetReferralHeaders( + base::ListValue* referral_headers) { + DCHECK_CURRENTLY_ON(content::BrowserThread::IO); + referral_headers_list_.reset(referral_headers); +} + +bool BraveRequestHandler::IsRequestIdentifierValid( + uint64_t request_identifier) { + return ContainsKey(callbacks_, request_identifier); + return true; +} + +int BraveRequestHandler::OnBeforeURLRequest( + std::shared_ptr ctx, + net::CompletionOnceCallback callback, + GURL* new_url) { + if (before_url_request_callbacks_.empty()) { + return net::OK; + } + ctx->new_url = new_url; + ctx->event_type = brave::kOnBeforeRequest; + callbacks_[ctx->request_identifier] = std::move(callback); + RunNextCallback(ctx); + return net::ERR_IO_PENDING; +} + +int BraveRequestHandler::OnBeforeStartTransaction( + std::shared_ptr ctx, + net::CompletionOnceCallback callback, + net::HttpRequestHeaders* headers) { + if (before_start_transaction_callbacks_.empty()) { + return net::OK; + } + ctx->event_type = brave::kOnBeforeStartTransaction; + ctx->headers = headers; + ctx->referral_headers_list = referral_headers_list_.get(); + callbacks_[ctx->request_identifier] = std::move(callback); + RunNextCallback(ctx); + return net::ERR_IO_PENDING; +} + +int BraveRequestHandler::OnHeadersReceived( + std::shared_ptr ctx, + net::CompletionOnceCallback callback, + const net::HttpResponseHeaders* original_response_headers, + scoped_refptr* override_response_headers, + GURL* allowed_unsafe_redirect_url) { + if (!ctx->tab_origin.is_empty()) { + brave::RemoveTrackableSecurityHeadersForThirdParty( + ctx->request_url, url::Origin::Create(ctx->tab_origin), + original_response_headers, override_response_headers); + } + + if (headers_received_callbacks_.empty()) { + return net::OK; + } + + callbacks_[ctx->request_identifier] = std::move(callback); + ctx->event_type = brave::kOnHeadersReceived; + ctx->original_response_headers = original_response_headers; + ctx->override_response_headers = override_response_headers; + ctx->allowed_unsafe_redirect_url = allowed_unsafe_redirect_url; + + base::PostTaskWithTraits(FROM_HERE, {content::BrowserThread::IO}, + base::Bind(&BraveRequestHandler::RunNextCallback, + weak_factory_.GetWeakPtr(), + ctx)); + return net::ERR_IO_PENDING; +} + +void BraveRequestHandler::OnURLRequestDestroyed( + std::shared_ptr ctx) { + if (ContainsKey(callbacks_, ctx->request_identifier)) { + callbacks_.erase(ctx->request_identifier); + } +} + +void BraveRequestHandler::RunCallbackForRequestIdentifier( + uint64_t request_identifier, + int rv) { + std::map::iterator it = + callbacks_.find(request_identifier); + // We intentionally do the async call to maintain the proper flow + // of URLLoader callbacks. + base::PostTaskWithTraits(FROM_HERE, {content::BrowserThread::IO}, + base::BindOnce(std::move(it->second), rv)); +} + +// TODO(iefremov): Merge all callback containers into one and run only one loop +// instead of many (issues/5574). +void BraveRequestHandler::RunNextCallback( + std::shared_ptr ctx) { + DCHECK_CURRENTLY_ON(content::BrowserThread::IO); + + if (!ContainsKey(callbacks_, ctx->request_identifier)) { + return; + } + + // Continue processing callbacks until we hit one that returns PENDING + int rv = net::OK; + + if (ctx->event_type == brave::kOnBeforeRequest) { + while (before_url_request_callbacks_.size() != + ctx->next_url_request_index) { + brave::OnBeforeURLRequestCallback callback = + before_url_request_callbacks_[ctx->next_url_request_index++]; + brave::ResponseCallback next_callback = base::Bind( + &BraveRequestHandler::RunNextCallback, base::Unretained(this), ctx); + rv = callback.Run(next_callback, ctx); + if (rv == net::ERR_IO_PENDING) { + return; + } + if (rv != net::OK) { + break; + } + } + } else if (ctx->event_type == brave::kOnBeforeStartTransaction) { + while (before_start_transaction_callbacks_.size() != + ctx->next_url_request_index) { + brave::OnBeforeStartTransactionCallback callback = + before_start_transaction_callbacks_[ctx->next_url_request_index++]; + brave::ResponseCallback next_callback = base::Bind( + &BraveRequestHandler::RunNextCallback, base::Unretained(this), ctx); + rv = callback.Run(ctx->headers, next_callback, ctx); + if (rv == net::ERR_IO_PENDING) { + return; + } + if (rv != net::OK) { + break; + } + } + } else if (ctx->event_type == brave::kOnHeadersReceived) { + while (headers_received_callbacks_.size() != ctx->next_url_request_index) { + brave::OnHeadersReceivedCallback callback = + headers_received_callbacks_[ctx->next_url_request_index++]; + brave::ResponseCallback next_callback = base::Bind( + &BraveRequestHandler::RunNextCallback, base::Unretained(this), ctx); + rv = callback.Run(ctx->original_response_headers, + ctx->override_response_headers, + ctx->allowed_unsafe_redirect_url, next_callback, ctx); + if (rv == net::ERR_IO_PENDING) { + return; + } + if (rv != net::OK) { + break; + } + } + } + + if (rv != net::OK) { + RunCallbackForRequestIdentifier(ctx->request_identifier, rv); + return; + } + + if (ctx->event_type == brave::kOnBeforeRequest) { + if (!ctx->new_url_spec.empty() && + (ctx->new_url_spec != ctx->request_url.spec()) && + IsRequestIdentifierValid(ctx->request_identifier)) { + *ctx->new_url = GURL(ctx->new_url_spec); + } + if (ctx->blocked_by == brave::kAdBlocked) { + if (ctx->cancel_request_explicitly) { + RunCallbackForRequestIdentifier(ctx->request_identifier, + net::ERR_ABORTED); + return; + } + } + } + RunCallbackForRequestIdentifier(ctx->request_identifier, rv); +} diff --git a/browser/net/brave_request_handler.h b/browser/net/brave_request_handler.h new file mode 100644 index 00000000000..c3a93ec015b --- /dev/null +++ b/browser/net/brave_request_handler.h @@ -0,0 +1,77 @@ +/* Copyright (c) 2019 The Brave Authors. All rights reserved. + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this file, + * You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#ifndef BRAVE_BROWSER_NET_BRAVE_REQUEST_HANDLER_H_ +#define BRAVE_BROWSER_NET_BRAVE_REQUEST_HANDLER_H_ + +#include +#include +#include +#include + +#include "brave/browser/net/url_context.h" +#include "content/public/browser/browser_thread.h" +#include "net/base/completion_once_callback.h" + +class PrefChangeRegistrar; + +// Contains different network stack hooks (similar to capabilities of WebRequest +// API). +class BraveRequestHandler { + public: + using ResponseCallback = base::Callback; + + BraveRequestHandler(); + ~BraveRequestHandler(); + + bool IsRequestIdentifierValid(uint64_t request_identifier); + + int OnBeforeURLRequest(std::shared_ptr ctx, + net::CompletionOnceCallback callback, + GURL* new_url); + + int OnBeforeStartTransaction(std::shared_ptr ctx, + net::CompletionOnceCallback callback, + net::HttpRequestHeaders* headers); + int OnHeadersReceived( + std::shared_ptr ctx, + net::CompletionOnceCallback callback, + const net::HttpResponseHeaders* original_response_headers, + scoped_refptr* override_response_headers, + GURL* allowed_unsafe_redirect_url); + + void OnURLRequestDestroyed(std::shared_ptr ctx); + void RunCallbackForRequestIdentifier(uint64_t request_identifier, int rv); + + private: + void SetupCallbacks(); + void InitPrefChangeRegistrarOnUI(); + void SetReferralHeaders(base::ListValue* referral_headers); + void OnReferralHeadersChanged(); + void OnPreferenceChanged(const std::string& pref_name); + void UpdateAdBlockFromPref(const std::string& pref_name); + + void RunNextCallback(std::shared_ptr ctx); + + std::vector before_url_request_callbacks_; + std::vector + before_start_transaction_callbacks_; + std::vector headers_received_callbacks_; + + // TODO(iefremov): actually, we don't have to keep the list here, since + // it is global for the whole browser and could live a singletonce in the + // rewards service. Eliminating this will also help to avoid using + // PrefChangeRegistrar and corresponding |base::Unretained| usages, that are + // illegal. + std::unique_ptr referral_headers_list_; + std::map callbacks_; + std::unique_ptr + pref_change_registrar_; + + base::WeakPtrFactory weak_factory_{this}; + DISALLOW_COPY_AND_ASSIGN(BraveRequestHandler); +}; + +#endif // BRAVE_BROWSER_NET_BRAVE_REQUEST_HANDLER_H_ diff --git a/browser/net/brave_site_hacks_network_delegate_helper.cc b/browser/net/brave_site_hacks_network_delegate_helper.cc index 0cc401208b5..6140f5710ee 100644 --- a/browser/net/brave_site_hacks_network_delegate_helper.cc +++ b/browser/net/brave_site_hacks_network_delegate_helper.cc @@ -71,36 +71,21 @@ void CheckForCookieOverride(const GURL& url, const URLPattern& pattern, } } -bool IsBlockTwitterSiteHack(std::shared_ptr ctx, - net::HttpRequestHeaders* headers) { - URLPattern redirectURLPattern(URLPattern::SCHEME_ALL, kTwitterRedirectURL); - URLPattern referrerPattern(URLPattern::SCHEME_ALL, kTwitterReferrer); - if (redirectURLPattern.MatchesURL(ctx->request_url)) { - std::string referrer; - if (headers->GetHeader(kRefererHeader, &referrer) && - referrerPattern.MatchesURL(GURL(referrer))) { - return true; - } - } - return false; -} - int OnBeforeStartTransaction_SiteHacksWork( net::HttpRequestHeaders* headers, const ResponseCallback& next_callback, std::shared_ptr ctx) { + // TODO(bridiver): Fix the Forbes cookie override with enabled NetworkService. CheckForCookieOverride(ctx->request_url, URLPattern(URLPattern::SCHEME_ALL, kForbesPattern), headers, kForbesExtraCookies); - if (IsBlockTwitterSiteHack(ctx, headers)) { - return net::ERR_ABORTED; - } if (IsUAWhitelisted(ctx->request_url)) { std::string user_agent; if (headers->GetHeader(kUserAgentHeader, &user_agent)) { base::ReplaceFirstSubstringAfterOffset(&user_agent, 0, "Chrome", "Brave Chrome"); headers->SetHeader(kUserAgentHeader, user_agent); + ctx->set_headers.insert(kUserAgentHeader); } } return net::OK; diff --git a/browser/net/brave_site_hacks_network_delegate_helper_unittest.cc b/browser/net/brave_site_hacks_network_delegate_helper_unittest.cc index 7a8637307d8..2e1d62bbcb7 100644 --- a/browser/net/brave_site_hacks_network_delegate_helper_unittest.cc +++ b/browser/net/brave_site_hacks_network_delegate_helper_unittest.cc @@ -98,61 +98,6 @@ TEST_F(BraveSiteHacksNetworkDelegateHelperTest, NotForbesNoCookieChange) { EXPECT_EQ(ret, net::OK); } -TEST_F(BraveSiteHacksNetworkDelegateHelperTest, NoScriptTwitterMobileRedirect) { - GURL url("https://mobile.twitter.com/i/nojs_router?path=%2F"); - net::TestDelegate test_delegate; - std::unique_ptr request = - context()->CreateRequest(url, net::IDLE, &test_delegate, - TRAFFIC_ANNOTATION_FOR_TESTS); - net::HttpRequestHeaders headers; - headers.SetHeader(kRefererHeader, "https://twitter.com/"); - std::shared_ptr - brave_request_info(new brave::BraveRequestInfo()); - brave::BraveRequestInfo::FillCTXFromRequest(request.get(), - brave_request_info); - brave::ResponseCallback callback; - int ret = brave::OnBeforeStartTransaction_SiteHacksWork( - &headers, callback, brave_request_info); - EXPECT_EQ(ret, net::ERR_ABORTED); -} - -TEST_F(BraveSiteHacksNetworkDelegateHelperTest, - AllowTwitterMobileRedirectFromDiffSite) { - GURL url("https://mobile.twitter.com/i/nojs_router?path=%2F"); - net::TestDelegate test_delegate; - std::unique_ptr request = - context()->CreateRequest(url, net::IDLE, &test_delegate, - TRAFFIC_ANNOTATION_FOR_TESTS); - net::HttpRequestHeaders headers; - headers.SetHeader(kRefererHeader, "https://brianbondy.com/"); - std::shared_ptr - brave_request_info(new brave::BraveRequestInfo()); - brave::BraveRequestInfo::FillCTXFromRequest(request.get(), - brave_request_info); - brave::ResponseCallback callback; - int ret = brave::OnBeforeStartTransaction_SiteHacksWork( - &headers, callback, brave_request_info); - EXPECT_EQ(ret, net::OK); -} - -TEST_F(BraveSiteHacksNetworkDelegateHelperTest, TwitterNoCancelWithReferer) { - GURL url("https://twitter.com/brianbondy"); - net::TestDelegate test_delegate; - std::unique_ptr request = - context()->CreateRequest(url, net::IDLE, &test_delegate, - TRAFFIC_ANNOTATION_FOR_TESTS); - net::HttpRequestHeaders headers; - headers.SetHeader(kRefererHeader, "https://twitter.com/"); - std::shared_ptr - brave_request_info(new brave::BraveRequestInfo()); - brave::BraveRequestInfo::FillCTXFromRequest(request.get(), - brave_request_info); - brave::ResponseCallback callback; - int ret = brave::OnBeforeStartTransaction_SiteHacksWork( - &headers, callback, brave_request_info); - EXPECT_EQ(ret, net::OK); -} - TEST_F(BraveSiteHacksNetworkDelegateHelperTest, UAWhitelistedTest) { std::vector urls({ GURL("https://adobe.com"), diff --git a/browser/net/brave_stp_util.cc b/browser/net/brave_stp_util.cc new file mode 100644 index 00000000000..aa872c55c74 --- /dev/null +++ b/browser/net/brave_stp_util.cc @@ -0,0 +1,44 @@ +/* Copyright (c) 2019 The Brave Authors. All rights reserved. + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this file, + * You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#include "brave/browser/net/brave_stp_util.h" + +#include "base/no_destructor.h" +#include "net/base/registry_controlled_domains/registry_controlled_domain.h" + +namespace brave { + +base::flat_set* TrackableSecurityHeaders() { + static base::NoDestructor> + kTrackableSecurityHeaders(base::flat_set{ + "Strict-Transport-Security", "Expect-CT", "Public-Key-Pins", + "Public-Key-Pins-Report-Only"}); + return kTrackableSecurityHeaders.get(); +} + +void RemoveTrackableSecurityHeadersForThirdParty( + const GURL& request_url, const url::Origin& top_frame_origin, + const net::HttpResponseHeaders* original_response_headers, + scoped_refptr* override_response_headers) { + if (!original_response_headers && !override_response_headers->get()) { + return; + } + + if (net::registry_controlled_domains::SameDomainOrHost( + request_url, top_frame_origin, + net::registry_controlled_domains::INCLUDE_PRIVATE_REGISTRIES)) { + return; + } + + if (!override_response_headers->get()) { + *override_response_headers = + new net::HttpResponseHeaders(original_response_headers->raw_headers()); + } + for (auto header : *TrackableSecurityHeaders()) { + (*override_response_headers)->RemoveHeader(header.as_string()); + } +} + +} // namespace brave diff --git a/browser/net/brave_stp_util.h b/browser/net/brave_stp_util.h new file mode 100644 index 00000000000..340b3d65781 --- /dev/null +++ b/browser/net/brave_stp_util.h @@ -0,0 +1,26 @@ +/* Copyright (c) 2019 The Brave Authors. All rights reserved. + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this file, + * You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#ifndef BRAVE_BROWSER_NET_BRAVE_STP_UTIL_H_ +#define BRAVE_BROWSER_NET_BRAVE_STP_UTIL_H_ + +#include "base/containers/flat_set.h" +#include "base/strings/string_piece.h" +#include "net/http/http_response_headers.h" +#include "url/gurl.h" +#include "url/origin.h" + +namespace brave { + +base::flat_set* TrackableSecurityHeaders(); + +void RemoveTrackableSecurityHeadersForThirdParty( + const GURL& request_url, const url::Origin& top_frame_origin, + const net::HttpResponseHeaders* original_response_headers, + scoped_refptr* override_response_headers); + +} // namespace brave + +#endif // BRAVE_BROWSER_NET_BRAVE_STP_UTIL_H_ diff --git a/browser/net/url_context.cc b/browser/net/url_context.cc index 5536443a63b..78dcd880819 100644 --- a/browser/net/url_context.cc +++ b/browser/net/url_context.cc @@ -78,6 +78,21 @@ std::string GetUploadDataFromURLRequest(const net::URLRequest* request) { return upload_data; } +std::string GetUploadData(const network::ResourceRequest& request) { + std::string upload_data; + if (!request.request_body) { + return {}; + } + const auto* elements = request.request_body->elements(); + for (const network::DataElement& element : *elements) { + if (element.type() == network::mojom::DataElementType::kBytes) { + upload_data.append(element.bytes(), element.length()); + } + } + + return upload_data; +} + } // namespace BraveRequestInfo::BraveRequestInfo() = default; @@ -139,4 +154,56 @@ void BraveRequestInfo::FillCTXFromRequest(const net::URLRequest* request, ctx->upload_data = GetUploadDataFromURLRequest(request); } +// static +void BraveRequestInfo::FillCTX( + const network::ResourceRequest& request, + int render_process_id, + int frame_tree_node_id, + uint64_t request_identifier, + content::ResourceContext* resource_context, + std::shared_ptr ctx) { + ctx->request_identifier = request_identifier; + ctx->request_url = request.url; + // TODO(iefremov): Replace GURL with Origin + ctx->initiator_url = + request.request_initiator.value_or(url::Origin()).GetURL(); + + ctx->referrer = request.referrer; + ctx->referrer_policy = request.referrer_policy; + + ctx->resource_type = + static_cast(request.resource_type); + + ctx->is_webtorrent_disabled = IsWebTorrentDisabled(resource_context); + + ctx->render_frame_id = request.render_frame_id; + ctx->render_process_id = render_process_id; + ctx->frame_tree_node_id = frame_tree_node_id; + + // TODO(iefremov): remove tab_url. Change tab_origin from GURL to Origin. + // ctx->tab_url = request.top_frame_origin; + ctx->tab_origin = request.top_frame_origin.value_or(url::Origin()).GetURL(); + + ProfileIOData* io_data = + ProfileIOData::FromResourceContext(resource_context); + + ctx->allow_brave_shields = brave_shields::IsAllowContentSettingWithIOData( + io_data, ctx->tab_origin, ctx->tab_origin, CONTENT_SETTINGS_TYPE_PLUGINS, + brave_shields::kBraveShields) && + !ctx->tab_origin.SchemeIs(kChromeExtensionScheme); + ctx->allow_ads = brave_shields::IsAllowContentSettingWithIOData( + io_data, ctx->tab_origin, ctx->tab_origin, CONTENT_SETTINGS_TYPE_PLUGINS, + brave_shields::kAds); + ctx->allow_http_upgradable_resource = + brave_shields::IsAllowContentSettingWithIOData(io_data, ctx->tab_origin, + ctx->tab_origin, CONTENT_SETTINGS_TYPE_PLUGINS, + brave_shields::kHTTPUpgradableResources); + ctx->allow_referrers = brave_shields::IsAllowContentSettingWithIOData( + io_data, ctx->tab_origin, ctx->tab_origin, CONTENT_SETTINGS_TYPE_PLUGINS, + brave_shields::kReferrers); + + ctx->upload_data = GetUploadData(request); +} + + } // namespace brave diff --git a/browser/net/url_context.h b/browser/net/url_context.h index 20b68fd872b..093bd28d457 100644 --- a/browser/net/url_context.h +++ b/browser/net/url_context.h @@ -7,6 +7,7 @@ #define BRAVE_BROWSER_NET_URL_CONTEXT_H_ #include +#include #include #include "chrome/browser/net/chrome_network_delegate.h" @@ -14,7 +15,15 @@ #include "net/url_request/url_request.h" #include "url/gurl.h" +namespace content { +class ResourceContext; +} + +namespace network { +struct ResourceRequest; +} class BraveNetworkDelegateBase; +class BraveRequestHandler; namespace brave { @@ -70,9 +79,15 @@ struct BraveRequestInfo { int frame_tree_node_id = 0; uint64_t request_identifier = 0; size_t next_url_request_index = 0; + net::HttpRequestHeaders* headers = nullptr; + // The following two sets are populated by |OnBeforeStartTransactionCallback|. + // |set_headers| contains headers which values were added or modified. + std::set set_headers; + std::set removed_headers; const net::HttpResponseHeaders* original_response_headers = nullptr; scoped_refptr* override_response_headers = nullptr; + GURL* allowed_unsafe_redirect_url = nullptr; BraveNetworkDelegateEventType event_type = kUnknownEventType; const base::ListValue* referral_headers_list = nullptr; @@ -89,16 +104,19 @@ struct BraveRequestInfo { static void FillCTXFromRequest(const net::URLRequest* request, std::shared_ptr ctx); + static void FillCTX( + const network::ResourceRequest& request, + int render_process_id, + int frame_tree_node_id, + uint64_t request_identifier, + content::ResourceContext* resource_context, + std::shared_ptr ctx); + private: // Please don't add any more friends here if it can be avoided. // We should also remove the ones below. - friend int OnBeforeURLRequest_SiteHacksWork( - const ResponseCallback& next_callback, - std::shared_ptr ctx); - friend int brave_rewards::OnBeforeURLRequest( - const brave::ResponseCallback& next_callback, - std::shared_ptr ctx); friend class ::BraveNetworkDelegateBase; + friend class ::BraveRequestHandler; GURL* new_url = nullptr; diff --git a/common/network_constants.cc b/common/network_constants.cc index 8fcc2f57dc6..ca7c8f0b9bb 100644 --- a/common/network_constants.cc +++ b/common/network_constants.cc @@ -54,8 +54,6 @@ const char kForbesExtraCookies[] = "forbes_ab=true; welcomeAd=true; adblock_session=Off; " "dailyWelcomeCookie=true"; const char kTwitterPattern[] = "https://*.twitter.com/*"; -const char kTwitterReferrer[] = "https://twitter.com/*"; -const char kTwitterRedirectURL[] = "https://mobile.twitter.com/i/nojs_router*"; const char kCookieHeader[] = "Cookie"; // Intentional misspelling on referrer to match HTTP spec diff --git a/common/network_constants.h b/common/network_constants.h index b36941d1fa6..1431caa6c7b 100644 --- a/common/network_constants.h +++ b/common/network_constants.h @@ -35,8 +35,6 @@ extern const char kCRLSetPrefix3[]; extern const char kCRLSetPrefix4[]; extern const char kChromeCastPrefix[]; extern const char kTwitterPattern[]; -extern const char kTwitterReferrer[]; -extern const char kTwitterRedirectURL[]; extern const char kCookieHeader[]; extern const char kRefererHeader[]; diff --git a/components/brave_shields/browser/BUILD.gn b/components/brave_shields/browser/BUILD.gn index e6a29a161e9..f285ebbd61f 100644 --- a/components/brave_shields/browser/BUILD.gn +++ b/components/brave_shields/browser/BUILD.gn @@ -23,6 +23,8 @@ source_set("browser") { "ad_block_service_helper.h", "adblock_interceptor.cc", "adblock_interceptor.h", + "adblock_stub_response.cc", + "adblock_stub_response.h", "autoplay_whitelist_service.cc", "autoplay_whitelist_service.h", "base_brave_shields_service.cc", @@ -54,6 +56,7 @@ source_set("browser") { "//brave/vendor/adblock_rust_ffi:adblock_ffi", "//brave/vendor/autoplay-whitelist/brave:autoplay-whitelist", "//chrome/common", + "//components/keyed_service/core", "//components/prefs", "//content/public/browser", "//net", diff --git a/components/brave_shields/browser/ad_block_service.cc b/components/brave_shields/browser/ad_block_service.cc index daa0b08dd5a..4d61117530a 100644 --- a/components/brave_shields/browser/ad_block_service.cc +++ b/components/brave_shields/browser/ad_block_service.cc @@ -17,33 +17,51 @@ #include "base/strings/string_number_conversions.h" #include "base/strings/utf_string_conversions.h" #include "base/threading/thread_restrictions.h" +#include "brave/browser/brave_browser_process_impl.h" #include "brave/common/pref_names.h" +#include "brave/components/brave_shields/browser/ad_block_custom_filters_service.h" +#include "brave/components/brave_shields/browser/ad_block_regional_service_manager.h" +#include "brave/components/brave_shields/common/brave_shield_constants.h" #include "brave/vendor/adblock_rust_ffi/src/wrapper.hpp" #include "components/prefs/pref_registry_simple.h" +#include "components/prefs/pref_service.h" #define DAT_FILE "rs-ABPFilterParserData.dat" namespace brave_shields { -std::string AdBlockService::g_ad_block_component_id_( - kAdBlockComponentId); +namespace { + +std::string GetTagFromPrefName(const std::string& pref_name) { + if (pref_name == kFBEmbedControlType) { + return brave_shields::kFacebookEmbeds; + } + if (pref_name == kTwitterEmbedControlType) { + return brave_shields::kTwitterEmbeds; + } + if (pref_name == kLinkedInEmbedControlType) { + return brave_shields::kLinkedInEmbeds; + } + return ""; +} + +} // namespace + +std::string AdBlockService::g_ad_block_component_id_(kAdBlockComponentId); std::string AdBlockService::g_ad_block_component_base64_public_key_( kAdBlockComponentBase64PublicKey); AdBlockService::AdBlockService( brave_component_updater::BraveComponent::Delegate* delegate) - : AdBlockBaseService(delegate) { -} + : AdBlockBaseService(delegate) {} -AdBlockService::~AdBlockService() { -} +AdBlockService::~AdBlockService() {} bool AdBlockService::Init() { if (!AdBlockBaseService::Init()) return false; - Register(kAdBlockComponentName, - g_ad_block_component_id_, + Register(kAdBlockComponentName, g_ad_block_component_id_, g_ad_block_component_base64_public_key_); return true; } @@ -51,8 +69,7 @@ bool AdBlockService::Init() { void AdBlockService::OnComponentReady(const std::string& component_id, const base::FilePath& install_dir, const std::string& manifest) { - base::FilePath dat_file_path = - install_dir.AppendASCII(DAT_FILE); + base::FilePath dat_file_path = install_dir.AppendASCII(DAT_FILE); GetDATFileData(dat_file_path); } @@ -78,4 +95,39 @@ void RegisterPrefsForAdBlockService(PrefRegistrySimple* registry) { registry->RegisterBooleanPref(kAdBlockCheckedDefaultRegion, false); } +AdBlockPrefService::AdBlockPrefService(PrefService* prefs) : prefs_(prefs) { + pref_change_registrar_.reset(new PrefChangeRegistrar()); + pref_change_registrar_->Init(prefs_); + pref_change_registrar_->Add( + kFBEmbedControlType, + base::BindRepeating(&AdBlockPrefService::OnPreferenceChanged, + base::Unretained(this), kFBEmbedControlType)); + pref_change_registrar_->Add( + kTwitterEmbedControlType, + base::BindRepeating(&AdBlockPrefService::OnPreferenceChanged, + base::Unretained(this), kTwitterEmbedControlType)); + pref_change_registrar_->Add( + kLinkedInEmbedControlType, + base::BindRepeating(&AdBlockPrefService::OnPreferenceChanged, + base::Unretained(this), kLinkedInEmbedControlType)); + OnPreferenceChanged(kFBEmbedControlType); + OnPreferenceChanged(kTwitterEmbedControlType); + OnPreferenceChanged(kLinkedInEmbedControlType); +} + +AdBlockPrefService::~AdBlockPrefService() = default; + +void AdBlockPrefService::OnPreferenceChanged(const std::string& pref_name) { + std::string tag = GetTagFromPrefName(pref_name); + if (tag.length() == 0) { + return; + } + bool enabled = prefs_->GetBoolean(pref_name); + g_brave_browser_process->ad_block_service()->EnableTag(tag, enabled); + g_brave_browser_process->ad_block_regional_service_manager()->EnableTag( + tag, enabled); + g_brave_browser_process->ad_block_custom_filters_service()->EnableTag( + tag, enabled); +} + } // namespace brave_shields diff --git a/components/brave_shields/browser/ad_block_service.h b/components/brave_shields/browser/ad_block_service.h index 3b8d3db549c..5dfc4a0948a 100644 --- a/components/brave_shields/browser/ad_block_service.h +++ b/components/brave_shields/browser/ad_block_service.h @@ -13,9 +13,13 @@ #include #include "brave/components/brave_shields/browser/ad_block_base_service.h" +#include "components/keyed_service/core/keyed_service.h" #include "components/prefs/pref_registry_simple.h" +#include "content/public/browser/browser_thread.h" class AdBlockServiceTest; +class PrefChangeRegistrar; +class PrefService; using brave_component_updater::BraveComponent; @@ -63,6 +67,21 @@ std::unique_ptr AdBlockServiceFactory( // Registers the local_state preferences used by Adblock void RegisterPrefsForAdBlockService(PrefRegistrySimple* registry); +// Eventually we should merge |AdBlockService| into this class. At the moment +// it's only responsibility is tracking some adblocking preferences. +class AdBlockPrefService : public KeyedService { + public: + explicit AdBlockPrefService(PrefService* prefs); + ~AdBlockPrefService() override; + + private: + void OnPreferenceChanged(const std::string& pref_name); + + PrefService* prefs_ = nullptr; + std::unique_ptr + pref_change_registrar_; +}; + } // namespace brave_shields #endif // BRAVE_COMPONENTS_BRAVE_SHIELDS_BROWSER_AD_BLOCK_SERVICE_H_ diff --git a/components/brave_shields/browser/adblock_stub_response.cc b/components/brave_shields/browser/adblock_stub_response.cc new file mode 100644 index 00000000000..efc4c57799c --- /dev/null +++ b/components/brave_shields/browser/adblock_stub_response.cc @@ -0,0 +1,113 @@ +/* Copyright 2019 The Brave Authors. All rights reserved. + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this file, + * You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#include "brave/components/brave_shields/browser/adblock_stub_response.h" + +#include + +#include "base/compiler_specific.h" +#include "base/containers/flat_map.h" +#include "base/no_destructor.h" +#include "base/strings/string_split.h" +#include "net/http/http_util.h" +#include "services/network/public/cpp/resource_response.h" +#include "services/network/public/cpp/resource_request.h" + +namespace brave_shields { +namespace { + +// Everything but jpeg is a transparent pixel. +const unsigned char kWebp1x1[] = { + 0x52, 0x49, 0x46, 0x46, 0x1a, 0x00, 0x00, 0x00, 0x57, 0x45, 0x42, 0x50, + 0x56, 0x50, 0x38, 0x4c, 0x0d, 0x00, 0x00, 0x00, 0x2f, 0x00, 0x00, 0x00, + 0x10, 0x07, 0x10, 0x11, 0x11, 0x88, 0x88, 0xfe, 0x07, 0x00}; +const unsigned char kPng1x1[] = { + 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0d, + 0x49, 0x48, 0x44, 0x52, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, + 0x08, 0x04, 0x00, 0x00, 0x00, 0xb5, 0x1c, 0x0c, 0x02, 0x00, 0x00, 0x00, + 0x0b, 0x49, 0x44, 0x41, 0x54, 0x78, 0x9c, 0x63, 0xfa, 0xcf, 0x00, 0x00, + 0x02, 0x07, 0x01, 0x02, 0x9a, 0x1c, 0x31, 0x71, 0x00, 0x00, 0x00, 0x00, + 0x49, 0x45, 0x4e, 0x44, 0xae, 0x42, 0x60, 0x82}; +const unsigned char kGif1x1[] = { + 0x47, 0x49, 0x46, 0x38, 0x39, 0x61, 0x01, 0x00, 0x01, 0x00, 0x80, + 0x01, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0x21, 0xf9, 0x04, + 0x01, 0x0a, 0x00, 0x01, 0x00, 0x2c, 0x00, 0x00, 0x00, 0x00, 0x01, + 0x00, 0x01, 0x00, 0x00, 0x02, 0x02, 0x4c, 0x01, 0x00, 0x3b}; +const unsigned char kJpeg1x1[] = { + 0xff, 0xd8, 0xff, 0xdb, 0x00, 0x43, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xc0, 0x00, 0x0b, 0x08, 0x00, 0x01, 0x00, 0x01, 0x01, 0x01, 0x11, 0x00, + 0xff, 0xc4, 0x00, 0x14, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0xff, 0xc4, + 0x00, 0x14, 0x10, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xda, 0x00, 0x08, + 0x01, 0x01, 0x00, 0x00, 0x3f, 0x00, 0x37, 0xff, 0xd9}; + +// Basically, for now all Chromium image resource requests use hardcoded +// 'Accept' header that starts with "image/webp". However, it is possible to +// craft a custom 'Accept', for example, using XHR, so we provide stubs for +// other popular mime types. +std::string GetContentForMimeType(const std::string& mime_type) { + static const base::NoDestructor< + base::flat_map> + content({ + {"image/webp", {kWebp1x1, std::end(kWebp1x1)}}, + {"image/*", {kPng1x1, std::end(kPng1x1)}}, + {"image/apng", {kPng1x1, std::end(kPng1x1)}}, + {"image/png", {kPng1x1, std::end(kPng1x1)}}, + {"image/x-png", {kPng1x1, std::end(kPng1x1)}}, + {"image/gif", {kGif1x1, std::end(kGif1x1)}}, + {"image/jpeg", {kJpeg1x1, std::end(kJpeg1x1)}}, + }); + auto it = content->find(mime_type); + if (it == content->end()) { + return {}; + } + return it->second; +} + +} // namespace + +void MakeStubResponse(const network::ResourceRequest& request, + network::ResourceResponseHead* response, + std::string* data) { + DCHECK(response); + DCHECK(data); + + response->mime_type = "text/html"; + *data = {}; + + // Possibly overwrite mime and stub data. + std::string accept_header; + request.headers.GetHeader("Accept", &accept_header); + auto mime_types = base::SplitString( + accept_header, ",;", base::TRIM_WHITESPACE, base::SPLIT_WANT_NONEMPTY); + if (!mime_types.empty()) { + DCHECK(!mime_types.front().empty()); + // If the entry looks like "*/*", use the default value. Otherwise, use + // the value from 'Accept', even if it looks like "audio/*". + if (mime_types.front()[0] != '*') { + response->mime_type = mime_types.front(); + } + *data = GetContentForMimeType(response->mime_type); + } + + // Craft response headers. + // TODO(iefremov): Allowing any origins still breaks some CORS requests. + // Maybe we can provide something smarter here (issues/4396). + std::string raw_headers = + "HTTP/1.1 200 OK\r\n" + "Access-Control-Allow-Origin: *\r\n" + "Content-Type: " + response->mime_type + "\r\n"; + response->headers = + new net::HttpResponseHeaders(net::HttpUtil::AssembleRawHeaders( + raw_headers)); +} + +} // namespace brave_shields diff --git a/components/brave_shields/browser/adblock_stub_response.h b/components/brave_shields/browser/adblock_stub_response.h new file mode 100644 index 00000000000..40c19e00f26 --- /dev/null +++ b/components/brave_shields/browser/adblock_stub_response.h @@ -0,0 +1,26 @@ +/* Copyright 2019 The Brave Authors. All rights reserved. + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this file, + * You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#ifndef BRAVE_COMPONENTS_BRAVE_SHIELDS_BROWSER_ADBLOCK_STUB_RESPONSE_H_ +#define BRAVE_COMPONENTS_BRAVE_SHIELDS_BROWSER_ADBLOCK_STUB_RESPONSE_H_ + +#include + +namespace network { +struct ResourceResponseHead; +struct ResourceRequest; +} + +namespace brave_shields { + +// Intercepts certain requests and blocks them by silently returning 200 OK +// and not allowing them to hit the network. +void MakeStubResponse(const network::ResourceRequest& request, + network::ResourceResponseHead* response, + std::string* data); + +} // namespace brave_shields + +#endif // BRAVE_COMPONENTS_BRAVE_SHIELDS_BROWSER_ADBLOCK_STUB_RESPONSE_H_ diff --git a/components/brave_webtorrent/browser/net/brave_torrent_redirect_network_delegate_helper_unittest.cc b/components/brave_webtorrent/browser/net/brave_torrent_redirect_network_delegate_helper_unittest.cc index 0d20c8901e8..4d52123fe9f 100644 --- a/components/brave_webtorrent/browser/net/brave_torrent_redirect_network_delegate_helper_unittest.cc +++ b/components/brave_webtorrent/browser/net/brave_torrent_redirect_network_delegate_helper_unittest.cc @@ -340,4 +340,16 @@ TEST_F(BraveTorrentRedirectNetworkDelegateHelperTest, &location)); EXPECT_EQ(allowed_unsafe_redirect_url, GURL::EmptyGURL()); EXPECT_EQ(ret, net::OK); + + brave_request_info->resource_type = content::ResourceType::kSubFrame; + + ret = webtorrent::OnHeadersReceived_TorrentRedirectWork( + orig_response_headers.get(), &overwrite_response_headers, + &allowed_unsafe_redirect_url, callback, brave_request_info); + + EXPECT_EQ(overwrite_response_headers->GetStatusLine(), "HTTP/1.0 200 OK"); + EXPECT_FALSE(overwrite_response_headers->EnumerateHeader(nullptr, "Location", + &location)); + EXPECT_EQ(allowed_unsafe_redirect_url, GURL::EmptyGURL()); + EXPECT_EQ(ret, net::OK); } From 17dbd270b0c9e0f0b8c0ef11d172f82e047feb35 Mon Sep 17 00:00:00 2001 From: Brian Johnson Date: Fri, 16 Aug 2019 09:43:15 -0700 Subject: [PATCH 4/6] Merge pull request #3130 from brave/brave-cookie-settings-ns use chromium cookie settings --- app/android/BUILD.gn | 19 -- browser/BUILD.gn | 5 +- browser/brave_content_browser_client.cc | 25 +- .../cookie_pref_service_factory.cc | 47 +++ .../cookie_pref_service_factory.h | 40 +++ browser/brave_tab_helpers.cc | 6 +- ...browser_context_keyed_service_factories.cc | 2 + .../brave_cookie_settings_factory.cc | 16 - .../brave_cookie_settings_factory.h | 33 --- browser/net/BUILD.gn | 12 +- browser/net/brave_network_delegate_base.cc | 28 +- .../net/brave_network_delegate_browsertest.cc | 17 +- browser/profiles/brave_profile_manager.cc | 1 + .../chrome_render_message_filter.cc | 11 - .../chrome_render_message_filter.h | 15 - .../services/network/network_context.cc | 36 +++ common/BUILD.gn | 8 +- common/shield_exceptions.cc | 40 --- common/shield_exceptions.h | 3 - common/shield_exceptions_unittest.cc | 4 +- components/brave_shields/browser/BUILD.gn | 5 + .../browser/brave_shields_util.cc | 73 +++-- .../browser/brave_shields_util.h | 6 + .../browser/cookie_pref_service.cc | 95 ++++++ .../browser/cookie_pref_service.h | 46 +++ .../browser/tracking_protection_helper.cc | 7 - .../browser/tracking_protection_helper.h | 1 - .../browser/tracking_protection_service.cc | 60 ++-- .../browser/tracking_protection_service.h | 16 +- .../content_settings/core/browser/BUILD.gn | 5 +- .../brave_content_settings_pref_provider.cc | 274 +++++++++++++++++- .../brave_content_settings_pref_provider.h | 36 ++- .../core/browser/brave_cookie_settings.cc | 168 ----------- .../core/browser/brave_cookie_settings.h | 60 ---- .../core/browser/content_settings_util.cc | 55 ---- .../core/browser/content_settings_util.h | 30 -- .../content_settings/core/common/BUILD.gn | 12 + .../core/common/content_settings_util.cc | 101 +++++++ .../core/common/content_settings_util.h | 33 +++ extensions/BUILD.gn | 24 ++ ..._settings-cookie_settings_factory.cc.patch | 21 -- ...ntent_settings-core-browser-BUILD.gn.patch | 12 - ...tings-core-browser-cookie_settings.h.patch | 12 - .../services-network-network_context.cc.patch | 20 ++ ...e_content_settings_observer_browsertest.cc | 128 +++----- 45 files changed, 935 insertions(+), 733 deletions(-) create mode 100644 browser/brave_shields/cookie_pref_service_factory.cc create mode 100644 browser/brave_shields/cookie_pref_service_factory.h delete mode 100644 browser/content_settings/brave_cookie_settings_factory.cc delete mode 100644 browser/content_settings/brave_cookie_settings_factory.h delete mode 100644 chromium_src/chrome/browser/renderer_host/chrome_render_message_filter.cc delete mode 100644 chromium_src/chrome/browser/renderer_host/chrome_render_message_filter.h create mode 100644 chromium_src/services/network/network_context.cc create mode 100644 components/brave_shields/browser/cookie_pref_service.cc create mode 100644 components/brave_shields/browser/cookie_pref_service.h delete mode 100644 components/content_settings/core/browser/brave_cookie_settings.cc delete mode 100644 components/content_settings/core/browser/brave_cookie_settings.h delete mode 100644 components/content_settings/core/browser/content_settings_util.cc delete mode 100644 components/content_settings/core/browser/content_settings_util.h create mode 100644 components/content_settings/core/common/BUILD.gn create mode 100644 components/content_settings/core/common/content_settings_util.cc create mode 100644 components/content_settings/core/common/content_settings_util.h create mode 100644 extensions/BUILD.gn delete mode 100644 patches/chrome-browser-content_settings-cookie_settings_factory.cc.patch delete mode 100644 patches/components-content_settings-core-browser-BUILD.gn.patch delete mode 100644 patches/components-content_settings-core-browser-cookie_settings.h.patch create mode 100644 patches/services-network-network_context.cc.patch diff --git a/app/android/BUILD.gn b/app/android/BUILD.gn index a6c5f91496b..5022d3a8543 100755 --- a/app/android/BUILD.gn +++ b/app/android/BUILD.gn @@ -2,22 +2,3 @@ import("//brave/build/config.gni") group("symbol_dist_resources") {} group("dist_resources") {} - -source_set("common_extensions") { - sources = [ - "//extensions/common/error_utils.cc", - "//extensions/common/error_utils.h", - "//extensions/common/url_pattern.cc", - "//extensions/common/url_pattern.h", - "//extensions/common/url_pattern_set.cc", - "//extensions/common/url_pattern_set.h", - ] - - deps = [ - "//base", - "//components/url_pattern_index", - "//extensions/buildflags", - "//extensions/common:common_constants", - "//url", - ] -} diff --git a/browser/BUILD.gn b/browser/BUILD.gn index 48892acc50f..9730da1fd16 100644 --- a/browser/BUILD.gn +++ b/browser/BUILD.gn @@ -23,6 +23,8 @@ source_set("browser_process") { "autocomplete/brave_autocomplete_scheme_classifier.h", "brave_shields/ad_block_pref_service_factory.cc", "brave_shields/ad_block_pref_service_factory.h", + "brave_shields/cookie_pref_service_factory.cc", + "brave_shields/cookie_pref_service_factory.h", "brave_browser_main_extra_parts.cc", "brave_browser_main_extra_parts.h", "brave_browser_main_parts.cc", @@ -59,8 +61,6 @@ source_set("browser_process") { "component_updater/brave_component_updater_delegate.h", "component_updater/brave_crx_update_service.cc", "component_updater/brave_crx_update_service.h", - "content_settings/brave_cookie_settings_factory.cc", - "content_settings/brave_cookie_settings_factory.h", "geolocation/brave_geolocation_permission_context.cc", "geolocation/brave_geolocation_permission_context.h", "metrics/metrics_reporting_util.cc", @@ -123,6 +123,7 @@ source_set("browser_process") { "//components/browsing_data/core", "//components/component_updater", "//components/content_settings/core/common", + "//components/content_settings/core/browser", "//components/keyed_service/content", "//components/password_manager/core/common", "//components/prefs", diff --git a/browser/brave_content_browser_client.cc b/browser/brave_content_browser_client.cc index 1560cd178bf..4a8a836e3de 100644 --- a/browser/brave_content_browser_client.cc +++ b/browser/brave_content_browser_client.cc @@ -22,12 +22,10 @@ #include "brave/components/brave_rewards/browser/buildflags/buildflags.h" #include "brave/components/brave_shields/browser/brave_shields_util.h" #include "brave/components/brave_shields/browser/brave_shields_web_contents_observer.h" -#include "brave/components/brave_shields/browser/buildflags/buildflags.h" // For STP #include "brave/components/brave_shields/browser/tracking_protection_service.h" #include "brave/components/brave_shields/common/brave_shield_constants.h" #include "brave/components/brave_wallet/browser/buildflags/buildflags.h" #include "brave/components/brave_webtorrent/browser/buildflags/buildflags.h" -#include "brave/components/content_settings/core/browser/brave_cookie_settings.h" #include "brave/components/services/brave_content_browser_overlay_manifest.h" #include "brave/grit/brave_generated_resources.h" #include "chrome/browser/content_settings/tab_specific_content_settings.h" @@ -142,18 +140,21 @@ bool BraveContentBrowserClient::AllowAccessCookie( content::ResourceContext* context, int render_process_id, int render_frame_id) { - GURL tab_origin = - BraveShieldsWebContentsObserver::GetTabURLFromRenderFrameInfo( - render_process_id, render_frame_id, -1).GetOrigin(); - ProfileIOData* io_data = ProfileIOData::FromResourceContext(context); - content_settings::BraveCookieSettings* cookie_settings = - (content_settings::BraveCookieSettings*)io_data->GetCookieSettings(); + GURL tab_origin = first_party; + + if (tab_origin.is_empty()) + tab_origin = BraveShieldsWebContentsObserver::GetTabURLFromRenderFrameInfo( + render_process_id, render_frame_id, -1).GetOrigin(); - return cookie_settings->IsCookieAccessAllowed(url, first_party, tab_origin) && - // TODO(bridiver) - handle this in BraveCookieSettings + ProfileIOData* io_data = ProfileIOData::FromResourceContext(context); + return + io_data->GetCookieSettings()->IsCookieAccessAllowed(url, tab_origin) && g_brave_browser_process->tracking_protection_service()->ShouldStoreState( - cookie_settings, io_data->GetHostContentSettingsMap(), - render_process_id, render_frame_id, url, first_party, tab_origin); + io_data->GetHostContentSettingsMap(), + render_process_id, + render_frame_id, + url, + tab_origin); } bool BraveContentBrowserClient::AllowGetCookie( diff --git a/browser/brave_shields/cookie_pref_service_factory.cc b/browser/brave_shields/cookie_pref_service_factory.cc new file mode 100644 index 00000000000..b91e8887743 --- /dev/null +++ b/browser/brave_shields/cookie_pref_service_factory.cc @@ -0,0 +1,47 @@ +/* Copyright (c) 2019 The Brave Authors. All rights reserved. + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this file, + * You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#include "brave/browser/brave_shields/cookie_pref_service_factory.h" +#include "brave/components/brave_shields/browser/cookie_pref_service.h" +#include "chrome/browser/content_settings/host_content_settings_map_factory.h" +#include "chrome/browser/profiles/profile.h" +#include "components/content_settings/core/browser/host_content_settings_map.h" +#include "components/keyed_service/content/browser_context_dependency_manager.h" + +namespace brave_shields { + +// static +CookiePrefService* CookiePrefServiceFactory::GetForBrowserContext( + content::BrowserContext* context) { + return static_cast( + GetInstance()->GetServiceForBrowserContext(context, + /*create_service=*/true)); +} + +// static +CookiePrefServiceFactory* CookiePrefServiceFactory::GetInstance() { + return base::Singleton::get(); +} + +CookiePrefServiceFactory::CookiePrefServiceFactory() + : BrowserContextKeyedServiceFactory( + "CookiePrefService", + BrowserContextDependencyManager::GetInstance()) {} + +CookiePrefServiceFactory::~CookiePrefServiceFactory() {} + +KeyedService* CookiePrefServiceFactory::BuildServiceInstanceFor( + content::BrowserContext* context) const { + auto* profile = Profile::FromBrowserContext(context); + return new CookiePrefService( + HostContentSettingsMapFactory::GetForProfile(profile), + profile->GetPrefs()); +} + +bool CookiePrefServiceFactory::ServiceIsCreatedWithBrowserContext() const { + return true; +} + +} // namespace brave_shields diff --git a/browser/brave_shields/cookie_pref_service_factory.h b/browser/brave_shields/cookie_pref_service_factory.h new file mode 100644 index 00000000000..4bed27bb233 --- /dev/null +++ b/browser/brave_shields/cookie_pref_service_factory.h @@ -0,0 +1,40 @@ +/* Copyright (c) 2019 The Brave Authors. All rights reserved. + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this file, + * You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#ifndef BRAVE_BROWSER_BRAVE_SHIELDS_COOKIE_PREF_SERVICE_FACTORY_H_ +#define BRAVE_BROWSER_BRAVE_SHIELDS_COOKIE_PREF_SERVICE_FACTORY_H_ + +#include "base/memory/singleton.h" +#include "components/keyed_service/content/browser_context_keyed_service_factory.h" + +namespace brave_shields { + +class CookiePrefService; + +class CookiePrefServiceFactory : public BrowserContextKeyedServiceFactory { + public: + static CookiePrefService* GetForBrowserContext( + content::BrowserContext* context); + + static CookiePrefServiceFactory* GetInstance(); + + private: + friend struct base::DefaultSingletonTraits; + + CookiePrefServiceFactory(); + ~CookiePrefServiceFactory() override; + + // BrowserContextKeyedServiceFactory: + KeyedService* BuildServiceInstanceFor( + content::BrowserContext* profile) const override; + + bool ServiceIsCreatedWithBrowserContext() const override; + + DISALLOW_COPY_AND_ASSIGN(CookiePrefServiceFactory); +}; + +} // namespace brave_shields + +#endif // BRAVE_BROWSER_BRAVE_SHIELDS_COOKIE_PREF_SERVICE_FACTORY_H_ diff --git a/browser/brave_tab_helpers.cc b/browser/brave_tab_helpers.cc index 026754caae7..510633bbcd7 100644 --- a/browser/brave_tab_helpers.cc +++ b/browser/brave_tab_helpers.cc @@ -18,10 +18,10 @@ #if BUILDFLAG(BRAVE_REWARDS_ENABLED) #include "brave/browser/brave_rewards/rewards_tab_helper.h" #endif + #if BUILDFLAG(BRAVE_STP_ENABLED) #include "brave/components/brave_shields/browser/tracking_protection_helper.h" - -using brave_shields::TrackingProtectionHelper; +#include "brave/components/brave_shields/browser/tracking_protection_service.h" #endif // Add tab helpers here unless they are intended for android too #endif @@ -40,7 +40,7 @@ void AttachTabHelpers(content::WebContents* web_contents) { BraveBookmarkTabHelper::CreateForWebContents(web_contents); #if BUILDFLAG(BRAVE_STP_ENABLED) - if (TrackingProtectionHelper::IsSmartTrackingProtectionEnabled()) { + if (TrackingProtectionService::IsSmartTrackingProtectionEnabled()) { brave_shields::TrackingProtectionHelper::CreateForWebContents(web_contents); } #endif diff --git a/browser/browser_context_keyed_service_factories.cc b/browser/browser_context_keyed_service_factories.cc index bd30e4581d6..e669b2abf3c 100644 --- a/browser/browser_context_keyed_service_factories.cc +++ b/browser/browser_context_keyed_service_factories.cc @@ -6,6 +6,7 @@ #include "brave/browser/browser_context_keyed_service_factories.h" #include "brave/browser/brave_shields/ad_block_pref_service_factory.h" +#include "brave/browser/brave_shields/cookie_pref_service_factory.h" #include "brave/browser/greaselion/greaselion_service_factory.h" #include "brave/browser/search_engines/search_engine_provider_service_factory.h" #include "brave/browser/tor/tor_profile_service_factory.h" @@ -22,6 +23,7 @@ void EnsureBrowserContextKeyedServiceFactoriesBuilt() { brave_ads::AdsServiceFactory::GetInstance(); brave_rewards::RewardsServiceFactory::GetInstance(); brave_shields::AdBlockPrefServiceFactory::GetInstance(); + brave_shields::CookiePrefServiceFactory::GetInstance(); greaselion::GreaselionServiceFactory::GetInstance(); TorProfileServiceFactory::GetInstance(); SearchEngineProviderServiceFactory::GetInstance(); diff --git a/browser/content_settings/brave_cookie_settings_factory.cc b/browser/content_settings/brave_cookie_settings_factory.cc deleted file mode 100644 index 6cb9979be9a..00000000000 --- a/browser/content_settings/brave_cookie_settings_factory.cc +++ /dev/null @@ -1,16 +0,0 @@ -/* Copyright (c) 2019 The Brave Authors. All rights reserved. - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#include "brave/browser/content_settings/brave_cookie_settings_factory.h" - -#include "brave/components/content_settings/core/browser/brave_cookie_settings.h" -#include "content/public/browser/browser_thread.h" - -// static -scoped_refptr -BraveCookieSettingsFactory::GetForProfile(Profile* profile) { - return static_cast( - CookieSettingsFactory::GetForProfile(profile).get()); -} diff --git a/browser/content_settings/brave_cookie_settings_factory.h b/browser/content_settings/brave_cookie_settings_factory.h deleted file mode 100644 index 8cdef86252c..00000000000 --- a/browser/content_settings/brave_cookie_settings_factory.h +++ /dev/null @@ -1,33 +0,0 @@ -/* Copyright (c) 2019 The Brave Authors. All rights reserved. - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef BRAVE_BROWSER_CONTENT_SETTINGS_BRAVE_COOKIE_SETTINGS_FACTORY_H_ -#define BRAVE_BROWSER_CONTENT_SETTINGS_BRAVE_COOKIE_SETTINGS_FACTORY_H_ - -#include - -#include "chrome/browser/content_settings/cookie_settings_factory.h" - -namespace content_settings { -class BraveCookieSettings; -} - -class Profile; - -class BraveCookieSettingsFactory : public CookieSettingsFactory { - public: - static scoped_refptr GetForProfile( - Profile* profile); - - private: - friend struct base::DefaultSingletonTraits; - - BraveCookieSettingsFactory(); - ~BraveCookieSettingsFactory() override; - - DISALLOW_COPY_AND_ASSIGN(BraveCookieSettingsFactory); -}; - -#endif // BRAVE_BROWSER_CONTENT_SETTINGS_BRAVE_COOKIE_SETTINGS_FACTORY_H_ diff --git a/browser/net/BUILD.gn b/browser/net/BUILD.gn index 14cefeda541..cce4e760f78 100644 --- a/browser/net/BUILD.gn +++ b/browser/net/BUILD.gn @@ -37,9 +37,11 @@ source_set("net") { "//brave/app:brave_generated_resources_grit", "//brave/browser/safebrowsing", "//brave/components/brave_shields/browser", + "//brave/extensions:common", "//components/prefs", "//content/public/browser", "//content/public/common", + "//components/content_settings/core/browser", "//extensions/common:common_constants", "//mojo/public/cpp/bindings", "//mojo/public/cpp/system", @@ -49,16 +51,6 @@ source_set("net") { "//url", ] - if (is_android) { - deps += [ - "//brave/app/android:common_extensions", - ] - } else { - deps += [ - "//extensions/common", - ] - } - if (enable_brave_referrals) { sources += [ "brave_referrals_network_delegate_helper.cc", diff --git a/browser/net/brave_network_delegate_base.cc b/browser/net/brave_network_delegate_base.cc index 4376a3940ec..4b03c7ea522 100644 --- a/browser/net/brave_network_delegate_base.cc +++ b/browser/net/brave_network_delegate_base.cc @@ -15,10 +15,10 @@ #include "brave/components/brave_shields/browser/brave_shields_util.h" #include "brave/components/brave_shields/browser/brave_shields_web_contents_observer.h" #include "brave/components/brave_shields/browser/tracking_protection_service.h" -#include "brave/components/content_settings/core/browser/brave_cookie_settings.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/content_settings/tab_specific_content_settings.h" #include "chrome/browser/profiles/profile_io_data.h" +#include "components/content_settings/core/browser/cookie_settings.h" #include "components/prefs/pref_change_registrar.h" #include "components/prefs/pref_service.h" #include "content/public/browser/browser_task_traits.h" @@ -40,25 +40,21 @@ bool OnAllowAccessCookies( ProfileIOData* io_data = ProfileIOData::FromResourceContext(info->GetContext()); - content_settings::BraveCookieSettings* cookie_settings = - (content_settings::BraveCookieSettings*)io_data->GetCookieSettings(); - GURL url = request.url(); - GURL first_party = request.site_for_cookies(); - GURL tab_origin = GURL(request.network_isolation_key().ToString()); + GURL tab_origin = request.site_for_cookies(); + if (tab_origin.is_empty()) + tab_origin = GURL(request.network_isolation_key().ToString()); if (tab_origin.is_empty() && request.top_frame_origin().has_value()) tab_origin = request.top_frame_origin()->GetURL(); + return - cookie_settings->IsCookieAccessAllowed(url, first_party, tab_origin) && - // TODO(bridiver) - handle this in BraveCookieSettings - g_brave_browser_process->tracking_protection_service() - ->ShouldStoreState(cookie_settings, - io_data->GetHostContentSettingsMap(), - ctx->render_process_id, - ctx->render_frame_id, - url, - first_party, - tab_origin); + io_data->GetCookieSettings()->IsCookieAccessAllowed(url, tab_origin) && + g_brave_browser_process->tracking_protection_service() + ->ShouldStoreState(io_data->GetHostContentSettingsMap(), + ctx->render_process_id, + ctx->render_frame_id, + url, + tab_origin); } return true; diff --git a/browser/net/brave_network_delegate_browsertest.cc b/browser/net/brave_network_delegate_browsertest.cc index 5bd1ebab452..b8bd2e30f11 100644 --- a/browser/net/brave_network_delegate_browsertest.cc +++ b/browser/net/brave_network_delegate_browsertest.cc @@ -1,9 +1,11 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public +/* Copyright (c) 2019 The Brave Authors. All rights reserved. + * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this file, * You can obtain one at http://mozilla.org/MPL/2.0/. */ #include "base/path_service.h" #include "brave/common/brave_paths.h" +#include "brave/components/brave_shields/browser/brave_shields_util.h" #include "brave/components/brave_shields/common/brave_shield_constants.h" #include "chrome/browser/content_settings/host_content_settings_map_factory.h" #include "chrome/browser/profiles/profile.h" @@ -34,6 +36,7 @@ class BraveNetworkDelegateBrowserTest : public InProcessBrowserTest { nested_iframe_script_url_ = embedded_test_server()->GetURL("a.com", "/nested_iframe_script.html"); + top_level_page_url_ = GURL("http://a.com/"); top_level_page_pattern_ = ContentSettingsPattern::FromString("http://a.com/*"); first_party_pattern_ = @@ -45,14 +48,9 @@ class BraveNetworkDelegateBrowserTest : public InProcessBrowserTest { } void AllowCookies() { - content_settings()->SetContentSettingCustomScope( - top_level_page_pattern_, ContentSettingsPattern::Wildcard(), - CONTENT_SETTINGS_TYPE_PLUGINS, brave_shields::kCookies, - CONTENT_SETTING_ALLOW); - content_settings()->SetContentSettingCustomScope( - top_level_page_pattern_, first_party_pattern_, - CONTENT_SETTINGS_TYPE_PLUGINS, brave_shields::kCookies, - CONTENT_SETTING_ALLOW); + brave_shields::SetCookieControlType(browser()->profile(), + brave_shields::ControlType::ALLOW, + top_level_page_url_); } protected: @@ -60,6 +58,7 @@ class BraveNetworkDelegateBrowserTest : public InProcessBrowserTest { GURL nested_iframe_script_url_; private: + GURL top_level_page_url_; ContentSettingsPattern top_level_page_pattern_; ContentSettingsPattern first_party_pattern_; ContentSettingsPattern iframe_pattern_; diff --git a/browser/profiles/brave_profile_manager.cc b/browser/profiles/brave_profile_manager.cc index 4d1be8ab7fd..44beb69314d 100644 --- a/browser/profiles/brave_profile_manager.cc +++ b/browser/profiles/brave_profile_manager.cc @@ -22,6 +22,7 @@ #include "brave/components/brave_rewards/browser/rewards_service_factory.h" #include "brave/components/brave_shields/browser/ad_block_regional_service.h" #include "brave/components/brave_shields/browser/ad_block_service.h" +#include "brave/components/brave_shields/browser/brave_shields_util.h" #include "brave/content/browser/webui/brave_shared_resources_data_source.h" #include "chrome/browser/browser_process.h" #include "chrome/common/chrome_constants.h" diff --git a/chromium_src/chrome/browser/renderer_host/chrome_render_message_filter.cc b/chromium_src/chrome/browser/renderer_host/chrome_render_message_filter.cc deleted file mode 100644 index 2836cf4f5e5..00000000000 --- a/chromium_src/chrome/browser/renderer_host/chrome_render_message_filter.cc +++ /dev/null @@ -1,11 +0,0 @@ -/* Copyright (c) 2019 The Brave Authors. All rights reserved. - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#include "chrome/browser/renderer_host/chrome_render_message_filter.h" -#include "brave/browser/content_settings/brave_cookie_settings_factory.h" - -#define CookieSettingsFactory BraveCookieSettingsFactory -#include "../../../../../../chrome/browser/renderer_host/chrome_render_message_filter.cc" // NOLINT -#undef CookieSettingsFactory diff --git a/chromium_src/chrome/browser/renderer_host/chrome_render_message_filter.h b/chromium_src/chrome/browser/renderer_host/chrome_render_message_filter.h deleted file mode 100644 index 3f7cc47ad9a..00000000000 --- a/chromium_src/chrome/browser/renderer_host/chrome_render_message_filter.h +++ /dev/null @@ -1,15 +0,0 @@ -/* Copyright (c) 2019 The Brave Authors. All rights reserved. - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef BRAVE_CHROMIUM_SRC_CHROME_BROWSER_RENDERER_HOST_CHROME_RENDER_MESSAGE_FILTER_H_ -#define BRAVE_CHROMIUM_SRC_CHROME_BROWSER_RENDERER_HOST_CHROME_RENDER_MESSAGE_FILTER_H_ - -#include "brave/components/content_settings/core/browser/brave_cookie_settings.h" - -#define CookieSettings BraveCookieSettings -#include "../../../../../../chrome/browser/renderer_host/chrome_render_message_filter.h" -#undef CookieSettings - -#endif // BRAVE_CHROMIUM_SRC_CHROME_BROWSER_RENDERER_HOST_CHROME_RENDER_MESSAGE_FILTER_H_ diff --git a/chromium_src/services/network/network_context.cc b/chromium_src/services/network/network_context.cc new file mode 100644 index 00000000000..64028dee201 --- /dev/null +++ b/chromium_src/services/network/network_context.cc @@ -0,0 +1,36 @@ +/* Copyright (c) 2019 The Brave Authors. All rights reserved. + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this file, + * You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#include "services/network/network_context.h" + +GURL GetURLForCookieAccess(const net::URLRequest& request) { + if (!request.site_for_cookies().is_empty()) + return request.site_for_cookies(); + + if (request.network_isolation_key().IsFullyPopulated()) { + GURL origin(request.network_isolation_key().ToString()); + if (origin.is_valid()) + return origin; + } + + if (request.top_frame_origin().has_value()) + return request.top_frame_origin()->GetURL(); + + return GURL(); +} + +#define BRAVE_ON_CAN_GET_COOKIES_INTERNAL \ +network_context_->cookie_manager() \ + ->cookie_settings() \ + .IsCookieAccessAllowed( \ + request.url(), \ + GetURLForCookieAccess(request)) \ + && + +#define BRAVE_ON_CAN_SET_COOKIES_INTERNAL BRAVE_ON_CAN_GET_COOKIES_INTERNAL + +#include "../../../../services/network/network_context.cc" // NOLINT +#undef BRAVE_ON_CAN_GET_COOKIES_INTERNAL +#undef BRAVE_ON_CAN_SET_COOKIES_INTERNAL diff --git a/common/BUILD.gn b/common/BUILD.gn index 9c5481e945a..caadf808411 100644 --- a/common/BUILD.gn +++ b/common/BUILD.gn @@ -123,15 +123,9 @@ source_set("shield_exceptions") { ] deps = [ + "//brave/extensions:common", "//url", ] - if (is_android) { - deps += [ - "//brave/app/android:common_extensions", - ] - } else { - deps += [ "//extensions/common" ] - } } config("constants_configs") { diff --git a/common/shield_exceptions.cc b/common/shield_exceptions.cc index 25995c52346..d888a1c092c 100644 --- a/common/shield_exceptions.cc +++ b/common/shield_exceptions.cc @@ -38,46 +38,6 @@ bool IsBlockedResource(const GURL& gurl) { }); } -bool IsWhitelistedCookieException(const GURL& firstPartyOrigin, - const GURL& subresourceUrl, bool allow_google_auth) { - // Note that there's already an exception for TLD+1, so don't add those here. - // Check with the security team before adding exceptions. - - // 1st-party-INdependent whitelist - std::vector fpi_whitelist_patterns = {}; - if (allow_google_auth) { - fpi_whitelist_patterns.push_back(URLPattern(URLPattern::SCHEME_ALL, - "https://accounts.google.com/o/oauth2/*")); - } - bool any_match = std::any_of(fpi_whitelist_patterns.begin(), - fpi_whitelist_patterns.end(), - [&subresourceUrl](const URLPattern& pattern) { - return pattern.MatchesURL(subresourceUrl); - }); - if (any_match) { - return true; - } - - // 1st-party-dependent whitelist - static std::map > whitelist_patterns = { - { - GURL("https://www.sliver.tv/"), - std::vector({URLPattern(URLPattern::SCHEME_ALL, - "https://*.thetatoken.org:8700/*")}) - } - }; - std::map >::iterator i = - whitelist_patterns.find(firstPartyOrigin); - if (i == whitelist_patterns.end()) { - return false; - } - std::vector &exceptions = i->second; - return std::any_of(exceptions.begin(), exceptions.end(), - [&subresourceUrl](const URLPattern& pattern) { - return pattern.MatchesURL(subresourceUrl); - }); -} - bool IsWhitelistedFingerprintingException(const GURL& firstPartyOrigin, const GURL& subresourceUrl) { static std::map > whitelist_patterns = { diff --git a/common/shield_exceptions.h b/common/shield_exceptions.h index 96948547cf7..95140a20ed1 100644 --- a/common/shield_exceptions.h +++ b/common/shield_exceptions.h @@ -12,9 +12,6 @@ namespace brave { bool IsUAWhitelisted(const GURL& gurl); bool IsBlockedResource(const GURL& gurl); -bool IsWhitelistedCookieException(const GURL& firstPartyOrigin, - const GURL& subresourceUrl, - bool allow_google_auth); bool IsWhitelistedFingerprintingException(const GURL& firstPartyOrigin, const GURL& subresourceUrl); diff --git a/common/shield_exceptions_unittest.cc b/common/shield_exceptions_unittest.cc index 1e0948370a8..95ccfc60672 100644 --- a/common/shield_exceptions_unittest.cc +++ b/common/shield_exceptions_unittest.cc @@ -5,13 +5,13 @@ #include "brave/common/shield_exceptions.h" - +#include "brave/components/content_settings/core/common/content_settings_util.h" #include "chrome/test/base/chrome_render_view_host_test_harness.h" namespace { typedef testing::Test BraveShieldsExceptionsTest; -using brave::IsWhitelistedCookieException; +using content_settings::IsWhitelistedCookieException; using brave::IsWhitelistedFingerprintingException; TEST_F(BraveShieldsExceptionsTest, IsWhitelistedCookieException) { diff --git a/components/brave_shields/browser/BUILD.gn b/components/brave_shields/browser/BUILD.gn index f285ebbd61f..ffa315db1cf 100644 --- a/components/brave_shields/browser/BUILD.gn +++ b/components/brave_shields/browser/BUILD.gn @@ -33,6 +33,8 @@ source_set("browser") { "brave_shields_util.h", "brave_shields_web_contents_observer.cc", "brave_shields_web_contents_observer.h", + "cookie_pref_service.cc", + "cookie_pref_service.h", "https_everywhere_recently_used_cache.h", "https_everywhere_service.cc", "https_everywhere_service.h", @@ -56,11 +58,14 @@ source_set("browser") { "//brave/vendor/adblock_rust_ffi:adblock_ffi", "//brave/vendor/autoplay-whitelist/brave:autoplay-whitelist", "//chrome/common", + "//components/content_settings/core/common", + "//components/content_settings/core/browser", "//components/keyed_service/core", "//components/prefs", "//content/public/browser", "//net", "//third_party/leveldatabase", + "//url", ] if (enable_extensions) { diff --git a/components/brave_shields/browser/brave_shields_util.cc b/components/brave_shields/browser/brave_shields_util.cc index 9cc76fec838..5af0943aed6 100644 --- a/components/brave_shields/browser/brave_shields_util.cc +++ b/components/brave_shields/browser/brave_shields_util.cc @@ -13,12 +13,13 @@ #include "brave/components/brave_shields/browser/brave_shields_web_contents_observer.h" #include "brave/components/brave_shields/browser/referrer_whitelist_service.h" #include "brave/components/brave_shields/common/brave_shield_constants.h" -#include "brave/components/content_settings/core/browser/content_settings_util.h" +#include "brave/components/content_settings/core/common/content_settings_util.h" #include "chrome/browser/content_settings/host_content_settings_map_factory.h" #include "chrome/browser/profiles/profile_io_data.h" #include "components/content_settings/core/browser/host_content_settings_map.h" #include "components/content_settings/core/common/content_settings_types.h" -#include "components/content_settings/core/common/content_settings_utils.h" +#include "components/content_settings/core/common/pref_names.h" +#include "components/prefs/pref_service.h" #include "content/public/browser/browser_task_traits.h" #include "content/public/browser/resource_request_info.h" #include "content/public/browser/websocket_handshake_request_info.h" @@ -133,18 +134,22 @@ void ResetBraveShieldsEnabled(Profile* profile, CONTENT_SETTING_DEFAULT); } -bool GetBraveShieldsEnabled(Profile* profile, const GURL& url) { +bool GetBraveShieldsEnabled(HostContentSettingsMap* map, const GURL& url) { if (url.is_valid() && !url.SchemeIsHTTPOrHTTPS()) return false; - ContentSetting setting = - HostContentSettingsMapFactory::GetForProfile(profile)->GetContentSetting( - url, GURL(), CONTENT_SETTINGS_TYPE_PLUGINS, kBraveShields); + ContentSetting setting = map->GetContentSetting( + url, GURL(), CONTENT_SETTINGS_TYPE_PLUGINS, kBraveShields); // see EnableBraveShields - allow and default == true return setting == CONTENT_SETTING_BLOCK ? false : true; } +bool GetBraveShieldsEnabled(Profile* profile, const GURL& url) { + return GetBraveShieldsEnabled( + HostContentSettingsMapFactory::GetForProfile(profile), url); +} + void SetAdControlType(Profile* profile, ControlType type, const GURL& url) { DCHECK(type != ControlType::BLOCK_THIRD_PARTY); auto primary_pattern = GetPatternFromURL(url); @@ -175,13 +180,28 @@ ControlType GetAdControlType(Profile* profile, const GURL& url) { : ControlType::BLOCK; } +// TODO(bridiver) - convert cookie settings to CONTENT_SETTINGS_TYPE_COOKIES +// while maintaining read backwards compat void SetCookieControlType(Profile* profile, ControlType type, const GURL& url) { + return SetCookieControlType( + HostContentSettingsMapFactory::GetForProfile(profile), + type, + url); +} + +ControlType GetCookieControlType(Profile* profile, const GURL& url) { + return GetCookieControlType( + HostContentSettingsMapFactory::GetForProfile(profile), url); +} + +void SetCookieControlType(HostContentSettingsMap* map, + ControlType type, + const GURL& url) { auto primary_pattern = GetPatternFromURL(url); if (!primary_pattern.IsValid()) return; - auto* map = HostContentSettingsMapFactory::GetForProfile(profile); map->SetContentSettingCustomScope(primary_pattern, ContentSettingsPattern::Wildcard(), CONTENT_SETTINGS_TYPE_PLUGINS, kReferrers, @@ -199,15 +219,15 @@ void SetCookieControlType(Profile* profile, ControlType type, const GURL& url) { GetDefaultAllowFromControlType(type)); } -ControlType GetCookieControlType(Profile* profile, const GURL& url) { - ContentSetting setting = - HostContentSettingsMapFactory::GetForProfile(profile)->GetContentSetting( - url, GURL(), CONTENT_SETTINGS_TYPE_PLUGINS, kCookies); +ControlType GetCookieControlType(HostContentSettingsMap* map, const GURL& url) { + ContentSetting setting = map->GetContentSetting( + url, GURL(), CONTENT_SETTINGS_TYPE_PLUGINS, kCookies); - ContentSetting fp_setting = - HostContentSettingsMapFactory::GetForProfile(profile)->GetContentSetting( - url, GURL("https://firstParty/"), CONTENT_SETTINGS_TYPE_PLUGINS, - kCookies); + ContentSetting fp_setting = map->GetContentSetting( + url, + GURL("https://firstParty/"), + CONTENT_SETTINGS_TYPE_PLUGINS, + kCookies); if (setting == CONTENT_SETTING_ALLOW) { return ControlType::ALLOW; @@ -333,7 +353,8 @@ bool IsAllowContentSettingFromIO(const net::URLRequest* request, content::ResourceRequestInfo::ForRequest(request); if (!resource_info) { return content_settings::GetDefaultFromResourceIdentifier( - resource_identifier, primary_url, secondary_url); + resource_identifier, primary_url, secondary_url) == + CONTENT_SETTING_ALLOW; } ProfileIOData* io_data = ProfileIOData::FromResourceContext(resource_info->GetContext()); @@ -348,9 +369,14 @@ bool IsAllowContentSettingsForProfile(Profile* profile, const std::string& resource_identifier) { DCHECK_CURRENTLY_ON(BrowserThread::UI); DCHECK(profile); + auto* map = HostContentSettingsMapFactory::GetForProfile(profile); + ContentSettingsForOneType settings; + map->GetSettingsForOneType(setting_type, resource_identifier, &settings); return content_settings::IsAllowContentSetting( - HostContentSettingsMapFactory::GetForProfile(profile), primary_url, - secondary_url, setting_type, resource_identifier); + settings, + primary_url, + secondary_url, + resource_identifier); } bool IsAllowContentSettingWithIOData(ProfileIOData* io_data, @@ -362,9 +388,16 @@ bool IsAllowContentSettingWithIOData(ProfileIOData* io_data, return content_settings::GetDefaultFromResourceIdentifier( resource_identifier, primary_url, secondary_url); } + + auto* map = io_data->GetHostContentSettingsMap(); + ContentSettingsForOneType settings; + map->GetSettingsForOneType(setting_type, resource_identifier, &settings); + return content_settings::IsAllowContentSetting( - io_data->GetHostContentSettingsMap(), primary_url, secondary_url, - setting_type, resource_identifier); + settings, + primary_url, + secondary_url, + resource_identifier); } void GetRenderFrameInfo(const URLRequest* request, diff --git a/components/brave_shields/browser/brave_shields_util.h b/components/brave_shields/browser/brave_shields_util.h index ad54c83a463..fa4f1e1ac1a 100644 --- a/components/brave_shields/browser/brave_shields_util.h +++ b/components/brave_shields/browser/brave_shields_util.h @@ -23,6 +23,7 @@ struct Referrer; class GURL; class HostContentSettingsMap; +class PrefService; class Profile; class ProfileIOData; @@ -39,12 +40,17 @@ void SetBraveShieldsEnabled(Profile* profile, bool enable, const GURL& url); // reset to the default value void ResetBraveShieldsEnabled(Profile* profile, const GURL& url); bool GetBraveShieldsEnabled(Profile* profile, const GURL& url); +bool GetBraveShieldsEnabled(HostContentSettingsMap* map, const GURL& url); void SetAdControlType(Profile* profile, ControlType type, const GURL& url); ControlType GetAdControlType(Profile* profile, const GURL& url); void SetCookieControlType(Profile* profile, ControlType type, const GURL& url); +void SetCookieControlType(HostContentSettingsMap* map, + ControlType type, + const GURL& url); ControlType GetCookieControlType(Profile* profile, const GURL& url); +ControlType GetCookieControlType(HostContentSettingsMap* map, const GURL& url); void SetFingerprintingControlType(Profile* profile, ControlType type, diff --git a/components/brave_shields/browser/cookie_pref_service.cc b/components/brave_shields/browser/cookie_pref_service.cc new file mode 100644 index 00000000000..c96dcd43b80 --- /dev/null +++ b/components/brave_shields/browser/cookie_pref_service.cc @@ -0,0 +1,95 @@ +/* Copyright (c) 2019 The Brave Authors. All rights reserved. + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this file, + * You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#include "brave/components/brave_shields/browser/cookie_pref_service.h" + +#include + +#include "base/bind.h" +#include "brave/components/brave_shields/browser/brave_shields_util.h" +#include "brave/components/brave_shields/common/brave_shield_constants.h" +#include "components/content_settings/core/browser/host_content_settings_map.h" +#include "components/content_settings/core/common/content_settings_pattern.h" +#include "components/content_settings/core/common/pref_names.h" +#include "components/prefs/pref_service.h" +#include "url/gurl.h" + +namespace brave_shields { + +namespace { + +void SetCookieControlTypeFromPrefs(HostContentSettingsMap* map, + PrefService* prefs) { + auto control_type = ControlType::ALLOW; + if (prefs->GetBoolean(prefs::kBlockThirdPartyCookies)) { + control_type = ControlType::BLOCK_THIRD_PARTY; + } + + if (!prefs->GetBoolean("profile.default_content_setting_values.cookies")) { + control_type = ControlType::BLOCK; + } + + SetCookieControlType(map, control_type, GURL()); +} + +void SetCookiePrefDefaults(HostContentSettingsMap* map, + PrefService* prefs) { + auto type = GetCookieControlType(map, GURL()); + prefs->SetBoolean(prefs::kBlockThirdPartyCookies, + type == ControlType::BLOCK_THIRD_PARTY); + + if (type == ControlType::BLOCK) { + prefs->SetInteger( + "profile.default_content_setting_values.cookies", + CONTENT_SETTING_BLOCK); + } else { + prefs->SetInteger( + "profile.default_content_setting_values.cookies", + CONTENT_SETTING_ALLOW); + } +} + +} // namespace + +CookiePrefService::CookiePrefService( + HostContentSettingsMap* host_content_settings_map, + PrefService* prefs) + : host_content_settings_map_(host_content_settings_map), + prefs_(prefs) { + SetCookiePrefDefaults(host_content_settings_map, prefs); + host_content_settings_map_->AddObserver(this); + pref_change_registrar_.Init(prefs_); + pref_change_registrar_.Add( + prefs::kBlockThirdPartyCookies, + base::BindRepeating(&CookiePrefService::OnPreferenceChanged, + base::Unretained(this))); + pref_change_registrar_.Add( + "profile.default_content_setting_values.cookies", + base::BindRepeating(&CookiePrefService::OnPreferenceChanged, + base::Unretained(this))); +} + +CookiePrefService::~CookiePrefService() { + host_content_settings_map_->RemoveObserver(this); +} + +void CookiePrefService::OnPreferenceChanged() { + SetCookieControlTypeFromPrefs(host_content_settings_map_, prefs_); +} + +void CookiePrefService::OnContentSettingChanged( + const ContentSettingsPattern& primary_pattern, + const ContentSettingsPattern& secondary_pattern, + ContentSettingsType content_type, + const std::string& resource_identifier) { + if (primary_pattern == ContentSettingsPattern::Wildcard() && + secondary_pattern == ContentSettingsPattern::Wildcard() && + content_type == CONTENT_SETTINGS_TYPE_PLUGINS && + resource_identifier == brave_shields::kCookies) { + SetCookiePrefDefaults(host_content_settings_map_, prefs_); + } +} + +} // namespace brave_shields diff --git a/components/brave_shields/browser/cookie_pref_service.h b/components/brave_shields/browser/cookie_pref_service.h new file mode 100644 index 00000000000..bcbdd4e9a36 --- /dev/null +++ b/components/brave_shields/browser/cookie_pref_service.h @@ -0,0 +1,46 @@ +/* Copyright (c) 2019 The Brave Authors. All rights reserved. + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this file, + * You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#ifndef BRAVE_COMPONENTS_BRAVE_SHIELDS_BROWSER_COOKIE_PREF_SERVICE_H_ +#define BRAVE_COMPONENTS_BRAVE_SHIELDS_BROWSER_COOKIE_PREF_SERVICE_H_ + +#include + +#include "components/keyed_service/core/keyed_service.h" +#include "components/content_settings/core/browser/content_settings_observer.h" +#include "components/prefs/pref_change_registrar.h" + +class HostContentSettingsMap; +class PrefService; + +namespace brave_shields { + +// sync brave plugin cookie settings with chromium cookie prefs +class CookiePrefService : public KeyedService, + public content_settings::Observer { + public: + explicit CookiePrefService( + HostContentSettingsMap* host_content_settings_map, + PrefService* prefs); + ~CookiePrefService() override; + + private: + void OnPreferenceChanged(); + + // content_settings::Observer overrides: + void OnContentSettingChanged( + const ContentSettingsPattern& primary_pattern, + const ContentSettingsPattern& secondary_pattern, + ContentSettingsType content_type, + const std::string& resource_identifier) override; + + HostContentSettingsMap* host_content_settings_map_; + PrefService* prefs_; + PrefChangeRegistrar pref_change_registrar_; +}; + +} // namespace brave_shields + +#endif // BRAVE_COMPONENTS_BRAVE_SHIELDS_BROWSER_COOKIE_PREF_SERVICE_H_ diff --git a/components/brave_shields/browser/tracking_protection_helper.cc b/components/brave_shields/browser/tracking_protection_helper.cc index 9581ef1e758..a280977b87c 100644 --- a/components/brave_shields/browser/tracking_protection_helper.cc +++ b/components/brave_shields/browser/tracking_protection_helper.cc @@ -7,7 +7,6 @@ #include "base/task/post_task.h" #include "brave/browser/brave_browser_process_impl.h" -#include "brave/common/brave_switches.h" #include "brave/components/brave_shields/browser/tracking_protection_service.h" #include "content/public/browser/browser_task_traits.h" #include "content/public/browser/browser_thread.h" @@ -52,12 +51,6 @@ void ModifyRenderFrameKey(int old_render_process_id, namespace brave_shields { -bool TrackingProtectionHelper::IsSmartTrackingProtectionEnabled() { - const base::CommandLine& command_line = - *base::CommandLine::ForCurrentProcess(); - return command_line.HasSwitch(switches::kEnableSmartTrackingProtection); -} - TrackingProtectionHelper::TrackingProtectionHelper(WebContents* web_contents) : WebContentsObserver(web_contents) {} diff --git a/components/brave_shields/browser/tracking_protection_helper.h b/components/brave_shields/browser/tracking_protection_helper.h index 2756a852a63..052d1a0508b 100644 --- a/components/brave_shields/browser/tracking_protection_helper.h +++ b/components/brave_shields/browser/tracking_protection_helper.h @@ -30,7 +30,6 @@ class TrackingProtectionHelper void RenderFrameHostChanged(content::RenderFrameHost* old_host, content::RenderFrameHost* new_host) override; void RenderFrameDeleted(content::RenderFrameHost* render_frame_host) override; - static bool IsSmartTrackingProtectionEnabled(); WEB_CONTENTS_USER_DATA_KEY_DECL(); private: diff --git a/components/brave_shields/browser/tracking_protection_service.cc b/components/brave_shields/browser/tracking_protection_service.cc index 764e4f8e63c..d6cb1ea5124 100644 --- a/components/brave_shields/browser/tracking_protection_service.cc +++ b/components/brave_shields/browser/tracking_protection_service.cc @@ -8,10 +8,11 @@ #include #include "base/bind.h" +#include "base/command_line.h" #include "base/task/post_task.h" #include "base/task_runner_util.h" +#include "brave/common/brave_switches.h" #include "brave/components/brave_component_updater/browser/local_data_files_service.h" -#include "brave/components/content_settings/core/browser/brave_cookie_settings.h" #include "content/public/browser/browser_task_traits.h" #include "content/public/browser/browser_thread.h" @@ -24,7 +25,6 @@ #endif using content::BrowserThread; -using content_settings::BraveCookieSettings; namespace brave_shields { @@ -43,6 +43,16 @@ TrackingProtectionService::TrackingProtectionService( TrackingProtectionService::~TrackingProtectionService() { } +bool TrackingProtectionService::IsSmartTrackingProtectionEnabled() { +#if BUILDFLAG(BRAVE_STP_ENABLED) + const base::CommandLine& command_line = + *base::CommandLine::ForCurrentProcess(); + return command_line.HasSwitch(switches::kEnableSmartTrackingProtection); +#else + return false; +#endif +} + #if BUILDFLAG(BRAVE_STP_ENABLED) TrackingProtectionService::RenderFrameIdKey::RenderFrameIdKey() : render_process_id(content::ChildProcessHost::kInvalidUniqueID), @@ -115,7 +125,7 @@ bool TrackingProtectionService::ShouldStoreState(HostContentSettingsMap* map, const GURL& top_origin_url, const GURL& origin_url) const { DCHECK_CURRENTLY_ON(BrowserThread::IO); - if (!TrackingProtectionHelper::IsSmartTrackingProtectionEnabled()) { + if (!IsSmartTrackingProtectionEnabled()) { return true; } @@ -134,27 +144,13 @@ bool TrackingProtectionService::ShouldStoreState(HostContentSettingsMap* map, return true; } - const bool allow_brave_shields = - starting_site.is_empty() - ? false - : IsAllowContentSetting(map, starting_site, GURL(), - CONTENT_SETTINGS_TYPE_PLUGINS, - brave_shields::kBraveShields); - - if (!allow_brave_shields) { + if (!brave_shields::GetBraveShieldsEnabled(map, starting_site)) return true; - } - const bool allow_trackers = - starting_site.is_empty() - ? true - : IsAllowContentSetting(map, starting_site, GURL(), - CONTENT_SETTINGS_TYPE_PLUGINS, - brave_shields::kTrackers); - if (allow_trackers) { + if (brave_shields::GetCookieControlType(map, starting_site) != + ControlType::BLOCK) return true; - } // deny storage if host is found in the tracker list return first_party_storage_trackers_.find(host) == @@ -190,25 +186,15 @@ void TrackingProtectionService::UpdateFirstPartyStorageTrackers( base::flat_set(std::move(storage_trackers)); } -#endif - -bool TrackingProtectionService::ShouldStoreState(BraveCookieSettings* settings, - HostContentSettingsMap* map, +#else // !BUILDFLAG(BRAVE_STP_ENABLED) +bool TrackingProtectionService::ShouldStoreState(HostContentSettingsMap* map, int render_process_id, int render_frame_id, - const GURL& url, - const GURL& first_party_url, - const GURL& tab_url) const { -#if BUILDFLAG(BRAVE_STP_ENABLED) - const bool allow = ShouldStoreState(map, render_process_id, render_frame_id, - url, first_party_url); - if (!allow) { - return allow; - } -#endif - - return settings->IsCookieAccessAllowed(url, first_party_url, tab_url); + const GURL& top_origin_url, + const GURL& origin_url) const { + return true; } +#endif // BUILDFLAG(BRAVE_STP_ENABLED) bool TrackingProtectionService::ShouldStartRequest( const GURL& url, @@ -230,7 +216,7 @@ void TrackingProtectionService::OnComponentReady( const base::FilePath& install_dir, const std::string& manifest) { #if BUILDFLAG(BRAVE_STP_ENABLED) - if (!TrackingProtectionHelper::IsSmartTrackingProtectionEnabled()) { + if (!IsSmartTrackingProtectionEnabled()) { return; } base::FilePath storage_tracking_protection_path = install_dir diff --git a/components/brave_shields/browser/tracking_protection_service.h b/components/brave_shields/browser/tracking_protection_service.h index 466d0df155e..081488aa395 100644 --- a/components/brave_shields/browser/tracking_protection_service.h +++ b/components/brave_shields/browser/tracking_protection_service.h @@ -26,10 +26,6 @@ class HostContentSettingsMap; class TrackingProtectionServiceTest; -namespace content_settings { -class BraveCookieSettings; -} - using brave_component_updater::LocalDataFilesObserver; using brave_component_updater::LocalDataFilesService; @@ -42,26 +38,19 @@ class TrackingProtectionService : public LocalDataFilesObserver { LocalDataFilesService* local_data_files_service); ~TrackingProtectionService() override; + static bool IsSmartTrackingProtectionEnabled(); + bool ShouldStartRequest(const GURL& spec, content::ResourceType resource_type, const std::string& tab_host, bool* matching_exception_filter, bool* cancel_request_explicitly); - bool ShouldStoreState(content_settings::BraveCookieSettings* settings, - HostContentSettingsMap* map, - int render_process_id, - int render_frame_id, - const GURL& url, - const GURL& first_party_url, - const GURL& tab_url) const; - // implementation of LocalDataFilesObserver void OnComponentReady(const std::string& component_id, const base::FilePath& install_dir, const std::string& manifest) override; -#if BUILDFLAG(BRAVE_STP_ENABLED) // ShouldStoreState returns false if the Storage API is being invoked // by a site in the tracker list, and tracking protection is enabled for the // site that initiated the redirect tracking @@ -71,6 +60,7 @@ class TrackingProtectionService : public LocalDataFilesObserver { const GURL& top_origin_url, const GURL& origin_url) const; +#if BUILDFLAG(BRAVE_STP_ENABLED) void SetStartingSiteForRenderFrame(GURL starting_site, int render_process_id, int render_frame_id); diff --git a/components/content_settings/core/browser/BUILD.gn b/components/content_settings/core/browser/BUILD.gn index b85c1681cec..5e9742b75f3 100644 --- a/components/content_settings/core/browser/BUILD.gn +++ b/components/content_settings/core/browser/BUILD.gn @@ -5,16 +5,13 @@ source_set("browser") { "brave_content_settings_ephemeral_provider.h", "brave_content_settings_pref_provider.cc", "brave_content_settings_pref_provider.h", - "brave_cookie_settings.cc", - "brave_cookie_settings.h", - "content_settings_util.cc", - "content_settings_util.h", ] deps = [ "//base", "//brave/common:pref_names", "//brave/common:shield_exceptions", + "//brave/components/content_settings/core/common", "//components/content_settings/core/common", "//components/prefs", "//extensions/buildflags", diff --git a/components/content_settings/core/browser/brave_content_settings_pref_provider.cc b/components/content_settings/core/browser/brave_content_settings_pref_provider.cc index 6ad0c0e078e..fb199e50c38 100644 --- a/components/content_settings/core/browser/brave_content_settings_pref_provider.cc +++ b/components/content_settings/core/browser/brave_content_settings_pref_provider.cc @@ -9,15 +9,101 @@ #include #include "base/bind.h" +#include "base/task/post_task.h" +#include "brave/components/brave_shields/common/brave_shield_constants.h" #include "components/content_settings/core/browser/content_settings_pref.h" #include "components/content_settings/core/browser/website_settings_registry.h" +#include "components/content_settings/core/common/content_settings_utils.h" +#include "content/public/browser/browser_task_traits.h" +#include "content/public/browser/browser_thread.h" namespace content_settings { +namespace { + +Rule CloneRule(const Rule& rule, bool reverse_patterns = false) { + auto secondary_pattern = rule.secondary_pattern; + if (secondary_pattern == + ContentSettingsPattern::FromString("https://firstParty/*")) { + secondary_pattern = rule.primary_pattern; + } + + // brave plugin rules incorrectly use the embedded url as the primary + if (reverse_patterns) + return Rule(secondary_pattern, + rule.primary_pattern, + rule.value.Clone()); + + return Rule(rule.primary_pattern, + secondary_pattern, + rule.value.Clone()); +} + +class BraveShieldsRuleIterator : public RuleIterator { + public: + BraveShieldsRuleIterator(std::vector::const_iterator iterator, + std::vector::const_iterator end) + : iterator_(iterator), + end_(end) {} + + bool HasNext() const override { + return iterator_ != end_; + } + + Rule Next() override { + return CloneRule(*(iterator_++)); + } + + private: + std::vector::const_iterator iterator_; + std::vector::const_iterator end_; + + DISALLOW_COPY_AND_ASSIGN(BraveShieldsRuleIterator); +}; + + +bool IsActive(const Rule& cookie_rule, + const std::vector& shield_rules, + bool* shields_down_for_site) { + // don't include default rules in the iterator + if (cookie_rule.primary_pattern == ContentSettingsPattern::Wildcard() && + (cookie_rule.secondary_pattern == ContentSettingsPattern::Wildcard() || + cookie_rule.secondary_pattern == + ContentSettingsPattern::FromString("https://firstParty/*"))) { + return false; + } + + bool default_value = true; + for (const auto& shield_rule : shield_rules) { + if (shield_rule.primary_pattern.MatchesAllHosts()) { + // TODO(bridiver) - move this logic into shields_util for allow/block + default_value = + ValueToContentSetting(&shield_rule.value) != CONTENT_SETTING_BLOCK; + } else { + auto primary_compare = + shield_rule.primary_pattern.Compare(cookie_rule.primary_pattern); + // TODO(bridiver) - verify that SUCCESSOR is correct and not PREDECESSOR + if (primary_compare == ContentSettingsPattern::IDENTITY || + primary_compare == ContentSettingsPattern::SUCCESSOR) { + // TODO(bridiver) - move this logic into shields_util for allow/block + *shields_down_for_site = + ValueToContentSetting(&shield_rule.value) == CONTENT_SETTING_BLOCK; + return + ValueToContentSetting(&shield_rule.value) != CONTENT_SETTING_BLOCK; + } + } + } + + return default_value; +} + +} // namespace + BravePrefProvider::BravePrefProvider(PrefService* prefs, bool incognito, bool store_last_modified) - : PrefProvider(prefs, incognito, store_last_modified) { + : PrefProvider(prefs, incognito, store_last_modified), + weak_factory_(this) { brave_pref_change_registrar_.Init(prefs_); WebsiteSettingsRegistry* website_settings = @@ -32,12 +118,18 @@ BravePrefProvider::BravePrefProvider(PrefService* prefs, info->pref_name(), is_incognito_, base::Bind(&PrefProvider::Notify, base::Unretained(this))))); - return; + break; } } + + AddObserver(this); + OnCookieSettingsChanged(CONTENT_SETTINGS_TYPE_PLUGINS); } +BravePrefProvider::~BravePrefProvider() {} + void BravePrefProvider::ShutdownOnUIThread() { + RemoveObserver(this); brave_pref_change_registrar_.RemoveAll(); PrefProvider::ShutdownOnUIThread(); } @@ -57,9 +149,187 @@ bool BravePrefProvider::SetWebsiteSetting( secondary_pattern == ContentSettingsPattern::Wildcard()); } + // handle changes to brave cookie settings from chromium cookie settings UI + if (content_type == CONTENT_SETTINGS_TYPE_COOKIES) { + auto* value = in_value.get(); + auto match = std::find_if( + brave_cookie_rules_[is_incognito_].begin(), + brave_cookie_rules_[is_incognito_].end(), + [primary_pattern, secondary_pattern, value](const auto& rule) { + return rule.primary_pattern == primary_pattern && + rule.secondary_pattern == secondary_pattern && + ValueToContentSetting(&rule.value) != + ValueToContentSetting(value); }); + if (match != brave_cookie_rules_[is_incognito_].end()) { + // swap primary/secondary pattern - see CloneRule + auto plugin_primary_pattern = secondary_pattern; + auto plugin_secondary_pattern = primary_pattern; + + // convert to legacy firstParty format for brave plugin settings + if (plugin_primary_pattern == plugin_secondary_pattern) { + plugin_secondary_pattern = + ContentSettingsPattern::FromString("https://firstParty/*"); + } + + // change to type PLUGINS + return PrefProvider::SetWebsiteSetting(plugin_primary_pattern, + plugin_secondary_pattern, + CONTENT_SETTINGS_TYPE_PLUGINS, + brave_shields::kCookies, + std::move(in_value)); + } + } + return PrefProvider::SetWebsiteSetting(primary_pattern, secondary_pattern, content_type, resource_identifier, std::move(in_value)); } +std::unique_ptr BravePrefProvider::GetRuleIterator( + ContentSettingsType content_type, + const ResourceIdentifier& resource_identifier, + bool incognito) const { + if (content_type == CONTENT_SETTINGS_TYPE_COOKIES) { + return std::make_unique( + cookie_rules_.at(incognito).begin(), + cookie_rules_.at(incognito).end()); + } + + return PrefProvider::GetRuleIterator(content_type, + resource_identifier, + incognito); +} + +void BravePrefProvider::UpdateCookieRules(ContentSettingsType content_type, + bool incognito) { + auto& rules = cookie_rules_[incognito]; + rules.clear(); + + // add chromium cookies + auto chromium_cookies_iterator = PrefProvider::GetRuleIterator( + CONTENT_SETTINGS_TYPE_COOKIES, + "", + incognito); + while (chromium_cookies_iterator && chromium_cookies_iterator->HasNext()) { + rules.push_back(CloneRule(chromium_cookies_iterator->Next())); + } + chromium_cookies_iterator.reset(); + + auto brave_shields_iterator = PrefProvider::GetRuleIterator( + CONTENT_SETTINGS_TYPE_PLUGINS, + brave_shields::kBraveShields, + incognito); + + // collect shield rules + std::vector shield_rules; + while (brave_shields_iterator && brave_shields_iterator->HasNext()) { + shield_rules.push_back(CloneRule(brave_shields_iterator->Next())); + } + brave_shields_iterator.reset(); + + // add brave cookies after checking shield status + auto brave_cookies_iterator = PrefProvider::GetRuleIterator( + CONTENT_SETTINGS_TYPE_PLUGINS, + brave_shields::kCookies, + incognito); + + auto old_rules = std::move(brave_cookie_rules_[incognito]); + + while (brave_cookies_iterator && brave_cookies_iterator->HasNext()) { + auto rule = brave_cookies_iterator->Next(); + bool shields_down_for_site = false; + if (IsActive(rule, shield_rules, &shields_down_for_site)) { + rules.push_back(CloneRule(rule, true)); + brave_cookie_rules_[incognito].push_back(CloneRule(rule, true)); + } else if (shields_down_for_site) { + rules.push_back( + Rule(ContentSettingsPattern::Wildcard(), + rule.primary_pattern, + ContentSettingToValue(CONTENT_SETTING_ALLOW)->Clone())); + brave_cookie_rules_[incognito].push_back( + Rule(ContentSettingsPattern::Wildcard(), + rule.primary_pattern, + ContentSettingToValue(CONTENT_SETTING_ALLOW)->Clone())); + } + } + + // get the list of changes + std::vector brave_cookie_updates; + for (const auto& new_rule : brave_cookie_rules_[incognito]) { + auto match = std::find_if( + old_rules.begin(), + old_rules.end(), + [&new_rule](const auto& old_rule) { + // we want an exact match here because any change to the rule + // is an update + return new_rule.primary_pattern == old_rule.primary_pattern && + new_rule.secondary_pattern == old_rule.secondary_pattern && + ValueToContentSetting(&new_rule.value) == + ValueToContentSetting(&old_rule.value); + }); + if (match == old_rules.end()) { + brave_cookie_updates.push_back(CloneRule(new_rule)); + } + } + + // find any removed rules + for (const auto& old_rule : old_rules) { + auto match = std::find_if( + brave_cookie_rules_[incognito].begin(), + brave_cookie_rules_[incognito].end(), + [&old_rule](const auto& new_rule) { + // we only care about the patterns here because we're looking + // for deleted rules, not changed rules + return new_rule.primary_pattern == old_rule.primary_pattern && + new_rule.secondary_pattern == old_rule.secondary_pattern; + }); + if (match == brave_cookie_rules_[incognito].end()) { + brave_cookie_updates.push_back( + Rule(old_rule.primary_pattern, + old_rule.secondary_pattern, + base::Value())); + } + } + + // Notify brave cookie changes as CONTENT_SETTINGS_TYPE_COOKIES + if (content_type == CONTENT_SETTINGS_TYPE_PLUGINS) { + // PostTask here to avoid content settings autolock DCHECK + base::PostTaskWithTraits( + FROM_HERE, + {content::BrowserThread::UI, base::TaskPriority::USER_VISIBLE}, + base::BindOnce(&BravePrefProvider::NotifyChanges, + weak_factory_.GetWeakPtr(), + std::move(brave_cookie_updates), + incognito)); + } +} + +void BravePrefProvider::NotifyChanges(const std::vector& rules, + bool incognito) { + for (const auto& rule : rules) { + Notify(rule.primary_pattern, + rule.secondary_pattern, + CONTENT_SETTINGS_TYPE_COOKIES, + ""); + } +} +void BravePrefProvider::OnCookieSettingsChanged( + ContentSettingsType content_type) { + UpdateCookieRules(content_type, true); + UpdateCookieRules(content_type, false); +} + +void BravePrefProvider::OnContentSettingChanged( + const ContentSettingsPattern& primary_pattern, + const ContentSettingsPattern& secondary_pattern, + ContentSettingsType content_type, + const std::string& resource_identifier) { + if (content_type == CONTENT_SETTINGS_TYPE_COOKIES || + (content_type == CONTENT_SETTINGS_TYPE_PLUGINS && + (resource_identifier == brave_shields::kCookies || + resource_identifier == brave_shields::kBraveShields))) { + OnCookieSettingsChanged(content_type); + } +} + } // namespace content_settings diff --git a/components/content_settings/core/browser/brave_content_settings_pref_provider.h b/components/content_settings/core/browser/brave_content_settings_pref_provider.h index 4dc8578289f..7f7ff25ec6a 100644 --- a/components/content_settings/core/browser/brave_content_settings_pref_provider.h +++ b/components/content_settings/core/browser/brave_content_settings_pref_provider.h @@ -6,8 +6,13 @@ #ifndef BRAVE_COMPONENTS_CONTENT_SETTINGS_CORE_BROWSER_BRAVE_CONTENT_SETTINGS_PREF_PROVIDER_H_ #define BRAVE_COMPONENTS_CONTENT_SETTINGS_CORE_BROWSER_BRAVE_CONTENT_SETTINGS_PREF_PROVIDER_H_ +#include #include +#include +#include +#include "base/memory/weak_ptr.h" +#include "components/content_settings/core/browser/content_settings_observer.h" #include "components/content_settings/core/browser/content_settings_pref_provider.h" #include "components/prefs/pref_change_registrar.h" @@ -20,13 +25,14 @@ namespace content_settings { // Because of this reasion, shields configuration was also ephemeral. // However, we want shilelds configuration persisted. To do this, we make // EphemeralProvider ignore shields type and this class handles. -class BravePrefProvider : public PrefProvider { +class BravePrefProvider : public PrefProvider, + public Observer { public: - BravePrefProvider( - PrefService* prefs, bool incognito, bool store_last_modified); - ~BravePrefProvider() override {} + BravePrefProvider(PrefService* prefs, + bool incognito, + bool store_last_modified); + ~BravePrefProvider() override; - private: // content_settings::PrefProvider overrides: void ShutdownOnUIThread() override; bool SetWebsiteSetting( @@ -35,10 +41,30 @@ class BravePrefProvider : public PrefProvider { ContentSettingsType content_type, const ResourceIdentifier& resource_identifier, std::unique_ptr&& value) override; + std::unique_ptr GetRuleIterator( + ContentSettingsType content_type, + const ResourceIdentifier& resource_identifier, + bool incognito) const override; + + private: + void UpdateCookieRules(ContentSettingsType content_type, bool incognito); + void OnCookieSettingsChanged(ContentSettingsType content_type); + void NotifyChanges(const std::vector& rules, bool incognito); + + // content_settings::Observer overrides: + void OnContentSettingChanged(const ContentSettingsPattern& primary_pattern, + const ContentSettingsPattern& secondary_pattern, + ContentSettingsType content_type, + const std::string& resource_identifier) override; // PrefProvider::pref_change_registrar_ alreay has plugin type. PrefChangeRegistrar brave_pref_change_registrar_; + std::map> cookie_rules_; + std::map> brave_cookie_rules_; + + base::WeakPtrFactory weak_factory_; + DISALLOW_COPY_AND_ASSIGN(BravePrefProvider); }; diff --git a/components/content_settings/core/browser/brave_cookie_settings.cc b/components/content_settings/core/browser/brave_cookie_settings.cc deleted file mode 100644 index 6b6631b172e..00000000000 --- a/components/content_settings/core/browser/brave_cookie_settings.cc +++ /dev/null @@ -1,168 +0,0 @@ -/* Copyright (c) 2019 The Brave Authors. All rights reserved. - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#include "brave/components/content_settings/core/browser/brave_cookie_settings.h" - -#include "base/bind.h" -#include "brave/common/pref_names.h" -#include "brave/common/shield_exceptions.h" -#include "brave/components/brave_shields/common/brave_shield_constants.h" -#include "brave/components/content_settings/core/browser/content_settings_util.h" -#include "components/prefs/pref_service.h" -#include "extensions/buildflags/buildflags.h" -#include "net/base/registry_controlled_domains/registry_controlled_domain.h" -#include "url/gurl.h" - -using namespace net::registry_controlled_domains; // NOLINT - -namespace content_settings { - -namespace { - -bool ShouldBlockCookie(bool allow_brave_shields, - bool allow_1p_cookies, - bool allow_3p_cookies, - const GURL& main_frame_url, - const GURL& url, - bool allow_google_auth) { - // shields settings only apply to http/https - if (!url.SchemeIsHTTPOrHTTPS()) { - return false; - } - - if (!allow_brave_shields) { - return false; - } - - // If 1p cookies are not allowed, then we just want to block everything. - if (!allow_1p_cookies) { - return true; - } - - // If 3p is allowed, we have nothing extra to block - if (allow_3p_cookies) { - return false; - } - - // If it is whitelisted, we shouldn't block - if (brave::IsWhitelistedCookieException(main_frame_url, - url, - allow_google_auth)) - return false; - - // Same TLD+1 whouldn't set the referrer - return !SameDomainOrHost(url, main_frame_url, INCLUDE_PRIVATE_REGISTRIES); -} - -} // namespace - -BraveCookieSettings::BraveCookieSettings( - HostContentSettingsMap* host_content_settings_map, - PrefService* prefs, - const char* extension_scheme) - : CookieSettings(host_content_settings_map, prefs, extension_scheme), - allow_google_auth_(prefs->GetBoolean(kGoogleLoginControlType)) { - pref_change_registrar_.Init(prefs); - pref_change_registrar_.Add( - kGoogleLoginControlType, - base::BindRepeating(&BraveCookieSettings::OnAllowGoogleAuthChanged, - base::Unretained(this))); -} - -BraveCookieSettings::~BraveCookieSettings() {} - -void BraveCookieSettings::GetCookieSetting( - const GURL& url, - const GURL& first_party_url, - content_settings::SettingSource* source, - ContentSetting* cookie_setting) const { - GetCookieSetting(url, first_party_url, first_party_url, source, - cookie_setting); -} - -void BraveCookieSettings::GetCookieSetting( - const GURL& url, - const GURL& first_party_url, - const GURL& tab_url, - content_settings::SettingSource* source, - ContentSetting* cookie_setting) const { - DCHECK(cookie_setting); - - // copied from CookieSettings::GetCookieSetting - if (first_party_url.SchemeIs(kChromeUIScheme) && - url.SchemeIsCryptographic()) { - *cookie_setting = CONTENT_SETTING_ALLOW; - return; - } - -#if BUILDFLAG(ENABLE_EXTENSIONS) - if (url.SchemeIs(extension_scheme_) && - first_party_url.SchemeIs(extension_scheme_)) { - *cookie_setting = CONTENT_SETTING_ALLOW; - return; - } -#endif - - - GURL main_frame_url = - (tab_url == GURL("about:blank") || tab_url.is_empty() ? first_party_url - : tab_url); - - if (main_frame_url.is_empty()) - main_frame_url = url; - - bool allow_brave_shields = - IsAllowContentSetting(host_content_settings_map_.get(), - main_frame_url, - main_frame_url, - CONTENT_SETTINGS_TYPE_PLUGINS, - brave_shields::kBraveShields); - - bool allow_1p_cookies = - IsAllowContentSetting(host_content_settings_map_.get(), - main_frame_url, - GURL("https://firstParty/"), - CONTENT_SETTINGS_TYPE_PLUGINS, - brave_shields::kCookies); - - bool allow_3p_cookies = - IsAllowContentSetting(host_content_settings_map_.get(), - main_frame_url, - GURL(), - CONTENT_SETTINGS_TYPE_PLUGINS, - brave_shields::kCookies); - - if (ShouldBlockCookie(allow_brave_shields, allow_1p_cookies, allow_3p_cookies, - main_frame_url, url, allow_google_auth_)) { - *cookie_setting = CONTENT_SETTING_BLOCK; - } else { - return CookieSettings::GetCookieSetting(url, - first_party_url, - source, - cookie_setting); - } -} - -bool BraveCookieSettings::IsCookieAccessAllowed(const GURL& url, - const GURL& first_party_url, - const GURL& tab_url) const { - ContentSetting setting; - GetCookieSetting(url, first_party_url, tab_url, nullptr, &setting); - DCHECK(setting == CONTENT_SETTING_ALLOW || - setting == CONTENT_SETTING_SESSION_ONLY || - setting == CONTENT_SETTING_DEFAULT || - setting == CONTENT_SETTING_BLOCK); - return setting == CONTENT_SETTING_ALLOW || - setting == CONTENT_SETTING_SESSION_ONLY; -} - -void BraveCookieSettings::OnAllowGoogleAuthChanged() { - DCHECK(thread_checker_.CalledOnValidThread()); - base::AutoLock auto_lock(lock_); - allow_google_auth_ = - pref_change_registrar_.prefs()->GetBoolean(kGoogleLoginControlType); -} - -} // namespace content_settings diff --git a/components/content_settings/core/browser/brave_cookie_settings.h b/components/content_settings/core/browser/brave_cookie_settings.h deleted file mode 100644 index a29116a8788..00000000000 --- a/components/content_settings/core/browser/brave_cookie_settings.h +++ /dev/null @@ -1,60 +0,0 @@ -/* Copyright (c) 2019 The Brave Authors. All rights reserved. - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef BRAVE_COMPONENTS_CONTENT_SETTINGS_CORE_BROWSER_BRAVE_COOKIE_SETTINGS_H_ -#define BRAVE_COMPONENTS_CONTENT_SETTINGS_CORE_BROWSER_BRAVE_COOKIE_SETTINGS_H_ - -#include "components/content_settings/core/browser/cookie_settings.h" - -class HostContentSettingsMap; - -namespace content_settings { - -class BraveCookieSettings : public CookieSettings { - public: - using CookieSettingsBase::IsCookieAccessAllowed; - - BraveCookieSettings(HostContentSettingsMap* host_content_settings_map, - PrefService* prefs, - const char* extension_scheme = kDummyExtensionScheme); - void GetCookieSetting(const GURL& url, - const GURL& first_party_url, - content_settings::SettingSource* source, - ContentSetting* cookie_setting) const override; - // For an iframe that tries to set a cookie, the first_party_url comes in as - // from the content_browser_client, so we need to pass in the tab_url as well - // so we can get proper shield override settings. - void GetCookieSetting(const GURL& url, - const GURL& first_party_url, - const GURL& tab_url, - content_settings::SettingSource* source, - ContentSetting* cookie_setting) const; - - // Should be used by default to gate access to cookies and other storage APIs - bool IsCookieAccessAllowed(const GURL& url, - const GURL& first_party_url, - const GURL& tab_url) const; - - bool ShouldStoreState(HostContentSettingsMap* map, - int render_process_id, - int render_frame_id, - const GURL& url, - const GURL& first_party_url, - const GURL& tab_url) const; - - bool GetAllowGoogleAuth() const { return allow_google_auth_; } - - protected: - ~BraveCookieSettings() override; - void OnAllowGoogleAuthChanged(); - - bool allow_google_auth_; - - DISALLOW_COPY_AND_ASSIGN(BraveCookieSettings); -}; - -} // namespace content_settings - -#endif // BRAVE_COMPONENTS_CONTENT_SETTINGS_CORE_BROWSER_BRAVE_COOKIE_SETTINGS_H_ diff --git a/components/content_settings/core/browser/content_settings_util.cc b/components/content_settings/core/browser/content_settings_util.cc deleted file mode 100644 index 0394e64ca22..00000000000 --- a/components/content_settings/core/browser/content_settings_util.cc +++ /dev/null @@ -1,55 +0,0 @@ -/* Copyright (c) 2019 The Brave Authors. All rights reserved. - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#include "brave/components/content_settings/core/browser/content_settings_util.h" - -#include "brave/components/brave_shields/common/brave_shield_constants.h" -#include "components/content_settings/core/browser/host_content_settings_map.h" -#include "components/content_settings/core/common/content_settings_types.h" -// #include "components/content_settings/core/common/content_settings_utils.h" - -namespace content_settings { - -bool GetDefaultFromResourceIdentifier(const std::string& resource_identifier, - const GURL& primary_url, - const GURL& secondary_url) { - if (resource_identifier == brave_shields::kAds) { - return false; - } else if (resource_identifier == brave_shields::kTrackers) { - return false; - } else if (resource_identifier == brave_shields::kHTTPUpgradableResources) { - return false; - } else if (resource_identifier == brave_shields::kBraveShields) { - return true; - } else if (resource_identifier == brave_shields::kReferrers) { - return false; - } else if (resource_identifier == brave_shields::kCookies) { - return secondary_url == GURL("https://firstParty/"); - } - return false; -} - -bool IsAllowContentSetting(HostContentSettingsMap* content_settings, - const GURL& primary_url, - const GURL& secondary_url, - ContentSettingsType setting_type, - const std::string& resource_identifier) { - ContentSetting setting = content_settings->GetContentSetting( - primary_url, - secondary_url, - setting_type, - resource_identifier); - - // TODO(bbondy): Add a static RegisterUserPrefs method for shields and use - // prefs instead of simply returning true / false below. - if (setting == CONTENT_SETTING_DEFAULT) { - return GetDefaultFromResourceIdentifier(resource_identifier, - primary_url, - secondary_url); - } - return setting == CONTENT_SETTING_ALLOW; -} - -} // namespace content_settings diff --git a/components/content_settings/core/browser/content_settings_util.h b/components/content_settings/core/browser/content_settings_util.h deleted file mode 100644 index 35106ccc376..00000000000 --- a/components/content_settings/core/browser/content_settings_util.h +++ /dev/null @@ -1,30 +0,0 @@ -/* Copyright (c) 2019 The Brave Authors. All rights reserved. - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef BRAVE_COMPONENTS_CONTENT_SETTINGS_CORE_BROWSER_CONTENT_SETTINGS_UTIL_H_ -#define BRAVE_COMPONENTS_CONTENT_SETTINGS_CORE_BROWSER_CONTENT_SETTINGS_UTIL_H_ - -#include - -#include "components/content_settings/core/common/content_settings_types.h" -#include "url/gurl.h" - -class HostContentSettingsMap; - -namespace content_settings { - -bool GetDefaultFromResourceIdentifier(const std::string& resource_identifier, - const GURL& primary_url, - const GURL& secondary_url); - -bool IsAllowContentSetting(HostContentSettingsMap* content_settings, - const GURL& primary_url, - const GURL& secondary_url, - ContentSettingsType setting_type, - const std::string& resource_identifier); - -} // namespace content_settings - -#endif // BRAVE_COMPONENTS_CONTENT_SETTINGS_CORE_BROWSER_CONTENT_SETTINGS_UTIL_H_ diff --git a/components/content_settings/core/common/BUILD.gn b/components/content_settings/core/common/BUILD.gn new file mode 100644 index 00000000000..b3c8a31ea7e --- /dev/null +++ b/components/content_settings/core/common/BUILD.gn @@ -0,0 +1,12 @@ +source_set("common") { + sources = [ + "content_settings_util.cc", + "content_settings_util.h", + ] + + deps = [ + "//brave/extensions:common", + "//components/content_settings/core/common", + "//url", + ] +} diff --git a/components/content_settings/core/common/content_settings_util.cc b/components/content_settings/core/common/content_settings_util.cc new file mode 100644 index 00000000000..cfca8ab664e --- /dev/null +++ b/components/content_settings/core/common/content_settings_util.cc @@ -0,0 +1,101 @@ +/* Copyright (c) 2019 The Brave Authors. All rights reserved. + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this file, + * You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#include "brave/components/content_settings/core/common/content_settings_util.h" + +#include +#include + +#include "brave/components/brave_shields/common/brave_shield_constants.h" +#include "components/content_settings/core/common/content_settings_types.h" +#include "extensions/common/url_pattern.h" + +namespace content_settings { + +ContentSetting GetDefaultFromResourceIdentifier( + const std::string& resource_identifier, + const GURL& primary_url, + const GURL& secondary_url) { + if (resource_identifier == brave_shields::kAds) { + return CONTENT_SETTING_BLOCK; + } else if (resource_identifier == brave_shields::kTrackers) { + return CONTENT_SETTING_BLOCK; + } else if (resource_identifier == brave_shields::kHTTPUpgradableResources) { + return CONTENT_SETTING_BLOCK; + } else if (resource_identifier == brave_shields::kBraveShields) { + return CONTENT_SETTING_ALLOW; + } else if (resource_identifier == brave_shields::kReferrers) { + return CONTENT_SETTING_BLOCK; + } else if (resource_identifier == brave_shields::kCookies) { + return secondary_url == GURL("https://firstParty/") + ? CONTENT_SETTING_BLOCK + : CONTENT_SETTING_ALLOW; + } + return CONTENT_SETTING_BLOCK; +} + +bool IsWhitelistedCookieException(const GURL& primary_url, + const GURL& secondary_url, + bool allow_google_auth) { + // Note that there's already an exception for TLD+1, so don't add those here. + // Check with the security team before adding exceptions. + + // 1st-party-INdependent whitelist + std::vector fpi_whitelist_patterns = {}; + if (allow_google_auth) { + fpi_whitelist_patterns.push_back(URLPattern(URLPattern::SCHEME_ALL, + "https://accounts.google.com/o/oauth2/*")); + } + bool any_match = std::any_of(fpi_whitelist_patterns.begin(), + fpi_whitelist_patterns.end(), + [&secondary_url](const URLPattern& pattern) { + return pattern.MatchesURL(secondary_url); + }); + if (any_match) { + return true; + } + + // 1st-party-dependent whitelist + static std::map > whitelist_patterns = { + { + GURL("https://www.sliver.tv/"), + std::vector({URLPattern(URLPattern::SCHEME_ALL, + "https://*.thetatoken.org:8700/*")}) + } + }; + + std::map >::iterator i = + whitelist_patterns.find(primary_url); + if (i == whitelist_patterns.end()) { + return false; + } + std::vector &exceptions = i->second; + return std::any_of(exceptions.begin(), exceptions.end(), + [&secondary_url](const URLPattern& pattern) { + return pattern.MatchesURL(secondary_url); + }); +} + +bool IsAllowContentSetting(const ContentSettingsForOneType& content_settings, + const GURL& primary_url, + const GURL& secondary_url, + const std::string& resource_identifier) { + ContentSetting setting = + GetDefaultFromResourceIdentifier(resource_identifier, + primary_url, + secondary_url); + + for (const auto& entry : content_settings) { + if (entry.primary_pattern.Matches(primary_url) && + entry.secondary_pattern.Matches(secondary_url)) { + setting = entry.GetContentSetting(); + break; + } + } + + return setting == CONTENT_SETTING_ALLOW; +} + +} // namespace content_settings diff --git a/components/content_settings/core/common/content_settings_util.h b/components/content_settings/core/common/content_settings_util.h new file mode 100644 index 00000000000..8c9d994c979 --- /dev/null +++ b/components/content_settings/core/common/content_settings_util.h @@ -0,0 +1,33 @@ +/* Copyright (c) 2019 The Brave Authors. All rights reserved. + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this file, + * You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#ifndef BRAVE_COMPONENTS_CONTENT_SETTINGS_CORE_COMMON_CONTENT_SETTINGS_UTIL_H_ +#define BRAVE_COMPONENTS_CONTENT_SETTINGS_CORE_COMMON_CONTENT_SETTINGS_UTIL_H_ + +#include + +#include "components/content_settings/core/common/content_settings.h" +#include "components/content_settings/core/common/content_settings_types.h" +#include "url/gurl.h" + +namespace content_settings { + +ContentSetting GetDefaultFromResourceIdentifier( + const std::string& resource_identifier, + const GURL& primary_url, + const GURL& secondary_url); + +bool IsWhitelistedCookieException(const GURL& primary_url, + const GURL& secondary_url, + bool allow_google_auth); + +bool IsAllowContentSetting(const ContentSettingsForOneType& content_settings, + const GURL& primary_url, + const GURL& secondary_url, + const std::string& resource_identifier); + +} // namespace content_settings + +#endif // BRAVE_COMPONENTS_CONTENT_SETTINGS_CORE_COMMON_CONTENT_SETTINGS_UTIL_H_ diff --git a/extensions/BUILD.gn b/extensions/BUILD.gn new file mode 100644 index 00000000000..fd551f18afb --- /dev/null +++ b/extensions/BUILD.gn @@ -0,0 +1,24 @@ +if (is_android) { + source_set("common") { + sources = [ + "//extensions/common/error_utils.cc", + "//extensions/common/error_utils.h", + "//extensions/common/url_pattern.cc", + "//extensions/common/url_pattern.h", + "//extensions/common/url_pattern_set.cc", + "//extensions/common/url_pattern_set.h", + ] + + deps = [ + "//base", + "//components/url_pattern_index", + "//extensions/buildflags", + "//extensions/common:common_constants", + "//url", + ] + } +} else { + group("common") { + deps = [ "//extensions/common" ] + } +} diff --git a/patches/chrome-browser-content_settings-cookie_settings_factory.cc.patch b/patches/chrome-browser-content_settings-cookie_settings_factory.cc.patch deleted file mode 100644 index c7b6e61e173..00000000000 --- a/patches/chrome-browser-content_settings-cookie_settings_factory.cc.patch +++ /dev/null @@ -1,21 +0,0 @@ -diff --git a/chrome/browser/content_settings/cookie_settings_factory.cc b/chrome/browser/content_settings/cookie_settings_factory.cc -index 2bdf232aa502d4e94febb5ee9d62132c699b946b..32de4d66f4787c5684b53b8e814e40dee3712f8a 100644 ---- a/chrome/browser/content_settings/cookie_settings_factory.cc -+++ b/chrome/browser/content_settings/cookie_settings_factory.cc -@@ -6,6 +6,7 @@ - - #include "base/logging.h" - #include "base/metrics/histogram_macros.h" -+#include "brave/components/content_settings/core/browser/brave_cookie_settings.h" - #include "chrome/browser/content_settings/host_content_settings_map_factory.h" - #include "chrome/browser/profiles/incognito_helpers.h" - #include "chrome/browser/profiles/profile.h" -@@ -68,7 +69,7 @@ CookieSettingsFactory::BuildServiceInstanceFor( - UMA_HISTOGRAM_BOOLEAN( - "Privacy.DoNotTrackSetting", - profile->GetPrefs()->GetBoolean(prefs::kEnableDoNotTrack)); -- return new content_settings::CookieSettings( -+ return new content_settings::BraveCookieSettings( - HostContentSettingsMapFactory::GetForProfile(profile), - profile->GetPrefs(), - extensions::kExtensionScheme); diff --git a/patches/components-content_settings-core-browser-BUILD.gn.patch b/patches/components-content_settings-core-browser-BUILD.gn.patch deleted file mode 100644 index 63acfb2d158..00000000000 --- a/patches/components-content_settings-core-browser-BUILD.gn.patch +++ /dev/null @@ -1,12 +0,0 @@ -diff --git a/components/content_settings/core/browser/BUILD.gn b/components/content_settings/core/browser/BUILD.gn -index bfabd7986d3859247ac628ec55c6768803a343c9..08494cbc88006cbf8ca73e47a8d73f482f10a9b0 100644 ---- a/components/content_settings/core/browser/BUILD.gn -+++ b/components/content_settings/core/browser/BUILD.gn -@@ -51,6 +51,7 @@ jumbo_static_library("browser") { - - deps = [ - "//base", -+ "//brave/components/content_settings/core/browser", - "//components/content_settings/core/common", - "//components/keyed_service/core", - "//components/pref_registry:pref_registry", diff --git a/patches/components-content_settings-core-browser-cookie_settings.h.patch b/patches/components-content_settings-core-browser-cookie_settings.h.patch deleted file mode 100644 index c292d0c3841..00000000000 --- a/patches/components-content_settings-core-browser-cookie_settings.h.patch +++ /dev/null @@ -1,12 +0,0 @@ -diff --git a/components/content_settings/core/browser/cookie_settings.h b/components/content_settings/core/browser/cookie_settings.h -index 6d3abef07732cd1c612b6afb8b36dc5145194968..51d62be40dad4ac074ce076d46f61553e0e2b5f2 100644 ---- a/components/content_settings/core/browser/cookie_settings.h -+++ b/components/content_settings/core/browser/cookie_settings.h -@@ -86,6 +86,7 @@ class CookieSettings : public CookieSettingsBase, - static void RegisterProfilePrefs(user_prefs::PrefRegistrySyncable* registry); - - private: -+ friend class BraveCookieSettings; - ~CookieSettings() override; - - void OnBlockThirdPartyCookiesChanged(); diff --git a/patches/services-network-network_context.cc.patch b/patches/services-network-network_context.cc.patch new file mode 100644 index 00000000000..9bd1c2c94a9 --- /dev/null +++ b/patches/services-network-network_context.cc.patch @@ -0,0 +1,20 @@ +diff --git a/services/network/network_context.cc b/services/network/network_context.cc +index 6082e82d5854b9d7cec0c2767d7ea7bcf1580614..e70aadc9ddf6141ca195099e5ce842d7b7f7b539 100644 +--- a/services/network/network_context.cc ++++ b/services/network/network_context.cc +@@ -431,6 +431,7 @@ class NetworkContext::ContextNetworkDelegate + const net::CookieList& cookie_list, + bool allowed_from_caller) override { + return allowed_from_caller && ++ BRAVE_ON_CAN_GET_COOKIES_INTERNAL + network_context_->cookie_manager() + ->cookie_settings() + .IsCookieAccessAllowed(request.url(), +@@ -442,6 +443,7 @@ class NetworkContext::ContextNetworkDelegate + net::CookieOptions* options, + bool allowed_from_caller) override { + return allowed_from_caller && ++ BRAVE_ON_CAN_SET_COOKIES_INTERNAL + network_context_->cookie_manager() + ->cookie_settings() + .IsCookieAccessAllowed(request.url(), diff --git a/renderer/brave_content_settings_observer_browsertest.cc b/renderer/brave_content_settings_observer_browsertest.cc index faa2efce456..f1045ddd790 100644 --- a/renderer/brave_content_settings_observer_browsertest.cc +++ b/renderer/brave_content_settings_observer_browsertest.cc @@ -6,6 +6,7 @@ #include "base/path_service.h" #include "brave/browser/brave_content_browser_client.h" #include "brave/common/brave_paths.h" +#include "brave/components/brave_shields/browser/brave_shields_util.h" #include "brave/components/brave_shields/common/brave_shield_constants.h" #include "chrome/browser/content_settings/host_content_settings_map_factory.h" #include "chrome/browser/ui/browser.h" @@ -21,6 +22,8 @@ #include "net/http/http_request_headers.h" #include "net/test/embedded_test_server/http_request.h" +using brave_shields::ControlType; + const char kIframeID[] = "test"; const char kPointInPathScript[] = @@ -74,6 +77,7 @@ class BraveContentSettingsObserverBrowserTest : public InProcessBrowserTest { url_ = embedded_test_server()->GetURL("a.com", "/iframe.html"); iframe_url_ = embedded_test_server()->GetURL("b.com", "/simple.html"); image_url_ = embedded_test_server()->GetURL("b.com", "/logo.png"); + top_level_page_url_ = GURL("http://a.com/"); top_level_page_pattern_ = ContentSettingsPattern::FromString("http://a.com/*"); iframe_pattern_ = ContentSettingsPattern::FromString("http://b.com/*"); @@ -132,6 +136,10 @@ class BraveContentSettingsObserverBrowserTest : public InProcessBrowserTest { return s; } + const GURL top_level_page_url() { + return top_level_page_url_; + } + const ContentSettingsPattern& top_level_page_pattern() { return top_level_page_pattern_; } @@ -169,121 +177,64 @@ class BraveContentSettingsObserverBrowserTest : public InProcessBrowserTest { } void Block3PCookies() { - content_settings()->SetContentSettingCustomScope( - top_level_page_pattern(), - ContentSettingsPattern::Wildcard(), - CONTENT_SETTINGS_TYPE_PLUGINS, - brave_shields::kCookies, CONTENT_SETTING_BLOCK); - content_settings()->SetContentSettingCustomScope( - top_level_page_pattern(), - first_party_pattern(), - CONTENT_SETTINGS_TYPE_PLUGINS, - brave_shields::kCookies, CONTENT_SETTING_ALLOW); + brave_shields::SetCookieControlType(browser()->profile(), + ControlType::BLOCK_THIRD_PARTY, + top_level_page_url()); } void BlockCookies() { - content_settings()->SetContentSettingCustomScope( - top_level_page_pattern(), - ContentSettingsPattern::Wildcard(), - CONTENT_SETTINGS_TYPE_PLUGINS, - brave_shields::kCookies, CONTENT_SETTING_BLOCK); - content_settings()->SetContentSettingCustomScope( - top_level_page_pattern(), - first_party_pattern(), - CONTENT_SETTINGS_TYPE_PLUGINS, - brave_shields::kCookies, CONTENT_SETTING_BLOCK); + brave_shields::SetCookieControlType(browser()->profile(), + ControlType::BLOCK, + top_level_page_url()); } void AllowCookies() { - content_settings()->SetContentSettingCustomScope( - top_level_page_pattern(), - ContentSettingsPattern::Wildcard(), - CONTENT_SETTINGS_TYPE_PLUGINS, - brave_shields::kCookies, CONTENT_SETTING_ALLOW); - content_settings()->SetContentSettingCustomScope( - top_level_page_pattern(), - first_party_pattern(), - CONTENT_SETTINGS_TYPE_PLUGINS, - brave_shields::kCookies, CONTENT_SETTING_ALLOW); + brave_shields::SetCookieControlType(browser()->profile(), + ControlType::ALLOW, + top_level_page_url()); } void ShieldsDown() { - content_settings()->SetContentSettingCustomScope( - top_level_page_pattern(), - ContentSettingsPattern::Wildcard(), - CONTENT_SETTINGS_TYPE_PLUGINS, - brave_shields::kBraveShields, CONTENT_SETTING_BLOCK); + brave_shields::SetBraveShieldsEnabled(browser()->profile(), + false, + top_level_page_url()); } void ShieldsUp() { - content_settings()->SetContentSettingCustomScope( - top_level_page_pattern(), - ContentSettingsPattern::Wildcard(), - CONTENT_SETTINGS_TYPE_PLUGINS, - brave_shields::kBraveShields, CONTENT_SETTING_ALLOW); + brave_shields::SetBraveShieldsEnabled(browser()->profile(), + true, + top_level_page_url()); } void AllowFingerprinting() { - content_settings()->SetContentSettingCustomScope( - top_level_page_pattern(), - ContentSettingsPattern::Wildcard(), - CONTENT_SETTINGS_TYPE_PLUGINS, - brave_shields::kFingerprinting, - CONTENT_SETTING_ALLOW); - content_settings()->SetContentSettingCustomScope( - top_level_page_pattern(), - first_party_pattern(), - CONTENT_SETTINGS_TYPE_PLUGINS, - brave_shields::kFingerprinting, - CONTENT_SETTING_ALLOW); + brave_shields::SetFingerprintingControlType(browser()->profile(), + ControlType::ALLOW, + top_level_page_url()); } void BlockFingerprinting() { - content_settings()->SetContentSettingCustomScope( - top_level_page_pattern(), - ContentSettingsPattern::Wildcard(), - CONTENT_SETTINGS_TYPE_PLUGINS, - brave_shields::kFingerprinting, - CONTENT_SETTING_BLOCK); - content_settings()->SetContentSettingCustomScope( - top_level_page_pattern(), - first_party_pattern(), - CONTENT_SETTINGS_TYPE_PLUGINS, - brave_shields::kFingerprinting, - CONTENT_SETTING_BLOCK); + brave_shields::SetFingerprintingControlType(browser()->profile(), + ControlType::BLOCK, + top_level_page_url()); } void Block3PFingerprinting() { - content_settings()->SetContentSettingCustomScope( - top_level_page_pattern(), - ContentSettingsPattern::Wildcard(), - CONTENT_SETTINGS_TYPE_PLUGINS, - brave_shields::kFingerprinting, - CONTENT_SETTING_BLOCK); - content_settings()->SetContentSettingCustomScope( - top_level_page_pattern(), - first_party_pattern(), - CONTENT_SETTINGS_TYPE_PLUGINS, - brave_shields::kFingerprinting, - CONTENT_SETTING_ALLOW); + brave_shields::SetFingerprintingControlType( + browser()->profile(), + ControlType::BLOCK_THIRD_PARTY, + top_level_page_url()); } void BlockScripts() { - content_settings()->SetContentSettingCustomScope( - ContentSettingsPattern::Wildcard(), - ContentSettingsPattern::Wildcard(), - CONTENT_SETTINGS_TYPE_JAVASCRIPT, - "", - CONTENT_SETTING_BLOCK); + brave_shields::SetNoScriptControlType(browser()->profile(), + ControlType::BLOCK, + top_level_page_url()); } void AllowScripts() { - content_settings()->SetContentSettingCustomScope( - ContentSettingsPattern::Wildcard(), - ContentSettingsPattern::Wildcard(), - CONTENT_SETTINGS_TYPE_JAVASCRIPT, - "", - CONTENT_SETTING_ALLOW); + brave_shields::SetNoScriptControlType(browser()->profile(), + ControlType::ALLOW, + top_level_page_url()); } content::WebContents* contents() { @@ -322,6 +273,7 @@ class BraveContentSettingsObserverBrowserTest : public InProcessBrowserTest { GURL url_; GURL iframe_url_; GURL image_url_; + GURL top_level_page_url_; ContentSettingsPattern top_level_page_pattern_; ContentSettingsPattern first_party_pattern_; ContentSettingsPattern iframe_pattern_; From 91a2c74e47b84412cac6a70e1d0f07dd602f8f51 Mon Sep 17 00:00:00 2001 From: Brian Johnson Date: Tue, 20 Aug 2019 15:39:16 -0700 Subject: [PATCH 5/6] Merge pull request #3211 from brave/extension_whitelist fix layering violations in component updater and add missing dep --- browser/BUILD.gn | 2 - browser/brave_browser_process_impl.cc | 41 ++----- browser/brave_browser_process_impl.h | 12 +- .../brave_component_updater_configurator.cc | 69 +---------- .../brave_component_updater_configurator.h | 71 ++++++++--- .../brave_crx_update_service.cc | 110 ------------------ .../brave_crx_update_service.h | 36 ------ .../brave_extension_install_prompt.cc | 6 +- .../extensions/brave_extension_provider.cc | 50 +------- browser/extensions/brave_extension_provider.h | 3 +- .../chrome_component_updater_configurator.cc | 21 ++++ .../component_updater_service.cc | 37 ------ common/BUILD.gn | 2 + common/extensions/whitelist.cc | 45 +++++++ common/extensions/whitelist.h | 14 +++ .../brave_component_updater/browser/BUILD.gn | 14 +++ .../browser/extension_whitelist_service.cc | 31 ++++- .../browser/extension_whitelist_service.h | 27 +++-- components/brave_shields/browser/BUILD.gn | 11 -- ...component_updater_service_internal.h.patch | 20 ---- 20 files changed, 218 insertions(+), 404 deletions(-) delete mode 100644 browser/component_updater/brave_crx_update_service.cc delete mode 100644 browser/component_updater/brave_crx_update_service.h create mode 100644 chromium_src/chrome/browser/component_updater/chrome_component_updater_configurator.cc delete mode 100644 chromium_src/components/component_updater/component_updater_service.cc create mode 100644 common/extensions/whitelist.cc create mode 100644 common/extensions/whitelist.h rename components/{brave_shields => brave_component_updater}/browser/extension_whitelist_service.cc (75%) rename components/{brave_shields => brave_component_updater}/browser/extension_whitelist_service.h (72%) delete mode 100644 patches/components-component_updater-component_updater_service_internal.h.patch diff --git a/browser/BUILD.gn b/browser/BUILD.gn index 9730da1fd16..a4489f41413 100644 --- a/browser/BUILD.gn +++ b/browser/BUILD.gn @@ -59,8 +59,6 @@ source_set("browser_process") { "component_updater/brave_component_updater_configurator.h", "component_updater/brave_component_updater_delegate.cc", "component_updater/brave_component_updater_delegate.h", - "component_updater/brave_crx_update_service.cc", - "component_updater/brave_crx_update_service.h", "geolocation/brave_geolocation_permission_context.cc", "geolocation/brave_geolocation_permission_context.h", "metrics/metrics_reporting_util.cc", diff --git a/browser/brave_browser_process_impl.cc b/browser/brave_browser_process_impl.cc index d8be13eec29..babfc46bf4f 100644 --- a/browser/brave_browser_process_impl.cc +++ b/browser/brave_browser_process_impl.cc @@ -21,7 +21,6 @@ #include "brave/components/brave_shields/browser/ad_block_regional_service_manager.h" #include "brave/components/brave_shields/browser/ad_block_service.h" #include "brave/components/brave_shields/browser/autoplay_whitelist_service.h" -#include "brave/components/brave_shields/browser/extension_whitelist_service.h" #include "brave/components/brave_shields/browser/https_everywhere_service.h" #include "brave/components/brave_shields/browser/referrer_whitelist_service.h" #include "brave/components/brave_shields/browser/tracking_protection_service.h" @@ -40,6 +39,11 @@ #include "brave/components/brave_referrals/browser/brave_referrals_service.h" #endif +#if BUILDFLAG(ENABLE_EXTENSIONS) +#include "brave/common/extensions/whitelist.h" +#include "brave/components/brave_component_updater/browser/extension_whitelist_service.h" +#endif + #if defined(OS_ANDROID) #include "chrome/browser/android/chrome_feature_list.h" #include "chrome/browser/android/component_updater/background_task_update_scheduler.h" @@ -86,35 +90,6 @@ BraveBrowserProcessImpl::brave_component_updater_delegate() { return brave_component_updater_delegate_.get(); } -component_updater::ComponentUpdateService* -BraveBrowserProcessImpl::component_updater() { - if (component_updater_) - return component_updater_.get(); - - if (!BrowserThread::CurrentlyOn(BrowserThread::UI)) - return nullptr; - - std::unique_ptr scheduler; -#if defined(OS_ANDROID) - if (base::FeatureList::IsEnabled( - chrome::android::kBackgroundTaskComponentUpdate) && - component_updater::BackgroundTaskUpdateScheduler::IsAvailable()) { - scheduler = - std::make_unique(); - } -#endif - if (!scheduler) - scheduler = std::make_unique(); - - component_updater_ = component_updater::ComponentUpdateServiceFactory( - component_updater::MakeBraveComponentUpdaterConfigurator( - base::CommandLine::ForCurrentProcess(), - g_browser_process->local_state()), - std::move(scheduler)); - - return component_updater_.get(); -} - void BraveBrowserProcessImpl::ResourceDispatcherHostCreated() { BrowserProcessImpl::ResourceDispatcherHostCreated(); ad_block_service()->Start(); @@ -177,12 +152,12 @@ BraveBrowserProcessImpl::autoplay_whitelist_service() { } #if BUILDFLAG(ENABLE_EXTENSIONS) -brave_shields::ExtensionWhitelistService* +brave_component_updater::ExtensionWhitelistService* BraveBrowserProcessImpl::extension_whitelist_service() { if (!extension_whitelist_service_) { extension_whitelist_service_ = - brave_shields::ExtensionWhitelistServiceFactory( - local_data_files_service()); + brave_component_updater::ExtensionWhitelistServiceFactory( + local_data_files_service(), kVettedExtensions); } return extension_whitelist_service_.get(); } diff --git a/browser/brave_browser_process_impl.h b/browser/brave_browser_process_impl.h index 70ae799e015..e00667ae37e 100644 --- a/browser/brave_browser_process_impl.h +++ b/browser/brave_browser_process_impl.h @@ -25,6 +25,9 @@ class BraveWidevineBundleManager; #endif namespace brave_component_updater { +#if BUILDFLAG(ENABLE_EXTENSIONS) +class ExtensionWhitelistService; +#endif class LocalDataFilesService; } @@ -33,7 +36,6 @@ class AdBlockService; class AdBlockCustomFiltersService; class AdBlockRegionalServiceManager; class AutoplayWhitelistService; -class ExtensionWhitelistService; class HTTPSEverywhereService; class ReferrerWhitelistService; class TrackingProtectionService; @@ -55,7 +57,6 @@ class BraveBrowserProcessImpl : public BrowserProcessImpl { ~BraveBrowserProcessImpl() override; // BrowserProcess implementation. - component_updater::ComponentUpdateService* component_updater() override; void ResourceDispatcherHostCreated() override; ProfileManager* profile_manager() override; @@ -66,7 +67,8 @@ class BraveBrowserProcessImpl : public BrowserProcessImpl { ad_block_regional_service_manager(); brave_shields::AutoplayWhitelistService* autoplay_whitelist_service(); #if BUILDFLAG(ENABLE_EXTENSIONS) - brave_shields::ExtensionWhitelistService* extension_whitelist_service(); + brave_component_updater::ExtensionWhitelistService* + extension_whitelist_service(); #endif brave_shields::ReferrerWhitelistService* referrer_whitelist_service(); greaselion::GreaselionDownloadService* greaselion_download_service(); @@ -97,8 +99,10 @@ class BraveBrowserProcessImpl : public BrowserProcessImpl { ad_block_regional_service_manager_; std::unique_ptr autoplay_whitelist_service_; - std::unique_ptr +#if BUILDFLAG(ENABLE_EXTENSIONS) + std::unique_ptr extension_whitelist_service_; +#endif std::unique_ptr referrer_whitelist_service_; std::unique_ptr diff --git a/browser/component_updater/brave_component_updater_configurator.cc b/browser/component_updater/brave_component_updater_configurator.cc index e966cf2f00e..8558de68124 100644 --- a/browser/component_updater/brave_component_updater_configurator.cc +++ b/browser/component_updater/brave_component_updater_configurator.cc @@ -18,7 +18,6 @@ #include "chrome/browser/net/system_network_context_manager.h" #include "chrome/common/pref_names.h" #include "components/component_updater/component_updater_command_line_config_policy.h" -#include "components/component_updater/configurator_impl.h" #include "components/prefs/pref_registry_simple.h" #include "components/prefs/pref_service.h" #include "components/update_client/activity_data_service.h" @@ -40,57 +39,6 @@ namespace component_updater { -namespace { - -class BraveConfigurator : public update_client::Configurator { - public: - BraveConfigurator(const base::CommandLine* cmdline, - PrefService* pref_service); - - // update_client::Configurator overrides. - int InitialDelay() const override; - int NextCheckDelay() const override; - int OnDemandDelay() const override; - int UpdateDelay() const override; - std::vector UpdateUrl() const override; - std::vector PingUrl() const override; - std::string GetProdId() const override; - base::Version GetBrowserVersion() const override; - std::string GetChannel() const override; - std::string GetBrand() const override; - std::string GetLang() const override; - std::string GetOSLongName() const override; - base::flat_map ExtraRequestParams() const override; - std::string GetDownloadPreference() const override; - scoped_refptr GetNetworkFetcherFactory() - override; - scoped_refptr GetUnzipperFactory() override; - scoped_refptr GetPatcherFactory() override; - bool EnabledDeltas() const override; - bool EnabledComponentUpdates() const override; - bool EnabledBackgroundDownloader() const override; - bool EnabledCupSigning() const override; - PrefService* GetPrefService() const override; - update_client::ActivityDataService* GetActivityDataService() const override; - bool IsPerUserInstall() const override; - std::vector GetRunActionKeyHash() const override; - std::string GetAppGuid() const override; - std::unique_ptr - GetProtocolHandlerFactory() const override; - update_client::RecoveryCRXElevator GetRecoveryCRXElevator() const override; - - private: - friend class base::RefCountedThreadSafe; - - ConfiguratorImpl configurator_impl_; - PrefService* pref_service_; // This member is not owned by this class. - scoped_refptr network_fetcher_factory_; - scoped_refptr unzip_factory_; - scoped_refptr patch_factory_; - - ~BraveConfigurator() override {} -}; - // Allows the component updater to use non-encrypted communication with the // update backend. The security of the update checks is enforced using // a custom message signing protocol and it does not depend on using HTTPS. @@ -103,6 +51,8 @@ BraveConfigurator::BraveConfigurator( DCHECK(pref_service_); } +BraveConfigurator::~BraveConfigurator() {} + int BraveConfigurator::InitialDelay() const { return configurator_impl_.InitialDelay(); } @@ -246,19 +196,4 @@ update_client::RecoveryCRXElevator BraveConfigurator::GetRecoveryCRXElevator() #endif } -} // namespace - -void RegisterPrefsForBraveComponentUpdaterConfigurator( - PrefRegistrySimple* registry) { - // The component updates are enabled by default, if the preference is not set. - registry->RegisterBooleanPref(prefs::kComponentUpdatesEnabled, true); -} - -scoped_refptr -MakeBraveComponentUpdaterConfigurator( - const base::CommandLine* cmdline, - PrefService* pref_service) { - return base::MakeRefCounted(cmdline, pref_service); -} - } // namespace component_updater diff --git a/browser/component_updater/brave_component_updater_configurator.h b/browser/component_updater/brave_component_updater_configurator.h index 14c1c38fa76..0667ecd4a19 100644 --- a/browser/component_updater/brave_component_updater_configurator.h +++ b/browser/component_updater/brave_component_updater_configurator.h @@ -1,11 +1,17 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public +/* Copyright (c) 2019 The Brave Authors. All rights reserved. + * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this file, * You can obtain one at http://mozilla.org/MPL/2.0/. */ -#ifndef BRAVE_BROWSER_COMPONENT_UPDATER_CHROME_COMPONENT_UPDATER_CONFIGURATOR_H_ -#define BRAVE_BROWSER_COMPONENT_UPDATER_CHROME_COMPONENT_UPDATER_CONFIGURATOR_H_ +#ifndef BRAVE_BROWSER_COMPONENT_UPDATER_BRAVE_COMPONENT_UPDATER_CONFIGURATOR_H_ +#define BRAVE_BROWSER_COMPONENT_UPDATER_BRAVE_COMPONENT_UPDATER_CONFIGURATOR_H_ + +#include +#include +#include #include "base/memory/ref_counted.h" +#include "components/component_updater/configurator_impl.h" #include "components/update_client/configurator.h" class PrefRegistrySimple; @@ -21,18 +27,55 @@ class URLRequestContextGetter; namespace component_updater { -// Registers preferences associated with the component updater configurator -// for Chrome. The preferences must be registered with the local pref store -// before they can be queried by the configurator instance. -// This function is called before MakeChromeComponentUpdaterConfigurator. -void RegisterPrefsForBraveComponentUpdaterConfigurator( - PrefRegistrySimple* registry); +class BraveConfigurator : public update_client::Configurator { + public: + BraveConfigurator(const base::CommandLine* cmdline, + PrefService* pref_service); + + // update_client::Configurator overrides. + int InitialDelay() const override; + int NextCheckDelay() const override; + int OnDemandDelay() const override; + int UpdateDelay() const override; + std::vector UpdateUrl() const override; + std::vector PingUrl() const override; + std::string GetProdId() const override; + base::Version GetBrowserVersion() const override; + std::string GetChannel() const override; + std::string GetBrand() const override; + std::string GetLang() const override; + std::string GetOSLongName() const override; + base::flat_map ExtraRequestParams() const override; + std::string GetDownloadPreference() const override; + scoped_refptr GetNetworkFetcherFactory() + override; + scoped_refptr GetUnzipperFactory() override; + scoped_refptr GetPatcherFactory() override; + bool EnabledDeltas() const override; + bool EnabledComponentUpdates() const override; + bool EnabledBackgroundDownloader() const override; + bool EnabledCupSigning() const override; + PrefService* GetPrefService() const override; + update_client::ActivityDataService* GetActivityDataService() const override; + bool IsPerUserInstall() const override; + std::vector GetRunActionKeyHash() const override; + std::string GetAppGuid() const override; + std::unique_ptr + GetProtocolHandlerFactory() const override; + update_client::RecoveryCRXElevator GetRecoveryCRXElevator() const override; + + private: + friend class base::RefCountedThreadSafe; + + ConfiguratorImpl configurator_impl_; + PrefService* pref_service_; // This member is not owned by this class. + scoped_refptr network_fetcher_factory_; + scoped_refptr unzip_factory_; + scoped_refptr patch_factory_; -scoped_refptr -MakeBraveComponentUpdaterConfigurator( - const base::CommandLine* cmdline, - PrefService* pref_service); + ~BraveConfigurator() override; +}; } // namespace component_updater -#endif // BRAVE_BROWSER_COMPONENT_UPDATER_CHROME_COMPONENT_UPDATER_CONFIGURATOR_H_ +#endif // BRAVE_BROWSER_COMPONENT_UPDATER_BRAVE_COMPONENT_UPDATER_CONFIGURATOR_H_ diff --git a/browser/component_updater/brave_crx_update_service.cc b/browser/component_updater/brave_crx_update_service.cc deleted file mode 100644 index 6988fe6e96f..00000000000 --- a/browser/component_updater/brave_crx_update_service.cc +++ /dev/null @@ -1,110 +0,0 @@ -/* Copyright (c) 2019 The Brave Authors. All rights reserved. - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#include "brave/browser/component_updater/brave_crx_update_service.h" - -#include -#include -#include - -#include "base/bind.h" -#include "base/bind_helpers.h" -#include "base/threading/thread_task_runner_handle.h" -#include "components/component_updater/update_scheduler.h" -#include "components/update_client/configurator.h" -#include "components/update_client/task_update.h" -#include "components/update_client/update_client_internal.h" -#include "components/update_client/update_engine.h" -#include "components/update_client/utils.h" -#include "extensions/buildflags/buildflags.h" - -#if BUILDFLAG(ENABLE_EXTENSIONS) -#include "brave/browser/extensions/brave_extension_provider.h" -#endif - -namespace component_updater { - -BraveCrxUpdateService::BraveCrxUpdateService( - scoped_refptr config, - std::unique_ptr scheduler, - scoped_refptr update_client) - : CrxUpdateService(config, std::move(scheduler), update_client) {} - -void BraveCrxUpdateService::Start() { - DCHECK(thread_checker_.CalledOnValidThread()); - scheduler_->Schedule( - base::TimeDelta::FromSeconds(config_->InitialDelay()), - base::TimeDelta::FromSeconds(config_->NextCheckDelay()), - base::Bind(base::IgnoreResult(&BraveCrxUpdateService::CheckForUpdates), - base::Unretained(this)), - base::DoNothing()); -} - -bool BraveCrxUpdateService::CheckForUpdates( - UpdateScheduler::OnFinishedCallback on_finished) { - DCHECK(thread_checker_.CalledOnValidThread()); - - std::vector secure_ids; // Requires HTTPS for update checks. - std::vector unsecure_ids; // Can fallback to HTTP. - for (const auto id : components_order_) { - DCHECK(components_.find(id) != components_.end()); -#if BUILDFLAG(ENABLE_EXTENSIONS) - if (!extensions::BraveExtensionProvider::IsVetted(id)) { - continue; - } -#endif - const auto component = GetComponent(id); - if (!component || component->requires_network_encryption) - secure_ids.push_back(id); - else - unsecure_ids.push_back(id); - } - - if (unsecure_ids.empty() && secure_ids.empty()) { - base::ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE, - std::move(on_finished)); - return true; - } - - Callback on_finished_callback = base::BindOnce( - [](UpdateScheduler::OnFinishedCallback on_finished, - update_client::Error error) { std::move(on_finished).Run(); }, - std::move(on_finished)); - - if (!unsecure_ids.empty()) { - for (auto id : unsecure_ids) { - update_client_->Update( - {id}, - base::BindOnce(&CrxUpdateService::GetCrxComponents, - base::Unretained(this)), - false, - base::BindOnce(&CrxUpdateService::OnUpdateComplete, - base::Unretained(this), - secure_ids.empty() && (id == unsecure_ids.back()) - ? std::move(on_finished_callback) - : Callback(), - base::TimeTicks::Now())); - } - } - - if (!secure_ids.empty()) { - for (auto id : secure_ids) { - update_client_->Update( - {id}, - base::BindOnce(&CrxUpdateService::GetCrxComponents, - base::Unretained(this)), - false, - base::BindOnce( - &CrxUpdateService::OnUpdateComplete, base::Unretained(this), - (id == secure_ids.back()) ? std::move(on_finished_callback) - : Callback(), - base::TimeTicks::Now())); - } - } - - return true; -} - -} // namespace component_updater diff --git a/browser/component_updater/brave_crx_update_service.h b/browser/component_updater/brave_crx_update_service.h deleted file mode 100644 index 41619c24dbe..00000000000 --- a/browser/component_updater/brave_crx_update_service.h +++ /dev/null @@ -1,36 +0,0 @@ -/* Copyright (c) 2019 The Brave Authors. All rights reserved. - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef BRAVE_BROWSER_COMPONENT_UPDATER_BRAVE_CRX_UPDATE_SERVICE_H_ -#define BRAVE_BROWSER_COMPONENT_UPDATER_BRAVE_CRX_UPDATE_SERVICE_H_ - -#include - -#include "components/component_updater/component_updater_service.h" -#include "components/component_updater/component_updater_service_internal.h" - -namespace component_updater { - -using CrxInstaller = update_client::CrxInstaller; -using UpdateClient = update_client::UpdateClient; - -class BraveCrxUpdateService : public CrxUpdateService { - public: - using CrxUpdateService::CrxUpdateService; - BraveCrxUpdateService(scoped_refptr config, - std::unique_ptr scheduler, - scoped_refptr update_client); - - ~BraveCrxUpdateService() override {} - - private: - bool CheckForUpdates(UpdateScheduler::OnFinishedCallback on_finished); - void Start(); - - DISALLOW_COPY_AND_ASSIGN(BraveCrxUpdateService); -}; -} // namespace component_updater - -#endif // BRAVE_BROWSER_COMPONENT_UPDATER_BRAVE_CRX_UPDATE_SERVICE_H_ diff --git a/browser/extensions/brave_extension_install_prompt.cc b/browser/extensions/brave_extension_install_prompt.cc index b55bffebe84..aade90853dc 100644 --- a/browser/extensions/brave_extension_install_prompt.cc +++ b/browser/extensions/brave_extension_install_prompt.cc @@ -5,12 +5,14 @@ #include "brave/browser/extensions/brave_extension_install_prompt.h" -#include "brave/browser/extensions/brave_extension_provider.h" +#include "brave/browser/brave_browser_process_impl.h" +#include "brave/components/brave_component_updater/browser/extension_whitelist_service.h" #include "brave/grit/brave_generated_resources.h" #include "ui/base/l10n/l10n_util.h" base::string16 BravePrompt::GetDialogTitle() const { - if (!extensions::BraveExtensionProvider::IsVetted(extension())) { + if (!g_brave_browser_process->extension_whitelist_service()->IsVetted( + extension())) { if (type_ == ExtensionInstallPrompt::INSTALL_PROMPT || type_ == ExtensionInstallPrompt::WEBSTORE_WIDGET_PROMPT) { return l10n_util::GetStringUTF16( diff --git a/browser/extensions/brave_extension_provider.cc b/browser/extensions/brave_extension_provider.cc index d75b9e5d57a..ebef3ad13ce 100644 --- a/browser/extensions/brave_extension_provider.cc +++ b/browser/extensions/brave_extension_provider.cc @@ -13,7 +13,7 @@ #include "brave/browser/brave_browser_process_impl.h" #include "brave/common/extensions/extension_constants.h" #include "brave/components/brave_component_updater/browser/local_data_files_service.h" -#include "brave/components/brave_shields/browser/extension_whitelist_service.h" +#include "brave/components/brave_component_updater/browser/extension_whitelist_service.h" #include "brave/grit/brave_generated_resources.h" #include "ui/base/l10n/l10n_util.h" @@ -41,54 +41,6 @@ bool IsBlacklisted(const extensions::Extension* extension) { namespace extensions { -bool BraveExtensionProvider::IsVetted(const Extension* extension) { - // This is a hardcoded list of vetted extensions, mostly - // the built-in ones that ship with Brave or are used for - // unit tests. - // Don't add new extensions to this list. Add them to - // the files managed by the extension whitelist service. - return BraveExtensionProvider::IsVetted(extension->id()); -} - -bool BraveExtensionProvider::IsVetted(const std::string id) { - static std::vector vetted_extensions({ - brave_extension_id, - brave_rewards_extension_id, - brave_sync_extension_id, - brave_webtorrent_extension_id, - crl_set_extension_id, - ethereum_remote_client_extension_id, - hangouts_extension_id, - widevine_extension_id, - brave_component_updater::kLocalDataFilesComponentId, - // Web Store - "ahfgeienlihckogmohjhadlkjgocpleb", - // Brave Automation Extension - "aapnijgdinlhnhlmodcfapnahmbfebeb", - // Test ID: Brave Default Ad Block Updater - "naccapggpomhlhoifnlebfoocegenbol", - // Test ID: Brave Regional Ad Block Updater - // (9852EFC4-99E4-4F2D-A915-9C3196C7A1DE) - "dlpmaigjliompnelofkljgcmlenklieh", - // Test ID: Brave Tracking Protection Updater - "eclbkhjphkhalklhipiicaldjbnhdfkc", - // Test ID: PDFJS - "kpbdcmcgkedhpbcpfndimofjnefgjidd", - // Test ID: Brave HTTPS Everywhere Updater - "bhlmpjhncoojbkemjkeppfahkglffilp", - // Test ID: Brave Tor Client Updater - "ngicbhhaldfdgmjhilmnleppfpmkgbbk", - // Chromium PDF Viewer. - "mhjfbmdgcfjbbpaeojofohoefgiehjai", - }); - if (std::find(vetted_extensions.begin(), vetted_extensions.end(), id) != - vetted_extensions.end()) - return true; - - return g_brave_browser_process->extension_whitelist_service()->IsWhitelisted( - id); -} - BraveExtensionProvider::BraveExtensionProvider() {} BraveExtensionProvider::~BraveExtensionProvider() {} diff --git a/browser/extensions/brave_extension_provider.h b/browser/extensions/brave_extension_provider.h index 4b34f980004..73499ab5eb1 100644 --- a/browser/extensions/brave_extension_provider.h +++ b/browser/extensions/brave_extension_provider.h @@ -21,8 +21,7 @@ class BraveExtensionProvider : public ManagementPolicy::Provider { base::string16* error) const override; bool MustRemainInstalled(const Extension* extension, base::string16* error) const override; - static bool IsVetted(const extensions::Extension* extension); - static bool IsVetted(const std::string id); + private: DISALLOW_COPY_AND_ASSIGN(BraveExtensionProvider); }; diff --git a/chromium_src/chrome/browser/component_updater/chrome_component_updater_configurator.cc b/chromium_src/chrome/browser/component_updater/chrome_component_updater_configurator.cc new file mode 100644 index 00000000000..79ec884e2ab --- /dev/null +++ b/chromium_src/chrome/browser/component_updater/chrome_component_updater_configurator.cc @@ -0,0 +1,21 @@ +/* Copyright (c) 2019 The Brave Authors. All rights reserved. + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this file, + * You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#include "brave/browser/component_updater/brave_component_updater_configurator.h" + +#define MakeChromeComponentUpdaterConfigurator \ + MakeChromeComponentUpdaterConfigurator_ChromiumImpl +#include "../../../../../chrome/browser/component_updater/chrome_component_updater_configurator.cc" // NOLINT +#undef MakeChromeComponentUpdaterConfigurator + +namespace component_updater { + +scoped_refptr +MakeChromeComponentUpdaterConfigurator(const base::CommandLine* cmdline, + PrefService* pref_service) { + return base::MakeRefCounted(cmdline, pref_service); +} + +} // namespace component_updater diff --git a/chromium_src/components/component_updater/component_updater_service.cc b/chromium_src/components/component_updater/component_updater_service.cc deleted file mode 100644 index 75487e0156c..00000000000 --- a/chromium_src/components/component_updater/component_updater_service.cc +++ /dev/null @@ -1,37 +0,0 @@ -/* Copyright (c) 2019 The Brave Authors. All rights reserved. - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#include "components/component_updater/component_updater_service.h" - -#include "brave/browser/component_updater/brave_crx_update_service.h" -#include "components/update_client/crx_downloader.h" -#include "components/update_client/ping_manager.h" -#include "components/update_client/update_checker.h" -#include "components/update_client/update_client_internal.h" - -#define ComponentUpdateServiceFactory ComponentUpdateServiceFactory_ChromiumImpl -#include "../../../../components/component_updater/component_updater_service.cc" // NOLINT -#undef ComponentUpdateServiceFactory - -using update_client::CrxDownloader; -using update_client::PingManager; -using update_client::UpdateChecker; -using update_client::UpdateClientImpl; - -namespace component_updater { - -std::unique_ptr ComponentUpdateServiceFactory( - scoped_refptr config, - std::unique_ptr scheduler) { - DCHECK(config); - DCHECK(scheduler); - auto update_client = base::MakeRefCounted( - config, base::MakeRefCounted(config), &UpdateChecker::Create, - &CrxDownloader::Create); - return std::make_unique(config, std::move(scheduler), - std::move(update_client)); -} - -} // namespace component_updater diff --git a/common/BUILD.gn b/common/BUILD.gn index caadf808411..574fe5434f1 100644 --- a/common/BUILD.gn +++ b/common/BUILD.gn @@ -79,6 +79,8 @@ source_set("common") { "extensions/brave_extensions_api_provider.h", "extensions/extension_constants.cc", "extensions/extension_constants.h", + "extensions/whitelist.cc", + "extensions/whitelist.h", ] public_deps = [ diff --git a/common/extensions/whitelist.cc b/common/extensions/whitelist.cc new file mode 100644 index 00000000000..76e6dc2c4b2 --- /dev/null +++ b/common/extensions/whitelist.cc @@ -0,0 +1,45 @@ +/* Copyright (c) 2019 The Brave Authors. All rights reserved. + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this file, + * You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#include "brave/common/extensions/whitelist.h" + +#include "brave/common/extensions/extension_constants.h" +#include "brave/components/brave_component_updater/browser/local_data_files_service.h" + +// This is a hardcoded list of vetted extensions, mostly +// the built-in ones that ship with Brave or are used for +// unit tests. +// Don't add new extensions to this list. Add them to +// the files managed by the extension whitelist service. +const std::vector kVettedExtensions{ + brave_extension_id, + brave_rewards_extension_id, + brave_sync_extension_id, + brave_webtorrent_extension_id, + crl_set_extension_id, + ethereum_remote_client_extension_id, + hangouts_extension_id, + widevine_extension_id, + brave_component_updater::kLocalDataFilesComponentId, + // Web Store + "ahfgeienlihckogmohjhadlkjgocpleb", + // Brave Automation Extension + "aapnijgdinlhnhlmodcfapnahmbfebeb", + // Test ID: Brave Default Ad Block Updater + "naccapggpomhlhoifnlebfoocegenbol", + // Test ID: Brave Regional Ad Block Updater + // (9852EFC4-99E4-4F2D-A915-9C3196C7A1DE) + "dlpmaigjliompnelofkljgcmlenklieh", + // Test ID: Brave Tracking Protection Updater + "eclbkhjphkhalklhipiicaldjbnhdfkc", + // Test ID: PDFJS + "kpbdcmcgkedhpbcpfndimofjnefgjidd", + // Test ID: Brave HTTPS Everywhere Updater + "bhlmpjhncoojbkemjkeppfahkglffilp", + // Test ID: Brave Tor Client Updater + "ngicbhhaldfdgmjhilmnleppfpmkgbbk", + // Chromium PDF Viewer. + "mhjfbmdgcfjbbpaeojofohoefgiehjai", +}; diff --git a/common/extensions/whitelist.h b/common/extensions/whitelist.h new file mode 100644 index 00000000000..70f286f649d --- /dev/null +++ b/common/extensions/whitelist.h @@ -0,0 +1,14 @@ +/* Copyright (c) 2019 The Brave Authors. All rights reserved. + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this file, + * You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#ifndef BRAVE_COMMON_EXTENSIONS_WHITELIST_H_ +#define BRAVE_COMMON_EXTENSIONS_WHITELIST_H_ + +#include +#include + +extern const std::vector kVettedExtensions; + +#endif // BRAVE_COMMON_EXTENSIONS_WHITELIST_H_ diff --git a/components/brave_component_updater/browser/BUILD.gn b/components/brave_component_updater/browser/BUILD.gn index 74bc1982118..d7418994bc3 100644 --- a/components/brave_component_updater/browser/BUILD.gn +++ b/components/brave_component_updater/browser/BUILD.gn @@ -1,3 +1,5 @@ +import("//extensions/buildflags/buildflags.gni") + source_set("browser") { sources = [ "brave_component.cc", @@ -13,4 +15,16 @@ source_set("browser") { deps = [ "//base", ] + + if (enable_extensions) { + sources += [ + "extension_whitelist_service.cc", + "extension_whitelist_service.h", + ] + + deps += [ + "//brave/vendor/extension-whitelist/brave:extension-whitelist", + "//extensions/common", + ] + } } diff --git a/components/brave_shields/browser/extension_whitelist_service.cc b/components/brave_component_updater/browser/extension_whitelist_service.cc similarity index 75% rename from components/brave_shields/browser/extension_whitelist_service.cc rename to components/brave_component_updater/browser/extension_whitelist_service.cc index ca1196c2e56..6775c832bc9 100644 --- a/components/brave_shields/browser/extension_whitelist_service.cc +++ b/components/brave_component_updater/browser/extension_whitelist_service.cc @@ -3,7 +3,7 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this file, * You can obtain one at http://mozilla.org/MPL/2.0/. */ -#include "brave/components/brave_shields/browser/extension_whitelist_service.h" +#include "brave/components/brave_component_updater/browser/extension_whitelist_service.h" #include @@ -11,13 +11,18 @@ #include "base/task_runner_util.h" #include "brave/components/brave_component_updater/browser/local_data_files_service.h" #include "brave/vendor/extension-whitelist/extension_whitelist_parser.h" +#include "extensions/common/extension.h" -namespace brave_shields { +using extensions::Extension; + +namespace brave_component_updater { ExtensionWhitelistService::ExtensionWhitelistService( - LocalDataFilesService* local_data_files_service) + LocalDataFilesService* local_data_files_service, + const std::vector& whitelist) : LocalDataFilesObserver(local_data_files_service), extension_whitelist_client_(new ExtensionWhitelistParser()), + whitelist_(whitelist), weak_factory_(this) { } @@ -38,6 +43,18 @@ bool ExtensionWhitelistService::IsBlacklisted( return extension_whitelist_client_->isBlacklisted(extension_id.c_str()); } +bool ExtensionWhitelistService::IsVetted(const Extension* extension) const { + return ExtensionWhitelistService::IsVetted(extension->id()); +} + +bool ExtensionWhitelistService::IsVetted(const std::string& id) const { + if (std::find(whitelist_.begin(), whitelist_.end(), id) != + whitelist_.end()) + return true; + + return IsWhitelisted(id); +} + void ExtensionWhitelistService::OnComponentReady( const std::string& component_id, const base::FilePath& install_dir, @@ -75,8 +92,10 @@ void ExtensionWhitelistService::OnGetDATFileData(GetDATFileDataResult result) { /////////////////////////////////////////////////////////////////////////////// std::unique_ptr ExtensionWhitelistServiceFactory( - LocalDataFilesService* local_data_files_service) { - return std::make_unique(local_data_files_service); + LocalDataFilesService* local_data_files_service, + const std::vector& whitelist) { + return std::make_unique(local_data_files_service, + whitelist); } -} // namespace brave_shields +} // namespace brave_component_updater diff --git a/components/brave_shields/browser/extension_whitelist_service.h b/components/brave_component_updater/browser/extension_whitelist_service.h similarity index 72% rename from components/brave_shields/browser/extension_whitelist_service.h rename to components/brave_component_updater/browser/extension_whitelist_service.h index 79fd9dafe44..227cc353b2a 100644 --- a/components/brave_shields/browser/extension_whitelist_service.h +++ b/components/brave_component_updater/browser/extension_whitelist_service.h @@ -3,8 +3,8 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this file, * You can obtain one at http://mozilla.org/MPL/2.0/. */ -#ifndef BRAVE_COMPONENTS_BRAVE_SHIELDS_BROWSER_EXTENSION_WHITELIST_SERVICE_H_ -#define BRAVE_COMPONENTS_BRAVE_SHIELDS_BROWSER_EXTENSION_WHITELIST_SERVICE_H_ +#ifndef BRAVE_COMPONENTS_BRAVE_COMPONENT_UPDATER_BROWSER_EXTENSION_WHITELIST_SERVICE_H_ +#define BRAVE_COMPONENTS_BRAVE_COMPONENT_UPDATER_BROWSER_EXTENSION_WHITELIST_SERVICE_H_ #include #include @@ -22,11 +22,11 @@ class ExtensionWhitelistParser; class BraveExtensionProviderTest; class BravePDFDownloadTest; -using brave_component_updater::LocalDataFilesObserver; -using brave_component_updater::LocalDataFilesService; +namespace extensions { +class Extension; +} -// TODO(bridiver) - move out of brave shields -namespace brave_shields { +namespace brave_component_updater { // The brave shields service in charge of extension whitelist class ExtensionWhitelistService : public LocalDataFilesObserver { @@ -35,11 +35,14 @@ class ExtensionWhitelistService : public LocalDataFilesObserver { brave_component_updater::LoadDATFileDataResult; explicit ExtensionWhitelistService( - LocalDataFilesService* local_data_files_service); + LocalDataFilesService* local_data_files_service, + const std::vector& whitelist); ~ExtensionWhitelistService() override; bool IsWhitelisted(const std::string& extension_id) const; bool IsBlacklisted(const std::string& extension_id) const; + bool IsVetted(const std::string& extension_id) const; + bool IsVetted(const extensions::Extension* extension) const; // implementation of LocalDataFilesObserver void OnComponentReady(const std::string& component_id, @@ -52,9 +55,10 @@ class ExtensionWhitelistService : public LocalDataFilesObserver { void OnGetDATFileData(GetDATFileDataResult result); + SEQUENCE_CHECKER(sequence_checker_); std::unique_ptr extension_whitelist_client_; brave_component_updater::DATFileDataBuffer buffer_; - SEQUENCE_CHECKER(sequence_checker_); + std::vector whitelist_; base::WeakPtrFactory weak_factory_; DISALLOW_COPY_AND_ASSIGN(ExtensionWhitelistService); @@ -62,8 +66,9 @@ class ExtensionWhitelistService : public LocalDataFilesObserver { // Creates the ExtensionWhitelistService std::unique_ptr ExtensionWhitelistServiceFactory( - LocalDataFilesService* local_data_files_service); + LocalDataFilesService* local_data_files_service, + const std::vector& whitelist); -} // namespace brave_shields +} // namespace brave_component_updater -#endif // BRAVE_COMPONENTS_BRAVE_SHIELDS_BROWSER_EXTENSION_WHITELIST_SERVICE_H_ +#endif // BRAVE_COMPONENTS_BRAVE_COMPONENT_UPDATER_BROWSER_EXTENSION_WHITELIST_SERVICE_H_ diff --git a/components/brave_shields/browser/BUILD.gn b/components/brave_shields/browser/BUILD.gn index ffa315db1cf..689a6c07f7b 100644 --- a/components/brave_shields/browser/BUILD.gn +++ b/components/brave_shields/browser/BUILD.gn @@ -67,17 +67,6 @@ source_set("browser") { "//third_party/leveldatabase", "//url", ] - - if (enable_extensions) { - sources += [ - "extension_whitelist_service.cc", - "extension_whitelist_service.h", - ] - - deps += [ - "//brave/vendor/extension-whitelist/brave:extension-whitelist", - ] - } } if (is_mac) { diff --git a/patches/components-component_updater-component_updater_service_internal.h.patch b/patches/components-component_updater-component_updater_service_internal.h.patch deleted file mode 100644 index 4729da7d5cd..00000000000 --- a/patches/components-component_updater-component_updater_service_internal.h.patch +++ /dev/null @@ -1,20 +0,0 @@ -diff --git a/components/component_updater/component_updater_service_internal.h b/components/component_updater/component_updater_service_internal.h -index 341fbf78a96bb1b0b8e10bf9579dea9b930bec13..5d1d80b412cc8669c0acfd3b707651af27b62809 100644 ---- a/components/component_updater/component_updater_service_internal.h -+++ b/components/component_updater/component_updater_service_internal.h -@@ -26,6 +26,7 @@ enum class Error; - - namespace component_updater { - -+class BraveCrxUpdateService; - class OnDemandUpdater; - - using CrxInstaller = update_client::CrxInstaller; -@@ -66,6 +67,7 @@ class CrxUpdateService : public ComponentUpdateService, - Callback callback) override; - - private: -+ friend class BraveCrxUpdateService; - void Start(); - void Stop(); - From dfd95816c6444388e35f5acb51d65dd88aa676da Mon Sep 17 00:00:00 2001 From: Brian Johnson Date: Wed, 21 Aug 2019 08:45:55 -0700 Subject: [PATCH 6/6] Merge pull request #3218 from brave/chromium-cookie-prefs cookie pref value is an int, not a bool --- .../browser/cookie_pref_service.cc | 23 +++++++++---------- 1 file changed, 11 insertions(+), 12 deletions(-) diff --git a/components/brave_shields/browser/cookie_pref_service.cc b/components/brave_shields/browser/cookie_pref_service.cc index c96dcd43b80..143bda02e3e 100644 --- a/components/brave_shields/browser/cookie_pref_service.cc +++ b/components/brave_shields/browser/cookie_pref_service.cc @@ -11,6 +11,7 @@ #include "brave/components/brave_shields/browser/brave_shields_util.h" #include "brave/components/brave_shields/common/brave_shield_constants.h" #include "components/content_settings/core/browser/host_content_settings_map.h" +#include "components/content_settings/core/common/content_settings.h" #include "components/content_settings/core/common/content_settings_pattern.h" #include "components/content_settings/core/common/pref_names.h" #include "components/prefs/pref_service.h" @@ -27,27 +28,26 @@ void SetCookieControlTypeFromPrefs(HostContentSettingsMap* map, control_type = ControlType::BLOCK_THIRD_PARTY; } - if (!prefs->GetBoolean("profile.default_content_setting_values.cookies")) { + if (IntToContentSetting(prefs->GetInteger( + "profile.default_content_setting_values.cookies")) == + ContentSetting::CONTENT_SETTING_BLOCK) { control_type = ControlType::BLOCK; } SetCookieControlType(map, control_type, GURL()); } -void SetCookiePrefDefaults(HostContentSettingsMap* map, - PrefService* prefs) { +void SetCookiePrefDefaults(HostContentSettingsMap* map, PrefService* prefs) { auto type = GetCookieControlType(map, GURL()); prefs->SetBoolean(prefs::kBlockThirdPartyCookies, - type == ControlType::BLOCK_THIRD_PARTY); + type == ControlType::BLOCK_THIRD_PARTY); if (type == ControlType::BLOCK) { - prefs->SetInteger( - "profile.default_content_setting_values.cookies", - CONTENT_SETTING_BLOCK); + prefs->SetInteger("profile.default_content_setting_values.cookies", + CONTENT_SETTING_BLOCK); } else { - prefs->SetInteger( - "profile.default_content_setting_values.cookies", - CONTENT_SETTING_ALLOW); + prefs->SetInteger("profile.default_content_setting_values.cookies", + CONTENT_SETTING_ALLOW); } } @@ -56,8 +56,7 @@ void SetCookiePrefDefaults(HostContentSettingsMap* map, CookiePrefService::CookiePrefService( HostContentSettingsMap* host_content_settings_map, PrefService* prefs) - : host_content_settings_map_(host_content_settings_map), - prefs_(prefs) { + : host_content_settings_map_(host_content_settings_map), prefs_(prefs) { SetCookiePrefDefaults(host_content_settings_map, prefs); host_content_settings_map_->AddObserver(this); pref_change_registrar_.Init(prefs_);